command-code 1.65.3 → 1.65.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -11,6 +11,6 @@ import*as e from"path";import t,{join as n,dirname as r,parse as o,resolve as s,
11
11
  ░█▀▀░█▀▄▀█░█▀▄░
12
12
  ░█░░░█░▀░█░█░█░
13
13
  ░▀▀▀░▀░░░▀░▀▀░░
14
- `,oO=getMaxLineWidth(rO),sO=eO,iO=__name(e=>{const t=e??getTerminalWidth();return t>=ZL?"full":t>=sO?"compact":"minimal"},"getHeaderLayout");new Set(["dark","light"]),Gt(),SR();var aO=!1;async function resolveStartupTheme(){return aO||(aO=!0,setDetectedTerminalTheme(await detectTerminalTheme())),resolveCliTheme(getCliTheme())}async function applyStartupTheme(){const e=await resolveStartupTheme();return applyTuiTheme(e),e}function useAuthFlow(e){const{onSuccess:t,onFailure:n,onCancel:r,timeout:o=zo}=e,[s,i]=at("initializing"),[a,l]=at("Starting authentication..."),[c,d]=at(""),[u,m]=at(null),p=lt(t),g=lt(n),h=lt(r);ct(()=>{p.current=t,g.current=n,h.current=r});const f=lt(null);f.current??=createAuthFlowController({timeoutMs:o,openBrowser:__name(e=>Pt(e),"openBrowser"),onAuthStateChange:i,onStatusMessageChange:l,onBrowserUrlChange:m,onSuccess:__name(({config:e,source:t})=>p.current(e,t),"onSuccess"),onFailure:__name(({reason:e,message:t})=>g.current(e,t),"onFailure"),onCancel:__name(()=>h.current(),"onCancel")});const y=f.current,S=ut(()=>{y.cancel()},[y]),w=ut(e=>y.submitApiKey(e),[y]);return ct(()=>(y.start(),()=>{y.dispose()}),[y]),{authState:s,statusMessage:a,browserUrl:u,apiKeyInput:c,setApiKeyInput:d,handleApiKeySubmit:w,cancel:S,hasCompleted:y.hasCompleted()}}function useCursorState({value:e,focus:t,showCursor:n,initialCursor:r}){const[o,s]=at(r??(e||"").length),i=lt(o),a=lt(e);ct(()=>{const r=a.current;if(a.current=e,e===r)return;if(!t)return;if(!n)return;const l=(e||"").length;o>l&&(s(l),i.current=l)},[e,t,n,o]);const l=ut(e=>{s(e),i.current=e},[]);return{cursor:o,setCursor:l,cursorRef:i}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:o,stripBracketedPaste:s=!1,transformPaste:i,deferEmptyPaste:a=!1}){const l=lt(!1),c=lt(i);c.current=i;const d=lt(a);d.current=a,ct(()=>{if(!e)return;const i=process.stdin,a=__name(e=>{o(!0);const t=clampCursor(e.cursor,e.value.length);r(e.value,t),setTimeout(()=>o(!1),0)},"emitStdinResult"),u=__name(e=>{const r=e.toString();if(s){const e=processBracketedPasteInput({input:r,value:t.current,cursor:n.current,transform:c.current});if(e.handled)return void(e.value===t.current&&d.current||a(e))}const o=processRawInput(r,t.current,n.current);o.handled&&a(o)},"handleRawInput");if(i.on("data",u),!l.current&&hasBufferedInput()){l.current=!0;const e=consumeBufferedInput();e&&u(Buffer.from(e))}return stopEarlyInputCapture(),()=>{i.off("data",u)}},[e,t,n,r,o,s])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:o,onUpdate:s,onSubmit:i}){nt((e,a)=>{if(o())return;if(isIgnoredKey(e,a))return;if(a.return)return void(a.shift||a.ctrl||a.meta||i?.(n.current));const l=processInkInput(e,a,n.current,r.current,t);if(!l.handled)return;const c=clampCursor(l.cursor,l.value.length);s(l.value,c)},{isActive:e})}function useSyncedRef(e){const t=lt(e);return t.current=e,t}function useEchoAwareValueRef(e){const t=lt(e),n=lt([]),r=n.current.indexOf(e);return-1!==r&&n.current.splice(0,r+1),-1===r&&t.current!==e&&(t.current=e,n.current=[]),{valueRef:t,noteEmittedValue:ut(e=>{n.current.push(e),n.current.length>64&&n.current.shift()},[])}}__name(resolveStartupTheme,"resolveStartupTheme"),__name(applyStartupTheme,"applyStartupTheme"),Gt(),Gt(),SR(),__name(useAuthFlow,"useAuthFlow"),Gt(),SR(),Gt(),SR(),Gt(),SR(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef"),__name(useEchoAwareValueRef,"useEchoAwareValueRef"),Gt(),SR();var lO=ht.hex(ER.DIM),cO=__name(e=>ht.hex(WR.CODE)(e),"accentHex"),dO=/^\/[A-Za-z0-9][\w/:-]*/,uO=/(^|\s)(@\S+)/g;function pastedTokenRanges(e,t){const n=[],r=new RegExp(hM.source,"g");let o;for(;null!==(o=r.exec(e));)n.push({start:o.index,end:o.index+o[0].length,link:null,color:"dim"});if(t&&t.size>0){const r=new RegExp(fM.source,"g");for(;null!==(o=r.exec(e));){const e=Number(o[1]);if(!t.has(e))continue;const r=t.get(e)??null;n.push({start:o.index,end:o.index+o[0].length,link:r?fileUrl(r):null,color:"dim"})}}return n.sort((e,t)=>e.start-t.start)}function accentTokenRanges(e,t,n){const r=__name((e,n)=>t.some(t=>e<t.end&&n>t.start),"overlapsOccupied"),o=__name(e=>!n||n(e),"isAccentedCommand"),s=[],i=dO.exec(e);i&&!r(0,i[0].length)&&o(i[0])&&s.push({start:0,end:i[0].length,link:null,color:"accent"});const a=new RegExp(uO.source,"g");let l;for(;null!==(l=a.exec(e));){const e=l.index+l[1].length,t=e+l[2].length;r(e,t)||s.push({start:e,end:t,link:null,color:"accent"})}return s}function renderPlainSpan(e,t,n,r,o){let s="";for(let i=t;i<n;i++){const t=e[i];s+=o&&i===r?"\n"===t?Et.inverse(" ")+"\n":Et.inverse(t):t}return s}function renderTokenSpan(e,t,n,r,o,s="dim"){const i="accent"===s?cO:lO;return o&&r>=t&&r<n?i(e.slice(t,r))+Et.inverse(e[r])+i(e.slice(r+1,n)):i(e.slice(t,n))}function renderPlaceholder(e,t){return t?0===e.length?Et.inverse(" "):Et.inverse(e[0])+lO(e.slice(1)):lO(e)}function renderValue(e,t,n,r,o){const s=pastedTokenRanges(e,r),i=[...s,...accentTokenRanges(e,s,o)].sort((e,t)=>e.start-t.start);if(!n&&0===i.length)return e;if(n&&0===e.length)return Et.inverse(" ");let a="",l=0;for(const{start:r,end:o,link:s,color:c}of i){a+=renderPlainSpan(e,l,r,t,n);const i=renderTokenSpan(e,r,o,t,n,c);a+=s?createOSC8Link(s,i,!1):i,l=o}return a+=renderPlainSpan(e,l,e.length,t,n),n&&t===e.length&&(a+=Et.inverse(" ")),a}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(wt(e).length<=s)return e;const i=e.split(/(\s+)/);let a="",l=0,c=!0;for(const e of i){const t=wt(e).length;if(l+t>(c?s:o)&&l>0&&(a+="\n"+r,l=n,c=!1),a+=e,l+=t,e.includes("\n")){const t=e.substring(e.lastIndexOf("\n")+1);l=wt(t).length,c=!0}}return a}function getDisplayValue(e,t,n,r,o,s,i){const a=r&&o;return 0===e.length&&t?renderPlaceholder(t,a):renderValue(e,n,a,s,i)}function getMaskedValue(e,t){return t?t.repeat(e.length):e}__name(pastedTokenRanges,"pastedTokenRanges"),__name(accentTokenRanges,"accentTokenRanges"),__name(renderPlainSpan,"renderPlainSpan"),__name(renderTokenSpan,"renderTokenSpan"),__name(renderPlaceholder,"renderPlaceholder"),__name(renderValue,"renderValue"),__name(wrapWithIndent,"wrapWithIndent"),__name(getDisplayValue,"getDisplayValue"),__name(getMaskedValue,"getMaskedValue"),SR();var mO={white:Et.white,green:Et.green,red:Et.red,blue:Et.blue,yellow:Et.yellow,cyan:Et.cyan,magenta:Et.magenta,gray:Et.gray,grey:Et.gray};function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:o=!0,onChange:s,onSubmit:i,onCursorChange:a,prefix:l="",prefixColor:c,singleLine:d=!1,maxWidth:u,stripBracketedPaste:m=!1,disablePasteRouting:p=!1,clipboardOnEmptyPaste:g=!1,collapsePastedText:h=!1,onPasteCollapsed:f,initialCursor:y,imageTokenLinks:S,isRecognizedSlashCommand:w}){const v=lt(!1),k=lt(0),{valueRef:C,noteEmittedValue:b}=useEchoAwareValueRef(e),E=useSyncedRef(s),T=useSyncedRef(f),{cursor:P,setCursor:M,cursorRef:x}=useCursorState({value:e,focus:n,showCursor:o,initialCursor:y});st.useEffect(()=>{a?.(P)},[P,a]);const I=ut((e,t)=>{M(t),e!==C.current&&(b(e),C.current=e,E.current(e))},[M,C,E,b]),A=ut(e=>{const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");return h&&isPasteWorthCollapsing({content:t,multiline:!0})?(T.current?.(t),pastedTextToken(t)):e},[h,T]),R=ut(e=>{v.current=e},[]),L=ut(()=>v.current||k.current>0,[]);useRawStdinHandler({focus:n,valueRef:C,cursorRef:x,onUpdate:I,setHandled:R,stripBracketedPaste:m,transformPaste:A,deferEmptyPaste:g}),st.useEffect(()=>{if(!n||p)return;let e=!0;const t=registerPasteConsumer(t=>{v.current||__name(async()=>{let n=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n");if(0===n.length){if(!g)return;k.current+=1;try{const e=await detectClipboardText();n=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}finally{k.current-=1}if(!e||!n)return}const r=A(n),o=insertTextAt(C.current,x.current,r);I(o.text,o.cursor)},"applyRoutedPaste")().catch(()=>{})});return()=>{e=!1,t()}},[n,p,g,A,C,x,I]),useInkInputHandler({focus:n,showCursor:o,valueRef:C,cursorRef:x,isHandledByStdin:L,onUpdate:I,onSubmit:i});const{stdout:O}=et(),D=O?.columns??80,$=getMaskedValue(e,r),N=c?mO[c]:void 0,_=l?N?N(l):l:"",F=getDisplayValue($,t,P,o,n,S,w),U=l?.length??0,j=_+F;if(d){const e=j.replace(/\n/g," ");return null!=u?st.createElement(Qe,{width:u},st.createElement(Xe,{wrap:"truncate"},e)):st.createElement(Xe,{wrap:"truncate"},e)}const B=wrapWithIndent(j,D,U);return st.createElement(Xe,{wrap:"wrap"},B)}__name(TextInput,"TextInput"),Gt();var pO=__name(({children:e})=>st.createElement(Xe,{italic:!0,color:ER.DIM},e),"HintText"),gO=__name(({children:e})=>st.createElement(Xe,{bold:!0},e),"HintKey"),hO=__name(({hints:e,marginTop:t=1})=>{const n=e.filter(e=>null!=e&&!1!==e&&""!==e);return 0===n.length?null:st.createElement(Qe,{marginTop:t},st.createElement(pO,null,n.map((e,t)=>st.createElement(st.Fragment,{key:t},t>0&&" · ",e))))},"HintBar");Gt();var fO=TR,yO=ER.DIM,SO=ER.DIMMER,wO=TR,vO=ER.WHITE,kO=ER.GRAY,CO=ER.GREEN;function hasContent(e){return null!=e&&""!==e}__name(hasContent,"hasContent");var bO=__name(({title:e,titleSuffix:t,subtitle:n,children:r,hint:o,footer:s,rule:i=!0,titleColor:a=fO,ruleColor:l=SO,gapAfterHeader:c=!0,boxProps:d})=>{const u=hasContent(n);return st.createElement(Qe,{flexDirection:"column",width:"100%",...d},i&&st.createElement(ZR,{dividerColor:l}),st.createElement(Qe,null,st.createElement(Xe,{bold:!0,color:a},e),hasContent(t)&&st.createElement(Xe,{color:yO},t)),u?st.createElement(Qe,{marginBottom:c?1:0},st.createElement(Xe,{color:yO},n)):c&&st.createElement(Qe,{marginBottom:1}),r,s?st.createElement(Qe,{marginTop:1},s):o?st.createElement(Qe,{marginTop:1},st.createElement(Xe,{italic:!0,color:yO},o)):null)},"Overlay"),EO=st.memo(({authState:e,browserUrl:t,apiKeyInput:n,setApiKeyInput:r,handleApiKeySubmit:o})=>{const s="waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,i=t&&("waiting_browser"===e||"manual_entry"===e);return st.createElement(st.Fragment,null,s&&st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?ER.YELLOW:ER.GRAY,paddingX:1},st.createElement(Xe,{color:ER.DIM},"API Key: "),st.createElement(Qe,{flexGrow:1},st.createElement(TextInput,{value:n,onChange:r,onSubmit:o,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},getCommandAuthHelpText(e))),i&&st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},getCommandAuthUrlLabel(e)),st.createElement(cL,{url:t,text:t,color:ER.CYAN,dimColor:!0}))),"validating"===e&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"invalid_key"===e)&&st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"ctrl+c to cancel")))});EO.displayName="AuthInputSection";var TO=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s})=>{const i=__name(()=>"waiting_browser"===e?st.createElement(kt,{type:"dots"}):"browser_success"===e||"success"===e?st.createElement(Xe,{color:ER.GREEN},gt.tick):"denied"===e||"invalid_key"===e?st.createElement(Xe,{color:ER.RED},gt.cross):"manual_entry"===e?st.createElement(Xe,{color:ER.YELLOW},gt.arrowDown):"error"===e?st.createElement(Xe,{color:ER.RED},gt.warning):st.createElement(kt,{type:"dots"}),"getStatusIcon"),a=__name(()=>getCommandAuthStatusColor(e),"getStatusColor");return"browser_success"===e||"success"===e||"denied"===e?null:st.createElement(bO,{title:"Sign in to Command Code"},st.createElement(Qe,{marginBottom:1},st.createElement(Qe,{marginRight:1},i()),st.createElement(Xe,{color:a()},t)),st.createElement(EO,{authState:e,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s}))},"AuthFlowUI"),PO=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:i,cancel:a}=useAuthFlow({onSuccess:__name((t,n)=>{e({success:!0,config:t,source:n})},"onSuccess"),onFailure:__name((t,n)=>{e({success:!1,reason:t,message:n})},"onFailure"),onCancel:__name(()=>{e({success:!1,reason:"cancelled",message:"Authentication cancelled by user."})},"onCancel")});return nt((e,t)=>{t.ctrl&&"c"===e&&a()}),st.createElement(TO,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:i})},"LoginWithApiKey");Gt(),SR();var MO=getPackageJson(import.meta.url),xO="string"==typeof MO.version&&MO.version.trim()?MO.version:"unknown";function createApiClient(e){return createCommandApiClient({baseUrl:e.baseUrl,timeout:e.timeout,cliVersion:xO,deps:{getAuthKey:getAuthKey,getTraceId:getTraceId,getTelemetryEnv:getTelemetryEnv,trackApiCallStart:trackAPICallStart,cmdZdrEnabled:__name(()=>"1"===process.env.CMD_ZDR,"cmdZdrEnabled"),deepseekInternalEnabled:__name(()=>"1"===process.env.CMD_PROVIDER_DEEPSEEK_INTERNAL,"deepseekInternalEnabled")}})}function getAuthKey(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function isJevFree(e=Date.now()){return e<=Date.parse("2026-09-24T23:59:59Z")}function isLingFlashFreeEnded(e=new Date){return e.getTime()>=Date.parse("2026-08-03T13:00:00Z")}__name(createApiClient,"createApiClient"),__name(getAuthKey,"getAuthKey"),Gt(),SR(),Gt(),Gt(),__name(isJevFree,"isJevFree"),Gt(),__name(isLingFlashFreeEnded,"isLingFlashFreeEnded"),Gt();var IO={GENERATE:"/alpha/agent/generate"},AO={RECORD:"/alpha/fingerprint/record"},RO={START:"/alpha/sandbox/start",SESSIONS:"/alpha/sandbox/sessions"},LO={CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",APPEND:"/alpha/share/append"},OO={CREATE:"/alpha/devrel-thread/create",DELETE:"/alpha/devrel-thread/delete",UPDATE:"/alpha/devrel-thread/update"},DO={GET:"/alpha/taste/:projectSlug",UPDATE:"/alpha/taste/:projectSlug/update",DELETE:"/alpha/taste/:projectSlug",LEARN:"/alpha/learn"},$O={CREDITS:"/alpha/billing/credits",SUBSCRIPTIONS:"/alpha/billing/subscriptions"},NO={SUMMARY:"/alpha/usage/summary"},_O={TRACK:"/alpha/lifecycle-events"},FO={GET:/\/internal\/orgs\/[a-zA-Z0-9_-]+/,FOLLOW:/\/internal\/orgs\/[a-zA-Z0-9-]+\/follow/,FOLLOWERS:/\/internal\/orgs\/[a-zA-Z0-9-]+\/followers/},UO={FOLLOW:/\/internal\/users\/[a-zA-Z0-9-]+\/follow/,FOLLOWERS:/\/internal\/users\/[a-zA-Z0-9-]+\/followers/,FOLLOWING:/\/internal\/users\/[a-zA-Z0-9-]+\/following/},jO={PACKAGES:{GET:/\/internal\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+/,FILES:/\/internal\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/files/,DOWNLOAD:/\/internal\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/download/,UPDATE:/\/internal\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/update/,STAR:/\/internal\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/star/,PIN:/\/internal\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/pin/}};function getBinaryCommand(){return"win32"===process.platform?"cmdc":"cmd"}Object.values({GET:/\/alpha\/taste\/[a-z0-9-]+/,UPDATE:/\/alpha\/taste\/[a-z0-9-]+\/update/,DELETE:/\/alpha\/taste\/[a-z0-9-]+\/rules\/[a-z0-9-]+/,LIST:/\/alpha\/taste\/[a-z0-9-]+\/rules/}),Object.values({UPLOAD:/^\/beta\/taste\/packages\/[a-zA-Z0-9_-]+$/,FILES:/\/beta\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/files/,GET:/\/beta\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+/,DOWNLOAD:/\/beta\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/download/}),IO.GENERATE,AO.RECORD,RO.START,RO.SESSIONS,LO.CREATE,LO.DELETE,LO.APPEND,OO.CREATE,OO.DELETE,OO.UPDATE,DO.LEARN,DO.DELETE,DO.GET,DO.UPDATE,Object.values({UPLOAD:"/beta/taste/packages/:namespace",LIST:"/beta/taste/packages",GET:"/beta/taste/packages/:namespace/:packageName",FILES:"/beta/taste/packages/:namespace/:packageName/files",DOWNLOAD:"/beta/taste/packages/:namespace/:packageName/download",DELETE:"/beta/taste/packages/:namespace/:packageName"}),$O.CREDITS,$O.SUBSCRIPTIONS,NO.SUMMARY,_O.TRACK,Object.values(FO),Object.values(UO),Object.values(jO.PACKAGES),Object.values({GET:/\/internal\/profile\/[a-zA-Z0-9_-]+/,PACKAGES:/\/internal\/profile\/[a-zA-Z0-9_-]+\/packages/,FOLLOWING:/\/internal\/profile\/[a-zA-Z0-9_-]+\/following/,FOLLOWERS:/\/internal\/profile\/[a-zA-Z0-9_-]+\/followers/,PACKAGE_GET:/\/internal\/profile\/[a-zA-Z0-9_-]+\/packages\/[a-zA-Z0-9_-]+/,PACKAGE_DOWNLOAD:/\/internal\/profile\/[a-zA-Z0-9_-]+\/packages\/[a-zA-Z0-9_-]+\/download/}),__name(getBinaryCommand,"getBinaryCommand");var BO="anthropic",WO="openai",HO="baseten",GO="vercel-ai-gateway",VO="cloudflare-ai-gateway",zO="cmd-ai",KO="openrouter",qO="alibaba",YO="alibaba-intl",JO="novita",QO="morph",XO="wafer",ZO="longcat",eD="tencent",tD="terminal",nD=GO,rD={[BO]:[{id:"anthropic:claude-sonnet-5",provider:"Anthropic",category:"premium",promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:4,cacheHitCost:.2},{id:"anthropic:claude-sonnet-4-20250514",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-sonnet-4-5-20250929",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-opus-4-5-20251101",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-sonnet-4-6",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-fable-5-1",provider:"Anthropic",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:20,cacheHitCost:.25},{id:"anthropic:claude-fable-5",provider:"Anthropic",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:20,cacheHitCost:1},{id:"anthropic:claude-opus-5-5",provider:"Anthropic",category:"premium",promptCost:4,completionCost:20,cacheWrite5mCost:5,cacheWrite1hCost:8,cacheHitCost:.2},{id:"anthropic:claude-opus-5",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-8",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-7",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-6",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-haiku-4-5-20251001",provider:"Anthropic",category:"premium",promptCost:1,completionCost:5,cacheWrite5mCost:1.25,cacheWrite1hCost:2,cacheHitCost:.1}],[WO]:[{id:"openai:gpt-6-astra",provider:"OpenAI",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:0,cacheHitCost:1,contextTiers:[{maxInputTokens:272e3,promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:0,cacheHitCost:1},{promptCost:20,completionCost:75,cacheWrite5mCost:25,cacheWrite1hCost:0,cacheHitCost:2}]},{id:"openai:gpt-6-sol",provider:"OpenAI",category:"premium",promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.2,contextTiers:[{maxInputTokens:272e3,promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.2},{promptCost:4,completionCost:15,cacheWrite5mCost:5,cacheWrite1hCost:0,cacheHitCost:.4}]},{id:"openai:gpt-6-luna",provider:"OpenAI",category:"opensource",promptCost:.1,completionCost:.5,cacheWrite5mCost:.125,cacheWrite1hCost:0,cacheHitCost:.01,contextTiers:[{maxInputTokens:272e3,promptCost:.1,completionCost:.5,cacheWrite5mCost:.125,cacheWrite1hCost:0,cacheHitCost:.01},{promptCost:.2,completionCost:.75,cacheWrite5mCost:.25,cacheWrite1hCost:0,cacheHitCost:.02}]},{id:"openai:gpt-5.5",provider:"OpenAI",category:"premium",promptCost:5,completionCost:30,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.4",provider:"OpenAI",category:"premium",promptCost:2.5,completionCost:15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.25},{id:"openai:gpt-5.3-codex",provider:"OpenAI",category:"premium",promptCost:2,completionCost:8,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.4-mini",provider:"OpenAI",category:"premium",promptCost:.75,completionCost:4.5,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.075},{id:"openai:gpt-5.6-sol",provider:"OpenAI",category:"premium",promptCost:5,completionCost:30,cacheWrite5mCost:6.25,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.6-terra",provider:"OpenAI",category:"premium",promptCost:2,completionCost:12,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.2},{id:"openai:gpt-5.6-luna",provider:"OpenAI",category:"premium",promptCost:.2,completionCost:1.2,cacheWrite5mCost:.25,cacheWrite1hCost:0,cacheHitCost:.02}],[HO]:[{id:"baseten:zai-org/GLM-5",provider:"Baseten",category:"opensource",promptCost:.95,completionCost:3.15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0},{id:"baseten:moonshotai/Kimi-K2.5",provider:"Baseten",category:"opensource",promptCost:.6,completionCost:3,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0},{id:"baseten:moonshotai/Kimi-K2.6",provider:"Baseten",category:"opensource",promptCost:.95,completionCost:4,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.16},{id:"baseten:MiniMaxAI/MiniMax-M2.5",provider:"Baseten",category:"opensource",promptCost:.5,completionCost:2,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0}],[JO]:[{id:"novita:moonshotai/Kimi-K3",provider:"Novita",category:"opensource",promptCost:3,completionCost:15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.3},{id:"novita:zai-org/GLM-5.3",provider:"Novita",category:"opensource",promptCost:1.4,completionCost:4.4,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.26},{id:"novita:deepseek/deepseek-v4.1-flash",provider:"Novita",category:"opensource",promptCost:.15,completionCost:.6,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.003},{id:"novita:z-ai/glm-5.3-flash",provider:"Novita",category:"opensource",promptCost:.15,completionCost:.5,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.03}],[GO]:[],[KO]:[]};ye.enum(["owner","admin","member"]);var oD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,sD="chatComplete",iD="responses",aD="MiniMaxAI/MiniMax-M3-Free",lD={SONNET_5:{id:"claude-sonnet-5",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Sonnet 5",name:"Claude Sonnet 5",description:"best combo of speed & intelligence (recommended)",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},SONNET_4_6:{id:"claude-sonnet-4-6",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Sonnet 4.6",name:"Claude Sonnet 4.6",description:"prev Sonnet, still fast & capable",reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},FABLE_5_1:{id:"claude-fable-5-1",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Fable 5.1",name:"Claude Fable 5.1",description:"most capable for demanding reasoning & long-horizon agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},FABLE_5:{id:"claude-fable-5",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Fable 5",name:"Claude Fable 5",description:"prev Fable, still strong for deep reasoning & agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_5_5:{id:"claude-opus-5-5",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Opus 5.5",name:"Claude Opus 5.5",description:"most intelligent Opus for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_5:{id:"claude-opus-5",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Opus 5",name:"Claude Opus 5",description:"prev flagship, still strong for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_4_8:{id:"claude-opus-4-8",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Opus 4.8",name:"Claude Opus 4.8",description:"older Opus, still strong for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_4_7:{id:"claude-opus-4-7",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Opus 4.7",name:"Claude Opus 4.7",description:"older Opus, still strong for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},HAIKU_4_5:{id:"claude-haiku-4-5-20251001",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Haiku 4.5",name:"Claude Haiku 4.5",description:"fastest & most compact, great for quick tasks",contextWindow:2e5},GPT_6_ASTRA:{id:"gpt-6-astra",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-6 Astra",name:"GPT-6 Astra",description:"most capable OpenAI model for demanding reasoning & agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_6_SOL:{id:"gpt-6-sol",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-6 Sol",name:"GPT-6 Sol",description:"built for complex coding & agentic workflows",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_6_LUNA:{id:"gpt-6-luna",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-6 Luna",name:"GPT-6 Luna",description:"most efficient OpenAI model for focused, high-volume tasks",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_5_6_SOL:{id:"gpt-5.6-sol",inputModalities:["text","image"],provider:GO,spec:iD,label:"GPT-5.6 Sol",name:"GPT-5.6 Sol",description:"frontier model for complex professional work",vendorLabel:"OpenAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_5_6_TERRA:{id:"gpt-5.6-terra",inputModalities:["text","image"],provider:GO,spec:iD,label:"GPT-5.6 Terra",name:"GPT-5.6 Terra",description:"balances intelligence and cost",vendorLabel:"OpenAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_5_6_LUNA:{id:"gpt-5.6-luna",inputModalities:["text","image"],provider:GO,spec:iD,label:"GPT-5.6 Luna",name:"GPT-5.6 Luna",description:"optimized for cost-sensitive workloads",vendorLabel:"OpenAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_5_5:{id:"gpt-5.5",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-5.5",name:"GPT-5.5",description:"latest frontier model for general complex work",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:4e5},GPT_5_4:{id:"gpt-5.4",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-5.4",name:"GPT-5.4",description:"frontier model for general complex work",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:4e5},GPT_5_3_CODEX:{id:"gpt-5.3-codex",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-5.3 Codex",name:"GPT-5.3 Codex",description:"frontier coding model",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:4e5},GPT_5_4_MINI:{id:"gpt-5.4-mini",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-5.4 Mini",name:"GPT-5.4 Mini",description:"fast, cost-effective model for everyday tasks",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:4e5},MINIMAX_M3_PROMO_FREE:{id:aD,inputModalities:["text","image"],provider:nD,spec:sD,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",badge:"free",hidden:!0,reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},DEEPSEEK_V4_PRO:{id:"deepseek/deepseek-v4-pro",inputModalities:["text"],provider:nD,spec:sD,label:"DeepSeek V4 Pro (latest)",name:"DeepSeek V4 Pro (latest)",description:"hybrid-attention long-context reasoning",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},DEEPSEEK_V4_FLASH:{id:"deepseek/deepseek-v4-flash",inputModalities:["text"],provider:nD,spec:sD,label:"DeepSeek V4 Flash (latest)",name:"DeepSeek V4 Flash (latest)",description:"fast hybrid-attention reasoning",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},DEEPSEEK_V4_FLASH_VISION_EXP:{id:"deepseek/deepseek-v4-flash-vision-exp",inputModalities:["text","image"],provider:nD,spec:sD,label:"DeepSeek V4 Flash Vision (exp)",name:"DeepSeek V4 Flash Vision (exp)",description:"fast hybrid-attention reasoning with vision",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},DEEPSEEK_V4_FLASH_FAST:{id:"deepseek/deepseek-v4-flash-fast",inputModalities:["text"],provider:nD,spec:sD,label:"DeepSeek V4 Flash Fast",name:"DeepSeek V4 Flash Fast",description:"low-latency V4 Flash deployment",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},DEEPSEEK_V4_1_FLASH:{id:"deepseek/deepseek-v4.1-flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"DeepSeek V4.1 Flash",name:"DeepSeek V4.1 Flash",description:"V4.1 hybrid-attention reasoning with vision",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},KIMI_K3:{id:"moonshotai/Kimi-K3",inputModalities:["text","image"],provider:nD,spec:sD,label:"Kimi K3",name:"Kimi K3",description:"long-horizon coding & knowledge work with 1M context",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},KIMI_K2_7_CODE:{id:"moonshotai/Kimi-K2.7-Code",inputModalities:["text","image"],provider:nD,spec:sD,label:"Kimi K2.7 Code",name:"Kimi K2.7 Code",description:"improved long-horizon coding with vision",reasoning:!0,contextWindow:256e3},KIMI_K2_7_CODE_HIGHSPEED:{id:"moonshotai/Kimi-K2.7-Code-Highspeed",inputModalities:["text","image"],provider:nD,spec:sD,label:"Kimi K2.7 Code HighSpeed",name:"Kimi K2.7 Code HighSpeed",description:"high-speed long-horizon coding with vision",reasoning:!0,contextWindow:262e3},KIMI_K2_6:{id:"moonshotai/Kimi-K2.6",inputModalities:["text","image"],provider:nD,spec:sD,label:"Kimi K2.6",name:"Kimi K2.6",description:"long-horizon coding with vision",contextWindow:256e3},KIMI_K2_5:{id:"moonshotai/Kimi-K2.5",inputModalities:["text","image"],provider:nD,spec:sD,label:"Kimi K2.5",name:"Kimi K2.5",description:"multimodal frontend coding",contextWindow:256e3},GLM_5_3_FLASH:{id:"z-ai/glm-5.3-flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"GLM-5.3 Flash",name:"GLM-5.3 Flash",description:"fast, affordable GLM coding with 1M context",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1048576,maxOutputTokens:131072},GLM_5_3_FLASHX:{id:"z-ai/glm-5.3-flashx",inputModalities:["text","image"],provider:nD,spec:sD,label:"GLM-5.3 FlashX",name:"GLM-5.3 FlashX",description:"high-speed GLM-5.3 Flash with 1M context",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6,maxOutputTokens:131072},GLM_5_3:{id:"zai-org/GLM-5.3",inputModalities:["text"],provider:nD,spec:sD,label:"GLM-5.3",name:"GLM-5.3",description:"frontier coding with emergent cyber capabilities",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},GLM_5_2:{id:"zai-org/GLM-5.2",inputModalities:["text"],provider:nD,spec:sD,label:"GLM-5.2",name:"GLM-5.2",description:"powerful coding with 1M context and long-horizon tasks",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},GLM_5_2_FAST:{id:"zai-org/GLM-5.2-Fast",inputModalities:["text"],provider:nD,spec:sD,label:"GLM-5.2 Fast",name:"GLM-5.2 Fast",description:"high-throughput GLM-5.2 with 1M context",contextWindow:1e6},GLM_5_1:{id:"zai-org/GLM-5.1",inputModalities:["text"],provider:nD,spec:sD,label:"GLM-5.1",name:"GLM-5.1",description:"long-horizon autonomous coding agent"},GLM_5:{id:"zai-org/GLM-5",inputModalities:["text"],provider:nD,spec:sD,label:"GLM-5",name:"GLM-5",description:"multi-mode thinking & long-range planning",contextWindow:2e5},MINIMAX_M3:{id:"MiniMaxAI/MiniMax-M3",inputModalities:["text","image"],provider:nD,spec:sD,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},MINIMAX_M2_7:{id:"MiniMaxAI/MiniMax-M2.7",inputModalities:["text"],provider:nD,spec:sD,label:"MiniMax M2.7",name:"MiniMax M2.7",description:"end-to-end software engineering agent"},MINIMAX_M3_FREE:{id:"minimax/minimax-m3-free",inputModalities:["text","image"],provider:nD,spec:sD,label:"MiniMax M3",name:"MiniMax M3 (Free)",description:"frontier coding, agents & native multimodality",badge:"free",hidden:!0,reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},MINIMAX_M2_7_FREE:{id:"minimax/minimax-m2.7-free",inputModalities:["text"],provider:nD,spec:sD,label:"MiniMax M2.7",name:"MiniMax M2.7 (Free)",description:"end-to-end software engineering agent",badge:"free",hidden:!0,contextWindow:197e3},MINIMAX_M2_5:{id:"MiniMaxAI/MiniMax-M2.5",inputModalities:["text"],provider:nD,spec:sD,label:"MiniMax M2.5",name:"MiniMax M2.5",description:"cross-platform full-stack agentic dev",contextWindow:2e5},XIAOMI_MIMO_V2_6_PRO:{id:"xiaomi/mimo-v2.6-pro",inputModalities:["text","image"],provider:nD,spec:sD,label:"MiMo V2.6 Pro",name:"MiMo V2.6 Pro",description:"flagship multimodal agentic coding with 1M context",contextWindow:1048576},XIAOMI_MIMO_V2_6_PRO_ULTRASPEED:{id:"xiaomi/mimo-v2.6-pro-ultraspeed",inputModalities:["text","image"],provider:nD,spec:sD,label:"MiMo V2.6 Pro UltraSpeed",name:"MiMo V2.6 Pro UltraSpeed",description:"low-latency serving tier of MiMo V2.6 Pro",contextWindow:1048576},XIAOMI_MIMO_V2_6_FLASH:{id:"xiaomi/mimo-v2.6-flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"MiMo V2.6 Flash",name:"MiMo V2.6 Flash",description:"efficient multimodal agentic coding with 1M context",contextWindow:1048576},XIAOMI_MIMO_V2_5_PRO:{id:"xiaomi/mimo-v2.5-pro",inputModalities:["text"],provider:nD,spec:sD,label:"MiMo V2.5 Pro",name:"MiMo V2.5 Pro",description:"high-capability long-context agentic coding",contextWindow:1e6},XIAOMI_MIMO_V2_5:{id:"xiaomi/mimo-v2.5",inputModalities:["text","image"],provider:nD,spec:sD,label:"MiMo V2.5",name:"MiMo V2.5",description:"efficient long-context agentic coding",contextWindow:1e6},QWEN_3_8_OMNI_FLASH:{id:"Qwen/Qwen3.8-Omni-Flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.8 Omni Flash",name:"Qwen 3.8 Omni Flash",description:"omni-modal understanding & multimedia agentic work",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6,maxOutputTokens:131072},QWEN_3_8_MAX_0902:{id:"Qwen/Qwen3.8-Max-0902",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.8 Max 0902",name:"Qwen 3.8 Max 0902",description:"upgraded Qwen 3.8 Max: stronger coding & agentic tool use",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6},QWEN_3_8_MAX:{id:"Qwen/Qwen3.8-Max",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.8 Max",name:"Qwen 3.8 Max",description:"autonomous long-horizon coding & professional work",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6},QWEN_3_8_27B:{id:"Qwen/Qwen3.8-27B",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.8 27B",name:"Qwen 3.8 27B",description:"compact vision-language coding & agentic work",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:262144,maxOutputTokens:32768},QWEN_3_8_FLASH:{id:"Qwen/Qwen3.8-Flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.8 Flash",name:"Qwen 3.8 Flash",description:"fast low-cost agentic coding & reasoning",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6},QWEN_3_7_MAX:{id:"Qwen/Qwen3.7-Max",inputModalities:["text"],provider:nD,spec:sD,label:"Qwen 3.7 Max",name:"Qwen 3.7 Max",description:"frontier coding & long-horizon agent execution",reasoning:!0,contextWindow:1e6},QWEN_3_7_PLUS:{id:"Qwen/Qwen3.7-Plus",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.7 Plus",name:"Qwen 3.7 Plus",description:"agentic coding & reasoning at lower cost",reasoning:!0,contextWindow:1e6},QWEN_3_7_FLASH:{id:"Qwen/Qwen3.7-Flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.7 Flash",name:"Qwen 3.7 Flash",description:"fast low-cost agentic coding & reasoning",reasoning:!0,contextWindow:1e6},QWEN_3_6_MAX_PREVIEW:{id:"Qwen/Qwen3.6-Max-Preview",inputModalities:["text"],provider:nD,spec:sD,label:"Qwen 3.6 Max Preview",name:"Qwen 3.6 Max Preview",description:"vibe coding & efficient agent execution",reasoning:!0},QWEN_3_6_PLUS:{id:"Qwen/Qwen3.6-Plus",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.6 Plus",name:"Qwen 3.6 Plus",description:"agentic coding & reasoning",reasoning:!0},LONGCAT_2:{id:"meituan/LongCat-2.0",inputModalities:["text"],provider:nD,spec:sD,label:"LongCat 2.0",name:"LongCat 2.0",description:"trillion-parameter agentic coding with 1M context",reasoning:!0,contextWindow:1048576},LONGCAT_2_FREE:{id:"meituan/LongCat-2.0:free",inputModalities:["text"],provider:nD,spec:sD,label:"LongCat 2.0",name:"LongCat 2.0 (Free)",description:"trillion-parameter agentic coding with 1M context",badge:"free",hidden:!0,reasoning:!0,contextWindow:1048576},STEP_5_PREVIEW:{id:"stepfun/Step-5-Preview",inputModalities:["text","image"],provider:nD,spec:sD,label:"Step 5 Preview",name:"Step 5 Preview",description:"600B sparse-MoE agentic coding with 1M context",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},STEP_3_7_FLASH:{id:"stepfun/Step-3.7-Flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"Step 3.7 Flash",name:"Step 3.7 Flash",description:"multimodal sparse-MoE reasoning",reasoning:!0,contextWindow:256e3},STEP_3_5_FLASH:{id:"stepfun/Step-3.5-Flash",inputModalities:["text"],provider:nD,spec:sD,label:"Step 3.5 Flash",name:"Step 3.5 Flash",description:"fast sparse-MoE agentic reasoning",reasoning:!0,contextWindow:262144},TENCENT_HY3:{id:"tencent/Hy3",inputModalities:["text"],provider:nD,spec:sD,label:"Tencent Hy3 (Free)",name:"Tencent Hy3 (Free)",description:"sparse-MoE reasoning & agentic tool use",badge:"free",hidden:!0,reasoning:!0,contextWindow:262144},TENCENT_HY3_PAID:{id:"tencent/hy3-paid",inputModalities:["text"],provider:nD,spec:sD,label:"Tencent Hy3",name:"Tencent Hy3",description:"sparse-MoE reasoning & agentic tool use",reasoning:!0,contextWindow:262144},TENCENT_HY4_PREVIEW:{id:"tencent/hy4-preview",inputModalities:["text"],provider:nD,spec:sD,label:"Tencent Hy4 Preview",name:"Tencent Hy4 Preview",description:"agentic coding & sustained multi-step tool use",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1048576},GEMINI_3_8_FLASH:{id:"google/gemini-3.8-flash",inputModalities:["text","image"],provider:GO,spec:sD,label:"Gemini 3.8 Flash",name:"Gemini 3.8 Flash",description:"newest Gemini Flash, improved core reasoning",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},GEMINI_3_7_FLASH:{id:"google/gemini-3.7-flash",inputModalities:["text","image"],provider:KO,spec:sD,label:"Gemini 3.7 Flash",name:"Gemini 3.7 Flash",description:"higher-quality coding & agentic workflows, fewer tokens",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1048576},GEMINI_3_6_FLASH:{id:"google/gemini-3.6-flash",inputModalities:["text","image"],provider:GO,spec:sD,label:"Gemini 3.6 Flash",name:"Gemini 3.6 Flash",description:"previous Gemini Flash, still fast & capable",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},GEMINI_3_5_FLASH:{id:"google/gemini-3.5-flash",inputModalities:["text","image"],provider:GO,spec:sD,label:"Gemini 3.5 Flash",name:"Gemini 3.5 Flash",description:"Pro-level coding proficiency, parallel agentic execution",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},GEMINI_3_5_FLASH_LITE:{id:"google/gemini-3.5-flash-lite",inputModalities:["text","image"],provider:GO,spec:sD,label:"Gemini 3.5 Flash Lite",name:"Gemini 3.5 Flash Lite",description:"upgraded agentic capabilities, ideal for subagents",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},GEMINI_3_1_FLASH_LITE:{id:"google/gemini-3.1-flash-lite",inputModalities:["text","image"],provider:GO,spec:sD,label:"Gemini 3.1 Flash Lite",name:"Gemini 3.1 Flash Lite",description:"high-volume workhorse model with implicit caching",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},FUGU_ULTRA:{id:"sakana/fugu-ultra",inputModalities:["text","image"],provider:GO,spec:sD,label:"Fugu Ultra",name:"Fugu Ultra",description:"multi-agent orchestration across frontier models",vendorLabel:"Sakana",reasoning:!0,reasoningEfforts:["high","xhigh"],contextWindow:1e6},NEMOTRON_3_ULTRA:{id:"nvidia/nemotron-3-ultra-550b-a55b",inputModalities:["text"],provider:nD,spec:sD,label:"Nemotron 3 Ultra",name:"Nemotron 3 Ultra",description:"open reasoning model for long-horizon autonomous agents",reasoning:!0,contextWindow:1e6},INKLING:{id:"thinkingmachines/inkling",inputModalities:["text","image"],provider:nD,spec:sD,label:"Inkling",name:"Inkling",description:"multimodal MoE reasoning",reasoning:!0,contextWindow:256e3},INKLING_SMALL:{id:"thinkingmachines/inkling-small",inputModalities:["text","image"],provider:nD,spec:sD,label:"Inkling Small",name:"Inkling Small",description:"lightweight MoE reasoning at lower cost and latency",reasoning:!0,contextWindow:1e6},SPACE_BUNNY_ALPHA:{id:"stealth/space-bunny-alpha",inputModalities:["text","image"],provider:KO,spec:sD,label:"Space Bunny Alpha",name:"Space Bunny Alpha",description:"stealth model with 1M context",vendorLabel:"Stealth",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6,maxOutputTokens:524288},LAGUNA_S_2_1_FREE:{id:"poolside/laguna-s-2.1-free",inputModalities:["text"],provider:nD,spec:sD,label:"Laguna S 2.1",name:"Laguna S 2.1",description:"open-weight agentic coding and long-horizon work",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods",reasoning:!0,contextWindow:256e3,maxOutputTokens:32768},LING_3_0_FLASH_FREE:{id:"inclusionai/ling-3.0-flash-free",inputModalities:["text"],provider:nD,spec:sD,label:"Ling 3.0 Flash",name:"Ling 3.0 Flash",description:"fast lightweight-MoE coding & agentic work",badge:"free",reasoning:!0,get hidden(){return isLingFlashFreeEnded()},contextWindow:256e3,maxOutputTokens:32768},LING_3_0_FLASH_SANTE_FREE:{id:"inclusionai/ling-3.0-flash-sante:free",inputModalities:["text"],provider:nD,spec:sD,label:"Ling 3.0 Flash Sante",name:"Ling 3.0 Flash Sante",description:"health & medicine tuned lightweight-MoE, still strong on code",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods. 100 requests a day per account",reasoning:!0,contextWindow:262144,maxOutputTokens:32768},MUSE_SPARK_1_1:{id:"meta/muse-spark-1.1",inputModalities:["text","image"],provider:GO,spec:sD,label:"Muse Spark 1.1",name:"Muse Spark 1.1",description:"agentic performance, tool use, and computer use",vendorLabel:"Meta",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},MUSE_SPARK_1_2:{id:"meta/muse-spark-1.2",inputModalities:["text","image"],provider:GO,spec:sD,label:"Muse Spark 1.2",name:"Muse Spark 1.2",description:"coding-optimized for agentic workflows and large codebases",vendorLabel:"Meta",notice:"{name} is going through upstream inference issues at {vendor}, not Command Code. Expect slower responses and occasional rate limits.",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},MUSE_SPARK_1_2_CONTRIBUTOR:{id:"meta/muse-spark-1.2-contributor",inputModalities:["text","image"],provider:GO,spec:sD,label:"Muse Spark 1.2 Contributor",name:"Muse Spark 1.2 Contributor",description:"Muse Spark 1.2 at ~95% off",vendorLabel:"Meta",notice:"{name} is going through upstream inference issues at {vendor}, not Command Code. Expect slower responses and occasional rate limits.",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},MUSE_SPARK_1_3:{id:"meta/muse-spark-1.3",inputModalities:["text","image"],provider:GO,spec:sD,label:"Muse Spark 1.3",name:"Muse Spark 1.3",description:"multimodal reasoning for long-horizon agentic and coding workflows",vendorLabel:"Meta",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1048576},MUSE_SPARK_1_3_CONTRIBUTOR:{id:"meta/muse-spark-1.3-contributor",inputModalities:["text","image"],provider:GO,spec:sD,label:"Muse Spark 1.3 Contributor",name:"Muse Spark 1.3 Contributor",description:"Muse Spark 1.3 at up to 95% off",vendorLabel:"Meta",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},GROK_4_5:{id:"xai/grok-4.5",inputModalities:["text","image"],provider:GO,spec:sD,label:"Grok 4.5",name:"Grok 4.5",description:"smartest model for coding, agentic tasks, knowledge work",vendorLabel:"xAI",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:5e5},GROK_4_6:{id:"xai/grok-4.6",inputModalities:["text","image"],provider:GO,spec:sD,label:"Grok 4.6",name:"Grok 4.6",description:"frontier performance on coding, knowledge work, and STEM",vendorLabel:"xAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:5e5},GROK_4_7:{id:"xai/grok-4.7",inputModalities:["text","image"],provider:GO,spec:sD,label:"Grok 4.7",name:"Grok 4.7",description:"coding and knowledge work, built for multi-hour tasks",vendorLabel:"xAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:5e5}},cD=[{canonicalId:"zai-org/GLM-5",providers:{[GO]:"zai/glm-5",[HO]:"zai-org/GLM-5"}},{canonicalId:"zai-org/GLM-5.3",providers:{[JO]:"zai-org/glm-5.3",[GO]:"zai/glm-5.3"}},{canonicalId:"zai-org/GLM-5.2",providers:{[qO]:"glm-5.2",[GO]:"zai/glm-5.2"}},{canonicalId:"poolside/laguna-s-2.1-free",providers:{[GO]:"poolside/laguna-s-2.1-free"}},{canonicalId:"inclusionai/ling-3.0-flash-free",providers:{[GO]:"inclusionai/ling-3.0-flash-free"}},{canonicalId:"inclusionai/ling-3.0-flash-sante:free",providers:{[KO]:"inclusionai/ling-3.0-flash-sante:free"}},{canonicalId:"zai-org/GLM-5.2-Fast",providers:{[GO]:"zai/glm-5.2-fast"}},{canonicalId:"zai-org/GLM-5.1",providers:{[GO]:"zai/glm-5.1"}},{canonicalId:"moonshotai/Kimi-K3",providers:{[JO]:"moonshotai/kimi-k3",[GO]:"moonshotai/kimi-k3"}},{canonicalId:"moonshotai/Kimi-K2.5",providers:{[GO]:"moonshotai/kimi-k2.5",[HO]:"moonshotai/Kimi-K2.5",[VO]:"workers-ai/@cf/moonshotai/kimi-k2.5"}},{canonicalId:"moonshotai/Kimi-K2.6",providers:{[GO]:"moonshotai/kimi-k2.6",[HO]:"moonshotai/Kimi-K2.6",[VO]:"workers-ai/@cf/moonshotai/kimi-k2.6"}},{canonicalId:"moonshotai/Kimi-K2.7-Code",providers:{[qO]:"kimi-k2.7-code",[GO]:"moonshotai/kimi-k2.7-code"}},{canonicalId:"moonshotai/Kimi-K2.7-Code-Highspeed",providers:{[GO]:"moonshotai/kimi-k2.7-code-highspeed"}},{canonicalId:"MiniMaxAI/MiniMax-M2.5",providers:{[GO]:"minimax/minimax-m2.5",[HO]:"MiniMaxAI/MiniMax-M2.5"}},{canonicalId:"deepseek/deepseek-v4-pro",providers:{[GO]:"deepseek/deepseek-v4-pro"}},{canonicalId:"deepseek/deepseek-v4-flash",providers:{[GO]:"deepseek/deepseek-v4.1-flash",[QO]:"morph-dsv4flash",[tD]:"deepseek-v4-flash-0731"}},{canonicalId:"deepseek/deepseek-v4-flash-vision-exp",providers:{[GO]:"deepseek/deepseek-v4.1-flash"}},{canonicalId:"deepseek/deepseek-v4.1-flash",providers:{[JO]:"deepseek/deepseek-v4.1-flash",[GO]:"deepseek/deepseek-v4.1-flash"}},{canonicalId:"deepseek/deepseek-v4-flash-fast",providers:{[XO]:"DeepSeek-V4-Flash-0731-Fast"}},{canonicalId:"Qwen/Qwen3.6-Max-Preview",providers:{[GO]:"alibaba/qwen-3.6-max-preview"}},{canonicalId:"Qwen/Qwen3.6-Plus",providers:{[qO]:"qwen3.6-plus",[GO]:"alibaba/qwen3.6-plus"}},{canonicalId:"Qwen/Qwen3.7-Max",providers:{[qO]:"qwen3.7-max",[GO]:"alibaba/qwen3.7-max"}},{canonicalId:"Qwen/Qwen3.7-Plus",providers:{[qO]:"qwen3.7-plus",[GO]:"alibaba/qwen3.7-plus"}},{canonicalId:"Qwen/Qwen3.8-Max-0902",providers:{[qO]:"qwen3.8-max-0902"}},{canonicalId:"Qwen/Qwen3.8-Omni-Flash",providers:{[GO]:"alibaba/qwen3.8-omni-flash"}},{canonicalId:"Qwen/Qwen3.8-Max",providers:{[qO]:"qwen3.8-max",[GO]:"alibaba/qwen3.8-max"}},{canonicalId:"Qwen/Qwen3.8-27B",providers:{[GO]:"alibaba/qwen3.8-27b"}},{canonicalId:"Qwen/Qwen3.8-Flash",providers:{[YO]:"qwen3.8-flash"}},{canonicalId:"Qwen/Qwen3.7-Flash",providers:{[GO]:"alibaba/qwen3.7-flash"}},{canonicalId:"MiniMaxAI/MiniMax-M3",providers:{[GO]:"minimax/minimax-m3"}},{canonicalId:aD,providers:{[GO]:"minimax/minimax-m3"}},{canonicalId:"MiniMaxAI/MiniMax-M2.7",providers:{[GO]:"minimax/minimax-m2.7"}},{canonicalId:"meituan/LongCat-2.0",providers:{[ZO]:"LongCat-2.0"}},{canonicalId:"stepfun/Step-5-Preview",providers:{[GO]:"stepfun/step-5-preview"}},{canonicalId:"stepfun/Step-3.7-Flash",providers:{[GO]:"stepfun/step-3.7-flash"}},{canonicalId:"stepfun/Step-3.5-Flash",providers:{[GO]:"stepfun/step-3.5-flash",[KO]:"stepfun/step-3.5-flash"}},{canonicalId:"z-ai/glm-5.3-flash",providers:{[JO]:"zai-org/glm-5.3-flash",[GO]:"zai/glm-5.3-flash"}},{canonicalId:"z-ai/glm-5.3-flashx",providers:{[GO]:"zai/glm-5.3-flashx"}},{canonicalId:"gpt-5.6-sol",providers:{[GO]:"openai/gpt-5.6-sol"}},{canonicalId:"gpt-5.6-terra",providers:{[GO]:"openai/gpt-5.6-terra"}},{canonicalId:"gpt-5.6-luna",providers:{[GO]:"openai/gpt-5.6-luna"}},{canonicalId:"stealth/space-bunny-alpha",providers:{[KO]:"stealth/space-bunny-alpha"}},{canonicalId:"tencent/Hy3",providers:{[KO]:"tencent/hy3:free"}},{canonicalId:"tencent/hy3-paid",providers:{[GO]:"tencent/hy3"}},{canonicalId:"tencent/hy4-preview",providers:{[eD]:"hy4-preview"}},{canonicalId:"xiaomi/mimo-v2.6-pro",providers:{[GO]:"xiaomi/mimo-v2.6-pro"}},{canonicalId:"xiaomi/mimo-v2.6-pro-ultraspeed",providers:{[GO]:"xiaomi/mimo-v2.6-pro-ultraspeed"}},{canonicalId:"xiaomi/mimo-v2.6-flash",providers:{[GO]:"xiaomi/mimo-v2.6-flash"}},{canonicalId:"xiaomi/mimo-v2.5-pro",providers:{[GO]:"xiaomi/mimo-v2.5-pro"}},{canonicalId:"xiaomi/mimo-v2.5",providers:{[GO]:"xiaomi/mimo-v2.5"}},{canonicalId:"google/gemini-3.8-flash",providers:{[GO]:"google/gemini-3.8-flash"}},{canonicalId:"google/gemini-3.7-flash",providers:{[KO]:"google/gemini-3.7-flash"}},{canonicalId:"google/gemini-3.6-flash",providers:{[GO]:"google/gemini-3.6-flash"}},{canonicalId:"google/gemini-3.5-flash",providers:{[GO]:"google/gemini-3.5-flash"}},{canonicalId:"google/gemini-3.5-flash-lite",providers:{[GO]:"google/gemini-3.5-flash-lite"}},{canonicalId:"google/gemini-3.1-flash-lite",providers:{[GO]:"google/gemini-3.1-flash-lite"}},{canonicalId:"nvidia/nemotron-3-ultra-550b-a55b",providers:{[GO]:"nvidia/nemotron-3-ultra-550b-a55b"}},{canonicalId:"thinkingmachines/inkling",providers:{[GO]:"thinkingmachines/inkling"}},{canonicalId:"thinkingmachines/inkling-small",providers:{[GO]:"thinkingmachines/inkling-small"}},{canonicalId:"sakana/fugu-ultra",providers:{[GO]:"sakana/fugu-ultra"}},{canonicalId:"xai/grok-4.5",providers:{[GO]:"xai/grok-4.5"}},{canonicalId:"xai/grok-4.6",providers:{[GO]:"xai/grok-4.6"}},{canonicalId:"xai/grok-4.7",providers:{[GO]:"xai/grok-4.7"}},{canonicalId:"meta/muse-spark-1.1",providers:{[GO]:"meta/muse-spark-1.1"}},{canonicalId:"meta/muse-spark-1.2",providers:{[GO]:"meta/muse-spark-1.2"}},{canonicalId:"meta/muse-spark-1.2-contributor",providers:{[GO]:"meta/muse-spark-1.2-contributor"}},{canonicalId:"meta/muse-spark-1.3",providers:{[GO]:"meta/muse-spark-1.3"}},{canonicalId:"meta/muse-spark-1.3-contributor",providers:{[GO]:"meta/muse-spark-1.3-contributor"}}],dD="2026-08-16T16:00:00Z",uD=[{startHourUtc:1,endHourUtc:4},{startHourUtc:6,endHourUtc:10}],mD=[1,2,3,4,5],pD=["2026-09-25","2026-09-26","2026-09-27","2026-10-01","2026-10-02","2026-10-03","2026-10-04","2026-10-05","2026-10-06","2026-10-07"],gD={effectiveFrom:dD,peakWindowsUtc:uD,peakDaysUtc:mD,offPeakDatesUtc:pD,peak:{promptCost:.44,completionCost:1.32,cacheReadCost:.014},offPeak:{promptCost:.22,completionCost:.66,cacheReadCost:.007}},hD=new Set([lD.GLM_5_2_FAST.id,lD.MINIMAX_M3.id,lD.MINIMAX_M3_FREE.id,lD.STEP_3_7_FLASH.id,lD.STEP_5_PREVIEW.id,lD.XIAOMI_MIMO_V2_6_PRO.id,lD.XIAOMI_MIMO_V2_6_PRO_ULTRASPEED.id,lD.XIAOMI_MIMO_V2_6_FLASH.id,lD.FUGU_ULTRA.id,lD.GROK_4_5.id,lD.GROK_4_6.id,lD.MUSE_SPARK_1_1.id,lD.MUSE_SPARK_1_2.id,lD.MUSE_SPARK_1_2_CONTRIBUTOR.id,lD.MUSE_SPARK_1_3.id,lD.MUSE_SPARK_1_3_CONTRIBUTOR.id,lD.LAGUNA_S_2_1_FREE.id,lD.QWEN_3_8_MAX_0902.id,lD.LONGCAT_2.id,lD.GLM_5_3_FLASHX.id,lD.SPACE_BUNNY_ALPHA.id]),fD=[{canonicalId:"zai-org/GLM-5",gatewaySlug:"zai/glm-5",order:["deepinfra","fireworks","togetherai","parasail","bedrock"],providers:{deepinfra:{slug:"deepinfra",promptCost:.8,completionCost:2.56,cacheReadCost:.16},fireworks:{slug:"fireworks",promptCost:1,completionCost:3.2,cacheReadCost:.2},togetherai:{slug:"togetherai",promptCost:1,completionCost:3.2,cacheReadCost:0},parasail:{slug:"parasail",promptCost:1,completionCost:3.2,cacheReadCost:0},bedrock:{slug:"bedrock",promptCost:1,completionCost:3.2,cacheReadCost:0}}},{canonicalId:"zai-org/GLM-5.2",gatewaySlug:"zai/glm-5.2",order:["novita","deepinfra"],providers:{novita:{slug:"novita",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},deepinfra:{slug:"deepinfra",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},zai:{slug:"zai",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},fireworks:{slug:"fireworks",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{canonicalId:"zai-org/GLM-5.3",gatewaySlug:"zai/glm-5.3",order:["digitalocean"],providers:{digitalocean:{slug:"digitalocean",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{canonicalId:"z-ai/glm-5.3-flash",gatewaySlug:"zai/glm-5.3-flash",order:["zai"],providers:{zai:{slug:"zai",promptCost:.15,completionCost:.5,cacheReadCost:.03}}},{canonicalId:"z-ai/glm-5.3-flashx",gatewaySlug:"zai/glm-5.3-flashx",order:["zai"],providers:{zai:{slug:"zai",promptCost:.37,completionCost:1.25,cacheReadCost:.075}}},{canonicalId:"zai-org/GLM-5.2-Fast",gatewaySlug:"zai/glm-5.2-fast",order:["wafer"],providers:{wafer:{slug:"wafer",promptCost:3,completionCost:10.25,cacheReadCost:.5}}},{canonicalId:"zai-org/GLM-5.1",gatewaySlug:"zai/glm-5.1",order:["deepinfra","fireworks"],providers:{deepinfra:{slug:"deepinfra",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},fireworks:{slug:"fireworks",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{canonicalId:"moonshotai/Kimi-K3",gatewaySlug:"moonshotai/kimi-k3",order:["moonshotai"],providers:{moonshotai:{slug:"moonshotai",promptCost:3,completionCost:15,cacheReadCost:.3}}},{canonicalId:"moonshotai/Kimi-K2.5",gatewaySlug:"moonshotai/kimi-k2.5",order:["moonshotai","fireworks","bedrock","togetherai"],providers:{fireworks:{slug:"fireworks",promptCost:.6,completionCost:3,cacheReadCost:.1},bedrock:{slug:"bedrock",promptCost:.6,completionCost:3,cacheReadCost:.1},togetherai:{slug:"togetherai",promptCost:.5,completionCost:2.8,cacheReadCost:0},moonshotai:{slug:"moonshotai",promptCost:.6,completionCost:3,cacheReadCost:.1}}},{canonicalId:"moonshotai/Kimi-K2.6",gatewaySlug:"moonshotai/kimi-k2.6",order:["moonshotai","fireworks"],providers:{moonshotai:{slug:"moonshotai",promptCost:.95,completionCost:4,cacheReadCost:.16},fireworks:{slug:"fireworks",promptCost:.95,completionCost:4,cacheReadCost:.16}}},{canonicalId:"moonshotai/Kimi-K2.7-Code",gatewaySlug:"moonshotai/kimi-k2.7-code",order:["moonshotai"],providers:{moonshotai:{slug:"moonshotai",promptCost:.95,completionCost:4,cacheReadCost:.19}}},{canonicalId:"moonshotai/Kimi-K2.7-Code-Highspeed",gatewaySlug:"moonshotai/kimi-k2.7-code-highspeed",order:["moonshotai"],providers:{moonshotai:{slug:"moonshotai",promptCost:1.9,completionCost:8,cacheReadCost:.38}}},{canonicalId:"MiniMaxAI/MiniMax-M2.5",gatewaySlug:"minimax/minimax-m2.5",order:["deepinfra","parasail","nebius","bedrock"],providers:{deepinfra:{slug:"deepinfra",promptCost:.3,completionCost:1.2,cacheReadCost:.03},parasail:{slug:"parasail",promptCost:.3,completionCost:1.2,cacheReadCost:0},nebius:{slug:"nebius",promptCost:.3,completionCost:1.2,cacheReadCost:0},bedrock:{slug:"bedrock",promptCost:.3,completionCost:1.2,cacheReadCost:0}}},{canonicalId:"deepseek/deepseek-v4-pro",gatewaySlug:"deepseek/deepseek-v4-pro",order:["deepseek"],providers:{deepseek:{slug:"deepseek",promptCost:.435,completionCost:.87,cacheReadCost:.003625,timeOfDay:{effectiveFrom:dD,peakWindowsUtc:uD,peakDaysUtc:mD,offPeakDatesUtc:pD,peak:{promptCost:1.32,completionCost:3.96,cacheReadCost:.044},offPeak:{promptCost:.66,completionCost:1.98,cacheReadCost:.022}}},fireworks:{slug:"fireworks",promptCost:1.74,completionCost:3.48,cacheReadCost:.0145}}},{canonicalId:"deepseek/deepseek-v4-flash",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],zdr:{gatewaySlug:"deepseek/deepseek-v4-flash",only:["baseten","fireworks","deepinfra"]},providers:{deepseek:{slug:"deepseek",promptCost:.14,completionCost:.28,cacheReadCost:.0028,timeOfDay:{effectiveFrom:dD,peakWindowsUtc:uD,peakDaysUtc:mD,offPeakDatesUtc:pD,peak:{promptCost:.3,completionCost:1.2,cacheReadCost:.006},offPeak:{promptCost:.15,completionCost:.6,cacheReadCost:.003}}},baseten:{slug:"baseten",promptCost:.13,completionCost:.26,cacheReadCost:.028},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007},deepinfra:{slug:"deepinfra",promptCost:.08,completionCost:.18,cacheReadCost:.016}}},{canonicalId:"deepseek/deepseek-v4-flash-vision-exp",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],zdr:{gatewaySlug:"deepseek/deepseek-v4.1-flash",only:["fireworks","deepinfra"]},providers:{deepseek:{slug:"deepseek",promptCost:.15,completionCost:.6,cacheReadCost:.003,timeOfDay:{effectiveFrom:dD,peakWindowsUtc:uD,peakDaysUtc:mD,offPeakDatesUtc:pD,peak:{promptCost:.3,completionCost:1.2,cacheReadCost:.006},offPeak:{promptCost:.15,completionCost:.6,cacheReadCost:.003}}},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007},deepinfra:{slug:"deepinfra",promptCost:.2,completionCost:.6,cacheReadCost:.006}}},{canonicalId:"deepseek/deepseek-v4.1-flash",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],providers:{deepseek:{slug:"deepseek",promptCost:.15,completionCost:.6,cacheReadCost:.003,timeOfDay:{effectiveFrom:dD,peakWindowsUtc:uD,peakDaysUtc:mD,offPeakDatesUtc:pD,peak:{promptCost:.3,completionCost:1.2,cacheReadCost:.006},offPeak:{promptCost:.15,completionCost:.6,cacheReadCost:.003}}},novita:{slug:"novita",promptCost:.3,completionCost:1.2,cacheReadCost:.006},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007},deepinfra:{slug:"deepinfra",promptCost:.2,completionCost:.6,cacheReadCost:.006},morph:{slug:"morph",promptCost:.3,completionCost:1.2,cacheReadCost:.03},baseten:{slug:"baseten",promptCost:.3,completionCost:1.2,cacheReadCost:.03},wafer:{slug:"wafer",promptCost:.3,completionCost:1.2,cacheReadCost:.01},modal:{slug:"modal",promptCost:.3,completionCost:1.2,cacheReadCost:.03}}},{canonicalId:"Qwen/Qwen3.6-Max-Preview",gatewaySlug:"alibaba/qwen-3.6-max-preview",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:1.3,completionCost:7.8,cacheReadCost:.26,cacheWriteCost:1.63}}},{canonicalId:"Qwen/Qwen3.6-Plus",gatewaySlug:"alibaba/qwen3.6-plus",order:["fireworks"],providers:{fireworks:{slug:"fireworks",promptCost:.5,completionCost:3,cacheReadCost:.1}}},{canonicalId:"Qwen/Qwen3.7-Max",gatewaySlug:"alibaba/qwen3.7-max",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:2.5,completionCost:7.5,cacheReadCost:.5,cacheWriteCost:3.13}}},{canonicalId:"Qwen/Qwen3.7-Plus",gatewaySlug:"alibaba/qwen3.7-plus",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:.4,completionCost:1.6,cacheReadCost:.08,cacheWriteCost:.5}}},{canonicalId:"Qwen/Qwen3.8-Omni-Flash",gatewaySlug:"alibaba/qwen3.8-omni-flash",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:.15,completionCost:.47,cacheReadCost:.016}}},{canonicalId:"Qwen/Qwen3.8-Max",gatewaySlug:"alibaba/qwen3.8-max",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:2,completionCost:6,cacheReadCost:.25,cacheWriteCost:2.5}}},{canonicalId:"Qwen/Qwen3.8-27B",gatewaySlug:"alibaba/qwen3.8-27b",order:["runinfra"],providers:{runinfra:{slug:"runinfra",promptCost:.4,completionCost:3,cacheReadCost:.04},deepinfra:{slug:"deepinfra",promptCost:.4,completionCost:3,cacheReadCost:.04}}},{canonicalId:"Qwen/Qwen3.7-Flash",gatewaySlug:"alibaba/qwen3.7-flash",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:.03,completionCost:.13,cacheReadCost:.006,cacheWriteCost:.038}}},{canonicalId:"MiniMaxAI/MiniMax-M3",gatewaySlug:"minimax/minimax-m3",order:["minimax"],providers:{minimax:{slug:"minimax",promptCost:.3,completionCost:1.2,cacheReadCost:.06}}},{canonicalId:aD,gatewaySlug:"minimax/minimax-m3",order:["minimax"],providers:{minimax:{slug:"minimax",promptCost:.3,completionCost:1.2,cacheReadCost:.06}}},{canonicalId:"MiniMaxAI/MiniMax-M2.7",gatewaySlug:"minimax/minimax-m2.7",order:["fireworks","togetherai"],providers:{fireworks:{slug:"fireworks",promptCost:.3,completionCost:1.2,cacheReadCost:.06},togetherai:{slug:"togetherai",promptCost:.3,completionCost:1.2,cacheReadCost:0}}},{canonicalId:"xiaomi/mimo-v2.6-pro",gatewaySlug:"xiaomi/mimo-v2.6-pro",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.435,completionCost:.87,cacheReadCost:.0036}}},{canonicalId:"xiaomi/mimo-v2.6-pro-ultraspeed",gatewaySlug:"xiaomi/mimo-v2.6-pro-ultraspeed",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:4.35,completionCost:8.7,cacheReadCost:.036}}},{canonicalId:"xiaomi/mimo-v2.6-flash",gatewaySlug:"xiaomi/mimo-v2.6-flash",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.14,completionCost:.28,cacheReadCost:.0028}}},{canonicalId:"xiaomi/mimo-v2.5-pro",gatewaySlug:"xiaomi/mimo-v2.5-pro",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.435,completionCost:.87,cacheReadCost:.0036}}},{canonicalId:"xiaomi/mimo-v2.5",gatewaySlug:"xiaomi/mimo-v2.5",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.14,completionCost:.28,cacheReadCost:.0028}}},{canonicalId:"stepfun/Step-5-Preview",gatewaySlug:"stepfun/step-5-preview",order:["stepfun"],providers:{stepfun:{slug:"stepfun",promptCost:1,completionCost:2.7,cacheReadCost:.05}}},{canonicalId:"stepfun/Step-3.5-Flash",gatewaySlug:"stepfun/step-3.5-flash",order:["deepinfra"],providers:{deepinfra:{slug:"deepinfra",promptCost:.09,completionCost:.3,cacheReadCost:.02}}},{canonicalId:"stepfun/Step-3.7-Flash",gatewaySlug:"stepfun/step-3.7-flash",order:["stepfun"],providers:{stepfun:{slug:"stepfun",promptCost:.2,completionCost:1.15,cacheReadCost:.04}}},{canonicalId:"gpt-5.6-sol",gatewaySlug:"openai/gpt-5.6-sol",order:["openai"],providers:{openai:{slug:"openai",promptCost:5,completionCost:30,cacheReadCost:.5,cacheWriteCost:6.25},azure:{slug:"azure",promptCost:5,completionCost:30,cacheReadCost:.5,cacheWriteCost:6.25},bedrock:{slug:"bedrock",promptCost:5,completionCost:30,cacheReadCost:.5,cacheWriteCost:6.25}}},{canonicalId:"gpt-5.6-terra",gatewaySlug:"openai/gpt-5.6-terra",order:["openai"],providers:{openai:{slug:"openai",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5},azure:{slug:"azure",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5},bedrock:{slug:"bedrock",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5}}},{canonicalId:"gpt-5.6-luna",gatewaySlug:"openai/gpt-5.6-luna",order:["openai"],providers:{openai:{slug:"openai",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25},azure:{slug:"azure",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25},bedrock:{slug:"bedrock",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25}}},{canonicalId:"google/gemini-3.8-flash",gatewaySlug:"google/gemini-3.8-flash",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:1.5,completionCost:7.5,cacheReadCost:.15}}},{canonicalId:"google/gemini-3.6-flash",gatewaySlug:"google/gemini-3.6-flash",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:1.5,completionCost:7.5,cacheReadCost:.15}}},{canonicalId:"google/gemini-3.5-flash",gatewaySlug:"google/gemini-3.5-flash",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:1.5,completionCost:9,cacheReadCost:.15}}},{canonicalId:"google/gemini-3.5-flash-lite",gatewaySlug:"google/gemini-3.5-flash-lite",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:.3,completionCost:2.5,cacheReadCost:.03}}},{canonicalId:"google/gemini-3.1-flash-lite",gatewaySlug:"google/gemini-3.1-flash-lite",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:.25,completionCost:1.5,cacheReadCost:.03}}},{canonicalId:"nvidia/nemotron-3-ultra-550b-a55b",gatewaySlug:"nvidia/nemotron-3-ultra-550b-a55b",order:["baseten","deepinfra"],providers:{baseten:{slug:"baseten",promptCost:.6,completionCost:2.4,cacheReadCost:.12},deepinfra:{slug:"deepinfra",promptCost:.5,completionCost:2.5,cacheReadCost:.15}}},{canonicalId:"thinkingmachines/inkling",gatewaySlug:"thinkingmachines/inkling",order:["baseten"],providers:{baseten:{slug:"baseten",promptCost:1,completionCost:4.05,cacheReadCost:.17}}},{canonicalId:"thinkingmachines/inkling-small",gatewaySlug:"thinkingmachines/inkling-small",order:["baseten"],providers:{baseten:{slug:"baseten",promptCost:.5,completionCost:1.2,cacheReadCost:.1}}},{canonicalId:"sakana/fugu-ultra",gatewaySlug:"sakana/fugu-ultra",order:["sakana"],providers:{sakana:{slug:"sakana",promptCost:5,completionCost:30,cacheReadCost:.5}}},{canonicalId:"xai/grok-4.5",gatewaySlug:"xai/grok-4.5",order:["xai"],providers:{xai:{slug:"xai",promptCost:2,completionCost:6,cacheReadCost:.5}}},{canonicalId:"xai/grok-4.6",gatewaySlug:"xai/grok-4.6",order:["xai"],providers:{xai:{slug:"xai",promptCost:2,completionCost:6,cacheReadCost:.5}}},{canonicalId:"xai/grok-4.7",gatewaySlug:"xai/grok-4.7",order:["xai"],providers:{xai:{slug:"xai",promptCost:1.2,completionCost:3.6,cacheReadCost:.3}}},{canonicalId:"meta/muse-spark-1.1",gatewaySlug:"meta/muse-spark-1.1",order:["meta"],providers:{meta:{slug:"meta",promptCost:1.25,completionCost:4.25,cacheReadCost:.15}}},{canonicalId:"meta/muse-spark-1.2",gatewaySlug:"meta/muse-spark-1.2",order:["meta"],providers:{meta:{slug:"meta",promptCost:1.25,completionCost:4.25,cacheReadCost:.15}}},{canonicalId:"meta/muse-spark-1.2-contributor",gatewaySlug:"meta/muse-spark-1.2-contributor",order:["meta"],providers:{meta:{slug:"meta",promptCost:.1,completionCost:.2,cacheReadCost:.002}}},{canonicalId:"meta/muse-spark-1.3",gatewaySlug:"meta/muse-spark-1.3",order:["meta"],providers:{meta:{slug:"meta",promptCost:1.25,completionCost:4.25,cacheReadCost:.15}}},{canonicalId:"meta/muse-spark-1.3-contributor",gatewaySlug:"meta/muse-spark-1.3-contributor",order:["meta"],providers:{meta:{slug:"meta",promptCost:.1,completionCost:.2,cacheReadCost:.002}}},{canonicalId:"tencent/hy3-paid",gatewaySlug:"tencent/hy3",order:["novita"],providers:{novita:{slug:"novita",promptCost:.14,completionCost:.58,cacheReadCost:.035},deepinfra:{slug:"deepinfra",promptCost:.14,completionCost:.58,cacheReadCost:.035}}},{canonicalId:"poolside/laguna-s-2.1-free",gatewaySlug:"poolside/laguna-s-2.1-free",order:["poolside"],providers:{poolside:{slug:"poolside",promptCost:0,completionCost:0,cacheReadCost:0}}},{canonicalId:"inclusionai/ling-3.0-flash-free",gatewaySlug:"inclusionai/ling-3.0-flash-free",order:["novita"],providers:{novita:{slug:"novita",promptCost:0,completionCost:0,cacheReadCost:0}}}],yD=[{canonicalId:"Qwen/Qwen3.8-Max-0902",slug:"qwen3.8-max-0902",promptCost:2,completionCost:6,cacheReadCost:.25},{canonicalId:"Qwen/Qwen3.8-Max",slug:"qwen3.8-max",promptCost:2,completionCost:6,cacheReadCost:.25},{canonicalId:"Qwen/Qwen3.7-Max",slug:"qwen3.7-max",promptCost:2.5,completionCost:7.5,cacheReadCost:.5},{canonicalId:"Qwen/Qwen3.7-Plus",slug:"qwen3.7-plus",promptCost:.4,completionCost:1.6,cacheReadCost:.08,contextTiers:[{maxInputTokens:256e3,promptCost:.4,completionCost:1.6,cacheReadCost:.08},{promptCost:1.2,completionCost:4.8,cacheReadCost:.24}]},{canonicalId:"Qwen/Qwen3.6-Plus",slug:"qwen3.6-plus",promptCost:.5,completionCost:3,cacheReadCost:.1,contextTiers:[{maxInputTokens:256e3,promptCost:.5,completionCost:3,cacheReadCost:.1},{promptCost:2,completionCost:6,cacheReadCost:.2}]},{canonicalId:"zai-org/GLM-5.2",slug:"glm-5.2",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},{canonicalId:"moonshotai/Kimi-K2.7-Code",slug:"kimi-k2.7-code",promptCost:.95,completionCost:4,cacheReadCost:.19},{canonicalId:"Qwen/Qwen3.8-Flash",slug:"qwen3.8-flash",promptCost:.16,completionCost:.47,cacheReadCost:.016}],SD=[{canonicalId:"deepseek/deepseek-v4-flash",slug:"morph-dsv4flash",promptCost:.14,completionCost:.28,cacheReadCost:.0028,timeOfDay:gD}],wD=[{canonicalId:"deepseek/deepseek-v4-flash-fast",slug:"DeepSeek-V4-Flash-0731-Fast",promptCost:.28,completionCost:.56,cacheReadCost:.07}],vD=[{canonicalId:"meituan/LongCat-2.0",slug:"LongCat-2.0",promptCost:.3,completionCost:1.2,cacheReadCost:.006}],kD={promptCost:.834,completionCost:2.501,cacheReadCost:.042},CD=[{canonicalId:"tencent/hy4-preview",slug:"hy4-preview",...kD}],bD=[{canonicalId:"stepfun/Step-3.5-Flash",openrouterSlug:"stepfun/step-3.5-flash",order:["siliconflow"],providers:{siliconflow:{slug:"siliconflow",promptCost:.1,completionCost:.3,zdr:!0,noTraining:!0}}},{canonicalId:"stealth/space-bunny-alpha",openrouterSlug:"stealth/space-bunny-alpha",order:["stealth"],providers:{stealth:{slug:"stealth",promptCost:0,completionCost:0,zdr:!1,noTraining:!1}}},{canonicalId:"tencent/Hy3",openrouterSlug:"tencent/hy3:free",order:["novita"],providers:{novita:{slug:"novita",promptCost:0,completionCost:0,zdr:!1,noTraining:!1}}},{canonicalId:"inclusionai/ling-3.0-flash-sante:free",openrouterSlug:"inclusionai/ling-3.0-flash-sante:free",order:["novita"],providers:{novita:{slug:"novita",promptCost:0,completionCost:0,zdr:!0,noTraining:!0}}},{canonicalId:"tencent/hy4-preview",openrouterSlug:"tencent/hy4-preview",order:["tencent"],providers:{tencent:{slug:"tencent",...kD,zdr:!0,noTraining:!0}}},{canonicalId:"gpt-5.6-terra",openrouterSlug:"openai/gpt-5.6-terra",order:["openai"],providers:{openai:{slug:"openai",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5,zdr:!1,noTraining:!0}}},{canonicalId:"gpt-5.6-luna",openrouterSlug:"openai/gpt-5.6-luna",order:["openai"],providers:{openai:{slug:"openai",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25,zdr:!1,noTraining:!0}}},{canonicalId:"google/gemini-3.7-flash",openrouterSlug:"google/gemini-3.7-flash",order:["google-vertex"],providers:{"google-vertex":{slug:"google-vertex",promptCost:1.5,completionCost:7.5,cacheReadCost:.15,cacheWriteCost:.08334,zdr:!0,noTraining:!0}}}],ED={"claude-sonnet-4-20250514":lD.SONNET_4_6.id,"claude-sonnet-4-5-20250929":lD.SONNET_4_6.id,"claude-opus-4-5-20251101":lD.OPUS_4_7.id,"claude-opus-4-6":lD.OPUS_4_7.id,"claude-haiku-4-5":lD.HAIKU_4_5.id},TD=lD.DEEPSEEK_V4_FLASH.id,PD={[BO]:"Anthropic",[WO]:"OpenAI",[HO]:"Open Source",[GO]:"Open Source",[zO]:"Open Source",[KO]:"Open Source"},MD=["Open Source","Stealth","Anthropic","OpenAI","Google"],xD={"command-code":{id:"command-code",label:"Command Code",shortLabel:"cmd",description:"recommended",supportedModelProviders:[BO,WO,zO,HO,GO,KO],requiresAuth:!1,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!0},anthropic:{id:"anthropic",label:"Anthropic",shortLabel:"anth",description:"Claude Pro/Max",supportedModelProviders:[BO],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!1},"github-copilot":{id:"github-copilot",label:"GitHub Copilot",shortLabel:"copilot",description:"Copilot subscription",supportedModelProviders:[BO,WO],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!0},codex:{id:"codex",label:"OpenAI ChatGPT/Codex",shortLabel:"openai",description:"ChatGPT Pro/Plus subscription",supportedModelProviders:[WO],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!1}};function laneSupportsModel(e,t){if(e.includes(t.provider))return!0;const n=t.vendorLabel?.toLowerCase();return null!=n&&e.includes(n)}function buildModelGroups(e){const t=Object.values(lD).filter(e=>!e.hidden),n=[];for(const r of Object.values(xD)){if(!("co"===e?r.visibleInCoMode:"command-code"===r.id))continue;const o=t.filter(e=>laneSupportsModel(r.supportedModelProviders,e));o.length>0&&n.push({providerId:r.id,label:r.label,models:o})}return n}__name(laneSupportsModel,"laneSupportsModel"),__name(buildModelGroups,"buildModelGroups");var ID=buildModelGroups("co"),AD=buildModelGroups("normal");function formatColoredUserSuffix(e){return isGenericUserName(e)?"":formatUserSuffix(e).replace(e,Et.cyan(e))}function getStartedLine(){return`${Et.dim("Run")} ${Et.cyan(getBinaryCommand())} ${Et.dim("to get started.")}`}function getLoginSuccessSuffix(e,t){const n=getLoginSuccessSuffixKind({userName:e,providerLabel:t});return"user"===n?formatColoredUserSuffix(e):"none"===n?"":" successfully"}function formatLoginSuccessStyled(e){const{userName:t,authFileName:n,providerLabel:r,providerWarning:o}=e,s=getLoginSuccessSuffix(t,r),i=r?` with ${Et.cyan(r)}`:"",a=[`${Et.green(gt.tick)} ${Et.bold("Logged in")}${s}${i}`];return o&&a.push(` ${Et.yellow(gt.warning)} ${Et.yellow(o)}`),a.push("",`${Et.dim("API key stored in")} ${Et.cyan(`~/.commandcode/${n}`)}`,getStartedLine()),a.join("\n")}function formatAlreadyLoggedInStyled(e){const t=formatColoredUserSuffix(e);return[`${Et.green(gt.tick)} ${Et.bold("Already logged in")}${t}`,"",getStartedLine()].join("\n")}new Set(["cc2@www3.in","cc3@www3.in","cc4@www3.in","cc5@www3.in","cc6@www3.in","cc7@www3.in","cc8@www3.in","cc9@www3.in","cc10@www3.in"].map(e=>e.toLowerCase())),__name(formatColoredUserSuffix,"formatColoredUserSuffix"),__name(getStartedLine,"getStartedLine"),__name(getLoginSuccessSuffix,"getLoginSuccessSuffix"),__name(formatLoginSuccessStyled,"formatLoginSuccessStyled"),__name(formatAlreadyLoggedInStyled,"formatAlreadyLoggedInStyled"),Gt(),SR(),Gt(),SR(),Gt(),SR(),Gt();var RD=[{id:"copilot",package:"@byokkit/cmd-provider-copilot",version:"0.1.1",displayName:"GitHub Copilot"},{id:"openai",package:"@byokkit/cmd-provider-openai",version:"0.1.2",displayName:"OpenAI"},{id:"anthropic",package:"@byokkit/cmd-provider-anthropic",version:"0.1.1",displayName:"Anthropic",discoverable:!1}];function builtinProviderPackage(e){return RD.find(t=>t.id===e)}function builtinPackageForSpecifier(e){return builtinProviderPackage(e)??RD.find(t=>t.package===e)}__name(builtinProviderPackage,"builtinProviderPackage"),__name(builtinPackageForSpecifier,"builtinPackageForSpecifier");var LD=new Map;function isProviderWorkspaceDevMode(){return"local"===getApiEnv()}function workspaceDistEntry(e){const t=e.replace(/^@[^/]+\//,"").replace(/^cmd-/,""),o=r(p(import.meta.url)),i=s(o,n("../..",t,"dist","index.js"));return A(i)?i:void 0}function devWorkspaceProviderEntry(e){if(isProviderWorkspaceDevMode())return workspaceDistEntry(e)}__name(isProviderWorkspaceDevMode,"isProviderWorkspaceDevMode"),__name(workspaceDistEntry,"workspaceDistEntry"),__name(devWorkspaceProviderEntry,"devWorkspaceProviderEntry");var OD=__name(async e=>{const t=builtinProviderPackage(e.moduleId);if(!t)return;const n=LD.get(e.moduleId);if(n)return n;const r=!1===t.discoverable,o=devWorkspaceProviderEntry(t.package)??(r?await resolveManuallyInstalledProviderEntry({runtime:createNodeRuntime(),pkg:t.package}):void 0),s=o?coerceProviderModule(await import(g(o).href)):await loadProviderModuleFromPackage({runtime:createNodeRuntime(),pkg:t.package,version:t.version,install:e.install,...e.onInstallStart?{onInstallStart:e.onInstallStart}:{}});return o&&dlog("[ProviderPackages] workspace/local provider",{pkg:t.package,entry:o}),s&&LD.set(e.moduleId,s),s},"realLoader");function loadBuiltinProviderModule(e){return OD(e)}async function loadInstalledBuiltinProviderModules(){const e=RD.map(e=>e.id),t=[];for(const n of e)try{const e=await loadBuiltinProviderModule({moduleId:n,install:!1});e&&t.push(e)}catch(e){dlog("[ProviderPackages] installed provider failed to load",{moduleId:n,error:e instanceof Error?e.message:String(e)})}return t}function uniqueProviderModules(e){const t=new Map;for(const n of e)t.has(n.id)||t.set(n.id,n);return[...t.values()]}async function importProviderModule(e,n,r=!1,o){if(e.startsWith(".")||t.isAbsolute(e))return import(g(t.resolve(n,e)).href);const s=builtinPackageForSpecifier(e);if(s)return{default:await loadBuiltinProviderModule({moduleId:s.id,install:r,onInstallStart:__name(({pkg:e})=>dlog("[ProviderPackages] installing settings provider",{pkg:e}),"onInstallStart")})};if(isNpmPackageSpecifier(e)){const t=createNodeRuntime();if(r&&!o)throw new Error(`Provider package '${e}' requires an explicit semver "version" in user settings before it can be installed`);const n=r?(await ensureProviderPackage({runtime:t,pkg:e,version:o,onInstallStart:__name(({pkg:e})=>dlog("[ProviderPackages] installing settings provider",{pkg:e}),"onInstallStart")})).entry:await resolveInstalledProviderEntry({runtime:t,pkg:e});if(!n)throw new Error(`Provider package '${e}' is not installed; run its explicit login/install flow first`);return import(g(n).href)}return import(e)}async function loadInstalledProviderModules(){const e=createNodeRuntime(),t=createConfigStore({config:await loadCommandCodeConfig({runtime:e}),runtime:e}).getProviders(),n=await loadInstalledBuiltinProviderModules(),r=await loadProviderModules({entries:t,builtins:n,importModule:__name(t=>importProviderModule(t,e.cwd()),"importModule")}),o={};for(const[e,n]of Object.entries(t))o[e]=n.module??n.npm??e;return{modules:uniqueProviderModules([...n,...r.modules]),errors:r.errors,sources:o}}async function settingsProviderSpecifier(e){const t=createNodeRuntime(),n=createConfigStore({config:await loadCommandCodeConfig({runtime:t}),runtime:t}).getProviders()[e];if(!n||!0===n.disabled)return;const r=n.module??n.npm;return r&&r!==e?{specifier:r,version:n.version}:void 0}async function loadSettingsProviderModule(e,t){const n=await settingsProviderSpecifier(e);if(n)return coerceProviderModule(await importProviderModule(n.specifier,createNodeRuntime().cwd(),t,n.version))}__name(loadBuiltinProviderModule,"loadBuiltinProviderModule"),__name(loadInstalledBuiltinProviderModules,"loadInstalledBuiltinProviderModules"),__name(uniqueProviderModules,"uniqueProviderModules"),__name(importProviderModule,"importProviderModule"),__name(loadInstalledProviderModules,"loadInstalledProviderModules"),__name(settingsProviderSpecifier,"settingsProviderSpecifier"),__name(loadSettingsProviderModule,"loadSettingsProviderModule");var DD=createCommandProviderAuthService({loadModule:__name(async({moduleId:e,reason:t,hasCredential:n})=>{const r="login"===t||n;try{const n=await loadSettingsProviderModule(e,r).catch(t=>{dlog("[ProviderPackages] settings provider failed to load",{moduleId:e,error:t instanceof Error?t.message:String(t)})});return n||await loadBuiltinProviderModule({moduleId:e,install:r,onInstallStart:__name(({pkg:e})=>dlog("[ProviderPackages] installing provider",{pkg:e,reason:t}),"onInstallStart")})}catch(n){if("login"===t)throw n;return void dlog("[ProviderPackages] provider unavailable for headers",{moduleId:e,error:n instanceof Error?n.message:String(n)})}},"loadModule"),providerToModuleId:Pk});async function providerAuthHeaders(e){return DD.providerAuthHeaders(e)}async function hasProviderCredential(e){return DD.hasProviderCredential(e)}async function providerLogin(e){return DD.login(e)}async function providerLogout(e){return DD.logout(e)}function resolveProviderAuthTarget(e){const t=resolveCommandProviderId(e.provider);if(!t)return{success:!1,error:`Unknown provider '${e.provider}'. Supported providers: anthropic, copilot, openai.`};const n=Qo[t],r=getProviderDisplayName(t);return n?.requiresAuth?{success:!0,provider:t,displayName:r}:{success:!1,error:`${r} does not use provider ${e.action}. Run cmd ${e.action} without a provider for Command Code account auth.`}}function printProviderInstructions(e){console.log(Et.yellow(` ${e}`)),console.log()}function printLoginLink(e){console.log(),console.log(Et.dim(" Login: ")+createOSC8Link(e,"Open auth page ↗")),console.log()}async function openAuthPage(e,t){await Pt(e,t).catch(()=>{console.log(Et.dim(` Could not auto-open browser. Open: ${e}`))})}async function confirmOpenAfterCode(){const e=await qe({message:"Press Enter to open GitHub and paste the code there.",active:"Open",inactive:"Cancel",initialValue:!0});if(Ye(e)||!0!==e)throw new Error("GitHub Copilot authentication cancelled")}function extractDeviceCode(e){const t=e.match(/copy\s+this\s+code:\s*([^\s]+)/i);return t?.[1]??null}async function printDeviceCode(e){const t=extractDeviceCode(e);if(!t)return void printProviderInstructions(e);const n=await writeClipboardText(t)?Et.dim(" (copied)"):"";console.log(` ${Et.yellow("Logging into Copilot, use this code:")} ${Et.bold(t)}${n}`),console.log()}async function performProviderAuth(e){const{provider:t}=e,n=getProviderDisplayName(t);try{let e=!0;const r=t===uo.COPILOT;if(!r){const t=await qe({message:`Open browser to sign in with ${n}?`,initialValue:!0});if(Ye(t))return{success:!1,error:`${n} authentication cancelled`};e=!0===t}return await providerLogin({provider:t,onPending:__name(async t=>{if(!t.prompt){if(r)return await printDeviceCode(t.instructions),await confirmOpenAfterCode(),await openAuthPage(t.url),console.log(),void console.log(` ${Et.dim(gt.circleFilled)} ${Et.dim("Waiting for GitHub...")}`);printProviderInstructions(t.instructions)}if(printLoginLink(t.url),!0===e&&await openAuthPage(t.url,t.prompt?void 0:{wait:!1,background:!0}),t.prompt){printProviderInstructions(t.instructions);const e=await Je({message:t.prompt.label,mask:"*"});if(Ye(e)||!String(e).trim())throw new Error("No authorization code provided");return{code:String(e).trim()}}console.log(` ${Et.dim(gt.circleFilled)} ${Et.dim("Waiting for authorization...")}`)},"onPending")}),{success:!0}}catch(e){const n=e instanceof Error?e.message:"Unknown error";return dlog("[ProviderAuth] performProviderAuth failed",{provider:t,error:n}),{success:!1,error:n}}}__name(providerAuthHeaders,"providerAuthHeaders"),__name(hasProviderCredential,"hasProviderCredential"),configureCommandUserConfigHost({providerAuthHeaders:providerAuthHeaders,hasProviderCredential:hasProviderCredential,log:__name((e,t)=>{void 0!==t?dlog(e,t):dlog(e)},"log")}),__name(providerLogin,"providerLogin"),__name(providerLogout,"providerLogout"),__name(resolveProviderAuthTarget,"resolveProviderAuthTarget"),__name(printProviderInstructions,"printProviderInstructions"),__name(printLoginLink,"printLoginLink"),__name(openAuthPage,"openAuthPage"),__name(confirmOpenAfterCode,"confirmOpenAfterCode"),__name(extractDeviceCode,"extractDeviceCode"),__name(printDeviceCode,"printDeviceCode"),__name(performProviderAuth,"performProviderAuth");var $D=__name(({message:e})=>st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.CYAN},st.createElement(kt,{type:"dots"})),st.createElement(Xe,null," ",e)),"LoadingIndicator"),ND=__name(({message:e})=>st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.GREEN},gt.tick),st.createElement(Xe,null," ",e)),"SuccessIndicator"),_D=__name(({children:e})=>st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,null," "),st.createElement(Qe,null,e)),"StatusContainer");async function checkExistingAuth(e){return checkExistingCommandAuth({runtime:getCommandConfigRuntime(),authFilePath:getAuthFile(e)})}function buildAlreadyLoggedInMessage(e){return formatAlreadyLoggedInStyled(e)}function buildSuccessMessage(e,t){return formatLoginSuccessStyled({userName:e,authFileName:t})}function showAuthIntro(){console.log("\n"),Ge.intro(heading({text:"Command Code Authentication"}))}function showLoginCancelMessage(e){Ve(`${gt.cross} ${e}`)}function printMessage(e){console.log(""),console.log(e),console.log("")}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=tt(st.createElement(PO,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}__name(checkExistingAuth,"checkExistingAuth"),__name(buildAlreadyLoggedInMessage,"buildAlreadyLoggedInMessage"),__name(buildSuccessMessage,"buildSuccessMessage"),__name(showAuthIntro,"showAuthIntro"),__name(showLoginCancelMessage,"showLoginCancelMessage"),__name(printMessage,"printMessage"),__name(runLoginWithApiKeyFlow,"runLoginWithApiKeyFlow");var FD=__name(({env:e,onComplete:t})=>{const[n,r]=at("checking"),[o,s]=at(null);return ct(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),ct(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),st.createElement(_D,null,"checking"===n&&st.createElement($D,{message:"Checking authentication status..."}),"logged_in"===n&&st.createElement(ND,{message:"Authenticated"}),"not_logged_in"===n&&st.createElement(ND,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=tt(st.createElement(FD,{env:e,onComplete:e=>{n(),t(e)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function performProviderLogin(e){const t=resolveProviderAuthTarget({provider:e.provider,action:"login"});if(!t.success)return{success:!1,error:t.error};try{const n=await(e.authenticateProvider??performProviderAuth)({provider:t.provider});return n.success?(await(e.persistProvider??persistProviderSelection)(t.provider),{success:!0,provider:t.provider,message:`Logged in to ${t.displayName}`}):{success:!1,provider:t.provider,error:n.error??`${t.displayName} authentication failed`}}catch(e){return{success:!1,provider:t.provider,error:getErrorMessage(e)}}}async function runLogin(){await applyStartupTheme();const e=getApiEnv();return runLoginSequence({checkExistingAuth:__name(()=>checkAuthWithSpinner(e),"checkExistingAuth"),showAlreadyLoggedIn:__name(({userName:e})=>printMessage(buildAlreadyLoggedInMessage(e)),"showAlreadyLoggedIn"),showIntro:showAuthIntro,runCommandLogin:runLoginWithApiKeyFlow,showLoginCancelled:__name(({message:e})=>showLoginCancelMessage(e),"showLoginCancelled"),trackFirstInstall:__name(()=>detectAndTrackFirstInstall({loadUserConfig:loadUserConfig,updateUserConfig:updateUserConfig,trackLifecycleEvent:__name(e=>trackLifecycleEvent({...e,isTelemetryEnabled:isTelemetryEnabled,createClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createClient"),log:dlog}),"trackLifecycleEvent"),getCliVersion:__name(()=>getPackageJson(import.meta.url).version??"unknown","getCliVersion"),log:dlog}),"trackFirstInstall"),showLoginSuccess:__name(({userName:t})=>printMessage(buildSuccessMessage(t,getCommandAuthFileName(e))),"showLoginSuccess"),log:dlog})}async function loginAction(e){try{await applyStartupTheme();const t=e?.trim();if(t){const e=await performProviderLogin({provider:t});e.success||(Ve(`${gt.cross} Login failed: ${e.error}`),process.exit(1)),ze(Et.green(`${gt.tick} ${e.message}`)),process.exit(0)}await runLogin(),process.exit(0)}catch(e){isUserCancellation(e)&&process.exit(0),console.error(`${gt.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(performProviderLogin,"performProviderLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction");var UD=new Be("login").description("Login with Command Code account or a provider").argument("[provider]","Provider to log in with").allowUnknownOption().allowExcessArguments().action(loginAction);function performLogout(){return performCommandLogout({runtime:getCommandConfigRuntime(),authFilePath:getAuthFile(),env:process.env,envVarName:Ao})}async function performProviderLogout(e){const t=resolveProviderAuthTarget({provider:e.provider,action:"logout"});if(!t.success)return{success:!1,error:t.error};try{const n=await(e.logoutProvider??providerLogout)({provider:t.provider});return{success:!0,provider:t.provider,removed:n,message:n?`Logged out of ${t.displayName}`:`No saved ${t.displayName} credential found`}}catch(e){const n=e instanceof Error?e.message:"Unknown error";return{success:!1,provider:t.provider,error:`Failed to log out of ${t.displayName}: ${n}`}}}function readLogoutUserName(){return getCommandAuthUserName({runtime:getCommandConfigRuntime(),path:getAuthFile()})}Gt(),SR(),__name(performLogout,"performLogout"),__name(performProviderLogout,"performProviderLogout"),__name(readLogoutUserName,"readLogoutUserName");var jD=__name(({userName:e})=>{const t=e?`Logging out ${e}...`:"Logging out...";return st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.CYAN},st.createElement(kt,{type:"dots"})),st.createElement(Xe,null," ",t))},"LoadingIndicator"),BD=__name(({userName:e,wasAuthenticated:t})=>{const n=!1===t?"Not currently authenticated":formatLogoutSuccess(e);return st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.GREEN},gt.tick),st.createElement(Xe,null," ",n))},"SuccessIndicator"),WD=__name(({errorMessage:e})=>st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.RED},gt.cross),st.createElement(Xe,{color:ER.RED}," Logout failed: ",e)),"ErrorIndicator"),HD=__name(({status:e,errorMessage:t,userName:n,wasAuthenticated:r})=>"loading"===e?st.createElement(jD,{userName:n}):"success"===e?st.createElement(BD,{userName:n,wasAuthenticated:r}):st.createElement(WD,{errorMessage:t}),"StatusDisplay"),GD=__name(({onComplete:e,userName:t})=>{const[n,r]=at("loading"),[o,s]=at(""),[i,a]=at(null);return ct(()=>{performLogout().then(e=>{a(e),e.success?r("success"):(s(e.error||"Unknown error"),r("error"))})},[]),ct(()=>{if(("success"===n||"error"===n)&&i){const t=setTimeout(()=>e(i),100);return()=>clearTimeout(t)}},[n,i,e]),st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,null," "),st.createElement(Qe,null,st.createElement(HD,{status:n,errorMessage:o,userName:t,wasAuthenticated:i?.wasAuthenticated})))},"LogoutSpinner");function printWarnings(e){0!==e.length&&(console.warn(Et.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(Et.yellow(` - ${e}`))))}async function renderLogoutUI(){let e;await applyStartupTheme();try{const t=await readLogoutUserName();e=t||void 0}catch{e=void 0}return new Promise(t=>{const{unmount:n}=tt(st.createElement(GD,{onComplete:e=>{n(),t(e)},userName:e}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function logoutAction(e){const t=e?.trim();if(t){const e=await performProviderLogout({provider:t});e.success||(console.error(`${gt.cross} ${e.error}`),process.exit(1)),console.log(`${gt.tick} ${e.message}`),process.exit(0)}const n=await renderLogoutUI();n.success||process.exit(1),printWarnings(n.warnings),console.log(""),process.exit(0)}__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction");var VD=new Be("logout").description("Log out of Command Code or a provider").argument("[provider]","Provider to log out from").allowUnknownOption().allowExcessArguments().action(logoutAction);function checkAuthStatus(e){return checkCommandAuthStatus({runtime:getCommandConfigRuntime(),path:getAuthFile(e),env:process.env})}async function buildStatusJson(){return resolveCommandAuthStatusJson({version:getPackageJson(import.meta.url).version??"unknown",runtime:getCommandConfigRuntime(),apiEnv:getApiEnv(),env:process.env})}async function statusAction(e){if(e.json){const e=await buildStatusJson(),t=!e.authenticated||e.error?1:0;return void process.stdout.write(`${JSON.stringify(e)}\n`,()=>process.exit(t))}const t=Mt("Checking authentication status...").start();try{const e=getApiEnv(),n=await checkAuthStatus(e);n.error&&(t.fail(Et.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(t.fail(Et.red("Not authenticated")),console.log(""),console.log(`${Et.dim("Run")} ${Et.cyan(`${getBinaryCommand()} auth login`)} ${Et.dim("to authenticate.")}`),console.log(""),process.exit(1));const r=isGenericCommandAuthUserName(n.userName)?"":` as ${Et.cyan(n.userName)}`;t.succeed("Authentication verified"),console.log(`${Et.green(gt.tick)} ${Et.bold("Authenticated")}${r}`),console.log(` ${Et.dim("Provider:")} ${Et.cyan("Command Code")}`),n.fromEnv&&console.log(` ${Et.dim("Source:")} ${Et.cyan(`$${Ao}`)} ${Et.dim("(env var)")}`),console.log(""),process.exit(0)}catch(e){t.fail(Et.red(`Status check failed: ${e instanceof Error?e.message:"Unknown error"}`)),process.exit(1)}}Gt(),SR(),__name(checkAuthStatus,"checkAuthStatus"),__name(buildStatusJson,"buildStatusJson"),__name(statusAction,"statusAction");var zD=new Be("status").description("Show authentication status").option("--json","Output status as JSON for automation").allowUnknownOption().allowExcessArguments().action(statusAction);function parseValue(e){try{const t=JSON.parse(e);if("string"==typeof t||"boolean"==typeof t||"number"==typeof t)return t}catch{}return e}function rowValue(e){return e.currentValue}function rowMatchesScope(e,t){return"effective"===t||e.scope===t}function printValue(e,t){console.log(t?JSON.stringify(e,null,2):String(e))}function liveApplyInfo(e){return e===Mp?{liveSessionReloadsOnNextRound:!1,message:"This sets the default model for new sessions. Use /model to change the running session."}:{liveSessionReloadsOnNextRound:!0,message:"A running session picks this up at the start of its next round."}}function unknownKeyMessage(e,t){const n=e.suggest({raw:t});return 0===n.length?`Unknown configuration setting: ${t}`:`Unknown configuration setting: ${t}. Did you mean: ${n.join(", ")}?`}async function createRegistry(){const e=getCommandConfigRuntime(),t=await loadCommandCodeConfig({runtime:e});let n=normalizePermissionMode(t.permissions?.defaultMode)??normalizePermissionMode(t.permissionMode)??"default";return createConfigToolRegistry({runtime:e,listModelIds:__name(()=>listKnownModelIds(),"listModelIds"),model:{current:__name(()=>getConfiguredModel(),"current"),set:__name(async({model:e})=>persistDefaultModel({model:e}),"set")},permissionMode:{current:__name(()=>n,"current"),set:__name(async({mode:t})=>{await updateUserSettings({runtime:e,patch:{permissions:{defaultMode:t}}}),n=t},"set")}})}function withCommonOptions(e){return e.addOption(new We("--scope <scope>","Configuration scope").choices(["effective","user","project"]).default("effective")).option("--json","Print machine-readable JSON")}new Be("auth").description("Manage authentication with Command Code").addCommand(UD).addCommand(VD).addCommand(zD),Gt(),SR(),__name(parseValue,"parseValue"),__name(rowValue,"rowValue"),__name(rowMatchesScope,"rowMatchesScope"),__name(printValue,"printValue"),__name(liveApplyInfo,"liveApplyInfo"),__name(unknownKeyMessage,"unknownKeyMessage"),__name(createRegistry,"createRegistry"),__name(withCommonOptions,"withCommonOptions");var KD=withCommonOptions(new Be("list").alias("ls").description("List configuration settings")).action(async e=>{const t=await createRegistry(),n=(await t.list()).filter(t=>rowMatchesScope(t,e.scope));if(e.json)printValue(n.map(e=>({id:e.id,value:rowValue(e),scope:e.scope,locked:!0===e.locked})),!0);else for(const e of n)console.log(`${e.id} = ${JSON.stringify(rowValue(e))} (${e.scope})`)}),qD=withCommonOptions(new Be("get").description("Read one configuration setting").argument("<key>","Setting id")).action(async(e,t,n)=>{const r=await createRegistry(),o=r.resolveId({raw:e});o||n.error(unknownKeyMessage(r,e));const s=await r.get({id:o});s||n.error(unknownKeyMessage(r,e)),rowMatchesScope(s,t.scope)||n.error(`${o} is not available in ${t.scope} scope. It lives in ${s.scope} scope - use --scope ${s.scope}.`),t.json?printValue({id:s.id,value:rowValue(s),scope:s.scope},!0):printValue(rowValue(s),!1)}),YD=withCommonOptions(new Be("set").description("Validate and write one configuration setting").argument("<key>","Setting id").argument("<value>","JSON scalar or plain string value")).action(async(e,t,n,r)=>{"effective"===n.scope&&r.error("config set requires --scope user or project");const o=await createRegistry(),s=o.resolveId({raw:e});s||r.error(unknownKeyMessage(o,e));const i=await o.get({id:s});let a;i||r.error(unknownKeyMessage(o,e)),rowMatchesScope(i,n.scope)||r.error(`${s} cannot be written in ${n.scope} scope. It is a ${i.scope}-scope setting - use --scope ${i.scope}.`);try{a=await o.set({id:s,value:parseValue(t)})}catch(e){r.error(e instanceof Error?e.message:String(e))}const l=liveApplyInfo(a.id),c={id:a.id,previousValue:a.previousValue,newValue:a.newValue,scope:n.scope,liveSessionReloaded:!1,liveSessionReloadsOnNextRound:l.liveSessionReloadsOnNextRound};n.json?printValue(c,!0):(console.log(`${a.id}: ${JSON.stringify(a.previousValue)} -> ${JSON.stringify(a.newValue)} (${n.scope})`),console.log(l.message))}),JD=new Be("default").description("Reset one configuration setting to its default value").argument("<key>","Setting id").option("--json","Print machine-readable JSON").action(async(e,t,n)=>{const r=await createRegistry(),o=r.resolveId({raw:e});o||n.error(unknownKeyMessage(r,e));const s=await r.get({id:o});let i;s||n.error(unknownKeyMessage(r,e)),void 0===s.defaultValue&&n.error(`${o} has no default value to reset to.`);try{i=await r.set({id:o,value:s.defaultValue})}catch(e){n.error(e instanceof Error?e.message:String(e))}const a=liveApplyInfo(i.id),l={id:i.id,previousValue:i.previousValue,newValue:i.newValue,scope:s.scope,liveSessionReloaded:!1,liveSessionReloadsOnNextRound:a.liveSessionReloadsOnNextRound};t.json?printValue(l,!0):(console.log(`${i.id}: ${JSON.stringify(i.previousValue)} -> ${JSON.stringify(i.newValue)} (default, ${s.scope})`),console.log(a.message))}),QD=new Be("config").description("Inspect and update validated configuration settings").addCommand(KD).addCommand(qD).addCommand(YD).addCommand(JD);async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Mt("Opening the GitHub issue…").start();try{await Pt(t,{wait:!1,background:!0}),n.succeed(`Opened ${createOSC8Link(t,"the GitHub issue",!1)} in your browser`),console.log("")}catch(e){n.fail("Failed to open browser"),console.log(""),console.log(createOSC8Link(t,"Open GitHub issue manually",!1)),console.log("")}}Gt(),SR(),__name(openGitHubIssue,"openGitHubIssue");var XD=new Be("feedback").alias("issue").description("Report a bug or share feedback — opens a GitHub issue").argument("[title]","Optional issue title").action(openGitHubIssue);Gt();var ZD=new Be("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});Gt(),Gt(),SR(),Gt(),SR();var e$=__name(({icon:e,label:t,children:n})=>st.createElement(Xe,null,st.createElement(Xe,{color:ER.CYAN},e," "),st.createElement(Xe,{color:ER.DIM},t.padEnd(12)),n),"Row"),t$=__name(({title:e})=>st.createElement(Xe,null,st.createElement(Xe,{color:ER.GRAY},"───"),st.createElement(Xe,{color:ER.WHITE}," ",e," "),st.createElement(Xe,{color:ER.GRAY},"─".repeat(35))),"Header"),n$=__name(({title:e,marginTop:t=0,children:n})=>st.createElement(Qe,{flexDirection:"column",marginTop:t},st.createElement(t$,{title:e}),st.createElement(Qe,{flexDirection:"column",paddingY:1},n)),"Section"),r$=__name(({host:e,systemInfo:t})=>st.createElement(n$,{title:"System Information"},st.createElement(e$,{icon:gt.bullet,label:"Version"},st.createElement(Xe,{color:ER.GREEN},t.version)),st.createElement(e$,{icon:gt.bullet,label:"Date"},st.createElement(Xe,null,formatDate())),st.createElement(e$,{icon:gt.pointer,label:"Platform"},st.createElement(Xe,{color:ER.GREEN},t.os),st.createElement(Xe,{color:ER.DIM}," ","(",e.platform,", ",e.arch,")")),st.createElement(e$,{icon:gt.triangleUp,label:"Hostname"},st.createElement(Xe,null,e.hostname)),st.createElement(e$,{icon:gt.bullet,label:"User"},st.createElement(Xe,{color:ER.YELLOW},e.username)),st.createElement(e$,{icon:gt.bullet,label:"CPUs"},st.createElement(Xe,{color:ER.MAGENTA},e.cpus.length," cores")),st.createElement(e$,{icon:gt.bullet,label:"Memory"},st.createElement(Xe,{color:ER.CYAN},e.totalMemoryGb," GB")),st.createElement(e$,{icon:gt.play,label:"Uptime"},st.createElement(Xe,null,formatUptime(e.uptimeSeconds))),st.createElement(e$,{icon:gt.arrowRight,label:"Home"},st.createElement(Xe,{color:ER.DIM},e.homeDir)),st.createElement(e$,{icon:gt.pointer,label:"Shell"},st.createElement(Xe,null,t.shell)),st.createElement(e$,{icon:gt.bullet,label:"Node"},st.createElement(Xe,{color:ER.GREEN},e.nodeVersion)),st.createElement(e$,{icon:gt.pointer,label:"Terminal"},st.createElement(Xe,{color:ER.CYAN},t.terminal)),st.createElement(e$,{icon:gt.bullet,label:"IDE"},st.createElement(Xe,null,t.ide))),"SystemInfoSection"),o$=__name(({cpus:e})=>st.createElement(n$,{title:"CPU Details",marginTop:1},e.map((e,t)=>st.createElement(e$,{key:t,icon:gt.bullet,label:`Core ${t}`},st.createElement(Xe,null,e.model),st.createElement(Xe,{color:ER.YELLOW}," @ ",e.speedMHz," MHz")))),"CPUDetailsSection"),s$=__name(({addresses:e})=>st.createElement(n$,{title:"Network",marginTop:1},e.map((e,t)=>st.createElement(e$,{key:`${e.interfaceName}-${t}`,icon:gt.bullet,label:e.interfaceName},st.createElement(Xe,{color:ER.GREEN},e.address)))),"NetworkSection"),i$=__name(({host:e,verbose:t,systemInfo:n})=>st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,null,"System Information"),st.createElement(Xe,null,"─".repeat(40)),st.createElement(Xe,null,"Version ",n.version),st.createElement(Xe,null,"Date ",formatDate()),st.createElement(Xe,null,"Platform ",n.os," (",e.platform,", ",e.arch,")"),st.createElement(Xe,null,"Hostname ",e.hostname),st.createElement(Xe,null,"User ",e.username),st.createElement(Xe,null,"CPUs ",e.cpus.length," cores"),st.createElement(Xe,null,"Memory ",e.totalMemoryGb," GB"),st.createElement(Xe,null,"Uptime ",formatUptime(e.uptimeSeconds)),st.createElement(Xe,null,"Home ",e.homeDir),st.createElement(Xe,null,"Shell ",n.shell),st.createElement(Xe,null,"Node ",e.nodeVersion),st.createElement(Xe,null,"Terminal ",n.terminal),st.createElement(Xe,null,"IDE ",n.ide),t&&st.createElement(st.Fragment,null,st.createElement(Xe,null,"\n","CPU Details"),st.createElement(Xe,null,"─".repeat(40)),e.cpus.map((e,t)=>st.createElement(Xe,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speedMHz," MHz")),st.createElement(Xe,null,"\n","Network"),st.createElement(Xe,null,"─".repeat(40)),e.externalIpv4.map((e,t)=>st.createElement(Xe,{key:`${e.interfaceName}-${t}`},e.interfaceName.padEnd(12),e.address)))),"PlainTextInfo"),a$=__name(({host:e,verbose:t,systemInfo:n})=>st.createElement(Qe,{flexDirection:"column"},st.createElement(r$,{host:e,systemInfo:n}),t&&st.createElement(o$,{cpus:e.cpus}),t&&st.createElement(s$,{addresses:e.externalIpv4})),"StyledInfo"),l$=__name(({verbose:e=!1,text:t=!1,systemInfo:n})=>{const{exit:r}=rt();ct(()=>{const e=setTimeout(()=>r(),50);return()=>clearTimeout(e)},[r]);const o=dt(()=>collectHostDiagnostics(),[]);return t?st.createElement(i$,{host:o,verbose:e,systemInfo:n}):st.createElement(a$,{host:o,verbose:e,systemInfo:n})},"InfoUI");async function runInfo(e){await applyStartupTheme();const t=getSystemInfo(),{waitUntilExit:n}=tt(st.createElement(l$,{verbose:e.verbose,text:e.text,systemInfo:t}));await n()}__name(runInfo,"runInfo");var c$=new Be("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{await runInfo(e)});function formatUsd(e){const t=e.toFixed(6).replace(/0+$/,"").replace(/\.$/,""),n=t.indexOf(".");return`$${(-1===n?0:t.length-n-1)>=2?t:e.toFixed(2)}`}Gt(),SR(),Gt(),SR(),Gt(),SR(),Gt(),Gt(),__name(formatUsd,"formatUsd");var d$=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatShortDateUtc(e){const t=d$[Number(e.slice(5,7))-1],n=Number(e.slice(8,10));return!t||!Number.isInteger(n)||n<1?e:`${t} ${n}`}function peakHoursPerDay(e){return e.reduce((e,t)=>e+(t.endHourUtc-t.startHourUtc),0)}__name(formatShortDateUtc,"formatShortDateUtc"),__name(peakHoursPerDay,"peakHoursPerDay");var u$={"zai-org/GLM-5":{inputCost:1,outputCost:3.2,cacheReadCost:.2},"zai-org/GLM-5.2":{inputCost:1.4,outputCost:4.4,cacheReadCost:.26}};function advertisedBandOf(e,t){const n=e.timeOfDay;return n?t<Date.parse(n.effectiveFrom)?e:n.offPeak:e}function primaryUpstreamOf(e,t){const n=e.order[0],r=n?e.providers[n]:void 0;if(!r)throw new Error(`display-pricing: billing entry "${t}" has no primary upstream in its \`order\``);return r}__name(advertisedBandOf,"advertisedBandOf"),__name(primaryUpstreamOf,"primaryUpstreamOf");var m$={inputCost:.042,outputCost:0,cacheReadCost:0};function jevBilledRates(e){return isJevFree(e)?{inputCost:0,outputCost:0,cacheReadCost:0}:m$}function getDisplayRates(e,t=Date.now()){const n=u$[e];if(n)return n;if("typesafe/jev"===e)return jevBilledRates(t);const r=Object.values(rD).flat().find(t=>t.id===e);if(r)return{inputCost:r.promptCost,outputCost:r.completionCost,cacheReadCost:r.cacheHitCost??0,...null!=r.cacheWrite5mCost&&{cacheWriteCost:r.cacheWrite5mCost},...null!=r.cacheWrite1hCost&&{cacheWrite1hCost:r.cacheWrite1hCost}};const o=fD.find(t=>t.canonicalId===e);if(o)return toDisplayRates(advertisedBandOf(primaryUpstreamOf(o,e),t));const s=bD.find(t=>t.canonicalId===e);if(s){const t=primaryUpstreamOf(s,e);return{inputCost:t.promptCost,outputCost:t.completionCost,cacheReadCost:t.cacheReadCost??0,...null!=t.cacheWriteCost&&{cacheWriteCost:t.cacheWriteCost}}}const i=yD.find(t=>t.canonicalId===e);if(i)return{inputCost:i.promptCost,outputCost:i.completionCost,cacheReadCost:i.cacheReadCost};const a=SD.find(t=>t.canonicalId===e);if(a)return{inputCost:a.promptCost,outputCost:a.completionCost,cacheReadCost:a.cacheReadCost};const l=wD.find(t=>t.canonicalId===e);if(l)return{inputCost:l.promptCost,outputCost:l.completionCost,cacheReadCost:l.cacheReadCost};const c=vD.find(t=>t.canonicalId===e);if(c)return{inputCost:c.promptCost,outputCost:c.completionCost,cacheReadCost:c.cacheReadCost};const d=CD.find(t=>t.canonicalId===e);if(d)return{inputCost:d.promptCost,outputCost:d.completionCost,cacheReadCost:d.cacheReadCost};throw new Error(`display-pricing: unknown billing id "${e}": not in MODELS, GATEWAY_MODEL_PRICING, OPENROUTER_MODEL_PRICING, ALIBABA_MODEL_PRICING, MORPH_MODEL_PRICING, WAFER_MODEL_PRICING, LONGCAT_MODEL_PRICING, TENCENT_MODEL_PRICING, or the decision model (JEV_MODEL_ID)`)}function toDisplayRates(e){return{inputCost:e.promptCost,outputCost:e.completionCost,cacheReadCost:e.cacheReadCost??0,...null!=e.cacheWriteCost&&{cacheWriteCost:e.cacheWriteCost}}}function getDisplayTimeOfDay(e){if(u$[e])return;const t=fD.find(t=>t.canonicalId===e),n=t?.order[0],r=n?t?.providers[n]?.timeOfDay:void 0;if(!r)return;const o=peakHoursPerDay(r.peakWindowsUtc);return{effective:r.effectiveFrom,peak:toDisplayRates(r.peak),offPeak:toDisplayRates(r.offPeak),peakWindowsUtc:r.peakWindowsUtc,peakDaysUtc:r.peakDaysUtc,peakHoursPerDay:o,offPeakHoursPerDay:24-o}}function timeOfDayNote(e){const t=`${formatUsd(e.offPeak.inputCost)}/${formatUsd(e.offPeak.outputCost)}`,n=`${formatUsd(e.peak.inputCost)}/${formatUsd(e.peak.outputCost)}`;return`From ${formatShortDateUtc(e.effective)}: ${t} off-peak, ${n} peak (${e.peakHoursPerDay}h/day)`}function timeOfDayScheduledChanges(){const e={};for(const t of fD){const n=getDisplayTimeOfDay(t.canonicalId);n&&(e[t.canonicalId]={effective:n.effective,rates:n.offPeak,note:timeOfDayNote(n)})}return e}function findModelById(e){return Object.values(lD).find(t=>t.id===e)}function getModelNotice(e){const t=findModelById(e);if(!t?.notice)return;const n=t.vendorLabel??PD[t.provider]??"the upstream provider";return t.notice.replaceAll("{name}",t.name).replaceAll("{vendor}",n)}function getProviderFromModel(e){return findModelById(e)?.provider??BO}function getAllModelOptions(){return Object.values(lD)}function getModelGroupLabel(e){return e.vendorLabel??PD[e.provider]??e.provider}function groupModelsByDisplayOrder(e){const t=new Map;for(const n of e){const e=getModelGroupLabel(n),r=t.get(e)??[];r.push(n),t.set(e,r)}return[...MD.filter(e=>t.has(e)),...[...t.keys()].filter(e=>!MD.includes(e))].map(e=>({label:e,models:t.get(e)}))}function getModelGroupsInOrder(){return groupModelsByDisplayOrder(getAllModelOptions().filter(e=>!e.hidden))}function resolveKnownModelId2(e){const t=getCanonicalModelId(e);return findModelById(t)?t:void 0}function modelSupportsVision(e){const t=findModelById(getCanonicalModelId(e));return!t?.inputModalities||t.inputModalities.includes("image")}function modelSupportsZdr(e){return!hD.has(getCanonicalModelId(e))}__name(jevBilledRates,"jevBilledRates"),__name(getDisplayRates,"getDisplayRates"),__name(toDisplayRates,"toDisplayRates"),__name(getDisplayTimeOfDay,"getDisplayTimeOfDay"),__name(timeOfDayNote,"timeOfDayNote"),__name(timeOfDayScheduledChanges,"timeOfDayScheduledChanges"),timeOfDayScheduledChanges(),Gt(),__name(findModelById,"findModelById"),__name(getModelNotice,"getModelNotice"),__name(getProviderFromModel,"getProviderFromModel"),__name(getAllModelOptions,"getAllModelOptions"),__name(getModelGroupLabel,"getModelGroupLabel"),__name(groupModelsByDisplayOrder,"groupModelsByDisplayOrder"),__name(getModelGroupsInOrder,"getModelGroupsInOrder"),__name(resolveKnownModelId2,"resolveKnownModelId"),__name(modelSupportsVision,"modelSupportsVision"),__name(modelSupportsZdr,"modelSupportsZdr");var p$=/[-@]\d{8}$/,g$="workers-ai/@cf/";function ossEntryMatches(e,t){return e.canonicalId.toLowerCase()===t||Object.values(e.providers).some(e=>"string"==typeof e&&e.toLowerCase()===t)}function tryResolveCanonical2(e){const t=(ED[e.toLowerCase()]??e).toLowerCase(),n=Object.values(lD).find(e=>e.id.toLowerCase()===t);if(n)return n.id;const r=cD.find(e=>e.canonicalId.toLowerCase()===t)??cD.find(e=>ossEntryMatches(e,t));return r?.canonicalId}function getCanonicalModelId(e){if(!e)return e;const t=e.startsWith(g$)?e.slice(g$.length):e,n=tryResolveCanonical2(t);if(n)return n;const r=t.replace(p$,"");return r===t?t:tryResolveCanonical2(r)??t}function getModelDisplayName(e){const t=getCanonicalModelId(e),n=Object.values(lD).find(e=>e.id===t);return n?.name??e}__name(ossEntryMatches,"ossEntryMatches"),__name(tryResolveCanonical2,"tryResolveCanonical"),__name(getCanonicalModelId,"getCanonicalModelId"),__name(getModelDisplayName,"getModelDisplayName"),Gt(),SR();var h$=null;function setRegisteredProviderModules(e){h$=new Set(e.modules.map(e=>e.id))}function isProviderLaneRegistered(e){const t=h$;if(!t)return!0;if(!Xo[e.providerId]?.requiresAuth)return!0;const n=Pk[e.providerId]??e.providerId;return t.has(n)}function isProviderLaneListable(e){if(!Xo[e.providerId]?.requiresAuth)return!0;const t=Pk[e.providerId]??e.providerId,n=builtinProviderPackage(t);return!(!n||!1===n.discoverable)||(h$?.has(t)??!1)}function filterModelGroupsByRegisteredModules(e){return e.filter(e=>isProviderLaneRegistered({providerId:e.providerId}))}__name(setRegisteredProviderModules,"setRegisteredProviderModules"),__name(isProviderLaneRegistered,"isProviderLaneRegistered"),__name(isProviderLaneListable,"isProviderLaneListable"),__name(filterModelGroupsByRegisteredModules,"filterModelGroupsByRegisteredModules");var f$=getPackageJson(import.meta.url),y$="string"==typeof f$.version&&f$.version.trim()?f$.version:"unknown",S$=new Set(Object.values(Pk));function selectActiveOAuthProviderModules(e){const t=e.provider?Pk[e.provider]:void 0;return e.modules.filter(e=>!S$.has(e.id)||e.id===t)}async function restoreSelectedOAuthProviderModule(e){if(!e.provider)return;if(e.disabled)return;const t=Pk[e.provider];if(!t)return;if(e.modules.some(e=>e.id===t))return;if(!await e.hasCredential(e.provider))return;const n=await e.loadModule(t);if(!n)throw new Error(`No installed or user-registered provider package is available for '${t}'`);e.modules.push(n)}function estimateSessionCostUsd(e){try{const t=getDisplayRates(e.model),{inputTokens:n,outputTokens:r,cacheReadTokens:o,cacheWriteTokens:s,cacheWriteTokens1h:i=0}=e.usage,a=Math.max(0,n-o-s),l=Math.min(i,s),c=s-l,d=t.cacheWriteCost??0,u=t.cacheWrite1hCost??d;return(a*t.inputCost+r*t.outputCost+o*t.cacheReadCost+c*d+l*u)/1e6}catch{return}}async function createHarnessSession(e){const t=e.runtime??createNodeRuntime(),n=await loadCommandCodeConfig({runtime:t}),r=e.configStore??createConfigStore({config:n,runtime:t,modelOverride:getModelOverride(),modelOverrideProvider:getModelOverrideProvider()});if(!e.configStore&&void 0===getModelOverride())try{const t=await loadCommandSessionMeta({sessionId:e.sessionId});t?.model&&(await loadCustomProviderModels(),(void 0!==resolveKnownModelId2(t.model)||isByok({model:t.model}))&&r.setSessionModel({model:t.model,...void 0!==t.modelProvider?{provider:t.modelProvider}:{}}))}catch{}const o=e.providerModules??e.modHost?.providerModules(),s=new Set((await loadProvidersConfig({runtime:t})).disabledProviderIds),i=[...o??[...await loadInstalledBuiltinProviderModules()]].filter(e=>!s.has(e.id)),a=(await loadUserConfig({runtime:t,path:legacyUserConfigPath({runtime:t})})).provider,l=a?Pk[a]:void 0,c=new Set(Array.isArray(n.mods?.disabled)?n.mods.disabled.filter(e=>"string"==typeof e):[]),d=l?r.getProviders()[l]:void 0;try{await restoreSelectedOAuthProviderModule({modules:i,provider:a,disabled:void 0!==l&&(c.has(`provider-${l}`)||s.has(l)),hasCredential:e.hasProviderCredential??(e=>hasProviderCredential({provider:e})),loadModule:e.loadProviderModuleForRestore??(async e=>{if(!0!==d?.disabled&&("string"==typeof d?.module||"string"==typeof d?.npm)){const n=d.module??d.npm;try{const e=coerceProviderModule(await importProviderModule(n,t.cwd()));if(e)return e}catch(t){dlog("[ProviderPackages] saved settings provider failed; trying builtin cache",{moduleId:e,error:t instanceof Error?t.message:String(t)})}}return loadBuiltinProviderModule({moduleId:e,install:!1})})})}catch(e){const t=l?`Run '${getBinaryCommand()} login ${l}' to install or repair it.`:"";throw new Error(`Could not restore the ${a} provider package for your saved login. ${e instanceof Error?e.message:String(e)}${t?` ${t}`:""}`,{cause:e})}const u=selectActiveOAuthProviderModules({modules:i,provider:a});return o&&setRegisteredProviderModules({modules:i}),createNodeHarnessSession({...e,runtime:t,configStore:r,cliVersion:e.cliVersion??y$,providerModules:u,providerBinding:{provider:a??null},importProviderModule:e.importProviderModule??(t=>importProviderModule(t,e.runtime?.cwd()??process.cwd())),estimateCostUsd:e.estimateCostUsd??estimateSessionCostUsd})}__name(selectActiveOAuthProviderModules,"selectActiveOAuthProviderModules"),__name(restoreSelectedOAuthProviderModule,"restoreSelectedOAuthProviderModule"),__name(estimateSessionCostUsd,"estimateSessionCostUsd"),__name(createHarnessSession,"createHarnessSession");var w$=createHarnessSessionManager({createSession:createHarnessSession}),v$=w$.getHarnessForSession,k$=w$.getResolvedHarness,C$=w$.forgetHarnessSession,b$=w$.disposeAllHarnessSessions,E$=new Set;function onHarnessSessionRebuild(e){return E$.add(e),()=>E$.delete(e)}async function rebuildHarnessSession(e){try{await(k$(e)?.flush())}catch{}C$(e);const t=[];for(const n of E$){const r=n(e);r&&t.push(r.catch(()=>{}))}if(0===t.length)return;let n;await Promise.race([Promise.all(t).then(()=>{}),new Promise(e=>{n=setTimeout(e,4e3)})]),clearTimeout(n)}__name(onHarnessSessionRebuild,"onHarnessSessionRebuild"),__name(rebuildHarnessSession,"rebuildHarnessSession");var T$=null,P$=null,M$=[],x$=null,I$=!1;async function loadFromConfig(){const e=await loadProvidersConfig({runtime:createNodeRuntime()});return M$=e.warnings,x$=JSON.stringify({providers:e.providers,disabled:e.disabledProviderIds}),e.providers.map(e=>({id:e.id,name:e.name??e.id,models:e.models}))}function diskLoadsBlocked(){return Boolean(process.env.VITEST)&&!0}async function loadCustomProviderModels(){return T$||(diskLoadsBlocked()?T$=[]:loadIntoCache())}function loadIntoCache(){return P$??=loadFromConfig().then(e=>(T$=e,e)).catch(()=>T$=[]),P$}async function refreshCustomProviderModels(e){if(diskLoadsBlocked())return T$??=[],{providers:T$,changed:!1};const t=null!==T$?x$:null;T$=null,P$=null;const n=await loadIntoCache();null!==t&&t!==x$&&(I$=!0);const r=I$;return I$&&e?.sessionId&&(await rebuildHarnessSession(e.sessionId),I$=!1),{providers:n,changed:r}}function seedSnapshotSync(){if(null===T$&&!process.env.VITEST)try{const e=x.readFileSync(`${W()}/.commandcode/providers.json`,"utf8"),t=parseProvidersConfig(JSON.parse(e));M$=t.warnings,x$=JSON.stringify({providers:t.providers,disabled:t.disabledProviderIds}),T$=t.providers.map(e=>({id:e.id,name:e.name??e.id,models:e.models}))}catch{}}function getCustomProviderModelsSync(){return T$||(seedSnapshotSync(),T$||(loadCustomProviderModels(),[]))}function getCustomProviderWarningsSync(){return M$}function findDeclared(e,t){const n=t.toLowerCase(),r=[];for(const t of e)for(const e of t.models)e.id.toLowerCase()===n&&r.push({providerId:t.id,modelId:e.id});if(1===r.length)return{modelId:`${r[0].providerId}/${r[0].modelId}`,providerId:r[0].providerId}}function findQualified(e,t){const n=t.indexOf("/");if(n<=0||n===t.length-1)return;const r=t.slice(0,n),o=t.slice(n+1),s=e.find(e=>e.id===r);if(!s)return;const i=s.models.find(e=>e.id.toLowerCase()===o.toLowerCase());return i?{modelId:`${s.id}/${i.id}`,providerId:s.id}:{modelId:t,providerId:s.id,warning:`"${o}" isn't declared under provider '${s.id}' in providers.json — sending it anyway. Declare it there to set its context window and options.`}}function isByok(e){const t=byokOwner(e.model);return void 0!==t&&(void 0===e.providerId||t===e.providerId)}function byokProviderId(e){return byokOwner(e.model)}function byokOwner(e){if(resolveKnownModelId2(e))return;const t=getCustomProviderModelsSync(),n=findQualified(t,e);return n?n.providerId:findDeclared(t,e)?.providerId}async function resolveSelectableModel(e){const t=e.trim();if(!t)return;const n=await loadCustomProviderModels(),r=resolveKnownModelId2(t);if(r)return{modelId:r};const o=t.indexOf("/");if(o>0){const e=t.slice(0,o).toLowerCase();if(n.some(t=>t.id===e))return findDeclared(n,t)??findQualified(n,t)}const s=resolveModelInput({model:t,models:getAllModelOptions()});return s?{modelId:s}:findDeclared(n,t)??findQualified(n,t)}function customProvidersDeclaring(e){const t=e.trim().toLowerCase();return getCustomProviderModelsSync().filter(e=>e.models.some(e=>e.id.toLowerCase()===t)).map(e=>e.id)}function customContextWindow(e){return declaredCustomModel(e)?.contextWindow}function customReasoningEfforts(e){return declaredCustomModel(e)?.reasoningEfforts}function declaredCustomModel(e){const t=getCustomProviderModelsSync(),n=findDeclared(t,e),r=n?void 0:findQualified(t,e),o=n??r;if(!o||o.warning)return;const s=t.find(e=>e.id===o.providerId);if(!s)return;const i=o.modelId.startsWith(`${s.id}/`)?o.modelId.slice(s.id.length+1):o.modelId;return s.models.find(e=>e.id===i)}function customAwareContextLimit(e){return customContextWindow(e.modelId)??e.fallback(e.modelId)}function customModelListOptions(){return getCustomProviderModelsSync().flatMap(e=>e.models.map(t=>({id:`${e.id}/${t.id}`,description:`${t.name??t.id} — ${e.name} (custom)`})))}function customModelListGroups(){return getCustomProviderModelsSync().filter(e=>e.models.length>0).map(e=>({label:`${e.name} (byok)`,models:e.models.map(t=>({id:`${e.id}/${t.id}`,description:t.name??t.id}))}))}function buildCustomModelPickerGroups(){return getCustomProviderModelsSync().map(e=>({provider:e,rows:e.models})).filter(({rows:e})=>e.length>0).map(({provider:e,rows:t})=>({providerId:e.id,label:`${e.name} (byok)`,models:t.map(t=>({id:`${e.id}/${t.id}`,provider:e.id,spec:"chatComplete",label:t.name??t.id,name:t.name??t.id,description:"",vendorLabel:e.name,...void 0!==t.contextWindow?{contextWindow:t.contextWindow}:{},...void 0!==t.reasoningEfforts?{reasoning:!0,reasoningEfforts:t.reasoningEfforts}:{}}))}))}__name(loadFromConfig,"loadFromConfig"),__name(diskLoadsBlocked,"diskLoadsBlocked"),__name(loadCustomProviderModels,"loadCustomProviderModels"),__name(loadIntoCache,"loadIntoCache"),__name(refreshCustomProviderModels,"refreshCustomProviderModels"),__name(seedSnapshotSync,"seedSnapshotSync"),__name(getCustomProviderModelsSync,"getCustomProviderModelsSync"),__name(getCustomProviderWarningsSync,"getCustomProviderWarningsSync"),__name(findDeclared,"findDeclared"),__name(findQualified,"findQualified"),__name(isByok,"isByok"),__name(byokProviderId,"byokProviderId"),__name(byokOwner,"byokOwner"),__name(resolveSelectableModel,"resolveSelectableModel"),__name(customProvidersDeclaring,"customProvidersDeclaring"),__name(customContextWindow,"customContextWindow"),__name(customReasoningEfforts,"customReasoningEfforts"),__name(declaredCustomModel,"declaredCustomModel"),__name(customAwareContextLimit,"customAwareContextLimit"),__name(customModelListOptions,"customModelListOptions"),__name(customModelListGroups,"customModelListGroups"),__name(buildCustomModelPickerGroups,"buildCustomModelPickerGroups"),Gt(),Gt(),Gt(),SR(),Gt(),Gt();var A$=__name(({label:e="Loading",spinner:t=!1})=>st.createElement(Xe,{color:ER.DIM},t&&st.createElement(st.Fragment,null,st.createElement(kt,{type:"dots"})," "),e,"…"),"LoadingLine"),R$=__name(({children:e,glyph:t=!0})=>st.createElement(Xe,{color:ER.RED},t&&`${gt.cross} `,e),"ErrorLine"),L$=__name(({children:e,glyph:t=!0})=>st.createElement(Xe,{color:ER.GREEN},t&&`${gt.tick} `,e),"SuccessLine"),O$=__name(({title:e="Oops, something went wrong:",children:t})=>st.createElement(Qe,{flexDirection:"column",borderStyle:"single",borderColor:ER.RED,paddingX:2,paddingY:1,marginTop:1},st.createElement(Xe,{color:ER.RED,bold:!0},e),st.createElement(Qe,{marginTop:1},st.createElement(Xe,null,t))),"ErrorPanel"),D$=__name(({message:e,hint:t})=>st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.GRAY},e),t?st.createElement(Xe,{color:ER.DIM},t):null),"EmptyState"),$$=__name(({error:e,traceId:t})=>st.createElement(Qe,{marginBottom:2},st.createElement(O$,null,e,t&&st.createElement(Xe,{color:ER.DIM},"\n\n","Trace ID: ",t))),"ErrorSection");async function runTasteImport(e={}){const t=await runOnboardingImportWithEvents({events:ip,signal:e.signal,onDebug:__name(e=>dlog(e),"onDebug"),runOnboarding:__name(async e=>(await createHarnessSession({sessionId:`taste-onboarding-${crypto.randomUUID()}`,baseUrl:getApiBaseUrl()})).runTasteOnboarding(e),"runOnboarding")});return{success:t.success,totalPrompts:t.totalPrompts,preferencesLearned:t.preferencesLearned,errors:[...t.errors],status:t.status,totalSessions:t.totalSessions,learnedSessions:t.learnedSessions,agentSessions:t.agentSessions?.map(e=>({agent:e.agent,sessionIds:[...e.sessionIds],displayName:e.displayName}))}}Gt(),Gt(),SR(),Gt(),SR(),__name(runTasteImport,"runTasteImport");var N$={isImporting:!1,waitingForInput:!1,error:null},_$=__name(e=>{const t=lt(null),n=lt(e);n.current=e;const[r,o]=at({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null}),s=ut(()=>{const e=t.current;!e||e.isAborted()||(e.finishCancelled(),o(e=>({...e,...N$})))},[]);return ct(()=>{const e=createOnboardingImportLifecycle({events:ip});t.current=e;let r=!1;return(async()=>{try{const t=await e.race(runTasteImport({signal:e.signal}));if(e.isAborted())return;if("cancelled"===t.status)return void o(e=>({...e,...N$}));if(t.success)return void o(e=>({...e,isImporting:!1,waitingForInput:!0}));if("already-learned"===t.status)return void o(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");o(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),n.current&&n.current(r)}catch(t){if(e.isAborted())return;const r=e.handleFailure(t);o(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),n.current&&n.current(r)}finally{e.dispose(),r=!0}})(),()=>{e.dispose(),r||e.finishCancelled(),t.current===e&&(t.current=null)}},[]),{...r,cancelImport:s}},"useImportProcess");Gt();var F$,U$,j$=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{nt((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");function getRuntime(){return F$??=createNodeRuntime()}function getStore(){return U$??=createOnboardingStore({runtime:getRuntime()})}async function checkOnboardingConditions2(){const e=await checkOnboardingConditions({runtime:getRuntime(),store:getStore()});return{shouldTrigger:e.shouldTrigger,reason:e.reason,sessionCount:e.sessionCount,hasTasteContent:e.hasTasteContent,agentSessions:e.agentSessions.map(e=>({agent:e.agent,sessionIds:[...e.sessionIds],displayName:e.displayName}))}}async function markOnboardingCompleted(){await getStore().markCompleted()}async function markOnboardingSkipped2(){await markOnboardingSkipped({runtime:getRuntime(),store:getStore()})}async function dismissOnboardingForeverForProject(){await getStore().dismissForever()}async function triggerTasteOnboarding({projectTrusted:e,onboardingComplete:t,isOnboardingMode:n,tasteOnboardingCheckedRef:r,setIsOnboardingMode:o}){if(e)if(t)dlog("[Onboarding] skipped - already completed");else if(n)dlog("[Onboarding] skipped - already showing");else if(r.current)dlog("[Onboarding] skipped - already checked this session");else{r.current=!0,dlog("[Onboarding] checking if taste learning should start...");try{const e=await checkOnboardingConditions2();if(!e.shouldTrigger)return void dlog("[Onboarding] not needed");dlog(`[Onboarding] starting taste learning (${e.reason})`),o(!0)}catch(e){dlog("[Onboarding] error",e)}}else dlog("[Onboarding] skipped - project not yet trusted")}Gt(),SR(),Gt(),SR(),__name(getRuntime,"getRuntime"),__name(getStore,"getStore"),__name(checkOnboardingConditions2,"checkOnboardingConditions"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(markOnboardingSkipped2,"markOnboardingSkipped"),__name(dismissOnboardingForeverForProject,"dismissOnboardingForeverForProject"),__name(triggerTasteOnboarding,"triggerTasteOnboarding");var B$=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=at(null),[o,s]=at(null),[i,a]=at(void 0),l=lt(!1);return ct(()=>{if(l.current)return;let n=null;return(async()=>{try{l.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions2();if(r(n),!n.shouldTrigger&&!e)return dlog("[Hook:Conditions] no trigger, skipping"),void t();dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`)}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r);const o=trackError({error:e instanceof Error?e:new Error(r),context:{component:Ho.LEARN_TASTE_COMMAND,heading:"Onboarding conditions check failed"}});a(o),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,traceId:i,isLoading:!n&&!o}},"useOnboardingConditions");Gt(),SR();var W$=__name(({conditions:e,autoLearn:t})=>{const[n,r]=at("checking"),o=lt(!1);return ct(()=>{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]),ct(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");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{ip.reset(),e()}}async function skipOnboarding(e){try{await markOnboardingSkipped2(),dlog("[Helper] onboarding marked skipped")}catch(e){dlog(`[Helper] skip error: ${e instanceof Error?e.message:String(e)}`)}finally{ip.reset(),e()}}Gt(),SR(),Gt(),SR(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var H$=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=lt(n),o=ut(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=ut(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=ut(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=ut(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=ut(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");Gt(),SR();var G$=__name(e=>{const[t,n]=at(()=>createTasteImportProjection({initialSteps:e})),r=ut(e=>{n(t=>({...t,importError:e}))},[]);return ct(()=>{const t=__name(()=>{n(resetTasteImportProjection({initialSteps:e}))},"handleReset"),r=__name(e=>{n(t=>reduceTasteImportEvent({state:t,event:e}))},"handleNewEvent");return ip.on("reset",t),ip.on("new-event",r),()=>{ip.off("reset",t),ip.off("new-event",r)}},[e]),{steps:t.steps,importError:t.importError,importTraceId:t.importTraceId,setImportError:r}},"useProgressEvents");Gt(),Gt(),Gt();var V$=__name(({isImporting:e=!1,waitingForInput:t=!1})=>st.createElement(st.Fragment,null,e&&st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Esc to cancel")),t&&st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to continue"))),"HelpTextSection");Gt(),Gt(),Gt(),Gt();var z$=__name(()=>{const[e,t]=at(!0);return ct(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),st.createElement(Xe,{color:ER.YELLOW},e?gt.circleFilled:gt.circle)},"PulsingDot");Gt();var K$=[gt.bullet,gt.squareSmallFilled,gt.lozenge,gt.star,gt.triangleRight,gt.triangleUp,gt.circleFilled,gt.pointer],q$=__name(e=>String(e).padStart(3," "),"padNum"),Y$=__name(e=>K$[e%K$.length],"getSymbol"),J$=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${q$(t)} ↓${q$(n)} (↑↓ scroll)`,"buildStatusLine"),Q$=__name(({insights:e})=>{const[t,n]=at(0),[r,o]=at(!0),s=e.length,i=s>10,a=Math.max(0,s-10),l=r&&i?a:t;if(nt((e,t)=>{if(i){if(t.upArrow)return o(!1),void n(Math.max(0,l-1));if(t.downArrow){const e=Math.min(a,l+1);o(e===a),n(e)}}}),0===s)return null;const c=e.slice(l,l+10),d=l,u=s-l-10;return st.createElement(Qe,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&st.createElement(Xe,{color:ER.DIM},J$(s,d,u,r)),c.map((e,t)=>{const n=l+t;return st.createElement(Qe,{key:n,marginBottom:0},st.createElement(Xe,{color:ER.DIM},Y$(n)," ",e))}))},"ScrollableInsights");function getLabelColor(e,t){return e?ER.WHITE:t?ER.YELLOW:ER.DIM}function formatCategorySuffix(e){if(0===e.length)return"";const t=1===e.length?"category":"categories";return` across ${e.length} ${t}`}__name(getLabelColor,"getLabelColor"),__name(formatCategorySuffix,"formatCategorySuffix");var X$=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:i,isAllComplete:a,summary:l,warning:c})=>{if(i)return st.createElement(Qe,{flexDirection:"column",marginBottom:0},st.createElement(kL,null),st.createElement(Qe,{marginTop:0},st.createElement(Xe,{color:ER.DIM},yL),st.createElement(Qe,{marginLeft:2},a?st.createElement(Xe,{color:PR.TEXT},"learned your coding taste"):st.createElement(mL,null))));const d=__name(()=>r?st.createElement(Xe,{color:AR.BG},gt.square):n?st.createElement(z$,null):st.createElement(Xe,{color:ER.DIM},gt.circle),"getStatusIcon"),u=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||u?st.createElement(Qe,{flexDirection:"column",marginBottom:0},(n||r)&&st.createElement(Qe,{marginBottom:0},st.createElement(Qe,{marginRight:1},d()),st.createElement(Xe,{color:getLabelColor(r,n)},e)),r&&t&&(!l||0===l.learningCount)&&st.createElement(Qe,{marginLeft:3,marginBottom:0},st.createElement(Xe,{color:ER.DIM},t)),o.length>0&&st.createElement(Qe,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map(e=>st.createElement(Xe,{key:e,color:ER.DIM},`${gt.bullet} ${e}`))),s.length>0&&st.createElement(Q$,{insights:s}),r&&l&&l.learningCount>0&&st.createElement(Qe,{flexDirection:"column",marginLeft:1,marginBottom:0},st.createElement(Qe,{marginBottom:1,flexDirection:"row"},st.createElement(Xe,null,yL),st.createElement(Qe,{marginLeft:2},st.createElement(Xe,{color:PR.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",formatCategorySuffix(l.categories)))),st.createElement(Qe,{flexDirection:"column",marginLeft:1},st.createElement(Xe,{color:ER.DIM},gt.pointerSmall," Stored in ",l.storage),st.createElement(Xe,{color:ER.DIM},"Command Code automatically uses & updates taste files."))),r&&c&&st.createElement(Qe,{flexDirection:"column",marginLeft:1,marginBottom:0},c.split("\n").map(e=>st.createElement(Xe,{key:e,color:ER.YELLOW},`${gt.warning} ${e}`)))):null},"StepItem"),Z$=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return st.createElement(Qe,{flexDirection:"column",marginBottom:1},e.map((e,n)=>st.createElement(Qe,{key:e.id,marginLeft:0===n?0:3},st.createElement(X$,{label:e.label,message:e.message,active:e.active,complete:e.complete,items:e.items,insights:e.insights,summary:e.summary,warning:e.warning,isIntro:0===n,isAllComplete:t}))))},"StepsSection"),eN=__name(({steps:e})=>st.createElement(Z$,{steps:e}),"ProgressSection"),tN=__name(({onComplete:e,onCancel:t,onError:n,onErrorDismiss:r})=>{const{steps:o,importError:s,importTraceId:i}=G$(RI),{isImporting:a,waitingForInput:l,error:c,cancelImport:d}=_$(n);return j$({onEscape:__name(()=>{if(a)return d(),void t?.();l&&((c||s)&&r?r():e())},"onEscape"),onEnter:__name(()=>{l&&((c||s)&&r?r():e())},"onEnter"),enabled:a||l}),st.createElement(Qe,{flexDirection:"column",padding:1},s&&st.createElement($$,{error:s,traceId:i}),!s&&st.createElement(eN,{steps:o}),st.createElement(V$,{isImporting:a,waitingForInput:l}))},"ImportProgress");async function runLearnTaste(){await applyStartupTheme();const{unmount:e}=tt(st.createElement(tN,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onCancel:__name(()=>{e(),process.exit(0)},"onCancel"),onErrorDismiss:__name(()=>{e(),process.exit(1)},"onErrorDismiss")}))}__name(runLearnTaste,"runLearnTaste");var nN=new Be("learn-taste").description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{if(await loadCustomProviderModels(),isByok({model:getConfiguredModel()??""}))return console.log(lg),void await shutdownTelemetry();await runLearnTaste()}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:Ho.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 getBinNames(){const e=getPackageJson(import.meta.url);return e.bin&&"object"==typeof e.bin?Object.keys(e.bin):e.bin&&"string"==typeof e.bin?[e.name??getBinaryCommand()]:[getBinaryCommand()]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||getBinaryCommand();const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||getBinaryCommand()}catch{return getBinaryCommand()}}function addMcpCommand(){const e=new Be("add");return e.description("Add an MCP server").argument("<name>","Server name (unique identifier)").argument("[url]","Server URL (required for http transport)").option("-t, --transport <type>","Transport type (stdio or http)","stdio").addOption(new We("-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{const s=await addMcpServerFromCliInput({name:e,url:t,transport:n.transport,scope:n.scope,env:n.env,headers:n.header,rawArgs:r.args,argv:process.argv,cliName:o,addMcpServer:addMcpServer,checkServerAuthRequirements:__name(async e=>{console.log(ht.gray("Checking server authentication requirements..."));const t=await checkCommandMcpServerAuthRequirements(e);return t.requiresAuth&&console.log(ht.cyan("Server requires OAuth authentication.")),t},"checkServerAuthRequirements"),registerOAuthClient:__name(async e=>(console.log(ht.gray("Registering OAuth client...")),registerCommandMcpOAuthClient({registrationEndpoint:e.registrationEndpoint,clientName:e.clientName,redirectUris:[...e.redirectUris]})),"registerOAuthClient"),performOAuthFlow:__name(async e=>{console.log(ht.gray("A browser window will open for authentication.\n"));const t=await performCommandMcpOAuthFlow(e.serverName,e.serverUrl,{authorizationUrl:e.config.authorizationUrl,tokenUrl:e.config.tokenUrl,clientId:e.config.clientId,clientSecret:e.config.clientSecret,scopes:e.config.scopes?[...e.config.scopes]:void 0,resource:e.config.resource},{onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),onStatus:__name(e=>{console.log(ht.gray(` ${e}`))},"onStatus")});for(const e of s.warnings)console.log(ht.yellow(`Warning: ${e}`));"success"===s.authStatus&&console.log(ht.green("✓ Successfully authenticated")),"failed"===s.authStatus&&(console.log(ht.yellow(`Warning: Authentication failed: ${s.authError}`)),console.log(ht.gray(`You can retry with: ${getBinaryCommand()} mcp auth ${e}`)),console.log(ht.gray("Or authenticate via the /mcp menu in a session")));const i="failed"===s.authStatus?`✓ Added MCP server '${e}' to ${s.scopeLabel} config (authentication pending)`:`✓ Added MCP server '${e}' to ${s.scopeLabel} config`;console.log("failed"===s.authStatus?ht.yellow(i):ht.green(i)),console.log(ht.gray(` ${formatMcpCommandSummary(s.serverConfig)}`)),console.log(""),console.log(ht.cyan("Next steps:")),console.log(ht.gray(`Start ${o} and run /mcp to manage configured MCP servers.`))}catch(e){printMcpAddError(e,{cliName:o}),process.exit(1)}}),e}function printMcpAddError(e,t){if(e instanceof IT)if(console.error(ht.red(`Error: ${e.message}`)),"invalid-name"!==e.code)if("invalid-transport"!==e.code){if("missing-http-url"!==e.code)return"missing-stdio-command"===e.code?(console.error(ht.gray(`Usage: ${t.cliName} mcp add --transport stdio <name> -- <command> [args...]`)),void console.error(ht.gray(` or: ${t.cliName} mcp add <name> <command> [args...]`))):void("stdio-command-is-url"!==e.code?"insecure-oauth-url"===e.code&&(console.error(ht.gray("OAuth requires https:// (http:// is only allowed for loopback hosts: localhost, 127.0.0.1, [::1]).")),console.error(ht.gray("Switch the URL to https:// or use a non-OAuth server."))):e.suggestedCommand&&console.error(ht.gray(`Did you mean: ${e.suggestedCommand}`)));console.error(ht.gray(`Usage: ${t.cliName} mcp add --transport http <name> <url>`))}else console.error(ht.gray("Valid options: stdio, http"));else console.error(ht.gray(xT));else console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function collectKeyValue(e,t){try{return addMcpKeyValue(e,t)}catch(e){printCollectError(e),process.exit(1)}}function collectHeaders(e,t){try{return addMcpHeader(e,t)}catch(e){printCollectError(e),process.exit(1)}}function printCollectError(e){console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function addJsonMcpCommand(){const e=new Be("add-json");return e.description("Add an MCP server from JSON configuration").argument("<name>","Server name (unique identifier)").argument("<json>","Server configuration as JSON string").addOption(new We("-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{const o=await addMcpServerFromJson({name:e,json:t,scope:n.scope,clientSecret:n.clientSecret,addMcpServer:addMcpServer,performOAuthFlow:__name(async e=>{console.log(ht.cyan("Starting OAuth authentication...")),console.log(ht.gray("A browser window will open for authentication.\n"));const t=await performCommandMcpOAuthFlow(e.serverName,e.serverUrl,{authorizationUrl:e.config.authorizationUrl,tokenUrl:e.config.tokenUrl,clientId:e.config.clientId,clientSecret:e.config.clientSecret,scopes:e.config.scopes?[...e.config.scopes]:void 0,resource:e.config.resource},{port:e.port,onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),onStatus:__name(e=>{console.log(ht.gray(` ${e}`))},"onStatus")});"success"===o.authStatus&&console.log(ht.green(`\n✓ Successfully authenticated with '${e}'`)),"failed"===o.authStatus&&(console.error(ht.yellow(`\nWarning: Authentication failed: ${o.authError}`)),console.error(ht.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(ht.gray("Or authenticate via the /mcp menu in a session")));const s="failed"===o.authStatus?`✓ Added MCP server '${e}' to ${o.scopeLabel} config (authentication pending)`:`✓ Added MCP server '${e}' to ${o.scopeLabel} config`;console.log("failed"===o.authStatus?ht.yellow(s):ht.green(s)),console.log(ht.gray(` ${formatMcpCommandSummary(o.serverConfig)}`)),console.log(""),console.log(ht.cyan("Next steps:")),console.log(ht.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){printMcpAddJsonError(e,{cliName:r}),process.exit(1)}}),e}function printMcpAddJsonError(e,t){if(e instanceof IT)if(console.error(ht.red(`Error: ${e.message}`)),"invalid-name"!==e.code){if("invalid-json"===e.code)return console.error(ht.gray("Make sure to quote the JSON string properly")),void console.error(ht.gray(`Example: ${t.cliName} mcp add-json github '{"type":"stdio","command":"npx"}'`));if("invalid-config"===e.code&&e.issues)for(const t of e.issues)console.error(ht.gray(` ${t.path.join(".")}: ${t.message}`));else"missing-http-url"!==e.code&&e.code}else console.error(ht.gray(xT));else console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function authMcpCommand(){const e=new Be("auth");return e.description("Manage OAuth authentication for MCP servers").argument("[server]","Server name to authenticate").option("--status","Check authentication status").option("--clear","Clear stored authentication").option("--list","List servers with stored authentication").action(async(e,t)=>{const n=getInvokedCommandName();try{if(t.list)return void await printAuthList();if(e||(console.error(ht.red("Error: Server name is required")),console.error(ht.gray(`Usage: ${n} mcp auth <server>`)),console.error(ht.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status)return void await printAuthStatus(e);if(t.clear)return(await clearMcpAuth({serverName:e,deleteTokens:deleteTokens})).deleted?void console.log(ht.green(`✓ Cleared authentication for '${e}'`)):void console.log(ht.yellow(`No authentication stored for '${e}'`));console.log(ht.cyan(`Authenticating with '${e}'...`)),console.log(ht.gray("A browser window will open for authentication.\n")),await authenticateConfiguredMcpServer({serverName:e,getMcpServer:getMcpServer,performOAuthFlow:__name(async e=>{const t=await performCommandMcpOAuthFlow(e.serverName,e.serverUrl,{authorizationUrl:e.config.authorizationUrl,tokenUrl:e.config.tokenUrl,clientId:e.config.clientId,clientSecret:e.config.clientSecret,scopes:e.config.scopes?[...e.config.scopes]:void 0,resource:e.config.resource},{onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),discoverAndAuthenticate:discoverAndAuthenticateCommandMcpServer,onStatus:__name(e=>{console.log(ht.gray(` ${e}`))},"onStatus")}),console.log(ht.green(`\n✓ Successfully authenticated with '${e}'`)),console.log(ht.gray("Restart the session to connect with the authenticated server."))}catch(t){printMcpAuthError(t,{cliName:n,serverName:e}),process.exit(1)}}),e}async function printAuthList(){const e=await listMcpAuthStatuses({listServersWithTokens:listServersWithTokens,getTokens:getTokens,isTokenExpired:isTokenExpired});if(0!==e.length){console.log(ht.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=t.expired?ht.yellow("expired"):ht.green("valid");console.log(` ${t.serverName}: ${e}`)}console.log("")}else console.log(ht.yellow("No servers with stored authentication."))}async function printAuthStatus(e){const t=await getMcpAuthStatus({serverName:e,hasTokens:hasTokens,getTokens:getTokens,isTokenExpired:isTokenExpired});if("missing"!==t.status){if("expired"===t.status)return console.log(ht.yellow(`Authentication for '${e}' has expired`)),void(t.hasRefreshToken&&console.log(ht.gray(" A refresh token is available for re-authentication")));console.log(ht.green(`Authentication for '${e}' is valid`)),"number"==typeof t.expiresInMinutes&&console.log(ht.gray(` Expires in ${t.expiresInMinutes} minutes`)),t.scope&&console.log(ht.gray(` Scopes: ${t.scope}`))}else console.log(ht.yellow(`No authentication stored for '${e}'`))}function printMcpAuthError(e,t){if(e instanceof IT)return"server-not-found"===e.code?(console.error(ht.red(`Error: ${e.message}`)),void console.error(ht.gray(`Use "${t.cliName} mcp list" to see configured servers`))):"auth-failed"===e.code?(console.error(ht.red(`\nError: ${e.message}`)),void(t.serverName&&console.log(ht.gray(`Try again with "${t.cliName} mcp auth ${t.serverName}"`)))):void console.error(ht.red(`Error: ${e.message}`));console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function getMcpCommand(){const e=new Be("get");return e.description("Show details for an MCP server").argument("<name>","Server name").action(async e=>{try{const t=await getMcpServerDetails({name:e,getMcpServer:getMcpServer}),{config:n,scope:r}=t;if(console.log(ht.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${ht.dim("Scope:")} ${r}`),console.log(` ${ht.dim("Transport:")} ${n.transport}`),console.log(` ${ht.dim("Status:")} ${n.enabled?ht.green("enabled"):ht.gray("disabled")}`),"http"===n.transport){if(console.log(` ${ht.dim("URL:")} ${n.url}`),t.headers.length>0){console.log(` ${ht.dim("Headers:")}`);for(const e of t.headers)console.log(` ${e.key}: ${e.value}`)}}else console.log(` ${ht.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${ht.dim("Args:")} ${n.args.join(" ")}`);if(t.env.length>0){console.log(` ${ht.dim("Environment:")}`);for(const e of t.env)console.log(` ${e.key}=${e.value}`)}console.log("")}catch(e){e instanceof IT&&(console.error(ht.red(`Error: ${e.message}`)),process.exit(1)),console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function formatAuthIcon(e){return"authenticated"===e||"static"===e?ht.green(gt.tick):"missing"===e?ht.red(gt.cross):ht.gray("-")}function listMcpCommand(){const e=new Be("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServerSummaries({listMcpServers:listMcpServers,hasTokens:hasTokens});if(0===e.length)return console.log(ht.yellow("\nNo MCP servers configured\n")),console.log(ht.gray("Add a server with:")),console.log(ht.gray(` ${getBinaryCommand()} mcp add --transport http <name> <url>`)),console.log(ht.gray(` ${getBinaryCommand()} mcp add --transport stdio <name> -- <command>`)),void console.log(ht.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(ht.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(ht.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.enabled?ht.green("enabled"):ht.gray("disabled"),s=formatAuthIcon(o.authStatus);console.log(` ${ht.white(o.name.padEnd(t))} ${ht.cyan(o.transport.padEnd(n))} ${ht.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(ht.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new Be("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new We("-s, --scope <scope>","Scope to remove from (auto-detects if not specified)").choices(["local","project","user"])).action(async(e,t)=>{try{const n=await removeMcpServerByName({name:e,scope:t.scope,getMcpServer:getMcpServer,removeMcpServer:removeMcpServer});console.log(ht.green(`✓ Removed MCP server '${e}' from ${n.scopeLabel} config`))}catch(e){e instanceof IT&&(console.error(ht.red(`Error: ${e.message}`)),process.exit(1)),console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new Be("mcp");return e.description("Manage MCP (Model Context Protocol) servers").allowUnknownOption().allowExcessArguments(),e.addCommand(addMcpCommand()),e.addCommand(listMcpCommand()),e.addCommand(getMcpCommand()),e.addCommand(removeMcpCommand()),e.addCommand(addJsonMcpCommand()),e.addCommand(authMcpCommand()),e}function shortenModPath(e,t){if(t){const n=i(t,e);if(n&&!n.startsWith("..")&&!a(n))return n}const n=i(W(),e);return!n||n.startsWith("..")||a(n)?e:`~${l}${n}`}Gt(),Gt(),SR(),Gt(),SR(),__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),__name(addMcpCommand,"addMcpCommand"),__name(printMcpAddError,"printMcpAddError"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),__name(printCollectError,"printCollectError"),Gt(),SR(),__name(addJsonMcpCommand,"addJsonMcpCommand"),__name(printMcpAddJsonError,"printMcpAddJsonError"),Gt(),SR(),__name(authMcpCommand,"authMcpCommand"),__name(printAuthList,"printAuthList"),__name(printAuthStatus,"printAuthStatus"),__name(printMcpAuthError,"printMcpAuthError"),Gt(),SR(),__name(getMcpCommand,"getMcpCommand"),Gt(),SR(),__name(formatAuthIcon,"formatAuthIcon"),__name(listMcpCommand,"listMcpCommand"),Gt(),SR(),__name(removeMcpCommand,"removeMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Gt(),Gt(),SR(),Gt(),SR(),__name(shortenModPath,"shortenModPath");var rN=__name(e=>e.split(W()).join("~"),"shortenHomeInText");async function createModPathShortener(e){const t=await modsDirectoryPath({runtime:e,scope:"project"}),n=t?s(t,"..",".."):void 0;return e=>shortenModPath(e,n)}async function addAction(e,t){const n=createNodeRuntime(),r=t.global?"user":"project";try{const t=parseModSource(e);console.log(Et.dim(`Installing ${t.kind} mod source ${Et.reset(Et.cyan(e))} (${r})…`));const o=await installModSource({runtime:n,source:e,scope:r}),s=await createModPathShortener(n);console.log(`${Et.green(gt.tick)} Installed ${Et.cyan(o.identity)}`),o.installedPath&&console.log(Et.dim(` ${s(o.installedPath)}`)),console.log(Et.dim(` Recorded in ${s(o.settingsPath)}`))}catch(e){console.error(`${Et.red(gt.cross)} ${rN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}__name(createModPathShortener,"createModPathShortener"),__name(addAction,"addAction");var oN=new Be("add").alias("install").description("Install a mod package (<npm-name>, owner/repo[@ref], or a local path)").argument("<source>","mod source: an npm package name, a git repo (owner/repo[@ref]), or a local path").option("-g, --global","install for all projects (user scope)").action(addAction);Gt(),SR(),Gt(),Gt(),Gt();var sN={running:0,waitingPermission:0,waitingQuestion:0,compacting:0};function bump(e,t){return Math.max(0,e+t)}function nextLifecycle(e,t){return"run_start"===t.type?{...e,running:e.running+1}:"run_end"===t.type?{...e,running:bump(e.running,-1)}:"compaction_start"===t.type?{...e,compacting:e.compacting+1}:"compaction_done"===t.type?{...e,compacting:bump(e.compacting,-1)}:"interaction_requested"===t.type?"permission"===t.kind?{...e,waitingPermission:e.waitingPermission+1}:{...e,waitingQuestion:e.waitingQuestion+1}:"interaction_resolved"===t.type?"permission"===t.kind?{...e,waitingPermission:bump(e.waitingPermission,-1)}:{...e,waitingQuestion:bump(e.waitingQuestion,-1)}:e}function reportFor(e){return e.waitingPermission>0?{state:"blocked",message:"permission"}:e.waitingQuestion>0?{state:"blocked",message:"question"}:e.running>0||e.compacting>0?{state:"working"}:{state:"idle"}}function reportKey(e){return`${e.state}:${e.message??""}`}__name(bump,"bump"),__name(nextLifecycle,"nextLifecycle"),__name(reportFor,"reportFor"),__name(reportKey,"reportKey"),Gt(),Gt();var iN=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`,"g");function sanitizeTitleForOutput(e){const t=e.replace(iN,"");let n="";for(const e of t){const t=e.codePointAt(0)??0;n+=t<=31||t>=127&&t<=159?" ":e}return n.replace(/\s{2,}/g," ").trim()}__name(sanitizeTitleForOutput,"sanitizeTitleForOutput");var aN="cmd",lN=`custom:${aN}`,cN="CMD_HERDR_PANE_OWNER";function resolveHerdrConfig(e){const t=e.CMD_HERDR?.trim().toLowerCase();if("0"===t||"false"===t)return null;if("1"!==e.HERDR_ENV?.trim())return null;if(e[cN])return null;const n=e.HERDR_SOCKET_PATH?.trim(),r=e.HERDR_PANE_ID?.trim();return n&&r?{socketPath:n,paneId:r}:null}function releasedPaneOwnerEnv(e,t){return e[cN]===String(t)?{[cN]:void 0}:{}}function claimHerdrPane(e){e[cN]=String(process.pid)}function clampBytes(e,t){if(!e)return;const n=sanitizeTitleForOutput(e);return n?Buffer.from(n,"utf-8").subarray(0,t).toString("utf-8").replace(/�$/,""):void 0}function clampText(e){if(!e)return;const t=sanitizeTitleForOutput(e);if(!t)return;const n=Array.from(t);return n.length<=80?t:n.slice(0,80).join("")}function metadataParams(e){const t=clampText(e.title),n=clampText(e.displayAgent),r=Object.fromEntries(Object.entries(e.tokens??{}).flatMap(([e,t])=>{const n=clampText(t);return n?[[e,n]]:[]}));return{...t?{title:t}:{},...!t&&e.clearTitle?{clear_title:!0}:{},...n?{display_agent:n}:{},...Object.keys(r).length>0?{tokens:r}:{}}}function buildHerdrLine(e){const{id:t,seq:n,paneId:r,request:o}=e,s={id:String(t)},i={pane_id:r,source:lN,agent:aN,seq:n};if("report"===o.kind){const e=clampBytes(o.message,32);return`${JSON.stringify({...s,method:"pane.report_agent",params:{...i,state:o.state,...e?{message:e}:{}}})}\n`}return"session"===o.kind?`${JSON.stringify({...s,method:"pane.report_agent_session",params:{...i,agent_session_id:o.sessionId}})}\n`:"metadata"===o.kind?`${JSON.stringify({...s,method:"pane.report_metadata",params:{...i,...metadataParams(o.metadata)}})}\n`:"paneRename"===o.kind?`${JSON.stringify({...s,method:"pane.rename",params:{pane_id:r,label:o.label}})}\n`:"agentRename"===o.kind?`${JSON.stringify({...s,method:"agent.rename",params:{target:r,name:o.name}})}\n`:`${JSON.stringify({...s,method:"pane.release_agent",params:i})}\n`}function herdrSocketEndpoint(e){const{socketPath:t,platform:n=process.platform}=e;return"win32"===n?`\\\\.\\pipe\\${t}`:t}function sendHerdrLine(e){const t=e.timeoutMs??250;return new Promise(n=>{let r=!1;const o=he.createConnection(herdrSocketEndpoint({socketPath:e.socketPath})),s=__name(()=>{r||(r=!0,clearTimeout(i),o.destroy(),n())},"finish"),i=setTimeout(s,t);i.unref?.(),o.setEncoding("utf-8"),o.on("connect",()=>{o.write(e.line)}),o.on("data",e=>{e.includes("\n")&&s()}),o.on("error",s),o.on("close",s)})}__name(resolveHerdrConfig,"resolveHerdrConfig"),__name(releasedPaneOwnerEnv,"releasedPaneOwnerEnv"),__name(claimHerdrPane,"claimHerdrPane"),__name(clampBytes,"clampBytes"),__name(clampText,"clampText"),__name(metadataParams,"metadataParams"),__name(buildHerdrLine,"buildHerdrLine"),__name(herdrSocketEndpoint,"herdrSocketEndpoint"),__name(sendHerdrLine,"sendHerdrLine");var dN={enabled:!1,reportState:__name(()=>{},"reportState"),reportSession:__name(()=>{},"reportSession"),reportMetadata:__name(()=>{},"reportMetadata"),announce:__name(()=>{},"announce"),release:__name(()=>Promise.resolve(),"release")};function createHerdrReporter(e){const{config:t}=e;if(!t)return dN;const n=e.send??sendHerdrLine,r=e.now??Date.now;let o=1,s=1e3*r(),i=Promise.resolve(),a=0;const l=__name(e=>{const n=o;return o+=1,s+=1,buildHerdrLine({id:n,seq:s,paneId:t.paneId,request:e})},"nextLine"),c=__name(e=>{const r=l(e),o=a;return i=i.then(()=>o!==a?Promise.resolve():n({socketPath:t.socketPath,line:r})).catch(()=>{}),i},"enqueue");return{enabled:!0,reportState:__name((e,t)=>{c({kind:"report",state:e,message:t})},"reportState"),reportSession:__name(e=>{e&&c({kind:"session",sessionId:e})},"reportSession"),reportMetadata:__name(e=>{c({kind:"metadata",metadata:e})},"reportMetadata"),announce:__name(()=>{c({kind:"paneRename",label:aN}),c({kind:"agentRename",name:aN})},"announce"),release:__name(()=>{const e=l({kind:"release"});return a+=1,n({socketPath:t.socketPath,line:e}).catch(()=>{})},"release")}}__name(createHerdrReporter,"createHerdrReporter");var uN=["run_start","run_end","interaction_requested","interaction_resolved","compaction_start","compaction_done"];function isHostEvent(e){return"session_start"===e.type||"session_shutdown"===e.type}function createHerdrMod(e={}){return t=>{const n=e.env??process.env,r=void 0!==e.config?e.config:resolveHerdrConfig(n),o=e.reporter??createHerdrReporter({config:r});r&&claimHerdrPane(n);let s=sN,i=null,a=null,l=null,c=null;if(t.addCommand({name:"herdr",description:"Show herdr reporting status for this pane",handler:__name(()=>{if(!o.enabled)return{message:["herdr: not reporting.","This session was not launched by herdr (HERDR_ENV, HERDR_SOCKET_PATH and","HERDR_PANE_ID must all be set), or CMD_HERDR=0 disabled it."].join("\n")};const e=reportFor(s);return{message:[`herdr: reporting to pane ${r?.paneId??"unknown"}`,` state ${e.state}${e.message?` (${e.message})`:""}`,` session ${a??"not yet started"}`,` model ${l??"not yet requested"}`,"","Control herdr from here — split panes, start other agents,","wait for them to finish:"," npx skills add herdrdev/herdr --skill herdr"].join("\n")}},"handler")}),!o.enabled)return;const d=__name(()=>{const e=reportFor(s),t=reportKey(e);t!==i&&(i=t,o.reportState(e.state,e.message))},"flushState"),u=__name(()=>{o.reportMetadata({...c?{title:c}:{clearTitle:!0},displayAgent:l?`cmd · ${l}`:"cmd",...l?{tokens:{model:l}}:{}})},"flushMetadata"),m=__name(e=>{e&&e!==a&&(a=e,o.reportSession(a))},"reportSessionOnce");t.hooks({onSessionStart:__name(({sessionId:e})=>{s=sN,i=null,a=null,l=null,c=null,o.announce(),m(e),u(),d()},"onSessionStart"),onSessionEnd:__name(()=>o.release(),"onSessionEnd")});for(const e of uN)t.on(e,e=>{isHostEvent(e)||(s=nextLifecycle(s,e),"run_start"===e.type&&m(e.sessionId),d())});t.on("session_titled",e=>{"session_titled"===e.type&&e.title!==c&&(c=e.title,u())}),t.on("model_request_start",e=>{"model_request_start"===e.type&&e.model!==l&&(l=e.model,u())})}}__name(isHostEvent,"isHostEvent"),__name(createHerdrMod,"createHerdrMod");var mN=createHerdrMod();function providerMod(e){return{name:`provider-${e.id}`,factory:__name(async t=>{try{const n=await loadBuiltinProviderModule({moduleId:e.id,install:!1});n&&t.addProvider(n)}catch(t){dlog("[ProviderPackages] builtin provider mod skipped",{pkg:e.package,error:t instanceof Error?t.message:String(t)})}},"factory")}}function providerBuiltinMods(){return RD.map(providerMod)}function updateNoticeMod(e){try{const t=readUpdatesConfig().pending;if(!t?.targetVersion)return;const n=getPackageJson(import.meta.url).version;if(t.targetVersion===n)return;e.ui.notify(`update available: v${t.targetVersion} (installing in the background — a restart applies it)`)}catch{}}function commandBuiltinMods(){return[...providerBuiltinMods(),{name:"update-notice",factory:updateNoticeMod},{name:"herdr",factory:mN}]}Gt(),SR(),__name(providerMod,"providerMod"),__name(providerBuiltinMods,"providerBuiltinMods"),Gt(),SR(),__name(updateNoticeMod,"updateNoticeMod"),__name(commandBuiltinMods,"commandBuiltinMods");var pN=__name((e,t,n)=>` ${Et.cyan(e)} ${Et.dim(`· ${t} · ${n}`)}`,"formatModLine"),gN=__name((e,t)=>`${Et.bold(Et.white(e))} ${Et.dim(`(${t})`)}`,"formatSectionHeader");function scopeFor(e){const{entry:t}=e;if("project"===t.source)return"project";if("user"===t.source)return"user";if("path"===t.source)return"session";const n=modSourceForPath({statuses:e.sources,path:t.path});return n?.scope??"package"}function detailFor(e){const{entry:t}=e,n=e.disabled.has(t.name)?" (disabled)":"";if("package"===t.source){const r=modSourceForPath({statuses:e.sources,path:t.path});return`from ${r?.identity??"a package source"}${n}`}return`${shortenModPath(t.path,e.projectRoot)}${n}`}async function listAction(e){const t=createNodeRuntime(),n=await isCommandProjectSessionInitialized(),r=await discoverMods({runtime:t,includeProject:n}),o=await listModSources({runtime:t,includeProject:n}),i=new Set(r.disabled),a=await modsDirectoryPath({runtime:t,scope:"project"}),l=await modsDirectoryPath({runtime:t,scope:"user"}),c=a?s(a,"..",".."):void 0,d=["project","user","package","path"].flatMap(e=>r.entries.filter(t=>t.source===e));console.log(""),console.log(`${Et.bold(Et.white("Mods"))} ${Et.dim(`(${r.entries.length})`)}`),0===r.entries.length&&(console.log(""),console.log(Et.dim(" No mods loaded. Looking in:")),a&&console.log(Et.dim(` ${shortenModPath(a,c)} ${Et.white("(project)")}`)),l&&console.log(Et.dim(` ${shortenModPath(l,void 0)} ${Et.white("(user)")}`)),console.log(""),console.log(Et.dim(` Drop a .ts file in one (\`${getBinaryCommand()} mods open --user\`) or install a package: \`${getBinaryCommand()} mods add <source>\`.`)));for(const e of d)console.log(pN(e.name,scopeFor({entry:e,sources:o}),detailFor({entry:e,sources:o,projectRoot:c,disabled:i})));if(!0===e.builtin){const e=commandBuiltinMods();console.log(""),console.log(gN("Built-in",e.length));for(const t of e)console.log(pN(t.name,"builtin",i.has(t.name)?"disabled":"enabled"))}const u=new Set;if(o.length>0){const e=__name(e=>r.entries.some(t=>"package"===t.source&&void 0!==modSourceForPath({statuses:[e],path:t.path})),"contributes"),t=o.filter(t=>!t.installed||!e(t));if(t.length>0){console.log(""),console.log(gN("Package sources",t.length));for(const e of t){u.add(e.source);const t=e.installed?Et.yellow("installed, but provides no mods"):Et.yellow(`not installed — run \`${getBinaryCommand()} mods update\``);console.log(pN(e.identity,e.scope,t))}}}const m=r.warnings.filter(e=>!u.has(e.path));if(m.length>0){console.log(""),console.log(`${Et.bold(Et.yellow("Warnings"))} ${Et.dim(`(${m.length})`)}`);for(const e of m)console.log(` ${Et.cyan(shortenModPath(e.path,c))} ${Et.dim(`· ${e.reason}`)}`)}console.log("")}__name(scopeFor,"scopeFor"),__name(detailFor,"detailFor"),__name(listAction,"listAction");var hN=new Be("list").alias("ls").description("List the mods a session loads, and where each one comes from").addOption(new We("--builtin","also list Command Code's built-in mods").hideHelp()).action(listAction);async function openAction(e){const t=createNodeRuntime(),n=!0===e.user||!0===e.global;try{const r=n?void 0:await modsDirectoryPath({runtime:t,scope:"project"}),o=r??await modsDirectoryPath({runtime:t,scope:"user"});if(!o)throw new Error("Could not resolve a mods directory");const s=r?"project":"user";if(!0===e.path)return void console.log(o);await t.fs.mkdir({path:o}),await Pt(o);const i=await createModPathShortener(t);console.log(`${Et.green(gt.tick)} Opened ${Et.cyan(i(o))} ${Et.dim(`· ${s}`)}`)}catch(e){console.error(`${Et.red(gt.cross)} ${rN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}Gt(),SR(),__name(openAction,"openAction");var fN=new Be("open").description("Open the mods directory (project by default, --user for ~)").option("-u, --user","open the user mods directory (~/.commandcode/mods)").option("-g, --global","alias for --user").option("--path","print the directory path instead of opening it").action(openAction);async function removeAction(e,t){const n=createNodeRuntime();commandBuiltinMods().some(t=>t.name===e)&&(console.error(`${Et.red(gt.cross)} ${Et.cyan(e)} is a built-in mod — it cannot be removed. Add it to ${Et.cyan('"mods": {"disabled": [...]}')} in settings.json to turn it off.`),process.exit(1));const r=await isCommandProjectSessionInitialized();try{const o=await removeMod({runtime:n,target:e,scope:t.global?"user":"project",includeProject:r});if(!o.removedFromSettings&&!o.removedPath)return void console.log(`${Et.yellow(gt.warning)} ${Et.cyan(o.target)} is not configured (${o.scope} scope) — nothing to remove`);const s=await createModPathShortener(n);console.log(`${Et.green(gt.tick)} Removed ${Et.cyan(o.target)} ${Et.dim(`· ${o.scope}`)}`),o.sourceIdentity&&o.sourceIdentity!==o.target&&console.log(Et.dim(` Removed its source ${o.sourceIdentity}`)),o.alsoRemoved&&o.alsoRemoved.length>0&&console.log(Et.dim(` That source also provided ${o.alsoRemoved.join(", ")}`)),o.removedPath&&console.log(Et.dim(` Deleted ${s(o.removedPath)}`)),o.removedFromSettings&&o.settingsPath&&console.log(Et.dim(` Updated ${s(o.settingsPath)}`))}catch(e){console.error(`${Et.red(gt.cross)} ${rN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}Gt(),SR(),__name(removeAction,"removeAction");var yN=new Be("remove").alias("rm").alias("uninstall").description("Remove a mod by its listed name or by its package source").argument("<target>","mod name from `mods list`, or the mod source (any spelling of it)").option("-g, --global","remove from user scope instead of project").action(removeAction);async function updateAction(){const e=createNodeRuntime(),t=await updateModSources({runtime:e,includeProject:await isCommandProjectSessionInitialized()});for(const e of t.updated)console.log(`${Et.green(gt.tick)} ${Et.cyan(e)}`);for(const e of t.failures)console.error(`${Et.red(gt.cross)} ${e.source} ${Et.dim(`· ${e.reason}`)}`);0===t.updated.length&&0===t.failures.length&&console.log(Et.dim("No mod package sources configured.")),t.failures.length>0&&process.exit(1)}Gt(),SR(),__name(updateAction,"updateAction");var SN=new Be("update").alias("up").description("Reinstall and reconcile every configured mod package").action(updateAction),wN=new Be("mods").description("Manage mods — loadable extensions from npm, git, or local paths").addCommand(oN).addCommand(yN).addCommand(hN).addCommand(SN).addCommand(fN);function resolveBundledRipgrepPath(){try{const e=vt(import.meta.url),{rgPath:t}=e("@vscode/ripgrep");if("string"==typeof t&&t.length>0&&A(t))return t}catch{}}function registerBundledRipgrep(){if(process.env[lc])return;const e=resolveBundledRipgrepPath();void 0!==e&&(process.env[lc]=e)}Gt(),SR(),__name(resolveBundledRipgrepPath,"resolveBundledRipgrepPath"),__name(registerBundledRipgrep,"registerBundledRipgrep"),Gt(),SR(),Gt();var vN=["EPIPE","ECONNRESET","EOF"];function asErrnoLike(e){if("object"==typeof e&&null!==e)return e}function isBenignStreamWriteError(e){const t=asErrnoLike(e);if(!t)return!1;const n="string"==typeof t.code?t.code:"",r="string"==typeof t.message?t.message:"";return!!vN.some(e=>r.includes(`write ${e}`))||"write"===("string"==typeof t.syscall?t.syscall:"")&&vN.includes(n)}async function handleEffortCommand(e,t){const n=e.currentModel,r=n?customReasoningEfforts(n)??getSupportedEfforts(n):null,o=t.trim().toLowerCase();if(o&&n&&r){if(r.includes(o)){const t=o,r=getReasoningEffort(n),s=k$(e.sessionId),i=s?s.getEffort():r;return t!==r&&await setReasoningEffort({modelId:n,effort:t}),t!==i&&(s?.recordEffortChange({model:n,effort:t}),hardResetForResize(),e.setStaticKey(e=>e+1)),void e.setFeed(e=>[...e,uh(`Reasoning effort set to ${t}.`)])}if(r.length>0)return void e.setFeed(e=>[...e,uh(`Unknown effort "${t.trim()}". Supported: ${r.join(", ")}.`)])}const s=resolveEffortCommand({model:n,supportedEfforts:r,modelLabel:n?getModelDisplayName(n):void 0});"notice"!==s.kind?e.setShowEffortSelector(!0):e.setFeed(e=>[...e,uh(s.message)])}async function applyEffortSetting(e,t){const n=e.trim().toLowerCase();if(!n)return{ok:!1,message:"Provide a level, e.g. --effort high."};const r=t?.model??getConfiguredModel(),o=customReasoningEfforts(r)??getSupportedEfforts(r);return o&&0!==o.length?o.includes(n)?(await setReasoningEffort({modelId:r,effort:n}),{ok:!0,message:`Reasoning effort set to ${n} for ${getModelDisplayName(r)}.`}):{ok:!1,message:`Unknown effort "${e.trim()}". Supported: ${o.join(", ")}.`}:{ok:!1,message:`${getModelDisplayName(r)} has no adjustable reasoning effort.`}}function usePasteAwareChange(e){const{onChange:t,onPaste:n}=e,r=lt(!1);return ut(async e=>{const o=processBracketedPaste(e),s=n??t,i=__name(async()=>{r.current=!1;const e=await detectClipboardTextNative();e?s(e):o.cleanedContent&&s(o.cleanedContent)},"applyPastedText");if(!o.isPasteStart||r.current)r.current&&!o.isPasteEnd||(r.current&&o.isPasteEnd?await i():t(e));else{if(r.current=!0,!o.isPasteEnd)return;await i()}},[t,n])}function extractDeviceCode2(e){const t=e.match(/copy\s+this\s+code:\s*([^\s]+)/i);return t?.[1]??null}__name(asErrnoLike,"asErrnoLike"),__name(isBenignStreamWriteError,"isBenignStreamWriteError"),Gt(),SR(),Gt(),SR(),Gt(),SR(),Gt(),SR(),__name(handleEffortCommand,"handleEffortCommand"),__name(applyEffortSetting,"applyEffortSetting"),Gt(),SR(),Gt(),SR(),Gt(),SR(),Gt(),SR(),__name(usePasteAwareChange,"usePasteAwareChange"),__name(extractDeviceCode2,"extractDeviceCode");var kN=__name(({providerId:e,onSuccess:t,onCancel:n,onFailure:r})=>{const o=getProviderDisplayName(e),[s,i]=at("confirm"),[a,l]=at(""),[c,d]=at(""),[u,m]=at(""),[p,g]=at(""),[h,f]=at(null),y=lt(!1),S=lt(!0),w=lt(!1),v=lt(null),k=lt(null),C=lt(null),b=lt(!1);ct(()=>()=>{S.current=!1,v.current&&clearTimeout(v.current),C.current=null},[]);const E=ut(e=>{w.current||(w.current=!0,v.current=setTimeout(()=>{if(v.current=null,!S.current)return;const t=e.keepTerminalActive?{wait:!1,background:!0}:void 0;Pt(e.authUrl,t).catch(()=>{S.current&&f(`Failed to open browser. Please manually open: ${e.authUrl}`)})},300))},[]),T=ut(async t=>{if(!S.current)return;if(l(t.url),t.prompt)return d(t.instructions),b.current=!0,m(t.prompt.label),i("paste"),E({authUrl:t.url,keepTerminalActive:!1}),new Promise(e=>{k.current=e});b.current=!1;const n=e===uo.COPILOT?extractDeviceCode2(t.instructions):null;if(n){const e=await writeClipboardText(n);if(!S.current)return;d(`Logging into Copilot, use this code: ${n}${e?" (copied)":""}`)}else d(t.instructions);return i("open-browser"),new Promise(e=>{C.current=()=>{C.current=null,i("waiting"),Pt(t.url).catch(()=>{S.current&&f(`Failed to open browser. Please manually open: ${t.url}`)}),e({})}})},[e,E]),P=lt(()=>{});P.current=()=>{providerLogin({provider:e,onPending:T}).then(async()=>{S.current&&(await persistProviderSelection(e),i("success"),t())}).catch(e=>{if(!S.current)return;const t=e instanceof Error?e.message:"Authentication failed";if(f(t),y.current=!1,k.current=null,r?.(t),b.current)return g(""),void P.current();i("error")})};const M=ut(e=>{g(e.trim())},[]),x=usePasteAwareChange({onChange:g,onPaste:M}),I=__name(()=>{if(!p.trim()||y.current||!k.current)return;y.current=!0,f(null);const e=k.current;k.current=null,e({code:p.trim()})},"handleSubmit");if(nt((e,t)=>{if(t.escape)n();else if(!t.leftArrow||"confirm"!==s&&"open-browser"!==s&&"waiting"!==s&&"error"!==s&&("paste"!==s||p)){if("confirm"===s){if(t.return||"y"===e||"Y"===e)return i("connecting"),void P.current();"n"!==e&&"N"!==e||n()}"open-browser"===s&&t.return&&C.current?.()}else n()}),"confirm"===s){const t=e===uo.COPILOT?"This will get a GitHub sign-in code.":`This will open your browser to sign in with ${o}.`;return st.createElement(bO,{title:`Sign in to ${o}`,subtitle:t,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"y"),"/",st.createElement(gO,null,"enter")," ","continue"),st.createElement(st.Fragment,null,st.createElement(gO,null,"n"),"/",st.createElement(gO,null,"esc")," ","cancel")]})})}return"connecting"===s?st.createElement(bO,{title:`Sign in to ${o}`,subtitle:"Getting sign-in code…",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," cancel")]})}):"paste"===s?st.createElement(bO,{title:`Sign in to ${o}`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," submit"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," cancel")]})},a&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},"Login: "),st.createElement(cL,{url:a,text:"Open auth page ↗",color:ER.CYAN})),c&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},c)),h&&st.createElement(Qe,{marginBottom:1},st.createElement(R$,null,h)),st.createElement(Qe,null,st.createElement(Xe,null,u||"Authorization code",": "),st.createElement(TextInput,{mask:"*",focus:!0,value:p,onChange:x,onSubmit:I,placeholder:"Paste code here..."}))):"open-browser"===s?st.createElement(bO,{title:`Sign in to ${o}`,subtitle:e===uo.COPILOT?"Press enter to open GitHub and paste the code there":"Press enter to open your browser",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," cancel")]})},c&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0,color:ER.GREEN},c)),a&&e!==uo.COPILOT&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},"Login: "),st.createElement(cL,{url:a,text:"Open auth page ↗",color:ER.CYAN}))):"waiting"===s?st.createElement(bO,{title:`Sign in to ${o}`,subtitle:"Waiting for authorization…",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," cancel")]})},c&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0,color:ER.GREEN},c)),a&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},"Open: "),st.createElement(cL,{url:a,text:"Open auth page ↗",color:ER.CYAN}))):"error"===s?st.createElement(bO,{title:`Sign in to ${o}`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," back")]})},st.createElement(R$,null,h)):null},"ProviderAuth");function makeProviderAuthComponent(e){const t=__name(({onSuccess:t,onCancel:n})=>st.createElement(kN,{providerId:e,onSuccess:t,onCancel:n}),"Bound");return t.displayName=`ProviderAuth(${e})`,t}__name(makeProviderAuthComponent,"makeProviderAuthComponent");var CN=Object.fromEntries(Object.entries(Xo).map(([e,t])=>[e,{...t}]));function getProviderConfig(e){return CN[e]}async function getProviderAuthState(e){if(!e)return null;const t=getProviderConfig(e);return t?resolveProviderAuthState({displayName:t.displayName,requiresAuth:t.requiresAuth,checkAuth:t.checkAuth}):null}async function handleModelSelect({modelId:e,provider:t,routeProvider:n,setCurrentModel:r,setShowModelSelector:o,setStatus:s,modelNotificationTimer:i,setShowModelNotification:a,setCurrentProvider:l,setStaticKey:c,sessionId:d,setFeed:u,setContextUsage:m,setModelNotice:p}){try{const g=t&&getProviderConfig(t)?t:void 0,h=n??(t&&!getProviderConfig(t)?t:void 0),f=g?await getConfiguredProvider():void 0,y=await applyCommandModelSelection({modelId:e,provider:g,routeProvider:h,sessionId:d,catalog:{getDisplayName:getModelDisplayName},deps:{getProviderAuthState:getProviderAuthState,getCurrentModel:getConfiguredModel,persistProvider:__name(async t=>{dlog(`[Model] Setting provider to ${t} for ${e}`),await updateUserConfig({provider:t})},"persistProvider"),persistDefaultModel:__name(async(e,t)=>{await persistDefaultModel({model:e,provider:t})},"persistDefaultModel"),setSessionModel:setSessionModel,clearModelOverride:clearModelOverride,saveSessionModel:__name(async({sessionId:e,modelId:t,routeProvider:n})=>{await saveCommandSessionMeta({sessionId:e,meta:{model:t,modelProvider:n}})},"saveSessionModel"),onProviderPersisted:l,log:dlog}});if("auth-blocked"===y.status)return s(y.message),void o(!1);if(d&&g&&g!==f&&await rebuildHarnessSession(d),r(e),y.modelChanged&&(hardResetForResize(),c(e=>e+1)),o(!1),s(y.statusMessage),y.modelChanged&&p?.(getModelNotice(e)??null),y.modelChanged){const t=await reconcileCommandModelSelection({modelId:e,...void 0!==h?{routeProvider:h}:{},modelName:y.modelName,previousModel:y.previousModel,harness:d?k$(d):void 0,catalog:{getContextLimit:__name(e=>customAwareContextLimit({modelId:e,fallback:getContextLimit}),"getContextLimit"),supportsVision:modelSupportsVision},hasImagesInHistory:harnessHasImagesInHistory});m?.(t.contextUsage);for(const e of t.notices)u?.(t=>[...t,uh(e.message)])}i.current&&clearTimeout(i.current),a(!0),i.current=setTimeout(()=>{a(!1),i.current=null},5e3)}catch(e){console.error("Failed to set model:",e),s("Failed to set model"),o(!1)}}function handleModelCancel({setShowModelSelector:e}){e(!1)}async function handleModelCommand(e,t){const n=t.trim();if(!n)return void e.setShowModelSelector(!0);const r=await resolveSelectableModel(n);if(!r)return e.setFeed(e=>[...e,uh(`Unknown model "${n}" — opening the model picker so you can choose.`)]),void e.setShowModelSelector(!0);r.warning&&e.setFeed(e=>[...e,uh(r.warning)]);const o=r.modelId;await handleModelSelect({modelId:o,routeProvider:r.providerId,provider:r.providerId?void 0:getProviderFromModel(o)||void 0,setCurrentModel:e.setCurrentModel??(()=>{}),setShowModelSelector:e.setShowModelSelector,setStatus:e.setStatus,modelNotificationTimer:{current:null},setShowModelNotification:__name(()=>{},"setShowModelNotification"),setStaticKey:e.setStaticKey,sessionId:e.sessionId,setFeed:e.setFeed,setContextUsage:e.setContextUsage,setModelNotice:e.setModelNotice})}async function applyModelSetting(e){const t=e.trim();if(!t)return{ok:!1,message:"Provide a model, e.g. --model gpt-5."};const n=await resolveSelectableModel(t);if(!n)return{ok:!1,message:`Unknown model "${t}". Run with --list-models to see the options.`};const r=n.modelId;await persistDefaultModel({model:r,provider:n.providerId});const o=n.providerId?void 0:getProviderFromModel(r);o&&await updateUserConfig({provider:o});const s=n.warning?` (note: ${n.warning})`:"";return{ok:!0,message:`Default model set to ${getModelDisplayName(r)}.${s}`}}async function handleThemeSelect({theme:e,setShowThemeSelector:t,setStatus:n,setStaticKey:r}){t(!1);try{const t=resolveCliTheme(getCliTheme()),o=resolveCliTheme(e),s=t!==o;await setCliTheme({theme:e}),applyTuiTheme(o),s&&(RL(),hardResetForResize(),r(e=>e+1)),n(buildThemeStatusMessage(e))}catch{n(Eo)}}function handleThemeCancel({setShowThemeSelector:e}){e(!1)}async function handleThemeCommand(e,t){const n=t.trim().toLowerCase();n?so.includes(n)?await handleThemeSelect({theme:n,setShowThemeSelector:e.setShowThemeSelector,setStatus:e.setStatus,setStaticKey:e.setStaticKey}):e.setFeed(e=>[...e,uh(`Unknown theme "${n}". Options: ${so.join(", ")}.`)]):e.setShowThemeSelector(!0)}async function applyThemeSetting(e){const t=e.trim().toLowerCase();return t?so.includes(t)?(await setCliTheme({theme:t}),{ok:!0,message:`Theme set to ${t}.`}):{ok:!1,message:`Unknown theme "${e.trim()}". Options: ${so.join(", ")}.`}:{ok:!1,message:"Provide a theme, e.g. --theme auto."}}CN.anthropic&&(CN.anthropic.authComponent=makeProviderAuthComponent(uo.ANTHROPIC),CN.anthropic.checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:uo.ANTHROPIC});return!!e}),CN["github-copilot"]&&(CN["github-copilot"].authComponent=makeProviderAuthComponent(uo.COPILOT),CN["github-copilot"].checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:uo.COPILOT});return!!e}),CN.codex&&(CN.codex.authComponent=makeProviderAuthComponent(uo.CODEX),CN.codex.checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:uo.CODEX});return!!e}),__name(getProviderConfig,"getProviderConfig"),__name(getProviderAuthState,"getProviderAuthState"),__name(handleModelSelect,"handleModelSelect"),__name(handleModelCancel,"handleModelCancel"),__name(handleModelCommand,"handleModelCommand"),__name(applyModelSetting,"applyModelSetting"),Gt(),SR(),__name(handleThemeSelect,"handleThemeSelect"),__name(handleThemeCancel,"handleThemeCancel"),__name(handleThemeCommand,"handleThemeCommand"),__name(applyThemeSetting,"applyThemeSetting");var bN=[{key:"model",apply:__name(e=>applyModelSetting(e),"apply")},{key:"effort",valueHint:"level",description:"Set reasoning effort for the session (e.g. low, medium, high) — depends on the model",apply:__name((e,t)=>applyEffortSetting(e,t),"apply")},{key:"theme",valueHint:"theme",description:"Set the color theme (dark or light)",apply:__name(e=>applyThemeSetting(e),"apply")}],EN=__name(e=>`--${e.key} <${e.valueHint}>`,"flagSpecOf"),TN=bN.filter(e=>void 0!==e.valueHint&&void 0!==e.description);async function applyConfigSetting(e){const t=e.indexOf("=");if(t<1)return{ok:!1,message:"Use --config key=value, e.g. --config theme=dark."};const n=e.slice(0,t).trim().toLowerCase(),r=e.slice(t+1).trim(),o=bN.find(e=>e.key===n);if(o)return o.apply(r);const s="true"===r||"false"!==r&&r;try{return await updateConfigSetting({id:n,value:s}),{ok:!0,message:`Set ${n} = ${r}.`}}catch(e){return{ok:!1,message:e instanceof Error?e.message:`Could not set config "${n}".`}}}__name(applyConfigSetting,"applyConfigSetting"),Gt(),SR();var PN=["default","standard","plan","accept-edits","auto-accept","yolo","bypass","dont-ask"];function parsePermissionModeOption(e){const t=PN.includes(e)?normalizePermissionMode(e):void 0;if(!t)throw new He(`Allowed choices are ${PN.join(", ")}.`);return t}__name(parsePermissionModeOption,"parsePermissionModeOption");var MN=getPackageJson(import.meta.url),xN=__name((e,t=[])=>[...t,e],"collectAddDir"),IN=__name((e,t=[])=>[...t,e],"collectConfig");function displayCustomHelp(){const e=MN.version,t=getInvokedCommandName(),n=getVisibleSlashCommands();console.log(),console.log(ht.bold("Command Code")+ht.gray(` v${e}`)),console.log(ht.gray(hi)),console.log(),console.log(ht.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(ht.bold("Options"));for(const e of ki){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(fi)+ht.gray(e.description))}console.log(),console.log(ht.bold("Commands"));for(const e of bi){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(fi)+ht.gray(e.description))}console.log(),console.log(ht.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(fi)+ht.gray(e.description));console.log(),console.log(ht.bold("Keyboard Shortcuts"));for(const e of vi)console.log(" "+e.key.padEnd(fi)+ht.gray(e.description));console.log(),console.log(ht.bold("Examples"));for(const e of Ti){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(fi)+ht.gray(e.description))}console.log(),console.log(ht.cyan("❯")+" "+ht.gray(yi.replace(/cmd/,t))),console.log(),console.log(ht.bold("Links"));for(const e of Ei)console.log(" "+e.key.padEnd(fi)+ht.cyan(e.description));console.log()}function createProgram(){const e=new Be;e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(MN.version??"0.0.0","-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume [name]","Resume a session by id or name, or pick from history").option("--sessions [name]","Alias of --resume — resume a session by id or name, or pick from history").option("-c, --continue"," Continue the most recent session in the current directory").option("--fork-session","With --resume/--continue, fork the session into a new one (original left untouched)").option("--session <path|id>","Resume a session by transcript path (.jsonl) or a unique session-id prefix").option("--no-session","Don't persist this session to disk (in-memory only)").option("-n, --name <name>","Set the session display name").option("-t, --trust","Trust the project (skip initial trust permission prompt)").addOption(new We("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new We("--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 We("--accept-edits","Start in accept edits mode").implies({permissionMode:"auto-accept"})).addOption(new We("--auto-accept").implies({permissionMode:"auto-accept"}).hideHelp()).addOption(new We("--permission-mode <mode>","Set permission mode").choices(PN).argParser(parsePermissionModeOption)).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>",`Max agentic turns (model API round trips): print mode limit (default ${pi}); interactive mode sets the /goal turn budget (default 100)`,e=>{const t=parseInt(e,10);if(isNaN(t)||t<1)throw new He("--max-turns must be a positive integer");return t}).option("--verbose","Stream tool execution progress to stderr in print mode").option("--tools-all","Print mode: enable every tool, including the ones a headless run withholds").option("--tools-enable <names>","Print mode: enable specific withheld tools by name, comma-separated (e.g. ask_user_question,exit_plan_mode); repeatable",xN,[]).addOption(new We("--output-format <format>","Print-mode output: text (default) or json — newline-delimited AgentEvent frames plus one final result line").choices(["text","json"])).option("--ide-setup",Si).option("--no-auto-update","Disable automatic background updates for this run").option("--add-dir <directory>","Add directory to workspace context",xN,[]).option("-w, --worktree [name]","Run this session in an isolated git worktree (managed under ~/.commandcode/worktrees/). Accepts a name, a path, or a PR (#1234). Generates a name when omitted.").option("--mod <path>","Load a mod file or directory for this session (repeatable)",xN,[]).option("--mod-option <name=value>","Set a mod-declared flag value (repeatable)",xN,[]).option("--skill <path>","Load extra skills from a path (a skill directory or a directory of skills); repeatable",xN,[]).option("--no-skills","Skip skill discovery; paths given via --skill still load").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 We("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new We("--experimental","Enable experimental features").hideHelp()).addOption(new We("-d, --debug","Enable debug mode").hideHelp()).option("--local-only","For BYOK: local-only with your BYOK providers, no Command Code traffic (same as CMD_LOCAL_ONLY=1)").addOption(new We("--local","Use local server").hideHelp()).addOption(new We("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption();for(const t of TN)e.option(EN(t),t.description);return e.option("--config <key=value>","Set a setting headlessly, e.g. --config theme=dark (repeatable)",IN),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram");var AN=null;function commandPath(e){const t=[];let n=e;for(;null!==n&&null!==n.parent;)t.unshift(n.name()),n=n.parent;return t.join(" ")}function flagNames(e){return Object.entries(e.opts()).filter(([,e])=>void 0!==e&&!1!==e).map(([e])=>`--${e}`).join(" ")}function failPendingCommandSpan(e){null!==AN&&(recordError({span:AN,error:sanitizeErrorForTelemetry({error:e,label:"command_error"})}),AN.end(),AN=null)}function abandonPendingCommandSpan(){null!==AN&&(AN.setAttribute("cmd.command.outcome","abandoned"),AN.end(),AN=null)}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(" ")}`);const a=commandPath(t);if(!a)return;const l=flagNames(t);AN=createSpan({name:`command:${a}`,attributes:{"cmd.command.name":a,"cmd.command.arg_count":i.length,...l?{"cmd.command.args":l}:{}}})}),e.hook("postAction",()=>{dlogSection("Done"),null!==AN&&(endSpan({span:AN,status:"success"}),AN=null)})}__name(commandPath,"commandPath"),__name(flagNames,"flagNames"),__name(failPendingCommandSpan,"failPendingCommandSpan"),__name(abandonPendingCommandSpan,"abandonPendingCommandSpan"),__name(setupCommanderHooks,"setupCommanderHooks");var{red:RN,yellow:LN,dim:ON}=ht;function printErrorDetails(e,t){if(console.log(`${xt.error} ${RN(t)}`),console.log(`${xt.error} ${RN("ERROR →")} ${e.name}`),console.log(`${xt.info} ${RN("REASON →")} ${e.message}`),console.log(`${xt.info} ${RN("ERROR STACK ↓ \n")} ${e.stack}\n`),!isTelemetryInitialized())return;const n=getDisplayTraceId();console.log(`${xt.info} ${ON(`Trace ID: ${n}`)}`),console.log(`${ON(" Share this ID with support to help debug your issue.")}\n`)}__name(printErrorDetails,"printErrorDetails");var DN=__name(e=>{const{heading:t="ERROR: ",error:n,displayError:r=!0,exit:o=!0,skipTelemetry:s=!1}=e;if(n){if(s||trackCliError({error:n,heading:t}),failPendingCommandSpan(n),console.log(),r||console.log(`${xt.warning} ${LN(t)}\n`),r&&printErrorDetails(n,t),!o)return!1;process.exit(0)}},"handleError");Gt(),SR();var $N,NN,_N=[],FN=[];function setModPathsOverride(e){_N=e}function setModOptionsOverride(e){FN=e}function loadCommandModHost(e={}){return $N||($N=buildHost(e))}async function buildHost(e){try{const t=createNodeRuntime(),n=createModHost({runtime:t}),r=!1!==e.projectMods&&await isCommandProjectSessionInitialized();await loadMods({runtime:t,host:n,includeProject:r,extraPaths:_N,builtins:commandBuiltinMods()});for(const e of FN){const t=e.indexOf("=");t<=0?dlog(`[mods] ignoring malformed --mod-option "${e}"`):n.setFlagValue({name:e.slice(0,t),value:e.slice(t+1)})}for(const e of n.warnings())dlog(`[mods] ${e.path}: ${e.reason}`);return setActiveModHost(n),setRegisteredProviderModules({modules:n.providerModules()}),n}catch(e){return void dlog(`[mods] host construction failed: ${e instanceof Error?e.message:String(e)}`)}}function disposeCommandModHost(){return NN??=$N?runModHostTeardown({host:$N}):Promise.resolve(),NN}function exitAfterModHostTeardown(e){disposeCommandModHost().finally(()=>{process.exit(e)})}async function runModHostTeardown(e){const t=__name(async()=>{const t=await e.host;t&&(t.dispose(),await t.settle())},"teardown");try{await Promise.race([t(),new Promise(t=>{const n=setTimeout(t,e.graceMs??300);n.unref?.()})])}catch(e){dlog(`[mods] teardown failed: ${e instanceof Error?e.message:String(e)}`)}}function handleStdoutError(e){if(!isBenignStreamWriteError(e))throw e;exitAfterModHostTeardown(0)}function handleStderrError(e){if(!isBenignStreamWriteError(e))throw e}function handleUnhandledErrors(){process.stdout.on("error",handleStdoutError),process.stderr.on("error",handleStderrError),process.on("unhandledRejection",e=>{const t=e instanceof Error?e:new Error(String(e));trackError({error:sanitizeErrorForTelemetry({error:t,label:"unhandled_rejection"}),context:{component:Ho.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),DN({heading:Tt`CRITICAL: Unhandled Promise Rejection!
14
+ `,oO=getMaxLineWidth(rO),sO=eO,iO=__name(e=>{const t=e??getTerminalWidth();return t>=ZL?"full":t>=sO?"compact":"minimal"},"getHeaderLayout");new Set(["dark","light"]),Gt(),SR();var aO=!1;async function resolveStartupTheme(){return aO||(aO=!0,setDetectedTerminalTheme(await detectTerminalTheme())),resolveCliTheme(getCliTheme())}async function applyStartupTheme(){const e=await resolveStartupTheme();return applyTuiTheme(e),e}function useAuthFlow(e){const{onSuccess:t,onFailure:n,onCancel:r,timeout:o=zo}=e,[s,i]=at("initializing"),[a,l]=at("Starting authentication..."),[c,d]=at(""),[u,m]=at(null),p=lt(t),g=lt(n),h=lt(r);ct(()=>{p.current=t,g.current=n,h.current=r});const f=lt(null);f.current??=createAuthFlowController({timeoutMs:o,openBrowser:__name(e=>Pt(e),"openBrowser"),onAuthStateChange:i,onStatusMessageChange:l,onBrowserUrlChange:m,onSuccess:__name(({config:e,source:t})=>p.current(e,t),"onSuccess"),onFailure:__name(({reason:e,message:t})=>g.current(e,t),"onFailure"),onCancel:__name(()=>h.current(),"onCancel")});const y=f.current,S=ut(()=>{y.cancel()},[y]),w=ut(e=>y.submitApiKey(e),[y]);return ct(()=>(y.start(),()=>{y.dispose()}),[y]),{authState:s,statusMessage:a,browserUrl:u,apiKeyInput:c,setApiKeyInput:d,handleApiKeySubmit:w,cancel:S,hasCompleted:y.hasCompleted()}}function useCursorState({value:e,focus:t,showCursor:n,initialCursor:r}){const[o,s]=at(r??(e||"").length),i=lt(o),a=lt(e);ct(()=>{const r=a.current;if(a.current=e,e===r)return;if(!t)return;if(!n)return;const l=(e||"").length;o>l&&(s(l),i.current=l)},[e,t,n,o]);const l=ut(e=>{s(e),i.current=e},[]);return{cursor:o,setCursor:l,cursorRef:i}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:o,stripBracketedPaste:s=!1,transformPaste:i,deferEmptyPaste:a=!1}){const l=lt(!1),c=lt(i);c.current=i;const d=lt(a);d.current=a,ct(()=>{if(!e)return;const i=process.stdin,a=__name(e=>{o(!0);const t=clampCursor(e.cursor,e.value.length);r(e.value,t),setTimeout(()=>o(!1),0)},"emitStdinResult"),u=__name(e=>{const r=e.toString();if(s){const e=processBracketedPasteInput({input:r,value:t.current,cursor:n.current,transform:c.current});if(e.handled)return void(e.value===t.current&&d.current||a(e))}const o=processRawInput(r,t.current,n.current);o.handled&&a(o)},"handleRawInput");if(i.on("data",u),!l.current&&hasBufferedInput()){l.current=!0;const e=consumeBufferedInput();e&&u(Buffer.from(e))}return stopEarlyInputCapture(),()=>{i.off("data",u)}},[e,t,n,r,o,s])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:o,onUpdate:s,onSubmit:i}){nt((e,a)=>{if(o())return;if(isIgnoredKey(e,a))return;if(a.return)return void(a.shift||a.ctrl||a.meta||i?.(n.current));const l=processInkInput(e,a,n.current,r.current,t);if(!l.handled)return;const c=clampCursor(l.cursor,l.value.length);s(l.value,c)},{isActive:e})}function useSyncedRef(e){const t=lt(e);return t.current=e,t}function useEchoAwareValueRef(e){const t=lt(e),n=lt([]),r=n.current.indexOf(e);return-1!==r&&n.current.splice(0,r+1),-1===r&&t.current!==e&&(t.current=e,n.current=[]),{valueRef:t,noteEmittedValue:ut(e=>{n.current.push(e),n.current.length>64&&n.current.shift()},[])}}__name(resolveStartupTheme,"resolveStartupTheme"),__name(applyStartupTheme,"applyStartupTheme"),Gt(),Gt(),SR(),__name(useAuthFlow,"useAuthFlow"),Gt(),SR(),Gt(),SR(),Gt(),SR(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef"),__name(useEchoAwareValueRef,"useEchoAwareValueRef"),Gt(),SR();var lO=ht.hex(ER.DIM),cO=__name(e=>ht.hex(WR.CODE)(e),"accentHex"),dO=/^\/[A-Za-z0-9][\w/:-]*/,uO=/(^|\s)(@\S+)/g;function pastedTokenRanges(e,t){const n=[],r=new RegExp(hM.source,"g");let o;for(;null!==(o=r.exec(e));)n.push({start:o.index,end:o.index+o[0].length,link:null,color:"dim"});if(t&&t.size>0){const r=new RegExp(fM.source,"g");for(;null!==(o=r.exec(e));){const e=Number(o[1]);if(!t.has(e))continue;const r=t.get(e)??null;n.push({start:o.index,end:o.index+o[0].length,link:r?fileUrl(r):null,color:"dim"})}}return n.sort((e,t)=>e.start-t.start)}function accentTokenRanges(e,t,n){const r=__name((e,n)=>t.some(t=>e<t.end&&n>t.start),"overlapsOccupied"),o=__name(e=>!n||n(e),"isAccentedCommand"),s=[],i=dO.exec(e);i&&!r(0,i[0].length)&&o(i[0])&&s.push({start:0,end:i[0].length,link:null,color:"accent"});const a=new RegExp(uO.source,"g");let l;for(;null!==(l=a.exec(e));){const e=l.index+l[1].length,t=e+l[2].length;r(e,t)||s.push({start:e,end:t,link:null,color:"accent"})}return s}function renderPlainSpan(e,t,n,r,o){let s="";for(let i=t;i<n;i++){const t=e[i];s+=o&&i===r?"\n"===t?Et.inverse(" ")+"\n":Et.inverse(t):t}return s}function renderTokenSpan(e,t,n,r,o,s="dim"){const i="accent"===s?cO:lO;return o&&r>=t&&r<n?i(e.slice(t,r))+Et.inverse(e[r])+i(e.slice(r+1,n)):i(e.slice(t,n))}function renderPlaceholder(e,t){return t?0===e.length?Et.inverse(" "):Et.inverse(e[0])+lO(e.slice(1)):lO(e)}function renderValue(e,t,n,r,o){const s=pastedTokenRanges(e,r),i=[...s,...accentTokenRanges(e,s,o)].sort((e,t)=>e.start-t.start);if(!n&&0===i.length)return e;if(n&&0===e.length)return Et.inverse(" ");let a="",l=0;for(const{start:r,end:o,link:s,color:c}of i){a+=renderPlainSpan(e,l,r,t,n);const i=renderTokenSpan(e,r,o,t,n,c);a+=s?createOSC8Link(s,i,!1):i,l=o}return a+=renderPlainSpan(e,l,e.length,t,n),n&&t===e.length&&(a+=Et.inverse(" ")),a}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(wt(e).length<=s)return e;const i=e.split(/(\s+)/);let a="",l=0,c=!0;for(const e of i){const t=wt(e).length;if(l+t>(c?s:o)&&l>0&&(a+="\n"+r,l=n,c=!1),a+=e,l+=t,e.includes("\n")){const t=e.substring(e.lastIndexOf("\n")+1);l=wt(t).length,c=!0}}return a}function getDisplayValue(e,t,n,r,o,s,i){const a=r&&o;return 0===e.length&&t?renderPlaceholder(t,a):renderValue(e,n,a,s,i)}function getMaskedValue(e,t){return t?t.repeat(e.length):e}__name(pastedTokenRanges,"pastedTokenRanges"),__name(accentTokenRanges,"accentTokenRanges"),__name(renderPlainSpan,"renderPlainSpan"),__name(renderTokenSpan,"renderTokenSpan"),__name(renderPlaceholder,"renderPlaceholder"),__name(renderValue,"renderValue"),__name(wrapWithIndent,"wrapWithIndent"),__name(getDisplayValue,"getDisplayValue"),__name(getMaskedValue,"getMaskedValue"),SR();var mO={white:Et.white,green:Et.green,red:Et.red,blue:Et.blue,yellow:Et.yellow,cyan:Et.cyan,magenta:Et.magenta,gray:Et.gray,grey:Et.gray};function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:o=!0,onChange:s,onSubmit:i,onCursorChange:a,prefix:l="",prefixColor:c,singleLine:d=!1,maxWidth:u,stripBracketedPaste:m=!1,disablePasteRouting:p=!1,clipboardOnEmptyPaste:g=!1,collapsePastedText:h=!1,onPasteCollapsed:f,initialCursor:y,imageTokenLinks:S,isRecognizedSlashCommand:w}){const v=lt(!1),k=lt(0),{valueRef:C,noteEmittedValue:b}=useEchoAwareValueRef(e),E=useSyncedRef(s),T=useSyncedRef(f),{cursor:P,setCursor:M,cursorRef:x}=useCursorState({value:e,focus:n,showCursor:o,initialCursor:y});st.useEffect(()=>{a?.(P)},[P,a]);const I=ut((e,t)=>{M(t),e!==C.current&&(b(e),C.current=e,E.current(e))},[M,C,E,b]),A=ut(e=>{const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");return h&&isPasteWorthCollapsing({content:t,multiline:!0})?(T.current?.(t),pastedTextToken(t)):e},[h,T]),R=ut(e=>{v.current=e},[]),L=ut(()=>v.current||k.current>0,[]);useRawStdinHandler({focus:n,valueRef:C,cursorRef:x,onUpdate:I,setHandled:R,stripBracketedPaste:m,transformPaste:A,deferEmptyPaste:g}),st.useEffect(()=>{if(!n||p)return;let e=!0;const t=registerPasteConsumer(t=>{v.current||__name(async()=>{let n=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n");if(0===n.length){if(!g)return;k.current+=1;try{const e=await detectClipboardText();n=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}finally{k.current-=1}if(!e||!n)return}const r=A(n),o=insertTextAt(C.current,x.current,r);I(o.text,o.cursor)},"applyRoutedPaste")().catch(()=>{})});return()=>{e=!1,t()}},[n,p,g,A,C,x,I]),useInkInputHandler({focus:n,showCursor:o,valueRef:C,cursorRef:x,isHandledByStdin:L,onUpdate:I,onSubmit:i});const{stdout:O}=et(),D=O?.columns??80,$=getMaskedValue(e,r),N=c?mO[c]:void 0,_=l?N?N(l):l:"",F=getDisplayValue($,t,P,o,n,S,w),U=l?.length??0,j=_+F;if(d){const e=j.replace(/\n/g," ");return null!=u?st.createElement(Qe,{width:u},st.createElement(Xe,{wrap:"truncate"},e)):st.createElement(Xe,{wrap:"truncate"},e)}const B=wrapWithIndent(j,D,U);return st.createElement(Xe,{wrap:"wrap"},B)}__name(TextInput,"TextInput"),Gt();var pO=__name(({children:e})=>st.createElement(Xe,{italic:!0,color:ER.DIM},e),"HintText"),gO=__name(({children:e})=>st.createElement(Xe,{bold:!0},e),"HintKey"),hO=__name(({hints:e,marginTop:t=1})=>{const n=e.filter(e=>null!=e&&!1!==e&&""!==e);return 0===n.length?null:st.createElement(Qe,{marginTop:t},st.createElement(pO,null,n.map((e,t)=>st.createElement(st.Fragment,{key:t},t>0&&" · ",e))))},"HintBar");Gt();var fO=TR,yO=ER.DIM,SO=ER.DIMMER,wO=TR,vO=ER.WHITE,kO=ER.GRAY,CO=ER.GREEN;function hasContent(e){return null!=e&&""!==e}__name(hasContent,"hasContent");var bO=__name(({title:e,titleSuffix:t,subtitle:n,children:r,hint:o,footer:s,rule:i=!0,titleColor:a=fO,ruleColor:l=SO,gapAfterHeader:c=!0,boxProps:d})=>{const u=hasContent(n);return st.createElement(Qe,{flexDirection:"column",width:"100%",...d},i&&st.createElement(ZR,{dividerColor:l}),st.createElement(Qe,null,st.createElement(Xe,{bold:!0,color:a},e),hasContent(t)&&st.createElement(Xe,{color:yO},t)),u?st.createElement(Qe,{marginBottom:c?1:0},st.createElement(Xe,{color:yO},n)):c&&st.createElement(Qe,{marginBottom:1}),r,s?st.createElement(Qe,{marginTop:1},s):o?st.createElement(Qe,{marginTop:1},st.createElement(Xe,{italic:!0,color:yO},o)):null)},"Overlay"),EO=st.memo(({authState:e,browserUrl:t,apiKeyInput:n,setApiKeyInput:r,handleApiKeySubmit:o})=>{const s="waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,i=t&&("waiting_browser"===e||"manual_entry"===e);return st.createElement(st.Fragment,null,s&&st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?ER.YELLOW:ER.GRAY,paddingX:1},st.createElement(Xe,{color:ER.DIM},"API Key: "),st.createElement(Qe,{flexGrow:1},st.createElement(TextInput,{value:n,onChange:r,onSubmit:o,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},getCommandAuthHelpText(e))),i&&st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},getCommandAuthUrlLabel(e)),st.createElement(cL,{url:t,text:t,color:ER.CYAN,dimColor:!0}))),"validating"===e&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"invalid_key"===e)&&st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"ctrl+c to cancel")))});EO.displayName="AuthInputSection";var TO=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s})=>{const i=__name(()=>"waiting_browser"===e?st.createElement(kt,{type:"dots"}):"browser_success"===e||"success"===e?st.createElement(Xe,{color:ER.GREEN},gt.tick):"denied"===e||"invalid_key"===e?st.createElement(Xe,{color:ER.RED},gt.cross):"manual_entry"===e?st.createElement(Xe,{color:ER.YELLOW},gt.arrowDown):"error"===e?st.createElement(Xe,{color:ER.RED},gt.warning):st.createElement(kt,{type:"dots"}),"getStatusIcon"),a=__name(()=>getCommandAuthStatusColor(e),"getStatusColor");return"browser_success"===e||"success"===e||"denied"===e?null:st.createElement(bO,{title:"Sign in to Command Code"},st.createElement(Qe,{marginBottom:1},st.createElement(Qe,{marginRight:1},i()),st.createElement(Xe,{color:a()},t)),st.createElement(EO,{authState:e,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s}))},"AuthFlowUI"),PO=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:i,cancel:a}=useAuthFlow({onSuccess:__name((t,n)=>{e({success:!0,config:t,source:n})},"onSuccess"),onFailure:__name((t,n)=>{e({success:!1,reason:t,message:n})},"onFailure"),onCancel:__name(()=>{e({success:!1,reason:"cancelled",message:"Authentication cancelled by user."})},"onCancel")});return nt((e,t)=>{t.ctrl&&"c"===e&&a()}),st.createElement(TO,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:i})},"LoginWithApiKey");Gt(),SR();var MO=getPackageJson(import.meta.url),xO="string"==typeof MO.version&&MO.version.trim()?MO.version:"unknown";function createApiClient(e){return createCommandApiClient({baseUrl:e.baseUrl,timeout:e.timeout,cliVersion:xO,deps:{getAuthKey:getAuthKey,getTraceId:getTraceId,getTelemetryEnv:getTelemetryEnv,trackApiCallStart:trackAPICallStart,cmdZdrEnabled:__name(()=>"1"===process.env.CMD_ZDR,"cmdZdrEnabled"),deepseekInternalEnabled:__name(()=>"1"===process.env.CMD_PROVIDER_DEEPSEEK_INTERNAL,"deepseekInternalEnabled")}})}function getAuthKey(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function isJevFree(e=Date.now()){return e<=Date.parse("2026-09-24T23:59:59Z")}function isLingFlashFreeEnded(e=new Date){return e.getTime()>=Date.parse("2026-08-03T13:00:00Z")}__name(createApiClient,"createApiClient"),__name(getAuthKey,"getAuthKey"),Gt(),SR(),Gt(),Gt(),__name(isJevFree,"isJevFree"),Gt(),__name(isLingFlashFreeEnded,"isLingFlashFreeEnded"),Gt();var IO={GENERATE:"/alpha/agent/generate"},AO={RECORD:"/alpha/fingerprint/record"},RO={START:"/alpha/sandbox/start",SESSIONS:"/alpha/sandbox/sessions"},LO={CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",APPEND:"/alpha/share/append"},OO={CREATE:"/alpha/devrel-thread/create",DELETE:"/alpha/devrel-thread/delete",UPDATE:"/alpha/devrel-thread/update"},DO={GET:"/alpha/taste/:projectSlug",UPDATE:"/alpha/taste/:projectSlug/update",DELETE:"/alpha/taste/:projectSlug",LEARN:"/alpha/learn"},$O={CREDITS:"/alpha/billing/credits",SUBSCRIPTIONS:"/alpha/billing/subscriptions"},NO={SUMMARY:"/alpha/usage/summary"},_O={TRACK:"/alpha/lifecycle-events"},FO={GET:/\/internal\/orgs\/[a-zA-Z0-9_-]+/,FOLLOW:/\/internal\/orgs\/[a-zA-Z0-9-]+\/follow/,FOLLOWERS:/\/internal\/orgs\/[a-zA-Z0-9-]+\/followers/},UO={FOLLOW:/\/internal\/users\/[a-zA-Z0-9-]+\/follow/,FOLLOWERS:/\/internal\/users\/[a-zA-Z0-9-]+\/followers/,FOLLOWING:/\/internal\/users\/[a-zA-Z0-9-]+\/following/},jO={PACKAGES:{GET:/\/internal\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+/,FILES:/\/internal\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/files/,DOWNLOAD:/\/internal\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/download/,UPDATE:/\/internal\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/update/,STAR:/\/internal\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/star/,PIN:/\/internal\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/pin/}};function getBinaryCommand(){return"win32"===process.platform?"cmdc":"cmd"}Object.values({GET:/\/alpha\/taste\/[a-z0-9-]+/,UPDATE:/\/alpha\/taste\/[a-z0-9-]+\/update/,DELETE:/\/alpha\/taste\/[a-z0-9-]+\/rules\/[a-z0-9-]+/,LIST:/\/alpha\/taste\/[a-z0-9-]+\/rules/}),Object.values({UPLOAD:/^\/beta\/taste\/packages\/[a-zA-Z0-9_-]+$/,FILES:/\/beta\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/files/,GET:/\/beta\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+/,DOWNLOAD:/\/beta\/taste\/packages\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\/download/}),IO.GENERATE,AO.RECORD,RO.START,RO.SESSIONS,LO.CREATE,LO.DELETE,LO.APPEND,OO.CREATE,OO.DELETE,OO.UPDATE,DO.LEARN,DO.DELETE,DO.GET,DO.UPDATE,Object.values({UPLOAD:"/beta/taste/packages/:namespace",LIST:"/beta/taste/packages",GET:"/beta/taste/packages/:namespace/:packageName",FILES:"/beta/taste/packages/:namespace/:packageName/files",DOWNLOAD:"/beta/taste/packages/:namespace/:packageName/download",DELETE:"/beta/taste/packages/:namespace/:packageName"}),$O.CREDITS,$O.SUBSCRIPTIONS,NO.SUMMARY,_O.TRACK,Object.values(FO),Object.values(UO),Object.values(jO.PACKAGES),Object.values({GET:/\/internal\/profile\/[a-zA-Z0-9_-]+/,PACKAGES:/\/internal\/profile\/[a-zA-Z0-9_-]+\/packages/,FOLLOWING:/\/internal\/profile\/[a-zA-Z0-9_-]+\/following/,FOLLOWERS:/\/internal\/profile\/[a-zA-Z0-9_-]+\/followers/,PACKAGE_GET:/\/internal\/profile\/[a-zA-Z0-9_-]+\/packages\/[a-zA-Z0-9_-]+/,PACKAGE_DOWNLOAD:/\/internal\/profile\/[a-zA-Z0-9_-]+\/packages\/[a-zA-Z0-9_-]+\/download/}),__name(getBinaryCommand,"getBinaryCommand");var BO="anthropic",WO="openai",HO="baseten",GO="vercel-ai-gateway",VO="cloudflare-ai-gateway",zO="cmd-ai",KO="openrouter",qO="alibaba",YO="alibaba-intl",JO="novita",QO="morph",XO="wafer",ZO="longcat",eD="tencent",tD="terminal",nD=GO,rD={[BO]:[{id:"anthropic:claude-sonnet-5",provider:"Anthropic",category:"premium",promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:4,cacheHitCost:.2},{id:"anthropic:claude-sonnet-4-20250514",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-sonnet-4-5-20250929",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-opus-4-5-20251101",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-sonnet-4-6",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-fable-5-1",provider:"Anthropic",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:20,cacheHitCost:.25},{id:"anthropic:claude-fable-5",provider:"Anthropic",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:20,cacheHitCost:1},{id:"anthropic:claude-opus-5-5",provider:"Anthropic",category:"premium",promptCost:4,completionCost:20,cacheWrite5mCost:5,cacheWrite1hCost:8,cacheHitCost:.2},{id:"anthropic:claude-opus-5",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-8",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-7",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-6",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-haiku-4-5-20251001",provider:"Anthropic",category:"premium",promptCost:1,completionCost:5,cacheWrite5mCost:1.25,cacheWrite1hCost:2,cacheHitCost:.1}],[WO]:[{id:"openai:gpt-6-astra",provider:"OpenAI",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:0,cacheHitCost:1,contextTiers:[{maxInputTokens:272e3,promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:0,cacheHitCost:1},{promptCost:20,completionCost:75,cacheWrite5mCost:25,cacheWrite1hCost:0,cacheHitCost:2}]},{id:"openai:gpt-6-sol",provider:"OpenAI",category:"premium",promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.2,contextTiers:[{maxInputTokens:272e3,promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.2},{promptCost:4,completionCost:15,cacheWrite5mCost:5,cacheWrite1hCost:0,cacheHitCost:.4}]},{id:"openai:gpt-6-luna",provider:"OpenAI",category:"opensource",promptCost:.1,completionCost:.5,cacheWrite5mCost:.125,cacheWrite1hCost:0,cacheHitCost:.01,contextTiers:[{maxInputTokens:272e3,promptCost:.1,completionCost:.5,cacheWrite5mCost:.125,cacheWrite1hCost:0,cacheHitCost:.01},{promptCost:.2,completionCost:.75,cacheWrite5mCost:.25,cacheWrite1hCost:0,cacheHitCost:.02}]},{id:"openai:gpt-5.5",provider:"OpenAI",category:"premium",promptCost:5,completionCost:30,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.4",provider:"OpenAI",category:"premium",promptCost:2.5,completionCost:15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.25},{id:"openai:gpt-5.3-codex",provider:"OpenAI",category:"premium",promptCost:2,completionCost:8,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.4-mini",provider:"OpenAI",category:"premium",promptCost:.75,completionCost:4.5,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.075},{id:"openai:gpt-5.6-sol",provider:"OpenAI",category:"premium",promptCost:5,completionCost:30,cacheWrite5mCost:6.25,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.6-terra",provider:"OpenAI",category:"premium",promptCost:2,completionCost:12,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.2},{id:"openai:gpt-5.6-luna",provider:"OpenAI",category:"premium",promptCost:.2,completionCost:1.2,cacheWrite5mCost:.25,cacheWrite1hCost:0,cacheHitCost:.02}],[HO]:[{id:"baseten:zai-org/GLM-5",provider:"Baseten",category:"opensource",promptCost:.95,completionCost:3.15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0},{id:"baseten:moonshotai/Kimi-K2.5",provider:"Baseten",category:"opensource",promptCost:.6,completionCost:3,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0},{id:"baseten:moonshotai/Kimi-K2.6",provider:"Baseten",category:"opensource",promptCost:.95,completionCost:4,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.16},{id:"baseten:MiniMaxAI/MiniMax-M2.5",provider:"Baseten",category:"opensource",promptCost:.5,completionCost:2,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0}],[JO]:[{id:"novita:moonshotai/Kimi-K3",provider:"Novita",category:"opensource",promptCost:3,completionCost:15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.3},{id:"novita:zai-org/GLM-5.3",provider:"Novita",category:"opensource",promptCost:1.4,completionCost:4.4,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.26},{id:"novita:deepseek/deepseek-v4.1-flash",provider:"Novita",category:"opensource",promptCost:.15,completionCost:.6,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.003},{id:"novita:z-ai/glm-5.3-flash",provider:"Novita",category:"opensource",promptCost:.15,completionCost:.5,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.03}],[GO]:[],[KO]:[]};ye.enum(["owner","admin","member"]);var oD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,sD="chatComplete",iD="responses",aD="MiniMaxAI/MiniMax-M3-Free",lD={SONNET_5:{id:"claude-sonnet-5",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Sonnet 5",name:"Claude Sonnet 5",description:"best combo of speed & intelligence (recommended)",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},SONNET_4_6:{id:"claude-sonnet-4-6",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Sonnet 4.6",name:"Claude Sonnet 4.6",description:"prev Sonnet, still fast & capable",reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},FABLE_5_1:{id:"claude-fable-5-1",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Fable 5.1",name:"Claude Fable 5.1",description:"most capable for demanding reasoning & long-horizon agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},FABLE_5:{id:"claude-fable-5",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Fable 5",name:"Claude Fable 5",description:"prev Fable, still strong for deep reasoning & agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_5_5:{id:"claude-opus-5-5",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Opus 5.5",name:"Claude Opus 5.5",description:"most intelligent Opus for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_5:{id:"claude-opus-5",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Opus 5",name:"Claude Opus 5",description:"prev flagship, still strong for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_4_8:{id:"claude-opus-4-8",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Opus 4.8",name:"Claude Opus 4.8",description:"older Opus, still strong for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_4_7:{id:"claude-opus-4-7",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Opus 4.7",name:"Claude Opus 4.7",description:"older Opus, still strong for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},HAIKU_4_5:{id:"claude-haiku-4-5-20251001",inputModalities:["text","image"],provider:BO,spec:sD,label:"Claude Haiku 4.5",name:"Claude Haiku 4.5",description:"fastest & most compact, great for quick tasks",contextWindow:2e5},GPT_6_ASTRA:{id:"gpt-6-astra",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-6 Astra",name:"GPT-6 Astra",description:"most capable OpenAI model for demanding reasoning & agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_6_SOL:{id:"gpt-6-sol",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-6 Sol",name:"GPT-6 Sol",description:"built for complex coding & agentic workflows",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_6_LUNA:{id:"gpt-6-luna",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-6 Luna",name:"GPT-6 Luna",description:"most efficient OpenAI model for focused, high-volume tasks",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_5_6_SOL:{id:"gpt-5.6-sol",inputModalities:["text","image"],provider:GO,spec:iD,label:"GPT-5.6 Sol",name:"GPT-5.6 Sol",description:"frontier model for complex professional work",vendorLabel:"OpenAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_5_6_TERRA:{id:"gpt-5.6-terra",inputModalities:["text","image"],provider:GO,spec:iD,label:"GPT-5.6 Terra",name:"GPT-5.6 Terra",description:"balances intelligence and cost",vendorLabel:"OpenAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_5_6_LUNA:{id:"gpt-5.6-luna",inputModalities:["text","image"],provider:GO,spec:iD,label:"GPT-5.6 Luna",name:"GPT-5.6 Luna",description:"optimized for cost-sensitive workloads",vendorLabel:"OpenAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_5_5:{id:"gpt-5.5",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-5.5",name:"GPT-5.5",description:"latest frontier model for general complex work",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:4e5},GPT_5_4:{id:"gpt-5.4",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-5.4",name:"GPT-5.4",description:"frontier model for general complex work",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:4e5},GPT_5_3_CODEX:{id:"gpt-5.3-codex",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-5.3 Codex",name:"GPT-5.3 Codex",description:"frontier coding model",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:4e5},GPT_5_4_MINI:{id:"gpt-5.4-mini",inputModalities:["text","image"],provider:WO,spec:iD,label:"GPT-5.4 Mini",name:"GPT-5.4 Mini",description:"fast, cost-effective model for everyday tasks",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:4e5},MINIMAX_M3_PROMO_FREE:{id:aD,inputModalities:["text","image"],provider:nD,spec:sD,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",badge:"free",hidden:!0,reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},DEEPSEEK_V4_PRO:{id:"deepseek/deepseek-v4-pro",inputModalities:["text"],provider:nD,spec:sD,label:"DeepSeek V4 Pro (latest)",name:"DeepSeek V4 Pro (latest)",description:"hybrid-attention long-context reasoning",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},DEEPSEEK_V4_FLASH:{id:"deepseek/deepseek-v4-flash",inputModalities:["text"],provider:nD,spec:sD,label:"DeepSeek V4 Flash (latest)",name:"DeepSeek V4 Flash (latest)",description:"fast hybrid-attention reasoning",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},DEEPSEEK_V4_FLASH_VISION_EXP:{id:"deepseek/deepseek-v4-flash-vision-exp",inputModalities:["text","image"],provider:nD,spec:sD,label:"DeepSeek V4 Flash Vision (exp)",name:"DeepSeek V4 Flash Vision (exp)",description:"fast hybrid-attention reasoning with vision",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},DEEPSEEK_V4_FLASH_FAST:{id:"deepseek/deepseek-v4-flash-fast",inputModalities:["text"],provider:nD,spec:sD,label:"DeepSeek V4 Flash Fast",name:"DeepSeek V4 Flash Fast",description:"low-latency V4 Flash deployment",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},DEEPSEEK_V4_1_FLASH:{id:"deepseek/deepseek-v4.1-flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"DeepSeek V4.1 Flash",name:"DeepSeek V4.1 Flash",description:"V4.1 hybrid-attention reasoning with vision",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},KIMI_K3:{id:"moonshotai/Kimi-K3",inputModalities:["text","image"],provider:nD,spec:sD,label:"Kimi K3",name:"Kimi K3",description:"long-horizon coding & knowledge work with 1M context",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},KIMI_K2_7_CODE:{id:"moonshotai/Kimi-K2.7-Code",inputModalities:["text","image"],provider:nD,spec:sD,label:"Kimi K2.7 Code",name:"Kimi K2.7 Code",description:"improved long-horizon coding with vision",reasoning:!0,contextWindow:256e3},KIMI_K2_7_CODE_HIGHSPEED:{id:"moonshotai/Kimi-K2.7-Code-Highspeed",inputModalities:["text","image"],provider:nD,spec:sD,label:"Kimi K2.7 Code HighSpeed",name:"Kimi K2.7 Code HighSpeed",description:"high-speed long-horizon coding with vision",reasoning:!0,contextWindow:262e3},KIMI_K2_6:{id:"moonshotai/Kimi-K2.6",inputModalities:["text","image"],provider:nD,spec:sD,label:"Kimi K2.6",name:"Kimi K2.6",description:"long-horizon coding with vision",contextWindow:256e3},KIMI_K2_5:{id:"moonshotai/Kimi-K2.5",inputModalities:["text","image"],provider:nD,spec:sD,label:"Kimi K2.5",name:"Kimi K2.5",description:"multimodal frontend coding",contextWindow:256e3},GLM_5_3_FLASH:{id:"z-ai/glm-5.3-flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"GLM-5.3 Flash",name:"GLM-5.3 Flash",description:"fast, affordable GLM coding with 1M context",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1048576,maxOutputTokens:131072},GLM_5_3_FLASHX:{id:"z-ai/glm-5.3-flashx",inputModalities:["text","image"],provider:nD,spec:sD,label:"GLM-5.3 FlashX",name:"GLM-5.3 FlashX",description:"high-speed GLM-5.3 Flash with 1M context",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6,maxOutputTokens:131072},GLM_5_3:{id:"zai-org/GLM-5.3",inputModalities:["text"],provider:nD,spec:sD,label:"GLM-5.3",name:"GLM-5.3",description:"frontier coding with emergent cyber capabilities",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},GLM_5_2:{id:"zai-org/GLM-5.2",inputModalities:["text"],provider:nD,spec:sD,label:"GLM-5.2",name:"GLM-5.2",description:"powerful coding with 1M context and long-horizon tasks",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},GLM_5_2_FAST:{id:"zai-org/GLM-5.2-Fast",inputModalities:["text"],provider:nD,spec:sD,label:"GLM-5.2 Fast",name:"GLM-5.2 Fast",description:"high-throughput GLM-5.2 with 1M context",contextWindow:1e6},GLM_5_1:{id:"zai-org/GLM-5.1",inputModalities:["text"],provider:nD,spec:sD,label:"GLM-5.1",name:"GLM-5.1",description:"long-horizon autonomous coding agent"},GLM_5:{id:"zai-org/GLM-5",inputModalities:["text"],provider:nD,spec:sD,label:"GLM-5",name:"GLM-5",description:"multi-mode thinking & long-range planning",contextWindow:2e5},MINIMAX_M3:{id:"MiniMaxAI/MiniMax-M3",inputModalities:["text","image"],provider:nD,spec:sD,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},MINIMAX_M2_7:{id:"MiniMaxAI/MiniMax-M2.7",inputModalities:["text"],provider:nD,spec:sD,label:"MiniMax M2.7",name:"MiniMax M2.7",description:"end-to-end software engineering agent"},MINIMAX_M3_FREE:{id:"minimax/minimax-m3-free",inputModalities:["text","image"],provider:nD,spec:sD,label:"MiniMax M3",name:"MiniMax M3 (Free)",description:"frontier coding, agents & native multimodality",badge:"free",hidden:!0,reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},MINIMAX_M2_7_FREE:{id:"minimax/minimax-m2.7-free",inputModalities:["text"],provider:nD,spec:sD,label:"MiniMax M2.7",name:"MiniMax M2.7 (Free)",description:"end-to-end software engineering agent",badge:"free",hidden:!0,contextWindow:197e3},MINIMAX_M2_5:{id:"MiniMaxAI/MiniMax-M2.5",inputModalities:["text"],provider:nD,spec:sD,label:"MiniMax M2.5",name:"MiniMax M2.5",description:"cross-platform full-stack agentic dev",contextWindow:2e5},XIAOMI_MIMO_V2_6_PRO:{id:"xiaomi/mimo-v2.6-pro",inputModalities:["text","image"],provider:nD,spec:sD,label:"MiMo V2.6 Pro",name:"MiMo V2.6 Pro",description:"flagship multimodal agentic coding with 1M context",contextWindow:1048576},XIAOMI_MIMO_V2_6_PRO_ULTRASPEED:{id:"xiaomi/mimo-v2.6-pro-ultraspeed",inputModalities:["text","image"],provider:nD,spec:sD,label:"MiMo V2.6 Pro UltraSpeed",name:"MiMo V2.6 Pro UltraSpeed",description:"low-latency serving tier of MiMo V2.6 Pro",contextWindow:1048576},XIAOMI_MIMO_V2_6_FLASH:{id:"xiaomi/mimo-v2.6-flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"MiMo V2.6 Flash",name:"MiMo V2.6 Flash",description:"efficient multimodal agentic coding with 1M context",contextWindow:1048576},XIAOMI_MIMO_V2_5_PRO:{id:"xiaomi/mimo-v2.5-pro",inputModalities:["text"],provider:nD,spec:sD,label:"MiMo V2.5 Pro",name:"MiMo V2.5 Pro",description:"high-capability long-context agentic coding",contextWindow:1e6},XIAOMI_MIMO_V2_5:{id:"xiaomi/mimo-v2.5",inputModalities:["text","image"],provider:nD,spec:sD,label:"MiMo V2.5",name:"MiMo V2.5",description:"efficient long-context agentic coding",contextWindow:1e6},QWEN_3_8_OMNI_FLASH:{id:"Qwen/Qwen3.8-Omni-Flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.8 Omni Flash",name:"Qwen 3.8 Omni Flash",description:"omni-modal understanding & multimedia agentic work",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6,maxOutputTokens:131072},QWEN_3_8_MAX_0902:{id:"Qwen/Qwen3.8-Max-0902",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.8 Max 0902",name:"Qwen 3.8 Max 0902",description:"upgraded Qwen 3.8 Max: stronger coding & agentic tool use",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6},QWEN_3_8_MAX:{id:"Qwen/Qwen3.8-Max",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.8 Max",name:"Qwen 3.8 Max",description:"autonomous long-horizon coding & professional work",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6},QWEN_3_8_27B:{id:"Qwen/Qwen3.8-27B",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.8 27B",name:"Qwen 3.8 27B",description:"compact vision-language coding & agentic work",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:262144,maxOutputTokens:32768},QWEN_3_8_FLASH:{id:"Qwen/Qwen3.8-Flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.8 Flash",name:"Qwen 3.8 Flash",description:"fast low-cost agentic coding & reasoning",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6},QWEN_3_7_MAX:{id:"Qwen/Qwen3.7-Max",inputModalities:["text"],provider:nD,spec:sD,label:"Qwen 3.7 Max",name:"Qwen 3.7 Max",description:"frontier coding & long-horizon agent execution",reasoning:!0,contextWindow:1e6},QWEN_3_7_PLUS:{id:"Qwen/Qwen3.7-Plus",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.7 Plus",name:"Qwen 3.7 Plus",description:"agentic coding & reasoning at lower cost",reasoning:!0,contextWindow:1e6},QWEN_3_7_FLASH:{id:"Qwen/Qwen3.7-Flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.7 Flash",name:"Qwen 3.7 Flash",description:"fast low-cost agentic coding & reasoning",reasoning:!0,contextWindow:1e6},QWEN_3_6_MAX_PREVIEW:{id:"Qwen/Qwen3.6-Max-Preview",inputModalities:["text"],provider:nD,spec:sD,label:"Qwen 3.6 Max Preview",name:"Qwen 3.6 Max Preview",description:"vibe coding & efficient agent execution",reasoning:!0},QWEN_3_6_PLUS:{id:"Qwen/Qwen3.6-Plus",inputModalities:["text","image"],provider:nD,spec:sD,label:"Qwen 3.6 Plus",name:"Qwen 3.6 Plus",description:"agentic coding & reasoning",reasoning:!0},LONGCAT_2:{id:"meituan/LongCat-2.0",inputModalities:["text"],provider:nD,spec:sD,label:"LongCat 2.0",name:"LongCat 2.0",description:"trillion-parameter agentic coding with 1M context",reasoning:!0,contextWindow:1048576},LONGCAT_2_FREE:{id:"meituan/LongCat-2.0:free",inputModalities:["text"],provider:nD,spec:sD,label:"LongCat 2.0",name:"LongCat 2.0 (Free)",description:"trillion-parameter agentic coding with 1M context",badge:"free",hidden:!0,reasoning:!0,contextWindow:1048576},STEP_5_PREVIEW:{id:"stepfun/Step-5-Preview",inputModalities:["text","image"],provider:nD,spec:sD,label:"Step 5 Preview",name:"Step 5 Preview",description:"600B sparse-MoE agentic coding with 1M context",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},STEP_3_7_FLASH:{id:"stepfun/Step-3.7-Flash",inputModalities:["text","image"],provider:nD,spec:sD,label:"Step 3.7 Flash",name:"Step 3.7 Flash",description:"multimodal sparse-MoE reasoning",reasoning:!0,contextWindow:256e3},STEP_3_5_FLASH:{id:"stepfun/Step-3.5-Flash",inputModalities:["text"],provider:nD,spec:sD,label:"Step 3.5 Flash",name:"Step 3.5 Flash",description:"fast sparse-MoE agentic reasoning",reasoning:!0,contextWindow:262144},TENCENT_HY3:{id:"tencent/Hy3",inputModalities:["text"],provider:nD,spec:sD,label:"Tencent Hy3 (Free)",name:"Tencent Hy3 (Free)",description:"sparse-MoE reasoning & agentic tool use",badge:"free",hidden:!0,reasoning:!0,contextWindow:262144},TENCENT_HY3_PAID:{id:"tencent/hy3-paid",inputModalities:["text"],provider:nD,spec:sD,label:"Tencent Hy3",name:"Tencent Hy3",description:"sparse-MoE reasoning & agentic tool use",reasoning:!0,contextWindow:262144},TENCENT_HY4_PREVIEW:{id:"tencent/hy4-preview",inputModalities:["text"],provider:nD,spec:sD,label:"Tencent Hy4 Preview",name:"Tencent Hy4 Preview",description:"agentic coding & sustained multi-step tool use",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1048576},GEMINI_3_8_FLASH:{id:"google/gemini-3.8-flash",inputModalities:["text","image"],provider:GO,spec:sD,label:"Gemini 3.8 Flash",name:"Gemini 3.8 Flash",description:"newest Gemini Flash, improved core reasoning",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},GEMINI_3_7_FLASH:{id:"google/gemini-3.7-flash",inputModalities:["text","image"],provider:KO,spec:sD,label:"Gemini 3.7 Flash",name:"Gemini 3.7 Flash",description:"higher-quality coding & agentic workflows, fewer tokens",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1048576},GEMINI_3_6_FLASH:{id:"google/gemini-3.6-flash",inputModalities:["text","image"],provider:GO,spec:sD,label:"Gemini 3.6 Flash",name:"Gemini 3.6 Flash",description:"previous Gemini Flash, still fast & capable",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},GEMINI_3_5_FLASH:{id:"google/gemini-3.5-flash",inputModalities:["text","image"],provider:GO,spec:sD,label:"Gemini 3.5 Flash",name:"Gemini 3.5 Flash",description:"Pro-level coding proficiency, parallel agentic execution",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},GEMINI_3_5_FLASH_LITE:{id:"google/gemini-3.5-flash-lite",inputModalities:["text","image"],provider:GO,spec:sD,label:"Gemini 3.5 Flash Lite",name:"Gemini 3.5 Flash Lite",description:"upgraded agentic capabilities, ideal for subagents",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},GEMINI_3_1_FLASH_LITE:{id:"google/gemini-3.1-flash-lite",inputModalities:["text","image"],provider:GO,spec:sD,label:"Gemini 3.1 Flash Lite",name:"Gemini 3.1 Flash Lite",description:"high-volume workhorse model with implicit caching",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},FUGU_ULTRA:{id:"sakana/fugu-ultra",inputModalities:["text","image"],provider:GO,spec:sD,label:"Fugu Ultra",name:"Fugu Ultra",description:"multi-agent orchestration across frontier models",vendorLabel:"Sakana",reasoning:!0,reasoningEfforts:["high","xhigh"],contextWindow:1e6},NEMOTRON_3_ULTRA:{id:"nvidia/nemotron-3-ultra-550b-a55b",inputModalities:["text"],provider:nD,spec:sD,label:"Nemotron 3 Ultra",name:"Nemotron 3 Ultra",description:"open reasoning model for long-horizon autonomous agents",reasoning:!0,contextWindow:1e6},INKLING:{id:"thinkingmachines/inkling",inputModalities:["text","image"],provider:nD,spec:sD,label:"Inkling",name:"Inkling",description:"multimodal MoE reasoning",reasoning:!0,contextWindow:256e3},INKLING_SMALL:{id:"thinkingmachines/inkling-small",inputModalities:["text","image"],provider:nD,spec:sD,label:"Inkling Small",name:"Inkling Small",description:"lightweight MoE reasoning at lower cost and latency",reasoning:!0,contextWindow:1e6},SPACE_BUNNY_ALPHA:{id:"stealth/space-bunny-alpha",inputModalities:["text","image"],provider:KO,spec:sD,label:"Space Bunny Alpha",name:"Space Bunny Alpha",description:"stealth model with 1M context",vendorLabel:"Stealth",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6,maxOutputTokens:524288},LAGUNA_S_2_1_FREE:{id:"poolside/laguna-s-2.1-free",inputModalities:["text"],provider:nD,spec:sD,label:"Laguna S 2.1",name:"Laguna S 2.1",description:"open-weight agentic coding and long-horizon work",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods",reasoning:!0,contextWindow:256e3,maxOutputTokens:32768},LING_3_0_FLASH_FREE:{id:"inclusionai/ling-3.0-flash-free",inputModalities:["text"],provider:nD,spec:sD,label:"Ling 3.0 Flash",name:"Ling 3.0 Flash",description:"fast lightweight-MoE coding & agentic work",badge:"free",reasoning:!0,get hidden(){return isLingFlashFreeEnded()},contextWindow:256e3,maxOutputTokens:32768},LING_3_0_FLASH_SANTE_FREE:{id:"inclusionai/ling-3.0-flash-sante:free",inputModalities:["text"],provider:nD,spec:sD,label:"Ling 3.0 Flash Sante",name:"Ling 3.0 Flash Sante",description:"health & medicine tuned lightweight-MoE, still strong on code",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods. 100 requests a day per account",reasoning:!0,contextWindow:262144,maxOutputTokens:32768},MUSE_SPARK_1_1:{id:"meta/muse-spark-1.1",inputModalities:["text","image"],provider:GO,spec:sD,label:"Muse Spark 1.1",name:"Muse Spark 1.1",description:"agentic performance, tool use, and computer use",vendorLabel:"Meta",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},MUSE_SPARK_1_2:{id:"meta/muse-spark-1.2",inputModalities:["text","image"],provider:GO,spec:sD,label:"Muse Spark 1.2",name:"Muse Spark 1.2",description:"coding-optimized for agentic workflows and large codebases",vendorLabel:"Meta",notice:"{name} is going through upstream inference issues at {vendor}, not Command Code. Expect slower responses and occasional rate limits.",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},MUSE_SPARK_1_2_CONTRIBUTOR:{id:"meta/muse-spark-1.2-contributor",inputModalities:["text","image"],provider:GO,spec:sD,label:"Muse Spark 1.2 Contributor",name:"Muse Spark 1.2 Contributor",description:"Muse Spark 1.2 at ~95% off",vendorLabel:"Meta",notice:"{name} is going through upstream inference issues at {vendor}, not Command Code. Expect slower responses and occasional rate limits.",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},MUSE_SPARK_1_3:{id:"meta/muse-spark-1.3",inputModalities:["text","image"],provider:GO,spec:sD,label:"Muse Spark 1.3",name:"Muse Spark 1.3",description:"multimodal reasoning for long-horizon agentic and coding workflows",vendorLabel:"Meta",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1048576},MUSE_SPARK_1_3_CONTRIBUTOR:{id:"meta/muse-spark-1.3-contributor",inputModalities:["text","image"],provider:GO,spec:sD,label:"Muse Spark 1.3 Contributor",name:"Muse Spark 1.3 Contributor",description:"Muse Spark 1.3 at up to 95% off",vendorLabel:"Meta",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},GROK_4_5:{id:"xai/grok-4.5",inputModalities:["text","image"],provider:GO,spec:sD,label:"Grok 4.5",name:"Grok 4.5",description:"smartest model for coding, agentic tasks, knowledge work",vendorLabel:"xAI",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:5e5},GROK_4_6:{id:"xai/grok-4.6",inputModalities:["text","image"],provider:GO,spec:sD,label:"Grok 4.6",name:"Grok 4.6",description:"frontier performance on coding, knowledge work, and STEM",vendorLabel:"xAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:5e5},GROK_4_7:{id:"xai/grok-4.7",inputModalities:["text","image"],provider:GO,spec:sD,label:"Grok 4.7",name:"Grok 4.7",description:"coding and knowledge work, built for multi-hour tasks",vendorLabel:"xAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:5e5}},cD=[{canonicalId:"zai-org/GLM-5",providers:{[GO]:"zai/glm-5",[HO]:"zai-org/GLM-5"}},{canonicalId:"zai-org/GLM-5.3",providers:{[JO]:"zai-org/glm-5.3",[GO]:"zai/glm-5.3"}},{canonicalId:"zai-org/GLM-5.2",providers:{[qO]:"glm-5.2",[GO]:"zai/glm-5.2"}},{canonicalId:"poolside/laguna-s-2.1-free",providers:{[GO]:"poolside/laguna-s-2.1-free"}},{canonicalId:"inclusionai/ling-3.0-flash-free",providers:{[GO]:"inclusionai/ling-3.0-flash-free"}},{canonicalId:"inclusionai/ling-3.0-flash-sante:free",providers:{[KO]:"inclusionai/ling-3.0-flash-sante:free"}},{canonicalId:"zai-org/GLM-5.2-Fast",providers:{[GO]:"zai/glm-5.2-fast"}},{canonicalId:"zai-org/GLM-5.1",providers:{[GO]:"zai/glm-5.1"}},{canonicalId:"moonshotai/Kimi-K3",providers:{[JO]:"moonshotai/kimi-k3",[GO]:"moonshotai/kimi-k3"}},{canonicalId:"moonshotai/Kimi-K2.5",providers:{[GO]:"moonshotai/kimi-k2.5",[HO]:"moonshotai/Kimi-K2.5",[VO]:"workers-ai/@cf/moonshotai/kimi-k2.5"}},{canonicalId:"moonshotai/Kimi-K2.6",providers:{[GO]:"moonshotai/kimi-k2.6",[HO]:"moonshotai/Kimi-K2.6",[VO]:"workers-ai/@cf/moonshotai/kimi-k2.6"}},{canonicalId:"moonshotai/Kimi-K2.7-Code",providers:{[qO]:"kimi-k2.7-code",[GO]:"moonshotai/kimi-k2.7-code"}},{canonicalId:"moonshotai/Kimi-K2.7-Code-Highspeed",providers:{[GO]:"moonshotai/kimi-k2.7-code-highspeed"}},{canonicalId:"MiniMaxAI/MiniMax-M2.5",providers:{[GO]:"minimax/minimax-m2.5",[HO]:"MiniMaxAI/MiniMax-M2.5"}},{canonicalId:"deepseek/deepseek-v4-pro",providers:{[GO]:"deepseek/deepseek-v4-pro"}},{canonicalId:"deepseek/deepseek-v4-flash",providers:{[GO]:"deepseek/deepseek-v4.1-flash",[QO]:"morph-dsv4flash",[tD]:"deepseek-v4-flash-0731"}},{canonicalId:"deepseek/deepseek-v4-flash-vision-exp",providers:{[GO]:"deepseek/deepseek-v4.1-flash"}},{canonicalId:"deepseek/deepseek-v4.1-flash",providers:{[JO]:"deepseek/deepseek-v4.1-flash",[GO]:"deepseek/deepseek-v4.1-flash"}},{canonicalId:"deepseek/deepseek-v4-flash-fast",providers:{[XO]:"DeepSeek-V4-Flash-0731-Fast"}},{canonicalId:"Qwen/Qwen3.6-Max-Preview",providers:{[GO]:"alibaba/qwen-3.6-max-preview"}},{canonicalId:"Qwen/Qwen3.6-Plus",providers:{[qO]:"qwen3.6-plus",[GO]:"alibaba/qwen3.6-plus"}},{canonicalId:"Qwen/Qwen3.7-Max",providers:{[qO]:"qwen3.7-max",[GO]:"alibaba/qwen3.7-max"}},{canonicalId:"Qwen/Qwen3.7-Plus",providers:{[qO]:"qwen3.7-plus",[GO]:"alibaba/qwen3.7-plus"}},{canonicalId:"Qwen/Qwen3.8-Max-0902",providers:{[qO]:"qwen3.8-max-0902"}},{canonicalId:"Qwen/Qwen3.8-Omni-Flash",providers:{[GO]:"alibaba/qwen3.8-omni-flash"}},{canonicalId:"Qwen/Qwen3.8-Max",providers:{[qO]:"qwen3.8-max",[GO]:"alibaba/qwen3.8-max"}},{canonicalId:"Qwen/Qwen3.8-27B",providers:{[GO]:"alibaba/qwen3.8-27b"}},{canonicalId:"Qwen/Qwen3.8-Flash",providers:{[YO]:"qwen3.8-flash"}},{canonicalId:"Qwen/Qwen3.7-Flash",providers:{[GO]:"alibaba/qwen3.7-flash"}},{canonicalId:"MiniMaxAI/MiniMax-M3",providers:{[GO]:"minimax/minimax-m3"}},{canonicalId:aD,providers:{[GO]:"minimax/minimax-m3"}},{canonicalId:"MiniMaxAI/MiniMax-M2.7",providers:{[GO]:"minimax/minimax-m2.7"}},{canonicalId:"meituan/LongCat-2.0",providers:{[ZO]:"LongCat-2.0"}},{canonicalId:"stepfun/Step-5-Preview",providers:{[GO]:"stepfun/step-5-preview"}},{canonicalId:"stepfun/Step-3.7-Flash",providers:{[GO]:"stepfun/step-3.7-flash"}},{canonicalId:"stepfun/Step-3.5-Flash",providers:{[GO]:"stepfun/step-3.5-flash",[KO]:"stepfun/step-3.5-flash"}},{canonicalId:"z-ai/glm-5.3-flash",providers:{[JO]:"zai-org/glm-5.3-flash",[GO]:"zai/glm-5.3-flash"}},{canonicalId:"z-ai/glm-5.3-flashx",providers:{[GO]:"zai/glm-5.3-flashx"}},{canonicalId:"gpt-5.6-sol",providers:{[GO]:"openai/gpt-5.6-sol"}},{canonicalId:"gpt-5.6-terra",providers:{[GO]:"openai/gpt-5.6-terra"}},{canonicalId:"gpt-5.6-luna",providers:{[GO]:"openai/gpt-5.6-luna"}},{canonicalId:"stealth/space-bunny-alpha",providers:{[KO]:"stealth/space-bunny-alpha"}},{canonicalId:"tencent/Hy3",providers:{[KO]:"tencent/hy3:free"}},{canonicalId:"tencent/hy3-paid",providers:{[GO]:"tencent/hy3"}},{canonicalId:"tencent/hy4-preview",providers:{[eD]:"hy4-preview"}},{canonicalId:"xiaomi/mimo-v2.6-pro",providers:{[GO]:"xiaomi/mimo-v2.6-pro"}},{canonicalId:"xiaomi/mimo-v2.6-pro-ultraspeed",providers:{[GO]:"xiaomi/mimo-v2.6-pro-ultraspeed"}},{canonicalId:"xiaomi/mimo-v2.6-flash",providers:{[GO]:"xiaomi/mimo-v2.6-flash"}},{canonicalId:"xiaomi/mimo-v2.5-pro",providers:{[GO]:"xiaomi/mimo-v2.5-pro"}},{canonicalId:"xiaomi/mimo-v2.5",providers:{[GO]:"xiaomi/mimo-v2.5"}},{canonicalId:"google/gemini-3.8-flash",providers:{[GO]:"google/gemini-3.8-flash"}},{canonicalId:"google/gemini-3.7-flash",providers:{[KO]:"google/gemini-3.7-flash"}},{canonicalId:"google/gemini-3.6-flash",providers:{[GO]:"google/gemini-3.6-flash"}},{canonicalId:"google/gemini-3.5-flash",providers:{[GO]:"google/gemini-3.5-flash"}},{canonicalId:"google/gemini-3.5-flash-lite",providers:{[GO]:"google/gemini-3.5-flash-lite"}},{canonicalId:"google/gemini-3.1-flash-lite",providers:{[GO]:"google/gemini-3.1-flash-lite"}},{canonicalId:"nvidia/nemotron-3-ultra-550b-a55b",providers:{[GO]:"nvidia/nemotron-3-ultra-550b-a55b"}},{canonicalId:"thinkingmachines/inkling",providers:{[GO]:"thinkingmachines/inkling"}},{canonicalId:"thinkingmachines/inkling-small",providers:{[GO]:"thinkingmachines/inkling-small"}},{canonicalId:"sakana/fugu-ultra",providers:{[GO]:"sakana/fugu-ultra"}},{canonicalId:"xai/grok-4.5",providers:{[GO]:"xai/grok-4.5"}},{canonicalId:"xai/grok-4.6",providers:{[GO]:"xai/grok-4.6"}},{canonicalId:"xai/grok-4.7",providers:{[GO]:"xai/grok-4.7"}},{canonicalId:"meta/muse-spark-1.1",providers:{[GO]:"meta/muse-spark-1.1"}},{canonicalId:"meta/muse-spark-1.2",providers:{[GO]:"meta/muse-spark-1.2"}},{canonicalId:"meta/muse-spark-1.2-contributor",providers:{[GO]:"meta/muse-spark-1.2-contributor"}},{canonicalId:"meta/muse-spark-1.3",providers:{[GO]:"meta/muse-spark-1.3"}},{canonicalId:"meta/muse-spark-1.3-contributor",providers:{[GO]:"meta/muse-spark-1.3-contributor"}}],dD="2026-08-16T16:00:00Z",uD=[{startHourUtc:1,endHourUtc:4},{startHourUtc:6,endHourUtc:10}],mD=[1,2,3,4,5],pD=["2026-09-25","2026-09-26","2026-09-27","2026-10-01","2026-10-02","2026-10-03","2026-10-04","2026-10-05","2026-10-06","2026-10-07"],gD={effectiveFrom:dD,peakWindowsUtc:uD,peakDaysUtc:mD,offPeakDatesUtc:pD,peak:{promptCost:.44,completionCost:1.32,cacheReadCost:.014},offPeak:{promptCost:.22,completionCost:.66,cacheReadCost:.007}},hD=new Set([lD.GLM_5_2_FAST.id,lD.MINIMAX_M3.id,lD.MINIMAX_M3_FREE.id,lD.STEP_3_7_FLASH.id,lD.STEP_5_PREVIEW.id,lD.XIAOMI_MIMO_V2_6_PRO.id,lD.XIAOMI_MIMO_V2_6_PRO_ULTRASPEED.id,lD.XIAOMI_MIMO_V2_6_FLASH.id,lD.FUGU_ULTRA.id,lD.GROK_4_5.id,lD.GROK_4_6.id,lD.MUSE_SPARK_1_1.id,lD.MUSE_SPARK_1_2.id,lD.MUSE_SPARK_1_2_CONTRIBUTOR.id,lD.MUSE_SPARK_1_3.id,lD.MUSE_SPARK_1_3_CONTRIBUTOR.id,lD.LAGUNA_S_2_1_FREE.id,lD.QWEN_3_8_MAX_0902.id,lD.LONGCAT_2.id,lD.GLM_5_3_FLASHX.id,lD.SPACE_BUNNY_ALPHA.id]),fD=[{canonicalId:"zai-org/GLM-5",gatewaySlug:"zai/glm-5",order:["deepinfra","fireworks","togetherai","parasail","bedrock"],providers:{deepinfra:{slug:"deepinfra",promptCost:.8,completionCost:2.56,cacheReadCost:.16},fireworks:{slug:"fireworks",promptCost:1,completionCost:3.2,cacheReadCost:.2},togetherai:{slug:"togetherai",promptCost:1,completionCost:3.2,cacheReadCost:0},parasail:{slug:"parasail",promptCost:1,completionCost:3.2,cacheReadCost:0},bedrock:{slug:"bedrock",promptCost:1,completionCost:3.2,cacheReadCost:0}}},{canonicalId:"zai-org/GLM-5.2",gatewaySlug:"zai/glm-5.2",order:["novita","deepinfra"],providers:{novita:{slug:"novita",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},deepinfra:{slug:"deepinfra",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},zai:{slug:"zai",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},fireworks:{slug:"fireworks",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{canonicalId:"zai-org/GLM-5.3",gatewaySlug:"zai/glm-5.3",order:["digitalocean"],providers:{digitalocean:{slug:"digitalocean",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{canonicalId:"z-ai/glm-5.3-flash",gatewaySlug:"zai/glm-5.3-flash",order:["zai"],providers:{zai:{slug:"zai",promptCost:.15,completionCost:.5,cacheReadCost:.03}}},{canonicalId:"z-ai/glm-5.3-flashx",gatewaySlug:"zai/glm-5.3-flashx",order:["zai"],providers:{zai:{slug:"zai",promptCost:.37,completionCost:1.25,cacheReadCost:.075}}},{canonicalId:"zai-org/GLM-5.2-Fast",gatewaySlug:"zai/glm-5.2-fast",order:["wafer"],providers:{wafer:{slug:"wafer",promptCost:3,completionCost:10.25,cacheReadCost:.5}}},{canonicalId:"zai-org/GLM-5.1",gatewaySlug:"zai/glm-5.1",order:["deepinfra","fireworks"],providers:{deepinfra:{slug:"deepinfra",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},fireworks:{slug:"fireworks",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{canonicalId:"moonshotai/Kimi-K3",gatewaySlug:"moonshotai/kimi-k3",order:["moonshotai"],providers:{moonshotai:{slug:"moonshotai",promptCost:3,completionCost:15,cacheReadCost:.3}}},{canonicalId:"moonshotai/Kimi-K2.5",gatewaySlug:"moonshotai/kimi-k2.5",order:["moonshotai","fireworks","bedrock","togetherai"],providers:{fireworks:{slug:"fireworks",promptCost:.6,completionCost:3,cacheReadCost:.1},bedrock:{slug:"bedrock",promptCost:.6,completionCost:3,cacheReadCost:.1},togetherai:{slug:"togetherai",promptCost:.5,completionCost:2.8,cacheReadCost:0},moonshotai:{slug:"moonshotai",promptCost:.6,completionCost:3,cacheReadCost:.1}}},{canonicalId:"moonshotai/Kimi-K2.6",gatewaySlug:"moonshotai/kimi-k2.6",order:["moonshotai","fireworks"],providers:{moonshotai:{slug:"moonshotai",promptCost:.95,completionCost:4,cacheReadCost:.16},fireworks:{slug:"fireworks",promptCost:.95,completionCost:4,cacheReadCost:.16}}},{canonicalId:"moonshotai/Kimi-K2.7-Code",gatewaySlug:"moonshotai/kimi-k2.7-code",order:["moonshotai"],providers:{moonshotai:{slug:"moonshotai",promptCost:.95,completionCost:4,cacheReadCost:.19}}},{canonicalId:"moonshotai/Kimi-K2.7-Code-Highspeed",gatewaySlug:"moonshotai/kimi-k2.7-code-highspeed",order:["moonshotai"],providers:{moonshotai:{slug:"moonshotai",promptCost:1.9,completionCost:8,cacheReadCost:.38}}},{canonicalId:"MiniMaxAI/MiniMax-M2.5",gatewaySlug:"minimax/minimax-m2.5",order:["deepinfra","parasail","nebius","bedrock"],providers:{deepinfra:{slug:"deepinfra",promptCost:.3,completionCost:1.2,cacheReadCost:.03},parasail:{slug:"parasail",promptCost:.3,completionCost:1.2,cacheReadCost:0},nebius:{slug:"nebius",promptCost:.3,completionCost:1.2,cacheReadCost:0},bedrock:{slug:"bedrock",promptCost:.3,completionCost:1.2,cacheReadCost:0}}},{canonicalId:"deepseek/deepseek-v4-pro",gatewaySlug:"deepseek/deepseek-v4-pro",order:["deepseek"],providers:{deepseek:{slug:"deepseek",promptCost:.435,completionCost:.87,cacheReadCost:.003625,timeOfDay:{effectiveFrom:dD,peakWindowsUtc:uD,peakDaysUtc:mD,offPeakDatesUtc:pD,peak:{promptCost:1.32,completionCost:3.96,cacheReadCost:.044},offPeak:{promptCost:.66,completionCost:1.98,cacheReadCost:.022}}},fireworks:{slug:"fireworks",promptCost:1.74,completionCost:3.48,cacheReadCost:.0145}}},{canonicalId:"deepseek/deepseek-v4-flash",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],zdr:{gatewaySlug:"deepseek/deepseek-v4-flash",only:["baseten","fireworks","deepinfra"]},providers:{deepseek:{slug:"deepseek",promptCost:.14,completionCost:.28,cacheReadCost:.0028,timeOfDay:{effectiveFrom:dD,peakWindowsUtc:uD,peakDaysUtc:mD,offPeakDatesUtc:pD,peak:{promptCost:.3,completionCost:1.2,cacheReadCost:.006},offPeak:{promptCost:.15,completionCost:.6,cacheReadCost:.003}}},baseten:{slug:"baseten",promptCost:.13,completionCost:.26,cacheReadCost:.028},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007},deepinfra:{slug:"deepinfra",promptCost:.08,completionCost:.18,cacheReadCost:.016}}},{canonicalId:"deepseek/deepseek-v4-flash-vision-exp",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],zdr:{gatewaySlug:"deepseek/deepseek-v4.1-flash",only:["fireworks","deepinfra"]},providers:{deepseek:{slug:"deepseek",promptCost:.15,completionCost:.6,cacheReadCost:.003,timeOfDay:{effectiveFrom:dD,peakWindowsUtc:uD,peakDaysUtc:mD,offPeakDatesUtc:pD,peak:{promptCost:.3,completionCost:1.2,cacheReadCost:.006},offPeak:{promptCost:.15,completionCost:.6,cacheReadCost:.003}}},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007},deepinfra:{slug:"deepinfra",promptCost:.2,completionCost:.6,cacheReadCost:.006}}},{canonicalId:"deepseek/deepseek-v4.1-flash",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],providers:{deepseek:{slug:"deepseek",promptCost:.15,completionCost:.6,cacheReadCost:.003,timeOfDay:{effectiveFrom:dD,peakWindowsUtc:uD,peakDaysUtc:mD,offPeakDatesUtc:pD,peak:{promptCost:.3,completionCost:1.2,cacheReadCost:.006},offPeak:{promptCost:.15,completionCost:.6,cacheReadCost:.003}}},novita:{slug:"novita",promptCost:.3,completionCost:1.2,cacheReadCost:.006},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007},deepinfra:{slug:"deepinfra",promptCost:.2,completionCost:.6,cacheReadCost:.006},morph:{slug:"morph",promptCost:.3,completionCost:1.2,cacheReadCost:.03},baseten:{slug:"baseten",promptCost:.3,completionCost:1.2,cacheReadCost:.03},wafer:{slug:"wafer",promptCost:.3,completionCost:1.2,cacheReadCost:.01},modal:{slug:"modal",promptCost:.3,completionCost:1.2,cacheReadCost:.03}}},{canonicalId:"Qwen/Qwen3.6-Max-Preview",gatewaySlug:"alibaba/qwen-3.6-max-preview",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:1.3,completionCost:7.8,cacheReadCost:.26,cacheWriteCost:1.63}}},{canonicalId:"Qwen/Qwen3.6-Plus",gatewaySlug:"alibaba/qwen3.6-plus",order:["fireworks"],providers:{fireworks:{slug:"fireworks",promptCost:.5,completionCost:3,cacheReadCost:.1}}},{canonicalId:"Qwen/Qwen3.7-Max",gatewaySlug:"alibaba/qwen3.7-max",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:2.5,completionCost:7.5,cacheReadCost:.5,cacheWriteCost:3.13}}},{canonicalId:"Qwen/Qwen3.7-Plus",gatewaySlug:"alibaba/qwen3.7-plus",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:.4,completionCost:1.6,cacheReadCost:.08,cacheWriteCost:.5}}},{canonicalId:"Qwen/Qwen3.8-Omni-Flash",gatewaySlug:"alibaba/qwen3.8-omni-flash",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:.15,completionCost:.47,cacheReadCost:.016}}},{canonicalId:"Qwen/Qwen3.8-Max",gatewaySlug:"alibaba/qwen3.8-max",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:2,completionCost:6,cacheReadCost:.25,cacheWriteCost:2.5}}},{canonicalId:"Qwen/Qwen3.8-27B",gatewaySlug:"alibaba/qwen3.8-27b",order:["runinfra"],providers:{runinfra:{slug:"runinfra",promptCost:.4,completionCost:3,cacheReadCost:.04},deepinfra:{slug:"deepinfra",promptCost:.4,completionCost:3,cacheReadCost:.04}}},{canonicalId:"Qwen/Qwen3.7-Flash",gatewaySlug:"alibaba/qwen3.7-flash",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:.03,completionCost:.13,cacheReadCost:.006,cacheWriteCost:.038}}},{canonicalId:"MiniMaxAI/MiniMax-M3",gatewaySlug:"minimax/minimax-m3",order:["minimax"],providers:{minimax:{slug:"minimax",promptCost:.3,completionCost:1.2,cacheReadCost:.06}}},{canonicalId:aD,gatewaySlug:"minimax/minimax-m3",order:["minimax"],providers:{minimax:{slug:"minimax",promptCost:.3,completionCost:1.2,cacheReadCost:.06}}},{canonicalId:"MiniMaxAI/MiniMax-M2.7",gatewaySlug:"minimax/minimax-m2.7",order:["fireworks","togetherai"],providers:{fireworks:{slug:"fireworks",promptCost:.3,completionCost:1.2,cacheReadCost:.06},togetherai:{slug:"togetherai",promptCost:.3,completionCost:1.2,cacheReadCost:0}}},{canonicalId:"xiaomi/mimo-v2.6-pro",gatewaySlug:"xiaomi/mimo-v2.6-pro",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.435,completionCost:.87,cacheReadCost:.0036}}},{canonicalId:"xiaomi/mimo-v2.6-pro-ultraspeed",gatewaySlug:"xiaomi/mimo-v2.6-pro-ultraspeed",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:4.35,completionCost:8.7,cacheReadCost:.036}}},{canonicalId:"xiaomi/mimo-v2.6-flash",gatewaySlug:"xiaomi/mimo-v2.6-flash",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.14,completionCost:.28,cacheReadCost:.0028}}},{canonicalId:"xiaomi/mimo-v2.5-pro",gatewaySlug:"xiaomi/mimo-v2.5-pro",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.435,completionCost:.87,cacheReadCost:.0036}}},{canonicalId:"xiaomi/mimo-v2.5",gatewaySlug:"xiaomi/mimo-v2.5",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.14,completionCost:.28,cacheReadCost:.0028}}},{canonicalId:"stepfun/Step-5-Preview",gatewaySlug:"stepfun/step-5-preview",order:["stepfun"],providers:{stepfun:{slug:"stepfun",promptCost:1,completionCost:2.7,cacheReadCost:.05}}},{canonicalId:"stepfun/Step-3.5-Flash",gatewaySlug:"stepfun/step-3.5-flash",order:["deepinfra"],providers:{deepinfra:{slug:"deepinfra",promptCost:.09,completionCost:.3,cacheReadCost:.02}}},{canonicalId:"stepfun/Step-3.7-Flash",gatewaySlug:"stepfun/step-3.7-flash",order:["stepfun"],providers:{stepfun:{slug:"stepfun",promptCost:.2,completionCost:1.15,cacheReadCost:.04}}},{canonicalId:"gpt-5.6-sol",gatewaySlug:"openai/gpt-5.6-sol",order:["openai"],providers:{openai:{slug:"openai",promptCost:5,completionCost:30,cacheReadCost:.5,cacheWriteCost:6.25},azure:{slug:"azure",promptCost:5,completionCost:30,cacheReadCost:.5,cacheWriteCost:6.25},bedrock:{slug:"bedrock",promptCost:5,completionCost:30,cacheReadCost:.5,cacheWriteCost:6.25}}},{canonicalId:"gpt-5.6-terra",gatewaySlug:"openai/gpt-5.6-terra",order:["openai"],providers:{openai:{slug:"openai",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5},azure:{slug:"azure",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5},bedrock:{slug:"bedrock",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5}}},{canonicalId:"gpt-5.6-luna",gatewaySlug:"openai/gpt-5.6-luna",order:["openai"],providers:{openai:{slug:"openai",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25},azure:{slug:"azure",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25},bedrock:{slug:"bedrock",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25}}},{canonicalId:"google/gemini-3.8-flash",gatewaySlug:"google/gemini-3.8-flash",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:1.5,completionCost:7.5,cacheReadCost:.15}}},{canonicalId:"google/gemini-3.6-flash",gatewaySlug:"google/gemini-3.6-flash",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:1.5,completionCost:7.5,cacheReadCost:.15}}},{canonicalId:"google/gemini-3.5-flash",gatewaySlug:"google/gemini-3.5-flash",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:1.5,completionCost:9,cacheReadCost:.15}}},{canonicalId:"google/gemini-3.5-flash-lite",gatewaySlug:"google/gemini-3.5-flash-lite",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:.3,completionCost:2.5,cacheReadCost:.03}}},{canonicalId:"google/gemini-3.1-flash-lite",gatewaySlug:"google/gemini-3.1-flash-lite",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:.25,completionCost:1.5,cacheReadCost:.03}}},{canonicalId:"nvidia/nemotron-3-ultra-550b-a55b",gatewaySlug:"nvidia/nemotron-3-ultra-550b-a55b",order:["baseten","deepinfra"],providers:{baseten:{slug:"baseten",promptCost:.6,completionCost:2.4,cacheReadCost:.12},deepinfra:{slug:"deepinfra",promptCost:.5,completionCost:2.5,cacheReadCost:.15}}},{canonicalId:"thinkingmachines/inkling",gatewaySlug:"thinkingmachines/inkling",order:["baseten"],providers:{baseten:{slug:"baseten",promptCost:1,completionCost:4.05,cacheReadCost:.17}}},{canonicalId:"thinkingmachines/inkling-small",gatewaySlug:"thinkingmachines/inkling-small",order:["baseten"],providers:{baseten:{slug:"baseten",promptCost:.5,completionCost:1.2,cacheReadCost:.1}}},{canonicalId:"sakana/fugu-ultra",gatewaySlug:"sakana/fugu-ultra",order:["sakana"],providers:{sakana:{slug:"sakana",promptCost:5,completionCost:30,cacheReadCost:.5}}},{canonicalId:"xai/grok-4.5",gatewaySlug:"xai/grok-4.5",order:["xai"],providers:{xai:{slug:"xai",promptCost:2,completionCost:6,cacheReadCost:.5}}},{canonicalId:"xai/grok-4.6",gatewaySlug:"xai/grok-4.6",order:["xai"],providers:{xai:{slug:"xai",promptCost:2,completionCost:6,cacheReadCost:.5}}},{canonicalId:"xai/grok-4.7",gatewaySlug:"xai/grok-4.7",order:["xai"],providers:{xai:{slug:"xai",promptCost:1.2,completionCost:3.6,cacheReadCost:.3}}},{canonicalId:"meta/muse-spark-1.1",gatewaySlug:"meta/muse-spark-1.1",order:["meta"],providers:{meta:{slug:"meta",promptCost:1.25,completionCost:4.25,cacheReadCost:.15}}},{canonicalId:"meta/muse-spark-1.2",gatewaySlug:"meta/muse-spark-1.2",order:["meta"],providers:{meta:{slug:"meta",promptCost:1.25,completionCost:4.25,cacheReadCost:.15}}},{canonicalId:"meta/muse-spark-1.2-contributor",gatewaySlug:"meta/muse-spark-1.2-contributor",order:["meta"],providers:{meta:{slug:"meta",promptCost:.1,completionCost:.2,cacheReadCost:.002}}},{canonicalId:"meta/muse-spark-1.3",gatewaySlug:"meta/muse-spark-1.3",order:["meta"],providers:{meta:{slug:"meta",promptCost:1.25,completionCost:4.25,cacheReadCost:.15}}},{canonicalId:"meta/muse-spark-1.3-contributor",gatewaySlug:"meta/muse-spark-1.3-contributor",order:["meta"],providers:{meta:{slug:"meta",promptCost:.1,completionCost:.2,cacheReadCost:.002}}},{canonicalId:"tencent/hy3-paid",gatewaySlug:"tencent/hy3",order:["novita"],providers:{novita:{slug:"novita",promptCost:.14,completionCost:.58,cacheReadCost:.035},deepinfra:{slug:"deepinfra",promptCost:.14,completionCost:.58,cacheReadCost:.035}}},{canonicalId:"poolside/laguna-s-2.1-free",gatewaySlug:"poolside/laguna-s-2.1-free",order:["poolside"],providers:{poolside:{slug:"poolside",promptCost:0,completionCost:0,cacheReadCost:0}}},{canonicalId:"inclusionai/ling-3.0-flash-free",gatewaySlug:"inclusionai/ling-3.0-flash-free",order:["novita"],providers:{novita:{slug:"novita",promptCost:0,completionCost:0,cacheReadCost:0}}}],yD=[{canonicalId:"Qwen/Qwen3.8-Max-0902",slug:"qwen3.8-max-0902",promptCost:2,completionCost:6,cacheReadCost:.25},{canonicalId:"Qwen/Qwen3.8-Max",slug:"qwen3.8-max",promptCost:2,completionCost:6,cacheReadCost:.25},{canonicalId:"Qwen/Qwen3.7-Max",slug:"qwen3.7-max",promptCost:2.5,completionCost:7.5,cacheReadCost:.5},{canonicalId:"Qwen/Qwen3.7-Plus",slug:"qwen3.7-plus",promptCost:.4,completionCost:1.6,cacheReadCost:.08,contextTiers:[{maxInputTokens:256e3,promptCost:.4,completionCost:1.6,cacheReadCost:.08},{promptCost:1.2,completionCost:4.8,cacheReadCost:.24}]},{canonicalId:"Qwen/Qwen3.6-Plus",slug:"qwen3.6-plus",promptCost:.5,completionCost:3,cacheReadCost:.1,contextTiers:[{maxInputTokens:256e3,promptCost:.5,completionCost:3,cacheReadCost:.1},{promptCost:2,completionCost:6,cacheReadCost:.2}]},{canonicalId:"zai-org/GLM-5.2",slug:"glm-5.2",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},{canonicalId:"moonshotai/Kimi-K2.7-Code",slug:"kimi-k2.7-code",promptCost:.95,completionCost:4,cacheReadCost:.19},{canonicalId:"Qwen/Qwen3.8-Flash",slug:"qwen3.8-flash",promptCost:.16,completionCost:.47,cacheReadCost:.016}],SD=[{canonicalId:"deepseek/deepseek-v4-flash",slug:"morph-dsv4flash",promptCost:.14,completionCost:.28,cacheReadCost:.0028,timeOfDay:gD}],wD=[{canonicalId:"deepseek/deepseek-v4-flash-fast",slug:"DeepSeek-V4-Flash-0731-Fast",promptCost:.28,completionCost:.56,cacheReadCost:.07}],vD=[{canonicalId:"meituan/LongCat-2.0",slug:"LongCat-2.0",promptCost:.3,completionCost:1.2,cacheReadCost:.006}],kD={promptCost:.834,completionCost:2.501,cacheReadCost:.042},CD=[{canonicalId:"tencent/hy4-preview",slug:"hy4-preview",...kD}],bD=[{canonicalId:"stepfun/Step-3.5-Flash",openrouterSlug:"stepfun/step-3.5-flash",order:["siliconflow"],providers:{siliconflow:{slug:"siliconflow",promptCost:.1,completionCost:.3,zdr:!0,noTraining:!0}}},{canonicalId:"stealth/space-bunny-alpha",openrouterSlug:"stealth/space-bunny-alpha",order:["stealth"],providers:{stealth:{slug:"stealth",promptCost:0,completionCost:0,zdr:!1,noTraining:!1}}},{canonicalId:"tencent/Hy3",openrouterSlug:"tencent/hy3:free",order:["novita"],providers:{novita:{slug:"novita",promptCost:0,completionCost:0,zdr:!1,noTraining:!1}}},{canonicalId:"inclusionai/ling-3.0-flash-sante:free",openrouterSlug:"inclusionai/ling-3.0-flash-sante:free",order:["novita"],providers:{novita:{slug:"novita",promptCost:0,completionCost:0,zdr:!0,noTraining:!0}}},{canonicalId:"tencent/hy4-preview",openrouterSlug:"tencent/hy4-preview",order:["tencent"],providers:{tencent:{slug:"tencent",...kD,zdr:!0,noTraining:!0}}},{canonicalId:"gpt-5.6-terra",openrouterSlug:"openai/gpt-5.6-terra",order:["openai"],providers:{openai:{slug:"openai",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5,zdr:!1,noTraining:!0}}},{canonicalId:"gpt-5.6-luna",openrouterSlug:"openai/gpt-5.6-luna",order:["openai"],providers:{openai:{slug:"openai",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25,zdr:!1,noTraining:!0}}},{canonicalId:"google/gemini-3.7-flash",openrouterSlug:"google/gemini-3.7-flash",order:["google-vertex"],providers:{"google-vertex":{slug:"google-vertex",promptCost:1.5,completionCost:7.5,cacheReadCost:.15,cacheWriteCost:.08334,zdr:!0,noTraining:!0}}}],ED={"claude-sonnet-4-20250514":lD.SONNET_4_6.id,"claude-sonnet-4-5-20250929":lD.SONNET_4_6.id,"claude-opus-4-5-20251101":lD.OPUS_4_7.id,"claude-opus-4-6":lD.OPUS_4_7.id,"claude-haiku-4-5":lD.HAIKU_4_5.id},TD=lD.DEEPSEEK_V4_FLASH.id,PD={[BO]:"Anthropic",[WO]:"OpenAI",[HO]:"Open Source",[GO]:"Open Source",[zO]:"Open Source",[KO]:"Open Source"},MD=["Open Source","Stealth","Anthropic","OpenAI","Google"],xD={"command-code":{id:"command-code",label:"Command Code",shortLabel:"cmd",description:"recommended",supportedModelProviders:[BO,WO,zO,HO,GO,KO],requiresAuth:!1,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!0},anthropic:{id:"anthropic",label:"Anthropic",shortLabel:"anth",description:"Claude Pro/Max",supportedModelProviders:[BO],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!1},"github-copilot":{id:"github-copilot",label:"GitHub Copilot",shortLabel:"copilot",description:"Copilot subscription",supportedModelProviders:[BO,WO],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!0},codex:{id:"codex",label:"OpenAI ChatGPT/Codex",shortLabel:"openai",description:"ChatGPT Pro/Plus subscription",supportedModelProviders:[WO],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!1}};function laneSupportsModel(e,t){if(e.includes(t.provider))return!0;const n=t.vendorLabel?.toLowerCase();return null!=n&&e.includes(n)}function buildModelGroups(e){const t=Object.values(lD).filter(e=>!e.hidden),n=[];for(const r of Object.values(xD)){if(!("co"===e?r.visibleInCoMode:"command-code"===r.id))continue;const o=t.filter(e=>laneSupportsModel(r.supportedModelProviders,e));o.length>0&&n.push({providerId:r.id,label:r.label,models:o})}return n}__name(laneSupportsModel,"laneSupportsModel"),__name(buildModelGroups,"buildModelGroups");var ID=buildModelGroups("co"),AD=buildModelGroups("normal");function formatColoredUserSuffix(e){return isGenericUserName(e)?"":formatUserSuffix(e).replace(e,Et.cyan(e))}function getStartedLine(){return`${Et.dim("Run")} ${Et.cyan(getBinaryCommand())} ${Et.dim("to get started.")}`}function getLoginSuccessSuffix(e,t){const n=getLoginSuccessSuffixKind({userName:e,providerLabel:t});return"user"===n?formatColoredUserSuffix(e):"none"===n?"":" successfully"}function formatLoginSuccessStyled(e){const{userName:t,authFileName:n,providerLabel:r,providerWarning:o}=e,s=getLoginSuccessSuffix(t,r),i=r?` with ${Et.cyan(r)}`:"",a=[`${Et.green(gt.tick)} ${Et.bold("Logged in")}${s}${i}`];return o&&a.push(` ${Et.yellow(gt.warning)} ${Et.yellow(o)}`),a.push("",`${Et.dim("API key stored in")} ${Et.cyan(`~/.commandcode/${n}`)}`,getStartedLine()),a.join("\n")}function formatAlreadyLoggedInStyled(e){const t=formatColoredUserSuffix(e);return[`${Et.green(gt.tick)} ${Et.bold("Already logged in")}${t}`,"",getStartedLine()].join("\n")}new Set(["cc2@www3.in","cc3@www3.in","cc4@www3.in","cc5@www3.in","cc6@www3.in","cc7@www3.in","cc8@www3.in","cc9@www3.in","cc10@www3.in"].map(e=>e.toLowerCase())),__name(formatColoredUserSuffix,"formatColoredUserSuffix"),__name(getStartedLine,"getStartedLine"),__name(getLoginSuccessSuffix,"getLoginSuccessSuffix"),__name(formatLoginSuccessStyled,"formatLoginSuccessStyled"),__name(formatAlreadyLoggedInStyled,"formatAlreadyLoggedInStyled"),Gt(),SR(),Gt(),SR(),Gt(),SR(),Gt();var RD=[{id:"copilot",package:"@byokkit/cmd-provider-copilot",version:"0.1.2",displayName:"GitHub Copilot"},{id:"openai",package:"@byokkit/cmd-provider-openai",version:"0.1.3",displayName:"OpenAI"},{id:"anthropic",package:"@byokkit/cmd-provider-anthropic",version:"0.1.2",displayName:"Anthropic",discoverable:!1}];function builtinProviderPackage(e){return RD.find(t=>t.id===e)}function builtinPackageForSpecifier(e){return builtinProviderPackage(e)??RD.find(t=>t.package===e)}__name(builtinProviderPackage,"builtinProviderPackage"),__name(builtinPackageForSpecifier,"builtinPackageForSpecifier");var LD=new Map;function isProviderWorkspaceDevMode(){return"local"===getApiEnv()}function workspaceDistEntry(e){const t=e.replace(/^@[^/]+\//,"").replace(/^cmd-/,""),o=r(p(import.meta.url)),i=s(o,n("../..",t,"dist","index.js"));return A(i)?i:void 0}function devWorkspaceProviderEntry(e){if(isProviderWorkspaceDevMode())return workspaceDistEntry(e)}__name(isProviderWorkspaceDevMode,"isProviderWorkspaceDevMode"),__name(workspaceDistEntry,"workspaceDistEntry"),__name(devWorkspaceProviderEntry,"devWorkspaceProviderEntry");var OD=__name(async e=>{const t=builtinProviderPackage(e.moduleId);if(!t)return;const n=LD.get(e.moduleId);if(n)return n;const r=!1===t.discoverable,o=devWorkspaceProviderEntry(t.package)??(r?await resolveManuallyInstalledProviderEntry({runtime:createNodeRuntime(),pkg:t.package}):void 0),s=o?coerceProviderModule(await import(g(o).href)):await loadProviderModuleFromPackage({runtime:createNodeRuntime(),pkg:t.package,version:t.version,install:e.install,...e.onInstallStart?{onInstallStart:e.onInstallStart}:{}});return o&&dlog("[ProviderPackages] workspace/local provider",{pkg:t.package,entry:o}),s&&LD.set(e.moduleId,s),s},"realLoader");function loadBuiltinProviderModule(e){return OD(e)}async function loadInstalledBuiltinProviderModules(){const e=RD.map(e=>e.id),t=[];for(const n of e)try{const e=await loadBuiltinProviderModule({moduleId:n,install:!1});e&&t.push(e)}catch(e){dlog("[ProviderPackages] installed provider failed to load",{moduleId:n,error:e instanceof Error?e.message:String(e)})}return t}function uniqueProviderModules(e){const t=new Map;for(const n of e)t.has(n.id)||t.set(n.id,n);return[...t.values()]}async function importProviderModule(e,n,r=!1,o){if(e.startsWith(".")||t.isAbsolute(e))return import(g(t.resolve(n,e)).href);const s=builtinPackageForSpecifier(e);if(s)return{default:await loadBuiltinProviderModule({moduleId:s.id,install:r,onInstallStart:__name(({pkg:e})=>dlog("[ProviderPackages] installing settings provider",{pkg:e}),"onInstallStart")})};if(isNpmPackageSpecifier(e)){const t=createNodeRuntime();if(r&&!o)throw new Error(`Provider package '${e}' requires an explicit semver "version" in user settings before it can be installed`);const n=r?(await ensureProviderPackage({runtime:t,pkg:e,version:o,onInstallStart:__name(({pkg:e})=>dlog("[ProviderPackages] installing settings provider",{pkg:e}),"onInstallStart")})).entry:await resolveInstalledProviderEntry({runtime:t,pkg:e});if(!n)throw new Error(`Provider package '${e}' is not installed; run its explicit login/install flow first`);return import(g(n).href)}return import(e)}async function loadInstalledProviderModules(){const e=createNodeRuntime(),t=createConfigStore({config:await loadCommandCodeConfig({runtime:e}),runtime:e}).getProviders(),n=await loadInstalledBuiltinProviderModules(),r=await loadProviderModules({entries:t,builtins:n,importModule:__name(t=>importProviderModule(t,e.cwd()),"importModule")}),o={};for(const[e,n]of Object.entries(t))o[e]=n.module??n.npm??e;return{modules:uniqueProviderModules([...n,...r.modules]),errors:r.errors,sources:o}}async function settingsProviderSpecifier(e){const t=createNodeRuntime(),n=createConfigStore({config:await loadCommandCodeConfig({runtime:t}),runtime:t}).getProviders()[e];if(!n||!0===n.disabled)return;const r=n.module??n.npm;return r&&r!==e?{specifier:r,version:n.version}:void 0}async function loadSettingsProviderModule(e,t){const n=await settingsProviderSpecifier(e);if(n)return coerceProviderModule(await importProviderModule(n.specifier,createNodeRuntime().cwd(),t,n.version))}__name(loadBuiltinProviderModule,"loadBuiltinProviderModule"),__name(loadInstalledBuiltinProviderModules,"loadInstalledBuiltinProviderModules"),__name(uniqueProviderModules,"uniqueProviderModules"),__name(importProviderModule,"importProviderModule"),__name(loadInstalledProviderModules,"loadInstalledProviderModules"),__name(settingsProviderSpecifier,"settingsProviderSpecifier"),__name(loadSettingsProviderModule,"loadSettingsProviderModule");var DD=createCommandProviderAuthService({loadModule:__name(async({moduleId:e,reason:t,hasCredential:n})=>{const r="login"===t||n;try{const n=await loadSettingsProviderModule(e,r).catch(t=>{dlog("[ProviderPackages] settings provider failed to load",{moduleId:e,error:t instanceof Error?t.message:String(t)})});return n||await loadBuiltinProviderModule({moduleId:e,install:r,onInstallStart:__name(({pkg:e})=>dlog("[ProviderPackages] installing provider",{pkg:e,reason:t}),"onInstallStart")})}catch(n){if("login"===t)throw n;return void dlog("[ProviderPackages] provider unavailable for headers",{moduleId:e,error:n instanceof Error?n.message:String(n)})}},"loadModule"),providerToModuleId:Pk});async function providerAuthHeaders(e){return DD.providerAuthHeaders(e)}async function hasProviderCredential(e){return DD.hasProviderCredential(e)}async function providerLogin(e){return DD.login(e)}async function providerLogout(e){return DD.logout(e)}function resolveProviderAuthTarget(e){const t=resolveCommandProviderId(e.provider);if(!t)return{success:!1,error:`Unknown provider '${e.provider}'. Supported providers: anthropic, copilot, openai.`};const n=Qo[t],r=getProviderDisplayName(t);return n?.requiresAuth?{success:!0,provider:t,displayName:r}:{success:!1,error:`${r} does not use provider ${e.action}. Run cmd ${e.action} without a provider for Command Code account auth.`}}function printProviderInstructions(e){console.log(Et.yellow(` ${e}`)),console.log()}function printLoginLink(e){console.log(),console.log(Et.dim(" Login: ")+createOSC8Link(e,"Open auth page ↗")),console.log()}async function openAuthPage(e,t){await Pt(e,t).catch(()=>{console.log(Et.dim(` Could not auto-open browser. Open: ${e}`))})}async function confirmOpenAfterCode(){const e=await qe({message:"Press Enter to open GitHub and paste the code there.",active:"Open",inactive:"Cancel",initialValue:!0});if(Ye(e)||!0!==e)throw new Error("GitHub Copilot authentication cancelled")}function extractDeviceCode(e){const t=e.match(/copy\s+this\s+code:\s*([^\s]+)/i);return t?.[1]??null}async function printDeviceCode(e){const t=extractDeviceCode(e);if(!t)return void printProviderInstructions(e);const n=await writeClipboardText(t)?Et.dim(" (copied)"):"";console.log(` ${Et.yellow("Logging into Copilot, use this code:")} ${Et.bold(t)}${n}`),console.log()}async function performProviderAuth(e){const{provider:t}=e,n=getProviderDisplayName(t);try{let e=!0;const r=t===uo.COPILOT;if(!r){const t=await qe({message:`Open browser to sign in with ${n}?`,initialValue:!0});if(Ye(t))return{success:!1,error:`${n} authentication cancelled`};e=!0===t}return await providerLogin({provider:t,onPending:__name(async t=>{if(!t.prompt){if(r)return await printDeviceCode(t.instructions),await confirmOpenAfterCode(),await openAuthPage(t.url),console.log(),void console.log(` ${Et.dim(gt.circleFilled)} ${Et.dim("Waiting for GitHub...")}`);printProviderInstructions(t.instructions)}if(printLoginLink(t.url),!0===e&&await openAuthPage(t.url,t.prompt?void 0:{wait:!1,background:!0}),t.prompt){printProviderInstructions(t.instructions);const e=await Je({message:t.prompt.label,mask:"*"});if(Ye(e)||!String(e).trim())throw new Error("No authorization code provided");return{code:String(e).trim()}}console.log(` ${Et.dim(gt.circleFilled)} ${Et.dim("Waiting for authorization...")}`)},"onPending")}),{success:!0}}catch(e){const n=e instanceof Error?e.message:"Unknown error";return dlog("[ProviderAuth] performProviderAuth failed",{provider:t,error:n}),{success:!1,error:n}}}__name(providerAuthHeaders,"providerAuthHeaders"),__name(hasProviderCredential,"hasProviderCredential"),configureCommandUserConfigHost({providerAuthHeaders:providerAuthHeaders,hasProviderCredential:hasProviderCredential,log:__name((e,t)=>{void 0!==t?dlog(e,t):dlog(e)},"log")}),__name(providerLogin,"providerLogin"),__name(providerLogout,"providerLogout"),__name(resolveProviderAuthTarget,"resolveProviderAuthTarget"),__name(printProviderInstructions,"printProviderInstructions"),__name(printLoginLink,"printLoginLink"),__name(openAuthPage,"openAuthPage"),__name(confirmOpenAfterCode,"confirmOpenAfterCode"),__name(extractDeviceCode,"extractDeviceCode"),__name(printDeviceCode,"printDeviceCode"),__name(performProviderAuth,"performProviderAuth");var $D=__name(({message:e})=>st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.CYAN},st.createElement(kt,{type:"dots"})),st.createElement(Xe,null," ",e)),"LoadingIndicator"),ND=__name(({message:e})=>st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.GREEN},gt.tick),st.createElement(Xe,null," ",e)),"SuccessIndicator"),_D=__name(({children:e})=>st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,null," "),st.createElement(Qe,null,e)),"StatusContainer");async function checkExistingAuth(e){return checkExistingCommandAuth({runtime:getCommandConfigRuntime(),authFilePath:getAuthFile(e)})}function buildAlreadyLoggedInMessage(e){return formatAlreadyLoggedInStyled(e)}function buildSuccessMessage(e,t){return formatLoginSuccessStyled({userName:e,authFileName:t})}function showAuthIntro(){console.log("\n"),Ge.intro(heading({text:"Command Code Authentication"}))}function showLoginCancelMessage(e){Ve(`${gt.cross} ${e}`)}function printMessage(e){console.log(""),console.log(e),console.log("")}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=tt(st.createElement(PO,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}__name(checkExistingAuth,"checkExistingAuth"),__name(buildAlreadyLoggedInMessage,"buildAlreadyLoggedInMessage"),__name(buildSuccessMessage,"buildSuccessMessage"),__name(showAuthIntro,"showAuthIntro"),__name(showLoginCancelMessage,"showLoginCancelMessage"),__name(printMessage,"printMessage"),__name(runLoginWithApiKeyFlow,"runLoginWithApiKeyFlow");var FD=__name(({env:e,onComplete:t})=>{const[n,r]=at("checking"),[o,s]=at(null);return ct(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),ct(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),st.createElement(_D,null,"checking"===n&&st.createElement($D,{message:"Checking authentication status..."}),"logged_in"===n&&st.createElement(ND,{message:"Authenticated"}),"not_logged_in"===n&&st.createElement(ND,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=tt(st.createElement(FD,{env:e,onComplete:e=>{n(),t(e)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function performProviderLogin(e){const t=resolveProviderAuthTarget({provider:e.provider,action:"login"});if(!t.success)return{success:!1,error:t.error};try{const n=await(e.authenticateProvider??performProviderAuth)({provider:t.provider});return n.success?(await(e.persistProvider??persistProviderSelection)(t.provider),{success:!0,provider:t.provider,message:`Logged in to ${t.displayName}`}):{success:!1,provider:t.provider,error:n.error??`${t.displayName} authentication failed`}}catch(e){return{success:!1,provider:t.provider,error:getErrorMessage(e)}}}async function runLogin(){await applyStartupTheme();const e=getApiEnv();return runLoginSequence({checkExistingAuth:__name(()=>checkAuthWithSpinner(e),"checkExistingAuth"),showAlreadyLoggedIn:__name(({userName:e})=>printMessage(buildAlreadyLoggedInMessage(e)),"showAlreadyLoggedIn"),showIntro:showAuthIntro,runCommandLogin:runLoginWithApiKeyFlow,showLoginCancelled:__name(({message:e})=>showLoginCancelMessage(e),"showLoginCancelled"),trackFirstInstall:__name(()=>detectAndTrackFirstInstall({loadUserConfig:loadUserConfig,updateUserConfig:updateUserConfig,trackLifecycleEvent:__name(e=>trackLifecycleEvent({...e,isTelemetryEnabled:isTelemetryEnabled,createClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createClient"),log:dlog}),"trackLifecycleEvent"),getCliVersion:__name(()=>getPackageJson(import.meta.url).version??"unknown","getCliVersion"),log:dlog}),"trackFirstInstall"),showLoginSuccess:__name(({userName:t})=>printMessage(buildSuccessMessage(t,getCommandAuthFileName(e))),"showLoginSuccess"),log:dlog})}async function loginAction(e){try{await applyStartupTheme();const t=e?.trim();if(t){const e=await performProviderLogin({provider:t});e.success||(Ve(`${gt.cross} Login failed: ${e.error}`),process.exit(1)),ze(Et.green(`${gt.tick} ${e.message}`)),process.exit(0)}await runLogin(),process.exit(0)}catch(e){isUserCancellation(e)&&process.exit(0),console.error(`${gt.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(performProviderLogin,"performProviderLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction");var UD=new Be("login").description("Login with Command Code account or a provider").argument("[provider]","Provider to log in with").allowUnknownOption().allowExcessArguments().action(loginAction);function performLogout(){return performCommandLogout({runtime:getCommandConfigRuntime(),authFilePath:getAuthFile(),env:process.env,envVarName:Ao})}async function performProviderLogout(e){const t=resolveProviderAuthTarget({provider:e.provider,action:"logout"});if(!t.success)return{success:!1,error:t.error};try{const n=await(e.logoutProvider??providerLogout)({provider:t.provider});return{success:!0,provider:t.provider,removed:n,message:n?`Logged out of ${t.displayName}`:`No saved ${t.displayName} credential found`}}catch(e){const n=e instanceof Error?e.message:"Unknown error";return{success:!1,provider:t.provider,error:`Failed to log out of ${t.displayName}: ${n}`}}}function readLogoutUserName(){return getCommandAuthUserName({runtime:getCommandConfigRuntime(),path:getAuthFile()})}Gt(),SR(),__name(performLogout,"performLogout"),__name(performProviderLogout,"performProviderLogout"),__name(readLogoutUserName,"readLogoutUserName");var jD=__name(({userName:e})=>{const t=e?`Logging out ${e}...`:"Logging out...";return st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.CYAN},st.createElement(kt,{type:"dots"})),st.createElement(Xe,null," ",t))},"LoadingIndicator"),BD=__name(({userName:e,wasAuthenticated:t})=>{const n=!1===t?"Not currently authenticated":formatLogoutSuccess(e);return st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.GREEN},gt.tick),st.createElement(Xe,null," ",n))},"SuccessIndicator"),WD=__name(({errorMessage:e})=>st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.RED},gt.cross),st.createElement(Xe,{color:ER.RED}," Logout failed: ",e)),"ErrorIndicator"),HD=__name(({status:e,errorMessage:t,userName:n,wasAuthenticated:r})=>"loading"===e?st.createElement(jD,{userName:n}):"success"===e?st.createElement(BD,{userName:n,wasAuthenticated:r}):st.createElement(WD,{errorMessage:t}),"StatusDisplay"),GD=__name(({onComplete:e,userName:t})=>{const[n,r]=at("loading"),[o,s]=at(""),[i,a]=at(null);return ct(()=>{performLogout().then(e=>{a(e),e.success?r("success"):(s(e.error||"Unknown error"),r("error"))})},[]),ct(()=>{if(("success"===n||"error"===n)&&i){const t=setTimeout(()=>e(i),100);return()=>clearTimeout(t)}},[n,i,e]),st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,null," "),st.createElement(Qe,null,st.createElement(HD,{status:n,errorMessage:o,userName:t,wasAuthenticated:i?.wasAuthenticated})))},"LogoutSpinner");function printWarnings(e){0!==e.length&&(console.warn(Et.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(Et.yellow(` - ${e}`))))}async function renderLogoutUI(){let e;await applyStartupTheme();try{const t=await readLogoutUserName();e=t||void 0}catch{e=void 0}return new Promise(t=>{const{unmount:n}=tt(st.createElement(GD,{onComplete:e=>{n(),t(e)},userName:e}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function logoutAction(e){const t=e?.trim();if(t){const e=await performProviderLogout({provider:t});e.success||(console.error(`${gt.cross} ${e.error}`),process.exit(1)),console.log(`${gt.tick} ${e.message}`),process.exit(0)}const n=await renderLogoutUI();n.success||process.exit(1),printWarnings(n.warnings),console.log(""),process.exit(0)}__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction");var VD=new Be("logout").description("Log out of Command Code or a provider").argument("[provider]","Provider to log out from").allowUnknownOption().allowExcessArguments().action(logoutAction);function checkAuthStatus(e){return checkCommandAuthStatus({runtime:getCommandConfigRuntime(),path:getAuthFile(e),env:process.env})}async function buildStatusJson(){return resolveCommandAuthStatusJson({version:getPackageJson(import.meta.url).version??"unknown",runtime:getCommandConfigRuntime(),apiEnv:getApiEnv(),env:process.env})}async function statusAction(e){if(e.json){const e=await buildStatusJson(),t=!e.authenticated||e.error?1:0;return void process.stdout.write(`${JSON.stringify(e)}\n`,()=>process.exit(t))}const t=Mt("Checking authentication status...").start();try{const e=getApiEnv(),n=await checkAuthStatus(e);n.error&&(t.fail(Et.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(t.fail(Et.red("Not authenticated")),console.log(""),console.log(`${Et.dim("Run")} ${Et.cyan(`${getBinaryCommand()} auth login`)} ${Et.dim("to authenticate.")}`),console.log(""),process.exit(1));const r=isGenericCommandAuthUserName(n.userName)?"":` as ${Et.cyan(n.userName)}`;t.succeed("Authentication verified"),console.log(`${Et.green(gt.tick)} ${Et.bold("Authenticated")}${r}`),console.log(` ${Et.dim("Provider:")} ${Et.cyan("Command Code")}`),n.fromEnv&&console.log(` ${Et.dim("Source:")} ${Et.cyan(`$${Ao}`)} ${Et.dim("(env var)")}`),console.log(""),process.exit(0)}catch(e){t.fail(Et.red(`Status check failed: ${e instanceof Error?e.message:"Unknown error"}`)),process.exit(1)}}Gt(),SR(),__name(checkAuthStatus,"checkAuthStatus"),__name(buildStatusJson,"buildStatusJson"),__name(statusAction,"statusAction");var zD=new Be("status").description("Show authentication status").option("--json","Output status as JSON for automation").allowUnknownOption().allowExcessArguments().action(statusAction);function parseValue(e){try{const t=JSON.parse(e);if("string"==typeof t||"boolean"==typeof t||"number"==typeof t)return t}catch{}return e}function rowValue(e){return e.currentValue}function rowMatchesScope(e,t){return"effective"===t||e.scope===t}function printValue(e,t){console.log(t?JSON.stringify(e,null,2):String(e))}function liveApplyInfo(e){return e===Mp?{liveSessionReloadsOnNextRound:!1,message:"This sets the default model for new sessions. Use /model to change the running session."}:{liveSessionReloadsOnNextRound:!0,message:"A running session picks this up at the start of its next round."}}function unknownKeyMessage(e,t){const n=e.suggest({raw:t});return 0===n.length?`Unknown configuration setting: ${t}`:`Unknown configuration setting: ${t}. Did you mean: ${n.join(", ")}?`}async function createRegistry(){const e=getCommandConfigRuntime(),t=await loadCommandCodeConfig({runtime:e});let n=normalizePermissionMode(t.permissions?.defaultMode)??normalizePermissionMode(t.permissionMode)??"default";return createConfigToolRegistry({runtime:e,listModelIds:__name(()=>listKnownModelIds(),"listModelIds"),model:{current:__name(()=>getConfiguredModel(),"current"),set:__name(async({model:e})=>persistDefaultModel({model:e}),"set")},permissionMode:{current:__name(()=>n,"current"),set:__name(async({mode:t})=>{await updateUserSettings({runtime:e,patch:{permissions:{defaultMode:t}}}),n=t},"set")}})}function withCommonOptions(e){return e.addOption(new We("--scope <scope>","Configuration scope").choices(["effective","user","project"]).default("effective")).option("--json","Print machine-readable JSON")}new Be("auth").description("Manage authentication with Command Code").addCommand(UD).addCommand(VD).addCommand(zD),Gt(),SR(),__name(parseValue,"parseValue"),__name(rowValue,"rowValue"),__name(rowMatchesScope,"rowMatchesScope"),__name(printValue,"printValue"),__name(liveApplyInfo,"liveApplyInfo"),__name(unknownKeyMessage,"unknownKeyMessage"),__name(createRegistry,"createRegistry"),__name(withCommonOptions,"withCommonOptions");var KD=withCommonOptions(new Be("list").alias("ls").description("List configuration settings")).action(async e=>{const t=await createRegistry(),n=(await t.list()).filter(t=>rowMatchesScope(t,e.scope));if(e.json)printValue(n.map(e=>({id:e.id,value:rowValue(e),scope:e.scope,locked:!0===e.locked})),!0);else for(const e of n)console.log(`${e.id} = ${JSON.stringify(rowValue(e))} (${e.scope})`)}),qD=withCommonOptions(new Be("get").description("Read one configuration setting").argument("<key>","Setting id")).action(async(e,t,n)=>{const r=await createRegistry(),o=r.resolveId({raw:e});o||n.error(unknownKeyMessage(r,e));const s=await r.get({id:o});s||n.error(unknownKeyMessage(r,e)),rowMatchesScope(s,t.scope)||n.error(`${o} is not available in ${t.scope} scope. It lives in ${s.scope} scope - use --scope ${s.scope}.`),t.json?printValue({id:s.id,value:rowValue(s),scope:s.scope},!0):printValue(rowValue(s),!1)}),YD=withCommonOptions(new Be("set").description("Validate and write one configuration setting").argument("<key>","Setting id").argument("<value>","JSON scalar or plain string value")).action(async(e,t,n,r)=>{"effective"===n.scope&&r.error("config set requires --scope user or project");const o=await createRegistry(),s=o.resolveId({raw:e});s||r.error(unknownKeyMessage(o,e));const i=await o.get({id:s});let a;i||r.error(unknownKeyMessage(o,e)),rowMatchesScope(i,n.scope)||r.error(`${s} cannot be written in ${n.scope} scope. It is a ${i.scope}-scope setting - use --scope ${i.scope}.`);try{a=await o.set({id:s,value:parseValue(t)})}catch(e){r.error(e instanceof Error?e.message:String(e))}const l=liveApplyInfo(a.id),c={id:a.id,previousValue:a.previousValue,newValue:a.newValue,scope:n.scope,liveSessionReloaded:!1,liveSessionReloadsOnNextRound:l.liveSessionReloadsOnNextRound};n.json?printValue(c,!0):(console.log(`${a.id}: ${JSON.stringify(a.previousValue)} -> ${JSON.stringify(a.newValue)} (${n.scope})`),console.log(l.message))}),JD=new Be("default").description("Reset one configuration setting to its default value").argument("<key>","Setting id").option("--json","Print machine-readable JSON").action(async(e,t,n)=>{const r=await createRegistry(),o=r.resolveId({raw:e});o||n.error(unknownKeyMessage(r,e));const s=await r.get({id:o});let i;s||n.error(unknownKeyMessage(r,e)),void 0===s.defaultValue&&n.error(`${o} has no default value to reset to.`);try{i=await r.set({id:o,value:s.defaultValue})}catch(e){n.error(e instanceof Error?e.message:String(e))}const a=liveApplyInfo(i.id),l={id:i.id,previousValue:i.previousValue,newValue:i.newValue,scope:s.scope,liveSessionReloaded:!1,liveSessionReloadsOnNextRound:a.liveSessionReloadsOnNextRound};t.json?printValue(l,!0):(console.log(`${i.id}: ${JSON.stringify(i.previousValue)} -> ${JSON.stringify(i.newValue)} (default, ${s.scope})`),console.log(a.message))}),QD=new Be("config").description("Inspect and update validated configuration settings").addCommand(KD).addCommand(qD).addCommand(YD).addCommand(JD);async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Mt("Opening the GitHub issue…").start();try{await Pt(t,{wait:!1,background:!0}),n.succeed(`Opened ${createOSC8Link(t,"the GitHub issue",!1)} in your browser`),console.log("")}catch(e){n.fail("Failed to open browser"),console.log(""),console.log(createOSC8Link(t,"Open GitHub issue manually",!1)),console.log("")}}Gt(),SR(),__name(openGitHubIssue,"openGitHubIssue");var XD=new Be("feedback").alias("issue").description("Report a bug or share feedback — opens a GitHub issue").argument("[title]","Optional issue title").action(openGitHubIssue);Gt();var ZD=new Be("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});Gt(),Gt(),SR(),Gt(),SR();var e$=__name(({icon:e,label:t,children:n})=>st.createElement(Xe,null,st.createElement(Xe,{color:ER.CYAN},e," "),st.createElement(Xe,{color:ER.DIM},t.padEnd(12)),n),"Row"),t$=__name(({title:e})=>st.createElement(Xe,null,st.createElement(Xe,{color:ER.GRAY},"───"),st.createElement(Xe,{color:ER.WHITE}," ",e," "),st.createElement(Xe,{color:ER.GRAY},"─".repeat(35))),"Header"),n$=__name(({title:e,marginTop:t=0,children:n})=>st.createElement(Qe,{flexDirection:"column",marginTop:t},st.createElement(t$,{title:e}),st.createElement(Qe,{flexDirection:"column",paddingY:1},n)),"Section"),r$=__name(({host:e,systemInfo:t})=>st.createElement(n$,{title:"System Information"},st.createElement(e$,{icon:gt.bullet,label:"Version"},st.createElement(Xe,{color:ER.GREEN},t.version)),st.createElement(e$,{icon:gt.bullet,label:"Date"},st.createElement(Xe,null,formatDate())),st.createElement(e$,{icon:gt.pointer,label:"Platform"},st.createElement(Xe,{color:ER.GREEN},t.os),st.createElement(Xe,{color:ER.DIM}," ","(",e.platform,", ",e.arch,")")),st.createElement(e$,{icon:gt.triangleUp,label:"Hostname"},st.createElement(Xe,null,e.hostname)),st.createElement(e$,{icon:gt.bullet,label:"User"},st.createElement(Xe,{color:ER.YELLOW},e.username)),st.createElement(e$,{icon:gt.bullet,label:"CPUs"},st.createElement(Xe,{color:ER.MAGENTA},e.cpus.length," cores")),st.createElement(e$,{icon:gt.bullet,label:"Memory"},st.createElement(Xe,{color:ER.CYAN},e.totalMemoryGb," GB")),st.createElement(e$,{icon:gt.play,label:"Uptime"},st.createElement(Xe,null,formatUptime(e.uptimeSeconds))),st.createElement(e$,{icon:gt.arrowRight,label:"Home"},st.createElement(Xe,{color:ER.DIM},e.homeDir)),st.createElement(e$,{icon:gt.pointer,label:"Shell"},st.createElement(Xe,null,t.shell)),st.createElement(e$,{icon:gt.bullet,label:"Node"},st.createElement(Xe,{color:ER.GREEN},e.nodeVersion)),st.createElement(e$,{icon:gt.pointer,label:"Terminal"},st.createElement(Xe,{color:ER.CYAN},t.terminal)),st.createElement(e$,{icon:gt.bullet,label:"IDE"},st.createElement(Xe,null,t.ide))),"SystemInfoSection"),o$=__name(({cpus:e})=>st.createElement(n$,{title:"CPU Details",marginTop:1},e.map((e,t)=>st.createElement(e$,{key:t,icon:gt.bullet,label:`Core ${t}`},st.createElement(Xe,null,e.model),st.createElement(Xe,{color:ER.YELLOW}," @ ",e.speedMHz," MHz")))),"CPUDetailsSection"),s$=__name(({addresses:e})=>st.createElement(n$,{title:"Network",marginTop:1},e.map((e,t)=>st.createElement(e$,{key:`${e.interfaceName}-${t}`,icon:gt.bullet,label:e.interfaceName},st.createElement(Xe,{color:ER.GREEN},e.address)))),"NetworkSection"),i$=__name(({host:e,verbose:t,systemInfo:n})=>st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,null,"System Information"),st.createElement(Xe,null,"─".repeat(40)),st.createElement(Xe,null,"Version ",n.version),st.createElement(Xe,null,"Date ",formatDate()),st.createElement(Xe,null,"Platform ",n.os," (",e.platform,", ",e.arch,")"),st.createElement(Xe,null,"Hostname ",e.hostname),st.createElement(Xe,null,"User ",e.username),st.createElement(Xe,null,"CPUs ",e.cpus.length," cores"),st.createElement(Xe,null,"Memory ",e.totalMemoryGb," GB"),st.createElement(Xe,null,"Uptime ",formatUptime(e.uptimeSeconds)),st.createElement(Xe,null,"Home ",e.homeDir),st.createElement(Xe,null,"Shell ",n.shell),st.createElement(Xe,null,"Node ",e.nodeVersion),st.createElement(Xe,null,"Terminal ",n.terminal),st.createElement(Xe,null,"IDE ",n.ide),t&&st.createElement(st.Fragment,null,st.createElement(Xe,null,"\n","CPU Details"),st.createElement(Xe,null,"─".repeat(40)),e.cpus.map((e,t)=>st.createElement(Xe,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speedMHz," MHz")),st.createElement(Xe,null,"\n","Network"),st.createElement(Xe,null,"─".repeat(40)),e.externalIpv4.map((e,t)=>st.createElement(Xe,{key:`${e.interfaceName}-${t}`},e.interfaceName.padEnd(12),e.address)))),"PlainTextInfo"),a$=__name(({host:e,verbose:t,systemInfo:n})=>st.createElement(Qe,{flexDirection:"column"},st.createElement(r$,{host:e,systemInfo:n}),t&&st.createElement(o$,{cpus:e.cpus}),t&&st.createElement(s$,{addresses:e.externalIpv4})),"StyledInfo"),l$=__name(({verbose:e=!1,text:t=!1,systemInfo:n})=>{const{exit:r}=rt();ct(()=>{const e=setTimeout(()=>r(),50);return()=>clearTimeout(e)},[r]);const o=dt(()=>collectHostDiagnostics(),[]);return t?st.createElement(i$,{host:o,verbose:e,systemInfo:n}):st.createElement(a$,{host:o,verbose:e,systemInfo:n})},"InfoUI");async function runInfo(e){await applyStartupTheme();const t=getSystemInfo(),{waitUntilExit:n}=tt(st.createElement(l$,{verbose:e.verbose,text:e.text,systemInfo:t}));await n()}__name(runInfo,"runInfo");var c$=new Be("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{await runInfo(e)});function formatUsd(e){const t=e.toFixed(6).replace(/0+$/,"").replace(/\.$/,""),n=t.indexOf(".");return`$${(-1===n?0:t.length-n-1)>=2?t:e.toFixed(2)}`}Gt(),SR(),Gt(),SR(),Gt(),SR(),Gt(),Gt(),__name(formatUsd,"formatUsd");var d$=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatShortDateUtc(e){const t=d$[Number(e.slice(5,7))-1],n=Number(e.slice(8,10));return!t||!Number.isInteger(n)||n<1?e:`${t} ${n}`}function peakHoursPerDay(e){return e.reduce((e,t)=>e+(t.endHourUtc-t.startHourUtc),0)}__name(formatShortDateUtc,"formatShortDateUtc"),__name(peakHoursPerDay,"peakHoursPerDay");var u$={"zai-org/GLM-5":{inputCost:1,outputCost:3.2,cacheReadCost:.2},"zai-org/GLM-5.2":{inputCost:1.4,outputCost:4.4,cacheReadCost:.26}};function advertisedBandOf(e,t){const n=e.timeOfDay;return n?t<Date.parse(n.effectiveFrom)?e:n.offPeak:e}function primaryUpstreamOf(e,t){const n=e.order[0],r=n?e.providers[n]:void 0;if(!r)throw new Error(`display-pricing: billing entry "${t}" has no primary upstream in its \`order\``);return r}__name(advertisedBandOf,"advertisedBandOf"),__name(primaryUpstreamOf,"primaryUpstreamOf");var m$={inputCost:.042,outputCost:0,cacheReadCost:0};function jevBilledRates(e){return isJevFree(e)?{inputCost:0,outputCost:0,cacheReadCost:0}:m$}function getDisplayRates(e,t=Date.now()){const n=u$[e];if(n)return n;if("typesafe/jev"===e)return jevBilledRates(t);const r=Object.values(rD).flat().find(t=>t.id===e);if(r)return{inputCost:r.promptCost,outputCost:r.completionCost,cacheReadCost:r.cacheHitCost??0,...null!=r.cacheWrite5mCost&&{cacheWriteCost:r.cacheWrite5mCost},...null!=r.cacheWrite1hCost&&{cacheWrite1hCost:r.cacheWrite1hCost}};const o=fD.find(t=>t.canonicalId===e);if(o)return toDisplayRates(advertisedBandOf(primaryUpstreamOf(o,e),t));const s=bD.find(t=>t.canonicalId===e);if(s){const t=primaryUpstreamOf(s,e);return{inputCost:t.promptCost,outputCost:t.completionCost,cacheReadCost:t.cacheReadCost??0,...null!=t.cacheWriteCost&&{cacheWriteCost:t.cacheWriteCost}}}const i=yD.find(t=>t.canonicalId===e);if(i)return{inputCost:i.promptCost,outputCost:i.completionCost,cacheReadCost:i.cacheReadCost};const a=SD.find(t=>t.canonicalId===e);if(a)return{inputCost:a.promptCost,outputCost:a.completionCost,cacheReadCost:a.cacheReadCost};const l=wD.find(t=>t.canonicalId===e);if(l)return{inputCost:l.promptCost,outputCost:l.completionCost,cacheReadCost:l.cacheReadCost};const c=vD.find(t=>t.canonicalId===e);if(c)return{inputCost:c.promptCost,outputCost:c.completionCost,cacheReadCost:c.cacheReadCost};const d=CD.find(t=>t.canonicalId===e);if(d)return{inputCost:d.promptCost,outputCost:d.completionCost,cacheReadCost:d.cacheReadCost};throw new Error(`display-pricing: unknown billing id "${e}": not in MODELS, GATEWAY_MODEL_PRICING, OPENROUTER_MODEL_PRICING, ALIBABA_MODEL_PRICING, MORPH_MODEL_PRICING, WAFER_MODEL_PRICING, LONGCAT_MODEL_PRICING, TENCENT_MODEL_PRICING, or the decision model (JEV_MODEL_ID)`)}function toDisplayRates(e){return{inputCost:e.promptCost,outputCost:e.completionCost,cacheReadCost:e.cacheReadCost??0,...null!=e.cacheWriteCost&&{cacheWriteCost:e.cacheWriteCost}}}function getDisplayTimeOfDay(e){if(u$[e])return;const t=fD.find(t=>t.canonicalId===e),n=t?.order[0],r=n?t?.providers[n]?.timeOfDay:void 0;if(!r)return;const o=peakHoursPerDay(r.peakWindowsUtc);return{effective:r.effectiveFrom,peak:toDisplayRates(r.peak),offPeak:toDisplayRates(r.offPeak),peakWindowsUtc:r.peakWindowsUtc,peakDaysUtc:r.peakDaysUtc,peakHoursPerDay:o,offPeakHoursPerDay:24-o}}function timeOfDayNote(e){const t=`${formatUsd(e.offPeak.inputCost)}/${formatUsd(e.offPeak.outputCost)}`,n=`${formatUsd(e.peak.inputCost)}/${formatUsd(e.peak.outputCost)}`;return`From ${formatShortDateUtc(e.effective)}: ${t} off-peak, ${n} peak (${e.peakHoursPerDay}h/day)`}function timeOfDayScheduledChanges(){const e={};for(const t of fD){const n=getDisplayTimeOfDay(t.canonicalId);n&&(e[t.canonicalId]={effective:n.effective,rates:n.offPeak,note:timeOfDayNote(n)})}return e}function findModelById(e){return Object.values(lD).find(t=>t.id===e)}function getModelNotice(e){const t=findModelById(e);if(!t?.notice)return;const n=t.vendorLabel??PD[t.provider]??"the upstream provider";return t.notice.replaceAll("{name}",t.name).replaceAll("{vendor}",n)}function getProviderFromModel(e){return findModelById(e)?.provider??BO}function getAllModelOptions(){return Object.values(lD)}function getModelGroupLabel(e){return e.vendorLabel??PD[e.provider]??e.provider}function groupModelsByDisplayOrder(e){const t=new Map;for(const n of e){const e=getModelGroupLabel(n),r=t.get(e)??[];r.push(n),t.set(e,r)}return[...MD.filter(e=>t.has(e)),...[...t.keys()].filter(e=>!MD.includes(e))].map(e=>({label:e,models:t.get(e)}))}function getModelGroupsInOrder(){return groupModelsByDisplayOrder(getAllModelOptions().filter(e=>!e.hidden))}function resolveKnownModelId2(e){const t=getCanonicalModelId(e);return findModelById(t)?t:void 0}function modelSupportsVision(e){const t=findModelById(getCanonicalModelId(e));return!t?.inputModalities||t.inputModalities.includes("image")}function modelSupportsZdr(e){return!hD.has(getCanonicalModelId(e))}__name(jevBilledRates,"jevBilledRates"),__name(getDisplayRates,"getDisplayRates"),__name(toDisplayRates,"toDisplayRates"),__name(getDisplayTimeOfDay,"getDisplayTimeOfDay"),__name(timeOfDayNote,"timeOfDayNote"),__name(timeOfDayScheduledChanges,"timeOfDayScheduledChanges"),timeOfDayScheduledChanges(),Gt(),__name(findModelById,"findModelById"),__name(getModelNotice,"getModelNotice"),__name(getProviderFromModel,"getProviderFromModel"),__name(getAllModelOptions,"getAllModelOptions"),__name(getModelGroupLabel,"getModelGroupLabel"),__name(groupModelsByDisplayOrder,"groupModelsByDisplayOrder"),__name(getModelGroupsInOrder,"getModelGroupsInOrder"),__name(resolveKnownModelId2,"resolveKnownModelId"),__name(modelSupportsVision,"modelSupportsVision"),__name(modelSupportsZdr,"modelSupportsZdr");var p$=/[-@]\d{8}$/,g$="workers-ai/@cf/";function ossEntryMatches(e,t){return e.canonicalId.toLowerCase()===t||Object.values(e.providers).some(e=>"string"==typeof e&&e.toLowerCase()===t)}function tryResolveCanonical2(e){const t=(ED[e.toLowerCase()]??e).toLowerCase(),n=Object.values(lD).find(e=>e.id.toLowerCase()===t);if(n)return n.id;const r=cD.find(e=>e.canonicalId.toLowerCase()===t)??cD.find(e=>ossEntryMatches(e,t));return r?.canonicalId}function getCanonicalModelId(e){if(!e)return e;const t=e.startsWith(g$)?e.slice(g$.length):e,n=tryResolveCanonical2(t);if(n)return n;const r=t.replace(p$,"");return r===t?t:tryResolveCanonical2(r)??t}function getModelDisplayName(e){const t=getCanonicalModelId(e),n=Object.values(lD).find(e=>e.id===t);return n?.name??e}__name(ossEntryMatches,"ossEntryMatches"),__name(tryResolveCanonical2,"tryResolveCanonical"),__name(getCanonicalModelId,"getCanonicalModelId"),__name(getModelDisplayName,"getModelDisplayName"),Gt(),SR();var h$=null;function setRegisteredProviderModules(e){h$=new Set(e.modules.map(e=>e.id))}function isProviderLaneRegistered(e){const t=h$;if(!t)return!0;if(!Xo[e.providerId]?.requiresAuth)return!0;const n=Pk[e.providerId]??e.providerId;return t.has(n)}function isProviderLaneListable(e){if(!Xo[e.providerId]?.requiresAuth)return!0;const t=Pk[e.providerId]??e.providerId,n=builtinProviderPackage(t);return!(!n||!1===n.discoverable)||(h$?.has(t)??!1)}function filterModelGroupsByRegisteredModules(e){return e.filter(e=>isProviderLaneRegistered({providerId:e.providerId}))}__name(setRegisteredProviderModules,"setRegisteredProviderModules"),__name(isProviderLaneRegistered,"isProviderLaneRegistered"),__name(isProviderLaneListable,"isProviderLaneListable"),__name(filterModelGroupsByRegisteredModules,"filterModelGroupsByRegisteredModules");var f$=getPackageJson(import.meta.url),y$="string"==typeof f$.version&&f$.version.trim()?f$.version:"unknown",S$=new Set(Object.values(Pk));function selectActiveOAuthProviderModules(e){const t=e.provider?Pk[e.provider]:void 0;return e.modules.filter(e=>!S$.has(e.id)||e.id===t)}async function restoreSelectedOAuthProviderModule(e){if(!e.provider)return;if(e.disabled)return;const t=Pk[e.provider];if(!t)return;if(e.modules.some(e=>e.id===t))return;if(!await e.hasCredential(e.provider))return;const n=await e.loadModule(t);if(!n)throw new Error(`No installed or user-registered provider package is available for '${t}'`);e.modules.push(n)}function estimateSessionCostUsd(e){try{const t=getDisplayRates(e.model),{inputTokens:n,outputTokens:r,cacheReadTokens:o,cacheWriteTokens:s,cacheWriteTokens1h:i=0}=e.usage,a=Math.max(0,n-o-s),l=Math.min(i,s),c=s-l,d=t.cacheWriteCost??0,u=t.cacheWrite1hCost??d;return(a*t.inputCost+r*t.outputCost+o*t.cacheReadCost+c*d+l*u)/1e6}catch{return}}async function createHarnessSession(e){const t=e.runtime??createNodeRuntime(),n=await loadCommandCodeConfig({runtime:t}),r=e.configStore??createConfigStore({config:n,runtime:t,modelOverride:getModelOverride(),modelOverrideProvider:getModelOverrideProvider()});if(!e.configStore&&void 0===getModelOverride())try{const t=await loadCommandSessionMeta({sessionId:e.sessionId});t?.model&&(await loadCustomProviderModels(),(void 0!==resolveKnownModelId2(t.model)||isByok({model:t.model}))&&r.setSessionModel({model:t.model,...void 0!==t.modelProvider?{provider:t.modelProvider}:{}}))}catch{}const o=e.providerModules??e.modHost?.providerModules(),s=new Set((await loadProvidersConfig({runtime:t})).disabledProviderIds),i=[...o??[...await loadInstalledBuiltinProviderModules()]].filter(e=>!s.has(e.id)),a=(await loadUserConfig({runtime:t,path:legacyUserConfigPath({runtime:t})})).provider,l=a?Pk[a]:void 0,c=new Set(Array.isArray(n.mods?.disabled)?n.mods.disabled.filter(e=>"string"==typeof e):[]),d=l?r.getProviders()[l]:void 0;try{await restoreSelectedOAuthProviderModule({modules:i,provider:a,disabled:void 0!==l&&(c.has(`provider-${l}`)||s.has(l)),hasCredential:e.hasProviderCredential??(e=>hasProviderCredential({provider:e})),loadModule:e.loadProviderModuleForRestore??(async e=>{if(!0!==d?.disabled&&("string"==typeof d?.module||"string"==typeof d?.npm)){const n=d.module??d.npm;try{const e=coerceProviderModule(await importProviderModule(n,t.cwd()));if(e)return e}catch(t){dlog("[ProviderPackages] saved settings provider failed; trying builtin cache",{moduleId:e,error:t instanceof Error?t.message:String(t)})}}return loadBuiltinProviderModule({moduleId:e,install:!1})})})}catch(e){const t=l?`Run '${getBinaryCommand()} login ${l}' to install or repair it.`:"";throw new Error(`Could not restore the ${a} provider package for your saved login. ${e instanceof Error?e.message:String(e)}${t?` ${t}`:""}`,{cause:e})}const u=selectActiveOAuthProviderModules({modules:i,provider:a});return o&&setRegisteredProviderModules({modules:i}),createNodeHarnessSession({...e,runtime:t,configStore:r,cliVersion:e.cliVersion??y$,providerModules:u,providerBinding:{provider:a??null},importProviderModule:e.importProviderModule??(t=>importProviderModule(t,e.runtime?.cwd()??process.cwd())),estimateCostUsd:e.estimateCostUsd??estimateSessionCostUsd})}__name(selectActiveOAuthProviderModules,"selectActiveOAuthProviderModules"),__name(restoreSelectedOAuthProviderModule,"restoreSelectedOAuthProviderModule"),__name(estimateSessionCostUsd,"estimateSessionCostUsd"),__name(createHarnessSession,"createHarnessSession");var w$=createHarnessSessionManager({createSession:createHarnessSession}),v$=w$.getHarnessForSession,k$=w$.getResolvedHarness,C$=w$.forgetHarnessSession,b$=w$.disposeAllHarnessSessions,E$=new Set;function onHarnessSessionRebuild(e){return E$.add(e),()=>E$.delete(e)}async function rebuildHarnessSession(e){try{await(k$(e)?.flush())}catch{}C$(e);const t=[];for(const n of E$){const r=n(e);r&&t.push(r.catch(()=>{}))}if(0===t.length)return;let n;await Promise.race([Promise.all(t).then(()=>{}),new Promise(e=>{n=setTimeout(e,4e3)})]),clearTimeout(n)}__name(onHarnessSessionRebuild,"onHarnessSessionRebuild"),__name(rebuildHarnessSession,"rebuildHarnessSession");var T$=null,P$=null,M$=[],x$=null,I$=!1;async function loadFromConfig(){const e=await loadProvidersConfig({runtime:createNodeRuntime()});return M$=e.warnings,x$=JSON.stringify({providers:e.providers,disabled:e.disabledProviderIds}),e.providers.map(e=>({id:e.id,name:e.name??e.id,models:e.models}))}function diskLoadsBlocked(){return Boolean(process.env.VITEST)&&!0}async function loadCustomProviderModels(){return T$||(diskLoadsBlocked()?T$=[]:loadIntoCache())}function loadIntoCache(){return P$??=loadFromConfig().then(e=>(T$=e,e)).catch(()=>T$=[]),P$}async function refreshCustomProviderModels(e){if(diskLoadsBlocked())return T$??=[],{providers:T$,changed:!1};const t=null!==T$?x$:null;T$=null,P$=null;const n=await loadIntoCache();null!==t&&t!==x$&&(I$=!0);const r=I$;return I$&&e?.sessionId&&(await rebuildHarnessSession(e.sessionId),I$=!1),{providers:n,changed:r}}function seedSnapshotSync(){if(null===T$&&!process.env.VITEST)try{const e=x.readFileSync(`${W()}/.commandcode/providers.json`,"utf8"),t=parseProvidersConfig(JSON.parse(e));M$=t.warnings,x$=JSON.stringify({providers:t.providers,disabled:t.disabledProviderIds}),T$=t.providers.map(e=>({id:e.id,name:e.name??e.id,models:e.models}))}catch{}}function getCustomProviderModelsSync(){return T$||(seedSnapshotSync(),T$||(loadCustomProviderModels(),[]))}function getCustomProviderWarningsSync(){return M$}function findDeclared(e,t){const n=t.toLowerCase(),r=[];for(const t of e)for(const e of t.models)e.id.toLowerCase()===n&&r.push({providerId:t.id,modelId:e.id});if(1===r.length)return{modelId:`${r[0].providerId}/${r[0].modelId}`,providerId:r[0].providerId}}function findQualified(e,t){const n=t.indexOf("/");if(n<=0||n===t.length-1)return;const r=t.slice(0,n),o=t.slice(n+1),s=e.find(e=>e.id===r);if(!s)return;const i=s.models.find(e=>e.id.toLowerCase()===o.toLowerCase());return i?{modelId:`${s.id}/${i.id}`,providerId:s.id}:{modelId:t,providerId:s.id,warning:`"${o}" isn't declared under provider '${s.id}' in providers.json — sending it anyway. Declare it there to set its context window and options.`}}function isByok(e){const t=byokOwner(e.model);return void 0!==t&&(void 0===e.providerId||t===e.providerId)}function byokProviderId(e){return byokOwner(e.model)}function byokOwner(e){if(resolveKnownModelId2(e))return;const t=getCustomProviderModelsSync(),n=findQualified(t,e);return n?n.providerId:findDeclared(t,e)?.providerId}async function resolveSelectableModel(e){const t=e.trim();if(!t)return;const n=await loadCustomProviderModels(),r=resolveKnownModelId2(t);if(r)return{modelId:r};const o=t.indexOf("/");if(o>0){const e=t.slice(0,o).toLowerCase();if(n.some(t=>t.id===e))return findDeclared(n,t)??findQualified(n,t)}const s=resolveModelInput({model:t,models:getAllModelOptions()});return s?{modelId:s}:findDeclared(n,t)??findQualified(n,t)}function customProvidersDeclaring(e){const t=e.trim().toLowerCase();return getCustomProviderModelsSync().filter(e=>e.models.some(e=>e.id.toLowerCase()===t)).map(e=>e.id)}function customContextWindow(e){return declaredCustomModel(e)?.contextWindow}function customReasoningEfforts(e){return declaredCustomModel(e)?.reasoningEfforts}function declaredCustomModel(e){const t=getCustomProviderModelsSync(),n=findDeclared(t,e),r=n?void 0:findQualified(t,e),o=n??r;if(!o||o.warning)return;const s=t.find(e=>e.id===o.providerId);if(!s)return;const i=o.modelId.startsWith(`${s.id}/`)?o.modelId.slice(s.id.length+1):o.modelId;return s.models.find(e=>e.id===i)}function customAwareContextLimit(e){return customContextWindow(e.modelId)??e.fallback(e.modelId)}function customModelListOptions(){return getCustomProviderModelsSync().flatMap(e=>e.models.map(t=>({id:`${e.id}/${t.id}`,description:`${t.name??t.id} — ${e.name} (custom)`})))}function customModelListGroups(){return getCustomProviderModelsSync().filter(e=>e.models.length>0).map(e=>({label:`${e.name} (byok)`,models:e.models.map(t=>({id:`${e.id}/${t.id}`,description:t.name??t.id}))}))}function buildCustomModelPickerGroups(){return getCustomProviderModelsSync().map(e=>({provider:e,rows:e.models})).filter(({rows:e})=>e.length>0).map(({provider:e,rows:t})=>({providerId:e.id,label:`${e.name} (byok)`,models:t.map(t=>({id:`${e.id}/${t.id}`,provider:e.id,spec:"chatComplete",label:t.name??t.id,name:t.name??t.id,description:"",vendorLabel:e.name,...void 0!==t.contextWindow?{contextWindow:t.contextWindow}:{},...void 0!==t.reasoningEfforts?{reasoning:!0,reasoningEfforts:t.reasoningEfforts}:{}}))}))}__name(loadFromConfig,"loadFromConfig"),__name(diskLoadsBlocked,"diskLoadsBlocked"),__name(loadCustomProviderModels,"loadCustomProviderModels"),__name(loadIntoCache,"loadIntoCache"),__name(refreshCustomProviderModels,"refreshCustomProviderModels"),__name(seedSnapshotSync,"seedSnapshotSync"),__name(getCustomProviderModelsSync,"getCustomProviderModelsSync"),__name(getCustomProviderWarningsSync,"getCustomProviderWarningsSync"),__name(findDeclared,"findDeclared"),__name(findQualified,"findQualified"),__name(isByok,"isByok"),__name(byokProviderId,"byokProviderId"),__name(byokOwner,"byokOwner"),__name(resolveSelectableModel,"resolveSelectableModel"),__name(customProvidersDeclaring,"customProvidersDeclaring"),__name(customContextWindow,"customContextWindow"),__name(customReasoningEfforts,"customReasoningEfforts"),__name(declaredCustomModel,"declaredCustomModel"),__name(customAwareContextLimit,"customAwareContextLimit"),__name(customModelListOptions,"customModelListOptions"),__name(customModelListGroups,"customModelListGroups"),__name(buildCustomModelPickerGroups,"buildCustomModelPickerGroups"),Gt(),Gt(),Gt(),SR(),Gt(),Gt();var A$=__name(({label:e="Loading",spinner:t=!1})=>st.createElement(Xe,{color:ER.DIM},t&&st.createElement(st.Fragment,null,st.createElement(kt,{type:"dots"})," "),e,"…"),"LoadingLine"),R$=__name(({children:e,glyph:t=!0})=>st.createElement(Xe,{color:ER.RED},t&&`${gt.cross} `,e),"ErrorLine"),L$=__name(({children:e,glyph:t=!0})=>st.createElement(Xe,{color:ER.GREEN},t&&`${gt.tick} `,e),"SuccessLine"),O$=__name(({title:e="Oops, something went wrong:",children:t})=>st.createElement(Qe,{flexDirection:"column",borderStyle:"single",borderColor:ER.RED,paddingX:2,paddingY:1,marginTop:1},st.createElement(Xe,{color:ER.RED,bold:!0},e),st.createElement(Qe,{marginTop:1},st.createElement(Xe,null,t))),"ErrorPanel"),D$=__name(({message:e,hint:t})=>st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.GRAY},e),t?st.createElement(Xe,{color:ER.DIM},t):null),"EmptyState"),$$=__name(({error:e,traceId:t})=>st.createElement(Qe,{marginBottom:2},st.createElement(O$,null,e,t&&st.createElement(Xe,{color:ER.DIM},"\n\n","Trace ID: ",t))),"ErrorSection");async function runTasteImport(e={}){const t=await runOnboardingImportWithEvents({events:ip,signal:e.signal,onDebug:__name(e=>dlog(e),"onDebug"),runOnboarding:__name(async e=>(await createHarnessSession({sessionId:`taste-onboarding-${crypto.randomUUID()}`,baseUrl:getApiBaseUrl()})).runTasteOnboarding(e),"runOnboarding")});return{success:t.success,totalPrompts:t.totalPrompts,preferencesLearned:t.preferencesLearned,errors:[...t.errors],status:t.status,totalSessions:t.totalSessions,learnedSessions:t.learnedSessions,agentSessions:t.agentSessions?.map(e=>({agent:e.agent,sessionIds:[...e.sessionIds],displayName:e.displayName}))}}Gt(),Gt(),SR(),Gt(),SR(),__name(runTasteImport,"runTasteImport");var N$={isImporting:!1,waitingForInput:!1,error:null},_$=__name(e=>{const t=lt(null),n=lt(e);n.current=e;const[r,o]=at({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null}),s=ut(()=>{const e=t.current;!e||e.isAborted()||(e.finishCancelled(),o(e=>({...e,...N$})))},[]);return ct(()=>{const e=createOnboardingImportLifecycle({events:ip});t.current=e;let r=!1;return(async()=>{try{const t=await e.race(runTasteImport({signal:e.signal}));if(e.isAborted())return;if("cancelled"===t.status)return void o(e=>({...e,...N$}));if(t.success)return void o(e=>({...e,isImporting:!1,waitingForInput:!0}));if("already-learned"===t.status)return void o(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");o(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),n.current&&n.current(r)}catch(t){if(e.isAborted())return;const r=e.handleFailure(t);o(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),n.current&&n.current(r)}finally{e.dispose(),r=!0}})(),()=>{e.dispose(),r||e.finishCancelled(),t.current===e&&(t.current=null)}},[]),{...r,cancelImport:s}},"useImportProcess");Gt();var F$,U$,j$=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{nt((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");function getRuntime(){return F$??=createNodeRuntime()}function getStore(){return U$??=createOnboardingStore({runtime:getRuntime()})}async function checkOnboardingConditions2(){const e=await checkOnboardingConditions({runtime:getRuntime(),store:getStore()});return{shouldTrigger:e.shouldTrigger,reason:e.reason,sessionCount:e.sessionCount,hasTasteContent:e.hasTasteContent,agentSessions:e.agentSessions.map(e=>({agent:e.agent,sessionIds:[...e.sessionIds],displayName:e.displayName}))}}async function markOnboardingCompleted(){await getStore().markCompleted()}async function markOnboardingSkipped2(){await markOnboardingSkipped({runtime:getRuntime(),store:getStore()})}async function dismissOnboardingForeverForProject(){await getStore().dismissForever()}async function triggerTasteOnboarding({projectTrusted:e,onboardingComplete:t,isOnboardingMode:n,tasteOnboardingCheckedRef:r,setIsOnboardingMode:o}){if(e)if(t)dlog("[Onboarding] skipped - already completed");else if(n)dlog("[Onboarding] skipped - already showing");else if(r.current)dlog("[Onboarding] skipped - already checked this session");else{r.current=!0,dlog("[Onboarding] checking if taste learning should start...");try{const e=await checkOnboardingConditions2();if(!e.shouldTrigger)return void dlog("[Onboarding] not needed");dlog(`[Onboarding] starting taste learning (${e.reason})`),o(!0)}catch(e){dlog("[Onboarding] error",e)}}else dlog("[Onboarding] skipped - project not yet trusted")}Gt(),SR(),Gt(),SR(),__name(getRuntime,"getRuntime"),__name(getStore,"getStore"),__name(checkOnboardingConditions2,"checkOnboardingConditions"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(markOnboardingSkipped2,"markOnboardingSkipped"),__name(dismissOnboardingForeverForProject,"dismissOnboardingForeverForProject"),__name(triggerTasteOnboarding,"triggerTasteOnboarding");var B$=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=at(null),[o,s]=at(null),[i,a]=at(void 0),l=lt(!1);return ct(()=>{if(l.current)return;let n=null;return(async()=>{try{l.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions2();if(r(n),!n.shouldTrigger&&!e)return dlog("[Hook:Conditions] no trigger, skipping"),void t();dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`)}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r);const o=trackError({error:e instanceof Error?e:new Error(r),context:{component:Ho.LEARN_TASTE_COMMAND,heading:"Onboarding conditions check failed"}});a(o),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,traceId:i,isLoading:!n&&!o}},"useOnboardingConditions");Gt(),SR();var W$=__name(({conditions:e,autoLearn:t})=>{const[n,r]=at("checking"),o=lt(!1);return ct(()=>{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]),ct(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");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{ip.reset(),e()}}async function skipOnboarding(e){try{await markOnboardingSkipped2(),dlog("[Helper] onboarding marked skipped")}catch(e){dlog(`[Helper] skip error: ${e instanceof Error?e.message:String(e)}`)}finally{ip.reset(),e()}}Gt(),SR(),Gt(),SR(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var H$=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=lt(n),o=ut(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=ut(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=ut(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=ut(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=ut(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");Gt(),SR();var G$=__name(e=>{const[t,n]=at(()=>createTasteImportProjection({initialSteps:e})),r=ut(e=>{n(t=>({...t,importError:e}))},[]);return ct(()=>{const t=__name(()=>{n(resetTasteImportProjection({initialSteps:e}))},"handleReset"),r=__name(e=>{n(t=>reduceTasteImportEvent({state:t,event:e}))},"handleNewEvent");return ip.on("reset",t),ip.on("new-event",r),()=>{ip.off("reset",t),ip.off("new-event",r)}},[e]),{steps:t.steps,importError:t.importError,importTraceId:t.importTraceId,setImportError:r}},"useProgressEvents");Gt(),Gt(),Gt();var V$=__name(({isImporting:e=!1,waitingForInput:t=!1})=>st.createElement(st.Fragment,null,e&&st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Esc to cancel")),t&&st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to continue"))),"HelpTextSection");Gt(),Gt(),Gt(),Gt();var z$=__name(()=>{const[e,t]=at(!0);return ct(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),st.createElement(Xe,{color:ER.YELLOW},e?gt.circleFilled:gt.circle)},"PulsingDot");Gt();var K$=[gt.bullet,gt.squareSmallFilled,gt.lozenge,gt.star,gt.triangleRight,gt.triangleUp,gt.circleFilled,gt.pointer],q$=__name(e=>String(e).padStart(3," "),"padNum"),Y$=__name(e=>K$[e%K$.length],"getSymbol"),J$=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${q$(t)} ↓${q$(n)} (↑↓ scroll)`,"buildStatusLine"),Q$=__name(({insights:e})=>{const[t,n]=at(0),[r,o]=at(!0),s=e.length,i=s>10,a=Math.max(0,s-10),l=r&&i?a:t;if(nt((e,t)=>{if(i){if(t.upArrow)return o(!1),void n(Math.max(0,l-1));if(t.downArrow){const e=Math.min(a,l+1);o(e===a),n(e)}}}),0===s)return null;const c=e.slice(l,l+10),d=l,u=s-l-10;return st.createElement(Qe,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&st.createElement(Xe,{color:ER.DIM},J$(s,d,u,r)),c.map((e,t)=>{const n=l+t;return st.createElement(Qe,{key:n,marginBottom:0},st.createElement(Xe,{color:ER.DIM},Y$(n)," ",e))}))},"ScrollableInsights");function getLabelColor(e,t){return e?ER.WHITE:t?ER.YELLOW:ER.DIM}function formatCategorySuffix(e){if(0===e.length)return"";const t=1===e.length?"category":"categories";return` across ${e.length} ${t}`}__name(getLabelColor,"getLabelColor"),__name(formatCategorySuffix,"formatCategorySuffix");var X$=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:i,isAllComplete:a,summary:l,warning:c})=>{if(i)return st.createElement(Qe,{flexDirection:"column",marginBottom:0},st.createElement(kL,null),st.createElement(Qe,{marginTop:0},st.createElement(Xe,{color:ER.DIM},yL),st.createElement(Qe,{marginLeft:2},a?st.createElement(Xe,{color:PR.TEXT},"learned your coding taste"):st.createElement(mL,null))));const d=__name(()=>r?st.createElement(Xe,{color:AR.BG},gt.square):n?st.createElement(z$,null):st.createElement(Xe,{color:ER.DIM},gt.circle),"getStatusIcon"),u=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||u?st.createElement(Qe,{flexDirection:"column",marginBottom:0},(n||r)&&st.createElement(Qe,{marginBottom:0},st.createElement(Qe,{marginRight:1},d()),st.createElement(Xe,{color:getLabelColor(r,n)},e)),r&&t&&(!l||0===l.learningCount)&&st.createElement(Qe,{marginLeft:3,marginBottom:0},st.createElement(Xe,{color:ER.DIM},t)),o.length>0&&st.createElement(Qe,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map(e=>st.createElement(Xe,{key:e,color:ER.DIM},`${gt.bullet} ${e}`))),s.length>0&&st.createElement(Q$,{insights:s}),r&&l&&l.learningCount>0&&st.createElement(Qe,{flexDirection:"column",marginLeft:1,marginBottom:0},st.createElement(Qe,{marginBottom:1,flexDirection:"row"},st.createElement(Xe,null,yL),st.createElement(Qe,{marginLeft:2},st.createElement(Xe,{color:PR.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",formatCategorySuffix(l.categories)))),st.createElement(Qe,{flexDirection:"column",marginLeft:1},st.createElement(Xe,{color:ER.DIM},gt.pointerSmall," Stored in ",l.storage),st.createElement(Xe,{color:ER.DIM},"Command Code automatically uses & updates taste files."))),r&&c&&st.createElement(Qe,{flexDirection:"column",marginLeft:1,marginBottom:0},c.split("\n").map(e=>st.createElement(Xe,{key:e,color:ER.YELLOW},`${gt.warning} ${e}`)))):null},"StepItem"),Z$=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return st.createElement(Qe,{flexDirection:"column",marginBottom:1},e.map((e,n)=>st.createElement(Qe,{key:e.id,marginLeft:0===n?0:3},st.createElement(X$,{label:e.label,message:e.message,active:e.active,complete:e.complete,items:e.items,insights:e.insights,summary:e.summary,warning:e.warning,isIntro:0===n,isAllComplete:t}))))},"StepsSection"),eN=__name(({steps:e})=>st.createElement(Z$,{steps:e}),"ProgressSection"),tN=__name(({onComplete:e,onCancel:t,onError:n,onErrorDismiss:r})=>{const{steps:o,importError:s,importTraceId:i}=G$(RI),{isImporting:a,waitingForInput:l,error:c,cancelImport:d}=_$(n);return j$({onEscape:__name(()=>{if(a)return d(),void t?.();l&&((c||s)&&r?r():e())},"onEscape"),onEnter:__name(()=>{l&&((c||s)&&r?r():e())},"onEnter"),enabled:a||l}),st.createElement(Qe,{flexDirection:"column",padding:1},s&&st.createElement($$,{error:s,traceId:i}),!s&&st.createElement(eN,{steps:o}),st.createElement(V$,{isImporting:a,waitingForInput:l}))},"ImportProgress");async function runLearnTaste(){await applyStartupTheme();const{unmount:e}=tt(st.createElement(tN,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onCancel:__name(()=>{e(),process.exit(0)},"onCancel"),onErrorDismiss:__name(()=>{e(),process.exit(1)},"onErrorDismiss")}))}__name(runLearnTaste,"runLearnTaste");var nN=new Be("learn-taste").description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{if(await loadCustomProviderModels(),isByok({model:getConfiguredModel()??""}))return console.log(lg),void await shutdownTelemetry();await runLearnTaste()}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:Ho.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 getBinNames(){const e=getPackageJson(import.meta.url);return e.bin&&"object"==typeof e.bin?Object.keys(e.bin):e.bin&&"string"==typeof e.bin?[e.name??getBinaryCommand()]:[getBinaryCommand()]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||getBinaryCommand();const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||getBinaryCommand()}catch{return getBinaryCommand()}}function addMcpCommand(){const e=new Be("add");return e.description("Add an MCP server").argument("<name>","Server name (unique identifier)").argument("[url]","Server URL (required for http transport)").option("-t, --transport <type>","Transport type (stdio or http)","stdio").addOption(new We("-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{const s=await addMcpServerFromCliInput({name:e,url:t,transport:n.transport,scope:n.scope,env:n.env,headers:n.header,rawArgs:r.args,argv:process.argv,cliName:o,addMcpServer:addMcpServer,checkServerAuthRequirements:__name(async e=>{console.log(ht.gray("Checking server authentication requirements..."));const t=await checkCommandMcpServerAuthRequirements(e);return t.requiresAuth&&console.log(ht.cyan("Server requires OAuth authentication.")),t},"checkServerAuthRequirements"),registerOAuthClient:__name(async e=>(console.log(ht.gray("Registering OAuth client...")),registerCommandMcpOAuthClient({registrationEndpoint:e.registrationEndpoint,clientName:e.clientName,redirectUris:[...e.redirectUris]})),"registerOAuthClient"),performOAuthFlow:__name(async e=>{console.log(ht.gray("A browser window will open for authentication.\n"));const t=await performCommandMcpOAuthFlow(e.serverName,e.serverUrl,{authorizationUrl:e.config.authorizationUrl,tokenUrl:e.config.tokenUrl,clientId:e.config.clientId,clientSecret:e.config.clientSecret,scopes:e.config.scopes?[...e.config.scopes]:void 0,resource:e.config.resource},{onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),onStatus:__name(e=>{console.log(ht.gray(` ${e}`))},"onStatus")});for(const e of s.warnings)console.log(ht.yellow(`Warning: ${e}`));"success"===s.authStatus&&console.log(ht.green("✓ Successfully authenticated")),"failed"===s.authStatus&&(console.log(ht.yellow(`Warning: Authentication failed: ${s.authError}`)),console.log(ht.gray(`You can retry with: ${getBinaryCommand()} mcp auth ${e}`)),console.log(ht.gray("Or authenticate via the /mcp menu in a session")));const i="failed"===s.authStatus?`✓ Added MCP server '${e}' to ${s.scopeLabel} config (authentication pending)`:`✓ Added MCP server '${e}' to ${s.scopeLabel} config`;console.log("failed"===s.authStatus?ht.yellow(i):ht.green(i)),console.log(ht.gray(` ${formatMcpCommandSummary(s.serverConfig)}`)),console.log(""),console.log(ht.cyan("Next steps:")),console.log(ht.gray(`Start ${o} and run /mcp to manage configured MCP servers.`))}catch(e){printMcpAddError(e,{cliName:o}),process.exit(1)}}),e}function printMcpAddError(e,t){if(e instanceof IT)if(console.error(ht.red(`Error: ${e.message}`)),"invalid-name"!==e.code)if("invalid-transport"!==e.code){if("missing-http-url"!==e.code)return"missing-stdio-command"===e.code?(console.error(ht.gray(`Usage: ${t.cliName} mcp add --transport stdio <name> -- <command> [args...]`)),void console.error(ht.gray(` or: ${t.cliName} mcp add <name> <command> [args...]`))):void("stdio-command-is-url"!==e.code?"insecure-oauth-url"===e.code&&(console.error(ht.gray("OAuth requires https:// (http:// is only allowed for loopback hosts: localhost, 127.0.0.1, [::1]).")),console.error(ht.gray("Switch the URL to https:// or use a non-OAuth server."))):e.suggestedCommand&&console.error(ht.gray(`Did you mean: ${e.suggestedCommand}`)));console.error(ht.gray(`Usage: ${t.cliName} mcp add --transport http <name> <url>`))}else console.error(ht.gray("Valid options: stdio, http"));else console.error(ht.gray(xT));else console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function collectKeyValue(e,t){try{return addMcpKeyValue(e,t)}catch(e){printCollectError(e),process.exit(1)}}function collectHeaders(e,t){try{return addMcpHeader(e,t)}catch(e){printCollectError(e),process.exit(1)}}function printCollectError(e){console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function addJsonMcpCommand(){const e=new Be("add-json");return e.description("Add an MCP server from JSON configuration").argument("<name>","Server name (unique identifier)").argument("<json>","Server configuration as JSON string").addOption(new We("-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{const o=await addMcpServerFromJson({name:e,json:t,scope:n.scope,clientSecret:n.clientSecret,addMcpServer:addMcpServer,performOAuthFlow:__name(async e=>{console.log(ht.cyan("Starting OAuth authentication...")),console.log(ht.gray("A browser window will open for authentication.\n"));const t=await performCommandMcpOAuthFlow(e.serverName,e.serverUrl,{authorizationUrl:e.config.authorizationUrl,tokenUrl:e.config.tokenUrl,clientId:e.config.clientId,clientSecret:e.config.clientSecret,scopes:e.config.scopes?[...e.config.scopes]:void 0,resource:e.config.resource},{port:e.port,onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),onStatus:__name(e=>{console.log(ht.gray(` ${e}`))},"onStatus")});"success"===o.authStatus&&console.log(ht.green(`\n✓ Successfully authenticated with '${e}'`)),"failed"===o.authStatus&&(console.error(ht.yellow(`\nWarning: Authentication failed: ${o.authError}`)),console.error(ht.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(ht.gray("Or authenticate via the /mcp menu in a session")));const s="failed"===o.authStatus?`✓ Added MCP server '${e}' to ${o.scopeLabel} config (authentication pending)`:`✓ Added MCP server '${e}' to ${o.scopeLabel} config`;console.log("failed"===o.authStatus?ht.yellow(s):ht.green(s)),console.log(ht.gray(` ${formatMcpCommandSummary(o.serverConfig)}`)),console.log(""),console.log(ht.cyan("Next steps:")),console.log(ht.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){printMcpAddJsonError(e,{cliName:r}),process.exit(1)}}),e}function printMcpAddJsonError(e,t){if(e instanceof IT)if(console.error(ht.red(`Error: ${e.message}`)),"invalid-name"!==e.code){if("invalid-json"===e.code)return console.error(ht.gray("Make sure to quote the JSON string properly")),void console.error(ht.gray(`Example: ${t.cliName} mcp add-json github '{"type":"stdio","command":"npx"}'`));if("invalid-config"===e.code&&e.issues)for(const t of e.issues)console.error(ht.gray(` ${t.path.join(".")}: ${t.message}`));else"missing-http-url"!==e.code&&e.code}else console.error(ht.gray(xT));else console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function authMcpCommand(){const e=new Be("auth");return e.description("Manage OAuth authentication for MCP servers").argument("[server]","Server name to authenticate").option("--status","Check authentication status").option("--clear","Clear stored authentication").option("--list","List servers with stored authentication").action(async(e,t)=>{const n=getInvokedCommandName();try{if(t.list)return void await printAuthList();if(e||(console.error(ht.red("Error: Server name is required")),console.error(ht.gray(`Usage: ${n} mcp auth <server>`)),console.error(ht.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status)return void await printAuthStatus(e);if(t.clear)return(await clearMcpAuth({serverName:e,deleteTokens:deleteTokens})).deleted?void console.log(ht.green(`✓ Cleared authentication for '${e}'`)):void console.log(ht.yellow(`No authentication stored for '${e}'`));console.log(ht.cyan(`Authenticating with '${e}'...`)),console.log(ht.gray("A browser window will open for authentication.\n")),await authenticateConfiguredMcpServer({serverName:e,getMcpServer:getMcpServer,performOAuthFlow:__name(async e=>{const t=await performCommandMcpOAuthFlow(e.serverName,e.serverUrl,{authorizationUrl:e.config.authorizationUrl,tokenUrl:e.config.tokenUrl,clientId:e.config.clientId,clientSecret:e.config.clientSecret,scopes:e.config.scopes?[...e.config.scopes]:void 0,resource:e.config.resource},{onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),discoverAndAuthenticate:discoverAndAuthenticateCommandMcpServer,onStatus:__name(e=>{console.log(ht.gray(` ${e}`))},"onStatus")}),console.log(ht.green(`\n✓ Successfully authenticated with '${e}'`)),console.log(ht.gray("Restart the session to connect with the authenticated server."))}catch(t){printMcpAuthError(t,{cliName:n,serverName:e}),process.exit(1)}}),e}async function printAuthList(){const e=await listMcpAuthStatuses({listServersWithTokens:listServersWithTokens,getTokens:getTokens,isTokenExpired:isTokenExpired});if(0!==e.length){console.log(ht.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=t.expired?ht.yellow("expired"):ht.green("valid");console.log(` ${t.serverName}: ${e}`)}console.log("")}else console.log(ht.yellow("No servers with stored authentication."))}async function printAuthStatus(e){const t=await getMcpAuthStatus({serverName:e,hasTokens:hasTokens,getTokens:getTokens,isTokenExpired:isTokenExpired});if("missing"!==t.status){if("expired"===t.status)return console.log(ht.yellow(`Authentication for '${e}' has expired`)),void(t.hasRefreshToken&&console.log(ht.gray(" A refresh token is available for re-authentication")));console.log(ht.green(`Authentication for '${e}' is valid`)),"number"==typeof t.expiresInMinutes&&console.log(ht.gray(` Expires in ${t.expiresInMinutes} minutes`)),t.scope&&console.log(ht.gray(` Scopes: ${t.scope}`))}else console.log(ht.yellow(`No authentication stored for '${e}'`))}function printMcpAuthError(e,t){if(e instanceof IT)return"server-not-found"===e.code?(console.error(ht.red(`Error: ${e.message}`)),void console.error(ht.gray(`Use "${t.cliName} mcp list" to see configured servers`))):"auth-failed"===e.code?(console.error(ht.red(`\nError: ${e.message}`)),void(t.serverName&&console.log(ht.gray(`Try again with "${t.cliName} mcp auth ${t.serverName}"`)))):void console.error(ht.red(`Error: ${e.message}`));console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function getMcpCommand(){const e=new Be("get");return e.description("Show details for an MCP server").argument("<name>","Server name").action(async e=>{try{const t=await getMcpServerDetails({name:e,getMcpServer:getMcpServer}),{config:n,scope:r}=t;if(console.log(ht.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${ht.dim("Scope:")} ${r}`),console.log(` ${ht.dim("Transport:")} ${n.transport}`),console.log(` ${ht.dim("Status:")} ${n.enabled?ht.green("enabled"):ht.gray("disabled")}`),"http"===n.transport){if(console.log(` ${ht.dim("URL:")} ${n.url}`),t.headers.length>0){console.log(` ${ht.dim("Headers:")}`);for(const e of t.headers)console.log(` ${e.key}: ${e.value}`)}}else console.log(` ${ht.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${ht.dim("Args:")} ${n.args.join(" ")}`);if(t.env.length>0){console.log(` ${ht.dim("Environment:")}`);for(const e of t.env)console.log(` ${e.key}=${e.value}`)}console.log("")}catch(e){e instanceof IT&&(console.error(ht.red(`Error: ${e.message}`)),process.exit(1)),console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function formatAuthIcon(e){return"authenticated"===e||"static"===e?ht.green(gt.tick):"missing"===e?ht.red(gt.cross):ht.gray("-")}function listMcpCommand(){const e=new Be("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServerSummaries({listMcpServers:listMcpServers,hasTokens:hasTokens});if(0===e.length)return console.log(ht.yellow("\nNo MCP servers configured\n")),console.log(ht.gray("Add a server with:")),console.log(ht.gray(` ${getBinaryCommand()} mcp add --transport http <name> <url>`)),console.log(ht.gray(` ${getBinaryCommand()} mcp add --transport stdio <name> -- <command>`)),void console.log(ht.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(ht.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(ht.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.enabled?ht.green("enabled"):ht.gray("disabled"),s=formatAuthIcon(o.authStatus);console.log(` ${ht.white(o.name.padEnd(t))} ${ht.cyan(o.transport.padEnd(n))} ${ht.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(ht.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new Be("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new We("-s, --scope <scope>","Scope to remove from (auto-detects if not specified)").choices(["local","project","user"])).action(async(e,t)=>{try{const n=await removeMcpServerByName({name:e,scope:t.scope,getMcpServer:getMcpServer,removeMcpServer:removeMcpServer});console.log(ht.green(`✓ Removed MCP server '${e}' from ${n.scopeLabel} config`))}catch(e){e instanceof IT&&(console.error(ht.red(`Error: ${e.message}`)),process.exit(1)),console.error(ht.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new Be("mcp");return e.description("Manage MCP (Model Context Protocol) servers").allowUnknownOption().allowExcessArguments(),e.addCommand(addMcpCommand()),e.addCommand(listMcpCommand()),e.addCommand(getMcpCommand()),e.addCommand(removeMcpCommand()),e.addCommand(addJsonMcpCommand()),e.addCommand(authMcpCommand()),e}function shortenModPath(e,t){if(t){const n=i(t,e);if(n&&!n.startsWith("..")&&!a(n))return n}const n=i(W(),e);return!n||n.startsWith("..")||a(n)?e:`~${l}${n}`}Gt(),Gt(),SR(),Gt(),SR(),__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),__name(addMcpCommand,"addMcpCommand"),__name(printMcpAddError,"printMcpAddError"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),__name(printCollectError,"printCollectError"),Gt(),SR(),__name(addJsonMcpCommand,"addJsonMcpCommand"),__name(printMcpAddJsonError,"printMcpAddJsonError"),Gt(),SR(),__name(authMcpCommand,"authMcpCommand"),__name(printAuthList,"printAuthList"),__name(printAuthStatus,"printAuthStatus"),__name(printMcpAuthError,"printMcpAuthError"),Gt(),SR(),__name(getMcpCommand,"getMcpCommand"),Gt(),SR(),__name(formatAuthIcon,"formatAuthIcon"),__name(listMcpCommand,"listMcpCommand"),Gt(),SR(),__name(removeMcpCommand,"removeMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Gt(),Gt(),SR(),Gt(),SR(),__name(shortenModPath,"shortenModPath");var rN=__name(e=>e.split(W()).join("~"),"shortenHomeInText");async function createModPathShortener(e){const t=await modsDirectoryPath({runtime:e,scope:"project"}),n=t?s(t,"..",".."):void 0;return e=>shortenModPath(e,n)}async function addAction(e,t){const n=createNodeRuntime(),r=t.global?"user":"project";try{const t=parseModSource(e);console.log(Et.dim(`Installing ${t.kind} mod source ${Et.reset(Et.cyan(e))} (${r})…`));const o=await installModSource({runtime:n,source:e,scope:r}),s=await createModPathShortener(n);console.log(`${Et.green(gt.tick)} Installed ${Et.cyan(o.identity)}`),o.installedPath&&console.log(Et.dim(` ${s(o.installedPath)}`)),console.log(Et.dim(` Recorded in ${s(o.settingsPath)}`))}catch(e){console.error(`${Et.red(gt.cross)} ${rN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}__name(createModPathShortener,"createModPathShortener"),__name(addAction,"addAction");var oN=new Be("add").alias("install").description("Install a mod package (<npm-name>, owner/repo[@ref], or a local path)").argument("<source>","mod source: an npm package name, a git repo (owner/repo[@ref]), or a local path").option("-g, --global","install for all projects (user scope)").action(addAction);Gt(),SR(),Gt(),Gt(),Gt();var sN={running:0,waitingPermission:0,waitingQuestion:0,compacting:0};function bump(e,t){return Math.max(0,e+t)}function nextLifecycle(e,t){return"run_start"===t.type?{...e,running:e.running+1}:"run_end"===t.type?{...e,running:bump(e.running,-1)}:"compaction_start"===t.type?{...e,compacting:e.compacting+1}:"compaction_done"===t.type?{...e,compacting:bump(e.compacting,-1)}:"interaction_requested"===t.type?"permission"===t.kind?{...e,waitingPermission:e.waitingPermission+1}:{...e,waitingQuestion:e.waitingQuestion+1}:"interaction_resolved"===t.type?"permission"===t.kind?{...e,waitingPermission:bump(e.waitingPermission,-1)}:{...e,waitingQuestion:bump(e.waitingQuestion,-1)}:e}function reportFor(e){return e.waitingPermission>0?{state:"blocked",message:"permission"}:e.waitingQuestion>0?{state:"blocked",message:"question"}:e.running>0||e.compacting>0?{state:"working"}:{state:"idle"}}function reportKey(e){return`${e.state}:${e.message??""}`}__name(bump,"bump"),__name(nextLifecycle,"nextLifecycle"),__name(reportFor,"reportFor"),__name(reportKey,"reportKey"),Gt(),Gt();var iN=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`,"g");function sanitizeTitleForOutput(e){const t=e.replace(iN,"");let n="";for(const e of t){const t=e.codePointAt(0)??0;n+=t<=31||t>=127&&t<=159?" ":e}return n.replace(/\s{2,}/g," ").trim()}__name(sanitizeTitleForOutput,"sanitizeTitleForOutput");var aN="cmd",lN=`custom:${aN}`,cN="CMD_HERDR_PANE_OWNER";function resolveHerdrConfig(e){const t=e.CMD_HERDR?.trim().toLowerCase();if("0"===t||"false"===t)return null;if("1"!==e.HERDR_ENV?.trim())return null;if(e[cN])return null;const n=e.HERDR_SOCKET_PATH?.trim(),r=e.HERDR_PANE_ID?.trim();return n&&r?{socketPath:n,paneId:r}:null}function releasedPaneOwnerEnv(e,t){return e[cN]===String(t)?{[cN]:void 0}:{}}function claimHerdrPane(e){e[cN]=String(process.pid)}function clampBytes(e,t){if(!e)return;const n=sanitizeTitleForOutput(e);return n?Buffer.from(n,"utf-8").subarray(0,t).toString("utf-8").replace(/�$/,""):void 0}function clampText(e){if(!e)return;const t=sanitizeTitleForOutput(e);if(!t)return;const n=Array.from(t);return n.length<=80?t:n.slice(0,80).join("")}function metadataParams(e){const t=clampText(e.title),n=clampText(e.displayAgent),r=Object.fromEntries(Object.entries(e.tokens??{}).flatMap(([e,t])=>{const n=clampText(t);return n?[[e,n]]:[]}));return{...t?{title:t}:{},...!t&&e.clearTitle?{clear_title:!0}:{},...n?{display_agent:n}:{},...Object.keys(r).length>0?{tokens:r}:{}}}function buildHerdrLine(e){const{id:t,seq:n,paneId:r,request:o}=e,s={id:String(t)},i={pane_id:r,source:lN,agent:aN,seq:n};if("report"===o.kind){const e=clampBytes(o.message,32);return`${JSON.stringify({...s,method:"pane.report_agent",params:{...i,state:o.state,...e?{message:e}:{}}})}\n`}return"session"===o.kind?`${JSON.stringify({...s,method:"pane.report_agent_session",params:{...i,agent_session_id:o.sessionId}})}\n`:"metadata"===o.kind?`${JSON.stringify({...s,method:"pane.report_metadata",params:{...i,...metadataParams(o.metadata)}})}\n`:"paneRename"===o.kind?`${JSON.stringify({...s,method:"pane.rename",params:{pane_id:r,label:o.label}})}\n`:"agentRename"===o.kind?`${JSON.stringify({...s,method:"agent.rename",params:{target:r,name:o.name}})}\n`:`${JSON.stringify({...s,method:"pane.release_agent",params:i})}\n`}function herdrSocketEndpoint(e){const{socketPath:t,platform:n=process.platform}=e;return"win32"===n?`\\\\.\\pipe\\${t}`:t}function sendHerdrLine(e){const t=e.timeoutMs??250;return new Promise(n=>{let r=!1;const o=he.createConnection(herdrSocketEndpoint({socketPath:e.socketPath})),s=__name(()=>{r||(r=!0,clearTimeout(i),o.destroy(),n())},"finish"),i=setTimeout(s,t);i.unref?.(),o.setEncoding("utf-8"),o.on("connect",()=>{o.write(e.line)}),o.on("data",e=>{e.includes("\n")&&s()}),o.on("error",s),o.on("close",s)})}__name(resolveHerdrConfig,"resolveHerdrConfig"),__name(releasedPaneOwnerEnv,"releasedPaneOwnerEnv"),__name(claimHerdrPane,"claimHerdrPane"),__name(clampBytes,"clampBytes"),__name(clampText,"clampText"),__name(metadataParams,"metadataParams"),__name(buildHerdrLine,"buildHerdrLine"),__name(herdrSocketEndpoint,"herdrSocketEndpoint"),__name(sendHerdrLine,"sendHerdrLine");var dN={enabled:!1,reportState:__name(()=>{},"reportState"),reportSession:__name(()=>{},"reportSession"),reportMetadata:__name(()=>{},"reportMetadata"),announce:__name(()=>{},"announce"),release:__name(()=>Promise.resolve(),"release")};function createHerdrReporter(e){const{config:t}=e;if(!t)return dN;const n=e.send??sendHerdrLine,r=e.now??Date.now;let o=1,s=1e3*r(),i=Promise.resolve(),a=0;const l=__name(e=>{const n=o;return o+=1,s+=1,buildHerdrLine({id:n,seq:s,paneId:t.paneId,request:e})},"nextLine"),c=__name(e=>{const r=l(e),o=a;return i=i.then(()=>o!==a?Promise.resolve():n({socketPath:t.socketPath,line:r})).catch(()=>{}),i},"enqueue");return{enabled:!0,reportState:__name((e,t)=>{c({kind:"report",state:e,message:t})},"reportState"),reportSession:__name(e=>{e&&c({kind:"session",sessionId:e})},"reportSession"),reportMetadata:__name(e=>{c({kind:"metadata",metadata:e})},"reportMetadata"),announce:__name(()=>{c({kind:"paneRename",label:aN}),c({kind:"agentRename",name:aN})},"announce"),release:__name(()=>{const e=l({kind:"release"});return a+=1,n({socketPath:t.socketPath,line:e}).catch(()=>{})},"release")}}__name(createHerdrReporter,"createHerdrReporter");var uN=["run_start","run_end","interaction_requested","interaction_resolved","compaction_start","compaction_done"];function isHostEvent(e){return"session_start"===e.type||"session_shutdown"===e.type}function createHerdrMod(e={}){return t=>{const n=e.env??process.env,r=void 0!==e.config?e.config:resolveHerdrConfig(n),o=e.reporter??createHerdrReporter({config:r});r&&claimHerdrPane(n);let s=sN,i=null,a=null,l=null,c=null;if(t.addCommand({name:"herdr",description:"Show herdr reporting status for this pane",handler:__name(()=>{if(!o.enabled)return{message:["herdr: not reporting.","This session was not launched by herdr (HERDR_ENV, HERDR_SOCKET_PATH and","HERDR_PANE_ID must all be set), or CMD_HERDR=0 disabled it."].join("\n")};const e=reportFor(s);return{message:[`herdr: reporting to pane ${r?.paneId??"unknown"}`,` state ${e.state}${e.message?` (${e.message})`:""}`,` session ${a??"not yet started"}`,` model ${l??"not yet requested"}`,"","Control herdr from here — split panes, start other agents,","wait for them to finish:"," npx skills add herdrdev/herdr --skill herdr"].join("\n")}},"handler")}),!o.enabled)return;const d=__name(()=>{const e=reportFor(s),t=reportKey(e);t!==i&&(i=t,o.reportState(e.state,e.message))},"flushState"),u=__name(()=>{o.reportMetadata({...c?{title:c}:{clearTitle:!0},displayAgent:l?`cmd · ${l}`:"cmd",...l?{tokens:{model:l}}:{}})},"flushMetadata"),m=__name(e=>{e&&e!==a&&(a=e,o.reportSession(a))},"reportSessionOnce");t.hooks({onSessionStart:__name(({sessionId:e})=>{s=sN,i=null,a=null,l=null,c=null,o.announce(),m(e),u(),d()},"onSessionStart"),onSessionEnd:__name(()=>o.release(),"onSessionEnd")});for(const e of uN)t.on(e,e=>{isHostEvent(e)||(s=nextLifecycle(s,e),"run_start"===e.type&&m(e.sessionId),d())});t.on("session_titled",e=>{"session_titled"===e.type&&e.title!==c&&(c=e.title,u())}),t.on("model_request_start",e=>{"model_request_start"===e.type&&e.model!==l&&(l=e.model,u())})}}__name(isHostEvent,"isHostEvent"),__name(createHerdrMod,"createHerdrMod");var mN=createHerdrMod();function providerMod(e){return{name:`provider-${e.id}`,factory:__name(async t=>{try{const n=await loadBuiltinProviderModule({moduleId:e.id,install:!1});n&&t.addProvider(n)}catch(t){dlog("[ProviderPackages] builtin provider mod skipped",{pkg:e.package,error:t instanceof Error?t.message:String(t)})}},"factory")}}function providerBuiltinMods(){return RD.map(providerMod)}function updateNoticeMod(e){try{const t=readUpdatesConfig().pending;if(!t?.targetVersion)return;const n=getPackageJson(import.meta.url).version;if(t.targetVersion===n)return;e.ui.notify(`update available: v${t.targetVersion} (installing in the background — a restart applies it)`)}catch{}}function commandBuiltinMods(){return[...providerBuiltinMods(),{name:"update-notice",factory:updateNoticeMod},{name:"herdr",factory:mN}]}Gt(),SR(),__name(providerMod,"providerMod"),__name(providerBuiltinMods,"providerBuiltinMods"),Gt(),SR(),__name(updateNoticeMod,"updateNoticeMod"),__name(commandBuiltinMods,"commandBuiltinMods");var pN=__name((e,t,n)=>` ${Et.cyan(e)} ${Et.dim(`· ${t} · ${n}`)}`,"formatModLine"),gN=__name((e,t)=>`${Et.bold(Et.white(e))} ${Et.dim(`(${t})`)}`,"formatSectionHeader");function scopeFor(e){const{entry:t}=e;if("project"===t.source)return"project";if("user"===t.source)return"user";if("path"===t.source)return"session";const n=modSourceForPath({statuses:e.sources,path:t.path});return n?.scope??"package"}function detailFor(e){const{entry:t}=e,n=e.disabled.has(t.name)?" (disabled)":"";if("package"===t.source){const r=modSourceForPath({statuses:e.sources,path:t.path});return`from ${r?.identity??"a package source"}${n}`}return`${shortenModPath(t.path,e.projectRoot)}${n}`}async function listAction(e){const t=createNodeRuntime(),n=await isCommandProjectSessionInitialized(),r=await discoverMods({runtime:t,includeProject:n}),o=await listModSources({runtime:t,includeProject:n}),i=new Set(r.disabled),a=await modsDirectoryPath({runtime:t,scope:"project"}),l=await modsDirectoryPath({runtime:t,scope:"user"}),c=a?s(a,"..",".."):void 0,d=["project","user","package","path"].flatMap(e=>r.entries.filter(t=>t.source===e));console.log(""),console.log(`${Et.bold(Et.white("Mods"))} ${Et.dim(`(${r.entries.length})`)}`),0===r.entries.length&&(console.log(""),console.log(Et.dim(" No mods loaded. Looking in:")),a&&console.log(Et.dim(` ${shortenModPath(a,c)} ${Et.white("(project)")}`)),l&&console.log(Et.dim(` ${shortenModPath(l,void 0)} ${Et.white("(user)")}`)),console.log(""),console.log(Et.dim(` Drop a .ts file in one (\`${getBinaryCommand()} mods open --user\`) or install a package: \`${getBinaryCommand()} mods add <source>\`.`)));for(const e of d)console.log(pN(e.name,scopeFor({entry:e,sources:o}),detailFor({entry:e,sources:o,projectRoot:c,disabled:i})));if(!0===e.builtin){const e=commandBuiltinMods();console.log(""),console.log(gN("Built-in",e.length));for(const t of e)console.log(pN(t.name,"builtin",i.has(t.name)?"disabled":"enabled"))}const u=new Set;if(o.length>0){const e=__name(e=>r.entries.some(t=>"package"===t.source&&void 0!==modSourceForPath({statuses:[e],path:t.path})),"contributes"),t=o.filter(t=>!t.installed||!e(t));if(t.length>0){console.log(""),console.log(gN("Package sources",t.length));for(const e of t){u.add(e.source);const t=e.installed?Et.yellow("installed, but provides no mods"):Et.yellow(`not installed — run \`${getBinaryCommand()} mods update\``);console.log(pN(e.identity,e.scope,t))}}}const m=r.warnings.filter(e=>!u.has(e.path));if(m.length>0){console.log(""),console.log(`${Et.bold(Et.yellow("Warnings"))} ${Et.dim(`(${m.length})`)}`);for(const e of m)console.log(` ${Et.cyan(shortenModPath(e.path,c))} ${Et.dim(`· ${e.reason}`)}`)}console.log("")}__name(scopeFor,"scopeFor"),__name(detailFor,"detailFor"),__name(listAction,"listAction");var hN=new Be("list").alias("ls").description("List the mods a session loads, and where each one comes from").addOption(new We("--builtin","also list Command Code's built-in mods").hideHelp()).action(listAction);async function openAction(e){const t=createNodeRuntime(),n=!0===e.user||!0===e.global;try{const r=n?void 0:await modsDirectoryPath({runtime:t,scope:"project"}),o=r??await modsDirectoryPath({runtime:t,scope:"user"});if(!o)throw new Error("Could not resolve a mods directory");const s=r?"project":"user";if(!0===e.path)return void console.log(o);await t.fs.mkdir({path:o}),await Pt(o);const i=await createModPathShortener(t);console.log(`${Et.green(gt.tick)} Opened ${Et.cyan(i(o))} ${Et.dim(`· ${s}`)}`)}catch(e){console.error(`${Et.red(gt.cross)} ${rN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}Gt(),SR(),__name(openAction,"openAction");var fN=new Be("open").description("Open the mods directory (project by default, --user for ~)").option("-u, --user","open the user mods directory (~/.commandcode/mods)").option("-g, --global","alias for --user").option("--path","print the directory path instead of opening it").action(openAction);async function removeAction(e,t){const n=createNodeRuntime();commandBuiltinMods().some(t=>t.name===e)&&(console.error(`${Et.red(gt.cross)} ${Et.cyan(e)} is a built-in mod — it cannot be removed. Add it to ${Et.cyan('"mods": {"disabled": [...]}')} in settings.json to turn it off.`),process.exit(1));const r=await isCommandProjectSessionInitialized();try{const o=await removeMod({runtime:n,target:e,scope:t.global?"user":"project",includeProject:r});if(!o.removedFromSettings&&!o.removedPath)return void console.log(`${Et.yellow(gt.warning)} ${Et.cyan(o.target)} is not configured (${o.scope} scope) — nothing to remove`);const s=await createModPathShortener(n);console.log(`${Et.green(gt.tick)} Removed ${Et.cyan(o.target)} ${Et.dim(`· ${o.scope}`)}`),o.sourceIdentity&&o.sourceIdentity!==o.target&&console.log(Et.dim(` Removed its source ${o.sourceIdentity}`)),o.alsoRemoved&&o.alsoRemoved.length>0&&console.log(Et.dim(` That source also provided ${o.alsoRemoved.join(", ")}`)),o.removedPath&&console.log(Et.dim(` Deleted ${s(o.removedPath)}`)),o.removedFromSettings&&o.settingsPath&&console.log(Et.dim(` Updated ${s(o.settingsPath)}`))}catch(e){console.error(`${Et.red(gt.cross)} ${rN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}Gt(),SR(),__name(removeAction,"removeAction");var yN=new Be("remove").alias("rm").alias("uninstall").description("Remove a mod by its listed name or by its package source").argument("<target>","mod name from `mods list`, or the mod source (any spelling of it)").option("-g, --global","remove from user scope instead of project").action(removeAction);async function updateAction(){const e=createNodeRuntime(),t=await updateModSources({runtime:e,includeProject:await isCommandProjectSessionInitialized()});for(const e of t.updated)console.log(`${Et.green(gt.tick)} ${Et.cyan(e)}`);for(const e of t.failures)console.error(`${Et.red(gt.cross)} ${e.source} ${Et.dim(`· ${e.reason}`)}`);0===t.updated.length&&0===t.failures.length&&console.log(Et.dim("No mod package sources configured.")),t.failures.length>0&&process.exit(1)}Gt(),SR(),__name(updateAction,"updateAction");var SN=new Be("update").alias("up").description("Reinstall and reconcile every configured mod package").action(updateAction),wN=new Be("mods").description("Manage mods — loadable extensions from npm, git, or local paths").addCommand(oN).addCommand(yN).addCommand(hN).addCommand(SN).addCommand(fN);function resolveBundledRipgrepPath(){try{const e=vt(import.meta.url),{rgPath:t}=e("@vscode/ripgrep");if("string"==typeof t&&t.length>0&&A(t))return t}catch{}}function registerBundledRipgrep(){if(process.env[lc])return;const e=resolveBundledRipgrepPath();void 0!==e&&(process.env[lc]=e)}Gt(),SR(),__name(resolveBundledRipgrepPath,"resolveBundledRipgrepPath"),__name(registerBundledRipgrep,"registerBundledRipgrep"),Gt(),SR(),Gt();var vN=["EPIPE","ECONNRESET","EOF"];function asErrnoLike(e){if("object"==typeof e&&null!==e)return e}function isBenignStreamWriteError(e){const t=asErrnoLike(e);if(!t)return!1;const n="string"==typeof t.code?t.code:"",r="string"==typeof t.message?t.message:"";return!!vN.some(e=>r.includes(`write ${e}`))||"write"===("string"==typeof t.syscall?t.syscall:"")&&vN.includes(n)}async function handleEffortCommand(e,t){const n=e.currentModel,r=n?customReasoningEfforts(n)??getSupportedEfforts(n):null,o=t.trim().toLowerCase();if(o&&n&&r){if(r.includes(o)){const t=o,r=getReasoningEffort(n),s=k$(e.sessionId),i=s?s.getEffort():r;return t!==r&&await setReasoningEffort({modelId:n,effort:t}),t!==i&&(s?.recordEffortChange({model:n,effort:t}),hardResetForResize(),e.setStaticKey(e=>e+1)),void e.setFeed(e=>[...e,uh(`Reasoning effort set to ${t}.`)])}if(r.length>0)return void e.setFeed(e=>[...e,uh(`Unknown effort "${t.trim()}". Supported: ${r.join(", ")}.`)])}const s=resolveEffortCommand({model:n,supportedEfforts:r,modelLabel:n?getModelDisplayName(n):void 0});"notice"!==s.kind?e.setShowEffortSelector(!0):e.setFeed(e=>[...e,uh(s.message)])}async function applyEffortSetting(e,t){const n=e.trim().toLowerCase();if(!n)return{ok:!1,message:"Provide a level, e.g. --effort high."};const r=t?.model??getConfiguredModel(),o=customReasoningEfforts(r)??getSupportedEfforts(r);return o&&0!==o.length?o.includes(n)?(await setReasoningEffort({modelId:r,effort:n}),{ok:!0,message:`Reasoning effort set to ${n} for ${getModelDisplayName(r)}.`}):{ok:!1,message:`Unknown effort "${e.trim()}". Supported: ${o.join(", ")}.`}:{ok:!1,message:`${getModelDisplayName(r)} has no adjustable reasoning effort.`}}function usePasteAwareChange(e){const{onChange:t,onPaste:n}=e,r=lt(!1);return ut(async e=>{const o=processBracketedPaste(e),s=n??t,i=__name(async()=>{r.current=!1;const e=await detectClipboardTextNative();e?s(e):o.cleanedContent&&s(o.cleanedContent)},"applyPastedText");if(!o.isPasteStart||r.current)r.current&&!o.isPasteEnd||(r.current&&o.isPasteEnd?await i():t(e));else{if(r.current=!0,!o.isPasteEnd)return;await i()}},[t,n])}function extractDeviceCode2(e){const t=e.match(/copy\s+this\s+code:\s*([^\s]+)/i);return t?.[1]??null}__name(asErrnoLike,"asErrnoLike"),__name(isBenignStreamWriteError,"isBenignStreamWriteError"),Gt(),SR(),Gt(),SR(),Gt(),SR(),Gt(),SR(),__name(handleEffortCommand,"handleEffortCommand"),__name(applyEffortSetting,"applyEffortSetting"),Gt(),SR(),Gt(),SR(),Gt(),SR(),Gt(),SR(),__name(usePasteAwareChange,"usePasteAwareChange"),__name(extractDeviceCode2,"extractDeviceCode");var kN=__name(({providerId:e,onSuccess:t,onCancel:n,onFailure:r})=>{const o=getProviderDisplayName(e),[s,i]=at("confirm"),[a,l]=at(""),[c,d]=at(""),[u,m]=at(""),[p,g]=at(""),[h,f]=at(null),y=lt(!1),S=lt(!0),w=lt(!1),v=lt(null),k=lt(null),C=lt(null),b=lt(!1);ct(()=>()=>{S.current=!1,v.current&&clearTimeout(v.current),C.current=null},[]);const E=ut(e=>{w.current||(w.current=!0,v.current=setTimeout(()=>{if(v.current=null,!S.current)return;const t=e.keepTerminalActive?{wait:!1,background:!0}:void 0;Pt(e.authUrl,t).catch(()=>{S.current&&f(`Failed to open browser. Please manually open: ${e.authUrl}`)})},300))},[]),T=ut(async t=>{if(!S.current)return;if(l(t.url),t.prompt)return d(t.instructions),b.current=!0,m(t.prompt.label),i("paste"),E({authUrl:t.url,keepTerminalActive:!1}),new Promise(e=>{k.current=e});b.current=!1;const n=e===uo.COPILOT?extractDeviceCode2(t.instructions):null;if(n){const e=await writeClipboardText(n);if(!S.current)return;d(`Logging into Copilot, use this code: ${n}${e?" (copied)":""}`)}else d(t.instructions);return i("open-browser"),new Promise(e=>{C.current=()=>{C.current=null,i("waiting"),Pt(t.url).catch(()=>{S.current&&f(`Failed to open browser. Please manually open: ${t.url}`)}),e({})}})},[e,E]),P=lt(()=>{});P.current=()=>{providerLogin({provider:e,onPending:T}).then(async()=>{S.current&&(await persistProviderSelection(e),i("success"),t())}).catch(e=>{if(!S.current)return;const t=e instanceof Error?e.message:"Authentication failed";if(f(t),y.current=!1,k.current=null,r?.(t),b.current)return g(""),void P.current();i("error")})};const M=ut(e=>{g(e.trim())},[]),x=usePasteAwareChange({onChange:g,onPaste:M}),I=__name(()=>{if(!p.trim()||y.current||!k.current)return;y.current=!0,f(null);const e=k.current;k.current=null,e({code:p.trim()})},"handleSubmit");if(nt((e,t)=>{if(t.escape)n();else if(!t.leftArrow||"confirm"!==s&&"open-browser"!==s&&"waiting"!==s&&"error"!==s&&("paste"!==s||p)){if("confirm"===s){if(t.return||"y"===e||"Y"===e)return i("connecting"),void P.current();"n"!==e&&"N"!==e||n()}"open-browser"===s&&t.return&&C.current?.()}else n()}),"confirm"===s){const t=e===uo.COPILOT?"This will get a GitHub sign-in code.":`This will open your browser to sign in with ${o}.`;return st.createElement(bO,{title:`Sign in to ${o}`,subtitle:t,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"y"),"/",st.createElement(gO,null,"enter")," ","continue"),st.createElement(st.Fragment,null,st.createElement(gO,null,"n"),"/",st.createElement(gO,null,"esc")," ","cancel")]})})}return"connecting"===s?st.createElement(bO,{title:`Sign in to ${o}`,subtitle:"Getting sign-in code…",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," cancel")]})}):"paste"===s?st.createElement(bO,{title:`Sign in to ${o}`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," submit"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," cancel")]})},a&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},"Login: "),st.createElement(cL,{url:a,text:"Open auth page ↗",color:ER.CYAN})),c&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},c)),h&&st.createElement(Qe,{marginBottom:1},st.createElement(R$,null,h)),st.createElement(Qe,null,st.createElement(Xe,null,u||"Authorization code",": "),st.createElement(TextInput,{mask:"*",focus:!0,value:p,onChange:x,onSubmit:I,placeholder:"Paste code here..."}))):"open-browser"===s?st.createElement(bO,{title:`Sign in to ${o}`,subtitle:e===uo.COPILOT?"Press enter to open GitHub and paste the code there":"Press enter to open your browser",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," cancel")]})},c&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0,color:ER.GREEN},c)),a&&e!==uo.COPILOT&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},"Login: "),st.createElement(cL,{url:a,text:"Open auth page ↗",color:ER.CYAN}))):"waiting"===s?st.createElement(bO,{title:`Sign in to ${o}`,subtitle:"Waiting for authorization…",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," cancel")]})},c&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0,color:ER.GREEN},c)),a&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},"Open: "),st.createElement(cL,{url:a,text:"Open auth page ↗",color:ER.CYAN}))):"error"===s?st.createElement(bO,{title:`Sign in to ${o}`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," back")]})},st.createElement(R$,null,h)):null},"ProviderAuth");function makeProviderAuthComponent(e){const t=__name(({onSuccess:t,onCancel:n})=>st.createElement(kN,{providerId:e,onSuccess:t,onCancel:n}),"Bound");return t.displayName=`ProviderAuth(${e})`,t}__name(makeProviderAuthComponent,"makeProviderAuthComponent");var CN=Object.fromEntries(Object.entries(Xo).map(([e,t])=>[e,{...t}]));function getProviderConfig(e){return CN[e]}async function getProviderAuthState(e){if(!e)return null;const t=getProviderConfig(e);return t?resolveProviderAuthState({displayName:t.displayName,requiresAuth:t.requiresAuth,checkAuth:t.checkAuth}):null}async function handleModelSelect({modelId:e,provider:t,routeProvider:n,setCurrentModel:r,setShowModelSelector:o,setStatus:s,modelNotificationTimer:i,setShowModelNotification:a,setCurrentProvider:l,setStaticKey:c,sessionId:d,setFeed:u,setContextUsage:m,setModelNotice:p}){try{const g=t&&getProviderConfig(t)?t:void 0,h=n??(t&&!getProviderConfig(t)?t:void 0),f=g?await getConfiguredProvider():void 0,y=await applyCommandModelSelection({modelId:e,provider:g,routeProvider:h,sessionId:d,catalog:{getDisplayName:getModelDisplayName},deps:{getProviderAuthState:getProviderAuthState,getCurrentModel:getConfiguredModel,persistProvider:__name(async t=>{dlog(`[Model] Setting provider to ${t} for ${e}`),await updateUserConfig({provider:t})},"persistProvider"),persistDefaultModel:__name(async(e,t)=>{await persistDefaultModel({model:e,provider:t})},"persistDefaultModel"),setSessionModel:setSessionModel,clearModelOverride:clearModelOverride,saveSessionModel:__name(async({sessionId:e,modelId:t,routeProvider:n})=>{await saveCommandSessionMeta({sessionId:e,meta:{model:t,modelProvider:n}})},"saveSessionModel"),onProviderPersisted:l,log:dlog}});if("auth-blocked"===y.status)return s(y.message),void o(!1);if(d&&g&&g!==f&&await rebuildHarnessSession(d),r(e),y.modelChanged&&(hardResetForResize(),c(e=>e+1)),o(!1),s(y.statusMessage),y.modelChanged&&p?.(getModelNotice(e)??null),y.modelChanged){const t=await reconcileCommandModelSelection({modelId:e,...void 0!==h?{routeProvider:h}:{},modelName:y.modelName,previousModel:y.previousModel,harness:d?k$(d):void 0,catalog:{getContextLimit:__name(e=>customAwareContextLimit({modelId:e,fallback:getContextLimit}),"getContextLimit"),supportsVision:modelSupportsVision},hasImagesInHistory:harnessHasImagesInHistory});m?.(t.contextUsage);for(const e of t.notices)u?.(t=>[...t,uh(e.message)])}i.current&&clearTimeout(i.current),a(!0),i.current=setTimeout(()=>{a(!1),i.current=null},5e3)}catch(e){console.error("Failed to set model:",e),s("Failed to set model"),o(!1)}}function handleModelCancel({setShowModelSelector:e}){e(!1)}async function handleModelCommand(e,t){const n=t.trim();if(!n)return void e.setShowModelSelector(!0);const r=await resolveSelectableModel(n);if(!r)return e.setFeed(e=>[...e,uh(`Unknown model "${n}" — opening the model picker so you can choose.`)]),void e.setShowModelSelector(!0);r.warning&&e.setFeed(e=>[...e,uh(r.warning)]);const o=r.modelId;await handleModelSelect({modelId:o,routeProvider:r.providerId,provider:r.providerId?void 0:getProviderFromModel(o)||void 0,setCurrentModel:e.setCurrentModel??(()=>{}),setShowModelSelector:e.setShowModelSelector,setStatus:e.setStatus,modelNotificationTimer:{current:null},setShowModelNotification:__name(()=>{},"setShowModelNotification"),setStaticKey:e.setStaticKey,sessionId:e.sessionId,setFeed:e.setFeed,setContextUsage:e.setContextUsage,setModelNotice:e.setModelNotice})}async function applyModelSetting(e){const t=e.trim();if(!t)return{ok:!1,message:"Provide a model, e.g. --model gpt-5."};const n=await resolveSelectableModel(t);if(!n)return{ok:!1,message:`Unknown model "${t}". Run with --list-models to see the options.`};const r=n.modelId;await persistDefaultModel({model:r,provider:n.providerId});const o=n.providerId?void 0:getProviderFromModel(r);o&&await updateUserConfig({provider:o});const s=n.warning?` (note: ${n.warning})`:"";return{ok:!0,message:`Default model set to ${getModelDisplayName(r)}.${s}`}}async function handleThemeSelect({theme:e,setShowThemeSelector:t,setStatus:n,setStaticKey:r}){t(!1);try{const t=resolveCliTheme(getCliTheme()),o=resolveCliTheme(e),s=t!==o;await setCliTheme({theme:e}),applyTuiTheme(o),s&&(RL(),hardResetForResize(),r(e=>e+1)),n(buildThemeStatusMessage(e))}catch{n(Eo)}}function handleThemeCancel({setShowThemeSelector:e}){e(!1)}async function handleThemeCommand(e,t){const n=t.trim().toLowerCase();n?so.includes(n)?await handleThemeSelect({theme:n,setShowThemeSelector:e.setShowThemeSelector,setStatus:e.setStatus,setStaticKey:e.setStaticKey}):e.setFeed(e=>[...e,uh(`Unknown theme "${n}". Options: ${so.join(", ")}.`)]):e.setShowThemeSelector(!0)}async function applyThemeSetting(e){const t=e.trim().toLowerCase();return t?so.includes(t)?(await setCliTheme({theme:t}),{ok:!0,message:`Theme set to ${t}.`}):{ok:!1,message:`Unknown theme "${e.trim()}". Options: ${so.join(", ")}.`}:{ok:!1,message:"Provide a theme, e.g. --theme auto."}}CN.anthropic&&(CN.anthropic.authComponent=makeProviderAuthComponent(uo.ANTHROPIC),CN.anthropic.checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:uo.ANTHROPIC});return!!e}),CN["github-copilot"]&&(CN["github-copilot"].authComponent=makeProviderAuthComponent(uo.COPILOT),CN["github-copilot"].checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:uo.COPILOT});return!!e}),CN.codex&&(CN.codex.authComponent=makeProviderAuthComponent(uo.CODEX),CN.codex.checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:uo.CODEX});return!!e}),__name(getProviderConfig,"getProviderConfig"),__name(getProviderAuthState,"getProviderAuthState"),__name(handleModelSelect,"handleModelSelect"),__name(handleModelCancel,"handleModelCancel"),__name(handleModelCommand,"handleModelCommand"),__name(applyModelSetting,"applyModelSetting"),Gt(),SR(),__name(handleThemeSelect,"handleThemeSelect"),__name(handleThemeCancel,"handleThemeCancel"),__name(handleThemeCommand,"handleThemeCommand"),__name(applyThemeSetting,"applyThemeSetting");var bN=[{key:"model",apply:__name(e=>applyModelSetting(e),"apply")},{key:"effort",valueHint:"level",description:"Set reasoning effort for the session (e.g. low, medium, high) — depends on the model",apply:__name((e,t)=>applyEffortSetting(e,t),"apply")},{key:"theme",valueHint:"theme",description:"Set the color theme (dark or light)",apply:__name(e=>applyThemeSetting(e),"apply")}],EN=__name(e=>`--${e.key} <${e.valueHint}>`,"flagSpecOf"),TN=bN.filter(e=>void 0!==e.valueHint&&void 0!==e.description);async function applyConfigSetting(e){const t=e.indexOf("=");if(t<1)return{ok:!1,message:"Use --config key=value, e.g. --config theme=dark."};const n=e.slice(0,t).trim().toLowerCase(),r=e.slice(t+1).trim(),o=bN.find(e=>e.key===n);if(o)return o.apply(r);const s="true"===r||"false"!==r&&r;try{return await updateConfigSetting({id:n,value:s}),{ok:!0,message:`Set ${n} = ${r}.`}}catch(e){return{ok:!1,message:e instanceof Error?e.message:`Could not set config "${n}".`}}}__name(applyConfigSetting,"applyConfigSetting"),Gt(),SR();var PN=["default","standard","plan","accept-edits","auto-accept","yolo","bypass","dont-ask"];function parsePermissionModeOption(e){const t=PN.includes(e)?normalizePermissionMode(e):void 0;if(!t)throw new He(`Allowed choices are ${PN.join(", ")}.`);return t}__name(parsePermissionModeOption,"parsePermissionModeOption");var MN=getPackageJson(import.meta.url),xN=__name((e,t=[])=>[...t,e],"collectAddDir"),IN=__name((e,t=[])=>[...t,e],"collectConfig");function displayCustomHelp(){const e=MN.version,t=getInvokedCommandName(),n=getVisibleSlashCommands();console.log(),console.log(ht.bold("Command Code")+ht.gray(` v${e}`)),console.log(ht.gray(hi)),console.log(),console.log(ht.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(ht.bold("Options"));for(const e of ki){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(fi)+ht.gray(e.description))}console.log(),console.log(ht.bold("Commands"));for(const e of bi){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(fi)+ht.gray(e.description))}console.log(),console.log(ht.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(fi)+ht.gray(e.description));console.log(),console.log(ht.bold("Keyboard Shortcuts"));for(const e of vi)console.log(" "+e.key.padEnd(fi)+ht.gray(e.description));console.log(),console.log(ht.bold("Examples"));for(const e of Ti){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(fi)+ht.gray(e.description))}console.log(),console.log(ht.cyan("❯")+" "+ht.gray(yi.replace(/cmd/,t))),console.log(),console.log(ht.bold("Links"));for(const e of Ei)console.log(" "+e.key.padEnd(fi)+ht.cyan(e.description));console.log()}function createProgram(){const e=new Be;e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(MN.version??"0.0.0","-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume [name]","Resume a session by id or name, or pick from history").option("--sessions [name]","Alias of --resume — resume a session by id or name, or pick from history").option("-c, --continue"," Continue the most recent session in the current directory").option("--fork-session","With --resume/--continue, fork the session into a new one (original left untouched)").option("--session <path|id>","Resume a session by transcript path (.jsonl) or a unique session-id prefix").option("--no-session","Don't persist this session to disk (in-memory only)").option("-n, --name <name>","Set the session display name").option("-t, --trust","Trust the project (skip initial trust permission prompt)").addOption(new We("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new We("--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 We("--accept-edits","Start in accept edits mode").implies({permissionMode:"auto-accept"})).addOption(new We("--auto-accept").implies({permissionMode:"auto-accept"}).hideHelp()).addOption(new We("--permission-mode <mode>","Set permission mode").choices(PN).argParser(parsePermissionModeOption)).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>",`Max agentic turns (model API round trips): print mode limit (default ${pi}); interactive mode sets the /goal turn budget (default 100)`,e=>{const t=parseInt(e,10);if(isNaN(t)||t<1)throw new He("--max-turns must be a positive integer");return t}).option("--verbose","Stream tool execution progress to stderr in print mode").option("--tools-all","Print mode: enable every tool, including the ones a headless run withholds").option("--tools-enable <names>","Print mode: enable specific withheld tools by name, comma-separated (e.g. ask_user_question,exit_plan_mode); repeatable",xN,[]).addOption(new We("--output-format <format>","Print-mode output: text (default) or json — newline-delimited AgentEvent frames plus one final result line").choices(["text","json"])).option("--ide-setup",Si).option("--no-auto-update","Disable automatic background updates for this run").option("--add-dir <directory>","Add directory to workspace context",xN,[]).option("-w, --worktree [name]","Run this session in an isolated git worktree (managed under ~/.commandcode/worktrees/). Accepts a name, a path, or a PR (#1234). Generates a name when omitted.").option("--mod <path>","Load a mod file or directory for this session (repeatable)",xN,[]).option("--mod-option <name=value>","Set a mod-declared flag value (repeatable)",xN,[]).option("--skill <path>","Load extra skills from a path (a skill directory or a directory of skills); repeatable",xN,[]).option("--no-skills","Skip skill discovery; paths given via --skill still load").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 We("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new We("--experimental","Enable experimental features").hideHelp()).addOption(new We("-d, --debug","Enable debug mode").hideHelp()).option("--local-only","For BYOK: local-only with your BYOK providers, no Command Code traffic (same as CMD_LOCAL_ONLY=1)").addOption(new We("--local","Use local server").hideHelp()).addOption(new We("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption();for(const t of TN)e.option(EN(t),t.description);return e.option("--config <key=value>","Set a setting headlessly, e.g. --config theme=dark (repeatable)",IN),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram");var AN=null;function commandPath(e){const t=[];let n=e;for(;null!==n&&null!==n.parent;)t.unshift(n.name()),n=n.parent;return t.join(" ")}function flagNames(e){return Object.entries(e.opts()).filter(([,e])=>void 0!==e&&!1!==e).map(([e])=>`--${e}`).join(" ")}function failPendingCommandSpan(e){null!==AN&&(recordError({span:AN,error:sanitizeErrorForTelemetry({error:e,label:"command_error"})}),AN.end(),AN=null)}function abandonPendingCommandSpan(){null!==AN&&(AN.setAttribute("cmd.command.outcome","abandoned"),AN.end(),AN=null)}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(" ")}`);const a=commandPath(t);if(!a)return;const l=flagNames(t);AN=createSpan({name:`command:${a}`,attributes:{"cmd.command.name":a,"cmd.command.arg_count":i.length,...l?{"cmd.command.args":l}:{}}})}),e.hook("postAction",()=>{dlogSection("Done"),null!==AN&&(endSpan({span:AN,status:"success"}),AN=null)})}__name(commandPath,"commandPath"),__name(flagNames,"flagNames"),__name(failPendingCommandSpan,"failPendingCommandSpan"),__name(abandonPendingCommandSpan,"abandonPendingCommandSpan"),__name(setupCommanderHooks,"setupCommanderHooks");var{red:RN,yellow:LN,dim:ON}=ht;function printErrorDetails(e,t){if(console.log(`${xt.error} ${RN(t)}`),console.log(`${xt.error} ${RN("ERROR →")} ${e.name}`),console.log(`${xt.info} ${RN("REASON →")} ${e.message}`),console.log(`${xt.info} ${RN("ERROR STACK ↓ \n")} ${e.stack}\n`),!isTelemetryInitialized())return;const n=getDisplayTraceId();console.log(`${xt.info} ${ON(`Trace ID: ${n}`)}`),console.log(`${ON(" Share this ID with support to help debug your issue.")}\n`)}__name(printErrorDetails,"printErrorDetails");var DN=__name(e=>{const{heading:t="ERROR: ",error:n,displayError:r=!0,exit:o=!0,skipTelemetry:s=!1}=e;if(n){if(s||trackCliError({error:n,heading:t}),failPendingCommandSpan(n),console.log(),r||console.log(`${xt.warning} ${LN(t)}\n`),r&&printErrorDetails(n,t),!o)return!1;process.exit(0)}},"handleError");Gt(),SR();var $N,NN,_N=[],FN=[];function setModPathsOverride(e){_N=e}function setModOptionsOverride(e){FN=e}function loadCommandModHost(e={}){return $N||($N=buildHost(e))}async function buildHost(e){try{const t=createNodeRuntime(),n=createModHost({runtime:t}),r=!1!==e.projectMods&&await isCommandProjectSessionInitialized();await loadMods({runtime:t,host:n,includeProject:r,extraPaths:_N,builtins:commandBuiltinMods()});for(const e of FN){const t=e.indexOf("=");t<=0?dlog(`[mods] ignoring malformed --mod-option "${e}"`):n.setFlagValue({name:e.slice(0,t),value:e.slice(t+1)})}for(const e of n.warnings())dlog(`[mods] ${e.path}: ${e.reason}`);return setActiveModHost(n),setRegisteredProviderModules({modules:n.providerModules()}),n}catch(e){return void dlog(`[mods] host construction failed: ${e instanceof Error?e.message:String(e)}`)}}function disposeCommandModHost(){return NN??=$N?runModHostTeardown({host:$N}):Promise.resolve(),NN}function exitAfterModHostTeardown(e){disposeCommandModHost().finally(()=>{process.exit(e)})}async function runModHostTeardown(e){const t=__name(async()=>{const t=await e.host;t&&(t.dispose(),await t.settle())},"teardown");try{await Promise.race([t(),new Promise(t=>{const n=setTimeout(t,e.graceMs??300);n.unref?.()})])}catch(e){dlog(`[mods] teardown failed: ${e instanceof Error?e.message:String(e)}`)}}function handleStdoutError(e){if(!isBenignStreamWriteError(e))throw e;exitAfterModHostTeardown(0)}function handleStderrError(e){if(!isBenignStreamWriteError(e))throw e}function handleUnhandledErrors(){process.stdout.on("error",handleStdoutError),process.stderr.on("error",handleStderrError),process.on("unhandledRejection",e=>{const t=e instanceof Error?e:new Error(String(e));trackError({error:sanitizeErrorForTelemetry({error:t,label:"unhandled_rejection"}),context:{component:Ho.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),DN({heading:Tt`CRITICAL: Unhandled Promise Rejection!
15
15
  This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:t,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})}),process.on("uncaughtException",e=>{trackError({error:sanitizeErrorForTelemetry({error:e,label:"uncaught_exception"}),context:{component:Ho.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),DN({heading:Tt`CRITICAL: Uncaught Exception!
16
- This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:e,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})})}__name(setModPathsOverride,"setModPathsOverride"),__name(setModOptionsOverride,"setModOptionsOverride"),__name(loadCommandModHost,"loadCommandModHost"),__name(buildHost,"buildHost"),__name(disposeCommandModHost,"disposeCommandModHost"),__name(exitAfterModHostTeardown,"exitAfterModHostTeardown"),__name(runModHostTeardown,"runModHostTeardown"),__name(handleStdoutError,"handleStdoutError"),__name(handleStderrError,"handleStderrError"),__name(handleUnhandledErrors,"handleUnhandledErrors"),Gt(),SR(),Gt(),Gt(),SR(),Gt(),SR(),Gt(),SR(),Gt();var UN=gt.pointer,jN=__name(({isSelected:e,backgroundColor:t})=>st.createElement(Xe,{color:e?wO:kO,backgroundColor:t,bold:e&&isLightTheme()},e?UN:" "),"OverlayCaret"),BN=__name(({isSelected:e,isActive:t,idleColor:n=vO,backgroundColor:r,children:o})=>st.createElement(Xe,{color:e?wO:t?CO:n,backgroundColor:r,bold:e&&isLightTheme()},o),"OverlayOptionText"),WN=__name(({isSelected:e,label:t})=>st.createElement(BN,{isSelected:e}," ",t),"OverlayOptionItem"),HN=__name(({backgroundColor:e})=>st.createElement(Xe,{color:CO,backgroundColor:e}," ",gt.tick),"OverlayActiveTick"),GN=__name(({indent:e=4,children:t})=>st.createElement(Xe,{color:yO}," ".repeat(e),t),"OverlayOptionDescription"),VN=__name(({isSelected:e,idleColor:t=ER.GRAY,selectedColor:n=ER.WHITE,bold:r,children:o})=>st.createElement(Xe,{color:e?n:t,backgroundColor:e?KR:void 0,bold:r??e},o),"OverlayBarText"),zN=__name(({isSelected:e,label:t})=>st.createElement(VN,{isSelected:e}," ",t," "),"OverlayBarItem"),KN=__name(()=>null,"OverlayBarIndicator");Gt();var qN=createOSC8Link("https://commandcode.ai/docs/permissions#permission-modes","Docs ↗",!1),YN=__name(({hint:e})=>st.createElement(Xe,{italic:!0,color:ER.DIM},e," · Run ",st.createElement(Xe,{color:ER.WHITE},"cmd --yolo")," to bypass all permissions (",qN,")"),"PermissionFooter"),JN=__name(({request:e,onResponse:t})=>{const[n]=at(0),r=getPermissionChoicesForRisk({choices:getGenericToolPermissionChoices({toolName:e.toolName}),risk:e.risk}),o=__name(e=>{const n=r.find(t=>t.value===e.value);n&&t(n)},"handleSelect");return st.createElement(bO,{title:"Tool Permission",subtitle:st.createElement(Xe,{wrap:"wrap"},"Command Code needs to run ",st.createElement(Xe,{color:wO},e.toolName),"."),footer:st.createElement(YN,{hint:"↑/↓ navigate · enter select"})},e.risk&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0,color:ER.RED,wrap:"wrap"},gt.warning," ",getRiskDisplay(e.risk))),e.description&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM,italic:!0},e.description)),st.createElement(SelectInput,{items:r.map((e,t)=>({label:`${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:n,indicatorComponent:jN,itemComponent:WN}))},"GenericPermissionPrompt");function buildTreeConnectors(e,t={}){const{isTruncated:n=!1,closesFrame:r=!0}=t;return e.split("\n").map((e,t,o)=>r&&!n&&t===o.length-1?yL:SL).join("\n")}Gt(),SR(),Gt(),SR(),Gt(),__name(buildTreeConnectors,"buildTreeConnectors");var QN=bt()?"⟳":"*",XN=" │ ";function DiffWordSegments({segments:e,type:t,paired:n,dimDiff:r,language:o,highlightOptions:s}){const i="removed"===t?IR.REMOVED_HIGHLIGHT_BG:IR.ADDED_HIGHLIGHT_BG,a=[];let l=0;for(const c of e){const e=c.highlighted,d=highlightSyntax(c.text,o,s),u=`${t}-${l++}-${e?"highlighted":"unchanged"}`;e?a.push(st.createElement(Xe,{key:u,backgroundColor:i,dimColor:r},d)):n?a.push(st.createElement(Xe,{key:u,color:ER.WHITE,dimColor:r},d)):a.push(st.createElement(Xe,{key:u,color:"removed"===t?IR.REMOVED_TEXT:IR.ADDED_TEXT,dimColor:r},d))}return a}function DiffRow({background:e,prefix:t,wrap:n="wrap",children:r}){return st.createElement(Qe,{width:"100%",backgroundColor:e},st.createElement(Qe,{flexShrink:0},t),st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{wrap:n},r)))}function renderDiffLine({line:e,dimDiff:t,language:n,highlightOptions:r}){if("skip"===e.kind)return st.createElement(Qe,{key:e.key,width:"100%"},st.createElement(Xe,{color:IR.LINE_NUM,dimColor:t},e.spacer,XN,e.label));if("context"===e.kind)return st.createElement(DiffRow,{key:e.key,prefix:st.createElement(Xe,{color:IR.LINE_NUM,dimColor:t}," "+e.lineNumberLabel+XN)},st.createElement(Xe,{color:ER.WHITE,dimColor:t}," ",highlightSyntax(e.text,n,r)));const o="removed"===e.kind,s=o?IR.REMOVED_TEXT:IR.ADDED_TEXT,i=o?IR.REMOVED_BG:IR.ADDED_BG;return st.createElement(DiffRow,{key:e.key,background:i,prefix:st.createElement(Xe,null,st.createElement(Xe,{color:s,dimColor:t}," "+e.lineNumberLabel),st.createElement(Xe,{color:IR.LINE_NUM,dimColor:t},XN),st.createElement(Xe,{color:s,dimColor:t},o?"- ":"+ "))},st.createElement(DiffWordSegments,{segments:e.segments,type:e.kind,paired:e.paired,dimDiff:t,language:n,highlightOptions:r}))}function DiffMetadata({metadata:e}){return e?"rejected"===e.kind?st.createElement(Xe,{color:ER.RED},"Rejected update to",st.createElement(Xe,{color:ER.RED},` ${e.filePath}`)):st.createElement(Xe,{color:ER.GRAY},"Updated"," ",st.createElement(Xe,{color:ER.WHITE,bold:!0},e.filePath)," ","with"," ",e.additions>0&&st.createElement(st.Fragment,null,st.createElement(Xe,{color:OR.SUCCESS},e.additions)," ","addition",1!==e.additions?"s":"",e.removals>0?" and ":""),e.removals>0&&st.createElement(st.Fragment,null,st.createElement(Xe,{color:OR.ERROR},e.removals)," ","removal",1!==e.removals?"s":"")):null}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:s=2,startLine:i=1,dimDiff:a=!1,maxLines:l}){const c=projectEditDiffView({oldValue:e,newValue:t,filePath:n,permissionDenied:r,showMetadata:o,startLine:i,maxLines:l});let d="";"string"==typeof t&&t?d=t:"string"==typeof e&&(d=e);const u=syntaxLanguageFromFilePath(n,d.split("\n",1)[0]??null),m=getSyntaxHighlightOptions(isLightTheme());return{diffContent:st.createElement(Qe,{flexDirection:"column"},st.createElement(DiffMetadata,{metadata:c.metadata}),st.createElement(Qe,{flexDirection:"column",marginLeft:s,marginRight:s+4,width:Math.max(20,(process.stdout.columns||80)-2*s-8)},c.displayedLines.map(e=>renderDiffLine({line:e,dimDiff:a,language:u,highlightOptions:m})))),isTruncated:c.isTruncated,totalLines:c.totalLines}}function resolveTodoTextStyle(e){return"completed"===e?{textColor:OR.SUCCESS,strikethrough:!0}:"in_progress"===e?{textColor:OR.IN_PROGRESS,strikethrough:!1}:{textColor:ER.WHITE,strikethrough:!1}}function TodoChecklist({todos:e}){return st.createElement(Qe,{flexDirection:"column"},e.map((e,t)=>{const n="completed"===e.status?gt.checkboxOn:gt.checkboxOff,{textColor:r,strikethrough:o}=resolveTodoTextStyle(e.status),s="in_progress"===e.status&&e.activeForm?`${e.activeForm}…`:e.content;return st.createElement(Qe,{key:e.id||t,flexDirection:"row"},st.createElement(Qe,{width:2},st.createElement(Xe,{color:r},n)),st.createElement(Xe,{color:r,bold:"in_progress"===e.status,strikethrough:o},s))}))}function formatTodosForDisplay(e){const t=Nh(e);return t?st.createElement(TodoChecklist,{todos:t}):st.createElement(Xe,null,e)}function computeDisplayInput({input:e,isAgent:t,isShell:n,expandedOutput:r}){return e?t?summarizeAgentTaskInput(e):n&&!r?truncateCommand({command:e}):e:e}function formatToolInput({input:e,isShell:t}){return st.createElement(BracketWrap,null,t?e:st.createElement(Markdown,null,e))}function ReadToolInlineSummaryRow({summary:e}){return e?.dimText?st.createElement(Xe,{dimColor:!0}," ",e.dimText):null}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:o}){if(e)return{symbolColor:ER.YELLOW,symbol:gt.arrowRight};if(t)return{symbolColor:ER.RED,symbol:gt.square};if(n)return{symbolColor:MR,symbol:"✻"};if(r&&o){const e=Nh(o),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?OR.SUCCESS:OR.WARNING,symbol:gt.square}}return{symbolColor:AR.BG,symbol:gt.square}}function ToolHeader({isThinking:e,isTasteFile:t,tasteCategory:n,name:r,summaryMatch:o,expandedOutput:s,expandKey:i,input:a,output:l}){if(e){const e=estimateReasoningSeconds(a||l||"");return st.createElement(st.Fragment,null,st.createElement(Xe,{color:MR},`Thought for ${e} second${1!==e?"s":""}`," "),!s&&st.createElement(BracketWrap,{color:ER.DIM},`${i}+o to expand`))}if(t)return st.createElement(st.Fragment,null,st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:PR.BADGE_BG,color:PR.BADGE_FG,bold:!0},vL)),st.createElement(Xe,null," ","Using your taste"," ",n?"package of ":"packages",n&&st.createElement(Xe,{bold:!0},n)));let c=r;return"READ[n]"===r&&o&&(c=`READ[${Number(o[1])}]`),st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:AR.BG,color:AR.FG,bold:!0},`${wL}${c}${wL}`))}function stripAgentUsageTrailer(e){return e.replace(/\n*<usage>[\s\S]*?<\/usage>\s*$/,"").trimEnd()}function AgentStatus({agentStatus:e,hasError:t,output:n,elapsedSeconds:r,tokensUsed:o}){const s=`${formatTime3(r)} | ${formatTokens(o)}`;return"running"===e?st.createElement(Xe,{color:ER.GRAY},"Running (",s,")"):"background"===e?st.createElement(Xe,{color:ER.GRAY},"Running in background"):"interrupted"===e||n===eS?st.createElement(Xe,{color:ER.GRAY,wrap:"wrap"},"Interrupted"):"error"===e||t?st.createElement(Xe,{color:ER.RED,wrap:"wrap"},n," (",s,")"):st.createElement(st.Fragment,null,st.createElement(Xe,{wrap:"wrap"},"Done"),st.createElement(Xe,{color:ER.GRAY}," (",s,")"))}function getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}){if(n)return{text:e,isTruncated:!1,remainingLines:0,truncationMsg:null};const o=dedentText(e),{text:s,isTruncated:i,remainingLines:a}=truncateToVisualLines({output:o,maxVisualLines:"Question"===t?Nd:Dd,maxChars:"Question"===t?1/0:Wd}),l=i&&"Question"!==t;return{text:s,isTruncated:l,remainingLines:a,truncationMsg:l?a>0?st.createElement(BracketedText,{text:`... +${a} lines [${r}+o to expand]`,color:ER.DIM}):st.createElement(BracketedText,{text:`... [${r}+o to expand]`,color:ER.DIM}):null}}function renderTruncatedOutput({output:e,name:t,expandedOutput:n,expandKey:r}){const{text:o,isTruncated:s,truncationMsg:i}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r});return s?st.createElement(st.Fragment,null,o,"\n",i):o}function renderEditFileDiff({input:e,metadata:t,expandedOutput:n,isPermissionDenied:r,output:o,expandKey:s}){const i=n?void 0:_d,{diffContent:a,isTruncated:l,totalLines:c}=generateDiff({filePath:e,showMetadata:!0,oldValue:t.oldValue??"",newValue:t.newValue??"",startLine:"number"==typeof t.startLine?t.startLine:1,dimDiff:r,permissionDenied:r,maxLines:i}),d=c-_d;return st.createElement(Qe,{flexDirection:"column"},a,l&&st.createElement(Qe,{marginTop:1},st.createElement(BracketedText,{text:`… (${d} more ${1===d?"line":"lines"}) [${s}+o to expand]`,color:ER.DIM})),r&&o&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.RED,wrap:"wrap"},o)))}function renderWriteFileContent({input:e,metadata:t,expandedOutput:n,expandKey:r}){const o=syntaxLanguageFromFilePath(e,t.content?.split("\n",1)[0]??null),s=getSyntaxHighlightOptions(isLightTheme()),i=projectWriteFileContentView({filePath:e,content:t.content,totalLines:t.totalLines,expandedOutput:n,expandKey:r});return i.empty?st.createElement(Xe,{color:ER.GRAY},"Created"," ",st.createElement(Xe,{color:ER.WHITE,bold:!0},i.filePath)," ","(empty file)"):st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.GRAY},"Created"," ",st.createElement(Xe,{color:ER.WHITE,bold:!0},i.filePath)," ","(",i.totalLinesLabel,")"),st.createElement(Qe,{marginTop:1,flexDirection:"column"},i.visibleLines.map(e=>st.createElement(DiffRow,{key:e.lineNumber,background:IR.ADDED_BG,wrap:"truncate-end",prefix:st.createElement(Xe,null,st.createElement(Xe,{color:IR.ADDED_TEXT}," "+e.lineNumberLabel),st.createElement(Xe,{color:IR.LINE_NUM},XN))},st.createElement(Xe,{color:IR.ADDED_TEXT},highlightSyntax(e.text,o,s))))),i.isTruncated&&i.moreLinesLabel&&st.createElement(Qe,{marginTop:1},st.createElement(BracketedText,{text:i.expandHint?`… (${i.moreLinesLabel}) ${i.expandHint}`:`… (${i.moreLinesLabel})`,color:ER.DIM})))}function renderOutputContent({isTodos:e,isThinking:t,isEditFile:n,isWriteFile:r,metadata:o,output:s,expandedOutput:i,isPermissionDenied:a,input:l,hasError:c,name:d,expandKey:u,showTreeConnector:m,closesFrame:p}){if(e)return formatTodosForDisplay(s);if(t){if(!i)return null;const e=l||s;return st.createElement(Qe,{width:"100%",flexDirection:"column"},st.createElement(Xe,null," "),st.createElement(Xe,{color:MR,wrap:"wrap",italic:!0},e))}const g=p?yL:SL;if(n&&"string"==typeof o?.oldValue&&"string"==typeof o?.newValue){const e=renderEditFileDiff({input:l,metadata:o,expandedOutput:i,isPermissionDenied:a,output:s,expandKey:u});return m?st.createElement(Qe,{columnGap:1},st.createElement(Xe,{color:zR},g," "),e):e}if(r&&o&&"content"in o){const e=renderWriteFileContent({input:l,metadata:o,expandedOutput:i,expandKey:u});return m?st.createElement(Qe,{columnGap:1},st.createElement(Xe,{color:zR},g," "),e):e}return m?renderTextWithLongConnector({output:s,name:d,expandedOutput:i,expandKey:u,hasError:c,closesFrame:p}):st.createElement(Qe,{width:"100%"},st.createElement(Xe,{color:c?ER.RED:"",wrap:"wrap"},renderTruncatedOutput({output:s,name:d,expandedOutput:i,expandKey:u})))}function renderTextWithLongConnector({output:e,name:t,expandedOutput:n,expandKey:r,hasError:o,closesFrame:s}){const{text:i,isTruncated:a,truncationMsg:l}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}),c=o?ER.RED:void 0,d=buildTreeConnectors(i,{isTruncated:a,closesFrame:s}),u=s?yL:SL;return st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(Qe,{columnGap:1,width:"100%"},st.createElement(Xe,{color:zR},d),st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:c,wrap:"wrap"},i))),a&&st.createElement(Qe,{columnGap:1},st.createElement(Xe,{color:zR},u," "),l))}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:i=!1}){const a="thinking…"===e,l="TODOS"===e,c="EDIT"===e,d="WRITE"===e,u="READ"===e||e.startsWith("READ[")&&e.endsWith("]"),m=!0===s?.isTasteFile,p=s?.tasteCategory,g=!0===s?.permissionDenied,h=!a&&!l&&!m,f="ctrl",y=!0===s?.isAgent,S=computeDisplayInput({input:t,isAgent:y,isShell:"SHELL"===e,expandedOutput:i}),w=!a&&S&&!m,v=s?.status,k=s?.tokensUsed||0,C="number"==typeof s?.elapsedSeconds?Math.floor(s.elapsedSeconds):0,{notes:b}=extractRepairNotes(n??""),E=b.length,T=u?parseReadSummaryLine(extractRepairNotes(n??"").body):null,P=u?projectReadToolInlineSummary({name:e,summaryMatch:T}):null,M=u?projectReadToolBadge({name:e,summaryMatch:T}):e,x=y&&!0===s?.showOutput&&"done"===v,I=Boolean((n||a&&t)&&!m&&(!y||x)&&(!u||o)),{symbolColor:A,symbol:R}=resolveSymbol({isPending:r,hasError:o,isThinking:a,isTodos:l,output:n}),L=s?.preHookLines,O=s?.postHookLines,D=Boolean(L?.length),$=Boolean(O?.length),N=Boolean(s?.hookOutcome),_=r&&!y&&!N,F=!N&&!_,U=I&&!$&&!N&&!_,j=D&&!I&&!$&&!N&&!_;return st.createElement(Qe,null,a&&st.createElement(Xe,{color:A},R),st.createElement(Qe,{flexDirection:"column",marginLeft:a?1:0},st.createElement(Qe,null,st.createElement(ToolHeader,{isThinking:a,isTasteFile:m,tasteCategory:p,name:M,summaryMatch:T,expandedOutput:i,expandKey:f,input:t,output:n}),w&&st.createElement(Xe,null," ",formatToolInput({input:S,isShell:"SHELL"===e})),st.createElement(ReadToolInlineSummaryRow,{summary:P}),E>0&&st.createElement(Xe,{dimColor:!0},` ${QN}${E>1?` ${E}`:""}`)),y&&("running"===v||"background"===v||"done"===v||"error"===v||n)&&st.createElement(Qe,{columnGap:1,marginLeft:h?1:0},h&&st.createElement(Xe,{color:zR},yL," "),st.createElement(AgentStatus,{agentStatus:v,hasError:o,output:n,elapsedSeconds:C,tokensUsed:k})),st.createElement(HookLines,{lines:L,showTreeConnector:h,closesFrame:j}),I&&renderOutputWithRepairNotes({output:x?stripAgentUsageTrailer(n??""):n??"",isTodos:l,isThinking:a,isEditFile:c,isWriteFile:d,metadata:s,expandedOutput:i||x,isPermissionDenied:g,input:t,hasError:o,name:e,expandKey:f,showTreeConnector:h,closesFrame:U}),st.createElement(HookLines,{lines:O,showTreeConnector:h,closesFrame:F}),st.createElement(HookOutcome,{outcome:s?.hookOutcome,showTreeConnector:h}),_&&st.createElement(Qe,{columnGap:1,marginLeft:1},st.createElement(Xe,{color:zR},yL," "),st.createElement(Xe,{color:ER.GRAY},"Processing…"))))}function renderOutputWithRepairNotes({output:e,isTodos:t,isThinking:n,isEditFile:r,isWriteFile:o,metadata:s,expandedOutput:i,isPermissionDenied:a,input:l,hasError:c,name:d,expandKey:u,showTreeConnector:m,closesFrame:p}){const{body:g}=extractRepairNotes(e);return st.createElement(Qe,{marginLeft:m?1:0},renderOutputContent({isTodos:t,isThinking:n,isEditFile:r,isWriteFile:o,metadata:s,output:g,expandedOutput:i,isPermissionDenied:a,input:l,hasError:c,name:d,expandKey:u,showTreeConnector:m,closesFrame:p}))}function HookLines({lines:e,showTreeConnector:t,closesFrame:n=!1}){if(!e||0===e.length)return null;const r=e.length-1;return st.createElement(Qe,{flexDirection:"column",marginLeft:t?1:0},e.map((e,t)=>{const o=n&&t===r?yL:SL;return st.createElement(Qe,{key:t,columnGap:1},st.createElement(Xe,{color:zR},o),st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},e)))}))}function HookOutcome({outcome:e,showTreeConnector:t}){if(!e)return null;const n="stop"===e.kind?ER.YELLOW:ER.RED;return st.createElement(Qe,{columnGap:1,marginLeft:t?1:0},st.createElement(Xe,{color:zR},yL),st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:n},e.text)))}__name(DiffWordSegments,"DiffWordSegments"),__name(DiffRow,"DiffRow"),__name(renderDiffLine,"renderDiffLine"),__name(DiffMetadata,"DiffMetadata"),__name(generateDiff,"generateDiff"),__name(resolveTodoTextStyle,"resolveTodoTextStyle"),__name(TodoChecklist,"TodoChecklist"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(computeDisplayInput,"computeDisplayInput"),__name(formatToolInput,"formatToolInput"),__name(ReadToolInlineSummaryRow,"ReadToolInlineSummaryRow"),__name(resolveSymbol,"resolveSymbol"),__name(ToolHeader,"ToolHeader"),__name(stripAgentUsageTrailer,"stripAgentUsageTrailer"),__name(AgentStatus,"AgentStatus"),__name(getTruncatedOutputParts,"getTruncatedOutputParts"),__name(renderTruncatedOutput,"renderTruncatedOutput"),__name(renderEditFileDiff,"renderEditFileDiff"),__name(renderWriteFileContent,"renderWriteFileContent"),__name(renderOutputContent,"renderOutputContent"),__name(renderTextWithLongConnector,"renderTextWithLongConnector"),__name(ToolMessage,"ToolMessage"),__name(renderOutputWithRepairNotes,"renderOutputWithRepairNotes"),__name(HookLines,"HookLines"),__name(HookOutcome,"HookOutcome");var ZN=createNodeRuntime(),e_=__name(({label:e,isSelected:t})=>e.includes("[shift+tab]")?st.createElement(st.Fragment,null,e.split("[shift+tab]")[0],st.createElement(BracketWrap,{color:t?wO:vO,bold:!0},"shift+tab")):e.includes("(")?st.createElement(st.Fragment,null,e.split("(")[0],st.createElement(Xe,{color:ER.GRAY},"(",e.split("(")[1])):e,"ChoiceLabel"),t_=__name(({request:e,onResponse:t,onEnableAutoAccept:n})=>{const[r]=at(0),[o,s]=at(1);ct(()=>{"edit"===e.action&&e.oldContent&&e.filePath&&resolveEditStartLine({runtime:ZN,filePath:e.filePath,oldContent:e.oldContent}).then(e=>{void 0!==e&&s(e)}).catch(()=>{})},[e.filePath,e.oldContent,e.action]);const i=getPermissionChoicesForRisk({choices:lM,risk:e.risk}),a=__name(e=>{const r=i.find(t=>t.value===e.value);r&&(t(r),"yes-session"===r.value&&n&&n())},"handleSelect"),l=__name(()=>"edit"===e.action?"make this edit to":"create"===e.action?"create":"delete"===e.action?"delete":"execute"===e.action?"execute":"modify","getActionDescription"),c=getDisplayPath({filePath:e.filePath,cwd:process.cwd()}),d=__name(()=>"edit"===e.action?"Edit File":"create"===e.action?"Create File":"delete"===e.action?"Delete File":"execute"===e.action?"Execute File":"File Operation","getHeading");return st.createElement(bO,{title:`${d()}${"edit"===e.action?` ${c}`:""}`,footer:st.createElement(YN,{hint:"↑/↓ navigate · enter select"})},"edit"===e.action&&e.oldContent&&e.newContent&&st.createElement(Qe,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c,marginLeft:0,startLine:o}).diffContent),e.risk&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0,color:ER.RED,wrap:"wrap"},gt.warning," ",getRiskDisplay(e.risk))),st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0},"Do you want to ",l()," ",st.createElement(Xe,{color:wO},c),"?")),st.createElement(SelectInput,{items:i.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:r,indicatorComponent:jN,itemComponent:({label:e,isSelected:t})=>st.createElement(BN,{isSelected:t},st.createElement(e_,{label:e,isSelected:t}))}))},"PermissionPrompt");Gt(),SR();var n_=NE?"ctrl+y":"ctrl+e",r_=__name(({request:e,onResponse:t})=>{const[n]=at(0),[r,o]=at({phase:"idle"}),s=e.description??("done"===r.phase?r.explanation:void 0),i=void 0!==e.explain&&void 0===e.description&&"done"!==r.phase;nt((t,n)=>{i&&"loading"!==r.phase&&(isCtrlKey({inputChar:t,key:n,letter:"e",ctrlCode:5})||isCtrlKey({inputChar:t,key:n,letter:"y",ctrlCode:25}))&&(o({phase:"loading"}),e.explain?.().then(e=>{o(e?{phase:"done",explanation:e}:{phase:"failed"})}).catch(()=>o({phase:"failed"})))});const a=getPermissionChoicesForRisk({choices:getShellPermissionChoices({command:e.command,...void 0!==e.args?{args:e.args}:{}}),risk:e.risk}),l=__name(e=>{const n=a.find(t=>t.value===e.value);n&&t(n)},"handleSelect");return st.createElement(bO,{title:"Execute Shell Command",subtitle:st.createElement(Xe,{wrap:"wrap"},"Command Code needs to execute ",st.createElement(Xe,{color:wO},getCommandDisplay(e)),"."),footer:st.createElement(YN,{hint:i?`↑/↓ navigate · enter select · ${n_} explain`:"↑/↓ navigate · enter select"})},e.risk&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0,color:ER.RED,wrap:"wrap"},gt.warning," ",getRiskDisplay(e.risk))),e.workingDirectory&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.GRAY},"Working directory: ",e.workingDirectory)),s&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM,italic:!0},s)),i&&"idle"===r.phase&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM,italic:!0},"Press"," ",st.createElement(BracketWrap,{color:ER.DIM,bold:!0},n_)," ","to explain this command")),"loading"===r.phase&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM,italic:!0},st.createElement(kt,{type:"dots"})," Explaining this command…")),"failed"===r.phase&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM,italic:!0},"Couldn't generate an explanation — press"," ",n_," to retry")),st.createElement(SelectInput,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:n,indicatorComponent:jN,itemComponent:({label:e,isSelected:t})=>st.createElement(BN,{isSelected:t},e.includes("[shift+tab]")?st.createElement(st.Fragment,null,e.split("[shift+tab]")[0],st.createElement(BracketWrap,{color:t?wO:vO,bold:!0},"shift+tab")):e)}))},"ShellPermissionPrompt");function handlePermissionResponse({choice:e,resolve:t,setPendingPermission:n,respondToPrompt:r,setStatus:o,permissionMode:s,showHintMessage:i,allowedStatus:a,deniedStatus:l}){r(e);const c="no"!==e.value;t(c),n(null),c?(o(a),"default"===s&&i("Use shift+tab to enable accept edits")):o(l)}__name(handlePermissionResponse,"handlePermissionResponse");var o_=it(__name(function PermissionView2({pendingPermission:e,permissionMode:t,setPendingPermission:n,setStatus:r,respondToPrompt:o,showHintMessage:s,handleEnableAutoAccept:i}){const a={resolve:e.resolve,setPendingPermission:n,respondToPrompt:o,setStatus:r,permissionMode:t,showHintMessage:s};if("shell_command"===e.toolName){const t=e.params;return st.createElement(Qe,{marginY:1},st.createElement(r_,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Shell command allowed",deniedStatus:"Shell command denied"})}))}if("kill_shell"===e.toolName){const t=buildKillShellPermissionRequest(e.params);return st.createElement(Qe,{marginY:1},st.createElement(r_,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Process termination allowed",deniedStatus:"Process termination denied"})}))}if(isGenericToolRequest(e.params)){const t=e.params;return st.createElement(Qe,{marginY:1},st.createElement(JN,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Tool call allowed",deniedStatus:"Tool call denied"})}))}const l=isFileEditRequest(e.params)?e.params:buildFileToolPermissionRequest({toolName:e.toolName,input:e.params,fallbackDescription:`Allow ${e.toolName} operation`,useInputDescription:!1});return st.createElement(Qe,{marginY:1},st.createElement(t_,{request:l,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"File operation allowed",deniedStatus:"File operation denied"}),onEnableAutoAccept:i}))},"PermissionView"));function isGenericToolRequest(e){return"object"==typeof e&&null!==e&&"toolName"in e&&"string"==typeof e.toolName}function isFileEditRequest(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.action&&"string"==typeof t.filePath}function PlanPanel({content:e,filePath:n,expanded:r}){const{stdout:o}=et(),s=trimPlanMarkdown(e,getCollapsedPlanMaxLines(o?.rows)),i=s.hiddenLineCount>0,a=r?e:s.visible,l=1!==s.hiddenLineCount?"s":"",c=`… +${s.hiddenLineCount} more line${l} · ctrl+o to expand`;return st.createElement(bO,{title:"Plan",titleSuffix:n?` · ${t.basename(n)}`:void 0,gapAfterHeader:!1,hint:i?r?"ctrl+o to collapse":c:void 0},st.createElement(Qe,{marginTop:1},st.createElement(Markdown,null,a)))}__name(isGenericToolRequest,"isGenericToolRequest"),__name(isFileEditRequest,"isFileEditRequest"),Gt(),SR(),Gt(),SR(),__name(PlanPanel,"PlanPanel"),Gt(),SR();var s_=__name(({preview:e})=>{const t=e.trim().split("\n"),n=t.slice(0,8),r=t.length-n.length,o="─".repeat(70),s=`─── ✂ ─── ${r} line${1===r?"":"s"} hidden `,i="─".repeat(Math.max(0,70-s.length));return st.createElement(Qe,{flexDirection:"column",marginTop:1,paddingLeft:4},st.createElement(Xe,{italic:!0,color:ER.DIM},"Preview"),st.createElement(Xe,{color:ER.DIM},`┌${o}┐`),n.map((e,t)=>{const n=e.length>68?e.slice(0,68):e,r=" ".repeat(Math.max(0,68-n.length));return st.createElement(Xe,{key:t},st.createElement(Xe,{color:ER.DIM},"│ "),st.createElement(Xe,{color:ER.GRAY},n),st.createElement(Xe,{color:ER.DIM},`${r} │`))}),r>0?st.createElement(Xe,{color:ER.YELLOW},`├${s}${i}┤`):null,st.createElement(Xe,{color:ER.DIM},`└${o}┘`))},"OptionPreview"),i_=[{label:"1. Submit",value:"submit"},{label:"2. Cancel",value:"cancel"}],a_=__name(({checked:e})=>e?st.createElement(Xe,{color:ER.GREEN},"[",gt.tick,"] "):st.createElement(Xe,{color:ER.DIM},"[ ] "),"MultiSelectCheckbox"),l_=__name((e,t)=>{if(!e.startsWith("option_"))return null;const n=e.slice(7),r=parseInt(n,10);return Number.isNaN(r)||r<0||r>t?null:r},"parseOptionIndex"),c_=__name((e,t)=>{const n=new Set(e);return n.has(t)?(n.delete(t),n):(n.add(t),n)},"toggleLabel"),d_=__name((e,t)=>e?{indicator:gt.bullet,color:wO}:t?{indicator:gt.tick,color:ER.GREEN}:{indicator:gt.circle,color:ER.GRAY},"getTabMarker"),u_=__name(({questions:e,currentIndex:t,answeredQuestions:n,isReviewPage:r,hideReview:o=!1})=>{if(o&&1===e.length)return null;const s=[];if(e.forEach((o,i)=>{const a=i===t&&!r,l=n.has(i),{indicator:c,color:d}=d_(a,l);s.push(st.createElement(Xe,{key:i},st.createElement(Xe,{color:d},c),st.createElement(Xe,{color:a?wO:void 0}," ",o.header),i<e.length-1?st.createElement(Xe,{color:ER.DIM}," | "):null))}),!o){const e=r;s.push(st.createElement(Xe,{key:"review"},st.createElement(Xe,{color:ER.DIM}," | "),st.createElement(Xe,{color:e?wO:ER.GRAY},e?gt.bullet:gt.circle),st.createElement(Xe,{color:e?wO:void 0,bold:e}," ","Review")))}return st.createElement(Qe,null,s)},"TabIndicator"),m_=__name(({questions:e,onResponse:t,hideCustomInput:n=!1,compact:r=!1})=>{const[o,s]=at(0),[i,a]=at(new Map),l=lt(null);null===l.current&&(l.current=new Map);const c=l.current,[d,u]=at(""),[m,p]=at(new Set),[g,h]=at(null),[f,y]=at(!1),[S,w]=at(!1),[v,k]=at(!1),[C,b]=at(null),[E,T]=at(!1),P=lt(null);null===P.current&&(P.current=new Map);const M=lt(null);null===M.current&&(M.current=new Map);const[x,I]=at(!1),[A,R]=at(""),[,L]=at(0),O=e[o],D=O?.multiSelect??!1,$=i.get(o),N=O?[...O.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description,...void 0!==e.preview?{preview:e.preview}:{}}))]:[],_=N.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),F=new Map(_.map((e,t)=>[e.label,N[t]])),U=__name((e,t)=>{t.size>0?c.set(e,Array.from(t)):c.delete(e)},"saveOrClearMultiAnswer"),j=__name(t=>{const n=e[t],r=c.get(t);if(n?.multiSelect&&r){p(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));return void u(e||"")}if(p(new Set),!n?.multiSelect&&1===r?.length){const e=r[0],t=!n?.options.some(t=>t.label===e);return void u(t&&e?e:"")}u("")},"restoreInputsForQuestion"),B=__name(e=>{"submit"!==e.value?"cancel"===e.value&&t({answers:[]}):q()},"handleReviewSelect"),W=__name(()=>{if(!$||0===$.length)return 0;const e=$[0],t=O.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),H=__name(e=>{if(f)return;if(D){const t=l_(e.value,O.options.length-1);if(null===t)return;const n=O.options[t]?.label||"";return void p(e=>c_(e,n))}const t=l_(e.value,O.options.length-1);if(null===t)return;y(!0);const n=O.options[t]?.label||"";z([n])},"handleSelect"),G=__name(()=>{if(f)return;y(!0);const e=Array.from(m);z(e)},"handleMultiSelectDone"),V=__name(()=>{if(f)return;const e=d.trim();if(e){if(D){const t=new Set(O.options.map(e=>e.label));return void p(n=>{const r=new Set;return n.forEach(e=>{t.has(e)&&r.add(e)}),r.add(e),r})}y(!0),z([e])}},"handleOtherSubmit"),z=__name(t=>{c.set(o,t);const r=new Map(c);if(a(r),o<e.length-1){const e=o+1;return j(e),s(e),y(!1),k(!1),b(null),void T(!1)}if(e.every((e,t)=>r.has(t)))return n&&1===e.length?void q():(p(new Set),u(""),k(!1),T(!1),b(null),w(!0),void y(!1));const i=e.findIndex((e,t)=>!r.has(t));-1!==i&&(j(i),s(i)),y(!1),k(!1),b(null),T(!1)},"finishQuestion"),K=__name(()=>e.map((e,t)=>{const n=c.get(t)||[],r=M.current?.get(t),o=0===n.length&&r?.length?["(Image attached)"]:n,s=P.current?.get(t)?.trim(),i=e.multiSelect||1!==n.length?void 0:e.options.find(e=>e.label===n[0]);return{questionIndex:t,selectedOptions:o,...i?.preview?{preview:i.preview}:{},...s?{notes:s}:{},...r?.length?{images:r}:{}}}),"buildAnswers"),q=__name(()=>{t({answers:K()})},"submitAnswers"),Y=__name(()=>{t({answers:K(),disposition:"chat"})},"chatAboutQuestions"),J=__name(()=>{P.current&&(A.trim()?P.current.set(o,A):P.current.delete(o)),I(!1)},"saveNotesAndClose"),Q=__name(async()=>{try{const e=await detectClipboardImage();if(!e)return;const t=M.current?.get(o)??[];M.current?.set(o,[...t,{data:e.data,mediaType:e.mediaType}]),L(e=>e+1)}catch{}},"pasteClipboardImageIntoQuestion"),X=__name(async(e,t)=>{try{const n=await openInEditor(e);n!==e&&t(n)}catch{}},"editExternally"),Z=__name(e=>{w(!1),s(e),T(!1),k(!1),b(null),j(e)},"editQuestion"),ee=__name(t=>{t<0||t>=e.length||(D&&(U(o,m),a(new Map(c))),y(!1),k(!1),b(null),T(!1),j(t),s(t))},"navigateToQuestion"),te=__name(()=>{if(!g||!D)return;if("done"===g.value)return;const e=l_(g.value,O.options.length-1);if(null===e)return;const t=O.options[e]?.label||"";p(e=>c_(e,t))},"toggleMultiSelection"),ne=__name(e=>{const t=_[0],r=_[_.length-1],o=g&&t&&g.value===t.value,s=g&&r&&g.value===r.value;if(!e.downArrow||v||E||n||!(_.length>0)||!s)return e.upArrow&&!v&&!E&&_.length>0&&o?D?void T(!0):void(n||(k(!0),b(_.length-1))):e.upArrow&&v?(k(!1),b(_.length-1),void(r&&h(r))):e.downArrow&&v?(k(!1),D?void T(!0):(b(0),void(t&&h(t)))):e.upArrow&&E?(T(!1),void k(!0)):e.downArrow&&E?(T(!1),b(0),void(t&&h(t))):void(e.return&&E&&D&&G());k(!0)},"handleVerticalNav"),re=__name(t=>{f||v||E||(S?t.leftArrow&&Z(e.length-1):t.leftArrow&&o>0?ee(o-1):t.rightArrow&&(o<e.length-1?ee(o+1):(D&&(U(o,m),a(new Map(c))),w(!0))))},"handleHorizontalNav"),oe=__name(()=>{if(!f)if(S)w(!1);else{if(v){k(!1);const e=C??_.length-1;b(e);const t=_[e];return void(t&&h(t))}if(E){T(!1);const e=_[_.length-1];e&&h(e)}}},"handleEscape");if(nt((e,t)=>{const r="v"===e&&(t.ctrl||t.meta&&"darwin"!==process.platform);if(x)t.escape?J():r?Q():t.ctrl&&"g"===e&&X(A,R);else if(r&&v)Q();else if(t.ctrl&&"g"===e&&v)X(d,u);else{if(" "===e&&D&&!v&&te(),"d"!==e||!D||v||S||G(),!(v||S||f||n)){if("n"===e)return R(P.current?.get(o)??""),void I(!0);if("c"===e)return void Y()}S||f||ne(t),re(t),t.escape&&oe()}}),!O&&!S)return null;if(S)return st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(ZR,{dividerColor:SO}),st.createElement(Qe,{marginBottom:1},st.createElement(u_,{questions:e,currentIndex:e.length,answeredQuestions:new Set(i.keys()),isReviewPage:!0})),e.some((e,t)=>!i.get(t)?.length)&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.YELLOW},"⚠ You have not answered all questions")),e.map((e,t)=>st.createElement(Qe,{key:t,marginBottom:1,flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},t+1,". ",e.question),st.createElement(Xe,{color:ER.GREEN}," ",i.get(t)?.join(", ")||"No answer"))),st.createElement(SelectInput,{items:i_,onSelect:B,initialIndex:0,indicatorComponent:jN,itemComponent:WN}),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{italic:!0,color:ER.DIM},gt.arrowLeft," to go back and edit")));const se=r&&1===e.length;return st.createElement(Qe,{flexDirection:"column",width:"100%"},!se&&st.createElement(ZR,{dividerColor:SO}),!se&&st.createElement(Qe,{marginBottom:1},st.createElement(u_,{questions:e,currentIndex:o,answeredQuestions:new Set(i.keys()),isReviewPage:!1,hideReview:n})),st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0,color:fO},O.question)),v||E||x?st.createElement(Qe,{flexDirection:"column"},_.map((e,t)=>{const n=F.get(e.label),r=D&&n&&m.has(n.label),o=!D&&n&&$?.includes(n.label),s=r||o;return st.createElement(Qe,{key:e.value,flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,null," "),st.createElement(BN,{isActive:s,idleColor:ER.GRAY}," ",t+1,"."," "),D&&st.createElement(a_,{checked:s}),st.createElement(BN,{isActive:s,idleColor:ER.GRAY},n?.label||""),!D&&s&&st.createElement(HN,null)),n?.description&&st.createElement(Qe,null,st.createElement(Xe,null," "),st.createElement(GN,{indent:D?7:4},n.description)))})):st.createElement(SelectInput,{key:`${o}-${C??"default"}`,items:_,initialIndex:C??W(),onSelect:H,onHighlight:h,indicatorComponent:jN,itemComponent:({label:e,isSelected:t})=>{const n=F.get(e),r=D&&n&&m.has(n.label),o=!D&&n&&$?.includes(n.label),s=r||o,i=e.match(/^\s*(\d+)\.\s*(.*)$/),a=i?.[1]||"",l=i?.[2]||e;return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(BN,{isSelected:t,isActive:s}," ",a,"."," "),D&&st.createElement(a_,{checked:s}),st.createElement(BN,{isSelected:t,isActive:s},l),!D&&s&&st.createElement(HN,null)),n?.description&&st.createElement(GN,{indent:D?7:4},n.description))}}),!v&&!E&&(()=>{const e=(g?F.get(g.label):void 0)??N[C??W()];return e?.preview?st.createElement(s_,{preview:e.preview}):null})(),!n&&st.createElement(Qe,null,st.createElement(jN,{isSelected:v}),st.createElement(BN,{isSelected:v}," ",_.length+1,"."," "),D&&st.createElement(a_,{checked:m.has(d.trim())}),st.createElement(TextInput,{value:d,onChange:e=>{const t=e.replace(/\r\n/g," ").replace(/[\r\n]/g," "),n=d.trim();u(t),D&&p(e=>{const r=new Set(e);return n&&r.has(n)&&r.delete(n),t.trim()&&r.add(t.trim()),r})},onSubmit:V,placeholder:"Type something...",focus:v,stripBracketedPaste:!0})),x?st.createElement(Qe,null,st.createElement(jN,{isSelected:!0}),st.createElement(BN,{isSelected:!0}," ","notes:"," "),st.createElement(TextInput,{value:A,onChange:R,onSubmit:J,placeholder:"Add notes on this design…",focus:x,stripBracketedPaste:!0})):(()=>{const e=P.current?.get(o)?.trim();return e?st.createElement(Qe,null,st.createElement(Xe,{italic:!0,color:ER.DIM}," ","notes: ",e)):null})(),(M.current?.get(o)??[]).map((e,t)=>st.createElement(Qe,{key:t},st.createElement(Xe,{color:ER.DIM}," ","[Image #",t+1," attached —"," ",e.mediaType,"]"))),D&&st.createElement(Qe,null,st.createElement(jN,{isSelected:E}),st.createElement(BN,{isSelected:E}," ",o===e.length-1?"Submit":"Next")),e.length>1&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{italic:!0,color:ER.DIM},"Enter to select | Arrow keys to navigate |"," ",n?"Esc to cancel":"1-9 quick select | n notes | c chat | Esc to cancel")))},"QuestionPrompt");function QuestionView({pendingQuestion:e,setPermissionMode:t,dangerouslySkipPermissions:n,setPendingQuestion:r,setStatus:o,setStaticKey:s}){const[i,a]=at(!1),l=e.params.planContent;return nt((e,t)=>{l&&getIsExpandToolShortcut(t,e)&&a(e=>!e)}),st.createElement(Qe,{marginY:1,flexDirection:"column"},l&&st.createElement(Qe,{marginBottom:1},st.createElement(PlanPanel,{content:l,filePath:e.params.planFilePath,expanded:i})),st.createElement(m_,{questions:e.params.questions,hideCustomInput:e.params.hideCustomInput,compact:e.params.compact,onResponse:i=>{const a=resolvePlanModeAnswerTransition({answer:i.answers[0]?.selectedOptions[0]||"",exitPlanMode:e.params.exitPlanMode,enterPlanMode:e.params.enterPlanMode,dangerouslySkipPermissions:n});a&&t(a),e.resolve(i),r(null),o("Answers submitted"),hardResetForResize(),s(e=>e+1)}}))}__name(QuestionView,"QuestionView"),Gt(),SR();var p_="__skip__",g_=__name(({suggestion:e,onSelect:t,onClose:n})=>{const{completedMode:r,primary:o,secondary:s,description:i}=e,a=[...o.map(e=>({label:e,value:e,isPrimary:!0})),...s.map(e=>({label:e,value:e,isPrimary:!1})),{label:"skip",value:p_,isPrimary:!1}],l=new Map(a.map(e=>[e.label,e]));nt((e,t)=>{t.escape&&n()});const c=__name(e=>{e.value!==p_?(t(e.value),n()):n()},"handleSelect");return st.createElement(bO,{title:`/design ${r} complete`,titleSuffix:` · ${i}`,hint:"Enter to run · Esc to dismiss"},st.createElement(SelectInput,{items:a,onSelect:c,indicatorComponent:KN,itemComponent:({label:e,isSelected:t})=>{const n=l.get(e),r=n?.value===p_,o=n?.isPrimary??!1,s=r?"run /design manually":hy[e]??"";return st.createElement(Qe,{flexDirection:"column"},st.createElement(VN,{isSelected:t,idleColor:o?ER.WHITE:ER.DIM},r?" skip ":` /design ${e} `),s&&st.createElement(VN,{isSelected:t,idleColor:ER.DIM,bold:!1},` ${s} `))}}))},"DesignModeSelector");function getUsageToneColor(e){return"danger"===e?ER.RED:"warning"===e?ER.YELLOW:ER.GREEN}function getDistanceToneColor(e){return"danger"===e?ER.RED:"warning"===e?ER.YELLOW:ER.GRAY}function ContextProgress({view:e,progressBarWidth:t}){const n=getUsageToneColor(e.tone),r=buildBlockBar({percentage:e.percentage,width:t});return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{marginBottom:1},st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:ER.BLUE,color:"#f4f4f4",bold:!0},`${wL}CONTEXT${wL}`)),st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:ER.GRAY},e.modelLabel)),st.createElement(Qe,null,st.createElement(Xe,{color:n},r.filled),st.createElement(Xe,{color:$R},r.empty),st.createElement(Xe,{bold:!0,color:n},` ${e.percentageLabel}`)),st.createElement(Qe,null,st.createElement(Xe,null,e.tokensUsedLabel),st.createElement(Xe,{color:ER.GRAY},` / ${e.tokenLimitLabel}`),st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:n},e.tokensRemainingLabel),st.createElement(Xe,{color:ER.GRAY}," remaining"),e.isEstimated&&st.createElement(Xe,{color:ER.DIM}," (estimated)")))}function CompactionDistance({view:e}){if(!e)return null;const t=getDistanceToneColor(e.tone);return st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:t},e.tokensAwayLabel),st.createElement(Xe,{color:ER.DIM},e.label))}function BreakdownRow({item:e,labelWidth:t}){return st.createElement(Qe,null,st.createElement(Xe,null,e.name.padEnd(t)),st.createElement(Xe,{bold:!0},e.paddedValue),st.createElement(Xe,{color:ER.GRAY}," tokens"),e.detail&&st.createElement(Xe,{color:ER.DIM},` · ${e.detail}`))}function ContextBreakdown({view:e,labelWidth:t}){return 0===e.rows.length?null:st.createElement(Qe,{flexDirection:"column",marginTop:1},e.rows.map(e=>st.createElement(BreakdownRow,{key:e.name,item:e,labelWidth:t})))}function ContextTips({tips:e}){return 0===e.length?null:st.createElement(Qe,{flexDirection:"column",marginTop:1},e.map(e=>st.createElement(Qe,{key:e},st.createElement(Xe,{color:ER.CYAN},gt.pointer),st.createElement(Xe,{color:ER.GRAY}," ",e))))}function ContextMessage({analysis:e}){const t=projectContextView(e,{terminalWidth:useTerminalWidth(),modelDisplayName:getModelDisplayName(e.model)});return st.createElement(Qe,{flexDirection:"column",paddingTop:1},st.createElement(ContextProgress,{view:t.progress,progressBarWidth:t.layout.progressBarWidth}),st.createElement(CompactionDistance,{view:t.compactionDistance}),st.createElement(ContextBreakdown,{view:t.breakdown,labelWidth:t.layout.labelWidth}),st.createElement(ContextTips,{tips:t.tips}))}function ContextConfigView({staticKey:e,sessionId:t,onClose:n,setInput:r}){const[o,s]=at(null),[i,a]=at(null);return ct(()=>{let e=!0;return __name(async()=>{const n=k$(t);if(n)try{const t=await analyzeCommandContext({messages:harnessSessionMessages(n),deps:{getContextLimit:__name(e=>customAwareContextLimit({modelId:e,fallback:getContextLimit}),"getContextLimit")}});e&&s(t)}catch{e&&a("Failed to analyze context.")}else e&&a("No active conversation. Start chatting first.")},"load")(),()=>{e=!1}},[t]),nt((e,t)=>{t.escape&&(r(""),n())}),st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(ContextBody,{error:i,analysis:o}),st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Press ",st.createElement(gO,null,"Esc")," to return to conversation"))))}function ContextBody({error:e,analysis:t}){return e?st.createElement(bO,{title:"Context",gapAfterHeader:!1},st.createElement(Xe,{color:ER.DIM},e)):t?st.createElement(ContextMessage,{analysis:t}):st.createElement(bO,{title:"Context",gapAfterHeader:!1},st.createElement(A$,{label:"Loading context analysis"}))}Gt(),SR(),Gt(),SR(),__name(getUsageToneColor,"getUsageToneColor"),__name(getDistanceToneColor,"getDistanceToneColor"),__name(ContextProgress,"ContextProgress"),__name(CompactionDistance,"CompactionDistance"),__name(BreakdownRow,"BreakdownRow"),__name(ContextBreakdown,"ContextBreakdown"),__name(ContextTips,"ContextTips"),__name(ContextMessage,"ContextMessage"),__name(ContextConfigView,"ContextConfigView"),__name(ContextBody,"ContextBody"),Gt(),Gt(),SR(),Gt(),SR();var h_="https://commandcode.ai/studio";function getVersionStatus(){try{return{current:getPackageJson(import.meta.url).version??"Unknown",updateAvailable:null}}catch{return{current:"Unknown",updateAvailable:null}}}async function getAuthStatus(){try{const e=await checkCommandAuthStatus({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env}),t=e.userName||null;return{authenticated:e.authenticated,username:t}}catch{return{authenticated:!1,username:null}}}async function getModelStatus(e){try{const t=e?.sessionId?k$(e.sessionId):void 0,n=t?.getModel()??await getSelectedModel(),r=getProviderDisplayName((await loadUserConfig()).provider||null),o=getModelShortName({modelId:n,findModelById:findModelById});let s;return modelSupportsReasoningEffort(n)&&(s=t?t.getEffort():getReasoningEffort(n)),{id:n,displayName:s?`${o} with ${s} effort`:o,provider:r}}catch{return{id:"Unknown",displayName:"Unknown",provider:"Unknown"}}}function getPrStatus(e){try{const t=getCachedPR(e);return t?{number:t.number,url:t.url,state:t.state}:null}catch{return null}}function gatherStatusData(e){const t=e?.runtime??createNodeRuntime();return getStatusSnapshot({runtime:t,version:getVersionStatus,auth:getAuthStatus,model:__name(()=>getModelStatus({sessionId:e?.sessionId}),"model"),pr:getPrStatus,taste:__name(()=>getTasteStatus({runtime:t,learningEnabled:isTasteLearningEnabled,byokSuppressed:isByok({model:getConfiguredModel()})}),"taste"),system:__name(()=>getSystemStatus({runtime:t,arch:process.arch,nodeVersion:process.version}),"system"),disabledSkillNames:__name(async()=>(await loadCommandDisabledSkills()).names,"disabledSkillNames")})}__name(getVersionStatus,"getVersionStatus"),__name(getAuthStatus,"getAuthStatus"),__name(getModelStatus,"getModelStatus"),__name(getPrStatus,"getPrStatus"),__name(gatherStatusData,"gatherStatusData");var f_=__name(({label:e,value:t,valueColor:n,dimValue:r})=>st.createElement(Qe,null,st.createElement(Xe,{dimColor:!0},`${e}:`.padEnd(14)),r?st.createElement(Xe,{dimColor:!0},t):st.createElement(Xe,{color:n},t)),"Row");function StatusMessage({statusData:e}){const t=projectStatusView(e,{profileBaseUrl:"https://commandcode.ai"}),n=t.account.authenticated?gt.tick:gt.cross,r=t.account.authenticated?ER.WHITE:OR.ERROR;return st.createElement(Qe,{flexDirection:"column",paddingX:0},st.createElement(Qe,null,st.createElement(Xe,{color:TR,bold:!0},"Command Code"," "),st.createElement(Xe,{dimColor:!0},t.versionText)),st.createElement(Qe,null,st.createElement(Xe,{dimColor:!0},"Visit "),st.createElement(cL,{url:h_,text:h_,color:ER.CYAN}),st.createElement(Xe,{dimColor:!0}," for usage and billing")),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{dimColor:!0},"Account:".padEnd(14)),t.account.username&&t.account.profileUrl?st.createElement(st.Fragment,null,st.createElement(cL,{url:t.account.profileUrl,text:t.account.label,color:ER.CYAN}),st.createElement(Xe,{color:r}," ",n)):t.account.authenticated?st.createElement(st.Fragment,null,st.createElement(Xe,null,t.account.label),st.createElement(Xe,{color:r}," ",n)):st.createElement(st.Fragment,null,st.createElement(Xe,{color:OR.WARNING},t.account.label),st.createElement(Xe,{color:r}," ",n),st.createElement(Xe,{dimColor:!0}," — run "),st.createElement(Xe,{bold:!0},t.account.loginHint))),st.createElement(f_,{label:"Model",value:t.model.value}),st.createElement(f_,{label:"Branch",value:t.branch.value,dimValue:t.branch.dim}),t.worktree?st.createElement(f_,{label:"Worktree",value:t.worktree.value}):null,t.repository?st.createElement(Qe,null,st.createElement(Xe,{dimColor:!0},"Repository:".padEnd(14)),st.createElement(cL,{url:t.repository.url,text:t.repository.text,color:ER.CYAN}),t.pullRequest?st.createElement(st.Fragment,null,st.createElement(Xe,{dimColor:!0}," · "),st.createElement(cL,{url:t.pullRequest.url,text:t.pullRequest.text,color:t.pullRequest.open?ER.CYAN:ER.GRAY}),st.createElement(Xe,{dimColor:!0}," ","(",t.pullRequest.stateLabel,")")):null):t.pullRequest?st.createElement(Qe,null,st.createElement(Xe,{dimColor:!0},"Pull Request:".padEnd(14)),st.createElement(cL,{url:t.pullRequest.url,text:t.pullRequest.text,color:t.pullRequest.open?ER.CYAN:ER.GRAY}),st.createElement(Xe,{dimColor:!0}," (",t.pullRequest.stateLabel,")")):null,st.createElement(f_,{label:"Taste",value:t.taste.value,dimValue:t.taste.dim}),st.createElement(f_,{label:"Directory",value:t.directory.value}),st.createElement(f_,{label:"Skills",value:t.skills.value,dimValue:t.skills.dim}),st.createElement(f_,{label:"Agents",value:t.agents.value,dimValue:t.agents.dim}),st.createElement(f_,{label:"System",value:t.system.value}),t.proxy?st.createElement(f_,{label:"Proxy",value:t.proxy.value}):null)}function StatusBody({state:e}){return"ready"===e.phase?st.createElement(StatusMessage,{statusData:e.data}):"error"===e.phase?st.createElement(Xe,{dimColor:!0},"Could not load status: ",e.message):st.createElement(Xe,{dimColor:!0},"Gathering status…")}function StatusConfigView({staticKey:e,sessionId:t,onClose:n,setInput:r}){const[o,s]=at({phase:"loading"});return ct(()=>{let e=!1;return gatherStatusData({sessionId:t}).then(t=>{e||s({phase:"ready",data:t})}).catch(t=>{if(e)return;const n=t instanceof Error?t.message:"Failed to gather status";s({phase:"error",message:n})}),()=>{e=!0}},[t]),nt((e,t)=>{t.escape&&(r(""),n())}),st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(StatusBody,{state:o}),st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Press ",st.createElement(gO,null,"Esc")," to return to conversation"))))}__name(StatusMessage,"StatusMessage"),__name(StatusBody,"StatusBody"),__name(StatusConfigView,"StatusConfigView"),Gt(),SR(),SR(),Gt(),SR();var{addDirectory:y_,formatDirectoryForDisplay:S_,getAdditionalDirectories:w_,removeAdditionalDirectory:v_}=By,k_=__name(({onClose:e})=>{const[t,n]=at(""),[r,o]=at(null),[s,i]=at([]),[a,l]=at(()=>w_()),[c,d]=at(()=>({zone:"input",suggestionIndex:0,activeDirIndex:0})),[u,m]=at(0);ct(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),m(0)},[t]),ct(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const p=__name(e=>{const t=y_(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(w_()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),g=__name(e=>{if(!v_(e))return o({tone:"error",text:`${S_(e)} is no longer in workspace scope`}),void l(w_());o({tone:"success",text:`Removed ${S_(e)} from directory scope`}),l(w_()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");nt((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===c.zone&&s[c.suggestionIndex]?void p(s[c.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===c.zone&&a[c.activeDirIndex])g(a[c.activeDirIndex]);else{if(r.tab&&s.length>0){const e=s[c.suggestionIndex]??s[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),o(null)))}r.downArrow?d(e=>moveAddDirFocusDown(e,{suggestionCount:s.length,activeDirCount:a.length})):r.upArrow&&d(e=>moveAddDirFocusUp(e,{suggestionCount:s.length,activeDirCount:a.length}))}}}),ct(()=>{"suggestions"===c.zone&&m(e=>getAdjustedSuggestionOffset({selectedIndex:c.suggestionIndex,currentOffset:e,maxVisible:aR,totalSuggestions:s.length}))},[c,s.length]),ct(()=>{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 h=s.slice(u,u+aR),f=getAddDirFooterText({focusZone:c.zone});return st.createElement(bO,{title:"Add directory to workspace",subtitle:st.createElement(Xe,{color:ER.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),footer:st.createElement(Xe,{italic:!0,color:ER.DIM},st.createElement(BracketedText,{text:f,color:ER.DIM})),gapAfterHeader:!1},st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Xe,{color:ER.GRAY},"Added directories"),0===a.length?st.createElement(Xe,{color:ER.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===c.zone&&c.activeDirIndex===t;return st.createElement(Qe,{key:e},st.createElement(Xe,null," "),st.createElement(jN,{isSelected:n}),st.createElement(BN,{isSelected:n,isActive:!0}," ",S_(e)))})),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{bold:!0,color:ER.WHITE},"Path")),st.createElement(Qe,null,st.createElement(TextInput,{value:t,focus:"input"===c.zone,prefix:`${"input"===c.zone?gt.pointer:" "} `,prefixColor:"input"===c.zone?wO:ER.GRAY,onChange:e=>{n(e),o(null)},onSubmit:p})),!t&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:{error:ER.RED,warning:ER.YELLOW,success:ER.GREEN}[r.tone]},r.text)),s.length>0&&st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.GRAY},"Suggestions"),h.map((e,t)=>{const n=u+t,r="suggestions"===c.zone&&c.suggestionIndex===n;return st.createElement(Qe,{key:e},st.createElement(Xe,null," "),st.createElement(jN,{isSelected:r}),st.createElement(BN,{isSelected:r,idleColor:ER.GRAY}," ",e))})))},"AddDirModal");function createBillingTransport(){const e=createApiClient({baseUrl:getApiBaseUrl()});return{get:__name(({route:t})=>e.get({endpoint:t}),"get"),post:__name(({route:t,body:n})=>e.post({endpoint:t,body:n}),"post"),postMultipart:__name(()=>Promise.reject(new Error("billing transport does not upload multipart")),"postMultipart"),delete:__name(({route:t})=>e.delete({endpoint:t}),"delete"),postStream:__name(()=>Promise.reject(new Error("billing transport does not stream")),"postStream")}}Gt(),Gt(),SR(),Gt(),SR(),Gt(),SR(),Gt(),Gt(),SR(),Gt(),SR(),__name(createBillingTransport,"createBillingTransport");var C_=null;function getBilling(){return C_||(C_=createBilling({transport:createBillingTransport()})),C_}function getCachedBillingContext(){return C_?.getCached()??null}function getBillingContext(){return getBilling().get()}function prefetchBillingContext(){getBilling().prefetch()}function invalidateBillingContext(){C_=null}function buildLaneModelPickerGroups(){const e=filterModelGroupsByRegisteredModules(ID).filter(e=>e.providerId!==uo.COMMAND);return[...buildModelPickerGroups({normalModeGroups:AD}),...e,...buildCustomModelPickerGroups()]}function buildCatalogModelPickerGroups(){return[...buildModelPickerGroups({normalModeGroups:AD}),...buildCustomModelPickerGroups()]}function laneServesModel(e){if(e.activeLane===uo.COMMAND)return!0;const t=Qo[e.activeLane]?.supportedModelProviders;if(!t)return!0;const n=Object.values(lD).find(t=>t.id===e.modelId);return!n||laneSupportsModel(t,n)}function laneModelCount(e){return e.laneId===uo.COMMAND?AD.reduce((e,t)=>e+t.models.length,0):ID.find(t=>t.providerId===e.laneId)?.models.length??0}function defaultModelForLane(e){const t=filterModelGroupsByRegisteredModules(ID),n=t.filter(t=>t.providerId===e.activeLane),r=n.length>0?n:t.filter(e=>e.providerId===uo.COMMAND);return r[0]?.models[0]?.id}function useCustomModelsReady(e){const[t,n]=at(!1);return ct(()=>{let t=!0;return(async()=>{await refreshCustomProviderModels(e?{sessionId:e}:void 0),t&&n(!0)})(),()=>{t=!1}},[e]),t}__name(getBilling,"getBilling"),__name(getCachedBillingContext,"getCachedBillingContext"),__name(getBillingContext,"getBillingContext"),__name(prefetchBillingContext,"prefetchBillingContext"),__name(invalidateBillingContext,"invalidateBillingContext"),Gt(),SR(),__name(buildLaneModelPickerGroups,"buildLaneModelPickerGroups"),__name(buildCatalogModelPickerGroups,"buildCatalogModelPickerGroups"),__name(laneServesModel,"laneServesModel"),__name(laneModelCount,"laneModelCount"),__name(defaultModelForLane,"defaultModelForLane"),Gt(),__name(useCustomModelsReady,"useCustomModelsReady"),Gt(),SR();var b_=__name((e,t)=>{const n=t&&e.id===TD?" (default)":"",r="free"===e.badge?" (FREE)":"";return e.label.length+n.length+r.length},"renderedLabelLength");function getModelLabelColumnWidth(e,{showDefaultBadge:t=!0}={}){return e.reduce((e,n)=>Math.max(e,b_(n,t)+2),32)}__name(getModelLabelColumnWidth,"getModelLabelColumnWidth");var E_=__name(({model:e,providerId:t,isHighlighted:n,isCurrent:r,showProviderLabel:o,showDefaultBadge:s=!0,labelColumnWidth:i=32})=>{const a=Qo[t],l=o??a?.showProviderLabelInSelector??!1,c=e.vendorLabel??PD[e.provider],d=s&&e.id===TD,u="free"===e.badge,m=d?`${e.label} (default)`:e.label,p=u?" (FREE)":"",g=" ".repeat(Math.max(2,i-m.length-p.length)),h=n?KR:void 0,f=e.description?`${l?`${c} · `:""}${e.description}`:"",y=useTerminalWidth()>=i+38&&f;return st.createElement(Qe,null,st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:h,color:r?ER.GREEN:ER.WHITE,bold:r},m),u&&st.createElement(Xe,{backgroundColor:h,color:ER.GREEN,bold:!0},p),y&&st.createElement(Xe,{backgroundColor:h},g)),y&&st.createElement(Qe,{flexShrink:1},st.createElement(Xe,{backgroundColor:h,color:ER.DIM,wrap:"truncate-end"},f)),st.createElement(Xe,{backgroundColor:h,color:ER.GREEN},r?` ${gt.tick} `:" "))},"ModelRow");Gt(),SR();var T_=__name((e,t)=>`${e+1}. ${t}`,"labelText"),P_=__name(({modelLabel:e,supportedEfforts:t,currentEffort:n,onSelect:r,onCancel:o})=>{const s=dt(()=>buildEffortPickerRows(t),[t]),i=dt(()=>{if(void 0===n)return 0;const e=s.findIndex(e=>e.value===n);return e>=0?e:0},[s,n]),a=dt(()=>Math.max(...s.map((e,t)=>T_(t,e.label).length))+4,[s]),{cursor:l}=useListNavigation({items:s,onSelect:__name(e=>r(e.value),"onSelect"),onCancel:o,initialIndex:i,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,selectByNumber:!0});return st.createElement(bO,{title:`Select reasoning effort for ${e}`,hint:"↑/↓ navigate · enter to select · esc to go back"},st.createElement(Qe,{flexDirection:"column"},s.map((e,t)=>{const r=t===l,o=e.value===n;return st.createElement(Qe,{key:e.label},st.createElement(Xe,{color:r||!o?ER.WHITE:ER.GREEN,backgroundColor:r?KR:void 0,bold:r||o},T_(t,e.label).padEnd(a)),st.createElement(Xe,{color:r?ER.WHITE:ER.DIM,backgroundColor:r?KR:void 0},e.description," "),o&&st.createElement(Xe,{color:ER.GREEN}," ",gt.tick))})))},"ReasoningEffortSelector");function windowModelGroups(e){const{groups:t,firstSectionBase:n,windowStart:r,windowEnd:o}=e;let s=n;return t.flatMap(e=>{const t=sliceSectionForWindow({section:e.models,sectionBase:s,windowStart:r,windowEnd:o});return s+=e.models.length,t.rows.length>0?[{group:e,groupWindow:t}]:[]})}Gt(),SR(),__name(windowModelGroups,"windowModelGroups");var M_=__name(({onSelect:e,onCancel:t,currentModel:n,currentProvider:r,planId:o,purchasedCredits:s=0,freeCredits:i=0,refreshBanner:a,subtitle:l,skipEffortStep:c=!1,sessionId:d})=>{const[u,m]=at(""),[p,g]=at(null),[h,f]=at(()=>new Set),[y,S]=at(()=>new Set),w=r??p??uo.COMMAND,v=useCustomModelsReady(d),k=dt(()=>buildLaneModelPickerGroups(),[v]),C=dt(()=>filterModelPickerGroupsByAuth({groups:k,authResolvedProviders:y,unauthedProviders:h}),[k,y,h]),b=dt(()=>filterModelPickerGroups(C,u),[C,u]),E=dt(()=>{const e=new Set(C.map(e=>`${e.providerId}:${e.label}`));return k.filter(t=>!e.has(`${t.providerId}:${t.label}`))},[k,C]),T=dt(()=>filterModelPickerGroups(E,u),[E,u]),P=dt(()=>flattenModelPickerGroups(b),[b]),M=dt(()=>{const e=[];let t=0;for(const n of b)n.models.length>0&&e.push(t),t+=n.models.length;return e},[b]),x=dt(()=>getModelLabelColumnWidth(k.flatMap(e=>e.models)),[k]),[I,A]=at(0),R=useTerminalHeight()-1,L=Math.max(4,R-16-2*b.length),O=void 0!==o,D=dt(()=>O?null:getCachedBillingContext(),[O]),[$,N]=at(D),[_,F]=at(!O&&!D);ct(()=>{if(O)return;if($)return;let e=!0;return getBillingContext().then(t=>{e&&(N(t),F(!1))}),()=>{e=!1}},[O,$]);const U=!O&&!0===$?.fetchFailed,j=O?o:$?.planId??null,B=O?s:$?.purchasedCredits??0,W=O?i:$?.freeCredits??0,H=n?Math.max(0,P.findIndex(e=>e.model.id===n)):0,[G,V]=at("model"),[z,K]=at(null),{cursor:q,error:Y,setError:J}=useListNavigation({items:P,onSelect:__name(t=>{const n=t.model.reasoningEfforts??getSupportedEfforts(t.model.id);if(!c&&n&&n.length>0)return K(t),void V("effort");e(t.model.id,t.providerId)},"onSelect"),onCancel:t,initialIndex:H,searchQuery:u,onSearchChange:m,isActive:"model"===G,sectionStarts:M,validate:__name(e=>validateModelPickerSelection({row:e,unauthedProviders:h,accessDataLoading:_,billing:{planId:j,purchasedCredits:B,freeCredits:W},getProviderDisplayName:__name(e=>getProviderConfig(e)?.displayName,"getProviderDisplayName")}),"validate")});ct(()=>{A(e=>clampScrollOffset({cursor:q,total:P.length,maxVisible:L,currentOffset:e}))},[q,P.length,L]);const Q=lt(!1),X=__name(t=>{if(!z||Q.current)return;Q.current=!0;const{model:r,providerId:o}=z,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"),Z=__name(()=>{Q.current||(K(null),V("model"))},"handleEffortCancel");if(ct(()=>{if(_)return;if(Y!==WP)return;const e=P[q];J(e&&!U?getModelPickerAccessError({model:e.model,providerId:e.providerId,billing:{planId:j,purchasedCredits:B,freeCredits:W}}):null)},[_,U,Y,J,P,q,j,B,W]),ct(()=>{(async()=>{const e=await getConfiguredProvider();e&&e!==uo.COMMAND&&g(e)})()},[]),ct(()=>{let e=!0;return(async()=>{const t=new Set(k.map(e=>e.providerId)),n=new Set,r=new Set,o=await Promise.all([...t].map(async e=>{const t=getProviderConfig(e);if(!t?.requiresAuth)return null;if(!t.checkAuth)return{providerId:e,authed:!0};let n=!1;try{n=await t.checkAuth()}catch{n=!1}return{providerId:e,authed:n}}));for(const e of o)e&&(r.add(e.providerId),e.authed||n.add(e.providerId));e&&(S(r),f(n))})(),()=>{e=!1}},[k]),"effort"===G&&z){const e=z.model.reasoningEfforts??getSupportedEfforts(z.model.id)??[];return st.createElement(P_,{modelLabel:z.model.label,supportedEfforts:e,currentEffort:getReasoningEffort(z.model.id),onSelect:X,onCancel:Z})}const ee=I,te=I+L,ne=windowModelGroups({groups:b,firstSectionBase:0,windowStart:ee,windowEnd:te}),re=P.length>L;return st.createElement(bO,{title:"Select model",subtitle:l??"Switch between the available models. Sets the default for new sessions; other open sessions are unaffected.",footer:st.createElement(Xe,{italic:!0,color:ER.DIM},"type to search · ↑/↓ navigate · shift+↑/↓ jump provider · enter to select",u?" · esc to clear":" · esc to cancel")},st.createElement(Qe,{marginBottom:2,flexDirection:"column",width:"100%"},st.createElement(pL,{query:u,resultCount:u?P.length:void 0,placeholder:"Type to search models..."})),0===P.length?st.createElement(Qe,{marginY:1},st.createElement(Xe,{color:ER.GRAY},T.length>0?"Provider login required. Run /connect to authenticate.":`No models match "${u}"`)):st.createElement(Qe,{flexDirection:"column"},ne.map(({group:e,groupWindow:t},r)=>st.createElement(Qe,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:r>0?1:0},st.createElement(Xe,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>st.createElement(E_,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===q,isCurrent:r.id===n&&e.providerId===w,showProviderLabel:!1,labelColumnWidth:x}))))),re&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",ee+1,"–",Math.min(te,P.length)," of ",P.length,ee>0?" · ↑ more":"",te<P.length?" · ↓ more":"")),Y&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.GRAY},Y)))},"ModelSelector"),x_=__name(e=>{if(!e)return"Inherit from session";for(const t of AD)for(const n of t.models)if(n.id===e)return n.label;return e},"agentModelLabel"),I_=[{value:"inherit",label:"1. Inherit from session (default)"},{value:"pick",label:"2. Pick a specific model"}],A_=__name(({selectedModel:e,onSelect:t})=>{const[n,r]=at("choice"),[o,s]=at(e?1:0);return nt((e,n)=>{if(n.upArrow)s(e=>Math.max(0,e-1));else if(n.downArrow)s(e=>Math.min(I_.length-1,e+1));else if("1"!==e)if("2"!==e){if(n.return){const e=I_[o];if(!e)return;"inherit"===e.value?t(null):r("picker")}}else r("picker");else t(null)},{isActive:"choice"===n}),"picker"===n?st.createElement(M_,{onSelect:e=>t(e),onCancel:()=>r("choice"),currentModel:e,subtitle:"Pin a model for this agent. It will always run on this model, independent of the session's /model.",skipEffortStep:!0}):st.createElement(Qe,{flexDirection:"column"},I_.map((e,t)=>{const n=t===o;return st.createElement(Qe,{key:e.value},st.createElement(Xe,{color:n?ER.WHITE:ER.GRAY,backgroundColor:n?KR:void 0,bold:n},n?">":" "," ",e.label))}),e&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.GRAY},"Currently pinned: ",x_(e))),st.createElement(hO,{hints:["↑↓ navigate","Enter to select","Inherit follows /model; pinned agents keep their own model and prompt cache"]}))},"AgentModelSelector"),R_=__name(({config:e,onSaveComplete:t,viewOnly:n=!1})=>{const[r,o]=at("idle"),[s,i]=at(""),a=__name(async()=>{if(!e.location||!e.agentType||!e.sysPrompt)return o("error"),void i("Agent configuration is incomplete");o("saving");try{await saveAgentDefinition({runtime:createNodeRuntime(),location:e.location,name:e.agentType,description:e.ccToolDefinition,systemPrompt:e.sysPrompt,selectedTools:[...e.selectedTools],allToolNames:xS,model:e.model,reasoningEffort:e.reasoningEffort}),t(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),i(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");nt((e,t)=>{n||!t.return||"idle"!==r&&"error"!==r||a()});const l=formatAgentToolAccessForDisplay({access:[...e.selectedTools],allToolNames:xS,displayNameByToolName:RS,displayNameToToolName:LS}),c=e.location&&e.agentType?getAgentDisplayPath({location:e.location,name:e.agentType}):"";return st.createElement(Qe,{flexDirection:"column",gap:1},st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"Name:"),st.createElement(Xe,{color:ER.GRAY},e.agentType)),st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"Location:"),st.createElement(Xe,{color:ER.GRAY},c)),st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"Tools:"),st.createElement(Xe,{color:ER.GRAY},l)),st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"Model:"),st.createElement(Xe,{color:ER.GRAY},x_(e.model))),st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"Reasoning effort:"),st.createElement(Xe,{color:ER.GRAY},e.reasoningEffort??"model default"))),st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"Description"),st.createElement(Xe,{color:ER.GRAY},"(Tells ","Command Code"," when to use this agent):")),st.createElement(Xe,{color:ER.GRAY},e.ccToolDefinition),st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"System Prompt:")),st.createElement(Xe,{color:ER.GRAY},e.sysPrompt),!n&&st.createElement(Qe,{marginTop:1},"idle"===r&&st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to save ·"," ",st.createElement(gO,null,"Esc")," to cancel"),"saving"===r&&st.createElement(Xe,{color:ER.YELLOW},"Saving agent…"),"saved"===r&&st.createElement(L$,null,s),"error"===r&&st.createElement(Qe,{flexDirection:"column"},st.createElement(R$,null,"Error: ",s),st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to retry"))))},"AgentSummary"),L_=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],O_=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=at("menu"),i=new Set(resolveAgentToolSelection({access:e.tools,allToolNames:xS,displayNameToToolName:LS})),a={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:i,model:e.model??null,reasoningEffort:e.reasoningEffort??null},l=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],c=__name(e=>{"back"!==e.value?"view"!==e.value?"edit"!==e.value?"delete"===e.value&&s("delete"):s("edit"):s("view"):t()},"handleMenuSelect"),d=__name(async r=>{if("confirm-delete"===r.value)try{await deleteAgentDefinition({runtime:createNodeRuntime(),filePath:e.filePath}),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return nt((e,n)=>{if(n.escape)return"menu"===o?void t():void s("menu");if(n.return&&"view"===o)return void s("menu");if(1!==e.length||e<"1"||e>"9")return;const r=Number(e)-1;if("menu"===o){const e=l[r];return void(e&&c(e))}if("delete"===o){const e=L_[r];e&&d(e)}}),"view"===o?st.createElement(bO,{title:e.name,gapAfterHeader:!1,footer:st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to go back")},st.createElement(R_,{config:a,onSaveComplete:()=>s("menu"),viewOnly:!0})):"edit"===o?st.createElement(bO,{title:e.name,gapAfterHeader:!1},st.createElement(Xe,{color:ER.YELLOW},"Edit functionality coming soon..."),st.createElement(pO,null,"Press ",st.createElement(gO,null,"Esc")," to go back")):"delete"===o?st.createElement(bO,{title:"Delete agent",subtitle:`Are you sure you want to delete the agent ${e.name}?`},st.createElement(Qe,null,st.createElement(SelectInput,{items:L_,onSelect:d,indicatorComponent:KN,itemComponent:zN}))):st.createElement(bO,{title:e.name,footer:st.createElement(pO,null,"Press ",st.createElement(gO,null,"↑↓")," to navigate ·"," ",st.createElement(gO,null,"Enter")," to select · ",st.createElement(gO,null,"Esc")," ","to go back")},st.createElement(SelectInput,{items:l,onSelect:c,indicatorComponent:KN,itemComponent:zN}))},"AgentDetails");Gt();var D_="https://commandcode.ai/docs/core-concepts/custom-agents",$_=__name(({onDone:e})=>(nt((t,n)=>{n.return&&e()}),st.createElement(bO,{title:"Create agents with Command Code",gapAfterHeader:!1,boxProps:{gap:1}},st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.GRAY},"Ask Command Code to create or update subagents for you, e.g."),st.createElement(Xe,{color:ER.GRAY}," ",gt.pointerSmall," “create a code-reviewer subagent that reviews diffs for bugs”"),st.createElement(Xe,{color:ER.GRAY}," ",gt.pointerSmall," “make a changelog agent that uses a fast model”")),st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.GRAY},"Or edit the files directly:"),st.createElement(Xe,{color:ER.GRAY}," • .commandcode/agents/ (this project)"),st.createElement(Xe,{color:ER.GRAY}," • ~/.commandcode/agents/ (all projects)")),st.createElement(Xe,{color:ER.GRAY},"Docs: ",D_),st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to go back and just ask"))),"AskCommandCodeGuide"),N_=__name(({handleSelect:e,createdAgentName:t})=>{const[n,r]=at([]),[o,s]=at([]),[i,a]=at([]),[l,c]=at(!0),[d,u]=at(!1),[m,p]=at(null),[g,h]=at(!1),[f,y]=at(0),[S,w]=at(0),v=useTerminalHeight();ct(()=>{__name(async()=>{c(!0),u(!1);const{personal:e,project:t}=await discoverAgents({runtime:createNodeRuntime()}),n=listDefaultAgentsForDisplay();r(e.map(e=>toDisplayAgent({definition:e,location:"personal"}))),s(t.map(e=>toDisplayAgent({definition:e,location:"project"}))),a(n),c(!1)},"loadAgents")()},[d]);const k=[{label:"1. Create agents with Command Code (recommended)",value:"ask_command_code"},{label:"2. Create manually",value:"create_new_agent"}];n.forEach(e=>{k.push({label:e.name,value:e.filePath})}),o.forEach(e=>{k.push({label:e.name,value:e.filePath})}),i.forEach(e=>{k.push({label:e.name.charAt(0).toUpperCase()+e.name.slice(1),value:e.filePath})});const C=n.length+o.length,b=(n.length>0?1:0)+(o.length>0?1:0)+(i.length>0?1:0),E=__name(e=>e<2?"action":e<2+n.length?"user":e<2+n.length+o.length?"project":"default","sectionOf"),T=v-1,P=Math.max(4,T-12-2*b),M=__name(t=>{if("ask_command_code"===t.value||"create_new_agent"===t.value)return void e(t);const r=[...n,...o,...i].find(e=>e.filePath===t.value);r&&(p(r),h(!0))},"handleAgentSelect");if(nt((e,t)=>{if(t.upArrow)y(e=>Math.max(0,e-1));else if(t.downArrow)y(e=>Math.min(k.length-1,e+1));else if(t.return){const e=k[f];e&&M(e)}},{isActive:!l&&!g}),ct(()=>{y(e=>Math.min(e,Math.max(0,k.length-1)))},[k.length]),ct(()=>{w(e=>clampScrollOffset({cursor:f,total:k.length,maxVisible:P,currentOffset:e}))},[f,k.length,P]),l)return st.createElement(A$,{label:"Loading agents"});if(g&&m){const e=isBuiltinAgentPath(m.filePath);return st.createElement(O_,{agent:m,onBack:()=>{h(!1),p(null)},setRevalidateAgent:u,isReadOnly:e})}const x=S,I=S+P,A=k.slice(x,I),R=k.length>P;let L=null;return st.createElement(bO,{title:"Agents",titleSuffix:C>0?` (${C} agent${C>1?"s":""})`:" (No custom agents)"},t&&st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{color:ER.GREEN,dimColor:!0},"Created agent: ",t)),st.createElement(Qe,{flexDirection:"column"},A.map((e,t)=>{const n=x+t,r=E(n),o="action"!==r&&r!==L;L=r;const s=n===f,i="user"===r?"User agents":"project"===r?"Project agents":"Default agents (read-only)";return st.createElement(st.Fragment,{key:e.value},o&&st.createElement(Qe,{marginTop:0===t?0:1},st.createElement(Xe,{color:$R,bold:!0},i)),st.createElement(Qe,null,st.createElement(Xe,{color:s?ER.WHITE:ER.GRAY,backgroundColor:s?KR:void 0,bold:s},s?"> ":" ",e.label," ")))})),R&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",x+1,"–",Math.min(I,k.length)," of ",k.length,x>0?" · ↑ more":"",I<k.length?" · ↓ more":"")),st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(hO,{hints:["↑↓ navigate","Enter to select","Esc to close"],marginTop:0}),st.createElement(Xe,{color:ER.DIM},"Agents live in .commandcode/agents/ (project) and ~/.commandcode/agents/ (all projects) — edit the files directly anytime."),st.createElement(Xe,{color:ER.DIM},"Docs: ",D_)))},"ManageAgents");Gt(),SR(),Gt(),Gt(),SR();var __=__name(({model:e,selectedEffort:t,onSelect:n,onBack:r})=>{const o=(e?getSupportedEfforts(e):null)??[];return st.createElement(P_,{modelLabel:x_(e),supportedEfforts:o,currentEffort:t??void 0,onSelect:e=>n(e??null),onCancel:r})},"AgentEffortSelector");Gt();var F_=[{label:"1. Project (.commandcode/agents/)",value:"project"},{label:"2. Personal (~/.commandcode/agents/)",value:"personal"}],U_=__name(({onSelect:e})=>st.createElement(SelectInput,{items:F_,onSelect:t=>{"project"!==t.value&&"personal"!==t.value||e(t.value)},indicatorComponent:jN,itemComponent:WN}),"LocationSelector");Gt(),SR();var j_=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:c})=>{const d=t?validateAgentName({name:t,displayNameByToolName:RS}):null,u=usePasteAwareChange({onChange:s}),m=usePasteAwareChange({onChange:i});return"agentType"===e?st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.WHITE},"Enter a unique identifier for your agent:"),"tool_conflict"===d?.issue&&st.createElement(Xe,{color:ER.RED},gt.warning," This name conflicts with an existing tool name. Please choose a different name."),"reserved"===d?.issue&&st.createElement(Xe,{color:ER.RED},gt.warning," This name is reserved. Reserved names: ",Vw.join(", "))),st.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{canSubmitAgentManualStep({manualStep:"agentType",config:{agentType:t,sysPrompt:n,ccToolDefinition:r}})&&a()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.WHITE},"Enter the system prompt for your agent:"),st.createElement(Xe,{color:ER.GRAY},"Be comprehensive for best results.")),st.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{canSubmitAgentManualStep({manualStep:"sysPrompt",config:{agentType:t,sysPrompt:n,ccToolDefinition:r}})&&l()},onChange:u,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.WHITE},"When should ","Command Code"," use this agent?"),st.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{canSubmitAgentManualStep({manualStep:"ccToolDefinition",config:{agentType:t,sysPrompt:n,ccToolDefinition:r}})&&c()},onChange:m,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Gt(),SR();var B_=__name((e,t)=>e?"[x]":"[ ]","categoryCheckbox"),W_=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=at(!1),[i,a]=at(0),[l,c]=at(0),d=useTerminalHeight(),u=dt(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),FS.forEach(t=>{e.push({type:"category",value:t.name})}),o?(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:"}),xS.forEach(t=>{e.push({type:"tool",value:t})}),e):(e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"}),e)},[o]),m=u.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=FS.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t)),s=r?.tools.some(t=>e.has(t));return{label:`${B_(Boolean(o),Boolean(s))} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${RS[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),p=m.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type),g=Math.max(5,d-1-10),h=p[i]?.value??0;ct(()=>{c(e=>clampScrollOffset({cursor:h,total:m.length,maxVisible:g,currentOffset:e}))},[h,m.length,g]);const f=l,y=l+g,S=m.slice(f,y),w=m.length>g;return nt((e,l)=>{if(l.upArrow)return void a(e=>{const t=e-1;return t<0?p.length-1:t});if(l.downArrow)return void a(e=>{const t=e+1;return t>=p.length?0:t});if(!l.return&&" "!==e)return;const c=p[i];if(!c)return;const d=u[c.value];if(d){if("continue"!==d.type)return"toggle"===d.type?(s(!o),void a(0)):void("category"!==d.type?"tool"===d.type&&t(d.value):n(d.value));r()}}),st.createElement(Qe,{flexDirection:"column"},S.map(e=>{const t=p.findIndex(t=>t.value===e.value),n=-1!==t&&t===i;if("divider"===e.type)return st.createElement(Qe,{key:`divider-${e.value}`},st.createElement(Xe,{color:ER.GRAY}," ",e.label));if("spacer"===e.type)return st.createElement(Qe,{key:`spacer-${e.value}`,height:1});if("label"===e.type)return st.createElement(Qe,{key:`label-${e.value}`},st.createElement(Xe,{color:ER.GRAY}," ",e.label));const r="continue"===e.type;return st.createElement(Qe,{key:`item-${e.value}`},st.createElement(Xe,{color:n?ER.WHITE:ER.GRAY,bold:r&&n},n?">":" "," ",e.label))}),w&&st.createElement(Qe,null,st.createElement(Xe,{color:ER.GRAY}," ","Showing ",f+1,"–",Math.min(y,m.length)," of"," ",m.length,f>0?" · ↑ more":"",y<m.length?" · ↓ more":"")),st.createElement(Qe,{marginTop:1},e.size===xS.length&&st.createElement(Xe,{color:ER.GRAY},"All tools selected"),e.size>0&&e.size<xS.length&&st.createElement(Xe,{color:ER.GRAY},e.size," tools selected"),0===e.size&&st.createElement(Xe,{color:ER.GRAY},"No tools selected")))},"ToolsSelector"),H_=__name(({onComplete:e})=>{const[t,n]=at(createAgentCreationState),{step:r,manualStep:o,config:s}=t,i=__name(e=>n(t=>reduceAgentCreation({state:t,event:e})),"dispatch"),a=__name(t=>{i({type:"reset"}),e(t)},"resetToDefaults"),l=__name(()=>{if("location"===r)return"Choose location";if("configuration"===r){if("agentType"===o)return"Agent type (identifier)";if("sysPrompt"===o)return"System prompt";if("ccToolDefinition"===o)return"Description (Tell Command Code when to use this agent)"}return"tools"===r?"Select tools":"model"===r?"Select model":"effort"===r?"Select reasoning effort":"summary"===r?"Confirm and save":""},"getSubText"),c=__name(e=>{i({type:"select_location",location:e}),i({type:"select_method",method:"manual"})},"handleLocationSelect");return st.createElement(bO,{title:"Create new agent",subtitle:l()},st.createElement(Qe,null,"location"===r&&st.createElement(U_,{onSelect:c}),"configuration"===r&&st.createElement(Qe,{flexDirection:"column",gap:1},st.createElement(j_,{step:o,agentType:s.agentType,sysPrompt:s.sysPrompt,ccToolDefinition:s.ccToolDefinition,onAgentTypeChange:e=>i({type:"set_agent_type",value:e}),onSysPromptChange:e=>i({type:"set_sys_prompt",value:e}),onCCToolDefinitionChange:e=>i({type:"set_cc_tool_definition",value:e}),onAgentTypeSubmit:()=>i({type:"submit_agent_type"}),onSysPromptSubmit:()=>i({type:"submit_sys_prompt"}),onCCToolDefinitionSubmit:()=>i({type:"submit_cc_tool_definition"})})),"tools"===r&&st.createElement(W_,{selectedTools:s.selectedTools,onToggleTool:e=>i({type:"toggle_tool",tool:e}),onToggleCategory:e=>i({type:"toggle_category",category:e}),onComplete:()=>i({type:"complete_tools"})}),"model"===r&&st.createElement(A_,{selectedModel:s.model,onSelect:e=>i({type:"select_model",model:e})}),"effort"===r&&st.createElement(__,{model:s.model,selectedEffort:s.reasoningEffort??null,onSelect:e=>i({type:"select_effort",effort:e}),onBack:()=>i({type:"back"})}),"summary"===r&&st.createElement(R_,{config:s,onSaveComplete:a})))},"AgentNew"),G_=__name(({onCancel:e})=>{const[t,n]=at(null),[r,o]=at(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return nt((t,n)=>{n.escape&&e()}),st.createElement(Qe,{width:"100%",flexDirection:"column"},null===t&&st.createElement(N_,{handleSelect:s,createdAgentName:r}),"ask_command_code"===t&&st.createElement($_,{onDone:e}),"create_new_agent"===t&&st.createElement(H_,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");function isToggleShortcut(e,t){return""===e||!0===t.ctrl&&"b"===e}Gt(),SR(),__name(isToggleShortcut,"isToggleShortcut");var V_=new Set;function requestBackgroundTasksExpand(){for(const e of V_)e()}function formatShellTaskCounts(e){const t=e.filter(e=>"running"===e.status),n=t.filter(e=>"shell"===e.kind).length,r=t.filter(e=>"monitor"===e.kind).length,o=[];return n>0&&o.push(`${n} shell${1===n?"":"s"}`),r>0&&o.push(`${r} monitor${1===r?"":"s"}`),o.join(", ")}function formatPanelSubtitle(e){const t=e.filter(e=>"running"===e.status);if(0===t.length)return"none running";const n=t.filter(e=>"shell"===e.kind).length,r=t.filter(e=>"monitor"===e.kind).length;return n>0&&0===r?`${n} active shell${1===n?"":"s"}`:r>0&&0===n?`${r} active monitor${1===r?"":"s"}`:formatShellTaskCounts(e)}function formatTaskRuntime(e){const t=Date.parse(e.startedAt);if(Number.isNaN(t))return;const n=e.stoppedAt?Date.parse(e.stoppedAt):Date.now();if(Number.isNaN(n))return;const r=Math.max(0,Math.floor((n-t)/1e3)),o=Math.floor(r/3600),s=Math.floor(r%3600/60),i=r%60;return o>0?`${o}h ${s}m ${i}s`:s>0?`${s}m ${i}s`:`${i}s`}function useShellTaskSnapshot(){const[e,t]=at(()=>listShellTasks({includeStopped:!0}));return ct(()=>{const e=setInterval(__name(()=>t(listShellTasks({includeStopped:!0})),"refresh"),1e3);return()=>clearInterval(e)},[]),e}__name(requestBackgroundTasksExpand,"requestBackgroundTasksExpand"),__name(formatShellTaskCounts,"formatShellTaskCounts"),__name(formatPanelSubtitle,"formatPanelSubtitle"),__name(formatTaskRuntime,"formatTaskRuntime"),__name(useShellTaskSnapshot,"useShellTaskSnapshot");var z_=getShellTaskLabel,K_=getShellTaskStatusText,q_=getVisibleShellTasks,Y_=latestShellTaskOutputLines,J_={running:ER.CYAN,completed:ER.GREEN,failed:ER.RED,"auto-stopped":ER.YELLOW,stopped:ER.GRAY};function getStatusColor(e){return J_[getShellTaskStatusTone(e)]}function TaskRow({task:e,selected:t}){const n=truncateString2({text:z_(e),maxChars:56}),r=t?KR:void 0;return st.createElement(Qe,null,st.createElement(jN,{isSelected:t,backgroundColor:r}),st.createElement(Xe,{color:t?wO:void 0,backgroundColor:r}," ",n),st.createElement(Xe,{color:ER.DIM,backgroundColor:r}," ","(",K_(e),")"))}function TaskGroup({title:e,tasks:t,selectedTaskId:n}){return 0===t.length?null:st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.DIM,bold:!0},e," (",t.length,")"),t.map(e=>st.createElement(TaskRow,{key:e.id,task:e,selected:e.id===n})))}function TaskDetailsBody({task:e,output:t}){const n=Y_(t,10),r=formatTaskRuntime(e);return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,{bold:!0},"Status: "),st.createElement(Xe,{color:getStatusColor(e)},K_(e))),void 0!==r&&st.createElement(Qe,null,st.createElement(Xe,{bold:!0},"Runtime: "),st.createElement(Xe,null,r)),st.createElement(Qe,null,st.createElement(Xe,{bold:!0},"Script: "),st.createElement(Xe,{wrap:"wrap"},e.command)),st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{bold:!0},"Output:"),st.createElement(Qe,{flexDirection:"column",borderStyle:"single",borderColor:ER.DIM,paddingX:1},n.length>0?n.map((t,n)=>st.createElement(Xe,{key:`${e.id}-${n}`},truncateString2({text:t,maxChars:100}))):st.createElement(Xe,{color:ER.DIM},"No output yet.")),st.createElement(Xe,{italic:!0,color:ER.DIM},"Showing ",n.length," line",1===n.length?"":"s")))}function BackgroundTasksPanel({onExpandedChange:e}={}){const t=useShellTaskSnapshot(),n=t.filter(e=>"running"===e.status),[r,o]=at(!1),[s,i]=at("list"),[a,l]=at(0),[c,d]=at(""),u=dt(()=>q_(t),[t]),m=u[a]??u[0];ct(()=>{e?.(r)},[r,e]),ct(()=>{const e=__name(()=>{i("list"),o(!0)},"listener");return V_.add(e),()=>{V_.delete(e)}},[]),ct(()=>{if(0===u.length)return o(!1),i("list"),void l(0);l(e=>Math.min(e,Math.max(0,u.length-1)))},[u.length]),ct(()=>{if(!r||"details"!==s||!m)return void d("");const e=readShellTaskOutputTail({taskId:m.id,maxBytes:4096});d(e?.content??"")},[r,s,m?.id,t]);const p=__name(()=>{o(!1),i("list")},"closePanel");if(nt((e,t)=>isToggleShortcut(e,t)&&(n.length>0||r)?(i("list"),void o(e=>!e)):r?"details"===s?t.leftArrow?void i("list"):t.escape||t.return||" "===e?void p():void("x"===e&&"running"===m?.status&&stopShellTaskById(m.id)):void(t.escape||t.leftArrow?p():0!==u.length&&(t.upArrow?l(e=>Math.max(0,e-1)):t.downArrow?l(e=>Math.min(u.length-1,e+1)):t.return&&m?i("details"):"x"===e&&"running"===m?.status&&stopShellTaskById(m.id))):void 0,{isActive:n.length>0||r}),!r)return null;if("details"===s&&m)return st.createElement(bO,{title:"monitor"===m.kind?"Monitor details":"Shell details",titleColor:ER.CYAN,ruleColor:ER.CYAN,subtitle:truncateString2({text:z_(m),maxChars:80}),hint:"← to go back · Esc/Enter/Space to close · x to stop",boxProps:{marginTop:1,marginBottom:1}},st.createElement(TaskDetailsBody,{task:m,output:c}));const g=u.filter(e=>"monitor"===e.kind),h=u.filter(e=>"shell"===e.kind),f=g.length>0&&h.length>0;return st.createElement(bO,{title:"Background",titleColor:ER.CYAN,ruleColor:ER.CYAN,subtitle:formatPanelSubtitle(t),hint:"↑/↓ to select · Enter to view · x to stop · ←/Esc to go back to feed",gapAfterHeader:!1,boxProps:{marginTop:1,marginBottom:1}},f?st.createElement(st.Fragment,null,st.createElement(TaskGroup,{title:"Monitors",tasks:g,selectedTaskId:m?.id}),st.createElement(TaskGroup,{title:"Shells",tasks:h,selectedTaskId:m?.id})):st.createElement(Qe,{flexDirection:"column",marginTop:1},u.map(e=>st.createElement(TaskRow,{key:e.id,task:e,selected:e.id===m?.id}))))}__name(getStatusColor,"getStatusColor"),__name(TaskRow,"TaskRow"),__name(TaskGroup,"TaskGroup"),__name(TaskDetailsBody,"TaskDetailsBody"),__name(BackgroundTasksPanel,"BackgroundTasksPanel"),Gt(),SR();var Q_=[{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."}],X_=__name(({onSelect:e,onCancel:t})=>{const[n,r]=at(null);ct(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(nt((e,n)=>{n.escape&&t()}),null===n)return null;const s=Q_.findIndex(e=>e.value===n);return st.createElement(bO,{title:"Select a compact mode to compact sessions",subtitle:"Choose how Command Code handles automatic context compaction.",footer:st.createElement(Xe,{italic:!0,color:ER.DIM},"Press ",st.createElement(Xe,{bold:!0},"Esc")," to cancel")},st.createElement(SelectInput,{items:Q_,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:KN,itemComponent:({isSelected:e,label:t})=>{const r=Q_.find(e=>e.label===t),o=r?.value===n,s=Q_.findIndex(e=>e.label===t);return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(VN,{isSelected:e,idleColor:o?ER.GREEN:ER.WHITE,bold:e||o},` ${s+1}. ${r?.label??t} `),o&&st.createElement(HN,null)),st.createElement(VN,{isSelected:e,idleColor:ER.DIM,bold:!1},` ${r?.description??""} `))}}))},"CompactModeSelector");Gt(),Gt(),SR();var Z_=["·","○","◇","☆","✧","☆","◇","○","⌘"],eF=[12,5,4,4,4,4,4,5,16],tF=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<eF.length;e++)if(n+=eF[e],t<n)return Z_[e];const r=t-58;n=0;for(let e=0;e<tF.length;e++)if(n+=tF[e],r<n)return Z_[7-e];return Z_[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=dt(()=>e.split(""),[e]),o=__name(e=>{const n=e-(t-5);return n>=0&&n<HR.length?HR[n]:GR},"getCharColor");return st.createElement(Xe,null,r.map((e,t)=>st.createElement(Xe,{key:`${t}:${e}`,color:o(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return st.createElement(Xe,{color:t??TR,bold:!0},`${getWaveSymbol(e)} `)}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var nF=formatStatusTokenCount,rF=formatElapsedMs,oF=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=at(0),[s,i]=at(n),a=lt(n);a.current=n;const l=getTerminalWidth(),[c,d]=at(()=>l>=72?"all":l>=42?"medium":"none");ct(()=>{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]),ct(()=>{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 u=r%(e.length+10),m="all"===c,p="medium"===c;return AL.statusRender({width:l,layoutMode:c,status:e,frame:r}),st.createElement(Qe,{width:l,height:1,paddingLeft:0,marginLeft:0},st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:RR.BG,color:RR.FG}," "),st.createElement(Xe,{backgroundColor:RR.BG},st.createElement(CMDIcon,{frame:4*r,color:RR.FG})),st.createElement(ShimmerText,{text:e,offset:u,bg:RR.BG}),st.createElement(Xe,{backgroundColor:RR.BG,color:RR.FG}," ")),m&&st.createElement(Qe,{columnGap:1,marginLeft:1},st.createElement(Xe,{bold:!0,color:ER.GRAY},"esc"),st.createElement(Xe,{color:ER.DIM},"to interrupt"),st.createElement(Xe,{color:ER.DIM},"•"),st.createElement(Xe,{color:ER.DIM},rF(t)),st.createElement(Xe,{color:ER.DIM},"•"),st.createElement(Xe,{color:ER.GRAY},gt.arrowDown),st.createElement(Xe,{color:ER.DIM},nF(Math.round(s)))),p&&st.createElement(Qe,{marginLeft:1},st.createElement(Xe,{color:ER.DIM},nF(Math.round(s)))))},"Status");function useExternalEditor({input:e,setInput:t,setInputKey:n,detectedContent:r,setDetectedContent:o,onEditorClose:s}){const[i,a]=at(!1),[l,c]=at(null),d=ut(async()=>{if(!i){a(!0),c(null);try{const i=resolvePastedTextTokens({input:e.replace(/\n+$/,""),detectedContent:r}),a=await openInEditor(i);t(a),o([]),n(e=>e+1),s?.()}catch(e){if(e instanceof Zf)return void c("No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/docs/core-concepts/interactive-mode#setting-up-your-editor");c(`Editor error: ${e instanceof Error?e.message:String(e)}`)}finally{a(!1)}}},[e,t,n,r,o,s,i]),u=ut(()=>{c(null)},[]);return{isEditorOpen:i,editorError:l,handleOpenInEditor:d,clearEditorError:u}}Gt(),SR(),Gt(),SR(),__name(useExternalEditor,"useExternalEditor"),Gt(),SR();var sF=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=at(null),[s,i]=at(!1),[a,l]=at({visible:!1,type:"connected"}),c=lt(null);null===c.current&&(c.current=PE({onConnectedChange:i,onContext:o,onIndicatorChange:l}));const d=c.current;ct(()=>{d.setPaused(n)},[d,n]),ct(()=>{if(t)return d.start(),()=>{d.stop()}},[t,d]);const u=aE(),m=u?RE[u]??"IDE":"IDE",p={visible:a.visible,message:"connected"===a.type?`${m} ${gt.tick}`:"run /ide",type:a.type};return{context:r,connected:s,refresh:d.refresh,connectionIndicator:p}},"useVSCodeContext");Gt(),SR();var iF=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=at(null),o=lt(!1);return ct(()=>{if(!t||o.current)return;let e=!0;return o.current=!0,detectPR().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");function pushEntry(e,t){e.push(t),e.length>50&&e.shift()}function commitBurst({stack:e,burstStart:t,inBurst:n,timer:r}){r.current&&(clearTimeout(r.current),r.current=null),n.current=!1,pushEntry(e,t)}function useUndoStack({input:e,setInput:t,initialCursorRef:n,incrementInputKey:r}){const o=lt([]),s=lt(""),i=lt(!1),a=lt(null),l=lt(!1),c=lt("");return ct(()=>{if(l.current)return l.current=!1,void(c.current=e);if(e===c.current)return;const t=c.current;return c.current=e,i.current||(s.current=t,i.current=!0),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i.current=!1,a.current=null,pushEntry(o.current,s.current)},400),()=>{a.current&&(clearTimeout(a.current),a.current=null)}},[e]),{commitUndo:__name(()=>{i.current&&commitBurst({stack:o.current,burstStart:s.current,inBurst:i,timer:a});const e=o.current.pop();void 0!==e&&(l.current=!0,t(e),n.current=e.length,r())},"commitUndo")}}function getCommandHintLayout(e){const t=getCommandMenuDescriptionWidth(e.terminalWidth);return{descriptionWidth:t,text:truncateString2({text:e.text,maxChars:t})}}function getModelHintText(e){return formatCurrentModelHint({modelId:e,findModelById:findModelById})}Gt(),__name(pushEntry,"pushEntry"),__name(commitBurst,"commitBurst"),__name(useUndoStack,"useUndoStack"),Gt(),SR(),__name(getCommandHintLayout,"getCommandHintLayout"),__name(getModelHintText,"getModelHintText"),Gt(),SR();var aF=createNodeRuntime(),lF=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=at(()=>process.cwd()),[i,a]=at([]),[l,c]=at(0),[d,u]=at(0),m=n.trim()?15:10;ct(()=>{invalidateFileIndex()},[]),ct(()=>{let e=!1;return __name(async()=>{if(n.trim()){const t=await searchFiles({runtime:aF,searchTerm:n,basePath:process.cwd()});if(e)return;return a(t),c(0),void u(0)}try{const t=await browseDirectory({runtime:aF,dirPath:r,basePath:process.cwd()});if(e)return;a(t),c(0),u(0)}catch{}},"run")(),()=>{e=!0}},[r,n]),nt((r,a)=>{if(a.escape)t();else if(a.upArrow)c(e=>{const t=Math.max(0,e-1);return t<d&&u(t),t});else if(a.downArrow)c(e=>{const t=Math.min(i.length-1,e+1);return t>=d+m&&u(t-m+1),t});else{if(a.rightArrow){const e=i[l];if(!e)return;return void(e.isDirectory&&!n.trim()&&o(s(e.path)))}if(a.return){const t=i[l];if(!t)return;return void e(t.path)}}});const p=i.slice(d,d+m);return st.createElement(Qe,{flexDirection:"column",paddingLeft:1},st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},n.trim()?`Searching for: "${n}"`:`Files: ${r}`)),0===p.length?st.createElement(D$,{message:n.trim()?`No files found matching "${n}"`:"No files found in this directory"}):p.map((e,t)=>{const n=d+t,r=e.name,o=n===l;return st.createElement(Xe,{key:e.path,color:o?wO:ER.DIM,bold:o&&isLightTheme()},e.isDirectory?`${r}/`:r)}),st.createElement(hO,{hints:["↑↓ navigate",!n.trim()&&"→ to open folder","Enter to select","Esc to close"]}))},"FileList");Gt(),SR();var cF=__name(()=>st.createElement(Qe,{paddingRight:3},st.createElement(Xe,{color:ER.DIM,wrap:"truncate"},gt.pointerSmall," ","stashed")),"StashBadge"),dF=__name(({hint:e})=>st.createElement(Qe,{paddingRight:1},st.createElement(Xe,{color:ER.DIM,wrap:"truncate"},e)),"PasteKeyHint"),uF=__name(({tasteLearningOn:e,byokSession:t,showSeparator:n=!0})=>{if(null==e)return null;const r=e&&t;return st.createElement(st.Fragment,null,n&&st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:e&&!r?PR.TEXT:ER.DIM},r?"taste off (byok)":"taste "+(e?"on":"off")))},"TasteStateBadge");function useBackgroundTasksSummary(){const[e,t]=at(()=>formatShellTaskCounts(listShellTasks({includeStopped:!1})));return ct(()=>{const e=setInterval(__name(()=>t(formatShellTaskCounts(listShellTasks({includeStopped:!1}))),"refresh"),1e3);return()=>clearInterval(e)},[]),e}__name(useBackgroundTasksSummary,"useBackgroundTasksSummary");var mF=__name(({showSeparator:e=!0,armed:t=!1})=>{const n=useBackgroundTasksSummary();return n?st.createElement(st.Fragment,null,e&&st.createElement(Xe,{color:ER.DIM}," · "),t?st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.CYAN,inverse:!0},` ${n} `),st.createElement(Xe,{color:ER.DIM}," · Enter to open")):st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.CYAN},n),st.createElement(Xe,{color:ER.DIM}," · ↓ to manage"))):null},"BackgroundTasksBadge"),pF=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?st.createElement(st.Fragment,null,t&&st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:"connected"===e.type?ER.GREEN:ER.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),gF=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="default",prInfo:o,contextUsage:s,connectionIndicator:i,pendingExitKey:a,updateStatus:l,updateFailedInfo:c,currentProvider:d,showProviderInfo:u,isBashMode:m,shareInfo:p,showShareNotification:g,unshareNotificationMessage:h,tasteNotificationMessage:f,creditWarning:y,hasStashedPrompt:S,tasteLearningOn:w,byokSession:v,backgroundTasksArmed:k,pasteKeyHint:C})=>{const b=e>=60,E=C&&e>=90?C:null;return st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r&&"bypass"!==r&&"dont-ask"!==r||a?st.createElement(Qe,{flexDirection:"row",justifyContent:"space-between",width:e-1},st.createElement(Qe,{flexDirection:"row",columnGap:0},n&&!a?st.createElement(Xe,{color:DR},t):st.createElement(lL,{mode:r,pendingExitKey:a}),!a&&st.createElement(dL,{prInfo:o}),!a&&st.createElement(pF,{indicator:i}),!a&&b&&st.createElement(uF,{tasteLearningOn:w,byokSession:v}),!a&&st.createElement(mF,{armed:k})),(b||S||E)&&st.createElement(Qe,{flexDirection:"column",alignItems:"flex-end"},!S&&E&&st.createElement(dF,{hint:E}),S?st.createElement(cF,null):null,!S&&b&&s&&st.createElement(XR,{usage:s}))):st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"row",justifyContent:"space-between",width:e-1},st.createElement(lL,{mode:r}),S&&st.createElement(cF,null),!S&&E&&st.createElement(dF,{hint:E})),st.createElement(Qe,{flexDirection:"row",justifyContent:"space-between",width:e-1},st.createElement(Qe,{flexDirection:"row",columnGap:0},st.createElement(Xe,{color:n?DR:ER.DIM},t),st.createElement(dL,{prInfo:o}),st.createElement(pF,{indicator:i}),b&&st.createElement(uF,{tasteLearningOn:w,byokSession:v}),st.createElement(mF,{armed:k})),st.createElement(Qe,{flexDirection:"row",columnGap:2},b&&s&&st.createElement(XR,{usage:s})))),(l||c||u&&d)&&st.createElement(Qe,{flexDirection:"row",columnGap:1},l&&st.createElement(Xe,null,gt.tick," ","Command Code"," updated:"," ",st.createElement(Xe,{color:ER.DIM},"v",l.updatedFrom),st.createElement(Xe,{color:ER.DIM}," ",gt.arrowRight," "),st.createElement(Xe,null,"v",l.updatedTo)),!l&&c&&st.createElement(Xe,{color:ER.YELLOW,dimColor:!0},gt.info," Update available:"," ",c.currentVersion," ",gt.arrowRight," ",c.latestVersion),u&&d&&st.createElement(Xe,{color:ER.GREEN,dimColor:!0},gt.bullet," Provider:"," ",getProviderDisplayName(d)))),m&&st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,{color:ER.GREEN},"! for bash mode")),g&&p&&st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,{color:TR},"SHARED: ",p.url," (copied to clipboard)")),h&&st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,{color:h.includes("NOT SHARED")?ER.RED:TR},h)),f&&st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,{color:TR},f)),y&&st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,{color:ER.YELLOW},gt.warning," ",y)))},"BottomIndicator");function useClipboardPasteKey(e){const{latestInputRef:t,cursorPositionRef:n,detectedImagesRef:r,setDetectedImages:o,setInput:s,incrementInputKey:i,setInitialCursor:a,handlePaste:l,onTextPasted:c,showClipboardNotice:d,clearClipboardNotice:u,showPasteKeyHint:m}=e,p=ut(e=>{const l=nextImagePasteNumber(r.current),{text:c,cursor:d}=insertTextAt(t.current,n.current,imagePasteToken(l)),u=[...r.current,{imageNumber:l,image:e}];r.current=u,o(u),s(c),t.current=c,n.current=d,a(d),i()},[n,r,i,t,o,a,s]),g=ut(async e=>{const r=stripEmbeddedPasteEndMarker(e),o=t.current,s=n.current,i=o.slice(0,s),a=o.slice(s);await l(`${i}[200~${r}[201~${a}`)&&c()},[n,l,t,c]);return ut(async()=>{const e=setTimeout(()=>{d("Reading clipboard…",{sticky:!0})},150);try{const t=await probeClipboardImage();if(t.image)return p(t.image),clearTimeout(e),void u();const n=t.text??await detectClipboardText();if(clearTimeout(e),n)return u(),void await g(n);d(describeClipboardImageMiss({environment:t.environment,attempted:t.attempted})),m()}catch{clearTimeout(e),u()}},[u,p,g,d,m])}Gt(),SR(),__name(useClipboardPasteKey,"useClipboardPasteKey");var hF=["","","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function buildFileMentionInput(e){const{currentInput:t,mentionPath:n,isSearchMode:r}=e;if(!r)return`${t}${n} `;const o=t.lastIndexOf("@");return-1===o?`${n} `:`${t.substring(0,o+1)}${n} `}__name(removeAltPCharacter,"removeAltPCharacter"),__name(buildFileMentionInput,"buildFileMentionInput");var fF=__name(({pasteKeyAdvice:e})=>st.createElement(Qe,{flexDirection:"column",paddingLeft:1},st.createElement(Xe,{color:ER.DIM,bold:!0},"Available Shortcuts:"),st.createElement(Qe,{columnGap:4},st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},"! for bash mode"),st.createElement(Xe,{color:ER.DIM},"/ for commands"),st.createElement(Xe,{color:ER.DIM},"@ for file paths"),st.createElement(Xe,{color:ER.DIM},getModeToggleShortcutHint()," to toggle accept edits")),st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},"double tap esc to clear input"),st.createElement(Xe,{color:ER.DIM},getNewlineShortcutHint()," for newline"),st.createElement(Xe,{color:ER.DIM},"ctrl + g to open in editor"),st.createElement(Xe,{color:ER.DIM},"ctrl + z to undo"),st.createElement(Xe,{color:ER.DIM},"ctrl + s to stash prompt"),st.createElement(Xe,{color:ER.DIM},spacedKey(e.key)," to paste image"),e.textOnlyKey&&st.createElement(Xe,{color:ER.DIM},spacedKey(e.textOnlyKey)," pastes text only in ",e.terminal)))),"ShortcutMenu");function spacedKey(e){return e.split("+").join(" + ")}function currentPasteKeyAdvice(){return pasteImageKeyAdvice({terminal:detectTerminal({env:process.env}),environment:currentClipboardEnvironment()})}__name(spacedKey,"spacedKey"),__name(currentPasteKeyAdvice,"currentPasteKeyAdvice");var yF=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:s,setShowFileList:a,fileSearchQuery:l,setFileSearchQuery:c,onCommand:d,contextUsage:u,tasteLearningOn:m,tasteUsage:p=!1,shareInfo:g,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,creditWarning:S,updateStatus:w,updateFailedInfo:v,currentProvider:k,currentModel:C,showProviderInfo:b,permissionMode:E="default",onToggleAutoAccept:T,hintMessage:P,historyManager:M,pendingExitKey:x=null,onOverlayVisibilityChange:I,onDoubleEscapeEmpty:A,onAltP:R,isProcessing:L=!1,ideContextEnabled:O=!0,footer:D})=>{const[$,N]=at(0),[_,F]=at(!1),[U,j]=at(!1),[B,W]=at(!1),[H,G]=at(""),[V,z]=at(null),K=lt(0),q=lt(0),[Y,J]=at([]),[Q,X]=at([]),[Z,ee]=at(null),[te,ne]=at(null),re=lt(null),oe=ut(()=>{re.current&&(clearTimeout(re.current),re.current=null),ne(null)},[]),se=ut((e,t)=>{re.current&&(clearTimeout(re.current),re.current=null),ne(e),t?.sticky||(re.current=setTimeout(()=>{re.current=null,ne(null)},5e3))},[]);ct(()=>()=>{re.current&&clearTimeout(re.current)},[]);const ie=dt(currentPasteKeyAdvice,[]),ae=dt(()=>formatPasteImageKeyHint(ie),[ie]),[le,ce]=at(()=>ae?Date.now():null);ct(()=>{if(null===le)return;const e=setTimeout(()=>{ce(null)},2e4);return()=>clearTimeout(e)},[le]);const de=ut(()=>{ae&&ce(Date.now())},[ae]),ue=lt(!1),me=lt(!1),[pe,ge]=at(!1),he=lt(!1),fe=ut(e=>{he.current=e,ge(e)},[]),ye=lt(!1),Se=lt(void 0),[we,ve]=at(-1),[ke,Ce]=at(""),be=lt(0),Ee=lt(e);Ee.current=e;const Te=lt(Q);Te.current=Q;const{commitUndo:Pe}=useUndoStack({input:e,setInput:n,initialCursorRef:Se,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey")}),{isEditorOpen:Me,editorError:xe,handleOpenInEditor:Ie,clearEditorError:Ae}=useExternalEditor({input:e,setInput:n,setInputKey:N,detectedContent:Y,setDetectedContent:J,onEditorClose:__name(()=>{ue.current=!1},"onEditorClose")}),Re=dt(()=>shouldCollapsePastedText(),[]),{handlePaste:Le,resetPasteState:Oe,isPasting:De}=useBracketedPaste({input:e,setInput:n,setDetectedImages:X,setDetectedContent:J,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{Se.current=e},"setInitialCursor"),collapsePastedText:Re,nextImageNumber:nextImagePasteNumber(Q),onPasteMiss:__name(e=>{se(describeClipboardImageMiss({environment:e.environment,attempted:e.attempted})),de()},"onPasteMiss")}),$e=useClipboardPasteKey({latestInputRef:Ee,cursorPositionRef:be,detectedImagesRef:Te,setDetectedImages:X,setInput:n,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{Se.current=e},"setInitialCursor"),handlePaste:Le,onTextPasted:__name(()=>{ye.current=!0},"onTextPasted"),showClipboardNotice:se,clearClipboardNotice:oe,showPasteKeyHint:de}),Ne=lt(()=>{});Ne.current=t=>{Me||(async()=>{const n=be.current,r=e.slice(0,n),o=e.slice(n),s=stripEmbeddedPasteEndMarker(t);await Le(`${r}[200~${s}[201~${o}`)&&(ye.current=!0)})()},ct(()=>registerPasteConsumer(e=>Ne.current(e)),[]);const _e=lt(new Map),Fe=dt(()=>{const e=_e.current,t=new Map,n=new Map;for(const r of Q){const o=e.has(r)?e.get(r)??null:saveTempImage(r.image,r.imageNumber);t.set(r,o),n.set(r.imageNumber,o)}return _e.current=t,n},[Q]),{skills:Ue,customMenuItems:je}=useSlashMenuData(),Be=dt(()=>{const e=resolveSlashMenuItems({searchQuery:"",customMenuItems:je,skills:Ue,showProviderCommand:!0,showTerminalSetupCommand:isVSCodeTerminal2()});return new Set([...e.map(e=>e.command),...Ue.map(e=>buildSkillNamespacedCommand(e.name))])},[Ue,je]),We=ut(e=>Be.has(e),[Be]),{context:He,connected:Ge,refresh:Ve,connectionIndicator:ze}=sF({enabled:O,paused:L}),{stdout:Ke}=et(),qe=Ke?.columns??80,{pr:Ye}=iF();ct(()=>{const e=s||B;I?.(e)},[s,B,I]),ct(()=>{if(!ye.current)return;ye.current=!1;const t=Ty(e);!B&&t.showCommandMenu||(W(t.showCommandMenu),G(t.showCommandMenu?t.commandSearchQuery:""))},[e,B]);const Je=ut(()=>{X([])},[]),Ze=ut(()=>{W(!1),z(null)},[]),tt=ut(()=>{Ze(),G(""),a(!1),c(""),ve(-1),Ce(""),Se.current=void 0,N(e=>e+1)},[Ze,c,a]),rt=ut(t=>!(null===Z||!t?.replaceCurrentInput&&e.trim().length>0||(ue.current=!0,n(Z),ee(null),tt(),setTimeout(()=>{ue.current=!1},0),0)),[e,tt,n,Z]),ot=ut(()=>{n(""),j(!1),Ze(),G(""),J([]),Je(),Oe(),ve(-1),Ce(""),N(e=>e+1)},[n,Oe,Je,Ze]),it=ut(e=>{ue.current=!0,n(e.text),Se.current=e.cursor,N(e=>e+1),setTimeout(()=>{ue.current=!1},0)},[n]),mt=ut(()=>{it(insertTextAt(e,be.current,"\n"))},[e,it]);nt(async(t,r)=>{if(he.current&&!r.downArrow&&!r.return&&"\r"!==t&&(fe(!1),r.upArrow))return;if(r.upArrow){if(s||B)return;const t=e.indexOf("\n"),r=-1===t||be.current<=t;if(0!==e.length&&-1===we&&!r)return;const o=M?.count()??0;if(0===o)return;-1===we&&Ce(e);const i=Math.min(we+1,o-1);return void(i!==we&&(ve(i),n(M?.getAt(i)||""),N(e=>e+1)))}if(r.downArrow){if(s||B)return;if(-1===we){const t=e.lastIndexOf("\n"),n=-1===t||be.current>t;return void((0===e.length||n)&&listShellTasks().some(e=>"running"===e.status)&&fe(!0))}const t=e.lastIndexOf("\n");if(!(-1===t||be.current>t))return;const r=we-1;return ve(r),n(-1===r?ke:M?.getAt(r)||""),void N(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void Je();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return ue.current=!0,void Ie();if(isCtrlKey({inputChar:t,key:r,letter:"s",ctrlCode:19})){const t=e.trim().length>0;if(!t&&null===Z)return;if(!t&&rt())return;ue.current=!0;const r=Z??"";return ee(t?e:null),n(r),tt(),void setTimeout(()=>{ue.current=!1},0)}if(getIsExpandToolShortcut(r,t))return ue.current=!0,n(e),N(e=>e+1),void setTimeout(()=>{ue.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:De()}))return me.current=!0,mt(),void setTimeout(()=>{me.current=!1},0);if(r.meta&&"w"===t)return ue.current=!0,void ot();const o=r.ctrl&&"v"===t.toLowerCase()||hF.includes(t),i=r.meta&&"v"===t.toLowerCase();if(o||i){if(Me)return;return ue.current=!0,setTimeout(()=>{ue.current=!1},0),void await $e()}if(!r.ctrl&&!r.meta||"u"!==t)if(r.ctrl&&"z"===t?.toLowerCase())Pe();else{if(r.escape){if(B)return;const t=Date.now();return t-K.current<500?(e.length>0?ot():A?.(),K.current=0,q.current=0,F(!1),void j(!1)):(K.current=t,_||U||(q.current=t),F(!1),void j(!1))}if(_&&(r.backspace||r.delete)&&0===e.length)F(!1);else if(r.return&&!r.shift&&!r.ctrl&&!r.meta){if(he.current&&(fe(!1),listShellTasks().some(e=>"running"===e.status)))return void requestBackgroundTasksExpand();if(me.current)return void(me.current=!1);if(Date.now()-q.current<100)return q.current=0,void mt();if(s)return;if(B)return;if(Me)return;const e=applyBackslashNewline(Ee.current,be.current);return e?void it(e):void await ht(Ee.current)}}});const pt=ut(async t=>{if(Me)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void R?.();const o=processBracketedPaste(t),i=findInsertion({before:e,after:t}),d=null!==i&&looksLikeDroppedImagePath(i.text);if((o.isPasteStart||o.isPasteEnd||d||De())&&await Le(t))return void(ye.current=!0);if(ue.current)return void(ue.current=!1);-1!==we&&ve(-1),X(e=>{if(0===e.length)return e;const n=prunePastedImages({input:t,images:e});return n===e?e:[...n]});const u=1===t.length,m=t.slice(-1);if(u){if("?"===m&&!_)return F(!0),n(""),void N(e=>e+1);if("!"===m&&!U)return F(!1),j(!0),n(""),void N(e=>e+1)}const p=Ty(t),g=t.length<e.length&&!e.startsWith(t),h=!g&&t.length<e.length,f=t.length===e.length+1||h,y=Py({canOpenMenu:f,deletedFromMiddle:g,menuState:p,showCommandMenu:B});B===y&&H===p.commandSearchQuery||(W(y),G(y?p.commandSearchQuery:""));const S=reduceFileMentionInput({prevInput:e,nextInput:t,state:{showFileList:s,query:l}});S.showFileList!==s&&a(S.showFileList),S.query!==l&&c(S.query),_&&(t!==e||t.length<e.length)&&F(!1),xe&&Ae(),0===t.length&&(j(!1),Ze(),G(""),J([]),c(""),Oe()),n(t)},[_,e,n,s,a,l,c,B,H,U,we,Le,Oe,De,R,xe,Ae,Me,Ze]),ht=ut(async(r=e)=>{if(Ve(),q.current=0,_)return void F(!1);const o=r.trim(),s=!U&&o.startsWith("/");let i=o;!U&&Y.length>0&&(i=resolvePastedTextTokens({input:i,detectedContent:Y}));const a=U?[]:resolvePastedImageTokens({input:o,images:Q}),l={};if(!U)for(const e of Q){if(!o.includes(imagePasteToken(e.imageNumber)))continue;const t=Fe.get(e.imageNumber);t&&(l[e.imageNumber]=t)}const c=Object.keys(l).length>0,u=He?wE(He):void 0;if(s&&d&&(n(""),"handled"===(await d(i,a,u)).status))return M?.add(i),j(!1),Ze(),G(""),Je(),J([]),ve(-1),Ce(""),void rt({replaceCurrentInput:!0});ve(-1),Ce(""),i.length>0&&M?.add(i);const m=buildIdeContextHint({ideContext:He});t({input:i,role:U?"bash":"user",images:a,ideContext:u,ideHint:m,imageTokenPaths:c?l:void 0}),j(!1),Ze(),G(""),Je(),J([]),rt({replaceCurrentInput:!0})},[t,d,_,e,U,Q,Fe,Y,M,Ve,He,Je,Ze,rt,n]),ft=ut(t=>{const r=i(process.cwd(),t),o=r.includes(" ")?`"${r}"`:r,d=buildFileMentionInput({currentInput:e,mentionPath:o,isSearchMode:s&&""!==l});n(d),a(!1),c(""),N(e=>e+1)},[n,a,e,s,l,c]),yt=ut(()=>{a(!1),c("")},[a,c]),St=ut(e=>{const t=vy.has(e),r="/design"===e.trimEnd();if(t||r){const t=e.trimEnd();return n(t+" "),G(t.substring(1)+" "),void N(e=>e+1)}Ze(),G(""),n(e+" "),N(e=>e+1)},[n,Ze]),wt=ut(t=>{if("/design help"===t)return Ze(),G(""),n(""),N(e=>e+1),M?.add(t),void d?.("/design help");if(wy.has(t))return Ze(),G(""),M?.add(t),ve(-1),Ce(""),n(""),N(e=>e+1),void d?.(t);const r=vy.has(t),o=Ni.has(t),s=_i.has(t);if(r)St(t);else{if(Ze(),G(""),!o&&!s&&e!==t)return n(t+" "),void N(e=>e+1);M?.add(t),ve(-1),Ce(""),n(""),N(e=>e+1),d?.(t)}},[d,n,e,M,St,Ze]),vt=ut(()=>{Ze(),G(""),ve(-1),Ce(""),N(e=>e+1)},[Ze]),kt=ut(e=>{be.current=e,Se.current=void 0},[]),Ct=dt(()=>formatSlashCommandInputHint({value:e,selectedCommand:B?V:null}),[e,B,V]),bt=Boolean(Ct)&&!x,Et=dt(()=>{const t=Ye&&("OPEN"===Ye.state||"MERGED"===Ye.state);return"auto-accept"===E||"plan"===E||"bypass"===E||"dont-ask"===E||Ge||t?!_:!_&&0===e.length&&!U},[_,e,U,E,Ge,Ye]),Tt=null!==Z,Pt=__name(()=>_||s||B?0:bt||Et||x||U?3:4,"getBottomMargin");return st.createElement(Qe,{width:"100%",flexDirection:"column",marginBottom:Pt()},st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(Xe,{color:U?ER.GREEN:ER.GRAY},gt.line.repeat(qe)),(()=>{const t=__name(t=>st.createElement(TextInput,{key:$,value:e,placeholder:Me?"Save and close the editor to continue...":o,onChange:pt,showCursor:!Me&&r,onCursorChange:kt,initialCursor:Se.current,prefix:`${U?"!":gt.pointer} `,prefixColor:U?ER.GREEN:ER.WHITE,singleLine:t?.singleLine,maxWidth:t?.maxWidth,imageTokenLinks:Fe,isRecognizedSlashCommand:We,disablePasteRouting:!0}),"renderTextInput"),n=B?"/model"===V&&C?getModelHintText(C):Ct:null,s=n?getCommandHintLayout({text:n,terminalWidth:qe}):null;return s?st.createElement(Qe,{flexDirection:"row",width:"100%"},st.createElement(Qe,{width:25},t({singleLine:!0,maxWidth:25})),st.createElement(Qe,{width:s.descriptionWidth},st.createElement(Xe,{color:ER.DIM,wrap:"truncate"},s.text))):t()})(),st.createElement(Xe,{color:U?ER.GREEN:ER.GRAY},gt.line.repeat(qe))),_&&st.createElement(fF,{pasteKeyAdvice:ie}),s&&st.createElement(lF,{onSelectFile:ft,onClose:yt,searchQuery:l}),B&&st.createElement(JR,{onSelectCommand:wt,onInsertCommand:St,onSubmitSearch:ht,onClose:vt,searchQuery:H,onSelectedCommandChange:z}),!B&&!s&&bt&&st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM,wrap:"truncate"},Ct)),!B&&!s&&!bt&&(Et||x||Tt)&&st.createElement(gF,{termWidth:qe,indicatorText:getIdeInputIndicatorText(Ge,He,qe),isIDEIndicator:hasIdeInputIndicatorContext(Ge,He),permissionMode:E,prInfo:Ye,contextUsage:u,tasteLearningOn:m,byokSession:isByok({model:C??""}),connectionIndicator:ze,pendingExitKey:x,updateStatus:w,updateFailedInfo:v,currentProvider:k,showProviderInfo:b,isBashMode:U,shareInfo:g,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,creditWarning:S,hasStashedPrompt:Tt,backgroundTasksArmed:pe,pasteKeyHint:null!==le&&0===Q.length?ae:null}),xe&&st.createElement(Qe,{paddingLeft:1,flexDirection:"column"},st.createElement(Xe,{color:ER.YELLOW},xe)),!xe&&te&&st.createElement(Qe,{paddingLeft:1},st.createElement(Xe,{color:ER.DIM,wrap:"truncate"},te)),D)},"InputBox");Gt(),SR();var SF=__name(()=>{const[e,t]=at([]);return ct(()=>subscribeModStatus(t),[]),0===e.length?null:st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,{wrap:"truncate"},e.map(e=>e.text).join(" ")))},"ModStatusLine");Gt(),SR();var wF=__name(({messages:e})=>{const t=countVisibleQueuedMessages(e);if(0===t)return null;const n=getQueuedDisplayRows(e);return st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Qe,{marginBottom:0},st.createElement(Xe,{color:xR,inverse:!0},` Queued (${t}) `)),n.map(e=>st.createElement(Qe,{key:e.text},st.createElement(Xe,{color:ER.DIM},gt.pointerSmall," "),st.createElement(Xe,{color:ER.DIM},truncateString2({text:e.count>1?`${e.text} (${e.count})`:e.text,maxChars:80})))))},"QueuedMessages");function useWorkedDuration(e,t){const n=lt(null),[r,o]=at(null);return ct(()=>{n.current=null,o(null)},[t]),ct(()=>{if(e)return n.current??=Date.now(),void o(null);null!==n.current&&(o(Date.now()-n.current),n.current=null)},[e]),r}function WorkedDurationNote({durationMs:e}){return null===e||e<1e3?null:st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},`✻ Worked for ${formatElapsedMs(e)}`))}Gt(),SR(),__name(useWorkedDuration,"useWorkedDuration"),__name(WorkedDurationNote,"WorkedDurationNote");var vF=st.memo(({queuedMessages:e,isProcessing:t,processingStartedAt:n=null,executionState:r,status:o,input:s,setInput:i,onSubmit:a,showFileList:l,setShowFileList:c,fileSearchQuery:d,setFileSearchQuery:u,onCommand:m,outputTokens:p=0,contextUsage:g,tasteLearningOn:h,tasteUsage:f,shareInfo:y,showShareNotification:S,unshareNotificationMessage:w,tasteNotificationMessage:v,updateStatus:k,updateFailedInfo:C,creditWarning:b,currentProvider:E,currentModel:T,showProviderInfo:P,permissionMode:M,onToggleAutoAccept:x,hintMessage:I,historyManager:A,pendingExitKey:R,onResetPendingExitKey:L,onDoubleEscapeEmpty:O,retryAttempt:D,onAltP:$,inputActive:N=!0,inactiveHint:_,sessionId:F})=>{const[U,j]=at(()=>null===n?0:Date.now()-n),B=lt(s),W=t||r.isExecuting,H=useWorkedDuration(W,F);return ct(()=>{R&&s!==B.current&&s.length>0&&L?.(),B.current=s},[s,R,L]),ct(()=>{if(!t||null===n)return void j(0);j(Date.now()-n);const e=setInterval(()=>{j(Date.now()-n)},1e3);return()=>{clearInterval(e)}},[t,n]),st.createElement(Qe,{flexDirection:"column"},st.createElement(wF,{messages:e}),st.createElement(Qe,{flexDirection:"row",justifyContent:"space-between"},st.createElement(Qe,{flexDirection:"column"},W&&null===D&&st.createElement(oF,{tokens:p,timeElapsed:U,status:r.isExecuting?`Executing: ${r.currentCommand}`:o}),!W&&st.createElement(WorkedDurationNote,{durationMs:H}),W&&null===D&&I&&st.createElement(Qe,{marginLeft:1},st.createElement(Xe,{color:ER.DIM}," ","⎿"," ","Tip: ",I)))),N?st.createElement(yF,{input:s,setInput:i,onSubmit:a,placeholder:"Ask your question...",showFileList:l,setShowFileList:c,fileSearchQuery:d,setFileSearchQuery:u,onCommand:m,contextUsage:g,tasteLearningOn:h,tasteUsage:f,shareInfo:y,showShareNotification:S,unshareNotificationMessage:w,tasteNotificationMessage:v,updateStatus:k,updateFailedInfo:C,creditWarning:b,currentProvider:E,currentModel:T,showProviderInfo:P,permissionMode:M,onToggleAutoAccept:x,hintMessage:I,historyManager:A,pendingExitKey:!R||t||r.isExecuting?null:R,onDoubleEscapeEmpty:O,onAltP:$,isProcessing:t,footer:st.createElement(SF,null)}):st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{marginLeft:1},st.createElement(pO,null,_??"Background focused · ↑/↓ to select · Enter to view · x to stop · ←/Esc to go back to feed")),st.createElement(SF,null)))});Gt();var kF=__name(({onComplete:e,onCancel:t})=>{const{authState:n,statusMessage:r,browserUrl:o,apiKeyInput:s,setApiKeyInput:i,handleApiKeySubmit:a,cancel:l}=useAuthFlow({onSuccess:__name((t,n)=>{const r=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";e(!0,r?`Logged in as ${r}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return nt((e,t)=>{t.ctrl&&"c"===e&&l()}),st.createElement(TO,{authState:n,statusMessage:r,browserUrl:o,apiKeyInput:s,setApiKeyInput:i,handleApiKeySubmit:a})},"LoginOverlay");function getStatusTextColor(e){return"connected"===e?ER.GREEN:"connecting"===e||"authenticated"===e?ER.CYAN:"requires_auth"===e?ER.YELLOW:ER.GRAY}Gt(),SR(),__name(getStatusTextColor,"getStatusTextColor");var CF=__name((e,t)=>{const n=__name((e,n)=>st.createElement(Xe,{color:e,backgroundColor:t},n),"icon");return"connected"===e?n(ER.GREEN,gt.tick):"connecting"===e?n(ER.CYAN,gt.circle):"authenticated"===e?n(ER.CYAN,gt.tick):"requires_auth"===e?n(ER.YELLOW,gt.warning):"error"===e?n(ER.RED,gt.cross):n(ER.GRAY,gt.circle)},"getStatusIcon"),bF=__name(({onClose:e,mcp:t})=>{const[n,r]=at([]),[o,s]=at(!0),[i,a]=at(0),[l,c]=at("list"),[d,u]=at(null),[m,p]=at(0),g=useTerminalHeight(),h=ut(async()=>{try{const e=await listMcpServers(),n=t?mcpManagerConnectionsFromRegistry(t):mcpManagerConnectionsFromPool(getConnectedMcpServers()),o=await buildMcpManagerServerInfos({configuredServers:e,connectedServers:n,hasTokens:hasTokens});r([...o])}catch{}finally{s(!1)}},[t]);ct(()=>{h()},[h]),ct(()=>{if(t)return t.onChange(()=>{h()})},[t,h]);const f=dt(()=>[...orderMcpManagerServers(n)],[n]),y=f[i]??null,S=g-1,w=dt(()=>new Set(f.map(e=>e.scope)).size,[f]),v=Math.max(4,S-8-2*w);ct(()=>{p(e=>clampScrollOffset({cursor:i,total:f.length,maxVisible:v,currentOffset:e}))},[i,f.length,v]),nt((t,n)=>{if(n.ctrl&&"c"===t)e();else{if(n.escape)return"actions"===l||"confirm-remove"===l?(c("list"),void u(null)):void e();if("list"===l){if(n.upArrow&&(a(e=>Math.max(0,e-1)),u(null)),n.downArrow){if(0===f.length)return;const e=Math.max(0,f.length-1);a(t=>Math.min(e,t+1)),u(null)}n.return&&y&&(c("actions"),u(null))}}});const k=__name(async e=>{if(y)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{u({text:`Enabling ${y.name}...`,color:ER.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:y.name,enabled:!0,scope:y.scope}))return void u({text:`${gt.cross} Failed to enable ${y.name}, server may no longer exist in ${y.scope} scope`,color:ER.YELLOW});await h(),u({text:`${gt.tick} Enabled ${y.name}`,color:ER.GREEN})}catch(e){u({text:`${gt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ER.RED})}}else{u({text:`Disabling ${y.name}...`,color:ER.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:y.name,enabled:!1,scope:y.scope}))return void u({text:`${gt.cross} Failed to disable ${y.name}, server may no longer exist in ${y.scope} scope`,color:ER.YELLOW});await disconnectMcpServer({name:y.name,registry:t}),await h(),u({text:`${gt.tick} Disabled ${y.name}`,color:ER.GREEN})}catch(e){u({text:`${gt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ER.RED})}}else c("confirm-remove");else{u({text:`Authenticating ${y.name}...`,color:ER.CYAN,loading:!0});try{const e=await runMcpServerAuthFlow({serverName:y.name,config:y.config,connectAfterAuth:__name(({name:e})=>connectMcpServer({name:e,registry:t}),"connectAfterAuth")});if("unsupported"===e.kind)return void u({text:e.message,color:ER.YELLOW});"success"===e.kind?(u({text:`${gt.tick} Authenticated with ${y.name}`,color:ER.GREEN}),await h()):u({text:`${gt.cross} Auth failed: ${e.message}`,color:ER.RED})}catch(e){u({text:`${gt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ER.RED})}}else{u({text:`Connecting ${y.name}...`,color:ER.CYAN,loading:!0});try{await connectMcpServer({name:y.name,registry:t}),u({text:`${gt.tick} Connected to ${y.name}`,color:ER.GREEN}),await h()}catch(e){u({text:`${gt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ER.RED})}}else u({text:"Already authenticated",color:ER.GREEN});else u({text:"Already connected",color:ER.GREEN});else c("list")},"handleActionSelect"),C=__name(async e=>{if(y)if("yes"===e.value)try{"connected"===y.status&&await disconnectMcpServer({name:y.name,registry:t}),await removeMcpServer({name:y.name,scope:y.scope}),c("list"),await h(),a(e=>Math.min(e,Math.max(0,f.length-2)))}catch(e){u({text:`${gt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ER.RED}),c("actions")}else c("actions")},"handleRemoveConfirm");if(o)return st.createElement(bO,{title:"Manage MCP servers"},st.createElement(Xe,{color:ER.DIM},"Loading..."));if("confirm-remove"===l&&y)return st.createElement(bO,{title:`Remove ${y.name}?`,titleColor:ER.RED,hint:"↑↓ navigate · Enter to select · Esc to cancel"},st.createElement(Xe,{color:ER.DIM},"This will remove the server from ",y.scope," ","config."),st.createElement(Qe,{marginTop:1},st.createElement(SelectInput,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:C,indicatorComponent:KN,itemComponent:zN})));if("actions"===l&&y){const e=buildMcpManagerActionItems(y);return st.createElement(bO,{title:y.name,hint:"↑↓ navigate · Enter to select · Esc to go back"},st.createElement(Qe,null,CF(y.status),st.createElement(Xe,{color:ER.DIM}," ",getMcpManagerStatusText(y))),st.createElement(Qe,{marginTop:1},st.createElement(SelectInput,{items:[...e],onSelect:k,indicatorComponent:KN,itemComponent:zN})),d&&st.createElement(Qe,{marginTop:1},d.loading&&st.createElement(Xe,{color:d.color},st.createElement(kt,{type:"dots"})," "),st.createElement(Xe,{color:d.color},d.text)))}let b=null;const E=m,T=m+v,P=f.slice(E,T),M=f.length>v;return st.createElement(bO,{title:"Manage MCP servers",hint:0===n.length?"Esc to close":"↑↓ navigate · Enter to select · Esc to close"},st.createElement(Xe,{color:ER.DIM},n.length," ",1===n.length?"server":"servers"),0===n.length?st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},"No MCP servers configured."),st.createElement(Xe,{color:ER.DIM},'Use "',getBinaryCommand(),' mcp add" to add a server.'),st.createElement(cL,{url:"https://commandcode.ai/docs/mcp",text:"View MCP Docs ↗",color:ER.CYAN,dimColor:!0})):st.createElement(Qe,{marginTop:1,flexDirection:"column"},P.map((e,t)=>{const n=E+t,r=e.scope!==b;b=e.scope;const o=n===i;return st.createElement(st.Fragment,{key:e.name},r&&st.createElement(Qe,{marginTop:0===t?0:1},st.createElement(Xe,{bold:!0},getMcpManagerScopeLabel(e.scope)),st.createElement(Xe,{color:ER.DIM}," ","(",getMcpManagerScopePath(e.scope),")")),st.createElement(Qe,null,st.createElement(Xe,{color:o?ER.WHITE:void 0,backgroundColor:o?KR:void 0,bold:o},e.name),st.createElement(Xe,{color:ER.DIM,backgroundColor:o?KR:void 0}," · "),CF(e.status,o?KR:void 0),st.createElement(Xe,{color:getStatusTextColor(e.status),backgroundColor:o?KR:void 0}," ",getMcpManagerStatusText(e)," ")))})),M&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",E+1,"–",Math.min(T,f.length)," of"," ",f.length,E>0?" · ↑ more":"",T<f.length?" · ↓ more":"")),d&&st.createElement(Qe,{marginTop:1},d.loading&&st.createElement(Xe,{color:d.color},st.createElement(kt,{type:"dots"})," "),st.createElement(Xe,{color:d.color},d.text)))},"McpManager");Gt(),SR();var EF=__name(({onClose:e})=>{const[t,n]=at([]),[r,o]=at(0),[s,i]=at(!0),[a,l]=at(null);ct(()=>{__name(async()=>{try{const e=await discoverCommandMemoryFiles(process.cwd());n(e),i(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),i(!1)}},"loadMemoryFiles")()},[]);const c=__name(async t=>{try{await openMemoryFileInEditor(t.path,{logError:__name(e=>console.error(e),"logError")}),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=filterEditableMemoryLocations(t);if(nt((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]&&c(d[r]),"1"===t&&d[0]&&c(d[0]),"2"===t&&d[1]&&c(d[1]))}),s)return st.createElement(bO,{title:"Select memory to edit:"},st.createElement(Xe,{color:ER.DIM},"Loading memory files..."));if(a)return st.createElement(bO,{title:"Select memory to edit:"},st.createElement(Xe,{color:ER.RED},gt.cross," ",a));const u=projectMemorySelectorOptions(d);return st.createElement(bO,{title:"Select memory to edit:",hint:"↑/↓ to navigate · enter to edit · esc to cancel"},st.createElement(Qe,{columnGap:4},st.createElement(Qe,{flexDirection:"column"},u.map((e,t)=>st.createElement(Qe,{key:e.label},st.createElement(jN,{isSelected:r===t}),st.createElement(BN,{isSelected:r===t,idleColor:kO}," ",e.label)))),st.createElement(Qe,{flexDirection:"column"},u.map((e,t)=>st.createElement(BN,{key:e.label,isSelected:r===t,idleColor:kO},e.description)))))},"MemorySelector");function linkImageTokens(e,t){if(!t)return e;const n=new RegExp(fM.source,"g");return e.replace(n,(e,n)=>{const r=t[Number(n)];return r?createOSC8Link(fileUrl(r),e,!1):e})}function UserMessage({content:e,ideHint:t,imageTokenPaths:n}){const r=isSpecialUserMessageContent(e),o=r&&isInterruptedByUserMessage(e)?ER.DIM:ER.RED,s=r?getSpecialUserMessageContent({content:e,billingUrl:os}):linkImageTokens(e,n);return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{backgroundColor:r?void 0:NR.BG,paddingRight:1},st.createElement(Xe,{color:r?o:NR.POINTER,bold:!r},gt.pointer),st.createElement(Qe,{marginLeft:1},st.createElement(Xe,{color:r?o:NR.FG,wrap:"wrap"},s))),t&&!r&&st.createElement(Qe,{marginLeft:2},st.createElement(Xe,{color:zR},yL),st.createElement(Xe,{color:ER.DIM}," ","Selected ",t.lines," ",1===t.lines?"line":"lines"," from"," ",t.file," in ",t.ide)))}Gt(),SR(),Gt(),SR(),__name(linkImageTokens,"linkImageTokens"),__name(UserMessage,"UserMessage");var TF=gt.squareSmallFilled;function goalStatusGlyph(e){return"completed"===e?gt.tick:"paused"===e?"⏸":"idle"===e?gt.circle:TF}function goalStatusHeadColor(e){return"completed"===e?ER.GREEN:"paused"===e?ER.YELLOW:ER.DIM}function goalNoticeGlyph(e){return"cleared"===e?gt.tick:"none"===e?gt.circle:"paused"===e?"⏸":TF}function AutoCompactMessage({content:e}){return st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},TF," ",e))}function ZdrPausedMessage(){return st.createElement(Qe,{marginTop:1,marginBottom:1},st.createElement(Xe,null,st.createElement(Xe,{color:ER.DIM},TF," "),st.createElement(Xe,{color:ER.DIM},"Per-task model overrides reverted to ZDR safe defaults. Run"," "),st.createElement(Xe,{color:WR.CODE},"/config"),st.createElement(Xe,{color:ER.DIM}," to review · esc to dismiss")))}function ModelNoticeMessage({text:e}){return st.createElement(Qe,{marginTop:1,marginBottom:1},st.createElement(Xe,null,st.createElement(Xe,{color:ER.DIM},TF," "),st.createElement(Xe,{color:ER.DIM},e),st.createElement(Xe,{color:ER.DIM}," · esc to dismiss")))}function TasteSkipMessage(){return st.createElement(Qe,{marginTop:1,marginBottom:1},st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:PR.BADGE_BG,color:PR.BADGE_FG,bold:!0},vL)),st.createElement(Xe,{color:ER.DIM}," Skipped. Run "),st.createElement(Xe,{color:WR.CODE},"/learn-taste"),st.createElement(Xe,{color:ER.DIM}," or "),st.createElement(Xe,{color:WR.CODE},"cmd learn-taste"),st.createElement(Xe,{color:ER.DIM}," anytime."))}function TasteNoticeMessage({notice:e}){const t=e.path?`${tasteDirForRoot({projectRoot:process.cwd()})}/${e.path}`:null;return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:PR.BADGE_BG,color:PR.BADGE_FG,bold:!0},vL)),st.createElement(Xe,{color:PR.TEXT}," ",e.label)),st.createElement(Qe,{columnGap:1,marginLeft:1},st.createElement(Xe,{color:zR},yL),st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{wrap:"wrap"},e.text,e.confidence&&st.createElement(Xe,{color:ER.DIM},` [Confidence ${e.confidence}]`)))),e.path&&t&&st.createElement(Qe,{marginLeft:3},st.createElement(cL,{url:fileUrl(t),text:e.path,color:ER.DIM})))}function SkillLoadedMessage({name:e}){return st.createElement(Qe,null,st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:AR.BG,color:AR.FG,bold:!0},`${wL}SKILL${wL}`)),st.createElement(Xe,null," ",e),st.createElement(Xe,{color:ER.DIM}," loaded"))}function HookWarningMessage({content:e}){return st.createElement(Qe,null,st.createElement(Xe,{color:ER.YELLOW},gt.warning),st.createElement(Qe,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.YELLOW},e)))}function HookLineMessage({content:e}){return st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},` ${e}`))}function HookLineContinuationMessage({content:e}){return st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},` ${e}`))}function HookFrameMessage({lines:e,header:t}){return st.createElement(Qe,{flexDirection:"column"},void 0!==t&&st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},` ${t}`)),e.map((e,t)=>st.createElement(Qe,{key:t,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},e.primary?` └ ${e.text}`:` ${e.text}`))))}function GoalLineMessage({content:e,subline:t}){return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:zR},yL),st.createElement(Xe,{color:ER.DIM,wrap:"wrap"}," ",e)),t?st.createElement(Qe,{marginLeft:4,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM,wrap:"wrap"},t)):null)}function GoalAcceptMessage({command:e,acceptLine:t,hint:n}){return st.createElement(Qe,{flexDirection:"column"},st.createElement(UserMessage,{content:e}),st.createElement(GoalLineMessage,{content:t,subline:n}))}function GoalCompleteMessage({elapsed:e,turns:t,goal:n}){const r=`${t} ${1===t?"turn":"turns"}`;return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,null,st.createElement(Xe,{color:ER.GREEN},gt.tick," Goal achieved"),st.createElement(Xe,{color:ER.DIM},` (${e} · ${r})`))),st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM,wrap:"wrap"},"Goal: ",n)))}function GoalStatusMessage({state:e,headline:t,goal:n,detail:r,hint:o}){const s=goalStatusGlyph(e),i=goalStatusHeadColor(e);return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:i},s," ",t)),st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM,wrap:"wrap"},n)),r?st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM,wrap:"wrap"},r)):null,o?st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},o)):null)}function BranchResultMessage({title:e}){return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},e?st.createElement(Xe,null,st.createElement(Xe,{color:ER.GREEN},"⑂ Forked."),st.createElement(Xe,null," You're now in "),st.createElement(Xe,{bold:!0},'"',e,'"')):st.createElement(Xe,null,st.createElement(Xe,{color:ER.GREEN},"⑂ Forked."),st.createElement(Xe,null," You're now in the new session"))),st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},"Original session saved · /resume to switch back")))}function SessionFileMessage({sessionId:e,fileLine:t}){return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},TF," Session ID: "),st.createElement(Xe,null,e)),st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:zR},yL," "),st.createElement(Xe,{color:ER.DIM,wrap:"wrap"},t)))}function InfoMessage({content:e,metadata:t}){if(t?.isTasteSkip)return st.createElement(TasteSkipMessage,null);if(t?.tasteNotice)return st.createElement(TasteNoticeMessage,{notice:t.tasteNotice});if(t?.skillLoaded)return st.createElement(SkillLoadedMessage,{name:t.skillLoaded.name});if(t?.isAutoCompact)return st.createElement(AutoCompactMessage,{content:e});if(t?.hookFrame&&t.hookFrame.length>0)return st.createElement(HookFrameMessage,{lines:t.hookFrame,header:t.hookFrameHeader});if(t?.isHookLine)return st.createElement(HookLineMessage,{content:e});if(t?.isHookLineContinuation)return st.createElement(HookLineContinuationMessage,{content:e});if(t?.isHookWarning)return st.createElement(HookWarningMessage,{content:e});if(t?.isSuccess)return st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.GREEN},gt.tick," ",e));if(t?.isGoalAccept)return st.createElement(GoalAcceptMessage,{command:e,acceptLine:t.goalAcceptLine??"",hint:t.goalSubline});if(t?.isGoalComplete)return st.createElement(GoalCompleteMessage,{elapsed:t.goalElapsed??"",turns:t.goalTurns??1,goal:t.goalText??""});if(t?.isGoalStatus)return st.createElement(GoalStatusMessage,{state:t.goalState??"running",headline:t.goalHeadline??"",goal:t.goalText??"",detail:t.goalDetail,hint:t.goalSubline});if(t?.isBranchResult)return st.createElement(BranchResultMessage,{title:t.branchTitle});if(t?.isSessionFile)return st.createElement(SessionFileMessage,{sessionId:t.sessionFileId??"",fileLine:t.sessionFileLine??""});if(t?.isGoalNotice){const n=goalNoticeGlyph(t.goalNoticeKind);return st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},n," ",e))}return t?.isGoalLine?st.createElement(GoalLineMessage,{content:e,subline:t.goalSubline}):st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},TF," ",e))}__name(goalStatusGlyph,"goalStatusGlyph"),__name(goalStatusHeadColor,"goalStatusHeadColor"),__name(goalNoticeGlyph,"goalNoticeGlyph"),__name(AutoCompactMessage,"AutoCompactMessage"),__name(ZdrPausedMessage,"ZdrPausedMessage"),__name(ModelNoticeMessage,"ModelNoticeMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(TasteNoticeMessage,"TasteNoticeMessage"),__name(SkillLoadedMessage,"SkillLoadedMessage"),__name(HookWarningMessage,"HookWarningMessage"),__name(HookLineMessage,"HookLineMessage"),__name(HookLineContinuationMessage,"HookLineContinuationMessage"),__name(HookFrameMessage,"HookFrameMessage"),__name(GoalLineMessage,"GoalLineMessage"),__name(GoalAcceptMessage,"GoalAcceptMessage"),__name(GoalCompleteMessage,"GoalCompleteMessage"),__name(GoalStatusMessage,"GoalStatusMessage"),__name(BranchResultMessage,"BranchResultMessage"),__name(SessionFileMessage,"SessionFileMessage"),__name(InfoMessage,"InfoMessage"),Gt(),SR(),Gt(),Gt(),Gt(),Gt();var PF=/\[\^[^\]]+\]/;function splitMarkdownBlocks(e){return e?PF.test(e)?[e]:yt.lex(e,{gfm:!0}).map(e=>e.raw):[]}function isWhitespaceOnly2(e){return 0===e.trim().length}function createBlockStream(){let e="",t=0,n=!1;function frozenAdvance(n){return{newlyCompleted:[],openTail:n.startsWith(e)?n.slice(e.length):n,committedBlockCount:t,frozen:!0}}function advance(r){if(n)return frozenAdvance(r);if(!r.startsWith(e))return n=!0,frozenAdvance(r);const o=splitMarkdownBlocks(r);if(o.length<=1)return{newlyCompleted:[],openTail:r.slice(e.length),committedBlockCount:t,frozen:!1};const s=o.slice(0,-1),i=[];let a=0;for(const o of s){const s=a+o.length;if(s<=e.length){if(e.slice(a,s)!==o)return n=!0,frozenAdvance(r)}else{if(a!==e.length)return n=!0,frozenAdvance(r);i.push(o),e+=o,isWhitespaceOnly2(o)||(t+=1)}a=s}return{newlyCompleted:i,openTail:r.slice(e.length),committedBlockCount:t,frozen:!1}}function finalize(r){if(n||!r.startsWith(e)){const n=r.startsWith(e)?r.slice(e.length):r;return{remaining:n?[n]:[],committedBlockCount:t}}const o=r.slice(e.length);return o?{remaining:splitMarkdownBlocks(o),committedBlockCount:t}:{remaining:[],committedBlockCount:t}}return __name(frozenAdvance,"frozenAdvance"),__name(advance,"advance"),__name(finalize,"finalize"),{advance:advance,finalize:finalize}}__name(splitMarkdownBlocks,"splitMarkdownBlocks"),__name(isWhitespaceOnly2,"isWhitespaceOnly"),__name(createBlockStream,"createBlockStream"),Gt();var MF=String.fromCharCode(8203),xF=new Set(["_","~","*","`"]),IF=/!?\[[^\]]*\]\([^)]*$/,AF=/!?\[[^\]]*$/;function isSpace(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function isOnlyMarkersOrSpace(e){for(const t of e)if(!isSpace(t)&&!xF.has(t))return!1;return!0}function isShortSetextUnderline(e){if(0===e.length||e.length>2)return!1;const t=e[0];if("-"!==t&&"="!==t)return!1;for(const n of e)if(n!==t)return!1;return!0}function isTagOpener(e){const t=e.startsWith("</")?e[2]:e[1];return void 0!==t&&/[a-zA-Z]/.test(t)}function countFenceMarkers(e){let t=0;for(let n=0;n<e.length;n+=1)"\\"!==e[n]||"`"!==e[n+1]?e.startsWith("```",n)&&(t+=1,n+=2):n+=1;return t}function countMarkerOutsideCode(e,t){let n=0,r=!1,o=!1;for(let s=0;s<e.length;s+=1){const i=e[s];"\\"!==i?e.startsWith("```",s)?(r=!r,s+=2):r||("`"!==i?o||e.startsWith(t,s)&&(n+=1,s+=t.length-1):o=!o):s+=1}return n}function countSingleBackticks(e){let t=0,n=!1;for(let r=0;r<e.length;r+=1)"\\"!==e[r]||"`"!==e[r+1]?e.startsWith("```",r)?(n=!n,r+=2):n||"`"!==e[r]||(t+=1):r+=1;return t}function stripDanglingHtmlTag(e){const t=e.lastIndexOf("<");if(-1===t)return e;const n=e.slice(t);return n.includes(">")?e:isTagOpener(n)?e.slice(0,t).trimEnd():e}function stripDanglingLink(e){const t=e.match(IF);if(void 0!==t?.index)return e.slice(0,t.index).trimEnd();const n=e.match(AF);return void 0!==n?.index?e.slice(0,n.index).trimEnd():e}function guardSetextUnderline(e){const t=e.lastIndexOf("\n");if(-1===t)return e;const n=e.slice(t+1),r=n.trim();if(!isShortSetextUnderline(r))return e;if(n!==r&&n.endsWith(" "))return e;const o=e.slice(0,t).split("\n").at(-1);return o&&0!==o.trim().length?`${e}${MF}`:e}function closeUnbalancedMarker(e,t,n){if(countMarkerOutsideCode(e,t)%2==0)return e;const r=e.lastIndexOf(t),o=e.slice(r+t.length);return isOnlyMarkersOrSpace(o)?e:n&&o.endsWith(n)?`${e}${n}`:`${e}${t}`}function completeInlineTripleFence(e){if(e.includes("\n"))return null;if(!e.startsWith("```"))return null;if(!e.endsWith("``")||e.endsWith("```"))return null;const t=e.slice(3,-2);return 0===t.length||t.includes("`")?null:`${e}\``}function closeInlineCode(e){if(countSingleBackticks(e)%2==0)return e;const t=e.lastIndexOf("`");return isOnlyMarkersOrSpace(e.slice(t+1))?e:`${e}\``}function mendMarkdown(e){if(!e)return e;const t=completeInlineTripleFence(e);if(null!==t)return t;if(countFenceMarkers(e)%2==1)return e;let n=e;return n=stripDanglingHtmlTag(n),n=stripDanglingLink(n),n=guardSetextUnderline(n),n=closeUnbalancedMarker(n,"***",""),n=closeUnbalancedMarker(n,"**","*"),n=closeUnbalancedMarker(n,"__","_"),n=closeUnbalancedMarker(n,"~~","~"),n=closeInlineCode(n),n}__name(isSpace,"isSpace"),__name(isOnlyMarkersOrSpace,"isOnlyMarkersOrSpace"),__name(isShortSetextUnderline,"isShortSetextUnderline"),__name(isTagOpener,"isTagOpener"),__name(countFenceMarkers,"countFenceMarkers"),__name(countMarkerOutsideCode,"countMarkerOutsideCode"),__name(countSingleBackticks,"countSingleBackticks"),__name(stripDanglingHtmlTag,"stripDanglingHtmlTag"),__name(stripDanglingLink,"stripDanglingLink"),__name(guardSetextUnderline,"guardSetextUnderline"),__name(closeUnbalancedMarker,"closeUnbalancedMarker"),__name(completeInlineTripleFence,"completeInlineTripleFence"),__name(closeInlineCode,"closeInlineCode"),__name(mendMarkdown,"mendMarkdown");var RF=bt()?"⠶":"#";function streamingMaxRows(e){return Math.max(8,e-12)}function AssistantMessage({content:e,isStreaming:t=!1,continuation:n=!1}){const r=useTerminalRows(),o=t?mendMarkdown(e):e;return st.createElement(Qe,null,n?st.createElement(Qe,{width:2,flexShrink:0}):st.createElement(Xe,{color:_R},RF),st.createElement(Qe,{marginLeft:n?0:1,flexGrow:1,flexShrink:1,minWidth:0,flexDirection:"column"},st.createElement(Markdown,{maxPhysicalRows:t?streamingMaxRows(r):void 0},o)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o=ER.GREEN,s=gt.tick,i="default",a=t||"(No output)";n&&(o=ER.YELLOW,s=gt.arrowRight,i=ER.YELLOW,a="Executing…"),r&&(o=ER.RED,s=gt.cross,i=ER.RED);const l=dt(()=>buildTreeConnectors(a),[a]);return st.createElement(Qe,null,st.createElement(Xe,{color:o},s),st.createElement(Qe,{flexDirection:"column",marginLeft:1},st.createElement(Qe,null,st.createElement(Xe,{color:ER.GRAY},"$ "),st.createElement(Xe,{color:o,bold:!0},e)),st.createElement(Qe,{columnGap:1,marginLeft:1},st.createElement(Xe,{color:zR},l),st.createElement(Xe,{color:i,wrap:"wrap"},a))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?ER.YELLOW:void 0,o=dt(()=>buildTreeConnectors(e),[e]);return st.createElement(Qe,{flexDirection:"column",marginBottom:0,marginTop:-1},st.createElement(Qe,{columnGap:1},st.createElement(Xe,{color:zR},o),st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:r},e))),t&&st.createElement(Qe,{marginLeft:3},st.createElement(Xe,{color:ER.DIM},"See ",t)))}function ErrorMessage({content:e}){return isInterruptedByUserMessage(e)?st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},gt.pointer),st.createElement(Qe,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM,wrap:"wrap"},tS))):st.createElement(Qe,null,st.createElement(Xe,{color:ER.RED},gt.warning),st.createElement(Qe,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Markdown,{color:ER.RED},e)))}__name(streamingMaxRows,"streamingMaxRows"),__name(AssistantMessage,"AssistantMessage"),Gt(),__name(BashMessage,"BashMessage"),Gt(),__name(CommandResultMessage,"CommandResultMessage"),Gt(),SR(),__name(ErrorMessage,"ErrorMessage"),Gt(),SR();var LF={connected:{char:gt.tick,color:ER.GREEN},installed:{char:gt.tick,color:ER.GREEN},up_to_date:{char:gt.tick,color:ER.GREEN},needs_reload:{char:gt.circle,color:ER.YELLOW},failed:{char:gt.cross,color:ER.RED},not_in_ide:{char:gt.circle,color:ER.YELLOW}};function IDEStatusMessage({status:e,ide:t,details:n}){const{prefix:r,ide:o,suffix:s}=getIDESetupStatusHeadline(e,t),i=LF[e];return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,null,st.createElement(Xe,{color:i.color},i.char),st.createElement(Xe,null," ",r),o&&st.createElement(Xe,{color:ER.CYAN},o),s&&st.createElement(Xe,null,s))),n?.map(e=>st.createElement(Xe,{key:e,color:ER.DIM}," ",e)))}function reasoningBodyColumns(e){const t=Math.floor(.9*Math.floor(.9*e));return Math.max(1,t-2)}function ReasoningMessage({content:e,expandedOutput:t,expandKey:n,isStreaming:r=!1}){const o=projectReasoningView({content:e,expandedOutput:t,expandKey:n,isStreaming:r,columns:reasoningBodyColumns(useTerminalWidth()),measureWidth:Ne});return st.createElement(Qe,{flexDirection:"column",width:"90%"},st.createElement(Qe,null,st.createElement(Xe,{color:MR},"✻"," "),st.createElement(Xe,{color:MR},o.showExpandHint?`${o.headerLabel} `:o.headerLabel),o.showExpandHint&&st.createElement(BracketWrap,{color:ER.DIM},o.expandHint)),o.showBody&&o.hiddenAboveLabel&&st.createElement(Qe,{marginLeft:2},st.createElement(Xe,{color:ER.DIM},o.hiddenAboveLabel)),o.showBody&&st.createElement(Qe,{marginLeft:2,flexDirection:"column"},st.createElement(Xe,{color:MR,wrap:"wrap",italic:!0},o.bodyText)))}__name(IDEStatusMessage,"IDEStatusMessage"),Gt(),SR(),__name(reasoningBodyColumns,"reasoningBodyColumns"),__name(ReasoningMessage,"ReasoningMessage"),Gt(),SR(),Gt(),SR();function HelpMessage(){const e=getInvokedCommandName(),t=dt(()=>getVisibleSlashCommands(),[]);return st.createElement(Qe,{flexDirection:"column",paddingY:1},st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Qe,null,st.createElement(Xe,{bold:!0},"Command Code"),st.createElement(Xe,{color:ER.GRAY}," v","1.65.3")),st.createElement(Xe,{color:ER.GRAY},hi)),st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{bold:!0},"Usage"),st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,null,e," <command> [options]"))),st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{bold:!0},"Options"),st.createElement(Qe,{flexDirection:"column",paddingLeft:2},ki.map(t=>st.createElement(Qe,{key:t.key},st.createElement(Xe,null,t.key.replace(/^cmd/,e).padEnd(fi)),st.createElement(Xe,{color:ER.GRAY},t.description))))),st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{bold:!0},"Commands"),st.createElement(Qe,{flexDirection:"column",paddingLeft:2},bi.map(t=>st.createElement(Qe,{key:t.key},st.createElement(Xe,null,t.key.replace(/^cmd/,e).padEnd(fi)),st.createElement(Xe,{color:ER.GRAY},t.description))))),st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{bold:!0},"Slash Commands"),st.createElement(Qe,{flexDirection:"column",paddingLeft:2},t.map(e=>st.createElement(Qe,{key:e.key},st.createElement(Xe,null,e.key.padEnd(fi)),st.createElement(Xe,{color:ER.GRAY},e.description))))),st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{bold:!0},"Keyboard Shortcuts"),st.createElement(Qe,{flexDirection:"column",paddingLeft:2},vi.map(e=>st.createElement(Qe,{key:e.key},st.createElement(Xe,null,e.key.padEnd(fi)),st.createElement(Xe,{color:ER.GRAY},e.description))))),st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{bold:!0},"Examples"),st.createElement(Qe,{flexDirection:"column",paddingLeft:2},Ti.map(t=>st.createElement(Qe,{key:t.key},st.createElement(Xe,null,t.key.replace(/^cmd/,e).padEnd(fi)),st.createElement(Xe,{color:ER.GRAY},t.description))))),st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.CYAN},gt.pointer),st.createElement(Xe,{color:ER.GRAY}," ",yi.replace(/cmd/,e))),st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{bold:!0},"Links"),st.createElement(Qe,{flexDirection:"column",paddingLeft:2},Ei.map(e=>st.createElement(Qe,{key:e.key},st.createElement(Xe,null,e.key.padEnd(fi)),st.createElement(Xe,{color:ER.CYAN},e.description))))))}function SystemMessage({content:e}){return isHelpSystemEntryContent(e)?st.createElement(HelpMessage,null):st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{wrap:"wrap"},st.createElement(Markdown,null,e)))}function FeedEntryView({entry:e,expandedToolOutput:t}){return renderFeedEntry(e,t)}function renderFeedEntry(e,t){if("user"===e.role){const t=e.metadata?.ideHint,n=e.metadata?.imageTokenPaths;return st.createElement(UserMessage,{content:e.input,ideHint:t,imageTokenPaths:n})}return"assistant"===e.role?st.createElement(AssistantMessage,{content:e.input,isStreaming:"running"===e.metadata?.status,continuation:!0===e.metadata?.continuation}):"reasoning"===e.role?st.createElement(ReasoningMessage,{content:e.input,expandedOutput:t,expandKey:"ctrl",isStreaming:"running"===e.metadata?.status}):"tool"===e.role?st.createElement(ToolMessage,{name:Ah(e.name||""),input:e.input,output:e.output||"",isPending:Ph(e),hasError:Th(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?st.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:Ph(e),hasError:Th(e)}):"system"===e.role?st.createElement(SystemMessage,{content:e.input}):"info"===e.role?st.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?st.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?st.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?st.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),__name(FeedEntryView,"FeedEntryView"),__name(renderFeedEntry,"renderFeedEntry");var OF=__name(e=>getModelShortName({modelId:e,findModelById:findModelById}),"getModelShortName");function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages [${NE?"ctrl+y":"ctrl+e"} to expand more] `,r=Math.max(0,Math.floor((t-n.length)/2)),o="─".repeat(r);return st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:$R},o),st.createElement(BracketedText,{text:n,color:$R}),st.createElement(Xe,{color:$R},o))}__name(TranscriptDivider,"TranscriptDivider");var DF=st.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o,currentEffort:s=null,currentProvider:i,hiddenCount:a=0})=>{const l=a>0?{role:"transcript-divider",count:a}:null,c=[...t?["header"]:[],...l?[l]:[],...e],d=useTerminalWidth(),u=dt(()=>tO(d),[d]),m=dt(()=>iO(d),[d]),p=dt(()=>getPackageJson(import.meta.url).version||"0.0.0",[]),g=dt(()=>getGitHeaderInfo(),[]),h=dt(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),f=o?OF(o):"sonnet-4.6",y=Boolean(o&&byokProviderId({model:o}))?"":" · taste-1",S=dt(()=>{if(!o)return"";if(!modelSupportsReasoningEffort(o))return"";const e=null===s?getReasoningEffort(o):s;return e?` with ${e} effort`:""},[s,o,n]),w=dt(()=>{const e=o?byokProviderId({model:o}):void 0;return e?` · ${e} (byok)`:i&&i!==uo.COMMAND?` · ${getProviderShortName(i)} (byok)`:""},[o,i,n]);return st.createElement(Ze,{items:c,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return st.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:d});if("header"===e)return"compact"===m?st.createElement(Qe,{key:"header",marginBottom:1,flexDirection:"row"},st.createElement(Qe,{width:oO,flexShrink:0},st.createElement(qR,null,rO)),st.createElement(Qe,{flexDirection:"column",marginLeft:2},st.createElement(Qe,null,st.createElement(Xe,{bold:!0},"Command Code"),st.createElement(Xe,{color:$R}," ","v",p)),st.createElement(Xe,{color:$R},"models: ",f,S,y,w),st.createElement(Xe,{color:$R},h,g&&g.isLocal&&g.branch&&` (${g.branch})`))):st.createElement(Qe,{key:"header",marginBottom:1,flexDirection:"column"},st.createElement(qR,null,u.trimEnd()),st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Qe,null,st.createElement(Xe,{color:$R},"# "),st.createElement(Xe,{bold:!0},"Command Code"),st.createElement(Xe,{color:$R}," v",p)),st.createElement(Xe,{color:$R},"# models: ",f,S,y,w),st.createElement(Qe,null,st.createElement(Xe,{color:$R},"# ",h,g&&g.isLocal&&g.branch&&st.createElement(Xe,{color:$R}," ","(branch:"," ",g.branch,")")))));const t=e,n=renderFeedEntry(t,r);return st.createElement(Qe,{key:t.id,paddingBottom:1,width:"90%"},n)})});Gt(),SR();var $F=it(__name(function LiveAgentStatusInner2({entry:e}){const t=Ah(e.name||"Agent"),n=summarizeAgentTaskInput(e.input||""),r=e.metadata?.tokensUsed||0,o=e.metadata?.elapsedSeconds||0,s=e.metadata?.recentTools||[],[i,a]=at(".");return ct(()=>{const e=setInterval(()=>{a(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),st.createElement(Qe,{flexDirection:"column",marginBottom:1,width:"90%"},st.createElement(Qe,null,st.createElement(Xe,{backgroundColor:LR.BG,color:LR.FG,bold:!0},` ${t} `),n&&st.createElement(Xe,null," (",n,")")),st.createElement(Qe,{columnGap:1,marginLeft:1},st.createElement(Xe,null,"⎿"," "),st.createElement(Xe,{color:ER.GRAY},"Running (",formatTime3(o)," |"," ",formatTokens(r),")",i)),s.length>0&&st.createElement(Qe,{flexDirection:"column",marginLeft:1},s.map((e,t)=>{const n=Ah(e.name);return st.createElement(Qe,{key:t,columnGap:1},st.createElement(Xe,{color:ER.GRAY},"⎿"),st.createElement(Xe,{color:ER.GRAY}," ",n),e.input&&st.createElement(Xe,{color:ER.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),NF=it(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:st.createElement($F,{entry:e})},"LiveAgentStatus"));Gt(),Gt(),SR();var _F=[],FF=_F,UF=!1,jF=null,BF="",WF=new Set,HF=new Set,GF=new Set;function shapeOf(e){return e.map(e=>e.content.replace(/\d+/g,"#")).join("\0")}function emit2(){for(const e of GF)e()}function cancelPeek(){jF&&clearTimeout(jF),jF=null,UF=!1}function armPeek(){jF&&clearTimeout(jF),UF=!0,jF=setTimeout(()=>{jF=null,UF=!1,emit2()},5e3),jF.unref?.()}function projectUserEdits(e){return e.filter(e=>!WF.has(e.content)).map(e=>"completed"!==e.status&&HF.has(e.content)?{...e,status:"completed"}:e)}function setSessionTodos(e){const t=projectUserEdits(e);if(t.length>0&&HF.size>0&&t.every(e=>"completed"===e.status))return void clearSessionTodos();const n=shapeOf(t),r=n!==BF;(r||JSON.stringify(t)!==JSON.stringify(FF))&&(FF=t.length>0?t:_F,BF=n,FF.length>0&&r&&armPeek(),emit2())}function adoptSettled(e){FF=e.length>0?[...e]:_F,BF=shapeOf(FF),cancelPeek(),emit2()}function seedSessionTodos(e){WF.clear(),HF.clear(),adoptSettled(e)}function removeSessionTodoAt(e){const t=FF[e];return t&&WF.add(t.content),adoptSettled(FF.filter((t,n)=>n!==e)),FF}function seedTodosFromFeedEntries(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(!n||"tool"!==n.role||"todo_write"!==n.name)continue;const r="output"in n?n.output:void 0,o="string"==typeof r?Nh(r):null;if(o){if(o.every(e=>"completed"===e.status))break;return seedSessionTodos(o),FF}}return clearSessionTodos(),_F}function clearSessionTodos(){(FF!==_F||UF||0!==WF.size||0!==HF.size)&&(FF=_F,BF="",WF.clear(),HF.clear(),cancelPeek(),emit2())}function getSessionTodos(){return FF}function isTodoPanelCollapsed(){return!UF}function completeSessionTodoAt(e){const t=FF[e];return t&&HF.add(t.content),adoptSettled(FF.map((t,n)=>n===e?{...t,status:"completed"}:t)),FF}function completeAllSessionTodos(){const e=FF.map(e=>e.content);for(const t of e)HF.add(t);return adoptSettled(_F),e}function subscribe(e){return GF.add(e),()=>GF.delete(e)}function useSessionTodos(){return pt(subscribe,getSessionTodos)}function useTodoPanelCollapsed(){return pt(subscribe,isTodoPanelCollapsed)}function usePausedLabel(e){const[t,n]=at(!e);return ct(()=>{if(e)return void n(!1);const t=setTimeout(()=>n(!0),1500);return t.unref?.(),()=>clearTimeout(t)},[e]),t}function projectVisibleTodos(e){if(e.length<=8)return{foldedDone:0,visible:e,hiddenTail:0};const t=e.filter(e=>"completed"!==e.status),n=e.length-t.length,r=8-(n>0?1:0),o=t.slice(0,Math.max(1,r));return{foldedDone:n,visible:o,hiddenTail:t.length-o.length}}function currentTaskLabel(e){const t=e.find(e=>"in_progress"===e.status);if(t)return t.activeForm?`${t.activeForm}…`:t.content;const n=e.find(e=>"pending"===e.status);return n?n.content:null}function TodoPanel({active:e=!0}){const t=useSessionTodos(),n=useTodoPanelCollapsed(),r=usePausedLabel(e);if(0===t.length)return null;const o=t.filter(e=>"completed"===e.status).length,s=o>0?`${t.length} items · ${o} done`:`${t.length} items`,i=n?currentTaskLabel(t):null;return st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Qe,null,st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:AR.BG,color:AR.FG,bold:!0},`${wL}TODOS${wL}`)),st.createElement(Qe,{flexShrink:0},st.createElement(Xe,null," ",st.createElement(BracketWrap,null,s))),i&&st.createElement(Qe,{flexShrink:1,minWidth:0},st.createElement(Xe,{color:r?ER.DIM:OR.IN_PROGRESS,bold:!r,wrap:"truncate-end"},` ${i}${r?" (paused)":""}`)),st.createElement(Qe,{flexShrink:0},st.createElement(Xe,null," ",st.createElement(BracketWrap,{color:ER.DIM},n?"ctrl+x to expand":"ctrl+x to manage")))),!n&&st.createElement(CappedChecklist,{todos:t}))}function CappedChecklist({todos:e}){const{foldedDone:t,visible:n,hiddenTail:r}=projectVisibleTodos(e);return st.createElement(Qe,{flexDirection:"column"},t>0&&st.createElement(Qe,{flexDirection:"row"},st.createElement(Qe,{width:2},st.createElement(Xe,{color:OR.SUCCESS},gt.checkboxOn)),st.createElement(Xe,{color:OR.SUCCESS,strikethrough:!0},t," completed")),st.createElement(TodoChecklist,{todos:n}),r>0&&st.createElement(Xe,{color:ER.DIM},` … +${r} more`))}__name(shapeOf,"shapeOf"),__name(emit2,"emit"),__name(cancelPeek,"cancelPeek"),__name(armPeek,"armPeek"),__name(projectUserEdits,"projectUserEdits"),__name(setSessionTodos,"setSessionTodos"),__name(adoptSettled,"adoptSettled"),__name(seedSessionTodos,"seedSessionTodos"),__name(removeSessionTodoAt,"removeSessionTodoAt"),__name(seedTodosFromFeedEntries,"seedTodosFromFeedEntries"),__name(clearSessionTodos,"clearSessionTodos"),__name(getSessionTodos,"getSessionTodos"),__name(isTodoPanelCollapsed,"isTodoPanelCollapsed"),__name(completeSessionTodoAt,"completeSessionTodoAt"),__name(completeAllSessionTodos,"completeAllSessionTodos"),__name(subscribe,"subscribe"),__name(useSessionTodos,"useSessionTodos"),__name(useTodoPanelCollapsed,"useTodoPanelCollapsed"),__name(usePausedLabel,"usePausedLabel"),__name(projectVisibleTodos,"projectVisibleTodos"),__name(currentTaskLabel,"currentTaskLabel"),__name(TodoPanel,"TodoPanel"),__name(CappedChecklist,"CappedChecklist"),Gt();var VF=new Set,zF=!1;function isTodosManagerOpen(){return zF}function requestTodosManagerOpen(){for(const e of VF)e()}function statusColor(e){return"completed"===e?ER.GREEN:"in_progress"===e?ER.CYAN:ER.WHITE}function TodoRow({todo:e,selected:t}){const n="completed"===e.status?gt.checkboxOn:gt.checkboxOff,r=t?KR:void 0;return st.createElement(Qe,null,st.createElement(jN,{isSelected:t,backgroundColor:r}),st.createElement(Xe,{color:statusColor(e.status),backgroundColor:r}," ",n),st.createElement(Xe,{color:t?wO:statusColor(e.status),strikethrough:"completed"===e.status,backgroundColor:r,wrap:"truncate-end"}," ",e.content),"in_progress"===e.status&&st.createElement(Xe,{color:ER.DIM,backgroundColor:r}," ","(in progress)"))}function TodosManagerPanel({sessionId:e,onExpandedChange:t}){const n=useSessionTodos(),[r,o]=at(!1),[s,i]=at(0);ct(()=>(zF=r,t?.(r),()=>{zF=!1,t?.(!1)}),[r,t]),ct(()=>{const e=__name(()=>{i(0),o(!0)},"listener");return VF.add(e),()=>{VF.delete(e)}},[]),ct(()=>{if(0===n.length)return o(!1),void i(0);i(e=>Math.min(e,n.length-1))},[n.length]);const a=__name(t=>{k$(e)?.applyTodoUserEdit(t)},"syncHarness");if(nt((e,t)=>{if(t.escape||t.leftArrow||t.ctrl&&"x"===e||""===e)o(!1);else if(0!==n.length)if(t.upArrow)i(e=>Math.max(0,e-1));else if(t.downArrow)i(e=>Math.min(n.length-1,e+1));else{if("c"===e){const e=n[s];return void a({todos:completeSessionTodoAt(s),...e?{completedContents:[e.content]}:{}})}if("x"===e){const e=n[s];return void a({todos:removeSessionTodoAt(s),...e?{removedContents:[e.content]}:{}})}"a"===e&&a({todos:[],completedContents:completeAllSessionTodos()})}},{isActive:r}),!r)return null;const l=n.filter(e=>"completed"===e.status).length;return st.createElement(bO,{title:"Todos",subtitle:l>0?`${n.length} items · ${l} done`:`${n.length} items`,gapAfterHeader:!1,boxProps:{marginTop:1,marginBottom:1}},st.createElement(Qe,{flexDirection:"column",marginTop:1},n.map((e,t)=>st.createElement(TodoRow,{key:e.id??t,todo:e,selected:t===s}))))}__name(isTodosManagerOpen,"isTodosManagerOpen"),__name(requestTodosManagerOpen,"requestTodosManagerOpen"),__name(statusColor,"statusColor"),__name(TodoRow,"TodoRow"),__name(TodosManagerPanel,"TodosManagerPanel"),Gt(),SR(),SR();var KF=__name(({currentModel:e,onClose:t,refreshBanner:n,sessionId:r})=>{const o=customReasoningEfforts(e)??getSupportedEfforts(e)??[],s=findModelById(e)?.label??getModelDisplayName(e),i=lt(!1),a=__name(o=>{if(i.current)return;i.current=!0;const s=o!==getReasoningEffort(e);(async()=>{try{s&&(await setReasoningEffort({modelId:e,effort:o}),n(),void 0!==o&&r&&k$(r)?.recordEffortChange({model:e,effort:o}))}catch(e){dlog(`[Effort] Failed to persist reasoning effort: ${e}`)}finally{t()}})()},"handleSelect"),l=__name(()=>{i.current||t()},"handleCancel");return st.createElement(P_,{modelLabel:s,supportedEfforts:o,currentEffort:getReasoningEffort(e),onSelect:a,onCancel:l})},"EffortSelector");function store(){return createAuthFileCredentialStore({authStore:createCommandAuthFileStore({runtime:createNodeRuntime()})})}async function getCustomProviderKeyState(e){const t=await store().get({provider:e});if("api"===t?.kind&&t.token)return"stored";const n=(await loadProvidersConfig({runtime:createNodeRuntime()})).providers.find(t=>t.id===e);return n?.apiKey?"configured":n?.keyless?"keyless":"missing"}async function getConfiguredKeyReference(e){const t=await loadProvidersConfig({runtime:createNodeRuntime()});return t.providers.find(t=>t.id===e)?.apiKey}async function storeCustomProviderKey(e){await store().set({provider:e.providerId,credential:{kind:"api",token:e.key}})}async function getStoredKeyPreview(e){const t=await store().get({provider:e});if("api"===t?.kind&&t.token)return`${t.token.slice(0,8)}…`}async function getStoredKeyToken(e){const t=await store().get({provider:e});return"api"===t?.kind&&t.token?t.token:void 0}async function clearCustomProviderKey(e){await store().remove({provider:e})}Gt(),SR(),Gt(),SR(),__name(store,"store"),__name(getCustomProviderKeyState,"getCustomProviderKeyState"),__name(getConfiguredKeyReference,"getConfiguredKeyReference"),__name(storeCustomProviderKey,"storeCustomProviderKey"),__name(getStoredKeyPreview,"getStoredKeyPreview"),__name(getStoredKeyToken,"getStoredKeyToken"),__name(clearCustomProviderKey,"clearCustomProviderKey"),Gt(),SR(),Gt();var qF={"@ai-sdk/openai":"openai-responses","@ai-sdk/anthropic":"anthropic-messages","@ai-sdk/openai-compatible":"openai-completions"};function modelOverrides(e){if(!isPlainObject8(e))return{};const t=e.provider;if(!isPlainObject8(t))return{};if("string"!=typeof t.npm)return{};const n=qF[t.npm];if(void 0===n)return;const r="string"==typeof t.api&&t.api.startsWith("https://")&&!t.api.includes("${")?t.api.replace(/\/+$/,""):void 0;return{api:n,...void 0!==r?{baseURL:r}:{}}}function cachePath(){return n(W(),".commandcode","cache","models-dev.json")}function isPlainObject8(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}async function readCache(){try{const e=JSON.parse(await se(cachePath(),"utf8"));if(!isPlainObject8(e.data))return null;const t=Date.now()-(e.fetchedAt??0);return{data:e.data,fresh:t>=0&&t<864e5}}catch{return null}}async function writeCache(e){try{const t=cachePath();await Z(r(t),{recursive:!0}),await K(t,JSON.stringify({fetchedAt:Date.now(),data:e}))}catch{}}async function fetchCatalog(e){const t=new AbortController,n=setTimeout(()=>t.abort(),6e3);try{const n=await e("https://models.dev/api.json",{headers:{accept:"application/json"},signal:t.signal});if(!n.ok)return null;const r=await n.json();return isPlainObject8(r)?r:null}catch{return null}finally{clearTimeout(n)}}async function loadCatalog(e){const t=await readCache();if(t?.fresh)return t.data;const n=await fetchCatalog(e);return n?(await writeCache(n),n):t?.data??null}function asPositive(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}function urlParts(e){try{const t=new URL(e);return{host:t.hostname.toLowerCase(),path:t.pathname.replace(/\/+$/,"")||"/"}}catch{return}}function recordContains(e,t){if(e===t)return!0;const n="/"===e?"/":`${e}/`;return t.startsWith(n)}function curateModels(e){return isPlainObject8(e)?Object.entries(e).filter(e=>isPlainObject8(e[1])).filter(([,e])=>"deprecated"!==e.status).filter(([,e])=>{const t=isPlainObject8(e.modalities)?e.modalities.output:void 0;return!Array.isArray(t)||t.includes("text")}).sort(([,e],[,t])=>String(t.release_date??"").localeCompare(String(e.release_date??""))).flatMap(([e,t])=>{const n=modelOverrides(t);if(void 0===n)return[];const r=isPlainObject8(t.limit)?t.limit:void 0;return{id:e,...n,..."string"==typeof t.name&&t.name?{name:t.name}:{},...void 0!==asPositive(r?.context)?{contextWindow:asPositive(r?.context)}:{},...void 0!==asPositive(r?.output)?{maxOutput:asPositive(r?.output)}:{}}}):[]}__name(modelOverrides,"modelOverrides"),__name(cachePath,"cachePath"),__name(isPlainObject8,"isPlainObject"),__name(readCache,"readCache"),__name(writeCache,"writeCache"),__name(fetchCatalog,"fetchCatalog"),__name(loadCatalog,"loadCatalog"),__name(asPositive,"asPositive"),__name(urlParts,"urlParts"),__name(recordContains,"recordContains"),__name(curateModels,"curateModels");var YF=new Set(["github-copilot","amazon-bedrock","google-vertex","azure"]);async function listModelsDevProviders(e){const t=await loadCatalog(e?.fetchImpl??globalThis.fetch);if(!t)return[];const n=[];for(const[e,r]of Object.entries(t)){if(!isPlainObject8(r))continue;if(YF.has(e))continue;const t="string"==typeof r.api?r.api:void 0;if(!t||!t.startsWith("https://")||t.includes("${"))continue;const o=e.toLowerCase();n.push({id:"openai"===o||"anthropic"===o?`${o}-api`:o,name:"string"==typeof r.name&&r.name?r.name:e,baseURL:t.replace(/\/+$/,""),wire:"@ai-sdk/anthropic"===r.npm?"anthropic-messages":"openai-completions"})}return n}async function findModelsDevProvider(e){const t=urlParts(e.baseURL);if(!t)return null;const n=await loadCatalog(e.fetchImpl??globalThis.fetch);if(!n)return null;const r=[];for(const[e,o]of Object.entries(n)){if(!isPlainObject8(o))continue;const n="string"==typeof o.api?urlParts(o.api):void 0;n&&n.host===t.host&&r.push({slug:e,record:o,path:n.path})}if(0===r.length)return null;const o=r.filter(e=>recordContains(e.path,t.path)).sort((e,t)=>t.path.length-e.path.length),s=o[0]??(1===r.length?r[0]:void 0);if(!s)return null;if(o.length>1&&o[1]?.path===s.path)return null;const i=curateModels(s.record.models);if(0===i.length)return null;const a=Array.isArray(s.record.env)?s.record.env.find(e=>"string"==typeof e):void 0;return{slug:s.slug,displayName:"string"==typeof s.record.name&&s.record.name?s.record.name:s.slug,...a?{envVar:a}:{},models:i}}__name(listModelsDevProviders,"listModelsDevProviders"),__name(findModelsDevProvider,"findModelsDevProvider"),Gt();var JF=[{id:"ollama",name:"Ollama (local)",baseURL:"http://localhost:11434/v1",wire:"openai-completions",keyless:!0},{id:"lmstudio",name:"LM Studio (local)",baseURL:"http://127.0.0.1:1234/v1",wire:"openai-completions",keyless:!0}],QF=[{id:"vercel",name:"Vercel AI Gateway",baseURL:"https://ai-gateway.vercel.sh/v1",wire:"openai-completions"},{id:"groq",name:"Groq",baseURL:"https://api.groq.com/openai/v1",wire:"openai-completions"},{id:"mistral",name:"Mistral",baseURL:"https://api.mistral.ai/v1",wire:"openai-completions"},{id:"xai",name:"xAI",baseURL:"https://api.x.ai/v1",wire:"openai-completions"},{id:"together",name:"Together AI",baseURL:"https://api.together.xyz/v1",wire:"openai-completions"},{id:"cerebras",name:"Cerebras",baseURL:"https://api.cerebras.ai/v1",wire:"openai-completions"},{id:"deepinfra",name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/openai",wire:"openai-completions"},{id:"perplexity",name:"Perplexity",baseURL:"https://api.perplexity.ai",wire:"openai-completions"}],XF=/^[a-z0-9._-]+$/;function hostOf2(e){try{return new URL(e).hostname.toLowerCase()}catch{return}}function fallbackProviderSuggestions(){return[...QF,...JF]}async function loadProviderSuggestions(e){let t=[];try{t=await listModelsDevProviders(e?.fetchImpl?{fetchImpl:e.fetchImpl}:void 0)}catch{}const n=t.filter(e=>XF.test(e.id)).map(e=>({id:e.id,name:e.name,baseURL:e.baseURL,wire:e.wire})),r=[],o=new Set;for(const e of fallbackProviderSuggestions()){const t=n.find(t=>t.id===e.id||hostOf2(t.baseURL)===hostOf2(e.baseURL))??e;o.has(t.id)||(r.push(t),o.add(t.id))}return[...r,...n.filter(e=>!o.has(e.id)).sort((e,t)=>e.id.localeCompare(t.id))]}function matchKnownProviders(e){const t=e.query.trim().toLowerCase();return t?e.providers.filter(e=>e.id.startsWith(t)||e.name.toLowerCase().includes(t)).slice(0,e.limit??3):[]}function findKnownProvider(e){const t=e.id.trim().toLowerCase();return e.providers.find(e=>e.id===t)}__name(hostOf2,"hostOf"),__name(fallbackProviderSuggestions,"fallbackProviderSuggestions"),__name(loadProviderSuggestions,"loadProviderSuggestions"),__name(matchKnownProviders,"matchKnownProviders"),__name(findKnownProvider,"findKnownProvider"),Gt();var ZF=["/chat/completions","/completions","/responses","/messages","/models"];function normalizeEndpointInput(e){let t=e.trim().replace(/\/+$/,"");for(const e of ZF)if(t.toLowerCase().endsWith(e))return t=t.slice(0,-e.length).replace(/\/+$/,""),{url:t,stripped:e};return{url:t}}function asPositiveInt(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}function extractModels(e){const t=Array.isArray(e)?e:"object"==typeof e&&null!==e?e.data??e.models:void 0;if(!Array.isArray(t))return[];const n=new Map;for(const e of t){if("string"==typeof e){n.has(e)||n.set(e,{id:e});continue}if("object"!=typeof e||null===e)continue;const t=e,r="string"==typeof t.id?t.id:"string"==typeof t.name?t.name:void 0;if(!r||n.has(r))continue;const o="string"==typeof t.name&&t.name!==r?t.name:void 0,s=asPositiveInt(t.context_length)??asPositiveInt(t.context_window)??asPositiveInt(t.top_provider?.context_length),i=asPositiveInt(t.top_provider?.max_completion_tokens)??asPositiveInt(t.max_output_tokens)??asPositiveInt(t.max_tokens);n.set(r,{id:r,...o?{name:o}:{},...void 0!==s?{contextWindow:s}:{},...void 0!==i?{maxOutput:i}:{}})}return[...n.values()]}async function probeProviderModels(e){const t=e.fetchImpl??globalThis.fetch,n=e.baseURL.replace(/\/+$/,""),r=new AbortController,o=setTimeout(()=>r.abort(),e.timeoutMs??5e3);try{const o=await t(`${n}/models`,{headers:{accept:"application/json",...e.apiKey?{authorization:`Bearer ${e.apiKey}`,"x-api-key":e.apiKey}:{}},signal:r.signal});if(!o.ok)return{ok:!1,models:[],detail:`the endpoint answered ${o.status} on /models`};const s=extractModels(await o.json());return 0===s.length?{ok:!1,models:[],detail:"the endpoint listed no models"}:{ok:!0,models:s}}catch(e){return{ok:!1,models:[],detail:e instanceof Error&&("AbortError"===e.name||r.signal.aborted)?"no answer within 5s":"could not reach the endpoint"}}finally{clearTimeout(o)}}function ProvidersJsonLink({color:e=ER.DIM}){const t=`${W()}/.commandcode/providers.json`;return st.createElement(cL,{url:`file://${t}`,text:"~/.commandcode/providers.json",color:e})}function toNewProviderModels(e){return e.map(e=>({id:e.id,...e.name?{name:e.name}:{},...void 0!==e.contextWindow?{contextWindow:e.contextWindow}:{},...void 0!==e.maxOutput?{maxOutput:e.maxOutput}:{},...e.api?{api:e.api}:{},...e.baseURL?{baseURL:e.baseURL}:{}}))}function cardKeyLine(e){return"stored"===e.keyState?st.createElement(Xe,null,"key ",st.createElement(Xe,{color:ER.GREEN},e.keyPreview)," ",st.createElement(Xe,{color:ER.GREEN},"✓")," stored in auth.json",e.configuredReference?` · overrides ${e.configuredReference}`:""):"configured"===e.keyState?st.createElement(Xe,null,"key ",e.configuredReference??"set"):"keyless"===e.keyState?st.createElement(Xe,null,"no key — the endpoint asks for none"):st.createElement(Xe,{color:ER.YELLOW},"no key yet, requests fail until one is added")}function cardHints(e){const t=[st.createElement(st.Fragment,null,st.createElement(gO,null,"u")," update models"),st.createElement(st.Fragment,null,st.createElement(gO,null,"d")," delete"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," close")];return"stored"===e?[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," save"),st.createElement(st.Fragment,null,st.createElement(gO,null,"r")," replace key"),st.createElement(st.Fragment,null,st.createElement(gO,null,"c")," clear"),...t]:"missing"===e?[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," add key"),...t]:[st.createElement(st.Fragment,null,st.createElement(gO,null,"r")," store key"),...t]}function CustomProviderKeyEntry({providerId:e,providerName:t,keyState:n,keyPreview:r,configuredReference:o,onClose:s,onOpenModels:i,sessionId:a,onActiveModelOrphaned:l,onDiskDefaultOrphaned:c}){const[d,u]=at(""),[m,p]=at("card"),[g,h]=at(void 0),[f,y]=at(!1),[S,w]=at(void 0),[v,k]=at(void 0);st.useEffect(()=>{let t=!0;return(async()=>{const n=(await loadProvidersConfig({runtime:createNodeRuntime()})).providers.find(t=>t.id===e);t&&n&&w({baseURL:n.baseURL,modelCount:n.models.length})})(),()=>{t=!1}},[e]);const C=__name(async()=>{p("removing");try{const t=isByok({model:getConfiguredModel()??"",providerId:e}),n=(await loadUserConfig()).model??"",r=!t&&isByok({model:n,providerId:e});await removeUserProviderEntry({runtime:createNodeRuntime(),id:e}),await clearCustomProviderKey(e),t?(await(l?.()),y(!0)):r&&await(c?.()),await refreshCustomProviderModels(a?{sessionId:a}:void 0),p("removed")}catch(e){h(e instanceof Error?e.message:String(e)),p("error")}},"removeProvider"),b=__name(async()=>{p("updating-models");try{const t=(await loadProvidersConfig({runtime:createNodeRuntime()})).providers.find(t=>t.id===e);if(!t)throw new Error(`'${e}' is not in providers.json`);const n=await findModelsDevProvider({baseURL:t.baseURL}).catch(()=>null);let r,o;if(n&&n.models.length>0)r=toNewProviderModels(n.models),o="the model registry";else{const n=await getStoredKeyToken(e),s=await probeProviderModels({baseURL:t.baseURL,...n?{apiKey:n}:{}});if(!s.ok||0===s.models.length)throw new Error(`couldn't fetch models — ${s.detail??"no source answered"}`);r=toNewProviderModels(s.models),o="the endpoint"}const{count:s}=await updateUserProviderEntryModels({runtime:createNodeRuntime(),id:e,models:r});await refreshCustomProviderModels(a?{sessionId:a}:void 0),w(e=>e?{...e,modelCount:s}:e),k({count:s,source:o}),p("models-updated")}catch(e){h(e instanceof Error?e.message:String(e)),p("error")}},"updateModels");nt((t,r)=>{if(r.escape){if("removing"===m||"updating-models"===m)return;return"entry"===m?(u(""),void p("card")):"confirm-remove"===m?void p("card"):void s()}if("entry"!==m||!r.leftArrow||d){if("card"===m)return"d"===t||"D"===t?void p("confirm-remove"):"r"===t||"R"===t?void p("entry"):"u"===t||"U"===t?void b():"stored"!==n||"c"!==t&&"C"!==t?"missing"===n&&r.return?void p("entry"):void(r.return&&s()):void clearCustomProviderKey(e).then(()=>p("cleared"),()=>p("error"));if("confirm-remove"!==m)return"saved"===m&&r.return?(s(),void i?.()):void("models-updated"===m&&r.return?p("card"):"cleared"!==m&&"removed"!==m&&"error"!==m||!r.return||s());"y"===t||"Y"===t?C():(r.return||t)&&p("card")}else p("card")});const E=__name(async()=>{const t=d.trim();if(t)try{await storeCustomProviderKey({providerId:e,key:t}),p("saved")}catch{p("error")}},"handleSubmit"),T=S?st.createElement(st.Fragment,null,S.baseURL," · ",S.modelCount," ",1===S.modelCount?"model":"models"," · config:"," ",st.createElement(cL,{url:`file://${W()}/.commandcode/providers.json`,text:"providers.json",color:ER.DIM})):void 0;if("card"===m){const e=cardKeyLine({keyState:n,keyPreview:r,configuredReference:o}),s=cardHints(n);return st.createElement(bO,{title:t,titleSuffix:st.createElement(Xe,{color:ER.DIM}," (byok)"),subtitle:T,footer:st.createElement(hO,{hints:s,marginTop:0})},st.createElement(Qe,null,e))}return"confirm-remove"===m?st.createElement(bO,{title:`Remove ${t}?`,subtitle:"Its entry, models, and stored key go with it",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"y")," remove"),"any other key keeps it"]})},st.createElement(Xe,null,"Deletes the entry from ",st.createElement(ProvidersJsonLink,null)," and clears its stored key.")):"removing"===m||"updating-models"===m?st.createElement(bO,{title:t,rule:!1},st.createElement(Xe,null,"removing"===m?`Removing '${e}'…`:`Refetching models for '${e}'…`)):"removed"===m?st.createElement(bO,{title:`${t} removed`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," close")]})},st.createElement(Xe,{color:ER.DIM},"Provider deleted from ",st.createElement(ProvidersJsonLink,null)," · stored key cleared · its models left /model",f?" · it owned your active model — switched to your lane’s default":"")):"models-updated"===m?st.createElement(bO,{title:t,subtitle:T,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," back"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," close")]})},st.createElement(Xe,{color:ER.GREEN},"Models updated — ",v?.count??0," declared from"," ",v?.source??"the refetch",".")):"saved"===m?st.createElement(bO,{title:`Key saved for ${t}`,subtitle:"Stored in ~/.commandcode/auth.json",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," pick a model"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," close")]})}):"cleared"===m?st.createElement(bO,{title:`Stored key cleared for ${t}`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," close")]})},st.createElement(Xe,{color:ER.DIM},"Its models stay listed",o?" — the providers.json key applies again":"; requests will need a key again")):"error"===m?st.createElement(bO,{title:`Could not update ${t}`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," close")]})},st.createElement(Xe,{color:ER.DIM},g??'Check that ~/.commandcode is writable, or set "apiKey" to a "$ENV_VAR" reference in providers.json')):st.createElement(bO,{title:`API key for ${t}`,subtitle:`Saved to ~/.commandcode/auth.json under '${e}'. requests go straight to this provider with your key`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," save"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," back")]})},st.createElement(Qe,{borderStyle:"single",borderColor:ER.YELLOW,paddingX:1,width:"100%"},st.createElement(Xe,{color:ER.DIM},"key: "),st.createElement(Qe,{flexGrow:1},st.createElement(TextInput,{value:d,onChange:u,onSubmit:()=>{E()},placeholder:"paste your API key…",mask:"*",showCursor:!0}))))}function makeCustomProviderKeyEntry(e){return __name(function CustomProviderKeyEntryAdapter({onCancel:t}){return st.createElement(CustomProviderKeyEntry,{providerId:e.providerId,providerName:e.providerName,keyState:e.keyState,keyPreview:e.keyPreview,configuredReference:e.configuredReference,onClose:t,onOpenModels:e.onOpenModels,sessionId:e.sessionId,onActiveModelOrphaned:e.onActiveModelOrphaned,onDiskDefaultOrphaned:e.onDiskDefaultOrphaned})},"CustomProviderKeyEntryAdapter")}function makeAddCustomProviderEntry(e={}){return __name(function AddCustomProviderAdapter({onCancel:t}){return st.createElement(AddCustomProviderEntry,{onClose:t,onOpenModels:e.onOpenModels,sessionId:e.sessionId})},"AddCustomProviderAdapter")}__name(normalizeEndpointInput,"normalizeEndpointInput"),__name(asPositiveInt,"asPositiveInt"),__name(extractModels,"extractModels"),__name(probeProviderModels,"probeProviderModels"),__name(ProvidersJsonLink,"ProvidersJsonLink"),__name(toNewProviderModels,"toNewProviderModels"),__name(cardKeyLine,"cardKeyLine"),__name(cardHints,"cardHints"),__name(CustomProviderKeyEntry,"CustomProviderKeyEntry"),__name(makeCustomProviderKeyEntry,"makeCustomProviderKeyEntry"),__name(makeAddCustomProviderEntry,"makeAddCustomProviderEntry");var eU=[{value:"openai-completions",label:"OpenAI-compatible",detail:"/chat/completions · Ollama, vLLM, LM Studio, most hosted APIs"},{value:"openai-responses",label:"OpenAI Responses",detail:"/responses · endpoints speaking the OpenAI Responses API"},{value:"anthropic-messages",label:"Anthropic wire",detail:"/v1/messages · endpoints speaking the Claude Messages API"}];function cycleWire(e){const t=eU.findIndex(t=>t.value===e.current),n=eU.length,r=((e.forward?t+1:t-1)+n)%n;return eU[r]?.value??e.current}__name(cycleWire,"cycleWire");var tU=[["{",""],[' "provider": {',""],[' "openrouter": {',"the id you typed"],[' "baseURL": "https://openrouter.ai/api/v1",',"API root, no route"],[' "apiKey": "$OPENROUTER_API_KEY",',"reference — never a raw key"],[' "models": { "openai/gpt-5.6": {} }',"edit anytime, reloads live"],[" }",""],[" }",""],["}",""]];function endpointSubtitle(e){return e.prefilledName?`Prefilled for ${e.prefilledName} — edit it or press enter to accept`:"anthropic-messages"===e.wire?"The Messages API root · /v1 is added on the wire when missing":"openai-responses"===e.wire?"The API root requests go to · /responses is added on the wire":"The API root requests go to · most end in /v1"}function endpointPlaceholder(e){return"anthropic-messages"===e?"https://api.example.com/anthropic":"openai-responses"===e?"https://api.example.com/v1":"http://localhost:11434/v1"}function idStepMatches(e){return"id"!==e.phase?[]:e.query.trim()?matchKnownProviders({query:e.query,providers:e.providers,limit:e.providers.length}):e.providers}function AddCustomProviderEntry({onClose:e,onOpenModels:t,sessionId:n}){const[r,o]=at(""),[s,i]=at("openai-completions"),[a,l]=at(""),[c,d]=at(""),[u,m]=at(""),[p,g]=at("id"),[h,f]=at(()=>fallbackProviderSuggestions());st.useEffect(()=>{let e=!0;return loadProviderSuggestions().then(t=>{e&&t.length>0&&f(t)}),()=>{e=!1}},[]);const[y,S]=at(void 0),[w,v]=at(null),[k,C]=at(void 0),[b,E]=at(void 0),T=st.useRef(null),P=st.useRef("api"),M=st.useRef([]),[x,I]=at(void 0),[A,R]=at(0),[L,O]=at(void 0),D=""===c.trim(),$=idStepMatches({phase:p,query:r,providers:h}),N=__name(e=>{M.current.push(p),g(e)},"goTo"),_=__name((e,t)=>{M.current.push(e),g(t)},"arriveFrom"),F=__name(()=>{const t=M.current.pop();C(void 0),E(void 0),t?g(t):e()},"goBack");nt((n,o)=>{if("help"!==p){if(o.escape){if("saving"===p||"probing"===p)return;return"done"===p||"error"===p?void e():void F()}if(o.leftArrow&&("api"===p||"id"===p&&!r||"endpoint"===p&&!a||"key"===p&&!c||"manual-models"===p&&!u))F();else{if("api"===p&&("h"===n||"H"===n))return P.current=p,void g("help");if("id"!==p)return"api"===p?((o.upArrow||o.downArrow)&&i(e=>cycleWire({current:e,forward:!0===o.downArrow})),void(o.return&&N("endpoint"))):"done"===p&&o.return?(e(),void t?.()):void("error"===p&&o.return&&e());(o.upArrow||o.downArrow)&&$.length>0&&v(e=>{const t=$.length-1;if(null===e)return o.downArrow?0:t;const n=e+(o.downArrow?1:-1);return n<0?t:n>t?0:n})}}else g(P.current)});const U=__name(()=>{const e=null===w?void 0:$[w];if(e)return getCustomProviderModelsSync().some(t=>t.id===e.id)?void C(`'${e.id}' already exists — select it in /connect to manage it.`):(C(void 0),o(e.id),S(e),i(e.wire),l(e.baseURL),v(null),void N("api"));const t=r.trim().toLowerCase();if(!t)return;if(!isValidProviderId(t))return void C("Lowercase letters, digits, dots, dashes and underscores only.");if(isReservedProviderId(t))return void C(`'${t}' is a built-in subscription lane — try '${t}-api'.`);if(getCustomProviderModelsSync().some(e=>e.id===t))return void C(`'${t}' already exists — select it in /connect to manage it.`);C(void 0),o(t);const n=findKnownProvider({id:t,providers:h});S(n),n&&(i(n.wire),l(n.baseURL)),N("api")},"submitId"),j=__name(()=>{const{url:e,stripped:t}=normalizeEndpointInput(a);if(!e)return;let n;try{n=new URL(e)}catch{return void C("That is not a URL — include the scheme (http…).")}if("http:"===n.protocol||"https:"===n.protocol){if(C(void 0),t)return l(e),void E(`removed ${t} — the endpoint is the API root`);E(void 0),l(e),T.current=findModelsDevProvider({baseURL:e}).catch(()=>null),N("key")}else C("http:// or https:// URLs only.")},"submitEndpoint"),B=__name(async()=>{g("probing");const e=c.trim();let t=await probeProviderModels({baseURL:a,...e?{apiKey:e}:{}});t.ok||"anthropic-messages"!==s||a.endsWith("/v1")||(t=await probeProviderModels({baseURL:`${a}/v1`,...e?{apiKey:e}:{}})),t.ok&&t.models.length>0?await G(t.models):(I(t.detail),_("key","manual-models"))},"runProbe"),W=__name(async()=>{const e=c.trim();if(e)try{await storeCustomProviderKey({providerId:r,key:e})}catch{return O("The key could not be stored — check that ~/.commandcode is writable."),void g("error")}g("probing");const t=await T.current??null;t&&t.models.length>0?await G(t.models):await B()},"submitKey"),H=__name(()=>{const e=u.split(",").map(e=>e.trim()).filter(Boolean);0!==e.length&&G(e.map(e=>({id:e})))},"submitManualIds"),G=__name(async e=>{g("saving");try{await addUserProviderEntry({runtime:createNodeRuntime(),id:r,baseURL:a,api:s,keyless:D,models:toNewProviderModels(e)}),R(e.length),await refreshCustomProviderModels(n?{sessionId:n}:void 0),g("done")}catch(e){O(e instanceof Error?e.message:String(e)),g("error")}},"writeEntry"),V=k?st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.RED},k)):null,z=r.trim()?`Add a provider · ${r.trim().toLowerCase()}`:"Add a provider";if("saving"===p||"probing"===p)return st.createElement(bO,{title:z,rule:!1},st.createElement(Xe,null,"probing"===p?`Asking ${a} which models it serves…`:`Writing '${r}' to ~/.commandcode/providers.json…`));if("done"===p)return st.createElement(bO,{title:`'${r}' is set up`,subtitle:`${A} ${1===A?"model":"models"} declared${D?" · keyless endpoint":" · key stored in auth.json"}`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," pick a model"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," close")]})},st.createElement(Xe,{color:ER.DIM},"Provider added to ",st.createElement(ProvidersJsonLink,null),". Edit it anytime, it reloads live."));if("error"===p)return st.createElement(bO,{title:`Adding '${r}' didn't finish`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," close")]})},st.createElement(Xe,{color:ER.DIM},L));if("help"===p)return st.createElement(bO,{title:"Adding a provider: the short version",footer:st.createElement(Qe,{flexDirection:"column"},st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,"docs:"," ",st.createElement(cL,{url:"https://commandcode.ai/docs/byok",text:"commandcode.ai/docs/byok",color:ER.DIM})),"any key to go back"]}))},st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},"• provider id names the entry in ",st.createElement(ProvidersJsonLink,null)," · models select as id/model"),st.createElement(Xe,{color:ER.DIM},"• endpoint is the base URL requests go to · most end in /v1"),st.createElement(Xe,{color:ER.DIM},"• pasted keys go to auth.json · providers.json only ever holds $ENV_VAR or !command references"),st.createElement(Xe,{color:ER.DIM},"• no key needed? press enter on the empty key field (local servers)"),st.createElement(Xe,{color:ER.DIM},"• models: you can import the fetched list, probe the endpoint's /models route, or type ids by hand. Ids you leave undeclared still run as id/model"),st.createElement(Xe,{color:ER.DIM},"• the ",st.createElement(ProvidersJsonLink,null)," file is yours · edit it anytime, it reloads live · manage it from /connect"),st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.DIM},"what it writes:"),tU.map(([e,t])=>st.createElement(Xe,{key:e},st.createElement(Xe,{color:ER.CYAN}," ",e),t?st.createElement(Xe,{color:ER.DIM}," ","// ",t):null)))));if("manual-models"===p)return st.createElement(bO,{title:z,subtitle:x?`Couldn't list models automatically — ${x}`:`Which models does ${r} serve?`,footer:st.createElement(hO,{marginTop:0,hints:["comma-separated, exact ids",st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," save"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," back")]})},st.createElement(Qe,{borderStyle:"single",borderColor:ER.YELLOW,paddingX:1,width:"100%"},st.createElement(Xe,{color:ER.DIM},"models: "),st.createElement(Qe,{flexGrow:1},st.createElement(TextInput,{value:u,onChange:m,onSubmit:H,placeholder:"llama3.3:70b, qwen2.5-coder:32b",showCursor:!0}))));if("key"===p)return st.createElement(bO,{title:z,subtitle:"Keys live in ~/.commandcode/auth.json, never in providers.json",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," save"),"empty enter = keyless (local servers)",st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," back")]})},st.createElement(Qe,{borderStyle:"single",borderColor:ER.YELLOW,paddingX:1,width:"100%"},st.createElement(Xe,{color:ER.DIM},"key: "),st.createElement(Qe,{flexGrow:1},st.createElement(TextInput,{value:c,onChange:d,onSubmit:()=>{W()},placeholder:"paste it — or press enter if none is needed",mask:"*",showCursor:!0}))));if("api"===p)return st.createElement(bO,{title:z,subtitle:"What does the endpoint speak?",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"↑/↓")," switch"),st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," continue"),st.createElement(st.Fragment,null,st.createElement(gO,null,"h")," help"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," back")]})},st.createElement(Qe,{flexDirection:"column"},eU.map(e=>st.createElement(Xe,{key:e.value},s===e.value?"❯ ":" ",st.createElement(Xe,{bold:s===e.value},e.label),st.createElement(Xe,{color:ER.DIM}," · ",e.detail)))));if("endpoint"===p){const e=y&&a===y.baseURL;return st.createElement(bO,{title:z,subtitle:endpointSubtitle({prefilledName:e?y.name:void 0,wire:s}),footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," continue"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," back")]})},st.createElement(Qe,{borderStyle:"single",borderColor:ER.YELLOW,paddingX:1,width:"100%"},st.createElement(Xe,{color:ER.DIM},"base URL: "),st.createElement(Qe,{flexGrow:1},st.createElement(TextInput,{value:a,onChange:e=>{l(e),C(void 0),E(void 0)},onSubmit:j,placeholder:endpointPlaceholder(s),showCursor:!0}))),b&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.YELLOW},b)),V)}const K=null===w?0:Math.min(Math.max(0,w-6+1),Math.max(0,$.length-6)),q=$.slice(K,K+6),Y=$.length-(K+q.length);return st.createElement(bO,{title:"Add a provider",subtitle:"Pick a known provider below, or type your own id.",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"↑/↓")," pick from the list"),st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," continue"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," close")]})},st.createElement(Qe,{borderStyle:"single",borderColor:ER.YELLOW,paddingX:1,width:"100%"},st.createElement(Xe,{color:ER.DIM},"provider id: "),st.createElement(Qe,{flexGrow:1},st.createElement(TextInput,{value:r,onChange:e=>{o(e),C(void 0),v(null)},onSubmit:U,placeholder:"ollama, work-llm, openrouter…",showCursor:!0}))),V,q.length>0&&st.createElement(Qe,{flexDirection:"column",marginTop:1},q.map((e,t)=>{const n=null!==w&&K+t===w;return st.createElement(Qe,{key:e.id},st.createElement(jN,{isSelected:n}),st.createElement(BN,{isSelected:n,idleColor:ER.DIM},` ${e.id}`),st.createElement(Xe,{color:ER.DIM}," ","· ",e.baseURL))}),(K>0||Y>0)&&st.createElement(Xe,{color:ER.DIM}," ",K>0?`↑ ${K} more · `:"",Y>0?`↓ ${Y} more`:"")))}__name(endpointSubtitle,"endpointSubtitle"),__name(endpointPlaceholder,"endpointPlaceholder"),__name(idStepMatches,"idStepMatches"),__name(AddCustomProviderEntry,"AddCustomProviderEntry"),Gt(),SR();var nU="__add-custom-provider__";async function invalidateHarnessForLaneSwitch(e){e&&await rebuildHarnessSession(e)}function showProviderNotification({setShowProviderNotification:e,providerNotificationTimer:t}){t.current&&clearTimeout(t.current),e(!0),t.current=setTimeout(()=>{e(!1),t.current=null},jM)}async function handleProviderSelect({provider:e,setCurrentProvider:t,setShowProviderSelector:n,setAuthComponentInfo:r,setStatus:o,setShowProviderNotification:s,providerNotificationTimer:i,setShowModelSelector:a,sessionId:l,onActiveModelOrphaned:c,onDiskDefaultOrphaned:d}){if(e===nU)return n(!1),r({provider:e,Component:makeAddCustomProviderEntry({...a?{onOpenModels:__name(()=>a(!0),"onOpenModels")}:{},...l?{sessionId:l}:{}})}),{switched:!1};const u=getCustomProviderModelsSync().find(t=>t.id===e);if(u){const t=await getCustomProviderKeyState(e),o="stored"===t?await getStoredKeyPreview(e):void 0,s=await getConfiguredKeyReference(e);return n(!1),r({provider:e,Component:makeCustomProviderKeyEntry({providerId:u.id,providerName:u.name,keyState:t,keyPreview:o,configuredReference:s,onOpenModels:a?()=>a(!0):void 0,sessionId:l,onActiveModelOrphaned:c,onDiskDefaultOrphaned:d})}),{switched:!1}}const m=getProviderConfig(e),p=m?.authComponent,g=await resolveProviderSelection({provider:e,requiresAuth:m?.requiresAuth,hasAuthFlow:Boolean(p),checkAuth:m?.checkAuth});return"auth-required"===g.status?(p&&r({provider:e,Component:p}),{switched:!1}):"error"===g.status?(o(g.statusMessage),n(!1),{switched:!1}):(t(e),await invalidateHarnessForLaneSwitch(l),n(!1),o(g.statusMessage),showProviderNotification({setShowProviderNotification:s,providerNotificationTimer:i}),{switched:!0})}function handleProviderCancel({setShowProviderSelector:e}){e(!1)}async function handleAuthSuccess({authComponentInfo:e,setAuthComponentInfo:t,setShowProviderSelector:n,setCurrentProvider:r,setStatus:o,setShowProviderNotification:s,providerNotificationTimer:i,sessionId:a}){return e?(t(null),n(!1),r(e.provider),await invalidateHarnessForLaneSwitch(a),o(buildProviderAuthSuccessStatus(e.provider)),showProviderNotification({setShowProviderNotification:s,providerNotificationTimer:i}),{switchedProvider:e.provider}):{switchedProvider:null}}function handleAuthCancel({setAuthComponentInfo:e}){e(null)}__name(invalidateHarnessForLaneSwitch,"invalidateHarnessForLaneSwitch"),__name(showProviderNotification,"showProviderNotification"),__name(handleProviderSelect,"handleProviderSelect"),__name(handleProviderCancel,"handleProviderCancel"),__name(handleAuthSuccess,"handleAuthSuccess"),__name(handleAuthCancel,"handleAuthCancel");var rU=__name(({onSelect:e,onCancel:t,sessionId:n})=>{const[r,o]=st.useState(()=>getCustomProviderModelsSync()),[s,i]=st.useState(()=>getCustomProviderWarningsSync()),[a,l]=st.useState({});st.useEffect(()=>{let e=!0;return(async()=>{const{providers:t}=await refreshCustomProviderModels(n?{sessionId:n}:void 0);if(!e)return;o(t),i(getCustomProviderWarningsSync());const r=await Promise.all(t.map(async e=>[e.id,await getCustomProviderKeyState(e.id)]));e&&l(Object.fromEntries(r))})(),()=>{e=!1}},[n]);const[c,d]=st.useState({});st.useEffect(()=>{let e=!0;return(async()=>{const t=getProviderOptions().filter(e=>isProviderLaneListable({providerId:e.value})),n=await Promise.all(t.map(async e=>{const t=getProviderConfig(e.value);if(!t?.requiresAuth||!t.checkAuth)return[e.value,!0];try{return[e.value,await t.checkAuth()]}catch{return[e.value,!1]}}));e&&d(Object.fromEntries(n))})(),()=>{e=!1}},[]);const u=__name(e=>{const t=c[e];if(void 0===t)return"";if(!t)return"○ not connected";const n=laneModelCount({laneId:e});return n>0?`✓ ${n} ${1===n?"model":"models"}`:"✓"},"laneStatus"),m=__name((e,t)=>{const n=a[e];if("missing"===n)return"○ needs a key";const r=`${t} ${1===t?"model":"models"}`;return void 0===n?r:`✓ ${r}`},"customStatus"),p=[...getProviderOptions().filter(e=>isProviderLaneListable({providerId:e.value})).map(e=>({label:"command-code"===e.value?`${getProviderDisplayName(e.value)} (recommended)`:getProviderDisplayName(e.value),value:e.value,status:u(e.value),notLive:!1===c[e.value]})),...r.map(e=>({label:e.name,value:e.id,status:m(e.id,e.models.length),notLive:"missing"===a[e.id]})),{label:"(BYOK) Add your own provider",value:nU,status:"",notLive:!1}],g=Math.max(42,...p.map(e=>e.label.length+12)),h=new Map(p.map(e=>[e.label,e])),f=__name(t=>{e(t.value)},"handleSelect");return nt((e,n)=>{n.escape&&t()}),st.createElement(bO,{title:"Connect",subtitle:"Connect to AI providers and see currently connected providers",hint:"↑/↓ navigate · enter select · esc close"},st.createElement(SelectInput,{items:p.map(e=>({label:e.label,value:e.value})),onSelect:f,initialIndex:0,indicatorComponent:jN,itemComponent:({isSelected:e,label:t})=>{const n=h.get(t??"");return st.createElement(Qe,null,st.createElement(BN,{isSelected:e,...n?.notLive?{idleColor:ER.DIM}:{}},` ${(t??"").padEnd(g)}`,n?.status.startsWith("✓")?st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.GREEN},"✓"),n.status.slice(1)):n?.status??""))}}),s.length>0&&st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.YELLOW},st.createElement(ProvidersJsonLink,{color:ER.YELLOW})," needs attention —"," ",1===s.length?"one entry":"some entries"," ","did not load as written:"),s.slice(0,3).map(e=>st.createElement(Xe,{key:e,color:ER.DIM}," ",e)),s.length>3&&st.createElement(Xe,{color:ER.DIM}," ","… and"," ",s.length-3," more")))},"ProviderSelector");Gt(),SR();var oU=__name(e=>0===e?"No code changes":`${e} file${e>1?"s":""} changed`,"formatFileCountLabel"),sU=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=dt(()=>[...e].sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),[e]),[o,s]=at(()=>Math.max(0,r.length-1)),[i,a]=at(()=>Math.max(0,r.length-8)),[l,c]=at("checkpoint"),[d,u]=at(null),[m,p]=at(0),g=dt(()=>hasCodeChangesToRestore({sortedCheckpoints:r,selectedCheckpoint:d}),[d,r]),h=dt(()=>g?Ax:Ax.filter(e=>"conversation"===e.mode),[g]);if(ct(()=>{if(r.length>0){const e=r.length-1;s(e),a(Math.max(0,r.length-8))}},[r.length,8]),nt((e,g)=>{if(g.escape)return"mode"===l?(c("checkpoint"),u(null),void p(0)):void n();"checkpoint"===l&&g.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):"checkpoint"===l&&g.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):"checkpoint"===l&&g.return?r.length>0&&(u(r[o]),c("mode"),p(0)):"mode"===l&&g.upArrow?p(e=>Math.max(0,e-1)):"mode"===l&&g.downArrow?p(e=>Math.min(h.length-1,e+1)):"mode"===l&&g.return&&d&&h[m]&&t({messageId:d.messageId,mode:h[m].mode})}),0===r.length)return st.createElement(bO,{title:"Rewind",subtitle:"No checkpoints available. Start a conversation to create checkpoints.",gapAfterHeader:!1,footer:st.createElement(pO,null,"Press ",st.createElement(gO,null,"Esc")," to close")});if("mode"===l&&d)return st.createElement(bO,{title:"Rewind",subtitle:st.createElement(st.Fragment,null,"Restore to:"," ",st.createElement(Xe,{color:ER.WHITE},truncateString2({text:d.prompt||"checkpoint",maxChars:50}))),footer:st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to confirm ·"," ",st.createElement(gO,null,"Esc")," to go back")},st.createElement(Qe,{flexDirection:"column"},h.map((e,t)=>{const n=m===t,r=t===h.length-1;return st.createElement(Qe,{key:e.mode,flexDirection:"column"},st.createElement(Qe,{flexDirection:"row"},st.createElement(Xe,{color:n?TR:void 0},n?`${fL} `:" "),st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:n?TR:ER.WHITE},e.label),st.createElement(Xe,{color:ER.DIM},e.description))),!r&&st.createElement(Xe,null," "))})));const f=r.slice(i,i+8);return st.createElement(bO,{title:"Rewind",subtitle:"Select a checkpoint to restore your session",gapAfterHeader:!1,footer:st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to select ·"," ",st.createElement(gO,null,"Esc")," to cancel")},r.length>8&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),st.createElement(Qe,{marginTop:1}),st.createElement(Qe,{flexDirection:"column"},f.map((e,t)=>{const n=i+t,s=o===n,a=e.filesModified.length,l=t===f.length-1,c=n===r.length-1;return st.createElement(Qe,{key:e.messageId,flexDirection:"column"},st.createElement(Qe,{flexDirection:"row"},st.createElement(Xe,{color:s?TR:void 0},s?`${fL} `:" "),st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,{color:s?TR:ER.WHITE},truncateString2({text:e.prompt||"(no prompt)",maxChars:60})),st.createElement(Xe,{color:ER.DIM}," • "),st.createElement(Xe,{color:ER.DIM},getRelativeTimeString({timestamp:e.createdAt}),c&&" (latest)")),st.createElement(Xe,{color:ER.DIM},oU(a)))),!l&&st.createElement(Xe,null," "))})))},"RewindSelector");Gt(),SR();var iU=["default","no-tools","user-only","labeled-only","all"],aU={default:"","no-tools":"[no-tools]","user-only":"[user]","labeled-only":"[labeled]",all:"[all]"};function nextFilterMode(e){const t=iU.indexOf(e);return iU[(t+1)%iU.length]}function previousFilterMode(e){const t=iU.indexOf(e);return iU[(t-1+iU.length)%iU.length]}function buildToolCallMap(e){const t=new Map,n=__name(e=>{for(const r of e){const{entry:e}=r;if("message"===e.type&&"assistant"===e.message.role)for(const n of e.message.content)"tool_use"===n.type&&t.set(n.id,{name:n.name,input:n.input});n(r.children)}},"visit");return n(e),t}function pathArgOf(e){const t=e.file_path??e.path;return"string"==typeof t?toRelativePath(t):"?"}function formatToolBracket(e){const{name:t,input:n}=e;if("read_file"===t){const e=pathArgOf(n),t=n.offset,r=n.limit;return"number"==typeof t&&"number"==typeof r?`[read: ${e}:${t}-${t+r}]`:`[read: ${e}]`}return"write_file"===t?`[write: ${pathArgOf(n)}]`:"edit_file"===t?`[edit: ${pathArgOf(n)}]`:"shell_command"===t?`[bash: ${truncateString2({text:"string"==typeof n.command?n.command:"",maxChars:50})}]`:"grep"===t?`[grep: /${"string"==typeof n.pattern?n.pattern:""}/ in ${"string"==typeof n.directory?toRelativePath(n.directory):"."}]`:"glob"===t?`[glob: ${"string"==typeof n.pattern?n.pattern:""}]`:"read_directory"===t?`[ls: ${pathArgOf(n)}]`:`[${t}: ${truncateString2({text:JSON.stringify(n),maxChars:40})}]`}function messageText5(e){return extractTextFromMessageContent({content:e.content})}function isToolResultOnlyUserMessage2(e){return"user"===e.role&&e.content.length>0&&e.content.every(e=>"tool_result"===e.type)}__name(nextFilterMode,"nextFilterMode"),__name(previousFilterMode,"previousFilterMode"),__name(buildToolCallMap,"buildToolCallMap"),__name(pathArgOf,"pathArgOf"),__name(formatToolBracket,"formatToolBracket"),__name(messageText5,"messageText"),__name(isToolResultOnlyUserMessage2,"isToolResultOnlyUserMessage");var lU=new Set(["label","custom","model_change","effort_change","session_info"]);function isContentlessAssistantMessage(e){return"message"===e.type&&"assistant"===e.message.role&&0===messageText5(e.message).trim().length}function passesFilter(e){const{entry:t,mode:n,isCurrentLeaf:r,hasLabel:o}=e;return"all"===n||("labeled-only"===n?o:"user-only"===n?"message"===t.type&&"user"===t.message.role&&!isToolResultOnlyUserMessage2(t.message)&&messageText5(t.message).trim().length>0:!lU.has(t.type)&&(!(isContentlessAssistantMessage(t)&&!r)&&("no-tools"!==n||"message"!==t.type||"user"!==t.message.role||!isToolResultOnlyUserMessage2(t.message))))}function buildVisibleNodes(e){const{nodes:t,mode:n,currentLeafId:r}=e,o=[];for(const e of t){const t=buildVisibleNodes({nodes:e.children,mode:n,currentLeafId:r});passesFilter({entry:e.entry,mode:n,isCurrentLeaf:e.entry.id===r,hasLabel:void 0!==e.label})?o.push({entry:e.entry,children:t,...void 0!==e.label?{label:e.label}:{},...void 0!==e.labelTimestamp?{labelTimestamp:e.labelTimestamp}:{}}):o.push(...t)}return o}function containsId(e,t){return e.entry.id===t||e.children.some(e=>containsId(e,t))}function reorderActiveFirst(e,t){for(const n of e)n.children=reorderActiveFirst(n.children,t);if(null===t)return e;const n=e.findIndex(e=>containsId(e,t));return n<=0?e:[e[n],...e.slice(0,n),...e.slice(n+1)]}function connectorGlyph(e){return e.folded?"⊞":e.foldable?"⊟":"─"}function buildRowPrefix(e){const{displayIndent:t,gutters:n,connectorVisible:r,isLast:o,folded:s,foldable:i}=e,a=r?t-1:-1,l=[];for(let e=0;e<3*t;e++){const t=Math.floor(e/3),r=e%3,c=n.find(e=>e.position===t);c?l.push(0===r&&c.show?"│":" "):t!==a?l.push(" "):0===r?l.push(o?"└":"├"):1===r?l.push(connectorGlyph({folded:s,foldable:i})):l.push(" ")}const c=s&&!r?"⊞ ":"";return l.join("")+c}function flattenVisibleTree(e){const{roots:t,activePathIds:n,foldedNodes:r}=e,o=[],s=new Map,i=t.length>1;function visit(e){const{node:t,parentId:a,indent:l,justBranched:c,isLast:d,gutters:u}=e,m=t.children.map(e=>e.entry.id);s.set(t.entry.id,m);const p=r.has(t.entry.id),g=t.children.length>0,h=e.showConnector&&!e.isVirtualRootChild,f=i?Math.max(0,l-1):l;if(o.push({id:t.entry.id,entry:t.entry,parentId:a,prefix:buildRowPrefix({displayIndent:f,gutters:u,connectorVisible:h,isLast:d,folded:p,foldable:g}),isActivePath:n.has(t.entry.id),isBranchChild:e.showConnector,hasVisibleChildren:g,...void 0!==t.label?{label:t.label}:{},...void 0!==t.labelTimestamp?{labelTimestamp:t.labelTimestamp}:{}}),p)return;const y=t.children.length>1,S=y||c&&l>0?l+1:l,w=h?[...u,{position:Math.max(0,f-1),show:!d}]:u;t.children.forEach((e,n)=>{visit({node:e,parentId:t.entry.id,indent:S,justBranched:y,showConnector:y,isLast:n===t.children.length-1,gutters:w,isVirtualRootChild:!1})})}return __name(visit,"visit"),t.forEach((e,n)=>{visit({node:e,parentId:null,indent:i?1:0,justBranched:i,showConnector:i,isLast:n===t.length-1,gutters:[],isVirtualRootChild:i})}),{rows:o,visibleChildrenIds:s}}function normalizeRowText(e){return truncateString2({text:e.replace(/[\n\t]+/g," ").trim(),maxChars:200})}function describeRow(e,t){if("message"===e.type){const{message:n}=e;if("user"===n.role){if(isToolResultOnlyUserMessage2(n)){const e=n.content.find(e=>"tool_result"===e.type),r=e?t.get(e.tool_use_id):void 0;return{text:r?formatToolBracket(r):"[tool result]",color:ER.DIM}}return{text:`user: ${normalizeRowText(messageText5(n))}`,color:ER.CYAN}}const r=messageText5(n).trim();return r?{text:`assistant: ${normalizeRowText(r)}`,color:ER.GREEN}:{text:"assistant: (no content)",color:ER.DIM}}return"compaction"===e.type?{text:`[compaction: ${Math.round(e.tokensBefore/1e3)}k tokens]`,color:ER.CYAN}:"branch_summary"===e.type?{text:`[branch summary]: ${normalizeRowText(e.summary)}`,color:ER.YELLOW}:"custom_message"===e.type?{text:`[${e.customType}]: ${normalizeRowText(extractTextFromMessageContent({content:e.content}))}`,color:ER.MAGENTA}:"custom"===e.type?{text:`[custom: ${e.customType}]`,color:ER.DIM}:"model_change"===e.type?{text:`[model: ${e.model}]`,color:ER.DIM}:"effort_change"===e.type?{text:`[effort: ${e.effort}]`,color:ER.DIM}:"label"===e.type?{text:`[label: ${e.label??"(cleared)"}]`,color:ER.DIM}:{text:e.name?`[title: ${e.name}]`:"[title: (empty)]",color:ER.DIM}}__name(isContentlessAssistantMessage,"isContentlessAssistantMessage"),__name(passesFilter,"passesFilter"),__name(buildVisibleNodes,"buildVisibleNodes"),__name(containsId,"containsId"),__name(reorderActiveFirst,"reorderActiveFirst"),__name(connectorGlyph,"connectorGlyph"),__name(buildRowPrefix,"buildRowPrefix"),__name(flattenVisibleTree,"flattenVisibleTree"),__name(normalizeRowText,"normalizeRowText"),__name(describeRow,"describeRow");var cU={compaction:"compaction",branch_summary:"branch summary",session_info:"title",model_change:"model",effort_change:"effort",custom:"custom",custom_message:"custom",label:"label"};function searchableText(e){const{entry:t,label:n,toolCallMap:r}=e,o=[t.type];n&&o.push(n);const s=cU[t.type];if(s&&o.push(s),"message"===t.type)if(o.push(t.message.role),isToolResultOnlyUserMessage2(t.message)){const e=t.message.content.find(e=>"tool_result"===e.type),n=e?r.get(e.tool_use_id):void 0;if(n){o.push(n.name);const e=n.input.command;"string"==typeof e&&o.push(e);const t=n.input.file_path??n.input.path;"string"==typeof t&&o.push(t)}}else o.push(messageText5(t.message));return"branch_summary"===t.type&&o.push(t.summary),"custom_message"===t.type&&o.push(extractTextFromMessageContent({content:t.content})),o.join(" ").toLowerCase()}function matchesSearch(e,t){const n=t.toLowerCase().split(/\s+/).filter(Boolean);return 0===n.length||n.every(t=>e.includes(t))}function formatLabelTimestamp(e,t){const n=new Date(e),r=__name(e=>String(e).padStart(2,"0"),"pad"),o=`${r(n.getHours())}:${r(n.getMinutes())}`;return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?o:n.getFullYear()===t.getFullYear()?`${n.getMonth()+1}/${n.getDate()} ${o}`:`${String(n.getFullYear()).slice(-2)}/${n.getMonth()+1}/${n.getDate()} ${o}`}function previousSegmentStart(e,t,n){let r=t.get(n),o=null;for(;r?.parentId;){const e=t.get(r.parentId);if(!e)break;if(e.isBranchChild)return e.id;o=e.id,r=e}return o}function nextSegmentStart(e,t,n){const r=t.get(n)?.[0];if(void 0===r)return null;let o=r;for(let n=0;n<1e4;n++){const n=e.get(o);if(!n||n.isBranchChild)return o;const r=t.get(o)?.[0];if(void 0===r)return o;o=r}return o}function resolveTargetLocally(e){const t=e.byId.get(e.entryId);return t?"message"===t.type&&"user"===t.message.role&&messageText5(t.message).trim().length>0||"custom_message"===t.type?{targetId:t.parentId}:{targetId:t.id}:{targetId:e.entryId}}function isOnPathLocally(e){if(null===e.ancestorId)return!0;if(null===e.targetId)return!1;let t=e.targetId;const n=new Set;for(;null!==t;){if(t===e.ancestorId)return!0;if(n.has(t))return!1;n.add(t);const r=e.byId.get(t);t=r?r.parentId:null}return!1}__name(searchableText,"searchableText"),__name(matchesSearch,"matchesSearch"),__name(formatLabelTimestamp,"formatLabelTimestamp"),__name(previousSegmentStart,"previousSegmentStart"),__name(nextSegmentStart,"nextSegmentStart"),__name(resolveTargetLocally,"resolveTargetLocally"),__name(isOnPathLocally,"isOnPathLocally");var dU=[{value:"none",label:"No summary"},{value:"summarize",label:"Summarize"},{value:"custom",label:"Summarize with custom prompt"}],uU=__name(({tree:e,currentLeafId:t,initialSelectedId:n,initialFilterMode:r,branchSummarySkipPrompt:o,onSelect:s,onAbortSummary:i,onCancel:a,onLabelChange:l})=>{const[c,d]=at(r),[u,m]=at(""),[p,g]=at(()=>new Set),h=__name(e=>{d(e),g(new Set)},"applyFilterMode"),f=__name(e=>{h(t=>t===e?"default":e)},"toggleFilterMode"),[y,S]=at(!1),[w,v]=at("browse"),[k,C]=at(""),[b,E]=at(""),[T,P]=at(0),[M,x]=at(null),[I,A]=at(0),[R,L]=at(0),[O,D]=at(n??t??void 0),$=useTerminalHeight(),N=dt(()=>{const t=new Map,n=__name(e=>{for(const r of e)t.set(r.entry.id,r.entry),n(r.children)},"visit");return n(e),t},[e]),_=dt(()=>buildToolCallMap(e),[e]),F=dt(()=>{const e=new Set;let n=t;for(;null!==n;){e.add(n);const t=N.get(n);n=t?t.parentId:null}return e},[N,t]),U=dt(()=>reorderActiveFirst(buildVisibleNodes({nodes:e,mode:c,currentLeafId:t}),t),[e,c,t]),{rows:j,visibleChildrenIds:B}=dt(()=>flattenVisibleTree({roots:U,activePathIds:F,foldedNodes:p}),[U,F,p]),W=dt(()=>new Map(j.map(e=>[e.id,e])),[j]),H=dt(()=>u?j.filter(e=>matchesSearch(searchableText({entry:e.entry,label:e.label,toolCallMap:_}),u)):j,[j,u,_]);ct(()=>{if(0===H.length)return void A(0);let e=O;for(;e;){const t=H.findIndex(t=>t.id===e);if(t>=0)return void A(t);e=N.get(e)?.parentId}A(H.length-1)},[H,c,u,N]);const G=H[I]?.id,V=lt(!1);ct(()=>{V.current?G&&D(G):V.current=!0},[G]);const z=$-1,K=Math.max(6,z-10);ct(()=>{L(e=>clampScrollOffset({cursor:I,total:H.length,maxVisible:K,currentOffset:e}))},[I,H.length,K]);const q=H[I],Y=__name(e=>{D(e.entryId),e.summarize?(v("summarizing"),s(e).then(e=>{e.aborted&&v("browse")})):s(e)},"commitSelection"),J=__name(()=>{if(!q)return;D(q.id);const{targetId:e}=resolveTargetLocally({byId:N,entryId:q.id});isOnPathLocally({byId:N,ancestorId:t,targetId:e})||o?Y({entryId:q.id,summarize:!1}):(x(q.id),P(0),v("confirm-summary"))},"handleEnterInBrowse");nt((e,t)=>{if("summarizing"===w)return void(t.escape&&i());if("label"===w)return void(t.escape&&v("browse"));if("custom-prompt"===w)return void(t.escape&&v("confirm-summary"));if("confirm-summary"===w){if(t.escape)return void v("browse");if(t.upArrow)return void P(e=>Math.max(0,e-1));if(t.downArrow)return void P(e=>Math.min(dU.length-1,e+1));if(t.return&&M){const e=dU[T]?.value;"none"===e?(Y({entryId:M,summarize:!1}),v("browse")):"summarize"===e?Y({entryId:M,summarize:!0}):(E(""),v("custom-prompt"))}return}const n=getKeybindings();if(t.escape)return u?void m(""):void a();if(t.upArrow)A(e=>0===H.length?0:(e-1+H.length)%H.length);else if(t.downArrow)A(e=>0===H.length?0:(e+1)%H.length);else if(!t.leftArrow||t.ctrl||t.meta)if(!t.rightArrow||t.ctrl||t.meta){if((keybindingMatches(n,"app.tree.foldOrPrevBranch",e,t)||isWordLeftSequence(e)||(t.ctrl||t.meta)&&t.leftArrow)&&q){if(q.hasVisibleChildren&&!p.has(q.id))return void g(e=>new Set(e).add(q.id));const e=previousSegmentStart(0,W,q.id);if(e&&D(e),e){const t=H.findIndex(t=>t.id===e);t>=0&&A(t)}return}if((keybindingMatches(n,"app.tree.unfoldOrNextBranch",e,t)||isWordRightSequence(e)||(t.ctrl||t.meta)&&t.rightArrow)&&q){if(p.has(q.id))return void g(e=>{const t=new Set(e);return t.delete(q.id),t});const e=nextSegmentStart(W,B,q.id);if(e){D(e);const t=H.findIndex(t=>t.id===e);t>=0&&A(t)}return}if(t.return)J();else if(t.ctrl&&"O"===e||keybindingMatches(n,"app.tree.filter.cycleBack",e,t))h(e=>previousFilterMode(e));else if(keybindingMatches(n,"app.tree.filter.cycle",e,t))h(e=>nextFilterMode(e));else if(keybindingMatches(n,"app.tree.filter.default",e,t))h("default");else if(keybindingMatches(n,"app.tree.filter.noTools",e,t))f("no-tools");else if(keybindingMatches(n,"app.tree.filter.userOnly",e,t))f("user-only");else if(keybindingMatches(n,"app.tree.filter.labeledOnly",e,t))f("labeled-only");else if(keybindingMatches(n,"app.tree.filter.all",e,t))f("all");else{if("L"===e||keybindingMatches(n,"app.tree.label",e,t)){if(!q)return;return C(q.label??""),void v("label")}"T"===e||keybindingMatches(n,"app.tree.labelTime",e,t)?S(e=>!e):t.backspace||t.delete?u&&m(e=>e.slice(0,-1)):!t.ctrl&&!t.meta&&!t.tab&&e&&1===e.length&&e>=" "&&m(t=>t+e)}}else A(e=>Math.min(H.length-1,e+K));else A(e=>Math.max(0,e-K))});const Q=__name(e=>{if(q){const t=e.trim();l({entryId:q.id,label:t.length>0?t:void 0})}v("browse")},"submitLabel"),X=__name(e=>{if(M){const t=e.trim();Y({entryId:M,summarize:!0,...t.length>0?{customInstructions:t}:{}})}},"submitCustomPrompt");if("summarizing"===w)return st.createElement(bO,{title:"/tree",gapAfterHeader:!1},st.createElement(Xe,{color:ER.CYAN},"Summarizing abandoned branch… (Esc to cancel)"));if("confirm-summary"===w)return st.createElement(bO,{title:"/tree",subtitle:"You're leaving work behind on this branch. Summarize it before jumping?",hint:"enter confirm · esc back"},st.createElement(Qe,{flexDirection:"column"},dU.map((e,t)=>st.createElement(Xe,{key:e.value,color:t===T?TR:ER.WHITE,bold:t===T},t===T?`${fL} `:" ",e.label))));if("custom-prompt"===w)return st.createElement(bO,{title:"/tree",subtitle:"Focus instructions for the summary:",gapAfterHeader:!1,hint:"enter confirm · esc back"},st.createElement(TextInput,{value:b,focus:!0,prefix:`${fL} `,prefixColor:"cyan",onChange:E,onSubmit:X}));if("label"===w&&q)return st.createElement(bO,{title:"/tree",subtitle:"Label:",gapAfterHeader:!1,hint:"enter save (empty clears) · esc cancel"},st.createElement(TextInput,{value:k,focus:!0,prefix:`${fL} `,prefixColor:"cyan",onChange:C,onSubmit:Q}));const Z=H.slice(R,R+K),ee=new Date,te=aU[c];return st.createElement(Qe,{flexDirection:"column",paddingLeft:1,width:"100%"},st.createElement(Xe,{color:TR,bold:!0},"/tree"),st.createElement(Qe,{marginBottom:1,width:"100%"},st.createElement(pL,{query:u,resultCount:u?H.length:void 0,placeholder:"Type to search…"})),0===H.length?st.createElement(Qe,{marginBottom:1},st.createElement(D$,{message:"No entries found"})):st.createElement(Qe,{flexDirection:"column"},Z.map((e,t)=>{const n=R+t===I,{text:r,color:o}=describeRow(e.entry,_);return st.createElement(Xe,{key:e.id,backgroundColor:n?KR:void 0,bold:n,wrap:"truncate-end"},n?`${fL} `:" ",st.createElement(Xe,{color:zR},e.prefix),e.isActivePath?st.createElement(Xe,{color:TR},"• "):null,void 0!==e.label?st.createElement(Xe,{color:ER.YELLOW},"[",e.label,"]"," "):null,y&&e.labelTimestamp?st.createElement(Xe,{color:ER.DIM},formatLabelTimestamp(e.labelTimestamp,ee)," "):null,st.createElement(Xe,{color:o},r))})),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"(",0===H.length?0:I+1,"/",H.length,")",te?` ${te}`:"",y?" [+label time]":"")),st.createElement(Qe,{flexDirection:"column"},st.createElement(pO,null,"↑/↓ move · ←/→ page · tab / alt+←/→ branch · shift+L label · shift+T label time"),st.createElement(pO,null,"filters ctrl+d/t/u/l/a · cycle ctrl+o · type to search · rebind via ~/.commandcode/keybindings.json")))},"TreeSelector");Gt(),SR();var mU=[{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."}],pU=['/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"'],gU=__name(({onCancel:e})=>(nt((t,n)=>{n.escape&&e()}),st.createElement(Qe,{flexDirection:"column",paddingLeft:2,paddingRight:2},st.createElement(Qe,{marginBottom:1,flexDirection:"column"},st.createElement(Xe,{bold:!0,color:TR},"Use"),st.createElement(Qe,{paddingLeft:2,flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},'/design <mode> "target or request"'),st.createElement(Xe,{color:ER.DIM},'/design "freeform request" also works. The closest mode is inferred.'))),st.createElement(Qe,{marginBottom:1,flexDirection:"column"},st.createElement(Xe,{bold:!0,color:TR},"Modes"),st.createElement(Qe,{paddingLeft:2,flexDirection:"column"},py.map(e=>st.createElement(Qe,{key:e.name,columnGap:2},st.createElement(Qe,{width:18,flexShrink:0},st.createElement(Xe,{color:ER.CYAN},"/design ",e.name)),st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},e.description)))))),st.createElement(Qe,{marginBottom:1,marginTop:1,flexDirection:"column"},st.createElement(Xe,{bold:!0,color:TR},"Working rules"),st.createElement(Qe,{paddingLeft:2,flexDirection:"column"},mU.map(e=>st.createElement(Qe,{key:e.label,columnGap:2},st.createElement(Qe,{width:16,flexShrink:0},st.createElement(Xe,{color:ER.CYAN},e.label)),st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},e.desc)))))),st.createElement(Qe,{marginBottom:1,marginTop:1,flexDirection:"column"},st.createElement(Xe,{bold:!0,color:TR},"Quick examples:"),st.createElement(Qe,{paddingLeft:2,flexDirection:"column"},pU.map(e=>st.createElement(Xe,{key:e,color:ER.DIM},e)))),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Press Esc to close. Type /design help anytime to return.")))),"DesignGuide");Gt(),SR(),Gt(),Gt();var hU=__name(({error:e,traceId:t})=>st.createElement(Qe,{padding:1},st.createElement(O$,{title:"Error initializing onboarding:"},e,t&&st.createElement(Xe,{color:ER.DIM},"\n\n","Trace ID: ",t),"\n\n","Continuing without onboarding...")),"OnboardingError");Gt(),Gt();var fU=__name(()=>st.createElement(Xe,null,"Skip"),"SkipOptionText"),yU=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[o,s]=at(1);return nt((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())}),st.createElement(Qe,{flexDirection:"column",borderStyle:"single",borderColor:PR.TEXT,paddingX:1,paddingY:0},st.createElement(Xe,{color:PR.TEXT,bold:!0},"Build Your Coding Taste"),st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Xe,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),st.createElement(Qe,{marginTop:1},st.createElement(Xe,null,"Analyze"," ",1===e?"that session":"those sessions"," ","to build your coding taste package?"))),st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,{color:1===o?PR.TEXT:ER.GRAY},1===o?gt.pointer:" "," 1. Yes, learn (recommended)")),st.createElement(Qe,null,st.createElement(Xe,{color:2===o?PR.TEXT:ER.GRAY},2===o?gt.pointer:" "," 2."," ",st.createElement(fU,null)))),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"↑↓ · "),st.createElement(Xe,{color:WR.CODE},"enter"),st.createElement(Xe,{color:ER.DIM}," ok · "),st.createElement(Xe,{color:WR.CODE},"esc"),st.createElement(Xe,{color:ER.DIM}," skip · "),st.createElement(Xe,{color:WR.CODE},"n"),st.createElement(Xe,{color:ER.DIM}," never")))},"ImportChoice"),SU=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?st.createElement(yU,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?st.createElement(tN,{onComplete:r,onCancel:i,onError:o,onErrorDismiss:s}):null,"OnboardingStepRenderer"),wU=__name(({onComplete:e,autoLearn:t=!1})=>{ct(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,traceId:o,isLoading:s}=B$({autoLearn:t,onShouldSkip:e}),{step:i,setStep:a}=W$({conditions:n,autoLearn:t}),{handleImportStart:l,handleImportComplete:c,handleImportError:d,handleErrorDismiss:u,handleSkip:m}=H$({onStepChange:__name(e=>{a(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${i}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),s?null:r?st.createElement(hU,{error:r,traceId:o}):"done"===i||"asking"!==i&&"learning"!==i?null:st.createElement(SU,{step:i,conditions:n,onImportStart:l,onImportComplete:c,onImportError:d,onErrorDismiss:u,onSkip:m})},"TasteOnboarding");Gt(),SR();var vU=[{label:"Auto theme",value:"auto",description:"Automatically detect your terminal background and use light or dark to match."},{label:"Dark theme",value:"dark",description:"Use purple accent colors on dark backgrounds."},{label:"Light theme",value:"light",description:"Use higher-contrast colors for white terminal backgrounds."}];function labelFor(e,t){return"auto"===e.value?`${e.label} (${t})`:e.label}__name(labelFor,"labelFor");var kU=__name(({onSelect:e,onCancel:t})=>{const[n]=at(()=>getCliTheme()),[r]=at(()=>resolveCliTheme("auto")),o=dt(()=>vU.map(e=>({...e,label:labelFor(e,r)})),[r]),s=__name(t=>{const n=o.find(e=>e.value===t.value)?.value;n&&e(n)},"handleSelect");nt((e,n)=>{n.escape&&t()});const i=o.findIndex(e=>e.value===n),a=o.find(e=>e.value===n)?.label??`${n} theme`;return st.createElement(bO,{title:"Select a theme",subtitle:`Choose the color palette for this terminal · currently ${a}`,footer:st.createElement(Xe,{italic:!0,color:ER.DIM},"Press ",st.createElement(Xe,{bold:!0},"Esc")," to cancel")},st.createElement(SelectInput,{items:o,onSelect:s,initialIndex:i>=0?i:0,indicatorComponent:jN,itemComponent:({isSelected:e,label:t})=>{const r=o.findIndex(e=>e.label===t),s=o[r],i=s?.value===n,a=r===o.length-1;return st.createElement(Qe,{flexDirection:"column",marginBottom:a?0:1},st.createElement(Qe,null,st.createElement(BN,{isSelected:e,isActive:i,idleColor:ER.DIM},` ${r+1}. ${s?.label??t}`),i&&st.createElement(HN,null)),st.createElement(GN,null,s?.description??""))}}))},"ThemeSelector"),CU=it(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:o,setStaticKey:s,transcriptMode:i,tasteOnboardingEntryId:a,autoLearnTaste:l,showTasteSkipBanner:c,showZdrNotice:d,modelNotice:u,retryAttempt:m,input:p,setInput:g,fileSearchQuery:h,setFileSearchQuery:f,showFileList:y,setShowFileList:S,showProviderSelector:w,showModelSelector:v,showEffortSelector:k,showMemorySelector:C,showMcpManager:b,showAgentsConfig:E,showRewindSelector:T,showTreeSelector:P,treeFilterMode:M,treeBranchSummarySkipPrompt:x,showLoginOverlay:I,showUsageOverlay:A,showAddDirModal:R,showCompactModeSelector:L,showThemeSelector:O,authComponentInfo:D,status:$,currentProvider:N,currentModel:_,showProviderNotification:F,shareInfo:U,showShareNotification:j,unshareNotificationMessage:B,updateStatus:W,updateFailedInfo:H,creditWarning:G,permissionMode:V,hintMessage:z,pendingExitKey:K,interactionTokens:q,contextUsage:Y,tasteLearningOn:J,historyManagerRef:Q,executionState:X,sessionId:Z,onSubmit:ee,onCommand:te,onToggleAutoAccept:ne,onResetPendingExitKey:re,onDoubleEscapeEmpty:oe,onTasteOnboardingComplete:se,permissionPanel:ie,questionPanel:ae,designSuggestionPanel:le,onRewindSelect:ce,onRewindCancel:de,onTreeSelect:ue,onTreeCancel:me,onTreeLabel:pe,onTreeAbortSummary:ge,onLoginComplete:he,onLoginCancel:fe,setShowProviderSelector:ye,setShowModelSelector:Se,setShowEffortSelector:we,setShowMemorySelector:ve,setShowMcpManager:ke,setShowAgentsConfig:Ce,setShowAddDirModal:be,setShowUsageOverlay:Ee,handleProviderSelect:Te,handleProviderCancel:Pe,handleModelSelect:Me,handleModelCancel:xe,handleCompactModeSelect:Ie,handleCompactModeCancel:Ae,handleThemeSelect:Re,handleThemeCancel:Le,handleAuthSuccess:Oe,handleAuthCancel:De,showDesignGuide:$e,setShowDesignGuide:Ne}){const _e=dt(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Fe=ut(()=>Ne(!1),[Ne]),Ue=useTerminalWidth(),[je,Be]=at(!1),[We,He]=at(!1),Ge=lt(null);Ge.current=r?Ge.current??Date.now():null;const Ve=dt(()=>"off"===i?_e:projectTranscriptWindow({feed:_e,mode:i}),[_e,i]),ze=dt(()=>"off"===i?0:Math.max(0,_e.length-Ve.length),[_e.length,Ve.length,i]),Ke=dt(()=>0===ze?Ve:Ve.filter(e=>"user"!==e.role),[Ve,ze]),qe=ut(()=>Ce(!1),[Ce]),Ye=ut(()=>ve(!1),[ve]),Je=ut(()=>ke(!1),[ke]),Ze=ut(()=>be(!1),[be]),et=ut(()=>Se(!0),[Se]),tt=ut(()=>we(!1),[we]),nt=ut(()=>{hardResetForResize(),s(e=>e+1)},[s]),rt=!("off"!==i||ie||ae||le||w||v||k||D||C||b||E||T||P||I||A||R||L||O||$e||a),ot=k$(Z),it=ot?ot.getEffort():null;return st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(DF,{staticKey:o,feed:Ke,showHeader:!0,expandedToolOutput:"off"!==i,currentModel:_,currentEffort:it,currentProvider:N,hiddenCount:ze}),a&&st.createElement(wU,{onComplete:se,autoLearn:l}),c&&st.createElement(TasteSkipMessage,null),d&&st.createElement(ZdrPausedMessage,null),u&&st.createElement(ModelNoticeMessage,{text:u}),t.map(e=>e.metadata?.isAgent?st.createElement(NF,{key:e.id,entry:e}):st.createElement(Qe,{key:e.id,marginBottom:1,width:"90%"},st.createElement(FeedEntryView,{entry:e,expandedToolOutput:"off"!==i}))),st.createElement(RetryMessage,{attempt:m}),"off"===i&&!a&&!We&&st.createElement(TodoPanel,{active:r}),le,ae,ie,"off"!==i&&st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},"─".repeat(Ue))),st.createElement(Qe,{paddingRight:1},st.createElement(Xe,{backgroundColor:AR.BG,color:AR.FG,bold:!0},`${wL}DETAILED TRANSCRIPT${wL}`),st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{bold:!0},"ctrl+o"),st.createElement(Xe,{color:ER.DIM}," to toggle"),st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{bold:!0},NE?"ctrl+y":"ctrl+e"),st.createElement(Xe,{color:ER.DIM}," ","to"," ","limited"===i?"show all":"collapse"),st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{bold:!0},"esc"),st.createElement(Xe,{color:ER.DIM}," to exit"))),rt&&st.createElement(st.Fragment,null,st.createElement(BackgroundTasksPanel,{onExpandedChange:Be}),st.createElement(TodosManagerPanel,{sessionId:Z,onExpandedChange:He}),st.createElement(vF,{queuedMessages:n,sessionId:Z,isProcessing:r,processingStartedAt:Ge.current,executionState:X,status:$,input:p,setInput:g,onSubmit:ee,showFileList:y,setShowFileList:S,fileSearchQuery:h,setFileSearchQuery:f,onCommand:te,outputTokens:q,contextUsage:Y,tasteLearningOn:J,shareInfo:U,showShareNotification:j,unshareNotificationMessage:B,updateStatus:W,updateFailedInfo:H,creditWarning:G,currentProvider:N,currentModel:_,showProviderInfo:F,permissionMode:V,onToggleAutoAccept:ne,hintMessage:z,historyManager:Q.current,pendingExitKey:K,onResetPendingExitKey:re,onDoubleEscapeEmpty:oe,retryAttempt:m,onAltP:et,renderKey:o,inputActive:!je&&!We,inactiveHint:We?"Todos focused · ↑/↓ to select · c to complete · x to remove · a all done · Esc to go back to feed":void 0})),w&&st.createElement(Qe,{marginY:1},st.createElement(rU,{onSelect:Te,onCancel:Pe,sessionId:Z})),v&&st.createElement(Qe,{marginY:1},st.createElement(M_,{onSelect:Me,onCancel:xe,currentModel:_,currentProvider:N,refreshBanner:nt,sessionId:Z})),k&&st.createElement(Qe,{marginY:1},st.createElement(KF,{currentModel:_,sessionId:Z,onClose:tt,refreshBanner:nt})),$e&&st.createElement(Qe,{marginY:1},st.createElement(gU,{onCancel:Fe})),L&&st.createElement(Qe,{marginY:1},st.createElement(X_,{onSelect:Ie,onCancel:Ae})),O&&st.createElement(Qe,{marginY:1},st.createElement(kU,{onSelect:Re,onCancel:Le})),E&&st.createElement(Qe,{marginY:1},st.createElement(G_,{onCancel:qe})),C&&st.createElement(Qe,{marginY:1},st.createElement(EF,{onClose:Ye})),b&&st.createElement(Qe,{marginY:1},st.createElement(bF,{onClose:Je,mcp:k$(Z)?.mcp})),T&&k$(Z)&&st.createElement(Qe,{marginY:1},st.createElement(sU,{checkpoints:[...k$(Z).listCheckpoints()],onSelect:ce,onCancel:de})),P&&k$(Z)&&st.createElement(Qe,{marginY:1},st.createElement(uU,{tree:k$(Z).getSessionTree(),currentLeafId:k$(Z).getSessionLeafId(),initialFilterMode:M,branchSummarySkipPrompt:x,onSelect:ue,onAbortSummary:ge,onCancel:me,onLabelChange:pe})),D&&st.createElement(Qe,{marginY:1},st.createElement(D.Component,{onSuccess:Oe,onCancel:De})),I&&st.createElement(Qe,{marginY:1},st.createElement(kF,{onComplete:he,onCancel:fe})),R&&st.createElement(Qe,{marginY:1},st.createElement(k_,{onClose:Ze})))},"MainView"));function useFeatureModelCatalog(){const[e,t]=at(()=>getCachedBillingContext());ct(()=>{if(e)return;let n=!0;return getBillingContext().then(e=>{n&&t(e)}),()=>{n=!1}},[e]);const n=useCustomModelsReady(),r=dt(()=>buildCatalogModelPickerGroups(),[n]),o=dt(()=>filterModelPickerGroupsByPlan({groups:r,billing:e}),[r,e]),s=dt(()=>flattenModelPickerGroups(o).map(e=>({id:e.model.id,label:getModelDisplayName(e.model.id)})),[o]);return{groups:o,catalog:s,resolved:null!==e}}Gt(),Gt(),SR(),Gt(),SR(),__name(useFeatureModelCatalog,"useFeatureModelCatalog"),Gt(),SR();var bU=["Listing only models with a zero-data-retention upstream."];function wrappedRowCount(e){const t=Math.max(1,e.width),n=e.text.split(/\s+/).filter(Boolean);if(0===n.length)return 1;let r=1,o=0;for(const e of n){if(e.length>t){o>0&&(r+=1),r+=Math.ceil(e.length/t)-1,o=e.length%t||t;continue}const n=0===o?e.length:e.length+1;o+n<=t?o+=n:(r+=1,o=e.length)}return r}function zdrBannerRowCount(e){return bU.reduce((t,n)=>t+wrappedRowCount({text:n,width:e}),0)+1}function narrowGroups(e){return e.groups.map(t=>({...t,models:t.models.filter(e.accepts)})).filter(e=>e.models.length>0)}__name(wrappedRowCount,"wrappedRowCount"),__name(zdrBannerRowCount,"zdrBannerRowCount"),__name(narrowGroups,"narrowGroups");var EU=__name(({featureLabel:e,defaultLabel:t,currentModelId:n,modelFilter:r,onPick:o,onBack:s})=>{const[i,a]=at(""),{groups:l,resolved:c}=useFeatureModelCatalog(),d=isCmdZdrEnabled(),u=dt(()=>r||d?narrowGroups({groups:l,accepts:__name(e=>!(r&&!r(e)||d&&!modelSupportsZdr(e.id)),"accepts")}):l,[l,r,d]),m=dt(()=>filterModelPickerGroups(u,i),[u,i]),p=dt(()=>getModelLabelColumnWidth(u.flatMap(e=>e.models),{showDefaultBadge:!1}),[u]),g=dt(()=>[{kind:"reset"},...flattenModelPickerGroups(m).map(e=>({kind:"model",providerId:e.providerId,model:e.model}))],[m]),h=dt(()=>{if(!n)return 0;const e=g.findIndex(e=>"model"===e.kind&&e.model.id===n);return e>=0?e:0},[g,n]),{cursor:f}=useListNavigation({items:g,initialIndex:h,searchCursorIndex:1,searchQuery:i,onSearchChange:a,onSelect:__name(e=>{c&&o("reset"===e.kind?void 0:e.model.id)},"onSelect"),onCancel:s}),[y,S]=at(0),w=useTerminalHeight(),v=useTerminalWidth(),k=w-1,C=d?zdrBannerRowCount(v):0,b=Math.max(4,k-13-C-2*m.length);ct(()=>{S(e=>clampScrollOffset({cursor:f,total:g.length,maxVisible:b,currentOffset:e}))},[f,g.length,b]);const E=y,T=y+b,P=0===E,M=windowModelGroups({groups:m,firstSectionBase:1,windowStart:E,windowEnd:T}),x=g.length>b;return st.createElement(bO,{title:`${e} › select model`,subtitle:st.createElement(st.Fragment,null,"Pick a model for this task, or reset it to the default."," ",createOSC8Link("https://commandcode.ai/docs/troubleshooting/faqs#why-do-i-see-small-background-requests","Why background requests?",!1)),footer:st.createElement(Xe,{italic:!0,color:ER.DIM},"type to search · ↑/↓ navigate · enter select",i?" · esc to clear":" · esc back")},d&&st.createElement(Qe,{marginBottom:1,flexDirection:"column"},bU.map(e=>st.createElement(Xe,{key:e,color:ER.YELLOW},e))),st.createElement(Qe,{marginBottom:2,flexDirection:"column",width:"100%"},st.createElement(pL,{query:i,resultCount:i?g.length-1:void 0,placeholder:"Type to search models..."})),c?st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"column"},P&&st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{bold:!0,dimColor:!0},"Default"),st.createElement(Qe,null,st.createElement(Xe,{backgroundColor:0===f?KR:void 0,color:n?ER.WHITE:ER.GREEN},t," "),!n&&st.createElement(Xe,{color:ER.GREEN},gt.tick))),M.map(({group:e,groupWindow:t},r)=>st.createElement(Qe,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:0!==r||P?1:0},st.createElement(Xe,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>st.createElement(E_,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===f,isCurrent:r.id===n,showProviderLabel:!1,showDefaultBadge:!1,labelColumnWidth:p}))))),x&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",E+1,"–",Math.min(T,g.length)," of"," ",g.length,E>0?" · ↑ more":"",T<g.length?" · ↓ more":""))):st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},"Loading available models…")))},"FeatureModelPicker"),TU="Taste learning is off on BYOK models. Switch to a Command Code model to change it.";function isTasteRow(e){return"taste-learning"===e.id||e.id===wp}function clampDescriptionLines(e){const t=Math.max(e.width,10),{maxLines:n}=e,r=e.text.trim().split(/\s+/).filter(Boolean);if(0===r.length||n<=0)return[];const o=[];let s="",i=0,a=!1;for(;i<r.length;){let e=r[i];e.length>t&&(r.splice(i,1,e.slice(0,t),e.slice(t)),e=r[i]);const l=s?`${s} ${e}`:e;if(l.length<=t)s=l,i+=1;else if(o.push(s),s="",o.length===n){a=!0;break}}if(!a)return s&&o.push(s),o;const l=o[n-1];return o[n-1]=l.length>=t?`${l.slice(0,t-1)}…`:`${l}…`,o}function formatSettingValue(e){if(void 0!==e.displayValue)return e.displayValue;if("boolean"===e.kind)return!0===e.currentValue?"Enabled":"Disabled";const t=(e.options??[]).find(t=>t.value===e.currentValue);return t?t.label:String(e.currentValue)}function startsNewGroup(e,t){return 0===t||e[t-1]?.group!==e[t]?.group}__name(isTasteRow,"isTasteRow"),__name(clampDescriptionLines,"clampDescriptionLines"),__name(formatSettingValue,"formatSettingValue"),__name(startsNewGroup,"startsNewGroup");var PU=__name(({onClose:e,staticKey:t,loadTasteStatus:n})=>{const[r,o]=at([]),s=isByok({model:getConfiguredModel()}),[i,a]=at(!0),[l,c]=at(""),[d,u]=at(null),{catalog:m}=useFeatureModelCatalog(),p=ut(()=>listConfigSettings({modelCatalog:m,isByok:isByok}).then(e=>o(e)),[m]);ct(()=>{let e=!0;return listConfigSettings({modelCatalog:m,isByok:isByok}).then(t=>{e&&o(t)}).finally(()=>{e&&a(!1)}),()=>{e=!1}},[m]);const g=dt(()=>filterConfigSettings({settings:r,query:l}),[r,l]),h=dt(()=>r.reduce((e,t)=>Math.max(e,t.label.length),0)+2,[r]),f=__name((e,t)=>{"theme"!==e.id||"string"!=typeof t?"taste-learning"!==e.id&&e.id!==wp||n():applyTuiTheme(resolveCliTheme(t))},"applyLiveSideEffect"),y=__name(async e=>{if(e.featureModelKey)return void u(e);const t=nextSettingValue(e),n=r;o(n=>n.map(n=>n.id===e.id?{...n,currentValue:t}:n));try{await updateConfigSetting({id:e.id,value:t}),f(e,t)}catch{o(n)}},"selectSetting"),S=__name(async(e,t)=>{try{await updateConfigSetting({id:e.id,value:t??Pp}),await p()}catch{}u(null)},"pickFeatureModel"),{cursor:w,error:v,setError:k}=useListNavigation({items:[...g],onSelect:__name(e=>{y(e)},"onSelect"),onReset:__name(e=>{C(e)},"onReset"),onCancel:e,searchQuery:l,onSearchChange:c,isActive:!i&&null===d,validate:__name(e=>s&&isTasteRow(e)?TU:e.locked?`${e.label} is locked by settings.local.json — edit that file to change it.`:null,"validate")}),C=__name(async e=>{if(s&&isTasteRow(e))return void k(TU);if(e.locked)return void k(`${e.label} is locked by settings.local.json — edit that file to change it.`);if(e.currentValue===e.defaultValue)return void k(`${e.label} is already at its default.`);if(e.featureModelKey){try{await updateConfigSetting({id:e.id,value:e.defaultValue}),await p()}catch{}return}const t=r;o(t=>t.map(t=>t.id===e.id?{...t,currentValue:e.defaultValue}:t));try{await updateConfigSetting({id:e.id,value:e.defaultValue}),f(e,e.defaultValue)}catch{o(t)}},"resetSetting"),b=useTerminalWidth(),E=g[w],T=dt(()=>E?clampDescriptionLines({text:E.description,width:Math.max(20,b-2),maxLines:2}):[],[E,b]);if(d?.featureModelKey){const e=ap.find(e=>e.key===d.featureModelKey),t="string"==typeof d.currentValue&&d.currentValue!==Pp?d.currentValue:void 0;return st.createElement(EU,{featureLabel:d.label,defaultLabel:e?getFeatureDefaultLabel({meta:e,getModelDisplayName:getModelDisplayName,zdrEnabled:isCmdZdrEnabled()}):"",currentModelId:t,modelFilter:"vision"===d.featureModelKey?e=>modelSupportsVision(e.id):void 0,onBack:()=>u(null),onPick:e=>{S(d,e)}})}return i?st.createElement(bO,{key:t,title:"Settings",gapAfterHeader:!1},st.createElement(A$,{label:"Loading settings"})):st.createElement(bO,{title:"Settings",footer:st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(Qe,{flexDirection:"column",height:2,width:"100%"},T.map((e,t)=>st.createElement(Xe,{key:t,color:ER.DIM,wrap:"truncate-end"},e))),st.createElement(hO,{marginTop:0,hints:["type to filter","↑↓ navigate","enter to change","tab to reset",l?"esc to clear":"esc to close"]}))},st.createElement(Qe,{marginBottom:1,flexDirection:"column",width:"100%"},st.createElement(pL,{query:l,resultCount:l?g.length:void 0,placeholder:"Search settings..."})),0===g.length?st.createElement(Qe,{marginY:1},st.createElement(Xe,{color:ER.GRAY},'No settings match "',l,'"')):st.createElement(Qe,{flexDirection:"column"},g.map((e,t)=>{const n=t===w?KR:void 0,r=!l&&startsNewGroup(g,t);return st.createElement(st.Fragment,{key:e.id},r&&st.createElement(Qe,{marginTop:0===t?0:1},st.createElement(Xe,{color:ER.DIM,bold:!0},e.group)),st.createElement(Qe,null,st.createElement(Xe,{color:e.locked||s&&isTasteRow(e)?ER.DIM:ER.WHITE,backgroundColor:n},e.label.padEnd(h)),st.createElement(Xe,{color:e.locked||s&&isTasteRow(e)?ER.DIM:ER.GREEN,backgroundColor:n},formatSettingValue(e)),(e.locked||s&&isTasteRow(e))&&st.createElement(Xe,{color:ER.DIM,backgroundColor:n},s&&isTasteRow(e)?" (unavailable on BYOK)":" (locked by settings.local.json)")))})),v&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.GRAY},v)))},"SettingsConfig");function SettingsConfigView({staticKey:e,onClose:t,loadTasteStatus:n}){return st.useEffect(()=>{hardResetForResize()},[]),st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(PU,{onClose:t,staticKey:e,loadTasteStatus:n})))}function categoryColor(e){return isFatalWarningCategory(e)?ER.RED:ER.YELLOW}__name(SettingsConfigView,"SettingsConfigView"),Gt(),Gt(),SR(),Gt(),Gt(),SR(),__name(categoryColor,"categoryColor");var MU=formatSkillWarningsAsMarkdown;async function copyAllWarnings(e,t){try{const{writeClipboardText:n}=await Promise.resolve().then(()=>(SR(),yR));if(!await n(MU(e)))throw new Error("clipboard unavailable");const r=e.length;t({text:`Copied ${r} issue${1===r?"":"s"} to clipboard`,color:ER.GREEN})}catch{t({text:"Clipboard write failed",color:ER.YELLOW})}}__name(copyAllWarnings,"copyAllWarnings");var xU=__name(({warnings:e,onClose:t,isActive:n=!0})=>{const r=groupWarnings(e),o=e.length>0,[s,i]=at(null),a=lt(null),l=lt(!0);ct(()=>()=>{l.current=!1,a.current&&(clearTimeout(a.current),a.current=null)},[]);const c=__name(e=>{l.current&&(a.current&&clearTimeout(a.current),i(e),a.current=setTimeout(()=>{l.current&&(i(null),a.current=null)},3e3))},"showStatus");return nt((n,r)=>r.escape||" "===n&&o?(RL(),void t()):void("c"===n&&o&&copyAllWarnings(e,c)),{isActive:n}),st.createElement(Qe,{flexDirection:"column",paddingX:0,width:"100%"},st.createElement(Qe,null,st.createElement(Xe,{color:TR,bold:!0},"Skills"," "),st.createElement(Xe,{color:ER.DIM},"› "),st.createElement(Xe,{color:TR,bold:!0},"Skipped"," "),st.createElement(Xe,{color:ER.WHITE},e.length)),o&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},"Press c to copy all issues")),o?st.createElement(Qe,{flexDirection:"column"},r.map(e=>st.createElement(Qe,{key:e.category,flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,{color:categoryColor(e.category)},e.category)),e.items.map(e=>st.createElement(Qe,{key:e.path,flexDirection:"column",marginBottom:1},st.createElement(Qe,{paddingLeft:2},st.createElement(cL,{url:g(e.path).href,text:skillIdentifier(e.path),color:ER.WHITE})),st.createElement(Qe,{paddingLeft:4},st.createElement(Xe,{color:ER.WHITE},e.reason))))))):st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"No issues — every skill loaded.")),s&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:s.color},s.text)),st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},o?"c copy all issues · esc back to skills":"esc back to skills")))},"SkillsConfigIssues"),IU=[],AU=__name(({warnings:e=IU,onClose:t})=>{const[n,r]=at("list");return nt((o,s)=>{"list"===n&&(s.escape&&t?t():" "===o&&!s.ctrl&&!s.meta&&e.length>0&&r("issues"))},{isActive:"list"===n}),"issues"===n?st.createElement(xU,{warnings:e,onClose:()=>r("list"),isActive:!0}):st.createElement(Qe,{flexDirection:"column",paddingX:0,width:"100%"},st.createElement(Qe,null,st.createElement(Xe,{color:TR,bold:!0},"Skills"),e.length>0&&st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:ER.YELLOW},e.length," skipped"))),st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},"No skills found")),st.createElement(Xe,{color:ER.DIM},"Create skills in:"),st.createElement(Xe,{color:ER.DIM}," ","~/",".commandcode","/","skills","/ (user)"),st.createElement(Xe,{color:ER.DIM}," ","~/.agents/","skills","/ (user, .agents)"),st.createElement(Xe,{color:ER.DIM}," ",".commandcode","/","skills","/ (project)"),st.createElement(Xe,{color:ER.DIM}," ",".agents/","skills","/ (project, .agents)"),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},e.length>0&&"space to view issues · ","Press ",st.createElement(Xe,{bold:!0},"Esc")," to close")))},"SkillsConfigEmpty");Gt();var RU=__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");Gt();var LU=__name(({title:e,subtitle:t,skills:n,baseIndex:r,cursor:o,disabled:s})=>st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Qe,null,st.createElement(Xe,{color:$R,bold:!0},e," "),st.createElement(Xe,{color:$R},t)),n.map((e,t)=>{const n=r+t===o,i=s.has(e.label),a=n?KR:void 0;return st.createElement(Qe,{key:e.filePath},st.createElement(Xe,{color:i?ER.DIM:ER.GREEN,backgroundColor:a},i?"[off] ":"[on] "),st.createElement(Xe,{color:i?ER.DIM:ER.WHITE,backgroundColor:a},e.label),e.fromAgents&&st.createElement(Xe,{color:ER.DIM,backgroundColor:a}," [.agents]"),st.createElement(Xe,{color:ER.DIM,backgroundColor:a}," · ~",e.estimatedTokens," tokens "))})),"SkillSection"),OU=__name(({onClose:e})=>{const[t,n]=at([]),[r,o]=at([]),[s,i]=at(!0),[a,l]=at(null),[c,d]=at(""),[u,m]=at(new Set),[p,g]=at(new Map),[h,f]=at(!1),[y,S]=at(null),[w,v]=at("list"),[k,C]=at(0),b=useTerminalHeight(),E=lt(!1);ct(()=>{__name(async()=>{try{const e=await loadCommandSkillPickerState();n([...e.skills]),o([...e.warnings]),m(new Set(e.disabled)),g(new Map(e.disabledScopes)),f(e.noProjectRoot)}catch(e){l(e instanceof Error?e.message:"Failed to load skills")}finally{i(!1)}},"load")()},[]);const T=dt(()=>filterSkillPickerRowsForQuery({rows:t,searchQuery:c}),[t,c]),P=T.sections.project,M=T.sections.user,x=T.sections.bundled,I=T.rows,A=b-1,R=(P.length>0?1:0)+(M.length>0?1:0)+(x.length>0?1:0),L=Math.max(4,A-14-2*R),O=__name(async e=>{if(E.current)return;const t=getSkillTogglePolicy({skillName:e.label,disabled:u,disabledScopes:p,noProjectRoot:h});if(!t.allowed)return void S(t.notice);E.current=!0;const n=new Set(u);t.enabling&&n.delete(e.label),t.enabling||n.add(e.label),m(n),S(null);try{const n=await setCommandSkillEnabled(e.label,t.enabling),r=new Map(p);t.enabling&&r.delete(e.label),t.enabling||r.set(e.label,n),g(r),S(getSkillPickerNoProjectWriteNotice(n))}catch(e){m(u),S(`Failed to save: ${e instanceof Error?e.message:String(e)}`)}finally{E.current=!1}},"toggleSkill");ct(()=>{"issues"===w&&d("")},[w]);const D="list"===w&&t.length>0,{cursor:$}=useListNavigation({items:I,onSelect:O,onCancel:e,searchQuery:c,onSearchChange:d,initialIndex:0,isActive:D});if(ct(()=>{C(e=>clampScrollOffset({cursor:$,total:I.length,maxVisible:L,currentOffset:e}))},[$,I.length,L]),nt((t,n)=>{if(!n.tab)return;const r=I[$];r&&(async()=>{try{await It([{file:r.filePath,line:1}]),e()}catch(e){if(e instanceof Error&&e.message.includes("$EDITOR environment variable"))return void l(RU());l(e instanceof Error?e.message:"Failed to open skill in editor")}})()},{isActive:D}),nt((e,n)=>{"list"===w&&0!==t.length&&" "===e&&!n.ctrl&&!n.meta&&r.length>0&&0===c.length&&v("issues")},{isActive:"list"===w&&t.length>0}),s)return st.createElement(bO,{title:"Skills",gapAfterHeader:!1},st.createElement(Xe,{color:ER.DIM},"Loading skills..."));if(a)return st.createElement(bO,{title:"Skills",titleColor:ER.RED,gapAfterHeader:!1,footer:st.createElement(Xe,{italic:!0,color:ER.DIM},"Press ",st.createElement(Xe,{bold:!0},"Esc")," to close")},st.createElement(Xe,{color:ER.DIM},a));if(0===t.length)return st.createElement(AU,{warnings:r,onClose:e});if("issues"===w)return st.createElement(xU,{warnings:r,onClose:()=>v("list"),isActive:!0});const N=t.filter(e=>u.has(e.label)).length,_=k,F=k+L,U=sliceSectionForWindow({section:P,sectionBase:0,windowStart:_,windowEnd:F}),j=sliceSectionForWindow({section:M,sectionBase:P.length,windowStart:_,windowEnd:F}),B=sliceSectionForWindow({section:x,sectionBase:P.length+M.length,windowStart:_,windowEnd:F}),W=I.length>L;return st.createElement(bO,{title:"Skills",titleSuffix:st.createElement(st.Fragment,null," ",t.length," skill",1===t.length?"":"s",N>0&&st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:ER.YELLOW},N," off")),r.length>0&&st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:ER.YELLOW},r.length," skipped"))),subtitle:getSkillPickerNoProjectNotice(h),footer:st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{italic:!0,color:ER.DIM},"type to search · ↑/↓ navigate · enter to toggle · tab to edit",r.length>0&&!c&&" · space to view issues",c?" · esc to clear":" · esc to close"),st.createElement(Xe,{color:ER.DIM},"add skills:"," ",st.createElement(Xe,{color:ER.CYAN},getBinaryCommand()," skills add ","<owner/repo>")))},st.createElement(Qe,{marginBottom:1,flexDirection:"column",width:"100%"},st.createElement(pL,{query:c,resultCount:c?I.length:void 0,placeholder:"Type to search skills..."})),0===I.length?st.createElement(Qe,{marginY:1},st.createElement(Xe,{color:ER.GRAY},'No skills match "',c,'"')):st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"column"},U.rows.length>0&&st.createElement(LU,{title:"Project skills",subtitle:"(.commandcode/skills or .agents/skills)",skills:U.rows,baseIndex:U.baseIndex,cursor:$,disabled:u}),j.rows.length>0&&st.createElement(LU,{title:"User skills",subtitle:"(~/.commandcode/skills or ~/.agents/skills)",skills:j.rows,baseIndex:j.baseIndex,cursor:$,disabled:u}),B.rows.length>0&&st.createElement(LU,{title:"Bundled skills",subtitle:"(ships with Command Code)",skills:B.rows,baseIndex:B.baseIndex,cursor:$,disabled:u})),W&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",_+1,"–",Math.min(F,I.length)," of"," ",I.length,_>0?" · ↑ more":"",F<I.length?" · ↓ more":""))),y&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.YELLOW},y)))},"SkillsConfig");function SkillsConfigView({staticKey:e,onClose:t}){return st.useEffect(()=>{hardResetForResize()},[]),st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(OU,{onClose:t,staticKey:e})))}__name(SkillsConfigView,"SkillsConfigView"),Gt(),Gt(),SR();var DU=[{scope:"project",label:"This project"},{scope:"global",label:"User"}],$U=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=at(!0),[s,i]=at(void 0),[a,l]=at(void 0),[c,d]=at(!0),u=isProjectTasteToggleLocked(a),m=ut(async()=>{try{const e=await getTasteLearningSettings();o(e.global),i(e.project),l(e.projectSource)}catch{}},[]);ct(()=>{m().finally(()=>d(!1))},[m]);const p=__name(async(e,n,r)=>{e();try{await r(),t?.(),await m()}catch(e){n()}},"persist"),g=isByok({model:getConfiguredModel()}),h=__name(e=>{if(g)return;const t=resolveTasteScopeToggle({scope:e.scope,globalEnabled:r,projectOverride:s,projectSource:a});if("locked"===t.kind)return;if("global"===t.scope)return p(()=>o(t.value),()=>o(!t.value),()=>setTasteLearning({tasteLearning:t.value,scope:"global"}));const n=s;return p(()=>i(t.value),()=>i(n),()=>setTasteLearning({tasteLearning:t.value,scope:"project"}))},"toggleRow"),f=__name(e=>{if(g)return;const t=resolveTasteScopeReset({scope:e.scope,globalEnabled:r,projectOverride:s,projectSource:a});if("noop"===t.kind)return;if("save-global"===t.kind)return p(()=>o(!0),()=>o(!1),()=>setTasteLearning({tasteLearning:!0,scope:"global"}));const n=s;return p(()=>i(void 0),()=>i(n),()=>clearProjectTasteLearning())},"resetRow"),{cursor:y}=useListNavigation({items:DU,onSelect:__name(e=>{h(e)},"onSelect"),onReset:__name(e=>{f(e)},"onReset"),onCancel:e,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,isActive:!c});if(c)return st.createElement(bO,{key:n,title:"Taste Learning",gapAfterHeader:!1},st.createElement(A$,{label:"Loading configuration"}));const S=__name(e=>!g&&("project"===e.scope?s??r:r),"valueFor");return st.createElement(bO,{key:n,title:"Taste Learning",subtitle:g?lg:"Learn from your interactions.",hint:g?"esc to close":"↑/↓ navigate · enter to toggle · r reset to default · esc to close"},DU.map((e,t)=>{const n=t===y,r=S(e),o=g||"project"===e.scope&&u;return st.createElement(Qe,{key:e.scope},st.createElement(Xe,{color:n?ER.CYAN:ER.GRAY},n?`${gt.pointer} `:" "),st.createElement(Xe,{color:n?ER.CYAN:ER.WHITE},e.label.padEnd(16)),st.createElement(Xe,{color:r?ER.GREEN:ER.DIM},r?"enabled":"disabled"),o?st.createElement(Xe,{color:ER.DIM}," ",g?"(unavailable on BYOK)":"(set in settings.local.json)"):null)}),st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},"Taste data stored in .commandcode/taste/taste.md"),u?st.createElement(Xe,{color:ER.DIM},"This project is pinned by .commandcode/settings.local.json — edit that file to change it."):null))},"TasteConfig");function TasteConfigView({staticKey:e,onClose:t,loadTasteStatus:n}){return st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement($U,{onClose:t,onSettingsChange:n,staticKey:e})))}function OrgLimitMeter({row:e,width:t,marginTop:n}){const r=e.reached?ER.RED:getUsageColor(e.pct),o=buildBlockBar({percentage:e.pct,width:t});return st.createElement(Qe,{flexDirection:"column",marginTop:n},st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},`${e.label} `),st.createElement(Xe,{color:r},o.filled),st.createElement(Xe,{color:$R},o.empty),st.createElement(Xe,{bold:!0,color:r},` ${Math.round(e.pct)}%`)),st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},`${" ".repeat(e.label.length+1)}${e.detail}`)))}function OrgLimitsSection({limits:e,width:t,now:n}){const r=projectOrgSpendLimitRows({limits:e,now:n});return 0===r.length?null:st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.DIM},"Spend limits"),r.map((e,n)=>st.createElement(OrgLimitMeter,{key:e.label,row:e,width:t,marginTop:0===n?0:1})))}function fetchUsageData2(){return fetchUsageData({getAuthKey:getAuthKey2,getApiBaseUrl:getApiBaseUrl,createRequest:__name(({baseUrl:e})=>createApiClient({baseUrl:e}),"createRequest")})}function getAuthKey2(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function WindowLimitMeter({label:e,used:t,cap:n,resetAt:r,width:o,now:s}){const i=n>0?Math.min(100,t/n*100):0,a=getUsageColor(i),l=buildBlockBar({percentage:i,width:o}),c=r>s?` · resets in ${formatDuration(r-s)}`:"";return st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},e.padEnd(7)," "),st.createElement(Xe,{color:a},l.filled),st.createElement(Xe,{color:$R},l.empty),st.createElement(Xe,{bold:!0,color:a},` ${Math.round(i)}%`),st.createElement(Xe,{color:ER.DIM},c))}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){const t=getRenewalUrgency(e);return"critical"===t?ER.RED:"warning"===t?ER.YELLOW:void 0}__name(TasteConfigView,"TasteConfigView"),Gt(),Gt(),SR(),Gt(),SR(),Gt(),__name(OrgLimitMeter,"OrgLimitMeter"),__name(OrgLimitsSection,"OrgLimitsSection"),__name(fetchUsageData2,"fetchUsageData"),__name(getAuthKey2,"getAuthKey"),__name(WindowLimitMeter,"WindowLimitMeter"),__name(getProgressBarWidth,"getProgressBarWidth"),__name(getDaysColor,"getDaysColor");var NU=__name(({plan:e,status:t})=>st.createElement(Qe,{marginBottom:0},st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:ER.BLUE,color:"#f4f4f4",bold:!0},`${wL}USAGE${wL}`)),e&&st.createElement(st.Fragment,null,st.createElement(Xe,null," "),st.createElement(Xe,{color:ER.GRAY},`${e.name} Plan`)),t&&st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:"active"===t?ER.GREEN:ER.YELLOW},t))),"UsageBadge"),_U=__name(({showRetry:e})=>st.createElement(Qe,{marginTop:1},st.createElement(pO,null,e&&st.createElement(st.Fragment,null,st.createElement(gO,null,"r")," to retry · "),"Press ",st.createElement(gO,null,"Esc")," to close")),"UsageFooter"),FU=__name(({onClose:e})=>{const[t,n]=at("loading"),[r,o]=at(null),[s,i]=at(!1),a=getProgressBarWidth({terminalWidth:useTerminalWidth()}),l=ut(async e=>{try{i(!1);const t=await fetchUsageData2();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")}},[]),c=st.useRef(null);nt((r,o)=>{if(o.escape&&e(),"r"===r&&"error"===t){n("loading"),c.current?.abort();const e=new AbortController;c.current=e,l(e.signal)}}),ct(()=>{const e=new AbortController;return c.current=e,l(e.signal),()=>e.abort()},[l]);const d=r?projectUsageView({usageData:r}):null,u=d?.subscription??null,m=d?.plan??null;if("loading"===t)return st.createElement(Qe,{flexDirection:"column",paddingX:0,width:"100%"},st.createElement(NU,{plan:m,status:u?.status??null}),st.createElement(A$,null),st.createElement(_U,null));if("error"===t)return st.createElement(Qe,{flexDirection:"column",paddingX:0,width:"100%"},st.createElement(NU,{plan:m,status:u?.status??null}),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},s?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),st.createElement(_U,{showRetry:!s}));if(!r)return null;const p=d?.hasBillingData??!1,g=d?.usageUrl??null,h=d?.orgLimits??[],f=d?.now??Date.now();if(!p)return st.createElement(Qe,{flexDirection:"column",paddingX:0,width:"100%"},st.createElement(NU,{plan:m,status:u?.status??null}),st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(D$,{message:"No billing data found."}),g&&st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},"Visit "),st.createElement(cL,{url:g,text:"Studio",color:ER.CYAN}),st.createElement(Xe,{color:ER.DIM}," for usage details."))),st.createElement(OrgLimitsSection,{limits:h,width:a,now:f}),st.createElement(_U,null));const y=d?.windowLimits??null,S=d?.sandboxMinutes??null,w=!0===d?.sandboxAccess&&null!==S&&(S.limitMinutes>0||S.usedMinutes>0),v=d?.summary??null,k=d?.credits,C=k?.usagePercent??0,b=Boolean(k?.hasCreditsInfo),E=(k?.purchasedRemaining??0)+(k?.freeRemaining??0),T=d?.daysLeft??null,P=getDaysColor(T),M=getUsageColor(C),x=buildBlockBar({percentage:C,width:a});return st.createElement(Qe,{flexDirection:"column",paddingX:0,width:"100%"},st.createElement(Qe,{marginBottom:1},st.createElement(NU,{plan:m,status:u?.status??null})),b?st.createElement(Qe,null,st.createElement(Xe,{color:M},x.filled),st.createElement(Xe,{color:$R},x.empty),st.createElement(Xe,{bold:!0,color:M},` ${Math.round(C)}% used`)):st.createElement(Xe,{color:ER.DIM},"Plan details unavailable"),b&&st.createElement(Qe,null,v&&st.createElement(st.Fragment,null,st.createElement(Xe,null,v.totalCount.toLocaleString()),st.createElement(Xe,{color:ER.DIM},"billing-period"===v.periodBasis?" requests this month":" requests")),null!==T&&st.createElement(st.Fragment,null,v&&st.createElement(Xe,{color:ER.DIM}," · "),0===T?st.createElement(Xe,{color:P},"renews today"):st.createElement(st.Fragment,null,st.createElement(Xe,{color:P},`${T} day${1===T?"":"s"}`),st.createElement(Xe,{color:ER.DIM}," to renew"))),E>0&&st.createElement(st.Fragment,null,(v||null!==T)&&st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:ER.DIM},"Extra Credits: "),st.createElement(Xe,null,formatCredits(E)))),y?.limited&&st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.DIM},"Usage limits"),y.fiveHour&&st.createElement(WindowLimitMeter,{label:"5-hour",used:y.fiveHour.used,cap:y.fiveHour.cap,resetAt:y.fiveHour.resetAt,width:a,now:f}),y.weekly&&st.createElement(Qe,{marginTop:y.fiveHour?1:0,flexDirection:"column"},st.createElement(WindowLimitMeter,{label:"Weekly",used:y.weekly.used,cap:y.weekly.cap,resetAt:y.weekly.resetAt,width:a,now:f}))),w&&st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.DIM},"Sandbox minutes"),S.limitMinutes>0?st.createElement(WindowLimitMeter,{label:"Month",used:S.usedMinutes,cap:S.limitMinutes,resetAt:S.resetAt,width:a,now:f}):st.createElement(Xe,null,`${S.usedMinutes} min used this month, billed per minute`)),st.createElement(OrgLimitsSection,{limits:h,width:a,now:f}),g&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Full breakdown at "),st.createElement(cL,{url:g,text:d?.usageUrlDisplay??g,color:ER.CYAN})),st.createElement(_U,null))},"UsageOverlay");function UsageView({staticKey:e,onClose:t}){return st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(FU,{onClose:t})))}__name(UsageView,"UsageView"),Gt(),SR(),Gt(),SR(),Gt();var UU="@last";function shortenHomePath(e){const t=W();return e.startsWith(t)?`~${e.slice(t.length)}`:e}__name(shortenHomePath,"shortenHomePath");var jU={approved:{label:`${gt.tick} approved`,color:ER.GREEN},"not-implemented":{label:`${gt.circleDotted} set aside`,color:ER.YELLOW},pending:{label:`${gt.dot} pending`,color:ER.DIM}},BU=createNodeRuntime(),WU={"?":"Why? Explain the reasoning behind this.",x:"Cut this — remove it from the plan.","!":"Risky — double-check this before implementing."};function lineStyleProps(e){if(e.changed)return{color:ER.GREEN,bold:!1,italic:!1};const t={color:ER.WHITE,bold:!1,italic:!1};if(!e.style)return t;switch(e.style.role){case"heading":return{color:WR.HEADING,bold:!0,italic:!1};case"code":case"code-fence":return{color:WR.CODE,bold:!1,italic:!1};case"quote":return{color:ER.DIM,bold:!1,italic:!0};case"table":return{color:ER.CYAN,bold:!1,italic:!1};default:return t}}__name(lineStyleProps,"lineStyleProps");var HU=__name(({plan:e,variant:t="browse",fallbackContent:n,onBack:r,onSubmitFeedback:o,onExecute:s,onAutoAccept:i})=>{const[a,l]=at(null),[c,d]=at(e.annotations),[u,m]=at(!1);ct(()=>{u||d(e.annotations)},[e.annotations,u]);const[p,g]=at({kind:"line",lineNumber:1}),[h,f]=at(null),y=lt([]),S=dt(()=>shouldCollapsePastedText(),[]),[w,v]=at(null),[k,C]=at(null),[b,E]=at(!1),[T,P]=at(0),[M,x]=at(null),I=useTerminalHeight(),A=useTerminalWidth();ct(()=>{__name(async()=>{const t=await readPlanContent({runtime:BU,filePath:e.filePath})??n??null;l(null===t?[]:splitPlanLines(t))},"load")()},[e.filePath,n]);const R=e.version??1;ct(()=>{R<=1||!e.filePath||readPlanVersionSnapshot({runtime:BU,filePath:e.filePath,version:R-1}).then(x).catch(()=>{})},[R,e.filePath]);const L=dt(()=>null!==M&&null!==a?diffPlanChangedLines({previous:M,current:a}):new Set,[M,a]),O=c.length,D=dt(()=>{const e={id:"feedback",label:`Submit review (${O})`,chord:"ctrl+r",color:ER.CYAN,hint:"agent revises the plan, returns it for review"};return"approval"===t?[...O>0?[e]:[],{id:"auto-accept",label:"Approve",chord:"ctrl+a",color:ER.GREEN,hint:O>0?"executes the plan · comments go along as notes":"executes the plan"},{id:"cancel",label:"Cancel",chord:"esc",color:ER.YELLOW,hint:""}]:[...O>0?[e]:[],{id:"execute",label:"Execute plan",chord:"ctrl+e",color:ER.GREEN,hint:"executes the plan as written"},{id:"cancel",label:"Back",chord:"esc",color:ER.YELLOW,hint:""}]},[t,O]),$=dt(()=>h?c.filter(e=>e.line!==h.line):c,[c,h]),N=dt(()=>buildPlanReaderRows({lines:a??[],annotations:$}),[a,$]),_=dt(()=>classifyPlanLines(a??[]),[a]),F=a?.length??0,U=resolvePlanWrapWidth(Math.max(20,A-7-2)),j=dt(()=>buildPlanReaderDisplayRows({rows:N,width:U}),[N,U]),B=getPlanReaderCursorDisplaySpan({displayRows:j,cursor:p}),W=I-1,H=Math.max(4,W-10-7),G=h?1:0,V=-1===B.first?j.length-1:B.first,z=-1===B.last?j.length-1:B.last+G;ct(()=>{P(e=>{const t=clampScrollOffset({cursor:Math.max(0,z),total:j.length+G,maxVisible:H,currentOffset:e});return clampScrollOffset({cursor:Math.max(0,V),total:j.length+G,maxVisible:H,currentOffset:t})})},[V,z,j.length,G,H]),ct(()=>{g(e=>snapPlanReaderCursor({cursor:e,lineCount:F,actions:[]}))},[F]),ct(()=>{g(e=>"action"!==e.kind||D.some(t=>t.id===e.id)?e:{kind:"line",lineNumber:Math.max(1,F)})},[D,F]);const K=__name(t=>{m(!0),d(t),e.filePath&&setPlanAnnotations({runtime:BU,filePath:e.filePath,annotations:t}).catch(()=>C("Failed to save comments to disk"))},"persistAnnotations"),q="line"===p.kind?c.find(e=>e.line===p.lineNumber):void 0,Y=__name(()=>{if(0===c.length||!a)return;const t=buildPlanAnnotationsPrompt({title:e.title,filePath:e.filePath||"(plan not saved to a file yet)",lines:a,annotations:c});e.filePath&&snapshotPlanVersion({runtime:BU,filePath:e.filePath}).catch(()=>{}),K([]),o(t)},"submitFeedback"),J=__name(t=>{if(t&&c.length>0&&a){const t=buildPlanApprovalNotesPrompt({title:e.title,...e.filePath?{filePath:e.filePath}:{},lines:a,annotations:c});return K([]),void i?.(t)}K([]),i?.()},"approve"),Q=__name(()=>{"approval"===t&&(O>0?v({kind:"approve",choice:"notes"}):J(!1))},"requestApprove"),X=__name(()=>{O>0&&!e.filePath?v({kind:"cancel"}):r()},"requestCancel"),Z=__name(t=>{"feedback"!==t?"execute"!==t?"auto-accept"!==t?"cancel"===t&&X():Q():(s??o)(buildPlanExecutePrompt({title:e.title,filePath:e.filePath||e.fileName})):Y()},"runAction"),ee=__name(()=>{e.filePath?(E(!0),openFileInEditor(e.filePath).then(async()=>{const t=await readPlanContent({runtime:BU,filePath:e.filePath});null!==t&&l(splitPlanLines(t))}).catch(e=>C(e instanceof Error?e.message:"Failed to open the editor")).finally(()=>{E(!1),hardResetForResize()})):C("This plan is not saved to a file yet")},"openExternalEditor"),te=__name(e=>{"line"!==p.kind||p.lineNumber<1||p.lineNumber>F||(y.current=e?[]:q?.pastes??[],f({line:p.lineNumber,value:e||(q?.text??""),hadExisting:void 0!==q}))},"openDraft"),ne=__name(e=>{h&&(K(upsertPlanAnnotation({annotations:c,line:h.line,text:e,createdAt:(new Date).toISOString(),pastes:y.current})),y.current=[],f(null))},"commitDraft"),re=dt(()=>{const e=new Set;for(const t of c)e.add(t.line);for(const t of L)e.add(t);return[...e].sort((e,t)=>e-t)},[c,L]),oe=__name(e=>{if(0===re.length)return;const t="line"===p.kind?p.lineNumber:F+1,n="next"===e?re.find(e=>e>t)??re[0]:[...re].reverse().find(e=>e<t)??re[re.length-1];void 0!==n&&g({kind:"line",lineNumber:n})},"jumpMarked");nt((e,t)=>{t.escape&&f(null)},{isActive:null!==h}),nt((e,t)=>{if(w)if(t.escape)v(null);else if("approve"===w.kind&&(t.leftArrow||t.rightArrow||t.tab))v({kind:"approve",choice:"notes"===w.choice?"original":"notes"});else if(t.return){if("approve"===w.kind)return v(null),void J("notes"===w.choice);v(null),r()}},{isActive:null!==w}),nt((e,n)=>{if(n.escape)return void X();if(n.upArrow||n.downArrow)return C(null),void g(e=>{if("action"===e.kind){const t=D.findIndex(t=>t.id===e.id);if(n.upArrow){if(t<=0&&F>0)return{kind:"line",lineNumber:F};const n=D[Math.max(0,t-1)];return n?{kind:"action",id:n.id}:e}const r=D[Math.min(D.length-1,t+1)];return r?{kind:"action",id:r.id}:e}if(n.upArrow)return{kind:"line",lineNumber:Math.max(1,e.lineNumber-1)};if(e.lineNumber>=F){const t=D[0];return t?{kind:"action",id:t.id}:e}return{kind:"line",lineNumber:e.lineNumber+1}});if(n.pageUp||n.pageDown)return C(null),void g(e=>"action"===e.kind&&n.pageDown?e:movePlanReaderCursorByPage({displayRows:j,cursor:e,direction:n.pageDown?"down":"up",pageRows:Math.max(1,H-1)}));if(n.home||n.end)return C(null),void(F>0&&g({kind:"line",lineNumber:n.home?1:F}));if(n.leftArrow||n.rightArrow){if("action"!==p.kind)return;const e=D.findIndex(e=>e.id===p.id);if(-1===e)return;const t=n.leftArrow?Math.max(0,e-1):Math.min(D.length-1,e+1),r=D[t];return void(r&&g({kind:"action",id:r.id}))}if(n.ctrl&&"r"===e)return void Y();if(n.ctrl&&"a"===e&&"approval"===t)return void Q();if(n.ctrl&&"e"===e&&"browse"===t)return void Z("execute");if(n.ctrl&&"g"===e)return void ee();if(n.ctrl&&"n"===e)return void oe("next");if(n.ctrl&&"p"===e)return void oe("previous");if(n.return)return"action"===p.kind?void Z(p.id):void te("");const r=WU[e];"line"!==p.kind||!r||n.ctrl||n.meta?"line"===p.kind&&e.length>0&&!n.ctrl&&!n.meta&&te(e):K(upsertPlanAnnotation({annotations:c,line:p.lineNumber,text:q?.text===r?"":r,createdAt:(new Date).toISOString()}))},{isActive:null===h&&null===w&&null!==a&&!b});const se=jU[e.status],ie=T,ae=T+H-G,le=j.slice(ie,ae),ce=h?h.hadExisting?"enter to keep · clear + enter removes · esc keep as was":"enter to pin · esc discard":w?"approve"===w.kind?"←/→ choose · enter confirm · esc back":"enter discard · esc back":"action"===p.kind?"↑/↓ choose · enter to run":["type + enter to comment",...re.length>0?["ctrl+n/p jump "+(L.size>0?"changes":"comments")]:[],"quick: ? why x cut ! risky","ctrl+g $EDITOR"].join(" · ");return st.createElement(bO,{title:"approval"===t?`Plan review: ${e.title}`:e.title,titleSuffix:"approval"===t?st.createElement(st.Fragment,null," ","· ",shortenHomePath(e.filePath)||e.fileName," · v",e.version??1):st.createElement(st.Fragment,null," ","· ",shortenHomePath(e.filePath)||e.fileName," · v",e.version??1," ",st.createElement(Xe,{color:se.color},se.label)),subtitle:"approval"===t?"Review the plan like a PR — type on any line to comment, enter pins it under the line.":void 0,footer:st.createElement(Xe,{italic:!0,color:ER.DIM},ce)},null===a?st.createElement(Xe,{color:ER.DIM},"Loading plan..."):0===F?st.createElement(Xe,{color:ER.DIM},"Plan file is empty or missing on disk."):st.createElement(Qe,{flexDirection:"column"},le.map((e,t)=>{const n=ie+t,{row:r}=e;if("action"===r.kind)return null;if("annotation"===r.kind)return st.createElement(Qe,{key:`annotation-${r.lineNumber}-${n}`},st.createElement(Xe,{color:ER.DIMMER}," ".repeat(5)),st.createElement(Xe,{backgroundColor:PR.BADGE_BG,color:PR.BADGE_FG}," ",e.isFirstSegment?"↳ ":" ",e.text," "));const o="line"===p.kind&&p.lineNumber===r.lineNumber,s=lineStyleProps({style:_[r.lineNumber-1],changed:L.has(r.lineNumber)}),i=j[n+1],a=!i||"line"!==i.row.kind||i.row.lineNumber!==r.lineNumber,l=n===ae-1,c=null!==h&&h.line===r.lineNumber&&(a||l);return st.createElement(st.Fragment,{key:`line-${r.lineNumber}-${n}`},st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIMMER},e.isFirstSegment?String(r.lineNumber).padStart(4," "):" "," "),st.createElement(Xe,{color:r.hasAnnotation?ER.CYAN:ER.DIMMER},e.isFirstSegment&&r.hasAnnotation?`${gt.bullet} `:" "),st.createElement(Xe,{color:s.color,bold:s.bold,italic:s.italic,backgroundColor:o?KR:void 0},e.text||" ")),c&&h&&st.createElement(Qe,null,st.createElement(Xe,{color:ER.CYAN}," ┃ ",gt.bullet," "),st.createElement(TextInput,{value:h.value,onChange:e=>{y.current=prunePlanAnnotationPastes(e,y.current),f(t=>t?{...t,value:e}:t)},onSubmit:ne,placeholder:"Type your comment…",focus:null!==h,stripBracketedPaste:!0,clipboardOnEmptyPaste:!0,collapsePastedText:S,onPasteCollapsed:e=>{y.current=[...y.current,e]}})))})),st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(ZR,{dividerColor:ER.DIMMER}),st.createElement(Qe,null,st.createElement(Xe,{bold:!0,backgroundColor:PR.BADGE_BG,color:ER.WHITE}," REVIEW "),st.createElement(Xe,{color:ER.DIM},O>0&&` ${O} pending comment${1===O?"":"s"}`,R>1&&` · round ${R}${L.size>0?` · ${L.size} line${1===L.size?"":"s"} changed`:""}`)),w?"approve"===w.kind?st.createElement(Qe,null,st.createElement(Xe,{bold:!0,color:ER.GREEN},"Approve"," "),st.createElement(Xe,{color:"notes"===w.choice?ER.WHITE:ER.DIM,backgroundColor:"notes"===w.choice?KR:void 0},"notes"===w.choice?"(•)":"( )"," ","with ",O," comment",1===O?"":"s"," as notes"),st.createElement(Xe,{color:ER.DIMMER}," "),st.createElement(Xe,{color:"original"===w.choice?ER.WHITE:ER.DIM,backgroundColor:"original"===w.choice?KR:void 0},"original"===w.choice?"(•)":"( )"," ","original plan · discard comments")):st.createElement(Qe,null,st.createElement(Xe,{color:ER.YELLOW},"Discard ",O," pending comment",1===O?"":"s"," and exit review?")):D.map(e=>{const t="action"===p.kind&&p.id===e.id;return st.createElement(Qe,{key:e.id},st.createElement(Xe,{bold:!0,color:e.color,backgroundColor:t?KR:void 0},t?`${gt.pointer} ${e.label} `:e.label),st.createElement(Xe,{color:ER.DIM}," ",e.chord),e.hint&&st.createElement(Xe,{color:ER.DIMMER}," ",e.hint))}),k&&st.createElement(Xe,{color:ER.YELLOW},k)))},"PlanReader"),GU=createNodeRuntime();function PlanApprovalView({staticKey:e,planContent:t,planFilePath:n,onAutoAccept:r,onCancel:o,onSendFeedback:s}){ct(()=>{hardResetForResize()},[]);const[i,a]=at(null);ct(()=>{n&&listPlans({runtime:GU}).then(e=>a(e.find(e=>e.filePath===n)??null)).catch(()=>{})},[n]);const l=dt(()=>{if(i)return i;const e=n?.split("/").pop()??"plan.md";return{fileName:e,filePath:n??"",title:derivePlanTitle({content:t,fileName:e}),status:"pending",createdAt:"",updatedAt:"",annotations:[]}},[i,n,t]);return st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(HU,{plan:l,variant:"approval",fallbackContent:t,onBack:o,onSubmitFeedback:s,onAutoAccept:r})))}__name(PlanApprovalView,"PlanApprovalView"),Gt(),Gt(),SR();var VU=Date.now(),zU=createNodeRuntime();function matchesTarget(e,t){const n=t.toLowerCase();return e.fileName.toLowerCase()===n||e.fileName.toLowerCase().replace(/\.md$/,"")===n||e.title.toLowerCase()===n}__name(matchesTarget,"matchesTarget");var KU=__name(({sessionId:e,target:t,onClose:n,onSubmitFeedback:r,onExecute:o})=>{const[s,i]=at([]),[a,l]=at([]),[c,d]=at(!0),[u,m]=at(null),[p,g]=at("session"),[h,f]=at(null),[y,S]=at(""),[w,v]=at(0),[k,C]=at(0),b=useTerminalHeight(),E=lt(!1);ct(()=>{__name(async()=>{try{const[n,r]=await Promise.all([listPlans({runtime:zU,sessionId:e,sessionStartMs:VU}),listPlans({runtime:zU})]);if(i([...n]),l([...r]),t&&!E.current)if(E.current=!0,t===UU){const e=n[0];e&&f(e)}else{const e=r.find(e=>matchesTarget(e,t.trim()));e?f(e):S(t.trim())}}catch(e){m(e instanceof Error?e.message:"Failed to load plans")}finally{d(!1)}},"load")()},[e,k]);const T="session"===p?s:a,P=dt(()=>{const e=y.trim().toLowerCase();return e?T.filter(t=>t.title.toLowerCase().includes(e)||t.fileName.toLowerCase().includes(e)):T},[T,y]),M=b-1,x=Math.max(3,M-9),I=null===h&&!c,{cursor:A}=useListNavigation({items:P,onSelect:__name(e=>f(e),"onSelect"),onCancel:n,searchQuery:y,onSearchChange:S,initialIndex:0,isActive:I});if(ct(()=>{v(e=>clampScrollOffset({cursor:A,total:P.length,maxVisible:x,currentOffset:e}))},[A,P.length,x]),nt((e,t)=>{(t.leftArrow||t.rightArrow)&&(g(e=>"session"===e?"all":"session"),v(0))},{isActive:I}),h)return st.createElement(HU,{plan:h,onBack:()=>{f(null),C(e=>e+1)},onSubmitFeedback:r,onExecute:o});if(c)return st.createElement(bO,{title:"Plans",gapAfterHeader:!1},st.createElement(Xe,{color:ER.DIM},"Loading plans..."));if(u)return st.createElement(bO,{title:"Plans",titleColor:ER.RED,gapAfterHeader:!1,hint:"Esc to close"},st.createElement(Xe,{color:ER.DIM},u));const R=w,L=w+x,O=P.slice(R,L),D=P.length>x;return st.createElement(bO,{title:"Plans",titleSuffix:st.createElement(st.Fragment,null," ",P.length," plan",1===P.length?"":"s"),subtitle:st.createElement(st.Fragment,null,st.createElement(Xe,{bold:"session"===p,color:"session"===p?fO:ER.DIM},"This session"),st.createElement(Xe,{color:ER.DIMMER},` ${gt.triangleLeftSmall} ${gt.triangleRightSmall} `),st.createElement(Xe,{bold:"all"===p,color:"all"===p?fO:ER.DIM},"All plans")),footer:st.createElement(Xe,{italic:!0,color:ER.DIM},"type to search · ↑/↓ navigate · ←/→ switch tab · enter to open",y?" · esc to clear":" · esc to close")},st.createElement(Qe,{marginBottom:1,flexDirection:"column",width:"100%"},st.createElement(pL,{query:y,resultCount:y?P.length:void 0,placeholder:"Type to search plans..."})),0===P.length?st.createElement(Qe,{marginY:1},st.createElement(Xe,{color:ER.GRAY},y?`No plans match "${y}"`:"session"===p?"No plans in this session yet — use /plan or plan mode to create one. Press → for all plans.":"No saved plans yet — plans land in ~/.commandcode/plans when you use plan mode.")):st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"column"},O.map((e,t)=>{const n=R+t===A,r=jU[e.status];return st.createElement(Qe,{key:e.fileName},st.createElement(Xe,{color:n?wO:ER.GRAY},n?`${gt.pointer} `:" "),st.createElement(Xe,{bold:n,color:n?wO:ER.WHITE},e.title),st.createElement(Xe,{color:r.color}," ",r.label),(e.version??1)>1&&st.createElement(Xe,{color:ER.DIM}," ","v",e.version),e.annotations.length>0&&st.createElement(Xe,{color:ER.CYAN}," ",e.annotations.length," comment",1===e.annotations.length?"":"s"),st.createElement(Xe,{color:ER.DIM}," ",formatRelativeTimeShort({timestamp:e.updatedAt})))})),D&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",R+1,"–",Math.min(L,P.length)," of"," ",P.length,R>0?" · ↑ more":"",L<P.length?" · ↓ more":""))))},"PlansScreen");function PlansView({staticKey:e,sessionId:t,target:n,onClose:r,onSubmitFeedback:o,onExecute:s}){return st.useEffect(()=>{hardResetForResize()},[]),st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(KU,{sessionId:t,target:n,onClose:r,onSubmitFeedback:o,onExecute:s})))}function ForkSummary({session:e,isSelected:t,nameColor:n}){if(!e.forkProvenance)return null;const r=t?void 0:ER.DIM,o=e.userRenamed&&e.title?e.title:null;return o?st.createElement(Xe,{color:n},`${o} `,st.createElement(Xe,{color:r},`· ${e.forkProvenance}`)):st.createElement(Xe,{color:r},e.forkProvenance)}__name(PlansView,"PlansView"),Gt(),Gt(),SR(),Gt(),__name(ForkSummary,"ForkSummary");var qU=__name((e,t)=>e.padEnd(t),"padCell"),YU=__name(e=>e instanceof Error&&e.message?e.message:"Unknown error","getActionErrorMessage");function resolveRowColor(e){return e.isDeletePending?ER.RED:e.isCurrentSession?TR:e.isSelected?ER.WHITE:ER.GRAY}function renderRowSummary(e){const{session:t,isSelected:n,nameColor:r}=e;if(t.forkProvenance)return st.createElement(ForkSummary,{session:t,isSelected:n,nameColor:r});const o=getSessionSummary({session:t});return t.userRenamed&&t.title?st.createElement(Xe,{color:r},o):o}__name(resolveRowColor,"resolveRowColor"),__name(renderRowSummary,"renderRowSummary");var JU=["recent","created","messages"],QU={recent:"Recent",created:"Created",messages:"Messages"};function nextSortMode(e){const t=JU.indexOf(e);return JU[(t+1)%JU.length]}function sortSessions(e,t){return"created"===t?[...e].sort((e,t)=>Date.parse(t.createdAt)-Date.parse(e.createdAt)):"messages"===t?[...e].sort((e,t)=>t.messageCount-e.messageCount):e}function matchesSearch2(e,t){const n=t.toLowerCase().split(/\s+/).filter(Boolean);if(0===n.length)return!0;const r=[e.id,e.title??"",e.firstMessage,e.gitBranch??""].join(" ").toLowerCase();return n.every(e=>r.includes(e))}function getFilteredEmptyState(e){return e.namedOnly?{text:"No named sessions.",hint:"Press ctrl+n to show all."}:e.searchQuery?{text:`No sessions match "${e.searchQuery}"`,hint:"Press Esc to clear search."}:e.branchFilter&&e.currentBranch?{text:`No sessions found for branch "${e.currentBranch}"`,hint:"Press ctrl+b to show all branches, Esc to cancel"}:{text:"No previous sessions found",hint:"Press Esc to go back"}}function resolveProjectBaseDir(){const e=getCommandSessionRuntime();return getProjectSessionDir({env:e.env(),cwd:e.cwd()})}__name(nextSortMode,"nextSortMode"),__name(sortSessions,"sortSessions"),__name(matchesSearch2,"matchesSearch"),__name(getFilteredEmptyState,"getFilteredEmptyState"),__name(resolveProjectBaseDir,"resolveProjectBaseDir");var XU=__name(({onSelectSession:e,onClose:t,currentSessionId:n})=>{const[r,o]=at([]),[s,i]=at(0),[a,l]=at(0),[c,d]=at(!0),[u,m]=at(!1),[p,g]=at(!1),[h,f]=at(null),[y,S]=at(null),[w,v]=at(""),[k,C]=at(!1),[b,E]=at("recent"),[T,P]=at(!1),[M,x]=at("list"),[I,A]=at(null),[R,L]=at(""),[O,D]=at(null),[$]=at(()=>getCurrentGitBranch()),[N]=at(()=>resolveProjectBaseDir()),_=useTerminalHeight(),F=Math.max(6,_-19),U=ut(async()=>{d(!0);const e=await listCommandSessions();o(e),d(!1)},[]);ct(()=>{U()},[U]),ct(()=>{if(!y)return;const e=setTimeout(()=>S(null),3e3);return()=>clearTimeout(e)},[y]);const j=ut(async e=>{try{const t=getCommandSessionRuntime(),{method:n}=await deleteSessionV3({runtime:t,baseDir:N,id:e});g(!1),f(null),i(0),l(0),S("trash"===n?"Session moved to trash":"Session deleted"),await U()}catch(e){g(!1),f(`Failed to delete session: ${YU(e)}`)}},[U,N]),B=ut(async e=>{const t=I;if(t)try{const n=getCommandSessionRuntime();await renameSessionFile({runtime:n,cwd:n.cwd(),baseDir:N,id:t,name:e}),x("list"),A(null),D(null),await U()}catch(e){D(`Failed to rename session: ${YU(e)}`)}else x("list")},[I,U,N]),W=filterSessionsByBranch({sessions:r,branchFilter:u,currentBranch:$}),H=T?W.filter(e=>e.userRenamed):W,G=sortSessions(w?H.filter(e=>matchesSearch2(e,w)):H,b);if(ct(()=>{i(e=>Math.min(e,Math.max(0,G.length-1)))},[G.length]),nt((r,o)=>{if("rename"===M)return o.escape?(x("list"),void A(null)):void 0;if(p){if(!o.return)return void g(!1);if(G.length>0&&s<G.length){const e=G[s];j(e.id)}}else{if(o.delete||isCtrlKey({inputChar:r,key:o,letter:"d",ctrlCode:4})){if(0===G.length)return;return G[s]?.id===n?void f("Cannot delete the current session"):(f(null),void g(!0))}if(isCtrlKey({inputChar:r,key:o,letter:"r",ctrlCode:18})){if(c)return;const e=G[s];if(!e)return;return D(null),L(e.title??""),A(e.id),void x("rename")}if(isCtrlKey({inputChar:r,key:o,letter:"p",ctrlCode:16}))C(e=>!e);else{if(!isCtrlKey({inputChar:r,key:o,letter:"s",ctrlCode:19}))return isCtrlKey({inputChar:r,key:o,letter:"n",ctrlCode:14})?(P(e=>!e),i(0),void l(0)):o.escape?w?(v(""),i(0),void l(0)):void t():isCtrlKey({inputChar:r,key:o,letter:"b",ctrlCode:2})?(m(e=>!e),i(0),void l(0)):void(o.upArrow?i(e=>{const t=Math.max(0,e-1);return t<a&&l(t),t}):o.downArrow?i(e=>{const t=Math.min(G.length-1,e+1);return t>=a+F&&l(t-F+1),t}):o.return?G.length>0&&s<G.length&&e(G[s].id):o.backspace?w&&(v(e=>e.slice(0,-1)),i(0),l(0)):!o.ctrl&&!o.meta&&!o.tab&&r&&1===r.length&&r>=" "&&(v(e=>e+r),i(0),l(0)));E(e=>nextSortMode(e))}}}),c)return st.createElement(Qe,{flexDirection:"column",paddingLeft:2},st.createElement(A$,{label:"Loading sessions"}));if(0===r.length)return st.createElement(Qe,{flexDirection:"column",paddingLeft:2},st.createElement(D$,{message:"No previous sessions found",hint:"Press Esc to go back"}));const V=G.slice(a,a+F),z=s<G.length?G[s]:null,K=p&&z?`Delete "${getSessionSummary({session:z})}"? Press Enter to confirm, any other key to cancel.`:null,q=getFilteredEmptyState({namedOnly:T,searchQuery:w,branchFilter:u,currentBranch:$});return st.createElement(bO,{title:"Resume Session",subtitle:`Sort: ${QU[b]} · Name: ${T?"Named":"All"} · Branch: ${u?$??"unknown":"All"}`},st.createElement(Qe,{marginBottom:1,width:"100%"},st.createElement(pL,{query:w,resultCount:w?G.length:void 0,placeholder:"Type to search sessions..."})),st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:$R,bold:!0},qU("#",6),qU("Modified",12),qU("Git Branch",22),qU("Messages",12),"Summary",k?" · Path":"")),0===G.length?st.createElement(Qe,{marginBottom:1},st.createElement(D$,{message:q.text,hint:q.hint})):st.createElement(Qe,{flexDirection:"column"},V.map((e,t)=>{const r=a+t,o=s===r,i=p&&o,l=i?void 0:ER.YELLOW,c=resolveRowColor({isDeletePending:i,isCurrentSession:e.id===n,isSelected:o}),d=truncateString2({text:e.gitBranch||"-",maxChars:20}),u=k?toRelativePath(`${N}/${e.id}.jsonl`):null;return st.createElement(Xe,{key:e.id,color:c,backgroundColor:o?KR:void 0,bold:o,wrap:"truncate-end"},qU(`${r+1}.`,6),qU(formatRelativeTimeShort({timestamp:e.lastModified}),12),qU(d,22),qU(String(e.messageCount),12),renderRowSummary({session:e,isSelected:o,nameColor:l}),u?st.createElement(Xe,{color:ER.DIM},` ${u}`):null," ")})),st.createElement(Qe,{marginTop:1}),"rename"===M&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.CYAN},"Rename: "),st.createElement(TextInput,{value:R,onChange:L,onSubmit:B,singleLine:!0,stripBracketedPaste:!0})),O&&st.createElement(Qe,{marginBottom:1},st.createElement(R$,{glyph:!1},O)),K&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.RED},K)),h&&st.createElement(Qe,{marginBottom:1},st.createElement(R$,{glyph:!1},h)),y&&st.createElement(Qe,{marginBottom:1},st.createElement(L$,{glyph:!1},y)),G.length>F&&st.createElement(Xe,{color:ER.DIM},"Showing ",a+1,"–",Math.min(a+F,G.length)," ","of ",G.length,a>0?" · ↑ more":"",a+F<G.length?" · ↓ more":""),st.createElement(hO,{marginTop:0,hints:["enter resume","ctrl+s sort","ctrl+n named","ctrl+r rename","ctrl+d delete","ctrl+p path","ctrl+b branch","type to search"]}))},"SessionsResumeTable"),ZU=it(__name(function SessionView2({onSelectSession:e,onClose:t,currentSessionId:n}){return st.createElement(XU,{onSelectSession:e,onClose:t,currentSessionId:n})},"SessionView"));Gt(),Gt();var ej=__name(({onTrust:e,onExit:t})=>{const{exit:n}=rt(),[r,o]=at(1),s=process.cwd(),i=W(),a=i&&s.startsWith(i)?`~${s.slice(i.length)}`:s;return nt((s,i)=>{if(i.upArrow||i.downArrow)o(1===r?2:1);else{if(i.return)return 1===r?void e():(t(),void n());if("1"!==s)return"2"===s?(t(),void n()):void((i.escape||i.ctrl&&"c"===s)&&(t(),n()));e()}}),st.createElement(bO,{title:"Do you trust the files in this folder?",subtitle:a,hint:"↑/↓ to navigate · enter to select · esc to exit"},st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),st.createElement(Qe,{marginTop:1},st.createElement(Xe,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Qe,null,st.createElement(jN,{isSelected:1===r}),st.createElement(BN,{isSelected:1===r,idleColor:kO}," ","1. Yes, proceed")),st.createElement(Qe,null,st.createElement(jN,{isSelected:2===r}),st.createElement(BN,{isSelected:2===r,idleColor:kO}," ","2. No, exit"))))},"TrustPrompt"),tj=it(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(ej,{onTrust:t,onExit:n}))},"TrustView"));Gt(),Gt();var nj=new Map;function enqueueAgentSlashCommand(e){const t=nj.get(e.sessionId);t?t.push(e.command):nj.set(e.sessionId,[e.command])}function drainAgentSlashCommands(e){const t=nj.get(e.sessionId);return t&&0!==t.length?(nj.delete(e.sessionId),t):[]}function useAgentSlashCommandQueue({sessionId:e,isCmdCodeBusy:t,onCommand:n}){const r=lt(!1);ct(()=>{if(t||r.current)return;const o=drainAgentSlashCommands({sessionId:e});0!==o.length&&(r.current=!0,(async()=>{try{for(const e of o)await n(e)}finally{r.current=!1}})())},[t,e,n])}function useAuth(){const[e,t]=at(()=>getConfiguredProviderSync()),[n,r]=at(()=>getConfiguredModel()),[o,s]=at(null),[i,a]=at(!1),[l,c]=at(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,authComponentInfo:o,setAuthComponentInfo:s,showProviderNotification:i,setShowProviderNotification:a,premiumCreditsExhausted:l,setPremiumCreditsExhausted:c,providerNotificationTimer:lt(null),modelNotificationTimer:lt(null)}}__name(enqueueAgentSlashCommand,"enqueueAgentSlashCommand"),__name(drainAgentSlashCommands,"drainAgentSlashCommands"),__name(useAgentSlashCommandQueue,"useAgentSlashCommandQueue"),Gt(),SR(),__name(useAuth,"useAuth"),Gt(),SR();var rj=__name(()=>{const[e,t]=at({isExecuting:!1,currentCommand:null});return{executeBash:ut(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await runUserBashCommand({command:e});n(n=>completePendingBashEntry({feed:n,command:e,output:t})),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");Gt(),Gt(),SR(),Gt(),SR();var oj={detectIDE:aE,isIdeIpcConnected:__name(async e=>{const t=yE(),n=await t.connect(e);return t.disconnect(),n},"isIdeIpcConnected"),log:dlog,platform:__name(()=>process.platform,"platform")};Gt();var sj=null,ij={};function requestReload(e){sj=e}function discardPendingReload(){sj=null}function consumePendingReload(){const e=sj;return sj=null,e}function setOriginalInvocation(e){ij=e}function getOriginalInvocation(){return ij}function resolveProviderOrReport(e){return resolveCommandProviderId(e.provider)||(e.setFeed(t=>[...t,yh(`Unknown provider '${e.provider}'. Run /connect to see available providers.`)]),null)}async function handleLoginCommand({provider:e,setFeed:t,setShowLoginOverlay:n,setAuthComponentInfo:r}){const o=e?.trim();if(o){const e=resolveProviderOrReport({provider:o,setFeed:t});if(!e)return;const n=getProviderConfig(e),s=n?.authComponent;return n?.requiresAuth&&s?r?void r({provider:e,Component:s}):void t(e=>[...e,yh("Provider login is not available here.")]):void t(t=>[...t,uh(`${getProviderDisplayName(e)} does not use provider login. Run /login without a provider for Command Code account auth.`)])}const s=await resolveLoginCommand({onDebugError:__name(e=>{process.env.DEBUG&&console.error("Failed to load credentials for display:",e)},"onDebugError")});"already-logged-in"!==s.kind?n(!0):t(e=>[...e,uh(s.message)])}function handleLoginComplete({success:e,message:t,setShowLoginOverlay:n,setFeed:r,setStatus:o}){if(n(!1),!e)return r(e=>[...e,yh(t)]),void o("Ready...");r(e=>[...e,uh(t)]),invalidateBillingContext(),o("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,uh("Authentication cancelled")]),n("Ready...")}async function handleLogoutCommand({provider:e,setFeed:t,setRetryAttempt:n,setIsCmdCodeBusy:r}){const o=e?.trim();if(o){const e=resolveProviderOrReport({provider:o,setFeed:t});if(!e)return;const n=getProviderConfig(e);if(!n?.requiresAuth)return void t(t=>[...t,uh(`${getProviderDisplayName(e)} does not use provider logout. Run /logout without a provider for Command Code account auth.`)]);try{const n=await providerLogout({provider:e}),r=getProviderDisplayName(e);t(e=>[...e,uh(n?`Logged out of ${r}`:`No saved ${r} credential found`)])}catch(n){const r=n instanceof Error?n.message:"Unknown error";t(t=>[...t,yh(`Failed to log out of ${getProviderDisplayName(e)}: ${r}`)])}return}const s=await runCommandLogoutFlow({env:process.env});s.success&&invalidateBillingContext(),s.turnInterrupted&&(n(null),r(!1)),t(e=>[...e,"error"===s.notice.kind?yh(s.notice.message):uh(s.notice.message)])}function parseChangelogVersions(e){return e.split(/^(?=## )/m).map(e=>e.trim()).filter(e=>e.startsWith("## "))}function findChangelogPath(e){let t=r(p(e));for(let e=0;e<6;e++){const e=n(t,"CHANGELOG.md");if(A(e))return e;const o=r(t);if(o===t)return null;t=o}return null}function handleChangelog({setFeed:e,rawArguments:t="",moduleUrl:n}){const r=findChangelogPath(n??import.meta.url);if(!r)return void e(e=>[...e,uh("No changelog available in this build.")]);const o=parseChangelogVersions(R(r,"utf8"));if(0===o.length)return void e(e=>[...e,uh("The changelog is empty.")]);const s="all"===t.trim().toLowerCase()?o.length:10,i=o.slice(0,s).join("\n\n"),a=o.length-s,l=a>0?`\n\n_…and ${a} earlier releases · /changelog all_`:"";e(e=>[...e,fh(`**What's new**\n\n${i}${l}`)])}async function releaseHarness(e){if(e){try{await(k$(e)?.flush())}catch{}C$(e)}}async function handleSelectSession({selectedSessionId:e,previousSessionId:t,sessionLoadIdRef:n,setFeed:r,setLiveEntries:o,setSessionId:s,setShowSessionSelector:i,setSessionLoaded:a,setStaticKey:l,setShareInfo:c,setCurrentModel:d,inTuiResume:u=!1}){const m=crypto.randomUUID();n.current=m;const p=__name(()=>n.current!==m,"isStale");t&&t!==e&&await releaseHarness(t),r([]),o([]),clearSessionTodos(),setNextSessionStartSource("resume"),s(e),i(!1),a(!0);const g=await resolveSessionSwitch({sessionId:e,inTuiResume:u,isModelSelectable:__name(async e=>(await loadCustomProviderModels(),Boolean(resolveKnownModelId2(e))||isByok({model:e})),"isModelSelectable"),isStale:p,onDebug:dlog});if("superseded"===g.status)return;if("error"===g.status){if(p())return;return console.error("Failed to load session:",g.message),r([yh(g.message)]),i(!1),a(!1),void s(crypto.randomUUID())}if(g.adoptedModel&&d?.(g.adoptedModel),g.shareInfo&&c({url:g.shareInfo.url,secret:g.shareInfo.secret}),p())return;r(g.feed);const h=seedTodosFromFeedEntries(g.feed);k$(e)?.applyTodoUserEdit({todos:h}),g.bannerModelChanged||isWrappedChild()?hardResetForResize():RL(),l(e=>e+1)}__name(requestReload,"requestReload"),__name(discardPendingReload,"discardPendingReload"),__name(consumePendingReload,"consumePendingReload"),__name(setOriginalInvocation,"setOriginalInvocation"),__name(getOriginalInvocation,"getOriginalInvocation"),Gt(),SR(),__name(resolveProviderOrReport,"resolveProviderOrReport"),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Gt(),SR(),__name(parseChangelogVersions,"parseChangelogVersions"),__name(findChangelogPath,"findChangelogPath"),__name(handleChangelog,"handleChangelog"),Gt(),SR(),Gt(),SR(),__name(releaseHarness,"releaseHarness"),__name(handleSelectSession,"handleSelectSession");var aj="Nothing to clone yet.";async function handleCloneCommand(e){const t=k$(e.sessionId);if(t)try{const n=await t.cloneSession();if(!n)return void e.setFeed(e=>[...e,uh(aj)]);e.setFeed(e=>[...e,uh(`Cloned to ${n.newId} — switching…`)]),await handleSelectSession({selectedSessionId:n.newId,previousSessionId:e.sessionId,sessionLoadIdRef:e.sessionLoadIdRef,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setSessionId:e.setSessionId,setShowSessionSelector:e.setShowSessionSelector,setSessionLoaded:e.setSessionLoaded,setStaticKey:e.setStaticKey,setShareInfo:e.setShareInfo,setCurrentModel:e.setCurrentModel,inTuiResume:!0})}catch{e.setFeed(e=>[...e,yh("Couldn't clone the session (storage error). Staying on the current session.")])}else e.setFeed(e=>[...e,uh(aj)])}async function handleCompactCommand({sessionId:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:o,setStaticKey:s}){try{r(!0),n("Compacting conversation...");const i=await v$({sessionId:e,baseUrl:getApiBaseUrl()}),a=await i.compact();RL(),s(e=>e+1);const l=buildCompactCommandNotice(a);t(e=>[...e,uh(l.message)]),r(!1),n("Ready..."),o(buildPostCompactContextUsage())}catch(e){t(t=>[...t,yh(buildCompactErrorNotice(e).message)]),r(!1),n("Ready...")}}__name(handleCloneCommand,"handleCloneCommand"),Gt(),SR(),__name(handleCompactCommand,"handleCompactCommand"),Gt(),SR();var lj=__name(e=>{const t=e.metadata?.blockOf;return"string"==typeof t?t:e.id},"groupIdOf"),cj=__name(e=>e.replace(/^(?:[^\S\n]*\n)+/,"").replace(/\s+$/,""),"stripOuterBlankLines");function findLastAssistantText(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(!n||"assistant"!==n.role)continue;if(!n.input.trim())continue;const r=lj(n),o=[];for(let n=t;n>=0;n--){const t=e[n];if(!t||"assistant"!==t.role||lj(t)!==r)break;const s=cj(t.input);s&&o.unshift(s)}return o.length>1?o.join("\n\n"):n.input}return null}async function handleCopy({feed:e,setFeed:t}){const n=findLastAssistantText(e);if(!n)return void t(e=>[...e,uh("Nothing to copy yet — no reply in this session.")]);const r=await writeClipboardText(n),o=n.length.toLocaleString("en-US");t(e=>[...e,uh(r?`Copied the last reply to the clipboard (${o} chars).`:"Could not reach the clipboard — is this a headless terminal?")])}function getAuthKey3(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function trackFirstMessage(){(async()=>{await getAuthKey3()&&await detectAndTrackFirstMessage({loadUserConfig:loadUserConfig,updateUserConfig:updateUserConfig,trackLifecycleEvent:__name(e=>trackLifecycleEvent({...e,isTelemetryEnabled:isTelemetryEnabled,createClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createClient"),log:dlog}),"trackLifecycleEvent"),log:dlog})})().catch(()=>{})}function isWhitespaceOnly3(e){return 0===e.trim().length}function routeTodoWriteEntry(e){const{entry:t,setFeed:n,setLiveEntries:r}=e;if("running"===t.metadata?.status)return!0;const o="output"in t?t.output:void 0,s="string"==typeof o?Nh(o):null;if(!s)return!1;const i=projectUserEdits(s);return i.every(e=>"completed"===e.status)?(clearSessionTodos(),i.length>0&&routeHarnessFeedEntry({entry:{...t,output:JSON.stringify(i)},setFeed:n,setLiveEntries:r}),!0):(setSessionTodos(s),!0)}function createBlockCommittingRouter(e){const{setFeed:t,setLiveEntries:n}=e,r=new Map;function buildBlockEntries(e,t,n){const r=[];for(const o of n){if(isWhitespaceOnly3(o))continue;const n=t.committedEntryCount;t.committedEntryCount+=1;const{status:s,...i}=e.metadata??{};r.push({...e,id:`${e.id}-block-${n}`,input:o,metadata:{...i,continuation:n>0,blockOf:e.id}})}return r}function routeRunningAssistant(e){let o=r.get(e.id);o||(o={stream:createBlockStream(),committedEntryCount:0},r.set(e.id,o));const s=o.stream.advance(e.input),i=buildBlockEntries(e,o,s.newlyCompleted);i.length>0&&t(e=>[...e,...i]);const a={...e,input:s.openTail,metadata:{...e.metadata,continuation:o.committedEntryCount>0}};n(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1===n)return[...t,a];const r=[...t];return r[n]=a,r})}function routeFinalAssistant(e){n(t=>t.filter(t=>t.id!==e.id));const o=r.get(e.id);if(!o)return void(isWhitespaceOnly3(e.input)||t(t=>[...t,e]));r.delete(e.id);const s=o.stream.finalize(e.input);if(0===o.committedEntryCount&&s.remaining.length<=1)return void(isWhitespaceOnly3(e.input)||t(t=>[...t,e]));const i=buildBlockEntries(e,o,s.remaining);i.length>0&&t(e=>[...e,...i])}return __name(buildBlockEntries,"buildBlockEntries"),__name(routeRunningAssistant,"routeRunningAssistant"),__name(routeFinalAssistant,"routeFinalAssistant"),__name(function routeEntry(e){if(isDiscardedEntry(e))return r.delete(e.id),void routeHarnessFeedEntry({entry:e,setFeed:t,setLiveEntries:n});if("assistant"===e.role)"running"!==e.metadata?.status?routeFinalAssistant(e):routeRunningAssistant(e);else{if("tool"===e.role&&"todo_write"===e.name&&routeTodoWriteEntry({entry:e,setFeed:t,setLiveEntries:n}))return;routeHarnessFeedEntry({entry:e,setFeed:t,setLiveEntries:n})}},"routeEntry")}async function getBillingLink({billingLink:e,setBillingLink:t}){return resolveCommandBillingLink({existingBillingLink:e,client:createApiClient({baseUrl:getApiBaseUrl()}),onResolvedBillingLink:t})}async function runModInputInterception(e){const t=getActiveModHost();if(!t||"user"!==e.role||e.isAutomated||e.isMeta||e.isGoalContinuation||0===e.input.length||(e.images?.length??0)>0)return{action:"continue"};try{return await t.transformInput({text:e.input})}catch{return{action:"continue"}}}async function handleSubmit(e){const{role:t,input:n,images:r,imageTokenPaths:o,ideContext:s,ideHint:i,displayMessage:a,isAutomated:l,isMeta:c,source:d,hiddenMessages:u,isGoalContinuation:m,isGoalBootstrap:p,suppressUserEcho:g,feed:h,setFeed:f,setLiveEntries:y,isCmdCodeBusy:S,setIsCmdCodeBusy:w,setQueuedMessages:v,setStatus:k,setInteractionTokens:C,updateStatus:b,setUpdateStatus:E,billingLink:T,setBillingLink:P,currentModel:M,currentProvider:x,premiumCreditsExhausted:I,setPremiumCreditsExhausted:A,setCurrentModel:R,sessionId:L,isSubmittingRef:O,setInput:D,setStaticKey:$,executeBash:N}=e,_=resolveSubmitStartPlan({role:t,input:n,isCmdCodeBusy:S,isSubmitting:O.current,displayMessage:a,isAutomated:l,isMeta:c,source:d,hiddenMessages:u,images:r,ideContext:s,ideHint:i});if("skip"===_.kind&&!n.length)return _.outcome;if(b&&E(null),C(0),"skip"===_.kind)return _.outcome;if("bash"===_.kind){O.current=!0;const e=hh(n);return f([...h,e]),D(""),await N(n,e=>{f(e)},()=>{RL(),$(e=>e+1)}),O.current=!1,"completed"}if("queue"===_.kind)return v(e=>[...e,_.queuedMessage]),l||D(""),_.outcome;O.current=!0;const F=await runModInputInterception(e);if("handled"===F.action){O.current=!1;const e=F.message;return e&&f(t=>[...t,uh(e)]),"skipped"}const U="transform"===F.action?F.text:n;await loadCustomProviderModels();const j=await checkOAuthSetupRequired({currentProvider:x??null,isByokModel:isByok({model:M??""}),providerAuthHeaders:providerAuthHeaders});if(j)return O.current=!1,k(j),f(e=>[...e,yh(j)]),"skipped";w(!0),k(xh()),l||D("");let B=!1,W=null,H=null,G=null,V=0;const z=createSubmitGoalSupervisor(e);let K=null;const q=resolvePremiumCreditsPreflight({premiumCreditsExhausted:I,currentModel:M});if(q.blocked)return B=!0,k(q.status),f(e=>[...e,uh(q.message)]),w(!1),O.current=!1,q.outcome;try{K=await z.getGoalTurnBudget();const e=await v$({sessionId:L,baseUrl:getApiBaseUrl()});if(p&&!isCommandGoalLoopArmed(L))return"skipped";const t=clipboardImagesToUserContent(r),n=s?`${s}\n\n${U}`:U,l=t.length>0?[...t,{type:"text",text:n}]:s?[{type:"text",text:n}]:void 0,c={...r&&r.length>0?{images:r,...o?{imageTokenPaths:o}:{}}:{},...i?{ideHint:i}:{}};trackFirstMessage();const d=await runHarnessTurnIntoFeed({harness:e,input:U,turnUserInput:l,runQuery:runHarnessQuery,setFeed:f,setLiveEntries:y,displayMessage:a,suppressUserEcho:g,additionalContent:hiddenMessagesToUserContent(u),inputMeta:_.inputMeta,maxTurns:K?.remainingTurns,onRoundTrip:__name(e=>{V=e},"onRoundTrip"),echoMetadata:Object.keys(c).length>0?c:void 0,setStatus:k,onInteractionTokens:C,onRunError:__name(e=>{H=e},"onRunError"),routeEntry:createBlockCommittingRouter({setFeed:f,setLiveEntries:y}),scrubGoalCompleteMarker:isCommandGoalLoopArmed(L)});if(H){const e=M?byokProviderId({model:M}):void 0;throw formatRunError(H,e?{byokProvider:e}:void 0)}return G=d.finalText,V=d.turnCount,"completed"}catch(e){const t=resolveSubmitErrorAction({error:e,sessionId:L});if("interrupted"===t.kind)return B=!0,t.outcome;if(trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"submit_error"}),context:{component:Ho.SUBMIT,heading:"Prompt submission failed",code:t.kind}}),B=!0,W=t.goalErrorKind,"insufficient-credits"===t.kind){k(t.status);const e=await getBillingLink({billingLink:T,setBillingLink:P});return f(t=>[...t,yh(buildInsufficientCreditsSubmitActionMessage({billingUrl:e}))]),t.outcome}if("premium-credits-exhausted"===t.kind)return A?.(!0),R?.(t.fallbackModelId),RL(),$(e=>e+1),k(t.status),f(e=>[...e,uh(t.message)]),t.outcome;k(t.status);const n="info"===t.renderKind?uh(t.message):yh(t.message);return f(e=>[...e,n]),t.outcome}finally{w(!1),B||k("Ready..."),O.current=!1,await z.afterTurn({assistantText:B?null:G,errorKind:B?W:null,isGoalContinuation:m,turnsUsed:V,goalStartedAt:K?.startedAt})}return"skipped"}function emitGoalNotice(e,t){e(e=>[...e,uh(t.message,buildGoalNoticeMetadata(t))])}function createSubmitGoalSupervisor(e){const{sessionId:t,setFeed:n}=e;return createGoalTurnSupervisor({sessionId:t,isArmed:__name(()=>isCommandGoalLoopArmed(t),"isArmed"),disarm:__name(()=>disarmCommandGoalLoop(t),"disarm"),loadSessionMeta:__name(()=>loadCommandSessionMeta({sessionId:t}),"loadSessionMeta"),saveGoal:__name(e=>saveCommandSessionMeta({sessionId:t,meta:{goal:e}}),"saveGoal"),verifyCompletion:__name(async e=>(k$(t)??await v$({sessionId:t,baseUrl:getApiBaseUrl()})).verifyGoal(e),"verifyCompletion"),getEvidence:__name(()=>{const e=k$(t);return e?harnessRecentToolEvidence(e):""},"getEvidence"),emitCompletion:__name(e=>{n(t=>[...t,uh("",e)])},"emitCompletion"),emitNotice:__name(e=>emitGoalNotice(n,e),"emitNotice"),runContinuation:__name(({prompt:t})=>handleSubmit({...e,...buildGoalContinuationTurnFields({prompt:t})}),"runContinuation")})}async function handleDesignCommand({ctx:e,rawArguments:t,positionalArgs:n,command:r}){try{const o=await resolveDesignCommand({runtime:createNodeRuntime(),rawArguments:t,positionalArgs:n});if("help"===o.status)return void e.setShowDesignGuide(!0);if("missing-skill"===o.status)return void e.setFeed(e=>[...e,yh(GC)]);const s=await handleSubmit({input:o.command.visible,hiddenMessages:[{role:"user",content:o.command.hidden}],role:"user",displayMessage:r,isAutomated:!0,feed:e.feed,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,setQueuedMessages:e.setQueuedMessages,setStatus:e.setStatus,setInteractionTokens:e.setInteractionTokens,updateStatus:e.updateStatus,setUpdateStatus:e.setUpdateStatus,billingLink:e.billingLink,setBillingLink:e.setBillingLink,currentModel:e.currentModel,currentProvider:e.currentProvider,premiumCreditsExhausted:e.premiumCreditsExhausted,setPremiumCreditsExhausted:e.setPremiumCreditsExhausted,setCurrentModel:e.setCurrentModel,sessionId:e.sessionId,isSubmittingRef:e.isSubmittingRef,setInput:e.setInput,setStaticKey:e.setStaticKey,executeBash:e.executeBash}),{modeName:i}=o.command;if("completed"===s&&i&&isDesignMode(i)){const t=getDesignModeSuggestions(i);t&&e.setPendingDesignSuggestion?.(t)}}catch(t){e.setFeed(e=>[...e,yh(buildDesignSkillLoadErrorMessage(t))])}}__name(findLastAssistantText,"findLastAssistantText"),__name(handleCopy,"handleCopy"),Gt(),SR(),Gt(),SR(),Gt(),SR(),__name(getAuthKey3,"getAuthKey"),__name(trackFirstMessage,"trackFirstMessage"),Gt(),SR(),__name(isWhitespaceOnly3,"isWhitespaceOnly"),__name(routeTodoWriteEntry,"routeTodoWriteEntry"),__name(createBlockCommittingRouter,"createBlockCommittingRouter"),__name(getBillingLink,"getBillingLink"),__name(runModInputInterception,"runModInputInterception"),__name(handleSubmit,"handleSubmit"),__name(emitGoalNotice,"emitGoalNotice"),__name(createSubmitGoalSupervisor,"createSubmitGoalSupervisor"),__name(handleDesignCommand,"handleDesignCommand"),Gt(),SR();var dj="Nothing to export yet — the transcript is created on the first message.",uj=new Set(["html","jsonl","md"]);function matchFormatKeyword(e){const t=e.toLowerCase();return uj.has(t)?t:void 0}function resolveConfiguredExportFormat(e){return e?matchFormatKeyword(e)??"html":"html"}function defaultExportFilename(e,t){return`command-code-session-${e.slice(0,8)}.${t}`}function resolveExportRoute(e){const t=e.rawPath.trim();if(!t){const t=e.defaultFormat??"html";return{kind:"target",format:t,path:n(e.cwd,defaultExportFilename(e.sessionId,t))}}const r=matchFormatKeyword(t);if(r)return{kind:"target",format:r,path:n(e.cwd,defaultExportFilename(e.sessionId,r))};const o=a(t)?t:s(e.cwd,t);if(A(o)&&N(o).isDirectory())return{kind:"target",format:"html",path:n(o,defaultExportFilename(e.sessionId,"html"))};const i=d(o).toLowerCase();return i?".html"===i?{kind:"target",format:"html",path:o}:".jsonl"===i?{kind:"target",format:"jsonl",path:o}:".md"===i?{kind:"target",format:"md",path:o}:{kind:"unknown-extension",extension:i}:{kind:"target",format:"html",path:n(o,defaultExportFilename(e.sessionId,"html"))}}function exportedMessage(e){const t=toRelativePath(e.path),n=At.isSupported?createOSC8Link(fileUrl(e.path),t,!1):t;return`Exported ${e.formatLabel} session to ${n}`}async function buildSessionHtmlExport(e){const{messages:t}=await loadCommandSessionMessages({sessionId:e.sessionId});if(0===t.length)return null;const n=await loadCommandUserRenamedTitle({sessionId:e.sessionId})??e.sessionId;return renderSessionHtml({messages:fromV2(t.map(e=>e.message)),title:n,sessionId:e.sessionId,exportedAt:(new Date).toISOString(),...e.currentModel?{model:e.currentModel}:{}})}async function buildSessionMarkdownExport(e){const{messages:t}=await loadCommandSessionMessages({sessionId:e.sessionId});if(0===t.length)return null;const n=await loadCommandUserRenamedTitle({sessionId:e.sessionId})??e.sessionId;return renderSessionMarkdown({messages:fromV2(t.map(e=>e.message)),title:n,sessionId:e.sessionId,exportedAt:(new Date).toISOString(),...e.currentModel?{model:e.currentModel}:{}})}async function exportJsonl(e){const t=n(getProjectSessionDir({env:process.env,cwd:e.cwd}),`${e.sessionId}.jsonl`);if(A(t)){try{U(t,e.target)}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,uh(`Export failed: ${n}`)])}e.setFeed(t=>[...t,uh(exportedMessage({path:e.target,formatLabel:"JSONL"}))])}else e.setFeed(e=>[...e,uh(dj)])}async function exportHtml(e){let t;try{t=await buildSessionHtmlExport({sessionId:e.sessionId,currentModel:e.currentModel})}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,uh(`Export failed: ${n}`)])}if(t){try{O(e.target,t,"utf8")}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,uh(`Export failed: ${n}`)])}e.setFeed(t=>[...t,uh(exportedMessage({path:e.target,formatLabel:"HTML"}))])}else e.setFeed(e=>[...e,uh(dj)])}async function exportMarkdown(e){let t;try{t=await buildSessionMarkdownExport({sessionId:e.sessionId,currentModel:e.currentModel})}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,uh(`Export failed: ${n}`)])}if(t){try{O(e.target,t,"utf8")}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,uh(`Export failed: ${n}`)])}e.setFeed(t=>[...t,uh(exportedMessage({path:e.target,formatLabel:"Markdown"}))])}else e.setFeed(e=>[...e,uh(dj)])}async function handleExport(e){const t=getCurrentWorkingDirectory(),n=await loadUserConfig(),r=resolveExportRoute({rawPath:e.rawPath,cwd:t,sessionId:e.sessionId,defaultFormat:resolveConfiguredExportFormat(n.defaultExportFormat)});"unknown-extension"!==r.kind?"jsonl"!==r.format?"md"!==r.format?await exportHtml({sessionId:e.sessionId,target:r.path,currentModel:e.currentModel,setFeed:e.setFeed}):await exportMarkdown({sessionId:e.sessionId,target:r.path,currentModel:e.currentModel,setFeed:e.setFeed}):await exportJsonl({sessionId:e.sessionId,target:r.path,cwd:t,setFeed:e.setFeed}):e.setFeed(e=>[...e,uh(`Unknown export extension "${r.extension}". Supported export formats: .html, .jsonl, .md`)])}async function handleForkCommand(e,t){const n=k$(e.sessionId),r=await resolveForkCommand({sourceId:e.sessionId,rawName:t,hasActiveSession:Boolean(n),messageCount:n?harnessSessionMessages(n).length:0});if("notice"!==r.kind)try{await handleSelectSession({selectedSessionId:r.newId,previousSessionId:e.sessionId,sessionLoadIdRef:e.sessionLoadIdRef,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setSessionId:e.setSessionId,setShowSessionSelector:e.setShowSessionSelector,setSessionLoaded:e.setSessionLoaded,setStaticKey:e.setStaticKey,setShareInfo:e.setShareInfo,setCurrentModel:e.setCurrentModel,inTuiResume:!0}),e.setFeed(e=>[...e,mh({name:r.title})])}catch{e.setFeed(e=>[...e,yh($f)])}else e.setFeed(e=>[...e,"error"===r.notice.kind?yh(r.notice.message):uh(r.notice.message)])}function setMode(e,t){e.permissionModeRef.current=t,e.setPermissionMode(t),k$(e.sessionId)?.setPermissionMode({mode:t})}async function handlePlanCommand({rawArguments:e,ctx:t}){const n=resolvePlanCommand({rawArguments:e,currentMode:t.permissionModeRef.current});if(t.permissionModeRef.current!==n.nextMode&&setMode(t,n.nextMode),"notice"===n.kind)return t.setFeed(e=>[...e,uh(n.message)]),void(n.clearInput&&t.setInput(""));await handleSubmit({input:n.task,role:"user",displayMessage:n.displayMessage,isAutomated:!0,feed:t.feed,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,currentModel:t.currentModel,currentProvider:t.currentProvider,premiumCreditsExhausted:t.premiumCreditsExhausted,setPremiumCreditsExhausted:t.setPremiumCreditsExhausted,setCurrentModel:t.setCurrentModel,sessionId:t.sessionId,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash})}__name(matchFormatKeyword,"matchFormatKeyword"),__name(resolveConfiguredExportFormat,"resolveConfiguredExportFormat"),__name(defaultExportFilename,"defaultExportFilename"),__name(resolveExportRoute,"resolveExportRoute"),__name(exportedMessage,"exportedMessage"),__name(buildSessionHtmlExport,"buildSessionHtmlExport"),__name(buildSessionMarkdownExport,"buildSessionMarkdownExport"),__name(exportJsonl,"exportJsonl"),__name(exportHtml,"exportHtml"),__name(exportMarkdown,"exportMarkdown"),__name(handleExport,"handleExport"),Gt(),SR(),__name(handleForkCommand,"handleForkCommand"),Gt(),SR(),__name(setMode,"setMode"),__name(handlePlanCommand,"handlePlanCommand"),Gt(),SR();var mj=[{title:"Composing",rows:[{keys:"Enter",action:"Send the prompt"},{keys:"Shift+Enter / Alt+Enter",action:"Insert a newline"},{keys:"Ctrl+G",action:"Edit the prompt in $EDITOR"},{keys:"Ctrl+S",action:"Stash / restore the current prompt"},{keys:"↑ / ↓",action:"Browse prompt history"},{keys:"@",action:"Mention a file (fuzzy search)"},{keys:"/",action:"Open the command menu"},{keys:"!",action:"Bash mode — run a shell command"}]},{title:"While it works",rows:[{keys:"Esc",action:"Interrupt the current turn"},{keys:"Type + Enter",action:"Queue a steering message"},{keys:"Ctrl+X",action:"Open the todo manager (/todos) for the current plan"}]},{title:"Transcript",rows:[{keys:"Ctrl+O",action:"Toggle expanded tool output"},{keys:"Ctrl+E / Ctrl+Y",action:"Toggle the full transcript"}]},{title:"Session & modes",rows:[{keys:"Shift+Tab",action:"Cycle mode: standard → accept edits → plan → yolo"},{keys:"Alt+P",action:"Quick model switch"},{keys:"Esc Esc",action:"Rewind to a checkpoint"},{keys:"Ctrl+C Ctrl+C",action:"Exit"}]}];function buildHotkeysMarkdown(){const e=["**Keyboard shortcuts**"];for(const t of mj){e.push("",`**${t.title}**`);for(const n of t.rows)e.push(`- \`${n.keys}\` — ${n.action}`)}return e.join("\n")}function handleHotkeys({setFeed:e}){e(e=>[...e,fh(buildHotkeysMarkdown())])}async function handleImportCommand({setFeed:e},t=""){const n=resolveAgentImportSourceArg(t);if(!n.ok)return void e(e=>[...e,yh(n.message)]);const r=createNodeRuntime();try{const t=await detectAgentImport({runtime:r,sources:n.sources});if(0===t.items.length&&0===t.sourceErrors.length)return void e(e=>[...e,uh("No setup was found to import (looked for Claude Code, Codex, Cursor, Pi, OpenCode, and Gemini CLI config in your home directory and this project).")]);const o=await importAgentSetup({runtime:r,inventory:t});e(e=>[...e,uh(formatAgentImportSummary(o))])}catch(t){e(e=>[...e,yh(`Import failed: ${t instanceof Error?t.message:"unknown error"}`)])}}function setMode2(e,t){e.permissionModeRef.current=t,e.setPermissionMode(t),k$(e.sessionId)?.setPermissionMode({mode:t})}async function handleModeCommand({rawArguments:e,ctx:t}){const n=resolveModeCommand({rawArguments:e,currentMode:t.permissionModeRef.current});n.nextMode&&setMode2(t,n.nextMode),t.setFeed(e=>[...e,uh(n.message)]),t.setInput("")}async function applyRenameResult(e){const t=await resolveRenameCommand({name:e.name,sessionId:e.sessionId});if(e.setFeed(e=>[...e,"error"===t.notice.kind?yh(t.notice.message):uh(t.notice.message)]),"renamed"===t.kind){e.setRenamedTerminalTitle(t.name);try{(e.harness??await v$({sessionId:e.sessionId,baseUrl:getApiBaseUrl()})).setSessionName(t.name)}catch{}}}async function autoRenameSession({sessionId:e,setFeed:t,setRenamedTerminalTitle:n,setStatus:r,setIsCmdCodeBusy:o}){o(!0),r("Naming session…");try{const r=await v$({sessionId:e,baseUrl:getApiBaseUrl()}),o=await r.regenerateTitle();if(!o)return void t(e=>[...e,uh("Nothing to name yet — send a message first, or use /rename <name>.")]);await applyRenameResult({name:o,sessionId:e,setFeed:t,setRenamedTerminalTitle:n,harness:r})}catch{t(e=>[...e,uh("Could not generate a title. Try /rename <name> instead.")])}finally{o(!1),r("Ready...")}}async function handleRenameCommand(e){e.name.trim()?await applyRenameResult({name:e.name,sessionId:e.sessionId,setFeed:e.setFeed,setRenamedTerminalTitle:e.setRenamedTerminalTitle}):await autoRenameSession(e)}async function handleNameCommand(e){if(e.name.trim())return void await applyRenameResult({name:e.name,sessionId:e.sessionId,setFeed:e.setFeed,setRenamedTerminalTitle:e.setRenamedTerminalTitle});const t=k$(e.sessionId)?.getSessionStats().name,n=t?null:await loadCommandSessionMeta({sessionId:e.sessionId}).catch(()=>null),r=t??n?.title;e.setFeed(e=>[...e,uh(r?`Current name: ${r}`:"This session has no name yet. Use /name <name> to set one.")])}function handleRewindCommand({sessionId:e,setFeed:t,setShowRewindSelector:n}){const r=k$(e),o=resolveRewindCommand({hasActiveConversation:Boolean(r),checkpointCount:r?.listCheckpoints().length??0});"notice"!==o.kind?n(!0):t(e=>[...e,"error"===o.notice.kind?yh(o.notice.message):uh(o.notice.message)])}async function handleRewindSelect({messageId:e,mode:t,sessionId:n,setFeed:r,setStatus:o,setShowRewindSelector:s,setStaticKey:i,setInput:a}){s(!1);const l=k$(n);if(!l)return;o("Restoring checkpoint...");const c=await performRewindRestore({harness:l,messageId:e,mode:t});if("restored"===c.kind)return r(c.feed),l.applyTodoUserEdit({todos:seedTodosFromFeedEntries(c.feed)}),RL(),i(e=>e+1),c.promptToRestore&&a(c.promptToRestore),r(e=>[...e,uh(c.notice.message)]),void o(c.statusMessage);r(e=>[...e,"error"===c.notice.kind?yh(c.notice.message):uh(c.notice.message)]),o(c.statusMessage)}function handleRewindCancel({setShowRewindSelector:e}){e(!1)}function compactTranscriptPath(e){return`${toRelativePath(getProjectsBasePath({env:process.env}))}/…/${c(e)}`}function formatSessionFileLine(e){const{absolutePath:t,exists:n,linksSupported:r}=e;return n?r?createOSC8Link(fileUrl(t),compactTranscriptPath(t),!1):t:`${t} (not created yet)`}function handleSessionFile({sessionId:e,setFeed:t}){if(!e)return void t(e=>[...e,uh("No active session.")]);const r=n(getProjectSessionDir({env:process.env,cwd:getCurrentWorkingDirectory()}),`${e}.jsonl`),o=formatSessionFileLine({absolutePath:r,exists:A(r),linksSupported:At.isSupported});t(t=>[...t,uh(`Session ID: ${e}\nCurrent session file: ${r}`,{isSessionFile:!0,sessionFileId:e,sessionFileLine:o})])}__name(buildHotkeysMarkdown,"buildHotkeysMarkdown"),__name(handleHotkeys,"handleHotkeys"),Gt(),SR(),__name(handleImportCommand,"handleImportCommand"),Gt(),SR(),__name(setMode2,"setMode"),__name(handleModeCommand,"handleModeCommand"),Gt(),SR(),__name(applyRenameResult,"applyRenameResult"),__name(autoRenameSession,"autoRenameSession"),__name(handleRenameCommand,"handleRenameCommand"),__name(handleNameCommand,"handleNameCommand"),Gt(),SR(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),Gt(),SR(),__name(compactTranscriptPath,"compactTranscriptPath"),__name(formatSessionFileLine,"formatSessionFileLine"),__name(handleSessionFile,"handleSessionFile"),Gt(),SR();var pj=Me(f),gj=/https:\/\/gist\.github\.com\/\S+/;function parseGistUrl(e){const t=gj.exec(e);return t?t[0]:null}function execErrorText(e){if(!(e instanceof Error))return String(e);const t=e;return("string"==typeof t.stderr?t.stderr.trim():"")||e.message}async function defaultCreateGist(e){const{stdout:t}=await pj("gh",["gist","create",e,"--desc","Command Code session"],{encoding:"utf8"});return{stdout:String(t)}}async function resolveShareGistFormat(e){const t=(e??"").trim();return t?matchFormatKeyword(t):resolveConfiguredExportFormat((await loadUserConfig()).defaultShareGistFormat)}async function writeGistPayload(e){const t=n(e.tempDir,`command-code-session-${e.sessionId.slice(0,8)}.${e.format}`);if("jsonl"===e.format){const r=n(getProjectSessionDir({env:process.env,cwd:getCurrentWorkingDirectory()}),`${e.sessionId}.jsonl`);return A(r)?(U(r,t),t):null}if("md"===e.format){const n=await e.buildMarkdownExport({sessionId:e.sessionId,currentModel:e.currentModel});return n?(await K(t,n,"utf8"),t):null}const r=await e.buildHtmlExport({sessionId:e.sessionId,currentModel:e.currentModel});return r?(await K(t,r,"utf8"),t):null}async function handleShareGistCommand(e){const{isCommandAvailable:t=isCommandAvailable,buildHtmlExport:r=buildSessionHtmlExport,buildMarkdownExport:o=buildSessionMarkdownExport,createGist:s=defaultCreateGist,writeClipboardText:i=writeClipboardText}=e.deps??{},a=__name(t=>e.setFeed(e=>[...e,uh(t)]),"info");if(!t("gh"))return void a("Requires the GitHub CLI (gh) — https://cli.github.com");const l=await resolveShareGistFormat(e.rawFormatArg);if(!l)return void a(`Unknown gist format "${(e.rawFormatArg??"").trim()}". Supported gist formats: html, jsonl, md`);let c;try{c=await ae(n(H(),"cmd-share-"));const t=await writeGistPayload({format:l,sessionId:e.sessionId,currentModel:e.currentModel,tempDir:c,buildHtmlExport:r,buildMarkdownExport:o});if(!t)return void a("Nothing to share yet — the transcript is created on the first message.");const{stdout:d}=await s(t),u=parseGistUrl(d);if(!u)return void a(`gh gist create did not return a URL: ${d.trim()}`);await i(u),a(`Shared session gist: ${At.isSupported?createOSC8Link(u,u,!1):u}`)}catch(e){const t=execErrorText(e);a(/auth/i.test(t)?`${t} — run gh auth login`:`Share failed: ${t}`)}finally{c&&await X(c,{recursive:!0,force:!0}).catch(()=>{})}}async function copyOrFallback(e,t){return!!await writeClipboardText(e)||(t(buildShareClipboardFallbackStatus(e)),!1)}async function handleShareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setShowShareNotification:o}){!t&&e&&r("Creating share link...");const s=createApiClient({baseUrl:getApiBaseUrl()}),i=await createCommandSessionShareLink({client:s,sessionId:e,existingShareInfo:t,harness:e?k$(e):void 0,projectRoot:global.COMMAND_CODE_CWD||process.cwd()});"no-session"!==i.status&&"error"!==i.status?(n(i.shareInfo),await copyOrFallback(i.shareInfo.url,r)&&(r(""),o(!0),setTimeout(()=>{o(!1)},shareNotificationDurationMs(i.status)))):r(i.message)}async function handleUnshareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setUnshareNotificationMessage:o}){e&&t&&r("Removing share link...");const s=createApiClient({baseUrl:getApiBaseUrl()}),i=await deleteCommandSessionShareLink({client:s,sessionId:e,shareInfo:t,harness:e?k$(e):void 0});if("no-session"!==i.status){if("not-shared"===i.status)return o(i.message),void setTimeout(()=>o(""),mC);if("error"===i.status)return r(i.message),void setTimeout(()=>r(""),mC);o(i.message),r(""),n(null),setTimeout(()=>{o("")},mC)}else r(i.message)}async function loadPersistedTraceIds(e){if(e.loadTraceIds)return e.loadTraceIds();if(!e.sessionId)return[];const t=await loadCommandSessionMeta({sessionId:e.sessionId}).catch(()=>null),n=t?.traceIds;return Array.isArray(n)?n.filter(e=>"string"==typeof e&&e.length>0):[]}async function handleTrace({setFeed:e,sessionId:t,loadTraceIds:n}){const r=getTraceId();if(r){const t=await writeClipboardText(r)?" (copied to clipboard)":"";return void e(e=>[...e,uh(`Trace ID: ${r}${t}`)])}const o=await loadPersistedTraceIds({sessionId:t,loadTraceIds:n});if(o.length>0){const t=o[o.length-1],n=await writeClipboardText(t)?" (copied to clipboard)":"";return void e(e=>[...e,uh(`Trace ID: ${t}${n}`)])}const s=isTelemetryInitialized()?"Trace ID not generated: Send a message first":"No trace ID — request tracing is off this session.";e(e=>[...e,uh(s)])}function actionErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}async function handleTreeCommand({sessionId:e,setFeed:t,setShowTreeSelector:n,setTreeFilterMode:r,setTreeBranchSummarySkipPrompt:o}){const s=k$(e),i=resolveTreeCommand({hasActiveConversation:Boolean(s),treeEntryCount:s?.getSessionTree().length??0});if("notice"===i.kind)return void t(e=>[...e,"error"===i.notice.kind?yh(i.notice.message):uh(i.notice.message)]);const[a,l]=await Promise.all([getTreeFilterMode(),getBranchSummarySkipPrompt()]);r(a),o(l),n(!0)}async function handleTreeSelect({entryId:e,summarize:t,customInstructions:n,sessionId:r,setFeed:o,setShowTreeSelector:s,setStaticKey:i,setInput:a}){const l=k$(r);if(!l)return{aborted:!1};try{const r=await l.navigateTree({targetId:e,summarize:t,...n?{customInstructions:n}:{}});return r.aborted?{aborted:!0}:r.cancelled?(o(e=>[...e,uh("Already at this point")]),{aborted:!1}):(s(!1),o(reconstructFeedFromMessages(harnessSessionMessages(l))),RL(),i(e=>e+1),r.editorText&&a(r.editorText),o(e=>[...e,uh("Navigated to selected point")]),{aborted:!1})}catch(e){return o(t=>[...t,yh(`Failed to navigate: ${actionErrorMessage(e)}`)]),{aborted:!1}}}function handleTreeCancel({setShowTreeSelector:e}){e(!1)}function handleTreeAbortSummary({sessionId:e}){k$(e)?.abortBranchSummary()}function handleTreeLabel({entryId:e,label:t,sessionId:n,setFeed:r}){const o=k$(n);if(o)try{o.setTreeLabel({targetId:e,label:t})}catch(e){r(t=>[...t,yh(`Failed to set label: ${actionErrorMessage(e)}`)])}}function announceCompletedUpdate({fromVersion:e,toVersion:t}){console.log(Et.green(`Updated ${e} → ${t}`))}function trackUpdateFailure({fromVersion:e,targetVersion:t,trigger:n,userName:r,failureReason:o}){trackError({error:new Error(`Update failed: ${e} -> ${t}${o?`: ${o}`:""}`),context:{component:Ho.UPDATER,heading:"CLI update failed (atomic + fallback)","cmd.update.from_version":e,"cmd.update.target_version":t,"cmd.update.trigger":n,...o&&{"cmd.update.failure_reason":o},...r&&{"user.name":r}}})}__name(parseGistUrl,"parseGistUrl"),__name(execErrorText,"execErrorText"),__name(defaultCreateGist,"defaultCreateGist"),__name(resolveShareGistFormat,"resolveShareGistFormat"),__name(writeGistPayload,"writeGistPayload"),__name(handleShareGistCommand,"handleShareGistCommand"),__name(copyOrFallback,"copyOrFallback"),__name(handleShareCommand,"handleShareCommand"),__name(handleUnshareCommand,"handleUnshareCommand"),Gt(),SR(),__name(loadPersistedTraceIds,"loadPersistedTraceIds"),__name(handleTrace,"handleTrace"),Gt(),SR(),__name(actionErrorMessage,"actionErrorMessage"),__name(handleTreeCommand,"handleTreeCommand"),__name(handleTreeSelect,"handleTreeSelect"),__name(handleTreeCancel,"handleTreeCancel"),__name(handleTreeAbortSummary,"handleTreeAbortSummary"),__name(handleTreeLabel,"handleTreeLabel"),Gt(),SR(),Gt(),SR(),__name(announceCompletedUpdate,"announceCompletedUpdate"),__name(trackUpdateFailure,"trackUpdateFailure");var hj={createLifecycleEventClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createLifecycleEventClient"),isTelemetryEnabled:isTelemetryEnabled,log:dlog,onCompletedUpdate:announceCompletedUpdate,trackUpdateFailure:trackUpdateFailure},fj={updatedVersionThisSession:null};async function handleUpdateCommand({setFeed:e,setStatus:t,setIsCmdCodeBusy:n,setUpdateStatus:r,pinnedStatusRef:o}){const s=__name(e=>{"busy"===e.type&&n(e.value),"pin-status"===e.type&&(o.current=e.value),"status"===e.type&&t(e.value),"update-status"===e.type&&r(e.value)},"emit"),i=await runTuiUpdateCommand({state:fj,host:hj,copy:{binCommand:`${getBinaryCommand()}`,updateCommand:"npm i -g command-code"},emit:s});trackTuiUpdateCommandTelemetry(i),"error"!==i.level?e(e=>[...e,uh(i.message,i.metadata)]):e(e=>[...e,yh(i.message)])}function tildeHome(e){const t=B.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function formatWorktreePathLine(e){return` ${ht.dim(gt.arrowRight)} ${createOSC8Link(fileUrl(e),tildeHome(e))}`}function enterWorktreeFromFlag(e,t={}){const{quiet:n=!1,track:r=!0}=t,o=process.cwd();if(!isGitRepo(o))return{ok:!1,error:"--worktree requires a git repository (none found here)."};const s=getMainWorktreeRoot(o)??o,i=createWorktree({spec:"string"==typeof e?e.trim():void 0,cwd:o});if(!i.ok)return{ok:!1,error:i.error};try{process.chdir(i.target.worktreePath),global.COMMAND_CODE_CWD=i.target.worktreePath}catch(e){return{ok:!1,error:`couldn't enter worktree: ${e instanceof Error?e.message:String(e)}`}}if(r&&i.created&&markAutoCreatedWorktree({worktreePath:i.target.worktreePath,branch:i.target.branch,baseSha:i.baseSha,mainRoot:s}),!n){const e=i.created?"Created":"Entered",t=i.created?ht.dim(` (branch ${i.target.branch}${i.usedRemote?", from origin":""})`):"",n=i.created&&i.copiedFiles>0?ht.dim(` · copied ${i.copiedFiles} file(s)`):"",r=i.created&&i.copyFailedFiles.length>0?ht.dim(` · ${i.copyFailedFiles.length} include copy failure(s)`):"";process.stdout.write(`${ht.cyan(gt.squareSmallFilled)} ${e} worktree ${ht.bold(i.target.name)}${t}${n}${r}\n${formatWorktreePathLine(i.target.worktreePath)}\n`)}return dlog(`[worktree] entered ${i.target.worktreePath} (created=${i.created})`),{ok:!0,name:i.target.name,path:i.target.worktreePath}}__name(handleUpdateCommand,"handleUpdateCommand"),Gt(),SR(),Gt(),SR(),__name(tildeHome,"tildeHome"),__name(formatWorktreePathLine,"formatWorktreePathLine"),__name(enterWorktreeFromFlag,"enterWorktreeFromFlag");var yj=__name((e,t)=>e.setFeed(e=>[...e,uh(t)]),"info"),Sj=__name((e,t)=>e.setFeed(e=>[...e,yh(t)]),"error");function renderList(e,n){const r=listWorktrees(e);return 0===r.length?"No worktrees found.":["Worktrees:",...r.map(r=>{const o=samePath2(r.path,e)?"●":"○",s=t.relative(n,r.path),i=r.isMain?".":s&&!s.startsWith("..")?s:tildeHome(r.path);return` ${o} ${r.isMain?`${i} (main)`:i}${r.branch?` [${r.branch}]`:" [detached]"}`}),"","Switch with /worktree <name>."].join("\n")}async function handleWorktreeCommand(e,t){const n=process.cwd();if(!isGitRepo(n))return void Sj(e,"/worktree requires a git repository.");const r=getMainWorktreeRoot(n)??n,o=t[0]?.toLowerCase();if(!o||"list"===o||"ls"===o)return void yj(e,renderList(n,r));if("remove"===o||"rm"===o){const o=t[1];return o?void await handleRemove(e,o,n,r):void Sj(e,"Usage: /worktree remove <name>")}const s="new"===o||"create"===o||"add"===o?t[1]:t[0];await handleSwitch(e,s,n)}async function handleRemove(e,n,r,o){const s=resolveTarget(n,o);if(samePath2(s.worktreePath,r))return void Sj(e,"Can't remove the worktree you're in. Switch away first, then remove it.");if(!listWorktrees(r).some(e=>samePath2(e.path,s.worktreePath)))return void Sj(e,`No worktree named "${n}".`);const i=removeWorktree({worktreePath:s.worktreePath,cwd:r,deleteBranch:isManagedWorktreePath(s.worktreePath,o)?s.branch:void 0});i.ok?yj(e,`Removed worktree "${n}".`):Sj(e,`Couldn't remove "${n}": ${i.message}. Commit or stash changes, or remove it manually with: git worktree remove --force ${t.relative(o,s.worktreePath)}`)}async function handleSwitch(e,t,n){const r=createWorktree({spec:t,cwd:n});if(!r.ok)return void Sj(e,`Couldn't create worktree: ${r.error}`);if(samePath2(r.target.worktreePath,n))return void yj(e,`Already in worktree "${r.target.name}".`);const o=r.created?"Created":"Reusing",s=r.created&&r.copiedFiles>0?` (copied ${r.copiedFiles} file(s))`:"",i=r.created&&r.copyFailedFiles.length>0?` (${r.copyFailedFiles.length} include copy failure(s))`:"";yj(e,`${o} worktree "${r.target.name}"${s}${i}. Switching… (a fresh session starts in the worktree; this one stays resumable).`),await(k$(e.sessionId)?.flush().catch(()=>{})),requestReload(buildReloadCarryoverState({sessionId:e.sessionId,permissionMode:e.permissionModeRef.current,worktree:r.target.name})),e.setShouldExit(!0)}function handleHelpCommand({setFeed:e}){e(e=>[...e,fh(Fh)])}async function handleTerminalSetupCommand({setFeed:e}){const t=dh("/terminal-setup"),n=setupVSCodeTerminal(),r=wh(n.message,!n.success,n.details),o=wh("Terminal tab titles need no setup — titles are set automatically via standard escape sequences (VS Code 1.117+ honors them out of the box).",!1),s=isKittyKeyboardActive()?[wh("Shift+Enter already works natively in this terminal (kitty keyboard protocol) — the VS Code keybindings only apply inside a VS Code-family terminal.",!1)]:[];e(e=>[...e,t,r,o,...s])}async function handleIDESetupCommand({setFeed:e}){const t=await runIdeSetup({host:oj,moduleUrl:import.meta.url}),n=vh(t.status,t.ide,t.details);e(e=>[...e,n])}async function handleClearCommand({setFeed:e,setLiveEntries:t,setQueuedMessages:n,setShareInfo:r,setShowShareNotification:o,setUnshareNotificationMessage:s,setStaticKey:i,setContextUsage:a,setInteractionTokens:l,sessionId:c,setSessionId:d,clearSessionPermissions:u}){e([]),t([]),n([]),clearSessionTodos(),clearShellTasks(),RL(),r(null),o(!1),s(""),await deleteCommandSessionShareInfo({sessionId:c}).catch(()=>{});const m=k$(c);m?.stopBackgroundLearning(),await(m?.flush().catch(()=>{})),C$(c),setNextSessionStartSource("clear"),d(crypto.randomUUID()),u(),i(e=>e+1),a(null),l(0)}async function handleInitCommand({setFeed:e}){const t=await resolveInitMemoryCommand({projectRoot:process.cwd()});e(e=>[...e,uh(t.message)])}async function runGoalTurn(e,t,n,r){await handleSubmit({role:"user",input:buildSlashCommandMessage({commandName:"/goal",skillName:"goal",rawArguments:t}),images:n,ideContext:r,suppressUserEcho:!0,persistVisibleMessage:!0,isAutomated:!0,isGoalBootstrap:!0,hiddenMessages:[{role:"user",content:buildGoalPrompt({kind:"bootstrap",goalText:t})}],feed:e.feed,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,setQueuedMessages:e.setQueuedMessages,setStatus:e.setStatus,setInteractionTokens:e.setInteractionTokens,updateStatus:e.updateStatus,setUpdateStatus:e.setUpdateStatus,billingLink:e.billingLink,setBillingLink:e.setBillingLink,currentModel:e.currentModel,currentProvider:e.currentProvider,premiumCreditsExhausted:e.premiumCreditsExhausted,setPremiumCreditsExhausted:e.setPremiumCreditsExhausted,setCurrentModel:e.setCurrentModel,sessionId:e.sessionId,isSubmittingRef:e.isSubmittingRef,setInput:e.setInput,setStaticKey:e.setStaticKey,executeBash:e.executeBash})}async function handleGoalCommand(e,t,n,r){const o=e.isSubmittingRef.current||e.isCmdCodeBusy,s=await resolveGoalSlashCommand({rawArguments:t,sessionId:e.sessionId,isSubmitting:o,permissionMode:e.permissionModeRef.current,maxTurnsOverride:getGoalMaxTurnsOverride(),loadSessionMeta:__name(async e=>await loadCommandSessionMeta(e),"loadSessionMeta"),saveSessionMeta:__name(async e=>saveCommandSessionMeta(e),"saveSessionMeta"),armGoalLoop:armCommandGoalLoop,disarmGoalLoop:disarmCommandGoalLoop,isGoalLoopArmed:isCommandGoalLoopArmed});e.setFeed(e=>[...e,uh(s.notice.message,s.notice.metadata)]),o&&"notice"===s.status&&"cleared"===s.notice.metadata?.goalNoticeKind&&k$(e.sessionId)?.requestStopAfterTurn(),"start"===s.status&&await runGoalTurn(e,s.goalText,n,r)}async function openExternalSlashCommandTarget({setFeed:e,target:t}){e(e=>[...e,uh(`Opening ${createOSC8Link(t.url,t.noticeLabel,!1)} in your browser…`)]);try{await Pt(t.url,{wait:!1,background:!0})}catch{const{fallback:n}=t;if("info"===n.kind)return void e(e=>[...e,uh(n.message)]);e(e=>[...e,yh("Failed to open browser"),fh(createOSC8Link(t.url,n.label,!1))])}}function handleLearnCommand({setAutoLearnTaste:e,setShowTasteOnboarding:t,setTasteOnboardingEntryId:n,setFeed:r}){e(!0),t(!0);const o=Sh();n(o.id),r(e=>[...e,o])}async function handleCommand(e,t,n,r){const o=e.trim().split(/\s+/)[0]??"",s=o.split(":")[0]?.replace(/^\//,"")||"unknown";return withSpan({name:`command:${s}`,attributes:{"cmd.command.name":s,"cmd.command.arg_length":Math.max(e.trim().length-o.length,0)},fn:__name(async o=>{const s=await dispatchCommand(e,t,n,r);return o.setAttribute("cmd.command.status",s.status),s},"fn")})}async function dispatchCommand(e,t,n,r){const o=resolveSlashCommandRoute({command:e,isBusy:t.isCmdCodeBusy});if("blocked"===o.kind)return t.setFeed(e=>[...e,uh(o.message)]),{status:"handled"};if("resume-by-id"===o.kind)return await handleSelectSession({selectedSessionId:o.selectedSessionId,previousSessionId:t.sessionId,sessionLoadIdRef:t.sessionLoadIdRef,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:t.setSessionId,setShowSessionSelector:t.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,setStaticKey:t.setStaticKey,setShareInfo:t.setShareInfo,setCurrentModel:t.setCurrentModel,inTuiResume:!0}),{status:"handled"};if("skill"===o.kind){if(0===o.skillName.length)return t.setFeed(e=>[...e,uh("Name a skill to run: /skill:<name>. Run /skills to see what is installed.")]),{status:"handled"};const e=buildSkillNamespacedCommand(o.skillName);return await handleSkillCommand({commandName:`/${o.skillName}`,command:`${e}${o.rawArguments?` ${o.rawArguments}`:""}`,rawArguments:o.rawArguments,positionalArgs:o.positionalArgs,ctx:t})||(t.setFeed(e=>[...e,yh(`No skill named "${o.skillName}". Run /skills to see what is installed.`)]),{status:"handled"})}if("unknown"===o.kind)return{status:"unknown"};const{commandName:s,rawArguments:i,positionalArgs:a}=o;if("/exit"===s||"/quit"===s)return discardPendingReload(),t.setShouldExit(!0),{status:"handled"};if("/reload"===s)return await(k$(t.sessionId)?.flush().catch(()=>{})),requestReload(buildReloadCarryoverState({sessionId:t.sessionId,permissionMode:t.permissionModeRef.current})),t.setShouldExit(!0),{status:"handled"};if("/clear"===s)return await handleClearCommand(t),{status:"handled"};if("/help"===s)return await handleHelpCommand(t),{status:"handled"};if("/share"===s){const e=i.trim();return"gist"===e||e.startsWith("gist ")?(await handleShareGistCommand({sessionId:t.sessionId,currentModel:t.currentModel,rawFormatArg:e.slice(4).trim(),setFeed:t.setFeed}),{status:"handled"}):(await handleShareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setShowShareNotification:t.setShowShareNotification}),{status:"handled"})}if("/unshare"===s)return await handleUnshareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setUnshareNotificationMessage:t.setUnshareNotificationMessage}),{status:"handled"};if("/taste"===s)return t.setShowTasteConfig(!0),{status:"handled"};if("/learn-taste"===s)return handleLearnCommand(t),{status:"handled"};if("/design"===s)return await handleDesignCommand({ctx:t,rawArguments:i,positionalArgs:a,command:e}),{status:"handled"};if("/skills"===s)return t.setShowSkillsConfig(!0),{status:"handled"};if("/plans"===s)return t.setPlansTarget(i.trim()||null),t.setShowPlansView(!0),{status:"handled"};if("/plan-review"===s)return t.setPlansTarget(UU),t.setShowPlansView(!0),{status:"handled"};if("/config"===s)return t.setShowSettingsConfig(!0),{status:"handled"};if("/connect"===s)return t.setShowProviderSelector(!0),{status:"handled"};if("/model"===s)return await handleModelCommand(t,i),{status:"handled"};if("/effort"===s)return await handleEffortCommand(t,i),{status:"handled"};if("/memory"===s)return t.setShowMemorySelector(!0),{status:"handled"};if("/resume"===s||"/sessions"===s)return t.setShowSessionSelector(!0),{status:"handled"};if("/fork"===s)return await handleForkCommand(t,i.trim()||void 0),{status:"handled"};if("/worktree"===s)return await handleWorktreeCommand(t,a),{status:"handled"};if("/clone"===s)return await handleCloneCommand(t),{status:"handled"};if("/init"===s)return await handleInitCommand(t),{status:"handled"};if("/import"===s)return await handleImportCommand(t,i),{status:"handled"};if("/goal"===s)return await handleGoalCommand(t,i,n,r),{status:"handled"};if("/agents"===s)return t.setShowAgentsConfig(!0),{status:"handled"};if("/mcp"===s)return t.setShowMcpManager(!0),{status:"handled"};if("/compact"===s)return await handleCompactCommand({sessionId:t.sessionId,setFeed:t.setFeed,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setContextUsage:t.setContextUsage,setStaticKey:t.setStaticKey}),{status:"handled"};if("/compact-mode"===s)return t.setShowCompactModeSelector(!0),{status:"handled"};if("/update"===s)return t.setInput(""),await handleUpdateCommand({setFeed:t.setFeed,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setUpdateStatus:t.setUpdateStatus,pinnedStatusRef:t.pinnedStatusRef}),{status:"handled"};if("/context"===s)return t.setShowContextView(!0),{status:"handled"};if("/rewind"===s)return handleRewindCommand({sessionId:t.sessionId,setFeed:t.setFeed,setShowRewindSelector:t.setShowRewindSelector}),{status:"handled"};if("/tree"===s)return await handleTreeCommand({sessionId:t.sessionId,setFeed:t.setFeed,setShowTreeSelector:t.setShowTreeSelector,setTreeFilterMode:t.setTreeFilterMode,setTreeBranchSummarySkipPrompt:t.setTreeBranchSummarySkipPrompt}),{status:"handled"};if("/login"===s)return await handleLoginCommand({provider:i,setFeed:t.setFeed,setShowLoginOverlay:t.setShowLoginOverlay,setAuthComponentInfo:t.setAuthComponentInfo}),t.setInput(""),{status:"handled"};if("/logout"===s)return await handleLogoutCommand({provider:i,setFeed:t.setFeed,setRetryAttempt:t.setRetryAttempt,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),t.setInput(""),{status:"handled"};if("/learn"===s){const e=resolveExternalSlashCommandTarget({commandName:s});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),{status:"handled"}}if("/feedback"===s){const e=resolveExternalSlashCommandTarget({commandName:s,rawArguments:i});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),t.setInput(""),{status:"handled"}}if("/trace"===s)return await handleTrace({setFeed:t.setFeed,sessionId:t.sessionId}),t.setInput(""),{status:"handled"};if("/copy"===s)return await handleCopy({feed:t.feed,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/export"===s)return await handleExport({sessionId:t.sessionId,rawPath:i,currentModel:t.currentModel,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/changelog"===s)return handleChangelog({setFeed:t.setFeed,rawArguments:i}),t.setInput(""),{status:"handled"};if("/hotkeys"===s)return handleHotkeys({setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/todos"===s)return 0===getSessionTodos().length?t.setFeed(e=>[...e,uh("No todos in this session yet.")]):requestTodosManagerOpen(),t.setInput(""),{status:"handled"};if("/session-file"===s)return handleSessionFile({sessionId:t.sessionId,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/terminal-setup"===s)return await handleTerminalSetupCommand(t),{status:"handled"};if("/ide"===s)return await handleIDESetupCommand(t),{status:"handled"};if("/add-dir"===s)return t.setShowAddDirModal(!0),{status:"handled"};if("/rename"===s)return await handleRenameCommand({name:i.trim(),sessionId:t.sessionId,setFeed:t.setFeed,setRenamedTerminalTitle:t.setRenamedTerminalTitle,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),t.setInput(""),{status:"handled"};if("/name"===s)return await handleNameCommand({name:i.trim(),sessionId:t.sessionId,setFeed:t.setFeed,setRenamedTerminalTitle:t.setRenamedTerminalTitle}),t.setInput(""),{status:"handled"};if("/usage"===s)return t.setShowUsageOverlay(!0),{status:"handled"};if("/theme"===s)return await handleThemeCommand(t,i),{status:"handled"};if("/plan"===s)return await handlePlanCommand({rawArguments:i,ctx:t}),{status:"handled"};if("/mode"===s||s.startsWith("/mode:")){const e=s.startsWith("/mode:")?s.slice(6):i;return await handleModeCommand({rawArguments:e,ctx:t}),{status:"handled"}}if("/review"===s){const e=await resolveReviewSlashCommand({rawArguments:i});return"missing-gh"===e.status?(t.setFeed(t=>[...t,uh(e.message,e.metadata)]),t.setInput(""),{status:"handled"}):(await submitAutomatedSlashTurn({turn:e.turn,ctx:t}),{status:"handled"})}if("/pr-comments"===s){await submitAutomatedSlashTurn({turn:buildPrCommentsSlashTurn(),ctx:t});const e=k$(t.sessionId),n=resolvePrCommentsFollowUpInput(e?harnessSessionMessages(e):[]);return n&&t.setInput(n),{status:"handled"}}if("/status"===s)return t.setShowStatusView(!0),{status:"handled"};if("/upgrade"===s){const e=resolveExternalSlashCommandTarget({commandName:s,billingUrl:await getBillingLink({billingLink:t.billingLink,setBillingLink:t.setBillingLink})});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),{status:"handled"}}if("/extra"===s){const e=resolveExternalSlashCommandTarget({commandName:s,billingUrl:await getBillingLink({billingLink:t.billingLink,setBillingLink:t.setBillingLink})});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),{status:"handled"}}const l=getActiveModHost(),c=s.slice(1);if(l?.commands().some(e=>e.name===c)){try{const e=await l.runCommand({name:c,args:i}),n=e?.message;n&&t.setFeed(e=>[...e,uh(n)]),e?.prompt&&await submitAutomatedSlashTurn({turn:buildAutomatedSlashTurn({commandName:c,rawArguments:i,fullPrompt:e.prompt}),ctx:t})}catch(e){t.setFeed(t=>[...t,yh(`Mod command /${c} failed: ${e instanceof Error?e.message:String(e)}`)])}return{status:"handled"}}const d=await resolveCustomSlashTurn({runtime:createNodeRuntime(),commandName:s,rawArguments:i,positionalArgs:a});if(d)return await submitAutomatedSlashTurn({turn:d,ctx:t}),{status:"handled"};return await handleSkillCommand({commandName:s,command:e,rawArguments:i,positionalArgs:a,ctx:t})||{status:"unknown"}}async function submitAutomatedSlashTurn({turn:e,ctx:t}){await handleSubmit({input:e.input,role:"user",displayMessage:e.displayMessage,hiddenMessages:e.hiddenMessages,isAutomated:!0,feed:t.feed,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,currentModel:t.currentModel,currentProvider:t.currentProvider,premiumCreditsExhausted:t.premiumCreditsExhausted,setPremiumCreditsExhausted:t.setPremiumCreditsExhausted,setCurrentModel:t.setCurrentModel,sessionId:t.sessionId,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash})}async function handleSkillCommand({commandName:e,command:t,rawArguments:n,positionalArgs:r,ctx:o}){const s=await resolveSkillSlashTurn({runtime:createNodeRuntime(),commandName:e,command:t,rawArguments:n,positionalArgs:r});return"not-found"===s.status?null:"disabled"===s.status?(o.setFeed(e=>[...e,uh(s.message)]),{status:"handled"}):"load-error"===s.status?(o.setFeed(e=>[...e,yh(s.message)]),{status:"handled"}):(await submitAutomatedSlashTurn({turn:s.turn,ctx:o}),{status:"handled"})}function useCommandCtx({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:i,permissionState:a,terminalTitleState:l,isSubmittingRef:c,executeBash:d,setInput:u}){const m=dt(()=>({feed:e.feed,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setQueuedMessages:e.setQueuedMessages,setStatus:n.setStatus,setInteractionTokens:n.setInteractionTokens,setContextUsage:n.setContextUsage,contextUsage:n.contextUsage,setStaticKey:o.setStaticKey,updateStatus:n.updateStatus,setUpdateStatus:n.setUpdateStatus,billingLink:n.billingLink,setBillingLink:n.setBillingLink,currentModel:r.currentModel,premiumCreditsExhausted:r.premiumCreditsExhausted,setPremiumCreditsExhausted:r.setPremiumCreditsExhausted,setCurrentModel:r.setCurrentModel,setModelNotice:o.setModelNotice,currentProvider:r.currentProvider,setAuthComponentInfo:r.setAuthComponentInfo,shareInfo:n.shareInfo,setShareInfo:n.setShareInfo,setShowShareNotification:n.setShowShareNotification,setUnshareNotificationMessage:n.setUnshareNotificationMessage,setRetryAttempt:n.setRetryAttempt,pinnedStatusRef:n.pinnedStatusRef,setShowTasteConfig:o.setShowTasteConfig,setShowSkillsConfig:o.setShowSkillsConfig,setShowSettingsConfig:o.setShowSettingsConfig,setShowProviderSelector:o.setShowProviderSelector,setShowModelSelector:o.setShowModelSelector,setShowEffortSelector:o.setShowEffortSelector,setShowMemorySelector:o.setShowMemorySelector,setShowAgentsConfig:o.setShowAgentsConfig,setShowMcpManager:o.setShowMcpManager,setShowRewindSelector:o.setShowRewindSelector,setShowTreeSelector:o.setShowTreeSelector,setTreeFilterMode:o.setTreeFilterMode,setTreeBranchSummarySkipPrompt:o.setTreeBranchSummarySkipPrompt,setShowCompactModeSelector:o.setShowCompactModeSelector,setShowContextView:o.setShowContextView,setShowAddDirModal:o.setShowAddDirModal,setShowLoginOverlay:o.setShowLoginOverlay,setShowStatusView:o.setShowStatusView,setShowPlansView:o.setShowPlansView,setPlansTarget:o.setPlansTarget,setShowUsageOverlay:o.setShowUsageOverlay,setShowThemeSelector:o.setShowThemeSelector,setShowDesignGuide:o.setShowDesignGuide,setPendingDesignSuggestion:o.setPendingDesignSuggestion,setShowTasteOnboarding:s.setShowTasteOnboarding,setAutoLearnTaste:s.setAutoLearnTaste,setTasteOnboardingEntryId:s.setTasteOnboardingEntryId,sessionId:t.sessionId,setSessionId:t.setSessionId,sessionLoadIdRef:t.sessionLoadIdRef,sessionLoaded:t.sessionLoaded,setSessionLoaded:t.setSessionLoaded,setShowSessionSelector:o.setShowSessionSelector,setPermissionMode:a.setPermissionMode,permissionModeRef:a.permissionModeRef,clearSessionPermissions:a.clearSessionPermissions,setShouldExit:i.setShouldExit,setInput:u,isSubmittingRef:c,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,executeBash:d,setRenamedTerminalTitle:l.setRenamedTerminalTitle}),[e,t,n,r,o,s,i,a,l,c,d,u]),p=lt(m);return p.current=m,{commandCtx:m,onCommand:ut((e,t,n)=>handleCommand(e,p.current,t,n),[])}}__name(renderList,"renderList"),__name(handleWorktreeCommand,"handleWorktreeCommand"),__name(handleRemove,"handleRemove"),__name(handleSwitch,"handleSwitch"),__name(handleHelpCommand,"handleHelpCommand"),__name(handleTerminalSetupCommand,"handleTerminalSetupCommand"),__name(handleIDESetupCommand,"handleIDESetupCommand"),__name(handleClearCommand,"handleClearCommand"),__name(handleInitCommand,"handleInitCommand"),__name(runGoalTurn,"runGoalTurn"),__name(handleGoalCommand,"handleGoalCommand"),__name(openExternalSlashCommandTarget,"openExternalSlashCommandTarget"),__name(handleLearnCommand,"handleLearnCommand"),__name(handleCommand,"handleCommand"),__name(dispatchCommand,"dispatchCommand"),__name(submitAutomatedSlashTurn,"submitAutomatedSlashTurn"),__name(handleSkillCommand,"handleSkillCommand"),__name(useCommandCtx,"useCommandCtx"),Gt(),SR();var wj=as,vj=ls;function useCreditWarning({interactionTokens:e,currentModel:t}){const[n,r]=at(null),o=lt(null),s=lt(null),i=lt(null),a=ut(async()=>{try{const e=createApiClient({baseUrl:getApiBaseUrl()});o.current??=createCreditWarningState();const t=await checkCreditWarning({client:e,state:o.current});if(o.current=t.state,!t.message)return;r(t.message),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{r(null),i.current=null},wj)}catch{}},[]);return ct(()=>{if(0!==e&&!isLocalOnly()&&!isByok({model:t}))return s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{a(),s.current=null},vj),()=>{s.current&&clearTimeout(s.current)}},[e,t,a]),ct(()=>()=>{i.current&&clearTimeout(i.current),s.current&&clearTimeout(s.current)},[]),{creditWarning:n}}__name(useCreditWarning,"useCreditWarning"),Gt(),SR();var kj=createNodeRuntime();function useCronWakeup({sessionId:e,onSubmit:t}){const n=lt(t),r=lt(e),o=lt(Promise.resolve());ct(()=>{n.current=t},[t]),ct(()=>{r.current=e},[e]),ct(()=>{const e=subscribeCronFire(e=>{o.current=o.current.catch(()=>{}).then(async()=>{const t="loop"===e.kind||!0===e.loopOwned,o=k$(r.current);if(t&&o&&!o.hasScheduledTask({id:e.taskId}))return;const s=await buildScheduledTaskWakeupSubmission({event:e,runtime:kj});await n.current(s)}),o.current.catch(()=>{})});return()=>{e()}},[])}function useExit(){const[e,t]=at(!1),[n,r]=at(null),o=lt(null),s=lt(0),i=lt(null),a=ut(()=>{o.current=null,r(null),i.current&&(clearTimeout(i.current),i.current=null)},[]);return{shouldExit:e,setShouldExit:t,pendingExitKey:n,setPendingExitKey:r,pendingExitKeyRef:o,lastExitKeyTimeRef:s,exitConfirmationTimeoutRef:i,resetPendingExitKey:a}}__name(useCronWakeup,"useCronWakeup"),Gt(),__name(useExit,"useExit"),Gt(),SR(),Gt(),SR();var Cj="1"===process.env.CMD_TEST_INJECT_LIVE_ENTRY;function makeInjectedShellEntry(e,t,n,r={}){return{...gh("shell_command",t,{status:n}),id:e,...r}}function buildInjectedLiveEntry(){return Cj?makeInjectedShellEntry("cmd-test-injected-live-entry",process.env.CMD_TEST_INJECT_INPUT??"sleep 60","running"):null}function buildInjectedFeed(){const e=Number.parseInt(process.env.CMD_TEST_INJECT_FEED_ITEMS??"0",10);return!Number.isFinite(e)||e<=0?[]:Array.from({length:e},(e,t)=>makeInjectedShellEntry(`cmd-test-feed-${t}`,`echo item ${t}`,"completed",{output:`item ${t}`}))}__name(makeInjectedShellEntry,"makeInjectedShellEntry"),__name(buildInjectedLiveEntry,"buildInjectedLiveEntry"),__name(buildInjectedFeed,"buildInjectedFeed");var bj="1"===process.env.CMD_TEST_INJECT_STREAM,Ej="cmd-test-injected-stream-entry";function streamRole(){const e=process.env.CMD_TEST_INJECT_STREAM_ROLE;return"reasoning"===e||"tool"===e||"agent"===e?e:"assistant"}function streamContentKind(){const e=process.env.CMD_TEST_INJECT_STREAM_CONTENT;return"code"===e||"paragraph"===e||"reasoning"===e||"mixed"===e||"huge"===e?e:"table"}function streamTickMs(){const e=Number.parseInt(process.env.CMD_TEST_INJECT_STREAM_TICK_MS??"",10);return Number.isFinite(e)&&e>0?e:100}function buildHugeStreamContent(){const e=[];e.push("# Huge streaming gauntlet","A very long reply exercising **every** markdown flavor while it streams. Scroll up mid-stream — the position must hold; finished blocks land in the scrollback above.");for(let t=0;t<6;t+=1){e.push(`## Section ${t} — prose, lists and a table`),e.push(...Array.from({length:4},(e,n)=>`Section ${t} paragraph ${n}: the quick brown fox keeps streaming words so this block wraps a couple of rows, with **bold**, *italic*, ***both***, ~~strikethrough~~, \`inline_code(${n})\` and a [link](https://example.com/s${t}/p${n}) mixed in.`)),e.push([`- Section ${t} unordered item one`,`- Section ${t} unordered item two`," - nested child with `code`"," - nested child with **bold**",`- Section ${t} unordered item three`].join("\n"),[`1. Section ${t} ordered first`,`2. Section ${t} ordered second`,`3. Section ${t} ordered third`].join("\n"),`> Section ${t} blockquote: streaming should never mangle a quote.\n> > And a nested quote inside it still reads fine.`);const n=Array.from({length:6},(e,n)=>`| s${t}-row-${n} | huge demo detail ${n} | ${3*n} |`);e.push(["| Key | Detail | N |","| --- | --- | --- |",...n].join("\n"),"---")}e.push("## Task list and headings ladder"),e.push(["- [x] streamed a task that is done","- [ ] a pending task with `code`","- [x] another finished task with **bold**","- [ ] the last pending task"].join("\n"),"### Heading three","#### Heading four","##### Heading five","###### Heading six"),e.push("## Code in several languages"),e.push(["```ts","const total = rows.reduce(sum);","export function streamGauntlet(rows: number[]): number {","\treturn rows.filter(Boolean).length;","}","```"].join("\n"),["```python","def stream_gauntlet(rows):",' """Docstring survives streaming."""'," return [row * 2 for row in rows if row]","```"].join("\n"),["```json","{",' "stream": "gauntlet",',' "blocks": ["table", "code", "list"],',' "huge": true',"}","```"].join("\n"),["```bash","for block in table code list; do",' echo "streaming $block"',"done","```"].join("\n"),["```diff","- const cap = 10;","+ const cap = viewportRows - reserved;","```"].join("\n")),e.push("## Wide table (column fitting / wrap layout)");const t=Array.from({length:10},(e,t)=>`| wide-${t} | alpha ${t} | beta ${t} | gamma ${t} | a longer cell that should wrap gracefully ${t} | ${11*t} |`);e.push(["| Id | Alpha | Beta | Gamma | Long description column | N |","| --- | --- | --- | --- | --- | --- |",...t].join("\n")),e.push("## Huge table (taller than the viewport — the one capped-while-open case)");const n=Array.from({length:40},(e,t)=>`| huge-row-${t} | streaming stress row number ${t} | ${7*t} |`);return e.push(["| Row | Description | N |","| --- | --- | --- |",...n].join("\n")),e.push("## Width edge cases"),e.push("CJK 漢字が流れても幅計算は崩れない、そしてまた漢字。Emoji too: 🚀🔥✨🎉🧪 — double-width glyphs must wrap correctly.","A single extremely long unbroken paragraph follows to force soft wrapping across many physical rows: "+Array.from({length:12},(e,t)=>`clause ${t} keeps the sentence rolling without a newline`).join(", ")+"."),e.push("## The end","Everything above should now sit in your scrollback exactly once.","Huge demo closing paragraph."),e.join("\n\n")}function buildStreamContent(e){return"code"===e?["```ts",...Array.from({length:34},(e,t)=>`const value_${t} = compute(${t});`),"```"].join("\n"):"paragraph"===e?Array.from({length:16},(e,t)=>`Paragraph ${t} adds a little more of the streaming story so the reply keeps growing past the viewport.`).join("\n\n"):"reasoning"===e?Array.from({length:40},(e,t)=>`step ${t}: consider the next detail`).join("\n"):"huge"===e?buildHugeStreamContent():"mixed"===e?`${Array.from({length:3},(e,t)=>`Mixed intro paragraph ${t} with enough words.`).join("\n\n")}\n\n${["| Col | Detail |","| --- | --- |",...Array.from({length:8},(e,t)=>`| row-${t} | mixed detail ${t} |`)].join("\n")}\n\nMixed closing paragraph.`:["| Item | Description | Value |","| --- | --- | --- |",...Array.from({length:20},(e,t)=>`| item-${t} | detail for row number ${t} | ${7*t} |`)].join("\n")}function buildStreamFrames(e){const t=e.split("\n");return t.length>1?t.map((e,n)=>t.slice(0,n+1).join("\n")):Array.from({length:20},(t,n)=>{const r=Math.ceil(e.length*(n+1)/20);return e.slice(0,r)})}function makeStreamRunningEntry(e,t){return"reasoning"===e?kh(t,{id:Ej,status:"running"}):"tool"===e?{...gh("shell_command",t,{status:"running"}),id:Ej}:"agent"===e?{...Ch({name:"Task",input:t}),id:Ej}:{...ph(t),id:Ej,metadata:{status:"running"}}}function makeStreamFinalEntry(e,t){return"reasoning"===e?kh(t,{id:Ej}):"tool"===e||"agent"===e?{...gh("shell_command",t,{}),id:Ej,output:"done"}:{...ph(t),id:Ej}}function maybeStartInjectedStream(e){if(!bj)return;const{setFeed:t,setLiveEntries:n,setIsCmdCodeBusy:r}=e,o=streamRole(),s=buildStreamFrames(buildStreamContent(streamContentKind())),i=streamTickMs();r(!0);const a=createBlockCommittingRouter({setFeed:t,setLiveEntries:n});a(makeStreamRunningEntry(o,s[0]??""));let l=0;const c=setInterval(()=>{if(l+=1,l<s.length)return void a(makeStreamRunningEntry(o,s[l]??""));clearInterval(c);const e=s[s.length-1]??"";a(makeStreamFinalEntry(o,e)),r(!1)},i);return()=>clearInterval(c)}__name(streamRole,"streamRole"),__name(streamContentKind,"streamContentKind"),__name(streamTickMs,"streamTickMs"),__name(buildHugeStreamContent,"buildHugeStreamContent"),__name(buildStreamContent,"buildStreamContent"),__name(buildStreamFrames,"buildStreamFrames"),__name(makeStreamRunningEntry,"makeStreamRunningEntry"),__name(makeStreamFinalEntry,"makeStreamFinalEntry"),__name(maybeStartInjectedStream,"maybeStartInjectedStream");var Tj="1"===process.env.CMD_TEST_INJECT_TODOS;function todosTickMs(){const e=Number.parseInt(process.env.CMD_TEST_INJECT_TODOS_TICK_MS??"",10);return Number.isFinite(e)&&e>0?e:1500}__name(todosTickMs,"todosTickMs");var Pj=(()=>{const e=[{content:"Create initial todo items",active:"Creating initial todo items"},{content:"Update status of a todo",active:"Updating todo status"},{content:"Mark all todos as completed",active:"Marking all todos as completed"}];return Array.from({length:e.length+1},(t,n)=>e.map((e,t)=>({content:e.content,status:t<n?"completed":t===n?"in_progress":"pending",...t===n?{activeForm:e.active}:{},id:String(t+1)})))})();function maybeStartInjectedTodos(e){if(!Tj)return;const t=createBlockCommittingRouter({setFeed:e.setFeed,setLiveEntries:e.setLiveEntries});let n=0;const r=setInterval(()=>{const e=Pj[n];e?(t({...gh("todo_write",Oh("todo_write",{todos:e}),{}),id:`cmd-test-todo-${n}`,output:JSON.stringify(e)}),n+=1):clearInterval(r)},todosTickMs());return()=>clearInterval(r)}__name(maybeStartInjectedTodos,"maybeStartInjectedTodos");var Mj=Number.parseInt(process.env.CMD_TEST_INJECT_TURNS??"0",10);function testTurnChars(){const e=Number.parseInt(process.env.CMD_TEST_INJECT_TURN_CHARS??"",10);return Number.isFinite(e)&&e>0?e:1e5}function testTurnTickMs(){const e=Number.parseInt(process.env.CMD_TEST_INJECT_TURN_TICK_MS??"",10);return Number.isFinite(e)&&e>0?e:20}function makeInjectedTurnEntry(e,t){const n=`turn ${e} `.repeat(Math.ceil(testTurnChars()/`turn ${e} `.length));return makeInjectedShellEntry(`cmd-test-turn-${e}`,t?"echo turns-done":`echo turn ${e}`,"completed",{output:t?"turns-done":n.slice(0,testTurnChars())})}function maybeStartInjectedTurns(e){if(!Number.isFinite(Mj)||Mj<=0)return;const{setFeed:t}=e;let n=0;const r=setInterval(()=>{const e=n===Mj-1,o=makeInjectedTurnEntry(n,e);t(e=>[...e,o]),n+=1,e&&clearInterval(r)},testTurnTickMs());return()=>clearInterval(r)}function useFeed(){const[e,t]=at(()=>buildInjectedFeed()),n=ut(e=>{t(t=>applyFeedRetention("function"==typeof e?e(t):e))},[]);ct(()=>{trimStaticBuffer()},[e]);const[r,o]=at(()=>{const e=buildInjectedLiveEntry();return e?[e]:[]}),[s,i]=at([]),[a,l]=at(Cj),c=lt([]),d=ut(e=>{const t="function"==typeof e?e(c.current):e;c.current=t,i(t)},[]);return ct(()=>maybeStartInjectedTurns({setFeed:n}),[n]),ct(()=>maybeStartInjectedStream({setFeed:n,setLiveEntries:o,setIsCmdCodeBusy:l}),[]),ct(()=>maybeStartInjectedTodos({setFeed:n,setLiveEntries:o}),[]),{feed:e,setFeed:n,liveEntries:r,setLiveEntries:o,queuedMessages:s,setQueuedMessages:d,isCmdCodeBusy:a,setIsCmdCodeBusy:l,queuedMessagesRef:c}}function useKeyboard({showTasteConfig:e,showSkillsConfig:t,showSettingsConfig:n,showProviderSelector:r,showModelSelector:o,showEffortSelector:s,showMemorySelector:i,showMcpManager:a,showRewindSelector:l,showTreeSelector:c,showLoginOverlay:d,showUsageOverlay:u,showAddDirModal:m,showDesignGuide:p,authComponentInfo:g,setShowModelSelector:h,setStaticKey:f,showTasteSkipBanner:y,setShowTasteSkipBanner:S,showZdrNotice:w,setShowZdrNotice:v,modelNotice:k,setModelNotice:C,transcriptMode:b,setTranscriptMode:E,isCmdCodeBusy:T,liveEntries:P,queuedMessagesRef:M,setInput:x,setQueuedMessages:I,setFeed:A,setLiveEntries:R,setIsCmdCodeBusy:L,setRetryAttempt:O,setStatus:D,pendingExitKey:$,setPendingExitKey:N,pendingExitKeyRef:_,lastExitKeyTimeRef:F,exitConfirmationTimeoutRef:U,resetPendingExitKey:j,pendingPermission:B,setPendingPermission:W,pendingQuestion:H,setPendingQuestion:G,setShouldExit:V,sessionId:z,handleToggleAutoAccept:K,handleDoubleEscapeEmpty:q,respondToPrompt:Y,createErrorEntry:J}){const Q=__name(()=>{k$(z)?.cancelLoops().then(e=>{if(0===e)return;const t=1===e?"task":"tasks";A(n=>[...n,uh(`Loop stopped · ${e} scheduled ${t} cancelled`,{isGoalNotice:!0,goalNoticeKind:"cleared"})])})},"cancelLoopsAndNotify"),X=__name(()=>{interruptActiveTurn(),clearCommandGoalIfActive(z),Q();const e=P.length>0;if(L(!1),O(null),R([]),D(tS),!e){const e=J(eS);A(t=>[...t,e])}if(M.current.length>0){const e=formatQueuedMessagesForRequeue(M.current);x(t=>mergeRequeuedInput({queuedText:e,currentInput:t})),I([]),M.current=[]}},"handleInterrupt");nt((P,M)=>{const I=getKeybindings();if(keybindingMatches(I,"app.permission.cycle",P,M)||""===P||M.meta&&"m"===P)return void K();if(y&&M.escape)return void S(!1);if(w&&M.escape)return void v(!1);if(k&&M.escape)return void C(null);if(isTodosManagerOpen())return void($&&j());if(e||t||n||r||o||s||i||a||g||l||c||d||u||m||p)return void($&&j());if(""===P||M.ctrl&&"c"===P){if(T)return void X();const e=Date.now(),t=e-F.current;return F.current=e,"ctrl-c"===_.current&&t<2e3?(U.current&&(clearTimeout(U.current),U.current=null),void V(!0)):(x(()=>""),_.current="ctrl-c",N("ctrl-c"),U.current&&clearTimeout(U.current),void(U.current=setTimeout(()=>{_.current=null,N(null),U.current=null},2e3)))}if(keybindingMatches(I,"app.tools.expand",P,M)){if(H?.params.planContent)return;return RL(),E("off"===b?"limited":"off"),void f(e=>e+1)}const A=isCtrlKey({inputChar:P,key:M,letter:"e",ctrlCode:5})||isCtrlKey({inputChar:P,key:M,letter:"y",ctrlCode:25}),R=null!==B&&"function"==typeof B.params?.explain;if("off"!==b&&A&&!R)return RL(),E("limited"===b?"full":"limited"),void f(e=>e+1);if("off"===b&&getSessionTodos().length>0&&keybindingMatches(I,"app.todos.toggle",P,M))requestTodosManagerOpen();else if(keybindingMatches(I,"app.model.select",P,M)||isAltP(P))h(!0);else if(M.escape){if("off"!==b)return RL(),E("off"),void f(e=>e+1);if(H)return H.reject(new Error("Question cancelled by user")),G(null),D("Question cancelled"),hardResetForResize(),void f(e=>e+1);if(B)return Y({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),B.resolve(!1),W(null),void D("Permission denied");T?X():Q()}})}function useHandlers({resume:e,feedState:t,onboarding:n,uiOverlays:r,exitState:o,pendingOps:s,permissionState:i,statusState:a,authState:l,sessionId:c,loadTasteStatus:d,loadCurrentProvider:u,setInput:m}){const p=ut(()=>{i.setPermissionMode(e=>{const t=cyclePermissionMode({current:e,disableBypass:k$(c)?.isBypassDisabled()??!0}),n=resolvePendingPromptOnModeChange(t,{pendingIsRisky:void 0!==s.pendingPermission?.params?.risk});return n&&s.pendingPermission&&("approve"===n&&i.respondToPrompt(iM),s.pendingPermission.resolve("approve"===n),s.setPendingPermission(null)),k$(c)?.setPermissionMode({mode:t}),t})},[i.setPermissionMode,i.respondToPrompt,s.pendingPermission,s.setPendingPermission,c]),g=ut(()=>{i.setPermissionMode(e=>{const t="bypass"===e?e:"auto-accept";return k$(c)?.setPermissionMode({mode:t}),t})},[i.setPermissionMode,c]),h=ut(()=>{const e=!t.isCmdCodeBusy&&!s.pendingPermission&&!s.pendingQuestion,n=(k$(c)?.listCheckpoints().length??0)>0;e&&n&&r.setShowRewindSelector(!0)},[t.isCmdCodeBusy,s.pendingPermission,s.pendingQuestion,r.setShowRewindSelector,c]),f=ut(t=>{n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),t?.skipped&&r.setShowTasteSkipBanner(!0),e&&r.setShowSessionSelector(!0)},[e,n,r]),y=ut(async()=>{try{if(await initializeCommandProjectSessions(),n.setShowTrustPrompt(!1),e)return console.log("No conversations found to resume."),void o.setShouldExit(!0);n.setProjectTrusted(!0),d(),u()}catch(e){console.error("Failed to initialize project:",e),n.setShowTrustPrompt(!1),o.setShouldExit(!0)}},[e,n,o,d,u]),S=ut(()=>{o.setShouldExit(!0)},[o.setShouldExit]);return useKeyboard({showTasteConfig:r.showTasteConfig,showSkillsConfig:r.showSkillsConfig,showSettingsConfig:r.showSettingsConfig,showProviderSelector:r.showProviderSelector,showModelSelector:r.showModelSelector,showEffortSelector:r.showEffortSelector,showMemorySelector:r.showMemorySelector,showMcpManager:r.showMcpManager,showRewindSelector:r.showRewindSelector,showTreeSelector:r.showTreeSelector,showLoginOverlay:r.showLoginOverlay,showUsageOverlay:r.showUsageOverlay,showAddDirModal:r.showAddDirModal,showDesignGuide:r.showDesignGuide,authComponentInfo:l.authComponentInfo,setShowModelSelector:r.setShowModelSelector,setStaticKey:r.setStaticKey,showTasteSkipBanner:r.showTasteSkipBanner,setShowTasteSkipBanner:r.setShowTasteSkipBanner,showZdrNotice:r.showZdrNotice,setShowZdrNotice:r.setShowZdrNotice,modelNotice:r.modelNotice,setModelNotice:r.setModelNotice,transcriptMode:r.transcriptMode,setTranscriptMode:r.setTranscriptMode,isCmdCodeBusy:t.isCmdCodeBusy,liveEntries:t.liveEntries,queuedMessagesRef:t.queuedMessagesRef,setInput:m,setQueuedMessages:t.setQueuedMessages,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setRetryAttempt:a.setRetryAttempt,setStatus:a.setStatus,pendingExitKey:o.pendingExitKey,setPendingExitKey:o.setPendingExitKey,pendingExitKeyRef:o.pendingExitKeyRef,lastExitKeyTimeRef:o.lastExitKeyTimeRef,exitConfirmationTimeoutRef:o.exitConfirmationTimeoutRef,resetPendingExitKey:o.resetPendingExitKey,pendingPermission:s.pendingPermission,setPendingPermission:s.setPendingPermission,pendingQuestion:s.pendingQuestion,setPendingQuestion:s.setPendingQuestion,setShouldExit:o.setShouldExit,sessionId:c,handleToggleAutoAccept:p,handleDoubleEscapeEmpty:h,respondToPrompt:i.respondToPrompt,createErrorEntry:yh}),{handleToggleAutoAccept:p,handleEnableAutoAccept:g,handleDoubleEscapeEmpty:h,handleTasteOnboardingComplete:f,handleTrust:y,handleNoTrust:S}}function resolveExternalModelChange(e){return"model"!==e.setting||"string"!=typeof e.value||0===e.value.length||e.value===e.currentModel?null:{modelId:e.value}}function raceAnswerAgainstAbort(e,t){return t?t.aborted?Promise.resolve("deny"):new Promise((n,r)=>{const o=__name(()=>n("deny"),"onAbort");t.addEventListener("abort",o,{once:!0}),e.then(e=>{t.removeEventListener("abort",o),n(e)},e=>{t.removeEventListener("abort",o),r(e)})}):e}__name(testTurnChars,"testTurnChars"),__name(testTurnTickMs,"testTurnTickMs"),__name(makeInjectedTurnEntry,"makeInjectedTurnEntry"),__name(maybeStartInjectedTurns,"maybeStartInjectedTurns"),__name(useFeed,"useFeed"),Gt(),SR(),Gt(),SR(),__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Gt(),SR(),Gt(),__name(resolveExternalModelChange,"resolveExternalModelChange"),Gt(),__name(raceAnswerAgainstAbort,"raceAnswerAgainstAbort"),Gt();var xj={},Ij={};function setStartupSessionOptions(e){xj=void 0===e.persist?{}:{persist:e.persist},Ij={...e.sessionFilePath?{sessionFilePath:e.sessionFilePath}:{},...e.name?{name:e.name}:{}}}function getStickyStartupSessionOptions(){return xj}function consumeStartupSessionOverrides(){const e=Ij;return Ij={},e}function buildInteraction({permissionsService:e,permissionModeRef:t,setPendingQuestion:n,setStatus:r}){return{confirmTool:__name(async({toolName:n,input:r,description:o,risk:s,explain:i,signal:a})=>{if(!e)return"allow";if(a?.aborted)return"deny";const l=__name(e=>raceAnswerAgainstAbort(e.then(e=>e.allowed?"allow":"deny"),a),"withInterrupt"),c=buildToolPermissionRequest({toolName:n,input:r,description:o,...void 0!==s?{risk:s}:{},...void 0!==i?{explain:i}:{}});return"shell"===c.kind?l(e.requestShellPermission(c.request)):"generic"===c.kind?l(e.requestGenericPermission(c.request)):l(e.requestPermission(c.request,t.current))},"confirmTool"),askQuestion:__name(async e=>new Promise(t=>{n({params:{questions:e.questions.map(e=>({question:e.question,header:e.header??"",options:e.options.map(e=>({label:e.label,description:e.description??"",...void 0!==e.preview?{preview:e.preview}:{}})),multiSelect:e.multiSelect??!1})),hideCustomInput:e.hideCustomInput,exitPlanMode:e.exitPlanMode,enterPlanMode:e.enterPlanMode,planContent:e.planContent,planFilePath:e.planFilePath,compact:e.compact},resolve:__name(e=>{t({answers:e.answers.map(e=>({questionIndex:e.questionIndex,selectedOptions:[...e.selectedOptions],...void 0!==e.notes?{notes:e.notes}:{},...void 0!==e.preview?{preview:e.preview}:{},...e.images?.length?{images:e.images}:{}})),...e.disposition?{disposition:e.disposition}:{}})},"resolve"),reject:__name(()=>{t({answers:[]})},"reject")}),r("Waiting for your answer…")}),"askQuestion")}}function useHarness({sessionId:e,sessionLoaded:t,showSessionSelector:n,projectTrusted:o,permissionsService:s,permissionModeRef:i,setPermissionMode:a,permissionModeExplicit:l,dangerouslySkipPermissions:c,setPendingQuestion:d,setStatus:u,setFeed:m,queuedMessagesRef:p,setQueuedMessages:g,onSessionTitled:h,currentModel:f,setCurrentModel:y,setStaticKey:S,isCmdCodeBusy:w}){const v=lt(f);v.current=f;const k=lt(null),C=lt(!1),b=lt(w);b.current=w;const E=ut(()=>{hardResetForResize(),S?.(e=>e+1)},[S]),T=ut(e=>{v.current=e,y?.(e),E()},[E,y]);ct(()=>{if(w)return;const e=k.current,t=C.current;k.current=null,C.current=!1,(null!==e||t)&&(null===e||e===v.current?t&&E():T(e))},[w,T,E]);const[P,M]=at(!1),[x,I]=at(0),A=lt(null),R=__name(()=>{A.current?.(),A.current=null},"releaseRebuildBarrier");ct(()=>onHarnessSessionRebuild(t=>{if(t===e)return new Promise(e=>{A.current?.(),A.current=e,I(e=>e+1)})}),[e]);const L=lt(i.current),O=lt(null);return ct(()=>{if(!o||n)return void R();const t=__name(()=>Boolean(l)||i.current!==L.current,"userChoseMode");let f,y,S=!1;return(async()=>{const n=consumeStartupSessionOverrides(),{persist:o}=getStickyStartupSessionOptions(),l=await loadResumeAgentState({sessionId:e,...n.sessionFilePath?{baseDir:r(n.sessionFilePath)}:{}});if(S)return;const w=__name(()=>{const e=p?.current??[];return 0===e.length?[]:(p&&(p.current=[]),g?.(()=>[]),m?.(t=>[...t,...e.flatMap(e=>{if(e.isMeta)return[];const t=dh(e.displayMessage??e.input);return e.ideHint&&(t.metadata={ideHint:e.ideHint}),[t]})]),e.map(e=>{const t=e.ideContext?`${e.ideContext}\n\n${e.input}`:e.input;return e.images&&0!==e.images.length?{input:[...clipboardImagesToUserContent(e.images),{type:"text",text:t}],...e.source?{source:e.source}:{}}:{input:t,...e.source?{source:e.source}:{}}}))},"drainQueuedMessages"),P=await loadCommandModHost(),x=await v$({sessionId:e,baseUrl:getApiBaseUrl(),...t()?{permissionMode:i.current}:{},dangerouslySkipPermissions:c,drainQueuedMessages:w,peekQueuedMessageCount:__name(()=>p?.current?.length??0,"peekQueuedMessageCount"),interaction:buildInteraction({permissionsService:s,permissionModeRef:i,setPendingQuestion:d,setStatus:u}),requestSlashCommand:__name(({command:t})=>(enqueueAgentSlashCommand({sessionId:e,command:t}),{status:"accepted"}),"requestSlashCommand"),resumeState:l,modHost:P,...void 0!==o?{persist:o}:{},...n.sessionFilePath?{sessionFilePath:n.sessionFilePath}:{},ideBridge:createLocalIdeBridge()}).catch(()=>{});if(R(),S||!x)return;n.name&&x.setSessionName(n.name),x.getPermissionMode()!==i.current&&(t()?x.setPermissionMode({mode:i.current}):(i.current=x.getPermissionMode(),a?.(x.getPermissionMode())));const I=x.getModel(),A=I!==v.current;A&&T(I),A||x.getEffort()===getReasoningEffort(I)||E(),P&&m&&(P.setEntrySink(e=>{m(t=>[...t,uh(e.join("\n"))])}),y=__name(()=>P.setEntrySink(void 0),"clearModEntrySink")),f=x.events.subscribe(e=>{if("session_titled"===e.type)return void h?.(e.title);if("permission_mode_changed"===e.type)return i.current=e.mode,void a?.(e.mode);if("config_setting_changed"===e.type){if("theme"===e.setting&&"string"==typeof e.value&&isCliTheme(e.value)&&applyTuiTheme(resolveCliTheme(e.value)),"effort"===e.setting)return void(b.current?C.current=!0:E());const t=resolveExternalModelChange({setting:e.setting,value:e.value,currentModel:v.current});return void(t&&(b.current?k.current=t.modelId:T(t.modelId)))}if("subagent_stop"===e.type){if(!m)return;return void m(t=>settleBackgroundAgentRow({entries:t,toolCallId:e.toolCallId,tokensUsed:e.tokensUsed,...e.status?{status:e.status}:{}}))}if("notice"!==e.type||!m)return;const t=tasteNoticeToFeedEntry(e);t&&m(e=>[...e,t])}),M(!0),O.current!==e&&(O.current=e,x.fireSessionStartHooks({source:consumeNextSessionStartSource()}).then(e=>{if(S||0===e.hooksRun||!m)return;const t=1===e.hooksRun?"":"s",n=[`Ran ${e.hooksRun} session start hook${t}`,...e.systemMessage?e.systemMessage.split("\n"):[]];m(e=>[...e,uh(n.join("\n"))])}).catch(()=>{}))})(),()=>{S=!0,f?.(),y?.()}},[e,t,n,o,s,i,a,l,c,d,u,y,T,x,E]),{ready:P}}function useLifecycle({exit:e,feedState:t,exitState:n,statusState:r,authState:o,onboarding:s,uiOverlays:i,skipOnboarding:a,sessionId:l,sessionTitleHolder:c}){ct(()=>{n.shouldExit&&(r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),o.providerNotificationTimer.current&&clearTimeout(o.providerNotificationTimer.current),o.modelNotificationTimer.current&&clearTimeout(o.modelNotificationTimer.current),c&&(c.loadTitle=()=>loadCommandUserRenamedTitle({sessionId:l}),c.sessionId=l),(async()=>{try{await Promise.allSettled([disconnectAllMcpServers(),b$()])}catch{}try{e()}catch{process.exit(0)}})())},[n.shouldExit,e]),ct(()=>()=>{r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),o.providerNotificationTimer.current&&clearTimeout(o.providerNotificationTimer.current),o.modelNotificationTimer.current&&clearTimeout(o.modelNotificationTimer.current)},[]),ct(()=>{(async()=>{await loadCustomProviderModels();const e=await checkOAuthSetupRequired({currentProvider:o.currentProvider,isByokModel:isByok({model:o.currentModel}),providerAuthHeaders:providerAuthHeaders});e&&r.setStatus(e)})()},[o.currentProvider,o.currentModel]),ct(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(xh())},_h);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),ct(()=>{a||triggerTasteOnboarding({projectTrusted:s.projectTrusted,onboardingComplete:s.onboardingComplete,isOnboardingMode:s.showTasteOnboarding,tasteOnboardingCheckedRef:s.tasteOnboardingCheckedRef,setIsOnboardingMode:s.setShowTasteOnboarding})},[s.projectTrusted,s.onboardingComplete,s.showTasteOnboarding,a]),ct(()=>{if(s.showTasteOnboarding&&!s.tasteOnboardingEntryId){const e=Sh();s.setTasteOnboardingEntryId(e.id),t.setFeed(t=>[...t,e])}!s.showTasteOnboarding&&s.tasteOnboardingEntryId&&(t.setFeed(e=>e.filter(e=>e.id!==s.tasteOnboardingEntryId)),s.setTasteOnboardingEntryId(null))},[s.showTasteOnboarding,s.tasteOnboardingEntryId])}async function handleCompactModeSelect({mode:e,setShowCompactModeSelector:t,setStatus:n}){try{await setCompactMode({mode:e}),t(!1),n(buildCompactModeStatusMessage(e))}catch{n(xo),t(!1)}}function handleCompactModeCancel({setShowCompactModeSelector:e}){e(!1)}__name(setStartupSessionOptions,"setStartupSessionOptions"),__name(getStickyStartupSessionOptions,"getStickyStartupSessionOptions"),__name(consumeStartupSessionOverrides,"consumeStartupSessionOverrides"),__name(buildInteraction,"buildInteraction"),__name(useHarness,"useHarness"),Gt(),SR(),__name(useLifecycle,"useLifecycle"),Gt(),SR(),Gt(),SR(),__name(handleCompactModeSelect,"handleCompactModeSelect"),__name(handleCompactModeCancel,"handleCompactModeCancel");var Aj=__name(e=>{},"noopBool");function useMainActionCallbacks({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,setInput:s}){const i=lt({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,setInput:s});i.current={feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,setInput:s};const a=ut(e=>{const{feedState:t,sessionState:n,statusState:r,uiOverlays:o,authState:s}=i.current;handleSelectSession({selectedSessionId:e,previousSessionId:n.sessionId,sessionLoadIdRef:n.sessionLoadIdRef,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:n.setSessionId,setShowSessionSelector:o.setShowSessionSelector,setSessionLoaded:n.setSessionLoaded,setStaticKey:o.setStaticKey,setShareInfo:r.setShareInfo,setCurrentModel:s.setCurrentModel,inTuiResume:!0})},[]),l=ut(({messageId:e,mode:t})=>{const{feedState:n,sessionState:r,statusState:o,uiOverlays:s,setInput:a}=i.current;handleRewindSelect({messageId:e,mode:t,sessionId:r.sessionId,setFeed:n.setFeed,setStatus:o.setStatus,setShowRewindSelector:s.setShowRewindSelector,setStaticKey:s.setStaticKey,setInput:a})},[]),c=ut(()=>{handleRewindCancel({setShowRewindSelector:i.current.uiOverlays.setShowRewindSelector})},[]),d=ut(e=>{const{feedState:t,sessionState:n,uiOverlays:r,setInput:o}=i.current;return handleTreeSelect({...e,sessionId:n.sessionId,setFeed:t.setFeed,setShowTreeSelector:r.setShowTreeSelector,setStaticKey:r.setStaticKey,setInput:o})},[]),u=ut(()=>{handleTreeCancel({setShowTreeSelector:i.current.uiOverlays.setShowTreeSelector})},[]),m=ut(e=>{const{feedState:t,sessionState:n}=i.current;handleTreeLabel({...e,sessionId:n.sessionId,setFeed:t.setFeed})},[]),p=ut(()=>{handleTreeAbortSummary({sessionId:i.current.sessionState.sessionId})},[]),g=ut((e,t)=>{const{feedState:n,statusState:r,uiOverlays:o}=i.current;handleLoginComplete({success:e,message:t,setShowLoginOverlay:o.setShowLoginOverlay,setFeed:n.setFeed,setStatus:r.setStatus})},[]),h=ut(()=>{const{feedState:e,statusState:t,uiOverlays:n}=i.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),f=__name(e=>{const t=i.current.authState.currentModel;if(dlog("[LaneSwitch] autoSwitchModelForLane",{provider:e,model:t}),laneServesModel({activeLane:e,modelId:t}))return;const n=defaultModelForLane({activeLane:e});dlog("[LaneSwitch] fallback",{fallback:n}),n&&v(n,e)},"autoSwitchModelForLane"),y=ut(e=>{const{authState:t,sessionState:n,statusState:r,uiOverlays:o}=i.current;handleProviderSelect({provider:e,setCurrentProvider:t.setCurrentProvider,setShowProviderSelector:o.setShowProviderSelector,setAuthComponentInfo:t.setAuthComponentInfo,setStatus:r.setStatus,setShowProviderNotification:t.setShowProviderNotification,providerNotificationTimer:t.providerNotificationTimer,setShowModelSelector:o.setShowModelSelector,sessionId:n.sessionId,onActiveModelOrphaned:__name(async()=>{{const e=await S();dlog("[LaneSwitch] orphaned → lane default",{fallback:e}),clearModelOverride(),setSessionModel(e),await persistDefaultModel({model:e});const t=i.current.sessionState.sessionId;t&&await saveCommandSessionMeta({sessionId:t,meta:{model:e}}),i.current.authState.setCurrentModel(e),i.current.uiOverlays.setStaticKey(e=>e+1)}},"onActiveModelOrphaned"),onDiskDefaultOrphaned:__name(async()=>{await persistDefaultModel({model:await S()})},"onDiskDefaultOrphaned")}).then(({switched:t})=>{t&&f(e)})},[]),S=__name(async()=>{const e=i.current.authState.currentProvider??await getConfiguredProvider()??uo.COMMAND;return e===uo.COMMAND?pr:defaultModelForLane({activeLane:e})??pr},"resolveOrphanFallback"),w=ut(()=>{handleProviderCancel({setShowProviderSelector:i.current.uiOverlays.setShowProviderSelector})},[]),v=ut((e,t)=>{const{authState:n,sessionState:r,statusState:o,uiOverlays:s,feedState:a}=i.current;handleModelSelect({modelId:e,provider:t,setCurrentModel:n.setCurrentModel,setShowModelSelector:s.setShowModelSelector,setStatus:o.setStatus,modelNotificationTimer:n.modelNotificationTimer,setShowModelNotification:Aj,setCurrentProvider:n.setCurrentProvider,setStaticKey:s.setStaticKey,sessionId:r.sessionId,setFeed:a.setFeed,setContextUsage:o.setContextUsage,setModelNotice:s.setModelNotice})},[]),k=ut(()=>{handleModelCancel({setShowModelSelector:i.current.uiOverlays.setShowModelSelector})},[]),C=ut(e=>{const{statusState:t,uiOverlays:n}=i.current;handleCompactModeSelect({mode:e,setShowCompactModeSelector:n.setShowCompactModeSelector,setStatus:t.setStatus})},[]),b=ut(()=>{handleCompactModeCancel({setShowCompactModeSelector:i.current.uiOverlays.setShowCompactModeSelector})},[]),E=ut(e=>{const{statusState:t,uiOverlays:n}=i.current;handleThemeSelect({theme:e,setShowThemeSelector:n.setShowThemeSelector,setStatus:t.setStatus,setStaticKey:n.setStaticKey})},[]),T=ut(()=>{handleThemeCancel({setShowThemeSelector:i.current.uiOverlays.setShowThemeSelector})},[]),P=ut(()=>{const{authState:e,sessionState:t,statusState:n,uiOverlays:r}=i.current;handleAuthSuccess({authComponentInfo:e.authComponentInfo,setAuthComponentInfo:e.setAuthComponentInfo,setShowProviderSelector:r.setShowProviderSelector,setCurrentProvider:e.setCurrentProvider,setStatus:n.setStatus,setShowProviderNotification:e.setShowProviderNotification,providerNotificationTimer:e.providerNotificationTimer,sessionId:t.sessionId}).then(({switchedProvider:e})=>{e&&f(e)})},[]),M=ut(()=>{handleAuthCancel({setAuthComponentInfo:i.current.authState.setAuthComponentInfo})},[]);return{onSelectSession:a,onRewindSelect:l,onRewindCancel:c,onTreeSelect:d,onTreeCancel:u,onTreeLabel:m,onTreeAbortSummary:p,onLoginComplete:g,onLoginCancel:h,handleProviderSelect:y,handleProviderCancel:w,handleModelSelect:v,handleModelCancel:k,handleCompactModeSelect:C,handleCompactModeCancel:b,handleThemeSelect:E,handleThemeCancel:T,handleAuthSuccess:P,handleAuthCancel:M}}function useMonitorOutputWakeup({onSubmit:e}){const t=lt(e);ct(()=>{t.current=e},[e]),ct(()=>{const e=subscribeMonitorCheck(e=>{t.current(buildMonitorWakeupSubmission(e))});return()=>{e()}},[])}function useOnboarding(){const[e,t]=at(!1),[n,r]=at(!1),[o,s]=at(!0),[i,a]=at(!1),[l,c]=at(!1),[d,u]=at(null),[m,p]=at(!1);return{showTrustPrompt:e,setShowTrustPrompt:t,projectTrusted:n,setProjectTrusted:r,checkingProject:o,setCheckingProject:s,showTasteOnboarding:i,setShowTasteOnboarding:a,onboardingComplete:l,setOnboardingComplete:c,tasteOnboardingEntryId:d,setTasteOnboardingEntryId:u,autoLearnTaste:m,setAutoLearnTaste:p,tasteOnboardingCheckedRef:lt(!1)}}function usePendingOps(){const[e,t]=at(null),[n,r]=at(null);return{pendingPermission:e,setPendingPermission:t,pendingQuestion:n,setPendingQuestion:r}}function resolvePermissionSettingsPath(e){return t.join(e.projectRoot,".commandcode",e.local?"settings.local.json":"settings.json")}__name(useMainActionCallbacks,"useMainActionCallbacks"),Gt(),SR(),__name(useMonitorOutputWakeup,"useMonitorOutputWakeup"),Gt(),__name(useOnboarding,"useOnboarding"),Gt(),__name(usePendingOps,"usePendingOps"),Gt(),SR(),Gt(),SR(),__name(resolvePermissionSettingsPath,"resolvePermissionSettingsPath");var Rj=__name((e={})=>{const{projectRoot:t,local:n=!1,onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:i}=e,a=t||process.cwd(),l=lt({onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:i}),[c,d]=at(null),u=lt(null),[m,p]=at(null),[g,h]=at(!1);return ct(()=>{l.current={onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:i}},[r,o,s,i]),ct(()=>{const e=resolvePermissionSettingsPath({projectRoot:a,local:n}),t=createPermissionsService(a,{configPath:e});return u.current=createPermissionPromptBridge({service:t,onFileRequest:__name(e=>{p(e),h(!0),l.current.onPermissionRequest?.(e)},"onFileRequest"),onShellRequest:__name(e=>{p(e),h(!0),l.current.onShellPermissionRequest?.(e)},"onShellRequest"),onGenericRequest:__name(e=>{p(e),h(!0),l.current.onGenericPermissionRequest?.(e)},"onGenericRequest")}),d(t),()=>{t.removeAllListeners(),u.current=null}},[n,a]),{requestPermission:ut(async e=>{if(!c)return{allowed:!0};const t=await c.requestPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),requestShellPermission:ut(async e=>{if(!c)return{allowed:!0};const t=await c.requestShellPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),requestGenericPermission:ut(async e=>{if(!c)return{allowed:!0};const t=await c.requestGenericPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),respondToPrompt:ut(e=>{u.current?.respond(e)&&(p(null),h(!1))},[]),clearSessionPermissions:ut(()=>{c?.clearSessionPermissions()},[c]),clearProjectPermissions:ut(()=>{c?.clearProjectPermissions()},[c]),setAutoApprove:ut((e,t)=>{c?.setAutoApprove(e,t)},[c]),setEnabled:ut(e=>{c?.setEnabled(e)},[c]),currentRequest:m,isPrompting:g,service:c}},"usePermissions");function usePermissionMode({initialPermissionMode:e,local:t=!1,dangerouslySkipPermissions:n=!1,setPendingPermission:r,setStatus:o}){const[s,i]=at(()=>e||(n?"bypass":"default")),a=lt(s);ct(()=>{a.current=s},[s]);const{requestShellPermission:l,service:c,respondToPrompt:d,clearSessionPermissions:u,setEnabled:m}=Rj({projectRoot:process.cwd(),local:t,onPermissionRequest:__name(e=>{r({toolName:getFileActionToolName(e.action),params:e,resolve:__name(e=>{},"resolve")}),o("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{r({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),o("Waiting for shell command permission...")},"onShellPermissionRequest"),onGenericPermissionRequest:__name(e=>{r({toolName:e.toolName,params:e,resolve:__name(e=>{},"resolve")}),o("Waiting for tool permission...")},"onGenericPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?o("Permission granted"):o("Permission denied")},"onPermissionResponse")});return ct(()=>{c&&applyAutoAcceptMode({enabled:s,service:c})},[s,c]),{permissionMode:s,setPermissionMode:i,permissionModeRef:a,permissionsService:c,respondToPrompt:d,clearSessionPermissions:u,dangerouslySkipPermissions:n}}function useQueuedMessageFlush({isCmdCodeBusy:e,queuedMessages:t,queuedMessagesRef:n,setQueuedMessages:r,isSubmittingRef:o,onSubmit:s}){const i=lt(s);ct(()=>{i.current=s},[s]);const a=t.length>0;ct(()=>{if(!a||e)return;const t=setInterval(()=>{if(o.current)return;const e=n.current[0];e&&(r(e=>e.slice(1)),i.current({role:"user",input:e.input,...void 0!==e.displayMessage?{displayMessage:e.displayMessage}:{},...void 0!==e.isAutomated?{isAutomated:e.isAutomated}:{},...void 0!==e.isMeta?{isMeta:e.isMeta}:{},...void 0!==e.source?{source:e.source}:{},...void 0!==e.hiddenMessages?{hiddenMessages:e.hiddenMessages}:{},...void 0!==e.ideContext?{ideContext:e.ideContext}:{},...void 0!==e.ideHint?{ideHint:e.ideHint}:{},...e.images&&e.images.length>0?{images:e.images.map(e=>({...e}))}:{}}))},250);return()=>clearInterval(t)},[a,e,o,n,r])}function useSession(){const[e,t]=at(()=>crypto.randomUUID()),[n,r]=at(!1);return{sessionId:e,setSessionId:t,sessionLoaded:n,setSessionLoaded:r,sessionLoadIdRef:lt(null)}}__name(usePermissionMode,"usePermissionMode"),Gt(),__name(useQueuedMessageFlush,"useQueuedMessageFlush"),Gt(),__name(useSession,"useSession"),Gt(),SR(),Gt(),SR();var Lj=createOSC8Link("https://commandcode.ai/docs/hooks","Docs ↗",!1),Oj=createOSC8Link("https://commandcode.ai/docs/core-concepts/custom-agents","Docs ↗",!1);function buildStartupWarningEntries(e){const t=[];for(const n of e.fileLevelMessages)t.push({message:n,isFileLevel:!0});if(e.summaryLine&&t.push({message:e.summaryLine,isFileLevel:!1}),0===t.length)return[];const n=t[t.length-1];return n.message=`${n.message} ${e.docsLink}`,t.map(t=>t.isFileLevel?uh(t.message,e.fileLevelMetadata):uh(t.message))}function buildHookStartupEntries(e){const t=buildHookStartupMessages(e),n=t.find(e=>!e.isHookWarning);return buildStartupWarningEntries({fileLevelMessages:t.filter(e=>e.isHookWarning).map(e=>e.message),summaryLine:n?.message??null,docsLink:Lj,fileLevelMetadata:{isHookWarning:!0}})}function buildAgentStartupEntries(e){return buildStartupWarningEntries({fileLevelMessages:[],summaryLine:summarizeAgentConfigWarnings(e),docsLink:Oj})}async function submitInitialPrompt({initialPrompt:e,onCommand:t,submitAsUserMessage:n}){const r=e.trim();r.startsWith("/")&&t&&"handled"===(await t(r)).status||await n()}function useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:o,stdout:s,feedState:i,sessionState:a,statusState:l,authState:c,onboarding:d,uiOverlays:u,permissionState:m,harnessReady:p,isSubmittingRef:g,initialPromptSubmittedRef:h,historyManagerRef:f,executeBash:y,setInput:S,onCommand:w}){const v=ut(async()=>{try{const e=await isTasteLearningEnabled();l.setTasteLearningOn(e),e&&await initTasteDir({runtime:createNodeRuntime()})}catch{}},[l.setTasteLearningOn]),k=ut(async()=>{const e=await getConfiguredProvider();c.setCurrentProvider(e)},[c.setCurrentProvider]),C=ut(()=>{},[]),b=ut(e=>{handleSelectSession({selectedSessionId:e,sessionLoadIdRef:a.sessionLoadIdRef,setFeed:i.setFeed,setLiveEntries:i.setLiveEntries,setSessionId:a.setSessionId,setShowSessionSelector:u.setShowSessionSelector,setSessionLoaded:a.setSessionLoaded,setStaticKey:u.setStaticKey,setShareInfo:l.setShareInfo,setCurrentModel:c.setCurrentModel})},[a,i,u,l,c.setCurrentModel]),E=ut(async()=>{const r=await resolveStartupSessionTarget({continueLatest:n,resumeSessionId:t,resume:e,listSessions:listCommandSessions});"load"!==r.kind?"open-picker"===r.kind&&u.setShowSessionSelector(!0):b(r.sessionId)},[n,t,e,b,u]);ct(()=>{(async()=>{const e=await resolveStartupTrust({trust:r,isProjectInitialized:isCommandProjectSessionInitialized,isDirectoryEmpty:__name(()=>isDirectoryEmpty({runtime:createNodeRuntime(),path:process.cwd()}),"isDirectoryEmpty")});if("prompt-trust"===e.kind)return d.setShowTrustPrompt(!0),void d.setCheckingProject(!1);e.initializeFirst&&await initializeCommandProjectSessions(),d.setProjectTrusted(!0),d.setCheckingProject(!1),v(),k(),loadCustomProviderModels(),C(),e.continueOrResume&&await E()})()},[e,n,r]);const T=lt(!1);ct(()=>{T.current||d.projectTrusted&&0!==getCommandZdrPausedFeatures().length&&(T.current=!0,u.setShowZdrNotice(!0))},[d.projectTrusted,u.setShowZdrNotice]);const P=lt(null);ct(()=>{d.projectTrusted&&c.currentModel!==P.current&&(P.current=c.currentModel,u.setModelNotice(getModelNotice(c.currentModel)??null))},[d.projectTrusted,c.currentModel,u.setModelNotice]);const M=lt(null);ct(()=>{if(!p||!d.projectTrusted)return;const e=a.sessionId;if(M.current===e)return;const t=k$(e);if(!t)return;M.current=e;const n=buildHookStartupEntries(t.hookSettingsWarnings);0!==n.length&&i.setFeed(e=>[...e,...n])},[p,d.projectTrusted,a.sessionId,i.setFeed]);const x=lt(null);ct(()=>{if(!p||!d.projectTrusted)return;const e=a.sessionId;if(x.current===e)return;const t=k$(e);if(!t)return;x.current=e;const n=buildAgentStartupEntries(t.agentConfigWarnings);0!==n.length&&i.setFeed(e=>[...e,...n])},[p,d.projectTrusted,a.sessionId,i.setFeed]),ct(()=>{if(!d.projectTrusted)return;const e=createCommandHistoryManager();return f.current=e,e.init(),()=>{e.cleanup()}},[d.projectTrusted,f]),ct(()=>{if(!s)return;const e=createResizeHandler({getColumns:__name(()=>s.columns??0,"getColumns"),bumpStaticKey:__name(()=>u.setStaticKey(e=>e+1),"bumpStaticKey")});return s.prependListener("resize",e),()=>{s.off("resize",e)}},[s,u.setStaticKey]),ct(()=>{o&&d.projectTrusted&&!d.checkingProject&&p&&!u.showSessionSelector&&!h.current&&(h.current=!0,submitInitialPrompt({initialPrompt:o,onCommand:w,submitAsUserMessage:__name(async()=>{await handleSubmit({role:"user",input:o,feed:i.feed,setFeed:i.setFeed,setLiveEntries:i.setLiveEntries,isCmdCodeBusy:i.isCmdCodeBusy,setIsCmdCodeBusy:i.setIsCmdCodeBusy,setQueuedMessages:i.setQueuedMessages,setStatus:l.setStatus,setInteractionTokens:l.setInteractionTokens,updateStatus:l.updateStatus,setUpdateStatus:l.setUpdateStatus,billingLink:l.billingLink,setBillingLink:l.setBillingLink,currentModel:c.currentModel,currentProvider:c.currentProvider,premiumCreditsExhausted:c.premiumCreditsExhausted,setPremiumCreditsExhausted:c.setPremiumCreditsExhausted,setCurrentModel:c.setCurrentModel,sessionId:a.sessionId,isSubmittingRef:g,setInput:S,setStaticKey:u.setStaticKey,executeBash:y})},"submitAsUserMessage")}))},[o,d.projectTrusted,d.checkingProject,u.showSessionSelector,p,a.sessionId,c.currentProvider,w]);const I=lt(null);I.current={feed:i.feed,setFeed:i.setFeed,setLiveEntries:i.setLiveEntries,isCmdCodeBusy:i.isCmdCodeBusy,setIsCmdCodeBusy:i.setIsCmdCodeBusy,setQueuedMessages:i.setQueuedMessages,setStatus:l.setStatus,setInteractionTokens:l.setInteractionTokens,updateStatus:l.updateStatus,setUpdateStatus:l.setUpdateStatus,billingLink:l.billingLink,setBillingLink:l.setBillingLink,currentModel:c.currentModel,currentProvider:c.currentProvider,premiumCreditsExhausted:c.premiumCreditsExhausted,setPremiumCreditsExhausted:c.setPremiumCreditsExhausted,setCurrentModel:c.setCurrentModel,sessionId:a.sessionId,isSubmittingRef:g,setInput:S,setStaticKey:u.setStaticKey,executeBash:y,role:"",input:""};const A=ut(async({role:e,input:t,images:n,imageTokenPaths:r,ideContext:o,ideHint:s,displayMessage:i,isAutomated:a,isMeta:l,source:c,hiddenMessages:d})=>{u.setShowTasteSkipBanner(!1),u.setShowZdrNotice(!1),u.setModelNotice(null),await handleSubmit({...I.current,role:e,input:t,images:n,imageTokenPaths:r,ideContext:o,ideHint:s,displayMessage:i,isAutomated:a,isMeta:l,source:c,hiddenMessages:d})},[u.setShowTasteSkipBanner,u.setShowZdrNotice,u.setModelNotice]);return{loadTasteStatus:v,loadCurrentProvider:k,initializeMcpInBackground:C,onSubmit:A}}function useStatus(e){const[t,n]=at("Ready..."),r=lt(!1),[o,s]=at(""),i=lt(null),[a,l]=at(null),c=lt(a),[d,u]=at(null),[m,p]=at(!1),[g,h]=at(""),[f,y]=at(null),[S,w]=at(0),[v,k]=at(null),[C,b]=at(null),[E,T]=at(e??null);ct(()=>{c.current=a},[a]),ct(()=>{if(!E)return;const e=setTimeout(()=>{T(null)},3e4);return()=>clearTimeout(e)},[E]);const P=__name(e=>{i.current&&clearTimeout(i.current),s(e),i.current=setTimeout(()=>{s(""),i.current=null},5e3)},"showHintMessage");return{status:t,setStatus:n,pinnedStatusRef:r,hintMessage:o,setHintMessage:s,hintTimerRef:i,shareInfo:a,setShareInfo:l,shareInfoRef:c,billingLink:d,setBillingLink:u,showShareNotification:m,setShowShareNotification:p,unshareNotificationMessage:g,setUnshareNotificationMessage:h,retryAttempt:f,setRetryAttempt:y,interactionTokens:S,setInteractionTokens:w,contextUsage:v,setContextUsage:k,tasteLearningOn:C,setTasteLearningOn:b,updateStatus:E,setUpdateStatus:T,showHintMessage:P}}function useTerminalTitle({sessionId:e,isCmdCodeBusy:t,modelLabel:n=null}){const r=lt(process.cwd()),o=lt(e),s=lt(null),i=lt(n);i.current=n;const a=ut(e=>{s.current=e,setTerminalTitle(formatSessionTabTitle({sessionTitle:e,projectDir:r.current,modelLabel:i.current}))},[]),l=ut(e=>{(async()=>{const t=await loadCommandSessionMeta({sessionId:e});o.current===e&&t?.title&&t.title!==s.current&&a(t.title)})()},[a]);ct(()=>{o.current=e,a(null),l(e)},[e,a,l]);const c=lt(!0);ct(()=>{c.current?c.current=!1:a(s.current)},[n,a]);const d=lt(t);ct(()=>{const n=d.current;d.current=t,t!==n&&reassertTerminalTitle(),!t&&n&&(s.current||l(e))},[t,e,l]),ct(()=>{if(!process.stderr.isTTY)return;const e=setInterval(reassertTerminalTitle,5e3);return()=>{clearInterval(e)}},[]);const u=ut(e=>{a(e)},[a]);return{setRenamedTerminalTitle:u,applyGeneratedTitle:u}}function useUiOverlays(){const[e,t]=at(!1),[n,r]=at(!1),[o,s]=at(!1),[i,a]=at(!1),[l,c]=at(!1),[d,u]=at(!1),[m,p]=at(!1),[g,h]=at(!1),[f,y]=at(!1),[S,w]=at(!1),[v,k]=at(!1),[C,b]=at(!1),[E,T]=at(!1),[P,M]=at(!1),[x,I]=at("default"),[A,R]=at(!1),[L,O]=at(!1),[D,$]=at(!1),[N,_]=at(!1),[F,U]=at(!1),[j,B]=at(!1),[W,H]=at(null),[G,V]=at(!1),[z,K]=at(!1),[q,Y]=at(!1),[J,Q]=at(!1),[X,Z]=at(null),[ee,te]=at(0),[ne,re]=at(!1),[oe,se]=at(!1),[ie,ae]=at(null),[le,ce]=at("off"),de="off"!==le,ue=ut(e=>{hardResetForResize(),te(e=>e+1),e(!1)},[]);return{showFileList:e,setShowFileList:t,showAgentsConfig:n,setShowAgentsConfig:r,showTasteConfig:o,setShowTasteConfig:s,showSkillsConfig:i,setShowSkillsConfig:a,showSettingsConfig:l,setShowSettingsConfig:c,showProviderSelector:d,setShowProviderSelector:u,showModelSelector:m,setShowModelSelector:p,showEffortSelector:g,setShowEffortSelector:h,showMemorySelector:f,setShowMemorySelector:y,showMcpManager:S,setShowMcpManager:w,showSessionSelector:v,setShowSessionSelector:k,showAddDirModal:C,setShowAddDirModal:b,showRewindSelector:E,setShowRewindSelector:T,showTreeSelector:P,setShowTreeSelector:M,treeFilterMode:x,setTreeFilterMode:I,treeBranchSummarySkipPrompt:A,setTreeBranchSummarySkipPrompt:R,showLoginOverlay:L,setShowLoginOverlay:O,showCompactModeSelector:D,setShowCompactModeSelector:$,showContextView:N,setShowContextView:_,showStatusView:F,setShowStatusView:U,showPlansView:j,setShowPlansView:B,plansTarget:W,setPlansTarget:H,planBreadcrumbPending:G,setPlanBreadcrumbPending:V,showUsageOverlay:z,setShowUsageOverlay:K,showThemeSelector:q,setShowThemeSelector:Y,staticKey:ee,setStaticKey:te,closeFullScreenOverlay:ue,showTasteSkipBanner:ne,setShowTasteSkipBanner:re,showZdrNotice:oe,setShowZdrNotice:se,modelNotice:ie,setModelNotice:ae,transcriptMode:le,setTranscriptMode:ce,expandedToolOutput:de,showDesignGuide:J,setShowDesignGuide:Q,pendingDesignSuggestion:X,setPendingDesignSuggestion:Z}}__name(buildStartupWarningEntries,"buildStartupWarningEntries"),__name(buildHookStartupEntries,"buildHookStartupEntries"),__name(buildAgentStartupEntries,"buildAgentStartupEntries"),__name(submitInitialPrompt,"submitInitialPrompt"),__name(useStartup,"useStartup"),Gt(),__name(useStatus,"useStatus"),Gt(),SR(),__name(useTerminalTitle,"useTerminalTitle"),Gt(),__name(useUiOverlays,"useUiOverlays");var Dj=__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:c,local:d=!1,sessionTitleHolder:u})=>{const{exit:m}=rt(),{stdout:p}=et();usePasteRouter(),ct(()=>{isLocalOnly()||prefetchBillingContext()},[]);const[g,h]=at(""),[f,y]=at(""),S=lt(!1),w=lt(!1),v=lt(null),k=useUiOverlays(),C=useFeed(),b=useSession(),E=useStatus(s),T=useAuth(),P=usePendingOps(),M=useOnboarding(),x=useExit(),{executeBash:I,executionState:A}=rj(),R=usePermissionMode({initialPermissionMode:c,local:d,dangerouslySkipPermissions:o,setPendingPermission:P.setPendingPermission,setStatus:E.setStatus}),L=dt(()=>getModelShortName({modelId:T.currentModel,findModelById:findModelById}),[T.currentModel]),O=useTerminalTitle({sessionId:b.sessionId,isCmdCodeBusy:C.isCmdCodeBusy,modelLabel:L}),{ready:D}=useHarness({sessionId:b.sessionId,sessionLoaded:b.sessionLoaded,showSessionSelector:k.showSessionSelector,projectTrusted:M.projectTrusted,permissionsService:R.permissionsService,permissionModeRef:R.permissionModeRef,setPermissionMode:R.setPermissionMode,permissionModeExplicit:Boolean(c)||o,dangerouslySkipPermissions:R.dangerouslySkipPermissions,setPendingQuestion:P.setPendingQuestion,setStatus:E.setStatus,setFeed:C.setFeed,queuedMessagesRef:C.queuedMessagesRef,setQueuedMessages:C.setQueuedMessages,onSessionTitled:O.applyGeneratedTitle,currentModel:T.currentModel,setCurrentModel:T.setCurrentModel,setStaticKey:k.setStaticKey,isCmdCodeBusy:C.isCmdCodeBusy}),{onCommand:$}=useCommandCtx({feedState:C,sessionState:b,statusState:E,authState:T,uiOverlays:k,onboarding:M,exitState:x,permissionState:R,terminalTitleState:O,isSubmittingRef:S,executeBash:I,setInput:h});useAgentSlashCommandQueue({sessionId:b.sessionId,isCmdCodeBusy:C.isCmdCodeBusy,onCommand:$}),ct(()=>{k.planBreadcrumbPending&&!C.isCmdCodeBusy&&(k.setPlanBreadcrumbPending(!1),C.setFeed(e=>[...e,fh("Plan saved — run /plans to review, annotate, or execute it anytime.")]))},[k.planBreadcrumbPending,k.setPlanBreadcrumbPending,C.isCmdCodeBusy,C.setFeed]);const{loadTasteStatus:N,loadCurrentProvider:_,onSubmit:F}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:a,stdout:p,feedState:C,sessionState:b,statusState:E,authState:T,onboarding:M,uiOverlays:k,permissionState:R,harnessReady:D,isSubmittingRef:S,initialPromptSubmittedRef:w,historyManagerRef:v,executeBash:I,setInput:h,onCommand:$});useMonitorOutputWakeup({onSubmit:F}),useCronWakeup({sessionId:b.sessionId,onSubmit:F}),useQueuedMessageFlush({isCmdCodeBusy:C.isCmdCodeBusy,queuedMessages:C.queuedMessages,queuedMessagesRef:C.queuedMessagesRef,setQueuedMessages:C.setQueuedMessages,isSubmittingRef:S,onSubmit:F}),useLifecycle({exit:m,feedState:C,exitState:x,statusState:E,authState:T,onboarding:M,uiOverlays:k,skipOnboarding:l,sessionId:b.sessionId,sessionTitleHolder:u});const{handleToggleAutoAccept:U,handleEnableAutoAccept:j,handleDoubleEscapeEmpty:B,handleTasteOnboardingComplete:W,handleTrust:H,handleNoTrust:G}=useHandlers({resume:e,feedState:C,onboarding:M,uiOverlays:k,exitState:x,pendingOps:P,permissionState:R,statusState:E,authState:T,sessionId:b.sessionId,loadTasteStatus:N,loadCurrentProvider:_,setInput:__name(e=>h(e),"setInput")}),V=useMainActionCallbacks({feedState:C,sessionState:b,statusState:E,authState:T,uiOverlays:k,setInput:h}),{creditWarning:z}=useCreditWarning({interactionTokens:E.interactionTokens,currentModel:T.currentModel});return renderView({feedState:C,sessionState:b,statusState:E,authState:T,uiOverlays:k,onboarding:M,exitState:x,pendingOps:P,permissionState:R,historyManagerRef:v,executionState:A,actionCallbacks:V,onSubmit:F,onCommand:$,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,updateFailedInfo:i,creditWarning:z,handleTrust:H,handleNoTrust:G,handleToggleAutoAccept:U,handleEnableAutoAccept:j,handleDoubleEscapeEmpty:B,handleTasteOnboardingComplete:W,loadTasteStatus:N})},"InteractiveCLI");function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:i,pendingOps:a,permissionState:l,historyManagerRef:c,executionState:d,actionCallbacks:u,onSubmit:m,onCommand:p,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,updateFailedInfo:S,creditWarning:w,handleTrust:v,handleNoTrust:k,handleToggleAutoAccept:C,handleEnableAutoAccept:b,handleDoubleEscapeEmpty:E,handleTasteOnboardingComplete:T,loadTasteStatus:P}){if(i.shouldExit)return null;if(s.checkingProject)return null;if(s.showTrustPrompt)return st.createElement(tj,{staticKey:o.staticKey,onTrust:v,onExit:k});if(o.showSessionSelector)return st.createElement(ZU,{onSelectSession:u.onSelectSession,onClose:()=>o.closeFullScreenOverlay(o.setShowSessionSelector),currentSessionId:t.sessionId});if(!s.projectTrusted)return null;const M=o.pendingDesignSuggestion?st.createElement(g_,{suggestion:o.pendingDesignSuggestion,onSelect:e=>{p(`/design ${e}`)},onClose:()=>o.setPendingDesignSuggestion(null)}):null,x=a.pendingQuestion?.params.exitPlanMode?a.pendingQuestion:null,I=a.pendingQuestion&&!x?st.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,dangerouslySkipPermissions:l.dangerouslySkipPermissions,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:o.setStaticKey}):null,A=a.pendingPermission?st.createElement(o_,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleEnableAutoAccept:b}):null,{closeFullScreenOverlay:R}=o;if(x){const e=__name(e=>{const t=resolvePlanModeAnswerTransition({answer:e,exitPlanMode:!0,dangerouslySkipPermissions:l.dangerouslySkipPermissions});t&&l.setPermissionMode(t),x.resolve({answers:[{questionIndex:0,selectedOptions:[e]}]}),a.setPendingQuestion(null),hardResetForResize(),o.setStaticKey(e=>e+1)},"resolveApproval");return st.createElement(PlanApprovalView,{staticKey:o.staticKey,planContent:x.params.planContent,planFilePath:x.params.planFilePath,onAutoAccept:t=>{e("Yes, auto-accept edits"),t&&m({role:"user",input:t})},onCancel:()=>{e("Cancel"),o.setPlanBreadcrumbPending(!0)},onSendFeedback:t=>{e("Cancel"),m({role:"user",input:t})}})}if(o.showTasteConfig)return st.createElement(TasteConfigView,{staticKey:o.staticKey,onClose:()=>R(o.setShowTasteConfig),loadTasteStatus:P});if(o.showSkillsConfig)return st.createElement(SkillsConfigView,{staticKey:o.staticKey,onClose:()=>R(o.setShowSkillsConfig)});if(o.showSettingsConfig)return st.createElement(SettingsConfigView,{staticKey:o.staticKey,onClose:()=>R(o.setShowSettingsConfig),loadTasteStatus:P});if(o.showUsageOverlay)return st.createElement(UsageView,{staticKey:o.staticKey,onClose:()=>R(o.setShowUsageOverlay)});if(o.showContextView)return st.createElement(ContextConfigView,{staticKey:o.staticKey,sessionId:t.sessionId,onClose:()=>R(o.setShowContextView),setInput:h});if(o.showStatusView)return st.createElement(StatusConfigView,{staticKey:o.staticKey,sessionId:t.sessionId,onClose:()=>R(o.setShowStatusView),setInput:h});if(o.showPlansView){const e=__name(e=>{o.setPlansTarget(null),R(o.setShowPlansView),m({role:"user",input:e})},"submitFromPlans");return st.createElement(PlansView,{staticKey:o.staticKey,sessionId:t.sessionId,target:o.plansTarget,onClose:()=>{o.setPlansTarget(null),R(o.setShowPlansView)},onSubmitFeedback:e,onExecute:n=>{"plan"===l.permissionModeRef.current&&(l.permissionModeRef.current="auto-accept",l.setPermissionMode("auto-accept"),k$(t.sessionId)?.setPermissionMode({mode:"auto-accept"})),e(n)}})}return st.createElement(CU,{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,modelNotice:o.modelNotice,retryAttempt:n.retryAttempt,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,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,showTreeSelector:o.showTreeSelector,treeFilterMode:o.treeFilterMode,treeBranchSummarySkipPrompt:o.treeBranchSummarySkipPrompt,showLoginOverlay:o.showLoginOverlay,showUsageOverlay:o.showUsageOverlay,setShowUsageOverlay:o.setShowUsageOverlay,showAddDirModal:o.showAddDirModal,showCompactModeSelector:o.showCompactModeSelector,showThemeSelector:o.showThemeSelector,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:S,creditWarning:w,permissionMode:l.permissionMode,hintMessage:n.hintMessage,pendingExitKey:i.pendingExitKey,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,tasteLearningOn:n.tasteLearningOn,historyManagerRef:c,executionState:d,sessionId:t.sessionId,onSubmit:m,onCommand:p,onToggleAutoAccept:C,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:E,onTasteOnboardingComplete:T,permissionPanel:A,questionPanel:I,designSuggestionPanel:M,onRewindSelect:u.onRewindSelect,onRewindCancel:u.onRewindCancel,onTreeSelect:u.onTreeSelect,onTreeCancel:u.onTreeCancel,onTreeLabel:u.onTreeLabel,onTreeAbortSummary:u.onTreeAbortSummary,onLoginComplete:u.onLoginComplete,onLoginCancel:u.onLoginCancel,setShowProviderSelector:o.setShowProviderSelector,setShowModelSelector:o.setShowModelSelector,setShowEffortSelector:o.setShowEffortSelector,setShowMemorySelector:o.setShowMemorySelector,setShowMcpManager:o.setShowMcpManager,setShowAgentsConfig:o.setShowAgentsConfig,setShowRewindSelector:o.setShowRewindSelector,setShowTreeSelector:o.setShowTreeSelector,setShowLoginOverlay:o.setShowLoginOverlay,setShowAddDirModal:o.setShowAddDirModal,handleProviderSelect:u.handleProviderSelect,handleProviderCancel:u.handleProviderCancel,handleModelSelect:u.handleModelSelect,handleModelCancel:u.handleModelCancel,handleCompactModeSelect:u.handleCompactModeSelect,handleCompactModeCancel:u.handleCompactModeCancel,handleThemeSelect:u.handleThemeSelect,handleThemeCancel:u.handleThemeCancel,handleAuthSuccess:u.handleAuthSuccess,handleAuthCancel:u.handleAuthCancel,showDesignGuide:o.showDesignGuide,setShowDesignGuide:o.setShowDesignGuide})}__name(renderView,"renderView"),SR(),Gt();var $j=__name(({worktreePath:e,warning:t,onChoice:n})=>{const[r,o]=at(1);return nt((e,t)=>{if(!t.upArrow&&!t.downArrow)return"1"===e?n("keep"):"2"===e?n("remove"):t.return?n(1===r?"keep":"remove"):t.escape||t.ctrl&&"c"===e?n("keep"):void 0;o(e=>1===e?2:1)}),st.createElement(bO,{title:"Exiting worktree session",subtitle:t,hint:"Enter to confirm · Esc to cancel"},st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,{color:1===r?ER.CYAN:ER.GRAY},1===r?gt.pointer:" "," 1. Keep worktree"," ",st.createElement(Xe,{color:ER.GRAY},"Stays at ",tildeHome(e)))),st.createElement(Qe,null,st.createElement(Xe,{color:2===r?ER.CYAN:ER.GRAY},2===r?gt.pointer:" "," 2. Remove worktree"," ",st.createElement(Xe,{color:ER.GRAY},"All changes and commits will be lost.")))))},"WorktreeExitPrompt");function promptWorktreeExit(e){return new Promise(t=>{const{unmount:n}=tt(st.createElement($j,{worktreePath:e.worktreePath,warning:e.warning,onChoice:e=>{n(),t(e)}}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})})}function clearedHandoffEnv(e=process.env,t=process.pid){return{...releasedPaneOwnerEnv(e,t)}}function canRespawn(){if(process.versions.bun)return!1;const e=process.argv[1];return"string"==typeof e&&e.length>0}function resetTerminalForRespawn(){process.stdout.isTTY&&RL()}async function writeReloadHandoff(e){const t=process.env[zM];if(t)try{await z.writeFile(t,serializeReloadCarryover(e))}catch{}}async function consumeReloadHandoff(e){try{return parseReloadCarryover(await z.readFile(e,"utf-8"))}catch{return null}finally{await z.unlink(e).catch(()=>{})}}function restoreTerminal({signal:e=null}={}){try{process.stdin.isTTY&&process.stdin.setRawMode(!1)}catch{}try{process.stdout.write("[?25h")}catch{}if(e)try{popKittyKeyboardProtocol()}catch{}}__name(promptWorktreeExit,"promptWorktreeExit"),Gt(),SR(),__name(clearedHandoffEnv,"clearedHandoffEnv"),__name(canRespawn,"canRespawn"),__name(resetTerminalForRespawn,"resetTerminalForRespawn"),__name(writeReloadHandoff,"writeReloadHandoff"),__name(consumeReloadHandoff,"consumeReloadHandoff"),__name(restoreTerminal,"restoreTerminal");var Nj=ht.hex(ER.DIM);function printReloadFallbackHint(){process.stdout.write(Nj("Couldn't restart automatically in this build — exiting instead.\n"))}async function shutdownWrapperRuntime(){try{await Promise.allSettled([disconnectAllMcpServers(),b$(),disposeCommandModHost()])}catch{}try{await shutdownTelemetry()}catch{}process.removeAllListeners("SIGINT"),process.removeAllListeners("SIGTERM"),process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{}),process.stdin.pause()}async function runRelaunchLoop(e){await shutdownWrapperRuntime();const n=await z.mkdtemp(t.join(B.tmpdir(),"cmd-reload-")),r=t.join(n,"handoff.json");let o=e;for(;;){const e=await commandSessionTranscriptExists(o.sessionId),t=buildRelaunchArgs({invocation:getOriginalInvocation(),request:o,resumable:e,argv:process.argv.slice(2)});clearTerminalTitle(),resetTerminalForRespawn();const s=w(process.execPath,[process.argv[1],...t],{stdio:"inherit",env:{...process.env,[zM]:r,[KM]:String(process.pid),...clearedHandoffEnv()}});let i,a;try{[i,a]=await new Promise((e,t)=>{s.once("exit",(t,n)=>e([t,n])),s.once("error",t)})}catch(e){restoreTerminal(),process.stderr.write(Nj(`\nCouldn't relaunch Command Code: ${e.message}\n`)),await z.rm(n,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}if(i!==VM){if(restoreTerminal({signal:a}),await z.rm(n,{recursive:!0,force:!0}).catch(()=>{}),a){const e=B.constants.signals[a];process.exit(e?128+e:1)}process.exit(i??1)}else o=await consumeReloadHandoff(r)??o}}async function handlePendingReload(e){canRespawn()?(isWrappedChild()&&(await writeReloadHandoff(e),await disposeCommandModHost(),process.exit(VM)),await runRelaunchLoop(e)):printReloadFallbackHint()}__name(printReloadFallbackHint,"printReloadFallbackHint"),__name(shutdownWrapperRuntime,"shutdownWrapperRuntime"),__name(runRelaunchLoop,"runRelaunchLoop"),__name(handlePendingReload,"handlePendingReload"),Gt(),SR();var _j=["disambiguateEscapeCodes"];async function resolveKittyKeyboard(e={}){const t=e.env??process.env,n=e.probe??queryKittyKeyboardSupport,r=!isVSCodeTerminal2({env:t})&&await n();return setKittyKeyboardActive(r),{mode:r?"enabled":"disabled",flags:_j}}__name(resolveKittyKeyboard,"resolveKittyKeyboard");var Fj=ht.hex(ER.DIM),Uj=__name(()=>{const e=getInvokedCommandName();return"win32"===process.platform&&"cmd"===e?"cmdc":e},"getResumeCommandName"),jj=__name((e,t)=>{const n=Uj(),r=Ce([e]),o=t?`cd ${Ce([t])} && ${n} --resume ${r}`:`${n} --resume ${r}`;return`${Fj("Resume this session with:")}\n${Fj(o)}\n`},"formatResumeHint"),Bj=__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"),Wj=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),Hj=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),Gj=__name(e=>e.permissionMode?e.permissionMode:e.plan?"plan":void 0,"resolveInitialPermissionMode"),Vj=__name(({options:e,resumeSessionId:t,sessionTitleHolder:n})=>{const r=Gj(e);return{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,local:e.local,sessionTitleHolder:n}},"buildInteractiveCLIProps"),zj=__name(e=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1,kittyKeyboard:e}),"getInkRenderOptions"),Kj=!1,qj=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode(),!Kj&&isKittyKeyboardActive()&&popKittyKeyboardProtocol()})},"setupBracketedPasteMode"),Yj=__name(()=>{qj()},"initializeTerminal"),Jj=__name(()=>{process.on("SIGINT",()=>{})},"swallowSigintDuringShutdown"),Qj=__name(async e=>{const{resumeSessionId:t,useContinue:n}=e,r=n?(await listCommandSessions())[0]?.id:void 0,o=t??r;if(!o)return console.error("--fork-session ignored: no session to fork (use with --resume <id|name> or --continue)."),null;try{const{newId:e}=await forkCommandSessionFiles({sourceId:o});return e}catch(e){const t=e instanceof Error?e.message:String(e);return console.error(`--fork-session failed: ${t}. Resuming the original session.`),null}},"forkSourceAtColdStart"),Xj=__name(async(e={})=>{const t=Bj(process.stdin.isTTY);let n,o;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),Yj(),"string"==typeof e.resume){const t=e.resume.trim();await isCommandProjectSessionInitialized()||(console.error("Project not initialized. Run cmd to start a conversation first."),process.exit(1));const r=await resolveCommandSessionRef({sessionRef:t});"not-found"===r.status&&(console.error(buildSessionRefNotFoundMessage(t)),process.exit(1)),n=r.sessionId}if("string"==typeof e.session&&!n){const t=getCommandSessionRuntime(),i=await listAllSessionsV3({runtime:t}),a=getProjectSessionDir({env:t.env(),cwd:t.cwd()}),l=resolveSessionRefFlag({ref:e.session,isExistingFile:__name(e=>A(e),"isExistingFile"),listSessionIds:__name(()=>i.map(e=>e.id),"listSessionIds")});"not-found"===l.kind&&(console.error(`--session "${e.session}" is neither an existing .jsonl transcript nor a known session-id prefix.`),process.exit(1)),"ambiguous"===l.kind&&(console.error(`--session "${e.session}" is ambiguous — matches: ${l.candidates.join(", ")}`),process.exit(1));const d="path"===l.kind?s(l.path):s(i.find(e=>e.id===l.sessionId)?.path??"");n=c(d,".jsonl"),r(d)!==a&&(o=d)}if(Wj(e)&&!n){const e=await isCommandProjectSessionInitialized(),t=e?await listCommandSessions():[],n=Hj({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}if(e.forkSession){const t=await Qj({resumeSessionId:n,useContinue:Boolean(e.continue)});t&&(n=t,e.continue=!1)}await applyStartupTheme();const i=await resolveKittyKeyboard();startEarlyInputCapture(),setStartupSessionOptions({...!1===e.session?{persist:!1}:{},...o?{sessionFilePath:o}:{},...e.name?{name:e.name}:{}});const a={},l=Vj({options:e,resumeSessionId:n,sessionTitleHolder:a}),d=zj(i),u=tt(st.createElement(Dj,{...l}),d);registerInkControl({clear:u.clear,stdout:process.stdout,instance:await resolveInkInstance(process.stdout)}),await u.waitUntilExit(),Kj=!0,clearTerminalTitle(),Jj();const m=consumePendingReload();m&&await handlePendingReload(m);const p=await(a.loadTitle?.())??null,g=Boolean(p);let h;const f=getAutoCreatedWorktree();if(f){const e=worktreeHasWork(f.worktreePath,f.baseSha);let t="auto";if(e||g){const n=worktreeChangeCount(f.worktreePath),r=e?n>0?`You have ${n} uncommitted file${1===n?"":"s"}. These will be lost if you remove the worktree.`:"This worktree has commits that are not on your main branch. They will be lost if you remove it.":null;t=await promptWorktreeExit({worktreePath:f.worktreePath,warning:r})}const n=finalizeAutoCreatedWorktree(t);if(n.worktreePath){const e=Fj(createOSC8Link(fileUrl(n.worktreePath),tildeHome(n.worktreePath),!1));if(n.removed){const n="auto"===t?"Removed empty worktree":"Removed worktree";process.stdout.write(`${Fj(n)}\n${e}\n\n`)}else if(n.kept){h=n.worktreePath;const t=n.reason&&"kept"!==n.reason?` (${n.reason})`:"";process.stdout.write(`${Fj(`Kept worktree${t}`)}\n${e}\n\n`)}}}const y=a.sessionId;if(y&&await commandSessionExists(y)){const e=p?sanitizeTitleForOutput(p):"";process.stdout.write(jj(e||y,h))}},"interactiveMode");Gt(),SR(),Gt();function isAgentMetrics(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&"number"==typeof t.turns&&"object"==typeof t.toolCalls&&null!==t.toolCalls&&"number"==typeof t.toolErrors&&"number"==typeof t.tokens&&"number"==typeof t.durationMs}function extractAgentMetrics(e){const t=e.indexOf("\x3c!-- BENCHMARK_AGENT_METRICS:");if(-1===t)return{cleanContent:e,metrics:null};const n=t+29,r=e.indexOf(" --\x3e",n);if(-1===r)return{cleanContent:e,metrics:null};try{const o=e.substring(n,r),s=JSON.parse(o);return isAgentMetrics(s)?{cleanContent:e.substring(0,t).trimEnd()+e.substring(r+4),metrics:s}:{cleanContent:e,metrics:null}}catch{return{cleanContent:e,metrics:null}}}__name(isAgentMetrics,"isAgentMetrics"),__name(extractAgentMetrics,"extractAgentMetrics");var Zj=__name(e=>({turnNumber:e,apiDurationMs:0,toolCalls:[],toolDurationMs:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}),"newTurn");function createBenchmarkCollector(e){const t=e.now??Date.now,n=e.writeFile??((e,t)=>{x.writeFileSync(e,t)}),r=t(),o=[],s=[],i=new Map,a=new Map;let l,c=!1;const d=__name(e=>{let t=e;for(;;){const{cleanContent:e,metrics:n}=extractAgentMetrics(t);if(!n)return;s.push(n),t=e}},"collectAgentMetrics"),u=__name(()=>{const e=o[o.length-1];if(e)return e;const t=Zj(o.length+1);return o.push(t),t},"currentTurn"),m=__name(e=>{const n=u(),r=i.get(e.toolCallId);void 0!==r&&(n.toolDurationMs+=t()-r,i.delete(e.toolCallId));const o=a.get(e.toolCallId);o?o.isError=e.isError||o.isError:n.toolCalls.push({name:e.toolName,isError:e.isError})},"finishToolCall"),p=__name(e=>{if("turn_start"!==e.type)if("model_request_start"!==e.type){if("model_request_end"===e.type){const n=u();return void 0!==l&&(n.apiDurationMs+=t()-l,l=void 0),n.inputTokens+=e.usage.inputTokens,n.outputTokens+=e.usage.outputTokens,n.cacheReadTokens+=e.usage.cacheReadTokens,void(n.cacheCreationTokens+=e.usage.cacheWriteTokens)}if("tool_running"===e.type){const n={name:e.toolName,isError:!1};return i.set(e.toolCallId,t()),a.set(e.toolCallId,n),void u().toolCalls.push(n)}if("tool_completed"!==e.type)"tool_errored"!==e.type&&"tool_denied"!==e.type&&"tool_hook_blocked"!==e.type?"run_end"!==e.type||(c=c||"max_turns"===e.result.stopReason):m({toolCallId:e.toolCallId,toolName:e.toolName,isError:!0});else{m({toolCallId:e.toolCallId,toolName:e.toolName,isError:!1});for(const t of e.result)"text"===t.type&&d(t.text)}}else l=t();else o.push(Zj(e.turnNumber))},"onEvent"),g=__name(()=>{const e={};let n=0,i=0,a=0,l=0;for(const t of o){for(const r of t.toolCalls)n++,e[r.name]=(e[r.name]??0)+1,r.isError&&i++;a+=t.inputTokens,l+=t.outputTokens}return{wallTimeMs:t()-r,turns:o.length,turnDetails:o.map(e=>({turnNumber:e.turnNumber,apiDurationMs:e.apiDurationMs,toolCalls:e.toolCalls.map(e=>({name:e.name,isError:e.isError})),toolDurationMs:e.toolDurationMs,inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheReadTokens:e.cacheReadTokens,cacheCreationTokens:e.cacheCreationTokens})),toolCalls:{total:n,byType:e,errors:i},tokens:{input:a,output:l},maxTurnsReached:c,agents:[...s]}},"snapshot"),h=__name(()=>{try{n(e.outputPath,JSON.stringify(g(),null,2))}catch{}},"write");return{onEvent:p,snapshot:g,write:h}}__name(createBenchmarkCollector,"createBenchmarkCollector");var eB=null,tB=!1;function resolveLaunchPermissionMode(e){return e.permissionMode?e.permissionMode:e.plan?"plan":e.dangerouslySkipPermissions?"bypass":void 0}function getAuthKey4(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}async function readStdin(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("Timeout reading from stdin"))},3e4);process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n)}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}function writeOutput(e,t){return!t||e.destroyed?Promise.resolve():new Promise((n,r)=>{e.write(t,e=>{e?r(e):n()})})}function setupSignalHandlers(){if(tB)return;tB=!0;const e=__name(e=>{eB?.abort(),process.stderr.write(`\n${e}\n`),exitAfterModHostTeardown(rT.INTERRUPTED)},"handleTermination");process.on("SIGINT",()=>e("Interrupted.")),process.on("SIGTERM",()=>e("Terminated."))}async function printMode(e={}){trackCommand({command:"print"}),setupSignalHandlers(),eB=new AbortController;const t=e.benchmarkOutput?createBenchmarkCollector({outputPath:e.benchmarkOutput}):null,n=resolveToolEnable({flags:e,env:process.env}),r=toolEnableWarning(n);r&&process.stderr.write(`${r}\n`);const o=await runPrintMode({options:e,stdinIsTTY:Boolean(process.stdin.isTTY),readStdin:readStdin,isAuthenticated:__name(async()=>null!==await getAuthKey4(),"isAuthenticated"),createHarness:__name(async({sessionId:t,entrypoint:r,headless:o,maxTurns:s,mods:i,resumeState:a,sessionFilePath:l})=>{const c=await createHarnessSession({sessionId:t,baseUrl:getApiBaseUrl(),entrypoint:r,headless:o,maxTurns:s,mods:i,dangerouslySkipPermissions:e.dangerouslySkipPermissions,permissionMode:resolveLaunchPermissionMode(e),...n.forceEnabledTools?{forceEnabledTools:n.forceEnabledTools}:{},modHost:await loadCommandModHost({projectMods:Boolean(e.dangerouslySkipPermissions)}),resumeState:a,persist:e.persist,sessionFilePath:l,ideBridge:createLocalIdeBridge()});return e.name&&c.setSessionName(e.name),c},"createHarness"),emit:__name(e=>{"session"===e.type&&process.stderr.write(`session: ${e.sessionId}\n`)},"emit"),writeStdout:__name(e=>{process.stdout.write(e)},"writeStdout"),...t?{runQuery:__name(e=>runHarnessQuery({...e,onEvent:__name(n=>{e.onEvent?.(n),t.onEvent(n)},"onEvent")}),"runQuery")}:{}});t?.write(),await Promise.all([writeOutput(process.stdout,o.stdoutText),writeOutput(process.stderr,o.stderrText)]),exitAfterModHostTeardown(o.exitCode)}__name(resolveLaunchPermissionMode,"resolveLaunchPermissionMode"),__name(getAuthKey4,"getAuthKey"),__name(readStdin,"readStdin"),__name(writeOutput,"writeOutput"),__name(setupSignalHandlers,"setupSignalHandlers"),__name(printMode,"printMode"),Gt(),SR();var nB=getPackageJson(import.meta.url),rB="string"==typeof nB.version&&nB.version.trim()?nB.version:"unknown";function createSystemOneTransport(){const e=b();return createNodeTransport({baseUrl:getApiBaseUrl(),headers:__name(()=>resolveCommandAuthHeaders({sessionId:e,cliVersion:rB}),"headers")})}function readStdinText(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("timeout reading from stdin"))},3e4);r.unref?.(),process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n)}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}function systemOneUsageHint(e){return`Run it headlessly: cmd -p '{"state": "...", "questions": {"<name>": {"type": "noul", "instructions": "..."}}}' -m ${e}`}async function runSystemOnePrint(e){const t=e.now??Date.now,n=t(),r="json"===e.outputFormat,o=__name((o,s,i=`Error: ${o}\n`)=>r?{exitCode:s,stderrText:i,stdoutText:`${safeJsonStringify({type:"result",subtype:"error",model:e.model,durationMs:t()-n,error:o})}\n`}:{exitCode:s,stderrText:i},"fail");let s=e.query;if(void 0===s||""===s.trim()){if(e.stdinIsTTY)return o(`no request given. ${systemOneUsageHint(e.model)}, or pipe the JSON on stdin`,rT.ERROR);try{s=await e.readStdin()}catch(e){return o(`could not read stdin: ${e instanceof Error?e.message:String(e)}`,rT.ERROR)}}const i=parseSystemOneQuery(s);if(!i.ok)return o(i.error,rT.ERROR);const a=await runSystemOne({transport:e.transport,model:e.model,request:i.request,...e.signal?{signal:e.signal}:{}});if(!a.ok&&"bad-response"===a.kind)return o(a.error,rT.SERVER_ERROR);if(!a.ok){const e=classifyPrintModeError(a.error);return o(e.stderrText.replace(/^\s*Error: /,"").trim(),e.exitCode,e.stderrText)}const{response:l}=a;if(!r){const t={model:l.model??e.model,answers:l.answers,usage:l.usage??{}};return{exitCode:rT.SUCCESS,stdoutText:`${JSON.stringify(t,null,2)}\n`}}const c=safeJsonStringify({type:"result",subtype:"success",model:l.model??e.model,answers:l.answers,usage:l.usage??{},durationMs:t()-n});return{exitCode:rT.SUCCESS,stdoutText:`${c}\n`}}async function ensureAuthenticated(){return ensureCommandAuthenticated({runLogin:__name(async()=>{await runLogin()},"runLogin"),getAuthKey:__name(()=>getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env}),"getAuthKey"),onAuthFailed:__name(()=>{console.error(`${gt.cross} Authentication failed. Please try again with: ${getBinaryCommand()} login`)},"onAuthFailed"),onLoginError:__name(e=>{console.error(`${gt.cross} Login failed: ${getErrorMessage(e)}`),console.error(`Please try again with: ${getBinaryCommand()} login`)},"onLoginError"),onCheckError:__name(e=>{console.error("Error checking authentication:",e)},"onCheckError")})}function suggestModel(e){return suggestModelInput({input:e,models:[...getAllModelOptions(),...customModelListOptions()]})}function formatModelList(e={}){return formatModelListText({color:e.color,defaultModel:pr,groups:[...getModelGroupsInOrder(),...customModelListGroups()]})}function formatSystemOneModelNote(){const e=["Decision models (headless only)"],t=isJevFree()?"free through September 24, 2026":"$0.042 per 1M input tokens, everything else free";for(const n of GP)e.push(`${n} typed questions in, probabilities out, ${t} — ${systemOneUsageHint(n)}`);return e.join("\n")}async function printModelList(){await loadCustomProviderModels();const e=Boolean(process.stdout.isTTY)&&void 0===process.env.NO_COLOR;process.stdout.write(`${formatModelList({color:e})}\n`),process.stdout.write(`\n${formatSystemOneModelNote()}\n`);const t=getCustomProviderWarningsSync();t.length>0&&process.stderr.write(`\nproviders.json needs attention — ${1===t.length?"one entry":"some entries"} did not load as written:\n${t.map(e=>` ${e}`).join("\n")}\n`)}async function resolveModelFlagOrExit({model:e}){const t=await resolveSelectableModel(e);if(t){if(t.warning&&process.stderr.write(`Note: ${t.warning}\n`),!t.providerId){const e=customProvidersDeclaring(t.modelId);e.length>0&&process.stderr.write(`Note: "${t.modelId}" routes via Command Code; your providers.json also declares it — use ${e.map(e=>`"${e}/${t.modelId}"`).join(" or ")} to route there instead.\n`)}return{modelId:t.modelId,...void 0!==t.providerId?{providerId:t.providerId}:{}}}const n=suggestModel(e),r=n?` Did you mean "${n}"?`:"";process.stderr.write(`Error: unknown model "${e}".${r}\nRun "${getBinaryCommand()} --list-models" to see all available models\n`),process.exit(1)}__name(createSystemOneTransport,"createSystemOneTransport"),__name(readStdinText,"readStdinText"),__name(systemOneUsageHint,"systemOneUsageHint"),__name(runSystemOnePrint,"runSystemOnePrint"),Gt(),SR(),__name(ensureAuthenticated,"ensureAuthenticated"),Gt(),SR(),__name(suggestModel,"suggestModel"),__name(formatModelList,"formatModelList"),__name(formatSystemOneModelNote,"formatSystemOneModelNote"),__name(printModelList,"printModelList"),__name(resolveModelFlagOrExit,"resolveModelFlagOrExit"),Gt(),SR();var oB=!1;function getAuthKey5(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function setupTelemetry(){initTelemetry()&&(startSession(),registerStartupTask(trackSystemInfo()),trackCliSessionExistsEvent(),registerCleanupHandlers())}function trackSystemInfo(){return trackTelemetryIdentity({client:createApiClient({baseUrl:getApiBaseUrl()}),platform:j.platform(),arch:j.arch()})}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}async function disconnectMcpServers(){try{await Promise.allSettled([disconnectAllMcpServers(),b$()])}catch{}}function handleShutdownSignal(){oB||(oB=!0,abandonPendingCommandSpan(),Promise.allSettled([disconnectMcpServers(),disposeCommandModHost(),shutdownTelemetry()]).finally(()=>{process.exit(0)}))}async function shutdownAndExit(e=0){oB=!0,abandonPendingCommandSpan();try{await Promise.allSettled([disconnectMcpServers(),disposeCommandModHost(),shutdownTelemetry(Un)])}finally{process.exit(e)}}async function trackCliSessionExistsEvent(){try{if(!await getAuthKey5())return;const e=getSessionId();if(!e)return;const t=getPackageJson(import.meta.url).version||"unknown",n=j.platform(),r=j.arch(),o=isTTY()?"interactive":"non-interactive";await trackLifecycleEvent({eventType:"cli_session_exists",metadata:{sessionId:e,cliVersion:t,mode:o,os:`${n}-${r}`},isTelemetryEnabled:isTelemetryEnabled,createClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createClient"),log:dlog})}catch{}}__name(getAuthKey5,"getAuthKey"),__name(setupTelemetry,"setupTelemetry"),__name(trackSystemInfo,"trackSystemInfo"),__name(registerCleanupHandlers,"registerCleanupHandlers"),__name(disconnectMcpServers,"disconnectMcpServers"),__name(handleShutdownSignal,"handleShutdownSignal"),__name(shutdownAndExit,"shutdownAndExit"),__name(trackCliSessionExistsEvent,"trackCliSessionExistsEvent");var sB=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth");async function interactiveModeAction(e,t){if(trackCommand({command:"interactive"}),t.listModels)return void await printModelList();if(t.addDir&&t.addDir.length>0)for(const e of t.addDir)By.addDirectory(e);t.mod&&t.mod.length>0&&setModPathsOverride(t.mod),t.modOption&&t.modOption.length>0&&setModOptionsOverride(t.modOption);const n=(t.skill??[]).map(e=>s(e)),r=!1!==t.skills;if(setSkillLoadOverrides({extraPaths:n,discovery:r}),void 0!==t.worktree&&!1!==t.worktree){const e=void 0!==t.print;e||Boolean(t.trust||t.dangerouslySkipPermissions)||await isCommandProjectSessionInitialized()||(console.error(`Worktree error: this directory isn't trusted yet. Run \`${getInvokedCommandName()}\` here once to trust it, then retry with --worktree.`),process.exit(1));const n=enterWorktreeFromFlag(t.worktree,{quiet:e,track:!e});n.ok||(console.error(`Worktree error: ${n.error}`),process.exit(1)),await initializeCommandProjectSessions()}const o=t.model?resolveSystemOneModel(t.model):void 0;if(o){void 0===t.print&&(process.stderr.write(`Error: ${o} is a decision model (TypeSafe System One): it answers typed questions with probabilities, not chat, so it has no interactive mode. ${systemOneUsageHint(o)}\n`),process.exit(1)),await sB(),trackCommand({command:"print"});const n=await runSystemOnePrint({model:o,query:extractPrintModeQuery({print:t.print,prompt:e}),outputFormat:t.outputFormat,stdinIsTTY:Boolean(process.stdin.isTTY),readStdin:readStdinText,transport:createSystemOneTransport()});n.stderrText&&process.stderr.write(n.stderrText),n.stdoutText&&process.stdout.write(n.stdoutText),await shutdownAndExit(n.exitCode)}const i=t.model?await resolveModelFlagOrExit({model:t.model}):void 0,a=i?.modelId,l=t,c=__name(e=>{process.stderr.write(`${e.message}\n`),e.ok||process.exit(1)},"applySettingResult");for(const e of TN){const t=l[e.key];"string"==typeof t&&c(await e.apply(t,{model:a}))}const d=l.config;if(Array.isArray(d))for(const e of d)"string"==typeof e&&c(await applyConfigSetting(e));if((t.dangerouslySkipPermissions||"bypass"===t.permissionMode)&&isBypassPermissionsDisabled(await loadCommandCodeConfig({runtime:getCommandConfigRuntime()}))&&(process.stderr.write("Bypass permissions are disabled by settings (permissions.disableBypass); continuing with normal permission prompts.\n"),t.dangerouslySkipPermissions=!1,"bypass"===t.permissionMode&&(t.permissionMode=void 0)),void 0!==t.print){const n=extractPrintModeQuery({print:t.print,prompt:e});return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions,plan:t.plan,permissionMode:t.permissionMode,maxTurns:t.maxTurns,verbose:t.verbose,toolsAll:t.toolsAll,toolsEnable:t.toolsEnable,outputFormat:t.outputFormat,model:a,benchmarkOutput:t.benchmarkOutput,name:t.name,resume:t.resume,continue:t.continue,forkSession:t.forkSession,session:"string"==typeof t.session?t.session:void 0,persist:!1!==t.session&&void 0})}a&&setModelOverride(a,i?.providerId),setGoalMaxTurnsOverride(t.maxTurns);const u=parseInteractivePromptArgument(e);await sB();const m=buildInteractiveRuntimeOptions(t),p=resolveInteractiveLaunchConfig({options:t,runtimeOptions:m,initialPrompt:u});setOriginalInvocation({trust:m.trust,dangerouslySkipPermissions:m.dangerouslySkipPermissions,skipOnboarding:m.skipOnboarding,maxTurns:t.maxTurns,skillPaths:n,skillDiscovery:r}),await installKeybindingsFromConfig({runtime:getCommandConfigRuntime()}),await Xj(p),await shutdownAndExit(0)}__name(interactiveModeAction,"interactiveModeAction"),Gt(),SR(),Gt(),SR();var iB={connected:ht.green("✔"),installed:ht.green("✔"),up_to_date:ht.green("✔"),needs_reload:ht.yellow("◌"),failed:ht.red("✖"),not_in_ide:ht.yellow("◌")};function formatSetupResult(e){const{prefix:t,ide:n,suffix:r}=getIDESetupStatusHeadline(e.status,e.ide),o=`${t}${n??""}${r}`;return["",`${iB[e.status]} ${o}`,...(e.details??[]).map(e=>ht.dim(` ${e}`)),""]}__name(formatSetupResult,"formatSetupResult"),globalThis.COMMAND_CODE_CWD=process.cwd();var aB=__name(()=>process.cwd(),"getCwd"),lB=__name(()=>process.argv.slice(2),"getArgs"),cB=__name(()=>{const e=aB(),t=lB(),n=getCliStartupEnvironment(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");function getAuthKey6(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}async function preRun(){cB();const e=resolveCliStartupPlan({args:lB()});if(e.shouldRunIdeSetup){const e=await runIdeSetup({host:oj,moduleUrl:import.meta.url});formatSetupResult(e).forEach(e=>console.log(e)),process.exit("failed"===e.status?1:0)}e.shouldRunAutoUpdate&&runCliStartupPendingUpdates({plan:e,host:hj}),await migrateDeprecatedModel(),await getAuthKey6()&&detectAndTrackFirstInstall({loadUserConfig:loadUserConfig,updateUserConfig:updateUserConfig,trackLifecycleEvent:__name(e=>trackLifecycleEvent({...e,isTelemetryEnabled:isTelemetryEnabled,createClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createClient"),log:dlog}),"trackLifecycleEvent"),getCliVersion:__name(()=>getPackageJson(import.meta.url).version??"unknown","getCliVersion"),log:dlog}).catch(()=>{}),e.shouldRunAutoUpdate&&runCliStartupUpdateCheck({plan:e,host:hj}),scheduleCliStartupIdeAutoInstall({host:oj,moduleUrl:import.meta.url})}__name(getAuthKey6,"getAuthKey"),__name(preRun,"preRun"),Gt(),SR();var dB=Object.fromEntries(Object.entries(Pk).map(([e,t])=>[t,e])),uB=new Set(RD.map(e=>e.id));function formatProviderModule(e){return uB.has(e)?`@byokkit/cmd-provider-${e}`:e}async function buildProviderLoginRows(e={}){const t=e.hasCredential??hasProviderCredential,n=e.modules??(await loadInstalledProviderModules()).modules,r=e.moduleSources??{},o=[];for(const e of n){const n=Boolean(e.auth?.methods.length),s=dB[e.id]??e.id;o.push({provider:e.id,name:e.displayName??e.id,module:r[e.id]??formatProviderModule(e.id),description:e.transport.kind,authenticated:!!n&&await t({provider:s}),canAuthenticate:n,installed:!0})}const s=new Set(o.map(e=>e.provider));for(const e of RD){if(s.has(e.id))continue;if(!1===e.discoverable)continue;const n=dB[e.id]??e.id;o.push({provider:e.id,name:e.displayName,module:e.package,description:"gateway",authenticated:await t({provider:n}),canAuthenticate:!0,installed:!1})}return o}function formatProviderLoginRows(e){const t=getBinaryCommand(),n=[Et.bold("Providers available for login/logout"),""];for(const r of e){const e=r.authenticated?Et.green("logged in"):Et.dim("not logged in"),o=r.installed?"":Et.dim(" (not installed, installs on first login)");n.push(Et.cyan(r.provider)),n.push(` Name: ${r.name}`),n.push(` Module: ${r.module}${o}`),n.push(` Type: ${r.description}`),r.canAuthenticate?(n.push(` Status: ${e}`),n.push(` Login: ${t} login ${r.provider}`),n.push(` Logout: ${t} logout ${r.provider}`),n.push("")):(n.push(` Status: ${Et.dim("no login")}`),n.push(""))}return n.join("\n")}async function providersAction(e){const t=await loadInstalledProviderModules(),n=await buildProviderLoginRows({modules:t.modules,moduleSources:t.sources});if(e.json)console.log(JSON.stringify({providers:n,errors:t.errors}));else if(console.log(formatProviderLoginRows(n)),t.errors.length>0){console.log(Et.yellow("Provider load errors"));for(const e of t.errors)console.log(`${Et.yellow(e.id)}: ${e.error}`)}}__name(formatProviderModule,"formatProviderModule"),__name(buildProviderLoginRows,"buildProviderLoginRows"),__name(formatProviderLoginRows,"formatProviderLoginRows"),__name(providersAction,"providersAction");var mB=new Be("providers").description("List providers available for login/logout").option("--json","Output providers as JSON for automation").action(providersAction);function setupStreamInput(e){const t=__name(t=>{3===t[0]&&e.onCancel(),4===t[0]&&e.onDetach()},"onData"),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 rgb(e){const t=e.replace("#","");return[Number.parseInt(t.slice(0,2),16),Number.parseInt(t.slice(2,4),16),Number.parseInt(t.slice(4,6),16)]}function fg(e){const[t,n,r]=rgb(e);return`[38;2;${t};${n};${r}m`}function bg(e){const[t,n,r]=rgb(e);return`[48;2;${t};${n};${r}m`}Gt(),Gt(),SR(),Gt(),SR(),Gt(),__name(setupStreamInput,"setupStreamInput"),Gt(),__name(rgb,"rgb"),__name(fg,"fg"),__name(bg,"bg");var pB="";function paintUserMessage(e){return process.stderr.isTTY?`${bg(NR.BG)}${fg(NR.POINTER)}${gt.pointer} ${fg(NR.FG)}${e} ${pB}`:`${gt.pointer} ${e}`}__name(paintUserMessage,"paintUserMessage");var gB="\r",hB=__name(()=>process.stderr.isTTY?gB:"","clearLine");function shimmer(e,t){const n=[...e],r=t%(n.length+10);return n.map((e,t)=>{const n=t-(r-5);return`${fg(n>=0&&n<HR.length?HR[n]??GR:GR)}${e}`}).join("").concat(pB)}function sessionHintLines(e){return[`${Et.yellow("[Ctrl+C]")} ${Et.dim("stop")} ${Et.yellow("[Ctrl+D]")} ${Et.dim("detach")}`,`${Et.dim("Session:")} ${Et.gray(e)}`]}function createReplayDivider(e){let t=null,n=!1;const r=__name(()=>{n||(n=!0,e.onReplayDivider())},"arm");return{onEvent:__name(()=>{n||(t&&clearTimeout(t),t=setTimeout(r,400))},"onEvent"),stop:__name(()=>{t&&clearTimeout(t),t=null},"stop")}}function createBottomLine(){let e=null,t="",n=0,r=null;const o=process.stderr,s=!0===o.isTTY,i=__name(()=>{if(!s)return;if(null===e)return void o.write(`${gB}${Et.cyan(gt.pointer)} ${t}`);const r=t?` ${Et.dim(gt.pointer)} ${t}`:"";o.write(`${gB}${shimmer(`${e}…`,n)}${r}`),n+=1},"render"),a=__name(()=>{!r&&s&&(r=setInterval(i,80))},"tick"),l=__name(()=>{r&&(clearInterval(r),r=null)},"still");return{setStatus(t){s||t===e||o.write(`${Et.dim(t)}\n`),e=t,a(),i()},showPrompt(){l(),e=null,i()},setDraft(e){t=e,i()},draft:()=>t,print(e){o.write(`${hB()}${e}\n`),i()},text(e,t){t&&(l(),o.write(hB())),process.stdout.write(e)},resume(){null!==e&&a(),i()},clear(){l(),o.write(hB())}}}function createView(e){const{bottom:t}=e;let n=!1;const r=__name(()=>{n&&(process.stdout.write("\n"),n=!1,t.resume())},"endText");return{onStatus:__name(e=>{if("setup_step"!==e.type&&"replayed_setup"!==e.type)if("running"!==e.type){if(r(),"note"===e.type)return t.print(Et.yellow(`${e.message}.`)),void t.setStatus("Wrapping up");"completed"===e.type&&e.prUrl&&t.print(`${Et.green("PR:")} ${Et.cyan(e.prUrl)}`),"failed"===e.type&&t.print(`${Et.red(`${gt.cross} Failed:`)} ${e.message}`),"timed_out"===e.type&&t.print(Et.red(`${gt.cross} Timed out`)),"cancelled"===e.type&&t.print(Et.yellow("Cancelled.")),"expired"===e.type&&t.print(Et.red(`${gt.cross} Session expired: its sandbox was removed after 14 idle days.`))}else t.setStatus("Working");else t.setStatus(e.message??"Setting up")},"onStatus"),onAgentEvent:__name(e=>{const o=e.type;if("text_delta"===o&&"string"==typeof e.delta)return t.text(e.delta,!n),void(n=!0);if("message_end"===o&&r(),"tool_running"===o&&"string"==typeof e.toolName){r();const n="string"==typeof e.description?e.description:"";t.print(Et.dim(`${gt.pointerSmall} ${e.toolName} ${n}`.trim())),t.setStatus("Working")}},"onAgentEvent"),onError:__name(e=>{r(),t.print(Et.red(e))},"onError"),onTerminal:__name(e=>{r(),e.error&&t.print(Et.red(e.error)),e.prUrl&&t.print(`${Et.green("PR:")} ${Et.cyan(e.prUrl)}`)},"onTerminal"),onDisconnected:__name(()=>{r(),e.onDisconnected()},"onDisconnected"),onReplayDivider:__name(()=>{r(),t.print(Et.dim("· replayed history above, live from here ·"))},"onReplayDivider")}}function sandboxHint(e){return`${getBinaryCommand()} --experimental sandbox --headless --watch ${e}`}async function authHeaders(){const e=getCommandConfigRuntime(),t=await getCommandAuthKey({runtime:e,path:getAuthFile(),env:e.env()});if(!t)throw new Error(`Not authenticated. Run: ${getBinaryCommand()} login`);return{authorization:`Bearer ${t}`}}function printTaskSummary(e){console.error(`${Et.dim("Status:")} ${e.status}`),e.prUrl&&console.error(`PR: ${Et.cyan(e.prUrl)}`),e.error&&console.error(Et.red(e.error))}async function attachToSession(e){const{client:t,sessionId:n}=e,r=await t.status({sessionId:n});if(isTerminalSandboxTaskStatus(r.status))return e.view?e.view.onTerminal(r):printTaskSummary(r),r.status;const o=e.view?null:createBottomLine(),s=e.view??createView({bottom:o??createBottomLine(),onDisconnected:__name(()=>{o?.print(`${Et.yellow("Disconnected.")} Session still running. Reattach: ${Et.cyan(sandboxHint(n))}`)},"onDisconnected")});if(o)for(const e of sessionHintLines(n))o.print(e);const i=__name(e=>s.onStatus(e),"onStatus");i({type:"setup_step",message:e.initialStatus??"Provisioning sandbox"});const a=e.isReattach&&!e.view?createReplayDivider(s):null;let l=!1;const c=streamSandboxTask({sessionId:n,isReattach:e.isReattach??!1,...e.cursor?{lastEventId:e.cursor.lastEventId}:{},getBaseUrl:getApiBaseUrl,getAuthHeaders:authHeaders,requestCancel:__name(async()=>(await t.cancel({sessionId:n})).status,"requestCancel"),callbacks:{onStatus:__name(({action:e})=>i(e),"onStatus"),onAgentEvent:__name(({event:e})=>{a?.onEvent(),s.onAgentEvent(e)},"onAgentEvent"),onErrorEvent:__name(({message:e})=>s.onError(e),"onErrorEvent"),onCancelled:__name(()=>i({type:"cancelled"}),"onCancelled"),onDisconnected:__name(()=>{l=!0},"onDisconnected"),onDetached:__name(()=>{console.error(`\n${Et.yellow("Detached.")} Reattach: ${Et.cyan(sandboxHint(n))}`)},"onDetached")}}),d=e.controls?bindControls({controls:e.controls,handle:c}):setupStreamInput({onCancel:c.cancel,onDetach:c.detach});process.once("SIGTERM",c.detach);try{const e=await c.done;return null===e&&l?reportAfterDisconnect({client:t,sessionId:n,view:s}):e}finally{e.cursor&&(e.cursor.lastEventId=c.getLastEventId()),a?.stop(),o?.clear(),d(),process.removeListener("SIGTERM",c.detach)}}function bindControls(e){return e.controls.set({cancel:e.handle.cancel,detach:e.handle.detach}),()=>e.controls.set(null)}async function reportAfterDisconnect(e){const{client:t,sessionId:n,view:r}=e,o=await t.status({sessionId:n}).catch(()=>null);return o&&isTerminalSandboxTaskStatus(o.status)?(r.onTerminal(o),o.status):(r.onDisconnected(),null)}function runGit2(e){return S(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}function warnAboutPromptTruncation(e){const t=e.trim().length;t<=Tx||console.error(Et.yellow(`Warning: prompt is ${t} characters; only the first ${Tx} are sent.`))}function warnAboutLocalOnlyWork(e){e||console.error(Et.yellow("Warning: local changes are not included (the sandbox works from the repo on GitHub)."))}function runSandboxStartPreflight(e){if(e.baseBranch&&!isValidSandboxBranchName(e.baseBranch))throw new Error("Invalid --base branch name.");warnAboutPromptTruncation(e.prompt);const t=validateSandboxGitRepo({run:__name(({command:e})=>runGit2(e),"run")});return warnAboutLocalOnlyWork(t.isClean),{repoUrl:t.repoUrl}}function stillStarting(e){return e instanceof gn&&409===e.status}async function waitForHistory(e){const t=Date.now()+24e4;for(;;)try{return(await e.sandbox.history({sessionId:e.sessionId})).turns}catch(e){if(!stillStarting(e)||Date.now()>t)throw e;await new Promise(e=>setTimeout(e,2e3))}}function printHistory(e){const{bottom:t,turns:n}=e;for(const e of n){t.print(paintUserMessage(e.prompt));for(const n of e.reply.split("\n"))t.print(n);t.print("")}}async function resumeWithHistory(e){const{sandbox:t,sessionId:n,bottom:r}=e;r.setStatus("Resuming sandbox"),await t.continueTask({sessionId:n,prompt:"",...e.mode?{mode:e.mode}:{}});try{printHistory({bottom:r,turns:await waitForHistory({sandbox:t,sessionId:n})})}catch{r.print(Et.dim("Earlier turns could not be read from the sandbox."))}}function startProgress(e){const t=createBottomLine();return t.setStatus(e),()=>t.clear()}function createSandboxTransport(){const e=createApiClient({baseUrl:getApiBaseUrl(),timeout:3e5});return{post:__name(t=>e.post({endpoint:t.route,body:t.body}),"post"),get:__name(t=>e.get({endpoint:t.route}),"get")}}__name(shimmer,"shimmer"),__name(sessionHintLines,"sessionHintLines"),__name(createReplayDivider,"createReplayDivider"),__name(createBottomLine,"createBottomLine"),__name(createView,"createView"),__name(sandboxHint,"sandboxHint"),__name(authHeaders,"authHeaders"),__name(printTaskSummary,"printTaskSummary"),__name(attachToSession,"attachToSession"),__name(bindControls,"bindControls"),__name(reportAfterDisconnect,"reportAfterDisconnect"),Gt(),SR(),__name(runGit2,"runGit"),__name(warnAboutPromptTruncation,"warnAboutPromptTruncation"),__name(warnAboutLocalOnlyWork,"warnAboutLocalOnlyWork"),__name(runSandboxStartPreflight,"runSandboxStartPreflight"),Gt(),SR(),__name(stillStarting,"stillStarting"),__name(waitForHistory,"waitForHistory"),__name(printHistory,"printHistory"),__name(resumeWithHistory,"resumeWithHistory"),Gt(),SR(),Gt(),__name(startProgress,"startProgress"),Gt(),SR(),__name(createSandboxTransport,"createSandboxTransport");var fB=["failed","timed_out","expired"];function assertSessionId(e){oD.test(e)||(console.error(Et.red(`Invalid session id: ${e}`)),console.error(Et.dim(`Find it with: ${getBinaryCommand()} --experimental sandbox list`)),process.exit(1))}function client(){return createSandboxClient({transport:createSandboxTransport()})}function exitForStatus(e){process.exit(e&&fB.includes(e)?1:0)}function reportStartFailure(e){const t=classifySandboxStartFailure({error:e.error});if("unauthorized"===t.kind&&(console.error(Et.red(`Authentication failed. Try: ${getBinaryCommand()} login`)),process.exit(1)),"github_app_not_installed"===t.kind){const t=e.repoUrl?.replace("https://github.com/","")??"this repo";console.error(`${Et.red("✖")} Command Code GitHub App is not installed on ${t}.`),console.error(` Install it and select ${t}, then run this command again:`),console.error(` ${Et.cyan("https://github.com/apps/command-code-ai/installations/new")}`),process.exit(1)}console.error(Et.red(t.message)),process.exit(1)}async function startSandboxTask(e){await ensureAuthenticated()||process.exit(1);const t=runSandboxStartPreflight({prompt:e.prompt,...e.baseBranch?{baseBranch:e.baseBranch}:{}}),n=client(),r=startProgress("Creating sandbox");let o;try{o=(await n.start({repoUrl:t.repoUrl,...e.baseBranch?{baseBranch:e.baseBranch}:{},prompt:truncateSandboxPrompt(e.prompt),mode:e.mode})).sessionId,r()}catch(e){r(),reportStartFailure({error:e,repoUrl:t.repoUrl})}"headless"===e.mode&&printStarted(o),exitForStatus(await attachToSession({client:n,sessionId:o}))}function printStarted(e){console.log(e),console.error(Et.dim(`Watch: ${sandboxHint(e)}`)),console.error(Et.dim(`Status: ${getBinaryCommand()} --experimental sandbox status ${e}`)),process.exit(0)}async function attachSandboxTask(e){assertSessionId(e);const t=client(),n=await t.status({sessionId:e});if(isTerminalSandboxTaskStatus(n.status)){if(yB.includes(n.status)){const n=createBottomLine();for(const t of sessionHintLines(e))n.print(t);try{await resumeWithHistory({sandbox:t,sessionId:e,bottom:n})}finally{n.clear()}}printTaskSummary(n),exitForStatus(n.status)}exitForStatus(await attachToSession({client:t,sessionId:e,isReattach:!0}))}__name(assertSessionId,"assertSessionId"),__name(client,"client"),__name(exitForStatus,"exitForStatus"),__name(reportStartFailure,"reportStartFailure"),__name(startSandboxTask,"startSandboxTask"),__name(printStarted,"printStarted"),__name(attachSandboxTask,"attachSandboxTask");var yB=["completed","failed","cancelled","timed_out"];async function statusSandboxTask(e){assertSessionId(e),printTaskSummary(await client().status({sessionId:e}))}async function stopSandboxTask(e){assertSessionId(e);const{status:t}=await client().cancel({sessionId:e});"cancelled"===t?console.error(Et.yellow("Session stopped.")):console.error(Et.yellow(`Session already ${t.replace("_"," ")}.`))}async function listSandboxTasks(){const{sessions:e}=await client().list();if(0!==e.length){console.log(Et.dim(`${"SESSION".padEnd(38)}${"STATUS".padEnd(12)}${"AGE".padEnd(12)}REPO`));for(const t of e){const e=t.repoUrl.replace(/^https:\/\/github\.com\//,""),n=formatRelativeTimeShort({timestamp:t.createdAt});console.log(`${t.sessionId.padEnd(38)}${t.status.padEnd(12)}${n.padEnd(12)}${Et.dim(e)}`)}}else console.error("No sandbox sessions yet.")}async function continueSandboxTask(e){assertSessionId(e.sessionId),await ensureAuthenticated()||process.exit(1),warnAboutPromptTruncation(e.prompt);const t=client(),n=startProgress("Resuming sandbox");try{await t.continueTask({sessionId:e.sessionId,prompt:truncateSandboxPrompt(e.prompt)})}catch(e){n(),reportStartFailure({error:e})}n(),"headless"===e.mode&&printStarted(e.sessionId),exitForStatus(await attachToSession({client:t,sessionId:e.sessionId}))}__name(statusSandboxTask,"statusSandboxTask"),__name(stopSandboxTask,"stopSandboxTask"),__name(listSandboxTasks,"listSandboxTasks"),__name(continueSandboxTask,"continueSandboxTask");var SB=["expired"];function createChatInput(e){const{bottom:t}=e,n=[...e.queued??[]];let r=null,o=null,s=!1;const i=__name(e=>{if(r){const t=r;return r=null,void t(e)}n.push(e),t.print(Et.dim(`queued ${gt.pointer} ${e}`))},"deliver"),a=__name(()=>{if(s=!0,!r)return;const e=r;r=null,e(null)},"leave"),l=__name(e=>{const r=e[0];if(void 0!==r)if(3!==r){if(4===r)return n.length=0,o?.detach(),void a();if(27!==r){if(13===r||10===r){const e=t.draft().trim();return t.setDraft(""),void(e&&(process.stderr.write(gB),i(e)))}127!==r&&8!==r?r<32||t.setDraft(t.draft()+e.toString("utf8")):t.setDraft(t.draft().slice(0,-1))}}else o?o.cancel():a()},"onKeys"),c=process.stdin.isTTY;let d=null;return c?(process.stdin.setRawMode(!0),process.once("exit",()=>{process.stdin.isTTY&&process.stdin.setRawMode(!1)}),process.stdin.resume(),process.stdin.on("data",l),process.on("SIGINT",()=>{})):(d=Rt.createInterface({input:process.stdin}),d.on("line",e=>{e.trim()&&i(e.trim())}),d.on("close",a),process.on("SIGINT",()=>o?o.cancel():a())),{next:__name(()=>new Promise(e=>{const t=n.shift();return void 0!==t?e(t):s?e(null):void(r=e)}),"next"),controls:{set:__name(e=>{o=e},"set")},close:__name(()=>{c&&(process.stdin.removeListener("data",l),process.stdin.setRawMode(!1),process.stdin.pause()),d?.close()},"close")}}async function followRun(e){const{sandbox:t,sessionId:n,controls:r,bottom:o}=e;let s=!1;const i=createView({bottom:o,onDisconnected:__name(()=>{s=!0},"onDisconnected")}),a={lastEventId:0};for(let e=0;e<=20;e++){s=!1;const o=await attachToSession({client:t,sessionId:n,controls:r,view:i,cursor:a,isReattach:e>0,initialStatus:e>0?"Reconnecting":"Working"});if(null!==o||!s)return o;await new Promise(e=>setTimeout(e,1500))}return o.print(Et.yellow("Lost the stream. The run continues in the sandbox.")),null}function describeError(e){const t=e?.error;return t&&"string"==typeof t.message?t.message:e instanceof Error?e.message:String(e)}async function continueWithRetry(e){const{sandbox:t,sessionId:n,message:r}=e,o=truncateSandboxPrompt(r);try{await t.continueTask({sessionId:n,prompt:o,mode:"chat"})}catch(e){if(!/shutting down/i.test(describeError(e)))throw e;await new Promise(e=>setTimeout(e,3e3)),await t.continueTask({sessionId:n,prompt:o,mode:"chat"})}}async function chatSandboxTask(e){await ensureAuthenticated()||process.exit(1);const t=client(),n=e.sessionId?await t.status({sessionId:e.sessionId}):null,r=n?{repoUrl:n.repoUrl}:runSandboxStartPreflight({prompt:"",...e.baseBranch?{baseBranch:e.baseBranch}:{}}),o=createBottomLine(),s=createChatInput({bottom:o,...e.firstMessage?{queued:[e.firstMessage]}:{}});let i=n?.sessionId??null;if(process.stdin.isTTY){const t=r.repoUrl.replace("https://github.com/",""),n=e.baseBranch?` ${Et.dim(e.baseBranch)}`:"";console.error(`${Et.bold("Sandbox")} ${Et.dim(t)}${n}`)}if(!i){o.setStatus("Provisioning sandbox");try{i=(await t.start({repoUrl:r.repoUrl,...e.baseBranch?{baseBranch:e.baseBranch}:{},prompt:"",mode:"chat"})).sessionId}catch(e){o.clear(),s.close(),reportStartFailure({error:e,repoUrl:r.repoUrl})}}for(const e of sessionHintLines(i))o.print(e);if(n&&SB.includes(n.status)&&(o.clear(),s.close(),printTaskSummary(n),process.exit(1)),n&&i)if(isTerminalSandboxTaskStatus(n.status))try{await resumeWithHistory({sandbox:t,sessionId:i,bottom:o,mode:"chat"})}catch(e){o.print(Et.red(describeError(e)))}else o.setStatus("Working"),await followRun({sandbox:t,sessionId:i,controls:s.controls,bottom:o});let a=null;for(;;){o.showPrompt();const e=await s.next();if(null===e)break;o.print(paintUserMessage(e)),o.setStatus("Working");try{await continueWithRetry({sandbox:t,sessionId:i,message:e})}catch(e){o.print(Et.red(describeError(e)));continue}const n=await followRun({sandbox:t,sessionId:i,controls:s.controls,bottom:o});if(a=n,n&&SB.includes(n))break;if(n&&!isTerminalSandboxTaskStatus(n))break}o.clear(),s.close(),i&&console.error(Et.dim(`Resume: ${getBinaryCommand()} --experimental sandbox ${i}`)),process.exit(a&&wB.includes(a)?1:0)}__name(createChatInput,"createChatInput"),__name(followRun,"followRun"),__name(describeError,"describeError"),__name(continueWithRetry,"continueWithRetry"),__name(chatSandboxTask,"chatSandboxTask");var wB=["failed","timed_out","expired"];function run3(e){e().catch(e=>{const t=e instanceof Error?e.message:"Unknown error";console.error(Et.red(t)),process.exit(1)})}function createSandboxCommand(){const e=new Be("sandbox").description("Work in a cloud sandbox: a chat by default, or one headless task").argument("[promptOrId]","First message (chat) or task (headless); a session id resumes that session").option("--headless","Run one task autonomously and print the session id").option("--watch","Stream a headless run, or watch a session by id (implies --headless)").option("--base <branch>","Branch the work branch out from (default: the repo default branch)").enablePositionalOptions().action((e,t)=>{const n=e?.trim()??"",r=oD.test(n),o=t.base?{baseBranch:t.base}:{};return t.headless||t.watch?r?run3(()=>attachSandboxTask(n)):(n||(console.error(Et.yellow('Usage: sandbox --headless [--watch] "task" | sandbox --headless --watch <id>')),process.exit(1)),run3(()=>startSandboxTask({prompt:n,mode:t.watch?"stream":"headless",...o}))):run3(r?()=>chatSandboxTask({sessionId:n}):()=>chatSandboxTask({...o,...n?{firstMessage:n}:{}}))});return e.command("list").description("List your sandbox sessions").action(()=>run3(listSandboxTasks)),e.command("status").description("Show a session summary").argument("<sessionId>").action(e=>run3(()=>statusSandboxTask(e))),e.command("stop").description("Stop a running session").argument("<sessionId>").action(e=>run3(()=>stopSandboxTask(e))),e.command("continue").description("Continue a finished session with a follow-up task").argument("<sessionId>").argument("<prompt...>").option("--watch","Stream the session after continuing it").action((e,t,n,r)=>{const{watch:o}=r.optsWithGlobals();return run3(()=>continueSandboxTask({sessionId:e,prompt:t.join(" "),mode:o?"stream":"headless"}))}),e}__name(run3,"run"),__name(createSandboxCommand,"createSandboxCommand"),Gt(),Gt(),SR();var vB=[`${Et.dim("Usage:")}`,` ${Et.cyan(`${getBinaryCommand()} skills add`)} ${Et.white("<owner/repo>")}`,"",`${Et.dim("Examples:")}`,` ${Et.cyan(`${getBinaryCommand()} skills add`)} ${Et.white("acme/my-skills")} ${Et.dim("# single-skill repo")}`,` ${Et.cyan(`${getBinaryCommand()} skills add`)} ${Et.white("acme/skills/path/to/skill")} ${Et.dim("# specific path in repo")}`,` ${Et.cyan(`${getBinaryCommand()} skills add`)} ${Et.white("acme/multi-skills -s my-skill")} ${Et.dim("# pick one from multi-skill repo")}`,` ${Et.cyan(`${getBinaryCommand()} skills add`)} ${Et.white("acme/repo@branch")} ${Et.dim("# specific branch")}`,` ${Et.cyan(`${getBinaryCommand()} skills add`)} ${Et.white("acme/repo --global")} ${Et.dim("# install to ~/.commandcode/skills/")}`],kB=__name((e,t)=>`${Et.green(gt.tick)} Installed ${Et.cyan(e)} ${Et.dim(`${gt.arrowRight} ${t}/`)}`,"formatInstalled"),CB=__name(e=>`${Et.red(gt.cross)} ${e}`,"formatError");async function cleanupAndExit(e,t){await removeSkillInstallTempDir(e),process.exit(t)}function validateRepoFormat(e){const t=validateSkillInstallRepoInput(e);t.valid||(console.error(CB(t.message)),console.log(""),t.message.startsWith("Invalid repository")&&(console.log(`Expected format: ${Et.cyan("owner/repo")} or ${Et.cyan("owner/repo/path")}`),console.log("")),vB.forEach(e=>console.log(e)),process.exit(1))}async function addAction2(e,t){const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"~/.commandcode/skills":".commandcode/skills";let o;validateRepoFormat(e);const s=Mt({text:`Fetching ${Et.cyan(e)}...`,color:"cyan"});try{let i=[];s.start();const a=await discoverCommandSkills(e,{keepTempDir:!0}),{skills:l,tempDir:c}=a;o=c,s.stop();const d=planSkillInstallSelection({skills:l,requestedSkillName:t.skill,interactive:n,repoInput:e});if("empty"===d.kind&&(console.error(CB(`No skills found in ${Et.cyan(e)}`)),console.log(Et.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(o,1)),"missing-requested-skill"===d.kind)return console.error(CB(`Skill "${d.requestedSkillName}" not found in ${Et.cyan(d.repoInput)}`)),console.log(""),console.log(Et.dim("Available skills:")),d.availableSkillNames.forEach(e=>console.log(` ${Et.cyan(e)}`)),void await cleanupAndExit(o,1);if("prompt"===d.kind){const t=await Ke({message:`Select skills to install from ${e}`,options:[...d.options],required:!0});"symbol"==typeof t&&(console.log(Et.dim("Cancelled")),await cleanupAndExit(o,0)),i=resolvePromptedSkillSelection({skills:l,selectedNames:t})}let u;"selected"===d.kind&&(i=d.skills);const m=await installSelectedCommandSkills({repoInput:e,skills:i,global:t.global,force:t.force,cachedTempDir:o,onSkillStart:__name(e=>{u=Mt({text:`Installing ${Et.cyan(e.name)}...`,color:"cyan"}),u.start()},"onSkillStart"),onSkillInstalled:__name(e=>{u?.stop(),console.log(kB(e.name,r))},"onSkillInstalled"),onSkillFailed:__name(({skillName:e,message:t})=>{u?.stop(),console.error(CB(`Failed to install "${e}"`)),console.log(Et.dim(` ${t}`))},"onSkillFailed")});await cleanupAndExit(o,m.exitCode)}catch(e){s.stop();const t=e instanceof Error?e.message:String(e);console.error(CB(t)),await cleanupAndExit(o,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction2,"addAction");var bB=new Be("add").description("Install a skill from a GitHub repository").argument("<repo>","GitHub repository (owner/repo or owner/repo/path)").option("-g, --global","Install to global skills (~/.commandcode/skills/)").option("-f, --force","Overwrite if skill already exists").option("-s, --skill <name>","Specific skill name to install from repo").addHelpText("after",`\n${vB.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(CB("No repository specified.")),console.log(""),vB.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction2);Gt(),SR();var EB=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${Et.cyan(e)} ${Et.dim(`· ${n}`)}`},"formatSkillLine"),TB=__name((e,t)=>`${Et.bold(Et.white(e))} ${Et.dim(`(${t})`)}`,"formatSectionHeader"),PB=__name(e=>{if(0!==e.warningCount){console.log(""),console.log(`${Et.bold(Et.yellow("Skipped"))} ${Et.dim(`(${e.warningCount})`)}`);for(const t of e.warningGroups){console.log(""),console.log(` ${Et.bold(t.category)} ${Et.dim(`(${t.items.length})`)}`);for(const e of t.items)console.log(` ${Et.bold(skillIdentifier(e.path))}`),console.log(` ${Et.dim(e.reason)}`)}}},"printWarnings"),MB=__name(e=>{const t=["",Et.dim("No skills installed."),"",Et.dim("Looking in:")];for(const n of e.lookupPaths)t.push(Et.dim(` ${n.path} ${Et.white(`(${n.label})`)}`));return t.push("",`Install a skill: ${Et.cyan(e.installCommand)} ${Et.dim(e.installPlaceholder)}`,""),t},"formatEmptyHint"),xB=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),IB=__name(e=>{e&&(console.log(""),console.log(Et.dim(e.replace("--debug",Et.cyan("--debug")))))},"printDebugHint");async function listAction2(){const e="true"===process.env.DEBUG;try{const{global:t,project:n,bundled:r,warnings:o}=await listCommandSkills(),s=planSkillListView({global:t,project:n,bundled:r,warnings:o,showWarnings:e});if(s.empty){const t=await buildSkillListEmptyHint({runtime:getCommandSkillRuntime(),binCommand:`${getBinaryCommand()}`});xB(MB(t));for(const e of s.sections)console.log(TB(e.title,e.skills.length)),e.skills.forEach(e=>{console.log(EB(e.name,e.description))}),console.log("");e&&(PB({warningCount:s.warningCount,warningGroups:s.warningGroups}),s.warningCount>0&&console.log("")),e||(IB(s.debugHint),console.log("")),process.exit(0)}console.log(""),console.log(heading({text:"Skills",sub:Et.dim(`${s.userInstalledTotal} installed`)}));for(const e of s.sections)console.log(""),console.log(TB(e.title,e.skills.length)),e.skills.forEach(e=>{console.log(EB(e.name,e.description))});e&&PB({warningCount:s.warningCount,warningGroups:s.warningGroups}),e||IB(s.debugHint),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${Et.red(gt.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction2,"listAction");var AB=new Be("list").description("List all installed skills. Run with -d/--debug to also see why any skills were skipped.").action(listAction2);Gt(),SR();var RB=__name((e,t)=>`${Et.green(gt.tick)} Removed ${Et.cyan(e)} from ${t} skills`,"formatRemoved"),LB=__name(e=>`${Et.red(gt.cross)} ${e}`,"formatError"),OB=__name((e,t)=>{let n=e;for(const e of t)n=n.replace(e,Et.cyan(e));return Et.dim(n)},"formatHint");function validateSkillNameEarly(e){const t=validateSkillRemoveName(e);return t.valid?null:t.message}async function removeAction2(e,t){try{const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"global":"project",o=validateSkillNameEarly(e);if(o&&(console.error(LB(o)),console.log(OB(getSkillListCommandHint({binCommand:`${getBinaryCommand()}`}),[`${getBinaryCommand()} skills list`])),process.exit(1)),!t.yes&&n){const t=await qe({message:`Remove ${Et.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(Et.dim("Cancelled")),process.exit(0))}await removeCommandSkill({skillName:e,global:t.global}),console.log(RB(e,r)),process.exit(0)}catch(n){const r=n instanceof Error?n.message:"Failed to remove skill",o=planSkillRemoveError({skillName:e,global:t.global,errorMessage:r,binCommand:`${getBinaryCommand()}`});if(console.error(LB(o.message)),"not-found"===o.kind)for(const t of o.hints)console.log(OB(t,[`${getBinaryCommand()} skills remove ${e} --global`,`${getBinaryCommand()} skills list`]));process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction2,"removeAction");var DB=new Be("remove").description("Remove an installed skill").argument("<skill-name>","Name of the skill to remove").option("-g, --global","Remove from global skills (~/.commandcode/skills/)").option("-y, --yes","Skip confirmation prompt").action(removeAction2),$B=new Be("skills").description("Manage skills from GitHub repositories").addCommand(bB).addCommand(DB).addCommand(AB);Gt(),SR(),Gt(),SR(),Gt(),Gt(),SR();var NB=[gt.bullet,gt.squareSmallFilled,gt.lozenge,gt.star,gt.triangleRight,gt.triangleUp];Gt(),SR(),Gt();var _B=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return _B.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}}__name(shouldIgnoreChunk,"shouldIgnoreChunk"),__name(chunkToString,"chunkToString"),__name(withFilteredStderrNoise,"withFilteredStderrNoise"),Gt(),SR(),Gt(),Gt();var FB=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),o=e.learningCount>0;return st.createElement(Qe,{flexDirection:"column",marginLeft:3},st.createElement(Qe,{marginBottom:1,flexDirection:"row"},st.createElement(Xe,{color:ER.DIM},yL),st.createElement(Qe,{marginLeft:2},st.createElement(Xe,{color:PR.TEXT},o?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),st.createElement(Qe,{flexDirection:"column",marginLeft:1},st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},gt.pointerSmall," Taste stored in"," "),st.createElement(cL,{url:fileUrl(e.storage),text:r||".commandcode/taste/taste.md",color:ER.CYAN})),st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},gt.pointerSmall," Share your coding taste:"," ",st.createElement(Xe,{color:ER.CYAN},"npx taste push --all")))),st.createElement(Qe,{marginTop:1,marginLeft:1},st.createElement(Xe,{color:ER.DIM},o?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Gt();var UB=__name(({message:e})=>st.createElement(O$,null,e),"RepoLearnErrorPanel");Gt();var jB=__name(({done:e,error:t})=>t?st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Press ",st.createElement(gO,null,"Esc")," to exit")):e?st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to continue")):st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Esc to cancel")),"RepoLearnFooter");Gt(),SR();var BB=__name(({insights:e,insightCount:t})=>0===e.length?null:st.createElement(Qe,{flexDirection:"column",marginTop:1,marginLeft:4},st.createElement(Xe,{color:ER.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>st.createElement(Xe,{key:`${t}-${e}`,color:ER.DIM},NB[t%NB.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Gt(),SR();var WB=__name(({status:e})=>"active"===e?st.createElement(Qe,null,st.createElement(Xe,{color:ER.YELLOW},st.createElement(kt,{type:"dots"})),st.createElement(Xe,null," ")):"complete"===e?st.createElement(Xe,{color:AR.BG},gt.square," "):st.createElement(Xe,{color:ER.DIM},gt.circle," "),"StepStatusIndicator");function getStepLabelColor(e,t){return"complete"===e?ER.WHITE:t?ER.YELLOW:ER.DIM}__name(getStepLabelColor,"getStepLabelColor");var HB=__name(({steps:e,currentMessage:t})=>st.createElement(Qe,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return st.createElement(Qe,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},st.createElement(Qe,null,st.createElement(Qe,{marginRight:1},st.createElement(WB,{status:e.status})),st.createElement(Xe,{bold:n,color:getStepLabelColor(e.status,n)},e.label)),n&&t?st.createElement(Qe,{marginLeft:3},st.createElement(Xe,{color:ER.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Gt();var GB=__name(({isComplete:e,hasError:t})=>t?st.createElement(Xe,{color:ER.DIM},"learning interrupted"):e?st.createElement(Xe,{color:PR.TEXT},"learned your coding taste"):st.createElement(mL,null),"TastePillStatus"),VB=__name(({isComplete:e,hasError:t})=>st.createElement(Qe,{flexDirection:"column",marginTop:1,marginBottom:0},st.createElement(kL,null),st.createElement(Qe,{marginTop:0},st.createElement(Xe,{color:ER.DIM},yL),st.createElement(Qe,{marginLeft:2},st.createElement(GB,{isComplete:e,hasError:t})))),"RepoLearnTastePill");Gt();var zB=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=dt(()=>tO(n),[n]);return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(qR,null,r.trimEnd())),e?st.createElement(Xe,{color:ER.WHITE},e):st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.WHITE},"Learning your coding taste from"," ",st.createElement(Xe,{bold:!0,color:ER.CYAN},t??"repository")),st.createElement(Xe,{color:ER.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function useRepoLearnState(e){const t=e??TI,[n,r]=at(()=>createRepoLearnProjection({stepOrder:t})),o=lt(null),[s,i]=at(null),a=ut(()=>{o.current=Date.now()},[]),l=ut(e=>{r(t=>({...t,showLogin:e}))},[]);return ct(()=>{const e=__name(()=>{r(createRepoLearnProjection({stepOrder:t})),o.current=null,i(null)},"handleReset"),n=__name(e=>{r(t=>reduceRepoLearnEvent({state:t,event:e}))},"handleEvent"),s=__name(()=>{r(e=>completeRepoLearnProjection({state:e})),o.current&&i(Math.round((Date.now()-o.current)/1e3))},"handleComplete");return ip.on("reset",e),ip.on("new-event",n),ip.on("learning-complete",s),()=>{ip.off("reset",e),ip.off("new-event",n),ip.off("learning-complete",s)}},[t]),{steps:n.steps,currentMessage:n.currentMessage,insights:n.insights,insightCount:n.insightCount,summary:n.summary,done:n.done,error:n.error,showLogin:n.showLogin,setShowLogin:l,elapsedSeconds:s,markStarted:a}}function StatusPanel({error:e,done:t,summary:n,elapsedSeconds:r,insights:o,insightCount:s}){return e?st.createElement(UB,{message:e}):t?st.createElement(FB,{summary:n,elapsedSeconds:r}):st.createElement(BB,{insights:o,insightCount:s})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:o}){const s=useRepoLearnState(n),i=lt(!1);return ct(()=>{i.current||(i.current=!0,s.markStarted(),e().catch(()=>{}))},[e,s.markStarted]),nt((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?st.createElement(Qe,{flexDirection:"column"},st.createElement(zB,{text:r,repoName:o}),st.createElement(kF,{onComplete:(e,t)=>{s.setShowLogin(!1),e?ip.resolveAuth():ip.rejectAuth(t)},onCancel:()=>{s.setShowLogin(!1),ip.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):st.createElement(Qe,{flexDirection:"column"},st.createElement(zB,{text:r,repoName:o}),st.createElement(VB,{isComplete:s.done&&!s.error,hasError:Boolean(s.error)}),st.createElement(HB,{steps:s.steps,currentMessage:s.currentMessage}),st.createElement(StatusPanel,{error:s.error,done:s.done,summary:s.summary,elapsedSeconds:s.elapsedSeconds,insights:s.insights,insightCount:s.insightCount}),st.createElement(jB,{done:s.done,error:s.error}))}async function runRepoLearnProgress(e){return await applyStartupTheme(),withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{ip.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,ip.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),ip.markLearningComplete())}},"handleRunTask"),c=__name(({published:e,cancelled:l})=>{a||(a=!0,i=e,r.abort(),d.unmount(),ip.reset(),s?n(s):t({result:o,published:i,cancelled:l}))},"handleExit"),d=tt(st.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:c}));d.waitUntilExit().catch(e=>{ip.reset(),n(e)})})}function getAuthKey7(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function logLearnSummary(e){const{summary:t}=e;console.log(ht.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("")}Gt(),SR(),__name(useRepoLearnState,"useRepoLearnState"),__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),__name(getAuthKey7,"getAuthKey"),__name(logLearnSummary,"logLearnSummary");var KB=__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 Be("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",KB("--max-commits"),200).addOption(new We("--max-signals <number>","Maximum diff signals to extract").default(50).argParser(KB("--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(e){const t=createNodeRuntime(),n=await isLocalTasteSource({runtime:t,source:e.source}),r=isTTY(),o=await resolveDisplayName({runtime:t,source:e.source}),s=!await getAuthKey7();if(s&&!r)return console.log(""),console.log(" Login required to learn taste."),console.log(""),console.log(` Run: ${getBinaryCommand()} login`),console.log(` Then: npx taste learn ${e.source}`),void console.log("");let i;const a=__name(()=>{i?.().finally(()=>process.exit(130))},"sigintHandler");process.once("SIGINT",a);let l=!1;try{const a=__name(async r=>{const{summary:o,resolved:a}=await runLearnPipeline({runtime:t,reporter:ip,runLearn:__name(e=>runTasteLearningAgent({...e,createSession:createHarnessSession}),"runLearn"),source:e.source,maxCommits:e.maxCommits,maxSignals:e.maxSignals,branch:e.branch,isLocalSource:n,needsAuth:s,signal:r});return i=a?.cleanup,o},"runTask");if(r){const e=n?void 0:[...PI];({cancelled:l}=await runRepoLearnProgress({runTask:a,repoName:o,stepOrder:e}))}else logLearnSummary({summary:await a((new AbortController).signal)})}finally{process.off("SIGINT",a),i&&await i()}r&&!l||process.exit(0),RL(),await Xj({skipOnboarding:!0}),await shutdownAndExit(0)}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Gt(),SR(),Gt(),SR();var qB=ht.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(`${ht.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?`${ht.dim(t[1])}${ht.green(t[2])}${ht.white(t[3]??"")}${t[4]?ht.dim(t[4]):""}`:ht.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${ht.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`);for(const e of t)console.error(formatUsageLine(e));process.exit(1)}function exitWithTasteCliValidation(e){e.valid||(e.usage&&exitWithUsage({message:e.message,usage:e.usage}),exitWithError(e.message))}__name(shortenPath,"shortenPath"),__name(exitWithError,"exitWithError"),__name(formatUsageLine,"formatUsageLine"),__name(exitWithUsage,"exitWithUsage"),__name(exitWithTasteCliValidation,"exitWithTasteCliValidation");var YB=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){const n=buildPackageUrl({owner:e,packageName:t});return At(`commandcode.ai/${e}/${t}`,n,{fallback:YB})}function getProfileLink(e){const t=buildProfileUrl2(e);return At(`commandcode.ai/${e}`,t,{fallback:YB})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return Lt(e,n,{trim:!1})}function logMergeReviewTip(){console.log(ht.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}function handleResultErrors(e){for(const t of e){const e=normalizeTasteResultError(t);console.error(`${ht.red("Error:")} ${e}`)}process.exit(1)}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(ht.red(`Error: ${t}`)),await flushAndExit(1)}}}function formatSingleIssue(e,t){const n=[`${e.line?ht.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(ht.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`${ht.green(e)} ${ht.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?ht.red(t.summary):ht.yellow(t.summary),"",...formatIssueGroup(r,ht.red,ht.bold(ht.red("Errors:"))),...formatIssueGroup(o,ht.yellow,ht.bold(ht.yellow("Warnings:")))].join("\n").trim()}__name(getPackageLink,"getPackageLink"),__name(getProfileLink,"getProfileLink"),__name(wrapLine,"wrapLine"),__name(logMergeReviewTip,"logMergeReviewTip"),__name(handleResultErrors,"handleResultErrors"),__name(flushAndExit,"flushAndExit"),__name(withErrorHandler,"withErrorHandler"),Gt(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var JB=createTasteLintService({runtime:createNodeRuntime(),formatValidationIssues:formatValidationIssues});function createLintCommand(){return new Be("lint").argument("[package]","Taste package name").option("-g, --global","Validate taste packages from global storage (~/.commandcode)").option("--all","Validate all taste packages").description(`Validate taste package format ${ht.dim("(structure, style, etc.)")}`).action(withErrorHandler(async(e,t)=>runLint({packageName:e,options:t})))}function validateLintOptions({packageName:e,options:t}){exitWithTasteCliValidation(validateTasteLintCliOptions({packageName:e,options:t}))}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(`${ht.green(gt.tick)} All ${ht.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(ht.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(ht.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 JB.lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(ht.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Gt(),SR();var QB={};__export(QB,{downloadPackage:()=>downloadPackage,downloadRemotePackage:()=>downloadRemotePackage,getAllPackages:()=>getAllPackages,getPackage:()=>getPackage,listPackages:()=>listPackages,writePackage:()=>writePackage,writePackages:()=>writePackages}),Gt(),SR();var XB=createNodeRuntime();function getAuthKey8(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}async function requireAuthKey(){const e=await getAuthKey8();if(!e)throw new Error(`No API key found. Please authenticate with: ${getBinaryCommand()} login`);return e}function storage(){return createTasteRemoteStorage({transport:createNodeTransport({baseUrl:getApiBaseUrl()}),requireAuthKey:requireAuthKey,getAuthKey:getAuthKey8,getAuthenticatedEntity:__name(()=>getAuthenticatedEntity({client:createApiClient({baseUrl:getApiBaseUrl()})}),"getAuthenticatedEntity"),trackError:__name(({error:e,label:t,heading:n,context:r})=>trackError({error:sanitizeErrorForTelemetry({error:e,label:t}),context:{component:Ho.TASTE_REMOTE_STORAGE,heading:n,...r??{}}}),"trackError"),onWarn:__name(e=>console.warn(e),"onWarn"),logDebug:__name(e=>dlog(e),"logDebug")})}function getAllPackages(){return storage().getAllPackages()}function getPackage(e){return storage().getPackage(e)}function downloadPackage(e){return storage().downloadPackage(e)}function downloadRemotePackage(e){return storage().downloadRemotePackage(e)}function writePackage(e){return storage().writePackage(e)}async function writePackages(e){const{packages:t,projectName:n,owner:r,isPublic:o,overwrite:s}=e,{rootContent:i,categoryContents:a}=await readProjectUploadFiles({runtime:XB,packages:t});return storage().writePackages({projectName:n,owner:r,isPublic:o,overwrite:s,rootContent:i,categoryContents:a,packageCount:t.length})}function listPackages(){return storage().listPackages()}__name(getAuthKey8,"getAuthKey"),__name(requireAuthKey,"requireAuthKey"),__name(storage,"storage"),__name(getAllPackages,"getAllPackages"),__name(getPackage,"getPackage"),__name(downloadPackage,"downloadPackage"),__name(downloadRemotePackage,"downloadRemotePackage"),__name(writePackage,"writePackage"),__name(writePackages,"writePackages"),__name(listPackages,"listPackages");var ZB=createNodeRuntime(),eW=createTasteLocalStorage({runtime:ZB,target:"local-project"}),tW=createTasteLocalStorage({runtime:ZB,target:"local-global"});function list(e){return createTasteListService({runtime:ZB,localProject:eW,localGlobal:tW,remote:QB}).list(e)}function getUserName(){return getCommandAuthUserName({runtime:getCommandConfigRuntime(),path:getAuthFile()})}function createListCommand(){return new Be("list").alias("ls").option("-g, --global","List global packages").addOption(new We("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new We("--staging","Use staging environment").hideHelp()).description(`List available packages ${ht.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}function formatPackageLine(e){return` ${ht.white(e.name)}${e.publicBadge?ht.green(e.publicBadge):""}${e.starsBadge?ht.yellow(e.starsBadge):""}${e.downloadsBadge?ht.gray(e.downloadsBadge):""}${e.padding}${ht.dim.gray(e.statsLabel)}`}function validateListOptions(e){exitWithTasteCliValidation(validateTasteListCliOptions(e))}async function fetchPackages({options:e}){const t=resolveTasteListStorage(e),n=e.remote?Mt(`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${qB} Packages`),console.log(`${ht.gray("⎿")} ${ht.dim(t)}\n`);const n=projectTasteListView({packages:e,symbols:{star:gt.star,arrowDown:gt.arrowDown}});for(const e of n.rows)console.log(formatPackageLine(e));console.log(ht.dim(`\n${n.totalLabel}\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(ht.yellow(`No taste packages found in ${n.name}`))}__name(list,"list"),__name(getUserName,"getUserName"),__name(createListCommand,"createListCommand"),__name(formatPackageLine,"formatPackageLine"),__name(validateListOptions,"validateListOptions"),__name(fetchPackages,"fetchPackages"),__name(getStorageLabel,"getStorageLabel"),__name(printPackageTable,"printPackageTable"),__name(runList,"runList"),Gt(),SR(),Gt(),SR();var nW=createNodeRuntime(),rW=createTasteLocalStorage({runtime:nW,target:"local-project"}),oW=createTasteLocalStorage({runtime:nW,target:"local-global"});async function open7(e){try{const t=await createTasteOpenService({runtime:nW,localProject:rW,localGlobal:oW,remote:QB}).resolveOpen(e);return t.success?(await It([{file:t.filePath,line:t.lineNumber}]),t):t}catch(e){return classifyTasteOpenError({error:e,platform:Te.platform})}}function createOpenCommand(){return new Be("open").argument("[package]","Taste package name, or owner/package to open in browser").option("-g, --global","Open taste package from global storage (~/.commandcode)").description(`Open a taste package in your editor ${ht.dim("(use owner/package to open in browser)")}`).action(withErrorHandler(async(e,t)=>runOpen({packageName:e,options:t})))}function validateOpenOptions(e){exitWithTasteCliValidation(validateTasteOpenCliOptions(e))}async function runOpen({packageName:e,options:t}){console.log(""),validateOpenOptions(e);const n=parseOwnerPackage(e);n?await openInBrowser(n):await openInEditor2({packageName:e,options:t})}async function openInBrowser(e){const t=`https://commandcode.ai/${e.owner}/${e.packageName}`;await Pt(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${ht.green(gt.tick)} Opened ${n} in browser`)}async function openInEditor2({packageName:e,options:t}){const n=resolveTasteOpenTarget(t),r=await open7({package:e,target:n});r.success||exitWithError(r.error??"Unknown error"),console.log(`${ht.green(gt.tick)} Opened ${ht.green(`'${e}'`)} taste package from ${t.global?"global":"project"}`)}__name(open7,"open"),__name(createOpenCommand,"createOpenCommand"),__name(validateOpenOptions,"validateOpenOptions"),__name(runOpen,"runOpen"),__name(openInBrowser,"openInBrowser"),__name(openInEditor2,"openInEditor"),Gt(),SR(),Gt(),SR(),Gt();var sW=null,iW=!1;function setActiveSpinner(e){sW=e}function stopActiveSpinner(e){sW&&(sW.stop(e),sW=null)}function setPrompted(e){iW=e}function wasPrompted(){return iW}function logResult(e){if(wasPrompted())return Ge.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{summary:t,sourceName:n}=e,r=wasPrompted()?"":`${gt.tick} `,o=t.detailPath?ht.dim(`\n ${shortenPath(t.detailPath)}`):"";return"single-replaced"===t.variant?`${ht.green(r)}Replaced ${ht.green(`'${t.packageName}'`)} taste package in project`+o:"single-merged"===t.variant?`${ht.green(r)}Pulled ${ht.green(`'${t.packageName}'`)} taste package from ${n} ${ht.gray(`(${t.mergeParts.join(", ")})`)}`+o:`${ht.green(r)}Pulled ${ht.green(`'${t.packageName}'`)} taste package from ${n}`+o}function logPullSummary(e){const{breakdown:t,sourceName:n}=e,r=[];if(t.succeeded.length>0&&r.push(wrapLine(`${ht.green("Pulled")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`,wasPrompted()?4:0)),t.overwritten.length>0&&r.push(wrapLine(`${ht.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`,wasPrompted()?4:0)),t.skipped.length>0&&r.push(wrapLine(`${ht.dim("Skipped")} (${t.skipped.length}) ${ht.dim(t.skipped.join(", "))}`,wasPrompted()?4:0)),wasPrompted())return r.length>0&&Ge.log.message(r.join("\n")),Ge.outro(`${t.totalLabel} from ${n}`),void setPrompted(!1);console.log(`${ht.green(gt.tick)} ${t.totalLabel} from ${n}`),r.length>0&&console.log(r.join("\n"))}function logPullSuccess(e){const{result:t,sourceName:n,options:r}=e,o=projectTastePullSummary({result:t,options:r});if("multi"===o.variant)return logPullSummary({breakdown:o.breakdown,sourceName:n}),void(o.showTip&&logMergeReviewTip());"single-skipped"!==o.variant?"none"!==o.variant&&(logResult(buildPullMessage({summary:o,sourceName:n})),o.showTip&&logMergeReviewTip()):logResult(ht.yellow(o.message))}function beginPrompt(e,t){stopActiveSpinner(),Ge.intro(ht.dim(e)),t&&Ge.log.message(ht.dim(t)),setPrompted(!0)}function handleCancel(e){Ge.isCancel(e)&&(Ge.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Ge.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Ge.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 runConflictPrompt(e){if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(e.existsMessage),setPrompted(!0),Ge.log.warn(e.nonInteractive.warning),e.nonInteractive.strategy;if(beginPrompt(`${e.title.prefix}${ht.green(e.title.emphasis)}${e.title.suffix}`,e.existsMessage),Ge.log.message(`${e.context.firstLine}\n${e.context.secondLine}${e.context.secondLineNote?` ${ht.dim(e.context.secondLineNote)}`:""}`),e.reviewLink){const t=At(e.reviewLink.text,e.reviewLink.url,{fallback:__name((e,t)=>t,"fallback")});Ge.log.info(`${e.reviewLink.prefix}${ht.cyan(t)} ${ht.dim(e.reviewLink.note)}`)}const t=await Ge.select({message:e.selectMessage,options:e.options.map(e=>({value:e.value,label:e.label,hint:e.hint})),initialValue:e.initialValue});handleCancel(t);const n=t;return startStrategySpinner(n),n}async function promptMergeStrategy(e){const{packageName:t,owner:n,localPkg:r,remoteLearningsCount:o}=e;return runConflictPrompt(buildTastePullConflictPrompt({packageName:t,owner:n,localLearningsCount:r.learnings.length,remoteLearningsCount:o}))}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalPkg:r}=e;return runConflictPrompt(buildTasteGlobalPushConflictPrompt({packageName:t,localLearningsCount:n,globalLearningsCount:r.learnings.length}))}async function promptGlobalPullStrategy(e){const{packageName:t,localPkg:n,globalLearningsCount:r}=e;return runConflictPrompt(buildTasteGlobalPullConflictPrompt({packageName:t,localLearningsCount:n.learnings.length,globalLearningsCount:r}))}async function promptTypeMismatchStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e;return runConflictPrompt(buildTasteTypeMismatchConflictPrompt({packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}))}async function promptSameTypeStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e;return runConflictPrompt(buildTasteSameTypeConflictPrompt({packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}))}__name(setActiveSpinner,"setActiveSpinner"),__name(stopActiveSpinner,"stopActiveSpinner"),__name(setPrompted,"setPrompted"),__name(wasPrompted,"wasPrompted"),__name(logResult,"logResult"),__name(buildPullMessage,"buildPullMessage"),__name(logPullSummary,"logPullSummary"),__name(logPullSuccess,"logPullSuccess"),Gt(),SR(),Gt(),SR(),__name(beginPrompt,"beginPrompt"),__name(handleCancel,"handleCancel"),__name(startStrategySpinner,"startStrategySpinner"),__name(runConflictPrompt,"runConflictPrompt"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy");var aW=createNodeRuntime(),lW=createTasteLocalStorage({runtime:aW,target:"local-project"}),cW=createTasteLocalStorage({runtime:aW,target:"local-global"});function service(){return createTastePullService({localProject:lW,localGlobal:cW,remote:QB,getDestinationPath:__name(e=>resolveTastePackageDestinationPathForRuntime({runtime:aW,...e}),"getDestinationPath"),promptGlobalPullStrategy:promptGlobalPullStrategy,promptMergeStrategy:promptMergeStrategy,validation:{formatValidationIssues:formatValidationIssues,onWarning:__name(e=>console.warn(e),"onWarning")}})}function pull(e){return service().pull(e)}function pullRemote(e){return service().pullRemote(e)}function createPullCommand(){return new Be("pull").argument("[package]","Taste package name, or owner/package to pull from remote").option("-g, --global","Pull taste package from global storage (~/.commandcode)").addOption(new We("--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 We("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${ht.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})}))}async function runPull(e){const{packageName:t,options:n}=e;console.log("");const r=planTastePullCommand({packageName:t,options:n});if(!r.valid)throw exitWithTasteCliValidation(r.validation),new Error("unreachable");return"remote-single"===r.route.type?pullRemoteSingle({options:r.options,route:r.route}):pullGlobal({options:r.options,route:r.route})}async function pullRemoteSingle(e){setActiveSpinner(Mt("Pulling taste package").start());const t=await pullRemote({owner:e.route.owner,packageName:e.route.packageName,overwrite:e.options.overwrite,strategy:e.route.strategy});return stopActiveSpinner(),{result:t,owner:e.route.owner}}async function pullGlobal(e){setActiveSpinner(Mt("Pulling taste package").start());const t=await pull({packages:[...e.route.packages],source:"local-global",overwrite:e.options.overwrite,strategy:e.route.strategy});return stopActiveSpinner(),{result:t}}function logResult2(e){if(wasPrompted())return Ge.outro(e),void setPrompted(!1);console.log(e)}function formatAllLocation(t){return"taste-dir"===t.kind?shortenPath(e.dirname(e.dirname(t.filePath))):t.filePath}function formatDetailPath(e){return e?ht.dim(`\n ${shortenPath(e)}`):""}function renderPushSummary(e){const t=wasPrompted()?"":`${gt.tick} `;if("none"!==e.variant)if("all-skipped"!==e.variant)if("all-pushed-remote"!==e.variant){if("all-replaced"===e.variant){const n=e.replacedLabel?` ${ht.gray(`(${e.replacedLabel})`)}`:"";return void logResult2(`${ht.green(t)}Replaced ${e.packageCountLabel} in ${formatAllLocation(e.location)}${n}`)}if("all-pushed"!==e.variant){if("all-merged"===e.variant){const n=e.mergeParts.length>0?` ${ht.gray(`(${e.mergeParts.join(", ")})`)}`:"";return void logResult2(`${ht.green(t)}Pushed ${e.packageCountLabel} to ${formatAllLocation(e.location)}${n}`)}"single-replaced"!==e.variant?"single-merged"!==e.variant?"single-pushed"!==e.variant?"multi"!==e.variant||logResult2(wrapLine(`${ht.green(t)}Pushed ${ht.green(e.count)} taste packages ${ht.green(`(${e.packages.join(", ")})`)} to ${e.targetName}`)):logResult2(`${ht.green(t)}Pushed ${ht.green(`'${e.packageName}'`)} taste package to ${e.locationLabel}`+formatDetailPath(e.detailPath)):logResult2(`${ht.green(t)}Pushed ${ht.green(`'${e.packageName}'`)} taste package to ${e.locationLabel} ${ht.gray(`(${e.mergeParts.join(", ")})`)}`+formatDetailPath(e.detailPath)):logResult2(`${ht.green(t)}Replaced ${ht.green(`'${e.packageName}'`)} taste package in ${e.locationLabel}`+formatDetailPath(e.detailPath))}else logResult2(`${ht.green(t)}Pushed ${e.packageCountLabel} to ${formatAllLocation(e.location)}`)}else logResult2(`${ht.green(t)}Pushed ${e.packageCountLabel} to remote`);else logResult2(`${ht.green(t)}Skipped ${e.packageCountLabel}`)}function logPushUrls(e){for(const t of collectTastePushRemoteLinks(e))console.log(ht.gray(` ${getPackageLink(t)}`))}function logConflictSummary(e){const t=projectTastePushOutcome(e.result),n=[];t.succeeded.length>0&&n.push(wrapLine(`${ht.green("Merged")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`,4)),t.overwritten.length>0&&n.push(wrapLine(`${ht.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`,4)),t.skipped.length>0&&n.push(wrapLine(`${ht.dim("Skipped")} (${t.skipped.length}) ${ht.dim(t.skipped.join(", "))}`,4)),n.length>0&&Ge.log.message(n.join("\n")),Ge.outro(t.totalLabel)}function logPushBreakdown(e){const t=projectTastePushOutcome(e);if(0===t.skipped.length&&0===t.overwritten.length)return;const n=[];t.succeeded.length>0&&n.push(wrapLine(`${ht.green("Pushed")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`)),t.overwritten.length>0&&n.push(wrapLine(`${ht.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`)),t.skipped.length>0&&n.push(wrapLine(`${ht.dim("Skipped")} (${t.skipped.length}) ${ht.dim(t.skipped.join(", "))}`)),n.length>0&&console.log(n.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=projectTastePushSummary({result:t,options:n});renderPushSummary(r),n.all&&logPushBreakdown(t),logPushUrls({result:t,options:n}),r.showTip&&logMergeReviewTip()}__name(service,"service"),__name(pull,"pull"),__name(pullRemote,"pullRemote"),__name(createPullCommand,"createPullCommand"),__name(runPull,"runPull"),__name(pullRemoteSingle,"pullRemoteSingle"),__name(pullGlobal,"pullGlobal"),Gt(),SR(),Gt(),SR(),__name(logResult2,"logResult"),__name(formatAllLocation,"formatAllLocation"),__name(formatDetailPath,"formatDetailPath"),__name(renderPushSummary,"renderPushSummary"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Gt(),SR();var dW=createNodeRuntime(),uW=createTasteLocalStorage({runtime:dW,target:"local-project"}),mW=createTasteLocalStorage({runtime:dW,target:"local-global"});async function getUserOwner(){try{const e=await getAuthenticatedEntity({client:createApiClient({baseUrl:getApiBaseUrl()})});if(e.success&&e.user?.userName)return e.user.userName}catch{}}function service2(){return createTastePushService({localProject:uW,localGlobal:mW,remote:QB,getUserOwner:getUserOwner,getProjectName:__name(()=>e.basename(process.cwd()),"getProjectName"),getDestinationPath:__name(e=>resolveTastePackageDestinationPathForRuntime({runtime:dW,...e}),"getDestinationPath"),promptGlobalPushStrategy:promptGlobalPushStrategy,promptTypeMismatchStrategy:promptTypeMismatchStrategy,promptSameTypeStrategy:promptSameTypeStrategy,validation:{formatValidationIssues:formatValidationIssues,onWarning:__name(e=>console.warn(e),"onWarning")}})}function push(e){return service2().push(e)}function pushRemote(e){return service2().pushRemote(e)}async function promptOwnerSelection(e){const{userName:t,orgs:n}=e;if(0===n.length)return t;const{options:r,initialValue:o}=buildTasteOwnerSelectOptions({userName:t,orgs:n}),s=await Ge.select({message:"Owner",options:[...r],initialValue:o});return Ge.isCancel(s)&&(Ge.cancel("Operation cancelled"),process.exit(0)),s}__name(getUserOwner,"getUserOwner"),__name(service2,"service"),__name(push,"push"),__name(pushRemote,"pushRemote"),Gt(),SR(),__name(promptOwnerSelection,"promptOwnerSelection");var pW=createNodeRuntime(),gW=createTasteLocalStorage({runtime:pW,target:"local-project"});function loadUserNamespaces(){return fetchUserNamespaces({client:createApiClient({baseUrl:getApiBaseUrl()})})}function createPushCommand(){return new Be("push").description(`Push taste packages to remote ${ht.dim("(commandcode.ai)")} or global ${ht.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 We("--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 We("--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})}))}async function validateOwnerAccess(e){const t=await checkTastePushOwnerAccess({owner:e,loadNamespaces:loadUserNamespaces});"unavailable"!==t.type?"denied"===t.type&&exitWithError(`No push access to '${e}'. Available: ${t.availableOwners.join(", ")}`):dlog(`[Auth] validateOwnerAccess: namespace service unavailable, skipping — ${t.error instanceof Error?t.error.message:String(t.error)}`)}async function resolveOwnerForPush(e){let t;return resolveTastePushOwner({ownerPlan:e,validateOwnerAccess:validateOwnerAccess,hasLocalPackage:__name(async e=>(await gW.getAllPackages()).some(t=>t.category===e),"hasLocalPackage"),loadNamespaces:loadUserNamespaces,prompt:{onPromptStart:__name(({packageName:e})=>{Ge.intro(ht.dim(`pushing ${e}`)),setPrompted(!0),t=Ge.spinner(),t.start("Resolving")},"onPromptStart"),onPackageMissing:__name(({packageName:e})=>{t?.error("Failed"),Ge.outro(ht.red(`Taste package '${e}' not found in project`)),process.exit(1)},"onPackageMissing"),onNamespacesLoaded:__name(({willPrompt:e})=>{t?.stop(e?"Select owner to push to":"")},"onNamespacesLoaded"),selectOwner:promptOwnerSelection}})}async function runPush(e){const{packageName:t,options:n}=e;console.log("");const r=planTastePushCommand({packageName:t,options:n});if(!r.valid)throw exitWithTasteCliValidation(r.validation),new Error("unreachable");return"remote-all"===r.route.type?pushRemoteAll({options:r.options,route:r.route}):"remote-single"===r.route.type?pushRemoteSingle({options:r.options,route:r.route}):pushGlobal({options:r.options,route:r.route})}async function pushRemoteAll(t){t.route.owner&&await validateOwnerAccess(t.route.owner);const n=formatTastePackageCount((await gW.getAllPackages()).length),r=e.basename(process.cwd()),o=resolveTasteStrategyLabel({strategy:t.route.strategy,isRemote:!0});console.log(ht.dim(` Pushing ${n} to ${r} (remote)${o}`)),console.log(""),setActiveSpinner(Mt("Pushing taste packages").start());const s=await push({packages:[],target:"remote-project",overwrite:t.options.overwrite,isPublic:t.route.isPublic,strategy:t.route.strategy,owner:t.route.owner});return stopActiveSpinner(),s}async function pushRemoteSingle(e){const{owner:t,packageName:n}=await resolveOwnerForPush(e.route.ownerPlan);startPushSpinner({owner:t,pkgName:n});const r=await pushRemote({owner:t,packageName:n,overwrite:e.options.overwrite,isPublic:e.route.isPublic,strategy:e.route.strategy});return stopActiveSpinner(`Pushed to ${t}/${n}`),r}function startPushSpinner(e){const{owner:t,pkgName:n}=e;if(wasPrompted()){const e=Ge.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Mt("Pushing taste package").start())}async function pushGlobal(e){const t=await gW.getAllPackages(),n=formatTastePackageCount(e.route.packages.length>0?e.route.packages.length:t.length),r=shortenPath(getTastePathForRuntime({runtime:pW,target:"local-global"})),o=resolveTasteStrategyLabel({strategy:e.route.strategy});console.log(ht.dim(` Pushing ${n} to ${r}${o}`)),console.log(""),setActiveSpinner(Mt("Pushing taste packages").start());const s=await push({packages:[...e.route.packages],target:"local-global",overwrite:e.options.overwrite,strategy:e.route.strategy});return stopActiveSpinner(),s}function scopeOf(e){return e.user?"global":"project"}function whereFor(e){return"project"===e?" for this project":" for all your projects"}async function applyTasteLearning(e){await setTasteLearning({tasteLearning:e.enabled,scope:e.scope,..."project"===e.scope?{projectPath:process.cwd()}:{}})}function reportEnabled(e){console.log(`${ht.green(gt.tick)} Taste learning is on${whereFor(e)}. New preferences are saved and reused across sessions.`)}function reportDisabled(e){const t=getBinaryCommand();console.log(`${ht.green(gt.tick)} Taste learning is off${whereFor(e)}. Turn it back on with ${ht.cyan(`${t} taste enable`)}.`)}function createEnableCommand(){return new Be("enable").option("-u, --user","Apply at the user level (all your projects)").description("Turn on taste learning (save preferences across sessions)").action(withErrorHandler(async e=>{const t=scopeOf(e);await applyTasteLearning({enabled:!0,scope:t}),console.log(""),reportEnabled(t)}))}function createDisableCommand(){return new Be("disable").option("-u, --user","Apply at the user level (all your projects)").description("Turn off taste learning (stop saving preferences)").action(withErrorHandler(async e=>{const t=scopeOf(e);await applyTasteLearning({enabled:!1,scope:t}),console.log(""),reportDisabled(t)}))}function createTasteCommand(){const e=new Be("taste");return e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments(),e.addCommand(createEnableCommand()),e.addCommand(createDisableCommand()),e.addCommand(createPushCommand()),e.addCommand(createPullCommand()),e.addCommand(createListCommand()),e.addCommand(createLintCommand()),e.addCommand(createOpenCommand()),isExperimentalEnabled()&&e.addCommand(createLearnCommand()),e}__name(loadUserNamespaces,"loadUserNamespaces"),__name(createPushCommand,"createPushCommand"),__name(validateOwnerAccess,"validateOwnerAccess"),__name(resolveOwnerForPush,"resolveOwnerForPush"),__name(runPush,"runPush"),__name(pushRemoteAll,"pushRemoteAll"),__name(pushRemoteSingle,"pushRemoteSingle"),__name(startPushSpinner,"startPushSpinner"),__name(pushGlobal,"pushGlobal"),Gt(),SR(),__name(scopeOf,"scopeOf"),__name(whereFor,"whereFor"),__name(applyTasteLearning,"applyTasteLearning"),__name(reportEnabled,"reportEnabled"),__name(reportDisabled,"reportDisabled"),__name(createEnableCommand,"createEnableCommand"),__name(createDisableCommand,"createDisableCommand"),__name(createTasteCommand,"createTasteCommand"),Gt(),SR();var hW=`${getBinaryCommand()}`;function formatVersion(e,t,n=!1){const r=n?Et.bold(Et.green(t)):Et.white(t);return`${Et.dim(e)} ${r}`}function showVersionDetails(e){for(const t of e.versionLines)console.log(formatVersion(t.label,t.version,t.highlight));console.log("");for(const t of e.detailLines)console.log(t.replace(`${hW} update`,Et.bold(Et.green(`${hW} update`))))}function showUpdateSuccessHint(e){for(const t of e.detailLines)console.log(Et.dim(t.replace(hW,Et.cyan(hW))))}function showManualUpdateHint(e){const[t,n]=e.manualUpdateLines;t&&console.log(Et.dim(t)),n&&console.log(Et.cyan(n))}function showCheckFailure(e){for(const t of e.detailLines)console.log(Et.dim(t))}function renderUpdateEvent(e,t){if("type"in e)"updating"===e.type&&(t.text=e.text.replace("→",gt.arrowRight));else{if("check-failed"===e.kind)return t.fail(e.outcome.spinnerMessage),void showCheckFailure(e.outcome);if("up-to-date"!==e.kind)return"update-available"===e.kind?(t.stop(),console.log(""),console.log(`${Et.green(gt.tick)} ${e.outcome.heading}`),void showVersionDetails(e.outcome)):"update-failed"===e.kind?(t.fail(e.outcome.spinnerMessage),void showManualUpdateHint(e.outcome)):"updated"===e.kind?(t.succeed(e.outcome.spinnerMessage),void showUpdateSuccessHint(e.outcome)):void 0;t.succeed(e.outcome.spinnerMessage)}}async function updateAction2(e){const t=Mt("Checking for updates...").start(),n=await runCliUpdateCommand({checkOnly:e.checkOnly,host:hj,copy:{binCommand:hW,updateCommand:"npm i -g command-code"},emit:__name(e=>renderUpdateEvent(e,t),"emit")});if("update-failed"===n.kind){const{failureReason:e}=n.outcome.telemetry;trackError({error:sanitizeErrorForTelemetry({error:new Error(e?`Update failed: ${e}`:"Update failed"),label:"cli_update_failed"}),context:{component:Ho.UPDATE_COMMAND,heading:n.outcome.telemetry.heading,"update.current_version":n.outcome.telemetry.currentVersion,"update.target_version":n.outcome.telemetry.targetVersion,...e&&{"update.failure_reason":e}}}),await shutdownTelemetry(),process.exit(1)}}__name(formatVersion,"formatVersion"),__name(showVersionDetails,"showVersionDetails"),__name(showUpdateSuccessHint,"showUpdateSuccessHint"),__name(showManualUpdateHint,"showManualUpdateHint"),__name(showCheckFailure,"showCheckFailure"),__name(renderUpdateEvent,"renderUpdateEvent"),__name(updateAction2,"updateAction");var fW=new Be("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction2);function getAuthKey9(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}Gt(),SR(),__name(getAuthKey9,"getAuthKey");var yW=__name((e,t)=>`${gt.info} ${e}: ${Et.cyan(t)}`,"formatInfoLine"),SW=__name(e=>Et.bold(`${e}:`),"formatSectionHeader"),wW=__name(e=>Et.red(e),"formatError"),vW=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),kW=__name((e,t)=>["",SW(e),...t.map(e=>yW(e.label,e.value))],"buildSection"),CW=__name(e=>kW("User Information",projectWhoamiUserRows(e)),"buildUserOutput"),bW=__name(e=>kW("Organization",projectWhoamiOrgRows(e)),"buildOrgOutput"),EW=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),TW=__name((e,t)=>{EW(CW(e)),t&&EW(bW(t)),console.log("")},"displayUserInfo");async function whoamiAction(){const e=Mt("Fetching user information...").start();try{hasCommandApiKey(await getAuthKey9())||(e.fail(wW(qt)),process.exit(1));const t=await getAuthenticatedEntity({client:createApiClient({baseUrl:getApiBaseUrl()})});isAuthenticatedEntityLoaded(t)||(e.fail(wW(Yt)),process.exit(1)),e.succeed("User information loaded"),TW(t.user,t.org)}catch(t){e.fail(wW(`Error: ${vW(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var PW=new Be("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);handleUnhandledErrors(),setVscodeIpcLogger(dlog),setupTelemetry(),registerBundledRipgrep(),setImmediate(()=>{const e=getTelemetryEnv();recordCliFingerprintInBackground({getAuthKey:__name(()=>getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env}),"getAuthKey"),baseUrl:getApiBaseUrl(),cliEnvironment:normalizeCliEnvironment(e),cliVersion:getPackageJson(import.meta.url).version??"unknown",cmdZdr:"1"===process.env.CMD_ZDR})}),await preRun();var MW=createProgram();MW.action(interactiveModeAction),MW.addCommand(ZD),MW.addCommand(c$),MW.addCommand(PW),MW.addCommand(fW),MW.addCommand(XD),MW.addCommand(QD),MW.addCommand(createTasteCommand()),MW.addCommand(createMcpCommand()),MW.addCommand(nN),MW.addCommand(zD),MW.addCommand(UD),MW.addCommand(VD),MW.addCommand(mB),MW.addCommand($B),MW.addCommand(wN),isExperimentalEnabled()&&MW.addCommand(createSandboxCommand()),setupCommanderHooks(MW),MW.parse();
16
+ This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:e,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})})}__name(setModPathsOverride,"setModPathsOverride"),__name(setModOptionsOverride,"setModOptionsOverride"),__name(loadCommandModHost,"loadCommandModHost"),__name(buildHost,"buildHost"),__name(disposeCommandModHost,"disposeCommandModHost"),__name(exitAfterModHostTeardown,"exitAfterModHostTeardown"),__name(runModHostTeardown,"runModHostTeardown"),__name(handleStdoutError,"handleStdoutError"),__name(handleStderrError,"handleStderrError"),__name(handleUnhandledErrors,"handleUnhandledErrors"),Gt(),SR(),Gt(),Gt(),SR(),Gt(),SR(),Gt(),SR(),Gt();var UN=gt.pointer,jN=__name(({isSelected:e,backgroundColor:t})=>st.createElement(Xe,{color:e?wO:kO,backgroundColor:t,bold:e&&isLightTheme()},e?UN:" "),"OverlayCaret"),BN=__name(({isSelected:e,isActive:t,idleColor:n=vO,backgroundColor:r,children:o})=>st.createElement(Xe,{color:e?wO:t?CO:n,backgroundColor:r,bold:e&&isLightTheme()},o),"OverlayOptionText"),WN=__name(({isSelected:e,label:t})=>st.createElement(BN,{isSelected:e}," ",t),"OverlayOptionItem"),HN=__name(({backgroundColor:e})=>st.createElement(Xe,{color:CO,backgroundColor:e}," ",gt.tick),"OverlayActiveTick"),GN=__name(({indent:e=4,children:t})=>st.createElement(Xe,{color:yO}," ".repeat(e),t),"OverlayOptionDescription"),VN=__name(({isSelected:e,idleColor:t=ER.GRAY,selectedColor:n=ER.WHITE,bold:r,children:o})=>st.createElement(Xe,{color:e?n:t,backgroundColor:e?KR:void 0,bold:r??e},o),"OverlayBarText"),zN=__name(({isSelected:e,label:t})=>st.createElement(VN,{isSelected:e}," ",t," "),"OverlayBarItem"),KN=__name(()=>null,"OverlayBarIndicator");Gt();var qN=createOSC8Link("https://commandcode.ai/docs/permissions#permission-modes","Docs ↗",!1),YN=__name(({hint:e})=>st.createElement(Xe,{italic:!0,color:ER.DIM},e," · Run ",st.createElement(Xe,{color:ER.WHITE},"cmd --yolo")," to bypass all permissions (",qN,")"),"PermissionFooter"),JN=__name(({request:e,onResponse:t})=>{const[n]=at(0),r=getPermissionChoicesForRisk({choices:getGenericToolPermissionChoices({toolName:e.toolName}),risk:e.risk}),o=__name(e=>{const n=r.find(t=>t.value===e.value);n&&t(n)},"handleSelect");return st.createElement(bO,{title:"Tool Permission",subtitle:st.createElement(Xe,{wrap:"wrap"},"Command Code needs to run ",st.createElement(Xe,{color:wO},e.toolName),"."),footer:st.createElement(YN,{hint:"↑/↓ navigate · enter select"})},e.risk&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0,color:ER.RED,wrap:"wrap"},gt.warning," ",getRiskDisplay(e.risk))),e.description&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM,italic:!0},e.description)),st.createElement(SelectInput,{items:r.map((e,t)=>({label:`${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:n,indicatorComponent:jN,itemComponent:WN}))},"GenericPermissionPrompt");function buildTreeConnectors(e,t={}){const{isTruncated:n=!1,closesFrame:r=!0}=t;return e.split("\n").map((e,t,o)=>r&&!n&&t===o.length-1?yL:SL).join("\n")}Gt(),SR(),Gt(),SR(),Gt(),__name(buildTreeConnectors,"buildTreeConnectors");var QN=bt()?"⟳":"*",XN=" │ ";function DiffWordSegments({segments:e,type:t,paired:n,dimDiff:r,language:o,highlightOptions:s}){const i="removed"===t?IR.REMOVED_HIGHLIGHT_BG:IR.ADDED_HIGHLIGHT_BG,a=[];let l=0;for(const c of e){const e=c.highlighted,d=highlightSyntax(c.text,o,s),u=`${t}-${l++}-${e?"highlighted":"unchanged"}`;e?a.push(st.createElement(Xe,{key:u,backgroundColor:i,dimColor:r},d)):n?a.push(st.createElement(Xe,{key:u,color:ER.WHITE,dimColor:r},d)):a.push(st.createElement(Xe,{key:u,color:"removed"===t?IR.REMOVED_TEXT:IR.ADDED_TEXT,dimColor:r},d))}return a}function DiffRow({background:e,prefix:t,wrap:n="wrap",children:r}){return st.createElement(Qe,{width:"100%",backgroundColor:e},st.createElement(Qe,{flexShrink:0},t),st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{wrap:n},r)))}function renderDiffLine({line:e,dimDiff:t,language:n,highlightOptions:r}){if("skip"===e.kind)return st.createElement(Qe,{key:e.key,width:"100%"},st.createElement(Xe,{color:IR.LINE_NUM,dimColor:t},e.spacer,XN,e.label));if("context"===e.kind)return st.createElement(DiffRow,{key:e.key,prefix:st.createElement(Xe,{color:IR.LINE_NUM,dimColor:t}," "+e.lineNumberLabel+XN)},st.createElement(Xe,{color:ER.WHITE,dimColor:t}," ",highlightSyntax(e.text,n,r)));const o="removed"===e.kind,s=o?IR.REMOVED_TEXT:IR.ADDED_TEXT,i=o?IR.REMOVED_BG:IR.ADDED_BG;return st.createElement(DiffRow,{key:e.key,background:i,prefix:st.createElement(Xe,null,st.createElement(Xe,{color:s,dimColor:t}," "+e.lineNumberLabel),st.createElement(Xe,{color:IR.LINE_NUM,dimColor:t},XN),st.createElement(Xe,{color:s,dimColor:t},o?"- ":"+ "))},st.createElement(DiffWordSegments,{segments:e.segments,type:e.kind,paired:e.paired,dimDiff:t,language:n,highlightOptions:r}))}function DiffMetadata({metadata:e}){return e?"rejected"===e.kind?st.createElement(Xe,{color:ER.RED},"Rejected update to",st.createElement(Xe,{color:ER.RED},` ${e.filePath}`)):st.createElement(Xe,{color:ER.GRAY},"Updated"," ",st.createElement(Xe,{color:ER.WHITE,bold:!0},e.filePath)," ","with"," ",e.additions>0&&st.createElement(st.Fragment,null,st.createElement(Xe,{color:OR.SUCCESS},e.additions)," ","addition",1!==e.additions?"s":"",e.removals>0?" and ":""),e.removals>0&&st.createElement(st.Fragment,null,st.createElement(Xe,{color:OR.ERROR},e.removals)," ","removal",1!==e.removals?"s":"")):null}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:s=2,startLine:i=1,dimDiff:a=!1,maxLines:l}){const c=projectEditDiffView({oldValue:e,newValue:t,filePath:n,permissionDenied:r,showMetadata:o,startLine:i,maxLines:l});let d="";"string"==typeof t&&t?d=t:"string"==typeof e&&(d=e);const u=syntaxLanguageFromFilePath(n,d.split("\n",1)[0]??null),m=getSyntaxHighlightOptions(isLightTheme());return{diffContent:st.createElement(Qe,{flexDirection:"column"},st.createElement(DiffMetadata,{metadata:c.metadata}),st.createElement(Qe,{flexDirection:"column",marginLeft:s,marginRight:s+4,width:Math.max(20,(process.stdout.columns||80)-2*s-8)},c.displayedLines.map(e=>renderDiffLine({line:e,dimDiff:a,language:u,highlightOptions:m})))),isTruncated:c.isTruncated,totalLines:c.totalLines}}function resolveTodoTextStyle(e){return"completed"===e?{textColor:OR.SUCCESS,strikethrough:!0}:"in_progress"===e?{textColor:OR.IN_PROGRESS,strikethrough:!1}:{textColor:ER.WHITE,strikethrough:!1}}function TodoChecklist({todos:e}){return st.createElement(Qe,{flexDirection:"column"},e.map((e,t)=>{const n="completed"===e.status?gt.checkboxOn:gt.checkboxOff,{textColor:r,strikethrough:o}=resolveTodoTextStyle(e.status),s="in_progress"===e.status&&e.activeForm?`${e.activeForm}…`:e.content;return st.createElement(Qe,{key:e.id||t,flexDirection:"row"},st.createElement(Qe,{width:2},st.createElement(Xe,{color:r},n)),st.createElement(Xe,{color:r,bold:"in_progress"===e.status,strikethrough:o},s))}))}function formatTodosForDisplay(e){const t=Nh(e);return t?st.createElement(TodoChecklist,{todos:t}):st.createElement(Xe,null,e)}function computeDisplayInput({input:e,isAgent:t,isShell:n,expandedOutput:r}){return e?t?summarizeAgentTaskInput(e):n&&!r?truncateCommand({command:e}):e:e}function formatToolInput({input:e,isShell:t}){return st.createElement(BracketWrap,null,t?e:st.createElement(Markdown,null,e))}function ReadToolInlineSummaryRow({summary:e}){return e?.dimText?st.createElement(Xe,{dimColor:!0}," ",e.dimText):null}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:o}){if(e)return{symbolColor:ER.YELLOW,symbol:gt.arrowRight};if(t)return{symbolColor:ER.RED,symbol:gt.square};if(n)return{symbolColor:MR,symbol:"✻"};if(r&&o){const e=Nh(o),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?OR.SUCCESS:OR.WARNING,symbol:gt.square}}return{symbolColor:AR.BG,symbol:gt.square}}function ToolHeader({isThinking:e,isTasteFile:t,tasteCategory:n,name:r,summaryMatch:o,expandedOutput:s,expandKey:i,input:a,output:l}){if(e){const e=estimateReasoningSeconds(a||l||"");return st.createElement(st.Fragment,null,st.createElement(Xe,{color:MR},`Thought for ${e} second${1!==e?"s":""}`," "),!s&&st.createElement(BracketWrap,{color:ER.DIM},`${i}+o to expand`))}if(t)return st.createElement(st.Fragment,null,st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:PR.BADGE_BG,color:PR.BADGE_FG,bold:!0},vL)),st.createElement(Xe,null," ","Using your taste"," ",n?"package of ":"packages",n&&st.createElement(Xe,{bold:!0},n)));let c=r;return"READ[n]"===r&&o&&(c=`READ[${Number(o[1])}]`),st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:AR.BG,color:AR.FG,bold:!0},`${wL}${c}${wL}`))}function stripAgentUsageTrailer(e){return e.replace(/\n*<usage>[\s\S]*?<\/usage>\s*$/,"").trimEnd()}function AgentStatus({agentStatus:e,hasError:t,output:n,elapsedSeconds:r,tokensUsed:o}){const s=`${formatTime3(r)} | ${formatTokens(o)}`;return"running"===e?st.createElement(Xe,{color:ER.GRAY},"Running (",s,")"):"background"===e?st.createElement(Xe,{color:ER.GRAY},"Running in background"):"interrupted"===e||n===eS?st.createElement(Xe,{color:ER.GRAY,wrap:"wrap"},"Interrupted"):"error"===e||t?st.createElement(Xe,{color:ER.RED,wrap:"wrap"},n," (",s,")"):st.createElement(st.Fragment,null,st.createElement(Xe,{wrap:"wrap"},"Done"),st.createElement(Xe,{color:ER.GRAY}," (",s,")"))}function getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}){if(n)return{text:e,isTruncated:!1,remainingLines:0,truncationMsg:null};const o=dedentText(e),{text:s,isTruncated:i,remainingLines:a}=truncateToVisualLines({output:o,maxVisualLines:"Question"===t?Nd:Dd,maxChars:"Question"===t?1/0:Wd}),l=i&&"Question"!==t;return{text:s,isTruncated:l,remainingLines:a,truncationMsg:l?a>0?st.createElement(BracketedText,{text:`... +${a} lines [${r}+o to expand]`,color:ER.DIM}):st.createElement(BracketedText,{text:`... [${r}+o to expand]`,color:ER.DIM}):null}}function renderTruncatedOutput({output:e,name:t,expandedOutput:n,expandKey:r}){const{text:o,isTruncated:s,truncationMsg:i}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r});return s?st.createElement(st.Fragment,null,o,"\n",i):o}function renderEditFileDiff({input:e,metadata:t,expandedOutput:n,isPermissionDenied:r,output:o,expandKey:s}){const i=n?void 0:_d,{diffContent:a,isTruncated:l,totalLines:c}=generateDiff({filePath:e,showMetadata:!0,oldValue:t.oldValue??"",newValue:t.newValue??"",startLine:"number"==typeof t.startLine?t.startLine:1,dimDiff:r,permissionDenied:r,maxLines:i}),d=c-_d;return st.createElement(Qe,{flexDirection:"column"},a,l&&st.createElement(Qe,{marginTop:1},st.createElement(BracketedText,{text:`… (${d} more ${1===d?"line":"lines"}) [${s}+o to expand]`,color:ER.DIM})),r&&o&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.RED,wrap:"wrap"},o)))}function renderWriteFileContent({input:e,metadata:t,expandedOutput:n,expandKey:r}){const o=syntaxLanguageFromFilePath(e,t.content?.split("\n",1)[0]??null),s=getSyntaxHighlightOptions(isLightTheme()),i=projectWriteFileContentView({filePath:e,content:t.content,totalLines:t.totalLines,expandedOutput:n,expandKey:r});return i.empty?st.createElement(Xe,{color:ER.GRAY},"Created"," ",st.createElement(Xe,{color:ER.WHITE,bold:!0},i.filePath)," ","(empty file)"):st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.GRAY},"Created"," ",st.createElement(Xe,{color:ER.WHITE,bold:!0},i.filePath)," ","(",i.totalLinesLabel,")"),st.createElement(Qe,{marginTop:1,flexDirection:"column"},i.visibleLines.map(e=>st.createElement(DiffRow,{key:e.lineNumber,background:IR.ADDED_BG,wrap:"truncate-end",prefix:st.createElement(Xe,null,st.createElement(Xe,{color:IR.ADDED_TEXT}," "+e.lineNumberLabel),st.createElement(Xe,{color:IR.LINE_NUM},XN))},st.createElement(Xe,{color:IR.ADDED_TEXT},highlightSyntax(e.text,o,s))))),i.isTruncated&&i.moreLinesLabel&&st.createElement(Qe,{marginTop:1},st.createElement(BracketedText,{text:i.expandHint?`… (${i.moreLinesLabel}) ${i.expandHint}`:`… (${i.moreLinesLabel})`,color:ER.DIM})))}function renderOutputContent({isTodos:e,isThinking:t,isEditFile:n,isWriteFile:r,metadata:o,output:s,expandedOutput:i,isPermissionDenied:a,input:l,hasError:c,name:d,expandKey:u,showTreeConnector:m,closesFrame:p}){if(e)return formatTodosForDisplay(s);if(t){if(!i)return null;const e=l||s;return st.createElement(Qe,{width:"100%",flexDirection:"column"},st.createElement(Xe,null," "),st.createElement(Xe,{color:MR,wrap:"wrap",italic:!0},e))}const g=p?yL:SL;if(n&&"string"==typeof o?.oldValue&&"string"==typeof o?.newValue){const e=renderEditFileDiff({input:l,metadata:o,expandedOutput:i,isPermissionDenied:a,output:s,expandKey:u});return m?st.createElement(Qe,{columnGap:1},st.createElement(Xe,{color:zR},g," "),e):e}if(r&&o&&"content"in o){const e=renderWriteFileContent({input:l,metadata:o,expandedOutput:i,expandKey:u});return m?st.createElement(Qe,{columnGap:1},st.createElement(Xe,{color:zR},g," "),e):e}return m?renderTextWithLongConnector({output:s,name:d,expandedOutput:i,expandKey:u,hasError:c,closesFrame:p}):st.createElement(Qe,{width:"100%"},st.createElement(Xe,{color:c?ER.RED:"",wrap:"wrap"},renderTruncatedOutput({output:s,name:d,expandedOutput:i,expandKey:u})))}function renderTextWithLongConnector({output:e,name:t,expandedOutput:n,expandKey:r,hasError:o,closesFrame:s}){const{text:i,isTruncated:a,truncationMsg:l}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}),c=o?ER.RED:void 0,d=buildTreeConnectors(i,{isTruncated:a,closesFrame:s}),u=s?yL:SL;return st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(Qe,{columnGap:1,width:"100%"},st.createElement(Xe,{color:zR},d),st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:c,wrap:"wrap"},i))),a&&st.createElement(Qe,{columnGap:1},st.createElement(Xe,{color:zR},u," "),l))}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:i=!1}){const a="thinking…"===e,l="TODOS"===e,c="EDIT"===e,d="WRITE"===e,u="READ"===e||e.startsWith("READ[")&&e.endsWith("]"),m=!0===s?.isTasteFile,p=s?.tasteCategory,g=!0===s?.permissionDenied,h=!a&&!l&&!m,f="ctrl",y=!0===s?.isAgent,S=computeDisplayInput({input:t,isAgent:y,isShell:"SHELL"===e,expandedOutput:i}),w=!a&&S&&!m,v=s?.status,k=s?.tokensUsed||0,C="number"==typeof s?.elapsedSeconds?Math.floor(s.elapsedSeconds):0,{notes:b}=extractRepairNotes(n??""),E=b.length,T=u?parseReadSummaryLine(extractRepairNotes(n??"").body):null,P=u?projectReadToolInlineSummary({name:e,summaryMatch:T}):null,M=u?projectReadToolBadge({name:e,summaryMatch:T}):e,x=y&&!0===s?.showOutput&&"done"===v,I=Boolean((n||a&&t)&&!m&&(!y||x)&&(!u||o)),{symbolColor:A,symbol:R}=resolveSymbol({isPending:r,hasError:o,isThinking:a,isTodos:l,output:n}),L=s?.preHookLines,O=s?.postHookLines,D=Boolean(L?.length),$=Boolean(O?.length),N=Boolean(s?.hookOutcome),_=r&&!y&&!N,F=!N&&!_,U=I&&!$&&!N&&!_,j=D&&!I&&!$&&!N&&!_;return st.createElement(Qe,null,a&&st.createElement(Xe,{color:A},R),st.createElement(Qe,{flexDirection:"column",marginLeft:a?1:0},st.createElement(Qe,null,st.createElement(ToolHeader,{isThinking:a,isTasteFile:m,tasteCategory:p,name:M,summaryMatch:T,expandedOutput:i,expandKey:f,input:t,output:n}),w&&st.createElement(Xe,null," ",formatToolInput({input:S,isShell:"SHELL"===e})),st.createElement(ReadToolInlineSummaryRow,{summary:P}),E>0&&st.createElement(Xe,{dimColor:!0},` ${QN}${E>1?` ${E}`:""}`)),y&&("running"===v||"background"===v||"done"===v||"error"===v||n)&&st.createElement(Qe,{columnGap:1,marginLeft:h?1:0},h&&st.createElement(Xe,{color:zR},yL," "),st.createElement(AgentStatus,{agentStatus:v,hasError:o,output:n,elapsedSeconds:C,tokensUsed:k})),st.createElement(HookLines,{lines:L,showTreeConnector:h,closesFrame:j}),I&&renderOutputWithRepairNotes({output:x?stripAgentUsageTrailer(n??""):n??"",isTodos:l,isThinking:a,isEditFile:c,isWriteFile:d,metadata:s,expandedOutput:i||x,isPermissionDenied:g,input:t,hasError:o,name:e,expandKey:f,showTreeConnector:h,closesFrame:U}),st.createElement(HookLines,{lines:O,showTreeConnector:h,closesFrame:F}),st.createElement(HookOutcome,{outcome:s?.hookOutcome,showTreeConnector:h}),_&&st.createElement(Qe,{columnGap:1,marginLeft:1},st.createElement(Xe,{color:zR},yL," "),st.createElement(Xe,{color:ER.GRAY},"Processing…"))))}function renderOutputWithRepairNotes({output:e,isTodos:t,isThinking:n,isEditFile:r,isWriteFile:o,metadata:s,expandedOutput:i,isPermissionDenied:a,input:l,hasError:c,name:d,expandKey:u,showTreeConnector:m,closesFrame:p}){const{body:g}=extractRepairNotes(e);return st.createElement(Qe,{marginLeft:m?1:0},renderOutputContent({isTodos:t,isThinking:n,isEditFile:r,isWriteFile:o,metadata:s,output:g,expandedOutput:i,isPermissionDenied:a,input:l,hasError:c,name:d,expandKey:u,showTreeConnector:m,closesFrame:p}))}function HookLines({lines:e,showTreeConnector:t,closesFrame:n=!1}){if(!e||0===e.length)return null;const r=e.length-1;return st.createElement(Qe,{flexDirection:"column",marginLeft:t?1:0},e.map((e,t)=>{const o=n&&t===r?yL:SL;return st.createElement(Qe,{key:t,columnGap:1},st.createElement(Xe,{color:zR},o),st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},e)))}))}function HookOutcome({outcome:e,showTreeConnector:t}){if(!e)return null;const n="stop"===e.kind?ER.YELLOW:ER.RED;return st.createElement(Qe,{columnGap:1,marginLeft:t?1:0},st.createElement(Xe,{color:zR},yL),st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:n},e.text)))}__name(DiffWordSegments,"DiffWordSegments"),__name(DiffRow,"DiffRow"),__name(renderDiffLine,"renderDiffLine"),__name(DiffMetadata,"DiffMetadata"),__name(generateDiff,"generateDiff"),__name(resolveTodoTextStyle,"resolveTodoTextStyle"),__name(TodoChecklist,"TodoChecklist"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(computeDisplayInput,"computeDisplayInput"),__name(formatToolInput,"formatToolInput"),__name(ReadToolInlineSummaryRow,"ReadToolInlineSummaryRow"),__name(resolveSymbol,"resolveSymbol"),__name(ToolHeader,"ToolHeader"),__name(stripAgentUsageTrailer,"stripAgentUsageTrailer"),__name(AgentStatus,"AgentStatus"),__name(getTruncatedOutputParts,"getTruncatedOutputParts"),__name(renderTruncatedOutput,"renderTruncatedOutput"),__name(renderEditFileDiff,"renderEditFileDiff"),__name(renderWriteFileContent,"renderWriteFileContent"),__name(renderOutputContent,"renderOutputContent"),__name(renderTextWithLongConnector,"renderTextWithLongConnector"),__name(ToolMessage,"ToolMessage"),__name(renderOutputWithRepairNotes,"renderOutputWithRepairNotes"),__name(HookLines,"HookLines"),__name(HookOutcome,"HookOutcome");var ZN=createNodeRuntime(),e_=__name(({label:e,isSelected:t})=>e.includes("[shift+tab]")?st.createElement(st.Fragment,null,e.split("[shift+tab]")[0],st.createElement(BracketWrap,{color:t?wO:vO,bold:!0},"shift+tab")):e.includes("(")?st.createElement(st.Fragment,null,e.split("(")[0],st.createElement(Xe,{color:ER.GRAY},"(",e.split("(")[1])):e,"ChoiceLabel"),t_=__name(({request:e,onResponse:t,onEnableAutoAccept:n})=>{const[r]=at(0),[o,s]=at(1);ct(()=>{"edit"===e.action&&e.oldContent&&e.filePath&&resolveEditStartLine({runtime:ZN,filePath:e.filePath,oldContent:e.oldContent}).then(e=>{void 0!==e&&s(e)}).catch(()=>{})},[e.filePath,e.oldContent,e.action]);const i=getPermissionChoicesForRisk({choices:lM,risk:e.risk}),a=__name(e=>{const r=i.find(t=>t.value===e.value);r&&(t(r),"yes-session"===r.value&&n&&n())},"handleSelect"),l=__name(()=>"edit"===e.action?"make this edit to":"create"===e.action?"create":"delete"===e.action?"delete":"execute"===e.action?"execute":"modify","getActionDescription"),c=getDisplayPath({filePath:e.filePath,cwd:process.cwd()}),d=__name(()=>"edit"===e.action?"Edit File":"create"===e.action?"Create File":"delete"===e.action?"Delete File":"execute"===e.action?"Execute File":"File Operation","getHeading");return st.createElement(bO,{title:`${d()}${"edit"===e.action?` ${c}`:""}`,footer:st.createElement(YN,{hint:"↑/↓ navigate · enter select"})},"edit"===e.action&&e.oldContent&&e.newContent&&st.createElement(Qe,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c,marginLeft:0,startLine:o}).diffContent),e.risk&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0,color:ER.RED,wrap:"wrap"},gt.warning," ",getRiskDisplay(e.risk))),st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0},"Do you want to ",l()," ",st.createElement(Xe,{color:wO},c),"?")),st.createElement(SelectInput,{items:i.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:r,indicatorComponent:jN,itemComponent:({label:e,isSelected:t})=>st.createElement(BN,{isSelected:t},st.createElement(e_,{label:e,isSelected:t}))}))},"PermissionPrompt");Gt(),SR();var n_=NE?"ctrl+y":"ctrl+e",r_=__name(({request:e,onResponse:t})=>{const[n]=at(0),[r,o]=at({phase:"idle"}),s=e.description??("done"===r.phase?r.explanation:void 0),i=void 0!==e.explain&&void 0===e.description&&"done"!==r.phase;nt((t,n)=>{i&&"loading"!==r.phase&&(isCtrlKey({inputChar:t,key:n,letter:"e",ctrlCode:5})||isCtrlKey({inputChar:t,key:n,letter:"y",ctrlCode:25}))&&(o({phase:"loading"}),e.explain?.().then(e=>{o(e?{phase:"done",explanation:e}:{phase:"failed"})}).catch(()=>o({phase:"failed"})))});const a=getPermissionChoicesForRisk({choices:getShellPermissionChoices({command:e.command,...void 0!==e.args?{args:e.args}:{}}),risk:e.risk}),l=__name(e=>{const n=a.find(t=>t.value===e.value);n&&t(n)},"handleSelect");return st.createElement(bO,{title:"Execute Shell Command",subtitle:st.createElement(Xe,{wrap:"wrap"},"Command Code needs to execute ",st.createElement(Xe,{color:wO},getCommandDisplay(e)),"."),footer:st.createElement(YN,{hint:i?`↑/↓ navigate · enter select · ${n_} explain`:"↑/↓ navigate · enter select"})},e.risk&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0,color:ER.RED,wrap:"wrap"},gt.warning," ",getRiskDisplay(e.risk))),e.workingDirectory&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.GRAY},"Working directory: ",e.workingDirectory)),s&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM,italic:!0},s)),i&&"idle"===r.phase&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM,italic:!0},"Press"," ",st.createElement(BracketWrap,{color:ER.DIM,bold:!0},n_)," ","to explain this command")),"loading"===r.phase&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM,italic:!0},st.createElement(kt,{type:"dots"})," Explaining this command…")),"failed"===r.phase&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM,italic:!0},"Couldn't generate an explanation — press"," ",n_," to retry")),st.createElement(SelectInput,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:n,indicatorComponent:jN,itemComponent:({label:e,isSelected:t})=>st.createElement(BN,{isSelected:t},e.includes("[shift+tab]")?st.createElement(st.Fragment,null,e.split("[shift+tab]")[0],st.createElement(BracketWrap,{color:t?wO:vO,bold:!0},"shift+tab")):e)}))},"ShellPermissionPrompt");function handlePermissionResponse({choice:e,resolve:t,setPendingPermission:n,respondToPrompt:r,setStatus:o,permissionMode:s,showHintMessage:i,allowedStatus:a,deniedStatus:l}){r(e);const c="no"!==e.value;t(c),n(null),c?(o(a),"default"===s&&i("Use shift+tab to enable accept edits")):o(l)}__name(handlePermissionResponse,"handlePermissionResponse");var o_=it(__name(function PermissionView2({pendingPermission:e,permissionMode:t,setPendingPermission:n,setStatus:r,respondToPrompt:o,showHintMessage:s,handleEnableAutoAccept:i}){const a={resolve:e.resolve,setPendingPermission:n,respondToPrompt:o,setStatus:r,permissionMode:t,showHintMessage:s};if("shell_command"===e.toolName){const t=e.params;return st.createElement(Qe,{marginY:1},st.createElement(r_,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Shell command allowed",deniedStatus:"Shell command denied"})}))}if("kill_shell"===e.toolName){const t=buildKillShellPermissionRequest(e.params);return st.createElement(Qe,{marginY:1},st.createElement(r_,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Process termination allowed",deniedStatus:"Process termination denied"})}))}if(isGenericToolRequest(e.params)){const t=e.params;return st.createElement(Qe,{marginY:1},st.createElement(JN,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Tool call allowed",deniedStatus:"Tool call denied"})}))}const l=isFileEditRequest(e.params)?e.params:buildFileToolPermissionRequest({toolName:e.toolName,input:e.params,fallbackDescription:`Allow ${e.toolName} operation`,useInputDescription:!1});return st.createElement(Qe,{marginY:1},st.createElement(t_,{request:l,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"File operation allowed",deniedStatus:"File operation denied"}),onEnableAutoAccept:i}))},"PermissionView"));function isGenericToolRequest(e){return"object"==typeof e&&null!==e&&"toolName"in e&&"string"==typeof e.toolName}function isFileEditRequest(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.action&&"string"==typeof t.filePath}function PlanPanel({content:e,filePath:n,expanded:r}){const{stdout:o}=et(),s=trimPlanMarkdown(e,getCollapsedPlanMaxLines(o?.rows)),i=s.hiddenLineCount>0,a=r?e:s.visible,l=1!==s.hiddenLineCount?"s":"",c=`… +${s.hiddenLineCount} more line${l} · ctrl+o to expand`;return st.createElement(bO,{title:"Plan",titleSuffix:n?` · ${t.basename(n)}`:void 0,gapAfterHeader:!1,hint:i?r?"ctrl+o to collapse":c:void 0},st.createElement(Qe,{marginTop:1},st.createElement(Markdown,null,a)))}__name(isGenericToolRequest,"isGenericToolRequest"),__name(isFileEditRequest,"isFileEditRequest"),Gt(),SR(),Gt(),SR(),__name(PlanPanel,"PlanPanel"),Gt(),SR();var s_=__name(({preview:e})=>{const t=e.trim().split("\n"),n=t.slice(0,8),r=t.length-n.length,o="─".repeat(70),s=`─── ✂ ─── ${r} line${1===r?"":"s"} hidden `,i="─".repeat(Math.max(0,70-s.length));return st.createElement(Qe,{flexDirection:"column",marginTop:1,paddingLeft:4},st.createElement(Xe,{italic:!0,color:ER.DIM},"Preview"),st.createElement(Xe,{color:ER.DIM},`┌${o}┐`),n.map((e,t)=>{const n=e.length>68?e.slice(0,68):e,r=" ".repeat(Math.max(0,68-n.length));return st.createElement(Xe,{key:t},st.createElement(Xe,{color:ER.DIM},"│ "),st.createElement(Xe,{color:ER.GRAY},n),st.createElement(Xe,{color:ER.DIM},`${r} │`))}),r>0?st.createElement(Xe,{color:ER.YELLOW},`├${s}${i}┤`):null,st.createElement(Xe,{color:ER.DIM},`└${o}┘`))},"OptionPreview"),i_=[{label:"1. Submit",value:"submit"},{label:"2. Cancel",value:"cancel"}],a_=__name(({checked:e})=>e?st.createElement(Xe,{color:ER.GREEN},"[",gt.tick,"] "):st.createElement(Xe,{color:ER.DIM},"[ ] "),"MultiSelectCheckbox"),l_=__name((e,t)=>{if(!e.startsWith("option_"))return null;const n=e.slice(7),r=parseInt(n,10);return Number.isNaN(r)||r<0||r>t?null:r},"parseOptionIndex"),c_=__name((e,t)=>{const n=new Set(e);return n.has(t)?(n.delete(t),n):(n.add(t),n)},"toggleLabel"),d_=__name((e,t)=>e?{indicator:gt.bullet,color:wO}:t?{indicator:gt.tick,color:ER.GREEN}:{indicator:gt.circle,color:ER.GRAY},"getTabMarker"),u_=__name(({questions:e,currentIndex:t,answeredQuestions:n,isReviewPage:r,hideReview:o=!1})=>{if(o&&1===e.length)return null;const s=[];if(e.forEach((o,i)=>{const a=i===t&&!r,l=n.has(i),{indicator:c,color:d}=d_(a,l);s.push(st.createElement(Xe,{key:i},st.createElement(Xe,{color:d},c),st.createElement(Xe,{color:a?wO:void 0}," ",o.header),i<e.length-1?st.createElement(Xe,{color:ER.DIM}," | "):null))}),!o){const e=r;s.push(st.createElement(Xe,{key:"review"},st.createElement(Xe,{color:ER.DIM}," | "),st.createElement(Xe,{color:e?wO:ER.GRAY},e?gt.bullet:gt.circle),st.createElement(Xe,{color:e?wO:void 0,bold:e}," ","Review")))}return st.createElement(Qe,null,s)},"TabIndicator"),m_=__name(({questions:e,onResponse:t,hideCustomInput:n=!1,compact:r=!1})=>{const[o,s]=at(0),[i,a]=at(new Map),l=lt(null);null===l.current&&(l.current=new Map);const c=l.current,[d,u]=at(""),[m,p]=at(new Set),[g,h]=at(null),[f,y]=at(!1),[S,w]=at(!1),[v,k]=at(!1),[C,b]=at(null),[E,T]=at(!1),P=lt(null);null===P.current&&(P.current=new Map);const M=lt(null);null===M.current&&(M.current=new Map);const[x,I]=at(!1),[A,R]=at(""),[,L]=at(0),O=e[o],D=O?.multiSelect??!1,$=i.get(o),N=O?[...O.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description,...void 0!==e.preview?{preview:e.preview}:{}}))]:[],_=N.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),F=new Map(_.map((e,t)=>[e.label,N[t]])),U=__name((e,t)=>{t.size>0?c.set(e,Array.from(t)):c.delete(e)},"saveOrClearMultiAnswer"),j=__name(t=>{const n=e[t],r=c.get(t);if(n?.multiSelect&&r){p(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));return void u(e||"")}if(p(new Set),!n?.multiSelect&&1===r?.length){const e=r[0],t=!n?.options.some(t=>t.label===e);return void u(t&&e?e:"")}u("")},"restoreInputsForQuestion"),B=__name(e=>{"submit"!==e.value?"cancel"===e.value&&t({answers:[]}):q()},"handleReviewSelect"),W=__name(()=>{if(!$||0===$.length)return 0;const e=$[0],t=O.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),H=__name(e=>{if(f)return;if(D){const t=l_(e.value,O.options.length-1);if(null===t)return;const n=O.options[t]?.label||"";return void p(e=>c_(e,n))}const t=l_(e.value,O.options.length-1);if(null===t)return;y(!0);const n=O.options[t]?.label||"";z([n])},"handleSelect"),G=__name(()=>{if(f)return;y(!0);const e=Array.from(m);z(e)},"handleMultiSelectDone"),V=__name(()=>{if(f)return;const e=d.trim();if(e){if(D){const t=new Set(O.options.map(e=>e.label));return void p(n=>{const r=new Set;return n.forEach(e=>{t.has(e)&&r.add(e)}),r.add(e),r})}y(!0),z([e])}},"handleOtherSubmit"),z=__name(t=>{c.set(o,t);const r=new Map(c);if(a(r),o<e.length-1){const e=o+1;return j(e),s(e),y(!1),k(!1),b(null),void T(!1)}if(e.every((e,t)=>r.has(t)))return n&&1===e.length?void q():(p(new Set),u(""),k(!1),T(!1),b(null),w(!0),void y(!1));const i=e.findIndex((e,t)=>!r.has(t));-1!==i&&(j(i),s(i)),y(!1),k(!1),b(null),T(!1)},"finishQuestion"),K=__name(()=>e.map((e,t)=>{const n=c.get(t)||[],r=M.current?.get(t),o=0===n.length&&r?.length?["(Image attached)"]:n,s=P.current?.get(t)?.trim(),i=e.multiSelect||1!==n.length?void 0:e.options.find(e=>e.label===n[0]);return{questionIndex:t,selectedOptions:o,...i?.preview?{preview:i.preview}:{},...s?{notes:s}:{},...r?.length?{images:r}:{}}}),"buildAnswers"),q=__name(()=>{t({answers:K()})},"submitAnswers"),Y=__name(()=>{t({answers:K(),disposition:"chat"})},"chatAboutQuestions"),J=__name(()=>{P.current&&(A.trim()?P.current.set(o,A):P.current.delete(o)),I(!1)},"saveNotesAndClose"),Q=__name(async()=>{try{const e=await detectClipboardImage();if(!e)return;const t=M.current?.get(o)??[];M.current?.set(o,[...t,{data:e.data,mediaType:e.mediaType}]),L(e=>e+1)}catch{}},"pasteClipboardImageIntoQuestion"),X=__name(async(e,t)=>{try{const n=await openInEditor(e);n!==e&&t(n)}catch{}},"editExternally"),Z=__name(e=>{w(!1),s(e),T(!1),k(!1),b(null),j(e)},"editQuestion"),ee=__name(t=>{t<0||t>=e.length||(D&&(U(o,m),a(new Map(c))),y(!1),k(!1),b(null),T(!1),j(t),s(t))},"navigateToQuestion"),te=__name(()=>{if(!g||!D)return;if("done"===g.value)return;const e=l_(g.value,O.options.length-1);if(null===e)return;const t=O.options[e]?.label||"";p(e=>c_(e,t))},"toggleMultiSelection"),ne=__name(e=>{const t=_[0],r=_[_.length-1],o=g&&t&&g.value===t.value,s=g&&r&&g.value===r.value;if(!e.downArrow||v||E||n||!(_.length>0)||!s)return e.upArrow&&!v&&!E&&_.length>0&&o?D?void T(!0):void(n||(k(!0),b(_.length-1))):e.upArrow&&v?(k(!1),b(_.length-1),void(r&&h(r))):e.downArrow&&v?(k(!1),D?void T(!0):(b(0),void(t&&h(t)))):e.upArrow&&E?(T(!1),void k(!0)):e.downArrow&&E?(T(!1),b(0),void(t&&h(t))):void(e.return&&E&&D&&G());k(!0)},"handleVerticalNav"),re=__name(t=>{f||v||E||(S?t.leftArrow&&Z(e.length-1):t.leftArrow&&o>0?ee(o-1):t.rightArrow&&(o<e.length-1?ee(o+1):(D&&(U(o,m),a(new Map(c))),w(!0))))},"handleHorizontalNav"),oe=__name(()=>{if(!f)if(S)w(!1);else{if(v){k(!1);const e=C??_.length-1;b(e);const t=_[e];return void(t&&h(t))}if(E){T(!1);const e=_[_.length-1];e&&h(e)}}},"handleEscape");if(nt((e,t)=>{const r="v"===e&&(t.ctrl||t.meta&&"darwin"!==process.platform);if(x)t.escape?J():r?Q():t.ctrl&&"g"===e&&X(A,R);else if(r&&v)Q();else if(t.ctrl&&"g"===e&&v)X(d,u);else{if(" "===e&&D&&!v&&te(),"d"!==e||!D||v||S||G(),!(v||S||f||n)){if("n"===e)return R(P.current?.get(o)??""),void I(!0);if("c"===e)return void Y()}S||f||ne(t),re(t),t.escape&&oe()}}),!O&&!S)return null;if(S)return st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(ZR,{dividerColor:SO}),st.createElement(Qe,{marginBottom:1},st.createElement(u_,{questions:e,currentIndex:e.length,answeredQuestions:new Set(i.keys()),isReviewPage:!0})),e.some((e,t)=>!i.get(t)?.length)&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.YELLOW},"⚠ You have not answered all questions")),e.map((e,t)=>st.createElement(Qe,{key:t,marginBottom:1,flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},t+1,". ",e.question),st.createElement(Xe,{color:ER.GREEN}," ",i.get(t)?.join(", ")||"No answer"))),st.createElement(SelectInput,{items:i_,onSelect:B,initialIndex:0,indicatorComponent:jN,itemComponent:WN}),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{italic:!0,color:ER.DIM},gt.arrowLeft," to go back and edit")));const se=r&&1===e.length;return st.createElement(Qe,{flexDirection:"column",width:"100%"},!se&&st.createElement(ZR,{dividerColor:SO}),!se&&st.createElement(Qe,{marginBottom:1},st.createElement(u_,{questions:e,currentIndex:o,answeredQuestions:new Set(i.keys()),isReviewPage:!1,hideReview:n})),st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{bold:!0,color:fO},O.question)),v||E||x?st.createElement(Qe,{flexDirection:"column"},_.map((e,t)=>{const n=F.get(e.label),r=D&&n&&m.has(n.label),o=!D&&n&&$?.includes(n.label),s=r||o;return st.createElement(Qe,{key:e.value,flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,null," "),st.createElement(BN,{isActive:s,idleColor:ER.GRAY}," ",t+1,"."," "),D&&st.createElement(a_,{checked:s}),st.createElement(BN,{isActive:s,idleColor:ER.GRAY},n?.label||""),!D&&s&&st.createElement(HN,null)),n?.description&&st.createElement(Qe,null,st.createElement(Xe,null," "),st.createElement(GN,{indent:D?7:4},n.description)))})):st.createElement(SelectInput,{key:`${o}-${C??"default"}`,items:_,initialIndex:C??W(),onSelect:H,onHighlight:h,indicatorComponent:jN,itemComponent:({label:e,isSelected:t})=>{const n=F.get(e),r=D&&n&&m.has(n.label),o=!D&&n&&$?.includes(n.label),s=r||o,i=e.match(/^\s*(\d+)\.\s*(.*)$/),a=i?.[1]||"",l=i?.[2]||e;return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(BN,{isSelected:t,isActive:s}," ",a,"."," "),D&&st.createElement(a_,{checked:s}),st.createElement(BN,{isSelected:t,isActive:s},l),!D&&s&&st.createElement(HN,null)),n?.description&&st.createElement(GN,{indent:D?7:4},n.description))}}),!v&&!E&&(()=>{const e=(g?F.get(g.label):void 0)??N[C??W()];return e?.preview?st.createElement(s_,{preview:e.preview}):null})(),!n&&st.createElement(Qe,null,st.createElement(jN,{isSelected:v}),st.createElement(BN,{isSelected:v}," ",_.length+1,"."," "),D&&st.createElement(a_,{checked:m.has(d.trim())}),st.createElement(TextInput,{value:d,onChange:e=>{const t=e.replace(/\r\n/g," ").replace(/[\r\n]/g," "),n=d.trim();u(t),D&&p(e=>{const r=new Set(e);return n&&r.has(n)&&r.delete(n),t.trim()&&r.add(t.trim()),r})},onSubmit:V,placeholder:"Type something...",focus:v,stripBracketedPaste:!0})),x?st.createElement(Qe,null,st.createElement(jN,{isSelected:!0}),st.createElement(BN,{isSelected:!0}," ","notes:"," "),st.createElement(TextInput,{value:A,onChange:R,onSubmit:J,placeholder:"Add notes on this design…",focus:x,stripBracketedPaste:!0})):(()=>{const e=P.current?.get(o)?.trim();return e?st.createElement(Qe,null,st.createElement(Xe,{italic:!0,color:ER.DIM}," ","notes: ",e)):null})(),(M.current?.get(o)??[]).map((e,t)=>st.createElement(Qe,{key:t},st.createElement(Xe,{color:ER.DIM}," ","[Image #",t+1," attached —"," ",e.mediaType,"]"))),D&&st.createElement(Qe,null,st.createElement(jN,{isSelected:E}),st.createElement(BN,{isSelected:E}," ",o===e.length-1?"Submit":"Next")),e.length>1&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{italic:!0,color:ER.DIM},"Enter to select | Arrow keys to navigate |"," ",n?"Esc to cancel":"1-9 quick select | n notes | c chat | Esc to cancel")))},"QuestionPrompt");function QuestionView({pendingQuestion:e,setPermissionMode:t,dangerouslySkipPermissions:n,setPendingQuestion:r,setStatus:o,setStaticKey:s}){const[i,a]=at(!1),l=e.params.planContent;return nt((e,t)=>{l&&getIsExpandToolShortcut(t,e)&&a(e=>!e)}),st.createElement(Qe,{marginY:1,flexDirection:"column"},l&&st.createElement(Qe,{marginBottom:1},st.createElement(PlanPanel,{content:l,filePath:e.params.planFilePath,expanded:i})),st.createElement(m_,{questions:e.params.questions,hideCustomInput:e.params.hideCustomInput,compact:e.params.compact,onResponse:i=>{const a=resolvePlanModeAnswerTransition({answer:i.answers[0]?.selectedOptions[0]||"",exitPlanMode:e.params.exitPlanMode,enterPlanMode:e.params.enterPlanMode,dangerouslySkipPermissions:n});a&&t(a),e.resolve(i),r(null),o("Answers submitted"),hardResetForResize(),s(e=>e+1)}}))}__name(QuestionView,"QuestionView"),Gt(),SR();var p_="__skip__",g_=__name(({suggestion:e,onSelect:t,onClose:n})=>{const{completedMode:r,primary:o,secondary:s,description:i}=e,a=[...o.map(e=>({label:e,value:e,isPrimary:!0})),...s.map(e=>({label:e,value:e,isPrimary:!1})),{label:"skip",value:p_,isPrimary:!1}],l=new Map(a.map(e=>[e.label,e]));nt((e,t)=>{t.escape&&n()});const c=__name(e=>{e.value!==p_?(t(e.value),n()):n()},"handleSelect");return st.createElement(bO,{title:`/design ${r} complete`,titleSuffix:` · ${i}`,hint:"Enter to run · Esc to dismiss"},st.createElement(SelectInput,{items:a,onSelect:c,indicatorComponent:KN,itemComponent:({label:e,isSelected:t})=>{const n=l.get(e),r=n?.value===p_,o=n?.isPrimary??!1,s=r?"run /design manually":hy[e]??"";return st.createElement(Qe,{flexDirection:"column"},st.createElement(VN,{isSelected:t,idleColor:o?ER.WHITE:ER.DIM},r?" skip ":` /design ${e} `),s&&st.createElement(VN,{isSelected:t,idleColor:ER.DIM,bold:!1},` ${s} `))}}))},"DesignModeSelector");function getUsageToneColor(e){return"danger"===e?ER.RED:"warning"===e?ER.YELLOW:ER.GREEN}function getDistanceToneColor(e){return"danger"===e?ER.RED:"warning"===e?ER.YELLOW:ER.GRAY}function ContextProgress({view:e,progressBarWidth:t}){const n=getUsageToneColor(e.tone),r=buildBlockBar({percentage:e.percentage,width:t});return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{marginBottom:1},st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:ER.BLUE,color:"#f4f4f4",bold:!0},`${wL}CONTEXT${wL}`)),st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:ER.GRAY},e.modelLabel)),st.createElement(Qe,null,st.createElement(Xe,{color:n},r.filled),st.createElement(Xe,{color:$R},r.empty),st.createElement(Xe,{bold:!0,color:n},` ${e.percentageLabel}`)),st.createElement(Qe,null,st.createElement(Xe,null,e.tokensUsedLabel),st.createElement(Xe,{color:ER.GRAY},` / ${e.tokenLimitLabel}`),st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:n},e.tokensRemainingLabel),st.createElement(Xe,{color:ER.GRAY}," remaining"),e.isEstimated&&st.createElement(Xe,{color:ER.DIM}," (estimated)")))}function CompactionDistance({view:e}){if(!e)return null;const t=getDistanceToneColor(e.tone);return st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:t},e.tokensAwayLabel),st.createElement(Xe,{color:ER.DIM},e.label))}function BreakdownRow({item:e,labelWidth:t}){return st.createElement(Qe,null,st.createElement(Xe,null,e.name.padEnd(t)),st.createElement(Xe,{bold:!0},e.paddedValue),st.createElement(Xe,{color:ER.GRAY}," tokens"),e.detail&&st.createElement(Xe,{color:ER.DIM},` · ${e.detail}`))}function ContextBreakdown({view:e,labelWidth:t}){return 0===e.rows.length?null:st.createElement(Qe,{flexDirection:"column",marginTop:1},e.rows.map(e=>st.createElement(BreakdownRow,{key:e.name,item:e,labelWidth:t})))}function ContextTips({tips:e}){return 0===e.length?null:st.createElement(Qe,{flexDirection:"column",marginTop:1},e.map(e=>st.createElement(Qe,{key:e},st.createElement(Xe,{color:ER.CYAN},gt.pointer),st.createElement(Xe,{color:ER.GRAY}," ",e))))}function ContextMessage({analysis:e}){const t=projectContextView(e,{terminalWidth:useTerminalWidth(),modelDisplayName:getModelDisplayName(e.model)});return st.createElement(Qe,{flexDirection:"column",paddingTop:1},st.createElement(ContextProgress,{view:t.progress,progressBarWidth:t.layout.progressBarWidth}),st.createElement(CompactionDistance,{view:t.compactionDistance}),st.createElement(ContextBreakdown,{view:t.breakdown,labelWidth:t.layout.labelWidth}),st.createElement(ContextTips,{tips:t.tips}))}function ContextConfigView({staticKey:e,sessionId:t,onClose:n,setInput:r}){const[o,s]=at(null),[i,a]=at(null);return ct(()=>{let e=!0;return __name(async()=>{const n=k$(t);if(n)try{const t=await analyzeCommandContext({messages:harnessSessionMessages(n),deps:{getContextLimit:__name(e=>customAwareContextLimit({modelId:e,fallback:getContextLimit}),"getContextLimit")}});e&&s(t)}catch{e&&a("Failed to analyze context.")}else e&&a("No active conversation. Start chatting first.")},"load")(),()=>{e=!1}},[t]),nt((e,t)=>{t.escape&&(r(""),n())}),st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(ContextBody,{error:i,analysis:o}),st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Press ",st.createElement(gO,null,"Esc")," to return to conversation"))))}function ContextBody({error:e,analysis:t}){return e?st.createElement(bO,{title:"Context",gapAfterHeader:!1},st.createElement(Xe,{color:ER.DIM},e)):t?st.createElement(ContextMessage,{analysis:t}):st.createElement(bO,{title:"Context",gapAfterHeader:!1},st.createElement(A$,{label:"Loading context analysis"}))}Gt(),SR(),Gt(),SR(),__name(getUsageToneColor,"getUsageToneColor"),__name(getDistanceToneColor,"getDistanceToneColor"),__name(ContextProgress,"ContextProgress"),__name(CompactionDistance,"CompactionDistance"),__name(BreakdownRow,"BreakdownRow"),__name(ContextBreakdown,"ContextBreakdown"),__name(ContextTips,"ContextTips"),__name(ContextMessage,"ContextMessage"),__name(ContextConfigView,"ContextConfigView"),__name(ContextBody,"ContextBody"),Gt(),Gt(),SR(),Gt(),SR();var h_="https://commandcode.ai/studio";function getVersionStatus(){try{return{current:getPackageJson(import.meta.url).version??"Unknown",updateAvailable:null}}catch{return{current:"Unknown",updateAvailable:null}}}async function getAuthStatus(){try{const e=await checkCommandAuthStatus({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env}),t=e.userName||null;return{authenticated:e.authenticated,username:t}}catch{return{authenticated:!1,username:null}}}async function getModelStatus(e){try{const t=e?.sessionId?k$(e.sessionId):void 0,n=t?.getModel()??await getSelectedModel(),r=getProviderDisplayName((await loadUserConfig()).provider||null),o=getModelShortName({modelId:n,findModelById:findModelById});let s;return modelSupportsReasoningEffort(n)&&(s=t?t.getEffort():getReasoningEffort(n)),{id:n,displayName:s?`${o} with ${s} effort`:o,provider:r}}catch{return{id:"Unknown",displayName:"Unknown",provider:"Unknown"}}}function getPrStatus(e){try{const t=getCachedPR(e);return t?{number:t.number,url:t.url,state:t.state}:null}catch{return null}}function gatherStatusData(e){const t=e?.runtime??createNodeRuntime();return getStatusSnapshot({runtime:t,version:getVersionStatus,auth:getAuthStatus,model:__name(()=>getModelStatus({sessionId:e?.sessionId}),"model"),pr:getPrStatus,taste:__name(()=>getTasteStatus({runtime:t,learningEnabled:isTasteLearningEnabled,byokSuppressed:isByok({model:getConfiguredModel()})}),"taste"),system:__name(()=>getSystemStatus({runtime:t,arch:process.arch,nodeVersion:process.version}),"system"),disabledSkillNames:__name(async()=>(await loadCommandDisabledSkills()).names,"disabledSkillNames")})}__name(getVersionStatus,"getVersionStatus"),__name(getAuthStatus,"getAuthStatus"),__name(getModelStatus,"getModelStatus"),__name(getPrStatus,"getPrStatus"),__name(gatherStatusData,"gatherStatusData");var f_=__name(({label:e,value:t,valueColor:n,dimValue:r})=>st.createElement(Qe,null,st.createElement(Xe,{dimColor:!0},`${e}:`.padEnd(14)),r?st.createElement(Xe,{dimColor:!0},t):st.createElement(Xe,{color:n},t)),"Row");function StatusMessage({statusData:e}){const t=projectStatusView(e,{profileBaseUrl:"https://commandcode.ai"}),n=t.account.authenticated?gt.tick:gt.cross,r=t.account.authenticated?ER.WHITE:OR.ERROR;return st.createElement(Qe,{flexDirection:"column",paddingX:0},st.createElement(Qe,null,st.createElement(Xe,{color:TR,bold:!0},"Command Code"," "),st.createElement(Xe,{dimColor:!0},t.versionText)),st.createElement(Qe,null,st.createElement(Xe,{dimColor:!0},"Visit "),st.createElement(cL,{url:h_,text:h_,color:ER.CYAN}),st.createElement(Xe,{dimColor:!0}," for usage and billing")),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{dimColor:!0},"Account:".padEnd(14)),t.account.username&&t.account.profileUrl?st.createElement(st.Fragment,null,st.createElement(cL,{url:t.account.profileUrl,text:t.account.label,color:ER.CYAN}),st.createElement(Xe,{color:r}," ",n)):t.account.authenticated?st.createElement(st.Fragment,null,st.createElement(Xe,null,t.account.label),st.createElement(Xe,{color:r}," ",n)):st.createElement(st.Fragment,null,st.createElement(Xe,{color:OR.WARNING},t.account.label),st.createElement(Xe,{color:r}," ",n),st.createElement(Xe,{dimColor:!0}," — run "),st.createElement(Xe,{bold:!0},t.account.loginHint))),st.createElement(f_,{label:"Model",value:t.model.value}),st.createElement(f_,{label:"Branch",value:t.branch.value,dimValue:t.branch.dim}),t.worktree?st.createElement(f_,{label:"Worktree",value:t.worktree.value}):null,t.repository?st.createElement(Qe,null,st.createElement(Xe,{dimColor:!0},"Repository:".padEnd(14)),st.createElement(cL,{url:t.repository.url,text:t.repository.text,color:ER.CYAN}),t.pullRequest?st.createElement(st.Fragment,null,st.createElement(Xe,{dimColor:!0}," · "),st.createElement(cL,{url:t.pullRequest.url,text:t.pullRequest.text,color:t.pullRequest.open?ER.CYAN:ER.GRAY}),st.createElement(Xe,{dimColor:!0}," ","(",t.pullRequest.stateLabel,")")):null):t.pullRequest?st.createElement(Qe,null,st.createElement(Xe,{dimColor:!0},"Pull Request:".padEnd(14)),st.createElement(cL,{url:t.pullRequest.url,text:t.pullRequest.text,color:t.pullRequest.open?ER.CYAN:ER.GRAY}),st.createElement(Xe,{dimColor:!0}," (",t.pullRequest.stateLabel,")")):null,st.createElement(f_,{label:"Taste",value:t.taste.value,dimValue:t.taste.dim}),st.createElement(f_,{label:"Directory",value:t.directory.value}),st.createElement(f_,{label:"Skills",value:t.skills.value,dimValue:t.skills.dim}),st.createElement(f_,{label:"Agents",value:t.agents.value,dimValue:t.agents.dim}),st.createElement(f_,{label:"System",value:t.system.value}),t.proxy?st.createElement(f_,{label:"Proxy",value:t.proxy.value}):null)}function StatusBody({state:e}){return"ready"===e.phase?st.createElement(StatusMessage,{statusData:e.data}):"error"===e.phase?st.createElement(Xe,{dimColor:!0},"Could not load status: ",e.message):st.createElement(Xe,{dimColor:!0},"Gathering status…")}function StatusConfigView({staticKey:e,sessionId:t,onClose:n,setInput:r}){const[o,s]=at({phase:"loading"});return ct(()=>{let e=!1;return gatherStatusData({sessionId:t}).then(t=>{e||s({phase:"ready",data:t})}).catch(t=>{if(e)return;const n=t instanceof Error?t.message:"Failed to gather status";s({phase:"error",message:n})}),()=>{e=!0}},[t]),nt((e,t)=>{t.escape&&(r(""),n())}),st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(StatusBody,{state:o}),st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Press ",st.createElement(gO,null,"Esc")," to return to conversation"))))}__name(StatusMessage,"StatusMessage"),__name(StatusBody,"StatusBody"),__name(StatusConfigView,"StatusConfigView"),Gt(),SR(),SR(),Gt(),SR();var{addDirectory:y_,formatDirectoryForDisplay:S_,getAdditionalDirectories:w_,removeAdditionalDirectory:v_}=By,k_=__name(({onClose:e})=>{const[t,n]=at(""),[r,o]=at(null),[s,i]=at([]),[a,l]=at(()=>w_()),[c,d]=at(()=>({zone:"input",suggestionIndex:0,activeDirIndex:0})),[u,m]=at(0);ct(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),m(0)},[t]),ct(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const p=__name(e=>{const t=y_(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(w_()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),g=__name(e=>{if(!v_(e))return o({tone:"error",text:`${S_(e)} is no longer in workspace scope`}),void l(w_());o({tone:"success",text:`Removed ${S_(e)} from directory scope`}),l(w_()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");nt((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===c.zone&&s[c.suggestionIndex]?void p(s[c.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===c.zone&&a[c.activeDirIndex])g(a[c.activeDirIndex]);else{if(r.tab&&s.length>0){const e=s[c.suggestionIndex]??s[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),o(null)))}r.downArrow?d(e=>moveAddDirFocusDown(e,{suggestionCount:s.length,activeDirCount:a.length})):r.upArrow&&d(e=>moveAddDirFocusUp(e,{suggestionCount:s.length,activeDirCount:a.length}))}}}),ct(()=>{"suggestions"===c.zone&&m(e=>getAdjustedSuggestionOffset({selectedIndex:c.suggestionIndex,currentOffset:e,maxVisible:aR,totalSuggestions:s.length}))},[c,s.length]),ct(()=>{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 h=s.slice(u,u+aR),f=getAddDirFooterText({focusZone:c.zone});return st.createElement(bO,{title:"Add directory to workspace",subtitle:st.createElement(Xe,{color:ER.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),footer:st.createElement(Xe,{italic:!0,color:ER.DIM},st.createElement(BracketedText,{text:f,color:ER.DIM})),gapAfterHeader:!1},st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Xe,{color:ER.GRAY},"Added directories"),0===a.length?st.createElement(Xe,{color:ER.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===c.zone&&c.activeDirIndex===t;return st.createElement(Qe,{key:e},st.createElement(Xe,null," "),st.createElement(jN,{isSelected:n}),st.createElement(BN,{isSelected:n,isActive:!0}," ",S_(e)))})),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{bold:!0,color:ER.WHITE},"Path")),st.createElement(Qe,null,st.createElement(TextInput,{value:t,focus:"input"===c.zone,prefix:`${"input"===c.zone?gt.pointer:" "} `,prefixColor:"input"===c.zone?wO:ER.GRAY,onChange:e=>{n(e),o(null)},onSubmit:p})),!t&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:{error:ER.RED,warning:ER.YELLOW,success:ER.GREEN}[r.tone]},r.text)),s.length>0&&st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.GRAY},"Suggestions"),h.map((e,t)=>{const n=u+t,r="suggestions"===c.zone&&c.suggestionIndex===n;return st.createElement(Qe,{key:e},st.createElement(Xe,null," "),st.createElement(jN,{isSelected:r}),st.createElement(BN,{isSelected:r,idleColor:ER.GRAY}," ",e))})))},"AddDirModal");function createBillingTransport(){const e=createApiClient({baseUrl:getApiBaseUrl()});return{get:__name(({route:t})=>e.get({endpoint:t}),"get"),post:__name(({route:t,body:n})=>e.post({endpoint:t,body:n}),"post"),postMultipart:__name(()=>Promise.reject(new Error("billing transport does not upload multipart")),"postMultipart"),delete:__name(({route:t})=>e.delete({endpoint:t}),"delete"),postStream:__name(()=>Promise.reject(new Error("billing transport does not stream")),"postStream")}}Gt(),Gt(),SR(),Gt(),SR(),Gt(),SR(),Gt(),Gt(),SR(),Gt(),SR(),__name(createBillingTransport,"createBillingTransport");var C_=null;function getBilling(){return C_||(C_=createBilling({transport:createBillingTransport()})),C_}function getCachedBillingContext(){return C_?.getCached()??null}function getBillingContext(){return getBilling().get()}function prefetchBillingContext(){getBilling().prefetch()}function invalidateBillingContext(){C_=null}function buildLaneModelPickerGroups(){const e=filterModelGroupsByRegisteredModules(ID).filter(e=>e.providerId!==uo.COMMAND);return[...buildModelPickerGroups({normalModeGroups:AD}),...e,...buildCustomModelPickerGroups()]}function buildCatalogModelPickerGroups(){return[...buildModelPickerGroups({normalModeGroups:AD}),...buildCustomModelPickerGroups()]}function laneServesModel(e){if(e.activeLane===uo.COMMAND)return!0;const t=Qo[e.activeLane]?.supportedModelProviders;if(!t)return!0;const n=Object.values(lD).find(t=>t.id===e.modelId);return!n||laneSupportsModel(t,n)}function laneModelCount(e){return e.laneId===uo.COMMAND?AD.reduce((e,t)=>e+t.models.length,0):ID.find(t=>t.providerId===e.laneId)?.models.length??0}function defaultModelForLane(e){const t=filterModelGroupsByRegisteredModules(ID),n=t.filter(t=>t.providerId===e.activeLane),r=n.length>0?n:t.filter(e=>e.providerId===uo.COMMAND);return r[0]?.models[0]?.id}function useCustomModelsReady(e){const[t,n]=at(!1);return ct(()=>{let t=!0;return(async()=>{await refreshCustomProviderModels(e?{sessionId:e}:void 0),t&&n(!0)})(),()=>{t=!1}},[e]),t}__name(getBilling,"getBilling"),__name(getCachedBillingContext,"getCachedBillingContext"),__name(getBillingContext,"getBillingContext"),__name(prefetchBillingContext,"prefetchBillingContext"),__name(invalidateBillingContext,"invalidateBillingContext"),Gt(),SR(),__name(buildLaneModelPickerGroups,"buildLaneModelPickerGroups"),__name(buildCatalogModelPickerGroups,"buildCatalogModelPickerGroups"),__name(laneServesModel,"laneServesModel"),__name(laneModelCount,"laneModelCount"),__name(defaultModelForLane,"defaultModelForLane"),Gt(),__name(useCustomModelsReady,"useCustomModelsReady"),Gt(),SR();var b_=__name((e,t)=>{const n=t&&e.id===TD?" (default)":"",r="free"===e.badge?" (FREE)":"";return e.label.length+n.length+r.length},"renderedLabelLength");function getModelLabelColumnWidth(e,{showDefaultBadge:t=!0}={}){return e.reduce((e,n)=>Math.max(e,b_(n,t)+2),32)}__name(getModelLabelColumnWidth,"getModelLabelColumnWidth");var E_=__name(({model:e,providerId:t,isHighlighted:n,isCurrent:r,showProviderLabel:o,showDefaultBadge:s=!0,labelColumnWidth:i=32})=>{const a=Qo[t],l=o??a?.showProviderLabelInSelector??!1,c=e.vendorLabel??PD[e.provider],d=s&&e.id===TD,u="free"===e.badge,m=d?`${e.label} (default)`:e.label,p=u?" (FREE)":"",g=" ".repeat(Math.max(2,i-m.length-p.length)),h=n?KR:void 0,f=e.description?`${l?`${c} · `:""}${e.description}`:"",y=useTerminalWidth()>=i+38&&f;return st.createElement(Qe,null,st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:h,color:r?ER.GREEN:ER.WHITE,bold:r},m),u&&st.createElement(Xe,{backgroundColor:h,color:ER.GREEN,bold:!0},p),y&&st.createElement(Xe,{backgroundColor:h},g)),y&&st.createElement(Qe,{flexShrink:1},st.createElement(Xe,{backgroundColor:h,color:ER.DIM,wrap:"truncate-end"},f)),st.createElement(Xe,{backgroundColor:h,color:ER.GREEN},r?` ${gt.tick} `:" "))},"ModelRow");Gt(),SR();var T_=__name((e,t)=>`${e+1}. ${t}`,"labelText"),P_=__name(({modelLabel:e,supportedEfforts:t,currentEffort:n,onSelect:r,onCancel:o})=>{const s=dt(()=>buildEffortPickerRows(t),[t]),i=dt(()=>{if(void 0===n)return 0;const e=s.findIndex(e=>e.value===n);return e>=0?e:0},[s,n]),a=dt(()=>Math.max(...s.map((e,t)=>T_(t,e.label).length))+4,[s]),{cursor:l}=useListNavigation({items:s,onSelect:__name(e=>r(e.value),"onSelect"),onCancel:o,initialIndex:i,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,selectByNumber:!0});return st.createElement(bO,{title:`Select reasoning effort for ${e}`,hint:"↑/↓ navigate · enter to select · esc to go back"},st.createElement(Qe,{flexDirection:"column"},s.map((e,t)=>{const r=t===l,o=e.value===n;return st.createElement(Qe,{key:e.label},st.createElement(Xe,{color:r||!o?ER.WHITE:ER.GREEN,backgroundColor:r?KR:void 0,bold:r||o},T_(t,e.label).padEnd(a)),st.createElement(Xe,{color:r?ER.WHITE:ER.DIM,backgroundColor:r?KR:void 0},e.description," "),o&&st.createElement(Xe,{color:ER.GREEN}," ",gt.tick))})))},"ReasoningEffortSelector");function windowModelGroups(e){const{groups:t,firstSectionBase:n,windowStart:r,windowEnd:o}=e;let s=n;return t.flatMap(e=>{const t=sliceSectionForWindow({section:e.models,sectionBase:s,windowStart:r,windowEnd:o});return s+=e.models.length,t.rows.length>0?[{group:e,groupWindow:t}]:[]})}Gt(),SR(),__name(windowModelGroups,"windowModelGroups");var M_=__name(({onSelect:e,onCancel:t,currentModel:n,currentProvider:r,planId:o,purchasedCredits:s=0,freeCredits:i=0,refreshBanner:a,subtitle:l,skipEffortStep:c=!1,sessionId:d})=>{const[u,m]=at(""),[p,g]=at(null),[h,f]=at(()=>new Set),[y,S]=at(()=>new Set),w=r??p??uo.COMMAND,v=useCustomModelsReady(d),k=dt(()=>buildLaneModelPickerGroups(),[v]),C=dt(()=>filterModelPickerGroupsByAuth({groups:k,authResolvedProviders:y,unauthedProviders:h}),[k,y,h]),b=dt(()=>filterModelPickerGroups(C,u),[C,u]),E=dt(()=>{const e=new Set(C.map(e=>`${e.providerId}:${e.label}`));return k.filter(t=>!e.has(`${t.providerId}:${t.label}`))},[k,C]),T=dt(()=>filterModelPickerGroups(E,u),[E,u]),P=dt(()=>flattenModelPickerGroups(b),[b]),M=dt(()=>{const e=[];let t=0;for(const n of b)n.models.length>0&&e.push(t),t+=n.models.length;return e},[b]),x=dt(()=>getModelLabelColumnWidth(k.flatMap(e=>e.models)),[k]),[I,A]=at(0),R=useTerminalHeight()-1,L=Math.max(4,R-16-2*b.length),O=void 0!==o,D=dt(()=>O?null:getCachedBillingContext(),[O]),[$,N]=at(D),[_,F]=at(!O&&!D);ct(()=>{if(O)return;if($)return;let e=!0;return getBillingContext().then(t=>{e&&(N(t),F(!1))}),()=>{e=!1}},[O,$]);const U=!O&&!0===$?.fetchFailed,j=O?o:$?.planId??null,B=O?s:$?.purchasedCredits??0,W=O?i:$?.freeCredits??0,H=n?Math.max(0,P.findIndex(e=>e.model.id===n)):0,[G,V]=at("model"),[z,K]=at(null),{cursor:q,error:Y,setError:J}=useListNavigation({items:P,onSelect:__name(t=>{const n=t.model.reasoningEfforts??getSupportedEfforts(t.model.id);if(!c&&n&&n.length>0)return K(t),void V("effort");e(t.model.id,t.providerId)},"onSelect"),onCancel:t,initialIndex:H,searchQuery:u,onSearchChange:m,isActive:"model"===G,sectionStarts:M,validate:__name(e=>validateModelPickerSelection({row:e,unauthedProviders:h,accessDataLoading:_,billing:{planId:j,purchasedCredits:B,freeCredits:W},getProviderDisplayName:__name(e=>getProviderConfig(e)?.displayName,"getProviderDisplayName")}),"validate")});ct(()=>{A(e=>clampScrollOffset({cursor:q,total:P.length,maxVisible:L,currentOffset:e}))},[q,P.length,L]);const Q=lt(!1),X=__name(t=>{if(!z||Q.current)return;Q.current=!0;const{model:r,providerId:o}=z,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"),Z=__name(()=>{Q.current||(K(null),V("model"))},"handleEffortCancel");if(ct(()=>{if(_)return;if(Y!==WP)return;const e=P[q];J(e&&!U?getModelPickerAccessError({model:e.model,providerId:e.providerId,billing:{planId:j,purchasedCredits:B,freeCredits:W}}):null)},[_,U,Y,J,P,q,j,B,W]),ct(()=>{(async()=>{const e=await getConfiguredProvider();e&&e!==uo.COMMAND&&g(e)})()},[]),ct(()=>{let e=!0;return(async()=>{const t=new Set(k.map(e=>e.providerId)),n=new Set,r=new Set,o=await Promise.all([...t].map(async e=>{const t=getProviderConfig(e);if(!t?.requiresAuth)return null;if(!t.checkAuth)return{providerId:e,authed:!0};let n=!1;try{n=await t.checkAuth()}catch{n=!1}return{providerId:e,authed:n}}));for(const e of o)e&&(r.add(e.providerId),e.authed||n.add(e.providerId));e&&(S(r),f(n))})(),()=>{e=!1}},[k]),"effort"===G&&z){const e=z.model.reasoningEfforts??getSupportedEfforts(z.model.id)??[];return st.createElement(P_,{modelLabel:z.model.label,supportedEfforts:e,currentEffort:getReasoningEffort(z.model.id),onSelect:X,onCancel:Z})}const ee=I,te=I+L,ne=windowModelGroups({groups:b,firstSectionBase:0,windowStart:ee,windowEnd:te}),re=P.length>L;return st.createElement(bO,{title:"Select model",subtitle:l??"Switch between the available models. Sets the default for new sessions; other open sessions are unaffected.",footer:st.createElement(Xe,{italic:!0,color:ER.DIM},"type to search · ↑/↓ navigate · shift+↑/↓ jump provider · enter to select",u?" · esc to clear":" · esc to cancel")},st.createElement(Qe,{marginBottom:2,flexDirection:"column",width:"100%"},st.createElement(pL,{query:u,resultCount:u?P.length:void 0,placeholder:"Type to search models..."})),0===P.length?st.createElement(Qe,{marginY:1},st.createElement(Xe,{color:ER.GRAY},T.length>0?"Provider login required. Run /connect to authenticate.":`No models match "${u}"`)):st.createElement(Qe,{flexDirection:"column"},ne.map(({group:e,groupWindow:t},r)=>st.createElement(Qe,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:r>0?1:0},st.createElement(Xe,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>st.createElement(E_,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===q,isCurrent:r.id===n&&e.providerId===w,showProviderLabel:!1,labelColumnWidth:x}))))),re&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",ee+1,"–",Math.min(te,P.length)," of ",P.length,ee>0?" · ↑ more":"",te<P.length?" · ↓ more":"")),Y&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.GRAY},Y)))},"ModelSelector"),x_=__name(e=>{if(!e)return"Inherit from session";for(const t of AD)for(const n of t.models)if(n.id===e)return n.label;return e},"agentModelLabel"),I_=[{value:"inherit",label:"1. Inherit from session (default)"},{value:"pick",label:"2. Pick a specific model"}],A_=__name(({selectedModel:e,onSelect:t})=>{const[n,r]=at("choice"),[o,s]=at(e?1:0);return nt((e,n)=>{if(n.upArrow)s(e=>Math.max(0,e-1));else if(n.downArrow)s(e=>Math.min(I_.length-1,e+1));else if("1"!==e)if("2"!==e){if(n.return){const e=I_[o];if(!e)return;"inherit"===e.value?t(null):r("picker")}}else r("picker");else t(null)},{isActive:"choice"===n}),"picker"===n?st.createElement(M_,{onSelect:e=>t(e),onCancel:()=>r("choice"),currentModel:e,subtitle:"Pin a model for this agent. It will always run on this model, independent of the session's /model.",skipEffortStep:!0}):st.createElement(Qe,{flexDirection:"column"},I_.map((e,t)=>{const n=t===o;return st.createElement(Qe,{key:e.value},st.createElement(Xe,{color:n?ER.WHITE:ER.GRAY,backgroundColor:n?KR:void 0,bold:n},n?">":" "," ",e.label))}),e&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.GRAY},"Currently pinned: ",x_(e))),st.createElement(hO,{hints:["↑↓ navigate","Enter to select","Inherit follows /model; pinned agents keep their own model and prompt cache"]}))},"AgentModelSelector"),R_=__name(({config:e,onSaveComplete:t,viewOnly:n=!1})=>{const[r,o]=at("idle"),[s,i]=at(""),a=__name(async()=>{if(!e.location||!e.agentType||!e.sysPrompt)return o("error"),void i("Agent configuration is incomplete");o("saving");try{await saveAgentDefinition({runtime:createNodeRuntime(),location:e.location,name:e.agentType,description:e.ccToolDefinition,systemPrompt:e.sysPrompt,selectedTools:[...e.selectedTools],allToolNames:xS,model:e.model,reasoningEffort:e.reasoningEffort}),t(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),i(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");nt((e,t)=>{n||!t.return||"idle"!==r&&"error"!==r||a()});const l=formatAgentToolAccessForDisplay({access:[...e.selectedTools],allToolNames:xS,displayNameByToolName:RS,displayNameToToolName:LS}),c=e.location&&e.agentType?getAgentDisplayPath({location:e.location,name:e.agentType}):"";return st.createElement(Qe,{flexDirection:"column",gap:1},st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"Name:"),st.createElement(Xe,{color:ER.GRAY},e.agentType)),st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"Location:"),st.createElement(Xe,{color:ER.GRAY},c)),st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"Tools:"),st.createElement(Xe,{color:ER.GRAY},l)),st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"Model:"),st.createElement(Xe,{color:ER.GRAY},x_(e.model))),st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"Reasoning effort:"),st.createElement(Xe,{color:ER.GRAY},e.reasoningEffort??"model default"))),st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"Description"),st.createElement(Xe,{color:ER.GRAY},"(Tells ","Command Code"," when to use this agent):")),st.createElement(Xe,{color:ER.GRAY},e.ccToolDefinition),st.createElement(Qe,{gap:1},st.createElement(Xe,{color:ER.WHITE,bold:!0},"System Prompt:")),st.createElement(Xe,{color:ER.GRAY},e.sysPrompt),!n&&st.createElement(Qe,{marginTop:1},"idle"===r&&st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to save ·"," ",st.createElement(gO,null,"Esc")," to cancel"),"saving"===r&&st.createElement(Xe,{color:ER.YELLOW},"Saving agent…"),"saved"===r&&st.createElement(L$,null,s),"error"===r&&st.createElement(Qe,{flexDirection:"column"},st.createElement(R$,null,"Error: ",s),st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to retry"))))},"AgentSummary"),L_=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],O_=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=at("menu"),i=new Set(resolveAgentToolSelection({access:e.tools,allToolNames:xS,displayNameToToolName:LS})),a={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:i,model:e.model??null,reasoningEffort:e.reasoningEffort??null},l=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],c=__name(e=>{"back"!==e.value?"view"!==e.value?"edit"!==e.value?"delete"===e.value&&s("delete"):s("edit"):s("view"):t()},"handleMenuSelect"),d=__name(async r=>{if("confirm-delete"===r.value)try{await deleteAgentDefinition({runtime:createNodeRuntime(),filePath:e.filePath}),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return nt((e,n)=>{if(n.escape)return"menu"===o?void t():void s("menu");if(n.return&&"view"===o)return void s("menu");if(1!==e.length||e<"1"||e>"9")return;const r=Number(e)-1;if("menu"===o){const e=l[r];return void(e&&c(e))}if("delete"===o){const e=L_[r];e&&d(e)}}),"view"===o?st.createElement(bO,{title:e.name,gapAfterHeader:!1,footer:st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to go back")},st.createElement(R_,{config:a,onSaveComplete:()=>s("menu"),viewOnly:!0})):"edit"===o?st.createElement(bO,{title:e.name,gapAfterHeader:!1},st.createElement(Xe,{color:ER.YELLOW},"Edit functionality coming soon..."),st.createElement(pO,null,"Press ",st.createElement(gO,null,"Esc")," to go back")):"delete"===o?st.createElement(bO,{title:"Delete agent",subtitle:`Are you sure you want to delete the agent ${e.name}?`},st.createElement(Qe,null,st.createElement(SelectInput,{items:L_,onSelect:d,indicatorComponent:KN,itemComponent:zN}))):st.createElement(bO,{title:e.name,footer:st.createElement(pO,null,"Press ",st.createElement(gO,null,"↑↓")," to navigate ·"," ",st.createElement(gO,null,"Enter")," to select · ",st.createElement(gO,null,"Esc")," ","to go back")},st.createElement(SelectInput,{items:l,onSelect:c,indicatorComponent:KN,itemComponent:zN}))},"AgentDetails");Gt();var D_="https://commandcode.ai/docs/core-concepts/custom-agents",$_=__name(({onDone:e})=>(nt((t,n)=>{n.return&&e()}),st.createElement(bO,{title:"Create agents with Command Code",gapAfterHeader:!1,boxProps:{gap:1}},st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.GRAY},"Ask Command Code to create or update subagents for you, e.g."),st.createElement(Xe,{color:ER.GRAY}," ",gt.pointerSmall," “create a code-reviewer subagent that reviews diffs for bugs”"),st.createElement(Xe,{color:ER.GRAY}," ",gt.pointerSmall," “make a changelog agent that uses a fast model”")),st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.GRAY},"Or edit the files directly:"),st.createElement(Xe,{color:ER.GRAY}," • .commandcode/agents/ (this project)"),st.createElement(Xe,{color:ER.GRAY}," • ~/.commandcode/agents/ (all projects)")),st.createElement(Xe,{color:ER.GRAY},"Docs: ",D_),st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to go back and just ask"))),"AskCommandCodeGuide"),N_=__name(({handleSelect:e,createdAgentName:t})=>{const[n,r]=at([]),[o,s]=at([]),[i,a]=at([]),[l,c]=at(!0),[d,u]=at(!1),[m,p]=at(null),[g,h]=at(!1),[f,y]=at(0),[S,w]=at(0),v=useTerminalHeight();ct(()=>{__name(async()=>{c(!0),u(!1);const{personal:e,project:t}=await discoverAgents({runtime:createNodeRuntime()}),n=listDefaultAgentsForDisplay();r(e.map(e=>toDisplayAgent({definition:e,location:"personal"}))),s(t.map(e=>toDisplayAgent({definition:e,location:"project"}))),a(n),c(!1)},"loadAgents")()},[d]);const k=[{label:"1. Create agents with Command Code (recommended)",value:"ask_command_code"},{label:"2. Create manually",value:"create_new_agent"}];n.forEach(e=>{k.push({label:e.name,value:e.filePath})}),o.forEach(e=>{k.push({label:e.name,value:e.filePath})}),i.forEach(e=>{k.push({label:e.name.charAt(0).toUpperCase()+e.name.slice(1),value:e.filePath})});const C=n.length+o.length,b=(n.length>0?1:0)+(o.length>0?1:0)+(i.length>0?1:0),E=__name(e=>e<2?"action":e<2+n.length?"user":e<2+n.length+o.length?"project":"default","sectionOf"),T=v-1,P=Math.max(4,T-12-2*b),M=__name(t=>{if("ask_command_code"===t.value||"create_new_agent"===t.value)return void e(t);const r=[...n,...o,...i].find(e=>e.filePath===t.value);r&&(p(r),h(!0))},"handleAgentSelect");if(nt((e,t)=>{if(t.upArrow)y(e=>Math.max(0,e-1));else if(t.downArrow)y(e=>Math.min(k.length-1,e+1));else if(t.return){const e=k[f];e&&M(e)}},{isActive:!l&&!g}),ct(()=>{y(e=>Math.min(e,Math.max(0,k.length-1)))},[k.length]),ct(()=>{w(e=>clampScrollOffset({cursor:f,total:k.length,maxVisible:P,currentOffset:e}))},[f,k.length,P]),l)return st.createElement(A$,{label:"Loading agents"});if(g&&m){const e=isBuiltinAgentPath(m.filePath);return st.createElement(O_,{agent:m,onBack:()=>{h(!1),p(null)},setRevalidateAgent:u,isReadOnly:e})}const x=S,I=S+P,A=k.slice(x,I),R=k.length>P;let L=null;return st.createElement(bO,{title:"Agents",titleSuffix:C>0?` (${C} agent${C>1?"s":""})`:" (No custom agents)"},t&&st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{color:ER.GREEN,dimColor:!0},"Created agent: ",t)),st.createElement(Qe,{flexDirection:"column"},A.map((e,t)=>{const n=x+t,r=E(n),o="action"!==r&&r!==L;L=r;const s=n===f,i="user"===r?"User agents":"project"===r?"Project agents":"Default agents (read-only)";return st.createElement(st.Fragment,{key:e.value},o&&st.createElement(Qe,{marginTop:0===t?0:1},st.createElement(Xe,{color:$R,bold:!0},i)),st.createElement(Qe,null,st.createElement(Xe,{color:s?ER.WHITE:ER.GRAY,backgroundColor:s?KR:void 0,bold:s},s?"> ":" ",e.label," ")))})),R&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",x+1,"–",Math.min(I,k.length)," of ",k.length,x>0?" · ↑ more":"",I<k.length?" · ↓ more":"")),st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(hO,{hints:["↑↓ navigate","Enter to select","Esc to close"],marginTop:0}),st.createElement(Xe,{color:ER.DIM},"Agents live in .commandcode/agents/ (project) and ~/.commandcode/agents/ (all projects) — edit the files directly anytime."),st.createElement(Xe,{color:ER.DIM},"Docs: ",D_)))},"ManageAgents");Gt(),SR(),Gt(),Gt(),SR();var __=__name(({model:e,selectedEffort:t,onSelect:n,onBack:r})=>{const o=(e?getSupportedEfforts(e):null)??[];return st.createElement(P_,{modelLabel:x_(e),supportedEfforts:o,currentEffort:t??void 0,onSelect:e=>n(e??null),onCancel:r})},"AgentEffortSelector");Gt();var F_=[{label:"1. Project (.commandcode/agents/)",value:"project"},{label:"2. Personal (~/.commandcode/agents/)",value:"personal"}],U_=__name(({onSelect:e})=>st.createElement(SelectInput,{items:F_,onSelect:t=>{"project"!==t.value&&"personal"!==t.value||e(t.value)},indicatorComponent:jN,itemComponent:WN}),"LocationSelector");Gt(),SR();var j_=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:c})=>{const d=t?validateAgentName({name:t,displayNameByToolName:RS}):null,u=usePasteAwareChange({onChange:s}),m=usePasteAwareChange({onChange:i});return"agentType"===e?st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.WHITE},"Enter a unique identifier for your agent:"),"tool_conflict"===d?.issue&&st.createElement(Xe,{color:ER.RED},gt.warning," This name conflicts with an existing tool name. Please choose a different name."),"reserved"===d?.issue&&st.createElement(Xe,{color:ER.RED},gt.warning," This name is reserved. Reserved names: ",Vw.join(", "))),st.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{canSubmitAgentManualStep({manualStep:"agentType",config:{agentType:t,sysPrompt:n,ccToolDefinition:r}})&&a()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.WHITE},"Enter the system prompt for your agent:"),st.createElement(Xe,{color:ER.GRAY},"Be comprehensive for best results.")),st.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{canSubmitAgentManualStep({manualStep:"sysPrompt",config:{agentType:t,sysPrompt:n,ccToolDefinition:r}})&&l()},onChange:u,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.WHITE},"When should ","Command Code"," use this agent?"),st.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{canSubmitAgentManualStep({manualStep:"ccToolDefinition",config:{agentType:t,sysPrompt:n,ccToolDefinition:r}})&&c()},onChange:m,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Gt(),SR();var B_=__name((e,t)=>e?"[x]":"[ ]","categoryCheckbox"),W_=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=at(!1),[i,a]=at(0),[l,c]=at(0),d=useTerminalHeight(),u=dt(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),FS.forEach(t=>{e.push({type:"category",value:t.name})}),o?(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:"}),xS.forEach(t=>{e.push({type:"tool",value:t})}),e):(e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"}),e)},[o]),m=u.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=FS.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t)),s=r?.tools.some(t=>e.has(t));return{label:`${B_(Boolean(o),Boolean(s))} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${RS[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),p=m.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type),g=Math.max(5,d-1-10),h=p[i]?.value??0;ct(()=>{c(e=>clampScrollOffset({cursor:h,total:m.length,maxVisible:g,currentOffset:e}))},[h,m.length,g]);const f=l,y=l+g,S=m.slice(f,y),w=m.length>g;return nt((e,l)=>{if(l.upArrow)return void a(e=>{const t=e-1;return t<0?p.length-1:t});if(l.downArrow)return void a(e=>{const t=e+1;return t>=p.length?0:t});if(!l.return&&" "!==e)return;const c=p[i];if(!c)return;const d=u[c.value];if(d){if("continue"!==d.type)return"toggle"===d.type?(s(!o),void a(0)):void("category"!==d.type?"tool"===d.type&&t(d.value):n(d.value));r()}}),st.createElement(Qe,{flexDirection:"column"},S.map(e=>{const t=p.findIndex(t=>t.value===e.value),n=-1!==t&&t===i;if("divider"===e.type)return st.createElement(Qe,{key:`divider-${e.value}`},st.createElement(Xe,{color:ER.GRAY}," ",e.label));if("spacer"===e.type)return st.createElement(Qe,{key:`spacer-${e.value}`,height:1});if("label"===e.type)return st.createElement(Qe,{key:`label-${e.value}`},st.createElement(Xe,{color:ER.GRAY}," ",e.label));const r="continue"===e.type;return st.createElement(Qe,{key:`item-${e.value}`},st.createElement(Xe,{color:n?ER.WHITE:ER.GRAY,bold:r&&n},n?">":" "," ",e.label))}),w&&st.createElement(Qe,null,st.createElement(Xe,{color:ER.GRAY}," ","Showing ",f+1,"–",Math.min(y,m.length)," of"," ",m.length,f>0?" · ↑ more":"",y<m.length?" · ↓ more":"")),st.createElement(Qe,{marginTop:1},e.size===xS.length&&st.createElement(Xe,{color:ER.GRAY},"All tools selected"),e.size>0&&e.size<xS.length&&st.createElement(Xe,{color:ER.GRAY},e.size," tools selected"),0===e.size&&st.createElement(Xe,{color:ER.GRAY},"No tools selected")))},"ToolsSelector"),H_=__name(({onComplete:e})=>{const[t,n]=at(createAgentCreationState),{step:r,manualStep:o,config:s}=t,i=__name(e=>n(t=>reduceAgentCreation({state:t,event:e})),"dispatch"),a=__name(t=>{i({type:"reset"}),e(t)},"resetToDefaults"),l=__name(()=>{if("location"===r)return"Choose location";if("configuration"===r){if("agentType"===o)return"Agent type (identifier)";if("sysPrompt"===o)return"System prompt";if("ccToolDefinition"===o)return"Description (Tell Command Code when to use this agent)"}return"tools"===r?"Select tools":"model"===r?"Select model":"effort"===r?"Select reasoning effort":"summary"===r?"Confirm and save":""},"getSubText"),c=__name(e=>{i({type:"select_location",location:e}),i({type:"select_method",method:"manual"})},"handleLocationSelect");return st.createElement(bO,{title:"Create new agent",subtitle:l()},st.createElement(Qe,null,"location"===r&&st.createElement(U_,{onSelect:c}),"configuration"===r&&st.createElement(Qe,{flexDirection:"column",gap:1},st.createElement(j_,{step:o,agentType:s.agentType,sysPrompt:s.sysPrompt,ccToolDefinition:s.ccToolDefinition,onAgentTypeChange:e=>i({type:"set_agent_type",value:e}),onSysPromptChange:e=>i({type:"set_sys_prompt",value:e}),onCCToolDefinitionChange:e=>i({type:"set_cc_tool_definition",value:e}),onAgentTypeSubmit:()=>i({type:"submit_agent_type"}),onSysPromptSubmit:()=>i({type:"submit_sys_prompt"}),onCCToolDefinitionSubmit:()=>i({type:"submit_cc_tool_definition"})})),"tools"===r&&st.createElement(W_,{selectedTools:s.selectedTools,onToggleTool:e=>i({type:"toggle_tool",tool:e}),onToggleCategory:e=>i({type:"toggle_category",category:e}),onComplete:()=>i({type:"complete_tools"})}),"model"===r&&st.createElement(A_,{selectedModel:s.model,onSelect:e=>i({type:"select_model",model:e})}),"effort"===r&&st.createElement(__,{model:s.model,selectedEffort:s.reasoningEffort??null,onSelect:e=>i({type:"select_effort",effort:e}),onBack:()=>i({type:"back"})}),"summary"===r&&st.createElement(R_,{config:s,onSaveComplete:a})))},"AgentNew"),G_=__name(({onCancel:e})=>{const[t,n]=at(null),[r,o]=at(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return nt((t,n)=>{n.escape&&e()}),st.createElement(Qe,{width:"100%",flexDirection:"column"},null===t&&st.createElement(N_,{handleSelect:s,createdAgentName:r}),"ask_command_code"===t&&st.createElement($_,{onDone:e}),"create_new_agent"===t&&st.createElement(H_,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");function isToggleShortcut(e,t){return""===e||!0===t.ctrl&&"b"===e}Gt(),SR(),__name(isToggleShortcut,"isToggleShortcut");var V_=new Set;function requestBackgroundTasksExpand(){for(const e of V_)e()}function formatShellTaskCounts(e){const t=e.filter(e=>"running"===e.status),n=t.filter(e=>"shell"===e.kind).length,r=t.filter(e=>"monitor"===e.kind).length,o=[];return n>0&&o.push(`${n} shell${1===n?"":"s"}`),r>0&&o.push(`${r} monitor${1===r?"":"s"}`),o.join(", ")}function formatPanelSubtitle(e){const t=e.filter(e=>"running"===e.status);if(0===t.length)return"none running";const n=t.filter(e=>"shell"===e.kind).length,r=t.filter(e=>"monitor"===e.kind).length;return n>0&&0===r?`${n} active shell${1===n?"":"s"}`:r>0&&0===n?`${r} active monitor${1===r?"":"s"}`:formatShellTaskCounts(e)}function formatTaskRuntime(e){const t=Date.parse(e.startedAt);if(Number.isNaN(t))return;const n=e.stoppedAt?Date.parse(e.stoppedAt):Date.now();if(Number.isNaN(n))return;const r=Math.max(0,Math.floor((n-t)/1e3)),o=Math.floor(r/3600),s=Math.floor(r%3600/60),i=r%60;return o>0?`${o}h ${s}m ${i}s`:s>0?`${s}m ${i}s`:`${i}s`}function useShellTaskSnapshot(){const[e,t]=at(()=>listShellTasks({includeStopped:!0}));return ct(()=>{const e=setInterval(__name(()=>t(listShellTasks({includeStopped:!0})),"refresh"),1e3);return()=>clearInterval(e)},[]),e}__name(requestBackgroundTasksExpand,"requestBackgroundTasksExpand"),__name(formatShellTaskCounts,"formatShellTaskCounts"),__name(formatPanelSubtitle,"formatPanelSubtitle"),__name(formatTaskRuntime,"formatTaskRuntime"),__name(useShellTaskSnapshot,"useShellTaskSnapshot");var z_=getShellTaskLabel,K_=getShellTaskStatusText,q_=getVisibleShellTasks,Y_=latestShellTaskOutputLines,J_={running:ER.CYAN,completed:ER.GREEN,failed:ER.RED,"auto-stopped":ER.YELLOW,stopped:ER.GRAY};function getStatusColor(e){return J_[getShellTaskStatusTone(e)]}function TaskRow({task:e,selected:t}){const n=truncateString2({text:z_(e),maxChars:56}),r=t?KR:void 0;return st.createElement(Qe,null,st.createElement(jN,{isSelected:t,backgroundColor:r}),st.createElement(Xe,{color:t?wO:void 0,backgroundColor:r}," ",n),st.createElement(Xe,{color:ER.DIM,backgroundColor:r}," ","(",K_(e),")"))}function TaskGroup({title:e,tasks:t,selectedTaskId:n}){return 0===t.length?null:st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.DIM,bold:!0},e," (",t.length,")"),t.map(e=>st.createElement(TaskRow,{key:e.id,task:e,selected:e.id===n})))}function TaskDetailsBody({task:e,output:t}){const n=Y_(t,10),r=formatTaskRuntime(e);return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,{bold:!0},"Status: "),st.createElement(Xe,{color:getStatusColor(e)},K_(e))),void 0!==r&&st.createElement(Qe,null,st.createElement(Xe,{bold:!0},"Runtime: "),st.createElement(Xe,null,r)),st.createElement(Qe,null,st.createElement(Xe,{bold:!0},"Script: "),st.createElement(Xe,{wrap:"wrap"},e.command)),st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{bold:!0},"Output:"),st.createElement(Qe,{flexDirection:"column",borderStyle:"single",borderColor:ER.DIM,paddingX:1},n.length>0?n.map((t,n)=>st.createElement(Xe,{key:`${e.id}-${n}`},truncateString2({text:t,maxChars:100}))):st.createElement(Xe,{color:ER.DIM},"No output yet.")),st.createElement(Xe,{italic:!0,color:ER.DIM},"Showing ",n.length," line",1===n.length?"":"s")))}function BackgroundTasksPanel({onExpandedChange:e}={}){const t=useShellTaskSnapshot(),n=t.filter(e=>"running"===e.status),[r,o]=at(!1),[s,i]=at("list"),[a,l]=at(0),[c,d]=at(""),u=dt(()=>q_(t),[t]),m=u[a]??u[0];ct(()=>{e?.(r)},[r,e]),ct(()=>{const e=__name(()=>{i("list"),o(!0)},"listener");return V_.add(e),()=>{V_.delete(e)}},[]),ct(()=>{if(0===u.length)return o(!1),i("list"),void l(0);l(e=>Math.min(e,Math.max(0,u.length-1)))},[u.length]),ct(()=>{if(!r||"details"!==s||!m)return void d("");const e=readShellTaskOutputTail({taskId:m.id,maxBytes:4096});d(e?.content??"")},[r,s,m?.id,t]);const p=__name(()=>{o(!1),i("list")},"closePanel");if(nt((e,t)=>isToggleShortcut(e,t)&&(n.length>0||r)?(i("list"),void o(e=>!e)):r?"details"===s?t.leftArrow?void i("list"):t.escape||t.return||" "===e?void p():void("x"===e&&"running"===m?.status&&stopShellTaskById(m.id)):void(t.escape||t.leftArrow?p():0!==u.length&&(t.upArrow?l(e=>Math.max(0,e-1)):t.downArrow?l(e=>Math.min(u.length-1,e+1)):t.return&&m?i("details"):"x"===e&&"running"===m?.status&&stopShellTaskById(m.id))):void 0,{isActive:n.length>0||r}),!r)return null;if("details"===s&&m)return st.createElement(bO,{title:"monitor"===m.kind?"Monitor details":"Shell details",titleColor:ER.CYAN,ruleColor:ER.CYAN,subtitle:truncateString2({text:z_(m),maxChars:80}),hint:"← to go back · Esc/Enter/Space to close · x to stop",boxProps:{marginTop:1,marginBottom:1}},st.createElement(TaskDetailsBody,{task:m,output:c}));const g=u.filter(e=>"monitor"===e.kind),h=u.filter(e=>"shell"===e.kind),f=g.length>0&&h.length>0;return st.createElement(bO,{title:"Background",titleColor:ER.CYAN,ruleColor:ER.CYAN,subtitle:formatPanelSubtitle(t),hint:"↑/↓ to select · Enter to view · x to stop · ←/Esc to go back to feed",gapAfterHeader:!1,boxProps:{marginTop:1,marginBottom:1}},f?st.createElement(st.Fragment,null,st.createElement(TaskGroup,{title:"Monitors",tasks:g,selectedTaskId:m?.id}),st.createElement(TaskGroup,{title:"Shells",tasks:h,selectedTaskId:m?.id})):st.createElement(Qe,{flexDirection:"column",marginTop:1},u.map(e=>st.createElement(TaskRow,{key:e.id,task:e,selected:e.id===m?.id}))))}__name(getStatusColor,"getStatusColor"),__name(TaskRow,"TaskRow"),__name(TaskGroup,"TaskGroup"),__name(TaskDetailsBody,"TaskDetailsBody"),__name(BackgroundTasksPanel,"BackgroundTasksPanel"),Gt(),SR();var Q_=[{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."}],X_=__name(({onSelect:e,onCancel:t})=>{const[n,r]=at(null);ct(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(nt((e,n)=>{n.escape&&t()}),null===n)return null;const s=Q_.findIndex(e=>e.value===n);return st.createElement(bO,{title:"Select a compact mode to compact sessions",subtitle:"Choose how Command Code handles automatic context compaction.",footer:st.createElement(Xe,{italic:!0,color:ER.DIM},"Press ",st.createElement(Xe,{bold:!0},"Esc")," to cancel")},st.createElement(SelectInput,{items:Q_,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:KN,itemComponent:({isSelected:e,label:t})=>{const r=Q_.find(e=>e.label===t),o=r?.value===n,s=Q_.findIndex(e=>e.label===t);return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(VN,{isSelected:e,idleColor:o?ER.GREEN:ER.WHITE,bold:e||o},` ${s+1}. ${r?.label??t} `),o&&st.createElement(HN,null)),st.createElement(VN,{isSelected:e,idleColor:ER.DIM,bold:!1},` ${r?.description??""} `))}}))},"CompactModeSelector");Gt(),Gt(),SR();var Z_=["·","○","◇","☆","✧","☆","◇","○","⌘"],eF=[12,5,4,4,4,4,4,5,16],tF=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<eF.length;e++)if(n+=eF[e],t<n)return Z_[e];const r=t-58;n=0;for(let e=0;e<tF.length;e++)if(n+=tF[e],r<n)return Z_[7-e];return Z_[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=dt(()=>e.split(""),[e]),o=__name(e=>{const n=e-(t-5);return n>=0&&n<HR.length?HR[n]:GR},"getCharColor");return st.createElement(Xe,null,r.map((e,t)=>st.createElement(Xe,{key:`${t}:${e}`,color:o(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return st.createElement(Xe,{color:t??TR,bold:!0},`${getWaveSymbol(e)} `)}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var nF=formatStatusTokenCount,rF=formatElapsedMs,oF=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=at(0),[s,i]=at(n),a=lt(n);a.current=n;const l=getTerminalWidth(),[c,d]=at(()=>l>=72?"all":l>=42?"medium":"none");ct(()=>{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]),ct(()=>{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 u=r%(e.length+10),m="all"===c,p="medium"===c;return AL.statusRender({width:l,layoutMode:c,status:e,frame:r}),st.createElement(Qe,{width:l,height:1,paddingLeft:0,marginLeft:0},st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:RR.BG,color:RR.FG}," "),st.createElement(Xe,{backgroundColor:RR.BG},st.createElement(CMDIcon,{frame:4*r,color:RR.FG})),st.createElement(ShimmerText,{text:e,offset:u,bg:RR.BG}),st.createElement(Xe,{backgroundColor:RR.BG,color:RR.FG}," ")),m&&st.createElement(Qe,{columnGap:1,marginLeft:1},st.createElement(Xe,{bold:!0,color:ER.GRAY},"esc"),st.createElement(Xe,{color:ER.DIM},"to interrupt"),st.createElement(Xe,{color:ER.DIM},"•"),st.createElement(Xe,{color:ER.DIM},rF(t)),st.createElement(Xe,{color:ER.DIM},"•"),st.createElement(Xe,{color:ER.GRAY},gt.arrowDown),st.createElement(Xe,{color:ER.DIM},nF(Math.round(s)))),p&&st.createElement(Qe,{marginLeft:1},st.createElement(Xe,{color:ER.DIM},nF(Math.round(s)))))},"Status");function useExternalEditor({input:e,setInput:t,setInputKey:n,detectedContent:r,setDetectedContent:o,onEditorClose:s}){const[i,a]=at(!1),[l,c]=at(null),d=ut(async()=>{if(!i){a(!0),c(null);try{const i=resolvePastedTextTokens({input:e.replace(/\n+$/,""),detectedContent:r}),a=await openInEditor(i);t(a),o([]),n(e=>e+1),s?.()}catch(e){if(e instanceof Zf)return void c("No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/docs/core-concepts/interactive-mode#setting-up-your-editor");c(`Editor error: ${e instanceof Error?e.message:String(e)}`)}finally{a(!1)}}},[e,t,n,r,o,s,i]),u=ut(()=>{c(null)},[]);return{isEditorOpen:i,editorError:l,handleOpenInEditor:d,clearEditorError:u}}Gt(),SR(),Gt(),SR(),__name(useExternalEditor,"useExternalEditor"),Gt(),SR();var sF=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=at(null),[s,i]=at(!1),[a,l]=at({visible:!1,type:"connected"}),c=lt(null);null===c.current&&(c.current=PE({onConnectedChange:i,onContext:o,onIndicatorChange:l}));const d=c.current;ct(()=>{d.setPaused(n)},[d,n]),ct(()=>{if(t)return d.start(),()=>{d.stop()}},[t,d]);const u=aE(),m=u?RE[u]??"IDE":"IDE",p={visible:a.visible,message:"connected"===a.type?`${m} ${gt.tick}`:"run /ide",type:a.type};return{context:r,connected:s,refresh:d.refresh,connectionIndicator:p}},"useVSCodeContext");Gt(),SR();var iF=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=at(null),o=lt(!1);return ct(()=>{if(!t||o.current)return;let e=!0;return o.current=!0,detectPR().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");function pushEntry(e,t){e.push(t),e.length>50&&e.shift()}function commitBurst({stack:e,burstStart:t,inBurst:n,timer:r}){r.current&&(clearTimeout(r.current),r.current=null),n.current=!1,pushEntry(e,t)}function useUndoStack({input:e,setInput:t,initialCursorRef:n,incrementInputKey:r}){const o=lt([]),s=lt(""),i=lt(!1),a=lt(null),l=lt(!1),c=lt("");return ct(()=>{if(l.current)return l.current=!1,void(c.current=e);if(e===c.current)return;const t=c.current;return c.current=e,i.current||(s.current=t,i.current=!0),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i.current=!1,a.current=null,pushEntry(o.current,s.current)},400),()=>{a.current&&(clearTimeout(a.current),a.current=null)}},[e]),{commitUndo:__name(()=>{i.current&&commitBurst({stack:o.current,burstStart:s.current,inBurst:i,timer:a});const e=o.current.pop();void 0!==e&&(l.current=!0,t(e),n.current=e.length,r())},"commitUndo")}}function getCommandHintLayout(e){const t=getCommandMenuDescriptionWidth(e.terminalWidth);return{descriptionWidth:t,text:truncateString2({text:e.text,maxChars:t})}}function getModelHintText(e){return formatCurrentModelHint({modelId:e,findModelById:findModelById})}Gt(),__name(pushEntry,"pushEntry"),__name(commitBurst,"commitBurst"),__name(useUndoStack,"useUndoStack"),Gt(),SR(),__name(getCommandHintLayout,"getCommandHintLayout"),__name(getModelHintText,"getModelHintText"),Gt(),SR();var aF=createNodeRuntime(),lF=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=at(()=>process.cwd()),[i,a]=at([]),[l,c]=at(0),[d,u]=at(0),m=n.trim()?15:10;ct(()=>{invalidateFileIndex()},[]),ct(()=>{let e=!1;return __name(async()=>{if(n.trim()){const t=await searchFiles({runtime:aF,searchTerm:n,basePath:process.cwd()});if(e)return;return a(t),c(0),void u(0)}try{const t=await browseDirectory({runtime:aF,dirPath:r,basePath:process.cwd()});if(e)return;a(t),c(0),u(0)}catch{}},"run")(),()=>{e=!0}},[r,n]),nt((r,a)=>{if(a.escape)t();else if(a.upArrow)c(e=>{const t=Math.max(0,e-1);return t<d&&u(t),t});else if(a.downArrow)c(e=>{const t=Math.min(i.length-1,e+1);return t>=d+m&&u(t-m+1),t});else{if(a.rightArrow){const e=i[l];if(!e)return;return void(e.isDirectory&&!n.trim()&&o(s(e.path)))}if(a.return){const t=i[l];if(!t)return;return void e(t.path)}}});const p=i.slice(d,d+m);return st.createElement(Qe,{flexDirection:"column",paddingLeft:1},st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},n.trim()?`Searching for: "${n}"`:`Files: ${r}`)),0===p.length?st.createElement(D$,{message:n.trim()?`No files found matching "${n}"`:"No files found in this directory"}):p.map((e,t)=>{const n=d+t,r=e.name,o=n===l;return st.createElement(Xe,{key:e.path,color:o?wO:ER.DIM,bold:o&&isLightTheme()},e.isDirectory?`${r}/`:r)}),st.createElement(hO,{hints:["↑↓ navigate",!n.trim()&&"→ to open folder","Enter to select","Esc to close"]}))},"FileList");Gt(),SR();var cF=__name(()=>st.createElement(Qe,{paddingRight:3},st.createElement(Xe,{color:ER.DIM,wrap:"truncate"},gt.pointerSmall," ","stashed")),"StashBadge"),dF=__name(({hint:e})=>st.createElement(Qe,{paddingRight:1},st.createElement(Xe,{color:ER.DIM,wrap:"truncate"},e)),"PasteKeyHint"),uF=__name(({tasteLearningOn:e,byokSession:t,showSeparator:n=!0})=>{if(null==e)return null;const r=e&&t;return st.createElement(st.Fragment,null,n&&st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:e&&!r?PR.TEXT:ER.DIM},r?"taste off (byok)":"taste "+(e?"on":"off")))},"TasteStateBadge");function useBackgroundTasksSummary(){const[e,t]=at(()=>formatShellTaskCounts(listShellTasks({includeStopped:!1})));return ct(()=>{const e=setInterval(__name(()=>t(formatShellTaskCounts(listShellTasks({includeStopped:!1}))),"refresh"),1e3);return()=>clearInterval(e)},[]),e}__name(useBackgroundTasksSummary,"useBackgroundTasksSummary");var mF=__name(({showSeparator:e=!0,armed:t=!1})=>{const n=useBackgroundTasksSummary();return n?st.createElement(st.Fragment,null,e&&st.createElement(Xe,{color:ER.DIM}," · "),t?st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.CYAN,inverse:!0},` ${n} `),st.createElement(Xe,{color:ER.DIM}," · Enter to open")):st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.CYAN},n),st.createElement(Xe,{color:ER.DIM}," · ↓ to manage"))):null},"BackgroundTasksBadge"),pF=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?st.createElement(st.Fragment,null,t&&st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:"connected"===e.type?ER.GREEN:ER.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),gF=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="default",prInfo:o,contextUsage:s,connectionIndicator:i,pendingExitKey:a,updateStatus:l,updateFailedInfo:c,currentProvider:d,showProviderInfo:u,isBashMode:m,shareInfo:p,showShareNotification:g,unshareNotificationMessage:h,tasteNotificationMessage:f,creditWarning:y,hasStashedPrompt:S,tasteLearningOn:w,byokSession:v,backgroundTasksArmed:k,pasteKeyHint:C})=>{const b=e>=60,E=C&&e>=90?C:null;return st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r&&"bypass"!==r&&"dont-ask"!==r||a?st.createElement(Qe,{flexDirection:"row",justifyContent:"space-between",width:e-1},st.createElement(Qe,{flexDirection:"row",columnGap:0},n&&!a?st.createElement(Xe,{color:DR},t):st.createElement(lL,{mode:r,pendingExitKey:a}),!a&&st.createElement(dL,{prInfo:o}),!a&&st.createElement(pF,{indicator:i}),!a&&b&&st.createElement(uF,{tasteLearningOn:w,byokSession:v}),!a&&st.createElement(mF,{armed:k})),(b||S||E)&&st.createElement(Qe,{flexDirection:"column",alignItems:"flex-end"},!S&&E&&st.createElement(dF,{hint:E}),S?st.createElement(cF,null):null,!S&&b&&s&&st.createElement(XR,{usage:s}))):st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"row",justifyContent:"space-between",width:e-1},st.createElement(lL,{mode:r}),S&&st.createElement(cF,null),!S&&E&&st.createElement(dF,{hint:E})),st.createElement(Qe,{flexDirection:"row",justifyContent:"space-between",width:e-1},st.createElement(Qe,{flexDirection:"row",columnGap:0},st.createElement(Xe,{color:n?DR:ER.DIM},t),st.createElement(dL,{prInfo:o}),st.createElement(pF,{indicator:i}),b&&st.createElement(uF,{tasteLearningOn:w,byokSession:v}),st.createElement(mF,{armed:k})),st.createElement(Qe,{flexDirection:"row",columnGap:2},b&&s&&st.createElement(XR,{usage:s})))),(l||c||u&&d)&&st.createElement(Qe,{flexDirection:"row",columnGap:1},l&&st.createElement(Xe,null,gt.tick," ","Command Code"," updated:"," ",st.createElement(Xe,{color:ER.DIM},"v",l.updatedFrom),st.createElement(Xe,{color:ER.DIM}," ",gt.arrowRight," "),st.createElement(Xe,null,"v",l.updatedTo)),!l&&c&&st.createElement(Xe,{color:ER.YELLOW,dimColor:!0},gt.info," Update available:"," ",c.currentVersion," ",gt.arrowRight," ",c.latestVersion),u&&d&&st.createElement(Xe,{color:ER.GREEN,dimColor:!0},gt.bullet," Provider:"," ",getProviderDisplayName(d)))),m&&st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,{color:ER.GREEN},"! for bash mode")),g&&p&&st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,{color:TR},"SHARED: ",p.url," (copied to clipboard)")),h&&st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,{color:h.includes("NOT SHARED")?ER.RED:TR},h)),f&&st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,{color:TR},f)),y&&st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,{color:ER.YELLOW},gt.warning," ",y)))},"BottomIndicator");function useClipboardPasteKey(e){const{latestInputRef:t,cursorPositionRef:n,detectedImagesRef:r,setDetectedImages:o,setInput:s,incrementInputKey:i,setInitialCursor:a,handlePaste:l,onTextPasted:c,showClipboardNotice:d,clearClipboardNotice:u,showPasteKeyHint:m}=e,p=ut(e=>{const l=nextImagePasteNumber(r.current),{text:c,cursor:d}=insertTextAt(t.current,n.current,imagePasteToken(l)),u=[...r.current,{imageNumber:l,image:e}];r.current=u,o(u),s(c),t.current=c,n.current=d,a(d),i()},[n,r,i,t,o,a,s]),g=ut(async e=>{const r=stripEmbeddedPasteEndMarker(e),o=t.current,s=n.current,i=o.slice(0,s),a=o.slice(s);await l(`${i}[200~${r}[201~${a}`)&&c()},[n,l,t,c]);return ut(async()=>{const e=setTimeout(()=>{d("Reading clipboard…",{sticky:!0})},150);try{const t=await probeClipboardImage();if(t.image)return p(t.image),clearTimeout(e),void u();const n=t.text??await detectClipboardText();if(clearTimeout(e),n)return u(),void await g(n);d(describeClipboardImageMiss({environment:t.environment,attempted:t.attempted})),m()}catch{clearTimeout(e),u()}},[u,p,g,d,m])}Gt(),SR(),__name(useClipboardPasteKey,"useClipboardPasteKey");var hF=["","","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function buildFileMentionInput(e){const{currentInput:t,mentionPath:n,isSearchMode:r}=e;if(!r)return`${t}${n} `;const o=t.lastIndexOf("@");return-1===o?`${n} `:`${t.substring(0,o+1)}${n} `}__name(removeAltPCharacter,"removeAltPCharacter"),__name(buildFileMentionInput,"buildFileMentionInput");var fF=__name(({pasteKeyAdvice:e})=>st.createElement(Qe,{flexDirection:"column",paddingLeft:1},st.createElement(Xe,{color:ER.DIM,bold:!0},"Available Shortcuts:"),st.createElement(Qe,{columnGap:4},st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},"! for bash mode"),st.createElement(Xe,{color:ER.DIM},"/ for commands"),st.createElement(Xe,{color:ER.DIM},"@ for file paths"),st.createElement(Xe,{color:ER.DIM},getModeToggleShortcutHint()," to toggle accept edits")),st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},"double tap esc to clear input"),st.createElement(Xe,{color:ER.DIM},getNewlineShortcutHint()," for newline"),st.createElement(Xe,{color:ER.DIM},"ctrl + g to open in editor"),st.createElement(Xe,{color:ER.DIM},"ctrl + z to undo"),st.createElement(Xe,{color:ER.DIM},"ctrl + s to stash prompt"),st.createElement(Xe,{color:ER.DIM},spacedKey(e.key)," to paste image"),e.textOnlyKey&&st.createElement(Xe,{color:ER.DIM},spacedKey(e.textOnlyKey)," pastes text only in ",e.terminal)))),"ShortcutMenu");function spacedKey(e){return e.split("+").join(" + ")}function currentPasteKeyAdvice(){return pasteImageKeyAdvice({terminal:detectTerminal({env:process.env}),environment:currentClipboardEnvironment()})}__name(spacedKey,"spacedKey"),__name(currentPasteKeyAdvice,"currentPasteKeyAdvice");var yF=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:s,setShowFileList:a,fileSearchQuery:l,setFileSearchQuery:c,onCommand:d,contextUsage:u,tasteLearningOn:m,tasteUsage:p=!1,shareInfo:g,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,creditWarning:S,updateStatus:w,updateFailedInfo:v,currentProvider:k,currentModel:C,showProviderInfo:b,permissionMode:E="default",onToggleAutoAccept:T,hintMessage:P,historyManager:M,pendingExitKey:x=null,onOverlayVisibilityChange:I,onDoubleEscapeEmpty:A,onAltP:R,isProcessing:L=!1,ideContextEnabled:O=!0,footer:D})=>{const[$,N]=at(0),[_,F]=at(!1),[U,j]=at(!1),[B,W]=at(!1),[H,G]=at(""),[V,z]=at(null),K=lt(0),q=lt(0),[Y,J]=at([]),[Q,X]=at([]),[Z,ee]=at(null),[te,ne]=at(null),re=lt(null),oe=ut(()=>{re.current&&(clearTimeout(re.current),re.current=null),ne(null)},[]),se=ut((e,t)=>{re.current&&(clearTimeout(re.current),re.current=null),ne(e),t?.sticky||(re.current=setTimeout(()=>{re.current=null,ne(null)},5e3))},[]);ct(()=>()=>{re.current&&clearTimeout(re.current)},[]);const ie=dt(currentPasteKeyAdvice,[]),ae=dt(()=>formatPasteImageKeyHint(ie),[ie]),[le,ce]=at(()=>ae?Date.now():null);ct(()=>{if(null===le)return;const e=setTimeout(()=>{ce(null)},2e4);return()=>clearTimeout(e)},[le]);const de=ut(()=>{ae&&ce(Date.now())},[ae]),ue=lt(!1),me=lt(!1),[pe,ge]=at(!1),he=lt(!1),fe=ut(e=>{he.current=e,ge(e)},[]),ye=lt(!1),Se=lt(void 0),[we,ve]=at(-1),[ke,Ce]=at(""),be=lt(0),Ee=lt(e);Ee.current=e;const Te=lt(Q);Te.current=Q;const{commitUndo:Pe}=useUndoStack({input:e,setInput:n,initialCursorRef:Se,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey")}),{isEditorOpen:Me,editorError:xe,handleOpenInEditor:Ie,clearEditorError:Ae}=useExternalEditor({input:e,setInput:n,setInputKey:N,detectedContent:Y,setDetectedContent:J,onEditorClose:__name(()=>{ue.current=!1},"onEditorClose")}),Re=dt(()=>shouldCollapsePastedText(),[]),{handlePaste:Le,resetPasteState:Oe,isPasting:De}=useBracketedPaste({input:e,setInput:n,setDetectedImages:X,setDetectedContent:J,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{Se.current=e},"setInitialCursor"),collapsePastedText:Re,nextImageNumber:nextImagePasteNumber(Q),onPasteMiss:__name(e=>{se(describeClipboardImageMiss({environment:e.environment,attempted:e.attempted})),de()},"onPasteMiss")}),$e=useClipboardPasteKey({latestInputRef:Ee,cursorPositionRef:be,detectedImagesRef:Te,setDetectedImages:X,setInput:n,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{Se.current=e},"setInitialCursor"),handlePaste:Le,onTextPasted:__name(()=>{ye.current=!0},"onTextPasted"),showClipboardNotice:se,clearClipboardNotice:oe,showPasteKeyHint:de}),Ne=lt(()=>{});Ne.current=t=>{Me||(async()=>{const n=be.current,r=e.slice(0,n),o=e.slice(n),s=stripEmbeddedPasteEndMarker(t);await Le(`${r}[200~${s}[201~${o}`)&&(ye.current=!0)})()},ct(()=>registerPasteConsumer(e=>Ne.current(e)),[]);const _e=lt(new Map),Fe=dt(()=>{const e=_e.current,t=new Map,n=new Map;for(const r of Q){const o=e.has(r)?e.get(r)??null:saveTempImage(r.image,r.imageNumber);t.set(r,o),n.set(r.imageNumber,o)}return _e.current=t,n},[Q]),{skills:Ue,customMenuItems:je}=useSlashMenuData(),Be=dt(()=>{const e=resolveSlashMenuItems({searchQuery:"",customMenuItems:je,skills:Ue,showProviderCommand:!0,showTerminalSetupCommand:isVSCodeTerminal2()});return new Set([...e.map(e=>e.command),...Ue.map(e=>buildSkillNamespacedCommand(e.name))])},[Ue,je]),We=ut(e=>Be.has(e),[Be]),{context:He,connected:Ge,refresh:Ve,connectionIndicator:ze}=sF({enabled:O,paused:L}),{stdout:Ke}=et(),qe=Ke?.columns??80,{pr:Ye}=iF();ct(()=>{const e=s||B;I?.(e)},[s,B,I]),ct(()=>{if(!ye.current)return;ye.current=!1;const t=Ty(e);!B&&t.showCommandMenu||(W(t.showCommandMenu),G(t.showCommandMenu?t.commandSearchQuery:""))},[e,B]);const Je=ut(()=>{X([])},[]),Ze=ut(()=>{W(!1),z(null)},[]),tt=ut(()=>{Ze(),G(""),a(!1),c(""),ve(-1),Ce(""),Se.current=void 0,N(e=>e+1)},[Ze,c,a]),rt=ut(t=>!(null===Z||!t?.replaceCurrentInput&&e.trim().length>0||(ue.current=!0,n(Z),ee(null),tt(),setTimeout(()=>{ue.current=!1},0),0)),[e,tt,n,Z]),ot=ut(()=>{n(""),j(!1),Ze(),G(""),J([]),Je(),Oe(),ve(-1),Ce(""),N(e=>e+1)},[n,Oe,Je,Ze]),it=ut(e=>{ue.current=!0,n(e.text),Se.current=e.cursor,N(e=>e+1),setTimeout(()=>{ue.current=!1},0)},[n]),mt=ut(()=>{it(insertTextAt(e,be.current,"\n"))},[e,it]);nt(async(t,r)=>{if(he.current&&!r.downArrow&&!r.return&&"\r"!==t&&(fe(!1),r.upArrow))return;if(r.upArrow){if(s||B)return;const t=e.indexOf("\n"),r=-1===t||be.current<=t;if(0!==e.length&&-1===we&&!r)return;const o=M?.count()??0;if(0===o)return;-1===we&&Ce(e);const i=Math.min(we+1,o-1);return void(i!==we&&(ve(i),n(M?.getAt(i)||""),N(e=>e+1)))}if(r.downArrow){if(s||B)return;if(-1===we){const t=e.lastIndexOf("\n"),n=-1===t||be.current>t;return void((0===e.length||n)&&listShellTasks().some(e=>"running"===e.status)&&fe(!0))}const t=e.lastIndexOf("\n");if(!(-1===t||be.current>t))return;const r=we-1;return ve(r),n(-1===r?ke:M?.getAt(r)||""),void N(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void Je();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return ue.current=!0,void Ie();if(isCtrlKey({inputChar:t,key:r,letter:"s",ctrlCode:19})){const t=e.trim().length>0;if(!t&&null===Z)return;if(!t&&rt())return;ue.current=!0;const r=Z??"";return ee(t?e:null),n(r),tt(),void setTimeout(()=>{ue.current=!1},0)}if(getIsExpandToolShortcut(r,t))return ue.current=!0,n(e),N(e=>e+1),void setTimeout(()=>{ue.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:De()}))return me.current=!0,mt(),void setTimeout(()=>{me.current=!1},0);if(r.meta&&"w"===t)return ue.current=!0,void ot();const o=r.ctrl&&"v"===t.toLowerCase()||hF.includes(t),i=r.meta&&"v"===t.toLowerCase();if(o||i){if(Me)return;return ue.current=!0,setTimeout(()=>{ue.current=!1},0),void await $e()}if(!r.ctrl&&!r.meta||"u"!==t)if(r.ctrl&&"z"===t?.toLowerCase())Pe();else{if(r.escape){if(B)return;const t=Date.now();return t-K.current<500?(e.length>0?ot():A?.(),K.current=0,q.current=0,F(!1),void j(!1)):(K.current=t,_||U||(q.current=t),F(!1),void j(!1))}if(_&&(r.backspace||r.delete)&&0===e.length)F(!1);else if(r.return&&!r.shift&&!r.ctrl&&!r.meta){if(he.current&&(fe(!1),listShellTasks().some(e=>"running"===e.status)))return void requestBackgroundTasksExpand();if(me.current)return void(me.current=!1);if(Date.now()-q.current<100)return q.current=0,void mt();if(s)return;if(B)return;if(Me)return;const e=applyBackslashNewline(Ee.current,be.current);return e?void it(e):void await ht(Ee.current)}}});const pt=ut(async t=>{if(Me)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void R?.();const o=processBracketedPaste(t),i=findInsertion({before:e,after:t}),d=null!==i&&looksLikeDroppedImagePath(i.text);if((o.isPasteStart||o.isPasteEnd||d||De())&&await Le(t))return void(ye.current=!0);if(ue.current)return void(ue.current=!1);-1!==we&&ve(-1),X(e=>{if(0===e.length)return e;const n=prunePastedImages({input:t,images:e});return n===e?e:[...n]});const u=1===t.length,m=t.slice(-1);if(u){if("?"===m&&!_)return F(!0),n(""),void N(e=>e+1);if("!"===m&&!U)return F(!1),j(!0),n(""),void N(e=>e+1)}const p=Ty(t),g=t.length<e.length&&!e.startsWith(t),h=!g&&t.length<e.length,f=t.length===e.length+1||h,y=Py({canOpenMenu:f,deletedFromMiddle:g,menuState:p,showCommandMenu:B});B===y&&H===p.commandSearchQuery||(W(y),G(y?p.commandSearchQuery:""));const S=reduceFileMentionInput({prevInput:e,nextInput:t,state:{showFileList:s,query:l}});S.showFileList!==s&&a(S.showFileList),S.query!==l&&c(S.query),_&&(t!==e||t.length<e.length)&&F(!1),xe&&Ae(),0===t.length&&(j(!1),Ze(),G(""),J([]),c(""),Oe()),n(t)},[_,e,n,s,a,l,c,B,H,U,we,Le,Oe,De,R,xe,Ae,Me,Ze]),ht=ut(async(r=e)=>{if(Ve(),q.current=0,_)return void F(!1);const o=r.trim(),s=!U&&o.startsWith("/");let i=o;!U&&Y.length>0&&(i=resolvePastedTextTokens({input:i,detectedContent:Y}));const a=U?[]:resolvePastedImageTokens({input:o,images:Q}),l={};if(!U)for(const e of Q){if(!o.includes(imagePasteToken(e.imageNumber)))continue;const t=Fe.get(e.imageNumber);t&&(l[e.imageNumber]=t)}const c=Object.keys(l).length>0,u=He?wE(He):void 0;if(s&&d&&(n(""),"handled"===(await d(i,a,u)).status))return M?.add(i),j(!1),Ze(),G(""),Je(),J([]),ve(-1),Ce(""),void rt({replaceCurrentInput:!0});ve(-1),Ce(""),i.length>0&&M?.add(i);const m=buildIdeContextHint({ideContext:He});t({input:i,role:U?"bash":"user",images:a,ideContext:u,ideHint:m,imageTokenPaths:c?l:void 0}),j(!1),Ze(),G(""),Je(),J([]),rt({replaceCurrentInput:!0})},[t,d,_,e,U,Q,Fe,Y,M,Ve,He,Je,Ze,rt,n]),ft=ut(t=>{const r=i(process.cwd(),t),o=r.includes(" ")?`"${r}"`:r,d=buildFileMentionInput({currentInput:e,mentionPath:o,isSearchMode:s&&""!==l});n(d),a(!1),c(""),N(e=>e+1)},[n,a,e,s,l,c]),yt=ut(()=>{a(!1),c("")},[a,c]),St=ut(e=>{const t=vy.has(e),r="/design"===e.trimEnd();if(t||r){const t=e.trimEnd();return n(t+" "),G(t.substring(1)+" "),void N(e=>e+1)}Ze(),G(""),n(e+" "),N(e=>e+1)},[n,Ze]),wt=ut(t=>{if("/design help"===t)return Ze(),G(""),n(""),N(e=>e+1),M?.add(t),void d?.("/design help");if(wy.has(t))return Ze(),G(""),M?.add(t),ve(-1),Ce(""),n(""),N(e=>e+1),void d?.(t);const r=vy.has(t),o=Ni.has(t),s=_i.has(t);if(r)St(t);else{if(Ze(),G(""),!o&&!s&&e!==t)return n(t+" "),void N(e=>e+1);M?.add(t),ve(-1),Ce(""),n(""),N(e=>e+1),d?.(t)}},[d,n,e,M,St,Ze]),vt=ut(()=>{Ze(),G(""),ve(-1),Ce(""),N(e=>e+1)},[Ze]),kt=ut(e=>{be.current=e,Se.current=void 0},[]),Ct=dt(()=>formatSlashCommandInputHint({value:e,selectedCommand:B?V:null}),[e,B,V]),bt=Boolean(Ct)&&!x,Et=dt(()=>{const t=Ye&&("OPEN"===Ye.state||"MERGED"===Ye.state);return"auto-accept"===E||"plan"===E||"bypass"===E||"dont-ask"===E||Ge||t?!_:!_&&0===e.length&&!U},[_,e,U,E,Ge,Ye]),Tt=null!==Z,Pt=__name(()=>_||s||B?0:bt||Et||x||U?3:4,"getBottomMargin");return st.createElement(Qe,{width:"100%",flexDirection:"column",marginBottom:Pt()},st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(Xe,{color:U?ER.GREEN:ER.GRAY},gt.line.repeat(qe)),(()=>{const t=__name(t=>st.createElement(TextInput,{key:$,value:e,placeholder:Me?"Save and close the editor to continue...":o,onChange:pt,showCursor:!Me&&r,onCursorChange:kt,initialCursor:Se.current,prefix:`${U?"!":gt.pointer} `,prefixColor:U?ER.GREEN:ER.WHITE,singleLine:t?.singleLine,maxWidth:t?.maxWidth,imageTokenLinks:Fe,isRecognizedSlashCommand:We,disablePasteRouting:!0}),"renderTextInput"),n=B?"/model"===V&&C?getModelHintText(C):Ct:null,s=n?getCommandHintLayout({text:n,terminalWidth:qe}):null;return s?st.createElement(Qe,{flexDirection:"row",width:"100%"},st.createElement(Qe,{width:25},t({singleLine:!0,maxWidth:25})),st.createElement(Qe,{width:s.descriptionWidth},st.createElement(Xe,{color:ER.DIM,wrap:"truncate"},s.text))):t()})(),st.createElement(Xe,{color:U?ER.GREEN:ER.GRAY},gt.line.repeat(qe))),_&&st.createElement(fF,{pasteKeyAdvice:ie}),s&&st.createElement(lF,{onSelectFile:ft,onClose:yt,searchQuery:l}),B&&st.createElement(JR,{onSelectCommand:wt,onInsertCommand:St,onSubmitSearch:ht,onClose:vt,searchQuery:H,onSelectedCommandChange:z}),!B&&!s&&bt&&st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM,wrap:"truncate"},Ct)),!B&&!s&&!bt&&(Et||x||Tt)&&st.createElement(gF,{termWidth:qe,indicatorText:getIdeInputIndicatorText(Ge,He,qe),isIDEIndicator:hasIdeInputIndicatorContext(Ge,He),permissionMode:E,prInfo:Ye,contextUsage:u,tasteLearningOn:m,byokSession:isByok({model:C??""}),connectionIndicator:ze,pendingExitKey:x,updateStatus:w,updateFailedInfo:v,currentProvider:k,showProviderInfo:b,isBashMode:U,shareInfo:g,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,creditWarning:S,hasStashedPrompt:Tt,backgroundTasksArmed:pe,pasteKeyHint:null!==le&&0===Q.length?ae:null}),xe&&st.createElement(Qe,{paddingLeft:1,flexDirection:"column"},st.createElement(Xe,{color:ER.YELLOW},xe)),!xe&&te&&st.createElement(Qe,{paddingLeft:1},st.createElement(Xe,{color:ER.DIM,wrap:"truncate"},te)),D)},"InputBox");Gt(),SR();var SF=__name(()=>{const[e,t]=at([]);return ct(()=>subscribeModStatus(t),[]),0===e.length?null:st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,{wrap:"truncate"},e.map(e=>e.text).join(" ")))},"ModStatusLine");Gt(),SR();var wF=__name(({messages:e})=>{const t=countVisibleQueuedMessages(e);if(0===t)return null;const n=getQueuedDisplayRows(e);return st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Qe,{marginBottom:0},st.createElement(Xe,{color:xR,inverse:!0},` Queued (${t}) `)),n.map(e=>st.createElement(Qe,{key:e.text},st.createElement(Xe,{color:ER.DIM},gt.pointerSmall," "),st.createElement(Xe,{color:ER.DIM},truncateString2({text:e.count>1?`${e.text} (${e.count})`:e.text,maxChars:80})))))},"QueuedMessages");function useWorkedDuration(e,t){const n=lt(null),[r,o]=at(null);return ct(()=>{n.current=null,o(null)},[t]),ct(()=>{if(e)return n.current??=Date.now(),void o(null);null!==n.current&&(o(Date.now()-n.current),n.current=null)},[e]),r}function WorkedDurationNote({durationMs:e}){return null===e||e<1e3?null:st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},`✻ Worked for ${formatElapsedMs(e)}`))}Gt(),SR(),__name(useWorkedDuration,"useWorkedDuration"),__name(WorkedDurationNote,"WorkedDurationNote");var vF=st.memo(({queuedMessages:e,isProcessing:t,processingStartedAt:n=null,executionState:r,status:o,input:s,setInput:i,onSubmit:a,showFileList:l,setShowFileList:c,fileSearchQuery:d,setFileSearchQuery:u,onCommand:m,outputTokens:p=0,contextUsage:g,tasteLearningOn:h,tasteUsage:f,shareInfo:y,showShareNotification:S,unshareNotificationMessage:w,tasteNotificationMessage:v,updateStatus:k,updateFailedInfo:C,creditWarning:b,currentProvider:E,currentModel:T,showProviderInfo:P,permissionMode:M,onToggleAutoAccept:x,hintMessage:I,historyManager:A,pendingExitKey:R,onResetPendingExitKey:L,onDoubleEscapeEmpty:O,retryAttempt:D,onAltP:$,inputActive:N=!0,inactiveHint:_,sessionId:F})=>{const[U,j]=at(()=>null===n?0:Date.now()-n),B=lt(s),W=t||r.isExecuting,H=useWorkedDuration(W,F);return ct(()=>{R&&s!==B.current&&s.length>0&&L?.(),B.current=s},[s,R,L]),ct(()=>{if(!t||null===n)return void j(0);j(Date.now()-n);const e=setInterval(()=>{j(Date.now()-n)},1e3);return()=>{clearInterval(e)}},[t,n]),st.createElement(Qe,{flexDirection:"column"},st.createElement(wF,{messages:e}),st.createElement(Qe,{flexDirection:"row",justifyContent:"space-between"},st.createElement(Qe,{flexDirection:"column"},W&&null===D&&st.createElement(oF,{tokens:p,timeElapsed:U,status:r.isExecuting?`Executing: ${r.currentCommand}`:o}),!W&&st.createElement(WorkedDurationNote,{durationMs:H}),W&&null===D&&I&&st.createElement(Qe,{marginLeft:1},st.createElement(Xe,{color:ER.DIM}," ","⎿"," ","Tip: ",I)))),N?st.createElement(yF,{input:s,setInput:i,onSubmit:a,placeholder:"Ask your question...",showFileList:l,setShowFileList:c,fileSearchQuery:d,setFileSearchQuery:u,onCommand:m,contextUsage:g,tasteLearningOn:h,tasteUsage:f,shareInfo:y,showShareNotification:S,unshareNotificationMessage:w,tasteNotificationMessage:v,updateStatus:k,updateFailedInfo:C,creditWarning:b,currentProvider:E,currentModel:T,showProviderInfo:P,permissionMode:M,onToggleAutoAccept:x,hintMessage:I,historyManager:A,pendingExitKey:!R||t||r.isExecuting?null:R,onDoubleEscapeEmpty:O,onAltP:$,isProcessing:t,footer:st.createElement(SF,null)}):st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{marginLeft:1},st.createElement(pO,null,_??"Background focused · ↑/↓ to select · Enter to view · x to stop · ←/Esc to go back to feed")),st.createElement(SF,null)))});Gt();var kF=__name(({onComplete:e,onCancel:t})=>{const{authState:n,statusMessage:r,browserUrl:o,apiKeyInput:s,setApiKeyInput:i,handleApiKeySubmit:a,cancel:l}=useAuthFlow({onSuccess:__name((t,n)=>{const r=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";e(!0,r?`Logged in as ${r}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return nt((e,t)=>{t.ctrl&&"c"===e&&l()}),st.createElement(TO,{authState:n,statusMessage:r,browserUrl:o,apiKeyInput:s,setApiKeyInput:i,handleApiKeySubmit:a})},"LoginOverlay");function getStatusTextColor(e){return"connected"===e?ER.GREEN:"connecting"===e||"authenticated"===e?ER.CYAN:"requires_auth"===e?ER.YELLOW:ER.GRAY}Gt(),SR(),__name(getStatusTextColor,"getStatusTextColor");var CF=__name((e,t)=>{const n=__name((e,n)=>st.createElement(Xe,{color:e,backgroundColor:t},n),"icon");return"connected"===e?n(ER.GREEN,gt.tick):"connecting"===e?n(ER.CYAN,gt.circle):"authenticated"===e?n(ER.CYAN,gt.tick):"requires_auth"===e?n(ER.YELLOW,gt.warning):"error"===e?n(ER.RED,gt.cross):n(ER.GRAY,gt.circle)},"getStatusIcon"),bF=__name(({onClose:e,mcp:t})=>{const[n,r]=at([]),[o,s]=at(!0),[i,a]=at(0),[l,c]=at("list"),[d,u]=at(null),[m,p]=at(0),g=useTerminalHeight(),h=ut(async()=>{try{const e=await listMcpServers(),n=t?mcpManagerConnectionsFromRegistry(t):mcpManagerConnectionsFromPool(getConnectedMcpServers()),o=await buildMcpManagerServerInfos({configuredServers:e,connectedServers:n,hasTokens:hasTokens});r([...o])}catch{}finally{s(!1)}},[t]);ct(()=>{h()},[h]),ct(()=>{if(t)return t.onChange(()=>{h()})},[t,h]);const f=dt(()=>[...orderMcpManagerServers(n)],[n]),y=f[i]??null,S=g-1,w=dt(()=>new Set(f.map(e=>e.scope)).size,[f]),v=Math.max(4,S-8-2*w);ct(()=>{p(e=>clampScrollOffset({cursor:i,total:f.length,maxVisible:v,currentOffset:e}))},[i,f.length,v]),nt((t,n)=>{if(n.ctrl&&"c"===t)e();else{if(n.escape)return"actions"===l||"confirm-remove"===l?(c("list"),void u(null)):void e();if("list"===l){if(n.upArrow&&(a(e=>Math.max(0,e-1)),u(null)),n.downArrow){if(0===f.length)return;const e=Math.max(0,f.length-1);a(t=>Math.min(e,t+1)),u(null)}n.return&&y&&(c("actions"),u(null))}}});const k=__name(async e=>{if(y)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{u({text:`Enabling ${y.name}...`,color:ER.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:y.name,enabled:!0,scope:y.scope}))return void u({text:`${gt.cross} Failed to enable ${y.name}, server may no longer exist in ${y.scope} scope`,color:ER.YELLOW});await h(),u({text:`${gt.tick} Enabled ${y.name}`,color:ER.GREEN})}catch(e){u({text:`${gt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ER.RED})}}else{u({text:`Disabling ${y.name}...`,color:ER.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:y.name,enabled:!1,scope:y.scope}))return void u({text:`${gt.cross} Failed to disable ${y.name}, server may no longer exist in ${y.scope} scope`,color:ER.YELLOW});await disconnectMcpServer({name:y.name,registry:t}),await h(),u({text:`${gt.tick} Disabled ${y.name}`,color:ER.GREEN})}catch(e){u({text:`${gt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ER.RED})}}else c("confirm-remove");else{u({text:`Authenticating ${y.name}...`,color:ER.CYAN,loading:!0});try{const e=await runMcpServerAuthFlow({serverName:y.name,config:y.config,connectAfterAuth:__name(({name:e})=>connectMcpServer({name:e,registry:t}),"connectAfterAuth")});if("unsupported"===e.kind)return void u({text:e.message,color:ER.YELLOW});"success"===e.kind?(u({text:`${gt.tick} Authenticated with ${y.name}`,color:ER.GREEN}),await h()):u({text:`${gt.cross} Auth failed: ${e.message}`,color:ER.RED})}catch(e){u({text:`${gt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ER.RED})}}else{u({text:`Connecting ${y.name}...`,color:ER.CYAN,loading:!0});try{await connectMcpServer({name:y.name,registry:t}),u({text:`${gt.tick} Connected to ${y.name}`,color:ER.GREEN}),await h()}catch(e){u({text:`${gt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ER.RED})}}else u({text:"Already authenticated",color:ER.GREEN});else u({text:"Already connected",color:ER.GREEN});else c("list")},"handleActionSelect"),C=__name(async e=>{if(y)if("yes"===e.value)try{"connected"===y.status&&await disconnectMcpServer({name:y.name,registry:t}),await removeMcpServer({name:y.name,scope:y.scope}),c("list"),await h(),a(e=>Math.min(e,Math.max(0,f.length-2)))}catch(e){u({text:`${gt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ER.RED}),c("actions")}else c("actions")},"handleRemoveConfirm");if(o)return st.createElement(bO,{title:"Manage MCP servers"},st.createElement(Xe,{color:ER.DIM},"Loading..."));if("confirm-remove"===l&&y)return st.createElement(bO,{title:`Remove ${y.name}?`,titleColor:ER.RED,hint:"↑↓ navigate · Enter to select · Esc to cancel"},st.createElement(Xe,{color:ER.DIM},"This will remove the server from ",y.scope," ","config."),st.createElement(Qe,{marginTop:1},st.createElement(SelectInput,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:C,indicatorComponent:KN,itemComponent:zN})));if("actions"===l&&y){const e=buildMcpManagerActionItems(y);return st.createElement(bO,{title:y.name,hint:"↑↓ navigate · Enter to select · Esc to go back"},st.createElement(Qe,null,CF(y.status),st.createElement(Xe,{color:ER.DIM}," ",getMcpManagerStatusText(y))),st.createElement(Qe,{marginTop:1},st.createElement(SelectInput,{items:[...e],onSelect:k,indicatorComponent:KN,itemComponent:zN})),d&&st.createElement(Qe,{marginTop:1},d.loading&&st.createElement(Xe,{color:d.color},st.createElement(kt,{type:"dots"})," "),st.createElement(Xe,{color:d.color},d.text)))}let b=null;const E=m,T=m+v,P=f.slice(E,T),M=f.length>v;return st.createElement(bO,{title:"Manage MCP servers",hint:0===n.length?"Esc to close":"↑↓ navigate · Enter to select · Esc to close"},st.createElement(Xe,{color:ER.DIM},n.length," ",1===n.length?"server":"servers"),0===n.length?st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},"No MCP servers configured."),st.createElement(Xe,{color:ER.DIM},'Use "',getBinaryCommand(),' mcp add" to add a server.'),st.createElement(cL,{url:"https://commandcode.ai/docs/mcp",text:"View MCP Docs ↗",color:ER.CYAN,dimColor:!0})):st.createElement(Qe,{marginTop:1,flexDirection:"column"},P.map((e,t)=>{const n=E+t,r=e.scope!==b;b=e.scope;const o=n===i;return st.createElement(st.Fragment,{key:e.name},r&&st.createElement(Qe,{marginTop:0===t?0:1},st.createElement(Xe,{bold:!0},getMcpManagerScopeLabel(e.scope)),st.createElement(Xe,{color:ER.DIM}," ","(",getMcpManagerScopePath(e.scope),")")),st.createElement(Qe,null,st.createElement(Xe,{color:o?ER.WHITE:void 0,backgroundColor:o?KR:void 0,bold:o},e.name),st.createElement(Xe,{color:ER.DIM,backgroundColor:o?KR:void 0}," · "),CF(e.status,o?KR:void 0),st.createElement(Xe,{color:getStatusTextColor(e.status),backgroundColor:o?KR:void 0}," ",getMcpManagerStatusText(e)," ")))})),M&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",E+1,"–",Math.min(T,f.length)," of"," ",f.length,E>0?" · ↑ more":"",T<f.length?" · ↓ more":"")),d&&st.createElement(Qe,{marginTop:1},d.loading&&st.createElement(Xe,{color:d.color},st.createElement(kt,{type:"dots"})," "),st.createElement(Xe,{color:d.color},d.text)))},"McpManager");Gt(),SR();var EF=__name(({onClose:e})=>{const[t,n]=at([]),[r,o]=at(0),[s,i]=at(!0),[a,l]=at(null);ct(()=>{__name(async()=>{try{const e=await discoverCommandMemoryFiles(process.cwd());n(e),i(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),i(!1)}},"loadMemoryFiles")()},[]);const c=__name(async t=>{try{await openMemoryFileInEditor(t.path,{logError:__name(e=>console.error(e),"logError")}),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=filterEditableMemoryLocations(t);if(nt((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]&&c(d[r]),"1"===t&&d[0]&&c(d[0]),"2"===t&&d[1]&&c(d[1]))}),s)return st.createElement(bO,{title:"Select memory to edit:"},st.createElement(Xe,{color:ER.DIM},"Loading memory files..."));if(a)return st.createElement(bO,{title:"Select memory to edit:"},st.createElement(Xe,{color:ER.RED},gt.cross," ",a));const u=projectMemorySelectorOptions(d);return st.createElement(bO,{title:"Select memory to edit:",hint:"↑/↓ to navigate · enter to edit · esc to cancel"},st.createElement(Qe,{columnGap:4},st.createElement(Qe,{flexDirection:"column"},u.map((e,t)=>st.createElement(Qe,{key:e.label},st.createElement(jN,{isSelected:r===t}),st.createElement(BN,{isSelected:r===t,idleColor:kO}," ",e.label)))),st.createElement(Qe,{flexDirection:"column"},u.map((e,t)=>st.createElement(BN,{key:e.label,isSelected:r===t,idleColor:kO},e.description)))))},"MemorySelector");function linkImageTokens(e,t){if(!t)return e;const n=new RegExp(fM.source,"g");return e.replace(n,(e,n)=>{const r=t[Number(n)];return r?createOSC8Link(fileUrl(r),e,!1):e})}function UserMessage({content:e,ideHint:t,imageTokenPaths:n}){const r=isSpecialUserMessageContent(e),o=r&&isInterruptedByUserMessage(e)?ER.DIM:ER.RED,s=r?getSpecialUserMessageContent({content:e,billingUrl:os}):linkImageTokens(e,n);return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{backgroundColor:r?void 0:NR.BG,paddingRight:1},st.createElement(Xe,{color:r?o:NR.POINTER,bold:!r},gt.pointer),st.createElement(Qe,{marginLeft:1},st.createElement(Xe,{color:r?o:NR.FG,wrap:"wrap"},s))),t&&!r&&st.createElement(Qe,{marginLeft:2},st.createElement(Xe,{color:zR},yL),st.createElement(Xe,{color:ER.DIM}," ","Selected ",t.lines," ",1===t.lines?"line":"lines"," from"," ",t.file," in ",t.ide)))}Gt(),SR(),Gt(),SR(),__name(linkImageTokens,"linkImageTokens"),__name(UserMessage,"UserMessage");var TF=gt.squareSmallFilled;function goalStatusGlyph(e){return"completed"===e?gt.tick:"paused"===e?"⏸":"idle"===e?gt.circle:TF}function goalStatusHeadColor(e){return"completed"===e?ER.GREEN:"paused"===e?ER.YELLOW:ER.DIM}function goalNoticeGlyph(e){return"cleared"===e?gt.tick:"none"===e?gt.circle:"paused"===e?"⏸":TF}function AutoCompactMessage({content:e}){return st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},TF," ",e))}function ZdrPausedMessage(){return st.createElement(Qe,{marginTop:1,marginBottom:1},st.createElement(Xe,null,st.createElement(Xe,{color:ER.DIM},TF," "),st.createElement(Xe,{color:ER.DIM},"Per-task model overrides reverted to ZDR safe defaults. Run"," "),st.createElement(Xe,{color:WR.CODE},"/config"),st.createElement(Xe,{color:ER.DIM}," to review · esc to dismiss")))}function ModelNoticeMessage({text:e}){return st.createElement(Qe,{marginTop:1,marginBottom:1},st.createElement(Xe,null,st.createElement(Xe,{color:ER.DIM},TF," "),st.createElement(Xe,{color:ER.DIM},e),st.createElement(Xe,{color:ER.DIM}," · esc to dismiss")))}function TasteSkipMessage(){return st.createElement(Qe,{marginTop:1,marginBottom:1},st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:PR.BADGE_BG,color:PR.BADGE_FG,bold:!0},vL)),st.createElement(Xe,{color:ER.DIM}," Skipped. Run "),st.createElement(Xe,{color:WR.CODE},"/learn-taste"),st.createElement(Xe,{color:ER.DIM}," or "),st.createElement(Xe,{color:WR.CODE},"cmd learn-taste"),st.createElement(Xe,{color:ER.DIM}," anytime."))}function TasteNoticeMessage({notice:e}){const t=e.path?`${tasteDirForRoot({projectRoot:process.cwd()})}/${e.path}`:null;return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:PR.BADGE_BG,color:PR.BADGE_FG,bold:!0},vL)),st.createElement(Xe,{color:PR.TEXT}," ",e.label)),st.createElement(Qe,{columnGap:1,marginLeft:1},st.createElement(Xe,{color:zR},yL),st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{wrap:"wrap"},e.text,e.confidence&&st.createElement(Xe,{color:ER.DIM},` [Confidence ${e.confidence}]`)))),e.path&&t&&st.createElement(Qe,{marginLeft:3},st.createElement(cL,{url:fileUrl(t),text:e.path,color:ER.DIM})))}function SkillLoadedMessage({name:e}){return st.createElement(Qe,null,st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:AR.BG,color:AR.FG,bold:!0},`${wL}SKILL${wL}`)),st.createElement(Xe,null," ",e),st.createElement(Xe,{color:ER.DIM}," loaded"))}function HookWarningMessage({content:e}){return st.createElement(Qe,null,st.createElement(Xe,{color:ER.YELLOW},gt.warning),st.createElement(Qe,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.YELLOW},e)))}function HookLineMessage({content:e}){return st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},` ${e}`))}function HookLineContinuationMessage({content:e}){return st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},` ${e}`))}function HookFrameMessage({lines:e,header:t}){return st.createElement(Qe,{flexDirection:"column"},void 0!==t&&st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},` ${t}`)),e.map((e,t)=>st.createElement(Qe,{key:t,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},e.primary?` └ ${e.text}`:` ${e.text}`))))}function GoalLineMessage({content:e,subline:t}){return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:zR},yL),st.createElement(Xe,{color:ER.DIM,wrap:"wrap"}," ",e)),t?st.createElement(Qe,{marginLeft:4,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM,wrap:"wrap"},t)):null)}function GoalAcceptMessage({command:e,acceptLine:t,hint:n}){return st.createElement(Qe,{flexDirection:"column"},st.createElement(UserMessage,{content:e}),st.createElement(GoalLineMessage,{content:t,subline:n}))}function GoalCompleteMessage({elapsed:e,turns:t,goal:n}){const r=`${t} ${1===t?"turn":"turns"}`;return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,null,st.createElement(Xe,{color:ER.GREEN},gt.tick," Goal achieved"),st.createElement(Xe,{color:ER.DIM},` (${e} · ${r})`))),st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM,wrap:"wrap"},"Goal: ",n)))}function GoalStatusMessage({state:e,headline:t,goal:n,detail:r,hint:o}){const s=goalStatusGlyph(e),i=goalStatusHeadColor(e);return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:i},s," ",t)),st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM,wrap:"wrap"},n)),r?st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM,wrap:"wrap"},r)):null,o?st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},o)):null)}function BranchResultMessage({title:e}){return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},e?st.createElement(Xe,null,st.createElement(Xe,{color:ER.GREEN},"⑂ Forked."),st.createElement(Xe,null," You're now in "),st.createElement(Xe,{bold:!0},'"',e,'"')):st.createElement(Xe,null,st.createElement(Xe,{color:ER.GREEN},"⑂ Forked."),st.createElement(Xe,null," You're now in the new session"))),st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},"Original session saved · /resume to switch back")))}function SessionFileMessage({sessionId:e,fileLine:t}){return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},TF," Session ID: "),st.createElement(Xe,null,e)),st.createElement(Qe,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:zR},yL," "),st.createElement(Xe,{color:ER.DIM,wrap:"wrap"},t)))}function InfoMessage({content:e,metadata:t}){if(t?.isTasteSkip)return st.createElement(TasteSkipMessage,null);if(t?.tasteNotice)return st.createElement(TasteNoticeMessage,{notice:t.tasteNotice});if(t?.skillLoaded)return st.createElement(SkillLoadedMessage,{name:t.skillLoaded.name});if(t?.isAutoCompact)return st.createElement(AutoCompactMessage,{content:e});if(t?.hookFrame&&t.hookFrame.length>0)return st.createElement(HookFrameMessage,{lines:t.hookFrame,header:t.hookFrameHeader});if(t?.isHookLine)return st.createElement(HookLineMessage,{content:e});if(t?.isHookLineContinuation)return st.createElement(HookLineContinuationMessage,{content:e});if(t?.isHookWarning)return st.createElement(HookWarningMessage,{content:e});if(t?.isSuccess)return st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.GREEN},gt.tick," ",e));if(t?.isGoalAccept)return st.createElement(GoalAcceptMessage,{command:e,acceptLine:t.goalAcceptLine??"",hint:t.goalSubline});if(t?.isGoalComplete)return st.createElement(GoalCompleteMessage,{elapsed:t.goalElapsed??"",turns:t.goalTurns??1,goal:t.goalText??""});if(t?.isGoalStatus)return st.createElement(GoalStatusMessage,{state:t.goalState??"running",headline:t.goalHeadline??"",goal:t.goalText??"",detail:t.goalDetail,hint:t.goalSubline});if(t?.isBranchResult)return st.createElement(BranchResultMessage,{title:t.branchTitle});if(t?.isSessionFile)return st.createElement(SessionFileMessage,{sessionId:t.sessionFileId??"",fileLine:t.sessionFileLine??""});if(t?.isGoalNotice){const n=goalNoticeGlyph(t.goalNoticeKind);return st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},n," ",e))}return t?.isGoalLine?st.createElement(GoalLineMessage,{content:e,subline:t.goalSubline}):st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM},TF," ",e))}__name(goalStatusGlyph,"goalStatusGlyph"),__name(goalStatusHeadColor,"goalStatusHeadColor"),__name(goalNoticeGlyph,"goalNoticeGlyph"),__name(AutoCompactMessage,"AutoCompactMessage"),__name(ZdrPausedMessage,"ZdrPausedMessage"),__name(ModelNoticeMessage,"ModelNoticeMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(TasteNoticeMessage,"TasteNoticeMessage"),__name(SkillLoadedMessage,"SkillLoadedMessage"),__name(HookWarningMessage,"HookWarningMessage"),__name(HookLineMessage,"HookLineMessage"),__name(HookLineContinuationMessage,"HookLineContinuationMessage"),__name(HookFrameMessage,"HookFrameMessage"),__name(GoalLineMessage,"GoalLineMessage"),__name(GoalAcceptMessage,"GoalAcceptMessage"),__name(GoalCompleteMessage,"GoalCompleteMessage"),__name(GoalStatusMessage,"GoalStatusMessage"),__name(BranchResultMessage,"BranchResultMessage"),__name(SessionFileMessage,"SessionFileMessage"),__name(InfoMessage,"InfoMessage"),Gt(),SR(),Gt(),Gt(),Gt(),Gt();var PF=/\[\^[^\]]+\]/;function splitMarkdownBlocks(e){return e?PF.test(e)?[e]:yt.lex(e,{gfm:!0}).map(e=>e.raw):[]}function isWhitespaceOnly2(e){return 0===e.trim().length}function createBlockStream(){let e="",t=0,n=!1;function frozenAdvance(n){return{newlyCompleted:[],openTail:n.startsWith(e)?n.slice(e.length):n,committedBlockCount:t,frozen:!0}}function advance(r){if(n)return frozenAdvance(r);if(!r.startsWith(e))return n=!0,frozenAdvance(r);const o=splitMarkdownBlocks(r);if(o.length<=1)return{newlyCompleted:[],openTail:r.slice(e.length),committedBlockCount:t,frozen:!1};const s=o.slice(0,-1),i=[];let a=0;for(const o of s){const s=a+o.length;if(s<=e.length){if(e.slice(a,s)!==o)return n=!0,frozenAdvance(r)}else{if(a!==e.length)return n=!0,frozenAdvance(r);i.push(o),e+=o,isWhitespaceOnly2(o)||(t+=1)}a=s}return{newlyCompleted:i,openTail:r.slice(e.length),committedBlockCount:t,frozen:!1}}function finalize(r){if(n||!r.startsWith(e)){const n=r.startsWith(e)?r.slice(e.length):r;return{remaining:n?[n]:[],committedBlockCount:t}}const o=r.slice(e.length);return o?{remaining:splitMarkdownBlocks(o),committedBlockCount:t}:{remaining:[],committedBlockCount:t}}return __name(frozenAdvance,"frozenAdvance"),__name(advance,"advance"),__name(finalize,"finalize"),{advance:advance,finalize:finalize}}__name(splitMarkdownBlocks,"splitMarkdownBlocks"),__name(isWhitespaceOnly2,"isWhitespaceOnly"),__name(createBlockStream,"createBlockStream"),Gt();var MF=String.fromCharCode(8203),xF=new Set(["_","~","*","`"]),IF=/!?\[[^\]]*\]\([^)]*$/,AF=/!?\[[^\]]*$/;function isSpace(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function isOnlyMarkersOrSpace(e){for(const t of e)if(!isSpace(t)&&!xF.has(t))return!1;return!0}function isShortSetextUnderline(e){if(0===e.length||e.length>2)return!1;const t=e[0];if("-"!==t&&"="!==t)return!1;for(const n of e)if(n!==t)return!1;return!0}function isTagOpener(e){const t=e.startsWith("</")?e[2]:e[1];return void 0!==t&&/[a-zA-Z]/.test(t)}function countFenceMarkers(e){let t=0;for(let n=0;n<e.length;n+=1)"\\"!==e[n]||"`"!==e[n+1]?e.startsWith("```",n)&&(t+=1,n+=2):n+=1;return t}function countMarkerOutsideCode(e,t){let n=0,r=!1,o=!1;for(let s=0;s<e.length;s+=1){const i=e[s];"\\"!==i?e.startsWith("```",s)?(r=!r,s+=2):r||("`"!==i?o||e.startsWith(t,s)&&(n+=1,s+=t.length-1):o=!o):s+=1}return n}function countSingleBackticks(e){let t=0,n=!1;for(let r=0;r<e.length;r+=1)"\\"!==e[r]||"`"!==e[r+1]?e.startsWith("```",r)?(n=!n,r+=2):n||"`"!==e[r]||(t+=1):r+=1;return t}function stripDanglingHtmlTag(e){const t=e.lastIndexOf("<");if(-1===t)return e;const n=e.slice(t);return n.includes(">")?e:isTagOpener(n)?e.slice(0,t).trimEnd():e}function stripDanglingLink(e){const t=e.match(IF);if(void 0!==t?.index)return e.slice(0,t.index).trimEnd();const n=e.match(AF);return void 0!==n?.index?e.slice(0,n.index).trimEnd():e}function guardSetextUnderline(e){const t=e.lastIndexOf("\n");if(-1===t)return e;const n=e.slice(t+1),r=n.trim();if(!isShortSetextUnderline(r))return e;if(n!==r&&n.endsWith(" "))return e;const o=e.slice(0,t).split("\n").at(-1);return o&&0!==o.trim().length?`${e}${MF}`:e}function closeUnbalancedMarker(e,t,n){if(countMarkerOutsideCode(e,t)%2==0)return e;const r=e.lastIndexOf(t),o=e.slice(r+t.length);return isOnlyMarkersOrSpace(o)?e:n&&o.endsWith(n)?`${e}${n}`:`${e}${t}`}function completeInlineTripleFence(e){if(e.includes("\n"))return null;if(!e.startsWith("```"))return null;if(!e.endsWith("``")||e.endsWith("```"))return null;const t=e.slice(3,-2);return 0===t.length||t.includes("`")?null:`${e}\``}function closeInlineCode(e){if(countSingleBackticks(e)%2==0)return e;const t=e.lastIndexOf("`");return isOnlyMarkersOrSpace(e.slice(t+1))?e:`${e}\``}function mendMarkdown(e){if(!e)return e;const t=completeInlineTripleFence(e);if(null!==t)return t;if(countFenceMarkers(e)%2==1)return e;let n=e;return n=stripDanglingHtmlTag(n),n=stripDanglingLink(n),n=guardSetextUnderline(n),n=closeUnbalancedMarker(n,"***",""),n=closeUnbalancedMarker(n,"**","*"),n=closeUnbalancedMarker(n,"__","_"),n=closeUnbalancedMarker(n,"~~","~"),n=closeInlineCode(n),n}__name(isSpace,"isSpace"),__name(isOnlyMarkersOrSpace,"isOnlyMarkersOrSpace"),__name(isShortSetextUnderline,"isShortSetextUnderline"),__name(isTagOpener,"isTagOpener"),__name(countFenceMarkers,"countFenceMarkers"),__name(countMarkerOutsideCode,"countMarkerOutsideCode"),__name(countSingleBackticks,"countSingleBackticks"),__name(stripDanglingHtmlTag,"stripDanglingHtmlTag"),__name(stripDanglingLink,"stripDanglingLink"),__name(guardSetextUnderline,"guardSetextUnderline"),__name(closeUnbalancedMarker,"closeUnbalancedMarker"),__name(completeInlineTripleFence,"completeInlineTripleFence"),__name(closeInlineCode,"closeInlineCode"),__name(mendMarkdown,"mendMarkdown");var RF=bt()?"⠶":"#";function streamingMaxRows(e){return Math.max(8,e-12)}function AssistantMessage({content:e,isStreaming:t=!1,continuation:n=!1}){const r=useTerminalRows(),o=t?mendMarkdown(e):e;return st.createElement(Qe,null,n?st.createElement(Qe,{width:2,flexShrink:0}):st.createElement(Xe,{color:_R},RF),st.createElement(Qe,{marginLeft:n?0:1,flexGrow:1,flexShrink:1,minWidth:0,flexDirection:"column"},st.createElement(Markdown,{maxPhysicalRows:t?streamingMaxRows(r):void 0},o)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o=ER.GREEN,s=gt.tick,i="default",a=t||"(No output)";n&&(o=ER.YELLOW,s=gt.arrowRight,i=ER.YELLOW,a="Executing…"),r&&(o=ER.RED,s=gt.cross,i=ER.RED);const l=dt(()=>buildTreeConnectors(a),[a]);return st.createElement(Qe,null,st.createElement(Xe,{color:o},s),st.createElement(Qe,{flexDirection:"column",marginLeft:1},st.createElement(Qe,null,st.createElement(Xe,{color:ER.GRAY},"$ "),st.createElement(Xe,{color:o,bold:!0},e)),st.createElement(Qe,{columnGap:1,marginLeft:1},st.createElement(Xe,{color:zR},l),st.createElement(Xe,{color:i,wrap:"wrap"},a))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?ER.YELLOW:void 0,o=dt(()=>buildTreeConnectors(e),[e]);return st.createElement(Qe,{flexDirection:"column",marginBottom:0,marginTop:-1},st.createElement(Qe,{columnGap:1},st.createElement(Xe,{color:zR},o),st.createElement(Qe,{flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:r},e))),t&&st.createElement(Qe,{marginLeft:3},st.createElement(Xe,{color:ER.DIM},"See ",t)))}function ErrorMessage({content:e}){return isInterruptedByUserMessage(e)?st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},gt.pointer),st.createElement(Qe,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Xe,{color:ER.DIM,wrap:"wrap"},tS))):st.createElement(Qe,null,st.createElement(Xe,{color:ER.RED},gt.warning),st.createElement(Qe,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},st.createElement(Markdown,{color:ER.RED},e)))}__name(streamingMaxRows,"streamingMaxRows"),__name(AssistantMessage,"AssistantMessage"),Gt(),__name(BashMessage,"BashMessage"),Gt(),__name(CommandResultMessage,"CommandResultMessage"),Gt(),SR(),__name(ErrorMessage,"ErrorMessage"),Gt(),SR();var LF={connected:{char:gt.tick,color:ER.GREEN},installed:{char:gt.tick,color:ER.GREEN},up_to_date:{char:gt.tick,color:ER.GREEN},needs_reload:{char:gt.circle,color:ER.YELLOW},failed:{char:gt.cross,color:ER.RED},not_in_ide:{char:gt.circle,color:ER.YELLOW}};function IDEStatusMessage({status:e,ide:t,details:n}){const{prefix:r,ide:o,suffix:s}=getIDESetupStatusHeadline(e,t),i=LF[e];return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,null,st.createElement(Xe,{color:i.color},i.char),st.createElement(Xe,null," ",r),o&&st.createElement(Xe,{color:ER.CYAN},o),s&&st.createElement(Xe,null,s))),n?.map(e=>st.createElement(Xe,{key:e,color:ER.DIM}," ",e)))}function reasoningBodyColumns(e){const t=Math.floor(.9*Math.floor(.9*e));return Math.max(1,t-2)}function ReasoningMessage({content:e,expandedOutput:t,expandKey:n,isStreaming:r=!1}){const o=projectReasoningView({content:e,expandedOutput:t,expandKey:n,isStreaming:r,columns:reasoningBodyColumns(useTerminalWidth()),measureWidth:Ne});return st.createElement(Qe,{flexDirection:"column",width:"90%"},st.createElement(Qe,null,st.createElement(Xe,{color:MR},"✻"," "),st.createElement(Xe,{color:MR},o.showExpandHint?`${o.headerLabel} `:o.headerLabel),o.showExpandHint&&st.createElement(BracketWrap,{color:ER.DIM},o.expandHint)),o.showBody&&o.hiddenAboveLabel&&st.createElement(Qe,{marginLeft:2},st.createElement(Xe,{color:ER.DIM},o.hiddenAboveLabel)),o.showBody&&st.createElement(Qe,{marginLeft:2,flexDirection:"column"},st.createElement(Xe,{color:MR,wrap:"wrap",italic:!0},o.bodyText)))}__name(IDEStatusMessage,"IDEStatusMessage"),Gt(),SR(),__name(reasoningBodyColumns,"reasoningBodyColumns"),__name(ReasoningMessage,"ReasoningMessage"),Gt(),SR(),Gt(),SR();function HelpMessage(){const e=getInvokedCommandName(),t=dt(()=>getVisibleSlashCommands(),[]);return st.createElement(Qe,{flexDirection:"column",paddingY:1},st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Qe,null,st.createElement(Xe,{bold:!0},"Command Code"),st.createElement(Xe,{color:ER.GRAY}," v","1.65.4")),st.createElement(Xe,{color:ER.GRAY},hi)),st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{bold:!0},"Usage"),st.createElement(Qe,{paddingLeft:2},st.createElement(Xe,null,e," <command> [options]"))),st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{bold:!0},"Options"),st.createElement(Qe,{flexDirection:"column",paddingLeft:2},ki.map(t=>st.createElement(Qe,{key:t.key},st.createElement(Xe,null,t.key.replace(/^cmd/,e).padEnd(fi)),st.createElement(Xe,{color:ER.GRAY},t.description))))),st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{bold:!0},"Commands"),st.createElement(Qe,{flexDirection:"column",paddingLeft:2},bi.map(t=>st.createElement(Qe,{key:t.key},st.createElement(Xe,null,t.key.replace(/^cmd/,e).padEnd(fi)),st.createElement(Xe,{color:ER.GRAY},t.description))))),st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{bold:!0},"Slash Commands"),st.createElement(Qe,{flexDirection:"column",paddingLeft:2},t.map(e=>st.createElement(Qe,{key:e.key},st.createElement(Xe,null,e.key.padEnd(fi)),st.createElement(Xe,{color:ER.GRAY},e.description))))),st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{bold:!0},"Keyboard Shortcuts"),st.createElement(Qe,{flexDirection:"column",paddingLeft:2},vi.map(e=>st.createElement(Qe,{key:e.key},st.createElement(Xe,null,e.key.padEnd(fi)),st.createElement(Xe,{color:ER.GRAY},e.description))))),st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Xe,{bold:!0},"Examples"),st.createElement(Qe,{flexDirection:"column",paddingLeft:2},Ti.map(t=>st.createElement(Qe,{key:t.key},st.createElement(Xe,null,t.key.replace(/^cmd/,e).padEnd(fi)),st.createElement(Xe,{color:ER.GRAY},t.description))))),st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.CYAN},gt.pointer),st.createElement(Xe,{color:ER.GRAY}," ",yi.replace(/cmd/,e))),st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{bold:!0},"Links"),st.createElement(Qe,{flexDirection:"column",paddingLeft:2},Ei.map(e=>st.createElement(Qe,{key:e.key},st.createElement(Xe,null,e.key.padEnd(fi)),st.createElement(Xe,{color:ER.CYAN},e.description))))))}function SystemMessage({content:e}){return isHelpSystemEntryContent(e)?st.createElement(HelpMessage,null):st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{wrap:"wrap"},st.createElement(Markdown,null,e)))}function FeedEntryView({entry:e,expandedToolOutput:t}){return renderFeedEntry(e,t)}function renderFeedEntry(e,t){if("user"===e.role){const t=e.metadata?.ideHint,n=e.metadata?.imageTokenPaths;return st.createElement(UserMessage,{content:e.input,ideHint:t,imageTokenPaths:n})}return"assistant"===e.role?st.createElement(AssistantMessage,{content:e.input,isStreaming:"running"===e.metadata?.status,continuation:!0===e.metadata?.continuation}):"reasoning"===e.role?st.createElement(ReasoningMessage,{content:e.input,expandedOutput:t,expandKey:"ctrl",isStreaming:"running"===e.metadata?.status}):"tool"===e.role?st.createElement(ToolMessage,{name:Ah(e.name||""),input:e.input,output:e.output||"",isPending:Ph(e),hasError:Th(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?st.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:Ph(e),hasError:Th(e)}):"system"===e.role?st.createElement(SystemMessage,{content:e.input}):"info"===e.role?st.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?st.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?st.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?st.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),__name(FeedEntryView,"FeedEntryView"),__name(renderFeedEntry,"renderFeedEntry");var OF=__name(e=>getModelShortName({modelId:e,findModelById:findModelById}),"getModelShortName");function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages [${NE?"ctrl+y":"ctrl+e"} to expand more] `,r=Math.max(0,Math.floor((t-n.length)/2)),o="─".repeat(r);return st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:$R},o),st.createElement(BracketedText,{text:n,color:$R}),st.createElement(Xe,{color:$R},o))}__name(TranscriptDivider,"TranscriptDivider");var DF=st.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o,currentEffort:s=null,currentProvider:i,hiddenCount:a=0})=>{const l=a>0?{role:"transcript-divider",count:a}:null,c=[...t?["header"]:[],...l?[l]:[],...e],d=useTerminalWidth(),u=dt(()=>tO(d),[d]),m=dt(()=>iO(d),[d]),p=dt(()=>getPackageJson(import.meta.url).version||"0.0.0",[]),g=dt(()=>getGitHeaderInfo(),[]),h=dt(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),f=o?OF(o):"sonnet-4.6",y=Boolean(o&&byokProviderId({model:o}))?"":" · taste-1",S=dt(()=>{if(!o)return"";if(!modelSupportsReasoningEffort(o))return"";const e=null===s?getReasoningEffort(o):s;return e?` with ${e} effort`:""},[s,o,n]),w=dt(()=>{const e=o?byokProviderId({model:o}):void 0;return e?` · ${e} (byok)`:i&&i!==uo.COMMAND?` · ${getProviderShortName(i)} (byok)`:""},[o,i,n]);return st.createElement(Ze,{items:c,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return st.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:d});if("header"===e)return"compact"===m?st.createElement(Qe,{key:"header",marginBottom:1,flexDirection:"row"},st.createElement(Qe,{width:oO,flexShrink:0},st.createElement(qR,null,rO)),st.createElement(Qe,{flexDirection:"column",marginLeft:2},st.createElement(Qe,null,st.createElement(Xe,{bold:!0},"Command Code"),st.createElement(Xe,{color:$R}," ","v",p)),st.createElement(Xe,{color:$R},"models: ",f,S,y,w),st.createElement(Xe,{color:$R},h,g&&g.isLocal&&g.branch&&` (${g.branch})`))):st.createElement(Qe,{key:"header",marginBottom:1,flexDirection:"column"},st.createElement(qR,null,u.trimEnd()),st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Qe,null,st.createElement(Xe,{color:$R},"# "),st.createElement(Xe,{bold:!0},"Command Code"),st.createElement(Xe,{color:$R}," v",p)),st.createElement(Xe,{color:$R},"# models: ",f,S,y,w),st.createElement(Qe,null,st.createElement(Xe,{color:$R},"# ",h,g&&g.isLocal&&g.branch&&st.createElement(Xe,{color:$R}," ","(branch:"," ",g.branch,")")))));const t=e,n=renderFeedEntry(t,r);return st.createElement(Qe,{key:t.id,paddingBottom:1,width:"90%"},n)})});Gt(),SR();var $F=it(__name(function LiveAgentStatusInner2({entry:e}){const t=Ah(e.name||"Agent"),n=summarizeAgentTaskInput(e.input||""),r=e.metadata?.tokensUsed||0,o=e.metadata?.elapsedSeconds||0,s=e.metadata?.recentTools||[],[i,a]=at(".");return ct(()=>{const e=setInterval(()=>{a(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),st.createElement(Qe,{flexDirection:"column",marginBottom:1,width:"90%"},st.createElement(Qe,null,st.createElement(Xe,{backgroundColor:LR.BG,color:LR.FG,bold:!0},` ${t} `),n&&st.createElement(Xe,null," (",n,")")),st.createElement(Qe,{columnGap:1,marginLeft:1},st.createElement(Xe,null,"⎿"," "),st.createElement(Xe,{color:ER.GRAY},"Running (",formatTime3(o)," |"," ",formatTokens(r),")",i)),s.length>0&&st.createElement(Qe,{flexDirection:"column",marginLeft:1},s.map((e,t)=>{const n=Ah(e.name);return st.createElement(Qe,{key:t,columnGap:1},st.createElement(Xe,{color:ER.GRAY},"⎿"),st.createElement(Xe,{color:ER.GRAY}," ",n),e.input&&st.createElement(Xe,{color:ER.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),NF=it(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:st.createElement($F,{entry:e})},"LiveAgentStatus"));Gt(),Gt(),SR();var _F=[],FF=_F,UF=!1,jF=null,BF="",WF=new Set,HF=new Set,GF=new Set;function shapeOf(e){return e.map(e=>e.content.replace(/\d+/g,"#")).join("\0")}function emit2(){for(const e of GF)e()}function cancelPeek(){jF&&clearTimeout(jF),jF=null,UF=!1}function armPeek(){jF&&clearTimeout(jF),UF=!0,jF=setTimeout(()=>{jF=null,UF=!1,emit2()},5e3),jF.unref?.()}function projectUserEdits(e){return e.filter(e=>!WF.has(e.content)).map(e=>"completed"!==e.status&&HF.has(e.content)?{...e,status:"completed"}:e)}function setSessionTodos(e){const t=projectUserEdits(e);if(t.length>0&&HF.size>0&&t.every(e=>"completed"===e.status))return void clearSessionTodos();const n=shapeOf(t),r=n!==BF;(r||JSON.stringify(t)!==JSON.stringify(FF))&&(FF=t.length>0?t:_F,BF=n,FF.length>0&&r&&armPeek(),emit2())}function adoptSettled(e){FF=e.length>0?[...e]:_F,BF=shapeOf(FF),cancelPeek(),emit2()}function seedSessionTodos(e){WF.clear(),HF.clear(),adoptSettled(e)}function removeSessionTodoAt(e){const t=FF[e];return t&&WF.add(t.content),adoptSettled(FF.filter((t,n)=>n!==e)),FF}function seedTodosFromFeedEntries(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(!n||"tool"!==n.role||"todo_write"!==n.name)continue;const r="output"in n?n.output:void 0,o="string"==typeof r?Nh(r):null;if(o){if(o.every(e=>"completed"===e.status))break;return seedSessionTodos(o),FF}}return clearSessionTodos(),_F}function clearSessionTodos(){(FF!==_F||UF||0!==WF.size||0!==HF.size)&&(FF=_F,BF="",WF.clear(),HF.clear(),cancelPeek(),emit2())}function getSessionTodos(){return FF}function isTodoPanelCollapsed(){return!UF}function completeSessionTodoAt(e){const t=FF[e];return t&&HF.add(t.content),adoptSettled(FF.map((t,n)=>n===e?{...t,status:"completed"}:t)),FF}function completeAllSessionTodos(){const e=FF.map(e=>e.content);for(const t of e)HF.add(t);return adoptSettled(_F),e}function subscribe(e){return GF.add(e),()=>GF.delete(e)}function useSessionTodos(){return pt(subscribe,getSessionTodos)}function useTodoPanelCollapsed(){return pt(subscribe,isTodoPanelCollapsed)}function usePausedLabel(e){const[t,n]=at(!e);return ct(()=>{if(e)return void n(!1);const t=setTimeout(()=>n(!0),1500);return t.unref?.(),()=>clearTimeout(t)},[e]),t}function projectVisibleTodos(e){if(e.length<=8)return{foldedDone:0,visible:e,hiddenTail:0};const t=e.filter(e=>"completed"!==e.status),n=e.length-t.length,r=8-(n>0?1:0),o=t.slice(0,Math.max(1,r));return{foldedDone:n,visible:o,hiddenTail:t.length-o.length}}function currentTaskLabel(e){const t=e.find(e=>"in_progress"===e.status);if(t)return t.activeForm?`${t.activeForm}…`:t.content;const n=e.find(e=>"pending"===e.status);return n?n.content:null}function TodoPanel({active:e=!0}){const t=useSessionTodos(),n=useTodoPanelCollapsed(),r=usePausedLabel(e);if(0===t.length)return null;const o=t.filter(e=>"completed"===e.status).length,s=o>0?`${t.length} items · ${o} done`:`${t.length} items`,i=n?currentTaskLabel(t):null;return st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(Qe,null,st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:AR.BG,color:AR.FG,bold:!0},`${wL}TODOS${wL}`)),st.createElement(Qe,{flexShrink:0},st.createElement(Xe,null," ",st.createElement(BracketWrap,null,s))),i&&st.createElement(Qe,{flexShrink:1,minWidth:0},st.createElement(Xe,{color:r?ER.DIM:OR.IN_PROGRESS,bold:!r,wrap:"truncate-end"},` ${i}${r?" (paused)":""}`)),st.createElement(Qe,{flexShrink:0},st.createElement(Xe,null," ",st.createElement(BracketWrap,{color:ER.DIM},n?"ctrl+x to expand":"ctrl+x to manage")))),!n&&st.createElement(CappedChecklist,{todos:t}))}function CappedChecklist({todos:e}){const{foldedDone:t,visible:n,hiddenTail:r}=projectVisibleTodos(e);return st.createElement(Qe,{flexDirection:"column"},t>0&&st.createElement(Qe,{flexDirection:"row"},st.createElement(Qe,{width:2},st.createElement(Xe,{color:OR.SUCCESS},gt.checkboxOn)),st.createElement(Xe,{color:OR.SUCCESS,strikethrough:!0},t," completed")),st.createElement(TodoChecklist,{todos:n}),r>0&&st.createElement(Xe,{color:ER.DIM},` … +${r} more`))}__name(shapeOf,"shapeOf"),__name(emit2,"emit"),__name(cancelPeek,"cancelPeek"),__name(armPeek,"armPeek"),__name(projectUserEdits,"projectUserEdits"),__name(setSessionTodos,"setSessionTodos"),__name(adoptSettled,"adoptSettled"),__name(seedSessionTodos,"seedSessionTodos"),__name(removeSessionTodoAt,"removeSessionTodoAt"),__name(seedTodosFromFeedEntries,"seedTodosFromFeedEntries"),__name(clearSessionTodos,"clearSessionTodos"),__name(getSessionTodos,"getSessionTodos"),__name(isTodoPanelCollapsed,"isTodoPanelCollapsed"),__name(completeSessionTodoAt,"completeSessionTodoAt"),__name(completeAllSessionTodos,"completeAllSessionTodos"),__name(subscribe,"subscribe"),__name(useSessionTodos,"useSessionTodos"),__name(useTodoPanelCollapsed,"useTodoPanelCollapsed"),__name(usePausedLabel,"usePausedLabel"),__name(projectVisibleTodos,"projectVisibleTodos"),__name(currentTaskLabel,"currentTaskLabel"),__name(TodoPanel,"TodoPanel"),__name(CappedChecklist,"CappedChecklist"),Gt();var VF=new Set,zF=!1;function isTodosManagerOpen(){return zF}function requestTodosManagerOpen(){for(const e of VF)e()}function statusColor(e){return"completed"===e?ER.GREEN:"in_progress"===e?ER.CYAN:ER.WHITE}function TodoRow({todo:e,selected:t}){const n="completed"===e.status?gt.checkboxOn:gt.checkboxOff,r=t?KR:void 0;return st.createElement(Qe,null,st.createElement(jN,{isSelected:t,backgroundColor:r}),st.createElement(Xe,{color:statusColor(e.status),backgroundColor:r}," ",n),st.createElement(Xe,{color:t?wO:statusColor(e.status),strikethrough:"completed"===e.status,backgroundColor:r,wrap:"truncate-end"}," ",e.content),"in_progress"===e.status&&st.createElement(Xe,{color:ER.DIM,backgroundColor:r}," ","(in progress)"))}function TodosManagerPanel({sessionId:e,onExpandedChange:t}){const n=useSessionTodos(),[r,o]=at(!1),[s,i]=at(0);ct(()=>(zF=r,t?.(r),()=>{zF=!1,t?.(!1)}),[r,t]),ct(()=>{const e=__name(()=>{i(0),o(!0)},"listener");return VF.add(e),()=>{VF.delete(e)}},[]),ct(()=>{if(0===n.length)return o(!1),void i(0);i(e=>Math.min(e,n.length-1))},[n.length]);const a=__name(t=>{k$(e)?.applyTodoUserEdit(t)},"syncHarness");if(nt((e,t)=>{if(t.escape||t.leftArrow||t.ctrl&&"x"===e||""===e)o(!1);else if(0!==n.length)if(t.upArrow)i(e=>Math.max(0,e-1));else if(t.downArrow)i(e=>Math.min(n.length-1,e+1));else{if("c"===e){const e=n[s];return void a({todos:completeSessionTodoAt(s),...e?{completedContents:[e.content]}:{}})}if("x"===e){const e=n[s];return void a({todos:removeSessionTodoAt(s),...e?{removedContents:[e.content]}:{}})}"a"===e&&a({todos:[],completedContents:completeAllSessionTodos()})}},{isActive:r}),!r)return null;const l=n.filter(e=>"completed"===e.status).length;return st.createElement(bO,{title:"Todos",subtitle:l>0?`${n.length} items · ${l} done`:`${n.length} items`,gapAfterHeader:!1,boxProps:{marginTop:1,marginBottom:1}},st.createElement(Qe,{flexDirection:"column",marginTop:1},n.map((e,t)=>st.createElement(TodoRow,{key:e.id??t,todo:e,selected:t===s}))))}__name(isTodosManagerOpen,"isTodosManagerOpen"),__name(requestTodosManagerOpen,"requestTodosManagerOpen"),__name(statusColor,"statusColor"),__name(TodoRow,"TodoRow"),__name(TodosManagerPanel,"TodosManagerPanel"),Gt(),SR(),SR();var KF=__name(({currentModel:e,onClose:t,refreshBanner:n,sessionId:r})=>{const o=customReasoningEfforts(e)??getSupportedEfforts(e)??[],s=findModelById(e)?.label??getModelDisplayName(e),i=lt(!1),a=__name(o=>{if(i.current)return;i.current=!0;const s=o!==getReasoningEffort(e);(async()=>{try{s&&(await setReasoningEffort({modelId:e,effort:o}),n(),void 0!==o&&r&&k$(r)?.recordEffortChange({model:e,effort:o}))}catch(e){dlog(`[Effort] Failed to persist reasoning effort: ${e}`)}finally{t()}})()},"handleSelect"),l=__name(()=>{i.current||t()},"handleCancel");return st.createElement(P_,{modelLabel:s,supportedEfforts:o,currentEffort:getReasoningEffort(e),onSelect:a,onCancel:l})},"EffortSelector");function store(){return createAuthFileCredentialStore({authStore:createCommandAuthFileStore({runtime:createNodeRuntime()})})}async function getCustomProviderKeyState(e){const t=await store().get({provider:e});if("api"===t?.kind&&t.token)return"stored";const n=(await loadProvidersConfig({runtime:createNodeRuntime()})).providers.find(t=>t.id===e);return n?.apiKey?"configured":n?.keyless?"keyless":"missing"}async function getConfiguredKeyReference(e){const t=await loadProvidersConfig({runtime:createNodeRuntime()});return t.providers.find(t=>t.id===e)?.apiKey}async function storeCustomProviderKey(e){await store().set({provider:e.providerId,credential:{kind:"api",token:e.key}})}async function getStoredKeyPreview(e){const t=await store().get({provider:e});if("api"===t?.kind&&t.token)return`${t.token.slice(0,8)}…`}async function getStoredKeyToken(e){const t=await store().get({provider:e});return"api"===t?.kind&&t.token?t.token:void 0}async function clearCustomProviderKey(e){await store().remove({provider:e})}Gt(),SR(),Gt(),SR(),__name(store,"store"),__name(getCustomProviderKeyState,"getCustomProviderKeyState"),__name(getConfiguredKeyReference,"getConfiguredKeyReference"),__name(storeCustomProviderKey,"storeCustomProviderKey"),__name(getStoredKeyPreview,"getStoredKeyPreview"),__name(getStoredKeyToken,"getStoredKeyToken"),__name(clearCustomProviderKey,"clearCustomProviderKey"),Gt(),SR(),Gt();var qF={"@ai-sdk/openai":"openai-responses","@ai-sdk/anthropic":"anthropic-messages","@ai-sdk/openai-compatible":"openai-completions"};function modelOverrides(e){if(!isPlainObject8(e))return{};const t=e.provider;if(!isPlainObject8(t))return{};if("string"!=typeof t.npm)return{};const n=qF[t.npm];if(void 0===n)return;const r="string"==typeof t.api&&t.api.startsWith("https://")&&!t.api.includes("${")?t.api.replace(/\/+$/,""):void 0;return{api:n,...void 0!==r?{baseURL:r}:{}}}function cachePath(){return n(W(),".commandcode","cache","models-dev.json")}function isPlainObject8(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}async function readCache(){try{const e=JSON.parse(await se(cachePath(),"utf8"));if(!isPlainObject8(e.data))return null;const t=Date.now()-(e.fetchedAt??0);return{data:e.data,fresh:t>=0&&t<864e5}}catch{return null}}async function writeCache(e){try{const t=cachePath();await Z(r(t),{recursive:!0}),await K(t,JSON.stringify({fetchedAt:Date.now(),data:e}))}catch{}}async function fetchCatalog(e){const t=new AbortController,n=setTimeout(()=>t.abort(),6e3);try{const n=await e("https://models.dev/api.json",{headers:{accept:"application/json"},signal:t.signal});if(!n.ok)return null;const r=await n.json();return isPlainObject8(r)?r:null}catch{return null}finally{clearTimeout(n)}}async function loadCatalog(e){const t=await readCache();if(t?.fresh)return t.data;const n=await fetchCatalog(e);return n?(await writeCache(n),n):t?.data??null}function asPositive(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}function urlParts(e){try{const t=new URL(e);return{host:t.hostname.toLowerCase(),path:t.pathname.replace(/\/+$/,"")||"/"}}catch{return}}function recordContains(e,t){if(e===t)return!0;const n="/"===e?"/":`${e}/`;return t.startsWith(n)}function curateModels(e){return isPlainObject8(e)?Object.entries(e).filter(e=>isPlainObject8(e[1])).filter(([,e])=>"deprecated"!==e.status).filter(([,e])=>{const t=isPlainObject8(e.modalities)?e.modalities.output:void 0;return!Array.isArray(t)||t.includes("text")}).sort(([,e],[,t])=>String(t.release_date??"").localeCompare(String(e.release_date??""))).flatMap(([e,t])=>{const n=modelOverrides(t);if(void 0===n)return[];const r=isPlainObject8(t.limit)?t.limit:void 0;return{id:e,...n,..."string"==typeof t.name&&t.name?{name:t.name}:{},...void 0!==asPositive(r?.context)?{contextWindow:asPositive(r?.context)}:{},...void 0!==asPositive(r?.output)?{maxOutput:asPositive(r?.output)}:{}}}):[]}__name(modelOverrides,"modelOverrides"),__name(cachePath,"cachePath"),__name(isPlainObject8,"isPlainObject"),__name(readCache,"readCache"),__name(writeCache,"writeCache"),__name(fetchCatalog,"fetchCatalog"),__name(loadCatalog,"loadCatalog"),__name(asPositive,"asPositive"),__name(urlParts,"urlParts"),__name(recordContains,"recordContains"),__name(curateModels,"curateModels");var YF=new Set(["github-copilot","amazon-bedrock","google-vertex","azure"]);async function listModelsDevProviders(e){const t=await loadCatalog(e?.fetchImpl??globalThis.fetch);if(!t)return[];const n=[];for(const[e,r]of Object.entries(t)){if(!isPlainObject8(r))continue;if(YF.has(e))continue;const t="string"==typeof r.api?r.api:void 0;if(!t||!t.startsWith("https://")||t.includes("${"))continue;const o=e.toLowerCase();n.push({id:"openai"===o||"anthropic"===o?`${o}-api`:o,name:"string"==typeof r.name&&r.name?r.name:e,baseURL:t.replace(/\/+$/,""),wire:"@ai-sdk/anthropic"===r.npm?"anthropic-messages":"openai-completions"})}return n}async function findModelsDevProvider(e){const t=urlParts(e.baseURL);if(!t)return null;const n=await loadCatalog(e.fetchImpl??globalThis.fetch);if(!n)return null;const r=[];for(const[e,o]of Object.entries(n)){if(!isPlainObject8(o))continue;const n="string"==typeof o.api?urlParts(o.api):void 0;n&&n.host===t.host&&r.push({slug:e,record:o,path:n.path})}if(0===r.length)return null;const o=r.filter(e=>recordContains(e.path,t.path)).sort((e,t)=>t.path.length-e.path.length),s=o[0]??(1===r.length?r[0]:void 0);if(!s)return null;if(o.length>1&&o[1]?.path===s.path)return null;const i=curateModels(s.record.models);if(0===i.length)return null;const a=Array.isArray(s.record.env)?s.record.env.find(e=>"string"==typeof e):void 0;return{slug:s.slug,displayName:"string"==typeof s.record.name&&s.record.name?s.record.name:s.slug,...a?{envVar:a}:{},models:i}}__name(listModelsDevProviders,"listModelsDevProviders"),__name(findModelsDevProvider,"findModelsDevProvider"),Gt();var JF=[{id:"ollama",name:"Ollama (local)",baseURL:"http://localhost:11434/v1",wire:"openai-completions",keyless:!0},{id:"lmstudio",name:"LM Studio (local)",baseURL:"http://127.0.0.1:1234/v1",wire:"openai-completions",keyless:!0}],QF=[{id:"vercel",name:"Vercel AI Gateway",baseURL:"https://ai-gateway.vercel.sh/v1",wire:"openai-completions"},{id:"groq",name:"Groq",baseURL:"https://api.groq.com/openai/v1",wire:"openai-completions"},{id:"mistral",name:"Mistral",baseURL:"https://api.mistral.ai/v1",wire:"openai-completions"},{id:"xai",name:"xAI",baseURL:"https://api.x.ai/v1",wire:"openai-completions"},{id:"together",name:"Together AI",baseURL:"https://api.together.xyz/v1",wire:"openai-completions"},{id:"cerebras",name:"Cerebras",baseURL:"https://api.cerebras.ai/v1",wire:"openai-completions"},{id:"deepinfra",name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/openai",wire:"openai-completions"},{id:"perplexity",name:"Perplexity",baseURL:"https://api.perplexity.ai",wire:"openai-completions"}],XF=/^[a-z0-9._-]+$/;function hostOf2(e){try{return new URL(e).hostname.toLowerCase()}catch{return}}function fallbackProviderSuggestions(){return[...QF,...JF]}async function loadProviderSuggestions(e){let t=[];try{t=await listModelsDevProviders(e?.fetchImpl?{fetchImpl:e.fetchImpl}:void 0)}catch{}const n=t.filter(e=>XF.test(e.id)).map(e=>({id:e.id,name:e.name,baseURL:e.baseURL,wire:e.wire})),r=[],o=new Set;for(const e of fallbackProviderSuggestions()){const t=n.find(t=>t.id===e.id||hostOf2(t.baseURL)===hostOf2(e.baseURL))??e;o.has(t.id)||(r.push(t),o.add(t.id))}return[...r,...n.filter(e=>!o.has(e.id)).sort((e,t)=>e.id.localeCompare(t.id))]}function matchKnownProviders(e){const t=e.query.trim().toLowerCase();return t?e.providers.filter(e=>e.id.startsWith(t)||e.name.toLowerCase().includes(t)).slice(0,e.limit??3):[]}function findKnownProvider(e){const t=e.id.trim().toLowerCase();return e.providers.find(e=>e.id===t)}__name(hostOf2,"hostOf"),__name(fallbackProviderSuggestions,"fallbackProviderSuggestions"),__name(loadProviderSuggestions,"loadProviderSuggestions"),__name(matchKnownProviders,"matchKnownProviders"),__name(findKnownProvider,"findKnownProvider"),Gt();var ZF=["/chat/completions","/completions","/responses","/messages","/models"];function normalizeEndpointInput(e){let t=e.trim().replace(/\/+$/,"");for(const e of ZF)if(t.toLowerCase().endsWith(e))return t=t.slice(0,-e.length).replace(/\/+$/,""),{url:t,stripped:e};return{url:t}}function asPositiveInt(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}function extractModels(e){const t=Array.isArray(e)?e:"object"==typeof e&&null!==e?e.data??e.models:void 0;if(!Array.isArray(t))return[];const n=new Map;for(const e of t){if("string"==typeof e){n.has(e)||n.set(e,{id:e});continue}if("object"!=typeof e||null===e)continue;const t=e,r="string"==typeof t.id?t.id:"string"==typeof t.name?t.name:void 0;if(!r||n.has(r))continue;const o="string"==typeof t.name&&t.name!==r?t.name:void 0,s=asPositiveInt(t.context_length)??asPositiveInt(t.context_window)??asPositiveInt(t.top_provider?.context_length),i=asPositiveInt(t.top_provider?.max_completion_tokens)??asPositiveInt(t.max_output_tokens)??asPositiveInt(t.max_tokens);n.set(r,{id:r,...o?{name:o}:{},...void 0!==s?{contextWindow:s}:{},...void 0!==i?{maxOutput:i}:{}})}return[...n.values()]}async function probeProviderModels(e){const t=e.fetchImpl??globalThis.fetch,n=e.baseURL.replace(/\/+$/,""),r=new AbortController,o=setTimeout(()=>r.abort(),e.timeoutMs??5e3);try{const o=await t(`${n}/models`,{headers:{accept:"application/json",...e.apiKey?{authorization:`Bearer ${e.apiKey}`,"x-api-key":e.apiKey}:{}},signal:r.signal});if(!o.ok)return{ok:!1,models:[],detail:`the endpoint answered ${o.status} on /models`};const s=extractModels(await o.json());return 0===s.length?{ok:!1,models:[],detail:"the endpoint listed no models"}:{ok:!0,models:s}}catch(e){return{ok:!1,models:[],detail:e instanceof Error&&("AbortError"===e.name||r.signal.aborted)?"no answer within 5s":"could not reach the endpoint"}}finally{clearTimeout(o)}}function ProvidersJsonLink({color:e=ER.DIM}){const t=`${W()}/.commandcode/providers.json`;return st.createElement(cL,{url:`file://${t}`,text:"~/.commandcode/providers.json",color:e})}function toNewProviderModels(e){return e.map(e=>({id:e.id,...e.name?{name:e.name}:{},...void 0!==e.contextWindow?{contextWindow:e.contextWindow}:{},...void 0!==e.maxOutput?{maxOutput:e.maxOutput}:{},...e.api?{api:e.api}:{},...e.baseURL?{baseURL:e.baseURL}:{}}))}function cardKeyLine(e){return"stored"===e.keyState?st.createElement(Xe,null,"key ",st.createElement(Xe,{color:ER.GREEN},e.keyPreview)," ",st.createElement(Xe,{color:ER.GREEN},"✓")," stored in auth.json",e.configuredReference?` · overrides ${e.configuredReference}`:""):"configured"===e.keyState?st.createElement(Xe,null,"key ",e.configuredReference??"set"):"keyless"===e.keyState?st.createElement(Xe,null,"no key — the endpoint asks for none"):st.createElement(Xe,{color:ER.YELLOW},"no key yet, requests fail until one is added")}function cardHints(e){const t=[st.createElement(st.Fragment,null,st.createElement(gO,null,"u")," update models"),st.createElement(st.Fragment,null,st.createElement(gO,null,"d")," delete"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," close")];return"stored"===e?[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," save"),st.createElement(st.Fragment,null,st.createElement(gO,null,"r")," replace key"),st.createElement(st.Fragment,null,st.createElement(gO,null,"c")," clear"),...t]:"missing"===e?[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," add key"),...t]:[st.createElement(st.Fragment,null,st.createElement(gO,null,"r")," store key"),...t]}function CustomProviderKeyEntry({providerId:e,providerName:t,keyState:n,keyPreview:r,configuredReference:o,onClose:s,onOpenModels:i,sessionId:a,onActiveModelOrphaned:l,onDiskDefaultOrphaned:c}){const[d,u]=at(""),[m,p]=at("card"),[g,h]=at(void 0),[f,y]=at(!1),[S,w]=at(void 0),[v,k]=at(void 0);st.useEffect(()=>{let t=!0;return(async()=>{const n=(await loadProvidersConfig({runtime:createNodeRuntime()})).providers.find(t=>t.id===e);t&&n&&w({baseURL:n.baseURL,modelCount:n.models.length})})(),()=>{t=!1}},[e]);const C=__name(async()=>{p("removing");try{const t=isByok({model:getConfiguredModel()??"",providerId:e}),n=(await loadUserConfig()).model??"",r=!t&&isByok({model:n,providerId:e});await removeUserProviderEntry({runtime:createNodeRuntime(),id:e}),await clearCustomProviderKey(e),t?(await(l?.()),y(!0)):r&&await(c?.()),await refreshCustomProviderModels(a?{sessionId:a}:void 0),p("removed")}catch(e){h(e instanceof Error?e.message:String(e)),p("error")}},"removeProvider"),b=__name(async()=>{p("updating-models");try{const t=(await loadProvidersConfig({runtime:createNodeRuntime()})).providers.find(t=>t.id===e);if(!t)throw new Error(`'${e}' is not in providers.json`);const n=await findModelsDevProvider({baseURL:t.baseURL}).catch(()=>null);let r,o;if(n&&n.models.length>0)r=toNewProviderModels(n.models),o="the model registry";else{const n=await getStoredKeyToken(e),s=await probeProviderModels({baseURL:t.baseURL,...n?{apiKey:n}:{}});if(!s.ok||0===s.models.length)throw new Error(`couldn't fetch models — ${s.detail??"no source answered"}`);r=toNewProviderModels(s.models),o="the endpoint"}const{count:s}=await updateUserProviderEntryModels({runtime:createNodeRuntime(),id:e,models:r});await refreshCustomProviderModels(a?{sessionId:a}:void 0),w(e=>e?{...e,modelCount:s}:e),k({count:s,source:o}),p("models-updated")}catch(e){h(e instanceof Error?e.message:String(e)),p("error")}},"updateModels");nt((t,r)=>{if(r.escape){if("removing"===m||"updating-models"===m)return;return"entry"===m?(u(""),void p("card")):"confirm-remove"===m?void p("card"):void s()}if("entry"!==m||!r.leftArrow||d){if("card"===m)return"d"===t||"D"===t?void p("confirm-remove"):"r"===t||"R"===t?void p("entry"):"u"===t||"U"===t?void b():"stored"!==n||"c"!==t&&"C"!==t?"missing"===n&&r.return?void p("entry"):void(r.return&&s()):void clearCustomProviderKey(e).then(()=>p("cleared"),()=>p("error"));if("confirm-remove"!==m)return"saved"===m&&r.return?(s(),void i?.()):void("models-updated"===m&&r.return?p("card"):"cleared"!==m&&"removed"!==m&&"error"!==m||!r.return||s());"y"===t||"Y"===t?C():(r.return||t)&&p("card")}else p("card")});const E=__name(async()=>{const t=d.trim();if(t)try{await storeCustomProviderKey({providerId:e,key:t}),p("saved")}catch{p("error")}},"handleSubmit"),T=S?st.createElement(st.Fragment,null,S.baseURL," · ",S.modelCount," ",1===S.modelCount?"model":"models"," · config:"," ",st.createElement(cL,{url:`file://${W()}/.commandcode/providers.json`,text:"providers.json",color:ER.DIM})):void 0;if("card"===m){const e=cardKeyLine({keyState:n,keyPreview:r,configuredReference:o}),s=cardHints(n);return st.createElement(bO,{title:t,titleSuffix:st.createElement(Xe,{color:ER.DIM}," (byok)"),subtitle:T,footer:st.createElement(hO,{hints:s,marginTop:0})},st.createElement(Qe,null,e))}return"confirm-remove"===m?st.createElement(bO,{title:`Remove ${t}?`,subtitle:"Its entry, models, and stored key go with it",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"y")," remove"),"any other key keeps it"]})},st.createElement(Xe,null,"Deletes the entry from ",st.createElement(ProvidersJsonLink,null)," and clears its stored key.")):"removing"===m||"updating-models"===m?st.createElement(bO,{title:t,rule:!1},st.createElement(Xe,null,"removing"===m?`Removing '${e}'…`:`Refetching models for '${e}'…`)):"removed"===m?st.createElement(bO,{title:`${t} removed`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," close")]})},st.createElement(Xe,{color:ER.DIM},"Provider deleted from ",st.createElement(ProvidersJsonLink,null)," · stored key cleared · its models left /model",f?" · it owned your active model — switched to your lane’s default":"")):"models-updated"===m?st.createElement(bO,{title:t,subtitle:T,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," back"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," close")]})},st.createElement(Xe,{color:ER.GREEN},"Models updated — ",v?.count??0," declared from"," ",v?.source??"the refetch",".")):"saved"===m?st.createElement(bO,{title:`Key saved for ${t}`,subtitle:"Stored in ~/.commandcode/auth.json",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," pick a model"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," close")]})}):"cleared"===m?st.createElement(bO,{title:`Stored key cleared for ${t}`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," close")]})},st.createElement(Xe,{color:ER.DIM},"Its models stay listed",o?" — the providers.json key applies again":"; requests will need a key again")):"error"===m?st.createElement(bO,{title:`Could not update ${t}`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," close")]})},st.createElement(Xe,{color:ER.DIM},g??'Check that ~/.commandcode is writable, or set "apiKey" to a "$ENV_VAR" reference in providers.json')):st.createElement(bO,{title:`API key for ${t}`,subtitle:`Saved to ~/.commandcode/auth.json under '${e}'. requests go straight to this provider with your key`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," save"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," back")]})},st.createElement(Qe,{borderStyle:"single",borderColor:ER.YELLOW,paddingX:1,width:"100%"},st.createElement(Xe,{color:ER.DIM},"key: "),st.createElement(Qe,{flexGrow:1},st.createElement(TextInput,{value:d,onChange:u,onSubmit:()=>{E()},placeholder:"paste your API key…",mask:"*",showCursor:!0}))))}function makeCustomProviderKeyEntry(e){return __name(function CustomProviderKeyEntryAdapter({onCancel:t}){return st.createElement(CustomProviderKeyEntry,{providerId:e.providerId,providerName:e.providerName,keyState:e.keyState,keyPreview:e.keyPreview,configuredReference:e.configuredReference,onClose:t,onOpenModels:e.onOpenModels,sessionId:e.sessionId,onActiveModelOrphaned:e.onActiveModelOrphaned,onDiskDefaultOrphaned:e.onDiskDefaultOrphaned})},"CustomProviderKeyEntryAdapter")}function makeAddCustomProviderEntry(e={}){return __name(function AddCustomProviderAdapter({onCancel:t}){return st.createElement(AddCustomProviderEntry,{onClose:t,onOpenModels:e.onOpenModels,sessionId:e.sessionId})},"AddCustomProviderAdapter")}__name(normalizeEndpointInput,"normalizeEndpointInput"),__name(asPositiveInt,"asPositiveInt"),__name(extractModels,"extractModels"),__name(probeProviderModels,"probeProviderModels"),__name(ProvidersJsonLink,"ProvidersJsonLink"),__name(toNewProviderModels,"toNewProviderModels"),__name(cardKeyLine,"cardKeyLine"),__name(cardHints,"cardHints"),__name(CustomProviderKeyEntry,"CustomProviderKeyEntry"),__name(makeCustomProviderKeyEntry,"makeCustomProviderKeyEntry"),__name(makeAddCustomProviderEntry,"makeAddCustomProviderEntry");var eU=[{value:"openai-completions",label:"OpenAI-compatible",detail:"/chat/completions · Ollama, vLLM, LM Studio, most hosted APIs"},{value:"openai-responses",label:"OpenAI Responses",detail:"/responses · endpoints speaking the OpenAI Responses API"},{value:"anthropic-messages",label:"Anthropic wire",detail:"/v1/messages · endpoints speaking the Claude Messages API"}];function cycleWire(e){const t=eU.findIndex(t=>t.value===e.current),n=eU.length,r=((e.forward?t+1:t-1)+n)%n;return eU[r]?.value??e.current}__name(cycleWire,"cycleWire");var tU=[["{",""],[' "provider": {',""],[' "openrouter": {',"the id you typed"],[' "baseURL": "https://openrouter.ai/api/v1",',"API root, no route"],[' "apiKey": "$OPENROUTER_API_KEY",',"reference — never a raw key"],[' "models": { "openai/gpt-5.6": {} }',"edit anytime, reloads live"],[" }",""],[" }",""],["}",""]];function endpointSubtitle(e){return e.prefilledName?`Prefilled for ${e.prefilledName} — edit it or press enter to accept`:"anthropic-messages"===e.wire?"The Messages API root · /v1 is added on the wire when missing":"openai-responses"===e.wire?"The API root requests go to · /responses is added on the wire":"The API root requests go to · most end in /v1"}function endpointPlaceholder(e){return"anthropic-messages"===e?"https://api.example.com/anthropic":"openai-responses"===e?"https://api.example.com/v1":"http://localhost:11434/v1"}function idStepMatches(e){return"id"!==e.phase?[]:e.query.trim()?matchKnownProviders({query:e.query,providers:e.providers,limit:e.providers.length}):e.providers}function AddCustomProviderEntry({onClose:e,onOpenModels:t,sessionId:n}){const[r,o]=at(""),[s,i]=at("openai-completions"),[a,l]=at(""),[c,d]=at(""),[u,m]=at(""),[p,g]=at("id"),[h,f]=at(()=>fallbackProviderSuggestions());st.useEffect(()=>{let e=!0;return loadProviderSuggestions().then(t=>{e&&t.length>0&&f(t)}),()=>{e=!1}},[]);const[y,S]=at(void 0),[w,v]=at(null),[k,C]=at(void 0),[b,E]=at(void 0),T=st.useRef(null),P=st.useRef("api"),M=st.useRef([]),[x,I]=at(void 0),[A,R]=at(0),[L,O]=at(void 0),D=""===c.trim(),$=idStepMatches({phase:p,query:r,providers:h}),N=__name(e=>{M.current.push(p),g(e)},"goTo"),_=__name((e,t)=>{M.current.push(e),g(t)},"arriveFrom"),F=__name(()=>{const t=M.current.pop();C(void 0),E(void 0),t?g(t):e()},"goBack");nt((n,o)=>{if("help"!==p){if(o.escape){if("saving"===p||"probing"===p)return;return"done"===p||"error"===p?void e():void F()}if(o.leftArrow&&("api"===p||"id"===p&&!r||"endpoint"===p&&!a||"key"===p&&!c||"manual-models"===p&&!u))F();else{if("api"===p&&("h"===n||"H"===n))return P.current=p,void g("help");if("id"!==p)return"api"===p?((o.upArrow||o.downArrow)&&i(e=>cycleWire({current:e,forward:!0===o.downArrow})),void(o.return&&N("endpoint"))):"done"===p&&o.return?(e(),void t?.()):void("error"===p&&o.return&&e());(o.upArrow||o.downArrow)&&$.length>0&&v(e=>{const t=$.length-1;if(null===e)return o.downArrow?0:t;const n=e+(o.downArrow?1:-1);return n<0?t:n>t?0:n})}}else g(P.current)});const U=__name(()=>{const e=null===w?void 0:$[w];if(e)return getCustomProviderModelsSync().some(t=>t.id===e.id)?void C(`'${e.id}' already exists — select it in /connect to manage it.`):(C(void 0),o(e.id),S(e),i(e.wire),l(e.baseURL),v(null),void N("api"));const t=r.trim().toLowerCase();if(!t)return;if(!isValidProviderId(t))return void C("Lowercase letters, digits, dots, dashes and underscores only.");if(isReservedProviderId(t))return void C(`'${t}' is a built-in subscription lane — try '${t}-api'.`);if(getCustomProviderModelsSync().some(e=>e.id===t))return void C(`'${t}' already exists — select it in /connect to manage it.`);C(void 0),o(t);const n=findKnownProvider({id:t,providers:h});S(n),n&&(i(n.wire),l(n.baseURL)),N("api")},"submitId"),j=__name(()=>{const{url:e,stripped:t}=normalizeEndpointInput(a);if(!e)return;let n;try{n=new URL(e)}catch{return void C("That is not a URL — include the scheme (http…).")}if("http:"===n.protocol||"https:"===n.protocol){if(C(void 0),t)return l(e),void E(`removed ${t} — the endpoint is the API root`);E(void 0),l(e),T.current=findModelsDevProvider({baseURL:e}).catch(()=>null),N("key")}else C("http:// or https:// URLs only.")},"submitEndpoint"),B=__name(async()=>{g("probing");const e=c.trim();let t=await probeProviderModels({baseURL:a,...e?{apiKey:e}:{}});t.ok||"anthropic-messages"!==s||a.endsWith("/v1")||(t=await probeProviderModels({baseURL:`${a}/v1`,...e?{apiKey:e}:{}})),t.ok&&t.models.length>0?await G(t.models):(I(t.detail),_("key","manual-models"))},"runProbe"),W=__name(async()=>{const e=c.trim();if(e)try{await storeCustomProviderKey({providerId:r,key:e})}catch{return O("The key could not be stored — check that ~/.commandcode is writable."),void g("error")}g("probing");const t=await T.current??null;t&&t.models.length>0?await G(t.models):await B()},"submitKey"),H=__name(()=>{const e=u.split(",").map(e=>e.trim()).filter(Boolean);0!==e.length&&G(e.map(e=>({id:e})))},"submitManualIds"),G=__name(async e=>{g("saving");try{await addUserProviderEntry({runtime:createNodeRuntime(),id:r,baseURL:a,api:s,keyless:D,models:toNewProviderModels(e)}),R(e.length),await refreshCustomProviderModels(n?{sessionId:n}:void 0),g("done")}catch(e){O(e instanceof Error?e.message:String(e)),g("error")}},"writeEntry"),V=k?st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.RED},k)):null,z=r.trim()?`Add a provider · ${r.trim().toLowerCase()}`:"Add a provider";if("saving"===p||"probing"===p)return st.createElement(bO,{title:z,rule:!1},st.createElement(Xe,null,"probing"===p?`Asking ${a} which models it serves…`:`Writing '${r}' to ~/.commandcode/providers.json…`));if("done"===p)return st.createElement(bO,{title:`'${r}' is set up`,subtitle:`${A} ${1===A?"model":"models"} declared${D?" · keyless endpoint":" · key stored in auth.json"}`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," pick a model"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," close")]})},st.createElement(Xe,{color:ER.DIM},"Provider added to ",st.createElement(ProvidersJsonLink,null),". Edit it anytime, it reloads live."));if("error"===p)return st.createElement(bO,{title:`Adding '${r}' didn't finish`,footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," close")]})},st.createElement(Xe,{color:ER.DIM},L));if("help"===p)return st.createElement(bO,{title:"Adding a provider: the short version",footer:st.createElement(Qe,{flexDirection:"column"},st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,"docs:"," ",st.createElement(cL,{url:"https://commandcode.ai/docs/byok",text:"commandcode.ai/docs/byok",color:ER.DIM})),"any key to go back"]}))},st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},"• provider id names the entry in ",st.createElement(ProvidersJsonLink,null)," · models select as id/model"),st.createElement(Xe,{color:ER.DIM},"• endpoint is the base URL requests go to · most end in /v1"),st.createElement(Xe,{color:ER.DIM},"• pasted keys go to auth.json · providers.json only ever holds $ENV_VAR or !command references"),st.createElement(Xe,{color:ER.DIM},"• no key needed? press enter on the empty key field (local servers)"),st.createElement(Xe,{color:ER.DIM},"• models: you can import the fetched list, probe the endpoint's /models route, or type ids by hand. Ids you leave undeclared still run as id/model"),st.createElement(Xe,{color:ER.DIM},"• the ",st.createElement(ProvidersJsonLink,null)," file is yours · edit it anytime, it reloads live · manage it from /connect"),st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.DIM},"what it writes:"),tU.map(([e,t])=>st.createElement(Xe,{key:e},st.createElement(Xe,{color:ER.CYAN}," ",e),t?st.createElement(Xe,{color:ER.DIM}," ","// ",t):null)))));if("manual-models"===p)return st.createElement(bO,{title:z,subtitle:x?`Couldn't list models automatically — ${x}`:`Which models does ${r} serve?`,footer:st.createElement(hO,{marginTop:0,hints:["comma-separated, exact ids",st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," save"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," back")]})},st.createElement(Qe,{borderStyle:"single",borderColor:ER.YELLOW,paddingX:1,width:"100%"},st.createElement(Xe,{color:ER.DIM},"models: "),st.createElement(Qe,{flexGrow:1},st.createElement(TextInput,{value:u,onChange:m,onSubmit:H,placeholder:"llama3.3:70b, qwen2.5-coder:32b",showCursor:!0}))));if("key"===p)return st.createElement(bO,{title:z,subtitle:"Keys live in ~/.commandcode/auth.json, never in providers.json",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," save"),"empty enter = keyless (local servers)",st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," back")]})},st.createElement(Qe,{borderStyle:"single",borderColor:ER.YELLOW,paddingX:1,width:"100%"},st.createElement(Xe,{color:ER.DIM},"key: "),st.createElement(Qe,{flexGrow:1},st.createElement(TextInput,{value:c,onChange:d,onSubmit:()=>{W()},placeholder:"paste it — or press enter if none is needed",mask:"*",showCursor:!0}))));if("api"===p)return st.createElement(bO,{title:z,subtitle:"What does the endpoint speak?",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"↑/↓")," switch"),st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," continue"),st.createElement(st.Fragment,null,st.createElement(gO,null,"h")," help"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," back")]})},st.createElement(Qe,{flexDirection:"column"},eU.map(e=>st.createElement(Xe,{key:e.value},s===e.value?"❯ ":" ",st.createElement(Xe,{bold:s===e.value},e.label),st.createElement(Xe,{color:ER.DIM}," · ",e.detail)))));if("endpoint"===p){const e=y&&a===y.baseURL;return st.createElement(bO,{title:z,subtitle:endpointSubtitle({prefilledName:e?y.name:void 0,wire:s}),footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," continue"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," back")]})},st.createElement(Qe,{borderStyle:"single",borderColor:ER.YELLOW,paddingX:1,width:"100%"},st.createElement(Xe,{color:ER.DIM},"base URL: "),st.createElement(Qe,{flexGrow:1},st.createElement(TextInput,{value:a,onChange:e=>{l(e),C(void 0),E(void 0)},onSubmit:j,placeholder:endpointPlaceholder(s),showCursor:!0}))),b&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.YELLOW},b)),V)}const K=null===w?0:Math.min(Math.max(0,w-6+1),Math.max(0,$.length-6)),q=$.slice(K,K+6),Y=$.length-(K+q.length);return st.createElement(bO,{title:"Add a provider",subtitle:"Pick a known provider below, or type your own id.",footer:st.createElement(hO,{marginTop:0,hints:[st.createElement(st.Fragment,null,st.createElement(gO,null,"↑/↓")," pick from the list"),st.createElement(st.Fragment,null,st.createElement(gO,null,"enter")," continue"),st.createElement(st.Fragment,null,st.createElement(gO,null,"esc")," close")]})},st.createElement(Qe,{borderStyle:"single",borderColor:ER.YELLOW,paddingX:1,width:"100%"},st.createElement(Xe,{color:ER.DIM},"provider id: "),st.createElement(Qe,{flexGrow:1},st.createElement(TextInput,{value:r,onChange:e=>{o(e),C(void 0),v(null)},onSubmit:U,placeholder:"ollama, work-llm, openrouter…",showCursor:!0}))),V,q.length>0&&st.createElement(Qe,{flexDirection:"column",marginTop:1},q.map((e,t)=>{const n=null!==w&&K+t===w;return st.createElement(Qe,{key:e.id},st.createElement(jN,{isSelected:n}),st.createElement(BN,{isSelected:n,idleColor:ER.DIM},` ${e.id}`),st.createElement(Xe,{color:ER.DIM}," ","· ",e.baseURL))}),(K>0||Y>0)&&st.createElement(Xe,{color:ER.DIM}," ",K>0?`↑ ${K} more · `:"",Y>0?`↓ ${Y} more`:"")))}__name(endpointSubtitle,"endpointSubtitle"),__name(endpointPlaceholder,"endpointPlaceholder"),__name(idStepMatches,"idStepMatches"),__name(AddCustomProviderEntry,"AddCustomProviderEntry"),Gt(),SR();var nU="__add-custom-provider__";async function invalidateHarnessForLaneSwitch(e){e&&await rebuildHarnessSession(e)}function showProviderNotification({setShowProviderNotification:e,providerNotificationTimer:t}){t.current&&clearTimeout(t.current),e(!0),t.current=setTimeout(()=>{e(!1),t.current=null},jM)}async function handleProviderSelect({provider:e,setCurrentProvider:t,setShowProviderSelector:n,setAuthComponentInfo:r,setStatus:o,setShowProviderNotification:s,providerNotificationTimer:i,setShowModelSelector:a,sessionId:l,onActiveModelOrphaned:c,onDiskDefaultOrphaned:d}){if(e===nU)return n(!1),r({provider:e,Component:makeAddCustomProviderEntry({...a?{onOpenModels:__name(()=>a(!0),"onOpenModels")}:{},...l?{sessionId:l}:{}})}),{switched:!1};const u=getCustomProviderModelsSync().find(t=>t.id===e);if(u){const t=await getCustomProviderKeyState(e),o="stored"===t?await getStoredKeyPreview(e):void 0,s=await getConfiguredKeyReference(e);return n(!1),r({provider:e,Component:makeCustomProviderKeyEntry({providerId:u.id,providerName:u.name,keyState:t,keyPreview:o,configuredReference:s,onOpenModels:a?()=>a(!0):void 0,sessionId:l,onActiveModelOrphaned:c,onDiskDefaultOrphaned:d})}),{switched:!1}}const m=getProviderConfig(e),p=m?.authComponent,g=await resolveProviderSelection({provider:e,requiresAuth:m?.requiresAuth,hasAuthFlow:Boolean(p),checkAuth:m?.checkAuth});return"auth-required"===g.status?(p&&r({provider:e,Component:p}),{switched:!1}):"error"===g.status?(o(g.statusMessage),n(!1),{switched:!1}):(t(e),await invalidateHarnessForLaneSwitch(l),n(!1),o(g.statusMessage),showProviderNotification({setShowProviderNotification:s,providerNotificationTimer:i}),{switched:!0})}function handleProviderCancel({setShowProviderSelector:e}){e(!1)}async function handleAuthSuccess({authComponentInfo:e,setAuthComponentInfo:t,setShowProviderSelector:n,setCurrentProvider:r,setStatus:o,setShowProviderNotification:s,providerNotificationTimer:i,sessionId:a}){return e?(t(null),n(!1),r(e.provider),await invalidateHarnessForLaneSwitch(a),o(buildProviderAuthSuccessStatus(e.provider)),showProviderNotification({setShowProviderNotification:s,providerNotificationTimer:i}),{switchedProvider:e.provider}):{switchedProvider:null}}function handleAuthCancel({setAuthComponentInfo:e}){e(null)}__name(invalidateHarnessForLaneSwitch,"invalidateHarnessForLaneSwitch"),__name(showProviderNotification,"showProviderNotification"),__name(handleProviderSelect,"handleProviderSelect"),__name(handleProviderCancel,"handleProviderCancel"),__name(handleAuthSuccess,"handleAuthSuccess"),__name(handleAuthCancel,"handleAuthCancel");var rU=__name(({onSelect:e,onCancel:t,sessionId:n})=>{const[r,o]=st.useState(()=>getCustomProviderModelsSync()),[s,i]=st.useState(()=>getCustomProviderWarningsSync()),[a,l]=st.useState({});st.useEffect(()=>{let e=!0;return(async()=>{const{providers:t}=await refreshCustomProviderModels(n?{sessionId:n}:void 0);if(!e)return;o(t),i(getCustomProviderWarningsSync());const r=await Promise.all(t.map(async e=>[e.id,await getCustomProviderKeyState(e.id)]));e&&l(Object.fromEntries(r))})(),()=>{e=!1}},[n]);const[c,d]=st.useState({});st.useEffect(()=>{let e=!0;return(async()=>{const t=getProviderOptions().filter(e=>isProviderLaneListable({providerId:e.value})),n=await Promise.all(t.map(async e=>{const t=getProviderConfig(e.value);if(!t?.requiresAuth||!t.checkAuth)return[e.value,!0];try{return[e.value,await t.checkAuth()]}catch{return[e.value,!1]}}));e&&d(Object.fromEntries(n))})(),()=>{e=!1}},[]);const u=__name(e=>{const t=c[e];if(void 0===t)return"";if(!t)return"○ not connected";const n=laneModelCount({laneId:e});return n>0?`✓ ${n} ${1===n?"model":"models"}`:"✓"},"laneStatus"),m=__name((e,t)=>{const n=a[e];if("missing"===n)return"○ needs a key";const r=`${t} ${1===t?"model":"models"}`;return void 0===n?r:`✓ ${r}`},"customStatus"),p=[...getProviderOptions().filter(e=>isProviderLaneListable({providerId:e.value})).map(e=>({label:"command-code"===e.value?`${getProviderDisplayName(e.value)} (recommended)`:getProviderDisplayName(e.value),value:e.value,status:u(e.value),notLive:!1===c[e.value]})),...r.map(e=>({label:e.name,value:e.id,status:m(e.id,e.models.length),notLive:"missing"===a[e.id]})),{label:"(BYOK) Add your own provider",value:nU,status:"",notLive:!1}],g=Math.max(42,...p.map(e=>e.label.length+12)),h=new Map(p.map(e=>[e.label,e])),f=__name(t=>{e(t.value)},"handleSelect");return nt((e,n)=>{n.escape&&t()}),st.createElement(bO,{title:"Connect",subtitle:"Connect to AI providers and see currently connected providers",hint:"↑/↓ navigate · enter select · esc close"},st.createElement(SelectInput,{items:p.map(e=>({label:e.label,value:e.value})),onSelect:f,initialIndex:0,indicatorComponent:jN,itemComponent:({isSelected:e,label:t})=>{const n=h.get(t??"");return st.createElement(Qe,null,st.createElement(BN,{isSelected:e,...n?.notLive?{idleColor:ER.DIM}:{}},` ${(t??"").padEnd(g)}`,n?.status.startsWith("✓")?st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.GREEN},"✓"),n.status.slice(1)):n?.status??""))}}),s.length>0&&st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.YELLOW},st.createElement(ProvidersJsonLink,{color:ER.YELLOW})," needs attention —"," ",1===s.length?"one entry":"some entries"," ","did not load as written:"),s.slice(0,3).map(e=>st.createElement(Xe,{key:e,color:ER.DIM}," ",e)),s.length>3&&st.createElement(Xe,{color:ER.DIM}," ","… and"," ",s.length-3," more")))},"ProviderSelector");Gt(),SR();var oU=__name(e=>0===e?"No code changes":`${e} file${e>1?"s":""} changed`,"formatFileCountLabel"),sU=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=dt(()=>[...e].sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),[e]),[o,s]=at(()=>Math.max(0,r.length-1)),[i,a]=at(()=>Math.max(0,r.length-8)),[l,c]=at("checkpoint"),[d,u]=at(null),[m,p]=at(0),g=dt(()=>hasCodeChangesToRestore({sortedCheckpoints:r,selectedCheckpoint:d}),[d,r]),h=dt(()=>g?Ax:Ax.filter(e=>"conversation"===e.mode),[g]);if(ct(()=>{if(r.length>0){const e=r.length-1;s(e),a(Math.max(0,r.length-8))}},[r.length,8]),nt((e,g)=>{if(g.escape)return"mode"===l?(c("checkpoint"),u(null),void p(0)):void n();"checkpoint"===l&&g.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):"checkpoint"===l&&g.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):"checkpoint"===l&&g.return?r.length>0&&(u(r[o]),c("mode"),p(0)):"mode"===l&&g.upArrow?p(e=>Math.max(0,e-1)):"mode"===l&&g.downArrow?p(e=>Math.min(h.length-1,e+1)):"mode"===l&&g.return&&d&&h[m]&&t({messageId:d.messageId,mode:h[m].mode})}),0===r.length)return st.createElement(bO,{title:"Rewind",subtitle:"No checkpoints available. Start a conversation to create checkpoints.",gapAfterHeader:!1,footer:st.createElement(pO,null,"Press ",st.createElement(gO,null,"Esc")," to close")});if("mode"===l&&d)return st.createElement(bO,{title:"Rewind",subtitle:st.createElement(st.Fragment,null,"Restore to:"," ",st.createElement(Xe,{color:ER.WHITE},truncateString2({text:d.prompt||"checkpoint",maxChars:50}))),footer:st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to confirm ·"," ",st.createElement(gO,null,"Esc")," to go back")},st.createElement(Qe,{flexDirection:"column"},h.map((e,t)=>{const n=m===t,r=t===h.length-1;return st.createElement(Qe,{key:e.mode,flexDirection:"column"},st.createElement(Qe,{flexDirection:"row"},st.createElement(Xe,{color:n?TR:void 0},n?`${fL} `:" "),st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{color:n?TR:ER.WHITE},e.label),st.createElement(Xe,{color:ER.DIM},e.description))),!r&&st.createElement(Xe,null," "))})));const f=r.slice(i,i+8);return st.createElement(bO,{title:"Rewind",subtitle:"Select a checkpoint to restore your session",gapAfterHeader:!1,footer:st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to select ·"," ",st.createElement(gO,null,"Esc")," to cancel")},r.length>8&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),st.createElement(Qe,{marginTop:1}),st.createElement(Qe,{flexDirection:"column"},f.map((e,t)=>{const n=i+t,s=o===n,a=e.filesModified.length,l=t===f.length-1,c=n===r.length-1;return st.createElement(Qe,{key:e.messageId,flexDirection:"column"},st.createElement(Qe,{flexDirection:"row"},st.createElement(Xe,{color:s?TR:void 0},s?`${fL} `:" "),st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,{color:s?TR:ER.WHITE},truncateString2({text:e.prompt||"(no prompt)",maxChars:60})),st.createElement(Xe,{color:ER.DIM}," • "),st.createElement(Xe,{color:ER.DIM},getRelativeTimeString({timestamp:e.createdAt}),c&&" (latest)")),st.createElement(Xe,{color:ER.DIM},oU(a)))),!l&&st.createElement(Xe,null," "))})))},"RewindSelector");Gt(),SR();var iU=["default","no-tools","user-only","labeled-only","all"],aU={default:"","no-tools":"[no-tools]","user-only":"[user]","labeled-only":"[labeled]",all:"[all]"};function nextFilterMode(e){const t=iU.indexOf(e);return iU[(t+1)%iU.length]}function previousFilterMode(e){const t=iU.indexOf(e);return iU[(t-1+iU.length)%iU.length]}function buildToolCallMap(e){const t=new Map,n=__name(e=>{for(const r of e){const{entry:e}=r;if("message"===e.type&&"assistant"===e.message.role)for(const n of e.message.content)"tool_use"===n.type&&t.set(n.id,{name:n.name,input:n.input});n(r.children)}},"visit");return n(e),t}function pathArgOf(e){const t=e.file_path??e.path;return"string"==typeof t?toRelativePath(t):"?"}function formatToolBracket(e){const{name:t,input:n}=e;if("read_file"===t){const e=pathArgOf(n),t=n.offset,r=n.limit;return"number"==typeof t&&"number"==typeof r?`[read: ${e}:${t}-${t+r}]`:`[read: ${e}]`}return"write_file"===t?`[write: ${pathArgOf(n)}]`:"edit_file"===t?`[edit: ${pathArgOf(n)}]`:"shell_command"===t?`[bash: ${truncateString2({text:"string"==typeof n.command?n.command:"",maxChars:50})}]`:"grep"===t?`[grep: /${"string"==typeof n.pattern?n.pattern:""}/ in ${"string"==typeof n.directory?toRelativePath(n.directory):"."}]`:"glob"===t?`[glob: ${"string"==typeof n.pattern?n.pattern:""}]`:"read_directory"===t?`[ls: ${pathArgOf(n)}]`:`[${t}: ${truncateString2({text:JSON.stringify(n),maxChars:40})}]`}function messageText5(e){return extractTextFromMessageContent({content:e.content})}function isToolResultOnlyUserMessage2(e){return"user"===e.role&&e.content.length>0&&e.content.every(e=>"tool_result"===e.type)}__name(nextFilterMode,"nextFilterMode"),__name(previousFilterMode,"previousFilterMode"),__name(buildToolCallMap,"buildToolCallMap"),__name(pathArgOf,"pathArgOf"),__name(formatToolBracket,"formatToolBracket"),__name(messageText5,"messageText"),__name(isToolResultOnlyUserMessage2,"isToolResultOnlyUserMessage");var lU=new Set(["label","custom","model_change","effort_change","session_info"]);function isContentlessAssistantMessage(e){return"message"===e.type&&"assistant"===e.message.role&&0===messageText5(e.message).trim().length}function passesFilter(e){const{entry:t,mode:n,isCurrentLeaf:r,hasLabel:o}=e;return"all"===n||("labeled-only"===n?o:"user-only"===n?"message"===t.type&&"user"===t.message.role&&!isToolResultOnlyUserMessage2(t.message)&&messageText5(t.message).trim().length>0:!lU.has(t.type)&&(!(isContentlessAssistantMessage(t)&&!r)&&("no-tools"!==n||"message"!==t.type||"user"!==t.message.role||!isToolResultOnlyUserMessage2(t.message))))}function buildVisibleNodes(e){const{nodes:t,mode:n,currentLeafId:r}=e,o=[];for(const e of t){const t=buildVisibleNodes({nodes:e.children,mode:n,currentLeafId:r});passesFilter({entry:e.entry,mode:n,isCurrentLeaf:e.entry.id===r,hasLabel:void 0!==e.label})?o.push({entry:e.entry,children:t,...void 0!==e.label?{label:e.label}:{},...void 0!==e.labelTimestamp?{labelTimestamp:e.labelTimestamp}:{}}):o.push(...t)}return o}function containsId(e,t){return e.entry.id===t||e.children.some(e=>containsId(e,t))}function reorderActiveFirst(e,t){for(const n of e)n.children=reorderActiveFirst(n.children,t);if(null===t)return e;const n=e.findIndex(e=>containsId(e,t));return n<=0?e:[e[n],...e.slice(0,n),...e.slice(n+1)]}function connectorGlyph(e){return e.folded?"⊞":e.foldable?"⊟":"─"}function buildRowPrefix(e){const{displayIndent:t,gutters:n,connectorVisible:r,isLast:o,folded:s,foldable:i}=e,a=r?t-1:-1,l=[];for(let e=0;e<3*t;e++){const t=Math.floor(e/3),r=e%3,c=n.find(e=>e.position===t);c?l.push(0===r&&c.show?"│":" "):t!==a?l.push(" "):0===r?l.push(o?"└":"├"):1===r?l.push(connectorGlyph({folded:s,foldable:i})):l.push(" ")}const c=s&&!r?"⊞ ":"";return l.join("")+c}function flattenVisibleTree(e){const{roots:t,activePathIds:n,foldedNodes:r}=e,o=[],s=new Map,i=t.length>1;function visit(e){const{node:t,parentId:a,indent:l,justBranched:c,isLast:d,gutters:u}=e,m=t.children.map(e=>e.entry.id);s.set(t.entry.id,m);const p=r.has(t.entry.id),g=t.children.length>0,h=e.showConnector&&!e.isVirtualRootChild,f=i?Math.max(0,l-1):l;if(o.push({id:t.entry.id,entry:t.entry,parentId:a,prefix:buildRowPrefix({displayIndent:f,gutters:u,connectorVisible:h,isLast:d,folded:p,foldable:g}),isActivePath:n.has(t.entry.id),isBranchChild:e.showConnector,hasVisibleChildren:g,...void 0!==t.label?{label:t.label}:{},...void 0!==t.labelTimestamp?{labelTimestamp:t.labelTimestamp}:{}}),p)return;const y=t.children.length>1,S=y||c&&l>0?l+1:l,w=h?[...u,{position:Math.max(0,f-1),show:!d}]:u;t.children.forEach((e,n)=>{visit({node:e,parentId:t.entry.id,indent:S,justBranched:y,showConnector:y,isLast:n===t.children.length-1,gutters:w,isVirtualRootChild:!1})})}return __name(visit,"visit"),t.forEach((e,n)=>{visit({node:e,parentId:null,indent:i?1:0,justBranched:i,showConnector:i,isLast:n===t.length-1,gutters:[],isVirtualRootChild:i})}),{rows:o,visibleChildrenIds:s}}function normalizeRowText(e){return truncateString2({text:e.replace(/[\n\t]+/g," ").trim(),maxChars:200})}function describeRow(e,t){if("message"===e.type){const{message:n}=e;if("user"===n.role){if(isToolResultOnlyUserMessage2(n)){const e=n.content.find(e=>"tool_result"===e.type),r=e?t.get(e.tool_use_id):void 0;return{text:r?formatToolBracket(r):"[tool result]",color:ER.DIM}}return{text:`user: ${normalizeRowText(messageText5(n))}`,color:ER.CYAN}}const r=messageText5(n).trim();return r?{text:`assistant: ${normalizeRowText(r)}`,color:ER.GREEN}:{text:"assistant: (no content)",color:ER.DIM}}return"compaction"===e.type?{text:`[compaction: ${Math.round(e.tokensBefore/1e3)}k tokens]`,color:ER.CYAN}:"branch_summary"===e.type?{text:`[branch summary]: ${normalizeRowText(e.summary)}`,color:ER.YELLOW}:"custom_message"===e.type?{text:`[${e.customType}]: ${normalizeRowText(extractTextFromMessageContent({content:e.content}))}`,color:ER.MAGENTA}:"custom"===e.type?{text:`[custom: ${e.customType}]`,color:ER.DIM}:"model_change"===e.type?{text:`[model: ${e.model}]`,color:ER.DIM}:"effort_change"===e.type?{text:`[effort: ${e.effort}]`,color:ER.DIM}:"label"===e.type?{text:`[label: ${e.label??"(cleared)"}]`,color:ER.DIM}:{text:e.name?`[title: ${e.name}]`:"[title: (empty)]",color:ER.DIM}}__name(isContentlessAssistantMessage,"isContentlessAssistantMessage"),__name(passesFilter,"passesFilter"),__name(buildVisibleNodes,"buildVisibleNodes"),__name(containsId,"containsId"),__name(reorderActiveFirst,"reorderActiveFirst"),__name(connectorGlyph,"connectorGlyph"),__name(buildRowPrefix,"buildRowPrefix"),__name(flattenVisibleTree,"flattenVisibleTree"),__name(normalizeRowText,"normalizeRowText"),__name(describeRow,"describeRow");var cU={compaction:"compaction",branch_summary:"branch summary",session_info:"title",model_change:"model",effort_change:"effort",custom:"custom",custom_message:"custom",label:"label"};function searchableText(e){const{entry:t,label:n,toolCallMap:r}=e,o=[t.type];n&&o.push(n);const s=cU[t.type];if(s&&o.push(s),"message"===t.type)if(o.push(t.message.role),isToolResultOnlyUserMessage2(t.message)){const e=t.message.content.find(e=>"tool_result"===e.type),n=e?r.get(e.tool_use_id):void 0;if(n){o.push(n.name);const e=n.input.command;"string"==typeof e&&o.push(e);const t=n.input.file_path??n.input.path;"string"==typeof t&&o.push(t)}}else o.push(messageText5(t.message));return"branch_summary"===t.type&&o.push(t.summary),"custom_message"===t.type&&o.push(extractTextFromMessageContent({content:t.content})),o.join(" ").toLowerCase()}function matchesSearch(e,t){const n=t.toLowerCase().split(/\s+/).filter(Boolean);return 0===n.length||n.every(t=>e.includes(t))}function formatLabelTimestamp(e,t){const n=new Date(e),r=__name(e=>String(e).padStart(2,"0"),"pad"),o=`${r(n.getHours())}:${r(n.getMinutes())}`;return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?o:n.getFullYear()===t.getFullYear()?`${n.getMonth()+1}/${n.getDate()} ${o}`:`${String(n.getFullYear()).slice(-2)}/${n.getMonth()+1}/${n.getDate()} ${o}`}function previousSegmentStart(e,t,n){let r=t.get(n),o=null;for(;r?.parentId;){const e=t.get(r.parentId);if(!e)break;if(e.isBranchChild)return e.id;o=e.id,r=e}return o}function nextSegmentStart(e,t,n){const r=t.get(n)?.[0];if(void 0===r)return null;let o=r;for(let n=0;n<1e4;n++){const n=e.get(o);if(!n||n.isBranchChild)return o;const r=t.get(o)?.[0];if(void 0===r)return o;o=r}return o}function resolveTargetLocally(e){const t=e.byId.get(e.entryId);return t?"message"===t.type&&"user"===t.message.role&&messageText5(t.message).trim().length>0||"custom_message"===t.type?{targetId:t.parentId}:{targetId:t.id}:{targetId:e.entryId}}function isOnPathLocally(e){if(null===e.ancestorId)return!0;if(null===e.targetId)return!1;let t=e.targetId;const n=new Set;for(;null!==t;){if(t===e.ancestorId)return!0;if(n.has(t))return!1;n.add(t);const r=e.byId.get(t);t=r?r.parentId:null}return!1}__name(searchableText,"searchableText"),__name(matchesSearch,"matchesSearch"),__name(formatLabelTimestamp,"formatLabelTimestamp"),__name(previousSegmentStart,"previousSegmentStart"),__name(nextSegmentStart,"nextSegmentStart"),__name(resolveTargetLocally,"resolveTargetLocally"),__name(isOnPathLocally,"isOnPathLocally");var dU=[{value:"none",label:"No summary"},{value:"summarize",label:"Summarize"},{value:"custom",label:"Summarize with custom prompt"}],uU=__name(({tree:e,currentLeafId:t,initialSelectedId:n,initialFilterMode:r,branchSummarySkipPrompt:o,onSelect:s,onAbortSummary:i,onCancel:a,onLabelChange:l})=>{const[c,d]=at(r),[u,m]=at(""),[p,g]=at(()=>new Set),h=__name(e=>{d(e),g(new Set)},"applyFilterMode"),f=__name(e=>{h(t=>t===e?"default":e)},"toggleFilterMode"),[y,S]=at(!1),[w,v]=at("browse"),[k,C]=at(""),[b,E]=at(""),[T,P]=at(0),[M,x]=at(null),[I,A]=at(0),[R,L]=at(0),[O,D]=at(n??t??void 0),$=useTerminalHeight(),N=dt(()=>{const t=new Map,n=__name(e=>{for(const r of e)t.set(r.entry.id,r.entry),n(r.children)},"visit");return n(e),t},[e]),_=dt(()=>buildToolCallMap(e),[e]),F=dt(()=>{const e=new Set;let n=t;for(;null!==n;){e.add(n);const t=N.get(n);n=t?t.parentId:null}return e},[N,t]),U=dt(()=>reorderActiveFirst(buildVisibleNodes({nodes:e,mode:c,currentLeafId:t}),t),[e,c,t]),{rows:j,visibleChildrenIds:B}=dt(()=>flattenVisibleTree({roots:U,activePathIds:F,foldedNodes:p}),[U,F,p]),W=dt(()=>new Map(j.map(e=>[e.id,e])),[j]),H=dt(()=>u?j.filter(e=>matchesSearch(searchableText({entry:e.entry,label:e.label,toolCallMap:_}),u)):j,[j,u,_]);ct(()=>{if(0===H.length)return void A(0);let e=O;for(;e;){const t=H.findIndex(t=>t.id===e);if(t>=0)return void A(t);e=N.get(e)?.parentId}A(H.length-1)},[H,c,u,N]);const G=H[I]?.id,V=lt(!1);ct(()=>{V.current?G&&D(G):V.current=!0},[G]);const z=$-1,K=Math.max(6,z-10);ct(()=>{L(e=>clampScrollOffset({cursor:I,total:H.length,maxVisible:K,currentOffset:e}))},[I,H.length,K]);const q=H[I],Y=__name(e=>{D(e.entryId),e.summarize?(v("summarizing"),s(e).then(e=>{e.aborted&&v("browse")})):s(e)},"commitSelection"),J=__name(()=>{if(!q)return;D(q.id);const{targetId:e}=resolveTargetLocally({byId:N,entryId:q.id});isOnPathLocally({byId:N,ancestorId:t,targetId:e})||o?Y({entryId:q.id,summarize:!1}):(x(q.id),P(0),v("confirm-summary"))},"handleEnterInBrowse");nt((e,t)=>{if("summarizing"===w)return void(t.escape&&i());if("label"===w)return void(t.escape&&v("browse"));if("custom-prompt"===w)return void(t.escape&&v("confirm-summary"));if("confirm-summary"===w){if(t.escape)return void v("browse");if(t.upArrow)return void P(e=>Math.max(0,e-1));if(t.downArrow)return void P(e=>Math.min(dU.length-1,e+1));if(t.return&&M){const e=dU[T]?.value;"none"===e?(Y({entryId:M,summarize:!1}),v("browse")):"summarize"===e?Y({entryId:M,summarize:!0}):(E(""),v("custom-prompt"))}return}const n=getKeybindings();if(t.escape)return u?void m(""):void a();if(t.upArrow)A(e=>0===H.length?0:(e-1+H.length)%H.length);else if(t.downArrow)A(e=>0===H.length?0:(e+1)%H.length);else if(!t.leftArrow||t.ctrl||t.meta)if(!t.rightArrow||t.ctrl||t.meta){if((keybindingMatches(n,"app.tree.foldOrPrevBranch",e,t)||isWordLeftSequence(e)||(t.ctrl||t.meta)&&t.leftArrow)&&q){if(q.hasVisibleChildren&&!p.has(q.id))return void g(e=>new Set(e).add(q.id));const e=previousSegmentStart(0,W,q.id);if(e&&D(e),e){const t=H.findIndex(t=>t.id===e);t>=0&&A(t)}return}if((keybindingMatches(n,"app.tree.unfoldOrNextBranch",e,t)||isWordRightSequence(e)||(t.ctrl||t.meta)&&t.rightArrow)&&q){if(p.has(q.id))return void g(e=>{const t=new Set(e);return t.delete(q.id),t});const e=nextSegmentStart(W,B,q.id);if(e){D(e);const t=H.findIndex(t=>t.id===e);t>=0&&A(t)}return}if(t.return)J();else if(t.ctrl&&"O"===e||keybindingMatches(n,"app.tree.filter.cycleBack",e,t))h(e=>previousFilterMode(e));else if(keybindingMatches(n,"app.tree.filter.cycle",e,t))h(e=>nextFilterMode(e));else if(keybindingMatches(n,"app.tree.filter.default",e,t))h("default");else if(keybindingMatches(n,"app.tree.filter.noTools",e,t))f("no-tools");else if(keybindingMatches(n,"app.tree.filter.userOnly",e,t))f("user-only");else if(keybindingMatches(n,"app.tree.filter.labeledOnly",e,t))f("labeled-only");else if(keybindingMatches(n,"app.tree.filter.all",e,t))f("all");else{if("L"===e||keybindingMatches(n,"app.tree.label",e,t)){if(!q)return;return C(q.label??""),void v("label")}"T"===e||keybindingMatches(n,"app.tree.labelTime",e,t)?S(e=>!e):t.backspace||t.delete?u&&m(e=>e.slice(0,-1)):!t.ctrl&&!t.meta&&!t.tab&&e&&1===e.length&&e>=" "&&m(t=>t+e)}}else A(e=>Math.min(H.length-1,e+K));else A(e=>Math.max(0,e-K))});const Q=__name(e=>{if(q){const t=e.trim();l({entryId:q.id,label:t.length>0?t:void 0})}v("browse")},"submitLabel"),X=__name(e=>{if(M){const t=e.trim();Y({entryId:M,summarize:!0,...t.length>0?{customInstructions:t}:{}})}},"submitCustomPrompt");if("summarizing"===w)return st.createElement(bO,{title:"/tree",gapAfterHeader:!1},st.createElement(Xe,{color:ER.CYAN},"Summarizing abandoned branch… (Esc to cancel)"));if("confirm-summary"===w)return st.createElement(bO,{title:"/tree",subtitle:"You're leaving work behind on this branch. Summarize it before jumping?",hint:"enter confirm · esc back"},st.createElement(Qe,{flexDirection:"column"},dU.map((e,t)=>st.createElement(Xe,{key:e.value,color:t===T?TR:ER.WHITE,bold:t===T},t===T?`${fL} `:" ",e.label))));if("custom-prompt"===w)return st.createElement(bO,{title:"/tree",subtitle:"Focus instructions for the summary:",gapAfterHeader:!1,hint:"enter confirm · esc back"},st.createElement(TextInput,{value:b,focus:!0,prefix:`${fL} `,prefixColor:"cyan",onChange:E,onSubmit:X}));if("label"===w&&q)return st.createElement(bO,{title:"/tree",subtitle:"Label:",gapAfterHeader:!1,hint:"enter save (empty clears) · esc cancel"},st.createElement(TextInput,{value:k,focus:!0,prefix:`${fL} `,prefixColor:"cyan",onChange:C,onSubmit:Q}));const Z=H.slice(R,R+K),ee=new Date,te=aU[c];return st.createElement(Qe,{flexDirection:"column",paddingLeft:1,width:"100%"},st.createElement(Xe,{color:TR,bold:!0},"/tree"),st.createElement(Qe,{marginBottom:1,width:"100%"},st.createElement(pL,{query:u,resultCount:u?H.length:void 0,placeholder:"Type to search…"})),0===H.length?st.createElement(Qe,{marginBottom:1},st.createElement(D$,{message:"No entries found"})):st.createElement(Qe,{flexDirection:"column"},Z.map((e,t)=>{const n=R+t===I,{text:r,color:o}=describeRow(e.entry,_);return st.createElement(Xe,{key:e.id,backgroundColor:n?KR:void 0,bold:n,wrap:"truncate-end"},n?`${fL} `:" ",st.createElement(Xe,{color:zR},e.prefix),e.isActivePath?st.createElement(Xe,{color:TR},"• "):null,void 0!==e.label?st.createElement(Xe,{color:ER.YELLOW},"[",e.label,"]"," "):null,y&&e.labelTimestamp?st.createElement(Xe,{color:ER.DIM},formatLabelTimestamp(e.labelTimestamp,ee)," "):null,st.createElement(Xe,{color:o},r))})),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"(",0===H.length?0:I+1,"/",H.length,")",te?` ${te}`:"",y?" [+label time]":"")),st.createElement(Qe,{flexDirection:"column"},st.createElement(pO,null,"↑/↓ move · ←/→ page · tab / alt+←/→ branch · shift+L label · shift+T label time"),st.createElement(pO,null,"filters ctrl+d/t/u/l/a · cycle ctrl+o · type to search · rebind via ~/.commandcode/keybindings.json")))},"TreeSelector");Gt(),SR();var mU=[{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."}],pU=['/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"'],gU=__name(({onCancel:e})=>(nt((t,n)=>{n.escape&&e()}),st.createElement(Qe,{flexDirection:"column",paddingLeft:2,paddingRight:2},st.createElement(Qe,{marginBottom:1,flexDirection:"column"},st.createElement(Xe,{bold:!0,color:TR},"Use"),st.createElement(Qe,{paddingLeft:2,flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},'/design <mode> "target or request"'),st.createElement(Xe,{color:ER.DIM},'/design "freeform request" also works. The closest mode is inferred.'))),st.createElement(Qe,{marginBottom:1,flexDirection:"column"},st.createElement(Xe,{bold:!0,color:TR},"Modes"),st.createElement(Qe,{paddingLeft:2,flexDirection:"column"},py.map(e=>st.createElement(Qe,{key:e.name,columnGap:2},st.createElement(Qe,{width:18,flexShrink:0},st.createElement(Xe,{color:ER.CYAN},"/design ",e.name)),st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},e.description)))))),st.createElement(Qe,{marginBottom:1,marginTop:1,flexDirection:"column"},st.createElement(Xe,{bold:!0,color:TR},"Working rules"),st.createElement(Qe,{paddingLeft:2,flexDirection:"column"},mU.map(e=>st.createElement(Qe,{key:e.label,columnGap:2},st.createElement(Qe,{width:16,flexShrink:0},st.createElement(Xe,{color:ER.CYAN},e.label)),st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},e.desc)))))),st.createElement(Qe,{marginBottom:1,marginTop:1,flexDirection:"column"},st.createElement(Xe,{bold:!0,color:TR},"Quick examples:"),st.createElement(Qe,{paddingLeft:2,flexDirection:"column"},pU.map(e=>st.createElement(Xe,{key:e,color:ER.DIM},e)))),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Press Esc to close. Type /design help anytime to return.")))),"DesignGuide");Gt(),SR(),Gt(),Gt();var hU=__name(({error:e,traceId:t})=>st.createElement(Qe,{padding:1},st.createElement(O$,{title:"Error initializing onboarding:"},e,t&&st.createElement(Xe,{color:ER.DIM},"\n\n","Trace ID: ",t),"\n\n","Continuing without onboarding...")),"OnboardingError");Gt(),Gt();var fU=__name(()=>st.createElement(Xe,null,"Skip"),"SkipOptionText"),yU=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[o,s]=at(1);return nt((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())}),st.createElement(Qe,{flexDirection:"column",borderStyle:"single",borderColor:PR.TEXT,paddingX:1,paddingY:0},st.createElement(Xe,{color:PR.TEXT,bold:!0},"Build Your Coding Taste"),st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Xe,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),st.createElement(Qe,{marginTop:1},st.createElement(Xe,null,"Analyze"," ",1===e?"that session":"those sessions"," ","to build your coding taste package?"))),st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,{color:1===o?PR.TEXT:ER.GRAY},1===o?gt.pointer:" "," 1. Yes, learn (recommended)")),st.createElement(Qe,null,st.createElement(Xe,{color:2===o?PR.TEXT:ER.GRAY},2===o?gt.pointer:" "," 2."," ",st.createElement(fU,null)))),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"↑↓ · "),st.createElement(Xe,{color:WR.CODE},"enter"),st.createElement(Xe,{color:ER.DIM}," ok · "),st.createElement(Xe,{color:WR.CODE},"esc"),st.createElement(Xe,{color:ER.DIM}," skip · "),st.createElement(Xe,{color:WR.CODE},"n"),st.createElement(Xe,{color:ER.DIM}," never")))},"ImportChoice"),SU=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?st.createElement(yU,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?st.createElement(tN,{onComplete:r,onCancel:i,onError:o,onErrorDismiss:s}):null,"OnboardingStepRenderer"),wU=__name(({onComplete:e,autoLearn:t=!1})=>{ct(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,traceId:o,isLoading:s}=B$({autoLearn:t,onShouldSkip:e}),{step:i,setStep:a}=W$({conditions:n,autoLearn:t}),{handleImportStart:l,handleImportComplete:c,handleImportError:d,handleErrorDismiss:u,handleSkip:m}=H$({onStepChange:__name(e=>{a(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${i}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),s?null:r?st.createElement(hU,{error:r,traceId:o}):"done"===i||"asking"!==i&&"learning"!==i?null:st.createElement(SU,{step:i,conditions:n,onImportStart:l,onImportComplete:c,onImportError:d,onErrorDismiss:u,onSkip:m})},"TasteOnboarding");Gt(),SR();var vU=[{label:"Auto theme",value:"auto",description:"Automatically detect your terminal background and use light or dark to match."},{label:"Dark theme",value:"dark",description:"Use purple accent colors on dark backgrounds."},{label:"Light theme",value:"light",description:"Use higher-contrast colors for white terminal backgrounds."}];function labelFor(e,t){return"auto"===e.value?`${e.label} (${t})`:e.label}__name(labelFor,"labelFor");var kU=__name(({onSelect:e,onCancel:t})=>{const[n]=at(()=>getCliTheme()),[r]=at(()=>resolveCliTheme("auto")),o=dt(()=>vU.map(e=>({...e,label:labelFor(e,r)})),[r]),s=__name(t=>{const n=o.find(e=>e.value===t.value)?.value;n&&e(n)},"handleSelect");nt((e,n)=>{n.escape&&t()});const i=o.findIndex(e=>e.value===n),a=o.find(e=>e.value===n)?.label??`${n} theme`;return st.createElement(bO,{title:"Select a theme",subtitle:`Choose the color palette for this terminal · currently ${a}`,footer:st.createElement(Xe,{italic:!0,color:ER.DIM},"Press ",st.createElement(Xe,{bold:!0},"Esc")," to cancel")},st.createElement(SelectInput,{items:o,onSelect:s,initialIndex:i>=0?i:0,indicatorComponent:jN,itemComponent:({isSelected:e,label:t})=>{const r=o.findIndex(e=>e.label===t),s=o[r],i=s?.value===n,a=r===o.length-1;return st.createElement(Qe,{flexDirection:"column",marginBottom:a?0:1},st.createElement(Qe,null,st.createElement(BN,{isSelected:e,isActive:i,idleColor:ER.DIM},` ${r+1}. ${s?.label??t}`),i&&st.createElement(HN,null)),st.createElement(GN,null,s?.description??""))}}))},"ThemeSelector"),CU=it(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:o,setStaticKey:s,transcriptMode:i,tasteOnboardingEntryId:a,autoLearnTaste:l,showTasteSkipBanner:c,showZdrNotice:d,modelNotice:u,retryAttempt:m,input:p,setInput:g,fileSearchQuery:h,setFileSearchQuery:f,showFileList:y,setShowFileList:S,showProviderSelector:w,showModelSelector:v,showEffortSelector:k,showMemorySelector:C,showMcpManager:b,showAgentsConfig:E,showRewindSelector:T,showTreeSelector:P,treeFilterMode:M,treeBranchSummarySkipPrompt:x,showLoginOverlay:I,showUsageOverlay:A,showAddDirModal:R,showCompactModeSelector:L,showThemeSelector:O,authComponentInfo:D,status:$,currentProvider:N,currentModel:_,showProviderNotification:F,shareInfo:U,showShareNotification:j,unshareNotificationMessage:B,updateStatus:W,updateFailedInfo:H,creditWarning:G,permissionMode:V,hintMessage:z,pendingExitKey:K,interactionTokens:q,contextUsage:Y,tasteLearningOn:J,historyManagerRef:Q,executionState:X,sessionId:Z,onSubmit:ee,onCommand:te,onToggleAutoAccept:ne,onResetPendingExitKey:re,onDoubleEscapeEmpty:oe,onTasteOnboardingComplete:se,permissionPanel:ie,questionPanel:ae,designSuggestionPanel:le,onRewindSelect:ce,onRewindCancel:de,onTreeSelect:ue,onTreeCancel:me,onTreeLabel:pe,onTreeAbortSummary:ge,onLoginComplete:he,onLoginCancel:fe,setShowProviderSelector:ye,setShowModelSelector:Se,setShowEffortSelector:we,setShowMemorySelector:ve,setShowMcpManager:ke,setShowAgentsConfig:Ce,setShowAddDirModal:be,setShowUsageOverlay:Ee,handleProviderSelect:Te,handleProviderCancel:Pe,handleModelSelect:Me,handleModelCancel:xe,handleCompactModeSelect:Ie,handleCompactModeCancel:Ae,handleThemeSelect:Re,handleThemeCancel:Le,handleAuthSuccess:Oe,handleAuthCancel:De,showDesignGuide:$e,setShowDesignGuide:Ne}){const _e=dt(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Fe=ut(()=>Ne(!1),[Ne]),Ue=useTerminalWidth(),[je,Be]=at(!1),[We,He]=at(!1),Ge=lt(null);Ge.current=r?Ge.current??Date.now():null;const Ve=dt(()=>"off"===i?_e:projectTranscriptWindow({feed:_e,mode:i}),[_e,i]),ze=dt(()=>"off"===i?0:Math.max(0,_e.length-Ve.length),[_e.length,Ve.length,i]),Ke=dt(()=>0===ze?Ve:Ve.filter(e=>"user"!==e.role),[Ve,ze]),qe=ut(()=>Ce(!1),[Ce]),Ye=ut(()=>ve(!1),[ve]),Je=ut(()=>ke(!1),[ke]),Ze=ut(()=>be(!1),[be]),et=ut(()=>Se(!0),[Se]),tt=ut(()=>we(!1),[we]),nt=ut(()=>{hardResetForResize(),s(e=>e+1)},[s]),rt=!("off"!==i||ie||ae||le||w||v||k||D||C||b||E||T||P||I||A||R||L||O||$e||a),ot=k$(Z),it=ot?ot.getEffort():null;return st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(DF,{staticKey:o,feed:Ke,showHeader:!0,expandedToolOutput:"off"!==i,currentModel:_,currentEffort:it,currentProvider:N,hiddenCount:ze}),a&&st.createElement(wU,{onComplete:se,autoLearn:l}),c&&st.createElement(TasteSkipMessage,null),d&&st.createElement(ZdrPausedMessage,null),u&&st.createElement(ModelNoticeMessage,{text:u}),t.map(e=>e.metadata?.isAgent?st.createElement(NF,{key:e.id,entry:e}):st.createElement(Qe,{key:e.id,marginBottom:1,width:"90%"},st.createElement(FeedEntryView,{entry:e,expandedToolOutput:"off"!==i}))),st.createElement(RetryMessage,{attempt:m}),"off"===i&&!a&&!We&&st.createElement(TodoPanel,{active:r}),le,ae,ie,"off"!==i&&st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},"─".repeat(Ue))),st.createElement(Qe,{paddingRight:1},st.createElement(Xe,{backgroundColor:AR.BG,color:AR.FG,bold:!0},`${wL}DETAILED TRANSCRIPT${wL}`),st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{bold:!0},"ctrl+o"),st.createElement(Xe,{color:ER.DIM}," to toggle"),st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{bold:!0},NE?"ctrl+y":"ctrl+e"),st.createElement(Xe,{color:ER.DIM}," ","to"," ","limited"===i?"show all":"collapse"),st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{bold:!0},"esc"),st.createElement(Xe,{color:ER.DIM}," to exit"))),rt&&st.createElement(st.Fragment,null,st.createElement(BackgroundTasksPanel,{onExpandedChange:Be}),st.createElement(TodosManagerPanel,{sessionId:Z,onExpandedChange:He}),st.createElement(vF,{queuedMessages:n,sessionId:Z,isProcessing:r,processingStartedAt:Ge.current,executionState:X,status:$,input:p,setInput:g,onSubmit:ee,showFileList:y,setShowFileList:S,fileSearchQuery:h,setFileSearchQuery:f,onCommand:te,outputTokens:q,contextUsage:Y,tasteLearningOn:J,shareInfo:U,showShareNotification:j,unshareNotificationMessage:B,updateStatus:W,updateFailedInfo:H,creditWarning:G,currentProvider:N,currentModel:_,showProviderInfo:F,permissionMode:V,onToggleAutoAccept:ne,hintMessage:z,historyManager:Q.current,pendingExitKey:K,onResetPendingExitKey:re,onDoubleEscapeEmpty:oe,retryAttempt:m,onAltP:et,renderKey:o,inputActive:!je&&!We,inactiveHint:We?"Todos focused · ↑/↓ to select · c to complete · x to remove · a all done · Esc to go back to feed":void 0})),w&&st.createElement(Qe,{marginY:1},st.createElement(rU,{onSelect:Te,onCancel:Pe,sessionId:Z})),v&&st.createElement(Qe,{marginY:1},st.createElement(M_,{onSelect:Me,onCancel:xe,currentModel:_,currentProvider:N,refreshBanner:nt,sessionId:Z})),k&&st.createElement(Qe,{marginY:1},st.createElement(KF,{currentModel:_,sessionId:Z,onClose:tt,refreshBanner:nt})),$e&&st.createElement(Qe,{marginY:1},st.createElement(gU,{onCancel:Fe})),L&&st.createElement(Qe,{marginY:1},st.createElement(X_,{onSelect:Ie,onCancel:Ae})),O&&st.createElement(Qe,{marginY:1},st.createElement(kU,{onSelect:Re,onCancel:Le})),E&&st.createElement(Qe,{marginY:1},st.createElement(G_,{onCancel:qe})),C&&st.createElement(Qe,{marginY:1},st.createElement(EF,{onClose:Ye})),b&&st.createElement(Qe,{marginY:1},st.createElement(bF,{onClose:Je,mcp:k$(Z)?.mcp})),T&&k$(Z)&&st.createElement(Qe,{marginY:1},st.createElement(sU,{checkpoints:[...k$(Z).listCheckpoints()],onSelect:ce,onCancel:de})),P&&k$(Z)&&st.createElement(Qe,{marginY:1},st.createElement(uU,{tree:k$(Z).getSessionTree(),currentLeafId:k$(Z).getSessionLeafId(),initialFilterMode:M,branchSummarySkipPrompt:x,onSelect:ue,onAbortSummary:ge,onCancel:me,onLabelChange:pe})),D&&st.createElement(Qe,{marginY:1},st.createElement(D.Component,{onSuccess:Oe,onCancel:De})),I&&st.createElement(Qe,{marginY:1},st.createElement(kF,{onComplete:he,onCancel:fe})),R&&st.createElement(Qe,{marginY:1},st.createElement(k_,{onClose:Ze})))},"MainView"));function useFeatureModelCatalog(){const[e,t]=at(()=>getCachedBillingContext());ct(()=>{if(e)return;let n=!0;return getBillingContext().then(e=>{n&&t(e)}),()=>{n=!1}},[e]);const n=useCustomModelsReady(),r=dt(()=>buildCatalogModelPickerGroups(),[n]),o=dt(()=>filterModelPickerGroupsByPlan({groups:r,billing:e}),[r,e]),s=dt(()=>flattenModelPickerGroups(o).map(e=>({id:e.model.id,label:getModelDisplayName(e.model.id)})),[o]);return{groups:o,catalog:s,resolved:null!==e}}Gt(),Gt(),SR(),Gt(),SR(),__name(useFeatureModelCatalog,"useFeatureModelCatalog"),Gt(),SR();var bU=["Listing only models with a zero-data-retention upstream."];function wrappedRowCount(e){const t=Math.max(1,e.width),n=e.text.split(/\s+/).filter(Boolean);if(0===n.length)return 1;let r=1,o=0;for(const e of n){if(e.length>t){o>0&&(r+=1),r+=Math.ceil(e.length/t)-1,o=e.length%t||t;continue}const n=0===o?e.length:e.length+1;o+n<=t?o+=n:(r+=1,o=e.length)}return r}function zdrBannerRowCount(e){return bU.reduce((t,n)=>t+wrappedRowCount({text:n,width:e}),0)+1}function narrowGroups(e){return e.groups.map(t=>({...t,models:t.models.filter(e.accepts)})).filter(e=>e.models.length>0)}__name(wrappedRowCount,"wrappedRowCount"),__name(zdrBannerRowCount,"zdrBannerRowCount"),__name(narrowGroups,"narrowGroups");var EU=__name(({featureLabel:e,defaultLabel:t,currentModelId:n,modelFilter:r,onPick:o,onBack:s})=>{const[i,a]=at(""),{groups:l,resolved:c}=useFeatureModelCatalog(),d=isCmdZdrEnabled(),u=dt(()=>r||d?narrowGroups({groups:l,accepts:__name(e=>!(r&&!r(e)||d&&!modelSupportsZdr(e.id)),"accepts")}):l,[l,r,d]),m=dt(()=>filterModelPickerGroups(u,i),[u,i]),p=dt(()=>getModelLabelColumnWidth(u.flatMap(e=>e.models),{showDefaultBadge:!1}),[u]),g=dt(()=>[{kind:"reset"},...flattenModelPickerGroups(m).map(e=>({kind:"model",providerId:e.providerId,model:e.model}))],[m]),h=dt(()=>{if(!n)return 0;const e=g.findIndex(e=>"model"===e.kind&&e.model.id===n);return e>=0?e:0},[g,n]),{cursor:f}=useListNavigation({items:g,initialIndex:h,searchCursorIndex:1,searchQuery:i,onSearchChange:a,onSelect:__name(e=>{c&&o("reset"===e.kind?void 0:e.model.id)},"onSelect"),onCancel:s}),[y,S]=at(0),w=useTerminalHeight(),v=useTerminalWidth(),k=w-1,C=d?zdrBannerRowCount(v):0,b=Math.max(4,k-13-C-2*m.length);ct(()=>{S(e=>clampScrollOffset({cursor:f,total:g.length,maxVisible:b,currentOffset:e}))},[f,g.length,b]);const E=y,T=y+b,P=0===E,M=windowModelGroups({groups:m,firstSectionBase:1,windowStart:E,windowEnd:T}),x=g.length>b;return st.createElement(bO,{title:`${e} › select model`,subtitle:st.createElement(st.Fragment,null,"Pick a model for this task, or reset it to the default."," ",createOSC8Link("https://commandcode.ai/docs/troubleshooting/faqs#why-do-i-see-small-background-requests","Why background requests?",!1)),footer:st.createElement(Xe,{italic:!0,color:ER.DIM},"type to search · ↑/↓ navigate · enter select",i?" · esc to clear":" · esc back")},d&&st.createElement(Qe,{marginBottom:1,flexDirection:"column"},bU.map(e=>st.createElement(Xe,{key:e,color:ER.YELLOW},e))),st.createElement(Qe,{marginBottom:2,flexDirection:"column",width:"100%"},st.createElement(pL,{query:i,resultCount:i?g.length-1:void 0,placeholder:"Type to search models..."})),c?st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"column"},P&&st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{bold:!0,dimColor:!0},"Default"),st.createElement(Qe,null,st.createElement(Xe,{backgroundColor:0===f?KR:void 0,color:n?ER.WHITE:ER.GREEN},t," "),!n&&st.createElement(Xe,{color:ER.GREEN},gt.tick))),M.map(({group:e,groupWindow:t},r)=>st.createElement(Qe,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:0!==r||P?1:0},st.createElement(Xe,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>st.createElement(E_,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===f,isCurrent:r.id===n,showProviderLabel:!1,showDefaultBadge:!1,labelColumnWidth:p}))))),x&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",E+1,"–",Math.min(T,g.length)," of"," ",g.length,E>0?" · ↑ more":"",T<g.length?" · ↓ more":""))):st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},"Loading available models…")))},"FeatureModelPicker"),TU="Taste learning is off on BYOK models. Switch to a Command Code model to change it.";function isTasteRow(e){return"taste-learning"===e.id||e.id===wp}function clampDescriptionLines(e){const t=Math.max(e.width,10),{maxLines:n}=e,r=e.text.trim().split(/\s+/).filter(Boolean);if(0===r.length||n<=0)return[];const o=[];let s="",i=0,a=!1;for(;i<r.length;){let e=r[i];e.length>t&&(r.splice(i,1,e.slice(0,t),e.slice(t)),e=r[i]);const l=s?`${s} ${e}`:e;if(l.length<=t)s=l,i+=1;else if(o.push(s),s="",o.length===n){a=!0;break}}if(!a)return s&&o.push(s),o;const l=o[n-1];return o[n-1]=l.length>=t?`${l.slice(0,t-1)}…`:`${l}…`,o}function formatSettingValue(e){if(void 0!==e.displayValue)return e.displayValue;if("boolean"===e.kind)return!0===e.currentValue?"Enabled":"Disabled";const t=(e.options??[]).find(t=>t.value===e.currentValue);return t?t.label:String(e.currentValue)}function startsNewGroup(e,t){return 0===t||e[t-1]?.group!==e[t]?.group}__name(isTasteRow,"isTasteRow"),__name(clampDescriptionLines,"clampDescriptionLines"),__name(formatSettingValue,"formatSettingValue"),__name(startsNewGroup,"startsNewGroup");var PU=__name(({onClose:e,staticKey:t,loadTasteStatus:n})=>{const[r,o]=at([]),s=isByok({model:getConfiguredModel()}),[i,a]=at(!0),[l,c]=at(""),[d,u]=at(null),{catalog:m}=useFeatureModelCatalog(),p=ut(()=>listConfigSettings({modelCatalog:m,isByok:isByok}).then(e=>o(e)),[m]);ct(()=>{let e=!0;return listConfigSettings({modelCatalog:m,isByok:isByok}).then(t=>{e&&o(t)}).finally(()=>{e&&a(!1)}),()=>{e=!1}},[m]);const g=dt(()=>filterConfigSettings({settings:r,query:l}),[r,l]),h=dt(()=>r.reduce((e,t)=>Math.max(e,t.label.length),0)+2,[r]),f=__name((e,t)=>{"theme"!==e.id||"string"!=typeof t?"taste-learning"!==e.id&&e.id!==wp||n():applyTuiTheme(resolveCliTheme(t))},"applyLiveSideEffect"),y=__name(async e=>{if(e.featureModelKey)return void u(e);const t=nextSettingValue(e),n=r;o(n=>n.map(n=>n.id===e.id?{...n,currentValue:t}:n));try{await updateConfigSetting({id:e.id,value:t}),f(e,t)}catch{o(n)}},"selectSetting"),S=__name(async(e,t)=>{try{await updateConfigSetting({id:e.id,value:t??Pp}),await p()}catch{}u(null)},"pickFeatureModel"),{cursor:w,error:v,setError:k}=useListNavigation({items:[...g],onSelect:__name(e=>{y(e)},"onSelect"),onReset:__name(e=>{C(e)},"onReset"),onCancel:e,searchQuery:l,onSearchChange:c,isActive:!i&&null===d,validate:__name(e=>s&&isTasteRow(e)?TU:e.locked?`${e.label} is locked by settings.local.json — edit that file to change it.`:null,"validate")}),C=__name(async e=>{if(s&&isTasteRow(e))return void k(TU);if(e.locked)return void k(`${e.label} is locked by settings.local.json — edit that file to change it.`);if(e.currentValue===e.defaultValue)return void k(`${e.label} is already at its default.`);if(e.featureModelKey){try{await updateConfigSetting({id:e.id,value:e.defaultValue}),await p()}catch{}return}const t=r;o(t=>t.map(t=>t.id===e.id?{...t,currentValue:e.defaultValue}:t));try{await updateConfigSetting({id:e.id,value:e.defaultValue}),f(e,e.defaultValue)}catch{o(t)}},"resetSetting"),b=useTerminalWidth(),E=g[w],T=dt(()=>E?clampDescriptionLines({text:E.description,width:Math.max(20,b-2),maxLines:2}):[],[E,b]);if(d?.featureModelKey){const e=ap.find(e=>e.key===d.featureModelKey),t="string"==typeof d.currentValue&&d.currentValue!==Pp?d.currentValue:void 0;return st.createElement(EU,{featureLabel:d.label,defaultLabel:e?getFeatureDefaultLabel({meta:e,getModelDisplayName:getModelDisplayName,zdrEnabled:isCmdZdrEnabled()}):"",currentModelId:t,modelFilter:"vision"===d.featureModelKey?e=>modelSupportsVision(e.id):void 0,onBack:()=>u(null),onPick:e=>{S(d,e)}})}return i?st.createElement(bO,{key:t,title:"Settings",gapAfterHeader:!1},st.createElement(A$,{label:"Loading settings"})):st.createElement(bO,{title:"Settings",footer:st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(Qe,{flexDirection:"column",height:2,width:"100%"},T.map((e,t)=>st.createElement(Xe,{key:t,color:ER.DIM,wrap:"truncate-end"},e))),st.createElement(hO,{marginTop:0,hints:["type to filter","↑↓ navigate","enter to change","tab to reset",l?"esc to clear":"esc to close"]}))},st.createElement(Qe,{marginBottom:1,flexDirection:"column",width:"100%"},st.createElement(pL,{query:l,resultCount:l?g.length:void 0,placeholder:"Search settings..."})),0===g.length?st.createElement(Qe,{marginY:1},st.createElement(Xe,{color:ER.GRAY},'No settings match "',l,'"')):st.createElement(Qe,{flexDirection:"column"},g.map((e,t)=>{const n=t===w?KR:void 0,r=!l&&startsNewGroup(g,t);return st.createElement(st.Fragment,{key:e.id},r&&st.createElement(Qe,{marginTop:0===t?0:1},st.createElement(Xe,{color:ER.DIM,bold:!0},e.group)),st.createElement(Qe,null,st.createElement(Xe,{color:e.locked||s&&isTasteRow(e)?ER.DIM:ER.WHITE,backgroundColor:n},e.label.padEnd(h)),st.createElement(Xe,{color:e.locked||s&&isTasteRow(e)?ER.DIM:ER.GREEN,backgroundColor:n},formatSettingValue(e)),(e.locked||s&&isTasteRow(e))&&st.createElement(Xe,{color:ER.DIM,backgroundColor:n},s&&isTasteRow(e)?" (unavailable on BYOK)":" (locked by settings.local.json)")))})),v&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.GRAY},v)))},"SettingsConfig");function SettingsConfigView({staticKey:e,onClose:t,loadTasteStatus:n}){return st.useEffect(()=>{hardResetForResize()},[]),st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(PU,{onClose:t,staticKey:e,loadTasteStatus:n})))}function categoryColor(e){return isFatalWarningCategory(e)?ER.RED:ER.YELLOW}__name(SettingsConfigView,"SettingsConfigView"),Gt(),Gt(),SR(),Gt(),Gt(),SR(),__name(categoryColor,"categoryColor");var MU=formatSkillWarningsAsMarkdown;async function copyAllWarnings(e,t){try{const{writeClipboardText:n}=await Promise.resolve().then(()=>(SR(),yR));if(!await n(MU(e)))throw new Error("clipboard unavailable");const r=e.length;t({text:`Copied ${r} issue${1===r?"":"s"} to clipboard`,color:ER.GREEN})}catch{t({text:"Clipboard write failed",color:ER.YELLOW})}}__name(copyAllWarnings,"copyAllWarnings");var xU=__name(({warnings:e,onClose:t,isActive:n=!0})=>{const r=groupWarnings(e),o=e.length>0,[s,i]=at(null),a=lt(null),l=lt(!0);ct(()=>()=>{l.current=!1,a.current&&(clearTimeout(a.current),a.current=null)},[]);const c=__name(e=>{l.current&&(a.current&&clearTimeout(a.current),i(e),a.current=setTimeout(()=>{l.current&&(i(null),a.current=null)},3e3))},"showStatus");return nt((n,r)=>r.escape||" "===n&&o?(RL(),void t()):void("c"===n&&o&&copyAllWarnings(e,c)),{isActive:n}),st.createElement(Qe,{flexDirection:"column",paddingX:0,width:"100%"},st.createElement(Qe,null,st.createElement(Xe,{color:TR,bold:!0},"Skills"," "),st.createElement(Xe,{color:ER.DIM},"› "),st.createElement(Xe,{color:TR,bold:!0},"Skipped"," "),st.createElement(Xe,{color:ER.WHITE},e.length)),o&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},"Press c to copy all issues")),o?st.createElement(Qe,{flexDirection:"column"},r.map(e=>st.createElement(Qe,{key:e.category,flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,{color:categoryColor(e.category)},e.category)),e.items.map(e=>st.createElement(Qe,{key:e.path,flexDirection:"column",marginBottom:1},st.createElement(Qe,{paddingLeft:2},st.createElement(cL,{url:g(e.path).href,text:skillIdentifier(e.path),color:ER.WHITE})),st.createElement(Qe,{paddingLeft:4},st.createElement(Xe,{color:ER.WHITE},e.reason))))))):st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"No issues — every skill loaded.")),s&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:s.color},s.text)),st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},o?"c copy all issues · esc back to skills":"esc back to skills")))},"SkillsConfigIssues"),IU=[],AU=__name(({warnings:e=IU,onClose:t})=>{const[n,r]=at("list");return nt((o,s)=>{"list"===n&&(s.escape&&t?t():" "===o&&!s.ctrl&&!s.meta&&e.length>0&&r("issues"))},{isActive:"list"===n}),"issues"===n?st.createElement(xU,{warnings:e,onClose:()=>r("list"),isActive:!0}):st.createElement(Qe,{flexDirection:"column",paddingX:0,width:"100%"},st.createElement(Qe,null,st.createElement(Xe,{color:TR,bold:!0},"Skills"),e.length>0&&st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:ER.YELLOW},e.length," skipped"))),st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.DIM},"No skills found")),st.createElement(Xe,{color:ER.DIM},"Create skills in:"),st.createElement(Xe,{color:ER.DIM}," ","~/",".commandcode","/","skills","/ (user)"),st.createElement(Xe,{color:ER.DIM}," ","~/.agents/","skills","/ (user, .agents)"),st.createElement(Xe,{color:ER.DIM}," ",".commandcode","/","skills","/ (project)"),st.createElement(Xe,{color:ER.DIM}," ",".agents/","skills","/ (project, .agents)"),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},e.length>0&&"space to view issues · ","Press ",st.createElement(Xe,{bold:!0},"Esc")," to close")))},"SkillsConfigEmpty");Gt();var RU=__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");Gt();var LU=__name(({title:e,subtitle:t,skills:n,baseIndex:r,cursor:o,disabled:s})=>st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Qe,null,st.createElement(Xe,{color:$R,bold:!0},e," "),st.createElement(Xe,{color:$R},t)),n.map((e,t)=>{const n=r+t===o,i=s.has(e.label),a=n?KR:void 0;return st.createElement(Qe,{key:e.filePath},st.createElement(Xe,{color:i?ER.DIM:ER.GREEN,backgroundColor:a},i?"[off] ":"[on] "),st.createElement(Xe,{color:i?ER.DIM:ER.WHITE,backgroundColor:a},e.label),e.fromAgents&&st.createElement(Xe,{color:ER.DIM,backgroundColor:a}," [.agents]"),st.createElement(Xe,{color:ER.DIM,backgroundColor:a}," · ~",e.estimatedTokens," tokens "))})),"SkillSection"),OU=__name(({onClose:e})=>{const[t,n]=at([]),[r,o]=at([]),[s,i]=at(!0),[a,l]=at(null),[c,d]=at(""),[u,m]=at(new Set),[p,g]=at(new Map),[h,f]=at(!1),[y,S]=at(null),[w,v]=at("list"),[k,C]=at(0),b=useTerminalHeight(),E=lt(!1);ct(()=>{__name(async()=>{try{const e=await loadCommandSkillPickerState();n([...e.skills]),o([...e.warnings]),m(new Set(e.disabled)),g(new Map(e.disabledScopes)),f(e.noProjectRoot)}catch(e){l(e instanceof Error?e.message:"Failed to load skills")}finally{i(!1)}},"load")()},[]);const T=dt(()=>filterSkillPickerRowsForQuery({rows:t,searchQuery:c}),[t,c]),P=T.sections.project,M=T.sections.user,x=T.sections.bundled,I=T.rows,A=b-1,R=(P.length>0?1:0)+(M.length>0?1:0)+(x.length>0?1:0),L=Math.max(4,A-14-2*R),O=__name(async e=>{if(E.current)return;const t=getSkillTogglePolicy({skillName:e.label,disabled:u,disabledScopes:p,noProjectRoot:h});if(!t.allowed)return void S(t.notice);E.current=!0;const n=new Set(u);t.enabling&&n.delete(e.label),t.enabling||n.add(e.label),m(n),S(null);try{const n=await setCommandSkillEnabled(e.label,t.enabling),r=new Map(p);t.enabling&&r.delete(e.label),t.enabling||r.set(e.label,n),g(r),S(getSkillPickerNoProjectWriteNotice(n))}catch(e){m(u),S(`Failed to save: ${e instanceof Error?e.message:String(e)}`)}finally{E.current=!1}},"toggleSkill");ct(()=>{"issues"===w&&d("")},[w]);const D="list"===w&&t.length>0,{cursor:$}=useListNavigation({items:I,onSelect:O,onCancel:e,searchQuery:c,onSearchChange:d,initialIndex:0,isActive:D});if(ct(()=>{C(e=>clampScrollOffset({cursor:$,total:I.length,maxVisible:L,currentOffset:e}))},[$,I.length,L]),nt((t,n)=>{if(!n.tab)return;const r=I[$];r&&(async()=>{try{await It([{file:r.filePath,line:1}]),e()}catch(e){if(e instanceof Error&&e.message.includes("$EDITOR environment variable"))return void l(RU());l(e instanceof Error?e.message:"Failed to open skill in editor")}})()},{isActive:D}),nt((e,n)=>{"list"===w&&0!==t.length&&" "===e&&!n.ctrl&&!n.meta&&r.length>0&&0===c.length&&v("issues")},{isActive:"list"===w&&t.length>0}),s)return st.createElement(bO,{title:"Skills",gapAfterHeader:!1},st.createElement(Xe,{color:ER.DIM},"Loading skills..."));if(a)return st.createElement(bO,{title:"Skills",titleColor:ER.RED,gapAfterHeader:!1,footer:st.createElement(Xe,{italic:!0,color:ER.DIM},"Press ",st.createElement(Xe,{bold:!0},"Esc")," to close")},st.createElement(Xe,{color:ER.DIM},a));if(0===t.length)return st.createElement(AU,{warnings:r,onClose:e});if("issues"===w)return st.createElement(xU,{warnings:r,onClose:()=>v("list"),isActive:!0});const N=t.filter(e=>u.has(e.label)).length,_=k,F=k+L,U=sliceSectionForWindow({section:P,sectionBase:0,windowStart:_,windowEnd:F}),j=sliceSectionForWindow({section:M,sectionBase:P.length,windowStart:_,windowEnd:F}),B=sliceSectionForWindow({section:x,sectionBase:P.length+M.length,windowStart:_,windowEnd:F}),W=I.length>L;return st.createElement(bO,{title:"Skills",titleSuffix:st.createElement(st.Fragment,null," ",t.length," skill",1===t.length?"":"s",N>0&&st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:ER.YELLOW},N," off")),r.length>0&&st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:ER.YELLOW},r.length," skipped"))),subtitle:getSkillPickerNoProjectNotice(h),footer:st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,{italic:!0,color:ER.DIM},"type to search · ↑/↓ navigate · enter to toggle · tab to edit",r.length>0&&!c&&" · space to view issues",c?" · esc to clear":" · esc to close"),st.createElement(Xe,{color:ER.DIM},"add skills:"," ",st.createElement(Xe,{color:ER.CYAN},getBinaryCommand()," skills add ","<owner/repo>")))},st.createElement(Qe,{marginBottom:1,flexDirection:"column",width:"100%"},st.createElement(pL,{query:c,resultCount:c?I.length:void 0,placeholder:"Type to search skills..."})),0===I.length?st.createElement(Qe,{marginY:1},st.createElement(Xe,{color:ER.GRAY},'No skills match "',c,'"')):st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"column"},U.rows.length>0&&st.createElement(LU,{title:"Project skills",subtitle:"(.commandcode/skills or .agents/skills)",skills:U.rows,baseIndex:U.baseIndex,cursor:$,disabled:u}),j.rows.length>0&&st.createElement(LU,{title:"User skills",subtitle:"(~/.commandcode/skills or ~/.agents/skills)",skills:j.rows,baseIndex:j.baseIndex,cursor:$,disabled:u}),B.rows.length>0&&st.createElement(LU,{title:"Bundled skills",subtitle:"(ships with Command Code)",skills:B.rows,baseIndex:B.baseIndex,cursor:$,disabled:u})),W&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",_+1,"–",Math.min(F,I.length)," of"," ",I.length,_>0?" · ↑ more":"",F<I.length?" · ↓ more":""))),y&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.YELLOW},y)))},"SkillsConfig");function SkillsConfigView({staticKey:e,onClose:t}){return st.useEffect(()=>{hardResetForResize()},[]),st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(OU,{onClose:t,staticKey:e})))}__name(SkillsConfigView,"SkillsConfigView"),Gt(),Gt(),SR();var DU=[{scope:"project",label:"This project"},{scope:"global",label:"User"}],$U=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=at(!0),[s,i]=at(void 0),[a,l]=at(void 0),[c,d]=at(!0),u=isProjectTasteToggleLocked(a),m=ut(async()=>{try{const e=await getTasteLearningSettings();o(e.global),i(e.project),l(e.projectSource)}catch{}},[]);ct(()=>{m().finally(()=>d(!1))},[m]);const p=__name(async(e,n,r)=>{e();try{await r(),t?.(),await m()}catch(e){n()}},"persist"),g=isByok({model:getConfiguredModel()}),h=__name(e=>{if(g)return;const t=resolveTasteScopeToggle({scope:e.scope,globalEnabled:r,projectOverride:s,projectSource:a});if("locked"===t.kind)return;if("global"===t.scope)return p(()=>o(t.value),()=>o(!t.value),()=>setTasteLearning({tasteLearning:t.value,scope:"global"}));const n=s;return p(()=>i(t.value),()=>i(n),()=>setTasteLearning({tasteLearning:t.value,scope:"project"}))},"toggleRow"),f=__name(e=>{if(g)return;const t=resolveTasteScopeReset({scope:e.scope,globalEnabled:r,projectOverride:s,projectSource:a});if("noop"===t.kind)return;if("save-global"===t.kind)return p(()=>o(!0),()=>o(!1),()=>setTasteLearning({tasteLearning:!0,scope:"global"}));const n=s;return p(()=>i(void 0),()=>i(n),()=>clearProjectTasteLearning())},"resetRow"),{cursor:y}=useListNavigation({items:DU,onSelect:__name(e=>{h(e)},"onSelect"),onReset:__name(e=>{f(e)},"onReset"),onCancel:e,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,isActive:!c});if(c)return st.createElement(bO,{key:n,title:"Taste Learning",gapAfterHeader:!1},st.createElement(A$,{label:"Loading configuration"}));const S=__name(e=>!g&&("project"===e.scope?s??r:r),"valueFor");return st.createElement(bO,{key:n,title:"Taste Learning",subtitle:g?lg:"Learn from your interactions.",hint:g?"esc to close":"↑/↓ navigate · enter to toggle · r reset to default · esc to close"},DU.map((e,t)=>{const n=t===y,r=S(e),o=g||"project"===e.scope&&u;return st.createElement(Qe,{key:e.scope},st.createElement(Xe,{color:n?ER.CYAN:ER.GRAY},n?`${gt.pointer} `:" "),st.createElement(Xe,{color:n?ER.CYAN:ER.WHITE},e.label.padEnd(16)),st.createElement(Xe,{color:r?ER.GREEN:ER.DIM},r?"enabled":"disabled"),o?st.createElement(Xe,{color:ER.DIM}," ",g?"(unavailable on BYOK)":"(set in settings.local.json)"):null)}),st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Xe,{color:ER.DIM},"Taste data stored in .commandcode/taste/taste.md"),u?st.createElement(Xe,{color:ER.DIM},"This project is pinned by .commandcode/settings.local.json — edit that file to change it."):null))},"TasteConfig");function TasteConfigView({staticKey:e,onClose:t,loadTasteStatus:n}){return st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement($U,{onClose:t,onSettingsChange:n,staticKey:e})))}function OrgLimitMeter({row:e,width:t,marginTop:n}){const r=e.reached?ER.RED:getUsageColor(e.pct),o=buildBlockBar({percentage:e.pct,width:t});return st.createElement(Qe,{flexDirection:"column",marginTop:n},st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},`${e.label} `),st.createElement(Xe,{color:r},o.filled),st.createElement(Xe,{color:$R},o.empty),st.createElement(Xe,{bold:!0,color:r},` ${Math.round(e.pct)}%`)),st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},`${" ".repeat(e.label.length+1)}${e.detail}`)))}function OrgLimitsSection({limits:e,width:t,now:n}){const r=projectOrgSpendLimitRows({limits:e,now:n});return 0===r.length?null:st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.DIM},"Spend limits"),r.map((e,n)=>st.createElement(OrgLimitMeter,{key:e.label,row:e,width:t,marginTop:0===n?0:1})))}function fetchUsageData2(){return fetchUsageData({getAuthKey:getAuthKey2,getApiBaseUrl:getApiBaseUrl,createRequest:__name(({baseUrl:e})=>createApiClient({baseUrl:e}),"createRequest")})}function getAuthKey2(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function WindowLimitMeter({label:e,used:t,cap:n,resetAt:r,width:o,now:s}){const i=n>0?Math.min(100,t/n*100):0,a=getUsageColor(i),l=buildBlockBar({percentage:i,width:o}),c=r>s?` · resets in ${formatDuration(r-s)}`:"";return st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},e.padEnd(7)," "),st.createElement(Xe,{color:a},l.filled),st.createElement(Xe,{color:$R},l.empty),st.createElement(Xe,{bold:!0,color:a},` ${Math.round(i)}%`),st.createElement(Xe,{color:ER.DIM},c))}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){const t=getRenewalUrgency(e);return"critical"===t?ER.RED:"warning"===t?ER.YELLOW:void 0}__name(TasteConfigView,"TasteConfigView"),Gt(),Gt(),SR(),Gt(),SR(),Gt(),__name(OrgLimitMeter,"OrgLimitMeter"),__name(OrgLimitsSection,"OrgLimitsSection"),__name(fetchUsageData2,"fetchUsageData"),__name(getAuthKey2,"getAuthKey"),__name(WindowLimitMeter,"WindowLimitMeter"),__name(getProgressBarWidth,"getProgressBarWidth"),__name(getDaysColor,"getDaysColor");var NU=__name(({plan:e,status:t})=>st.createElement(Qe,{marginBottom:0},st.createElement(Qe,{flexShrink:0},st.createElement(Xe,{backgroundColor:ER.BLUE,color:"#f4f4f4",bold:!0},`${wL}USAGE${wL}`)),e&&st.createElement(st.Fragment,null,st.createElement(Xe,null," "),st.createElement(Xe,{color:ER.GRAY},`${e.name} Plan`)),t&&st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:"active"===t?ER.GREEN:ER.YELLOW},t))),"UsageBadge"),_U=__name(({showRetry:e})=>st.createElement(Qe,{marginTop:1},st.createElement(pO,null,e&&st.createElement(st.Fragment,null,st.createElement(gO,null,"r")," to retry · "),"Press ",st.createElement(gO,null,"Esc")," to close")),"UsageFooter"),FU=__name(({onClose:e})=>{const[t,n]=at("loading"),[r,o]=at(null),[s,i]=at(!1),a=getProgressBarWidth({terminalWidth:useTerminalWidth()}),l=ut(async e=>{try{i(!1);const t=await fetchUsageData2();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")}},[]),c=st.useRef(null);nt((r,o)=>{if(o.escape&&e(),"r"===r&&"error"===t){n("loading"),c.current?.abort();const e=new AbortController;c.current=e,l(e.signal)}}),ct(()=>{const e=new AbortController;return c.current=e,l(e.signal),()=>e.abort()},[l]);const d=r?projectUsageView({usageData:r}):null,u=d?.subscription??null,m=d?.plan??null;if("loading"===t)return st.createElement(Qe,{flexDirection:"column",paddingX:0,width:"100%"},st.createElement(NU,{plan:m,status:u?.status??null}),st.createElement(A$,null),st.createElement(_U,null));if("error"===t)return st.createElement(Qe,{flexDirection:"column",paddingX:0,width:"100%"},st.createElement(NU,{plan:m,status:u?.status??null}),st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},s?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),st.createElement(_U,{showRetry:!s}));if(!r)return null;const p=d?.hasBillingData??!1,g=d?.usageUrl??null,h=d?.orgLimits??[],f=d?.now??Date.now();if(!p)return st.createElement(Qe,{flexDirection:"column",paddingX:0,width:"100%"},st.createElement(NU,{plan:m,status:u?.status??null}),st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(D$,{message:"No billing data found."}),g&&st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},"Visit "),st.createElement(cL,{url:g,text:"Studio",color:ER.CYAN}),st.createElement(Xe,{color:ER.DIM}," for usage details."))),st.createElement(OrgLimitsSection,{limits:h,width:a,now:f}),st.createElement(_U,null));const y=d?.windowLimits??null,S=d?.sandboxMinutes??null,w=!0===d?.sandboxAccess&&null!==S&&(S.limitMinutes>0||S.usedMinutes>0),v=d?.summary??null,k=d?.credits,C=k?.usagePercent??0,b=Boolean(k?.hasCreditsInfo),E=(k?.purchasedRemaining??0)+(k?.freeRemaining??0),T=d?.daysLeft??null,P=getDaysColor(T),M=getUsageColor(C),x=buildBlockBar({percentage:C,width:a});return st.createElement(Qe,{flexDirection:"column",paddingX:0,width:"100%"},st.createElement(Qe,{marginBottom:1},st.createElement(NU,{plan:m,status:u?.status??null})),b?st.createElement(Qe,null,st.createElement(Xe,{color:M},x.filled),st.createElement(Xe,{color:$R},x.empty),st.createElement(Xe,{bold:!0,color:M},` ${Math.round(C)}% used`)):st.createElement(Xe,{color:ER.DIM},"Plan details unavailable"),b&&st.createElement(Qe,null,v&&st.createElement(st.Fragment,null,st.createElement(Xe,null,v.totalCount.toLocaleString()),st.createElement(Xe,{color:ER.DIM},"billing-period"===v.periodBasis?" requests this month":" requests")),null!==T&&st.createElement(st.Fragment,null,v&&st.createElement(Xe,{color:ER.DIM}," · "),0===T?st.createElement(Xe,{color:P},"renews today"):st.createElement(st.Fragment,null,st.createElement(Xe,{color:P},`${T} day${1===T?"":"s"}`),st.createElement(Xe,{color:ER.DIM}," to renew"))),E>0&&st.createElement(st.Fragment,null,(v||null!==T)&&st.createElement(Xe,{color:ER.DIM}," · "),st.createElement(Xe,{color:ER.DIM},"Extra Credits: "),st.createElement(Xe,null,formatCredits(E)))),y?.limited&&st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.DIM},"Usage limits"),y.fiveHour&&st.createElement(WindowLimitMeter,{label:"5-hour",used:y.fiveHour.used,cap:y.fiveHour.cap,resetAt:y.fiveHour.resetAt,width:a,now:f}),y.weekly&&st.createElement(Qe,{marginTop:y.fiveHour?1:0,flexDirection:"column"},st.createElement(WindowLimitMeter,{label:"Weekly",used:y.weekly.used,cap:y.weekly.cap,resetAt:y.weekly.resetAt,width:a,now:f}))),w&&st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(Xe,{color:ER.DIM},"Sandbox minutes"),S.limitMinutes>0?st.createElement(WindowLimitMeter,{label:"Month",used:S.usedMinutes,cap:S.limitMinutes,resetAt:S.resetAt,width:a,now:f}):st.createElement(Xe,null,`${S.usedMinutes} min used this month, billed per minute`)),st.createElement(OrgLimitsSection,{limits:h,width:a,now:f}),g&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Full breakdown at "),st.createElement(cL,{url:g,text:d?.usageUrlDisplay??g,color:ER.CYAN})),st.createElement(_U,null))},"UsageOverlay");function UsageView({staticKey:e,onClose:t}){return st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(FU,{onClose:t})))}__name(UsageView,"UsageView"),Gt(),SR(),Gt(),SR(),Gt();var UU="@last";function shortenHomePath(e){const t=W();return e.startsWith(t)?`~${e.slice(t.length)}`:e}__name(shortenHomePath,"shortenHomePath");var jU={approved:{label:`${gt.tick} approved`,color:ER.GREEN},"not-implemented":{label:`${gt.circleDotted} set aside`,color:ER.YELLOW},pending:{label:`${gt.dot} pending`,color:ER.DIM}},BU=createNodeRuntime(),WU={"?":"Why? Explain the reasoning behind this.",x:"Cut this — remove it from the plan.","!":"Risky — double-check this before implementing."};function lineStyleProps(e){if(e.changed)return{color:ER.GREEN,bold:!1,italic:!1};const t={color:ER.WHITE,bold:!1,italic:!1};if(!e.style)return t;switch(e.style.role){case"heading":return{color:WR.HEADING,bold:!0,italic:!1};case"code":case"code-fence":return{color:WR.CODE,bold:!1,italic:!1};case"quote":return{color:ER.DIM,bold:!1,italic:!0};case"table":return{color:ER.CYAN,bold:!1,italic:!1};default:return t}}__name(lineStyleProps,"lineStyleProps");var HU=__name(({plan:e,variant:t="browse",fallbackContent:n,onBack:r,onSubmitFeedback:o,onExecute:s,onAutoAccept:i})=>{const[a,l]=at(null),[c,d]=at(e.annotations),[u,m]=at(!1);ct(()=>{u||d(e.annotations)},[e.annotations,u]);const[p,g]=at({kind:"line",lineNumber:1}),[h,f]=at(null),y=lt([]),S=dt(()=>shouldCollapsePastedText(),[]),[w,v]=at(null),[k,C]=at(null),[b,E]=at(!1),[T,P]=at(0),[M,x]=at(null),I=useTerminalHeight(),A=useTerminalWidth();ct(()=>{__name(async()=>{const t=await readPlanContent({runtime:BU,filePath:e.filePath})??n??null;l(null===t?[]:splitPlanLines(t))},"load")()},[e.filePath,n]);const R=e.version??1;ct(()=>{R<=1||!e.filePath||readPlanVersionSnapshot({runtime:BU,filePath:e.filePath,version:R-1}).then(x).catch(()=>{})},[R,e.filePath]);const L=dt(()=>null!==M&&null!==a?diffPlanChangedLines({previous:M,current:a}):new Set,[M,a]),O=c.length,D=dt(()=>{const e={id:"feedback",label:`Submit review (${O})`,chord:"ctrl+r",color:ER.CYAN,hint:"agent revises the plan, returns it for review"};return"approval"===t?[...O>0?[e]:[],{id:"auto-accept",label:"Approve",chord:"ctrl+a",color:ER.GREEN,hint:O>0?"executes the plan · comments go along as notes":"executes the plan"},{id:"cancel",label:"Cancel",chord:"esc",color:ER.YELLOW,hint:""}]:[...O>0?[e]:[],{id:"execute",label:"Execute plan",chord:"ctrl+e",color:ER.GREEN,hint:"executes the plan as written"},{id:"cancel",label:"Back",chord:"esc",color:ER.YELLOW,hint:""}]},[t,O]),$=dt(()=>h?c.filter(e=>e.line!==h.line):c,[c,h]),N=dt(()=>buildPlanReaderRows({lines:a??[],annotations:$}),[a,$]),_=dt(()=>classifyPlanLines(a??[]),[a]),F=a?.length??0,U=resolvePlanWrapWidth(Math.max(20,A-7-2)),j=dt(()=>buildPlanReaderDisplayRows({rows:N,width:U}),[N,U]),B=getPlanReaderCursorDisplaySpan({displayRows:j,cursor:p}),W=I-1,H=Math.max(4,W-10-7),G=h?1:0,V=-1===B.first?j.length-1:B.first,z=-1===B.last?j.length-1:B.last+G;ct(()=>{P(e=>{const t=clampScrollOffset({cursor:Math.max(0,z),total:j.length+G,maxVisible:H,currentOffset:e});return clampScrollOffset({cursor:Math.max(0,V),total:j.length+G,maxVisible:H,currentOffset:t})})},[V,z,j.length,G,H]),ct(()=>{g(e=>snapPlanReaderCursor({cursor:e,lineCount:F,actions:[]}))},[F]),ct(()=>{g(e=>"action"!==e.kind||D.some(t=>t.id===e.id)?e:{kind:"line",lineNumber:Math.max(1,F)})},[D,F]);const K=__name(t=>{m(!0),d(t),e.filePath&&setPlanAnnotations({runtime:BU,filePath:e.filePath,annotations:t}).catch(()=>C("Failed to save comments to disk"))},"persistAnnotations"),q="line"===p.kind?c.find(e=>e.line===p.lineNumber):void 0,Y=__name(()=>{if(0===c.length||!a)return;const t=buildPlanAnnotationsPrompt({title:e.title,filePath:e.filePath||"(plan not saved to a file yet)",lines:a,annotations:c});e.filePath&&snapshotPlanVersion({runtime:BU,filePath:e.filePath}).catch(()=>{}),K([]),o(t)},"submitFeedback"),J=__name(t=>{if(t&&c.length>0&&a){const t=buildPlanApprovalNotesPrompt({title:e.title,...e.filePath?{filePath:e.filePath}:{},lines:a,annotations:c});return K([]),void i?.(t)}K([]),i?.()},"approve"),Q=__name(()=>{"approval"===t&&(O>0?v({kind:"approve",choice:"notes"}):J(!1))},"requestApprove"),X=__name(()=>{O>0&&!e.filePath?v({kind:"cancel"}):r()},"requestCancel"),Z=__name(t=>{"feedback"!==t?"execute"!==t?"auto-accept"!==t?"cancel"===t&&X():Q():(s??o)(buildPlanExecutePrompt({title:e.title,filePath:e.filePath||e.fileName})):Y()},"runAction"),ee=__name(()=>{e.filePath?(E(!0),openFileInEditor(e.filePath).then(async()=>{const t=await readPlanContent({runtime:BU,filePath:e.filePath});null!==t&&l(splitPlanLines(t))}).catch(e=>C(e instanceof Error?e.message:"Failed to open the editor")).finally(()=>{E(!1),hardResetForResize()})):C("This plan is not saved to a file yet")},"openExternalEditor"),te=__name(e=>{"line"!==p.kind||p.lineNumber<1||p.lineNumber>F||(y.current=e?[]:q?.pastes??[],f({line:p.lineNumber,value:e||(q?.text??""),hadExisting:void 0!==q}))},"openDraft"),ne=__name(e=>{h&&(K(upsertPlanAnnotation({annotations:c,line:h.line,text:e,createdAt:(new Date).toISOString(),pastes:y.current})),y.current=[],f(null))},"commitDraft"),re=dt(()=>{const e=new Set;for(const t of c)e.add(t.line);for(const t of L)e.add(t);return[...e].sort((e,t)=>e-t)},[c,L]),oe=__name(e=>{if(0===re.length)return;const t="line"===p.kind?p.lineNumber:F+1,n="next"===e?re.find(e=>e>t)??re[0]:[...re].reverse().find(e=>e<t)??re[re.length-1];void 0!==n&&g({kind:"line",lineNumber:n})},"jumpMarked");nt((e,t)=>{t.escape&&f(null)},{isActive:null!==h}),nt((e,t)=>{if(w)if(t.escape)v(null);else if("approve"===w.kind&&(t.leftArrow||t.rightArrow||t.tab))v({kind:"approve",choice:"notes"===w.choice?"original":"notes"});else if(t.return){if("approve"===w.kind)return v(null),void J("notes"===w.choice);v(null),r()}},{isActive:null!==w}),nt((e,n)=>{if(n.escape)return void X();if(n.upArrow||n.downArrow)return C(null),void g(e=>{if("action"===e.kind){const t=D.findIndex(t=>t.id===e.id);if(n.upArrow){if(t<=0&&F>0)return{kind:"line",lineNumber:F};const n=D[Math.max(0,t-1)];return n?{kind:"action",id:n.id}:e}const r=D[Math.min(D.length-1,t+1)];return r?{kind:"action",id:r.id}:e}if(n.upArrow)return{kind:"line",lineNumber:Math.max(1,e.lineNumber-1)};if(e.lineNumber>=F){const t=D[0];return t?{kind:"action",id:t.id}:e}return{kind:"line",lineNumber:e.lineNumber+1}});if(n.pageUp||n.pageDown)return C(null),void g(e=>"action"===e.kind&&n.pageDown?e:movePlanReaderCursorByPage({displayRows:j,cursor:e,direction:n.pageDown?"down":"up",pageRows:Math.max(1,H-1)}));if(n.home||n.end)return C(null),void(F>0&&g({kind:"line",lineNumber:n.home?1:F}));if(n.leftArrow||n.rightArrow){if("action"!==p.kind)return;const e=D.findIndex(e=>e.id===p.id);if(-1===e)return;const t=n.leftArrow?Math.max(0,e-1):Math.min(D.length-1,e+1),r=D[t];return void(r&&g({kind:"action",id:r.id}))}if(n.ctrl&&"r"===e)return void Y();if(n.ctrl&&"a"===e&&"approval"===t)return void Q();if(n.ctrl&&"e"===e&&"browse"===t)return void Z("execute");if(n.ctrl&&"g"===e)return void ee();if(n.ctrl&&"n"===e)return void oe("next");if(n.ctrl&&"p"===e)return void oe("previous");if(n.return)return"action"===p.kind?void Z(p.id):void te("");const r=WU[e];"line"!==p.kind||!r||n.ctrl||n.meta?"line"===p.kind&&e.length>0&&!n.ctrl&&!n.meta&&te(e):K(upsertPlanAnnotation({annotations:c,line:p.lineNumber,text:q?.text===r?"":r,createdAt:(new Date).toISOString()}))},{isActive:null===h&&null===w&&null!==a&&!b});const se=jU[e.status],ie=T,ae=T+H-G,le=j.slice(ie,ae),ce=h?h.hadExisting?"enter to keep · clear + enter removes · esc keep as was":"enter to pin · esc discard":w?"approve"===w.kind?"←/→ choose · enter confirm · esc back":"enter discard · esc back":"action"===p.kind?"↑/↓ choose · enter to run":["type + enter to comment",...re.length>0?["ctrl+n/p jump "+(L.size>0?"changes":"comments")]:[],"quick: ? why x cut ! risky","ctrl+g $EDITOR"].join(" · ");return st.createElement(bO,{title:"approval"===t?`Plan review: ${e.title}`:e.title,titleSuffix:"approval"===t?st.createElement(st.Fragment,null," ","· ",shortenHomePath(e.filePath)||e.fileName," · v",e.version??1):st.createElement(st.Fragment,null," ","· ",shortenHomePath(e.filePath)||e.fileName," · v",e.version??1," ",st.createElement(Xe,{color:se.color},se.label)),subtitle:"approval"===t?"Review the plan like a PR — type on any line to comment, enter pins it under the line.":void 0,footer:st.createElement(Xe,{italic:!0,color:ER.DIM},ce)},null===a?st.createElement(Xe,{color:ER.DIM},"Loading plan..."):0===F?st.createElement(Xe,{color:ER.DIM},"Plan file is empty or missing on disk."):st.createElement(Qe,{flexDirection:"column"},le.map((e,t)=>{const n=ie+t,{row:r}=e;if("action"===r.kind)return null;if("annotation"===r.kind)return st.createElement(Qe,{key:`annotation-${r.lineNumber}-${n}`},st.createElement(Xe,{color:ER.DIMMER}," ".repeat(5)),st.createElement(Xe,{backgroundColor:PR.BADGE_BG,color:PR.BADGE_FG}," ",e.isFirstSegment?"↳ ":" ",e.text," "));const o="line"===p.kind&&p.lineNumber===r.lineNumber,s=lineStyleProps({style:_[r.lineNumber-1],changed:L.has(r.lineNumber)}),i=j[n+1],a=!i||"line"!==i.row.kind||i.row.lineNumber!==r.lineNumber,l=n===ae-1,c=null!==h&&h.line===r.lineNumber&&(a||l);return st.createElement(st.Fragment,{key:`line-${r.lineNumber}-${n}`},st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIMMER},e.isFirstSegment?String(r.lineNumber).padStart(4," "):" "," "),st.createElement(Xe,{color:r.hasAnnotation?ER.CYAN:ER.DIMMER},e.isFirstSegment&&r.hasAnnotation?`${gt.bullet} `:" "),st.createElement(Xe,{color:s.color,bold:s.bold,italic:s.italic,backgroundColor:o?KR:void 0},e.text||" ")),c&&h&&st.createElement(Qe,null,st.createElement(Xe,{color:ER.CYAN}," ┃ ",gt.bullet," "),st.createElement(TextInput,{value:h.value,onChange:e=>{y.current=prunePlanAnnotationPastes(e,y.current),f(t=>t?{...t,value:e}:t)},onSubmit:ne,placeholder:"Type your comment…",focus:null!==h,stripBracketedPaste:!0,clipboardOnEmptyPaste:!0,collapsePastedText:S,onPasteCollapsed:e=>{y.current=[...y.current,e]}})))})),st.createElement(Qe,{flexDirection:"column",marginTop:1},st.createElement(ZR,{dividerColor:ER.DIMMER}),st.createElement(Qe,null,st.createElement(Xe,{bold:!0,backgroundColor:PR.BADGE_BG,color:ER.WHITE}," REVIEW "),st.createElement(Xe,{color:ER.DIM},O>0&&` ${O} pending comment${1===O?"":"s"}`,R>1&&` · round ${R}${L.size>0?` · ${L.size} line${1===L.size?"":"s"} changed`:""}`)),w?"approve"===w.kind?st.createElement(Qe,null,st.createElement(Xe,{bold:!0,color:ER.GREEN},"Approve"," "),st.createElement(Xe,{color:"notes"===w.choice?ER.WHITE:ER.DIM,backgroundColor:"notes"===w.choice?KR:void 0},"notes"===w.choice?"(•)":"( )"," ","with ",O," comment",1===O?"":"s"," as notes"),st.createElement(Xe,{color:ER.DIMMER}," "),st.createElement(Xe,{color:"original"===w.choice?ER.WHITE:ER.DIM,backgroundColor:"original"===w.choice?KR:void 0},"original"===w.choice?"(•)":"( )"," ","original plan · discard comments")):st.createElement(Qe,null,st.createElement(Xe,{color:ER.YELLOW},"Discard ",O," pending comment",1===O?"":"s"," and exit review?")):D.map(e=>{const t="action"===p.kind&&p.id===e.id;return st.createElement(Qe,{key:e.id},st.createElement(Xe,{bold:!0,color:e.color,backgroundColor:t?KR:void 0},t?`${gt.pointer} ${e.label} `:e.label),st.createElement(Xe,{color:ER.DIM}," ",e.chord),e.hint&&st.createElement(Xe,{color:ER.DIMMER}," ",e.hint))}),k&&st.createElement(Xe,{color:ER.YELLOW},k)))},"PlanReader"),GU=createNodeRuntime();function PlanApprovalView({staticKey:e,planContent:t,planFilePath:n,onAutoAccept:r,onCancel:o,onSendFeedback:s}){ct(()=>{hardResetForResize()},[]);const[i,a]=at(null);ct(()=>{n&&listPlans({runtime:GU}).then(e=>a(e.find(e=>e.filePath===n)??null)).catch(()=>{})},[n]);const l=dt(()=>{if(i)return i;const e=n?.split("/").pop()??"plan.md";return{fileName:e,filePath:n??"",title:derivePlanTitle({content:t,fileName:e}),status:"pending",createdAt:"",updatedAt:"",annotations:[]}},[i,n,t]);return st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(HU,{plan:l,variant:"approval",fallbackContent:t,onBack:o,onSubmitFeedback:s,onAutoAccept:r})))}__name(PlanApprovalView,"PlanApprovalView"),Gt(),Gt(),SR();var VU=Date.now(),zU=createNodeRuntime();function matchesTarget(e,t){const n=t.toLowerCase();return e.fileName.toLowerCase()===n||e.fileName.toLowerCase().replace(/\.md$/,"")===n||e.title.toLowerCase()===n}__name(matchesTarget,"matchesTarget");var KU=__name(({sessionId:e,target:t,onClose:n,onSubmitFeedback:r,onExecute:o})=>{const[s,i]=at([]),[a,l]=at([]),[c,d]=at(!0),[u,m]=at(null),[p,g]=at("session"),[h,f]=at(null),[y,S]=at(""),[w,v]=at(0),[k,C]=at(0),b=useTerminalHeight(),E=lt(!1);ct(()=>{__name(async()=>{try{const[n,r]=await Promise.all([listPlans({runtime:zU,sessionId:e,sessionStartMs:VU}),listPlans({runtime:zU})]);if(i([...n]),l([...r]),t&&!E.current)if(E.current=!0,t===UU){const e=n[0];e&&f(e)}else{const e=r.find(e=>matchesTarget(e,t.trim()));e?f(e):S(t.trim())}}catch(e){m(e instanceof Error?e.message:"Failed to load plans")}finally{d(!1)}},"load")()},[e,k]);const T="session"===p?s:a,P=dt(()=>{const e=y.trim().toLowerCase();return e?T.filter(t=>t.title.toLowerCase().includes(e)||t.fileName.toLowerCase().includes(e)):T},[T,y]),M=b-1,x=Math.max(3,M-9),I=null===h&&!c,{cursor:A}=useListNavigation({items:P,onSelect:__name(e=>f(e),"onSelect"),onCancel:n,searchQuery:y,onSearchChange:S,initialIndex:0,isActive:I});if(ct(()=>{v(e=>clampScrollOffset({cursor:A,total:P.length,maxVisible:x,currentOffset:e}))},[A,P.length,x]),nt((e,t)=>{(t.leftArrow||t.rightArrow)&&(g(e=>"session"===e?"all":"session"),v(0))},{isActive:I}),h)return st.createElement(HU,{plan:h,onBack:()=>{f(null),C(e=>e+1)},onSubmitFeedback:r,onExecute:o});if(c)return st.createElement(bO,{title:"Plans",gapAfterHeader:!1},st.createElement(Xe,{color:ER.DIM},"Loading plans..."));if(u)return st.createElement(bO,{title:"Plans",titleColor:ER.RED,gapAfterHeader:!1,hint:"Esc to close"},st.createElement(Xe,{color:ER.DIM},u));const R=w,L=w+x,O=P.slice(R,L),D=P.length>x;return st.createElement(bO,{title:"Plans",titleSuffix:st.createElement(st.Fragment,null," ",P.length," plan",1===P.length?"":"s"),subtitle:st.createElement(st.Fragment,null,st.createElement(Xe,{bold:"session"===p,color:"session"===p?fO:ER.DIM},"This session"),st.createElement(Xe,{color:ER.DIMMER},` ${gt.triangleLeftSmall} ${gt.triangleRightSmall} `),st.createElement(Xe,{bold:"all"===p,color:"all"===p?fO:ER.DIM},"All plans")),footer:st.createElement(Xe,{italic:!0,color:ER.DIM},"type to search · ↑/↓ navigate · ←/→ switch tab · enter to open",y?" · esc to clear":" · esc to close")},st.createElement(Qe,{marginBottom:1,flexDirection:"column",width:"100%"},st.createElement(pL,{query:y,resultCount:y?P.length:void 0,placeholder:"Type to search plans..."})),0===P.length?st.createElement(Qe,{marginY:1},st.createElement(Xe,{color:ER.GRAY},y?`No plans match "${y}"`:"session"===p?"No plans in this session yet — use /plan or plan mode to create one. Press → for all plans.":"No saved plans yet — plans land in ~/.commandcode/plans when you use plan mode.")):st.createElement(st.Fragment,null,st.createElement(Qe,{flexDirection:"column"},O.map((e,t)=>{const n=R+t===A,r=jU[e.status];return st.createElement(Qe,{key:e.fileName},st.createElement(Xe,{color:n?wO:ER.GRAY},n?`${gt.pointer} `:" "),st.createElement(Xe,{bold:n,color:n?wO:ER.WHITE},e.title),st.createElement(Xe,{color:r.color}," ",r.label),(e.version??1)>1&&st.createElement(Xe,{color:ER.DIM}," ","v",e.version),e.annotations.length>0&&st.createElement(Xe,{color:ER.CYAN}," ",e.annotations.length," comment",1===e.annotations.length?"":"s"),st.createElement(Xe,{color:ER.DIM}," ",formatRelativeTimeShort({timestamp:e.updatedAt})))})),D&&st.createElement(Qe,{marginTop:1},st.createElement(Xe,{color:ER.DIM},"Showing ",R+1,"–",Math.min(L,P.length)," of"," ",P.length,R>0?" · ↑ more":"",L<P.length?" · ↓ more":""))))},"PlansScreen");function PlansView({staticKey:e,sessionId:t,target:n,onClose:r,onSubmitFeedback:o,onExecute:s}){return st.useEffect(()=>{hardResetForResize()},[]),st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(Qe,{flexDirection:"column",width:"100%"},st.createElement(KU,{sessionId:t,target:n,onClose:r,onSubmitFeedback:o,onExecute:s})))}function ForkSummary({session:e,isSelected:t,nameColor:n}){if(!e.forkProvenance)return null;const r=t?void 0:ER.DIM,o=e.userRenamed&&e.title?e.title:null;return o?st.createElement(Xe,{color:n},`${o} `,st.createElement(Xe,{color:r},`· ${e.forkProvenance}`)):st.createElement(Xe,{color:r},e.forkProvenance)}__name(PlansView,"PlansView"),Gt(),Gt(),SR(),Gt(),__name(ForkSummary,"ForkSummary");var qU=__name((e,t)=>e.padEnd(t),"padCell"),YU=__name(e=>e instanceof Error&&e.message?e.message:"Unknown error","getActionErrorMessage");function resolveRowColor(e){return e.isDeletePending?ER.RED:e.isCurrentSession?TR:e.isSelected?ER.WHITE:ER.GRAY}function renderRowSummary(e){const{session:t,isSelected:n,nameColor:r}=e;if(t.forkProvenance)return st.createElement(ForkSummary,{session:t,isSelected:n,nameColor:r});const o=getSessionSummary({session:t});return t.userRenamed&&t.title?st.createElement(Xe,{color:r},o):o}__name(resolveRowColor,"resolveRowColor"),__name(renderRowSummary,"renderRowSummary");var JU=["recent","created","messages"],QU={recent:"Recent",created:"Created",messages:"Messages"};function nextSortMode(e){const t=JU.indexOf(e);return JU[(t+1)%JU.length]}function sortSessions(e,t){return"created"===t?[...e].sort((e,t)=>Date.parse(t.createdAt)-Date.parse(e.createdAt)):"messages"===t?[...e].sort((e,t)=>t.messageCount-e.messageCount):e}function matchesSearch2(e,t){const n=t.toLowerCase().split(/\s+/).filter(Boolean);if(0===n.length)return!0;const r=[e.id,e.title??"",e.firstMessage,e.gitBranch??""].join(" ").toLowerCase();return n.every(e=>r.includes(e))}function getFilteredEmptyState(e){return e.namedOnly?{text:"No named sessions.",hint:"Press ctrl+n to show all."}:e.searchQuery?{text:`No sessions match "${e.searchQuery}"`,hint:"Press Esc to clear search."}:e.branchFilter&&e.currentBranch?{text:`No sessions found for branch "${e.currentBranch}"`,hint:"Press ctrl+b to show all branches, Esc to cancel"}:{text:"No previous sessions found",hint:"Press Esc to go back"}}function resolveProjectBaseDir(){const e=getCommandSessionRuntime();return getProjectSessionDir({env:e.env(),cwd:e.cwd()})}__name(nextSortMode,"nextSortMode"),__name(sortSessions,"sortSessions"),__name(matchesSearch2,"matchesSearch"),__name(getFilteredEmptyState,"getFilteredEmptyState"),__name(resolveProjectBaseDir,"resolveProjectBaseDir");var XU=__name(({onSelectSession:e,onClose:t,currentSessionId:n})=>{const[r,o]=at([]),[s,i]=at(0),[a,l]=at(0),[c,d]=at(!0),[u,m]=at(!1),[p,g]=at(!1),[h,f]=at(null),[y,S]=at(null),[w,v]=at(""),[k,C]=at(!1),[b,E]=at("recent"),[T,P]=at(!1),[M,x]=at("list"),[I,A]=at(null),[R,L]=at(""),[O,D]=at(null),[$]=at(()=>getCurrentGitBranch()),[N]=at(()=>resolveProjectBaseDir()),_=useTerminalHeight(),F=Math.max(6,_-19),U=ut(async()=>{d(!0);const e=await listCommandSessions();o(e),d(!1)},[]);ct(()=>{U()},[U]),ct(()=>{if(!y)return;const e=setTimeout(()=>S(null),3e3);return()=>clearTimeout(e)},[y]);const j=ut(async e=>{try{const t=getCommandSessionRuntime(),{method:n}=await deleteSessionV3({runtime:t,baseDir:N,id:e});g(!1),f(null),i(0),l(0),S("trash"===n?"Session moved to trash":"Session deleted"),await U()}catch(e){g(!1),f(`Failed to delete session: ${YU(e)}`)}},[U,N]),B=ut(async e=>{const t=I;if(t)try{const n=getCommandSessionRuntime();await renameSessionFile({runtime:n,cwd:n.cwd(),baseDir:N,id:t,name:e}),x("list"),A(null),D(null),await U()}catch(e){D(`Failed to rename session: ${YU(e)}`)}else x("list")},[I,U,N]),W=filterSessionsByBranch({sessions:r,branchFilter:u,currentBranch:$}),H=T?W.filter(e=>e.userRenamed):W,G=sortSessions(w?H.filter(e=>matchesSearch2(e,w)):H,b);if(ct(()=>{i(e=>Math.min(e,Math.max(0,G.length-1)))},[G.length]),nt((r,o)=>{if("rename"===M)return o.escape?(x("list"),void A(null)):void 0;if(p){if(!o.return)return void g(!1);if(G.length>0&&s<G.length){const e=G[s];j(e.id)}}else{if(o.delete||isCtrlKey({inputChar:r,key:o,letter:"d",ctrlCode:4})){if(0===G.length)return;return G[s]?.id===n?void f("Cannot delete the current session"):(f(null),void g(!0))}if(isCtrlKey({inputChar:r,key:o,letter:"r",ctrlCode:18})){if(c)return;const e=G[s];if(!e)return;return D(null),L(e.title??""),A(e.id),void x("rename")}if(isCtrlKey({inputChar:r,key:o,letter:"p",ctrlCode:16}))C(e=>!e);else{if(!isCtrlKey({inputChar:r,key:o,letter:"s",ctrlCode:19}))return isCtrlKey({inputChar:r,key:o,letter:"n",ctrlCode:14})?(P(e=>!e),i(0),void l(0)):o.escape?w?(v(""),i(0),void l(0)):void t():isCtrlKey({inputChar:r,key:o,letter:"b",ctrlCode:2})?(m(e=>!e),i(0),void l(0)):void(o.upArrow?i(e=>{const t=Math.max(0,e-1);return t<a&&l(t),t}):o.downArrow?i(e=>{const t=Math.min(G.length-1,e+1);return t>=a+F&&l(t-F+1),t}):o.return?G.length>0&&s<G.length&&e(G[s].id):o.backspace?w&&(v(e=>e.slice(0,-1)),i(0),l(0)):!o.ctrl&&!o.meta&&!o.tab&&r&&1===r.length&&r>=" "&&(v(e=>e+r),i(0),l(0)));E(e=>nextSortMode(e))}}}),c)return st.createElement(Qe,{flexDirection:"column",paddingLeft:2},st.createElement(A$,{label:"Loading sessions"}));if(0===r.length)return st.createElement(Qe,{flexDirection:"column",paddingLeft:2},st.createElement(D$,{message:"No previous sessions found",hint:"Press Esc to go back"}));const V=G.slice(a,a+F),z=s<G.length?G[s]:null,K=p&&z?`Delete "${getSessionSummary({session:z})}"? Press Enter to confirm, any other key to cancel.`:null,q=getFilteredEmptyState({namedOnly:T,searchQuery:w,branchFilter:u,currentBranch:$});return st.createElement(bO,{title:"Resume Session",subtitle:`Sort: ${QU[b]} · Name: ${T?"Named":"All"} · Branch: ${u?$??"unknown":"All"}`},st.createElement(Qe,{marginBottom:1,width:"100%"},st.createElement(pL,{query:w,resultCount:w?G.length:void 0,placeholder:"Type to search sessions..."})),st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:$R,bold:!0},qU("#",6),qU("Modified",12),qU("Git Branch",22),qU("Messages",12),"Summary",k?" · Path":"")),0===G.length?st.createElement(Qe,{marginBottom:1},st.createElement(D$,{message:q.text,hint:q.hint})):st.createElement(Qe,{flexDirection:"column"},V.map((e,t)=>{const r=a+t,o=s===r,i=p&&o,l=i?void 0:ER.YELLOW,c=resolveRowColor({isDeletePending:i,isCurrentSession:e.id===n,isSelected:o}),d=truncateString2({text:e.gitBranch||"-",maxChars:20}),u=k?toRelativePath(`${N}/${e.id}.jsonl`):null;return st.createElement(Xe,{key:e.id,color:c,backgroundColor:o?KR:void 0,bold:o,wrap:"truncate-end"},qU(`${r+1}.`,6),qU(formatRelativeTimeShort({timestamp:e.lastModified}),12),qU(d,22),qU(String(e.messageCount),12),renderRowSummary({session:e,isSelected:o,nameColor:l}),u?st.createElement(Xe,{color:ER.DIM},` ${u}`):null," ")})),st.createElement(Qe,{marginTop:1}),"rename"===M&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.CYAN},"Rename: "),st.createElement(TextInput,{value:R,onChange:L,onSubmit:B,singleLine:!0,stripBracketedPaste:!0})),O&&st.createElement(Qe,{marginBottom:1},st.createElement(R$,{glyph:!1},O)),K&&st.createElement(Qe,{marginBottom:1},st.createElement(Xe,{color:ER.RED},K)),h&&st.createElement(Qe,{marginBottom:1},st.createElement(R$,{glyph:!1},h)),y&&st.createElement(Qe,{marginBottom:1},st.createElement(L$,{glyph:!1},y)),G.length>F&&st.createElement(Xe,{color:ER.DIM},"Showing ",a+1,"–",Math.min(a+F,G.length)," ","of ",G.length,a>0?" · ↑ more":"",a+F<G.length?" · ↓ more":""),st.createElement(hO,{marginTop:0,hints:["enter resume","ctrl+s sort","ctrl+n named","ctrl+r rename","ctrl+d delete","ctrl+p path","ctrl+b branch","type to search"]}))},"SessionsResumeTable"),ZU=it(__name(function SessionView2({onSelectSession:e,onClose:t,currentSessionId:n}){return st.createElement(XU,{onSelectSession:e,onClose:t,currentSessionId:n})},"SessionView"));Gt(),Gt();var ej=__name(({onTrust:e,onExit:t})=>{const{exit:n}=rt(),[r,o]=at(1),s=process.cwd(),i=W(),a=i&&s.startsWith(i)?`~${s.slice(i.length)}`:s;return nt((s,i)=>{if(i.upArrow||i.downArrow)o(1===r?2:1);else{if(i.return)return 1===r?void e():(t(),void n());if("1"!==s)return"2"===s?(t(),void n()):void((i.escape||i.ctrl&&"c"===s)&&(t(),n()));e()}}),st.createElement(bO,{title:"Do you trust the files in this folder?",subtitle:a,hint:"↑/↓ to navigate · enter to select · esc to exit"},st.createElement(Qe,{flexDirection:"column"},st.createElement(Xe,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),st.createElement(Qe,{marginTop:1},st.createElement(Xe,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),st.createElement(Qe,{marginTop:1,flexDirection:"column"},st.createElement(Qe,null,st.createElement(jN,{isSelected:1===r}),st.createElement(BN,{isSelected:1===r,idleColor:kO}," ","1. Yes, proceed")),st.createElement(Qe,null,st.createElement(jN,{isSelected:2===r}),st.createElement(BN,{isSelected:2===r,idleColor:kO}," ","2. No, exit"))))},"TrustPrompt"),tj=it(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return st.createElement(st.Fragment,null,st.createElement(KL,{staticKey:e}),st.createElement(ej,{onTrust:t,onExit:n}))},"TrustView"));Gt(),Gt();var nj=new Map;function enqueueAgentSlashCommand(e){const t=nj.get(e.sessionId);t?t.push(e.command):nj.set(e.sessionId,[e.command])}function drainAgentSlashCommands(e){const t=nj.get(e.sessionId);return t&&0!==t.length?(nj.delete(e.sessionId),t):[]}function useAgentSlashCommandQueue({sessionId:e,isCmdCodeBusy:t,onCommand:n}){const r=lt(!1);ct(()=>{if(t||r.current)return;const o=drainAgentSlashCommands({sessionId:e});0!==o.length&&(r.current=!0,(async()=>{try{for(const e of o)await n(e)}finally{r.current=!1}})())},[t,e,n])}function useAuth(){const[e,t]=at(()=>getConfiguredProviderSync()),[n,r]=at(()=>getConfiguredModel()),[o,s]=at(null),[i,a]=at(!1),[l,c]=at(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,authComponentInfo:o,setAuthComponentInfo:s,showProviderNotification:i,setShowProviderNotification:a,premiumCreditsExhausted:l,setPremiumCreditsExhausted:c,providerNotificationTimer:lt(null),modelNotificationTimer:lt(null)}}__name(enqueueAgentSlashCommand,"enqueueAgentSlashCommand"),__name(drainAgentSlashCommands,"drainAgentSlashCommands"),__name(useAgentSlashCommandQueue,"useAgentSlashCommandQueue"),Gt(),SR(),__name(useAuth,"useAuth"),Gt(),SR();var rj=__name(()=>{const[e,t]=at({isExecuting:!1,currentCommand:null});return{executeBash:ut(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await runUserBashCommand({command:e});n(n=>completePendingBashEntry({feed:n,command:e,output:t})),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");Gt(),Gt(),SR(),Gt(),SR();var oj={detectIDE:aE,isIdeIpcConnected:__name(async e=>{const t=yE(),n=await t.connect(e);return t.disconnect(),n},"isIdeIpcConnected"),log:dlog,platform:__name(()=>process.platform,"platform")};Gt();var sj=null,ij={};function requestReload(e){sj=e}function discardPendingReload(){sj=null}function consumePendingReload(){const e=sj;return sj=null,e}function setOriginalInvocation(e){ij=e}function getOriginalInvocation(){return ij}function resolveProviderOrReport(e){return resolveCommandProviderId(e.provider)||(e.setFeed(t=>[...t,yh(`Unknown provider '${e.provider}'. Run /connect to see available providers.`)]),null)}async function handleLoginCommand({provider:e,setFeed:t,setShowLoginOverlay:n,setAuthComponentInfo:r}){const o=e?.trim();if(o){const e=resolveProviderOrReport({provider:o,setFeed:t});if(!e)return;const n=getProviderConfig(e),s=n?.authComponent;return n?.requiresAuth&&s?r?void r({provider:e,Component:s}):void t(e=>[...e,yh("Provider login is not available here.")]):void t(t=>[...t,uh(`${getProviderDisplayName(e)} does not use provider login. Run /login without a provider for Command Code account auth.`)])}const s=await resolveLoginCommand({onDebugError:__name(e=>{process.env.DEBUG&&console.error("Failed to load credentials for display:",e)},"onDebugError")});"already-logged-in"!==s.kind?n(!0):t(e=>[...e,uh(s.message)])}function handleLoginComplete({success:e,message:t,setShowLoginOverlay:n,setFeed:r,setStatus:o}){if(n(!1),!e)return r(e=>[...e,yh(t)]),void o("Ready...");r(e=>[...e,uh(t)]),invalidateBillingContext(),o("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,uh("Authentication cancelled")]),n("Ready...")}async function handleLogoutCommand({provider:e,setFeed:t,setRetryAttempt:n,setIsCmdCodeBusy:r}){const o=e?.trim();if(o){const e=resolveProviderOrReport({provider:o,setFeed:t});if(!e)return;const n=getProviderConfig(e);if(!n?.requiresAuth)return void t(t=>[...t,uh(`${getProviderDisplayName(e)} does not use provider logout. Run /logout without a provider for Command Code account auth.`)]);try{const n=await providerLogout({provider:e}),r=getProviderDisplayName(e);t(e=>[...e,uh(n?`Logged out of ${r}`:`No saved ${r} credential found`)])}catch(n){const r=n instanceof Error?n.message:"Unknown error";t(t=>[...t,yh(`Failed to log out of ${getProviderDisplayName(e)}: ${r}`)])}return}const s=await runCommandLogoutFlow({env:process.env});s.success&&invalidateBillingContext(),s.turnInterrupted&&(n(null),r(!1)),t(e=>[...e,"error"===s.notice.kind?yh(s.notice.message):uh(s.notice.message)])}function parseChangelogVersions(e){return e.split(/^(?=## )/m).map(e=>e.trim()).filter(e=>e.startsWith("## "))}function findChangelogPath(e){let t=r(p(e));for(let e=0;e<6;e++){const e=n(t,"CHANGELOG.md");if(A(e))return e;const o=r(t);if(o===t)return null;t=o}return null}function handleChangelog({setFeed:e,rawArguments:t="",moduleUrl:n}){const r=findChangelogPath(n??import.meta.url);if(!r)return void e(e=>[...e,uh("No changelog available in this build.")]);const o=parseChangelogVersions(R(r,"utf8"));if(0===o.length)return void e(e=>[...e,uh("The changelog is empty.")]);const s="all"===t.trim().toLowerCase()?o.length:10,i=o.slice(0,s).join("\n\n"),a=o.length-s,l=a>0?`\n\n_…and ${a} earlier releases · /changelog all_`:"";e(e=>[...e,fh(`**What's new**\n\n${i}${l}`)])}async function releaseHarness(e){if(e){try{await(k$(e)?.flush())}catch{}C$(e)}}async function handleSelectSession({selectedSessionId:e,previousSessionId:t,sessionLoadIdRef:n,setFeed:r,setLiveEntries:o,setSessionId:s,setShowSessionSelector:i,setSessionLoaded:a,setStaticKey:l,setShareInfo:c,setCurrentModel:d,inTuiResume:u=!1}){const m=crypto.randomUUID();n.current=m;const p=__name(()=>n.current!==m,"isStale");t&&t!==e&&await releaseHarness(t),r([]),o([]),clearSessionTodos(),setNextSessionStartSource("resume"),s(e),i(!1),a(!0);const g=await resolveSessionSwitch({sessionId:e,inTuiResume:u,isModelSelectable:__name(async e=>(await loadCustomProviderModels(),Boolean(resolveKnownModelId2(e))||isByok({model:e})),"isModelSelectable"),isStale:p,onDebug:dlog});if("superseded"===g.status)return;if("error"===g.status){if(p())return;return console.error("Failed to load session:",g.message),r([yh(g.message)]),i(!1),a(!1),void s(crypto.randomUUID())}if(g.adoptedModel&&d?.(g.adoptedModel),g.shareInfo&&c({url:g.shareInfo.url,secret:g.shareInfo.secret}),p())return;r(g.feed);const h=seedTodosFromFeedEntries(g.feed);k$(e)?.applyTodoUserEdit({todos:h}),g.bannerModelChanged||isWrappedChild()?hardResetForResize():RL(),l(e=>e+1)}__name(requestReload,"requestReload"),__name(discardPendingReload,"discardPendingReload"),__name(consumePendingReload,"consumePendingReload"),__name(setOriginalInvocation,"setOriginalInvocation"),__name(getOriginalInvocation,"getOriginalInvocation"),Gt(),SR(),__name(resolveProviderOrReport,"resolveProviderOrReport"),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Gt(),SR(),__name(parseChangelogVersions,"parseChangelogVersions"),__name(findChangelogPath,"findChangelogPath"),__name(handleChangelog,"handleChangelog"),Gt(),SR(),Gt(),SR(),__name(releaseHarness,"releaseHarness"),__name(handleSelectSession,"handleSelectSession");var aj="Nothing to clone yet.";async function handleCloneCommand(e){const t=k$(e.sessionId);if(t)try{const n=await t.cloneSession();if(!n)return void e.setFeed(e=>[...e,uh(aj)]);e.setFeed(e=>[...e,uh(`Cloned to ${n.newId} — switching…`)]),await handleSelectSession({selectedSessionId:n.newId,previousSessionId:e.sessionId,sessionLoadIdRef:e.sessionLoadIdRef,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setSessionId:e.setSessionId,setShowSessionSelector:e.setShowSessionSelector,setSessionLoaded:e.setSessionLoaded,setStaticKey:e.setStaticKey,setShareInfo:e.setShareInfo,setCurrentModel:e.setCurrentModel,inTuiResume:!0})}catch{e.setFeed(e=>[...e,yh("Couldn't clone the session (storage error). Staying on the current session.")])}else e.setFeed(e=>[...e,uh(aj)])}async function handleCompactCommand({sessionId:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:o,setStaticKey:s}){try{r(!0),n("Compacting conversation...");const i=await v$({sessionId:e,baseUrl:getApiBaseUrl()}),a=await i.compact();RL(),s(e=>e+1);const l=buildCompactCommandNotice(a);t(e=>[...e,uh(l.message)]),r(!1),n("Ready..."),o(buildPostCompactContextUsage())}catch(e){t(t=>[...t,yh(buildCompactErrorNotice(e).message)]),r(!1),n("Ready...")}}__name(handleCloneCommand,"handleCloneCommand"),Gt(),SR(),__name(handleCompactCommand,"handleCompactCommand"),Gt(),SR();var lj=__name(e=>{const t=e.metadata?.blockOf;return"string"==typeof t?t:e.id},"groupIdOf"),cj=__name(e=>e.replace(/^(?:[^\S\n]*\n)+/,"").replace(/\s+$/,""),"stripOuterBlankLines");function findLastAssistantText(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(!n||"assistant"!==n.role)continue;if(!n.input.trim())continue;const r=lj(n),o=[];for(let n=t;n>=0;n--){const t=e[n];if(!t||"assistant"!==t.role||lj(t)!==r)break;const s=cj(t.input);s&&o.unshift(s)}return o.length>1?o.join("\n\n"):n.input}return null}async function handleCopy({feed:e,setFeed:t}){const n=findLastAssistantText(e);if(!n)return void t(e=>[...e,uh("Nothing to copy yet — no reply in this session.")]);const r=await writeClipboardText(n),o=n.length.toLocaleString("en-US");t(e=>[...e,uh(r?`Copied the last reply to the clipboard (${o} chars).`:"Could not reach the clipboard — is this a headless terminal?")])}function getAuthKey3(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function trackFirstMessage(){(async()=>{await getAuthKey3()&&await detectAndTrackFirstMessage({loadUserConfig:loadUserConfig,updateUserConfig:updateUserConfig,trackLifecycleEvent:__name(e=>trackLifecycleEvent({...e,isTelemetryEnabled:isTelemetryEnabled,createClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createClient"),log:dlog}),"trackLifecycleEvent"),log:dlog})})().catch(()=>{})}function isWhitespaceOnly3(e){return 0===e.trim().length}function routeTodoWriteEntry(e){const{entry:t,setFeed:n,setLiveEntries:r}=e;if("running"===t.metadata?.status)return!0;const o="output"in t?t.output:void 0,s="string"==typeof o?Nh(o):null;if(!s)return!1;const i=projectUserEdits(s);return i.every(e=>"completed"===e.status)?(clearSessionTodos(),i.length>0&&routeHarnessFeedEntry({entry:{...t,output:JSON.stringify(i)},setFeed:n,setLiveEntries:r}),!0):(setSessionTodos(s),!0)}function createBlockCommittingRouter(e){const{setFeed:t,setLiveEntries:n}=e,r=new Map;function buildBlockEntries(e,t,n){const r=[];for(const o of n){if(isWhitespaceOnly3(o))continue;const n=t.committedEntryCount;t.committedEntryCount+=1;const{status:s,...i}=e.metadata??{};r.push({...e,id:`${e.id}-block-${n}`,input:o,metadata:{...i,continuation:n>0,blockOf:e.id}})}return r}function routeRunningAssistant(e){let o=r.get(e.id);o||(o={stream:createBlockStream(),committedEntryCount:0},r.set(e.id,o));const s=o.stream.advance(e.input),i=buildBlockEntries(e,o,s.newlyCompleted);i.length>0&&t(e=>[...e,...i]);const a={...e,input:s.openTail,metadata:{...e.metadata,continuation:o.committedEntryCount>0}};n(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1===n)return[...t,a];const r=[...t];return r[n]=a,r})}function routeFinalAssistant(e){n(t=>t.filter(t=>t.id!==e.id));const o=r.get(e.id);if(!o)return void(isWhitespaceOnly3(e.input)||t(t=>[...t,e]));r.delete(e.id);const s=o.stream.finalize(e.input);if(0===o.committedEntryCount&&s.remaining.length<=1)return void(isWhitespaceOnly3(e.input)||t(t=>[...t,e]));const i=buildBlockEntries(e,o,s.remaining);i.length>0&&t(e=>[...e,...i])}return __name(buildBlockEntries,"buildBlockEntries"),__name(routeRunningAssistant,"routeRunningAssistant"),__name(routeFinalAssistant,"routeFinalAssistant"),__name(function routeEntry(e){if(isDiscardedEntry(e))return r.delete(e.id),void routeHarnessFeedEntry({entry:e,setFeed:t,setLiveEntries:n});if("assistant"===e.role)"running"!==e.metadata?.status?routeFinalAssistant(e):routeRunningAssistant(e);else{if("tool"===e.role&&"todo_write"===e.name&&routeTodoWriteEntry({entry:e,setFeed:t,setLiveEntries:n}))return;routeHarnessFeedEntry({entry:e,setFeed:t,setLiveEntries:n})}},"routeEntry")}async function getBillingLink({billingLink:e,setBillingLink:t}){return resolveCommandBillingLink({existingBillingLink:e,client:createApiClient({baseUrl:getApiBaseUrl()}),onResolvedBillingLink:t})}async function runModInputInterception(e){const t=getActiveModHost();if(!t||"user"!==e.role||e.isAutomated||e.isMeta||e.isGoalContinuation||0===e.input.length||(e.images?.length??0)>0)return{action:"continue"};try{return await t.transformInput({text:e.input})}catch{return{action:"continue"}}}async function handleSubmit(e){const{role:t,input:n,images:r,imageTokenPaths:o,ideContext:s,ideHint:i,displayMessage:a,isAutomated:l,isMeta:c,source:d,hiddenMessages:u,isGoalContinuation:m,isGoalBootstrap:p,suppressUserEcho:g,feed:h,setFeed:f,setLiveEntries:y,isCmdCodeBusy:S,setIsCmdCodeBusy:w,setQueuedMessages:v,setStatus:k,setInteractionTokens:C,updateStatus:b,setUpdateStatus:E,billingLink:T,setBillingLink:P,currentModel:M,currentProvider:x,premiumCreditsExhausted:I,setPremiumCreditsExhausted:A,setCurrentModel:R,sessionId:L,isSubmittingRef:O,setInput:D,setStaticKey:$,executeBash:N}=e,_=resolveSubmitStartPlan({role:t,input:n,isCmdCodeBusy:S,isSubmitting:O.current,displayMessage:a,isAutomated:l,isMeta:c,source:d,hiddenMessages:u,images:r,ideContext:s,ideHint:i});if("skip"===_.kind&&!n.length)return _.outcome;if(b&&E(null),C(0),"skip"===_.kind)return _.outcome;if("bash"===_.kind){O.current=!0;const e=hh(n);return f([...h,e]),D(""),await N(n,e=>{f(e)},()=>{RL(),$(e=>e+1)}),O.current=!1,"completed"}if("queue"===_.kind)return v(e=>[...e,_.queuedMessage]),l||D(""),_.outcome;O.current=!0;const F=await runModInputInterception(e);if("handled"===F.action){O.current=!1;const e=F.message;return e&&f(t=>[...t,uh(e)]),"skipped"}const U="transform"===F.action?F.text:n;await loadCustomProviderModels();const j=await checkOAuthSetupRequired({currentProvider:x??null,isByokModel:isByok({model:M??""}),providerAuthHeaders:providerAuthHeaders});if(j)return O.current=!1,k(j),f(e=>[...e,yh(j)]),"skipped";w(!0),k(xh()),l||D("");let B=!1,W=null,H=null,G=null,V=0;const z=createSubmitGoalSupervisor(e);let K=null;const q=resolvePremiumCreditsPreflight({premiumCreditsExhausted:I,currentModel:M});if(q.blocked)return B=!0,k(q.status),f(e=>[...e,uh(q.message)]),w(!1),O.current=!1,q.outcome;try{K=await z.getGoalTurnBudget();const e=await v$({sessionId:L,baseUrl:getApiBaseUrl()});if(p&&!isCommandGoalLoopArmed(L))return"skipped";const t=clipboardImagesToUserContent(r),n=s?`${s}\n\n${U}`:U,l=t.length>0?[...t,{type:"text",text:n}]:s?[{type:"text",text:n}]:void 0,c={...r&&r.length>0?{images:r,...o?{imageTokenPaths:o}:{}}:{},...i?{ideHint:i}:{}};trackFirstMessage();const d=await runHarnessTurnIntoFeed({harness:e,input:U,turnUserInput:l,runQuery:runHarnessQuery,setFeed:f,setLiveEntries:y,displayMessage:a,suppressUserEcho:g,additionalContent:hiddenMessagesToUserContent(u),inputMeta:_.inputMeta,maxTurns:K?.remainingTurns,onRoundTrip:__name(e=>{V=e},"onRoundTrip"),echoMetadata:Object.keys(c).length>0?c:void 0,setStatus:k,onInteractionTokens:C,onRunError:__name(e=>{H=e},"onRunError"),routeEntry:createBlockCommittingRouter({setFeed:f,setLiveEntries:y}),scrubGoalCompleteMarker:isCommandGoalLoopArmed(L)});if(H){const e=M?byokProviderId({model:M}):void 0;throw formatRunError(H,e?{byokProvider:e}:void 0)}return G=d.finalText,V=d.turnCount,"completed"}catch(e){const t=resolveSubmitErrorAction({error:e,sessionId:L});if("interrupted"===t.kind)return B=!0,t.outcome;if(trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"submit_error"}),context:{component:Ho.SUBMIT,heading:"Prompt submission failed",code:t.kind}}),B=!0,W=t.goalErrorKind,"insufficient-credits"===t.kind){k(t.status);const e=await getBillingLink({billingLink:T,setBillingLink:P});return f(t=>[...t,yh(buildInsufficientCreditsSubmitActionMessage({billingUrl:e}))]),t.outcome}if("premium-credits-exhausted"===t.kind)return A?.(!0),R?.(t.fallbackModelId),RL(),$(e=>e+1),k(t.status),f(e=>[...e,uh(t.message)]),t.outcome;k(t.status);const n="info"===t.renderKind?uh(t.message):yh(t.message);return f(e=>[...e,n]),t.outcome}finally{w(!1),B||k("Ready..."),O.current=!1,await z.afterTurn({assistantText:B?null:G,errorKind:B?W:null,isGoalContinuation:m,turnsUsed:V,goalStartedAt:K?.startedAt})}return"skipped"}function emitGoalNotice(e,t){e(e=>[...e,uh(t.message,buildGoalNoticeMetadata(t))])}function createSubmitGoalSupervisor(e){const{sessionId:t,setFeed:n}=e;return createGoalTurnSupervisor({sessionId:t,isArmed:__name(()=>isCommandGoalLoopArmed(t),"isArmed"),disarm:__name(()=>disarmCommandGoalLoop(t),"disarm"),loadSessionMeta:__name(()=>loadCommandSessionMeta({sessionId:t}),"loadSessionMeta"),saveGoal:__name(e=>saveCommandSessionMeta({sessionId:t,meta:{goal:e}}),"saveGoal"),verifyCompletion:__name(async e=>(k$(t)??await v$({sessionId:t,baseUrl:getApiBaseUrl()})).verifyGoal(e),"verifyCompletion"),getEvidence:__name(()=>{const e=k$(t);return e?harnessRecentToolEvidence(e):""},"getEvidence"),emitCompletion:__name(e=>{n(t=>[...t,uh("",e)])},"emitCompletion"),emitNotice:__name(e=>emitGoalNotice(n,e),"emitNotice"),runContinuation:__name(({prompt:t})=>handleSubmit({...e,...buildGoalContinuationTurnFields({prompt:t})}),"runContinuation")})}async function handleDesignCommand({ctx:e,rawArguments:t,positionalArgs:n,command:r}){try{const o=await resolveDesignCommand({runtime:createNodeRuntime(),rawArguments:t,positionalArgs:n});if("help"===o.status)return void e.setShowDesignGuide(!0);if("missing-skill"===o.status)return void e.setFeed(e=>[...e,yh(GC)]);const s=await handleSubmit({input:o.command.visible,hiddenMessages:[{role:"user",content:o.command.hidden}],role:"user",displayMessage:r,isAutomated:!0,feed:e.feed,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,setQueuedMessages:e.setQueuedMessages,setStatus:e.setStatus,setInteractionTokens:e.setInteractionTokens,updateStatus:e.updateStatus,setUpdateStatus:e.setUpdateStatus,billingLink:e.billingLink,setBillingLink:e.setBillingLink,currentModel:e.currentModel,currentProvider:e.currentProvider,premiumCreditsExhausted:e.premiumCreditsExhausted,setPremiumCreditsExhausted:e.setPremiumCreditsExhausted,setCurrentModel:e.setCurrentModel,sessionId:e.sessionId,isSubmittingRef:e.isSubmittingRef,setInput:e.setInput,setStaticKey:e.setStaticKey,executeBash:e.executeBash}),{modeName:i}=o.command;if("completed"===s&&i&&isDesignMode(i)){const t=getDesignModeSuggestions(i);t&&e.setPendingDesignSuggestion?.(t)}}catch(t){e.setFeed(e=>[...e,yh(buildDesignSkillLoadErrorMessage(t))])}}__name(findLastAssistantText,"findLastAssistantText"),__name(handleCopy,"handleCopy"),Gt(),SR(),Gt(),SR(),Gt(),SR(),__name(getAuthKey3,"getAuthKey"),__name(trackFirstMessage,"trackFirstMessage"),Gt(),SR(),__name(isWhitespaceOnly3,"isWhitespaceOnly"),__name(routeTodoWriteEntry,"routeTodoWriteEntry"),__name(createBlockCommittingRouter,"createBlockCommittingRouter"),__name(getBillingLink,"getBillingLink"),__name(runModInputInterception,"runModInputInterception"),__name(handleSubmit,"handleSubmit"),__name(emitGoalNotice,"emitGoalNotice"),__name(createSubmitGoalSupervisor,"createSubmitGoalSupervisor"),__name(handleDesignCommand,"handleDesignCommand"),Gt(),SR();var dj="Nothing to export yet — the transcript is created on the first message.",uj=new Set(["html","jsonl","md"]);function matchFormatKeyword(e){const t=e.toLowerCase();return uj.has(t)?t:void 0}function resolveConfiguredExportFormat(e){return e?matchFormatKeyword(e)??"html":"html"}function defaultExportFilename(e,t){return`command-code-session-${e.slice(0,8)}.${t}`}function resolveExportRoute(e){const t=e.rawPath.trim();if(!t){const t=e.defaultFormat??"html";return{kind:"target",format:t,path:n(e.cwd,defaultExportFilename(e.sessionId,t))}}const r=matchFormatKeyword(t);if(r)return{kind:"target",format:r,path:n(e.cwd,defaultExportFilename(e.sessionId,r))};const o=a(t)?t:s(e.cwd,t);if(A(o)&&N(o).isDirectory())return{kind:"target",format:"html",path:n(o,defaultExportFilename(e.sessionId,"html"))};const i=d(o).toLowerCase();return i?".html"===i?{kind:"target",format:"html",path:o}:".jsonl"===i?{kind:"target",format:"jsonl",path:o}:".md"===i?{kind:"target",format:"md",path:o}:{kind:"unknown-extension",extension:i}:{kind:"target",format:"html",path:n(o,defaultExportFilename(e.sessionId,"html"))}}function exportedMessage(e){const t=toRelativePath(e.path),n=At.isSupported?createOSC8Link(fileUrl(e.path),t,!1):t;return`Exported ${e.formatLabel} session to ${n}`}async function buildSessionHtmlExport(e){const{messages:t}=await loadCommandSessionMessages({sessionId:e.sessionId});if(0===t.length)return null;const n=await loadCommandUserRenamedTitle({sessionId:e.sessionId})??e.sessionId;return renderSessionHtml({messages:fromV2(t.map(e=>e.message)),title:n,sessionId:e.sessionId,exportedAt:(new Date).toISOString(),...e.currentModel?{model:e.currentModel}:{}})}async function buildSessionMarkdownExport(e){const{messages:t}=await loadCommandSessionMessages({sessionId:e.sessionId});if(0===t.length)return null;const n=await loadCommandUserRenamedTitle({sessionId:e.sessionId})??e.sessionId;return renderSessionMarkdown({messages:fromV2(t.map(e=>e.message)),title:n,sessionId:e.sessionId,exportedAt:(new Date).toISOString(),...e.currentModel?{model:e.currentModel}:{}})}async function exportJsonl(e){const t=n(getProjectSessionDir({env:process.env,cwd:e.cwd}),`${e.sessionId}.jsonl`);if(A(t)){try{U(t,e.target)}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,uh(`Export failed: ${n}`)])}e.setFeed(t=>[...t,uh(exportedMessage({path:e.target,formatLabel:"JSONL"}))])}else e.setFeed(e=>[...e,uh(dj)])}async function exportHtml(e){let t;try{t=await buildSessionHtmlExport({sessionId:e.sessionId,currentModel:e.currentModel})}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,uh(`Export failed: ${n}`)])}if(t){try{O(e.target,t,"utf8")}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,uh(`Export failed: ${n}`)])}e.setFeed(t=>[...t,uh(exportedMessage({path:e.target,formatLabel:"HTML"}))])}else e.setFeed(e=>[...e,uh(dj)])}async function exportMarkdown(e){let t;try{t=await buildSessionMarkdownExport({sessionId:e.sessionId,currentModel:e.currentModel})}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,uh(`Export failed: ${n}`)])}if(t){try{O(e.target,t,"utf8")}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,uh(`Export failed: ${n}`)])}e.setFeed(t=>[...t,uh(exportedMessage({path:e.target,formatLabel:"Markdown"}))])}else e.setFeed(e=>[...e,uh(dj)])}async function handleExport(e){const t=getCurrentWorkingDirectory(),n=await loadUserConfig(),r=resolveExportRoute({rawPath:e.rawPath,cwd:t,sessionId:e.sessionId,defaultFormat:resolveConfiguredExportFormat(n.defaultExportFormat)});"unknown-extension"!==r.kind?"jsonl"!==r.format?"md"!==r.format?await exportHtml({sessionId:e.sessionId,target:r.path,currentModel:e.currentModel,setFeed:e.setFeed}):await exportMarkdown({sessionId:e.sessionId,target:r.path,currentModel:e.currentModel,setFeed:e.setFeed}):await exportJsonl({sessionId:e.sessionId,target:r.path,cwd:t,setFeed:e.setFeed}):e.setFeed(e=>[...e,uh(`Unknown export extension "${r.extension}". Supported export formats: .html, .jsonl, .md`)])}async function handleForkCommand(e,t){const n=k$(e.sessionId),r=await resolveForkCommand({sourceId:e.sessionId,rawName:t,hasActiveSession:Boolean(n),messageCount:n?harnessSessionMessages(n).length:0});if("notice"!==r.kind)try{await handleSelectSession({selectedSessionId:r.newId,previousSessionId:e.sessionId,sessionLoadIdRef:e.sessionLoadIdRef,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setSessionId:e.setSessionId,setShowSessionSelector:e.setShowSessionSelector,setSessionLoaded:e.setSessionLoaded,setStaticKey:e.setStaticKey,setShareInfo:e.setShareInfo,setCurrentModel:e.setCurrentModel,inTuiResume:!0}),e.setFeed(e=>[...e,mh({name:r.title})])}catch{e.setFeed(e=>[...e,yh($f)])}else e.setFeed(e=>[...e,"error"===r.notice.kind?yh(r.notice.message):uh(r.notice.message)])}function setMode(e,t){e.permissionModeRef.current=t,e.setPermissionMode(t),k$(e.sessionId)?.setPermissionMode({mode:t})}async function handlePlanCommand({rawArguments:e,ctx:t}){const n=resolvePlanCommand({rawArguments:e,currentMode:t.permissionModeRef.current});if(t.permissionModeRef.current!==n.nextMode&&setMode(t,n.nextMode),"notice"===n.kind)return t.setFeed(e=>[...e,uh(n.message)]),void(n.clearInput&&t.setInput(""));await handleSubmit({input:n.task,role:"user",displayMessage:n.displayMessage,isAutomated:!0,feed:t.feed,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,currentModel:t.currentModel,currentProvider:t.currentProvider,premiumCreditsExhausted:t.premiumCreditsExhausted,setPremiumCreditsExhausted:t.setPremiumCreditsExhausted,setCurrentModel:t.setCurrentModel,sessionId:t.sessionId,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash})}__name(matchFormatKeyword,"matchFormatKeyword"),__name(resolveConfiguredExportFormat,"resolveConfiguredExportFormat"),__name(defaultExportFilename,"defaultExportFilename"),__name(resolveExportRoute,"resolveExportRoute"),__name(exportedMessage,"exportedMessage"),__name(buildSessionHtmlExport,"buildSessionHtmlExport"),__name(buildSessionMarkdownExport,"buildSessionMarkdownExport"),__name(exportJsonl,"exportJsonl"),__name(exportHtml,"exportHtml"),__name(exportMarkdown,"exportMarkdown"),__name(handleExport,"handleExport"),Gt(),SR(),__name(handleForkCommand,"handleForkCommand"),Gt(),SR(),__name(setMode,"setMode"),__name(handlePlanCommand,"handlePlanCommand"),Gt(),SR();var mj=[{title:"Composing",rows:[{keys:"Enter",action:"Send the prompt"},{keys:"Shift+Enter / Alt+Enter",action:"Insert a newline"},{keys:"Ctrl+G",action:"Edit the prompt in $EDITOR"},{keys:"Ctrl+S",action:"Stash / restore the current prompt"},{keys:"↑ / ↓",action:"Browse prompt history"},{keys:"@",action:"Mention a file (fuzzy search)"},{keys:"/",action:"Open the command menu"},{keys:"!",action:"Bash mode — run a shell command"}]},{title:"While it works",rows:[{keys:"Esc",action:"Interrupt the current turn"},{keys:"Type + Enter",action:"Queue a steering message"},{keys:"Ctrl+X",action:"Open the todo manager (/todos) for the current plan"}]},{title:"Transcript",rows:[{keys:"Ctrl+O",action:"Toggle expanded tool output"},{keys:"Ctrl+E / Ctrl+Y",action:"Toggle the full transcript"}]},{title:"Session & modes",rows:[{keys:"Shift+Tab",action:"Cycle mode: standard → accept edits → plan → yolo"},{keys:"Alt+P",action:"Quick model switch"},{keys:"Esc Esc",action:"Rewind to a checkpoint"},{keys:"Ctrl+C Ctrl+C",action:"Exit"}]}];function buildHotkeysMarkdown(){const e=["**Keyboard shortcuts**"];for(const t of mj){e.push("",`**${t.title}**`);for(const n of t.rows)e.push(`- \`${n.keys}\` — ${n.action}`)}return e.join("\n")}function handleHotkeys({setFeed:e}){e(e=>[...e,fh(buildHotkeysMarkdown())])}async function handleImportCommand({setFeed:e},t=""){const n=resolveAgentImportSourceArg(t);if(!n.ok)return void e(e=>[...e,yh(n.message)]);const r=createNodeRuntime();try{const t=await detectAgentImport({runtime:r,sources:n.sources});if(0===t.items.length&&0===t.sourceErrors.length)return void e(e=>[...e,uh("No setup was found to import (looked for Claude Code, Codex, Cursor, Pi, OpenCode, and Gemini CLI config in your home directory and this project).")]);const o=await importAgentSetup({runtime:r,inventory:t});e(e=>[...e,uh(formatAgentImportSummary(o))])}catch(t){e(e=>[...e,yh(`Import failed: ${t instanceof Error?t.message:"unknown error"}`)])}}function setMode2(e,t){e.permissionModeRef.current=t,e.setPermissionMode(t),k$(e.sessionId)?.setPermissionMode({mode:t})}async function handleModeCommand({rawArguments:e,ctx:t}){const n=resolveModeCommand({rawArguments:e,currentMode:t.permissionModeRef.current});n.nextMode&&setMode2(t,n.nextMode),t.setFeed(e=>[...e,uh(n.message)]),t.setInput("")}async function applyRenameResult(e){const t=await resolveRenameCommand({name:e.name,sessionId:e.sessionId});if(e.setFeed(e=>[...e,"error"===t.notice.kind?yh(t.notice.message):uh(t.notice.message)]),"renamed"===t.kind){e.setRenamedTerminalTitle(t.name);try{(e.harness??await v$({sessionId:e.sessionId,baseUrl:getApiBaseUrl()})).setSessionName(t.name)}catch{}}}async function autoRenameSession({sessionId:e,setFeed:t,setRenamedTerminalTitle:n,setStatus:r,setIsCmdCodeBusy:o}){o(!0),r("Naming session…");try{const r=await v$({sessionId:e,baseUrl:getApiBaseUrl()}),o=await r.regenerateTitle();if(!o)return void t(e=>[...e,uh("Nothing to name yet — send a message first, or use /rename <name>.")]);await applyRenameResult({name:o,sessionId:e,setFeed:t,setRenamedTerminalTitle:n,harness:r})}catch{t(e=>[...e,uh("Could not generate a title. Try /rename <name> instead.")])}finally{o(!1),r("Ready...")}}async function handleRenameCommand(e){e.name.trim()?await applyRenameResult({name:e.name,sessionId:e.sessionId,setFeed:e.setFeed,setRenamedTerminalTitle:e.setRenamedTerminalTitle}):await autoRenameSession(e)}async function handleNameCommand(e){if(e.name.trim())return void await applyRenameResult({name:e.name,sessionId:e.sessionId,setFeed:e.setFeed,setRenamedTerminalTitle:e.setRenamedTerminalTitle});const t=k$(e.sessionId)?.getSessionStats().name,n=t?null:await loadCommandSessionMeta({sessionId:e.sessionId}).catch(()=>null),r=t??n?.title;e.setFeed(e=>[...e,uh(r?`Current name: ${r}`:"This session has no name yet. Use /name <name> to set one.")])}function handleRewindCommand({sessionId:e,setFeed:t,setShowRewindSelector:n}){const r=k$(e),o=resolveRewindCommand({hasActiveConversation:Boolean(r),checkpointCount:r?.listCheckpoints().length??0});"notice"!==o.kind?n(!0):t(e=>[...e,"error"===o.notice.kind?yh(o.notice.message):uh(o.notice.message)])}async function handleRewindSelect({messageId:e,mode:t,sessionId:n,setFeed:r,setStatus:o,setShowRewindSelector:s,setStaticKey:i,setInput:a}){s(!1);const l=k$(n);if(!l)return;o("Restoring checkpoint...");const c=await performRewindRestore({harness:l,messageId:e,mode:t});if("restored"===c.kind)return r(c.feed),l.applyTodoUserEdit({todos:seedTodosFromFeedEntries(c.feed)}),RL(),i(e=>e+1),c.promptToRestore&&a(c.promptToRestore),r(e=>[...e,uh(c.notice.message)]),void o(c.statusMessage);r(e=>[...e,"error"===c.notice.kind?yh(c.notice.message):uh(c.notice.message)]),o(c.statusMessage)}function handleRewindCancel({setShowRewindSelector:e}){e(!1)}function compactTranscriptPath(e){return`${toRelativePath(getProjectsBasePath({env:process.env}))}/…/${c(e)}`}function formatSessionFileLine(e){const{absolutePath:t,exists:n,linksSupported:r}=e;return n?r?createOSC8Link(fileUrl(t),compactTranscriptPath(t),!1):t:`${t} (not created yet)`}function handleSessionFile({sessionId:e,setFeed:t}){if(!e)return void t(e=>[...e,uh("No active session.")]);const r=n(getProjectSessionDir({env:process.env,cwd:getCurrentWorkingDirectory()}),`${e}.jsonl`),o=formatSessionFileLine({absolutePath:r,exists:A(r),linksSupported:At.isSupported});t(t=>[...t,uh(`Session ID: ${e}\nCurrent session file: ${r}`,{isSessionFile:!0,sessionFileId:e,sessionFileLine:o})])}__name(buildHotkeysMarkdown,"buildHotkeysMarkdown"),__name(handleHotkeys,"handleHotkeys"),Gt(),SR(),__name(handleImportCommand,"handleImportCommand"),Gt(),SR(),__name(setMode2,"setMode"),__name(handleModeCommand,"handleModeCommand"),Gt(),SR(),__name(applyRenameResult,"applyRenameResult"),__name(autoRenameSession,"autoRenameSession"),__name(handleRenameCommand,"handleRenameCommand"),__name(handleNameCommand,"handleNameCommand"),Gt(),SR(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),Gt(),SR(),__name(compactTranscriptPath,"compactTranscriptPath"),__name(formatSessionFileLine,"formatSessionFileLine"),__name(handleSessionFile,"handleSessionFile"),Gt(),SR();var pj=Me(f),gj=/https:\/\/gist\.github\.com\/\S+/;function parseGistUrl(e){const t=gj.exec(e);return t?t[0]:null}function execErrorText(e){if(!(e instanceof Error))return String(e);const t=e;return("string"==typeof t.stderr?t.stderr.trim():"")||e.message}async function defaultCreateGist(e){const{stdout:t}=await pj("gh",["gist","create",e,"--desc","Command Code session"],{encoding:"utf8"});return{stdout:String(t)}}async function resolveShareGistFormat(e){const t=(e??"").trim();return t?matchFormatKeyword(t):resolveConfiguredExportFormat((await loadUserConfig()).defaultShareGistFormat)}async function writeGistPayload(e){const t=n(e.tempDir,`command-code-session-${e.sessionId.slice(0,8)}.${e.format}`);if("jsonl"===e.format){const r=n(getProjectSessionDir({env:process.env,cwd:getCurrentWorkingDirectory()}),`${e.sessionId}.jsonl`);return A(r)?(U(r,t),t):null}if("md"===e.format){const n=await e.buildMarkdownExport({sessionId:e.sessionId,currentModel:e.currentModel});return n?(await K(t,n,"utf8"),t):null}const r=await e.buildHtmlExport({sessionId:e.sessionId,currentModel:e.currentModel});return r?(await K(t,r,"utf8"),t):null}async function handleShareGistCommand(e){const{isCommandAvailable:t=isCommandAvailable,buildHtmlExport:r=buildSessionHtmlExport,buildMarkdownExport:o=buildSessionMarkdownExport,createGist:s=defaultCreateGist,writeClipboardText:i=writeClipboardText}=e.deps??{},a=__name(t=>e.setFeed(e=>[...e,uh(t)]),"info");if(!t("gh"))return void a("Requires the GitHub CLI (gh) — https://cli.github.com");const l=await resolveShareGistFormat(e.rawFormatArg);if(!l)return void a(`Unknown gist format "${(e.rawFormatArg??"").trim()}". Supported gist formats: html, jsonl, md`);let c;try{c=await ae(n(H(),"cmd-share-"));const t=await writeGistPayload({format:l,sessionId:e.sessionId,currentModel:e.currentModel,tempDir:c,buildHtmlExport:r,buildMarkdownExport:o});if(!t)return void a("Nothing to share yet — the transcript is created on the first message.");const{stdout:d}=await s(t),u=parseGistUrl(d);if(!u)return void a(`gh gist create did not return a URL: ${d.trim()}`);await i(u),a(`Shared session gist: ${At.isSupported?createOSC8Link(u,u,!1):u}`)}catch(e){const t=execErrorText(e);a(/auth/i.test(t)?`${t} — run gh auth login`:`Share failed: ${t}`)}finally{c&&await X(c,{recursive:!0,force:!0}).catch(()=>{})}}async function copyOrFallback(e,t){return!!await writeClipboardText(e)||(t(buildShareClipboardFallbackStatus(e)),!1)}async function handleShareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setShowShareNotification:o}){!t&&e&&r("Creating share link...");const s=createApiClient({baseUrl:getApiBaseUrl()}),i=await createCommandSessionShareLink({client:s,sessionId:e,existingShareInfo:t,harness:e?k$(e):void 0,projectRoot:global.COMMAND_CODE_CWD||process.cwd()});"no-session"!==i.status&&"error"!==i.status?(n(i.shareInfo),await copyOrFallback(i.shareInfo.url,r)&&(r(""),o(!0),setTimeout(()=>{o(!1)},shareNotificationDurationMs(i.status)))):r(i.message)}async function handleUnshareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setUnshareNotificationMessage:o}){e&&t&&r("Removing share link...");const s=createApiClient({baseUrl:getApiBaseUrl()}),i=await deleteCommandSessionShareLink({client:s,sessionId:e,shareInfo:t,harness:e?k$(e):void 0});if("no-session"!==i.status){if("not-shared"===i.status)return o(i.message),void setTimeout(()=>o(""),mC);if("error"===i.status)return r(i.message),void setTimeout(()=>r(""),mC);o(i.message),r(""),n(null),setTimeout(()=>{o("")},mC)}else r(i.message)}async function loadPersistedTraceIds(e){if(e.loadTraceIds)return e.loadTraceIds();if(!e.sessionId)return[];const t=await loadCommandSessionMeta({sessionId:e.sessionId}).catch(()=>null),n=t?.traceIds;return Array.isArray(n)?n.filter(e=>"string"==typeof e&&e.length>0):[]}async function handleTrace({setFeed:e,sessionId:t,loadTraceIds:n}){const r=getTraceId();if(r){const t=await writeClipboardText(r)?" (copied to clipboard)":"";return void e(e=>[...e,uh(`Trace ID: ${r}${t}`)])}const o=await loadPersistedTraceIds({sessionId:t,loadTraceIds:n});if(o.length>0){const t=o[o.length-1],n=await writeClipboardText(t)?" (copied to clipboard)":"";return void e(e=>[...e,uh(`Trace ID: ${t}${n}`)])}const s=isTelemetryInitialized()?"Trace ID not generated: Send a message first":"No trace ID — request tracing is off this session.";e(e=>[...e,uh(s)])}function actionErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}async function handleTreeCommand({sessionId:e,setFeed:t,setShowTreeSelector:n,setTreeFilterMode:r,setTreeBranchSummarySkipPrompt:o}){const s=k$(e),i=resolveTreeCommand({hasActiveConversation:Boolean(s),treeEntryCount:s?.getSessionTree().length??0});if("notice"===i.kind)return void t(e=>[...e,"error"===i.notice.kind?yh(i.notice.message):uh(i.notice.message)]);const[a,l]=await Promise.all([getTreeFilterMode(),getBranchSummarySkipPrompt()]);r(a),o(l),n(!0)}async function handleTreeSelect({entryId:e,summarize:t,customInstructions:n,sessionId:r,setFeed:o,setShowTreeSelector:s,setStaticKey:i,setInput:a}){const l=k$(r);if(!l)return{aborted:!1};try{const r=await l.navigateTree({targetId:e,summarize:t,...n?{customInstructions:n}:{}});return r.aborted?{aborted:!0}:r.cancelled?(o(e=>[...e,uh("Already at this point")]),{aborted:!1}):(s(!1),o(reconstructFeedFromMessages(harnessSessionMessages(l))),RL(),i(e=>e+1),r.editorText&&a(r.editorText),o(e=>[...e,uh("Navigated to selected point")]),{aborted:!1})}catch(e){return o(t=>[...t,yh(`Failed to navigate: ${actionErrorMessage(e)}`)]),{aborted:!1}}}function handleTreeCancel({setShowTreeSelector:e}){e(!1)}function handleTreeAbortSummary({sessionId:e}){k$(e)?.abortBranchSummary()}function handleTreeLabel({entryId:e,label:t,sessionId:n,setFeed:r}){const o=k$(n);if(o)try{o.setTreeLabel({targetId:e,label:t})}catch(e){r(t=>[...t,yh(`Failed to set label: ${actionErrorMessage(e)}`)])}}function announceCompletedUpdate({fromVersion:e,toVersion:t}){console.log(Et.green(`Updated ${e} → ${t}`))}function trackUpdateFailure({fromVersion:e,targetVersion:t,trigger:n,userName:r,failureReason:o}){trackError({error:new Error(`Update failed: ${e} -> ${t}${o?`: ${o}`:""}`),context:{component:Ho.UPDATER,heading:"CLI update failed (atomic + fallback)","cmd.update.from_version":e,"cmd.update.target_version":t,"cmd.update.trigger":n,...o&&{"cmd.update.failure_reason":o},...r&&{"user.name":r}}})}__name(parseGistUrl,"parseGistUrl"),__name(execErrorText,"execErrorText"),__name(defaultCreateGist,"defaultCreateGist"),__name(resolveShareGistFormat,"resolveShareGistFormat"),__name(writeGistPayload,"writeGistPayload"),__name(handleShareGistCommand,"handleShareGistCommand"),__name(copyOrFallback,"copyOrFallback"),__name(handleShareCommand,"handleShareCommand"),__name(handleUnshareCommand,"handleUnshareCommand"),Gt(),SR(),__name(loadPersistedTraceIds,"loadPersistedTraceIds"),__name(handleTrace,"handleTrace"),Gt(),SR(),__name(actionErrorMessage,"actionErrorMessage"),__name(handleTreeCommand,"handleTreeCommand"),__name(handleTreeSelect,"handleTreeSelect"),__name(handleTreeCancel,"handleTreeCancel"),__name(handleTreeAbortSummary,"handleTreeAbortSummary"),__name(handleTreeLabel,"handleTreeLabel"),Gt(),SR(),Gt(),SR(),__name(announceCompletedUpdate,"announceCompletedUpdate"),__name(trackUpdateFailure,"trackUpdateFailure");var hj={createLifecycleEventClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createLifecycleEventClient"),isTelemetryEnabled:isTelemetryEnabled,log:dlog,onCompletedUpdate:announceCompletedUpdate,trackUpdateFailure:trackUpdateFailure},fj={updatedVersionThisSession:null};async function handleUpdateCommand({setFeed:e,setStatus:t,setIsCmdCodeBusy:n,setUpdateStatus:r,pinnedStatusRef:o}){const s=__name(e=>{"busy"===e.type&&n(e.value),"pin-status"===e.type&&(o.current=e.value),"status"===e.type&&t(e.value),"update-status"===e.type&&r(e.value)},"emit"),i=await runTuiUpdateCommand({state:fj,host:hj,copy:{binCommand:`${getBinaryCommand()}`,updateCommand:"npm i -g command-code"},emit:s});trackTuiUpdateCommandTelemetry(i),"error"!==i.level?e(e=>[...e,uh(i.message,i.metadata)]):e(e=>[...e,yh(i.message)])}function tildeHome(e){const t=B.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function formatWorktreePathLine(e){return` ${ht.dim(gt.arrowRight)} ${createOSC8Link(fileUrl(e),tildeHome(e))}`}function enterWorktreeFromFlag(e,t={}){const{quiet:n=!1,track:r=!0}=t,o=process.cwd();if(!isGitRepo(o))return{ok:!1,error:"--worktree requires a git repository (none found here)."};const s=getMainWorktreeRoot(o)??o,i=createWorktree({spec:"string"==typeof e?e.trim():void 0,cwd:o});if(!i.ok)return{ok:!1,error:i.error};try{process.chdir(i.target.worktreePath),global.COMMAND_CODE_CWD=i.target.worktreePath}catch(e){return{ok:!1,error:`couldn't enter worktree: ${e instanceof Error?e.message:String(e)}`}}if(r&&i.created&&markAutoCreatedWorktree({worktreePath:i.target.worktreePath,branch:i.target.branch,baseSha:i.baseSha,mainRoot:s}),!n){const e=i.created?"Created":"Entered",t=i.created?ht.dim(` (branch ${i.target.branch}${i.usedRemote?", from origin":""})`):"",n=i.created&&i.copiedFiles>0?ht.dim(` · copied ${i.copiedFiles} file(s)`):"",r=i.created&&i.copyFailedFiles.length>0?ht.dim(` · ${i.copyFailedFiles.length} include copy failure(s)`):"";process.stdout.write(`${ht.cyan(gt.squareSmallFilled)} ${e} worktree ${ht.bold(i.target.name)}${t}${n}${r}\n${formatWorktreePathLine(i.target.worktreePath)}\n`)}return dlog(`[worktree] entered ${i.target.worktreePath} (created=${i.created})`),{ok:!0,name:i.target.name,path:i.target.worktreePath}}__name(handleUpdateCommand,"handleUpdateCommand"),Gt(),SR(),Gt(),SR(),__name(tildeHome,"tildeHome"),__name(formatWorktreePathLine,"formatWorktreePathLine"),__name(enterWorktreeFromFlag,"enterWorktreeFromFlag");var yj=__name((e,t)=>e.setFeed(e=>[...e,uh(t)]),"info"),Sj=__name((e,t)=>e.setFeed(e=>[...e,yh(t)]),"error");function renderList(e,n){const r=listWorktrees(e);return 0===r.length?"No worktrees found.":["Worktrees:",...r.map(r=>{const o=samePath2(r.path,e)?"●":"○",s=t.relative(n,r.path),i=r.isMain?".":s&&!s.startsWith("..")?s:tildeHome(r.path);return` ${o} ${r.isMain?`${i} (main)`:i}${r.branch?` [${r.branch}]`:" [detached]"}`}),"","Switch with /worktree <name>."].join("\n")}async function handleWorktreeCommand(e,t){const n=process.cwd();if(!isGitRepo(n))return void Sj(e,"/worktree requires a git repository.");const r=getMainWorktreeRoot(n)??n,o=t[0]?.toLowerCase();if(!o||"list"===o||"ls"===o)return void yj(e,renderList(n,r));if("remove"===o||"rm"===o){const o=t[1];return o?void await handleRemove(e,o,n,r):void Sj(e,"Usage: /worktree remove <name>")}const s="new"===o||"create"===o||"add"===o?t[1]:t[0];await handleSwitch(e,s,n)}async function handleRemove(e,n,r,o){const s=resolveTarget(n,o);if(samePath2(s.worktreePath,r))return void Sj(e,"Can't remove the worktree you're in. Switch away first, then remove it.");if(!listWorktrees(r).some(e=>samePath2(e.path,s.worktreePath)))return void Sj(e,`No worktree named "${n}".`);const i=removeWorktree({worktreePath:s.worktreePath,cwd:r,deleteBranch:isManagedWorktreePath(s.worktreePath,o)?s.branch:void 0});i.ok?yj(e,`Removed worktree "${n}".`):Sj(e,`Couldn't remove "${n}": ${i.message}. Commit or stash changes, or remove it manually with: git worktree remove --force ${t.relative(o,s.worktreePath)}`)}async function handleSwitch(e,t,n){const r=createWorktree({spec:t,cwd:n});if(!r.ok)return void Sj(e,`Couldn't create worktree: ${r.error}`);if(samePath2(r.target.worktreePath,n))return void yj(e,`Already in worktree "${r.target.name}".`);const o=r.created?"Created":"Reusing",s=r.created&&r.copiedFiles>0?` (copied ${r.copiedFiles} file(s))`:"",i=r.created&&r.copyFailedFiles.length>0?` (${r.copyFailedFiles.length} include copy failure(s))`:"";yj(e,`${o} worktree "${r.target.name}"${s}${i}. Switching… (a fresh session starts in the worktree; this one stays resumable).`),await(k$(e.sessionId)?.flush().catch(()=>{})),requestReload(buildReloadCarryoverState({sessionId:e.sessionId,permissionMode:e.permissionModeRef.current,worktree:r.target.name})),e.setShouldExit(!0)}function handleHelpCommand({setFeed:e}){e(e=>[...e,fh(Fh)])}async function handleTerminalSetupCommand({setFeed:e}){const t=dh("/terminal-setup"),n=setupVSCodeTerminal(),r=wh(n.message,!n.success,n.details),o=wh("Terminal tab titles need no setup — titles are set automatically via standard escape sequences (VS Code 1.117+ honors them out of the box).",!1),s=isKittyKeyboardActive()?[wh("Shift+Enter already works natively in this terminal (kitty keyboard protocol) — the VS Code keybindings only apply inside a VS Code-family terminal.",!1)]:[];e(e=>[...e,t,r,o,...s])}async function handleIDESetupCommand({setFeed:e}){const t=await runIdeSetup({host:oj,moduleUrl:import.meta.url}),n=vh(t.status,t.ide,t.details);e(e=>[...e,n])}async function handleClearCommand({setFeed:e,setLiveEntries:t,setQueuedMessages:n,setShareInfo:r,setShowShareNotification:o,setUnshareNotificationMessage:s,setStaticKey:i,setContextUsage:a,setInteractionTokens:l,sessionId:c,setSessionId:d,clearSessionPermissions:u}){e([]),t([]),n([]),clearSessionTodos(),clearShellTasks(),RL(),r(null),o(!1),s(""),await deleteCommandSessionShareInfo({sessionId:c}).catch(()=>{});const m=k$(c);m?.stopBackgroundLearning(),await(m?.flush().catch(()=>{})),C$(c),setNextSessionStartSource("clear"),d(crypto.randomUUID()),u(),i(e=>e+1),a(null),l(0)}async function handleInitCommand({setFeed:e}){const t=await resolveInitMemoryCommand({projectRoot:process.cwd()});e(e=>[...e,uh(t.message)])}async function runGoalTurn(e,t,n,r){await handleSubmit({role:"user",input:buildSlashCommandMessage({commandName:"/goal",skillName:"goal",rawArguments:t}),images:n,ideContext:r,suppressUserEcho:!0,persistVisibleMessage:!0,isAutomated:!0,isGoalBootstrap:!0,hiddenMessages:[{role:"user",content:buildGoalPrompt({kind:"bootstrap",goalText:t})}],feed:e.feed,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,setQueuedMessages:e.setQueuedMessages,setStatus:e.setStatus,setInteractionTokens:e.setInteractionTokens,updateStatus:e.updateStatus,setUpdateStatus:e.setUpdateStatus,billingLink:e.billingLink,setBillingLink:e.setBillingLink,currentModel:e.currentModel,currentProvider:e.currentProvider,premiumCreditsExhausted:e.premiumCreditsExhausted,setPremiumCreditsExhausted:e.setPremiumCreditsExhausted,setCurrentModel:e.setCurrentModel,sessionId:e.sessionId,isSubmittingRef:e.isSubmittingRef,setInput:e.setInput,setStaticKey:e.setStaticKey,executeBash:e.executeBash})}async function handleGoalCommand(e,t,n,r){const o=e.isSubmittingRef.current||e.isCmdCodeBusy,s=await resolveGoalSlashCommand({rawArguments:t,sessionId:e.sessionId,isSubmitting:o,permissionMode:e.permissionModeRef.current,maxTurnsOverride:getGoalMaxTurnsOverride(),loadSessionMeta:__name(async e=>await loadCommandSessionMeta(e),"loadSessionMeta"),saveSessionMeta:__name(async e=>saveCommandSessionMeta(e),"saveSessionMeta"),armGoalLoop:armCommandGoalLoop,disarmGoalLoop:disarmCommandGoalLoop,isGoalLoopArmed:isCommandGoalLoopArmed});e.setFeed(e=>[...e,uh(s.notice.message,s.notice.metadata)]),o&&"notice"===s.status&&"cleared"===s.notice.metadata?.goalNoticeKind&&k$(e.sessionId)?.requestStopAfterTurn(),"start"===s.status&&await runGoalTurn(e,s.goalText,n,r)}async function openExternalSlashCommandTarget({setFeed:e,target:t}){e(e=>[...e,uh(`Opening ${createOSC8Link(t.url,t.noticeLabel,!1)} in your browser…`)]);try{await Pt(t.url,{wait:!1,background:!0})}catch{const{fallback:n}=t;if("info"===n.kind)return void e(e=>[...e,uh(n.message)]);e(e=>[...e,yh("Failed to open browser"),fh(createOSC8Link(t.url,n.label,!1))])}}function handleLearnCommand({setAutoLearnTaste:e,setShowTasteOnboarding:t,setTasteOnboardingEntryId:n,setFeed:r}){e(!0),t(!0);const o=Sh();n(o.id),r(e=>[...e,o])}async function handleCommand(e,t,n,r){const o=e.trim().split(/\s+/)[0]??"",s=o.split(":")[0]?.replace(/^\//,"")||"unknown";return withSpan({name:`command:${s}`,attributes:{"cmd.command.name":s,"cmd.command.arg_length":Math.max(e.trim().length-o.length,0)},fn:__name(async o=>{const s=await dispatchCommand(e,t,n,r);return o.setAttribute("cmd.command.status",s.status),s},"fn")})}async function dispatchCommand(e,t,n,r){const o=resolveSlashCommandRoute({command:e,isBusy:t.isCmdCodeBusy});if("blocked"===o.kind)return t.setFeed(e=>[...e,uh(o.message)]),{status:"handled"};if("resume-by-id"===o.kind)return await handleSelectSession({selectedSessionId:o.selectedSessionId,previousSessionId:t.sessionId,sessionLoadIdRef:t.sessionLoadIdRef,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:t.setSessionId,setShowSessionSelector:t.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,setStaticKey:t.setStaticKey,setShareInfo:t.setShareInfo,setCurrentModel:t.setCurrentModel,inTuiResume:!0}),{status:"handled"};if("skill"===o.kind){if(0===o.skillName.length)return t.setFeed(e=>[...e,uh("Name a skill to run: /skill:<name>. Run /skills to see what is installed.")]),{status:"handled"};const e=buildSkillNamespacedCommand(o.skillName);return await handleSkillCommand({commandName:`/${o.skillName}`,command:`${e}${o.rawArguments?` ${o.rawArguments}`:""}`,rawArguments:o.rawArguments,positionalArgs:o.positionalArgs,ctx:t})||(t.setFeed(e=>[...e,yh(`No skill named "${o.skillName}". Run /skills to see what is installed.`)]),{status:"handled"})}if("unknown"===o.kind)return{status:"unknown"};const{commandName:s,rawArguments:i,positionalArgs:a}=o;if("/exit"===s||"/quit"===s)return discardPendingReload(),t.setShouldExit(!0),{status:"handled"};if("/reload"===s)return await(k$(t.sessionId)?.flush().catch(()=>{})),requestReload(buildReloadCarryoverState({sessionId:t.sessionId,permissionMode:t.permissionModeRef.current})),t.setShouldExit(!0),{status:"handled"};if("/clear"===s)return await handleClearCommand(t),{status:"handled"};if("/help"===s)return await handleHelpCommand(t),{status:"handled"};if("/share"===s){const e=i.trim();return"gist"===e||e.startsWith("gist ")?(await handleShareGistCommand({sessionId:t.sessionId,currentModel:t.currentModel,rawFormatArg:e.slice(4).trim(),setFeed:t.setFeed}),{status:"handled"}):(await handleShareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setShowShareNotification:t.setShowShareNotification}),{status:"handled"})}if("/unshare"===s)return await handleUnshareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setUnshareNotificationMessage:t.setUnshareNotificationMessage}),{status:"handled"};if("/taste"===s)return t.setShowTasteConfig(!0),{status:"handled"};if("/learn-taste"===s)return handleLearnCommand(t),{status:"handled"};if("/design"===s)return await handleDesignCommand({ctx:t,rawArguments:i,positionalArgs:a,command:e}),{status:"handled"};if("/skills"===s)return t.setShowSkillsConfig(!0),{status:"handled"};if("/plans"===s)return t.setPlansTarget(i.trim()||null),t.setShowPlansView(!0),{status:"handled"};if("/plan-review"===s)return t.setPlansTarget(UU),t.setShowPlansView(!0),{status:"handled"};if("/config"===s)return t.setShowSettingsConfig(!0),{status:"handled"};if("/connect"===s)return t.setShowProviderSelector(!0),{status:"handled"};if("/model"===s)return await handleModelCommand(t,i),{status:"handled"};if("/effort"===s)return await handleEffortCommand(t,i),{status:"handled"};if("/memory"===s)return t.setShowMemorySelector(!0),{status:"handled"};if("/resume"===s||"/sessions"===s)return t.setShowSessionSelector(!0),{status:"handled"};if("/fork"===s)return await handleForkCommand(t,i.trim()||void 0),{status:"handled"};if("/worktree"===s)return await handleWorktreeCommand(t,a),{status:"handled"};if("/clone"===s)return await handleCloneCommand(t),{status:"handled"};if("/init"===s)return await handleInitCommand(t),{status:"handled"};if("/import"===s)return await handleImportCommand(t,i),{status:"handled"};if("/goal"===s)return await handleGoalCommand(t,i,n,r),{status:"handled"};if("/agents"===s)return t.setShowAgentsConfig(!0),{status:"handled"};if("/mcp"===s)return t.setShowMcpManager(!0),{status:"handled"};if("/compact"===s)return await handleCompactCommand({sessionId:t.sessionId,setFeed:t.setFeed,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setContextUsage:t.setContextUsage,setStaticKey:t.setStaticKey}),{status:"handled"};if("/compact-mode"===s)return t.setShowCompactModeSelector(!0),{status:"handled"};if("/update"===s)return t.setInput(""),await handleUpdateCommand({setFeed:t.setFeed,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setUpdateStatus:t.setUpdateStatus,pinnedStatusRef:t.pinnedStatusRef}),{status:"handled"};if("/context"===s)return t.setShowContextView(!0),{status:"handled"};if("/rewind"===s)return handleRewindCommand({sessionId:t.sessionId,setFeed:t.setFeed,setShowRewindSelector:t.setShowRewindSelector}),{status:"handled"};if("/tree"===s)return await handleTreeCommand({sessionId:t.sessionId,setFeed:t.setFeed,setShowTreeSelector:t.setShowTreeSelector,setTreeFilterMode:t.setTreeFilterMode,setTreeBranchSummarySkipPrompt:t.setTreeBranchSummarySkipPrompt}),{status:"handled"};if("/login"===s)return await handleLoginCommand({provider:i,setFeed:t.setFeed,setShowLoginOverlay:t.setShowLoginOverlay,setAuthComponentInfo:t.setAuthComponentInfo}),t.setInput(""),{status:"handled"};if("/logout"===s)return await handleLogoutCommand({provider:i,setFeed:t.setFeed,setRetryAttempt:t.setRetryAttempt,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),t.setInput(""),{status:"handled"};if("/learn"===s){const e=resolveExternalSlashCommandTarget({commandName:s});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),{status:"handled"}}if("/feedback"===s){const e=resolveExternalSlashCommandTarget({commandName:s,rawArguments:i});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),t.setInput(""),{status:"handled"}}if("/trace"===s)return await handleTrace({setFeed:t.setFeed,sessionId:t.sessionId}),t.setInput(""),{status:"handled"};if("/copy"===s)return await handleCopy({feed:t.feed,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/export"===s)return await handleExport({sessionId:t.sessionId,rawPath:i,currentModel:t.currentModel,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/changelog"===s)return handleChangelog({setFeed:t.setFeed,rawArguments:i}),t.setInput(""),{status:"handled"};if("/hotkeys"===s)return handleHotkeys({setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/todos"===s)return 0===getSessionTodos().length?t.setFeed(e=>[...e,uh("No todos in this session yet.")]):requestTodosManagerOpen(),t.setInput(""),{status:"handled"};if("/session-file"===s)return handleSessionFile({sessionId:t.sessionId,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/terminal-setup"===s)return await handleTerminalSetupCommand(t),{status:"handled"};if("/ide"===s)return await handleIDESetupCommand(t),{status:"handled"};if("/add-dir"===s)return t.setShowAddDirModal(!0),{status:"handled"};if("/rename"===s)return await handleRenameCommand({name:i.trim(),sessionId:t.sessionId,setFeed:t.setFeed,setRenamedTerminalTitle:t.setRenamedTerminalTitle,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),t.setInput(""),{status:"handled"};if("/name"===s)return await handleNameCommand({name:i.trim(),sessionId:t.sessionId,setFeed:t.setFeed,setRenamedTerminalTitle:t.setRenamedTerminalTitle}),t.setInput(""),{status:"handled"};if("/usage"===s)return t.setShowUsageOverlay(!0),{status:"handled"};if("/theme"===s)return await handleThemeCommand(t,i),{status:"handled"};if("/plan"===s)return await handlePlanCommand({rawArguments:i,ctx:t}),{status:"handled"};if("/mode"===s||s.startsWith("/mode:")){const e=s.startsWith("/mode:")?s.slice(6):i;return await handleModeCommand({rawArguments:e,ctx:t}),{status:"handled"}}if("/review"===s){const e=await resolveReviewSlashCommand({rawArguments:i});return"missing-gh"===e.status?(t.setFeed(t=>[...t,uh(e.message,e.metadata)]),t.setInput(""),{status:"handled"}):(await submitAutomatedSlashTurn({turn:e.turn,ctx:t}),{status:"handled"})}if("/pr-comments"===s){await submitAutomatedSlashTurn({turn:buildPrCommentsSlashTurn(),ctx:t});const e=k$(t.sessionId),n=resolvePrCommentsFollowUpInput(e?harnessSessionMessages(e):[]);return n&&t.setInput(n),{status:"handled"}}if("/status"===s)return t.setShowStatusView(!0),{status:"handled"};if("/upgrade"===s){const e=resolveExternalSlashCommandTarget({commandName:s,billingUrl:await getBillingLink({billingLink:t.billingLink,setBillingLink:t.setBillingLink})});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),{status:"handled"}}if("/extra"===s){const e=resolveExternalSlashCommandTarget({commandName:s,billingUrl:await getBillingLink({billingLink:t.billingLink,setBillingLink:t.setBillingLink})});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),{status:"handled"}}const l=getActiveModHost(),c=s.slice(1);if(l?.commands().some(e=>e.name===c)){try{const e=await l.runCommand({name:c,args:i}),n=e?.message;n&&t.setFeed(e=>[...e,uh(n)]),e?.prompt&&await submitAutomatedSlashTurn({turn:buildAutomatedSlashTurn({commandName:c,rawArguments:i,fullPrompt:e.prompt}),ctx:t})}catch(e){t.setFeed(t=>[...t,yh(`Mod command /${c} failed: ${e instanceof Error?e.message:String(e)}`)])}return{status:"handled"}}const d=await resolveCustomSlashTurn({runtime:createNodeRuntime(),commandName:s,rawArguments:i,positionalArgs:a});if(d)return await submitAutomatedSlashTurn({turn:d,ctx:t}),{status:"handled"};return await handleSkillCommand({commandName:s,command:e,rawArguments:i,positionalArgs:a,ctx:t})||{status:"unknown"}}async function submitAutomatedSlashTurn({turn:e,ctx:t}){await handleSubmit({input:e.input,role:"user",displayMessage:e.displayMessage,hiddenMessages:e.hiddenMessages,isAutomated:!0,feed:t.feed,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,currentModel:t.currentModel,currentProvider:t.currentProvider,premiumCreditsExhausted:t.premiumCreditsExhausted,setPremiumCreditsExhausted:t.setPremiumCreditsExhausted,setCurrentModel:t.setCurrentModel,sessionId:t.sessionId,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash})}async function handleSkillCommand({commandName:e,command:t,rawArguments:n,positionalArgs:r,ctx:o}){const s=await resolveSkillSlashTurn({runtime:createNodeRuntime(),commandName:e,command:t,rawArguments:n,positionalArgs:r});return"not-found"===s.status?null:"disabled"===s.status?(o.setFeed(e=>[...e,uh(s.message)]),{status:"handled"}):"load-error"===s.status?(o.setFeed(e=>[...e,yh(s.message)]),{status:"handled"}):(await submitAutomatedSlashTurn({turn:s.turn,ctx:o}),{status:"handled"})}function useCommandCtx({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:i,permissionState:a,terminalTitleState:l,isSubmittingRef:c,executeBash:d,setInput:u}){const m=dt(()=>({feed:e.feed,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setQueuedMessages:e.setQueuedMessages,setStatus:n.setStatus,setInteractionTokens:n.setInteractionTokens,setContextUsage:n.setContextUsage,contextUsage:n.contextUsage,setStaticKey:o.setStaticKey,updateStatus:n.updateStatus,setUpdateStatus:n.setUpdateStatus,billingLink:n.billingLink,setBillingLink:n.setBillingLink,currentModel:r.currentModel,premiumCreditsExhausted:r.premiumCreditsExhausted,setPremiumCreditsExhausted:r.setPremiumCreditsExhausted,setCurrentModel:r.setCurrentModel,setModelNotice:o.setModelNotice,currentProvider:r.currentProvider,setAuthComponentInfo:r.setAuthComponentInfo,shareInfo:n.shareInfo,setShareInfo:n.setShareInfo,setShowShareNotification:n.setShowShareNotification,setUnshareNotificationMessage:n.setUnshareNotificationMessage,setRetryAttempt:n.setRetryAttempt,pinnedStatusRef:n.pinnedStatusRef,setShowTasteConfig:o.setShowTasteConfig,setShowSkillsConfig:o.setShowSkillsConfig,setShowSettingsConfig:o.setShowSettingsConfig,setShowProviderSelector:o.setShowProviderSelector,setShowModelSelector:o.setShowModelSelector,setShowEffortSelector:o.setShowEffortSelector,setShowMemorySelector:o.setShowMemorySelector,setShowAgentsConfig:o.setShowAgentsConfig,setShowMcpManager:o.setShowMcpManager,setShowRewindSelector:o.setShowRewindSelector,setShowTreeSelector:o.setShowTreeSelector,setTreeFilterMode:o.setTreeFilterMode,setTreeBranchSummarySkipPrompt:o.setTreeBranchSummarySkipPrompt,setShowCompactModeSelector:o.setShowCompactModeSelector,setShowContextView:o.setShowContextView,setShowAddDirModal:o.setShowAddDirModal,setShowLoginOverlay:o.setShowLoginOverlay,setShowStatusView:o.setShowStatusView,setShowPlansView:o.setShowPlansView,setPlansTarget:o.setPlansTarget,setShowUsageOverlay:o.setShowUsageOverlay,setShowThemeSelector:o.setShowThemeSelector,setShowDesignGuide:o.setShowDesignGuide,setPendingDesignSuggestion:o.setPendingDesignSuggestion,setShowTasteOnboarding:s.setShowTasteOnboarding,setAutoLearnTaste:s.setAutoLearnTaste,setTasteOnboardingEntryId:s.setTasteOnboardingEntryId,sessionId:t.sessionId,setSessionId:t.setSessionId,sessionLoadIdRef:t.sessionLoadIdRef,sessionLoaded:t.sessionLoaded,setSessionLoaded:t.setSessionLoaded,setShowSessionSelector:o.setShowSessionSelector,setPermissionMode:a.setPermissionMode,permissionModeRef:a.permissionModeRef,clearSessionPermissions:a.clearSessionPermissions,setShouldExit:i.setShouldExit,setInput:u,isSubmittingRef:c,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,executeBash:d,setRenamedTerminalTitle:l.setRenamedTerminalTitle}),[e,t,n,r,o,s,i,a,l,c,d,u]),p=lt(m);return p.current=m,{commandCtx:m,onCommand:ut((e,t,n)=>handleCommand(e,p.current,t,n),[])}}__name(renderList,"renderList"),__name(handleWorktreeCommand,"handleWorktreeCommand"),__name(handleRemove,"handleRemove"),__name(handleSwitch,"handleSwitch"),__name(handleHelpCommand,"handleHelpCommand"),__name(handleTerminalSetupCommand,"handleTerminalSetupCommand"),__name(handleIDESetupCommand,"handleIDESetupCommand"),__name(handleClearCommand,"handleClearCommand"),__name(handleInitCommand,"handleInitCommand"),__name(runGoalTurn,"runGoalTurn"),__name(handleGoalCommand,"handleGoalCommand"),__name(openExternalSlashCommandTarget,"openExternalSlashCommandTarget"),__name(handleLearnCommand,"handleLearnCommand"),__name(handleCommand,"handleCommand"),__name(dispatchCommand,"dispatchCommand"),__name(submitAutomatedSlashTurn,"submitAutomatedSlashTurn"),__name(handleSkillCommand,"handleSkillCommand"),__name(useCommandCtx,"useCommandCtx"),Gt(),SR();var wj=as,vj=ls;function useCreditWarning({interactionTokens:e,currentModel:t}){const[n,r]=at(null),o=lt(null),s=lt(null),i=lt(null),a=ut(async()=>{try{const e=createApiClient({baseUrl:getApiBaseUrl()});o.current??=createCreditWarningState();const t=await checkCreditWarning({client:e,state:o.current});if(o.current=t.state,!t.message)return;r(t.message),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{r(null),i.current=null},wj)}catch{}},[]);return ct(()=>{if(0!==e&&!isLocalOnly()&&!isByok({model:t}))return s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{a(),s.current=null},vj),()=>{s.current&&clearTimeout(s.current)}},[e,t,a]),ct(()=>()=>{i.current&&clearTimeout(i.current),s.current&&clearTimeout(s.current)},[]),{creditWarning:n}}__name(useCreditWarning,"useCreditWarning"),Gt(),SR();var kj=createNodeRuntime();function useCronWakeup({sessionId:e,onSubmit:t}){const n=lt(t),r=lt(e),o=lt(Promise.resolve());ct(()=>{n.current=t},[t]),ct(()=>{r.current=e},[e]),ct(()=>{const e=subscribeCronFire(e=>{o.current=o.current.catch(()=>{}).then(async()=>{const t="loop"===e.kind||!0===e.loopOwned,o=k$(r.current);if(t&&o&&!o.hasScheduledTask({id:e.taskId}))return;const s=await buildScheduledTaskWakeupSubmission({event:e,runtime:kj});await n.current(s)}),o.current.catch(()=>{})});return()=>{e()}},[])}function useExit(){const[e,t]=at(!1),[n,r]=at(null),o=lt(null),s=lt(0),i=lt(null),a=ut(()=>{o.current=null,r(null),i.current&&(clearTimeout(i.current),i.current=null)},[]);return{shouldExit:e,setShouldExit:t,pendingExitKey:n,setPendingExitKey:r,pendingExitKeyRef:o,lastExitKeyTimeRef:s,exitConfirmationTimeoutRef:i,resetPendingExitKey:a}}__name(useCronWakeup,"useCronWakeup"),Gt(),__name(useExit,"useExit"),Gt(),SR(),Gt(),SR();var Cj="1"===process.env.CMD_TEST_INJECT_LIVE_ENTRY;function makeInjectedShellEntry(e,t,n,r={}){return{...gh("shell_command",t,{status:n}),id:e,...r}}function buildInjectedLiveEntry(){return Cj?makeInjectedShellEntry("cmd-test-injected-live-entry",process.env.CMD_TEST_INJECT_INPUT??"sleep 60","running"):null}function buildInjectedFeed(){const e=Number.parseInt(process.env.CMD_TEST_INJECT_FEED_ITEMS??"0",10);return!Number.isFinite(e)||e<=0?[]:Array.from({length:e},(e,t)=>makeInjectedShellEntry(`cmd-test-feed-${t}`,`echo item ${t}`,"completed",{output:`item ${t}`}))}__name(makeInjectedShellEntry,"makeInjectedShellEntry"),__name(buildInjectedLiveEntry,"buildInjectedLiveEntry"),__name(buildInjectedFeed,"buildInjectedFeed");var bj="1"===process.env.CMD_TEST_INJECT_STREAM,Ej="cmd-test-injected-stream-entry";function streamRole(){const e=process.env.CMD_TEST_INJECT_STREAM_ROLE;return"reasoning"===e||"tool"===e||"agent"===e?e:"assistant"}function streamContentKind(){const e=process.env.CMD_TEST_INJECT_STREAM_CONTENT;return"code"===e||"paragraph"===e||"reasoning"===e||"mixed"===e||"huge"===e?e:"table"}function streamTickMs(){const e=Number.parseInt(process.env.CMD_TEST_INJECT_STREAM_TICK_MS??"",10);return Number.isFinite(e)&&e>0?e:100}function buildHugeStreamContent(){const e=[];e.push("# Huge streaming gauntlet","A very long reply exercising **every** markdown flavor while it streams. Scroll up mid-stream — the position must hold; finished blocks land in the scrollback above.");for(let t=0;t<6;t+=1){e.push(`## Section ${t} — prose, lists and a table`),e.push(...Array.from({length:4},(e,n)=>`Section ${t} paragraph ${n}: the quick brown fox keeps streaming words so this block wraps a couple of rows, with **bold**, *italic*, ***both***, ~~strikethrough~~, \`inline_code(${n})\` and a [link](https://example.com/s${t}/p${n}) mixed in.`)),e.push([`- Section ${t} unordered item one`,`- Section ${t} unordered item two`," - nested child with `code`"," - nested child with **bold**",`- Section ${t} unordered item three`].join("\n"),[`1. Section ${t} ordered first`,`2. Section ${t} ordered second`,`3. Section ${t} ordered third`].join("\n"),`> Section ${t} blockquote: streaming should never mangle a quote.\n> > And a nested quote inside it still reads fine.`);const n=Array.from({length:6},(e,n)=>`| s${t}-row-${n} | huge demo detail ${n} | ${3*n} |`);e.push(["| Key | Detail | N |","| --- | --- | --- |",...n].join("\n"),"---")}e.push("## Task list and headings ladder"),e.push(["- [x] streamed a task that is done","- [ ] a pending task with `code`","- [x] another finished task with **bold**","- [ ] the last pending task"].join("\n"),"### Heading three","#### Heading four","##### Heading five","###### Heading six"),e.push("## Code in several languages"),e.push(["```ts","const total = rows.reduce(sum);","export function streamGauntlet(rows: number[]): number {","\treturn rows.filter(Boolean).length;","}","```"].join("\n"),["```python","def stream_gauntlet(rows):",' """Docstring survives streaming."""'," return [row * 2 for row in rows if row]","```"].join("\n"),["```json","{",' "stream": "gauntlet",',' "blocks": ["table", "code", "list"],',' "huge": true',"}","```"].join("\n"),["```bash","for block in table code list; do",' echo "streaming $block"',"done","```"].join("\n"),["```diff","- const cap = 10;","+ const cap = viewportRows - reserved;","```"].join("\n")),e.push("## Wide table (column fitting / wrap layout)");const t=Array.from({length:10},(e,t)=>`| wide-${t} | alpha ${t} | beta ${t} | gamma ${t} | a longer cell that should wrap gracefully ${t} | ${11*t} |`);e.push(["| Id | Alpha | Beta | Gamma | Long description column | N |","| --- | --- | --- | --- | --- | --- |",...t].join("\n")),e.push("## Huge table (taller than the viewport — the one capped-while-open case)");const n=Array.from({length:40},(e,t)=>`| huge-row-${t} | streaming stress row number ${t} | ${7*t} |`);return e.push(["| Row | Description | N |","| --- | --- | --- |",...n].join("\n")),e.push("## Width edge cases"),e.push("CJK 漢字が流れても幅計算は崩れない、そしてまた漢字。Emoji too: 🚀🔥✨🎉🧪 — double-width glyphs must wrap correctly.","A single extremely long unbroken paragraph follows to force soft wrapping across many physical rows: "+Array.from({length:12},(e,t)=>`clause ${t} keeps the sentence rolling without a newline`).join(", ")+"."),e.push("## The end","Everything above should now sit in your scrollback exactly once.","Huge demo closing paragraph."),e.join("\n\n")}function buildStreamContent(e){return"code"===e?["```ts",...Array.from({length:34},(e,t)=>`const value_${t} = compute(${t});`),"```"].join("\n"):"paragraph"===e?Array.from({length:16},(e,t)=>`Paragraph ${t} adds a little more of the streaming story so the reply keeps growing past the viewport.`).join("\n\n"):"reasoning"===e?Array.from({length:40},(e,t)=>`step ${t}: consider the next detail`).join("\n"):"huge"===e?buildHugeStreamContent():"mixed"===e?`${Array.from({length:3},(e,t)=>`Mixed intro paragraph ${t} with enough words.`).join("\n\n")}\n\n${["| Col | Detail |","| --- | --- |",...Array.from({length:8},(e,t)=>`| row-${t} | mixed detail ${t} |`)].join("\n")}\n\nMixed closing paragraph.`:["| Item | Description | Value |","| --- | --- | --- |",...Array.from({length:20},(e,t)=>`| item-${t} | detail for row number ${t} | ${7*t} |`)].join("\n")}function buildStreamFrames(e){const t=e.split("\n");return t.length>1?t.map((e,n)=>t.slice(0,n+1).join("\n")):Array.from({length:20},(t,n)=>{const r=Math.ceil(e.length*(n+1)/20);return e.slice(0,r)})}function makeStreamRunningEntry(e,t){return"reasoning"===e?kh(t,{id:Ej,status:"running"}):"tool"===e?{...gh("shell_command",t,{status:"running"}),id:Ej}:"agent"===e?{...Ch({name:"Task",input:t}),id:Ej}:{...ph(t),id:Ej,metadata:{status:"running"}}}function makeStreamFinalEntry(e,t){return"reasoning"===e?kh(t,{id:Ej}):"tool"===e||"agent"===e?{...gh("shell_command",t,{}),id:Ej,output:"done"}:{...ph(t),id:Ej}}function maybeStartInjectedStream(e){if(!bj)return;const{setFeed:t,setLiveEntries:n,setIsCmdCodeBusy:r}=e,o=streamRole(),s=buildStreamFrames(buildStreamContent(streamContentKind())),i=streamTickMs();r(!0);const a=createBlockCommittingRouter({setFeed:t,setLiveEntries:n});a(makeStreamRunningEntry(o,s[0]??""));let l=0;const c=setInterval(()=>{if(l+=1,l<s.length)return void a(makeStreamRunningEntry(o,s[l]??""));clearInterval(c);const e=s[s.length-1]??"";a(makeStreamFinalEntry(o,e)),r(!1)},i);return()=>clearInterval(c)}__name(streamRole,"streamRole"),__name(streamContentKind,"streamContentKind"),__name(streamTickMs,"streamTickMs"),__name(buildHugeStreamContent,"buildHugeStreamContent"),__name(buildStreamContent,"buildStreamContent"),__name(buildStreamFrames,"buildStreamFrames"),__name(makeStreamRunningEntry,"makeStreamRunningEntry"),__name(makeStreamFinalEntry,"makeStreamFinalEntry"),__name(maybeStartInjectedStream,"maybeStartInjectedStream");var Tj="1"===process.env.CMD_TEST_INJECT_TODOS;function todosTickMs(){const e=Number.parseInt(process.env.CMD_TEST_INJECT_TODOS_TICK_MS??"",10);return Number.isFinite(e)&&e>0?e:1500}__name(todosTickMs,"todosTickMs");var Pj=(()=>{const e=[{content:"Create initial todo items",active:"Creating initial todo items"},{content:"Update status of a todo",active:"Updating todo status"},{content:"Mark all todos as completed",active:"Marking all todos as completed"}];return Array.from({length:e.length+1},(t,n)=>e.map((e,t)=>({content:e.content,status:t<n?"completed":t===n?"in_progress":"pending",...t===n?{activeForm:e.active}:{},id:String(t+1)})))})();function maybeStartInjectedTodos(e){if(!Tj)return;const t=createBlockCommittingRouter({setFeed:e.setFeed,setLiveEntries:e.setLiveEntries});let n=0;const r=setInterval(()=>{const e=Pj[n];e?(t({...gh("todo_write",Oh("todo_write",{todos:e}),{}),id:`cmd-test-todo-${n}`,output:JSON.stringify(e)}),n+=1):clearInterval(r)},todosTickMs());return()=>clearInterval(r)}__name(maybeStartInjectedTodos,"maybeStartInjectedTodos");var Mj=Number.parseInt(process.env.CMD_TEST_INJECT_TURNS??"0",10);function testTurnChars(){const e=Number.parseInt(process.env.CMD_TEST_INJECT_TURN_CHARS??"",10);return Number.isFinite(e)&&e>0?e:1e5}function testTurnTickMs(){const e=Number.parseInt(process.env.CMD_TEST_INJECT_TURN_TICK_MS??"",10);return Number.isFinite(e)&&e>0?e:20}function makeInjectedTurnEntry(e,t){const n=`turn ${e} `.repeat(Math.ceil(testTurnChars()/`turn ${e} `.length));return makeInjectedShellEntry(`cmd-test-turn-${e}`,t?"echo turns-done":`echo turn ${e}`,"completed",{output:t?"turns-done":n.slice(0,testTurnChars())})}function maybeStartInjectedTurns(e){if(!Number.isFinite(Mj)||Mj<=0)return;const{setFeed:t}=e;let n=0;const r=setInterval(()=>{const e=n===Mj-1,o=makeInjectedTurnEntry(n,e);t(e=>[...e,o]),n+=1,e&&clearInterval(r)},testTurnTickMs());return()=>clearInterval(r)}function useFeed(){const[e,t]=at(()=>buildInjectedFeed()),n=ut(e=>{t(t=>applyFeedRetention("function"==typeof e?e(t):e))},[]);ct(()=>{trimStaticBuffer()},[e]);const[r,o]=at(()=>{const e=buildInjectedLiveEntry();return e?[e]:[]}),[s,i]=at([]),[a,l]=at(Cj),c=lt([]),d=ut(e=>{const t="function"==typeof e?e(c.current):e;c.current=t,i(t)},[]);return ct(()=>maybeStartInjectedTurns({setFeed:n}),[n]),ct(()=>maybeStartInjectedStream({setFeed:n,setLiveEntries:o,setIsCmdCodeBusy:l}),[]),ct(()=>maybeStartInjectedTodos({setFeed:n,setLiveEntries:o}),[]),{feed:e,setFeed:n,liveEntries:r,setLiveEntries:o,queuedMessages:s,setQueuedMessages:d,isCmdCodeBusy:a,setIsCmdCodeBusy:l,queuedMessagesRef:c}}function useKeyboard({showTasteConfig:e,showSkillsConfig:t,showSettingsConfig:n,showProviderSelector:r,showModelSelector:o,showEffortSelector:s,showMemorySelector:i,showMcpManager:a,showRewindSelector:l,showTreeSelector:c,showLoginOverlay:d,showUsageOverlay:u,showAddDirModal:m,showDesignGuide:p,authComponentInfo:g,setShowModelSelector:h,setStaticKey:f,showTasteSkipBanner:y,setShowTasteSkipBanner:S,showZdrNotice:w,setShowZdrNotice:v,modelNotice:k,setModelNotice:C,transcriptMode:b,setTranscriptMode:E,isCmdCodeBusy:T,liveEntries:P,queuedMessagesRef:M,setInput:x,setQueuedMessages:I,setFeed:A,setLiveEntries:R,setIsCmdCodeBusy:L,setRetryAttempt:O,setStatus:D,pendingExitKey:$,setPendingExitKey:N,pendingExitKeyRef:_,lastExitKeyTimeRef:F,exitConfirmationTimeoutRef:U,resetPendingExitKey:j,pendingPermission:B,setPendingPermission:W,pendingQuestion:H,setPendingQuestion:G,setShouldExit:V,sessionId:z,handleToggleAutoAccept:K,handleDoubleEscapeEmpty:q,respondToPrompt:Y,createErrorEntry:J}){const Q=__name(()=>{k$(z)?.cancelLoops().then(e=>{if(0===e)return;const t=1===e?"task":"tasks";A(n=>[...n,uh(`Loop stopped · ${e} scheduled ${t} cancelled`,{isGoalNotice:!0,goalNoticeKind:"cleared"})])})},"cancelLoopsAndNotify"),X=__name(()=>{interruptActiveTurn(),clearCommandGoalIfActive(z),Q();const e=P.length>0;if(L(!1),O(null),R([]),D(tS),!e){const e=J(eS);A(t=>[...t,e])}if(M.current.length>0){const e=formatQueuedMessagesForRequeue(M.current);x(t=>mergeRequeuedInput({queuedText:e,currentInput:t})),I([]),M.current=[]}},"handleInterrupt");nt((P,M)=>{const I=getKeybindings();if(keybindingMatches(I,"app.permission.cycle",P,M)||""===P||M.meta&&"m"===P)return void K();if(y&&M.escape)return void S(!1);if(w&&M.escape)return void v(!1);if(k&&M.escape)return void C(null);if(isTodosManagerOpen())return void($&&j());if(e||t||n||r||o||s||i||a||g||l||c||d||u||m||p)return void($&&j());if(""===P||M.ctrl&&"c"===P){if(T)return void X();const e=Date.now(),t=e-F.current;return F.current=e,"ctrl-c"===_.current&&t<2e3?(U.current&&(clearTimeout(U.current),U.current=null),void V(!0)):(x(()=>""),_.current="ctrl-c",N("ctrl-c"),U.current&&clearTimeout(U.current),void(U.current=setTimeout(()=>{_.current=null,N(null),U.current=null},2e3)))}if(keybindingMatches(I,"app.tools.expand",P,M)){if(H?.params.planContent)return;return RL(),E("off"===b?"limited":"off"),void f(e=>e+1)}const A=isCtrlKey({inputChar:P,key:M,letter:"e",ctrlCode:5})||isCtrlKey({inputChar:P,key:M,letter:"y",ctrlCode:25}),R=null!==B&&"function"==typeof B.params?.explain;if("off"!==b&&A&&!R)return RL(),E("limited"===b?"full":"limited"),void f(e=>e+1);if("off"===b&&getSessionTodos().length>0&&keybindingMatches(I,"app.todos.toggle",P,M))requestTodosManagerOpen();else if(keybindingMatches(I,"app.model.select",P,M)||isAltP(P))h(!0);else if(M.escape){if("off"!==b)return RL(),E("off"),void f(e=>e+1);if(H)return H.reject(new Error("Question cancelled by user")),G(null),D("Question cancelled"),hardResetForResize(),void f(e=>e+1);if(B)return Y({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),B.resolve(!1),W(null),void D("Permission denied");T?X():Q()}})}function useHandlers({resume:e,feedState:t,onboarding:n,uiOverlays:r,exitState:o,pendingOps:s,permissionState:i,statusState:a,authState:l,sessionId:c,loadTasteStatus:d,loadCurrentProvider:u,setInput:m}){const p=ut(()=>{i.setPermissionMode(e=>{const t=cyclePermissionMode({current:e,disableBypass:k$(c)?.isBypassDisabled()??!0}),n=resolvePendingPromptOnModeChange(t,{pendingIsRisky:void 0!==s.pendingPermission?.params?.risk});return n&&s.pendingPermission&&("approve"===n&&i.respondToPrompt(iM),s.pendingPermission.resolve("approve"===n),s.setPendingPermission(null)),k$(c)?.setPermissionMode({mode:t}),t})},[i.setPermissionMode,i.respondToPrompt,s.pendingPermission,s.setPendingPermission,c]),g=ut(()=>{i.setPermissionMode(e=>{const t="bypass"===e?e:"auto-accept";return k$(c)?.setPermissionMode({mode:t}),t})},[i.setPermissionMode,c]),h=ut(()=>{const e=!t.isCmdCodeBusy&&!s.pendingPermission&&!s.pendingQuestion,n=(k$(c)?.listCheckpoints().length??0)>0;e&&n&&r.setShowRewindSelector(!0)},[t.isCmdCodeBusy,s.pendingPermission,s.pendingQuestion,r.setShowRewindSelector,c]),f=ut(t=>{n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),t?.skipped&&r.setShowTasteSkipBanner(!0),e&&r.setShowSessionSelector(!0)},[e,n,r]),y=ut(async()=>{try{if(await initializeCommandProjectSessions(),n.setShowTrustPrompt(!1),e)return console.log("No conversations found to resume."),void o.setShouldExit(!0);n.setProjectTrusted(!0),d(),u()}catch(e){console.error("Failed to initialize project:",e),n.setShowTrustPrompt(!1),o.setShouldExit(!0)}},[e,n,o,d,u]),S=ut(()=>{o.setShouldExit(!0)},[o.setShouldExit]);return useKeyboard({showTasteConfig:r.showTasteConfig,showSkillsConfig:r.showSkillsConfig,showSettingsConfig:r.showSettingsConfig,showProviderSelector:r.showProviderSelector,showModelSelector:r.showModelSelector,showEffortSelector:r.showEffortSelector,showMemorySelector:r.showMemorySelector,showMcpManager:r.showMcpManager,showRewindSelector:r.showRewindSelector,showTreeSelector:r.showTreeSelector,showLoginOverlay:r.showLoginOverlay,showUsageOverlay:r.showUsageOverlay,showAddDirModal:r.showAddDirModal,showDesignGuide:r.showDesignGuide,authComponentInfo:l.authComponentInfo,setShowModelSelector:r.setShowModelSelector,setStaticKey:r.setStaticKey,showTasteSkipBanner:r.showTasteSkipBanner,setShowTasteSkipBanner:r.setShowTasteSkipBanner,showZdrNotice:r.showZdrNotice,setShowZdrNotice:r.setShowZdrNotice,modelNotice:r.modelNotice,setModelNotice:r.setModelNotice,transcriptMode:r.transcriptMode,setTranscriptMode:r.setTranscriptMode,isCmdCodeBusy:t.isCmdCodeBusy,liveEntries:t.liveEntries,queuedMessagesRef:t.queuedMessagesRef,setInput:m,setQueuedMessages:t.setQueuedMessages,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setRetryAttempt:a.setRetryAttempt,setStatus:a.setStatus,pendingExitKey:o.pendingExitKey,setPendingExitKey:o.setPendingExitKey,pendingExitKeyRef:o.pendingExitKeyRef,lastExitKeyTimeRef:o.lastExitKeyTimeRef,exitConfirmationTimeoutRef:o.exitConfirmationTimeoutRef,resetPendingExitKey:o.resetPendingExitKey,pendingPermission:s.pendingPermission,setPendingPermission:s.setPendingPermission,pendingQuestion:s.pendingQuestion,setPendingQuestion:s.setPendingQuestion,setShouldExit:o.setShouldExit,sessionId:c,handleToggleAutoAccept:p,handleDoubleEscapeEmpty:h,respondToPrompt:i.respondToPrompt,createErrorEntry:yh}),{handleToggleAutoAccept:p,handleEnableAutoAccept:g,handleDoubleEscapeEmpty:h,handleTasteOnboardingComplete:f,handleTrust:y,handleNoTrust:S}}function resolveExternalModelChange(e){return"model"!==e.setting||"string"!=typeof e.value||0===e.value.length||e.value===e.currentModel?null:{modelId:e.value}}function raceAnswerAgainstAbort(e,t){return t?t.aborted?Promise.resolve("deny"):new Promise((n,r)=>{const o=__name(()=>n("deny"),"onAbort");t.addEventListener("abort",o,{once:!0}),e.then(e=>{t.removeEventListener("abort",o),n(e)},e=>{t.removeEventListener("abort",o),r(e)})}):e}__name(testTurnChars,"testTurnChars"),__name(testTurnTickMs,"testTurnTickMs"),__name(makeInjectedTurnEntry,"makeInjectedTurnEntry"),__name(maybeStartInjectedTurns,"maybeStartInjectedTurns"),__name(useFeed,"useFeed"),Gt(),SR(),Gt(),SR(),__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Gt(),SR(),Gt(),__name(resolveExternalModelChange,"resolveExternalModelChange"),Gt(),__name(raceAnswerAgainstAbort,"raceAnswerAgainstAbort"),Gt();var xj={},Ij={};function setStartupSessionOptions(e){xj=void 0===e.persist?{}:{persist:e.persist},Ij={...e.sessionFilePath?{sessionFilePath:e.sessionFilePath}:{},...e.name?{name:e.name}:{}}}function getStickyStartupSessionOptions(){return xj}function consumeStartupSessionOverrides(){const e=Ij;return Ij={},e}function buildInteraction({permissionsService:e,permissionModeRef:t,setPendingQuestion:n,setStatus:r}){return{confirmTool:__name(async({toolName:n,input:r,description:o,risk:s,explain:i,signal:a})=>{if(!e)return"allow";if(a?.aborted)return"deny";const l=__name(e=>raceAnswerAgainstAbort(e.then(e=>e.allowed?"allow":"deny"),a),"withInterrupt"),c=buildToolPermissionRequest({toolName:n,input:r,description:o,...void 0!==s?{risk:s}:{},...void 0!==i?{explain:i}:{}});return"shell"===c.kind?l(e.requestShellPermission(c.request)):"generic"===c.kind?l(e.requestGenericPermission(c.request)):l(e.requestPermission(c.request,t.current))},"confirmTool"),askQuestion:__name(async e=>new Promise(t=>{n({params:{questions:e.questions.map(e=>({question:e.question,header:e.header??"",options:e.options.map(e=>({label:e.label,description:e.description??"",...void 0!==e.preview?{preview:e.preview}:{}})),multiSelect:e.multiSelect??!1})),hideCustomInput:e.hideCustomInput,exitPlanMode:e.exitPlanMode,enterPlanMode:e.enterPlanMode,planContent:e.planContent,planFilePath:e.planFilePath,compact:e.compact},resolve:__name(e=>{t({answers:e.answers.map(e=>({questionIndex:e.questionIndex,selectedOptions:[...e.selectedOptions],...void 0!==e.notes?{notes:e.notes}:{},...void 0!==e.preview?{preview:e.preview}:{},...e.images?.length?{images:e.images}:{}})),...e.disposition?{disposition:e.disposition}:{}})},"resolve"),reject:__name(()=>{t({answers:[]})},"reject")}),r("Waiting for your answer…")}),"askQuestion")}}function useHarness({sessionId:e,sessionLoaded:t,showSessionSelector:n,projectTrusted:o,permissionsService:s,permissionModeRef:i,setPermissionMode:a,permissionModeExplicit:l,dangerouslySkipPermissions:c,setPendingQuestion:d,setStatus:u,setFeed:m,queuedMessagesRef:p,setQueuedMessages:g,onSessionTitled:h,currentModel:f,setCurrentModel:y,setStaticKey:S,isCmdCodeBusy:w}){const v=lt(f);v.current=f;const k=lt(null),C=lt(!1),b=lt(w);b.current=w;const E=ut(()=>{hardResetForResize(),S?.(e=>e+1)},[S]),T=ut(e=>{v.current=e,y?.(e),E()},[E,y]);ct(()=>{if(w)return;const e=k.current,t=C.current;k.current=null,C.current=!1,(null!==e||t)&&(null===e||e===v.current?t&&E():T(e))},[w,T,E]);const[P,M]=at(!1),[x,I]=at(0),A=lt(null),R=__name(()=>{A.current?.(),A.current=null},"releaseRebuildBarrier");ct(()=>onHarnessSessionRebuild(t=>{if(t===e)return new Promise(e=>{A.current?.(),A.current=e,I(e=>e+1)})}),[e]);const L=lt(i.current),O=lt(null);return ct(()=>{if(!o||n)return void R();const t=__name(()=>Boolean(l)||i.current!==L.current,"userChoseMode");let f,y,S=!1;return(async()=>{const n=consumeStartupSessionOverrides(),{persist:o}=getStickyStartupSessionOptions(),l=await loadResumeAgentState({sessionId:e,...n.sessionFilePath?{baseDir:r(n.sessionFilePath)}:{}});if(S)return;const w=__name(()=>{const e=p?.current??[];return 0===e.length?[]:(p&&(p.current=[]),g?.(()=>[]),m?.(t=>[...t,...e.flatMap(e=>{if(e.isMeta)return[];const t=dh(e.displayMessage??e.input);return e.ideHint&&(t.metadata={ideHint:e.ideHint}),[t]})]),e.map(e=>{const t=e.ideContext?`${e.ideContext}\n\n${e.input}`:e.input;return e.images&&0!==e.images.length?{input:[...clipboardImagesToUserContent(e.images),{type:"text",text:t}],...e.source?{source:e.source}:{}}:{input:t,...e.source?{source:e.source}:{}}}))},"drainQueuedMessages"),P=await loadCommandModHost(),x=await v$({sessionId:e,baseUrl:getApiBaseUrl(),...t()?{permissionMode:i.current}:{},dangerouslySkipPermissions:c,drainQueuedMessages:w,peekQueuedMessageCount:__name(()=>p?.current?.length??0,"peekQueuedMessageCount"),interaction:buildInteraction({permissionsService:s,permissionModeRef:i,setPendingQuestion:d,setStatus:u}),requestSlashCommand:__name(({command:t})=>(enqueueAgentSlashCommand({sessionId:e,command:t}),{status:"accepted"}),"requestSlashCommand"),resumeState:l,modHost:P,...void 0!==o?{persist:o}:{},...n.sessionFilePath?{sessionFilePath:n.sessionFilePath}:{},ideBridge:createLocalIdeBridge()}).catch(()=>{});if(R(),S||!x)return;n.name&&x.setSessionName(n.name),x.getPermissionMode()!==i.current&&(t()?x.setPermissionMode({mode:i.current}):(i.current=x.getPermissionMode(),a?.(x.getPermissionMode())));const I=x.getModel(),A=I!==v.current;A&&T(I),A||x.getEffort()===getReasoningEffort(I)||E(),P&&m&&(P.setEntrySink(e=>{m(t=>[...t,uh(e.join("\n"))])}),y=__name(()=>P.setEntrySink(void 0),"clearModEntrySink")),f=x.events.subscribe(e=>{if("session_titled"===e.type)return void h?.(e.title);if("permission_mode_changed"===e.type)return i.current=e.mode,void a?.(e.mode);if("config_setting_changed"===e.type){if("theme"===e.setting&&"string"==typeof e.value&&isCliTheme(e.value)&&applyTuiTheme(resolveCliTheme(e.value)),"effort"===e.setting)return void(b.current?C.current=!0:E());const t=resolveExternalModelChange({setting:e.setting,value:e.value,currentModel:v.current});return void(t&&(b.current?k.current=t.modelId:T(t.modelId)))}if("subagent_stop"===e.type){if(!m)return;return void m(t=>settleBackgroundAgentRow({entries:t,toolCallId:e.toolCallId,tokensUsed:e.tokensUsed,...e.status?{status:e.status}:{}}))}if("notice"!==e.type||!m)return;const t=tasteNoticeToFeedEntry(e);t&&m(e=>[...e,t])}),M(!0),O.current!==e&&(O.current=e,x.fireSessionStartHooks({source:consumeNextSessionStartSource()}).then(e=>{if(S||0===e.hooksRun||!m)return;const t=1===e.hooksRun?"":"s",n=[`Ran ${e.hooksRun} session start hook${t}`,...e.systemMessage?e.systemMessage.split("\n"):[]];m(e=>[...e,uh(n.join("\n"))])}).catch(()=>{}))})(),()=>{S=!0,f?.(),y?.()}},[e,t,n,o,s,i,a,l,c,d,u,y,T,x,E]),{ready:P}}function useLifecycle({exit:e,feedState:t,exitState:n,statusState:r,authState:o,onboarding:s,uiOverlays:i,skipOnboarding:a,sessionId:l,sessionTitleHolder:c}){ct(()=>{n.shouldExit&&(r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),o.providerNotificationTimer.current&&clearTimeout(o.providerNotificationTimer.current),o.modelNotificationTimer.current&&clearTimeout(o.modelNotificationTimer.current),c&&(c.loadTitle=()=>loadCommandUserRenamedTitle({sessionId:l}),c.sessionId=l),(async()=>{try{await Promise.allSettled([disconnectAllMcpServers(),b$()])}catch{}try{e()}catch{process.exit(0)}})())},[n.shouldExit,e]),ct(()=>()=>{r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),o.providerNotificationTimer.current&&clearTimeout(o.providerNotificationTimer.current),o.modelNotificationTimer.current&&clearTimeout(o.modelNotificationTimer.current)},[]),ct(()=>{(async()=>{await loadCustomProviderModels();const e=await checkOAuthSetupRequired({currentProvider:o.currentProvider,isByokModel:isByok({model:o.currentModel}),providerAuthHeaders:providerAuthHeaders});e&&r.setStatus(e)})()},[o.currentProvider,o.currentModel]),ct(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(xh())},_h);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),ct(()=>{a||triggerTasteOnboarding({projectTrusted:s.projectTrusted,onboardingComplete:s.onboardingComplete,isOnboardingMode:s.showTasteOnboarding,tasteOnboardingCheckedRef:s.tasteOnboardingCheckedRef,setIsOnboardingMode:s.setShowTasteOnboarding})},[s.projectTrusted,s.onboardingComplete,s.showTasteOnboarding,a]),ct(()=>{if(s.showTasteOnboarding&&!s.tasteOnboardingEntryId){const e=Sh();s.setTasteOnboardingEntryId(e.id),t.setFeed(t=>[...t,e])}!s.showTasteOnboarding&&s.tasteOnboardingEntryId&&(t.setFeed(e=>e.filter(e=>e.id!==s.tasteOnboardingEntryId)),s.setTasteOnboardingEntryId(null))},[s.showTasteOnboarding,s.tasteOnboardingEntryId])}async function handleCompactModeSelect({mode:e,setShowCompactModeSelector:t,setStatus:n}){try{await setCompactMode({mode:e}),t(!1),n(buildCompactModeStatusMessage(e))}catch{n(xo),t(!1)}}function handleCompactModeCancel({setShowCompactModeSelector:e}){e(!1)}__name(setStartupSessionOptions,"setStartupSessionOptions"),__name(getStickyStartupSessionOptions,"getStickyStartupSessionOptions"),__name(consumeStartupSessionOverrides,"consumeStartupSessionOverrides"),__name(buildInteraction,"buildInteraction"),__name(useHarness,"useHarness"),Gt(),SR(),__name(useLifecycle,"useLifecycle"),Gt(),SR(),Gt(),SR(),__name(handleCompactModeSelect,"handleCompactModeSelect"),__name(handleCompactModeCancel,"handleCompactModeCancel");var Aj=__name(e=>{},"noopBool");function useMainActionCallbacks({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,setInput:s}){const i=lt({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,setInput:s});i.current={feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,setInput:s};const a=ut(e=>{const{feedState:t,sessionState:n,statusState:r,uiOverlays:o,authState:s}=i.current;handleSelectSession({selectedSessionId:e,previousSessionId:n.sessionId,sessionLoadIdRef:n.sessionLoadIdRef,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:n.setSessionId,setShowSessionSelector:o.setShowSessionSelector,setSessionLoaded:n.setSessionLoaded,setStaticKey:o.setStaticKey,setShareInfo:r.setShareInfo,setCurrentModel:s.setCurrentModel,inTuiResume:!0})},[]),l=ut(({messageId:e,mode:t})=>{const{feedState:n,sessionState:r,statusState:o,uiOverlays:s,setInput:a}=i.current;handleRewindSelect({messageId:e,mode:t,sessionId:r.sessionId,setFeed:n.setFeed,setStatus:o.setStatus,setShowRewindSelector:s.setShowRewindSelector,setStaticKey:s.setStaticKey,setInput:a})},[]),c=ut(()=>{handleRewindCancel({setShowRewindSelector:i.current.uiOverlays.setShowRewindSelector})},[]),d=ut(e=>{const{feedState:t,sessionState:n,uiOverlays:r,setInput:o}=i.current;return handleTreeSelect({...e,sessionId:n.sessionId,setFeed:t.setFeed,setShowTreeSelector:r.setShowTreeSelector,setStaticKey:r.setStaticKey,setInput:o})},[]),u=ut(()=>{handleTreeCancel({setShowTreeSelector:i.current.uiOverlays.setShowTreeSelector})},[]),m=ut(e=>{const{feedState:t,sessionState:n}=i.current;handleTreeLabel({...e,sessionId:n.sessionId,setFeed:t.setFeed})},[]),p=ut(()=>{handleTreeAbortSummary({sessionId:i.current.sessionState.sessionId})},[]),g=ut((e,t)=>{const{feedState:n,statusState:r,uiOverlays:o}=i.current;handleLoginComplete({success:e,message:t,setShowLoginOverlay:o.setShowLoginOverlay,setFeed:n.setFeed,setStatus:r.setStatus})},[]),h=ut(()=>{const{feedState:e,statusState:t,uiOverlays:n}=i.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),f=__name(e=>{const t=i.current.authState.currentModel;if(dlog("[LaneSwitch] autoSwitchModelForLane",{provider:e,model:t}),laneServesModel({activeLane:e,modelId:t}))return;const n=defaultModelForLane({activeLane:e});dlog("[LaneSwitch] fallback",{fallback:n}),n&&v(n,e)},"autoSwitchModelForLane"),y=ut(e=>{const{authState:t,sessionState:n,statusState:r,uiOverlays:o}=i.current;handleProviderSelect({provider:e,setCurrentProvider:t.setCurrentProvider,setShowProviderSelector:o.setShowProviderSelector,setAuthComponentInfo:t.setAuthComponentInfo,setStatus:r.setStatus,setShowProviderNotification:t.setShowProviderNotification,providerNotificationTimer:t.providerNotificationTimer,setShowModelSelector:o.setShowModelSelector,sessionId:n.sessionId,onActiveModelOrphaned:__name(async()=>{{const e=await S();dlog("[LaneSwitch] orphaned → lane default",{fallback:e}),clearModelOverride(),setSessionModel(e),await persistDefaultModel({model:e});const t=i.current.sessionState.sessionId;t&&await saveCommandSessionMeta({sessionId:t,meta:{model:e}}),i.current.authState.setCurrentModel(e),i.current.uiOverlays.setStaticKey(e=>e+1)}},"onActiveModelOrphaned"),onDiskDefaultOrphaned:__name(async()=>{await persistDefaultModel({model:await S()})},"onDiskDefaultOrphaned")}).then(({switched:t})=>{t&&f(e)})},[]),S=__name(async()=>{const e=i.current.authState.currentProvider??await getConfiguredProvider()??uo.COMMAND;return e===uo.COMMAND?pr:defaultModelForLane({activeLane:e})??pr},"resolveOrphanFallback"),w=ut(()=>{handleProviderCancel({setShowProviderSelector:i.current.uiOverlays.setShowProviderSelector})},[]),v=ut((e,t)=>{const{authState:n,sessionState:r,statusState:o,uiOverlays:s,feedState:a}=i.current;handleModelSelect({modelId:e,provider:t,setCurrentModel:n.setCurrentModel,setShowModelSelector:s.setShowModelSelector,setStatus:o.setStatus,modelNotificationTimer:n.modelNotificationTimer,setShowModelNotification:Aj,setCurrentProvider:n.setCurrentProvider,setStaticKey:s.setStaticKey,sessionId:r.sessionId,setFeed:a.setFeed,setContextUsage:o.setContextUsage,setModelNotice:s.setModelNotice})},[]),k=ut(()=>{handleModelCancel({setShowModelSelector:i.current.uiOverlays.setShowModelSelector})},[]),C=ut(e=>{const{statusState:t,uiOverlays:n}=i.current;handleCompactModeSelect({mode:e,setShowCompactModeSelector:n.setShowCompactModeSelector,setStatus:t.setStatus})},[]),b=ut(()=>{handleCompactModeCancel({setShowCompactModeSelector:i.current.uiOverlays.setShowCompactModeSelector})},[]),E=ut(e=>{const{statusState:t,uiOverlays:n}=i.current;handleThemeSelect({theme:e,setShowThemeSelector:n.setShowThemeSelector,setStatus:t.setStatus,setStaticKey:n.setStaticKey})},[]),T=ut(()=>{handleThemeCancel({setShowThemeSelector:i.current.uiOverlays.setShowThemeSelector})},[]),P=ut(()=>{const{authState:e,sessionState:t,statusState:n,uiOverlays:r}=i.current;handleAuthSuccess({authComponentInfo:e.authComponentInfo,setAuthComponentInfo:e.setAuthComponentInfo,setShowProviderSelector:r.setShowProviderSelector,setCurrentProvider:e.setCurrentProvider,setStatus:n.setStatus,setShowProviderNotification:e.setShowProviderNotification,providerNotificationTimer:e.providerNotificationTimer,sessionId:t.sessionId}).then(({switchedProvider:e})=>{e&&f(e)})},[]),M=ut(()=>{handleAuthCancel({setAuthComponentInfo:i.current.authState.setAuthComponentInfo})},[]);return{onSelectSession:a,onRewindSelect:l,onRewindCancel:c,onTreeSelect:d,onTreeCancel:u,onTreeLabel:m,onTreeAbortSummary:p,onLoginComplete:g,onLoginCancel:h,handleProviderSelect:y,handleProviderCancel:w,handleModelSelect:v,handleModelCancel:k,handleCompactModeSelect:C,handleCompactModeCancel:b,handleThemeSelect:E,handleThemeCancel:T,handleAuthSuccess:P,handleAuthCancel:M}}function useMonitorOutputWakeup({onSubmit:e}){const t=lt(e);ct(()=>{t.current=e},[e]),ct(()=>{const e=subscribeMonitorCheck(e=>{t.current(buildMonitorWakeupSubmission(e))});return()=>{e()}},[])}function useOnboarding(){const[e,t]=at(!1),[n,r]=at(!1),[o,s]=at(!0),[i,a]=at(!1),[l,c]=at(!1),[d,u]=at(null),[m,p]=at(!1);return{showTrustPrompt:e,setShowTrustPrompt:t,projectTrusted:n,setProjectTrusted:r,checkingProject:o,setCheckingProject:s,showTasteOnboarding:i,setShowTasteOnboarding:a,onboardingComplete:l,setOnboardingComplete:c,tasteOnboardingEntryId:d,setTasteOnboardingEntryId:u,autoLearnTaste:m,setAutoLearnTaste:p,tasteOnboardingCheckedRef:lt(!1)}}function usePendingOps(){const[e,t]=at(null),[n,r]=at(null);return{pendingPermission:e,setPendingPermission:t,pendingQuestion:n,setPendingQuestion:r}}function resolvePermissionSettingsPath(e){return t.join(e.projectRoot,".commandcode",e.local?"settings.local.json":"settings.json")}__name(useMainActionCallbacks,"useMainActionCallbacks"),Gt(),SR(),__name(useMonitorOutputWakeup,"useMonitorOutputWakeup"),Gt(),__name(useOnboarding,"useOnboarding"),Gt(),__name(usePendingOps,"usePendingOps"),Gt(),SR(),Gt(),SR(),__name(resolvePermissionSettingsPath,"resolvePermissionSettingsPath");var Rj=__name((e={})=>{const{projectRoot:t,local:n=!1,onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:i}=e,a=t||process.cwd(),l=lt({onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:i}),[c,d]=at(null),u=lt(null),[m,p]=at(null),[g,h]=at(!1);return ct(()=>{l.current={onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:i}},[r,o,s,i]),ct(()=>{const e=resolvePermissionSettingsPath({projectRoot:a,local:n}),t=createPermissionsService(a,{configPath:e});return u.current=createPermissionPromptBridge({service:t,onFileRequest:__name(e=>{p(e),h(!0),l.current.onPermissionRequest?.(e)},"onFileRequest"),onShellRequest:__name(e=>{p(e),h(!0),l.current.onShellPermissionRequest?.(e)},"onShellRequest"),onGenericRequest:__name(e=>{p(e),h(!0),l.current.onGenericPermissionRequest?.(e)},"onGenericRequest")}),d(t),()=>{t.removeAllListeners(),u.current=null}},[n,a]),{requestPermission:ut(async e=>{if(!c)return{allowed:!0};const t=await c.requestPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),requestShellPermission:ut(async e=>{if(!c)return{allowed:!0};const t=await c.requestShellPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),requestGenericPermission:ut(async e=>{if(!c)return{allowed:!0};const t=await c.requestGenericPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),respondToPrompt:ut(e=>{u.current?.respond(e)&&(p(null),h(!1))},[]),clearSessionPermissions:ut(()=>{c?.clearSessionPermissions()},[c]),clearProjectPermissions:ut(()=>{c?.clearProjectPermissions()},[c]),setAutoApprove:ut((e,t)=>{c?.setAutoApprove(e,t)},[c]),setEnabled:ut(e=>{c?.setEnabled(e)},[c]),currentRequest:m,isPrompting:g,service:c}},"usePermissions");function usePermissionMode({initialPermissionMode:e,local:t=!1,dangerouslySkipPermissions:n=!1,setPendingPermission:r,setStatus:o}){const[s,i]=at(()=>e||(n?"bypass":"default")),a=lt(s);ct(()=>{a.current=s},[s]);const{requestShellPermission:l,service:c,respondToPrompt:d,clearSessionPermissions:u,setEnabled:m}=Rj({projectRoot:process.cwd(),local:t,onPermissionRequest:__name(e=>{r({toolName:getFileActionToolName(e.action),params:e,resolve:__name(e=>{},"resolve")}),o("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{r({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),o("Waiting for shell command permission...")},"onShellPermissionRequest"),onGenericPermissionRequest:__name(e=>{r({toolName:e.toolName,params:e,resolve:__name(e=>{},"resolve")}),o("Waiting for tool permission...")},"onGenericPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?o("Permission granted"):o("Permission denied")},"onPermissionResponse")});return ct(()=>{c&&applyAutoAcceptMode({enabled:s,service:c})},[s,c]),{permissionMode:s,setPermissionMode:i,permissionModeRef:a,permissionsService:c,respondToPrompt:d,clearSessionPermissions:u,dangerouslySkipPermissions:n}}function useQueuedMessageFlush({isCmdCodeBusy:e,queuedMessages:t,queuedMessagesRef:n,setQueuedMessages:r,isSubmittingRef:o,onSubmit:s}){const i=lt(s);ct(()=>{i.current=s},[s]);const a=t.length>0;ct(()=>{if(!a||e)return;const t=setInterval(()=>{if(o.current)return;const e=n.current[0];e&&(r(e=>e.slice(1)),i.current({role:"user",input:e.input,...void 0!==e.displayMessage?{displayMessage:e.displayMessage}:{},...void 0!==e.isAutomated?{isAutomated:e.isAutomated}:{},...void 0!==e.isMeta?{isMeta:e.isMeta}:{},...void 0!==e.source?{source:e.source}:{},...void 0!==e.hiddenMessages?{hiddenMessages:e.hiddenMessages}:{},...void 0!==e.ideContext?{ideContext:e.ideContext}:{},...void 0!==e.ideHint?{ideHint:e.ideHint}:{},...e.images&&e.images.length>0?{images:e.images.map(e=>({...e}))}:{}}))},250);return()=>clearInterval(t)},[a,e,o,n,r])}function useSession(){const[e,t]=at(()=>crypto.randomUUID()),[n,r]=at(!1);return{sessionId:e,setSessionId:t,sessionLoaded:n,setSessionLoaded:r,sessionLoadIdRef:lt(null)}}__name(usePermissionMode,"usePermissionMode"),Gt(),__name(useQueuedMessageFlush,"useQueuedMessageFlush"),Gt(),__name(useSession,"useSession"),Gt(),SR(),Gt(),SR();var Lj=createOSC8Link("https://commandcode.ai/docs/hooks","Docs ↗",!1),Oj=createOSC8Link("https://commandcode.ai/docs/core-concepts/custom-agents","Docs ↗",!1);function buildStartupWarningEntries(e){const t=[];for(const n of e.fileLevelMessages)t.push({message:n,isFileLevel:!0});if(e.summaryLine&&t.push({message:e.summaryLine,isFileLevel:!1}),0===t.length)return[];const n=t[t.length-1];return n.message=`${n.message} ${e.docsLink}`,t.map(t=>t.isFileLevel?uh(t.message,e.fileLevelMetadata):uh(t.message))}function buildHookStartupEntries(e){const t=buildHookStartupMessages(e),n=t.find(e=>!e.isHookWarning);return buildStartupWarningEntries({fileLevelMessages:t.filter(e=>e.isHookWarning).map(e=>e.message),summaryLine:n?.message??null,docsLink:Lj,fileLevelMetadata:{isHookWarning:!0}})}function buildAgentStartupEntries(e){return buildStartupWarningEntries({fileLevelMessages:[],summaryLine:summarizeAgentConfigWarnings(e),docsLink:Oj})}async function submitInitialPrompt({initialPrompt:e,onCommand:t,submitAsUserMessage:n}){const r=e.trim();r.startsWith("/")&&t&&"handled"===(await t(r)).status||await n()}function useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:o,stdout:s,feedState:i,sessionState:a,statusState:l,authState:c,onboarding:d,uiOverlays:u,permissionState:m,harnessReady:p,isSubmittingRef:g,initialPromptSubmittedRef:h,historyManagerRef:f,executeBash:y,setInput:S,onCommand:w}){const v=ut(async()=>{try{const e=await isTasteLearningEnabled();l.setTasteLearningOn(e),e&&await initTasteDir({runtime:createNodeRuntime()})}catch{}},[l.setTasteLearningOn]),k=ut(async()=>{const e=await getConfiguredProvider();c.setCurrentProvider(e)},[c.setCurrentProvider]),C=ut(()=>{},[]),b=ut(e=>{handleSelectSession({selectedSessionId:e,sessionLoadIdRef:a.sessionLoadIdRef,setFeed:i.setFeed,setLiveEntries:i.setLiveEntries,setSessionId:a.setSessionId,setShowSessionSelector:u.setShowSessionSelector,setSessionLoaded:a.setSessionLoaded,setStaticKey:u.setStaticKey,setShareInfo:l.setShareInfo,setCurrentModel:c.setCurrentModel})},[a,i,u,l,c.setCurrentModel]),E=ut(async()=>{const r=await resolveStartupSessionTarget({continueLatest:n,resumeSessionId:t,resume:e,listSessions:listCommandSessions});"load"!==r.kind?"open-picker"===r.kind&&u.setShowSessionSelector(!0):b(r.sessionId)},[n,t,e,b,u]);ct(()=>{(async()=>{const e=await resolveStartupTrust({trust:r,isProjectInitialized:isCommandProjectSessionInitialized,isDirectoryEmpty:__name(()=>isDirectoryEmpty({runtime:createNodeRuntime(),path:process.cwd()}),"isDirectoryEmpty")});if("prompt-trust"===e.kind)return d.setShowTrustPrompt(!0),void d.setCheckingProject(!1);e.initializeFirst&&await initializeCommandProjectSessions(),d.setProjectTrusted(!0),d.setCheckingProject(!1),v(),k(),loadCustomProviderModels(),C(),e.continueOrResume&&await E()})()},[e,n,r]);const T=lt(!1);ct(()=>{T.current||d.projectTrusted&&0!==getCommandZdrPausedFeatures().length&&(T.current=!0,u.setShowZdrNotice(!0))},[d.projectTrusted,u.setShowZdrNotice]);const P=lt(null);ct(()=>{d.projectTrusted&&c.currentModel!==P.current&&(P.current=c.currentModel,u.setModelNotice(getModelNotice(c.currentModel)??null))},[d.projectTrusted,c.currentModel,u.setModelNotice]);const M=lt(null);ct(()=>{if(!p||!d.projectTrusted)return;const e=a.sessionId;if(M.current===e)return;const t=k$(e);if(!t)return;M.current=e;const n=buildHookStartupEntries(t.hookSettingsWarnings);0!==n.length&&i.setFeed(e=>[...e,...n])},[p,d.projectTrusted,a.sessionId,i.setFeed]);const x=lt(null);ct(()=>{if(!p||!d.projectTrusted)return;const e=a.sessionId;if(x.current===e)return;const t=k$(e);if(!t)return;x.current=e;const n=buildAgentStartupEntries(t.agentConfigWarnings);0!==n.length&&i.setFeed(e=>[...e,...n])},[p,d.projectTrusted,a.sessionId,i.setFeed]),ct(()=>{if(!d.projectTrusted)return;const e=createCommandHistoryManager();return f.current=e,e.init(),()=>{e.cleanup()}},[d.projectTrusted,f]),ct(()=>{if(!s)return;const e=createResizeHandler({getColumns:__name(()=>s.columns??0,"getColumns"),bumpStaticKey:__name(()=>u.setStaticKey(e=>e+1),"bumpStaticKey")});return s.prependListener("resize",e),()=>{s.off("resize",e)}},[s,u.setStaticKey]),ct(()=>{o&&d.projectTrusted&&!d.checkingProject&&p&&!u.showSessionSelector&&!h.current&&(h.current=!0,submitInitialPrompt({initialPrompt:o,onCommand:w,submitAsUserMessage:__name(async()=>{await handleSubmit({role:"user",input:o,feed:i.feed,setFeed:i.setFeed,setLiveEntries:i.setLiveEntries,isCmdCodeBusy:i.isCmdCodeBusy,setIsCmdCodeBusy:i.setIsCmdCodeBusy,setQueuedMessages:i.setQueuedMessages,setStatus:l.setStatus,setInteractionTokens:l.setInteractionTokens,updateStatus:l.updateStatus,setUpdateStatus:l.setUpdateStatus,billingLink:l.billingLink,setBillingLink:l.setBillingLink,currentModel:c.currentModel,currentProvider:c.currentProvider,premiumCreditsExhausted:c.premiumCreditsExhausted,setPremiumCreditsExhausted:c.setPremiumCreditsExhausted,setCurrentModel:c.setCurrentModel,sessionId:a.sessionId,isSubmittingRef:g,setInput:S,setStaticKey:u.setStaticKey,executeBash:y})},"submitAsUserMessage")}))},[o,d.projectTrusted,d.checkingProject,u.showSessionSelector,p,a.sessionId,c.currentProvider,w]);const I=lt(null);I.current={feed:i.feed,setFeed:i.setFeed,setLiveEntries:i.setLiveEntries,isCmdCodeBusy:i.isCmdCodeBusy,setIsCmdCodeBusy:i.setIsCmdCodeBusy,setQueuedMessages:i.setQueuedMessages,setStatus:l.setStatus,setInteractionTokens:l.setInteractionTokens,updateStatus:l.updateStatus,setUpdateStatus:l.setUpdateStatus,billingLink:l.billingLink,setBillingLink:l.setBillingLink,currentModel:c.currentModel,currentProvider:c.currentProvider,premiumCreditsExhausted:c.premiumCreditsExhausted,setPremiumCreditsExhausted:c.setPremiumCreditsExhausted,setCurrentModel:c.setCurrentModel,sessionId:a.sessionId,isSubmittingRef:g,setInput:S,setStaticKey:u.setStaticKey,executeBash:y,role:"",input:""};const A=ut(async({role:e,input:t,images:n,imageTokenPaths:r,ideContext:o,ideHint:s,displayMessage:i,isAutomated:a,isMeta:l,source:c,hiddenMessages:d})=>{u.setShowTasteSkipBanner(!1),u.setShowZdrNotice(!1),u.setModelNotice(null),await handleSubmit({...I.current,role:e,input:t,images:n,imageTokenPaths:r,ideContext:o,ideHint:s,displayMessage:i,isAutomated:a,isMeta:l,source:c,hiddenMessages:d})},[u.setShowTasteSkipBanner,u.setShowZdrNotice,u.setModelNotice]);return{loadTasteStatus:v,loadCurrentProvider:k,initializeMcpInBackground:C,onSubmit:A}}function useStatus(e){const[t,n]=at("Ready..."),r=lt(!1),[o,s]=at(""),i=lt(null),[a,l]=at(null),c=lt(a),[d,u]=at(null),[m,p]=at(!1),[g,h]=at(""),[f,y]=at(null),[S,w]=at(0),[v,k]=at(null),[C,b]=at(null),[E,T]=at(e??null);ct(()=>{c.current=a},[a]),ct(()=>{if(!E)return;const e=setTimeout(()=>{T(null)},3e4);return()=>clearTimeout(e)},[E]);const P=__name(e=>{i.current&&clearTimeout(i.current),s(e),i.current=setTimeout(()=>{s(""),i.current=null},5e3)},"showHintMessage");return{status:t,setStatus:n,pinnedStatusRef:r,hintMessage:o,setHintMessage:s,hintTimerRef:i,shareInfo:a,setShareInfo:l,shareInfoRef:c,billingLink:d,setBillingLink:u,showShareNotification:m,setShowShareNotification:p,unshareNotificationMessage:g,setUnshareNotificationMessage:h,retryAttempt:f,setRetryAttempt:y,interactionTokens:S,setInteractionTokens:w,contextUsage:v,setContextUsage:k,tasteLearningOn:C,setTasteLearningOn:b,updateStatus:E,setUpdateStatus:T,showHintMessage:P}}function useTerminalTitle({sessionId:e,isCmdCodeBusy:t,modelLabel:n=null}){const r=lt(process.cwd()),o=lt(e),s=lt(null),i=lt(n);i.current=n;const a=ut(e=>{s.current=e,setTerminalTitle(formatSessionTabTitle({sessionTitle:e,projectDir:r.current,modelLabel:i.current}))},[]),l=ut(e=>{(async()=>{const t=await loadCommandSessionMeta({sessionId:e});o.current===e&&t?.title&&t.title!==s.current&&a(t.title)})()},[a]);ct(()=>{o.current=e,a(null),l(e)},[e,a,l]);const c=lt(!0);ct(()=>{c.current?c.current=!1:a(s.current)},[n,a]);const d=lt(t);ct(()=>{const n=d.current;d.current=t,t!==n&&reassertTerminalTitle(),!t&&n&&(s.current||l(e))},[t,e,l]),ct(()=>{if(!process.stderr.isTTY)return;const e=setInterval(reassertTerminalTitle,5e3);return()=>{clearInterval(e)}},[]);const u=ut(e=>{a(e)},[a]);return{setRenamedTerminalTitle:u,applyGeneratedTitle:u}}function useUiOverlays(){const[e,t]=at(!1),[n,r]=at(!1),[o,s]=at(!1),[i,a]=at(!1),[l,c]=at(!1),[d,u]=at(!1),[m,p]=at(!1),[g,h]=at(!1),[f,y]=at(!1),[S,w]=at(!1),[v,k]=at(!1),[C,b]=at(!1),[E,T]=at(!1),[P,M]=at(!1),[x,I]=at("default"),[A,R]=at(!1),[L,O]=at(!1),[D,$]=at(!1),[N,_]=at(!1),[F,U]=at(!1),[j,B]=at(!1),[W,H]=at(null),[G,V]=at(!1),[z,K]=at(!1),[q,Y]=at(!1),[J,Q]=at(!1),[X,Z]=at(null),[ee,te]=at(0),[ne,re]=at(!1),[oe,se]=at(!1),[ie,ae]=at(null),[le,ce]=at("off"),de="off"!==le,ue=ut(e=>{hardResetForResize(),te(e=>e+1),e(!1)},[]);return{showFileList:e,setShowFileList:t,showAgentsConfig:n,setShowAgentsConfig:r,showTasteConfig:o,setShowTasteConfig:s,showSkillsConfig:i,setShowSkillsConfig:a,showSettingsConfig:l,setShowSettingsConfig:c,showProviderSelector:d,setShowProviderSelector:u,showModelSelector:m,setShowModelSelector:p,showEffortSelector:g,setShowEffortSelector:h,showMemorySelector:f,setShowMemorySelector:y,showMcpManager:S,setShowMcpManager:w,showSessionSelector:v,setShowSessionSelector:k,showAddDirModal:C,setShowAddDirModal:b,showRewindSelector:E,setShowRewindSelector:T,showTreeSelector:P,setShowTreeSelector:M,treeFilterMode:x,setTreeFilterMode:I,treeBranchSummarySkipPrompt:A,setTreeBranchSummarySkipPrompt:R,showLoginOverlay:L,setShowLoginOverlay:O,showCompactModeSelector:D,setShowCompactModeSelector:$,showContextView:N,setShowContextView:_,showStatusView:F,setShowStatusView:U,showPlansView:j,setShowPlansView:B,plansTarget:W,setPlansTarget:H,planBreadcrumbPending:G,setPlanBreadcrumbPending:V,showUsageOverlay:z,setShowUsageOverlay:K,showThemeSelector:q,setShowThemeSelector:Y,staticKey:ee,setStaticKey:te,closeFullScreenOverlay:ue,showTasteSkipBanner:ne,setShowTasteSkipBanner:re,showZdrNotice:oe,setShowZdrNotice:se,modelNotice:ie,setModelNotice:ae,transcriptMode:le,setTranscriptMode:ce,expandedToolOutput:de,showDesignGuide:J,setShowDesignGuide:Q,pendingDesignSuggestion:X,setPendingDesignSuggestion:Z}}__name(buildStartupWarningEntries,"buildStartupWarningEntries"),__name(buildHookStartupEntries,"buildHookStartupEntries"),__name(buildAgentStartupEntries,"buildAgentStartupEntries"),__name(submitInitialPrompt,"submitInitialPrompt"),__name(useStartup,"useStartup"),Gt(),__name(useStatus,"useStatus"),Gt(),SR(),__name(useTerminalTitle,"useTerminalTitle"),Gt(),__name(useUiOverlays,"useUiOverlays");var Dj=__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:c,local:d=!1,sessionTitleHolder:u})=>{const{exit:m}=rt(),{stdout:p}=et();usePasteRouter(),ct(()=>{isLocalOnly()||prefetchBillingContext()},[]);const[g,h]=at(""),[f,y]=at(""),S=lt(!1),w=lt(!1),v=lt(null),k=useUiOverlays(),C=useFeed(),b=useSession(),E=useStatus(s),T=useAuth(),P=usePendingOps(),M=useOnboarding(),x=useExit(),{executeBash:I,executionState:A}=rj(),R=usePermissionMode({initialPermissionMode:c,local:d,dangerouslySkipPermissions:o,setPendingPermission:P.setPendingPermission,setStatus:E.setStatus}),L=dt(()=>getModelShortName({modelId:T.currentModel,findModelById:findModelById}),[T.currentModel]),O=useTerminalTitle({sessionId:b.sessionId,isCmdCodeBusy:C.isCmdCodeBusy,modelLabel:L}),{ready:D}=useHarness({sessionId:b.sessionId,sessionLoaded:b.sessionLoaded,showSessionSelector:k.showSessionSelector,projectTrusted:M.projectTrusted,permissionsService:R.permissionsService,permissionModeRef:R.permissionModeRef,setPermissionMode:R.setPermissionMode,permissionModeExplicit:Boolean(c)||o,dangerouslySkipPermissions:R.dangerouslySkipPermissions,setPendingQuestion:P.setPendingQuestion,setStatus:E.setStatus,setFeed:C.setFeed,queuedMessagesRef:C.queuedMessagesRef,setQueuedMessages:C.setQueuedMessages,onSessionTitled:O.applyGeneratedTitle,currentModel:T.currentModel,setCurrentModel:T.setCurrentModel,setStaticKey:k.setStaticKey,isCmdCodeBusy:C.isCmdCodeBusy}),{onCommand:$}=useCommandCtx({feedState:C,sessionState:b,statusState:E,authState:T,uiOverlays:k,onboarding:M,exitState:x,permissionState:R,terminalTitleState:O,isSubmittingRef:S,executeBash:I,setInput:h});useAgentSlashCommandQueue({sessionId:b.sessionId,isCmdCodeBusy:C.isCmdCodeBusy,onCommand:$}),ct(()=>{k.planBreadcrumbPending&&!C.isCmdCodeBusy&&(k.setPlanBreadcrumbPending(!1),C.setFeed(e=>[...e,fh("Plan saved — run /plans to review, annotate, or execute it anytime.")]))},[k.planBreadcrumbPending,k.setPlanBreadcrumbPending,C.isCmdCodeBusy,C.setFeed]);const{loadTasteStatus:N,loadCurrentProvider:_,onSubmit:F}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:a,stdout:p,feedState:C,sessionState:b,statusState:E,authState:T,onboarding:M,uiOverlays:k,permissionState:R,harnessReady:D,isSubmittingRef:S,initialPromptSubmittedRef:w,historyManagerRef:v,executeBash:I,setInput:h,onCommand:$});useMonitorOutputWakeup({onSubmit:F}),useCronWakeup({sessionId:b.sessionId,onSubmit:F}),useQueuedMessageFlush({isCmdCodeBusy:C.isCmdCodeBusy,queuedMessages:C.queuedMessages,queuedMessagesRef:C.queuedMessagesRef,setQueuedMessages:C.setQueuedMessages,isSubmittingRef:S,onSubmit:F}),useLifecycle({exit:m,feedState:C,exitState:x,statusState:E,authState:T,onboarding:M,uiOverlays:k,skipOnboarding:l,sessionId:b.sessionId,sessionTitleHolder:u});const{handleToggleAutoAccept:U,handleEnableAutoAccept:j,handleDoubleEscapeEmpty:B,handleTasteOnboardingComplete:W,handleTrust:H,handleNoTrust:G}=useHandlers({resume:e,feedState:C,onboarding:M,uiOverlays:k,exitState:x,pendingOps:P,permissionState:R,statusState:E,authState:T,sessionId:b.sessionId,loadTasteStatus:N,loadCurrentProvider:_,setInput:__name(e=>h(e),"setInput")}),V=useMainActionCallbacks({feedState:C,sessionState:b,statusState:E,authState:T,uiOverlays:k,setInput:h}),{creditWarning:z}=useCreditWarning({interactionTokens:E.interactionTokens,currentModel:T.currentModel});return renderView({feedState:C,sessionState:b,statusState:E,authState:T,uiOverlays:k,onboarding:M,exitState:x,pendingOps:P,permissionState:R,historyManagerRef:v,executionState:A,actionCallbacks:V,onSubmit:F,onCommand:$,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,updateFailedInfo:i,creditWarning:z,handleTrust:H,handleNoTrust:G,handleToggleAutoAccept:U,handleEnableAutoAccept:j,handleDoubleEscapeEmpty:B,handleTasteOnboardingComplete:W,loadTasteStatus:N})},"InteractiveCLI");function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:i,pendingOps:a,permissionState:l,historyManagerRef:c,executionState:d,actionCallbacks:u,onSubmit:m,onCommand:p,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,updateFailedInfo:S,creditWarning:w,handleTrust:v,handleNoTrust:k,handleToggleAutoAccept:C,handleEnableAutoAccept:b,handleDoubleEscapeEmpty:E,handleTasteOnboardingComplete:T,loadTasteStatus:P}){if(i.shouldExit)return null;if(s.checkingProject)return null;if(s.showTrustPrompt)return st.createElement(tj,{staticKey:o.staticKey,onTrust:v,onExit:k});if(o.showSessionSelector)return st.createElement(ZU,{onSelectSession:u.onSelectSession,onClose:()=>o.closeFullScreenOverlay(o.setShowSessionSelector),currentSessionId:t.sessionId});if(!s.projectTrusted)return null;const M=o.pendingDesignSuggestion?st.createElement(g_,{suggestion:o.pendingDesignSuggestion,onSelect:e=>{p(`/design ${e}`)},onClose:()=>o.setPendingDesignSuggestion(null)}):null,x=a.pendingQuestion?.params.exitPlanMode?a.pendingQuestion:null,I=a.pendingQuestion&&!x?st.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,dangerouslySkipPermissions:l.dangerouslySkipPermissions,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:o.setStaticKey}):null,A=a.pendingPermission?st.createElement(o_,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleEnableAutoAccept:b}):null,{closeFullScreenOverlay:R}=o;if(x){const e=__name(e=>{const t=resolvePlanModeAnswerTransition({answer:e,exitPlanMode:!0,dangerouslySkipPermissions:l.dangerouslySkipPermissions});t&&l.setPermissionMode(t),x.resolve({answers:[{questionIndex:0,selectedOptions:[e]}]}),a.setPendingQuestion(null),hardResetForResize(),o.setStaticKey(e=>e+1)},"resolveApproval");return st.createElement(PlanApprovalView,{staticKey:o.staticKey,planContent:x.params.planContent,planFilePath:x.params.planFilePath,onAutoAccept:t=>{e("Yes, auto-accept edits"),t&&m({role:"user",input:t})},onCancel:()=>{e("Cancel"),o.setPlanBreadcrumbPending(!0)},onSendFeedback:t=>{e("Cancel"),m({role:"user",input:t})}})}if(o.showTasteConfig)return st.createElement(TasteConfigView,{staticKey:o.staticKey,onClose:()=>R(o.setShowTasteConfig),loadTasteStatus:P});if(o.showSkillsConfig)return st.createElement(SkillsConfigView,{staticKey:o.staticKey,onClose:()=>R(o.setShowSkillsConfig)});if(o.showSettingsConfig)return st.createElement(SettingsConfigView,{staticKey:o.staticKey,onClose:()=>R(o.setShowSettingsConfig),loadTasteStatus:P});if(o.showUsageOverlay)return st.createElement(UsageView,{staticKey:o.staticKey,onClose:()=>R(o.setShowUsageOverlay)});if(o.showContextView)return st.createElement(ContextConfigView,{staticKey:o.staticKey,sessionId:t.sessionId,onClose:()=>R(o.setShowContextView),setInput:h});if(o.showStatusView)return st.createElement(StatusConfigView,{staticKey:o.staticKey,sessionId:t.sessionId,onClose:()=>R(o.setShowStatusView),setInput:h});if(o.showPlansView){const e=__name(e=>{o.setPlansTarget(null),R(o.setShowPlansView),m({role:"user",input:e})},"submitFromPlans");return st.createElement(PlansView,{staticKey:o.staticKey,sessionId:t.sessionId,target:o.plansTarget,onClose:()=>{o.setPlansTarget(null),R(o.setShowPlansView)},onSubmitFeedback:e,onExecute:n=>{"plan"===l.permissionModeRef.current&&(l.permissionModeRef.current="auto-accept",l.setPermissionMode("auto-accept"),k$(t.sessionId)?.setPermissionMode({mode:"auto-accept"})),e(n)}})}return st.createElement(CU,{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,modelNotice:o.modelNotice,retryAttempt:n.retryAttempt,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,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,showTreeSelector:o.showTreeSelector,treeFilterMode:o.treeFilterMode,treeBranchSummarySkipPrompt:o.treeBranchSummarySkipPrompt,showLoginOverlay:o.showLoginOverlay,showUsageOverlay:o.showUsageOverlay,setShowUsageOverlay:o.setShowUsageOverlay,showAddDirModal:o.showAddDirModal,showCompactModeSelector:o.showCompactModeSelector,showThemeSelector:o.showThemeSelector,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:S,creditWarning:w,permissionMode:l.permissionMode,hintMessage:n.hintMessage,pendingExitKey:i.pendingExitKey,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,tasteLearningOn:n.tasteLearningOn,historyManagerRef:c,executionState:d,sessionId:t.sessionId,onSubmit:m,onCommand:p,onToggleAutoAccept:C,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:E,onTasteOnboardingComplete:T,permissionPanel:A,questionPanel:I,designSuggestionPanel:M,onRewindSelect:u.onRewindSelect,onRewindCancel:u.onRewindCancel,onTreeSelect:u.onTreeSelect,onTreeCancel:u.onTreeCancel,onTreeLabel:u.onTreeLabel,onTreeAbortSummary:u.onTreeAbortSummary,onLoginComplete:u.onLoginComplete,onLoginCancel:u.onLoginCancel,setShowProviderSelector:o.setShowProviderSelector,setShowModelSelector:o.setShowModelSelector,setShowEffortSelector:o.setShowEffortSelector,setShowMemorySelector:o.setShowMemorySelector,setShowMcpManager:o.setShowMcpManager,setShowAgentsConfig:o.setShowAgentsConfig,setShowRewindSelector:o.setShowRewindSelector,setShowTreeSelector:o.setShowTreeSelector,setShowLoginOverlay:o.setShowLoginOverlay,setShowAddDirModal:o.setShowAddDirModal,handleProviderSelect:u.handleProviderSelect,handleProviderCancel:u.handleProviderCancel,handleModelSelect:u.handleModelSelect,handleModelCancel:u.handleModelCancel,handleCompactModeSelect:u.handleCompactModeSelect,handleCompactModeCancel:u.handleCompactModeCancel,handleThemeSelect:u.handleThemeSelect,handleThemeCancel:u.handleThemeCancel,handleAuthSuccess:u.handleAuthSuccess,handleAuthCancel:u.handleAuthCancel,showDesignGuide:o.showDesignGuide,setShowDesignGuide:o.setShowDesignGuide})}__name(renderView,"renderView"),SR(),Gt();var $j=__name(({worktreePath:e,warning:t,onChoice:n})=>{const[r,o]=at(1);return nt((e,t)=>{if(!t.upArrow&&!t.downArrow)return"1"===e?n("keep"):"2"===e?n("remove"):t.return?n(1===r?"keep":"remove"):t.escape||t.ctrl&&"c"===e?n("keep"):void 0;o(e=>1===e?2:1)}),st.createElement(bO,{title:"Exiting worktree session",subtitle:t,hint:"Enter to confirm · Esc to cancel"},st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,null,st.createElement(Xe,{color:1===r?ER.CYAN:ER.GRAY},1===r?gt.pointer:" "," 1. Keep worktree"," ",st.createElement(Xe,{color:ER.GRAY},"Stays at ",tildeHome(e)))),st.createElement(Qe,null,st.createElement(Xe,{color:2===r?ER.CYAN:ER.GRAY},2===r?gt.pointer:" "," 2. Remove worktree"," ",st.createElement(Xe,{color:ER.GRAY},"All changes and commits will be lost.")))))},"WorktreeExitPrompt");function promptWorktreeExit(e){return new Promise(t=>{const{unmount:n}=tt(st.createElement($j,{worktreePath:e.worktreePath,warning:e.warning,onChoice:e=>{n(),t(e)}}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})})}function clearedHandoffEnv(e=process.env,t=process.pid){return{...releasedPaneOwnerEnv(e,t)}}function canRespawn(){if(process.versions.bun)return!1;const e=process.argv[1];return"string"==typeof e&&e.length>0}function resetTerminalForRespawn(){process.stdout.isTTY&&RL()}async function writeReloadHandoff(e){const t=process.env[zM];if(t)try{await z.writeFile(t,serializeReloadCarryover(e))}catch{}}async function consumeReloadHandoff(e){try{return parseReloadCarryover(await z.readFile(e,"utf-8"))}catch{return null}finally{await z.unlink(e).catch(()=>{})}}function restoreTerminal({signal:e=null}={}){try{process.stdin.isTTY&&process.stdin.setRawMode(!1)}catch{}try{process.stdout.write("[?25h")}catch{}if(e)try{popKittyKeyboardProtocol()}catch{}}__name(promptWorktreeExit,"promptWorktreeExit"),Gt(),SR(),__name(clearedHandoffEnv,"clearedHandoffEnv"),__name(canRespawn,"canRespawn"),__name(resetTerminalForRespawn,"resetTerminalForRespawn"),__name(writeReloadHandoff,"writeReloadHandoff"),__name(consumeReloadHandoff,"consumeReloadHandoff"),__name(restoreTerminal,"restoreTerminal");var Nj=ht.hex(ER.DIM);function printReloadFallbackHint(){process.stdout.write(Nj("Couldn't restart automatically in this build — exiting instead.\n"))}async function shutdownWrapperRuntime(){try{await Promise.allSettled([disconnectAllMcpServers(),b$(),disposeCommandModHost()])}catch{}try{await shutdownTelemetry()}catch{}process.removeAllListeners("SIGINT"),process.removeAllListeners("SIGTERM"),process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{}),process.stdin.pause()}async function runRelaunchLoop(e){await shutdownWrapperRuntime();const n=await z.mkdtemp(t.join(B.tmpdir(),"cmd-reload-")),r=t.join(n,"handoff.json");let o=e;for(;;){const e=await commandSessionTranscriptExists(o.sessionId),t=buildRelaunchArgs({invocation:getOriginalInvocation(),request:o,resumable:e,argv:process.argv.slice(2)});clearTerminalTitle(),resetTerminalForRespawn();const s=w(process.execPath,[process.argv[1],...t],{stdio:"inherit",env:{...process.env,[zM]:r,[KM]:String(process.pid),...clearedHandoffEnv()}});let i,a;try{[i,a]=await new Promise((e,t)=>{s.once("exit",(t,n)=>e([t,n])),s.once("error",t)})}catch(e){restoreTerminal(),process.stderr.write(Nj(`\nCouldn't relaunch Command Code: ${e.message}\n`)),await z.rm(n,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}if(i!==VM){if(restoreTerminal({signal:a}),await z.rm(n,{recursive:!0,force:!0}).catch(()=>{}),a){const e=B.constants.signals[a];process.exit(e?128+e:1)}process.exit(i??1)}else o=await consumeReloadHandoff(r)??o}}async function handlePendingReload(e){canRespawn()?(isWrappedChild()&&(await writeReloadHandoff(e),await disposeCommandModHost(),process.exit(VM)),await runRelaunchLoop(e)):printReloadFallbackHint()}__name(printReloadFallbackHint,"printReloadFallbackHint"),__name(shutdownWrapperRuntime,"shutdownWrapperRuntime"),__name(runRelaunchLoop,"runRelaunchLoop"),__name(handlePendingReload,"handlePendingReload"),Gt(),SR();var _j=["disambiguateEscapeCodes"];async function resolveKittyKeyboard(e={}){const t=e.env??process.env,n=e.probe??queryKittyKeyboardSupport,r=!isVSCodeTerminal2({env:t})&&await n();return setKittyKeyboardActive(r),{mode:r?"enabled":"disabled",flags:_j}}__name(resolveKittyKeyboard,"resolveKittyKeyboard");var Fj=ht.hex(ER.DIM),Uj=__name(()=>{const e=getInvokedCommandName();return"win32"===process.platform&&"cmd"===e?"cmdc":e},"getResumeCommandName"),jj=__name((e,t)=>{const n=Uj(),r=Ce([e]),o=t?`cd ${Ce([t])} && ${n} --resume ${r}`:`${n} --resume ${r}`;return`${Fj("Resume this session with:")}\n${Fj(o)}\n`},"formatResumeHint"),Bj=__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"),Wj=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),Hj=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),Gj=__name(e=>e.permissionMode?e.permissionMode:e.plan?"plan":void 0,"resolveInitialPermissionMode"),Vj=__name(({options:e,resumeSessionId:t,sessionTitleHolder:n})=>{const r=Gj(e);return{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,local:e.local,sessionTitleHolder:n}},"buildInteractiveCLIProps"),zj=__name(e=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1,kittyKeyboard:e}),"getInkRenderOptions"),Kj=!1,qj=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode(),!Kj&&isKittyKeyboardActive()&&popKittyKeyboardProtocol()})},"setupBracketedPasteMode"),Yj=__name(()=>{qj()},"initializeTerminal"),Jj=__name(()=>{process.on("SIGINT",()=>{})},"swallowSigintDuringShutdown"),Qj=__name(async e=>{const{resumeSessionId:t,useContinue:n}=e,r=n?(await listCommandSessions())[0]?.id:void 0,o=t??r;if(!o)return console.error("--fork-session ignored: no session to fork (use with --resume <id|name> or --continue)."),null;try{const{newId:e}=await forkCommandSessionFiles({sourceId:o});return e}catch(e){const t=e instanceof Error?e.message:String(e);return console.error(`--fork-session failed: ${t}. Resuming the original session.`),null}},"forkSourceAtColdStart"),Xj=__name(async(e={})=>{const t=Bj(process.stdin.isTTY);let n,o;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),Yj(),"string"==typeof e.resume){const t=e.resume.trim();await isCommandProjectSessionInitialized()||(console.error("Project not initialized. Run cmd to start a conversation first."),process.exit(1));const r=await resolveCommandSessionRef({sessionRef:t});"not-found"===r.status&&(console.error(buildSessionRefNotFoundMessage(t)),process.exit(1)),n=r.sessionId}if("string"==typeof e.session&&!n){const t=getCommandSessionRuntime(),i=await listAllSessionsV3({runtime:t}),a=getProjectSessionDir({env:t.env(),cwd:t.cwd()}),l=resolveSessionRefFlag({ref:e.session,isExistingFile:__name(e=>A(e),"isExistingFile"),listSessionIds:__name(()=>i.map(e=>e.id),"listSessionIds")});"not-found"===l.kind&&(console.error(`--session "${e.session}" is neither an existing .jsonl transcript nor a known session-id prefix.`),process.exit(1)),"ambiguous"===l.kind&&(console.error(`--session "${e.session}" is ambiguous — matches: ${l.candidates.join(", ")}`),process.exit(1));const d="path"===l.kind?s(l.path):s(i.find(e=>e.id===l.sessionId)?.path??"");n=c(d,".jsonl"),r(d)!==a&&(o=d)}if(Wj(e)&&!n){const e=await isCommandProjectSessionInitialized(),t=e?await listCommandSessions():[],n=Hj({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}if(e.forkSession){const t=await Qj({resumeSessionId:n,useContinue:Boolean(e.continue)});t&&(n=t,e.continue=!1)}await applyStartupTheme();const i=await resolveKittyKeyboard();startEarlyInputCapture(),setStartupSessionOptions({...!1===e.session?{persist:!1}:{},...o?{sessionFilePath:o}:{},...e.name?{name:e.name}:{}});const a={},l=Vj({options:e,resumeSessionId:n,sessionTitleHolder:a}),d=zj(i),u=tt(st.createElement(Dj,{...l}),d);registerInkControl({clear:u.clear,stdout:process.stdout,instance:await resolveInkInstance(process.stdout)}),await u.waitUntilExit(),Kj=!0,clearTerminalTitle(),Jj();const m=consumePendingReload();m&&await handlePendingReload(m);const p=await(a.loadTitle?.())??null,g=Boolean(p);let h;const f=getAutoCreatedWorktree();if(f){const e=worktreeHasWork(f.worktreePath,f.baseSha);let t="auto";if(e||g){const n=worktreeChangeCount(f.worktreePath),r=e?n>0?`You have ${n} uncommitted file${1===n?"":"s"}. These will be lost if you remove the worktree.`:"This worktree has commits that are not on your main branch. They will be lost if you remove it.":null;t=await promptWorktreeExit({worktreePath:f.worktreePath,warning:r})}const n=finalizeAutoCreatedWorktree(t);if(n.worktreePath){const e=Fj(createOSC8Link(fileUrl(n.worktreePath),tildeHome(n.worktreePath),!1));if(n.removed){const n="auto"===t?"Removed empty worktree":"Removed worktree";process.stdout.write(`${Fj(n)}\n${e}\n\n`)}else if(n.kept){h=n.worktreePath;const t=n.reason&&"kept"!==n.reason?` (${n.reason})`:"";process.stdout.write(`${Fj(`Kept worktree${t}`)}\n${e}\n\n`)}}}const y=a.sessionId;if(y&&await commandSessionExists(y)){const e=p?sanitizeTitleForOutput(p):"";process.stdout.write(jj(e||y,h))}},"interactiveMode");Gt(),SR(),Gt();function isAgentMetrics(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&"number"==typeof t.turns&&"object"==typeof t.toolCalls&&null!==t.toolCalls&&"number"==typeof t.toolErrors&&"number"==typeof t.tokens&&"number"==typeof t.durationMs}function extractAgentMetrics(e){const t=e.indexOf("\x3c!-- BENCHMARK_AGENT_METRICS:");if(-1===t)return{cleanContent:e,metrics:null};const n=t+29,r=e.indexOf(" --\x3e",n);if(-1===r)return{cleanContent:e,metrics:null};try{const o=e.substring(n,r),s=JSON.parse(o);return isAgentMetrics(s)?{cleanContent:e.substring(0,t).trimEnd()+e.substring(r+4),metrics:s}:{cleanContent:e,metrics:null}}catch{return{cleanContent:e,metrics:null}}}__name(isAgentMetrics,"isAgentMetrics"),__name(extractAgentMetrics,"extractAgentMetrics");var Zj=__name(e=>({turnNumber:e,apiDurationMs:0,toolCalls:[],toolDurationMs:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}),"newTurn");function createBenchmarkCollector(e){const t=e.now??Date.now,n=e.writeFile??((e,t)=>{x.writeFileSync(e,t)}),r=t(),o=[],s=[],i=new Map,a=new Map;let l,c=!1;const d=__name(e=>{let t=e;for(;;){const{cleanContent:e,metrics:n}=extractAgentMetrics(t);if(!n)return;s.push(n),t=e}},"collectAgentMetrics"),u=__name(()=>{const e=o[o.length-1];if(e)return e;const t=Zj(o.length+1);return o.push(t),t},"currentTurn"),m=__name(e=>{const n=u(),r=i.get(e.toolCallId);void 0!==r&&(n.toolDurationMs+=t()-r,i.delete(e.toolCallId));const o=a.get(e.toolCallId);o?o.isError=e.isError||o.isError:n.toolCalls.push({name:e.toolName,isError:e.isError})},"finishToolCall"),p=__name(e=>{if("turn_start"!==e.type)if("model_request_start"!==e.type){if("model_request_end"===e.type){const n=u();return void 0!==l&&(n.apiDurationMs+=t()-l,l=void 0),n.inputTokens+=e.usage.inputTokens,n.outputTokens+=e.usage.outputTokens,n.cacheReadTokens+=e.usage.cacheReadTokens,void(n.cacheCreationTokens+=e.usage.cacheWriteTokens)}if("tool_running"===e.type){const n={name:e.toolName,isError:!1};return i.set(e.toolCallId,t()),a.set(e.toolCallId,n),void u().toolCalls.push(n)}if("tool_completed"!==e.type)"tool_errored"!==e.type&&"tool_denied"!==e.type&&"tool_hook_blocked"!==e.type?"run_end"!==e.type||(c=c||"max_turns"===e.result.stopReason):m({toolCallId:e.toolCallId,toolName:e.toolName,isError:!0});else{m({toolCallId:e.toolCallId,toolName:e.toolName,isError:!1});for(const t of e.result)"text"===t.type&&d(t.text)}}else l=t();else o.push(Zj(e.turnNumber))},"onEvent"),g=__name(()=>{const e={};let n=0,i=0,a=0,l=0;for(const t of o){for(const r of t.toolCalls)n++,e[r.name]=(e[r.name]??0)+1,r.isError&&i++;a+=t.inputTokens,l+=t.outputTokens}return{wallTimeMs:t()-r,turns:o.length,turnDetails:o.map(e=>({turnNumber:e.turnNumber,apiDurationMs:e.apiDurationMs,toolCalls:e.toolCalls.map(e=>({name:e.name,isError:e.isError})),toolDurationMs:e.toolDurationMs,inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheReadTokens:e.cacheReadTokens,cacheCreationTokens:e.cacheCreationTokens})),toolCalls:{total:n,byType:e,errors:i},tokens:{input:a,output:l},maxTurnsReached:c,agents:[...s]}},"snapshot"),h=__name(()=>{try{n(e.outputPath,JSON.stringify(g(),null,2))}catch{}},"write");return{onEvent:p,snapshot:g,write:h}}__name(createBenchmarkCollector,"createBenchmarkCollector");var eB=null,tB=!1;function resolveLaunchPermissionMode(e){return e.permissionMode?e.permissionMode:e.plan?"plan":e.dangerouslySkipPermissions?"bypass":void 0}function getAuthKey4(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}async function readStdin(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("Timeout reading from stdin"))},3e4);process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n)}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}function writeOutput(e,t){return!t||e.destroyed?Promise.resolve():new Promise((n,r)=>{e.write(t,e=>{e?r(e):n()})})}function setupSignalHandlers(){if(tB)return;tB=!0;const e=__name(e=>{eB?.abort(),process.stderr.write(`\n${e}\n`),exitAfterModHostTeardown(rT.INTERRUPTED)},"handleTermination");process.on("SIGINT",()=>e("Interrupted.")),process.on("SIGTERM",()=>e("Terminated."))}async function printMode(e={}){trackCommand({command:"print"}),setupSignalHandlers(),eB=new AbortController;const t=e.benchmarkOutput?createBenchmarkCollector({outputPath:e.benchmarkOutput}):null,n=resolveToolEnable({flags:e,env:process.env}),r=toolEnableWarning(n);r&&process.stderr.write(`${r}\n`);const o=await runPrintMode({options:e,stdinIsTTY:Boolean(process.stdin.isTTY),readStdin:readStdin,isAuthenticated:__name(async()=>null!==await getAuthKey4(),"isAuthenticated"),createHarness:__name(async({sessionId:t,entrypoint:r,headless:o,maxTurns:s,mods:i,resumeState:a,sessionFilePath:l})=>{const c=await createHarnessSession({sessionId:t,baseUrl:getApiBaseUrl(),entrypoint:r,headless:o,maxTurns:s,mods:i,dangerouslySkipPermissions:e.dangerouslySkipPermissions,permissionMode:resolveLaunchPermissionMode(e),...n.forceEnabledTools?{forceEnabledTools:n.forceEnabledTools}:{},modHost:await loadCommandModHost({projectMods:Boolean(e.dangerouslySkipPermissions)}),resumeState:a,persist:e.persist,sessionFilePath:l,ideBridge:createLocalIdeBridge()});return e.name&&c.setSessionName(e.name),c},"createHarness"),emit:__name(e=>{"session"===e.type&&process.stderr.write(`session: ${e.sessionId}\n`)},"emit"),writeStdout:__name(e=>{process.stdout.write(e)},"writeStdout"),...t?{runQuery:__name(e=>runHarnessQuery({...e,onEvent:__name(n=>{e.onEvent?.(n),t.onEvent(n)},"onEvent")}),"runQuery")}:{}});t?.write(),await Promise.all([writeOutput(process.stdout,o.stdoutText),writeOutput(process.stderr,o.stderrText)]),exitAfterModHostTeardown(o.exitCode)}__name(resolveLaunchPermissionMode,"resolveLaunchPermissionMode"),__name(getAuthKey4,"getAuthKey"),__name(readStdin,"readStdin"),__name(writeOutput,"writeOutput"),__name(setupSignalHandlers,"setupSignalHandlers"),__name(printMode,"printMode"),Gt(),SR();var nB=getPackageJson(import.meta.url),rB="string"==typeof nB.version&&nB.version.trim()?nB.version:"unknown";function createSystemOneTransport(){const e=b();return createNodeTransport({baseUrl:getApiBaseUrl(),headers:__name(()=>resolveCommandAuthHeaders({sessionId:e,cliVersion:rB}),"headers")})}function readStdinText(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("timeout reading from stdin"))},3e4);r.unref?.(),process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n)}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}function systemOneUsageHint(e){return`Run it headlessly: cmd -p '{"state": "...", "questions": {"<name>": {"type": "noul", "instructions": "..."}}}' -m ${e}`}async function runSystemOnePrint(e){const t=e.now??Date.now,n=t(),r="json"===e.outputFormat,o=__name((o,s,i=`Error: ${o}\n`)=>r?{exitCode:s,stderrText:i,stdoutText:`${safeJsonStringify({type:"result",subtype:"error",model:e.model,durationMs:t()-n,error:o})}\n`}:{exitCode:s,stderrText:i},"fail");let s=e.query;if(void 0===s||""===s.trim()){if(e.stdinIsTTY)return o(`no request given. ${systemOneUsageHint(e.model)}, or pipe the JSON on stdin`,rT.ERROR);try{s=await e.readStdin()}catch(e){return o(`could not read stdin: ${e instanceof Error?e.message:String(e)}`,rT.ERROR)}}const i=parseSystemOneQuery(s);if(!i.ok)return o(i.error,rT.ERROR);const a=await runSystemOne({transport:e.transport,model:e.model,request:i.request,...e.signal?{signal:e.signal}:{}});if(!a.ok&&"bad-response"===a.kind)return o(a.error,rT.SERVER_ERROR);if(!a.ok){const e=classifyPrintModeError(a.error);return o(e.stderrText.replace(/^\s*Error: /,"").trim(),e.exitCode,e.stderrText)}const{response:l}=a;if(!r){const t={model:l.model??e.model,answers:l.answers,usage:l.usage??{}};return{exitCode:rT.SUCCESS,stdoutText:`${JSON.stringify(t,null,2)}\n`}}const c=safeJsonStringify({type:"result",subtype:"success",model:l.model??e.model,answers:l.answers,usage:l.usage??{},durationMs:t()-n});return{exitCode:rT.SUCCESS,stdoutText:`${c}\n`}}async function ensureAuthenticated(){return ensureCommandAuthenticated({runLogin:__name(async()=>{await runLogin()},"runLogin"),getAuthKey:__name(()=>getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env}),"getAuthKey"),onAuthFailed:__name(()=>{console.error(`${gt.cross} Authentication failed. Please try again with: ${getBinaryCommand()} login`)},"onAuthFailed"),onLoginError:__name(e=>{console.error(`${gt.cross} Login failed: ${getErrorMessage(e)}`),console.error(`Please try again with: ${getBinaryCommand()} login`)},"onLoginError"),onCheckError:__name(e=>{console.error("Error checking authentication:",e)},"onCheckError")})}function suggestModel(e){return suggestModelInput({input:e,models:[...getAllModelOptions(),...customModelListOptions()]})}function formatModelList(e={}){return formatModelListText({color:e.color,defaultModel:pr,groups:[...getModelGroupsInOrder(),...customModelListGroups()]})}function formatSystemOneModelNote(){const e=["Decision models (headless only)"],t=isJevFree()?"free through September 24, 2026":"$0.042 per 1M input tokens, everything else free";for(const n of GP)e.push(`${n} typed questions in, probabilities out, ${t} — ${systemOneUsageHint(n)}`);return e.join("\n")}async function printModelList(){await loadCustomProviderModels();const e=Boolean(process.stdout.isTTY)&&void 0===process.env.NO_COLOR;process.stdout.write(`${formatModelList({color:e})}\n`),process.stdout.write(`\n${formatSystemOneModelNote()}\n`);const t=getCustomProviderWarningsSync();t.length>0&&process.stderr.write(`\nproviders.json needs attention — ${1===t.length?"one entry":"some entries"} did not load as written:\n${t.map(e=>` ${e}`).join("\n")}\n`)}async function resolveModelFlagOrExit({model:e}){const t=await resolveSelectableModel(e);if(t){if(t.warning&&process.stderr.write(`Note: ${t.warning}\n`),!t.providerId){const e=customProvidersDeclaring(t.modelId);e.length>0&&process.stderr.write(`Note: "${t.modelId}" routes via Command Code; your providers.json also declares it — use ${e.map(e=>`"${e}/${t.modelId}"`).join(" or ")} to route there instead.\n`)}return{modelId:t.modelId,...void 0!==t.providerId?{providerId:t.providerId}:{}}}const n=suggestModel(e),r=n?` Did you mean "${n}"?`:"";process.stderr.write(`Error: unknown model "${e}".${r}\nRun "${getBinaryCommand()} --list-models" to see all available models\n`),process.exit(1)}__name(createSystemOneTransport,"createSystemOneTransport"),__name(readStdinText,"readStdinText"),__name(systemOneUsageHint,"systemOneUsageHint"),__name(runSystemOnePrint,"runSystemOnePrint"),Gt(),SR(),__name(ensureAuthenticated,"ensureAuthenticated"),Gt(),SR(),__name(suggestModel,"suggestModel"),__name(formatModelList,"formatModelList"),__name(formatSystemOneModelNote,"formatSystemOneModelNote"),__name(printModelList,"printModelList"),__name(resolveModelFlagOrExit,"resolveModelFlagOrExit"),Gt(),SR();var oB=!1;function getAuthKey5(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function setupTelemetry(){initTelemetry()&&(startSession(),registerStartupTask(trackSystemInfo()),trackCliSessionExistsEvent(),registerCleanupHandlers())}function trackSystemInfo(){return trackTelemetryIdentity({client:createApiClient({baseUrl:getApiBaseUrl()}),platform:j.platform(),arch:j.arch()})}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}async function disconnectMcpServers(){try{await Promise.allSettled([disconnectAllMcpServers(),b$()])}catch{}}function handleShutdownSignal(){oB||(oB=!0,abandonPendingCommandSpan(),Promise.allSettled([disconnectMcpServers(),disposeCommandModHost(),shutdownTelemetry()]).finally(()=>{process.exit(0)}))}async function shutdownAndExit(e=0){oB=!0,abandonPendingCommandSpan();try{await Promise.allSettled([disconnectMcpServers(),disposeCommandModHost(),shutdownTelemetry(Un)])}finally{process.exit(e)}}async function trackCliSessionExistsEvent(){try{if(!await getAuthKey5())return;const e=getSessionId();if(!e)return;const t=getPackageJson(import.meta.url).version||"unknown",n=j.platform(),r=j.arch(),o=isTTY()?"interactive":"non-interactive";await trackLifecycleEvent({eventType:"cli_session_exists",metadata:{sessionId:e,cliVersion:t,mode:o,os:`${n}-${r}`},isTelemetryEnabled:isTelemetryEnabled,createClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createClient"),log:dlog})}catch{}}__name(getAuthKey5,"getAuthKey"),__name(setupTelemetry,"setupTelemetry"),__name(trackSystemInfo,"trackSystemInfo"),__name(registerCleanupHandlers,"registerCleanupHandlers"),__name(disconnectMcpServers,"disconnectMcpServers"),__name(handleShutdownSignal,"handleShutdownSignal"),__name(shutdownAndExit,"shutdownAndExit"),__name(trackCliSessionExistsEvent,"trackCliSessionExistsEvent");var sB=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth");async function interactiveModeAction(e,t){if(trackCommand({command:"interactive"}),t.listModels)return void await printModelList();if(t.addDir&&t.addDir.length>0)for(const e of t.addDir)By.addDirectory(e);t.mod&&t.mod.length>0&&setModPathsOverride(t.mod),t.modOption&&t.modOption.length>0&&setModOptionsOverride(t.modOption);const n=(t.skill??[]).map(e=>s(e)),r=!1!==t.skills;if(setSkillLoadOverrides({extraPaths:n,discovery:r}),void 0!==t.worktree&&!1!==t.worktree){const e=void 0!==t.print;e||Boolean(t.trust||t.dangerouslySkipPermissions)||await isCommandProjectSessionInitialized()||(console.error(`Worktree error: this directory isn't trusted yet. Run \`${getInvokedCommandName()}\` here once to trust it, then retry with --worktree.`),process.exit(1));const n=enterWorktreeFromFlag(t.worktree,{quiet:e,track:!e});n.ok||(console.error(`Worktree error: ${n.error}`),process.exit(1)),await initializeCommandProjectSessions()}const o=t.model?resolveSystemOneModel(t.model):void 0;if(o){void 0===t.print&&(process.stderr.write(`Error: ${o} is a decision model (TypeSafe System One): it answers typed questions with probabilities, not chat, so it has no interactive mode. ${systemOneUsageHint(o)}\n`),process.exit(1)),await sB(),trackCommand({command:"print"});const n=await runSystemOnePrint({model:o,query:extractPrintModeQuery({print:t.print,prompt:e}),outputFormat:t.outputFormat,stdinIsTTY:Boolean(process.stdin.isTTY),readStdin:readStdinText,transport:createSystemOneTransport()});n.stderrText&&process.stderr.write(n.stderrText),n.stdoutText&&process.stdout.write(n.stdoutText),await shutdownAndExit(n.exitCode)}const i=t.model?await resolveModelFlagOrExit({model:t.model}):void 0,a=i?.modelId,l=t,c=__name(e=>{process.stderr.write(`${e.message}\n`),e.ok||process.exit(1)},"applySettingResult");for(const e of TN){const t=l[e.key];"string"==typeof t&&c(await e.apply(t,{model:a}))}const d=l.config;if(Array.isArray(d))for(const e of d)"string"==typeof e&&c(await applyConfigSetting(e));if((t.dangerouslySkipPermissions||"bypass"===t.permissionMode)&&isBypassPermissionsDisabled(await loadCommandCodeConfig({runtime:getCommandConfigRuntime()}))&&(process.stderr.write("Bypass permissions are disabled by settings (permissions.disableBypass); continuing with normal permission prompts.\n"),t.dangerouslySkipPermissions=!1,"bypass"===t.permissionMode&&(t.permissionMode=void 0)),void 0!==t.print){const n=extractPrintModeQuery({print:t.print,prompt:e});return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions,plan:t.plan,permissionMode:t.permissionMode,maxTurns:t.maxTurns,verbose:t.verbose,toolsAll:t.toolsAll,toolsEnable:t.toolsEnable,outputFormat:t.outputFormat,model:a,benchmarkOutput:t.benchmarkOutput,name:t.name,resume:t.resume,continue:t.continue,forkSession:t.forkSession,session:"string"==typeof t.session?t.session:void 0,persist:!1!==t.session&&void 0})}a&&setModelOverride(a,i?.providerId),setGoalMaxTurnsOverride(t.maxTurns);const u=parseInteractivePromptArgument(e);await sB();const m=buildInteractiveRuntimeOptions(t),p=resolveInteractiveLaunchConfig({options:t,runtimeOptions:m,initialPrompt:u});setOriginalInvocation({trust:m.trust,dangerouslySkipPermissions:m.dangerouslySkipPermissions,skipOnboarding:m.skipOnboarding,maxTurns:t.maxTurns,skillPaths:n,skillDiscovery:r}),await installKeybindingsFromConfig({runtime:getCommandConfigRuntime()}),await Xj(p),await shutdownAndExit(0)}__name(interactiveModeAction,"interactiveModeAction"),Gt(),SR(),Gt(),SR();var iB={connected:ht.green("✔"),installed:ht.green("✔"),up_to_date:ht.green("✔"),needs_reload:ht.yellow("◌"),failed:ht.red("✖"),not_in_ide:ht.yellow("◌")};function formatSetupResult(e){const{prefix:t,ide:n,suffix:r}=getIDESetupStatusHeadline(e.status,e.ide),o=`${t}${n??""}${r}`;return["",`${iB[e.status]} ${o}`,...(e.details??[]).map(e=>ht.dim(` ${e}`)),""]}__name(formatSetupResult,"formatSetupResult"),globalThis.COMMAND_CODE_CWD=process.cwd();var aB=__name(()=>process.cwd(),"getCwd"),lB=__name(()=>process.argv.slice(2),"getArgs"),cB=__name(()=>{const e=aB(),t=lB(),n=getCliStartupEnvironment(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");function getAuthKey6(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}async function preRun(){cB();const e=resolveCliStartupPlan({args:lB()});if(e.shouldRunIdeSetup){const e=await runIdeSetup({host:oj,moduleUrl:import.meta.url});formatSetupResult(e).forEach(e=>console.log(e)),process.exit("failed"===e.status?1:0)}e.shouldRunAutoUpdate&&runCliStartupPendingUpdates({plan:e,host:hj}),await migrateDeprecatedModel(),await getAuthKey6()&&detectAndTrackFirstInstall({loadUserConfig:loadUserConfig,updateUserConfig:updateUserConfig,trackLifecycleEvent:__name(e=>trackLifecycleEvent({...e,isTelemetryEnabled:isTelemetryEnabled,createClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createClient"),log:dlog}),"trackLifecycleEvent"),getCliVersion:__name(()=>getPackageJson(import.meta.url).version??"unknown","getCliVersion"),log:dlog}).catch(()=>{}),e.shouldRunAutoUpdate&&runCliStartupUpdateCheck({plan:e,host:hj}),scheduleCliStartupIdeAutoInstall({host:oj,moduleUrl:import.meta.url})}__name(getAuthKey6,"getAuthKey"),__name(preRun,"preRun"),Gt(),SR();var dB=Object.fromEntries(Object.entries(Pk).map(([e,t])=>[t,e])),uB=new Set(RD.map(e=>e.id));function formatProviderModule(e){return uB.has(e)?`@byokkit/cmd-provider-${e}`:e}async function buildProviderLoginRows(e={}){const t=e.hasCredential??hasProviderCredential,n=e.modules??(await loadInstalledProviderModules()).modules,r=e.moduleSources??{},o=[];for(const e of n){const n=Boolean(e.auth?.methods.length),s=dB[e.id]??e.id;o.push({provider:e.id,name:e.displayName??e.id,module:r[e.id]??formatProviderModule(e.id),description:e.transport.kind,authenticated:!!n&&await t({provider:s}),canAuthenticate:n,installed:!0})}const s=new Set(o.map(e=>e.provider));for(const e of RD){if(s.has(e.id))continue;if(!1===e.discoverable)continue;const n=dB[e.id]??e.id;o.push({provider:e.id,name:e.displayName,module:e.package,description:"gateway",authenticated:await t({provider:n}),canAuthenticate:!0,installed:!1})}return o}function formatProviderLoginRows(e){const t=getBinaryCommand(),n=[Et.bold("Providers available for login/logout"),""];for(const r of e){const e=r.authenticated?Et.green("logged in"):Et.dim("not logged in"),o=r.installed?"":Et.dim(" (not installed, installs on first login)");n.push(Et.cyan(r.provider)),n.push(` Name: ${r.name}`),n.push(` Module: ${r.module}${o}`),n.push(` Type: ${r.description}`),r.canAuthenticate?(n.push(` Status: ${e}`),n.push(` Login: ${t} login ${r.provider}`),n.push(` Logout: ${t} logout ${r.provider}`),n.push("")):(n.push(` Status: ${Et.dim("no login")}`),n.push(""))}return n.join("\n")}async function providersAction(e){const t=await loadInstalledProviderModules(),n=await buildProviderLoginRows({modules:t.modules,moduleSources:t.sources});if(e.json)console.log(JSON.stringify({providers:n,errors:t.errors}));else if(console.log(formatProviderLoginRows(n)),t.errors.length>0){console.log(Et.yellow("Provider load errors"));for(const e of t.errors)console.log(`${Et.yellow(e.id)}: ${e.error}`)}}__name(formatProviderModule,"formatProviderModule"),__name(buildProviderLoginRows,"buildProviderLoginRows"),__name(formatProviderLoginRows,"formatProviderLoginRows"),__name(providersAction,"providersAction");var mB=new Be("providers").description("List providers available for login/logout").option("--json","Output providers as JSON for automation").action(providersAction);function setupStreamInput(e){const t=__name(t=>{3===t[0]&&e.onCancel(),4===t[0]&&e.onDetach()},"onData"),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 rgb(e){const t=e.replace("#","");return[Number.parseInt(t.slice(0,2),16),Number.parseInt(t.slice(2,4),16),Number.parseInt(t.slice(4,6),16)]}function fg(e){const[t,n,r]=rgb(e);return`[38;2;${t};${n};${r}m`}function bg(e){const[t,n,r]=rgb(e);return`[48;2;${t};${n};${r}m`}Gt(),Gt(),SR(),Gt(),SR(),Gt(),__name(setupStreamInput,"setupStreamInput"),Gt(),__name(rgb,"rgb"),__name(fg,"fg"),__name(bg,"bg");var pB="";function paintUserMessage(e){return process.stderr.isTTY?`${bg(NR.BG)}${fg(NR.POINTER)}${gt.pointer} ${fg(NR.FG)}${e} ${pB}`:`${gt.pointer} ${e}`}__name(paintUserMessage,"paintUserMessage");var gB="\r",hB=__name(()=>process.stderr.isTTY?gB:"","clearLine");function shimmer(e,t){const n=[...e],r=t%(n.length+10);return n.map((e,t)=>{const n=t-(r-5);return`${fg(n>=0&&n<HR.length?HR[n]??GR:GR)}${e}`}).join("").concat(pB)}function sessionHintLines(e){return[`${Et.yellow("[Ctrl+C]")} ${Et.dim("stop")} ${Et.yellow("[Ctrl+D]")} ${Et.dim("detach")}`,`${Et.dim("Session:")} ${Et.gray(e)}`]}function createReplayDivider(e){let t=null,n=!1;const r=__name(()=>{n||(n=!0,e.onReplayDivider())},"arm");return{onEvent:__name(()=>{n||(t&&clearTimeout(t),t=setTimeout(r,400))},"onEvent"),stop:__name(()=>{t&&clearTimeout(t),t=null},"stop")}}function createBottomLine(){let e=null,t="",n=0,r=null;const o=process.stderr,s=!0===o.isTTY,i=__name(()=>{if(!s)return;if(null===e)return void o.write(`${gB}${Et.cyan(gt.pointer)} ${t}`);const r=t?` ${Et.dim(gt.pointer)} ${t}`:"";o.write(`${gB}${shimmer(`${e}…`,n)}${r}`),n+=1},"render"),a=__name(()=>{!r&&s&&(r=setInterval(i,80))},"tick"),l=__name(()=>{r&&(clearInterval(r),r=null)},"still");return{setStatus(t){s||t===e||o.write(`${Et.dim(t)}\n`),e=t,a(),i()},showPrompt(){l(),e=null,i()},setDraft(e){t=e,i()},draft:()=>t,print(e){o.write(`${hB()}${e}\n`),i()},text(e,t){t&&(l(),o.write(hB())),process.stdout.write(e)},resume(){null!==e&&a(),i()},clear(){l(),o.write(hB())}}}function createView(e){const{bottom:t}=e;let n=!1;const r=__name(()=>{n&&(process.stdout.write("\n"),n=!1,t.resume())},"endText");return{onStatus:__name(e=>{if("setup_step"!==e.type&&"replayed_setup"!==e.type)if("running"!==e.type){if(r(),"note"===e.type)return t.print(Et.yellow(`${e.message}.`)),void t.setStatus("Wrapping up");"completed"===e.type&&e.prUrl&&t.print(`${Et.green("PR:")} ${Et.cyan(e.prUrl)}`),"failed"===e.type&&t.print(`${Et.red(`${gt.cross} Failed:`)} ${e.message}`),"timed_out"===e.type&&t.print(Et.red(`${gt.cross} Timed out`)),"cancelled"===e.type&&t.print(Et.yellow("Cancelled.")),"expired"===e.type&&t.print(Et.red(`${gt.cross} Session expired: its sandbox was removed after 14 idle days.`))}else t.setStatus("Working");else t.setStatus(e.message??"Setting up")},"onStatus"),onAgentEvent:__name(e=>{const o=e.type;if("text_delta"===o&&"string"==typeof e.delta)return t.text(e.delta,!n),void(n=!0);if("message_end"===o&&r(),"tool_running"===o&&"string"==typeof e.toolName){r();const n="string"==typeof e.description?e.description:"";t.print(Et.dim(`${gt.pointerSmall} ${e.toolName} ${n}`.trim())),t.setStatus("Working")}},"onAgentEvent"),onError:__name(e=>{r(),t.print(Et.red(e))},"onError"),onTerminal:__name(e=>{r(),e.error&&t.print(Et.red(e.error)),e.prUrl&&t.print(`${Et.green("PR:")} ${Et.cyan(e.prUrl)}`)},"onTerminal"),onDisconnected:__name(()=>{r(),e.onDisconnected()},"onDisconnected"),onReplayDivider:__name(()=>{r(),t.print(Et.dim("· replayed history above, live from here ·"))},"onReplayDivider")}}function sandboxHint(e){return`${getBinaryCommand()} --experimental sandbox --headless --watch ${e}`}async function authHeaders(){const e=getCommandConfigRuntime(),t=await getCommandAuthKey({runtime:e,path:getAuthFile(),env:e.env()});if(!t)throw new Error(`Not authenticated. Run: ${getBinaryCommand()} login`);return{authorization:`Bearer ${t}`}}function printTaskSummary(e){console.error(`${Et.dim("Status:")} ${e.status}`),e.prUrl&&console.error(`PR: ${Et.cyan(e.prUrl)}`),e.error&&console.error(Et.red(e.error))}async function attachToSession(e){const{client:t,sessionId:n}=e,r=await t.status({sessionId:n});if(isTerminalSandboxTaskStatus(r.status))return e.view?e.view.onTerminal(r):printTaskSummary(r),r.status;const o=e.view?null:createBottomLine(),s=e.view??createView({bottom:o??createBottomLine(),onDisconnected:__name(()=>{o?.print(`${Et.yellow("Disconnected.")} Session still running. Reattach: ${Et.cyan(sandboxHint(n))}`)},"onDisconnected")});if(o)for(const e of sessionHintLines(n))o.print(e);const i=__name(e=>s.onStatus(e),"onStatus");i({type:"setup_step",message:e.initialStatus??"Provisioning sandbox"});const a=e.isReattach&&!e.view?createReplayDivider(s):null;let l=!1;const c=streamSandboxTask({sessionId:n,isReattach:e.isReattach??!1,...e.cursor?{lastEventId:e.cursor.lastEventId}:{},getBaseUrl:getApiBaseUrl,getAuthHeaders:authHeaders,requestCancel:__name(async()=>(await t.cancel({sessionId:n})).status,"requestCancel"),callbacks:{onStatus:__name(({action:e})=>i(e),"onStatus"),onAgentEvent:__name(({event:e})=>{a?.onEvent(),s.onAgentEvent(e)},"onAgentEvent"),onErrorEvent:__name(({message:e})=>s.onError(e),"onErrorEvent"),onCancelled:__name(()=>i({type:"cancelled"}),"onCancelled"),onDisconnected:__name(()=>{l=!0},"onDisconnected"),onDetached:__name(()=>{console.error(`\n${Et.yellow("Detached.")} Reattach: ${Et.cyan(sandboxHint(n))}`)},"onDetached")}}),d=e.controls?bindControls({controls:e.controls,handle:c}):setupStreamInput({onCancel:c.cancel,onDetach:c.detach});process.once("SIGTERM",c.detach);try{const e=await c.done;return null===e&&l?reportAfterDisconnect({client:t,sessionId:n,view:s}):e}finally{e.cursor&&(e.cursor.lastEventId=c.getLastEventId()),a?.stop(),o?.clear(),d(),process.removeListener("SIGTERM",c.detach)}}function bindControls(e){return e.controls.set({cancel:e.handle.cancel,detach:e.handle.detach}),()=>e.controls.set(null)}async function reportAfterDisconnect(e){const{client:t,sessionId:n,view:r}=e,o=await t.status({sessionId:n}).catch(()=>null);return o&&isTerminalSandboxTaskStatus(o.status)?(r.onTerminal(o),o.status):(r.onDisconnected(),null)}function runGit2(e){return S(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}function warnAboutPromptTruncation(e){const t=e.trim().length;t<=Tx||console.error(Et.yellow(`Warning: prompt is ${t} characters; only the first ${Tx} are sent.`))}function warnAboutLocalOnlyWork(e){e||console.error(Et.yellow("Warning: local changes are not included (the sandbox works from the repo on GitHub)."))}function runSandboxStartPreflight(e){if(e.baseBranch&&!isValidSandboxBranchName(e.baseBranch))throw new Error("Invalid --base branch name.");warnAboutPromptTruncation(e.prompt);const t=validateSandboxGitRepo({run:__name(({command:e})=>runGit2(e),"run")});return warnAboutLocalOnlyWork(t.isClean),{repoUrl:t.repoUrl}}function stillStarting(e){return e instanceof gn&&409===e.status}async function waitForHistory(e){const t=Date.now()+24e4;for(;;)try{return(await e.sandbox.history({sessionId:e.sessionId})).turns}catch(e){if(!stillStarting(e)||Date.now()>t)throw e;await new Promise(e=>setTimeout(e,2e3))}}function printHistory(e){const{bottom:t,turns:n}=e;for(const e of n){t.print(paintUserMessage(e.prompt));for(const n of e.reply.split("\n"))t.print(n);t.print("")}}async function resumeWithHistory(e){const{sandbox:t,sessionId:n,bottom:r}=e;r.setStatus("Resuming sandbox"),await t.continueTask({sessionId:n,prompt:"",...e.mode?{mode:e.mode}:{}});try{printHistory({bottom:r,turns:await waitForHistory({sandbox:t,sessionId:n})})}catch{r.print(Et.dim("Earlier turns could not be read from the sandbox."))}}function startProgress(e){const t=createBottomLine();return t.setStatus(e),()=>t.clear()}function createSandboxTransport(){const e=createApiClient({baseUrl:getApiBaseUrl(),timeout:3e5});return{post:__name(t=>e.post({endpoint:t.route,body:t.body}),"post"),get:__name(t=>e.get({endpoint:t.route}),"get")}}__name(shimmer,"shimmer"),__name(sessionHintLines,"sessionHintLines"),__name(createReplayDivider,"createReplayDivider"),__name(createBottomLine,"createBottomLine"),__name(createView,"createView"),__name(sandboxHint,"sandboxHint"),__name(authHeaders,"authHeaders"),__name(printTaskSummary,"printTaskSummary"),__name(attachToSession,"attachToSession"),__name(bindControls,"bindControls"),__name(reportAfterDisconnect,"reportAfterDisconnect"),Gt(),SR(),__name(runGit2,"runGit"),__name(warnAboutPromptTruncation,"warnAboutPromptTruncation"),__name(warnAboutLocalOnlyWork,"warnAboutLocalOnlyWork"),__name(runSandboxStartPreflight,"runSandboxStartPreflight"),Gt(),SR(),__name(stillStarting,"stillStarting"),__name(waitForHistory,"waitForHistory"),__name(printHistory,"printHistory"),__name(resumeWithHistory,"resumeWithHistory"),Gt(),SR(),Gt(),__name(startProgress,"startProgress"),Gt(),SR(),__name(createSandboxTransport,"createSandboxTransport");var fB=["failed","timed_out","expired"];function assertSessionId(e){oD.test(e)||(console.error(Et.red(`Invalid session id: ${e}`)),console.error(Et.dim(`Find it with: ${getBinaryCommand()} --experimental sandbox list`)),process.exit(1))}function client(){return createSandboxClient({transport:createSandboxTransport()})}function exitForStatus(e){process.exit(e&&fB.includes(e)?1:0)}function reportStartFailure(e){const t=classifySandboxStartFailure({error:e.error});if("unauthorized"===t.kind&&(console.error(Et.red(`Authentication failed. Try: ${getBinaryCommand()} login`)),process.exit(1)),"github_app_not_installed"===t.kind){const t=e.repoUrl?.replace("https://github.com/","")??"this repo";console.error(`${Et.red("✖")} Command Code GitHub App is not installed on ${t}.`),console.error(` Install it and select ${t}, then run this command again:`),console.error(` ${Et.cyan("https://github.com/apps/command-code-ai/installations/new")}`),process.exit(1)}console.error(Et.red(t.message)),process.exit(1)}async function startSandboxTask(e){await ensureAuthenticated()||process.exit(1);const t=runSandboxStartPreflight({prompt:e.prompt,...e.baseBranch?{baseBranch:e.baseBranch}:{}}),n=client(),r=startProgress("Creating sandbox");let o;try{o=(await n.start({repoUrl:t.repoUrl,...e.baseBranch?{baseBranch:e.baseBranch}:{},prompt:truncateSandboxPrompt(e.prompt),mode:e.mode})).sessionId,r()}catch(e){r(),reportStartFailure({error:e,repoUrl:t.repoUrl})}"headless"===e.mode&&printStarted(o),exitForStatus(await attachToSession({client:n,sessionId:o}))}function printStarted(e){console.log(e),console.error(Et.dim(`Watch: ${sandboxHint(e)}`)),console.error(Et.dim(`Status: ${getBinaryCommand()} --experimental sandbox status ${e}`)),process.exit(0)}async function attachSandboxTask(e){assertSessionId(e);const t=client(),n=await t.status({sessionId:e});if(isTerminalSandboxTaskStatus(n.status)){if(yB.includes(n.status)){const n=createBottomLine();for(const t of sessionHintLines(e))n.print(t);try{await resumeWithHistory({sandbox:t,sessionId:e,bottom:n})}finally{n.clear()}}printTaskSummary(n),exitForStatus(n.status)}exitForStatus(await attachToSession({client:t,sessionId:e,isReattach:!0}))}__name(assertSessionId,"assertSessionId"),__name(client,"client"),__name(exitForStatus,"exitForStatus"),__name(reportStartFailure,"reportStartFailure"),__name(startSandboxTask,"startSandboxTask"),__name(printStarted,"printStarted"),__name(attachSandboxTask,"attachSandboxTask");var yB=["completed","failed","cancelled","timed_out"];async function statusSandboxTask(e){assertSessionId(e),printTaskSummary(await client().status({sessionId:e}))}async function stopSandboxTask(e){assertSessionId(e);const{status:t}=await client().cancel({sessionId:e});"cancelled"===t?console.error(Et.yellow("Session stopped.")):console.error(Et.yellow(`Session already ${t.replace("_"," ")}.`))}async function listSandboxTasks(){const{sessions:e}=await client().list();if(0!==e.length){console.log(Et.dim(`${"SESSION".padEnd(38)}${"STATUS".padEnd(12)}${"AGE".padEnd(12)}REPO`));for(const t of e){const e=t.repoUrl.replace(/^https:\/\/github\.com\//,""),n=formatRelativeTimeShort({timestamp:t.createdAt});console.log(`${t.sessionId.padEnd(38)}${t.status.padEnd(12)}${n.padEnd(12)}${Et.dim(e)}`)}}else console.error("No sandbox sessions yet.")}async function continueSandboxTask(e){assertSessionId(e.sessionId),await ensureAuthenticated()||process.exit(1),warnAboutPromptTruncation(e.prompt);const t=client(),n=startProgress("Resuming sandbox");try{await t.continueTask({sessionId:e.sessionId,prompt:truncateSandboxPrompt(e.prompt)})}catch(e){n(),reportStartFailure({error:e})}n(),"headless"===e.mode&&printStarted(e.sessionId),exitForStatus(await attachToSession({client:t,sessionId:e.sessionId}))}__name(statusSandboxTask,"statusSandboxTask"),__name(stopSandboxTask,"stopSandboxTask"),__name(listSandboxTasks,"listSandboxTasks"),__name(continueSandboxTask,"continueSandboxTask");var SB=["expired"];function createChatInput(e){const{bottom:t}=e,n=[...e.queued??[]];let r=null,o=null,s=!1;const i=__name(e=>{if(r){const t=r;return r=null,void t(e)}n.push(e),t.print(Et.dim(`queued ${gt.pointer} ${e}`))},"deliver"),a=__name(()=>{if(s=!0,!r)return;const e=r;r=null,e(null)},"leave"),l=__name(e=>{const r=e[0];if(void 0!==r)if(3!==r){if(4===r)return n.length=0,o?.detach(),void a();if(27!==r){if(13===r||10===r){const e=t.draft().trim();return t.setDraft(""),void(e&&(process.stderr.write(gB),i(e)))}127!==r&&8!==r?r<32||t.setDraft(t.draft()+e.toString("utf8")):t.setDraft(t.draft().slice(0,-1))}}else o?o.cancel():a()},"onKeys"),c=process.stdin.isTTY;let d=null;return c?(process.stdin.setRawMode(!0),process.once("exit",()=>{process.stdin.isTTY&&process.stdin.setRawMode(!1)}),process.stdin.resume(),process.stdin.on("data",l),process.on("SIGINT",()=>{})):(d=Rt.createInterface({input:process.stdin}),d.on("line",e=>{e.trim()&&i(e.trim())}),d.on("close",a),process.on("SIGINT",()=>o?o.cancel():a())),{next:__name(()=>new Promise(e=>{const t=n.shift();return void 0!==t?e(t):s?e(null):void(r=e)}),"next"),controls:{set:__name(e=>{o=e},"set")},close:__name(()=>{c&&(process.stdin.removeListener("data",l),process.stdin.setRawMode(!1),process.stdin.pause()),d?.close()},"close")}}async function followRun(e){const{sandbox:t,sessionId:n,controls:r,bottom:o}=e;let s=!1;const i=createView({bottom:o,onDisconnected:__name(()=>{s=!0},"onDisconnected")}),a={lastEventId:0};for(let e=0;e<=20;e++){s=!1;const o=await attachToSession({client:t,sessionId:n,controls:r,view:i,cursor:a,isReattach:e>0,initialStatus:e>0?"Reconnecting":"Working"});if(null!==o||!s)return o;await new Promise(e=>setTimeout(e,1500))}return o.print(Et.yellow("Lost the stream. The run continues in the sandbox.")),null}function describeError(e){const t=e?.error;return t&&"string"==typeof t.message?t.message:e instanceof Error?e.message:String(e)}async function continueWithRetry(e){const{sandbox:t,sessionId:n,message:r}=e,o=truncateSandboxPrompt(r);try{await t.continueTask({sessionId:n,prompt:o,mode:"chat"})}catch(e){if(!/shutting down/i.test(describeError(e)))throw e;await new Promise(e=>setTimeout(e,3e3)),await t.continueTask({sessionId:n,prompt:o,mode:"chat"})}}async function chatSandboxTask(e){await ensureAuthenticated()||process.exit(1);const t=client(),n=e.sessionId?await t.status({sessionId:e.sessionId}):null,r=n?{repoUrl:n.repoUrl}:runSandboxStartPreflight({prompt:"",...e.baseBranch?{baseBranch:e.baseBranch}:{}}),o=createBottomLine(),s=createChatInput({bottom:o,...e.firstMessage?{queued:[e.firstMessage]}:{}});let i=n?.sessionId??null;if(process.stdin.isTTY){const t=r.repoUrl.replace("https://github.com/",""),n=e.baseBranch?` ${Et.dim(e.baseBranch)}`:"";console.error(`${Et.bold("Sandbox")} ${Et.dim(t)}${n}`)}if(!i){o.setStatus("Provisioning sandbox");try{i=(await t.start({repoUrl:r.repoUrl,...e.baseBranch?{baseBranch:e.baseBranch}:{},prompt:"",mode:"chat"})).sessionId}catch(e){o.clear(),s.close(),reportStartFailure({error:e,repoUrl:r.repoUrl})}}for(const e of sessionHintLines(i))o.print(e);if(n&&SB.includes(n.status)&&(o.clear(),s.close(),printTaskSummary(n),process.exit(1)),n&&i)if(isTerminalSandboxTaskStatus(n.status))try{await resumeWithHistory({sandbox:t,sessionId:i,bottom:o,mode:"chat"})}catch(e){o.print(Et.red(describeError(e)))}else o.setStatus("Working"),await followRun({sandbox:t,sessionId:i,controls:s.controls,bottom:o});let a=null;for(;;){o.showPrompt();const e=await s.next();if(null===e)break;o.print(paintUserMessage(e)),o.setStatus("Working");try{await continueWithRetry({sandbox:t,sessionId:i,message:e})}catch(e){o.print(Et.red(describeError(e)));continue}const n=await followRun({sandbox:t,sessionId:i,controls:s.controls,bottom:o});if(a=n,n&&SB.includes(n))break;if(n&&!isTerminalSandboxTaskStatus(n))break}o.clear(),s.close(),i&&console.error(Et.dim(`Resume: ${getBinaryCommand()} --experimental sandbox ${i}`)),process.exit(a&&wB.includes(a)?1:0)}__name(createChatInput,"createChatInput"),__name(followRun,"followRun"),__name(describeError,"describeError"),__name(continueWithRetry,"continueWithRetry"),__name(chatSandboxTask,"chatSandboxTask");var wB=["failed","timed_out","expired"];function run3(e){e().catch(e=>{const t=e instanceof Error?e.message:"Unknown error";console.error(Et.red(t)),process.exit(1)})}function createSandboxCommand(){const e=new Be("sandbox").description("Work in a cloud sandbox: a chat by default, or one headless task").argument("[promptOrId]","First message (chat) or task (headless); a session id resumes that session").option("--headless","Run one task autonomously and print the session id").option("--watch","Stream a headless run, or watch a session by id (implies --headless)").option("--base <branch>","Branch the work branch out from (default: the repo default branch)").enablePositionalOptions().action((e,t)=>{const n=e?.trim()??"",r=oD.test(n),o=t.base?{baseBranch:t.base}:{};return t.headless||t.watch?r?run3(()=>attachSandboxTask(n)):(n||(console.error(Et.yellow('Usage: sandbox --headless [--watch] "task" | sandbox --headless --watch <id>')),process.exit(1)),run3(()=>startSandboxTask({prompt:n,mode:t.watch?"stream":"headless",...o}))):run3(r?()=>chatSandboxTask({sessionId:n}):()=>chatSandboxTask({...o,...n?{firstMessage:n}:{}}))});return e.command("list").description("List your sandbox sessions").action(()=>run3(listSandboxTasks)),e.command("status").description("Show a session summary").argument("<sessionId>").action(e=>run3(()=>statusSandboxTask(e))),e.command("stop").description("Stop a running session").argument("<sessionId>").action(e=>run3(()=>stopSandboxTask(e))),e.command("continue").description("Continue a finished session with a follow-up task").argument("<sessionId>").argument("<prompt...>").option("--watch","Stream the session after continuing it").action((e,t,n,r)=>{const{watch:o}=r.optsWithGlobals();return run3(()=>continueSandboxTask({sessionId:e,prompt:t.join(" "),mode:o?"stream":"headless"}))}),e}__name(run3,"run"),__name(createSandboxCommand,"createSandboxCommand"),Gt(),Gt(),SR();var vB=[`${Et.dim("Usage:")}`,` ${Et.cyan(`${getBinaryCommand()} skills add`)} ${Et.white("<owner/repo>")}`,"",`${Et.dim("Examples:")}`,` ${Et.cyan(`${getBinaryCommand()} skills add`)} ${Et.white("acme/my-skills")} ${Et.dim("# single-skill repo")}`,` ${Et.cyan(`${getBinaryCommand()} skills add`)} ${Et.white("acme/skills/path/to/skill")} ${Et.dim("# specific path in repo")}`,` ${Et.cyan(`${getBinaryCommand()} skills add`)} ${Et.white("acme/multi-skills -s my-skill")} ${Et.dim("# pick one from multi-skill repo")}`,` ${Et.cyan(`${getBinaryCommand()} skills add`)} ${Et.white("acme/repo@branch")} ${Et.dim("# specific branch")}`,` ${Et.cyan(`${getBinaryCommand()} skills add`)} ${Et.white("acme/repo --global")} ${Et.dim("# install to ~/.commandcode/skills/")}`],kB=__name((e,t)=>`${Et.green(gt.tick)} Installed ${Et.cyan(e)} ${Et.dim(`${gt.arrowRight} ${t}/`)}`,"formatInstalled"),CB=__name(e=>`${Et.red(gt.cross)} ${e}`,"formatError");async function cleanupAndExit(e,t){await removeSkillInstallTempDir(e),process.exit(t)}function validateRepoFormat(e){const t=validateSkillInstallRepoInput(e);t.valid||(console.error(CB(t.message)),console.log(""),t.message.startsWith("Invalid repository")&&(console.log(`Expected format: ${Et.cyan("owner/repo")} or ${Et.cyan("owner/repo/path")}`),console.log("")),vB.forEach(e=>console.log(e)),process.exit(1))}async function addAction2(e,t){const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"~/.commandcode/skills":".commandcode/skills";let o;validateRepoFormat(e);const s=Mt({text:`Fetching ${Et.cyan(e)}...`,color:"cyan"});try{let i=[];s.start();const a=await discoverCommandSkills(e,{keepTempDir:!0}),{skills:l,tempDir:c}=a;o=c,s.stop();const d=planSkillInstallSelection({skills:l,requestedSkillName:t.skill,interactive:n,repoInput:e});if("empty"===d.kind&&(console.error(CB(`No skills found in ${Et.cyan(e)}`)),console.log(Et.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(o,1)),"missing-requested-skill"===d.kind)return console.error(CB(`Skill "${d.requestedSkillName}" not found in ${Et.cyan(d.repoInput)}`)),console.log(""),console.log(Et.dim("Available skills:")),d.availableSkillNames.forEach(e=>console.log(` ${Et.cyan(e)}`)),void await cleanupAndExit(o,1);if("prompt"===d.kind){const t=await Ke({message:`Select skills to install from ${e}`,options:[...d.options],required:!0});"symbol"==typeof t&&(console.log(Et.dim("Cancelled")),await cleanupAndExit(o,0)),i=resolvePromptedSkillSelection({skills:l,selectedNames:t})}let u;"selected"===d.kind&&(i=d.skills);const m=await installSelectedCommandSkills({repoInput:e,skills:i,global:t.global,force:t.force,cachedTempDir:o,onSkillStart:__name(e=>{u=Mt({text:`Installing ${Et.cyan(e.name)}...`,color:"cyan"}),u.start()},"onSkillStart"),onSkillInstalled:__name(e=>{u?.stop(),console.log(kB(e.name,r))},"onSkillInstalled"),onSkillFailed:__name(({skillName:e,message:t})=>{u?.stop(),console.error(CB(`Failed to install "${e}"`)),console.log(Et.dim(` ${t}`))},"onSkillFailed")});await cleanupAndExit(o,m.exitCode)}catch(e){s.stop();const t=e instanceof Error?e.message:String(e);console.error(CB(t)),await cleanupAndExit(o,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction2,"addAction");var bB=new Be("add").description("Install a skill from a GitHub repository").argument("<repo>","GitHub repository (owner/repo or owner/repo/path)").option("-g, --global","Install to global skills (~/.commandcode/skills/)").option("-f, --force","Overwrite if skill already exists").option("-s, --skill <name>","Specific skill name to install from repo").addHelpText("after",`\n${vB.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(CB("No repository specified.")),console.log(""),vB.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction2);Gt(),SR();var EB=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${Et.cyan(e)} ${Et.dim(`· ${n}`)}`},"formatSkillLine"),TB=__name((e,t)=>`${Et.bold(Et.white(e))} ${Et.dim(`(${t})`)}`,"formatSectionHeader"),PB=__name(e=>{if(0!==e.warningCount){console.log(""),console.log(`${Et.bold(Et.yellow("Skipped"))} ${Et.dim(`(${e.warningCount})`)}`);for(const t of e.warningGroups){console.log(""),console.log(` ${Et.bold(t.category)} ${Et.dim(`(${t.items.length})`)}`);for(const e of t.items)console.log(` ${Et.bold(skillIdentifier(e.path))}`),console.log(` ${Et.dim(e.reason)}`)}}},"printWarnings"),MB=__name(e=>{const t=["",Et.dim("No skills installed."),"",Et.dim("Looking in:")];for(const n of e.lookupPaths)t.push(Et.dim(` ${n.path} ${Et.white(`(${n.label})`)}`));return t.push("",`Install a skill: ${Et.cyan(e.installCommand)} ${Et.dim(e.installPlaceholder)}`,""),t},"formatEmptyHint"),xB=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),IB=__name(e=>{e&&(console.log(""),console.log(Et.dim(e.replace("--debug",Et.cyan("--debug")))))},"printDebugHint");async function listAction2(){const e="true"===process.env.DEBUG;try{const{global:t,project:n,bundled:r,warnings:o}=await listCommandSkills(),s=planSkillListView({global:t,project:n,bundled:r,warnings:o,showWarnings:e});if(s.empty){const t=await buildSkillListEmptyHint({runtime:getCommandSkillRuntime(),binCommand:`${getBinaryCommand()}`});xB(MB(t));for(const e of s.sections)console.log(TB(e.title,e.skills.length)),e.skills.forEach(e=>{console.log(EB(e.name,e.description))}),console.log("");e&&(PB({warningCount:s.warningCount,warningGroups:s.warningGroups}),s.warningCount>0&&console.log("")),e||(IB(s.debugHint),console.log("")),process.exit(0)}console.log(""),console.log(heading({text:"Skills",sub:Et.dim(`${s.userInstalledTotal} installed`)}));for(const e of s.sections)console.log(""),console.log(TB(e.title,e.skills.length)),e.skills.forEach(e=>{console.log(EB(e.name,e.description))});e&&PB({warningCount:s.warningCount,warningGroups:s.warningGroups}),e||IB(s.debugHint),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${Et.red(gt.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction2,"listAction");var AB=new Be("list").description("List all installed skills. Run with -d/--debug to also see why any skills were skipped.").action(listAction2);Gt(),SR();var RB=__name((e,t)=>`${Et.green(gt.tick)} Removed ${Et.cyan(e)} from ${t} skills`,"formatRemoved"),LB=__name(e=>`${Et.red(gt.cross)} ${e}`,"formatError"),OB=__name((e,t)=>{let n=e;for(const e of t)n=n.replace(e,Et.cyan(e));return Et.dim(n)},"formatHint");function validateSkillNameEarly(e){const t=validateSkillRemoveName(e);return t.valid?null:t.message}async function removeAction2(e,t){try{const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"global":"project",o=validateSkillNameEarly(e);if(o&&(console.error(LB(o)),console.log(OB(getSkillListCommandHint({binCommand:`${getBinaryCommand()}`}),[`${getBinaryCommand()} skills list`])),process.exit(1)),!t.yes&&n){const t=await qe({message:`Remove ${Et.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(Et.dim("Cancelled")),process.exit(0))}await removeCommandSkill({skillName:e,global:t.global}),console.log(RB(e,r)),process.exit(0)}catch(n){const r=n instanceof Error?n.message:"Failed to remove skill",o=planSkillRemoveError({skillName:e,global:t.global,errorMessage:r,binCommand:`${getBinaryCommand()}`});if(console.error(LB(o.message)),"not-found"===o.kind)for(const t of o.hints)console.log(OB(t,[`${getBinaryCommand()} skills remove ${e} --global`,`${getBinaryCommand()} skills list`]));process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction2,"removeAction");var DB=new Be("remove").description("Remove an installed skill").argument("<skill-name>","Name of the skill to remove").option("-g, --global","Remove from global skills (~/.commandcode/skills/)").option("-y, --yes","Skip confirmation prompt").action(removeAction2),$B=new Be("skills").description("Manage skills from GitHub repositories").addCommand(bB).addCommand(DB).addCommand(AB);Gt(),SR(),Gt(),SR(),Gt(),Gt(),SR();var NB=[gt.bullet,gt.squareSmallFilled,gt.lozenge,gt.star,gt.triangleRight,gt.triangleUp];Gt(),SR(),Gt();var _B=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return _B.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}}__name(shouldIgnoreChunk,"shouldIgnoreChunk"),__name(chunkToString,"chunkToString"),__name(withFilteredStderrNoise,"withFilteredStderrNoise"),Gt(),SR(),Gt(),Gt();var FB=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),o=e.learningCount>0;return st.createElement(Qe,{flexDirection:"column",marginLeft:3},st.createElement(Qe,{marginBottom:1,flexDirection:"row"},st.createElement(Xe,{color:ER.DIM},yL),st.createElement(Qe,{marginLeft:2},st.createElement(Xe,{color:PR.TEXT},o?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),st.createElement(Qe,{flexDirection:"column",marginLeft:1},st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},gt.pointerSmall," Taste stored in"," "),st.createElement(cL,{url:fileUrl(e.storage),text:r||".commandcode/taste/taste.md",color:ER.CYAN})),st.createElement(Qe,null,st.createElement(Xe,{color:ER.DIM},gt.pointerSmall," Share your coding taste:"," ",st.createElement(Xe,{color:ER.CYAN},"npx taste push --all")))),st.createElement(Qe,{marginTop:1,marginLeft:1},st.createElement(Xe,{color:ER.DIM},o?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Gt();var UB=__name(({message:e})=>st.createElement(O$,null,e),"RepoLearnErrorPanel");Gt();var jB=__name(({done:e,error:t})=>t?st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Press ",st.createElement(gO,null,"Esc")," to exit")):e?st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Press ",st.createElement(gO,null,"Enter")," to continue")):st.createElement(Qe,{marginTop:1},st.createElement(pO,null,"Esc to cancel")),"RepoLearnFooter");Gt(),SR();var BB=__name(({insights:e,insightCount:t})=>0===e.length?null:st.createElement(Qe,{flexDirection:"column",marginTop:1,marginLeft:4},st.createElement(Xe,{color:ER.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>st.createElement(Xe,{key:`${t}-${e}`,color:ER.DIM},NB[t%NB.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Gt(),SR();var WB=__name(({status:e})=>"active"===e?st.createElement(Qe,null,st.createElement(Xe,{color:ER.YELLOW},st.createElement(kt,{type:"dots"})),st.createElement(Xe,null," ")):"complete"===e?st.createElement(Xe,{color:AR.BG},gt.square," "):st.createElement(Xe,{color:ER.DIM},gt.circle," "),"StepStatusIndicator");function getStepLabelColor(e,t){return"complete"===e?ER.WHITE:t?ER.YELLOW:ER.DIM}__name(getStepLabelColor,"getStepLabelColor");var HB=__name(({steps:e,currentMessage:t})=>st.createElement(Qe,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return st.createElement(Qe,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},st.createElement(Qe,null,st.createElement(Qe,{marginRight:1},st.createElement(WB,{status:e.status})),st.createElement(Xe,{bold:n,color:getStepLabelColor(e.status,n)},e.label)),n&&t?st.createElement(Qe,{marginLeft:3},st.createElement(Xe,{color:ER.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Gt();var GB=__name(({isComplete:e,hasError:t})=>t?st.createElement(Xe,{color:ER.DIM},"learning interrupted"):e?st.createElement(Xe,{color:PR.TEXT},"learned your coding taste"):st.createElement(mL,null),"TastePillStatus"),VB=__name(({isComplete:e,hasError:t})=>st.createElement(Qe,{flexDirection:"column",marginTop:1,marginBottom:0},st.createElement(kL,null),st.createElement(Qe,{marginTop:0},st.createElement(Xe,{color:ER.DIM},yL),st.createElement(Qe,{marginLeft:2},st.createElement(GB,{isComplete:e,hasError:t})))),"RepoLearnTastePill");Gt();var zB=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=dt(()=>tO(n),[n]);return st.createElement(Qe,{flexDirection:"column"},st.createElement(Qe,{flexDirection:"column",marginBottom:1},st.createElement(qR,null,r.trimEnd())),e?st.createElement(Xe,{color:ER.WHITE},e):st.createElement(st.Fragment,null,st.createElement(Xe,{color:ER.WHITE},"Learning your coding taste from"," ",st.createElement(Xe,{bold:!0,color:ER.CYAN},t??"repository")),st.createElement(Xe,{color:ER.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function useRepoLearnState(e){const t=e??TI,[n,r]=at(()=>createRepoLearnProjection({stepOrder:t})),o=lt(null),[s,i]=at(null),a=ut(()=>{o.current=Date.now()},[]),l=ut(e=>{r(t=>({...t,showLogin:e}))},[]);return ct(()=>{const e=__name(()=>{r(createRepoLearnProjection({stepOrder:t})),o.current=null,i(null)},"handleReset"),n=__name(e=>{r(t=>reduceRepoLearnEvent({state:t,event:e}))},"handleEvent"),s=__name(()=>{r(e=>completeRepoLearnProjection({state:e})),o.current&&i(Math.round((Date.now()-o.current)/1e3))},"handleComplete");return ip.on("reset",e),ip.on("new-event",n),ip.on("learning-complete",s),()=>{ip.off("reset",e),ip.off("new-event",n),ip.off("learning-complete",s)}},[t]),{steps:n.steps,currentMessage:n.currentMessage,insights:n.insights,insightCount:n.insightCount,summary:n.summary,done:n.done,error:n.error,showLogin:n.showLogin,setShowLogin:l,elapsedSeconds:s,markStarted:a}}function StatusPanel({error:e,done:t,summary:n,elapsedSeconds:r,insights:o,insightCount:s}){return e?st.createElement(UB,{message:e}):t?st.createElement(FB,{summary:n,elapsedSeconds:r}):st.createElement(BB,{insights:o,insightCount:s})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:o}){const s=useRepoLearnState(n),i=lt(!1);return ct(()=>{i.current||(i.current=!0,s.markStarted(),e().catch(()=>{}))},[e,s.markStarted]),nt((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?st.createElement(Qe,{flexDirection:"column"},st.createElement(zB,{text:r,repoName:o}),st.createElement(kF,{onComplete:(e,t)=>{s.setShowLogin(!1),e?ip.resolveAuth():ip.rejectAuth(t)},onCancel:()=>{s.setShowLogin(!1),ip.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):st.createElement(Qe,{flexDirection:"column"},st.createElement(zB,{text:r,repoName:o}),st.createElement(VB,{isComplete:s.done&&!s.error,hasError:Boolean(s.error)}),st.createElement(HB,{steps:s.steps,currentMessage:s.currentMessage}),st.createElement(StatusPanel,{error:s.error,done:s.done,summary:s.summary,elapsedSeconds:s.elapsedSeconds,insights:s.insights,insightCount:s.insightCount}),st.createElement(jB,{done:s.done,error:s.error}))}async function runRepoLearnProgress(e){return await applyStartupTheme(),withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{ip.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,ip.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),ip.markLearningComplete())}},"handleRunTask"),c=__name(({published:e,cancelled:l})=>{a||(a=!0,i=e,r.abort(),d.unmount(),ip.reset(),s?n(s):t({result:o,published:i,cancelled:l}))},"handleExit"),d=tt(st.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:c}));d.waitUntilExit().catch(e=>{ip.reset(),n(e)})})}function getAuthKey7(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function logLearnSummary(e){const{summary:t}=e;console.log(ht.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("")}Gt(),SR(),__name(useRepoLearnState,"useRepoLearnState"),__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),__name(getAuthKey7,"getAuthKey"),__name(logLearnSummary,"logLearnSummary");var KB=__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 Be("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",KB("--max-commits"),200).addOption(new We("--max-signals <number>","Maximum diff signals to extract").default(50).argParser(KB("--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(e){const t=createNodeRuntime(),n=await isLocalTasteSource({runtime:t,source:e.source}),r=isTTY(),o=await resolveDisplayName({runtime:t,source:e.source}),s=!await getAuthKey7();if(s&&!r)return console.log(""),console.log(" Login required to learn taste."),console.log(""),console.log(` Run: ${getBinaryCommand()} login`),console.log(` Then: npx taste learn ${e.source}`),void console.log("");let i;const a=__name(()=>{i?.().finally(()=>process.exit(130))},"sigintHandler");process.once("SIGINT",a);let l=!1;try{const a=__name(async r=>{const{summary:o,resolved:a}=await runLearnPipeline({runtime:t,reporter:ip,runLearn:__name(e=>runTasteLearningAgent({...e,createSession:createHarnessSession}),"runLearn"),source:e.source,maxCommits:e.maxCommits,maxSignals:e.maxSignals,branch:e.branch,isLocalSource:n,needsAuth:s,signal:r});return i=a?.cleanup,o},"runTask");if(r){const e=n?void 0:[...PI];({cancelled:l}=await runRepoLearnProgress({runTask:a,repoName:o,stepOrder:e}))}else logLearnSummary({summary:await a((new AbortController).signal)})}finally{process.off("SIGINT",a),i&&await i()}r&&!l||process.exit(0),RL(),await Xj({skipOnboarding:!0}),await shutdownAndExit(0)}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Gt(),SR(),Gt(),SR();var qB=ht.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(`${ht.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?`${ht.dim(t[1])}${ht.green(t[2])}${ht.white(t[3]??"")}${t[4]?ht.dim(t[4]):""}`:ht.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${ht.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`);for(const e of t)console.error(formatUsageLine(e));process.exit(1)}function exitWithTasteCliValidation(e){e.valid||(e.usage&&exitWithUsage({message:e.message,usage:e.usage}),exitWithError(e.message))}__name(shortenPath,"shortenPath"),__name(exitWithError,"exitWithError"),__name(formatUsageLine,"formatUsageLine"),__name(exitWithUsage,"exitWithUsage"),__name(exitWithTasteCliValidation,"exitWithTasteCliValidation");var YB=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){const n=buildPackageUrl({owner:e,packageName:t});return At(`commandcode.ai/${e}/${t}`,n,{fallback:YB})}function getProfileLink(e){const t=buildProfileUrl2(e);return At(`commandcode.ai/${e}`,t,{fallback:YB})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return Lt(e,n,{trim:!1})}function logMergeReviewTip(){console.log(ht.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}function handleResultErrors(e){for(const t of e){const e=normalizeTasteResultError(t);console.error(`${ht.red("Error:")} ${e}`)}process.exit(1)}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(ht.red(`Error: ${t}`)),await flushAndExit(1)}}}function formatSingleIssue(e,t){const n=[`${e.line?ht.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(ht.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`${ht.green(e)} ${ht.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?ht.red(t.summary):ht.yellow(t.summary),"",...formatIssueGroup(r,ht.red,ht.bold(ht.red("Errors:"))),...formatIssueGroup(o,ht.yellow,ht.bold(ht.yellow("Warnings:")))].join("\n").trim()}__name(getPackageLink,"getPackageLink"),__name(getProfileLink,"getProfileLink"),__name(wrapLine,"wrapLine"),__name(logMergeReviewTip,"logMergeReviewTip"),__name(handleResultErrors,"handleResultErrors"),__name(flushAndExit,"flushAndExit"),__name(withErrorHandler,"withErrorHandler"),Gt(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var JB=createTasteLintService({runtime:createNodeRuntime(),formatValidationIssues:formatValidationIssues});function createLintCommand(){return new Be("lint").argument("[package]","Taste package name").option("-g, --global","Validate taste packages from global storage (~/.commandcode)").option("--all","Validate all taste packages").description(`Validate taste package format ${ht.dim("(structure, style, etc.)")}`).action(withErrorHandler(async(e,t)=>runLint({packageName:e,options:t})))}function validateLintOptions({packageName:e,options:t}){exitWithTasteCliValidation(validateTasteLintCliOptions({packageName:e,options:t}))}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(`${ht.green(gt.tick)} All ${ht.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(ht.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(ht.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 JB.lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(ht.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Gt(),SR();var QB={};__export(QB,{downloadPackage:()=>downloadPackage,downloadRemotePackage:()=>downloadRemotePackage,getAllPackages:()=>getAllPackages,getPackage:()=>getPackage,listPackages:()=>listPackages,writePackage:()=>writePackage,writePackages:()=>writePackages}),Gt(),SR();var XB=createNodeRuntime();function getAuthKey8(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}async function requireAuthKey(){const e=await getAuthKey8();if(!e)throw new Error(`No API key found. Please authenticate with: ${getBinaryCommand()} login`);return e}function storage(){return createTasteRemoteStorage({transport:createNodeTransport({baseUrl:getApiBaseUrl()}),requireAuthKey:requireAuthKey,getAuthKey:getAuthKey8,getAuthenticatedEntity:__name(()=>getAuthenticatedEntity({client:createApiClient({baseUrl:getApiBaseUrl()})}),"getAuthenticatedEntity"),trackError:__name(({error:e,label:t,heading:n,context:r})=>trackError({error:sanitizeErrorForTelemetry({error:e,label:t}),context:{component:Ho.TASTE_REMOTE_STORAGE,heading:n,...r??{}}}),"trackError"),onWarn:__name(e=>console.warn(e),"onWarn"),logDebug:__name(e=>dlog(e),"logDebug")})}function getAllPackages(){return storage().getAllPackages()}function getPackage(e){return storage().getPackage(e)}function downloadPackage(e){return storage().downloadPackage(e)}function downloadRemotePackage(e){return storage().downloadRemotePackage(e)}function writePackage(e){return storage().writePackage(e)}async function writePackages(e){const{packages:t,projectName:n,owner:r,isPublic:o,overwrite:s}=e,{rootContent:i,categoryContents:a}=await readProjectUploadFiles({runtime:XB,packages:t});return storage().writePackages({projectName:n,owner:r,isPublic:o,overwrite:s,rootContent:i,categoryContents:a,packageCount:t.length})}function listPackages(){return storage().listPackages()}__name(getAuthKey8,"getAuthKey"),__name(requireAuthKey,"requireAuthKey"),__name(storage,"storage"),__name(getAllPackages,"getAllPackages"),__name(getPackage,"getPackage"),__name(downloadPackage,"downloadPackage"),__name(downloadRemotePackage,"downloadRemotePackage"),__name(writePackage,"writePackage"),__name(writePackages,"writePackages"),__name(listPackages,"listPackages");var ZB=createNodeRuntime(),eW=createTasteLocalStorage({runtime:ZB,target:"local-project"}),tW=createTasteLocalStorage({runtime:ZB,target:"local-global"});function list(e){return createTasteListService({runtime:ZB,localProject:eW,localGlobal:tW,remote:QB}).list(e)}function getUserName(){return getCommandAuthUserName({runtime:getCommandConfigRuntime(),path:getAuthFile()})}function createListCommand(){return new Be("list").alias("ls").option("-g, --global","List global packages").addOption(new We("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new We("--staging","Use staging environment").hideHelp()).description(`List available packages ${ht.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}function formatPackageLine(e){return` ${ht.white(e.name)}${e.publicBadge?ht.green(e.publicBadge):""}${e.starsBadge?ht.yellow(e.starsBadge):""}${e.downloadsBadge?ht.gray(e.downloadsBadge):""}${e.padding}${ht.dim.gray(e.statsLabel)}`}function validateListOptions(e){exitWithTasteCliValidation(validateTasteListCliOptions(e))}async function fetchPackages({options:e}){const t=resolveTasteListStorage(e),n=e.remote?Mt(`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${qB} Packages`),console.log(`${ht.gray("⎿")} ${ht.dim(t)}\n`);const n=projectTasteListView({packages:e,symbols:{star:gt.star,arrowDown:gt.arrowDown}});for(const e of n.rows)console.log(formatPackageLine(e));console.log(ht.dim(`\n${n.totalLabel}\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(ht.yellow(`No taste packages found in ${n.name}`))}__name(list,"list"),__name(getUserName,"getUserName"),__name(createListCommand,"createListCommand"),__name(formatPackageLine,"formatPackageLine"),__name(validateListOptions,"validateListOptions"),__name(fetchPackages,"fetchPackages"),__name(getStorageLabel,"getStorageLabel"),__name(printPackageTable,"printPackageTable"),__name(runList,"runList"),Gt(),SR(),Gt(),SR();var nW=createNodeRuntime(),rW=createTasteLocalStorage({runtime:nW,target:"local-project"}),oW=createTasteLocalStorage({runtime:nW,target:"local-global"});async function open7(e){try{const t=await createTasteOpenService({runtime:nW,localProject:rW,localGlobal:oW,remote:QB}).resolveOpen(e);return t.success?(await It([{file:t.filePath,line:t.lineNumber}]),t):t}catch(e){return classifyTasteOpenError({error:e,platform:Te.platform})}}function createOpenCommand(){return new Be("open").argument("[package]","Taste package name, or owner/package to open in browser").option("-g, --global","Open taste package from global storage (~/.commandcode)").description(`Open a taste package in your editor ${ht.dim("(use owner/package to open in browser)")}`).action(withErrorHandler(async(e,t)=>runOpen({packageName:e,options:t})))}function validateOpenOptions(e){exitWithTasteCliValidation(validateTasteOpenCliOptions(e))}async function runOpen({packageName:e,options:t}){console.log(""),validateOpenOptions(e);const n=parseOwnerPackage(e);n?await openInBrowser(n):await openInEditor2({packageName:e,options:t})}async function openInBrowser(e){const t=`https://commandcode.ai/${e.owner}/${e.packageName}`;await Pt(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${ht.green(gt.tick)} Opened ${n} in browser`)}async function openInEditor2({packageName:e,options:t}){const n=resolveTasteOpenTarget(t),r=await open7({package:e,target:n});r.success||exitWithError(r.error??"Unknown error"),console.log(`${ht.green(gt.tick)} Opened ${ht.green(`'${e}'`)} taste package from ${t.global?"global":"project"}`)}__name(open7,"open"),__name(createOpenCommand,"createOpenCommand"),__name(validateOpenOptions,"validateOpenOptions"),__name(runOpen,"runOpen"),__name(openInBrowser,"openInBrowser"),__name(openInEditor2,"openInEditor"),Gt(),SR(),Gt(),SR(),Gt();var sW=null,iW=!1;function setActiveSpinner(e){sW=e}function stopActiveSpinner(e){sW&&(sW.stop(e),sW=null)}function setPrompted(e){iW=e}function wasPrompted(){return iW}function logResult(e){if(wasPrompted())return Ge.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{summary:t,sourceName:n}=e,r=wasPrompted()?"":`${gt.tick} `,o=t.detailPath?ht.dim(`\n ${shortenPath(t.detailPath)}`):"";return"single-replaced"===t.variant?`${ht.green(r)}Replaced ${ht.green(`'${t.packageName}'`)} taste package in project`+o:"single-merged"===t.variant?`${ht.green(r)}Pulled ${ht.green(`'${t.packageName}'`)} taste package from ${n} ${ht.gray(`(${t.mergeParts.join(", ")})`)}`+o:`${ht.green(r)}Pulled ${ht.green(`'${t.packageName}'`)} taste package from ${n}`+o}function logPullSummary(e){const{breakdown:t,sourceName:n}=e,r=[];if(t.succeeded.length>0&&r.push(wrapLine(`${ht.green("Pulled")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`,wasPrompted()?4:0)),t.overwritten.length>0&&r.push(wrapLine(`${ht.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`,wasPrompted()?4:0)),t.skipped.length>0&&r.push(wrapLine(`${ht.dim("Skipped")} (${t.skipped.length}) ${ht.dim(t.skipped.join(", "))}`,wasPrompted()?4:0)),wasPrompted())return r.length>0&&Ge.log.message(r.join("\n")),Ge.outro(`${t.totalLabel} from ${n}`),void setPrompted(!1);console.log(`${ht.green(gt.tick)} ${t.totalLabel} from ${n}`),r.length>0&&console.log(r.join("\n"))}function logPullSuccess(e){const{result:t,sourceName:n,options:r}=e,o=projectTastePullSummary({result:t,options:r});if("multi"===o.variant)return logPullSummary({breakdown:o.breakdown,sourceName:n}),void(o.showTip&&logMergeReviewTip());"single-skipped"!==o.variant?"none"!==o.variant&&(logResult(buildPullMessage({summary:o,sourceName:n})),o.showTip&&logMergeReviewTip()):logResult(ht.yellow(o.message))}function beginPrompt(e,t){stopActiveSpinner(),Ge.intro(ht.dim(e)),t&&Ge.log.message(ht.dim(t)),setPrompted(!0)}function handleCancel(e){Ge.isCancel(e)&&(Ge.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Ge.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Ge.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 runConflictPrompt(e){if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(e.existsMessage),setPrompted(!0),Ge.log.warn(e.nonInteractive.warning),e.nonInteractive.strategy;if(beginPrompt(`${e.title.prefix}${ht.green(e.title.emphasis)}${e.title.suffix}`,e.existsMessage),Ge.log.message(`${e.context.firstLine}\n${e.context.secondLine}${e.context.secondLineNote?` ${ht.dim(e.context.secondLineNote)}`:""}`),e.reviewLink){const t=At(e.reviewLink.text,e.reviewLink.url,{fallback:__name((e,t)=>t,"fallback")});Ge.log.info(`${e.reviewLink.prefix}${ht.cyan(t)} ${ht.dim(e.reviewLink.note)}`)}const t=await Ge.select({message:e.selectMessage,options:e.options.map(e=>({value:e.value,label:e.label,hint:e.hint})),initialValue:e.initialValue});handleCancel(t);const n=t;return startStrategySpinner(n),n}async function promptMergeStrategy(e){const{packageName:t,owner:n,localPkg:r,remoteLearningsCount:o}=e;return runConflictPrompt(buildTastePullConflictPrompt({packageName:t,owner:n,localLearningsCount:r.learnings.length,remoteLearningsCount:o}))}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalPkg:r}=e;return runConflictPrompt(buildTasteGlobalPushConflictPrompt({packageName:t,localLearningsCount:n,globalLearningsCount:r.learnings.length}))}async function promptGlobalPullStrategy(e){const{packageName:t,localPkg:n,globalLearningsCount:r}=e;return runConflictPrompt(buildTasteGlobalPullConflictPrompt({packageName:t,localLearningsCount:n.learnings.length,globalLearningsCount:r}))}async function promptTypeMismatchStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e;return runConflictPrompt(buildTasteTypeMismatchConflictPrompt({packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}))}async function promptSameTypeStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e;return runConflictPrompt(buildTasteSameTypeConflictPrompt({packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}))}__name(setActiveSpinner,"setActiveSpinner"),__name(stopActiveSpinner,"stopActiveSpinner"),__name(setPrompted,"setPrompted"),__name(wasPrompted,"wasPrompted"),__name(logResult,"logResult"),__name(buildPullMessage,"buildPullMessage"),__name(logPullSummary,"logPullSummary"),__name(logPullSuccess,"logPullSuccess"),Gt(),SR(),Gt(),SR(),__name(beginPrompt,"beginPrompt"),__name(handleCancel,"handleCancel"),__name(startStrategySpinner,"startStrategySpinner"),__name(runConflictPrompt,"runConflictPrompt"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy");var aW=createNodeRuntime(),lW=createTasteLocalStorage({runtime:aW,target:"local-project"}),cW=createTasteLocalStorage({runtime:aW,target:"local-global"});function service(){return createTastePullService({localProject:lW,localGlobal:cW,remote:QB,getDestinationPath:__name(e=>resolveTastePackageDestinationPathForRuntime({runtime:aW,...e}),"getDestinationPath"),promptGlobalPullStrategy:promptGlobalPullStrategy,promptMergeStrategy:promptMergeStrategy,validation:{formatValidationIssues:formatValidationIssues,onWarning:__name(e=>console.warn(e),"onWarning")}})}function pull(e){return service().pull(e)}function pullRemote(e){return service().pullRemote(e)}function createPullCommand(){return new Be("pull").argument("[package]","Taste package name, or owner/package to pull from remote").option("-g, --global","Pull taste package from global storage (~/.commandcode)").addOption(new We("--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 We("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${ht.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})}))}async function runPull(e){const{packageName:t,options:n}=e;console.log("");const r=planTastePullCommand({packageName:t,options:n});if(!r.valid)throw exitWithTasteCliValidation(r.validation),new Error("unreachable");return"remote-single"===r.route.type?pullRemoteSingle({options:r.options,route:r.route}):pullGlobal({options:r.options,route:r.route})}async function pullRemoteSingle(e){setActiveSpinner(Mt("Pulling taste package").start());const t=await pullRemote({owner:e.route.owner,packageName:e.route.packageName,overwrite:e.options.overwrite,strategy:e.route.strategy});return stopActiveSpinner(),{result:t,owner:e.route.owner}}async function pullGlobal(e){setActiveSpinner(Mt("Pulling taste package").start());const t=await pull({packages:[...e.route.packages],source:"local-global",overwrite:e.options.overwrite,strategy:e.route.strategy});return stopActiveSpinner(),{result:t}}function logResult2(e){if(wasPrompted())return Ge.outro(e),void setPrompted(!1);console.log(e)}function formatAllLocation(t){return"taste-dir"===t.kind?shortenPath(e.dirname(e.dirname(t.filePath))):t.filePath}function formatDetailPath(e){return e?ht.dim(`\n ${shortenPath(e)}`):""}function renderPushSummary(e){const t=wasPrompted()?"":`${gt.tick} `;if("none"!==e.variant)if("all-skipped"!==e.variant)if("all-pushed-remote"!==e.variant){if("all-replaced"===e.variant){const n=e.replacedLabel?` ${ht.gray(`(${e.replacedLabel})`)}`:"";return void logResult2(`${ht.green(t)}Replaced ${e.packageCountLabel} in ${formatAllLocation(e.location)}${n}`)}if("all-pushed"!==e.variant){if("all-merged"===e.variant){const n=e.mergeParts.length>0?` ${ht.gray(`(${e.mergeParts.join(", ")})`)}`:"";return void logResult2(`${ht.green(t)}Pushed ${e.packageCountLabel} to ${formatAllLocation(e.location)}${n}`)}"single-replaced"!==e.variant?"single-merged"!==e.variant?"single-pushed"!==e.variant?"multi"!==e.variant||logResult2(wrapLine(`${ht.green(t)}Pushed ${ht.green(e.count)} taste packages ${ht.green(`(${e.packages.join(", ")})`)} to ${e.targetName}`)):logResult2(`${ht.green(t)}Pushed ${ht.green(`'${e.packageName}'`)} taste package to ${e.locationLabel}`+formatDetailPath(e.detailPath)):logResult2(`${ht.green(t)}Pushed ${ht.green(`'${e.packageName}'`)} taste package to ${e.locationLabel} ${ht.gray(`(${e.mergeParts.join(", ")})`)}`+formatDetailPath(e.detailPath)):logResult2(`${ht.green(t)}Replaced ${ht.green(`'${e.packageName}'`)} taste package in ${e.locationLabel}`+formatDetailPath(e.detailPath))}else logResult2(`${ht.green(t)}Pushed ${e.packageCountLabel} to ${formatAllLocation(e.location)}`)}else logResult2(`${ht.green(t)}Pushed ${e.packageCountLabel} to remote`);else logResult2(`${ht.green(t)}Skipped ${e.packageCountLabel}`)}function logPushUrls(e){for(const t of collectTastePushRemoteLinks(e))console.log(ht.gray(` ${getPackageLink(t)}`))}function logConflictSummary(e){const t=projectTastePushOutcome(e.result),n=[];t.succeeded.length>0&&n.push(wrapLine(`${ht.green("Merged")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`,4)),t.overwritten.length>0&&n.push(wrapLine(`${ht.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`,4)),t.skipped.length>0&&n.push(wrapLine(`${ht.dim("Skipped")} (${t.skipped.length}) ${ht.dim(t.skipped.join(", "))}`,4)),n.length>0&&Ge.log.message(n.join("\n")),Ge.outro(t.totalLabel)}function logPushBreakdown(e){const t=projectTastePushOutcome(e);if(0===t.skipped.length&&0===t.overwritten.length)return;const n=[];t.succeeded.length>0&&n.push(wrapLine(`${ht.green("Pushed")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`)),t.overwritten.length>0&&n.push(wrapLine(`${ht.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`)),t.skipped.length>0&&n.push(wrapLine(`${ht.dim("Skipped")} (${t.skipped.length}) ${ht.dim(t.skipped.join(", "))}`)),n.length>0&&console.log(n.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=projectTastePushSummary({result:t,options:n});renderPushSummary(r),n.all&&logPushBreakdown(t),logPushUrls({result:t,options:n}),r.showTip&&logMergeReviewTip()}__name(service,"service"),__name(pull,"pull"),__name(pullRemote,"pullRemote"),__name(createPullCommand,"createPullCommand"),__name(runPull,"runPull"),__name(pullRemoteSingle,"pullRemoteSingle"),__name(pullGlobal,"pullGlobal"),Gt(),SR(),Gt(),SR(),__name(logResult2,"logResult"),__name(formatAllLocation,"formatAllLocation"),__name(formatDetailPath,"formatDetailPath"),__name(renderPushSummary,"renderPushSummary"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Gt(),SR();var dW=createNodeRuntime(),uW=createTasteLocalStorage({runtime:dW,target:"local-project"}),mW=createTasteLocalStorage({runtime:dW,target:"local-global"});async function getUserOwner(){try{const e=await getAuthenticatedEntity({client:createApiClient({baseUrl:getApiBaseUrl()})});if(e.success&&e.user?.userName)return e.user.userName}catch{}}function service2(){return createTastePushService({localProject:uW,localGlobal:mW,remote:QB,getUserOwner:getUserOwner,getProjectName:__name(()=>e.basename(process.cwd()),"getProjectName"),getDestinationPath:__name(e=>resolveTastePackageDestinationPathForRuntime({runtime:dW,...e}),"getDestinationPath"),promptGlobalPushStrategy:promptGlobalPushStrategy,promptTypeMismatchStrategy:promptTypeMismatchStrategy,promptSameTypeStrategy:promptSameTypeStrategy,validation:{formatValidationIssues:formatValidationIssues,onWarning:__name(e=>console.warn(e),"onWarning")}})}function push(e){return service2().push(e)}function pushRemote(e){return service2().pushRemote(e)}async function promptOwnerSelection(e){const{userName:t,orgs:n}=e;if(0===n.length)return t;const{options:r,initialValue:o}=buildTasteOwnerSelectOptions({userName:t,orgs:n}),s=await Ge.select({message:"Owner",options:[...r],initialValue:o});return Ge.isCancel(s)&&(Ge.cancel("Operation cancelled"),process.exit(0)),s}__name(getUserOwner,"getUserOwner"),__name(service2,"service"),__name(push,"push"),__name(pushRemote,"pushRemote"),Gt(),SR(),__name(promptOwnerSelection,"promptOwnerSelection");var pW=createNodeRuntime(),gW=createTasteLocalStorage({runtime:pW,target:"local-project"});function loadUserNamespaces(){return fetchUserNamespaces({client:createApiClient({baseUrl:getApiBaseUrl()})})}function createPushCommand(){return new Be("push").description(`Push taste packages to remote ${ht.dim("(commandcode.ai)")} or global ${ht.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 We("--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 We("--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})}))}async function validateOwnerAccess(e){const t=await checkTastePushOwnerAccess({owner:e,loadNamespaces:loadUserNamespaces});"unavailable"!==t.type?"denied"===t.type&&exitWithError(`No push access to '${e}'. Available: ${t.availableOwners.join(", ")}`):dlog(`[Auth] validateOwnerAccess: namespace service unavailable, skipping — ${t.error instanceof Error?t.error.message:String(t.error)}`)}async function resolveOwnerForPush(e){let t;return resolveTastePushOwner({ownerPlan:e,validateOwnerAccess:validateOwnerAccess,hasLocalPackage:__name(async e=>(await gW.getAllPackages()).some(t=>t.category===e),"hasLocalPackage"),loadNamespaces:loadUserNamespaces,prompt:{onPromptStart:__name(({packageName:e})=>{Ge.intro(ht.dim(`pushing ${e}`)),setPrompted(!0),t=Ge.spinner(),t.start("Resolving")},"onPromptStart"),onPackageMissing:__name(({packageName:e})=>{t?.error("Failed"),Ge.outro(ht.red(`Taste package '${e}' not found in project`)),process.exit(1)},"onPackageMissing"),onNamespacesLoaded:__name(({willPrompt:e})=>{t?.stop(e?"Select owner to push to":"")},"onNamespacesLoaded"),selectOwner:promptOwnerSelection}})}async function runPush(e){const{packageName:t,options:n}=e;console.log("");const r=planTastePushCommand({packageName:t,options:n});if(!r.valid)throw exitWithTasteCliValidation(r.validation),new Error("unreachable");return"remote-all"===r.route.type?pushRemoteAll({options:r.options,route:r.route}):"remote-single"===r.route.type?pushRemoteSingle({options:r.options,route:r.route}):pushGlobal({options:r.options,route:r.route})}async function pushRemoteAll(t){t.route.owner&&await validateOwnerAccess(t.route.owner);const n=formatTastePackageCount((await gW.getAllPackages()).length),r=e.basename(process.cwd()),o=resolveTasteStrategyLabel({strategy:t.route.strategy,isRemote:!0});console.log(ht.dim(` Pushing ${n} to ${r} (remote)${o}`)),console.log(""),setActiveSpinner(Mt("Pushing taste packages").start());const s=await push({packages:[],target:"remote-project",overwrite:t.options.overwrite,isPublic:t.route.isPublic,strategy:t.route.strategy,owner:t.route.owner});return stopActiveSpinner(),s}async function pushRemoteSingle(e){const{owner:t,packageName:n}=await resolveOwnerForPush(e.route.ownerPlan);startPushSpinner({owner:t,pkgName:n});const r=await pushRemote({owner:t,packageName:n,overwrite:e.options.overwrite,isPublic:e.route.isPublic,strategy:e.route.strategy});return stopActiveSpinner(`Pushed to ${t}/${n}`),r}function startPushSpinner(e){const{owner:t,pkgName:n}=e;if(wasPrompted()){const e=Ge.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Mt("Pushing taste package").start())}async function pushGlobal(e){const t=await gW.getAllPackages(),n=formatTastePackageCount(e.route.packages.length>0?e.route.packages.length:t.length),r=shortenPath(getTastePathForRuntime({runtime:pW,target:"local-global"})),o=resolveTasteStrategyLabel({strategy:e.route.strategy});console.log(ht.dim(` Pushing ${n} to ${r}${o}`)),console.log(""),setActiveSpinner(Mt("Pushing taste packages").start());const s=await push({packages:[...e.route.packages],target:"local-global",overwrite:e.options.overwrite,strategy:e.route.strategy});return stopActiveSpinner(),s}function scopeOf(e){return e.user?"global":"project"}function whereFor(e){return"project"===e?" for this project":" for all your projects"}async function applyTasteLearning(e){await setTasteLearning({tasteLearning:e.enabled,scope:e.scope,..."project"===e.scope?{projectPath:process.cwd()}:{}})}function reportEnabled(e){console.log(`${ht.green(gt.tick)} Taste learning is on${whereFor(e)}. New preferences are saved and reused across sessions.`)}function reportDisabled(e){const t=getBinaryCommand();console.log(`${ht.green(gt.tick)} Taste learning is off${whereFor(e)}. Turn it back on with ${ht.cyan(`${t} taste enable`)}.`)}function createEnableCommand(){return new Be("enable").option("-u, --user","Apply at the user level (all your projects)").description("Turn on taste learning (save preferences across sessions)").action(withErrorHandler(async e=>{const t=scopeOf(e);await applyTasteLearning({enabled:!0,scope:t}),console.log(""),reportEnabled(t)}))}function createDisableCommand(){return new Be("disable").option("-u, --user","Apply at the user level (all your projects)").description("Turn off taste learning (stop saving preferences)").action(withErrorHandler(async e=>{const t=scopeOf(e);await applyTasteLearning({enabled:!1,scope:t}),console.log(""),reportDisabled(t)}))}function createTasteCommand(){const e=new Be("taste");return e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments(),e.addCommand(createEnableCommand()),e.addCommand(createDisableCommand()),e.addCommand(createPushCommand()),e.addCommand(createPullCommand()),e.addCommand(createListCommand()),e.addCommand(createLintCommand()),e.addCommand(createOpenCommand()),isExperimentalEnabled()&&e.addCommand(createLearnCommand()),e}__name(loadUserNamespaces,"loadUserNamespaces"),__name(createPushCommand,"createPushCommand"),__name(validateOwnerAccess,"validateOwnerAccess"),__name(resolveOwnerForPush,"resolveOwnerForPush"),__name(runPush,"runPush"),__name(pushRemoteAll,"pushRemoteAll"),__name(pushRemoteSingle,"pushRemoteSingle"),__name(startPushSpinner,"startPushSpinner"),__name(pushGlobal,"pushGlobal"),Gt(),SR(),__name(scopeOf,"scopeOf"),__name(whereFor,"whereFor"),__name(applyTasteLearning,"applyTasteLearning"),__name(reportEnabled,"reportEnabled"),__name(reportDisabled,"reportDisabled"),__name(createEnableCommand,"createEnableCommand"),__name(createDisableCommand,"createDisableCommand"),__name(createTasteCommand,"createTasteCommand"),Gt(),SR();var hW=`${getBinaryCommand()}`;function formatVersion(e,t,n=!1){const r=n?Et.bold(Et.green(t)):Et.white(t);return`${Et.dim(e)} ${r}`}function showVersionDetails(e){for(const t of e.versionLines)console.log(formatVersion(t.label,t.version,t.highlight));console.log("");for(const t of e.detailLines)console.log(t.replace(`${hW} update`,Et.bold(Et.green(`${hW} update`))))}function showUpdateSuccessHint(e){for(const t of e.detailLines)console.log(Et.dim(t.replace(hW,Et.cyan(hW))))}function showManualUpdateHint(e){const[t,n]=e.manualUpdateLines;t&&console.log(Et.dim(t)),n&&console.log(Et.cyan(n))}function showCheckFailure(e){for(const t of e.detailLines)console.log(Et.dim(t))}function renderUpdateEvent(e,t){if("type"in e)"updating"===e.type&&(t.text=e.text.replace("→",gt.arrowRight));else{if("check-failed"===e.kind)return t.fail(e.outcome.spinnerMessage),void showCheckFailure(e.outcome);if("up-to-date"!==e.kind)return"update-available"===e.kind?(t.stop(),console.log(""),console.log(`${Et.green(gt.tick)} ${e.outcome.heading}`),void showVersionDetails(e.outcome)):"update-failed"===e.kind?(t.fail(e.outcome.spinnerMessage),void showManualUpdateHint(e.outcome)):"updated"===e.kind?(t.succeed(e.outcome.spinnerMessage),void showUpdateSuccessHint(e.outcome)):void 0;t.succeed(e.outcome.spinnerMessage)}}async function updateAction2(e){const t=Mt("Checking for updates...").start(),n=await runCliUpdateCommand({checkOnly:e.checkOnly,host:hj,copy:{binCommand:hW,updateCommand:"npm i -g command-code"},emit:__name(e=>renderUpdateEvent(e,t),"emit")});if("update-failed"===n.kind){const{failureReason:e}=n.outcome.telemetry;trackError({error:sanitizeErrorForTelemetry({error:new Error(e?`Update failed: ${e}`:"Update failed"),label:"cli_update_failed"}),context:{component:Ho.UPDATE_COMMAND,heading:n.outcome.telemetry.heading,"update.current_version":n.outcome.telemetry.currentVersion,"update.target_version":n.outcome.telemetry.targetVersion,...e&&{"update.failure_reason":e}}}),await shutdownTelemetry(),process.exit(1)}}__name(formatVersion,"formatVersion"),__name(showVersionDetails,"showVersionDetails"),__name(showUpdateSuccessHint,"showUpdateSuccessHint"),__name(showManualUpdateHint,"showManualUpdateHint"),__name(showCheckFailure,"showCheckFailure"),__name(renderUpdateEvent,"renderUpdateEvent"),__name(updateAction2,"updateAction");var fW=new Be("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction2);function getAuthKey9(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}Gt(),SR(),__name(getAuthKey9,"getAuthKey");var yW=__name((e,t)=>`${gt.info} ${e}: ${Et.cyan(t)}`,"formatInfoLine"),SW=__name(e=>Et.bold(`${e}:`),"formatSectionHeader"),wW=__name(e=>Et.red(e),"formatError"),vW=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),kW=__name((e,t)=>["",SW(e),...t.map(e=>yW(e.label,e.value))],"buildSection"),CW=__name(e=>kW("User Information",projectWhoamiUserRows(e)),"buildUserOutput"),bW=__name(e=>kW("Organization",projectWhoamiOrgRows(e)),"buildOrgOutput"),EW=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),TW=__name((e,t)=>{EW(CW(e)),t&&EW(bW(t)),console.log("")},"displayUserInfo");async function whoamiAction(){const e=Mt("Fetching user information...").start();try{hasCommandApiKey(await getAuthKey9())||(e.fail(wW(qt)),process.exit(1));const t=await getAuthenticatedEntity({client:createApiClient({baseUrl:getApiBaseUrl()})});isAuthenticatedEntityLoaded(t)||(e.fail(wW(Yt)),process.exit(1)),e.succeed("User information loaded"),TW(t.user,t.org)}catch(t){e.fail(wW(`Error: ${vW(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var PW=new Be("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);handleUnhandledErrors(),setVscodeIpcLogger(dlog),setupTelemetry(),registerBundledRipgrep(),setImmediate(()=>{const e=getTelemetryEnv();recordCliFingerprintInBackground({getAuthKey:__name(()=>getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env}),"getAuthKey"),baseUrl:getApiBaseUrl(),cliEnvironment:normalizeCliEnvironment(e),cliVersion:getPackageJson(import.meta.url).version??"unknown",cmdZdr:"1"===process.env.CMD_ZDR})}),await preRun();var MW=createProgram();MW.action(interactiveModeAction),MW.addCommand(ZD),MW.addCommand(c$),MW.addCommand(PW),MW.addCommand(fW),MW.addCommand(XD),MW.addCommand(QD),MW.addCommand(createTasteCommand()),MW.addCommand(createMcpCommand()),MW.addCommand(nN),MW.addCommand(zD),MW.addCommand(UD),MW.addCommand(VD),MW.addCommand(mB),MW.addCommand($B),MW.addCommand(wN),isExperimentalEnabled()&&MW.addCommand(createSandboxCommand()),setupCommanderHooks(MW),MW.parse();