command-code 1.32.1 → 1.32.2-rc.0

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
@@ -13,4 +13,4 @@ import*as e from"path";import t,{join as n,dirname as r,parse as o,resolve as s,
13
13
  ░▀▀▀░▀░░░▀░▀▀░░
14
14
  `,DA=getMaxLineWidth(LA),NA=AA,$A=__name(e=>{const t=e??getTerminalWidth();return t>=IA?"full":t>=NA?"compact":"minimal"},"getHeaderLayout");new Set(["dark","light"]),Ht(),Qx();var _A=!1;async function resolveStartupTheme(){return _A||(_A=!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=Ro}=e,[s,a]=at("initializing"),[i,l]=at("Starting authentication..."),[c,d]=at(""),[u,m]=at(null),p=it(t),g=it(n),h=it(r);lt(()=>{p.current=t,g.current=n,h.current=r});const f=it(null);f.current??=createAuthFlowController({timeoutMs:o,openBrowser:__name(e=>Tt(e),"openBrowser"),onAuthStateChange:a,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=dt(()=>{y.cancel()},[y]),w=dt(e=>y.submitApiKey(e),[y]);return lt(()=>(y.start(),()=>{y.dispose()}),[y]),{authState:s,statusMessage:i,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),a=it(o),i=it(e);lt(()=>{const r=i.current;if(i.current=e,e===r)return;if(!t)return;if(!n)return;const l=(e||"").length;o>l&&(s(l),a.current=l)},[e,t,n,o]);const l=dt(e=>{s(e),a.current=e},[]);return{cursor:o,setCursor:l,cursorRef:a}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:o,stripBracketedPaste:s=!1}){const a=it(!1);lt(()=>{if(!e)return;const i=process.stdin,l=__name(e=>{o(!0);const t=clampCursor(e.cursor,e.value.length);r(e.value,t),setTimeout(()=>o(!1),0)},"emitStdinResult"),c=__name(e=>{const r=e.toString();if(s){const e=processBracketedPasteInput({input:r,value:t.current,cursor:n.current});if(e.handled)return void l(e)}const o=processRawInput(r,t.current,n.current);o.handled&&l(o)},"handleRawInput");if(i.on("data",c),!a.current&&hasBufferedInput()){a.current=!0;const e=consumeBufferedInput();e&&c(Buffer.from(e))}return stopEarlyInputCapture(),()=>{i.off("data",c)}},[e,t,n,r,o,s])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:o,onUpdate:s,onSubmit:a}){tt((e,i)=>{if(o())return;if(isIgnoredKey(e,i))return;if(i.return)return void(i.shift||i.ctrl||i.meta||a?.(n.current));const l=processInkInput(e,i,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=it(e);return t.current=e,t}function useEchoAwareValueRef(e){const t=it(e),n=it([]),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:dt(e=>{n.current.push(e),n.current.length>64&&n.current.shift()},[])}}__name(resolveStartupTheme,"resolveStartupTheme"),__name(applyStartupTheme,"applyStartupTheme"),Ht(),Ht(),Qx(),__name(useAuthFlow,"useAuthFlow"),Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef"),__name(useEchoAwareValueRef,"useEchoAwareValueRef"),Ht(),Qx();var FA=gt.hex(nI.DIM),UA=__name(e=>gt.hex(vI.CODE)(e),"accentHex"),jA=/^\/[A-Za-z0-9][\w/:-]*/,BA=/(^|\s)(@\S+)/g;function pastedTokenRanges(e,t){const n=[],r=new RegExp(kT.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(CT.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=[],a=jA.exec(e);a&&!r(0,a[0].length)&&o(a[0])&&s.push({start:0,end:a[0].length,link:null,color:"accent"});const i=new RegExp(BA.source,"g");let l;for(;null!==(l=i.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 a=t;a<n;a++){const t=e[a];s+=o&&a===r?"\n"===t?bt.inverse(" ")+"\n":bt.inverse(t):t}return s}function renderTokenSpan(e,t,n,r,o,s="dim"){const a="accent"===s?UA:FA;return o&&r>=t&&r<n?a(e.slice(t,r))+bt.inverse(e[r])+a(e.slice(r+1,n)):a(e.slice(t,n))}function renderPlaceholder(e,t){return t?0===e.length?bt.inverse(" "):bt.inverse(e[0])+FA(e.slice(1)):FA(e)}function renderValue(e,t,n,r,o){const s=pastedTokenRanges(e,r),a=[...s,...accentTokenRanges(e,s,o)].sort((e,t)=>e.start-t.start);if(!n&&0===a.length)return e;if(n&&0===e.length)return bt.inverse(" ");let i="",l=0;for(const{start:r,end:o,link:s,color:c}of a){i+=renderPlainSpan(e,l,r,t,n);const a=renderTokenSpan(e,r,o,t,n,c);i+=s?createOSC8Link(s,a,!1):a,l=o}return i+=renderPlainSpan(e,l,e.length,t,n),n&&t===e.length&&(i+=bt.inverse(" ")),i}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(St(e).length<=s)return e;const a=e.split(/(\s+)/);let i="",l=0,c=!0;for(const e of a){const t=St(e).length;if(l+t>(c?s:o)&&l>0&&(i+="\n"+r,l=n,c=!1),i+=e,l+=t,e.includes("\n")){const t=e.substring(e.lastIndexOf("\n")+1);l=St(t).length,c=!0}}return i}function getDisplayValue(e,t,n,r,o,s,a){const i=r&&o;return 0===e.length&&t?renderPlaceholder(t,i):renderValue(e,n,i,s,a)}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"),Qx();var WA={white:bt.white,green:bt.green,red:bt.red,blue:bt.blue,yellow:bt.yellow,cyan:bt.cyan,magenta:bt.magenta,gray:bt.gray,grey:bt.gray};function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:o=!0,onChange:s,onSubmit:a,onCursorChange:i,prefix:l="",prefixColor:c,singleLine:d=!1,maxWidth:u,stripBracketedPaste:m=!1,disablePasteRouting:p=!1,initialCursor:g,imageTokenLinks:h,isRecognizedSlashCommand:f}){const y=it(!1),{valueRef:S,noteEmittedValue:w}=useEchoAwareValueRef(e),v=useSyncedRef(s),{cursor:k,setCursor:C,cursorRef:b}=useCursorState({value:e,focus:n,showCursor:o,initialCursor:g});ot.useEffect(()=>{i?.(k)},[k,i]);const E=dt((e,t)=>{C(t),e!==S.current&&(w(e),S.current=e,v.current(e))},[C,S,v,w]),T=dt(e=>{y.current=e},[]),P=dt(()=>y.current,[]);useRawStdinHandler({focus:n,valueRef:S,cursorRef:b,onUpdate:E,setHandled:T,stripBracketedPaste:m}),ot.useEffect(()=>{if(n&&!p)return registerPasteConsumer(e=>{if(y.current)return;const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),n=insertTextAt(S.current,b.current,t);E(n.text,n.cursor)})},[n,p,S,b,E]),useInkInputHandler({focus:n,showCursor:o,valueRef:S,cursorRef:b,isHandledByStdin:P,onUpdate:E,onSubmit:a});const{stdout:M}=Ze(),x=M?.columns??80,I=getMaskedValue(e,r),A=c?WA[c]:void 0,R=l?A?A(l):l:"",O=getDisplayValue(I,t,k,o,n,h,f),L=l?.length??0,D=R+O;if(d){const e=D.replace(/\n/g," ");return null!=u?ot.createElement(Je,{width:u},ot.createElement(Qe,{wrap:"truncate"},e)):ot.createElement(Qe,{wrap:"truncate"},e)}const N=wrapWithIndent(D,x,L);return ot.createElement(Qe,{wrap:"wrap"},N)}__name(TextInput,"TextInput"),Ht();var HA=__name(({children:e})=>ot.createElement(Qe,{italic:!0,color:nI.DIM},e),"HintText"),GA=__name(({children:e})=>ot.createElement(Qe,{bold:!0},e),"HintKey"),VA=__name(({hints:e,marginTop:t=1})=>{const n=e.filter(e=>null!=e&&!1!==e&&""!==e);return 0===n.length?null:ot.createElement(Je,{marginTop:t},ot.createElement(HA,null,n.map((e,t)=>ot.createElement(ot.Fragment,{key:t},t>0&&" · ",e))))},"HintBar");Ht();var zA=rI,KA=nI.DIM,qA=nI.DIMMER,YA=rI,JA=nI.WHITE,QA=nI.GRAY,XA=nI.GREEN;function hasContent(e){return null!=e&&""!==e}__name(hasContent,"hasContent");var ZA=__name(({title:e,titleSuffix:t,subtitle:n,children:r,hint:o,footer:s,rule:a=!0,titleColor:i=zA,ruleColor:l=qA,gapAfterHeader:c=!0,boxProps:d})=>{const u=hasContent(n);return ot.createElement(Je,{flexDirection:"column",width:"100%",...d},a&&ot.createElement(RI,{dividerColor:l}),ot.createElement(Je,null,ot.createElement(Qe,{bold:!0,color:i},e),hasContent(t)&&ot.createElement(Qe,{color:KA},t)),u?ot.createElement(Je,{marginBottom:c?1:0},ot.createElement(Qe,{color:KA},n)):c&&ot.createElement(Je,{marginBottom:1}),r,s?ot.createElement(Je,{marginTop:1},s):o?ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{italic:!0,color:KA},o)):null)},"Overlay"),eR=ot.memo(({authState:e,browserUrl:t,apiKeyInput:n,setApiKeyInput:r,handleApiKeySubmit:o})=>{const s="waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,a=t&&("waiting_browser"===e||"manual_entry"===e);return ot.createElement(ot.Fragment,null,s&&ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?nI.YELLOW:nI.GRAY,paddingX:1},ot.createElement(Qe,{color:nI.DIM},"API Key: "),ot.createElement(Je,{flexGrow:1},ot.createElement(TextInput,{value:n,onChange:r,onSubmit:o,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},getCommandAuthHelpText(e))),a&&ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},getCommandAuthUrlLabel(e)),ot.createElement(BI,{url:t,text:t,color:nI.CYAN,dimColor:!0}))),"validating"===e&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"invalid_key"===e)&&ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"ctrl+c to cancel")))});eR.displayName="AuthInputSection";var tR=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s})=>{const a=__name(()=>"waiting_browser"===e?ot.createElement(Qe,{color:nI.CYAN},pt.ellipsis):"browser_success"===e||"success"===e?ot.createElement(Qe,{color:nI.GREEN},pt.tick):"denied"===e||"invalid_key"===e?ot.createElement(Qe,{color:nI.RED},pt.cross):"manual_entry"===e?ot.createElement(Qe,{color:nI.YELLOW},pt.arrowDown):"error"===e?ot.createElement(Qe,{color:nI.RED},pt.warning):ot.createElement(vt,{type:"dots"}),"getStatusIcon"),i=__name(()=>getCommandAuthStatusColor(e),"getStatusColor");return"browser_success"===e||"success"===e||"denied"===e?null:ot.createElement(ZA,{title:"Sign in to Command Code"},ot.createElement(Je,{marginBottom:1},ot.createElement(Je,{marginRight:1},a()),ot.createElement(Qe,{color:i()},t)),ot.createElement(eR,{authState:e,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s}))},"AuthFlowUI"),nR=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a,cancel:i}=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 tt((e,t)=>{t.ctrl&&"c"===e&&i()}),ot.createElement(tR,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a})},"LoginWithApiKey");Ht(),Qx();var rR=getPackageJson(import.meta.url),oR="string"==typeof rR.version&&rR.version.trim()?rR.version:"unknown";function createApiClient(e){return createCommandApiClient({baseUrl:e.baseUrl,timeout:e.timeout,cliVersion:oR,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 isLingFlashFreeEnded(e=new Date){return e.getTime()>=Date.parse("2026-08-03T13:00:00Z")}__name(createApiClient,"createApiClient"),__name(getAuthKey,"getAuthKey"),Ht(),Qx(),Ht(),Ht(),__name(isLingFlashFreeEnded,"isLingFlashFreeEnded");var sR={GENERATE:"/alpha/agent/generate"},aR={RECORD:"/alpha/fingerprint/record"},iR={START:"/alpha/sandbox/start"},lR={CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",APPEND:"/alpha/share/append"},cR={CREATE:"/alpha/devrel-thread/create",DELETE:"/alpha/devrel-thread/delete",UPDATE:"/alpha/devrel-thread/update"},dR={GET:"/alpha/taste/:projectSlug",UPDATE:"/alpha/taste/:projectSlug/update",DELETE:"/alpha/taste/:projectSlug",LEARN:"/alpha/learn"},uR={CREDITS:"/alpha/billing/credits",SUBSCRIPTIONS:"/alpha/billing/subscriptions"},mR={SUMMARY:"/alpha/usage/summary"},pR={TRACK:"/alpha/lifecycle-events"},gR={GET:/\/internal\/orgs\/[a-zA-Z0-9_-]+/,FOLLOW:/\/internal\/orgs\/[a-zA-Z0-9-]+\/follow/,FOLLOWERS:/\/internal\/orgs\/[a-zA-Z0-9-]+\/followers/},hR={FOLLOW:/\/internal\/users\/[a-zA-Z0-9-]+\/follow/,FOLLOWERS:/\/internal\/users\/[a-zA-Z0-9-]+\/followers/,FOLLOWING:/\/internal\/users\/[a-zA-Z0-9-]+\/following/},fR={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/}),sR.GENERATE,aR.RECORD,iR.START,lR.CREATE,lR.DELETE,lR.APPEND,cR.CREATE,cR.DELETE,cR.UPDATE,dR.LEARN,dR.DELETE,dR.GET,dR.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"}),uR.CREDITS,uR.SUBSCRIPTIONS,mR.SUMMARY,pR.TRACK,Object.values(gR),Object.values(hR),Object.values(fR.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 yR="anthropic",SR="openai",wR="baseten",vR="vercel-ai-gateway",kR="cloudflare-ai-gateway",CR="cmd-ai",bR="openrouter",ER="alibaba",TR="novita",PR="morph",MR=vR,xR={[yR]:[{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",provider:"Anthropic",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:20,cacheHitCost:1},{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}],[SR]:[{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}],[wR]:[{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}],[TR]:[{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}],[vR]:[],[bR]:[]};fe.enum(["owner","admin","member"]);var IR="chatComplete",AR="responses",RR="MiniMaxAI/MiniMax-M3-Free",OR={SONNET_5:{id:"claude-sonnet-5",inputModalities:["text","image"],provider:yR,spec:IR,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:yR,spec:IR,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:{id:"claude-fable-5",inputModalities:["text","image"],provider:yR,spec:IR,label:"Claude Fable 5",name:"Claude Fable 5",description:"most capable for demanding reasoning & long-horizon agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_5:{id:"claude-opus-5",inputModalities:["text","image"],provider:yR,spec:IR,label:"Claude Opus 5",name:"Claude Opus 5",description:"most intelligent Opus 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:yR,spec:IR,label:"Claude Opus 4.8",name:"Claude Opus 4.8",description:"prev flagship, 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:yR,spec:IR,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:yR,spec:IR,label:"Claude Haiku 4.5",name:"Claude Haiku 4.5",description:"fastest & most compact, great for quick tasks",contextWindow:2e5},GPT_5_6_SOL:{id:"gpt-5.6-sol",inputModalities:["text","image"],provider:vR,spec:AR,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:bR,spec:AR,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:bR,spec:AR,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:SR,spec:AR,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:SR,spec:AR,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:SR,spec:AR,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:SR,spec:AR,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_FREE:{id:RR,inputModalities:["text","image"],provider:MR,spec:IR,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",badge:"free",hidden:!0,reasoning:!0,contextWindow:1e6},DEEPSEEK_V4_PRO:{id:"deepseek/deepseek-v4-pro",inputModalities:["text"],provider:MR,spec:IR,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:MR,spec:IR,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:MR,spec:IR,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},KIMI_K3:{id:"moonshotai/Kimi-K3",inputModalities:["text","image"],provider:MR,spec:IR,label:"Kimi K3",name:"Kimi K3",description:"long-horizon coding & knowledge work with 1M context",reasoning:!0,contextWindow:1e6},KIMI_K2_7_CODE:{id:"moonshotai/Kimi-K2.7-Code",inputModalities:["text","image"],provider:MR,spec:IR,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:MR,spec:IR,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:MR,spec:IR,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:MR,spec:IR,label:"Kimi K2.5",name:"Kimi K2.5",description:"multimodal frontend coding",contextWindow:256e3},GLM_5_3:{id:"zai-org/GLM-5.3",inputModalities:["text"],provider:MR,spec:IR,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:MR,spec:IR,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:MR,spec:IR,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:MR,spec:IR,label:"GLM-5.1",name:"GLM-5.1",description:"long-horizon autonomous coding agent"},GLM_5:{id:"zai-org/GLM-5",inputModalities:["text"],provider:MR,spec:IR,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:MR,spec:IR,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",reasoning:!0,contextWindow:1e6},MINIMAX_M2_7:{id:"MiniMaxAI/MiniMax-M2.7",inputModalities:["text"],provider:MR,spec:IR,label:"MiniMax M2.7",name:"MiniMax M2.7",description:"end-to-end software engineering agent"},MINIMAX_M2_5:{id:"MiniMaxAI/MiniMax-M2.5",inputModalities:["text"],provider:MR,spec:IR,label:"MiniMax M2.5",name:"MiniMax M2.5",description:"cross-platform full-stack agentic dev",contextWindow:2e5},XIAOMI_MIMO_V2_5_PRO:{id:"xiaomi/mimo-v2.5-pro",inputModalities:["text"],provider:MR,spec:IR,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:MR,spec:IR,label:"MiMo V2.5",name:"MiMo V2.5",description:"efficient long-context agentic coding",contextWindow:1e6},QWEN_3_8_MAX:{id:"Qwen/Qwen3.8-Max",inputModalities:["text","image"],provider:MR,spec:IR,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:MR,spec:IR,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_7_MAX:{id:"Qwen/Qwen3.7-Max",inputModalities:["text"],provider:MR,spec:IR,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:MR,spec:IR,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:MR,spec:IR,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:MR,spec:IR,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:MR,spec:IR,label:"Qwen 3.6 Plus",name:"Qwen 3.6 Plus",description:"agentic coding & reasoning",reasoning:!0},STEP_3_7_FLASH:{id:"stepfun/Step-3.7-Flash",inputModalities:["text","image"],provider:MR,spec:IR,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:MR,spec:IR,label:"Step 3.5 Flash",name:"Step 3.5 Flash",description:"fast sparse-MoE agentic reasoning",reasoning:!0,contextWindow:1e6},TENCENT_HY3:{id:"tencent/Hy3",inputModalities:["text"],provider:MR,spec:IR,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:MR,spec:IR,label:"Tencent Hy3",name:"Tencent Hy3",description:"sparse-MoE reasoning & agentic tool use",reasoning:!0,contextWindow:262144},GEMINI_3_7_FLASH:{id:"google/gemini-3.7-flash",inputModalities:["text","image"],provider:bR,spec:IR,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:vR,spec:IR,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:vR,spec:IR,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:vR,spec:IR,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:vR,spec:IR,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:vR,spec:IR,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:MR,spec:IR,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:MR,spec:IR,label:"Inkling",name:"Inkling",description:"multimodal MoE reasoning",reasoning:!0,contextWindow:256e3},INKLING_SMALL:{id:"thinkingmachines/inkling-small",inputModalities:["text","image"],provider:MR,spec:IR,label:"Inkling Small",name:"Inkling Small",description:"lightweight MoE reasoning at lower cost and latency",reasoning:!0,contextWindow:1e6},OX_ALPHA:{id:"stealth/ox-alpha",inputModalities:["text","image"],provider:bR,spec:IR,label:"Ox Alpha",name:"Ox Alpha",description:"long-horizon coding, agentic work & visual context",vendorLabel:"Stealth",badge:"free",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1048576,maxOutputTokens:131072},LAGUNA_S_2_1_FREE:{id:"poolside/laguna-s-2.1-free",inputModalities:["text"],provider:MR,spec:IR,label:"Laguna S 2.1",name:"Laguna S 2.1",description:"open-weight agentic coding and long-horizon work",badge:"free",reasoning:!0,contextWindow:256e3,maxOutputTokens:32768},LING_3_0_FLASH_FREE:{id:"inclusionai/ling-3.0-flash-free",inputModalities:["text"],provider:MR,spec:IR,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},MUSE_SPARK_1_1:{id:"meta/muse-spark-1.1",inputModalities:["text","image"],provider:vR,spec:IR,label:"Muse Spark 1.1",name:"Muse Spark 1.1",description:"agentic performance, tool use, and computer use",vendorLabel:"Meta",reasoning:!0,contextWindow:1048576},MUSE_SPARK_1_2:{id:"meta/muse-spark-1.2",inputModalities:["text","image"],provider:vR,spec:IR,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,contextWindow:1048576},MUSE_SPARK_1_2_CONTRIBUTOR:{id:"meta/muse-spark-1.2-contributor",inputModalities:["text","image"],provider:vR,spec:IR,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,contextWindow:1048576},GROK_4_5:{id:"xai/grok-4.5",inputModalities:["text","image"],provider:vR,spec:IR,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"],provider:vR,spec:IR,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}},LR=[{canonicalId:"zai-org/GLM-5",providers:{[vR]:"zai/glm-5",[wR]:"zai-org/GLM-5"}},{canonicalId:"zai-org/GLM-5.3",providers:{[TR]:"zai-org/glm-5.3"}},{canonicalId:"zai-org/GLM-5.2",providers:{[ER]:"glm-5.2",[vR]:"zai/glm-5.2"}},{canonicalId:"poolside/laguna-s-2.1-free",providers:{[vR]:"poolside/laguna-s-2.1-free"}},{canonicalId:"inclusionai/ling-3.0-flash-free",providers:{[vR]:"inclusionai/ling-3.0-flash-free"}},{canonicalId:"zai-org/GLM-5.2-Fast",providers:{[vR]:"zai/glm-5.2-fast"}},{canonicalId:"zai-org/GLM-5.1",providers:{[vR]:"zai/glm-5.1"}},{canonicalId:"moonshotai/Kimi-K3",providers:{[TR]:"moonshotai/kimi-k3",[vR]:"moonshotai/kimi-k3"}},{canonicalId:"moonshotai/Kimi-K2.5",providers:{[vR]:"moonshotai/kimi-k2.5",[wR]:"moonshotai/Kimi-K2.5",[kR]:"workers-ai/@cf/moonshotai/kimi-k2.5"}},{canonicalId:"moonshotai/Kimi-K2.6",providers:{[vR]:"moonshotai/kimi-k2.6",[wR]:"moonshotai/Kimi-K2.6",[kR]:"workers-ai/@cf/moonshotai/kimi-k2.6"}},{canonicalId:"moonshotai/Kimi-K2.7-Code",providers:{[ER]:"kimi-k2.7-code",[vR]:"moonshotai/kimi-k2.7-code"}},{canonicalId:"moonshotai/Kimi-K2.7-Code-Highspeed",providers:{[vR]:"moonshotai/kimi-k2.7-code-highspeed"}},{canonicalId:"MiniMaxAI/MiniMax-M2.5",providers:{[vR]:"minimax/minimax-m2.5",[wR]:"MiniMaxAI/MiniMax-M2.5"}},{canonicalId:"deepseek/deepseek-v4-pro",providers:{[vR]:"deepseek/deepseek-v4-pro"}},{canonicalId:"deepseek/deepseek-v4-flash",providers:{[vR]:"deepseek/deepseek-v4-flash",[PR]:"morph-dsv4flash"}},{canonicalId:"deepseek/deepseek-v4-flash-vision-exp",providers:{[vR]:"deepseek/deepseek-v4-flash-vision-exp"}},{canonicalId:"Qwen/Qwen3.6-Max-Preview",providers:{[vR]:"alibaba/qwen-3.6-max-preview"}},{canonicalId:"Qwen/Qwen3.6-Plus",providers:{[ER]:"qwen3.6-plus",[vR]:"alibaba/qwen3.6-plus"}},{canonicalId:"Qwen/Qwen3.7-Max",providers:{[ER]:"qwen3.7-max",[vR]:"alibaba/qwen3.7-max"}},{canonicalId:"Qwen/Qwen3.7-Plus",providers:{[ER]:"qwen3.7-plus",[vR]:"alibaba/qwen3.7-plus"}},{canonicalId:"Qwen/Qwen3.8-Max",providers:{[ER]:"qwen3.8-max",[vR]:"alibaba/qwen3.8-max"}},{canonicalId:"Qwen/Qwen3.8-27B",providers:{[vR]:"alibaba/qwen3.8-27b"}},{canonicalId:"Qwen/Qwen3.7-Flash",providers:{[vR]:"alibaba/qwen3.7-flash"}},{canonicalId:"MiniMaxAI/MiniMax-M3",providers:{[vR]:"minimax/minimax-m3"}},{canonicalId:RR,providers:{[vR]:"minimax/minimax-m3"}},{canonicalId:"MiniMaxAI/MiniMax-M2.7",providers:{[vR]:"minimax/minimax-m2.7"}},{canonicalId:"stepfun/Step-3.7-Flash",providers:{[vR]:"stepfun/step-3.7-flash"}},{canonicalId:"stepfun/Step-3.5-Flash",providers:{[bR]:"stepfun/step-3.5-flash"}},{canonicalId:"gpt-5.6-sol",providers:{[vR]:"openai/gpt-5.6-sol"}},{canonicalId:"gpt-5.6-terra",providers:{[bR]:"openai/gpt-5.6-terra"}},{canonicalId:"gpt-5.6-luna",providers:{[bR]:"openai/gpt-5.6-luna"}},{canonicalId:"stealth/ox-alpha",providers:{[bR]:"stealth/ox-alpha"}},{canonicalId:"tencent/Hy3",providers:{[bR]:"tencent/hy3:free"}},{canonicalId:"tencent/hy3-paid",providers:{[vR]:"tencent/hy3"}},{canonicalId:"xiaomi/mimo-v2.5-pro",providers:{[vR]:"xiaomi/mimo-v2.5-pro"}},{canonicalId:"xiaomi/mimo-v2.5",providers:{[vR]:"xiaomi/mimo-v2.5"}},{canonicalId:"google/gemini-3.7-flash",providers:{[bR]:"google/gemini-3.7-flash"}},{canonicalId:"google/gemini-3.6-flash",providers:{[vR]:"google/gemini-3.6-flash"}},{canonicalId:"google/gemini-3.5-flash",providers:{[vR]:"google/gemini-3.5-flash"}},{canonicalId:"google/gemini-3.5-flash-lite",providers:{[vR]:"google/gemini-3.5-flash-lite"}},{canonicalId:"google/gemini-3.1-flash-lite",providers:{[vR]:"google/gemini-3.1-flash-lite"}},{canonicalId:"nvidia/nemotron-3-ultra-550b-a55b",providers:{[vR]:"nvidia/nemotron-3-ultra-550b-a55b"}},{canonicalId:"thinkingmachines/inkling",providers:{[vR]:"thinkingmachines/inkling"}},{canonicalId:"thinkingmachines/inkling-small",providers:{[vR]:"thinkingmachines/inkling-small"}},{canonicalId:"sakana/fugu-ultra",providers:{[vR]:"sakana/fugu-ultra"}},{canonicalId:"xai/grok-4.5",providers:{[vR]:"xai/grok-4.5"}},{canonicalId:"xai/grok-4.6",providers:{[vR]:"xai/grok-4.6"}},{canonicalId:"meta/muse-spark-1.1",providers:{[vR]:"meta/muse-spark-1.1"}},{canonicalId:"meta/muse-spark-1.2",providers:{[vR]:"meta/muse-spark-1.2"}},{canonicalId:"meta/muse-spark-1.2-contributor",providers:{[vR]:"meta/muse-spark-1.2-contributor"}}],DR="2026-08-16T16:00:00Z",NR=[{startHourUtc:1,endHourUtc:4},{startHourUtc:6,endHourUtc:10}],$R=[{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:["zai"],providers:{zai:{slug:"zai",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{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:DR,peakWindowsUtc:NR,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-flash",order:["deepseek"],providers:{deepseek:{slug:"deepseek",promptCost:.14,completionCost:.28,cacheReadCost:.0028,timeOfDay:{effectiveFrom:DR,peakWindowsUtc:NR,peak:{promptCost:.44,completionCost:1.32,cacheReadCost:.014},offPeak:{promptCost:.22,completionCost:.66,cacheReadCost:.007}}},fireworks:{slug:"fireworks",promptCost:.14,completionCost:.28,cacheReadCost:.03}}},{canonicalId:"deepseek/deepseek-v4-flash-vision-exp",gatewaySlug:"deepseek/deepseek-v4-flash-vision-exp",order:["deepseek"],providers:{deepseek:{slug:"deepseek",promptCost:.22,completionCost:.66,cacheReadCost:.01,timeOfDay:{effectiveFrom:DR,peakWindowsUtc:NR,peak:{promptCost:.44,completionCost:1.32,cacheReadCost:.02},offPeak:{promptCost:.22,completionCost:.66,cacheReadCost:.01}}}}},{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-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:RR,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.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-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:"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:"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:"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}}}],_R=[{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}],FR=[{canonicalId:"deepseek/deepseek-v4-flash",slug:"morph-dsv4flash",promptCost:.14,completionCost:.28,cacheReadCost:.0028,timeOfDay:{effectiveFrom:DR,peakWindowsUtc:NR,peak:{promptCost:.44,completionCost:1.32,cacheReadCost:.014},offPeak:{promptCost:.22,completionCost:.66,cacheReadCost:.007}}}],UR=[{canonicalId:"stepfun/Step-3.5-Flash",openrouterSlug:"stepfun/step-3.5-flash",order:["parasail","deepinfra","siliconflow"],providers:{parasail:{slug:"parasail",promptCost:.1,completionCost:.3,cacheReadCost:.02,zdr:!0,noTraining:!0},deepinfra:{slug:"deepinfra",promptCost:.1,completionCost:.3,cacheReadCost:.02,zdr:!0,noTraining:!0},siliconflow:{slug:"siliconflow",promptCost:.1,completionCost:.3,zdr:!0,noTraining:!0}}},{canonicalId:"stealth/ox-alpha",openrouterSlug:"stealth/ox-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:"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:.75,completionCost:3.75,cacheReadCost:.075,cacheWriteCost:.04167,zdr:!0,noTraining:!0}}}],jR={"claude-sonnet-4-20250514":OR.SONNET_4_6.id,"claude-sonnet-4-5-20250929":OR.SONNET_4_6.id,"claude-opus-4-5-20251101":OR.OPUS_4_7.id,"claude-opus-4-6":OR.OPUS_4_7.id,"claude-haiku-4-5":OR.HAIKU_4_5.id},BR=OR.DEEPSEEK_V4_FLASH.id,WR={[yR]:"Anthropic",[SR]:"OpenAI",[wR]:"Open Source",[vR]:"Open Source",[CR]:"Open Source"},HR=["Open Source","Stealth","Anthropic","OpenAI","Google"],GR={"command-code":{id:"command-code",label:"Command Code",shortLabel:"cmd",description:"recommended",supportedModelProviders:[yR,SR,CR,wR,vR,bR],requiresAuth:!1,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!0},anthropic:{id:"anthropic",label:"Anthropic",shortLabel:"anth",description:"Claude Pro/Max",supportedModelProviders:[yR],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!1},"github-copilot":{id:"github-copilot",label:"GitHub Copilot",shortLabel:"copilot",description:"Copilot subscription",supportedModelProviders:[yR,SR],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!0},codex:{id:"codex",label:"OpenAI ChatGPT/Codex",shortLabel:"openai",description:"ChatGPT Pro/Plus subscription",supportedModelProviders:[SR],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(OR).filter(e=>!e.hidden),n=[];for(const r of Object.values(GR)){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 VR=buildModelGroups("co"),zR=buildModelGroups("normal");function formatColoredUserSuffix(e){return isGenericUserName(e)?"":formatUserSuffix(e).replace(e,bt.cyan(e))}function getStartedLine(){return`${bt.dim("Run")} ${bt.cyan(getBinaryCommand())} ${bt.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),a=r?` with ${bt.cyan(r)}`:"",i=[`${bt.green(pt.tick)} ${bt.bold("Logged in")}${s}${a}`];return o&&i.push(` ${bt.yellow(pt.warning)} ${bt.yellow(o)}`),i.push("",`${bt.dim("API key stored in")} ${bt.cyan(`~/.commandcode/${n}`)}`,getStartedLine()),i.join("\n")}function formatAlreadyLoggedInStyled(e){const t=formatColoredUserSuffix(e);return[`${bt.green(pt.tick)} ${bt.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"),Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),Ht();var KR=[{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 KR.find(t=>t.id===e)}function builtinPackageForSpecifier(e){return builtinProviderPackage(e)??KR.find(t=>t.package===e)}__name(builtinProviderPackage,"builtinProviderPackage"),__name(builtinPackageForSpecifier,"builtinPackageForSpecifier");var qR=new Map;function isProviderWorkspaceDevMode(){return"local"===getApiEnv()}function workspaceDistEntry(e){const t=e.replace(/^@[^/]+\//,"").replace(/^cmd-/,""),o=r(m(import.meta.url)),a=s(o,n("../..",t,"dist","index.js"));return I(a)?a:void 0}function devWorkspaceProviderEntry(e){if(isProviderWorkspaceDevMode())return workspaceDistEntry(e)}__name(isProviderWorkspaceDevMode,"isProviderWorkspaceDevMode"),__name(workspaceDistEntry,"workspaceDistEntry"),__name(devWorkspaceProviderEntry,"devWorkspaceProviderEntry");var YR=__name(async e=>{const t=builtinProviderPackage(e.moduleId);if(!t)return;const n=qR.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(p(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&&qR.set(e.moduleId,s),s},"realLoader");function loadBuiltinProviderModule(e){return YR(e)}async function loadInstalledBuiltinProviderModules(){const e=KR.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(p(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(p(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 JR=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:sv});async function providerAuthHeaders(e){return JR.providerAuthHeaders(e)}async function hasProviderCredential(e){return JR.hasProviderCredential(e)}async function providerLogin(e){return JR.login(e)}async function providerLogout(e){return JR.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=_o[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(bt.yellow(` ${e}`)),console.log()}function printLoginLink(e){console.log(),console.log(bt.dim(" Login: ")+createOSC8Link(e,"Open auth page ↗")),console.log()}async function openAuthPage(e,t){await Tt(e,t).catch(()=>{console.log(bt.dim(` Could not auto-open browser. Open: ${e}`))})}async function confirmOpenAfterCode(){const e=await Ke({message:"Press Enter to open GitHub and paste the code there.",active:"Open",inactive:"Cancel",initialValue:!0});if(qe(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)?bt.dim(" (copied)"):"";console.log(` ${bt.yellow("Logging into Copilot, use this code:")} ${bt.bold(t)}${n}`),console.log()}async function performProviderAuth(e){const{provider:t}=e,n=getProviderDisplayName(t);try{let e=!0;const r=t===ro.COPILOT;if(!r){const t=await Ke({message:`Open browser to sign in with ${n}?`,initialValue:!0});if(qe(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(` ${bt.dim(pt.circleFilled)} ${bt.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 Ye({message:t.prompt.label,mask:"*"});if(qe(e)||!String(e).trim())throw new Error("No authorization code provided");return{code:String(e).trim()}}console.log(` ${bt.dim(pt.circleFilled)} ${bt.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 QR=__name(({message:e})=>ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.CYAN},ot.createElement(vt,{type:"dots"})),ot.createElement(Qe,null," ",e)),"LoadingIndicator"),XR=__name(({message:e})=>ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.GREEN},pt.tick),ot.createElement(Qe,null," ",e)),"SuccessIndicator"),ZR=__name(({children:e})=>ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,null," "),ot.createElement(Je,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"),He.intro(heading({text:"Command Code Authentication"}))}function showLoginCancelMessage(e){Ge(`${pt.cross} ${e}`)}function printMessage(e){console.log(""),console.log(e),console.log("")}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=et(ot.createElement(nR,{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 eO=__name(({env:e,onComplete:t})=>{const[n,r]=at("checking"),[o,s]=at(null);return lt(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),lt(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),ot.createElement(ZR,null,"checking"===n&&ot.createElement(QR,{message:"Checking authentication status..."}),"logged_in"===n&&ot.createElement(XR,{message:"Authenticated"}),"not_logged_in"===n&&ot.createElement(XR,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=et(ot.createElement(eO,{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||(Ge(`${pt.cross} Login failed: ${e.error}`),process.exit(1)),Ve(bt.green(`${pt.tick} ${e.message}`)),process.exit(0)}await runLogin(),process.exit(0)}catch(e){isUserCancellation(e)&&process.exit(0),console.error(`${pt.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(performProviderLogin,"performProviderLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction");var tO=new je("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:bo})}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()})}Ht(),Qx(),__name(performLogout,"performLogout"),__name(performProviderLogout,"performProviderLogout"),__name(readLogoutUserName,"readLogoutUserName");var nO=__name(({userName:e})=>{const t=e?`Logging out ${e}...`:"Logging out...";return ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.CYAN},ot.createElement(vt,{type:"dots"})),ot.createElement(Qe,null," ",t))},"LoadingIndicator"),rO=__name(({userName:e,wasAuthenticated:t})=>{const n=!1===t?"Not currently authenticated":formatLogoutSuccess(e);return ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.GREEN},pt.tick),ot.createElement(Qe,null," ",n))},"SuccessIndicator"),oO=__name(({errorMessage:e})=>ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.RED},pt.cross),ot.createElement(Qe,{color:nI.RED}," Logout failed: ",e)),"ErrorIndicator"),sO=__name(({status:e,errorMessage:t,userName:n,wasAuthenticated:r})=>"loading"===e?ot.createElement(nO,{userName:n}):"success"===e?ot.createElement(rO,{userName:n,wasAuthenticated:r}):ot.createElement(oO,{errorMessage:t}),"StatusDisplay"),aO=__name(({onComplete:e,userName:t})=>{const[n,r]=at("loading"),[o,s]=at(""),[a,i]=at(null);return lt(()=>{performLogout().then(e=>{i(e),e.success?r("success"):(s(e.error||"Unknown error"),r("error"))})},[]),lt(()=>{if(("success"===n||"error"===n)&&a){const t=setTimeout(()=>e(a),100);return()=>clearTimeout(t)}},[n,a,e]),ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,null," "),ot.createElement(Je,null,ot.createElement(sO,{status:n,errorMessage:o,userName:t,wasAuthenticated:a?.wasAuthenticated})))},"LogoutSpinner");function printWarnings(e){0!==e.length&&(console.warn(bt.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(bt.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}=et(ot.createElement(aO,{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(`${pt.cross} ${e.error}`),process.exit(1)),console.log(`${pt.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 iO=new je("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=Pt("Checking authentication status...").start();try{const e=getApiEnv(),n=await checkAuthStatus(e);n.error&&(t.fail(bt.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(t.fail(bt.red("Not authenticated")),console.log(""),console.log(`${bt.dim("Run")} ${bt.cyan(`${getBinaryCommand()} auth login`)} ${bt.dim("to authenticate.")}`),console.log(""),process.exit(1));const r=isGenericCommandAuthUserName(n.userName)?"":` as ${bt.cyan(n.userName)}`;t.succeed("Authentication verified"),console.log(`${bt.green(pt.tick)} ${bt.bold("Authenticated")}${r}`),console.log(` ${bt.dim("Provider:")} ${bt.cyan("Command Code")}`),n.fromEnv&&console.log(` ${bt.dim("Source:")} ${bt.cyan(`$${bo}`)} ${bt.dim("(env var)")}`),console.log(""),process.exit(0)}catch(e){t.fail(bt.red(`Status check failed: ${e instanceof Error?e.message:"Unknown error"}`)),process.exit(1)}}Ht(),Qx(),__name(checkAuthStatus,"checkAuthStatus"),__name(buildStatusJson,"buildStatusJson"),__name(statusAction,"statusAction");var lO=new je("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 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 Be("--scope <scope>","Configuration scope").choices(["effective","user","project"]).default("effective")).option("--json","Print machine-readable JSON")}new je("auth").description("Manage authentication with Command Code").addCommand(tO).addCommand(iO).addCommand(lO),Ht(),Qx(),__name(parseValue,"parseValue"),__name(rowValue,"rowValue"),__name(rowMatchesScope,"rowMatchesScope"),__name(printValue,"printValue"),__name(unknownKeyMessage,"unknownKeyMessage"),__name(createRegistry,"createRegistry"),__name(withCommonOptions,"withCommonOptions");var cO=withCommonOptions(new je("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})`)}),dO=withCommonOptions(new je("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)}),uO=withCommonOptions(new je("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 a=await o.get({id:s});let i;a||r.error(unknownKeyMessage(o,e)),rowMatchesScope(a,n.scope)||r.error(`${s} cannot be written in ${n.scope} scope. It is a ${a.scope}-scope setting - use --scope ${a.scope}.`);try{i=await o.set({id:s,value:parseValue(t)})}catch(e){r.error(e instanceof Error?e.message:String(e))}const l={id:i.id,previousValue:i.previousValue,newValue:i.newValue,scope:n.scope,liveSessionReloaded:!1,liveSessionReloadsOnNextRound:!0};n.json?printValue(l,!0):(console.log(`${i.id}: ${JSON.stringify(i.previousValue)} -> ${JSON.stringify(i.newValue)} (${n.scope})`),console.log("A running session picks this up at the start of its next round."))}),mO=new je("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 a;s||n.error(unknownKeyMessage(r,e)),void 0===s.defaultValue&&n.error(`${o} has no default value to reset to.`);try{a=await r.set({id:o,value:s.defaultValue})}catch(e){n.error(e instanceof Error?e.message:String(e))}const i={id:a.id,previousValue:a.previousValue,newValue:a.newValue,scope:s.scope,liveSessionReloaded:!1,liveSessionReloadsOnNextRound:!0};t.json?printValue(i,!0):(console.log(`${a.id}: ${JSON.stringify(a.previousValue)} -> ${JSON.stringify(a.newValue)} (default, ${s.scope})`),console.log("A running session picks this up at the start of its next round."))}),pO=new je("config").description("Inspect and update validated configuration settings").addCommand(cO).addCommand(dO).addCommand(uO).addCommand(mO);async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Pt("Opening the GitHub issue…").start();try{await Tt(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("")}}Ht(),Qx(),__name(openGitHubIssue,"openGitHubIssue");var gO=new je("feedback").alias("issue").description("Report a bug or share feedback — opens a GitHub issue").argument("[title]","Optional issue title").action(openGitHubIssue);Ht();var hO=new je("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});Ht(),Ht(),Qx(),Ht(),Qx();var fO=__name(({icon:e,label:t,children:n})=>ot.createElement(Qe,null,ot.createElement(Qe,{color:nI.CYAN},e," "),ot.createElement(Qe,{color:nI.DIM},t.padEnd(12)),n),"Row"),yO=__name(({title:e})=>ot.createElement(Qe,null,ot.createElement(Qe,{color:nI.GRAY},"───"),ot.createElement(Qe,{color:nI.WHITE}," ",e," "),ot.createElement(Qe,{color:nI.GRAY},"─".repeat(35))),"Header"),SO=__name(({title:e,marginTop:t=0,children:n})=>ot.createElement(Je,{flexDirection:"column",marginTop:t},ot.createElement(yO,{title:e}),ot.createElement(Je,{flexDirection:"column",paddingY:1},n)),"Section"),wO=__name(({host:e,systemInfo:t})=>ot.createElement(SO,{title:"System Information"},ot.createElement(fO,{icon:pt.bullet,label:"Version"},ot.createElement(Qe,{color:nI.GREEN},t.version)),ot.createElement(fO,{icon:pt.bullet,label:"Date"},ot.createElement(Qe,null,formatDate())),ot.createElement(fO,{icon:pt.pointer,label:"Platform"},ot.createElement(Qe,{color:nI.GREEN},t.os),ot.createElement(Qe,{color:nI.DIM}," ","(",e.platform,", ",e.arch,")")),ot.createElement(fO,{icon:pt.triangleUp,label:"Hostname"},ot.createElement(Qe,null,e.hostname)),ot.createElement(fO,{icon:pt.bullet,label:"User"},ot.createElement(Qe,{color:nI.YELLOW},e.username)),ot.createElement(fO,{icon:pt.bullet,label:"CPUs"},ot.createElement(Qe,{color:nI.MAGENTA},e.cpus.length," cores")),ot.createElement(fO,{icon:pt.bullet,label:"Memory"},ot.createElement(Qe,{color:nI.CYAN},e.totalMemoryGb," GB")),ot.createElement(fO,{icon:pt.play,label:"Uptime"},ot.createElement(Qe,null,formatUptime(e.uptimeSeconds))),ot.createElement(fO,{icon:pt.arrowRight,label:"Home"},ot.createElement(Qe,{color:nI.DIM},e.homeDir)),ot.createElement(fO,{icon:pt.pointer,label:"Shell"},ot.createElement(Qe,null,t.shell)),ot.createElement(fO,{icon:pt.bullet,label:"Node"},ot.createElement(Qe,{color:nI.GREEN},e.nodeVersion)),ot.createElement(fO,{icon:pt.pointer,label:"Terminal"},ot.createElement(Qe,{color:nI.CYAN},t.terminal)),ot.createElement(fO,{icon:pt.bullet,label:"IDE"},ot.createElement(Qe,null,t.ide))),"SystemInfoSection"),vO=__name(({cpus:e})=>ot.createElement(SO,{title:"CPU Details",marginTop:1},e.map((e,t)=>ot.createElement(fO,{key:t,icon:pt.bullet,label:`Core ${t}`},ot.createElement(Qe,null,e.model),ot.createElement(Qe,{color:nI.YELLOW}," @ ",e.speedMHz," MHz")))),"CPUDetailsSection"),kO=__name(({addresses:e})=>ot.createElement(SO,{title:"Network",marginTop:1},e.map((e,t)=>ot.createElement(fO,{key:`${e.interfaceName}-${t}`,icon:pt.bullet,label:e.interfaceName},ot.createElement(Qe,{color:nI.GREEN},e.address)))),"NetworkSection"),CO=__name(({host:e,verbose:t,systemInfo:n})=>ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,null,"System Information"),ot.createElement(Qe,null,"─".repeat(40)),ot.createElement(Qe,null,"Version ",n.version),ot.createElement(Qe,null,"Date ",formatDate()),ot.createElement(Qe,null,"Platform ",n.os," (",e.platform,", ",e.arch,")"),ot.createElement(Qe,null,"Hostname ",e.hostname),ot.createElement(Qe,null,"User ",e.username),ot.createElement(Qe,null,"CPUs ",e.cpus.length," cores"),ot.createElement(Qe,null,"Memory ",e.totalMemoryGb," GB"),ot.createElement(Qe,null,"Uptime ",formatUptime(e.uptimeSeconds)),ot.createElement(Qe,null,"Home ",e.homeDir),ot.createElement(Qe,null,"Shell ",n.shell),ot.createElement(Qe,null,"Node ",e.nodeVersion),ot.createElement(Qe,null,"Terminal ",n.terminal),ot.createElement(Qe,null,"IDE ",n.ide),t&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,null,"\n","CPU Details"),ot.createElement(Qe,null,"─".repeat(40)),e.cpus.map((e,t)=>ot.createElement(Qe,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speedMHz," MHz")),ot.createElement(Qe,null,"\n","Network"),ot.createElement(Qe,null,"─".repeat(40)),e.externalIpv4.map((e,t)=>ot.createElement(Qe,{key:`${e.interfaceName}-${t}`},e.interfaceName.padEnd(12),e.address)))),"PlainTextInfo"),bO=__name(({host:e,verbose:t,systemInfo:n})=>ot.createElement(Je,{flexDirection:"column"},ot.createElement(wO,{host:e,systemInfo:n}),t&&ot.createElement(vO,{cpus:e.cpus}),t&&ot.createElement(kO,{addresses:e.externalIpv4})),"StyledInfo"),EO=__name(({verbose:e=!1,text:t=!1,systemInfo:n})=>{const{exit:r}=nt();lt(()=>{const e=setTimeout(()=>r(),50);return()=>clearTimeout(e)},[r]);const o=ct(()=>collectHostDiagnostics(),[]);return t?ot.createElement(CO,{host:o,verbose:e,systemInfo:n}):ot.createElement(bO,{host:o,verbose:e,systemInfo:n})},"InfoUI");async function runInfo(e){await applyStartupTheme();const t=getSystemInfo(),{waitUntilExit:n}=et(ot.createElement(EO,{verbose:e.verbose,text:e.text,systemInfo:t}));await n()}__name(runInfo,"runInfo");var TO=new je("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)}`}Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),Ht(),Ht(),__name(formatUsd,"formatUsd");var PO=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatShortDateUtc(e){const t=PO[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 MO={"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}function getDisplayRates(e,t=Date.now()){const n=MO[e];if(n)return n;const r=Object.values(xR).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}};const o=$R.find(t=>t.canonicalId===e);if(o)return toDisplayRates(advertisedBandOf(primaryUpstreamOf(o,e),t));const s=UR.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 a=_R.find(t=>t.canonicalId===e);if(a)return{inputCost:a.promptCost,outputCost:a.completionCost,cacheReadCost:a.cacheReadCost};const i=FR.find(t=>t.canonicalId===e);if(i)return{inputCost:i.promptCost,outputCost:i.completionCost,cacheReadCost:i.cacheReadCost};throw new Error(`display-pricing: unknown billing id "${e}" — not in MODELS, GATEWAY_MODEL_PRICING, OPENROUTER_MODEL_PRICING, ALIBABA_MODEL_PRICING, or MORPH_MODEL_PRICING`)}function toDisplayRates(e){return{inputCost:e.promptCost,outputCost:e.completionCost,cacheReadCost:e.cacheReadCost??0,...null!=e.cacheWriteCost&&{cacheWriteCost:e.cacheWriteCost}}}function getDisplayTimeOfDay(e){if(MO[e])return;const t=$R.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,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 $R){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(OR).find(t=>t.id===e)}function getModelNotice(e){const t=findModelById(e);if(!t?.notice)return;const n=t.vendorLabel??WR[t.provider]??"the upstream provider";return t.notice.replaceAll("{name}",t.name).replaceAll("{vendor}",n)}function getProviderFromModel(e){return findModelById(e)?.provider??yR}function getAllModelOptions(){return Object.values(OR)}function getModelGroupLabel(e){return e.vendorLabel??WR[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[...HR.filter(e=>t.has(e)),...[...t.keys()].filter(e=>!HR.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")}__name(advertisedBandOf,"advertisedBandOf"),__name(primaryUpstreamOf,"primaryUpstreamOf"),__name(getDisplayRates,"getDisplayRates"),__name(toDisplayRates,"toDisplayRates"),__name(getDisplayTimeOfDay,"getDisplayTimeOfDay"),__name(timeOfDayNote,"timeOfDayNote"),__name(timeOfDayScheduledChanges,"timeOfDayScheduledChanges"),timeOfDayScheduledChanges(),Ht(),__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");var xO=/[-@]\d{8}$/,IO="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=(jR[e.toLowerCase()]??e).toLowerCase(),n=Object.values(OR).find(e=>e.id.toLowerCase()===t);if(n)return n.id;const r=LR.find(e=>ossEntryMatches(e,t));return r?.canonicalId}function getCanonicalModelId(e){if(!e)return e;const t=e.startsWith(IO)?e.slice(IO.length):e,n=tryResolveCanonical2(t);if(n)return n;const r=t.replace(xO,"");return r===t?t:tryResolveCanonical2(r)??t}function getModelDisplayName(e){const t=getCanonicalModelId(e),n=Object.values(OR).find(e=>e.id===t);return n?.name??e}__name(ossEntryMatches,"ossEntryMatches"),__name(tryResolveCanonical2,"tryResolveCanonical"),__name(getCanonicalModelId,"getCanonicalModelId"),__name(getModelDisplayName,"getModelDisplayName"),Ht(),Qx();var AO=null;function setRegisteredProviderModules(e){AO=new Set(e.modules.map(e=>e.id))}function isProviderLaneRegistered(e){const t=AO;if(!t)return!0;if(!Fo[e.providerId]?.requiresAuth)return!0;const n=sv[e.providerId]??e.providerId;return t.has(n)}function isProviderLaneListable(e){if(!Fo[e.providerId]?.requiresAuth)return!0;const t=sv[e.providerId]??e.providerId,n=builtinProviderPackage(t);return!(!n||!1===n.discoverable)||(AO?.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 RO=getPackageJson(import.meta.url),OO="string"==typeof RO.version&&RO.version.trim()?RO.version:"unknown",LO=new Set(Object.values(sv));function selectActiveOAuthProviderModules(e){const t=e.provider?sv[e.provider]:void 0;return e.modules.filter(e=>!LO.has(e.id)||e.id===t)}async function restoreSelectedOAuthProviderModule(e){if(!e.provider)return;if(e.disabled)return;const t=sv[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}=e.usage;return(n*t.inputCost+r*t.outputCost+o*t.cacheReadCost+s*(t.cacheWriteCost??0))/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),a=[...o??[...await loadInstalledBuiltinProviderModules()]].filter(e=>!s.has(e.id)),i=(await loadUserConfig({runtime:t,path:legacyUserConfigPath({runtime:t})})).provider,l=i?sv[i]: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:a,provider:i,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 'cmd login ${l}' to install or repair it.`:"";throw new Error(`Could not restore the ${i} provider package for your saved login. ${e instanceof Error?e.message:String(e)}${t?` ${t}`:""}`,{cause:e})}const u=selectActiveOAuthProviderModules({modules:a,provider:i});return o&&setRegisteredProviderModules({modules:a}),createNodeHarnessSession({...e,runtime:t,configStore:r,cliVersion:e.cliVersion??OO,providerModules:u,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 DO=createHarnessSessionManager({createSession:createHarnessSession}),NO=DO.getHarnessForSession,$O=DO.getResolvedHarness,_O=DO.forgetHarnessSession,FO=DO.disposeAllHarnessSessions,UO=new Set;function onHarnessSessionRebuild(e){return UO.add(e),()=>UO.delete(e)}async function rebuildHarnessSession(e){try{await($O(e)?.flush())}catch{}_O(e);const t=[];for(const n of UO){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 jO=null,BO=null,WO=[],HO=null,GO=!1;async function loadFromConfig(){const e=await loadProvidersConfig({runtime:createNodeRuntime()});return WO=e.warnings,HO=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 jO||(diskLoadsBlocked()?jO=[]:loadIntoCache())}function loadIntoCache(){return BO??=loadFromConfig().then(e=>(jO=e,e)).catch(()=>jO=[]),BO}async function refreshCustomProviderModels(e){if(diskLoadsBlocked())return jO??=[],{providers:jO,changed:!1};const t=null!==jO?HO:null;jO=null,BO=null;const n=await loadIntoCache();null!==t&&t!==HO&&(GO=!0);const r=GO;return GO&&e?.sessionId&&(await rebuildHarnessSession(e.sessionId),GO=!1),{providers:n,changed:r}}function seedSnapshotSync(){if(null===jO&&!process.env.VITEST)try{const e=M.readFileSync(`${W()}/.commandcode/providers.json`,"utf8"),t=parseProvidersConfig(JSON.parse(e));WO=t.warnings,HO=JSON.stringify({providers:t.providers,disabled:t.disabledProviderIds}),jO=t.providers.map(e=>({id:e.id,name:e.name??e.id,models:e.models}))}catch{}}function getCustomProviderModelsSync(){return jO||(seedSnapshotSync(),jO||(loadCustomProviderModels(),[]))}function getCustomProviderWarningsSync(){return WO}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 a=s.models.find(e=>e.id.toLowerCase()===o.toLowerCase());return a?{modelId:`${s.id}/${a.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){const t=getCustomProviderModelsSync(),n=findQualified(t,e);return n?n.providerId:resolveKnownModelId2(e)?void 0: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 a=o.modelId.startsWith(`${s.id}/`)?o.modelId.slice(s.id.length+1):o.modelId;return s.models.find(e=>e.id===a)}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"),Ht(),Ht(),Ht(),Qx(),Ht(),Ht();var VO=__name(({label:e="Loading",spinner:t=!1})=>ot.createElement(Qe,{color:nI.DIM},t&&ot.createElement(ot.Fragment,null,ot.createElement(vt,{type:"dots"})," "),e,"…"),"LoadingLine"),zO=__name(({children:e,glyph:t=!0})=>ot.createElement(Qe,{color:nI.RED},t&&`${pt.cross} `,e),"ErrorLine"),KO=__name(({children:e,glyph:t=!0})=>ot.createElement(Qe,{color:nI.GREEN},t&&`${pt.tick} `,e),"SuccessLine"),qO=__name(({title:e="Oops, something went wrong:",children:t})=>ot.createElement(Je,{flexDirection:"column",borderStyle:"single",borderColor:nI.RED,paddingX:2,paddingY:1,marginTop:1},ot.createElement(Qe,{color:nI.RED,bold:!0},e),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,null,t))),"ErrorPanel"),YO=__name(({message:e,hint:t})=>ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.GRAY},e),t?ot.createElement(Qe,{color:nI.DIM},t):null),"EmptyState"),JO=__name(({error:e,traceId:t})=>ot.createElement(Je,{marginBottom:2},ot.createElement(qO,null,e,t&&ot.createElement(Qe,{color:nI.DIM},"\n\n","Trace ID: ",t))),"ErrorSection");async function runTasteImport(e={}){const t=await runOnboardingImportWithEvents({events:am,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}))}}Ht(),Ht(),Qx(),Ht(),Qx(),__name(runTasteImport,"runTasteImport");var QO={isImporting:!1,waitingForInput:!1,error:null},XO=__name(e=>{const t=it(null),n=it(e);n.current=e;const[r,o]=at({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null}),s=dt(()=>{const e=t.current;!e||e.isAborted()||(e.finishCancelled(),o(e=>({...e,...QO})))},[]);return lt(()=>{const e=createOnboardingImportLifecycle({events:am});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,...QO}));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");Ht();var ZO,eL,tL=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{tt((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");function getRuntime(){return ZO??=createNodeRuntime()}function getStore(){return eL??=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")}Ht(),Qx(),Ht(),Qx(),__name(getRuntime,"getRuntime"),__name(getStore,"getStore"),__name(checkOnboardingConditions2,"checkOnboardingConditions"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(markOnboardingSkipped2,"markOnboardingSkipped"),__name(dismissOnboardingForeverForProject,"dismissOnboardingForeverForProject"),__name(triggerTasteOnboarding,"triggerTasteOnboarding");var nL=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=at(null),[o,s]=at(null),[a,i]=at(void 0),l=it(!1);return lt(()=>{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:xo.LEARN_TASTE_COMMAND,heading:"Onboarding conditions check failed"}});i(o),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,traceId:a,isLoading:!n&&!o}},"useOnboardingConditions");Ht(),Qx();var rL=__name(({conditions:e,autoLearn:t})=>{const[n,r]=at("checking"),o=it(!1);return lt(()=>{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]),lt(()=>{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{am.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{am.reset(),e()}}Ht(),Qx(),Ht(),Qx(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var oL=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=it(n),o=dt(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=dt(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),a=dt(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),i=dt(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=dt(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:a,handleErrorDismiss:i,handleSkip:l}},"useOnboardingHandlers");Ht(),Qx();var sL=__name(e=>{const[t,n]=at(()=>createTasteImportProjection({initialSteps:e})),r=dt(e=>{n(t=>({...t,importError:e}))},[]);return lt(()=>{const t=__name(()=>{n(resetTasteImportProjection({initialSteps:e}))},"handleReset"),r=__name(e=>{n(t=>reduceTasteImportEvent({state:t,event:e}))},"handleNewEvent");return am.on("reset",t),am.on("new-event",r),()=>{am.off("reset",t),am.off("new-event",r)}},[e]),{steps:t.steps,importError:t.importError,importTraceId:t.importTraceId,setImportError:r}},"useProgressEvents");Ht(),Ht(),Ht();var aL=__name(({isImporting:e=!1,waitingForInput:t=!1})=>ot.createElement(ot.Fragment,null,e&&ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"Esc to cancel")),t&&ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to continue"))),"HelpTextSection");Ht(),Ht(),Ht(),Ht();var iL=__name(()=>{const[e,t]=at(!0);return lt(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),ot.createElement(Qe,{color:nI.YELLOW},e?pt.circleFilled:pt.circle)},"PulsingDot");Ht();var lL=[pt.bullet,pt.squareSmallFilled,pt.lozenge,pt.star,pt.triangleRight,pt.triangleUp,pt.circleFilled,pt.pointer],cL=__name(e=>String(e).padStart(3," "),"padNum"),dL=__name(e=>lL[e%lL.length],"getSymbol"),uL=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${cL(t)} ↓${cL(n)} (↑↓ scroll)`,"buildStatusLine"),mL=__name(({insights:e})=>{const[t,n]=at(0),[r,o]=at(!0),s=e.length,a=s>10,i=Math.max(0,s-10),l=r&&a?i:t;if(tt((e,t)=>{if(a){if(t.upArrow)return o(!1),void n(Math.max(0,l-1));if(t.downArrow){const e=Math.min(i,l+1);o(e===i),n(e)}}}),0===s)return null;const c=e.slice(l,l+10),d=l,u=s-l-10;return ot.createElement(Je,{flexDirection:"column",marginLeft:4,marginBottom:0},a&&ot.createElement(Qe,{color:nI.DIM},uL(s,d,u,r)),c.map((e,t)=>{const n=l+t;return ot.createElement(Je,{key:n,marginBottom:0},ot.createElement(Qe,{color:nI.DIM},dL(n)," ",e))}))},"ScrollableInsights");function getLabelColor(e,t){return e?nI.WHITE:t?nI.YELLOW:nI.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 pL=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:a,isAllComplete:i,summary:l})=>{if(a)return ot.createElement(Je,{flexDirection:"column",marginBottom:0},ot.createElement(ZI,null),ot.createElement(Je,{marginTop:0},ot.createElement(Qe,{color:nI.DIM},YI),ot.createElement(Je,{marginLeft:2},i?ot.createElement(Qe,{color:oI.TEXT},"learned your coding taste"):ot.createElement(GI,null))));const c=__name(()=>r?ot.createElement(Qe,{color:lI.BG},pt.square):n?ot.createElement(iL,null):ot.createElement(Qe,{color:nI.DIM},pt.circle),"getStatusIcon"),d=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||d?ot.createElement(Je,{flexDirection:"column",marginBottom:0},(n||r)&&ot.createElement(Je,{marginBottom:0},ot.createElement(Je,{marginRight:1},c()),ot.createElement(Qe,{color:getLabelColor(r,n)},e)),r&&t&&(!l||0===l.learningCount)&&ot.createElement(Je,{marginLeft:3,marginBottom:0},ot.createElement(Qe,{color:nI.DIM},t)),o.length>0&&ot.createElement(Je,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map(e=>ot.createElement(Qe,{key:e,color:nI.DIM},`${pt.bullet} ${e}`))),s.length>0&&ot.createElement(mL,{insights:s}),r&&l&&l.learningCount>0&&ot.createElement(Je,{flexDirection:"column",marginLeft:1,marginBottom:0},ot.createElement(Je,{marginBottom:1,flexDirection:"row"},ot.createElement(Qe,null,YI),ot.createElement(Je,{marginLeft:2},ot.createElement(Qe,{color:oI.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",formatCategorySuffix(l.categories)))),ot.createElement(Je,{flexDirection:"column",marginLeft:1},ot.createElement(Qe,{color:nI.DIM},pt.pointerSmall," Stored in ",l.storage),ot.createElement(Qe,{color:nI.DIM},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),gL=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return ot.createElement(Je,{flexDirection:"column",marginBottom:1},e.map((e,n)=>ot.createElement(Je,{key:e.id,marginLeft:0===n?0:3},ot.createElement(pL,{label:e.label,message:e.message,active:e.active,complete:e.complete,items:e.items,insights:e.insights,summary:e.summary,isIntro:0===n,isAllComplete:t}))))},"StepsSection"),hL=__name(({steps:e})=>ot.createElement(gL,{steps:e}),"ProgressSection"),fL=__name(({onComplete:e,onCancel:t,onError:n,onErrorDismiss:r})=>{const{steps:o,importError:s,importTraceId:a}=sL(RM),{isImporting:i,waitingForInput:l,error:c,cancelImport:d}=XO(n);return tL({onEscape:__name(()=>{if(i)return d(),void t?.();l&&((c||s)&&r?r():e())},"onEscape"),onEnter:__name(()=>{l&&((c||s)&&r?r():e())},"onEnter"),enabled:i||l}),ot.createElement(Je,{flexDirection:"column",padding:1},s&&ot.createElement(JO,{error:s,traceId:a}),!s&&ot.createElement(hL,{steps:o}),ot.createElement(aL,{isImporting:i,waitingForInput:l}))},"ImportProgress");async function runLearnTaste(){await applyStartupTheme();const{unmount:e}=et(ot.createElement(fL,{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 yL=new je("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(ip),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:xo.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 je("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 Be("-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(gt.gray("Checking server authentication requirements..."));const t=await checkCommandMcpServerAuthRequirements(e);return t.requiresAuth&&console.log(gt.cyan("Server requires OAuth authentication.")),t},"checkServerAuthRequirements"),registerOAuthClient:__name(async e=>(console.log(gt.gray("Registering OAuth client...")),registerCommandMcpOAuthClient({registrationEndpoint:e.registrationEndpoint,clientName:e.clientName,redirectUris:[...e.redirectUris]})),"registerOAuthClient"),performOAuthFlow:__name(async e=>{console.log(gt.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},{onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),onStatus:__name(e=>{console.log(gt.gray(` ${e}`))},"onStatus")});for(const e of s.warnings)console.log(gt.yellow(`Warning: ${e}`));"success"===s.authStatus&&console.log(gt.green("✓ Successfully authenticated")),"failed"===s.authStatus&&(console.log(gt.yellow(`Warning: Authentication failed: ${s.authError}`)),console.log(gt.gray(`You can retry with: ${getBinaryCommand()} mcp auth ${e}`)),console.log(gt.gray("Or authenticate via the /mcp menu in a session")));const a="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?gt.yellow(a):gt.green(a)),console.log(gt.gray(` ${formatMcpCommandSummary(s.serverConfig)}`)),console.log(""),console.log(gt.cyan("Next steps:")),console.log(gt.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 rE)if(console.error(gt.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(gt.gray(`Usage: ${t.cliName} mcp add --transport stdio <name> -- <command> [args...]`)),void console.error(gt.gray(` or: ${t.cliName} mcp add <name> <command> [args...]`))):void("stdio-command-is-url"!==e.code?"insecure-oauth-url"===e.code&&(console.error(gt.gray("OAuth requires https:// (http:// is only allowed for loopback hosts: localhost, 127.0.0.1, [::1]).")),console.error(gt.gray("Switch the URL to https:// or use a non-OAuth server."))):e.suggestedCommand&&console.error(gt.gray(`Did you mean: ${e.suggestedCommand}`)));console.error(gt.gray(`Usage: ${t.cliName} mcp add --transport http <name> <url>`))}else console.error(gt.gray("Valid options: stdio, http"));else console.error(gt.gray(nE));else console.error(gt.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(gt.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function addJsonMcpCommand(){const e=new je("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 Be("-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(gt.cyan("Starting OAuth authentication...")),console.log(gt.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},{port:e.port,onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),onStatus:__name(e=>{console.log(gt.gray(` ${e}`))},"onStatus")});"success"===o.authStatus&&console.log(gt.green(`\n✓ Successfully authenticated with '${e}'`)),"failed"===o.authStatus&&(console.error(gt.yellow(`\nWarning: Authentication failed: ${o.authError}`)),console.error(gt.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(gt.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?gt.yellow(s):gt.green(s)),console.log(gt.gray(` ${formatMcpCommandSummary(o.serverConfig)}`)),console.log(""),console.log(gt.cyan("Next steps:")),console.log(gt.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 rE)if(console.error(gt.red(`Error: ${e.message}`)),"invalid-name"!==e.code){if("invalid-json"===e.code)return console.error(gt.gray("Make sure to quote the JSON string properly")),void console.error(gt.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(gt.gray(` ${t.path.join(".")}: ${t.message}`));else"missing-http-url"!==e.code&&e.code}else console.error(gt.gray(nE));else console.error(gt.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function authMcpCommand(){const e=new je("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(gt.red("Error: Server name is required")),console.error(gt.gray(`Usage: ${n} mcp auth <server>`)),console.error(gt.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(gt.green(`✓ Cleared authentication for '${e}'`)):void console.log(gt.yellow(`No authentication stored for '${e}'`));console.log(gt.cyan(`Authenticating with '${e}'...`)),console.log(gt.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},{onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),discoverAndAuthenticate:discoverAndAuthenticateCommandMcpServer,onStatus:__name(e=>{console.log(gt.gray(` ${e}`))},"onStatus")}),console.log(gt.green(`\n✓ Successfully authenticated with '${e}'`)),console.log(gt.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(gt.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=t.expired?gt.yellow("expired"):gt.green("valid");console.log(` ${t.serverName}: ${e}`)}console.log("")}else console.log(gt.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(gt.yellow(`Authentication for '${e}' has expired`)),void(t.hasRefreshToken&&console.log(gt.gray(" A refresh token is available for re-authentication")));console.log(gt.green(`Authentication for '${e}' is valid`)),"number"==typeof t.expiresInMinutes&&console.log(gt.gray(` Expires in ${t.expiresInMinutes} minutes`)),t.scope&&console.log(gt.gray(` Scopes: ${t.scope}`))}else console.log(gt.yellow(`No authentication stored for '${e}'`))}function printMcpAuthError(e,t){if(e instanceof rE)return"server-not-found"===e.code?(console.error(gt.red(`Error: ${e.message}`)),void console.error(gt.gray(`Use "${t.cliName} mcp list" to see configured servers`))):"auth-failed"===e.code?(console.error(gt.red(`\nError: ${e.message}`)),void(t.serverName&&console.log(gt.gray(`Try again with "${t.cliName} mcp auth ${t.serverName}"`)))):void console.error(gt.red(`Error: ${e.message}`));console.error(gt.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function getMcpCommand(){const e=new je("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(gt.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${gt.dim("Scope:")} ${r}`),console.log(` ${gt.dim("Transport:")} ${n.transport}`),console.log(` ${gt.dim("Status:")} ${n.enabled?gt.green("enabled"):gt.gray("disabled")}`),"http"===n.transport){if(console.log(` ${gt.dim("URL:")} ${n.url}`),t.headers.length>0){console.log(` ${gt.dim("Headers:")}`);for(const e of t.headers)console.log(` ${e.key}: ${e.value}`)}}else console.log(` ${gt.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${gt.dim("Args:")} ${n.args.join(" ")}`);if(t.env.length>0){console.log(` ${gt.dim("Environment:")}`);for(const e of t.env)console.log(` ${e.key}=${e.value}`)}console.log("")}catch(e){e instanceof rE&&(console.error(gt.red(`Error: ${e.message}`)),process.exit(1)),console.error(gt.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function formatAuthIcon(e){return"authenticated"===e||"static"===e?gt.green(pt.tick):"missing"===e?gt.red(pt.cross):gt.gray("-")}function listMcpCommand(){const e=new je("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(gt.yellow("\nNo MCP servers configured\n")),console.log(gt.gray("Add a server with:")),console.log(gt.gray(` ${getBinaryCommand()} mcp add --transport http <name> <url>`)),console.log(gt.gray(` ${getBinaryCommand()} mcp add --transport stdio <name> -- <command>`)),void console.log(gt.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(gt.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(gt.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.enabled?gt.green("enabled"):gt.gray("disabled"),s=formatAuthIcon(o.authStatus);console.log(` ${gt.white(o.name.padEnd(t))} ${gt.cyan(o.transport.padEnd(n))} ${gt.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(gt.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(gt.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new je("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Be("-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(gt.green(`✓ Removed MCP server '${e}' from ${n.scopeLabel} config`))}catch(e){e instanceof rE&&(console.error(gt.red(`Error: ${e.message}`)),process.exit(1)),console.error(gt.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new je("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=a(t,e);if(n&&!n.startsWith("..")&&!i(n))return n}const n=a(W(),e);return!n||n.startsWith("..")||i(n)?e:`~${l}${n}`}Ht(),Ht(),Qx(),Ht(),Qx(),__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),__name(addMcpCommand,"addMcpCommand"),__name(printMcpAddError,"printMcpAddError"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),__name(printCollectError,"printCollectError"),Ht(),Qx(),__name(addJsonMcpCommand,"addJsonMcpCommand"),__name(printMcpAddJsonError,"printMcpAddJsonError"),Ht(),Qx(),__name(authMcpCommand,"authMcpCommand"),__name(printAuthList,"printAuthList"),__name(printAuthStatus,"printAuthStatus"),__name(printMcpAuthError,"printMcpAuthError"),Ht(),Qx(),__name(getMcpCommand,"getMcpCommand"),Ht(),Qx(),__name(formatAuthIcon,"formatAuthIcon"),__name(listMcpCommand,"listMcpCommand"),Ht(),Qx(),__name(removeMcpCommand,"removeMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Ht(),Ht(),Qx(),Ht(),Qx(),__name(shortenModPath,"shortenModPath");var SL=__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(bt.dim(`Installing ${t.kind} mod source ${bt.reset(bt.cyan(e))} (${r})…`));const o=await installModSource({runtime:n,source:e,scope:r}),s=await createModPathShortener(n);console.log(`${bt.green(pt.tick)} Installed ${bt.cyan(o.identity)}`),o.installedPath&&console.log(bt.dim(` ${s(o.installedPath)}`)),console.log(bt.dim(` Recorded in ${s(o.settingsPath)}`))}catch(e){console.error(`${bt.red(pt.cross)} ${SL(e instanceof Error?e.message:String(e))}`),process.exit(1)}}__name(createModPathShortener,"createModPathShortener"),__name(addAction,"addAction");var wL=new je("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);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 KR.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}]}Ht(),Qx(),Ht(),Ht(),Qx(),__name(providerMod,"providerMod"),__name(providerBuiltinMods,"providerBuiltinMods"),Ht(),Qx(),__name(updateNoticeMod,"updateNoticeMod"),__name(commandBuiltinMods,"commandBuiltinMods");var vL=__name((e,t,n)=>` ${bt.cyan(e)} ${bt.dim(`· ${t} · ${n}`)}`,"formatModLine"),kL=__name((e,t)=>`${bt.bold(bt.white(e))} ${bt.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}),a=new Set(r.disabled),i=await modsDirectoryPath({runtime:t,scope:"project"}),l=await modsDirectoryPath({runtime:t,scope:"user"}),c=i?s(i,"..",".."):void 0,d=["project","user","package","path"].flatMap(e=>r.entries.filter(t=>t.source===e));console.log(""),console.log(`${bt.bold(bt.white("Mods"))} ${bt.dim(`(${r.entries.length})`)}`),0===r.entries.length&&(console.log(""),console.log(bt.dim(" No mods loaded. Looking in:")),i&&console.log(bt.dim(` ${shortenModPath(i,c)} ${bt.white("(project)")}`)),l&&console.log(bt.dim(` ${shortenModPath(l,void 0)} ${bt.white("(user)")}`)),console.log(""),console.log(bt.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(vL(e.name,scopeFor({entry:e,sources:o}),detailFor({entry:e,sources:o,projectRoot:c,disabled:a})));if(!0===e.builtin){const e=commandBuiltinMods();console.log(""),console.log(kL("Built-in",e.length));for(const t of e)console.log(vL(t.name,"builtin",a.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(kL("Package sources",t.length));for(const e of t){u.add(e.source);const t=e.installed?bt.yellow("installed, but provides no mods"):bt.yellow(`not installed — run \`${getBinaryCommand()} mods update\``);console.log(vL(e.identity,e.scope,t))}}}const m=r.warnings.filter(e=>!u.has(e.path));if(m.length>0){console.log(""),console.log(`${bt.bold(bt.yellow("Warnings"))} ${bt.dim(`(${m.length})`)}`);for(const e of m)console.log(` ${bt.cyan(shortenModPath(e.path,c))} ${bt.dim(`· ${e.reason}`)}`)}console.log("")}__name(scopeFor,"scopeFor"),__name(detailFor,"detailFor"),__name(listAction,"listAction");var CL=new je("list").alias("ls").description("List the mods a session loads, and where each one comes from").addOption(new Be("--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 Tt(o);const a=await createModPathShortener(t);console.log(`${bt.green(pt.tick)} Opened ${bt.cyan(a(o))} ${bt.dim(`· ${s}`)}`)}catch(e){console.error(`${bt.red(pt.cross)} ${SL(e instanceof Error?e.message:String(e))}`),process.exit(1)}}Ht(),Qx(),__name(openAction,"openAction");var bL=new je("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(`${bt.red(pt.cross)} ${bt.cyan(e)} is a built-in mod — it cannot be removed. Add it to ${bt.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(`${bt.yellow(pt.warning)} ${bt.cyan(o.target)} is not configured (${o.scope} scope) — nothing to remove`);const s=await createModPathShortener(n);console.log(`${bt.green(pt.tick)} Removed ${bt.cyan(o.target)} ${bt.dim(`· ${o.scope}`)}`),o.sourceIdentity&&o.sourceIdentity!==o.target&&console.log(bt.dim(` Removed its source ${o.sourceIdentity}`)),o.alsoRemoved&&o.alsoRemoved.length>0&&console.log(bt.dim(` That source also provided ${o.alsoRemoved.join(", ")}`)),o.removedPath&&console.log(bt.dim(` Deleted ${s(o.removedPath)}`)),o.removedFromSettings&&o.settingsPath&&console.log(bt.dim(` Updated ${s(o.settingsPath)}`))}catch(e){console.error(`${bt.red(pt.cross)} ${SL(e instanceof Error?e.message:String(e))}`),process.exit(1)}}Ht(),Qx(),__name(removeAction,"removeAction");var EL=new je("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(`${bt.green(pt.tick)} ${bt.cyan(e)}`);for(const e of t.failures)console.error(`${bt.red(pt.cross)} ${e.source} ${bt.dim(`· ${e.reason}`)}`);0===t.updated.length&&0===t.failures.length&&console.log(bt.dim("No mod package sources configured.")),t.failures.length>0&&process.exit(1)}Ht(),Qx(),__name(updateAction,"updateAction");var TL=new je("update").alias("up").description("Reinstall and reconcile every configured mod package").action(updateAction),PL=new je("mods").description("Manage mods — loadable extensions from npm, git, or local paths").addCommand(wL).addCommand(EL).addCommand(CL).addCommand(TL).addCommand(bL);function resolveBundledRipgrepPath(){try{const e=wt(import.meta.url),{rgPath:t}=e("@vscode/ripgrep");if("string"==typeof t&&t.length>0&&I(t))return t}catch{}}function registerBundledRipgrep(){if(process.env[Ml])return;const e=resolveBundledRipgrepPath();void 0!==e&&(process.env[Ml]=e)}Ht(),Qx(),__name(resolveBundledRipgrepPath,"resolveBundledRipgrepPath"),__name(registerBundledRipgrep,"registerBundledRipgrep"),Ht(),Qx(),Ht();var ML=["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!!ML.some(e=>r.includes(`write ${e}`))||"write"===("string"==typeof t.syscall?t.syscall:"")&&ML.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=$O(e.sessionId),a=s?s.getEffort():r;return t!==r&&await setReasoningEffort({modelId:n,effort:t}),t!==a&&(s?.recordEffortChange({model:n,effort:t}),hardResetForResize(),e.setStaticKey(e=>e+1)),void e.setFeed(e=>[...e,lg(`Reasoning effort set to ${t}.`)])}if(r.length>0)return void e.setFeed(e=>[...e,lg(`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,lg(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=it(!1);return dt(async e=>{const o=processBracketedPaste(e),s=n??t,a=__name(async()=>{r.current=!1;const e=await detectClipboardText();e?s(e):o.cleanedContent&&s(o.cleanedContent)},"applyPastedText");if(!o.isPasteStart||r.current)r.current&&!o.isPasteEnd||(r.current&&o.isPasteEnd?await a():t(e));else{if(r.current=!0,!o.isPasteEnd)return;await a()}},[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"),Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),__name(handleEffortCommand,"handleEffortCommand"),__name(applyEffortSetting,"applyEffortSetting"),Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),__name(usePasteAwareChange,"usePasteAwareChange"),__name(extractDeviceCode2,"extractDeviceCode");var xL=__name(({providerId:e,onSuccess:t,onCancel:n,onFailure:r})=>{const o=getProviderDisplayName(e),[s,a]=at("confirm"),[i,l]=at(""),[c,d]=at(""),[u,m]=at(""),[p,g]=at(""),[h,f]=at(null),y=it(!1),S=it(!0),w=it(!1),v=it(null),k=it(null),C=it(null),b=it(!1);lt(()=>()=>{S.current=!1,v.current&&clearTimeout(v.current),C.current=null},[]);const E=dt(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;Tt(e.authUrl,t).catch(()=>{S.current&&f(`Failed to open browser. Please manually open: ${e.authUrl}`)})},300))},[]),T=dt(async t=>{if(!S.current)return;if(l(t.url),t.prompt)return d(t.instructions),b.current=!0,m(t.prompt.label),a("paste"),E({authUrl:t.url,keepTerminalActive:!1}),new Promise(e=>{k.current=e});b.current=!1;const n=e===ro.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 a("open-browser"),new Promise(e=>{C.current=()=>{C.current=null,a("waiting"),Tt(t.url).catch(()=>{S.current&&f(`Failed to open browser. Please manually open: ${t.url}`)}),e({})}})},[e,E]),P=it(()=>{});P.current=()=>{providerLogin({provider:e,onPending:T}).then(async()=>{S.current&&(await persistProviderSelection(e),a("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();a("error")})};const M=dt(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(tt((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 a("connecting"),void P.current();"n"!==e&&"N"!==e||n()}"open-browser"===s&&t.return&&C.current?.()}else n()}),"confirm"===s){const t=e===ro.COPILOT?"This will get a GitHub sign-in code.":`This will open your browser to sign in with ${o}.`;return ot.createElement(ZA,{title:`Sign in to ${o}`,subtitle:t,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"y"),"/",ot.createElement(GA,null,"enter")," ","continue"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"n"),"/",ot.createElement(GA,null,"esc")," ","cancel")]})})}return"connecting"===s?ot.createElement(ZA,{title:`Sign in to ${o}`,subtitle:"Getting sign-in code…",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," cancel")]})}):"paste"===s?ot.createElement(ZA,{title:`Sign in to ${o}`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," submit"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," cancel")]})},i&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM},"Login: "),ot.createElement(BI,{url:i,text:"Open auth page ↗",color:nI.CYAN})),c&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM},c)),h&&ot.createElement(Je,{marginBottom:1},ot.createElement(zO,null,h)),ot.createElement(Je,null,ot.createElement(Qe,null,u||"Authorization code",": "),ot.createElement(TextInput,{mask:"*",focus:!0,value:p,onChange:x,onSubmit:I,placeholder:"Paste code here..."}))):"open-browser"===s?ot.createElement(ZA,{title:`Sign in to ${o}`,subtitle:e===ro.COPILOT?"Press enter to open GitHub and paste the code there":"Press enter to open your browser",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," cancel")]})},c&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{bold:!0,color:nI.GREEN},c)),i&&e!==ro.COPILOT&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM},"Login: "),ot.createElement(BI,{url:i,text:"Open auth page ↗",color:nI.CYAN}))):"waiting"===s?ot.createElement(ZA,{title:`Sign in to ${o}`,subtitle:"Waiting for authorization…",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," cancel")]})},c&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{bold:!0,color:nI.GREEN},c)),i&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM},"Open: "),ot.createElement(BI,{url:i,text:"Open auth page ↗",color:nI.CYAN}))):"error"===s?ot.createElement(ZA,{title:`Sign in to ${o}`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," back")]})},ot.createElement(zO,null,h)):null},"ProviderAuth");function makeProviderAuthComponent(e){const t=__name(({onSuccess:t,onCancel:n})=>ot.createElement(xL,{providerId:e,onSuccess:t,onCancel:n}),"Bound");return t.displayName=`ProviderAuth(${e})`,t}__name(makeProviderAuthComponent,"makeProviderAuthComponent");var IL=Object.fromEntries(Object.entries(Fo).map(([e,t])=>[e,{...t}]));function getProviderConfig(e){return IL[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:a,setShowModelNotification:i,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?$O(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,lg(e.message)])}a.current&&clearTimeout(a.current),i(!0),a.current=setTimeout(()=>{i(!1),a.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,lg(`Unknown model "${n}" — opening the model picker so you can choose.`)]),void e.setShowModelSelector(!0);r.warning&&e.setFeed(e=>[...e,lg(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&&(cA(),hardResetForResize(),r(e=>e+1)),n(buildThemeStatusMessage(e))}catch{n(yo)}}function handleThemeCancel({setShowThemeSelector:e}){e(!1)}async function handleThemeCommand(e,t){const n=t.trim().toLowerCase();n?Xr.includes(n)?await handleThemeSelect({theme:n,setShowThemeSelector:e.setShowThemeSelector,setStatus:e.setStatus,setStaticKey:e.setStaticKey}):e.setFeed(e=>[...e,lg(`Unknown theme "${n}". Options: ${Xr.join(", ")}.`)]):e.setShowThemeSelector(!0)}async function applyThemeSetting(e){const t=e.trim().toLowerCase();return t?Xr.includes(t)?(await setCliTheme({theme:t}),{ok:!0,message:`Theme set to ${t}.`}):{ok:!1,message:`Unknown theme "${e.trim()}". Options: ${Xr.join(", ")}.`}:{ok:!1,message:"Provide a theme, e.g. --theme auto."}}IL.anthropic&&(IL.anthropic.authComponent=makeProviderAuthComponent(ro.ANTHROPIC),IL.anthropic.checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:ro.ANTHROPIC});return!!e}),IL["github-copilot"]&&(IL["github-copilot"].authComponent=makeProviderAuthComponent(ro.COPILOT),IL["github-copilot"].checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:ro.COPILOT});return!!e}),IL.codex&&(IL.codex.authComponent=makeProviderAuthComponent(ro.CODEX),IL.codex.checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:ro.CODEX});return!!e}),__name(getProviderConfig,"getProviderConfig"),__name(getProviderAuthState,"getProviderAuthState"),__name(handleModelSelect,"handleModelSelect"),__name(handleModelCancel,"handleModelCancel"),__name(handleModelCommand,"handleModelCommand"),__name(applyModelSetting,"applyModelSetting"),Ht(),Qx(),__name(handleThemeSelect,"handleThemeSelect"),__name(handleThemeCancel,"handleThemeCancel"),__name(handleThemeCommand,"handleThemeCommand"),__name(applyThemeSetting,"applyThemeSetting");var AL=[{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")}],RL=__name(e=>`--${e.key} <${e.valueHint}>`,"flagSpecOf"),OL=AL.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=AL.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");var LL=getPackageJson(import.meta.url),DL=__name((e,t=[])=>[...t,e],"collectAddDir"),NL=__name((e,t=[])=>[...t,e],"collectConfig");function displayCustomHelp(){const e=LL.version,t=getInvokedCommandName(),n=getVisibleSlashCommands();console.log(),console.log(gt.bold("Command Code")+gt.gray(` v${e}`)),console.log(gt.gray(Hs)),console.log(),console.log(gt.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(gt.bold("Options"));for(const e of Ys){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Gs)+gt.gray(e.description))}console.log(),console.log(gt.bold("Commands"));for(const e of Qs){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Gs)+gt.gray(e.description))}console.log(),console.log(gt.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Gs)+gt.gray(e.description));console.log(),console.log(gt.bold("Keyboard Shortcuts"));for(const e of qs)console.log(" "+e.key.padEnd(Gs)+gt.gray(e.description));console.log(),console.log(gt.bold("Examples"));for(const e of Zs){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Gs)+gt.gray(e.description))}console.log(),console.log(gt.cyan("❯")+" "+gt.gray(Vs.replace(/cmd/,t))),console.log(),console.log(gt.bold("Links"));for(const e of Xs)console.log(" "+e.key.padEnd(Gs)+gt.cyan(e.description));console.log()}function createProgram(){const e=new je;e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(LL.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 Be("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Be("--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 Be("--auto-accept","Start in auto-accept mode").implies({permissionMode:"auto-accept"})).addOption(new Be("--permission-mode <mode>","Set permission mode").choices(["default","standard","plan","auto-accept","dont-ask"])).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 ${Bs}); interactive mode sets the /goal turn budget (default 100)`,e=>{const t=parseInt(e,10);if(isNaN(t)||t<1)throw new We("--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",DL,[]).addOption(new Be("--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",zs).option("--no-auto-update","Disable automatic background updates for this run").option("--add-dir <directory>","Add directory to workspace context",DL,[]).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)",DL,[]).option("--mod-option <name=value>","Set a mod-declared flag value (repeatable)",DL,[]).option("--skill <path>","Load extra skills from a path (a skill directory or a directory of skills); repeatable",DL,[]).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 Be("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Be("--experimental","Enable experimental features").hideHelp()).addOption(new Be("-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 Be("--local","Use local server").hideHelp()).addOption(new Be("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption();for(const t of OL)e.option(RL(t),t.description);return e.option("--config <key=value>","Set a setting headlessly, e.g. --config theme=dark (repeatable)",NL),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram");var $L=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!==$L&&(recordError({span:$L,error:sanitizeErrorForTelemetry({error:e,label:"command_error"})}),$L.end(),$L=null)}function abandonPendingCommandSpan(){null!==$L&&($L.setAttribute("cmd.command.outcome","abandoned"),$L.end(),$L=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 a=t.args;a.length>0&&dlog(`[cmd] arguments: ${a.join(" ")}`);const i=commandPath(t);if(!i)return;const l=flagNames(t);$L=createSpan({name:`command:${i}`,attributes:{"cmd.command.name":i,"cmd.command.arg_count":a.length,...l?{"cmd.command.args":l}:{}}})}),e.hook("postAction",()=>{dlogSection("Done"),null!==$L&&(endSpan({span:$L,status:"success"}),$L=null)})}__name(commandPath,"commandPath"),__name(flagNames,"flagNames"),__name(failPendingCommandSpan,"failPendingCommandSpan"),__name(abandonPendingCommandSpan,"abandonPendingCommandSpan"),__name(setupCommanderHooks,"setupCommanderHooks");var{red:_L,yellow:FL,dim:UL}=gt;function printErrorDetails(e,t){if(console.log(`${Mt.error} ${_L(t)}`),console.log(`${Mt.error} ${_L("ERROR →")} ${e.name}`),console.log(`${Mt.info} ${_L("REASON →")} ${e.message}`),console.log(`${Mt.info} ${_L("ERROR STACK ↓ \n")} ${e.stack}\n`),!isTelemetryInitialized())return;const n=getDisplayTraceId();console.log(`${Mt.info} ${UL(`Trace ID: ${n}`)}`),console.log(`${UL(" Share this ID with support to help debug your issue.")}\n`)}__name(printErrorDetails,"printErrorDetails");var jL=__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(`${Mt.warning} ${FL(t)}\n`),r&&printErrorDetails(n,t),!o)return!1;process.exit(0)}},"handleError");function handleStdoutError(e){if(!isBenignStreamWriteError(e))throw e;process.exit(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:xo.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),jL({heading:Et`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:xo.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),jL({heading:Et`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(handleStdoutError,"handleStdoutError"),__name(handleStderrError,"handleStderrError"),__name(handleUnhandledErrors,"handleUnhandledErrors"),Ht(),Qx(),Ht(),Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),Ht();var BL=pt.pointer,WL=__name(({isSelected:e,backgroundColor:t})=>ot.createElement(Qe,{color:e?YA:QA,backgroundColor:t,bold:e&&isLightTheme()},e?BL:" "),"OverlayCaret"),HL=__name(({isSelected:e,isActive:t,idleColor:n=JA,backgroundColor:r,children:o})=>ot.createElement(Qe,{color:e?YA:t?XA:n,backgroundColor:r,bold:e&&isLightTheme()},o),"OverlayOptionText"),GL=__name(({isSelected:e,label:t})=>ot.createElement(HL,{isSelected:e}," ",t),"OverlayOptionItem"),VL=__name(({backgroundColor:e})=>ot.createElement(Qe,{color:XA,backgroundColor:e}," ",pt.tick),"OverlayActiveTick"),zL=__name(({indent:e=4,children:t})=>ot.createElement(Qe,{color:KA}," ".repeat(e),t),"OverlayOptionDescription"),KL=__name(({isSelected:e,idleColor:t=nI.GRAY,selectedColor:n=nI.WHITE,bold:r,children:o})=>ot.createElement(Qe,{color:e?n:t,backgroundColor:e?TI:void 0,bold:r??e},o),"OverlayBarText"),qL=__name(({isSelected:e,label:t})=>ot.createElement(KL,{isSelected:e}," ",t," "),"OverlayBarItem"),YL=__name(()=>null,"OverlayBarIndicator");Ht();var JL=createOSC8Link("https://commandcode.ai/docs/permissions#permission-modes","Docs ↗",!1),QL=__name(({hint:e})=>ot.createElement(Qe,{italic:!0,color:nI.DIM},e," · Run ",ot.createElement(Qe,{color:nI.WHITE},"cmd --yolo")," to bypass all permissions (",JL,")"),"PermissionFooter"),XL=__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 ot.createElement(ZA,{title:"Tool Permission",subtitle:ot.createElement(Qe,{wrap:"wrap"},"Command Code needs to run ",ot.createElement(Qe,{color:YA},e.toolName),"."),footer:ot.createElement(QL,{hint:"↑/↓ navigate · enter select"})},e.risk&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{bold:!0,color:nI.RED,wrap:"wrap"},pt.warning," ",getRiskDisplay(e.risk))),e.description&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM,italic:!0},e.description)),ot.createElement(SelectInput,{items:r.map((e,t)=>({label:`${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:n,indicatorComponent:WL,itemComponent:GL}))},"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?YI:JI).join("\n")}Ht(),Qx(),Ht(),Qx(),Ht(),__name(buildTreeConnectors,"buildTreeConnectors");var ZL=Ct()?"⟳":"*",eD=" │ ";function DiffWordSegments({segments:e,type:t,paired:n,dimDiff:r,language:o,highlightOptions:s}){const a="removed"===t?iI.REMOVED_HIGHLIGHT_BG:iI.ADDED_HIGHLIGHT_BG,i=[];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?i.push(ot.createElement(Qe,{key:u,backgroundColor:a,dimColor:r},d)):n?i.push(ot.createElement(Qe,{key:u,color:nI.WHITE,dimColor:r},d)):i.push(ot.createElement(Qe,{key:u,color:"removed"===t?iI.REMOVED_TEXT:iI.ADDED_TEXT,dimColor:r},d))}return i}function DiffRow({background:e,prefix:t,wrap:n="wrap",children:r}){return ot.createElement(Je,{width:"100%",backgroundColor:e},ot.createElement(Je,{flexShrink:0},t),ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{wrap:n},r)))}function renderDiffLine({line:e,dimDiff:t,language:n,highlightOptions:r}){if("skip"===e.kind)return ot.createElement(Je,{key:e.key,width:"100%"},ot.createElement(Qe,{color:iI.LINE_NUM,dimColor:t},e.spacer,eD,e.label));if("context"===e.kind)return ot.createElement(DiffRow,{key:e.key,prefix:ot.createElement(Qe,{color:iI.LINE_NUM,dimColor:t}," "+e.lineNumberLabel+eD)},ot.createElement(Qe,{color:nI.WHITE,dimColor:t}," ",highlightSyntax(e.text,n,r)));const o="removed"===e.kind,s=o?iI.REMOVED_TEXT:iI.ADDED_TEXT,a=o?iI.REMOVED_BG:iI.ADDED_BG;return ot.createElement(DiffRow,{key:e.key,background:a,prefix:ot.createElement(Qe,null,ot.createElement(Qe,{color:s,dimColor:t}," "+e.lineNumberLabel),ot.createElement(Qe,{color:iI.LINE_NUM,dimColor:t},eD),ot.createElement(Qe,{color:s,dimColor:t},o?"- ":"+ "))},ot.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?ot.createElement(Qe,{color:nI.RED},"Rejected update to",ot.createElement(Qe,{color:nI.RED},` ${e.filePath}`)):ot.createElement(Qe,{color:nI.GRAY},"Updated"," ",ot.createElement(Qe,{color:nI.WHITE,bold:!0},e.filePath)," ","with"," ",e.additions>0&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:uI.SUCCESS},e.additions)," ","addition",1!==e.additions?"s":"",e.removals>0?" and ":""),e.removals>0&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:uI.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:a=1,dimDiff:i=!1,maxLines:l}){const c=projectEditDiffView({oldValue:e,newValue:t,filePath:n,permissionDenied:r,showMetadata:o,startLine:a,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:ot.createElement(Je,{flexDirection:"column"},ot.createElement(DiffMetadata,{metadata:c.metadata}),ot.createElement(Je,{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:i,language:u,highlightOptions:m})))),isTruncated:c.isTruncated,totalLines:c.totalLines}}function resolveTodoTextStyle(e){return"completed"===e?{textColor:uI.SUCCESS,strikethrough:!0}:"in_progress"===e?{textColor:uI.IN_PROGRESS,strikethrough:!1}:{textColor:nI.WHITE,strikethrough:!1}}function TodoChecklist({todos:e}){return ot.createElement(Je,{flexDirection:"column"},e.map((e,t)=>{const n="completed"===e.status?pt.checkboxOn:pt.checkboxOff,{textColor:r,strikethrough:o}=resolveTodoTextStyle(e.status),s="in_progress"===e.status&&e.activeForm?`${e.activeForm}…`:e.content;return ot.createElement(Je,{key:e.id||t,flexDirection:"row"},ot.createElement(Je,{width:2},ot.createElement(Qe,{color:r},n)),ot.createElement(Qe,{color:r,bold:"in_progress"===e.status,strikethrough:o},s))}))}function formatTodosForDisplay(e){const t=Lg(e);return t?ot.createElement(TodoChecklist,{todos:t}):ot.createElement(Qe,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 ot.createElement(BracketWrap,null,t?e:ot.createElement(Markdown,null,e))}function ReadToolInlineSummaryRow({summary:e}){return e?.dimText?ot.createElement(Qe,{dimColor:!0}," ",e.dimText):null}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:o}){if(e)return{symbolColor:nI.YELLOW,symbol:pt.arrowRight};if(t)return{symbolColor:nI.RED,symbol:pt.square};if(n)return{symbolColor:sI,symbol:"✻"};if(r&&o){const e=Lg(o),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?uI.SUCCESS:uI.WARNING,symbol:pt.square}}return{symbolColor:lI.BG,symbol:pt.square}}function ToolHeader({isThinking:e,isTasteFile:t,tasteCategory:n,name:r,summaryMatch:o,expandedOutput:s,expandKey:a,input:i,output:l}){if(e){const e=estimateReasoningSeconds(i||l||"");return ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:sI},`Thought for ${e} second${1!==e?"s":""}`," "),!s&&ot.createElement(BracketWrap,{color:nI.DIM},`${a}+o to expand`))}if(t)return ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:oI.BADGE_BG,color:oI.BADGE_FG,bold:!0},XI)),ot.createElement(Qe,null," ","Using your taste"," ",n?"package of ":"packages",n&&ot.createElement(Qe,{bold:!0},n)));let c=r;return"READ[n]"===r&&o&&(c=`READ[${Number(o[1])}]`),ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:lI.BG,color:lI.FG,bold:!0},`${QI}${c}${QI}`))}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?ot.createElement(Qe,{color:nI.GRAY},"Running (",s,")"):"interrupted"===e||n===Uf?ot.createElement(Qe,{color:nI.GRAY,wrap:"wrap"},"Interrupted"):"error"===e||t?ot.createElement(Qe,{color:nI.RED,wrap:"wrap"},n," (",s,")"):ot.createElement(ot.Fragment,null,ot.createElement(Qe,{wrap:"wrap"},"Done"),ot.createElement(Qe,{color:nI.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:a,remainingLines:i}=truncateToVisualLines({output:o,maxVisualLines:"Question"===t?$c:Dc,maxChars:"Question"===t?1/0:Wc}),l=a&&"Question"!==t;return{text:s,isTruncated:l,remainingLines:i,truncationMsg:l?i>0?ot.createElement(BracketedText,{text:`... +${i} lines [${r}+o to expand]`,color:nI.DIM}):ot.createElement(BracketedText,{text:`... [${r}+o to expand]`,color:nI.DIM}):null}}function renderTruncatedOutput({output:e,name:t,expandedOutput:n,expandKey:r}){const{text:o,isTruncated:s,truncationMsg:a}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r});return s?ot.createElement(ot.Fragment,null,o,"\n",a):o}function renderEditFileDiff({input:e,metadata:t,expandedOutput:n,isPermissionDenied:r,output:o,expandKey:s}){const a=n?void 0:_c,{diffContent:i,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:a}),d=c-_c;return ot.createElement(Je,{flexDirection:"column"},i,l&&ot.createElement(Je,{marginTop:1},ot.createElement(BracketedText,{text:`… (${d} more ${1===d?"line":"lines"}) [${s}+o to expand]`,color:nI.DIM})),r&&o&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.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()),a=projectWriteFileContentView({filePath:e,content:t.content,totalLines:t.totalLines,expandedOutput:n,expandKey:r});return a.empty?ot.createElement(Qe,{color:nI.GRAY},"Created"," ",ot.createElement(Qe,{color:nI.WHITE,bold:!0},a.filePath)," ","(empty file)"):ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.GRAY},"Created"," ",ot.createElement(Qe,{color:nI.WHITE,bold:!0},a.filePath)," ","(",a.totalLinesLabel,")"),ot.createElement(Je,{marginTop:1,flexDirection:"column"},a.visibleLines.map(e=>ot.createElement(DiffRow,{key:e.lineNumber,background:iI.ADDED_BG,wrap:"truncate-end",prefix:ot.createElement(Qe,null,ot.createElement(Qe,{color:iI.ADDED_TEXT}," "+e.lineNumberLabel),ot.createElement(Qe,{color:iI.LINE_NUM},eD))},ot.createElement(Qe,{color:iI.ADDED_TEXT},highlightSyntax(e.text,o,s))))),a.isTruncated&&a.moreLinesLabel&&ot.createElement(Je,{marginTop:1},ot.createElement(BracketedText,{text:a.expandHint?`… (${a.moreLinesLabel}) ${a.expandHint}`:`… (${a.moreLinesLabel})`,color:nI.DIM})))}function renderOutputContent({isTodos:e,isThinking:t,isEditFile:n,isWriteFile:r,metadata:o,output:s,expandedOutput:a,isPermissionDenied:i,input:l,hasError:c,name:d,expandKey:u,showTreeConnector:m,closesFrame:p}){if(e)return formatTodosForDisplay(s);if(t){if(!a)return null;const e=l||s;return ot.createElement(Je,{width:"100%",flexDirection:"column"},ot.createElement(Qe,null," "),ot.createElement(Qe,{color:sI,wrap:"wrap",italic:!0},e))}const g=p?YI:JI;if(n&&"string"==typeof o?.oldValue&&"string"==typeof o?.newValue){const e=renderEditFileDiff({input:l,metadata:o,expandedOutput:a,isPermissionDenied:i,output:s,expandKey:u});return m?ot.createElement(Je,{columnGap:1},ot.createElement(Qe,{color:EI},g," "),e):e}if(r&&o&&"content"in o){const e=renderWriteFileContent({input:l,metadata:o,expandedOutput:a,expandKey:u});return m?ot.createElement(Je,{columnGap:1},ot.createElement(Qe,{color:EI},g," "),e):e}return m?renderTextWithLongConnector({output:s,name:d,expandedOutput:a,expandKey:u,hasError:c,closesFrame:p}):ot.createElement(Je,{width:"100%"},ot.createElement(Qe,{color:c?nI.RED:"",wrap:"wrap"},renderTruncatedOutput({output:s,name:d,expandedOutput:a,expandKey:u})))}function renderTextWithLongConnector({output:e,name:t,expandedOutput:n,expandKey:r,hasError:o,closesFrame:s}){const{text:a,isTruncated:i,truncationMsg:l}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}),c=o?nI.RED:void 0,d=buildTreeConnectors(a,{isTruncated:i,closesFrame:s}),u=s?YI:JI;return ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(Je,{columnGap:1,width:"100%"},ot.createElement(Qe,{color:EI},d),ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:c,wrap:"wrap"},a))),i&&ot.createElement(Je,{columnGap:1},ot.createElement(Qe,{color:EI},u," "),l))}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:a=!1}){const i="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=!i&&!l&&!m,f="ctrl",y=!0===s?.isAgent,S=computeDisplayInput({input:t,isAgent:y,isShell:"SHELL"===e,expandedOutput:a}),w=!i&&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||i&&t)&&!m&&(!y||x)&&(!u||o)),{symbolColor:A,symbol:R}=resolveSymbol({isPending:r,hasError:o,isThinking:i,isTodos:l,output:n}),O=s?.preHookLines,L=s?.postHookLines,D=Boolean(O?.length),N=Boolean(L?.length),$=Boolean(s?.hookOutcome),_=r&&!y&&!$,F=!$&&!_,U=I&&!N&&!$&&!_,j=D&&!I&&!N&&!$&&!_;return ot.createElement(Je,null,i&&ot.createElement(Qe,{color:A},R),ot.createElement(Je,{flexDirection:"column",marginLeft:i?1:0},ot.createElement(Je,null,ot.createElement(ToolHeader,{isThinking:i,isTasteFile:m,tasteCategory:p,name:M,summaryMatch:T,expandedOutput:a,expandKey:f,input:t,output:n}),w&&ot.createElement(Qe,null," ",formatToolInput({input:S,isShell:"SHELL"===e})),ot.createElement(ReadToolInlineSummaryRow,{summary:P}),E>0&&ot.createElement(Qe,{dimColor:!0},` ${ZL}${E>1?` ${E}`:""}`)),y&&("running"===v||n)&&ot.createElement(Je,{columnGap:1,marginLeft:h?1:0},h&&ot.createElement(Qe,{color:EI},YI," "),ot.createElement(AgentStatus,{agentStatus:v,hasError:o,output:n,elapsedSeconds:C,tokensUsed:k})),ot.createElement(HookLines,{lines:O,showTreeConnector:h,closesFrame:j}),I&&renderOutputWithRepairNotes({output:x?stripAgentUsageTrailer(n??""):n??"",isTodos:l,isThinking:i,isEditFile:c,isWriteFile:d,metadata:s,expandedOutput:a||x,isPermissionDenied:g,input:t,hasError:o,name:e,expandKey:f,showTreeConnector:h,closesFrame:U}),ot.createElement(HookLines,{lines:L,showTreeConnector:h,closesFrame:F}),ot.createElement(HookOutcome,{outcome:s?.hookOutcome,showTreeConnector:h}),_&&ot.createElement(Je,{columnGap:1,marginLeft:1},ot.createElement(Qe,{color:EI},YI," "),ot.createElement(Qe,{color:nI.GRAY},"Processing…"))))}function renderOutputWithRepairNotes({output:e,isTodos:t,isThinking:n,isEditFile:r,isWriteFile:o,metadata:s,expandedOutput:a,isPermissionDenied:i,input:l,hasError:c,name:d,expandKey:u,showTreeConnector:m,closesFrame:p}){const{body:g}=extractRepairNotes(e);return ot.createElement(Je,{marginLeft:m?1:0},renderOutputContent({isTodos:t,isThinking:n,isEditFile:r,isWriteFile:o,metadata:s,output:g,expandedOutput:a,isPermissionDenied:i,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 ot.createElement(Je,{flexDirection:"column",marginLeft:t?1:0},e.map((e,t)=>{const o=n&&t===r?YI:JI;return ot.createElement(Je,{key:t,columnGap:1},ot.createElement(Qe,{color:EI},o),ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},e)))}))}function HookOutcome({outcome:e,showTreeConnector:t}){if(!e)return null;const n="stop"===e.kind?nI.YELLOW:nI.RED;return ot.createElement(Je,{columnGap:1,marginLeft:t?1:0},ot.createElement(Qe,{color:EI},YI),ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{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 tD=createNodeRuntime(),nD=__name(({label:e,isSelected:t})=>e.includes("[shift+tab]")?ot.createElement(ot.Fragment,null,e.split("[shift+tab]")[0],ot.createElement(BracketWrap,{color:t?YA:JA,bold:!0},"shift+tab")):e.includes("(")?ot.createElement(ot.Fragment,null,e.split("(")[0],ot.createElement(Qe,{color:nI.GRAY},"(",e.split("(")[1])):e,"ChoiceLabel"),rD=__name(({request:e,onResponse:t,onEnableAutoAccept:n})=>{const[r]=at(0),[o,s]=at(1);lt(()=>{"edit"===e.action&&e.oldContent&&e.filePath&&resolveEditStartLine({runtime:tD,filePath:e.filePath,oldContent:e.oldContent}).then(e=>{void 0!==e&&s(e)}).catch(()=>{})},[e.filePath,e.oldContent,e.action]);const a=getPermissionChoicesForRisk({choices:zE,risk:e.risk}),i=__name(e=>{const r=a.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 ot.createElement(ZA,{title:`${d()}${"edit"===e.action?` ${c}`:""}`,footer:ot.createElement(QL,{hint:"↑/↓ navigate · enter select"})},"edit"===e.action&&e.oldContent&&e.newContent&&ot.createElement(Je,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c,marginLeft:0,startLine:o}).diffContent),e.risk&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{bold:!0,color:nI.RED,wrap:"wrap"},pt.warning," ",getRiskDisplay(e.risk))),ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{bold:!0},"Do you want to ",l()," ",ot.createElement(Qe,{color:YA},c),"?")),ot.createElement(SelectInput,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:i,initialIndex:r,indicatorComponent:WL,itemComponent:({label:e,isSelected:t})=>ot.createElement(HL,{isSelected:t},ot.createElement(nD,{label:e,isSelected:t}))}))},"PermissionPrompt");Ht(),Qx();var oD=db?"ctrl+y":"ctrl+e",sD=__name(({request:e,onResponse:t})=>{const[n]=at(0),[r,o]=at({phase:"idle"}),s=e.description??("done"===r.phase?r.explanation:void 0),a=void 0!==e.explain&&void 0===e.description&&"done"!==r.phase;tt((t,n)=>{a&&"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 i=getPermissionChoicesForRisk({choices:getShellPermissionChoices({command:e.command,...void 0!==e.args?{args:e.args}:{}}),risk:e.risk}),l=__name(e=>{const n=i.find(t=>t.value===e.value);n&&t(n)},"handleSelect");return ot.createElement(ZA,{title:"Execute Shell Command",subtitle:ot.createElement(Qe,{wrap:"wrap"},"Command Code needs to execute ",ot.createElement(Qe,{color:YA},getCommandDisplay(e)),"."),footer:ot.createElement(QL,{hint:a?`↑/↓ navigate · enter select · ${oD} explain`:"↑/↓ navigate · enter select"})},e.risk&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{bold:!0,color:nI.RED,wrap:"wrap"},pt.warning," ",getRiskDisplay(e.risk))),e.workingDirectory&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.GRAY},"Working directory: ",e.workingDirectory)),s&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM,italic:!0},s)),a&&"idle"===r.phase&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM,italic:!0},"Press"," ",ot.createElement(BracketWrap,{color:nI.DIM,bold:!0},oD)," ","to explain this command")),"loading"===r.phase&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM,italic:!0},ot.createElement(vt,{type:"dots"})," Explaining this command…")),"failed"===r.phase&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM,italic:!0},"Couldn't generate an explanation — press"," ",oD," to retry")),ot.createElement(SelectInput,{items:i.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:n,indicatorComponent:WL,itemComponent:({label:e,isSelected:t})=>ot.createElement(HL,{isSelected:t},e.includes("[shift+tab]")?ot.createElement(ot.Fragment,null,e.split("[shift+tab]")[0],ot.createElement(BracketWrap,{color:t?YA:JA,bold:!0},"shift+tab")):e)}))},"ShellPermissionPrompt");function handlePermissionResponse({choice:e,resolve:t,setPendingPermission:n,respondToPrompt:r,setStatus:o,permissionMode:s,showHintMessage:a,allowedStatus:i,deniedStatus:l}){r(e);const c="no"!==e.value;t(c),n(null),c?(o(i),"default"===s&&a("Use shift+tab to enable auto-accept")):o(l)}__name(handlePermissionResponse,"handlePermissionResponse");var aD=st(__name(function PermissionView2({pendingPermission:e,permissionMode:t,setPendingPermission:n,setStatus:r,respondToPrompt:o,showHintMessage:s,handleEnableAutoAccept:a}){const i={resolve:e.resolve,setPendingPermission:n,respondToPrompt:o,setStatus:r,permissionMode:t,showHintMessage:s};if("shell_command"===e.toolName){const t=e.params;return ot.createElement(Je,{marginY:1},ot.createElement(sD,{request:t,onResponse:e=>handlePermissionResponse({...i,choice:e,allowedStatus:"Shell command allowed",deniedStatus:"Shell command denied"})}))}if("kill_shell"===e.toolName){const t=buildKillShellPermissionRequest(e.params);return ot.createElement(Je,{marginY:1},ot.createElement(sD,{request:t,onResponse:e=>handlePermissionResponse({...i,choice:e,allowedStatus:"Process termination allowed",deniedStatus:"Process termination denied"})}))}if(isGenericToolRequest(e.params)){const t=e.params;return ot.createElement(Je,{marginY:1},ot.createElement(XL,{request:t,onResponse:e=>handlePermissionResponse({...i,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 ot.createElement(Je,{marginY:1},ot.createElement(rD,{request:l,onResponse:e=>handlePermissionResponse({...i,choice:e,allowedStatus:"File operation allowed",deniedStatus:"File operation denied"}),onEnableAutoAccept:a}))},"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}=Ze(),s=trimPlanMarkdown(e,getCollapsedPlanMaxLines(o?.rows)),a=s.hiddenLineCount>0,i=r?e:s.visible,l=1!==s.hiddenLineCount?"s":"",c=`… +${s.hiddenLineCount} more line${l} · ctrl+o to expand`;return ot.createElement(ZA,{title:"Plan",titleSuffix:n?` · ${t.basename(n)}`:void 0,gapAfterHeader:!1,hint:a?r?"ctrl+o to collapse":c:void 0},ot.createElement(Je,{marginTop:1},ot.createElement(Markdown,null,i)))}__name(isGenericToolRequest,"isGenericToolRequest"),__name(isFileEditRequest,"isFileEditRequest"),Ht(),Qx(),Ht(),Qx(),__name(PlanPanel,"PlanPanel"),Ht(),Qx();var iD=__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 `,a="─".repeat(Math.max(0,70-s.length));return ot.createElement(Je,{flexDirection:"column",marginTop:1,paddingLeft:4},ot.createElement(Qe,{italic:!0,color:nI.DIM},"Preview"),ot.createElement(Qe,{color:nI.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 ot.createElement(Qe,{key:t},ot.createElement(Qe,{color:nI.DIM},"│ "),ot.createElement(Qe,{color:nI.GRAY},n),ot.createElement(Qe,{color:nI.DIM},`${r} │`))}),r>0?ot.createElement(Qe,{color:nI.YELLOW},`├${s}${a}┤`):null,ot.createElement(Qe,{color:nI.DIM},`└${o}┘`))},"OptionPreview"),lD=[{label:"1. Submit",value:"submit"},{label:"2. Cancel",value:"cancel"}],cD=__name(({checked:e})=>e?ot.createElement(Qe,{color:nI.GREEN},"[",pt.tick,"] "):ot.createElement(Qe,{color:nI.DIM},"[ ] "),"MultiSelectCheckbox"),dD=__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"),uD=__name((e,t)=>{const n=new Set(e);return n.has(t)?(n.delete(t),n):(n.add(t),n)},"toggleLabel"),mD=__name((e,t)=>e?{indicator:pt.bullet,color:YA}:t?{indicator:pt.tick,color:nI.GREEN}:{indicator:pt.circle,color:nI.GRAY},"getTabMarker"),pD=__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,a)=>{const i=a===t&&!r,l=n.has(a),{indicator:c,color:d}=mD(i,l);s.push(ot.createElement(Qe,{key:a},ot.createElement(Qe,{color:d},c),ot.createElement(Qe,{color:i?YA:void 0}," ",o.header),a<e.length-1?ot.createElement(Qe,{color:nI.DIM}," | "):null))}),!o){const e=r;s.push(ot.createElement(Qe,{key:"review"},ot.createElement(Qe,{color:nI.DIM}," | "),ot.createElement(Qe,{color:e?YA:nI.GRAY},e?pt.bullet:pt.circle),ot.createElement(Qe,{color:e?YA:void 0,bold:e}," ","Review")))}return ot.createElement(Je,null,s)},"TabIndicator"),gD=__name(({questions:e,onResponse:t,hideCustomInput:n=!1,compact:r=!1})=>{const[o,s]=at(0),[a,i]=at(new Map),l=it(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=it(null);null===P.current&&(P.current=new Map);const M=it(null);null===M.current&&(M.current=new Map);const[x,I]=at(!1),[A,R]=at(""),[,O]=at(0),L=e[o],D=L?.multiSelect??!1,N=a.get(o),$=L?[...L.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description,...void 0!==e.preview?{preview:e.preview}:{}}))]:[],_=$.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),F=new Map(_.map((e,t)=>[e.label,$[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(!N||0===N.length)return 0;const e=N[0],t=L.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),H=__name(e=>{if(f)return;if(D){const t=dD(e.value,L.options.length-1);if(null===t)return;const n=L.options[t]?.label||"";return void p(e=>uD(e,n))}const t=dD(e.value,L.options.length-1);if(null===t)return;y(!0);const n=L.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(L.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(i(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 a=e.findIndex((e,t)=>!r.has(t));-1!==a&&(j(a),s(a)),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(),a=e.multiSelect||1!==n.length?void 0:e.options.find(e=>e.label===n[0]);return{questionIndex:t,selectedOptions:o,...a?.preview?{preview:a.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}]),O(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),i(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=dD(g.value,L.options.length-1);if(null===e)return;const t=L.options[e]?.label||"";p(e=>uD(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),i(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(tt((e,t)=>{if(x)t.escape?J():t.ctrl&&"v"===e?Q():t.ctrl&&"g"===e&&X(A,R);else if(t.ctrl&&"v"===e&&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()}}),!L&&!S)return null;if(S)return ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(RI,{dividerColor:qA}),ot.createElement(Je,{marginBottom:1},ot.createElement(pD,{questions:e,currentIndex:e.length,answeredQuestions:new Set(a.keys()),isReviewPage:!0})),e.some((e,t)=>!a.get(t)?.length)&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.YELLOW},"⚠ You have not answered all questions")),e.map((e,t)=>ot.createElement(Je,{key:t,marginBottom:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},t+1,". ",e.question),ot.createElement(Qe,{color:nI.GREEN}," ",a.get(t)?.join(", ")||"No answer"))),ot.createElement(SelectInput,{items:lD,onSelect:B,initialIndex:0,indicatorComponent:WL,itemComponent:GL}),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{italic:!0,color:nI.DIM},pt.arrowLeft," to go back and edit")));const se=r&&1===e.length;return ot.createElement(Je,{flexDirection:"column",width:"100%"},!se&&ot.createElement(RI,{dividerColor:qA}),!se&&ot.createElement(Je,{marginBottom:1},ot.createElement(pD,{questions:e,currentIndex:o,answeredQuestions:new Set(a.keys()),isReviewPage:!1,hideReview:n})),ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{bold:!0,color:zA},L.question)),v||E||x?ot.createElement(Je,{flexDirection:"column"},_.map((e,t)=>{const n=F.get(e.label),r=D&&n&&m.has(n.label),o=!D&&n&&N?.includes(n.label),s=r||o;return ot.createElement(Je,{key:e.value,flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,null," "),ot.createElement(HL,{isActive:s,idleColor:nI.GRAY}," ",t+1,"."," "),D&&ot.createElement(cD,{checked:s}),ot.createElement(HL,{isActive:s,idleColor:nI.GRAY},n?.label||""),!D&&s&&ot.createElement(VL,null)),n?.description&&ot.createElement(Je,null,ot.createElement(Qe,null," "),ot.createElement(zL,{indent:D?7:4},n.description)))})):ot.createElement(SelectInput,{key:`${o}-${C??"default"}`,items:_,initialIndex:C??W(),onSelect:H,onHighlight:h,indicatorComponent:WL,itemComponent:({label:e,isSelected:t})=>{const n=F.get(e),r=D&&n&&m.has(n.label),o=!D&&n&&N?.includes(n.label),s=r||o,a=e.match(/^\s*(\d+)\.\s*(.*)$/),i=a?.[1]||"",l=a?.[2]||e;return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(HL,{isSelected:t,isActive:s}," ",i,"."," "),D&&ot.createElement(cD,{checked:s}),ot.createElement(HL,{isSelected:t,isActive:s},l),!D&&s&&ot.createElement(VL,null)),n?.description&&ot.createElement(zL,{indent:D?7:4},n.description))}}),!v&&!E&&(()=>{const e=(g?F.get(g.label):void 0)??$[C??W()];return e?.preview?ot.createElement(iD,{preview:e.preview}):null})(),!n&&ot.createElement(Je,null,ot.createElement(WL,{isSelected:v}),ot.createElement(HL,{isSelected:v}," ",_.length+1,"."," "),D&&ot.createElement(cD,{checked:m.has(d.trim())}),ot.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?ot.createElement(Je,null,ot.createElement(WL,{isSelected:!0}),ot.createElement(HL,{isSelected:!0}," ","notes:"," "),ot.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?ot.createElement(Je,null,ot.createElement(Qe,{italic:!0,color:nI.DIM}," ","notes: ",e)):null})(),(M.current?.get(o)??[]).map((e,t)=>ot.createElement(Je,{key:t},ot.createElement(Qe,{color:nI.DIM}," ","[Image #",t+1," attached —"," ",e.mediaType,"]"))),D&&ot.createElement(Je,null,ot.createElement(WL,{isSelected:E}),ot.createElement(HL,{isSelected:E}," ",o===e.length-1?"Submit":"Next")),e.length>1&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{italic:!0,color:nI.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[a,i]=at(!1),l=e.params.planContent;return tt((e,t)=>{l&&getIsExpandToolShortcut(t,e)&&i(e=>!e)}),ot.createElement(Je,{marginY:1,flexDirection:"column"},l&&ot.createElement(Je,{marginBottom:1},ot.createElement(PlanPanel,{content:l,filePath:e.params.planFilePath,expanded:a})),ot.createElement(gD,{questions:e.params.questions,hideCustomInput:e.params.hideCustomInput,compact:e.params.compact,onResponse:a=>{const i=resolvePlanModeAnswerTransition({answer:a.answers[0]?.selectedOptions[0]||"",exitPlanMode:e.params.exitPlanMode,enterPlanMode:e.params.enterPlanMode,dangerouslySkipPermissions:n});i&&t(i),e.resolve(a),r(null),o("Answers submitted"),hardResetForResize(),s(e=>e+1)}}))}__name(QuestionView,"QuestionView"),Ht(),Qx();var hD="__skip__",fD=__name(({suggestion:e,onSelect:t,onClose:n})=>{const{completedMode:r,primary:o,secondary:s,description:a}=e,i=[...o.map(e=>({label:e,value:e,isPrimary:!0})),...s.map(e=>({label:e,value:e,isPrimary:!1})),{label:"skip",value:hD,isPrimary:!1}],l=new Map(i.map(e=>[e.label,e]));tt((e,t)=>{t.escape&&n()});const c=__name(e=>{e.value!==hD?(t(e.value),n()):n()},"handleSelect");return ot.createElement(ZA,{title:`/design ${r} complete`,titleSuffix:` · ${a}`,hint:"Enter to run · Esc to dismiss"},ot.createElement(SelectInput,{items:i,onSelect:c,indicatorComponent:YL,itemComponent:({label:e,isSelected:t})=>{const n=l.get(e),r=n?.value===hD,o=n?.isPrimary??!1,s=r?"run /design manually":Yh[e]??"";return ot.createElement(Je,{flexDirection:"column"},ot.createElement(KL,{isSelected:t,idleColor:o?nI.WHITE:nI.DIM},r?" skip ":` /design ${e} `),s&&ot.createElement(KL,{isSelected:t,idleColor:nI.DIM,bold:!1},` ${s} `))}}))},"DesignModeSelector");function getUsageToneColor(e){return"danger"===e?nI.RED:"warning"===e?nI.YELLOW:nI.GREEN}function getDistanceToneColor(e){return"danger"===e?nI.RED:"warning"===e?nI.YELLOW:nI.GRAY}function ContextProgress({view:e,progressBarWidth:t}){const n=getUsageToneColor(e.tone),r=buildBlockBar({percentage:e.percentage,width:t});return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{marginBottom:1},ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:nI.BLUE,color:"#f4f4f4",bold:!0},`${QI}CONTEXT${QI}`)),ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:nI.GRAY},e.modelLabel)),ot.createElement(Je,null,ot.createElement(Qe,{color:n},r.filled),ot.createElement(Qe,{color:pI},r.empty),ot.createElement(Qe,{bold:!0,color:n},` ${e.percentageLabel}`)),ot.createElement(Je,null,ot.createElement(Qe,null,e.tokensUsedLabel),ot.createElement(Qe,{color:nI.GRAY},` / ${e.tokenLimitLabel}`),ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:n},e.tokensRemainingLabel),ot.createElement(Qe,{color:nI.GRAY}," remaining"),e.isEstimated&&ot.createElement(Qe,{color:nI.DIM}," (estimated)")))}function CompactionDistance({view:e}){if(!e)return null;const t=getDistanceToneColor(e.tone);return ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:t},e.tokensAwayLabel),ot.createElement(Qe,{color:nI.DIM},e.label))}function BreakdownRow({item:e,labelWidth:t}){return ot.createElement(Je,null,ot.createElement(Qe,null,e.name.padEnd(t)),ot.createElement(Qe,{bold:!0},e.paddedValue),ot.createElement(Qe,{color:nI.GRAY}," tokens"),e.detail&&ot.createElement(Qe,{color:nI.DIM},` · ${e.detail}`))}function ContextBreakdown({view:e,labelWidth:t}){return 0===e.rows.length?null:ot.createElement(Je,{flexDirection:"column",marginTop:1},e.rows.map(e=>ot.createElement(BreakdownRow,{key:e.name,item:e,labelWidth:t})))}function ContextTips({tips:e}){return 0===e.length?null:ot.createElement(Je,{flexDirection:"column",marginTop:1},e.map(e=>ot.createElement(Je,{key:e},ot.createElement(Qe,{color:nI.CYAN},pt.pointer),ot.createElement(Qe,{color:nI.GRAY}," ",e))))}function ContextMessage({analysis:e}){const t=projectContextView(e,{terminalWidth:useTerminalWidth(),modelDisplayName:getModelDisplayName(e.model)});return ot.createElement(Je,{flexDirection:"column",paddingTop:1},ot.createElement(ContextProgress,{view:t.progress,progressBarWidth:t.layout.progressBarWidth}),ot.createElement(CompactionDistance,{view:t.compactionDistance}),ot.createElement(ContextBreakdown,{view:t.breakdown,labelWidth:t.layout.labelWidth}),ot.createElement(ContextTips,{tips:t.tips}))}function ContextConfigView({staticKey:e,sessionId:t,onClose:n,setInput:r}){const[o,s]=at(null),[a,i]=at(null);return lt(()=>{let e=!0;return __name(async()=>{const n=$O(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&&i("Failed to analyze context.")}else e&&i("No active conversation. Start chatting first.")},"load")(),()=>{e=!1}},[t]),tt((e,t)=>{t.escape&&(r(""),n())}),ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(ContextBody,{error:a,analysis:o}),ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Esc")," to return to conversation"))))}function ContextBody({error:e,analysis:t}){return e?ot.createElement(ZA,{title:"Context",gapAfterHeader:!1},ot.createElement(Qe,{color:nI.DIM},e)):t?ot.createElement(ContextMessage,{analysis:t}):ot.createElement(ZA,{title:"Context",gapAfterHeader:!1},ot.createElement(VO,{label:"Loading context analysis"}))}Ht(),Qx(),Ht(),Qx(),__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"),Ht(),Ht(),Qx(),Ht(),Qx();var yD="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?$O(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 SD=__name(({label:e,value:t,valueColor:n,dimValue:r})=>ot.createElement(Je,null,ot.createElement(Qe,{dimColor:!0},`${e}:`.padEnd(14)),r?ot.createElement(Qe,{dimColor:!0},t):ot.createElement(Qe,{color:n},t)),"Row");function StatusMessage({statusData:e}){const t=projectStatusView(e,{profileBaseUrl:"https://commandcode.ai"}),n=t.account.authenticated?pt.tick:pt.cross,r=t.account.authenticated?nI.WHITE:uI.ERROR;return ot.createElement(Je,{flexDirection:"column",paddingX:0},ot.createElement(Je,null,ot.createElement(Qe,{color:rI,bold:!0},"Command Code"," "),ot.createElement(Qe,{dimColor:!0},t.versionText)),ot.createElement(Je,null,ot.createElement(Qe,{dimColor:!0},"Visit "),ot.createElement(BI,{url:yD,text:yD,color:nI.CYAN}),ot.createElement(Qe,{dimColor:!0}," for usage and billing")),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{dimColor:!0},"Account:".padEnd(14)),t.account.username&&t.account.profileUrl?ot.createElement(ot.Fragment,null,ot.createElement(BI,{url:t.account.profileUrl,text:t.account.label,color:nI.CYAN}),ot.createElement(Qe,{color:r}," ",n)):t.account.authenticated?ot.createElement(ot.Fragment,null,ot.createElement(Qe,null,t.account.label),ot.createElement(Qe,{color:r}," ",n)):ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:uI.WARNING},t.account.label),ot.createElement(Qe,{color:r}," ",n),ot.createElement(Qe,{dimColor:!0}," — run "),ot.createElement(Qe,{bold:!0},t.account.loginHint))),ot.createElement(SD,{label:"Model",value:t.model.value}),ot.createElement(SD,{label:"Branch",value:t.branch.value,dimValue:t.branch.dim}),t.worktree?ot.createElement(SD,{label:"Worktree",value:t.worktree.value}):null,t.repository?ot.createElement(Je,null,ot.createElement(Qe,{dimColor:!0},"Repository:".padEnd(14)),ot.createElement(BI,{url:t.repository.url,text:t.repository.text,color:nI.CYAN}),t.pullRequest?ot.createElement(ot.Fragment,null,ot.createElement(Qe,{dimColor:!0}," · "),ot.createElement(BI,{url:t.pullRequest.url,text:t.pullRequest.text,color:t.pullRequest.open?nI.CYAN:nI.GRAY}),ot.createElement(Qe,{dimColor:!0}," ","(",t.pullRequest.stateLabel,")")):null):t.pullRequest?ot.createElement(Je,null,ot.createElement(Qe,{dimColor:!0},"Pull Request:".padEnd(14)),ot.createElement(BI,{url:t.pullRequest.url,text:t.pullRequest.text,color:t.pullRequest.open?nI.CYAN:nI.GRAY}),ot.createElement(Qe,{dimColor:!0}," (",t.pullRequest.stateLabel,")")):null,ot.createElement(SD,{label:"Taste",value:t.taste.value,dimValue:t.taste.dim}),ot.createElement(SD,{label:"Directory",value:t.directory.value}),ot.createElement(SD,{label:"Skills",value:t.skills.value,dimValue:t.skills.dim}),ot.createElement(SD,{label:"Agents",value:t.agents.value,dimValue:t.agents.dim}),ot.createElement(SD,{label:"System",value:t.system.value}),t.proxy?ot.createElement(SD,{label:"Proxy",value:t.proxy.value}):null)}function StatusBody({state:e}){return"ready"===e.phase?ot.createElement(StatusMessage,{statusData:e.data}):"error"===e.phase?ot.createElement(Qe,{dimColor:!0},"Could not load status: ",e.message):ot.createElement(Qe,{dimColor:!0},"Gathering status…")}function StatusConfigView({staticKey:e,sessionId:t,onClose:n,setInput:r}){const[o,s]=at({phase:"loading"});return lt(()=>{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]),tt((e,t)=>{t.escape&&(r(""),n())}),ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(StatusBody,{state:o}),ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Esc")," to return to conversation"))))}__name(StatusMessage,"StatusMessage"),__name(StatusBody,"StatusBody"),__name(StatusConfigView,"StatusConfigView"),Ht(),Qx(),Qx(),Ht(),Qx();var{addDirectory:wD,formatDirectoryForDisplay:vD,getAdditionalDirectories:kD,removeAdditionalDirectory:CD}=yf,bD=__name(({onClose:e})=>{const[t,n]=at(""),[r,o]=at(null),[s,a]=at([]),[i,l]=at(()=>kD()),[c,d]=at(()=>({zone:"input",suggestionIndex:0,activeDirIndex:0})),[u,m]=at(0);lt(()=>{a(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),m(0)},[t]),lt(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const p=__name(e=>{const t=wD(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(kD()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),g=__name(e=>{if(!CD(e))return o({tone:"error",text:`${vD(e)} is no longer in workspace scope`}),void l(kD());o({tone:"success",text:`Removed ${vD(e)} from directory scope`}),l(kD()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");tt((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&&i[c.activeDirIndex])g(i[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:i.length})):r.upArrow&&d(e=>moveAddDirFocusUp(e,{suggestionCount:s.length,activeDirCount:i.length}))}}}),lt(()=>{"suggestions"===c.zone&&m(e=>getAdjustedSuggestionOffset({selectedIndex:c.suggestionIndex,currentOffset:e,maxVisible:jx,totalSuggestions:s.length}))},[c,s.length]),lt(()=>{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>=i.length?{...e,zone:"input",activeDirIndex:Math.max(0,i.length-1)}:e)},[s.length,i.length]);const h=s.slice(u,u+jx),f=getAddDirFooterText({focusZone:c.zone});return ot.createElement(ZA,{title:"Add directory to workspace",subtitle:ot.createElement(Qe,{color:nI.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),footer:ot.createElement(Qe,{italic:!0,color:nI.DIM},ot.createElement(BracketedText,{text:f,color:nI.DIM})),gapAfterHeader:!1},ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.GRAY},"Added directories"),0===i.length?ot.createElement(Qe,{color:nI.GRAY}," None yet"):i.map((e,t)=>{const n="active-dir"===c.zone&&c.activeDirIndex===t;return ot.createElement(Je,{key:e},ot.createElement(Qe,null," "),ot.createElement(WL,{isSelected:n}),ot.createElement(HL,{isSelected:n,isActive:!0}," ",vD(e)))})),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{bold:!0,color:nI.WHITE},"Path")),ot.createElement(Je,null,ot.createElement(TextInput,{value:t,focus:"input"===c.zone,prefix:`${"input"===c.zone?pt.pointer:" "} `,prefixColor:"input"===c.zone?YA:nI.GRAY,onChange:e=>{n(e),o(null)},onSubmit:p})),!t&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:{error:nI.RED,warning:nI.YELLOW,success:nI.GREEN}[r.tone]},r.text)),s.length>0&&ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Qe,{color:nI.GRAY},"Suggestions"),h.map((e,t)=>{const n=u+t,r="suggestions"===c.zone&&c.suggestionIndex===n;return ot.createElement(Je,{key:e},ot.createElement(Qe,null," "),ot.createElement(WL,{isSelected:r}),ot.createElement(HL,{isSelected:r,idleColor:nI.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")}}Ht(),Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),Ht(),Ht(),Qx(),Ht(),Qx(),__name(createBillingTransport,"createBillingTransport");var ED=null;function getBilling(){return ED||(ED=createBilling({transport:createBillingTransport()})),ED}function getCachedBillingContext(){return ED?.getCached()??null}function getBillingContext(){return getBilling().get()}function prefetchBillingContext(){getBilling().prefetch()}function invalidateBillingContext(){ED=null}function buildLaneModelPickerGroups(){const e=filterModelGroupsByRegisteredModules(VR).filter(e=>e.providerId!==ro.COMMAND);return[...buildModelPickerGroups({normalModeGroups:zR}),...e,...buildCustomModelPickerGroups()]}function buildCatalogModelPickerGroups(){return[...buildModelPickerGroups({normalModeGroups:zR}),...buildCustomModelPickerGroups()]}function laneServesModel(e){if(e.activeLane===ro.COMMAND)return!0;const t=_o[e.activeLane]?.supportedModelProviders;if(!t)return!0;const n=Object.values(OR).find(t=>t.id===e.modelId);return!n||laneSupportsModel(t,n)}function laneModelCount(e){return e.laneId===ro.COMMAND?zR.reduce((e,t)=>e+t.models.length,0):VR.find(t=>t.providerId===e.laneId)?.models.length??0}function defaultModelForLane(e){const t=filterModelGroupsByRegisteredModules(VR),n=t.filter(t=>t.providerId===e.activeLane),r=n.length>0?n:t.filter(e=>e.providerId===ro.COMMAND);return r[0]?.models[0]?.id}function useCustomModelsReady(e){const[t,n]=at(!1);return lt(()=>{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"),Ht(),Qx(),__name(buildLaneModelPickerGroups,"buildLaneModelPickerGroups"),__name(buildCatalogModelPickerGroups,"buildCatalogModelPickerGroups"),__name(laneServesModel,"laneServesModel"),__name(laneModelCount,"laneModelCount"),__name(defaultModelForLane,"defaultModelForLane"),Ht(),__name(useCustomModelsReady,"useCustomModelsReady"),Ht(),Qx();var TD=__name((e,t)=>{const n=t&&e.id===BR?" (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,TD(n,t)+2),32)}__name(getModelLabelColumnWidth,"getModelLabelColumnWidth");var PD=__name(({model:e,providerId:t,isHighlighted:n,isCurrent:r,showProviderLabel:o,showDefaultBadge:s=!0,labelColumnWidth:a=32})=>{const i=_o[t],l=o??i?.showProviderLabelInSelector??!1,c=e.vendorLabel??WR[e.provider],d=s&&e.id===BR,u="free"===e.badge,m=d?`${e.label} (default)`:e.label,p=u?" (FREE)":"",g=" ".repeat(Math.max(2,a-m.length-p.length)),h=n?TI:void 0,f=e.description?`${l?`${c} · `:""}${e.description}`:"",y=useTerminalWidth()>=a+38&&f;return ot.createElement(Je,null,ot.createElement(Qe,{backgroundColor:h,color:r?nI.GREEN:nI.WHITE,bold:r},m),u&&ot.createElement(Qe,{backgroundColor:h,color:nI.GREEN,bold:!0},p),y&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{backgroundColor:h},g),ot.createElement(Qe,{backgroundColor:h,color:nI.DIM},f)),ot.createElement(Qe,{backgroundColor:h,color:nI.GREEN},r?` ${pt.tick} `:" "))},"ModelRow");Ht(),Qx();var MD=__name((e,t)=>`${e+1}. ${t}`,"labelText"),xD=__name(({modelLabel:e,supportedEfforts:t,currentEffort:n,onSelect:r,onCancel:o})=>{const s=ct(()=>buildEffortPickerRows(t),[t]),a=ct(()=>{if(void 0===n)return 0;const e=s.findIndex(e=>e.value===n);return e>=0?e:0},[s,n]),i=ct(()=>Math.max(...s.map((e,t)=>MD(t,e.label).length))+4,[s]),{cursor:l}=useListNavigation({items:s,onSelect:__name(e=>r(e.value),"onSelect"),onCancel:o,initialIndex:a,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,selectByNumber:!0});return ot.createElement(ZA,{title:`Select reasoning effort for ${e}`,hint:"↑/↓ navigate · enter to select · esc to go back"},ot.createElement(Je,{flexDirection:"column"},s.map((e,t)=>{const r=t===l,o=e.value===n;return ot.createElement(Je,{key:e.label},ot.createElement(Qe,{color:r||!o?nI.WHITE:nI.GREEN,backgroundColor:r?TI:void 0,bold:r||o},MD(t,e.label).padEnd(i)),ot.createElement(Qe,{color:r?nI.WHITE:nI.DIM,backgroundColor:r?TI:void 0},e.description," "),o&&ot.createElement(Qe,{color:nI.GREEN}," ",pt.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}]:[]})}Ht(),Qx(),__name(windowModelGroups,"windowModelGroups");var ID=__name(({onSelect:e,onCancel:t,currentModel:n,currentProvider:r,planId:o,purchasedCredits:s=0,freeCredits:a=0,refreshBanner:i,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??ro.COMMAND,v=useCustomModelsReady(d),k=ct(()=>buildLaneModelPickerGroups(),[v]),C=ct(()=>filterModelPickerGroupsByAuth({groups:k,authResolvedProviders:y,unauthedProviders:h}),[k,y,h]),b=ct(()=>filterModelPickerGroups(C,u),[C,u]),E=ct(()=>{const e=new Set(C.map(e=>`${e.providerId}:${e.label}`));return k.filter(t=>!e.has(`${t.providerId}:${t.label}`))},[k,C]),T=ct(()=>filterModelPickerGroups(E,u),[E,u]),P=ct(()=>flattenModelPickerGroups(b),[b]),M=ct(()=>{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=ct(()=>getModelLabelColumnWidth(k.flatMap(e=>e.models)),[k]),[I,A]=at(0),R=useTerminalHeight()-1,O=Math.max(4,R-16-2*b.length),L=void 0!==o,D=ct(()=>L?null:getCachedBillingContext(),[L]),[N,$]=at(D),[_,F]=at(!L&&!D);lt(()=>{if(L)return;if(N)return;let e=!0;return getBillingContext().then(t=>{e&&($(t),F(!1))}),()=>{e=!1}},[L,N]);const U=!L&&!0===N?.fetchFailed,j=L?o:N?.planId??null,B=L?s:N?.purchasedCredits??0,W=L?a:N?.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")});lt(()=>{A(e=>clampScrollOffset({cursor:q,total:P.length,maxVisible:O,currentOffset:e}))},[q,P.length,O]);const Q=it(!1),X=__name(t=>{if(!z||Q.current)return;Q.current=!0;const{model:r,providerId:o}=z,s=getReasoningEffort(r.id),a=t!==s,l=r.id===n;(async()=>{try{a&&(await setReasoningEffort({modelId:r.id,effort:t}),l&&i?.())}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(lt(()=>{if(_)return;if(Y!==jE)return;const e=P[q];J(e&&!U?getModelPickerAccessError({model:e.model,billing:{planId:j,purchasedCredits:B,freeCredits:W}}):null)},[_,U,Y,J,P,q,j,B,W]),lt(()=>{(async()=>{const e=await getConfiguredProvider();e&&e!==ro.COMMAND&&g(e)})()},[]),lt(()=>{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 ot.createElement(xD,{modelLabel:z.model.label,supportedEfforts:e,currentEffort:getReasoningEffort(z.model.id),onSelect:X,onCancel:Z})}const ee=I,te=I+O,ne=windowModelGroups({groups:b,firstSectionBase:0,windowStart:ee,windowEnd:te}),re=P.length>O;return ot.createElement(ZA,{title:"Select model",subtitle:l??"Pick a model - Command Code, your signed-in lanes, and custom providers. Sets the default for new sessions; other open sessions are unaffected.",footer:ot.createElement(Qe,{italic:!0,color:nI.DIM},"type to search · ↑/↓ navigate · shift+↑/↓ jump provider · enter to select",u?" · esc to clear":" · esc to cancel")},ot.createElement(Je,{marginBottom:2,flexDirection:"column",width:"100%"},ot.createElement(VI,{query:u,resultCount:u?P.length:void 0,placeholder:"Type to search models..."})),0===P.length?ot.createElement(Je,{marginY:1},ot.createElement(Qe,{color:nI.GRAY},T.length>0?"Provider login required. Run /connect to authenticate.":`No models match "${u}"`)):ot.createElement(Je,{flexDirection:"column"},ne.map(({group:e,groupWindow:t},r)=>ot.createElement(Je,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:r>0?1:0},ot.createElement(Qe,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>ot.createElement(PD,{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&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",ee+1,"–",Math.min(te,P.length)," of ",P.length,ee>0?" · ↑ more":"",te<P.length?" · ↓ more":"")),Y&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.GRAY},Y)))},"ModelSelector"),AD=__name(e=>{if(!e)return"Inherit from session";for(const t of zR)for(const n of t.models)if(n.id===e)return n.label;return e},"agentModelLabel"),RD=[{value:"inherit",label:"1. Inherit from session (default)"},{value:"pick",label:"2. Pick a specific model"}],OD=__name(({selectedModel:e,onSelect:t})=>{const[n,r]=at("choice"),[o,s]=at(e?1:0);return tt((e,n)=>{if(n.upArrow)s(e=>Math.max(0,e-1));else if(n.downArrow)s(e=>Math.min(RD.length-1,e+1));else if("1"!==e)if("2"!==e){if(n.return){const e=RD[o];if(!e)return;"inherit"===e.value?t(null):r("picker")}}else r("picker");else t(null)},{isActive:"choice"===n}),"picker"===n?ot.createElement(ID,{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}):ot.createElement(Je,{flexDirection:"column"},RD.map((e,t)=>{const n=t===o;return ot.createElement(Je,{key:e.value},ot.createElement(Qe,{color:n?nI.WHITE:nI.GRAY,backgroundColor:n?TI:void 0,bold:n},n?">":" "," ",e.label))}),e&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.GRAY},"Currently pinned: ",AD(e))),ot.createElement(VA,{hints:["↑↓ navigate","Enter to select","Inherit follows /model; pinned agents keep their own model and prompt cache"]}))},"AgentModelSelector"),LD=__name(({config:e,onSaveComplete:t,viewOnly:n=!1})=>{const[r,o]=at("idle"),[s,a]=at(""),i=__name(async()=>{if(!e.location||!e.agentType||!e.sysPrompt)return o("error"),void a("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:py,model:e.model}),t(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");tt((e,t)=>{n||!t.return||"idle"!==r&&"error"!==r||i()});const l=formatAgentToolAccessForDisplay({access:[...e.selectedTools],allToolNames:py,displayNameByToolName:fy,displayNameToToolName:yy}),c=e.location&&e.agentType?getAgentDisplayPath({location:e.location,name:e.agentType}):"";return ot.createElement(Je,{flexDirection:"column",gap:1},ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{gap:1},ot.createElement(Qe,{color:nI.WHITE,bold:!0},"Name:"),ot.createElement(Qe,{color:nI.GRAY},e.agentType)),ot.createElement(Je,{gap:1},ot.createElement(Qe,{color:nI.WHITE,bold:!0},"Location:"),ot.createElement(Qe,{color:nI.GRAY},c)),ot.createElement(Je,{gap:1},ot.createElement(Qe,{color:nI.WHITE,bold:!0},"Tools:"),ot.createElement(Qe,{color:nI.GRAY},l)),ot.createElement(Je,{gap:1},ot.createElement(Qe,{color:nI.WHITE,bold:!0},"Model:"),ot.createElement(Qe,{color:nI.GRAY},AD(e.model)))),ot.createElement(Je,{gap:1},ot.createElement(Qe,{color:nI.WHITE,bold:!0},"Description"),ot.createElement(Qe,{color:nI.GRAY},"(Tells ","Command Code"," when to use this agent):")),ot.createElement(Qe,{color:nI.GRAY},e.ccToolDefinition),ot.createElement(Je,{gap:1},ot.createElement(Qe,{color:nI.WHITE,bold:!0},"System Prompt:")),ot.createElement(Qe,{color:nI.GRAY},e.sysPrompt),!n&&ot.createElement(Je,{marginTop:1},"idle"===r&&ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to save ·"," ",ot.createElement(GA,null,"Esc")," to cancel"),"saving"===r&&ot.createElement(Qe,{color:nI.YELLOW},"Saving agent…"),"saved"===r&&ot.createElement(KO,null,s),"error"===r&&ot.createElement(Je,{flexDirection:"column"},ot.createElement(zO,null,"Error: ",s),ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to retry"))))},"AgentSummary"),DD=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],ND=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=at("menu"),a=new Set(resolveAgentToolSelection({access:e.tools,allToolNames:py,displayNameToToolName:yy})),i={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:a,model:e.model??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 tt((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=DD[r];e&&d(e)}}),"view"===o?ot.createElement(ZA,{title:e.name,gapAfterHeader:!1,footer:ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to go back")},ot.createElement(LD,{config:i,onSaveComplete:()=>s("menu"),viewOnly:!0})):"edit"===o?ot.createElement(ZA,{title:e.name,gapAfterHeader:!1},ot.createElement(Qe,{color:nI.YELLOW},"Edit functionality coming soon..."),ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Esc")," to go back")):"delete"===o?ot.createElement(ZA,{title:"Delete agent",subtitle:`Are you sure you want to delete the agent ${e.name}?`},ot.createElement(Je,null,ot.createElement(SelectInput,{items:DD,onSelect:d,indicatorComponent:YL,itemComponent:qL}))):ot.createElement(ZA,{title:e.name,footer:ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"↑↓")," to navigate ·"," ",ot.createElement(GA,null,"Enter")," to select · ",ot.createElement(GA,null,"Esc")," ","to go back")},ot.createElement(SelectInput,{items:l,onSelect:c,indicatorComponent:YL,itemComponent:qL}))},"AgentDetails");Ht();var $D="https://commandcode.ai/docs/core-concepts/custom-agents",_D=__name(({onDone:e})=>(tt((t,n)=>{n.return&&e()}),ot.createElement(ZA,{title:"Create agents with Command Code",gapAfterHeader:!1,boxProps:{gap:1}},ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.GRAY},"Ask Command Code to create or update subagents for you, e.g."),ot.createElement(Qe,{color:nI.GRAY}," ",pt.pointerSmall," “create a code-reviewer subagent that reviews diffs for bugs”"),ot.createElement(Qe,{color:nI.GRAY}," ",pt.pointerSmall," “make a changelog agent that uses a fast model”")),ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.GRAY},"Or edit the files directly:"),ot.createElement(Qe,{color:nI.GRAY}," • .commandcode/agents/ (this project)"),ot.createElement(Qe,{color:nI.GRAY}," • ~/.commandcode/agents/ (all projects)")),ot.createElement(Qe,{color:nI.GRAY},"Docs: ",$D),ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to go back and just ask"))),"AskCommandCodeGuide"),FD=__name(({handleSelect:e,createdAgentName:t})=>{const[n,r]=at([]),[o,s]=at([]),[a,i]=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();lt(()=>{__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"}))),i(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})}),a.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)+(a.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,...a].find(e=>e.filePath===t.value);r&&(p(r),h(!0))},"handleAgentSelect");if(tt((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}),lt(()=>{y(e=>Math.min(e,Math.max(0,k.length-1)))},[k.length]),lt(()=>{w(e=>clampScrollOffset({cursor:f,total:k.length,maxVisible:P,currentOffset:e}))},[f,k.length,P]),l)return ot.createElement(VO,{label:"Loading agents"});if(g&&m){const e=isBuiltinAgentPath(m.filePath);return ot.createElement(ND,{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 O=null;return ot.createElement(ZA,{title:"Agents",titleSuffix:C>0?` (${C} agent${C>1?"s":""})`:" (No custom agents)"},t&&ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{color:nI.GREEN,dimColor:!0},"Created agent: ",t)),ot.createElement(Je,{flexDirection:"column"},A.map((e,t)=>{const n=x+t,r=E(n),o="action"!==r&&r!==O;O=r;const s=n===f,a="user"===r?"User agents":"project"===r?"Project agents":"Default agents (read-only)";return ot.createElement(ot.Fragment,{key:e.value},o&&ot.createElement(Je,{marginTop:0===t?0:1},ot.createElement(Qe,{color:pI,bold:!0},a)),ot.createElement(Je,null,ot.createElement(Qe,{color:s?nI.WHITE:nI.GRAY,backgroundColor:s?TI:void 0,bold:s},s?"> ":" ",e.label," ")))})),R&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",x+1,"–",Math.min(I,k.length)," of ",k.length,x>0?" · ↑ more":"",I<k.length?" · ↓ more":"")),ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(VA,{hints:["↑↓ navigate","Enter to select","Esc to close"],marginTop:0}),ot.createElement(Qe,{color:nI.DIM},"Agents live in .commandcode/agents/ (project) and ~/.commandcode/agents/ (all projects) — edit the files directly anytime."),ot.createElement(Qe,{color:nI.DIM},"Docs: ",$D)))},"ManageAgents");Ht(),Qx(),Ht(),Ht();var UD=[{label:"1. Project (.commandcode/agents/)",value:"project"},{label:"2. Personal (~/.commandcode/agents/)",value:"personal"}],jD=__name(({onSelect:e})=>ot.createElement(SelectInput,{items:UD,onSelect:t=>{"project"!==t.value&&"personal"!==t.value||e(t.value)},indicatorComponent:WL,itemComponent:GL}),"LocationSelector");Ht(),Qx();var BD=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:a,onAgentTypeSubmit:i,onSysPromptSubmit:l,onCCToolDefinitionSubmit:c})=>{const d=t?validateAgentName({name:t,displayNameByToolName:fy}):null,u=usePasteAwareChange({onChange:s}),m=usePasteAwareChange({onChange:a});return"agentType"===e?ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.WHITE},"Enter a unique identifier for your agent:"),"tool_conflict"===d?.issue&&ot.createElement(Qe,{color:nI.RED},pt.warning," This name conflicts with an existing tool name. Please choose a different name."),"reserved"===d?.issue&&ot.createElement(Qe,{color:nI.RED},pt.warning," This name is reserved. Reserved names: ",xS.join(", "))),ot.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{canSubmitAgentManualStep({manualStep:"agentType",config:{agentType:t,sysPrompt:n,ccToolDefinition:r}})&&i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.WHITE},"Enter the system prompt for your agent:"),ot.createElement(Qe,{color:nI.GRAY},"Be comprehensive for best results.")),ot.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?ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.WHITE},"When should ","Command Code"," use this agent?"),ot.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");Ht(),Qx();var WD=__name((e,t)=>e?"[x]":"[ ]","categoryCheckbox"),HD=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=at(!1),[a,i]=at(0),[l,c]=at(0),d=useTerminalHeight(),u=ct(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),by.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:"}),py.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=by.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t)),s=r?.tools.some(t=>e.has(t));return{label:`${WD(Boolean(o),Boolean(s))} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${fy[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[a]?.value??0;lt(()=>{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 tt((e,l)=>{if(l.upArrow)return void i(e=>{const t=e-1;return t<0?p.length-1:t});if(l.downArrow)return void i(e=>{const t=e+1;return t>=p.length?0:t});if(!l.return&&" "!==e)return;const c=p[a];if(!c)return;const d=u[c.value];if(d){if("continue"!==d.type)return"toggle"===d.type?(s(!o),void i(0)):void("category"!==d.type?"tool"===d.type&&t(d.value):n(d.value));r()}}),ot.createElement(Je,{flexDirection:"column"},S.map(e=>{const t=p.findIndex(t=>t.value===e.value),n=-1!==t&&t===a;if("divider"===e.type)return ot.createElement(Je,{key:`divider-${e.value}`},ot.createElement(Qe,{color:nI.GRAY}," ",e.label));if("spacer"===e.type)return ot.createElement(Je,{key:`spacer-${e.value}`,height:1});if("label"===e.type)return ot.createElement(Je,{key:`label-${e.value}`},ot.createElement(Qe,{color:nI.GRAY}," ",e.label));const r="continue"===e.type;return ot.createElement(Je,{key:`item-${e.value}`},ot.createElement(Qe,{color:n?nI.WHITE:nI.GRAY,bold:r&&n},n?">":" "," ",e.label))}),w&&ot.createElement(Je,null,ot.createElement(Qe,{color:nI.GRAY}," ","Showing ",f+1,"–",Math.min(y,m.length)," of"," ",m.length,f>0?" · ↑ more":"",y<m.length?" · ↓ more":"")),ot.createElement(Je,{marginTop:1},e.size===py.length&&ot.createElement(Qe,{color:nI.GRAY},"All tools selected"),e.size>0&&e.size<py.length&&ot.createElement(Qe,{color:nI.GRAY},e.size," tools selected"),0===e.size&&ot.createElement(Qe,{color:nI.GRAY},"No tools selected")))},"ToolsSelector"),GD=__name(({onComplete:e})=>{const[t,n]=at(createAgentCreationState),{step:r,manualStep:o,config:s}=t,a=__name(e=>n(t=>reduceAgentCreation({state:t,event:e})),"dispatch"),i=__name(t=>{a({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":"summary"===r?"Confirm and save":""},"getSubText"),c=__name(e=>{a({type:"select_location",location:e}),a({type:"select_method",method:"manual"})},"handleLocationSelect");return ot.createElement(ZA,{title:"Create new agent",subtitle:l()},ot.createElement(Je,null,"location"===r&&ot.createElement(jD,{onSelect:c}),"configuration"===r&&ot.createElement(Je,{flexDirection:"column",gap:1},ot.createElement(BD,{step:o,agentType:s.agentType,sysPrompt:s.sysPrompt,ccToolDefinition:s.ccToolDefinition,onAgentTypeChange:e=>a({type:"set_agent_type",value:e}),onSysPromptChange:e=>a({type:"set_sys_prompt",value:e}),onCCToolDefinitionChange:e=>a({type:"set_cc_tool_definition",value:e}),onAgentTypeSubmit:()=>a({type:"submit_agent_type"}),onSysPromptSubmit:()=>a({type:"submit_sys_prompt"}),onCCToolDefinitionSubmit:()=>a({type:"submit_cc_tool_definition"})})),"tools"===r&&ot.createElement(HD,{selectedTools:s.selectedTools,onToggleTool:e=>a({type:"toggle_tool",tool:e}),onToggleCategory:e=>a({type:"toggle_category",category:e}),onComplete:()=>a({type:"complete_tools"})}),"model"===r&&ot.createElement(OD,{selectedModel:s.model,onSelect:e=>a({type:"select_model",model:e})}),"summary"===r&&ot.createElement(LD,{config:s,onSaveComplete:i})))},"AgentNew"),VD=__name(({onCancel:e})=>{const[t,n]=at(null),[r,o]=at(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return tt((t,n)=>{n.escape&&e()}),ot.createElement(Je,{width:"100%",flexDirection:"column"},null===t&&ot.createElement(FD,{handleSelect:s,createdAgentName:r}),"ask_command_code"===t&&ot.createElement(_D,{onDone:e}),"create_new_agent"===t&&ot.createElement(GD,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");function isToggleShortcut(e,t){return""===e||!0===t.ctrl&&"b"===e}Ht(),Qx(),__name(isToggleShortcut,"isToggleShortcut");var zD=new Set;function requestBackgroundTasksExpand(){for(const e of zD)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),a=r%60;return o>0?`${o}h ${s}m ${a}s`:s>0?`${s}m ${a}s`:`${a}s`}function useShellTaskSnapshot(){const[e,t]=at(()=>listShellTasks({includeStopped:!0}));return lt(()=>{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 KD=getShellTaskLabel,qD=getShellTaskStatusText,YD=getVisibleShellTasks,JD=latestShellTaskOutputLines,QD={running:nI.CYAN,completed:nI.GREEN,failed:nI.RED,"auto-stopped":nI.YELLOW,stopped:nI.GRAY};function getStatusColor(e){return QD[getShellTaskStatusTone(e)]}function TaskRow({task:e,selected:t}){const n=truncateString2({text:KD(e),maxChars:56}),r=t?TI:void 0;return ot.createElement(Je,null,ot.createElement(WL,{isSelected:t,backgroundColor:r}),ot.createElement(Qe,{color:t?YA:void 0,backgroundColor:r}," ",n),ot.createElement(Qe,{color:nI.DIM,backgroundColor:r}," ","(",qD(e),")"))}function TaskGroup({title:e,tasks:t,selectedTaskId:n}){return 0===t.length?null:ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Qe,{color:nI.DIM,bold:!0},e," (",t.length,")"),t.map(e=>ot.createElement(TaskRow,{key:e.id,task:e,selected:e.id===n})))}function TaskDetailsBody({task:e,output:t}){const n=JD(t,10),r=formatTaskRuntime(e);return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,{bold:!0},"Status: "),ot.createElement(Qe,{color:getStatusColor(e)},qD(e))),void 0!==r&&ot.createElement(Je,null,ot.createElement(Qe,{bold:!0},"Runtime: "),ot.createElement(Qe,null,r)),ot.createElement(Je,null,ot.createElement(Qe,{bold:!0},"Script: "),ot.createElement(Qe,{wrap:"wrap"},e.command)),ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Qe,{bold:!0},"Output:"),ot.createElement(Je,{flexDirection:"column",borderStyle:"single",borderColor:nI.DIM,paddingX:1},n.length>0?n.map((t,n)=>ot.createElement(Qe,{key:`${e.id}-${n}`},truncateString2({text:t,maxChars:100}))):ot.createElement(Qe,{color:nI.DIM},"No output yet.")),ot.createElement(Qe,{italic:!0,color:nI.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,a]=at("list"),[i,l]=at(0),[c,d]=at(""),u=ct(()=>YD(t),[t]),m=u[i]??u[0];lt(()=>{e?.(r)},[r,e]),lt(()=>{const e=__name(()=>{a("list"),o(!0)},"listener");return zD.add(e),()=>{zD.delete(e)}},[]),lt(()=>{if(0===u.length)return o(!1),a("list"),void l(0);l(e=>Math.min(e,Math.max(0,u.length-1)))},[u.length]),lt(()=>{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),a("list")},"closePanel");if(tt((e,t)=>isToggleShortcut(e,t)&&(n.length>0||r)?(a("list"),void o(e=>!e)):r?"details"===s?t.leftArrow?void a("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?a("details"):"x"===e&&"running"===m?.status&&stopShellTaskById(m.id))):void 0,{isActive:n.length>0||r}),!r)return null;if("details"===s&&m)return ot.createElement(ZA,{title:"monitor"===m.kind?"Monitor details":"Shell details",titleColor:nI.CYAN,ruleColor:nI.CYAN,subtitle:truncateString2({text:KD(m),maxChars:80}),hint:"← to go back · Esc/Enter/Space to close · x to stop",boxProps:{marginTop:1,marginBottom:1}},ot.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 ot.createElement(ZA,{title:"Background",titleColor:nI.CYAN,ruleColor:nI.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?ot.createElement(ot.Fragment,null,ot.createElement(TaskGroup,{title:"Monitors",tasks:g,selectedTaskId:m?.id}),ot.createElement(TaskGroup,{title:"Shells",tasks:h,selectedTaskId:m?.id})):ot.createElement(Je,{flexDirection:"column",marginTop:1},u.map(e=>ot.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"),Ht(),Qx();var XD=[{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."}],ZD=__name(({onSelect:e,onCancel:t})=>{const[n,r]=at(null);lt(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(tt((e,n)=>{n.escape&&t()}),null===n)return null;const s=XD.findIndex(e=>e.value===n);return ot.createElement(ZA,{title:"Select a compact mode to compact sessions",subtitle:"Choose how Command Code handles automatic context compaction.",footer:ot.createElement(Qe,{italic:!0,color:nI.DIM},"Press ",ot.createElement(Qe,{bold:!0},"Esc")," to cancel")},ot.createElement(SelectInput,{items:XD,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:YL,itemComponent:({isSelected:e,label:t})=>{const r=XD.find(e=>e.label===t),o=r?.value===n,s=XD.findIndex(e=>e.label===t);return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(KL,{isSelected:e,idleColor:o?nI.GREEN:nI.WHITE,bold:e||o},` ${s+1}. ${r?.label??t} `),o&&ot.createElement(VL,null)),ot.createElement(KL,{isSelected:e,idleColor:nI.DIM,bold:!1},` ${r?.description??""} `))}}))},"CompactModeSelector");Ht(),Ht(),Qx();var eN=["·","○","◇","☆","✧","☆","◇","○","⌘"],tN=[12,5,4,4,4,4,4,5,16],nN=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<tN.length;e++)if(n+=tN[e],t<n)return eN[e];const r=t-58;n=0;for(let e=0;e<nN.length;e++)if(n+=nN[e],r<n)return eN[7-e];return eN[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=ct(()=>e.split(""),[e]),o=__name(e=>{const n=e-(t-5);return n>=0&&n<kI.length?kI[n]:CI},"getCharColor");return ot.createElement(Qe,null,r.map((e,t)=>ot.createElement(Qe,{key:`${t}:${e}`,color:o(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return ot.createElement(Qe,{color:t??rI,bold:!0},`${getWaveSymbol(e)} `)}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var rN=formatStatusTokenCount,oN=formatElapsedMs,sN=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=at(0),[s,a]=at(n),i=it(n);i.current=n;const l=getTerminalWidth(),[c,d]=at(()=>l>=72?"all":l>=42?"medium":"none");lt(()=>{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]),lt(()=>{const e=setInterval(()=>{o(e=>(e+1)%88),a(e=>{const t=i.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 lA.statusRender({width:l,layoutMode:c,status:e,frame:r}),ot.createElement(Je,{width:l,height:1,paddingLeft:0,marginLeft:0},ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:cI.BG,color:cI.FG}," "),ot.createElement(Qe,{backgroundColor:cI.BG},ot.createElement(CMDIcon,{frame:4*r,color:cI.FG})),ot.createElement(ShimmerText,{text:e,offset:u,bg:cI.BG}),ot.createElement(Qe,{backgroundColor:cI.BG,color:cI.FG}," ")),m&&ot.createElement(Je,{columnGap:1,marginLeft:1},ot.createElement(Qe,{bold:!0,color:nI.GRAY},"esc"),ot.createElement(Qe,{color:nI.DIM},"to interrupt"),ot.createElement(Qe,{color:nI.DIM},"•"),ot.createElement(Qe,{color:nI.DIM},oN(t)),ot.createElement(Qe,{color:nI.DIM},"•"),ot.createElement(Qe,{color:nI.GRAY},pt.arrowDown),ot.createElement(Qe,{color:nI.DIM},rN(Math.round(s)))),p&&ot.createElement(Je,{marginLeft:1},ot.createElement(Qe,{color:nI.DIM},rN(Math.round(s)))))},"Status");function useExternalEditor({input:e,setInput:t,setInputKey:n,detectedContent:r,setDetectedContent:o,onEditorClose:s}){const[a,i]=at(!1),[l,c]=at(null),d=dt(async()=>{if(!a){i(!0),c(null);try{const a=resolvePastedTextTokens({input:e.replace(/\n+$/,""),detectedContent:r}),i=await openInEditor(a);t(i),o([]),n(e=>e+1),s?.()}catch(e){if(e instanceof Lh)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{i(!1)}}},[e,t,n,r,o,s,a]),u=dt(()=>{c(null)},[]);return{isEditorOpen:a,editorError:l,handleOpenInEditor:d,clearEditorError:u}}Ht(),Qx(),Ht(),Qx(),__name(useExternalEditor,"useExternalEditor"),Ht(),Qx();var aN=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=at(null),[s,a]=at(!1),[i,l]=at({visible:!1,type:"connected"}),c=it(null);null===c.current&&(c.current=eb({onConnectedChange:a,onContext:o,onIndicatorChange:l}));const d=c.current;lt(()=>{d.setPaused(n)},[d,n]),lt(()=>{if(t)return d.start(),()=>{d.stop()}},[t,d]);const u=NC(),m=u?sb[u]??"IDE":"IDE",p={visible:i.visible,message:"connected"===i.type?`${m} ${pt.tick}`:"run /ide",type:i.type};return{context:r,connected:s,refresh:d.refresh,connectionIndicator:p}},"useVSCodeContext");Ht(),Qx();var iN=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=at(null),o=it(!1);return lt(()=>{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=it([]),s=it(""),a=it(!1),i=it(null),l=it(!1),c=it("");return lt(()=>{if(l.current)return l.current=!1,void(c.current=e);if(e===c.current)return;const t=c.current;return c.current=e,a.current||(s.current=t,a.current=!0),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{a.current=!1,i.current=null,pushEntry(o.current,s.current)},400),()=>{i.current&&(clearTimeout(i.current),i.current=null)}},[e]),{commitUndo:__name(()=>{a.current&&commitBurst({stack:o.current,burstStart:s.current,inBurst:a,timer:i});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})}Ht(),__name(pushEntry,"pushEntry"),__name(commitBurst,"commitBurst"),__name(useUndoStack,"useUndoStack"),Ht(),Qx(),__name(getCommandHintLayout,"getCommandHintLayout"),__name(getModelHintText,"getModelHintText"),Ht(),Qx();var lN=createNodeRuntime(),cN=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=at(()=>process.cwd()),[a,i]=at([]),[l,c]=at(0),[d,u]=at(0),m=n.trim()?15:10;lt(()=>{invalidateFileIndex()},[]),lt(()=>{let e=!1;return __name(async()=>{if(n.trim()){const t=await searchFiles({runtime:lN,searchTerm:n,basePath:process.cwd()});if(e)return;return i(t),c(0),void u(0)}try{const t=await browseDirectory({runtime:lN,dirPath:r,basePath:process.cwd()});if(e)return;i(t),c(0),u(0)}catch{}},"run")(),()=>{e=!0}},[r,n]),tt((r,i)=>{if(i.escape)t();else if(i.upArrow)c(e=>{const t=Math.max(0,e-1);return t<d&&u(t),t});else if(i.downArrow)c(e=>{const t=Math.min(a.length-1,e+1);return t>=d+m&&u(t-m+1),t});else{if(i.rightArrow){const e=a[l];if(!e)return;return void(e.isDirectory&&!n.trim()&&o(s(e.path)))}if(i.return){const t=a[l];if(!t)return;return void e(t.path)}}});const p=a.slice(d,d+m);return ot.createElement(Je,{flexDirection:"column",paddingLeft:1},ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM},n.trim()?`Searching for: "${n}"`:`Files: ${r}`)),0===p.length?ot.createElement(YO,{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 ot.createElement(Qe,{key:e.path,color:o?YA:nI.DIM,bold:o&&isLightTheme()},e.isDirectory?`${r}/`:r)}),ot.createElement(VA,{hints:["↑↓ navigate",!n.trim()&&"→ to open folder","Enter to select","Esc to close"]}))},"FileList");Ht(),Qx();var dN=__name(()=>ot.createElement(Je,{paddingRight:3},ot.createElement(Qe,{color:nI.DIM,wrap:"truncate"},pt.pointerSmall," ","stashed")),"StashBadge"),uN=__name(({tasteLearningOn:e,byokSession:t,showSeparator:n=!0})=>{if(null==e)return null;const r=e&&t;return ot.createElement(ot.Fragment,null,n&&ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:e&&!r?oI.TEXT:nI.DIM},r?"taste off (byok)":"taste "+(e?"on":"off")))},"TasteStateBadge");function useBackgroundTasksSummary(){const[e,t]=at(()=>formatShellTaskCounts(listShellTasks({includeStopped:!1})));return lt(()=>{const e=setInterval(__name(()=>t(formatShellTaskCounts(listShellTasks({includeStopped:!1}))),"refresh"),1e3);return()=>clearInterval(e)},[]),e}__name(useBackgroundTasksSummary,"useBackgroundTasksSummary");var mN=__name(({showSeparator:e=!0,armed:t=!1})=>{const n=useBackgroundTasksSummary();return n?ot.createElement(ot.Fragment,null,e&&ot.createElement(Qe,{color:nI.DIM}," · "),t?ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.CYAN,inverse:!0},` ${n} `),ot.createElement(Qe,{color:nI.DIM}," · Enter to open")):ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.CYAN},n),ot.createElement(Qe,{color:nI.DIM}," · ↓ to manage"))):null},"BackgroundTasksBadge"),pN=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?ot.createElement(ot.Fragment,null,t&&ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:"connected"===e.type?nI.GREEN:nI.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),gN=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="default",prInfo:o,contextUsage:s,connectionIndicator:a,pendingExitKey:i,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})=>{const C=e>=60;return ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r&&"bypass"!==r&&"dont-ask"!==r||i?ot.createElement(Je,{flexDirection:"row",justifyContent:"space-between",width:e-1},ot.createElement(Je,{flexDirection:"row",columnGap:0},n&&!i?ot.createElement(Qe,{color:mI},t):ot.createElement(jI,{mode:r,pendingExitKey:i}),!i&&ot.createElement(WI,{prInfo:o}),!i&&ot.createElement(pN,{indicator:a}),!i&&C&&ot.createElement(uN,{tasteLearningOn:w,byokSession:v}),!i&&ot.createElement(mN,{armed:k})),(C||S)&&ot.createElement(Je,{flexDirection:"column",alignItems:"flex-end"},S?ot.createElement(dN,null):null,!S&&C&&s&&ot.createElement(AI,{usage:s}))):ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"row",justifyContent:"space-between",width:e-1},ot.createElement(jI,{mode:r}),S?ot.createElement(dN,null):null),ot.createElement(Je,{flexDirection:"row",justifyContent:"space-between",width:e-1},ot.createElement(Je,{flexDirection:"row",columnGap:0},ot.createElement(Qe,{color:n?mI:nI.DIM},t),ot.createElement(WI,{prInfo:o}),ot.createElement(pN,{indicator:a}),C&&ot.createElement(uN,{tasteLearningOn:w,byokSession:v}),ot.createElement(mN,{armed:k})),ot.createElement(Je,{flexDirection:"row",columnGap:2},C&&s&&ot.createElement(AI,{usage:s})))),(l||c||u&&d)&&ot.createElement(Je,{flexDirection:"row",columnGap:1},l&&ot.createElement(Qe,null,pt.tick," ","Command Code"," updated:"," ",ot.createElement(Qe,{color:nI.DIM},"v",l.updatedFrom),ot.createElement(Qe,{color:nI.DIM}," ",pt.arrowRight," "),ot.createElement(Qe,null,"v",l.updatedTo)),!l&&c&&ot.createElement(Qe,{color:nI.YELLOW,dimColor:!0},pt.info," Update available:"," ",c.currentVersion," ",pt.arrowRight," ",c.latestVersion),u&&d&&ot.createElement(Qe,{color:nI.GREEN,dimColor:!0},pt.bullet," Provider:"," ",getProviderDisplayName(d)))),m&&ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,{color:nI.GREEN},"! for bash mode")),g&&p&&ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,{color:rI},"SHARED: ",p.url," (copied to clipboard)")),h&&ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,{color:h.includes("NOT SHARED")?nI.RED:rI},h)),f&&ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,{color:rI},f)),y&&ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,{color:nI.YELLOW},pt.warning," ",y)))},"BottomIndicator"),hN=["","","[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 fN=__name(()=>ot.createElement(Je,{flexDirection:"column",paddingLeft:1},ot.createElement(Qe,{color:nI.DIM,bold:!0},"Available Shortcuts:"),ot.createElement(Je,{columnGap:4},ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},"! for bash mode"),ot.createElement(Qe,{color:nI.DIM},"/ for commands"),ot.createElement(Qe,{color:nI.DIM},"@ for file paths"),ot.createElement(Qe,{color:nI.DIM},getModeToggleShortcutHint()," to toggle auto-accept")),ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},"double tap esc to clear input"),ot.createElement(Qe,{color:nI.DIM},"ctrl + j / shift + ⏎ for newline"),ot.createElement(Qe,{color:nI.DIM},"ctrl + g to open in editor"),ot.createElement(Qe,{color:nI.DIM},"ctrl + z to undo"),ot.createElement(Qe,{color:nI.DIM},"ctrl + s to stash prompt")))),"ShortcutMenu"),yN=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:s,setShowFileList:i,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:O=!1,ideContextEnabled:L=!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=it(0),q=it(0),[Y,J]=at([]),[Q,X]=at([]),[Z,ee]=at(null),te=it(!1),ne=it(!1),[re,oe]=at(!1),se=it(!1),ae=dt(e=>{se.current=e,oe(e)},[]),ie=it(!1),le=it(void 0),[ce,de]=at(-1),[ue,me]=at(""),pe=it(0),{commitUndo:ge}=useUndoStack({input:e,setInput:n,initialCursorRef:le,incrementInputKey:__name(()=>$(e=>e+1),"incrementInputKey")}),{isEditorOpen:he,editorError:fe,handleOpenInEditor:ye,clearEditorError:Se}=useExternalEditor({input:e,setInput:n,setInputKey:$,detectedContent:Y,setDetectedContent:J,onEditorClose:__name(()=>{te.current=!1},"onEditorClose")}),we=ct(()=>shouldCollapsePastedText(),[]),{handlePaste:ve,resetPasteState:ke,isPasting:Ce}=useBracketedPaste({input:e,setInput:n,setDetectedImages:X,setDetectedContent:J,incrementInputKey:__name(()=>$(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{le.current=e},"setInitialCursor"),collapsePastedText:we,nextImageNumber:nextImagePasteNumber(Q)}),be=it(()=>{});be.current=t=>{he||(async()=>{const n=pe.current,r=e.slice(0,n),o=e.slice(n);await ve(`${r}[200~${t}[201~${o}`)&&(ie.current=!0)})()},lt(()=>registerPasteConsumer(e=>be.current(e)),[]);const Ee=it(new Map),Te=ct(()=>{const e=Ee.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 Ee.current=t,n},[Q]),{skills:Pe,customMenuItems:Me}=useSlashMenuData(),xe=ct(()=>{const e=resolveSlashMenuItems({searchQuery:"",customMenuItems:Me,skills:Pe,showProviderCommand:!0,showTerminalSetupCommand:isVSCodeTerminal2()});return new Set([...e.map(e=>e.command),...Pe.map(e=>buildSkillNamespacedCommand(e.name))])},[Pe,Me]),Ie=dt(e=>xe.has(e),[xe]),{context:Ae,connected:Re,refresh:Oe,connectionIndicator:Le}=aN({enabled:L,paused:O}),{stdout:De}=Ze(),Ne=De?.columns??80,{pr:$e}=iN();lt(()=>{const e=s||B;I?.(e)},[s,B,I]),lt(()=>{if(!ie.current)return;ie.current=!1;const t=sf(e);!B&&t.showCommandMenu||(W(t.showCommandMenu),G(t.showCommandMenu?t.commandSearchQuery:""))},[e,B]);const _e=dt(()=>{X([])},[]),Fe=dt(()=>{W(!1),z(null)},[]),Ue=dt(()=>{Fe(),G(""),i(!1),c(""),de(-1),me(""),le.current=void 0,$(e=>e+1)},[Fe,c,i]),je=dt(t=>!(null===Z||!t?.replaceCurrentInput&&e.trim().length>0||(te.current=!0,n(Z),ee(null),Ue(),setTimeout(()=>{te.current=!1},0),0)),[e,Ue,n,Z]),Be=dt(()=>{n(""),j(!1),Fe(),G(""),J([]),_e(),ke(),de(-1),me(""),$(e=>e+1)},[n,ke,_e,Fe]),We=dt(()=>{te.current=!0;const{text:t,cursor:r}=insertTextAt(e,pe.current,"\n");n(t),le.current=r,$(e=>e+1),setTimeout(()=>{te.current=!1},0)},[e,n]);tt(async(t,r)=>{if(se.current&&!r.downArrow&&!r.return&&"\r"!==t&&(ae(!1),r.upArrow))return;if(r.upArrow){if(s||B)return;const t=e.indexOf("\n"),r=-1===t||pe.current<=t;if(0!==e.length&&-1===ce&&!r)return;const o=M?.count()??0;if(0===o)return;-1===ce&&me(e);const a=Math.min(ce+1,o-1);return void(a!==ce&&(de(a),n(M?.getAt(a)||""),$(e=>e+1)))}if(r.downArrow){if(s||B)return;if(-1===ce){const t=e.lastIndexOf("\n"),n=-1===t||pe.current>t;return void((0===e.length||n)&&listShellTasks().some(e=>"running"===e.status)&&ae(!0))}const t=e.lastIndexOf("\n");if(!(-1===t||pe.current>t))return;const r=ce-1;return de(r),n(-1===r?ue:M?.getAt(r)||""),void $(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void _e();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return te.current=!0,void ye();if(isCtrlKey({inputChar:t,key:r,letter:"s",ctrlCode:19})){const t=e.trim().length>0;if(!t&&null===Z)return;if(!t&&je())return;te.current=!0;const r=Z??"";return ee(t?e:null),n(r),Ue(),void setTimeout(()=>{te.current=!1},0)}if(getIsExpandToolShortcut(r,t))return te.current=!0,n(e),$(e=>e+1),void setTimeout(()=>{te.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Ce()}))return ne.current=!0,We(),void setTimeout(()=>{ne.current=!1},0);if(r.meta&&"w"===t)return te.current=!0,void Be();const o=r.ctrl&&"v"===t||hN.includes(t),a=r.meta&&"v"===t;if(o||a){if(o&&"darwin"===process.platform){const t=e;te.current=!0;const r=await detectClipboardImage();if(r){const e=nextImagePasteNumber(Q),{text:o,cursor:s}=insertTextAt(t,pe.current,imagePasteToken(e));X(t=>[...t,{imageNumber:e,image:r}]),n(o),le.current=s,$(e=>e+1)}return void(te.current=!1)}}else if(!r.ctrl&&!r.meta||"u"!==t)if(r.ctrl&&"z"===t?.toLowerCase())ge();else{if(r.escape){if(B)return;const t=Date.now();return t-K.current<500?(e.length>0?Be():A?.(),K.current=0,q.current=0,F(!1),void j(!1)):(K.current=t,_||U||(q.current=t),F(!1),void j(!1))}_&&(r.backspace||r.delete)&&0===e.length&&F(!1)}});const He=dt(async t=>{if(he)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void R?.();const o=processBracketedPaste(t),a=findInsertion({before:e,after:t}),d=null!==a&&looksLikeDroppedImagePath(a.text);if((o.isPasteStart||o.isPasteEnd||d||Ce())&&await ve(t))return void(ie.current=!0);if(te.current)return void(te.current=!1);-1!==ce&&de(-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 $(e=>e+1);if("!"===m&&!U)return F(!1),j(!0),n(""),void $(e=>e+1)}const p=sf(t),g=t.length<e.length&&!e.startsWith(t),h=!g&&t.length<e.length,f=t.length===e.length+1||h,y=af({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&&i(S.showFileList),S.query!==l&&c(S.query),_&&(t!==e||t.length<e.length)&&F(!1),fe&&Se(),0===t.length&&(j(!1),Fe(),G(""),J([]),c(""),ke()),n(t)},[_,e,n,s,i,l,c,B,H,U,ce,ve,ke,Ce,R,fe,Se,he,Fe]),Ge=dt(async()=>{if(Oe(),q.current=0,_)return void F(!1);const r=e.trim(),o=!U&&r.startsWith("/");let s=r;!U&&Y.length>0&&(s=resolvePastedTextTokens({input:s,detectedContent:Y}));const a=U?[]:resolvePastedImageTokens({input:r,images:Q}),i={};if(!U)for(const e of Q){if(!r.includes(imagePasteToken(e.imageNumber)))continue;const t=Te.get(e.imageNumber);t&&(i[e.imageNumber]=t)}const l=Object.keys(i).length>0,c=Ae?KC(Ae):void 0;if(o&&d&&(n(""),"handled"===(await d(s,a,c)).status))return M?.add(s),j(!1),Fe(),G(""),_e(),J([]),de(-1),me(""),void je({replaceCurrentInput:!0});de(-1),me(""),s.length>0&&M?.add(s);const u=buildIdeContextHint({ideContext:Ae});t({input:s,role:U?"bash":"user",images:a,ideContext:c,ideHint:u,imageTokenPaths:l?i:void 0}),j(!1),Fe(),G(""),_e(),J([]),je({replaceCurrentInput:!0})},[t,d,_,e,U,Q,Te,Y,M,Oe,Ae,_e,Fe,je,n]),Ve=dt(t=>{const r=a(process.cwd(),t),o=r.includes(" ")?`"${r}"`:r,d=buildFileMentionInput({currentInput:e,mentionPath:o,isSearchMode:s&&""!==l});n(d),i(!1),c(""),$(e=>e+1)},[n,i,e,s,l,c]),ze=dt(()=>{i(!1),c("")},[i,c]),Ke=dt(e=>{const t=ef.has(e),r="/design"===e.trimEnd();if(t||r){const t=e.trimEnd();return n(t+" "),G(t.substring(1)+" "),void $(e=>e+1)}Fe(),G(""),n(e+" "),$(e=>e+1)},[n,Fe]),qe=dt(t=>{if("/design help"===t)return Fe(),G(""),n(""),$(e=>e+1),M?.add(t),void d?.("/design help");if(Zh.has(t))return Fe(),G(""),M?.add(t),de(-1),me(""),n(""),$(e=>e+1),void d?.(t);const r=ef.has(t),o=da.has(t),s=ua.has(t);if(r)Ke(t);else{if(Fe(),G(""),!o&&!s&&e!==t)return n(t+" "),void $(e=>e+1);M?.add(t),de(-1),me(""),n(""),$(e=>e+1),d?.(t)}},[d,n,e,M,Ke,Fe]),Ye=dt(()=>{Fe(),G(""),de(-1),me(""),$(e=>e+1)},[Fe]),Xe=dt(e=>{pe.current=e,le.current=void 0},[]),et=ct(()=>formatSlashCommandInputHint({value:e,selectedCommand:B?V:null}),[e,B,V]),nt=Boolean(et)&&!x,rt=ct(()=>{const t=$e&&("OPEN"===$e.state||"MERGED"===$e.state);return"auto-accept"===E||"plan"===E||"bypass"===E||"dont-ask"===E||Re||t?!_:!_&&0===e.length&&!U},[_,e,U,E,Re,$e]),st=null!==Z,ut=__name(()=>_||s||B?0:nt||rt||x||U?3:4,"getBottomMargin");return ot.createElement(Je,{width:"100%",flexDirection:"column",marginBottom:ut()},ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(Qe,{color:U?nI.GREEN:nI.GRAY},pt.line.repeat(Ne)),(()=>{const t=__name(()=>{if(se.current&&(ae(!1),listShellTasks().some(e=>"running"===e.status)))requestBackgroundTasksExpand();else{if(!ne.current)return Date.now()-q.current<100?(q.current=0,void We()):void(s||B||he||Ge());ne.current=!1}},"handleTextInputSubmit"),n=__name(n=>ot.createElement(TextInput,{key:N,value:e,placeholder:he?"Save and close the editor to continue...":o,onChange:He,onSubmit:t,showCursor:!he&&r,onCursorChange:Xe,initialCursor:le.current,prefix:`${U?"!":pt.pointer} `,prefixColor:U?nI.GREEN:nI.WHITE,singleLine:n?.singleLine,maxWidth:n?.maxWidth,imageTokenLinks:Te,isRecognizedSlashCommand:Ie,disablePasteRouting:!0}),"renderTextInput"),a=B?"/model"===V&&C?getModelHintText(C):et:null,i=a?getCommandHintLayout({text:a,terminalWidth:Ne}):null;return i?ot.createElement(Je,{flexDirection:"row",width:"100%"},ot.createElement(Je,{width:25},n({singleLine:!0,maxWidth:25})),ot.createElement(Je,{width:i.descriptionWidth},ot.createElement(Qe,{color:nI.DIM,wrap:"truncate"},i.text))):n()})(),ot.createElement(Qe,{color:U?nI.GREEN:nI.GRAY},pt.line.repeat(Ne))),_&&ot.createElement(fN,null),s&&ot.createElement(cN,{onSelectFile:Ve,onClose:ze,searchQuery:l}),B&&ot.createElement(xI,{onSelectCommand:qe,onInsertCommand:Ke,onSubmitSearch:Ge,onClose:Ye,searchQuery:H,onSelectedCommandChange:z}),!B&&!s&&nt&&ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM,wrap:"truncate"},et)),!B&&!s&&!nt&&(rt||x||st)&&ot.createElement(gN,{termWidth:Ne,indicatorText:getIdeInputIndicatorText(Re,Ae,Ne),isIDEIndicator:hasIdeInputIndicatorContext(Re,Ae),permissionMode:E,prInfo:$e,contextUsage:u,tasteLearningOn:m,byokSession:isByok({model:C??""}),connectionIndicator:Le,pendingExitKey:x,updateStatus:w,updateFailedInfo:v,currentProvider:k,showProviderInfo:b,isBashMode:U,shareInfo:g,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,creditWarning:S,hasStashedPrompt:st,backgroundTasksArmed:re}),fe&&ot.createElement(Je,{paddingLeft:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.YELLOW},fe)),D)},"InputBox");Ht(),Qx();var SN=__name(()=>{const[e,t]=at([]);return lt(()=>subscribeModStatus(t),[]),0===e.length?null:ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,{wrap:"truncate"},e.map(e=>e.text).join(" ")))},"ModStatusLine");Ht(),Qx();var wN=__name(({messages:e})=>{const t=countVisibleQueuedMessages(e);if(0===t)return null;const n=getQueuedDisplayRows(e);return ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Je,{marginBottom:0},ot.createElement(Qe,{color:aI,inverse:!0},` Queued (${t}) `)),n.map(e=>ot.createElement(Je,{key:e.text},ot.createElement(Qe,{color:nI.DIM},pt.pointerSmall," "),ot.createElement(Qe,{color:nI.DIM},truncateString2({text:e.count>1?`${e.text} (${e.count})`:e.text,maxChars:80})))))},"QueuedMessages");function useWorkedDuration(e,t){const n=it(null),[r,o]=at(null);return lt(()=>{n.current=null,o(null)},[t]),lt(()=>{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:ot.createElement(Je,{marginLeft:1,marginBottom:1},ot.createElement(Qe,{color:nI.DIM},`✻ Worked for ${formatElapsedMs(e)}`))}Ht(),Qx(),__name(useWorkedDuration,"useWorkedDuration"),__name(WorkedDurationNote,"WorkedDurationNote");var vN=ot.memo(({queuedMessages:e,isProcessing:t,processingStartedAt:n=null,executionState:r,status:o,input:s,setInput:a,onSubmit:i,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:O,onDoubleEscapeEmpty:L,retryAttempt:D,onAltP:N,inputActive:$=!0,inactiveHint:_,sessionId:F})=>{const[U,j]=at(()=>null===n?0:Date.now()-n),B=it(s),W=t||r.isExecuting,H=useWorkedDuration(W,F);return lt(()=>{R&&s!==B.current&&s.length>0&&O?.(),B.current=s},[s,R,O]),lt(()=>{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]),ot.createElement(Je,{flexDirection:"column"},ot.createElement(wN,{messages:e}),ot.createElement(Je,{flexDirection:"row",justifyContent:"space-between"},ot.createElement(Je,{flexDirection:"column"},W&&null===D&&ot.createElement(sN,{tokens:p,timeElapsed:U,status:r.isExecuting?`Executing: ${r.currentCommand}`:o}),!W&&ot.createElement(WorkedDurationNote,{durationMs:H}),W&&null===D&&I&&ot.createElement(Je,{marginLeft:1},ot.createElement(Qe,{color:nI.DIM}," ","⎿"," ","Tip: ",I)))),$?ot.createElement(yN,{input:s,setInput:a,onSubmit:i,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:L,onAltP:N,isProcessing:t,footer:ot.createElement(SN,null)}):ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{marginLeft:1},ot.createElement(HA,null,_??"Background focused · ↑/↓ to select · Enter to view · x to stop · ←/Esc to go back to feed")),ot.createElement(SN,null)))});Ht();var kN=__name(({onComplete:e,onCancel:t})=>{const{authState:n,statusMessage:r,browserUrl:o,apiKeyInput:s,setApiKeyInput:a,handleApiKeySubmit:i,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 tt((e,t)=>{t.ctrl&&"c"===e&&l()}),ot.createElement(tR,{authState:n,statusMessage:r,browserUrl:o,apiKeyInput:s,setApiKeyInput:a,handleApiKeySubmit:i})},"LoginOverlay");function getStatusTextColor(e){return"connected"===e?nI.GREEN:"connecting"===e||"authenticated"===e?nI.CYAN:"requires_auth"===e?nI.YELLOW:nI.GRAY}Ht(),Qx(),__name(getStatusTextColor,"getStatusTextColor");var CN=__name((e,t)=>{const n=__name((e,n)=>ot.createElement(Qe,{color:e,backgroundColor:t},n),"icon");return"connected"===e?n(nI.GREEN,pt.tick):"connecting"===e?n(nI.CYAN,pt.circle):"authenticated"===e?n(nI.CYAN,pt.tick):"requires_auth"===e?n(nI.YELLOW,pt.warning):"error"===e?n(nI.RED,pt.cross):n(nI.GRAY,pt.circle)},"getStatusIcon"),bN=__name(({onClose:e,mcp:t})=>{const[n,r]=at([]),[o,s]=at(!0),[a,i]=at(0),[l,c]=at("list"),[d,u]=at(null),[m,p]=at(0),g=useTerminalHeight(),h=dt(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]);lt(()=>{h()},[h]),lt(()=>{if(t)return t.onChange(()=>{h()})},[t,h]);const f=ct(()=>[...orderMcpManagerServers(n)],[n]),y=f[a]??null,S=g-1,w=ct(()=>new Set(f.map(e=>e.scope)).size,[f]),v=Math.max(4,S-8-2*w);lt(()=>{p(e=>clampScrollOffset({cursor:a,total:f.length,maxVisible:v,currentOffset:e}))},[a,f.length,v]),tt((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&&(i(e=>Math.max(0,e-1)),u(null)),n.downArrow){if(0===f.length)return;const e=Math.max(0,f.length-1);i(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:nI.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:y.name,enabled:!0,scope:y.scope}))return void u({text:`${pt.cross} Failed to enable ${y.name}, server may no longer exist in ${y.scope} scope`,color:nI.YELLOW});await h(),u({text:`${pt.tick} Enabled ${y.name}`,color:nI.GREEN})}catch(e){u({text:`${pt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:nI.RED})}}else{u({text:`Disabling ${y.name}...`,color:nI.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:y.name,enabled:!1,scope:y.scope}))return void u({text:`${pt.cross} Failed to disable ${y.name}, server may no longer exist in ${y.scope} scope`,color:nI.YELLOW});await disconnectMcpServer({name:y.name,registry:t}),await h(),u({text:`${pt.tick} Disabled ${y.name}`,color:nI.GREEN})}catch(e){u({text:`${pt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:nI.RED})}}else c("confirm-remove");else{u({text:`Authenticating ${y.name}...`,color:nI.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:nI.YELLOW});"success"===e.kind?(u({text:`${pt.tick} Authenticated with ${y.name}`,color:nI.GREEN}),await h()):u({text:`${pt.cross} Auth failed: ${e.message}`,color:nI.RED})}catch(e){u({text:`${pt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:nI.RED})}}else{u({text:`Connecting ${y.name}...`,color:nI.CYAN,loading:!0});try{await connectMcpServer({name:y.name,registry:t}),u({text:`${pt.tick} Connected to ${y.name}`,color:nI.GREEN}),await h()}catch(e){u({text:`${pt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:nI.RED})}}else u({text:"Already authenticated",color:nI.GREEN});else u({text:"Already connected",color:nI.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(),i(e=>Math.min(e,Math.max(0,f.length-2)))}catch(e){u({text:`${pt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:nI.RED}),c("actions")}else c("actions")},"handleRemoveConfirm");if(o)return ot.createElement(ZA,{title:"Manage MCP servers"},ot.createElement(Qe,{color:nI.DIM},"Loading..."));if("confirm-remove"===l&&y)return ot.createElement(ZA,{title:`Remove ${y.name}?`,titleColor:nI.RED,hint:"↑↓ navigate · Enter to select · Esc to cancel"},ot.createElement(Qe,{color:nI.DIM},"This will remove the server from ",y.scope," ","config."),ot.createElement(Je,{marginTop:1},ot.createElement(SelectInput,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:C,indicatorComponent:YL,itemComponent:qL})));if("actions"===l&&y){const e=buildMcpManagerActionItems(y);return ot.createElement(ZA,{title:y.name,hint:"↑↓ navigate · Enter to select · Esc to go back"},ot.createElement(Je,null,CN(y.status),ot.createElement(Qe,{color:nI.DIM}," ",getMcpManagerStatusText(y))),ot.createElement(Je,{marginTop:1},ot.createElement(SelectInput,{items:[...e],onSelect:k,indicatorComponent:YL,itemComponent:qL})),d&&ot.createElement(Je,{marginTop:1},d.loading&&ot.createElement(Qe,{color:d.color},ot.createElement(vt,{type:"dots"})," "),ot.createElement(Qe,{color:d.color},d.text)))}let b=null;const E=m,T=m+v,P=f.slice(E,T),M=f.length>v;return ot.createElement(ZA,{title:"Manage MCP servers",hint:0===n.length?"Esc to close":"↑↓ navigate · Enter to select · Esc to close"},ot.createElement(Qe,{color:nI.DIM},n.length," ",1===n.length?"server":"servers"),0===n.length?ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},"No MCP servers configured."),ot.createElement(Qe,{color:nI.DIM},'Use "',getBinaryCommand(),' mcp add" to add a server.'),ot.createElement(BI,{url:"https://commandcode.ai/docs/mcp",text:"View MCP Docs ↗",color:nI.CYAN,dimColor:!0})):ot.createElement(Je,{marginTop:1,flexDirection:"column"},P.map((e,t)=>{const n=E+t,r=e.scope!==b;b=e.scope;const o=n===a;return ot.createElement(ot.Fragment,{key:e.name},r&&ot.createElement(Je,{marginTop:0===t?0:1},ot.createElement(Qe,{bold:!0},getMcpManagerScopeLabel(e.scope)),ot.createElement(Qe,{color:nI.DIM}," ","(",getMcpManagerScopePath(e.scope),")")),ot.createElement(Je,null,ot.createElement(Qe,{color:o?nI.WHITE:void 0,backgroundColor:o?TI:void 0,bold:o},e.name),ot.createElement(Qe,{color:nI.DIM,backgroundColor:o?TI:void 0}," · "),CN(e.status,o?TI:void 0),ot.createElement(Qe,{color:getStatusTextColor(e.status),backgroundColor:o?TI:void 0}," ",getMcpManagerStatusText(e)," ")))})),M&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",E+1,"–",Math.min(T,f.length)," of"," ",f.length,E>0?" · ↑ more":"",T<f.length?" · ↓ more":"")),d&&ot.createElement(Je,{marginTop:1},d.loading&&ot.createElement(Qe,{color:d.color},ot.createElement(vt,{type:"dots"})," "),ot.createElement(Qe,{color:d.color},d.text)))},"McpManager");Ht(),Qx();var EN=__name(({onClose:e})=>{const[t,n]=at([]),[r,o]=at(0),[s,a]=at(!0),[i,l]=at(null);lt(()=>{__name(async()=>{try{const e=await discoverCommandMemoryFiles(process.cwd());n(e),a(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),a(!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(tt((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 ot.createElement(ZA,{title:"Select memory to edit:"},ot.createElement(Qe,{color:nI.DIM},"Loading memory files..."));if(i)return ot.createElement(ZA,{title:"Select memory to edit:"},ot.createElement(Qe,{color:nI.RED},pt.cross," ",i));const u=projectMemorySelectorOptions(d);return ot.createElement(ZA,{title:"Select memory to edit:",hint:"↑/↓ to navigate · enter to edit · esc to cancel"},ot.createElement(Je,{columnGap:4},ot.createElement(Je,{flexDirection:"column"},u.map((e,t)=>ot.createElement(Je,{key:e.label},ot.createElement(WL,{isSelected:r===t}),ot.createElement(HL,{isSelected:r===t,idleColor:QA}," ",e.label)))),ot.createElement(Je,{flexDirection:"column"},u.map((e,t)=>ot.createElement(HL,{key:e.label,isSelected:r===t,idleColor:QA},e.description)))))},"MemorySelector");function linkImageTokens(e,t){if(!t)return e;const n=new RegExp(CT.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)?nI.DIM:nI.RED,s=r?getSpecialUserMessageContent({content:e,billingUrl:Go}):linkImageTokens(e,n);return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{backgroundColor:r?void 0:gI.BG,paddingRight:1},ot.createElement(Qe,{color:r?o:gI.POINTER,bold:!r},pt.pointer),ot.createElement(Je,{marginLeft:1},ot.createElement(Qe,{color:r?o:gI.FG,wrap:"wrap"},s))),t&&!r&&ot.createElement(Je,{marginLeft:2},ot.createElement(Qe,{color:EI},YI),ot.createElement(Qe,{color:nI.DIM}," ","Selected ",t.lines," ",1===t.lines?"line":"lines"," from"," ",t.file," in ",t.ide)))}Ht(),Qx(),Ht(),Qx(),__name(linkImageTokens,"linkImageTokens"),__name(UserMessage,"UserMessage");var TN=pt.squareSmallFilled;function goalStatusGlyph(e){return"completed"===e?pt.tick:"paused"===e?"⏸":"idle"===e?pt.circle:TN}function goalStatusHeadColor(e){return"completed"===e?nI.GREEN:"paused"===e?nI.YELLOW:nI.DIM}function goalNoticeGlyph(e){return"cleared"===e?pt.tick:"none"===e?pt.circle:"paused"===e?"⏸":TN}function AutoCompactMessage({content:e}){return ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},TN," ",e))}function ZdrPausedMessage(){return ot.createElement(Je,{marginTop:1,marginBottom:1},ot.createElement(Qe,null,ot.createElement(Qe,{color:nI.DIM},TN," "),ot.createElement(Qe,{color:nI.DIM},"Per-task model overrides reverted to ZDR safe defaults. Run"," "),ot.createElement(Qe,{color:vI.CODE},"/config"),ot.createElement(Qe,{color:nI.DIM}," to review · esc to dismiss")))}function ModelNoticeMessage({text:e}){return ot.createElement(Je,{marginTop:1,marginBottom:1},ot.createElement(Qe,null,ot.createElement(Qe,{color:nI.DIM},TN," "),ot.createElement(Qe,{color:nI.DIM},e),ot.createElement(Qe,{color:nI.DIM}," · esc to dismiss")))}function TasteSkipMessage(){return ot.createElement(Je,{marginTop:1,marginBottom:1},ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:oI.BADGE_BG,color:oI.BADGE_FG,bold:!0},XI)),ot.createElement(Qe,{color:nI.DIM}," Skipped. Run "),ot.createElement(Qe,{color:vI.CODE},"/learn-taste"),ot.createElement(Qe,{color:nI.DIM}," or "),ot.createElement(Qe,{color:vI.CODE},"cmd learn-taste"),ot.createElement(Qe,{color:nI.DIM}," anytime."))}function TasteNoticeMessage({notice:e}){const t=e.path?`${tasteDirForRoot({projectRoot:process.cwd()})}/${e.path}`:null;return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:oI.BADGE_BG,color:oI.BADGE_FG,bold:!0},XI)),ot.createElement(Qe,{color:oI.TEXT}," ",e.label)),ot.createElement(Je,{columnGap:1,marginLeft:1},ot.createElement(Qe,{color:EI},YI),ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{wrap:"wrap"},e.text,e.confidence&&ot.createElement(Qe,{color:nI.DIM},` [Confidence ${e.confidence}]`)))),e.path&&t&&ot.createElement(Je,{marginLeft:3},ot.createElement(BI,{url:fileUrl(t),text:e.path,color:nI.DIM})))}function SkillLoadedMessage({name:e}){return ot.createElement(Je,null,ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:lI.BG,color:lI.FG,bold:!0},`${QI}SKILL${QI}`)),ot.createElement(Qe,null," ",e),ot.createElement(Qe,{color:nI.DIM}," loaded"))}function HookWarningMessage({content:e}){return ot.createElement(Je,null,ot.createElement(Qe,{color:nI.YELLOW},pt.warning),ot.createElement(Je,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.YELLOW},e)))}function HookLineMessage({content:e}){return ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},` ${e}`))}function HookLineContinuationMessage({content:e}){return ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},` ${e}`))}function HookFrameMessage({lines:e,header:t}){return ot.createElement(Je,{flexDirection:"column"},void 0!==t&&ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},` ${t}`)),e.map((e,t)=>ot.createElement(Je,{key:t,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},e.primary?` └ ${e.text}`:` ${e.text}`))))}function GoalLineMessage({content:e,subline:t}){return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:EI},YI),ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"}," ",e)),t?ot.createElement(Je,{marginLeft:4,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"},t)):null)}function GoalAcceptMessage({command:e,acceptLine:t,hint:n}){return ot.createElement(Je,{flexDirection:"column"},ot.createElement(UserMessage,{content:e}),ot.createElement(GoalLineMessage,{content:t,subline:n}))}function GoalCompleteMessage({elapsed:e,turns:t,goal:n}){const r=`${t} ${1===t?"turn":"turns"}`;return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,null,ot.createElement(Qe,{color:nI.GREEN},pt.tick," Goal achieved"),ot.createElement(Qe,{color:nI.DIM},` (${e} · ${r})`))),ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"},"Goal: ",n)))}function GoalStatusMessage({state:e,headline:t,goal:n,detail:r,hint:o}){const s=goalStatusGlyph(e),a=goalStatusHeadColor(e);return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:a},s," ",t)),ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"},n)),r?ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"},r)):null,o?ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},o)):null)}function BranchResultMessage({title:e}){return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},e?ot.createElement(Qe,null,ot.createElement(Qe,{color:nI.GREEN},"⑂ Forked."),ot.createElement(Qe,null," You're now in "),ot.createElement(Qe,{bold:!0},'"',e,'"')):ot.createElement(Qe,null,ot.createElement(Qe,{color:nI.GREEN},"⑂ Forked."),ot.createElement(Qe,null," You're now in the new session"))),ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},"Original session saved · /resume to switch back")))}function SessionFileMessage({sessionId:e,fileLine:t}){return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},TN," Session ID: "),ot.createElement(Qe,null,e)),ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:EI},YI," "),ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"},t)))}function InfoMessage({content:e,metadata:t}){if(t?.isTasteSkip)return ot.createElement(TasteSkipMessage,null);if(t?.tasteNotice)return ot.createElement(TasteNoticeMessage,{notice:t.tasteNotice});if(t?.skillLoaded)return ot.createElement(SkillLoadedMessage,{name:t.skillLoaded.name});if(t?.isAutoCompact)return ot.createElement(AutoCompactMessage,{content:e});if(t?.hookFrame&&t.hookFrame.length>0)return ot.createElement(HookFrameMessage,{lines:t.hookFrame,header:t.hookFrameHeader});if(t?.isHookLine)return ot.createElement(HookLineMessage,{content:e});if(t?.isHookLineContinuation)return ot.createElement(HookLineContinuationMessage,{content:e});if(t?.isHookWarning)return ot.createElement(HookWarningMessage,{content:e});if(t?.isSuccess)return ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.GREEN},pt.tick," ",e));if(t?.isGoalAccept)return ot.createElement(GoalAcceptMessage,{command:e,acceptLine:t.goalAcceptLine??"",hint:t.goalSubline});if(t?.isGoalComplete)return ot.createElement(GoalCompleteMessage,{elapsed:t.goalElapsed??"",turns:t.goalTurns??1,goal:t.goalText??""});if(t?.isGoalStatus)return ot.createElement(GoalStatusMessage,{state:t.goalState??"running",headline:t.goalHeadline??"",goal:t.goalText??"",detail:t.goalDetail,hint:t.goalSubline});if(t?.isBranchResult)return ot.createElement(BranchResultMessage,{title:t.branchTitle});if(t?.isSessionFile)return ot.createElement(SessionFileMessage,{sessionId:t.sessionFileId??"",fileLine:t.sessionFileLine??""});if(t?.isGoalNotice){const n=goalNoticeGlyph(t.goalNoticeKind);return ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},n," ",e))}return t?.isGoalLine?ot.createElement(GoalLineMessage,{content:e,subline:t.goalSubline}):ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},TN," ",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"),Ht(),Qx(),Ht(),Ht(),Ht(),Ht();var PN=/\[\^[^\]]+\]/;function splitMarkdownBlocks(e){return e?PN.test(e)?[e]:ft.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),a=[];let i=0;for(const o of s){const s=i+o.length;if(s<=e.length){if(e.slice(i,s)!==o)return n=!0,frozenAdvance(r)}else{if(i!==e.length)return n=!0,frozenAdvance(r);a.push(o),e+=o,isWhitespaceOnly2(o)||(t+=1)}i=s}return{newlyCompleted:a,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"),Ht();var MN=String.fromCharCode(8203),xN=new Set(["_","~","*","`"]),IN=/!?\[[^\]]*\]\([^)]*$/,AN=/!?\[[^\]]*$/;function isSpace(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function isOnlyMarkersOrSpace(e){for(const t of e)if(!isSpace(t)&&!xN.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 a=e[s];"\\"!==a?e.startsWith("```",s)?(r=!r,s+=2):r||("`"!==a?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(IN);if(void 0!==t?.index)return e.slice(0,t.index).trimEnd();const n=e.match(AN);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}${MN}`: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 RN=Ct()?"⠶":"#";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 ot.createElement(Je,null,n?ot.createElement(Je,{width:2,flexShrink:0}):ot.createElement(Qe,{color:hI},RN),ot.createElement(Je,{marginLeft:n?0:1,flexGrow:1,flexShrink:1,minWidth:0,flexDirection:"column"},ot.createElement(Markdown,{maxPhysicalRows:t?streamingMaxRows(r):void 0},o)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o=nI.GREEN,s=pt.tick,a="default",i=t||"(No output)";n&&(o=nI.YELLOW,s=pt.arrowRight,a=nI.YELLOW,i="Executing…"),r&&(o=nI.RED,s=pt.cross,a=nI.RED);const l=ct(()=>buildTreeConnectors(i),[i]);return ot.createElement(Je,null,ot.createElement(Qe,{color:o},s),ot.createElement(Je,{flexDirection:"column",marginLeft:1},ot.createElement(Je,null,ot.createElement(Qe,{color:nI.GRAY},"$ "),ot.createElement(Qe,{color:o,bold:!0},e)),ot.createElement(Je,{columnGap:1,marginLeft:1},ot.createElement(Qe,{color:EI},l),ot.createElement(Qe,{color:a,wrap:"wrap"},i))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?nI.YELLOW:void 0,o=ct(()=>buildTreeConnectors(e),[e]);return ot.createElement(Je,{flexDirection:"column",marginBottom:0,marginTop:-1},ot.createElement(Je,{columnGap:1},ot.createElement(Qe,{color:EI},o),ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:r},e))),t&&ot.createElement(Je,{marginLeft:3},ot.createElement(Qe,{color:nI.DIM},"See ",t)))}function ErrorMessage({content:e}){return isInterruptedByUserMessage(e)?ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},pt.pointer),ot.createElement(Je,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"},jf))):ot.createElement(Je,null,ot.createElement(Qe,{color:nI.RED},pt.warning),ot.createElement(Je,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Markdown,{color:nI.RED},e)))}__name(streamingMaxRows,"streamingMaxRows"),__name(AssistantMessage,"AssistantMessage"),Ht(),__name(BashMessage,"BashMessage"),Ht(),__name(CommandResultMessage,"CommandResultMessage"),Ht(),Qx(),__name(ErrorMessage,"ErrorMessage"),Ht(),Qx();var ON={connected:{char:pt.tick,color:nI.GREEN},installed:{char:pt.tick,color:nI.GREEN},up_to_date:{char:pt.tick,color:nI.GREEN},needs_reload:{char:pt.circle,color:nI.YELLOW},failed:{char:pt.cross,color:nI.RED},not_in_ide:{char:pt.circle,color:nI.YELLOW}};function IDEStatusMessage({status:e,ide:t,details:n}){const{prefix:r,ide:o,suffix:s}=getIDESetupStatusHeadline(e,t),a=ON[e];return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,null,ot.createElement(Qe,{color:a.color},a.char),ot.createElement(Qe,null," ",r),o&&ot.createElement(Qe,{color:nI.CYAN},o),s&&ot.createElement(Qe,null,s))),n?.map(e=>ot.createElement(Qe,{key:e,color:nI.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 ot.createElement(Je,{flexDirection:"column",width:"90%"},ot.createElement(Je,null,ot.createElement(Qe,{color:sI},"✻"," "),ot.createElement(Qe,{color:sI},o.showExpandHint?`${o.headerLabel} `:o.headerLabel),o.showExpandHint&&ot.createElement(BracketWrap,{color:nI.DIM},o.expandHint)),o.showBody&&o.hiddenAboveLabel&&ot.createElement(Je,{marginLeft:2},ot.createElement(Qe,{color:nI.DIM},o.hiddenAboveLabel)),o.showBody&&ot.createElement(Je,{marginLeft:2,flexDirection:"column"},ot.createElement(Qe,{color:sI,wrap:"wrap",italic:!0},o.bodyText)))}__name(IDEStatusMessage,"IDEStatusMessage"),Ht(),Qx(),__name(reasoningBodyColumns,"reasoningBodyColumns"),__name(ReasoningMessage,"ReasoningMessage"),Ht(),Qx(),Ht(),Qx();function HelpMessage(){const e=getInvokedCommandName(),t=ct(()=>getVisibleSlashCommands(),[]);return ot.createElement(Je,{flexDirection:"column",paddingY:1},ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Je,null,ot.createElement(Qe,{bold:!0},"Command Code"),ot.createElement(Qe,{color:nI.GRAY}," v","1.32.1")),ot.createElement(Qe,{color:nI.GRAY},Hs)),ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{bold:!0},"Usage"),ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,null,e," <command> [options]"))),ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{bold:!0},"Options"),ot.createElement(Je,{flexDirection:"column",paddingLeft:2},Ys.map(t=>ot.createElement(Je,{key:t.key},ot.createElement(Qe,null,t.key.replace(/^cmd/,e).padEnd(Gs)),ot.createElement(Qe,{color:nI.GRAY},t.description))))),ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{bold:!0},"Commands"),ot.createElement(Je,{flexDirection:"column",paddingLeft:2},Qs.map(t=>ot.createElement(Je,{key:t.key},ot.createElement(Qe,null,t.key.replace(/^cmd/,e).padEnd(Gs)),ot.createElement(Qe,{color:nI.GRAY},t.description))))),ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{bold:!0},"Slash Commands"),ot.createElement(Je,{flexDirection:"column",paddingLeft:2},t.map(e=>ot.createElement(Je,{key:e.key},ot.createElement(Qe,null,e.key.padEnd(Gs)),ot.createElement(Qe,{color:nI.GRAY},e.description))))),ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{bold:!0},"Keyboard Shortcuts"),ot.createElement(Je,{flexDirection:"column",paddingLeft:2},qs.map(e=>ot.createElement(Je,{key:e.key},ot.createElement(Qe,null,e.key.padEnd(Gs)),ot.createElement(Qe,{color:nI.GRAY},e.description))))),ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{bold:!0},"Examples"),ot.createElement(Je,{flexDirection:"column",paddingLeft:2},Zs.map(t=>ot.createElement(Je,{key:t.key},ot.createElement(Qe,null,t.key.replace(/^cmd/,e).padEnd(Gs)),ot.createElement(Qe,{color:nI.GRAY},t.description))))),ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.CYAN},pt.pointer),ot.createElement(Qe,{color:nI.GRAY}," ",Vs.replace(/cmd/,e))),ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{bold:!0},"Links"),ot.createElement(Je,{flexDirection:"column",paddingLeft:2},Xs.map(e=>ot.createElement(Je,{key:e.key},ot.createElement(Qe,null,e.key.padEnd(Gs)),ot.createElement(Qe,{color:nI.CYAN},e.description))))))}function SystemMessage({content:e}){return isHelpSystemEntryContent(e)?ot.createElement(HelpMessage,null):ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{wrap:"wrap"},ot.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 ot.createElement(UserMessage,{content:e.input,ideHint:t,imageTokenPaths:n})}return"assistant"===e.role?ot.createElement(AssistantMessage,{content:e.input,isStreaming:"running"===e.metadata?.status,continuation:!0===e.metadata?.continuation}):"reasoning"===e.role?ot.createElement(ReasoningMessage,{content:e.input,expandedOutput:t,expandKey:"ctrl",isStreaming:"running"===e.metadata?.status}):"tool"===e.role?ot.createElement(ToolMessage,{name:Mg(e.name||""),input:e.input,output:e.output||"",isPending:bg(e),hasError:Cg(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?ot.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:bg(e),hasError:Cg(e)}):"system"===e.role?ot.createElement(SystemMessage,{content:e.input}):"info"===e.role?ot.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?ot.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?ot.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?ot.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 LN=__name(e=>getModelShortName({modelId:e,findModelById:findModelById}),"getModelShortName");function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages [${db?"ctrl+y":"ctrl+e"} to expand more] `,r=Math.max(0,Math.floor((t-n.length)/2)),o="─".repeat(r);return ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:pI},o),ot.createElement(BracketedText,{text:n,color:pI}),ot.createElement(Qe,{color:pI},o))}__name(TranscriptDivider,"TranscriptDivider");var DN=ot.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o,currentEffort:s=null,currentProvider:a,hiddenCount:i=0})=>{const l=i>0?{role:"transcript-divider",count:i}:null,c=[...t?["header"]:[],...l?[l]:[],...e],d=useTerminalWidth(),u=ct(()=>RA(d),[d]),m=ct(()=>$A(d),[d]),p=ct(()=>getPackageJson(import.meta.url).version||"0.0.0",[]),g=ct(()=>getGitHeaderInfo(),[]),h=ct(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),f=o?LN(o):"sonnet-4.6",y=Boolean(o&&byokProviderId({model:o}))?"":" · taste-1",S=ct(()=>{if(!o)return"";if(!modelSupportsReasoningEffort(o))return"";const e=null===s?getReasoningEffort(o):s;return e?` with ${e} effort`:""},[s,o,n]),w=ct(()=>{const e=o?byokProviderId({model:o}):void 0;return e?` · ${e} (byok)`:a&&a!==ro.COMMAND?` · ${getProviderShortName(a)} (byok)`:""},[o,a,n]);return ot.createElement(Xe,{items:c,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return ot.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:d});if("header"===e)return"compact"===m?ot.createElement(Je,{key:"header",marginBottom:1,flexDirection:"row"},ot.createElement(Je,{width:DA,flexShrink:0},ot.createElement(PI,null,LA)),ot.createElement(Je,{flexDirection:"column",marginLeft:2},ot.createElement(Je,null,ot.createElement(Qe,{bold:!0},"Command Code"),ot.createElement(Qe,{color:pI}," ","v",p)),ot.createElement(Qe,{color:pI},"models: ",f,S,y,w),ot.createElement(Qe,{color:pI},h,g&&g.isLocal&&g.branch&&` (${g.branch})`))):ot.createElement(Je,{key:"header",marginBottom:1,flexDirection:"column"},ot.createElement(PI,null,u.trimEnd()),ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Je,null,ot.createElement(Qe,{color:pI},"# "),ot.createElement(Qe,{bold:!0},"Command Code"),ot.createElement(Qe,{color:pI}," v",p)),ot.createElement(Qe,{color:pI},"# models: ",f,S,y,w),ot.createElement(Je,null,ot.createElement(Qe,{color:pI},"# ",h,g&&g.isLocal&&g.branch&&ot.createElement(Qe,{color:pI}," ","(branch:"," ",g.branch,")")))));const t=e,n=renderFeedEntry(t,r);return ot.createElement(Je,{key:t.id,paddingBottom:1,width:"90%"},n)})});Ht(),Qx();var NN=st(__name(function LiveAgentStatusInner2({entry:e}){const t=Mg(e.name||"Agent"),n=summarizeAgentTaskInput(e.input||""),r=e.metadata?.tokensUsed||0,o=e.metadata?.elapsedSeconds||0,s=e.metadata?.recentTools||[],[a,i]=at(".");return lt(()=>{const e=setInterval(()=>{i(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),ot.createElement(Je,{flexDirection:"column",marginBottom:1,width:"90%"},ot.createElement(Je,null,ot.createElement(Qe,{backgroundColor:dI.BG,color:dI.FG,bold:!0},` ${t} `),n&&ot.createElement(Qe,null," (",n,")")),ot.createElement(Je,{columnGap:1,marginLeft:1},ot.createElement(Qe,null,"⎿"," "),ot.createElement(Qe,{color:nI.GRAY},"Running (",formatTime3(o)," |"," ",formatTokens(r),")",a)),s.length>0&&ot.createElement(Je,{flexDirection:"column",marginLeft:1},s.map((e,t)=>{const n=Mg(e.name);return ot.createElement(Je,{key:t,columnGap:1},ot.createElement(Qe,{color:nI.GRAY},"⎿"),ot.createElement(Qe,{color:nI.GRAY}," ",n),e.input&&ot.createElement(Qe,{color:nI.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),$N=st(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:ot.createElement(NN,{entry:e})},"LiveAgentStatus"));Ht(),Ht(),Qx();var _N=[],FN=_N,UN=!1,jN=null,BN="",WN=new Set,HN=new Set,GN=new Set;function shapeOf(e){return e.map(e=>e.content.replace(/\d+/g,"#")).join("\0")}function emit2(){for(const e of GN)e()}function cancelPeek(){jN&&clearTimeout(jN),jN=null,UN=!1}function armPeek(){jN&&clearTimeout(jN),UN=!0,jN=setTimeout(()=>{jN=null,UN=!1,emit2()},5e3),jN.unref?.()}function projectUserEdits(e){return e.filter(e=>!WN.has(e.content)).map(e=>"completed"!==e.status&&HN.has(e.content)?{...e,status:"completed"}:e)}function setSessionTodos(e){const t=projectUserEdits(e);if(t.length>0&&HN.size>0&&t.every(e=>"completed"===e.status))return void clearSessionTodos();const n=shapeOf(t),r=n!==BN;(r||JSON.stringify(t)!==JSON.stringify(FN))&&(FN=t.length>0?t:_N,BN=n,FN.length>0&&r&&armPeek(),emit2())}function adoptSettled(e){FN=e.length>0?[...e]:_N,BN=shapeOf(FN),cancelPeek(),emit2()}function seedSessionTodos(e){WN.clear(),HN.clear(),adoptSettled(e)}function removeSessionTodoAt(e){const t=FN[e];return t&&WN.add(t.content),adoptSettled(FN.filter((t,n)=>n!==e)),FN}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?Lg(r):null;if(o){if(o.every(e=>"completed"===e.status))break;return seedSessionTodos(o),FN}}return clearSessionTodos(),_N}function clearSessionTodos(){(FN!==_N||UN||0!==WN.size||0!==HN.size)&&(FN=_N,BN="",WN.clear(),HN.clear(),cancelPeek(),emit2())}function getSessionTodos(){return FN}function isTodoPanelCollapsed(){return!UN}function completeSessionTodoAt(e){const t=FN[e];return t&&HN.add(t.content),adoptSettled(FN.map((t,n)=>n===e?{...t,status:"completed"}:t)),FN}function completeAllSessionTodos(){const e=FN.map(e=>e.content);for(const t of e)HN.add(t);return adoptSettled(_N),e}function subscribe(e){return GN.add(e),()=>GN.delete(e)}function useSessionTodos(){return mt(subscribe,getSessionTodos)}function useTodoPanelCollapsed(){return mt(subscribe,isTodoPanelCollapsed)}function usePausedLabel(e){const[t,n]=at(!e);return lt(()=>{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`,a=n?currentTaskLabel(t):null;return ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Je,null,ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:lI.BG,color:lI.FG,bold:!0},`${QI}TODOS${QI}`)),ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,null," ",ot.createElement(BracketWrap,null,s))),a&&ot.createElement(Je,{flexShrink:1,minWidth:0},ot.createElement(Qe,{color:r?nI.DIM:uI.IN_PROGRESS,bold:!r,wrap:"truncate-end"},` ${a}${r?" (paused)":""}`)),ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,null," ",ot.createElement(BracketWrap,{color:nI.DIM},n?"ctrl+x to expand":"ctrl+x to manage")))),!n&&ot.createElement(CappedChecklist,{todos:t}))}function CappedChecklist({todos:e}){const{foldedDone:t,visible:n,hiddenTail:r}=projectVisibleTodos(e);return ot.createElement(Je,{flexDirection:"column"},t>0&&ot.createElement(Je,{flexDirection:"row"},ot.createElement(Je,{width:2},ot.createElement(Qe,{color:uI.SUCCESS},pt.checkboxOn)),ot.createElement(Qe,{color:uI.SUCCESS,strikethrough:!0},t," completed")),ot.createElement(TodoChecklist,{todos:n}),r>0&&ot.createElement(Qe,{color:nI.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"),Ht();var VN=new Set,zN=!1;function isTodosManagerOpen(){return zN}function requestTodosManagerOpen(){for(const e of VN)e()}function statusColor(e){return"completed"===e?nI.GREEN:"in_progress"===e?nI.CYAN:nI.WHITE}function TodoRow({todo:e,selected:t}){const n="completed"===e.status?pt.checkboxOn:pt.checkboxOff,r=t?TI:void 0;return ot.createElement(Je,null,ot.createElement(WL,{isSelected:t,backgroundColor:r}),ot.createElement(Qe,{color:statusColor(e.status),backgroundColor:r}," ",n),ot.createElement(Qe,{color:t?YA:statusColor(e.status),strikethrough:"completed"===e.status,backgroundColor:r,wrap:"truncate-end"}," ",e.content),"in_progress"===e.status&&ot.createElement(Qe,{color:nI.DIM,backgroundColor:r}," ","(in progress)"))}function TodosManagerPanel({sessionId:e,onExpandedChange:t}){const n=useSessionTodos(),[r,o]=at(!1),[s,a]=at(0);lt(()=>(zN=r,t?.(r),()=>{zN=!1,t?.(!1)}),[r,t]),lt(()=>{const e=__name(()=>{a(0),o(!0)},"listener");return VN.add(e),()=>{VN.delete(e)}},[]),lt(()=>{if(0===n.length)return o(!1),void a(0);a(e=>Math.min(e,n.length-1))},[n.length]);const i=__name(t=>{$O(e)?.applyTodoUserEdit(t)},"syncHarness");if(tt((e,t)=>{if(t.escape||t.leftArrow||t.ctrl&&"x"===e||""===e)o(!1);else if(0!==n.length)if(t.upArrow)a(e=>Math.max(0,e-1));else if(t.downArrow)a(e=>Math.min(n.length-1,e+1));else{if("c"===e){const e=n[s];return void i({todos:completeSessionTodoAt(s),...e?{completedContents:[e.content]}:{}})}if("x"===e){const e=n[s];return void i({todos:removeSessionTodoAt(s),...e?{removedContents:[e.content]}:{}})}"a"===e&&i({todos:[],completedContents:completeAllSessionTodos()})}},{isActive:r}),!r)return null;const l=n.filter(e=>"completed"===e.status).length;return ot.createElement(ZA,{title:"Todos",subtitle:l>0?`${n.length} items · ${l} done`:`${n.length} items`,gapAfterHeader:!1,boxProps:{marginTop:1,marginBottom:1}},ot.createElement(Je,{flexDirection:"column",marginTop:1},n.map((e,t)=>ot.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"),Ht(),Qx(),Qx();var KN=__name(({currentModel:e,onClose:t,refreshBanner:n,sessionId:r})=>{const o=customReasoningEfforts(e)??getSupportedEfforts(e)??[],s=findModelById(e)?.label??getModelDisplayName(e),a=it(!1),i=__name(o=>{if(a.current)return;a.current=!0;const s=o!==getReasoningEffort(e);(async()=>{try{s&&(await setReasoningEffort({modelId:e,effort:o}),n(),void 0!==o&&r&&$O(r)?.recordEffortChange({model:e,effort:o}))}catch(e){dlog(`[Effort] Failed to persist reasoning effort: ${e}`)}finally{t()}})()},"handleSelect"),l=__name(()=>{a.current||t()},"handleCancel");return ot.createElement(xD,{modelLabel:s,supportedEfforts:o,currentEffort:getReasoningEffort(e),onSelect:i,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})}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 q(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 te(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??""))).map(([e,t])=>{const n=isPlainObject8(t.limit)?t.limit:void 0;return{id:e,..."string"==typeof t.name&&t.name?{name:t.name}:{},...void 0!==asPositive(n?.context)?{contextWindow:asPositive(n?.context)}:{},...void 0!==asPositive(n?.output)?{maxOutput:asPositive(n?.output)}:{}}}):[]}Ht(),Qx(),Ht(),Qx(),__name(store,"store"),__name(getCustomProviderKeyState,"getCustomProviderKeyState"),__name(getConfiguredKeyReference,"getConfiguredKeyReference"),__name(storeCustomProviderKey,"storeCustomProviderKey"),__name(getStoredKeyPreview,"getStoredKeyPreview"),__name(getStoredKeyToken,"getStoredKeyToken"),__name(clearCustomProviderKey,"clearCustomProviderKey"),Ht(),Qx(),Ht(),__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 qN=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(qN.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 a=curateModels(s.record.models);if(0===a.length)return null;const i=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,...i?{envVar:i}:{},models:a}}__name(listModelsDevProviders,"listModelsDevProviders"),__name(findModelsDevProvider,"findModelsDevProvider"),Ht();var YN=[{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}],JN=[{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"}],QN=/^[a-z0-9._-]+$/;function hostOf2(e){try{return new URL(e).hostname.toLowerCase()}catch{return}}function fallbackProviderSuggestions(){return[...JN,...YN]}async function loadProviderSuggestions(e){let t=[];try{t=await listModelsDevProviders(e?.fetchImpl?{fetchImpl:e.fetchImpl}:void 0)}catch{}const n=t.filter(e=>QN.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"),Ht();var XN=["/chat/completions","/completions","/responses","/messages","/models"];function normalizeEndpointInput(e){let t=e.trim().replace(/\/+$/,"");for(const e of XN)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),a=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!==a?{maxOutput:a}:{}})}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=nI.DIM}){const t=`${W()}/.commandcode/providers.json`;return ot.createElement(BI,{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}:{}}))}function cardKeyLine(e){return"stored"===e.keyState?ot.createElement(Qe,null,"key ",ot.createElement(Qe,{color:nI.GREEN},e.keyPreview)," ",ot.createElement(Qe,{color:nI.GREEN},"✓")," stored in auth.json",e.configuredReference?` · overrides ${e.configuredReference}`:""):"configured"===e.keyState?ot.createElement(Qe,null,"key ",e.configuredReference??"set"):"keyless"===e.keyState?ot.createElement(Qe,null,"no key — the endpoint asks for none"):ot.createElement(Qe,{color:nI.YELLOW},"no key yet, requests fail until one is added")}function cardHints(e){const t=[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"u")," update models"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"d")," delete"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," close")];return"stored"===e?[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," save"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"r")," replace key"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"c")," clear"),...t]:"missing"===e?[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," add key"),...t]:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"r")," store key"),...t]}function CustomProviderKeyEntry({providerId:e,providerName:t,keyState:n,keyPreview:r,configuredReference:o,onClose:s,onOpenModels:a,sessionId:i,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);ot.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(i?{sessionId:i}: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(i?{sessionId:i}: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");tt((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 a?.()):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?ot.createElement(ot.Fragment,null,S.baseURL," · ",S.modelCount," ",1===S.modelCount?"model":"models"," · config:"," ",ot.createElement(BI,{url:`file://${W()}/.commandcode/providers.json`,text:"providers.json",color:nI.DIM})):void 0;if("card"===m){const e=cardKeyLine({keyState:n,keyPreview:r,configuredReference:o}),s=cardHints(n);return ot.createElement(ZA,{title:t,titleSuffix:ot.createElement(Qe,{color:nI.DIM}," (byok)"),subtitle:T,footer:ot.createElement(VA,{hints:s,marginTop:0})},ot.createElement(Je,null,e))}return"confirm-remove"===m?ot.createElement(ZA,{title:`Remove ${t}?`,subtitle:"Its entry, models, and stored key go with it",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"y")," remove"),"any other key keeps it"]})},ot.createElement(Qe,null,"Deletes the entry from ",ot.createElement(ProvidersJsonLink,null)," and clears its stored key.")):"removing"===m||"updating-models"===m?ot.createElement(ZA,{title:t,rule:!1},ot.createElement(Qe,null,"removing"===m?`Removing '${e}'…`:`Refetching models for '${e}'…`)):"removed"===m?ot.createElement(ZA,{title:`${t} removed`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," close")]})},ot.createElement(Qe,{color:nI.DIM},"Provider deleted from ",ot.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?ot.createElement(ZA,{title:t,subtitle:T,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," back"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," close")]})},ot.createElement(Qe,{color:nI.GREEN},"Models updated — ",v?.count??0," declared from"," ",v?.source??"the refetch",".")):"saved"===m?ot.createElement(ZA,{title:`Key saved for ${t}`,subtitle:"Stored in ~/.commandcode/auth.json",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," pick a model"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," close")]})}):"cleared"===m?ot.createElement(ZA,{title:`Stored key cleared for ${t}`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," close")]})},ot.createElement(Qe,{color:nI.DIM},"Its models stay listed",o?" — the providers.json key applies again":"; requests will need a key again")):"error"===m?ot.createElement(ZA,{title:`Could not update ${t}`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," close")]})},ot.createElement(Qe,{color:nI.DIM},g??'Check that ~/.commandcode is writable, or set "apiKey" to a "$ENV_VAR" reference in providers.json')):ot.createElement(ZA,{title:`API key for ${t}`,subtitle:`Saved to ~/.commandcode/auth.json under '${e}'. requests go straight to this provider with your key`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," save"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," back")]})},ot.createElement(Je,{borderStyle:"single",borderColor:nI.YELLOW,paddingX:1,width:"100%"},ot.createElement(Qe,{color:nI.DIM},"key: "),ot.createElement(Je,{flexGrow:1},ot.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 ot.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 ot.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 ZN=[{value:"openai-completions",label:"OpenAI-compatible",detail:"/chat/completions · Ollama, vLLM, LM Studio, most hosted APIs"},{value:"anthropic-messages",label:"Anthropic wire",detail:"/v1/messages · endpoints speaking the Claude Messages API"}],e$=[["{",""],[' "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`:e.anthropicWire?"The Messages API root · /v1 is added on the wire when missing":"The API root requests go to · most end in /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,a]=at("openai-completions"),[i,l]=at(""),[c,d]=at(""),[u,m]=at(""),[p,g]=at("id"),[h,f]=at(()=>fallbackProviderSuggestions());ot.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=ot.useRef(null),P=ot.useRef("api"),M=ot.useRef([]),[x,I]=at(void 0),[A,R]=at(0),[O,L]=at(void 0),D=""===c.trim(),N=idStepMatches({phase:p,query:r,providers:h}),$=__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");tt((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&&!i||"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)&&a(e=>"openai-completions"===e?"anthropic-messages":"openai-completions"),void(o.return&&$("endpoint"))):"done"===p&&o.return?(e(),void t?.()):void("error"===p&&o.return&&e());(o.upArrow||o.downArrow)&&N.length>0&&v(e=>{const t=N.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:N[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),a(e.wire),l(e.baseURL),v(null),void $("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&&(a(n.wire),l(n.baseURL)),$("api")},"submitId"),j=__name(()=>{const{url:e,stripped:t}=normalizeEndpointInput(i);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),$("key")}else C("http:// or https:// URLs only.")},"submitEndpoint"),B=__name(async()=>{g("probing");const e=c.trim();let t=await probeProviderModels({baseURL:i,...e?{apiKey:e}:{}});t.ok||"anthropic-messages"!==s||i.endsWith("/v1")||(t=await probeProviderModels({baseURL:`${i}/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 L("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:i,api:s,keyless:D,models:toNewProviderModels(e)}),R(e.length),await refreshCustomProviderModels(n?{sessionId:n}:void 0),g("done")}catch(e){L(e instanceof Error?e.message:String(e)),g("error")}},"writeEntry"),V=k?ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.RED},k)):null,z=r.trim()?`Add a provider · ${r.trim().toLowerCase()}`:"Add a provider";if("saving"===p||"probing"===p)return ot.createElement(ZA,{title:z,rule:!1},ot.createElement(Qe,null,"probing"===p?`Asking ${i} which models it serves…`:`Writing '${r}' to ~/.commandcode/providers.json…`));if("done"===p)return ot.createElement(ZA,{title:`'${r}' is set up`,subtitle:`${A} ${1===A?"model":"models"} declared${D?" · keyless endpoint":" · key stored in auth.json"}`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," pick a model"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," close")]})},ot.createElement(Qe,{color:nI.DIM},"Provider added to ",ot.createElement(ProvidersJsonLink,null),". Edit it anytime, it reloads live."));if("error"===p)return ot.createElement(ZA,{title:`Adding '${r}' didn't finish`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," close")]})},ot.createElement(Qe,{color:nI.DIM},O));if("help"===p)return ot.createElement(ZA,{title:"Adding a provider: the short version",footer:ot.createElement(Je,{flexDirection:"column"},ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,"docs:"," ",ot.createElement(BI,{url:"https://commandcode.ai/docs/byok",text:"commandcode.ai/docs/byok",color:nI.DIM})),"any key to go back"]}))},ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},"• provider id names the entry in ",ot.createElement(ProvidersJsonLink,null)," · models select as id/model"),ot.createElement(Qe,{color:nI.DIM},"• endpoint is the base URL requests go to · most end in /v1"),ot.createElement(Qe,{color:nI.DIM},"• pasted keys go to auth.json · providers.json only ever holds $ENV_VAR or !command references"),ot.createElement(Qe,{color:nI.DIM},"• no key needed? press enter on the empty key field (local servers)"),ot.createElement(Qe,{color:nI.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"),ot.createElement(Qe,{color:nI.DIM},"• the ",ot.createElement(ProvidersJsonLink,null)," file is yours · edit it anytime, it reloads live · manage it from /connect"),ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Qe,{color:nI.DIM},"what it writes:"),e$.map(([e,t])=>ot.createElement(Qe,{key:e},ot.createElement(Qe,{color:nI.CYAN}," ",e),t?ot.createElement(Qe,{color:nI.DIM}," ","// ",t):null)))));if("manual-models"===p)return ot.createElement(ZA,{title:z,subtitle:x?`Couldn't list models automatically — ${x}`:`Which models does ${r} serve?`,footer:ot.createElement(VA,{marginTop:0,hints:["comma-separated, exact ids",ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," save"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," back")]})},ot.createElement(Je,{borderStyle:"single",borderColor:nI.YELLOW,paddingX:1,width:"100%"},ot.createElement(Qe,{color:nI.DIM},"models: "),ot.createElement(Je,{flexGrow:1},ot.createElement(TextInput,{value:u,onChange:m,onSubmit:H,placeholder:"llama3.3:70b, qwen2.5-coder:32b",showCursor:!0}))));if("key"===p)return ot.createElement(ZA,{title:z,subtitle:"Keys live in ~/.commandcode/auth.json, never in providers.json",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," save"),"empty enter = keyless (local servers)",ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," back")]})},ot.createElement(Je,{borderStyle:"single",borderColor:nI.YELLOW,paddingX:1,width:"100%"},ot.createElement(Qe,{color:nI.DIM},"key: "),ot.createElement(Je,{flexGrow:1},ot.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 ot.createElement(ZA,{title:z,subtitle:"What does the endpoint speak?",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"↑/↓")," switch"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," continue"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"h")," help"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," back")]})},ot.createElement(Je,{flexDirection:"column"},ZN.map(e=>ot.createElement(Qe,{key:e.value},s===e.value?"❯ ":" ",ot.createElement(Qe,{bold:s===e.value},e.label),ot.createElement(Qe,{color:nI.DIM}," · ",e.detail)))));if("endpoint"===p){const e="anthropic-messages"===s,t=y&&i===y.baseURL;return ot.createElement(ZA,{title:z,subtitle:endpointSubtitle({prefilledName:t?y.name:void 0,anthropicWire:e}),footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," continue"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," back")]})},ot.createElement(Je,{borderStyle:"single",borderColor:nI.YELLOW,paddingX:1,width:"100%"},ot.createElement(Qe,{color:nI.DIM},"base URL: "),ot.createElement(Je,{flexGrow:1},ot.createElement(TextInput,{value:i,onChange:e=>{l(e),C(void 0),E(void 0)},onSubmit:j,placeholder:e?"https://api.example.com/anthropic":"http://localhost:11434/v1",showCursor:!0}))),b&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.YELLOW},b)),V)}const K=null===w?0:Math.min(Math.max(0,w-6+1),Math.max(0,N.length-6)),q=N.slice(K,K+6),Y=N.length-(K+q.length);return ot.createElement(ZA,{title:"Add a provider",subtitle:"Pick a known provider below, or type your own id.",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"↑/↓")," pick from the list"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," continue"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," close")]})},ot.createElement(Je,{borderStyle:"single",borderColor:nI.YELLOW,paddingX:1,width:"100%"},ot.createElement(Qe,{color:nI.DIM},"provider id: "),ot.createElement(Je,{flexGrow:1},ot.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&&ot.createElement(Je,{flexDirection:"column",marginTop:1},q.map((e,t)=>{const n=null!==w&&K+t===w;return ot.createElement(Je,{key:e.id},ot.createElement(WL,{isSelected:n}),ot.createElement(HL,{isSelected:n,idleColor:nI.DIM},` ${e.id}`),ot.createElement(Qe,{color:nI.DIM}," ","· ",e.baseURL))}),(K>0||Y>0)&&ot.createElement(Qe,{color:nI.DIM}," ",K>0?`↑ ${K} more · `:"",Y>0?`↓ ${Y} more`:"")))}__name(endpointSubtitle,"endpointSubtitle"),__name(idStepMatches,"idStepMatches"),__name(AddCustomProviderEntry,"AddCustomProviderEntry"),Ht(),Qx();var t$="__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},bT)}async function handleProviderSelect({provider:e,setCurrentProvider:t,setShowProviderSelector:n,setAuthComponentInfo:r,setStatus:o,setShowProviderNotification:s,providerNotificationTimer:a,setShowModelSelector:i,sessionId:l,onActiveModelOrphaned:c,onDiskDefaultOrphaned:d}){if(e===t$)return n(!1),r({provider:e,Component:makeAddCustomProviderEntry({...i?{onOpenModels:__name(()=>i(!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:i?()=>i(!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:a}),{switched:!0})}function handleProviderCancel({setShowProviderSelector:e}){e(!1)}async function handleAuthSuccess({authComponentInfo:e,setAuthComponentInfo:t,setShowProviderSelector:n,setCurrentProvider:r,setStatus:o,setShowProviderNotification:s,providerNotificationTimer:a,sessionId:i}){return e?(t(null),n(!1),r(e.provider),await invalidateHarnessForLaneSwitch(i),o(buildProviderAuthSuccessStatus(e.provider)),showProviderNotification({setShowProviderNotification:s,providerNotificationTimer:a}),{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 n$=__name(({onSelect:e,onCancel:t,sessionId:n})=>{const[r,o]=ot.useState(()=>getCustomProviderModelsSync()),[s,a]=ot.useState(()=>getCustomProviderWarningsSync()),[i,l]=ot.useState({});ot.useEffect(()=>{let e=!0;return(async()=>{const{providers:t}=await refreshCustomProviderModels(n?{sessionId:n}:void 0);if(!e)return;o(t),a(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]=ot.useState({});ot.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=i[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"===i[e.id]})),{label:"(BYOK) Add your own provider",value:t$,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 tt((e,n)=>{n.escape&&t()}),ot.createElement(ZA,{title:"Connect",subtitle:"Connect to AI providers and see currently connected providers",hint:"↑/↓ navigate · enter select · esc close"},ot.createElement(SelectInput,{items:p.map(e=>({label:e.label,value:e.value})),onSelect:f,initialIndex:0,indicatorComponent:WL,itemComponent:({isSelected:e,label:t})=>{const n=h.get(t??"");return ot.createElement(Je,null,ot.createElement(HL,{isSelected:e,...n?.notLive?{idleColor:nI.DIM}:{}},` ${(t??"").padEnd(g)}`,n?.status.startsWith("✓")?ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.GREEN},"✓"),n.status.slice(1)):n?.status??""))}}),s.length>0&&ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Qe,{color:nI.YELLOW},ot.createElement(ProvidersJsonLink,{color:nI.YELLOW})," needs attention —"," ",1===s.length?"one entry":"some entries"," ","did not load as written:"),s.slice(0,3).map(e=>ot.createElement(Qe,{key:e,color:nI.DIM}," ",e)),s.length>3&&ot.createElement(Qe,{color:nI.DIM}," ","… and"," ",s.length-3," more")))},"ProviderSelector");Ht(),Qx();var r$=__name(e=>0===e?"No code changes":`${e} file${e>1?"s":""} changed`,"formatFileCountLabel"),o$=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=ct(()=>[...e].sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),[e]),[o,s]=at(()=>Math.max(0,r.length-1)),[a,i]=at(()=>Math.max(0,r.length-8)),[l,c]=at("checkpoint"),[d,u]=at(null),[m,p]=at(0),g=ct(()=>hasCodeChangesToRestore({sortedCheckpoints:r,selectedCheckpoint:d}),[d,r]),h=ct(()=>g?pP:pP.filter(e=>"conversation"===e.mode),[g]);if(lt(()=>{if(r.length>0){const e=r.length-1;s(e),i(Math.max(0,r.length-8))}},[r.length,8]),tt((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<a&&i(t),t}):"checkpoint"===l&&g.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=a+8&&i(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 ot.createElement(ZA,{title:"Rewind",subtitle:"No checkpoints available. Start a conversation to create checkpoints.",gapAfterHeader:!1,footer:ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Esc")," to close")});if("mode"===l&&d)return ot.createElement(ZA,{title:"Rewind",subtitle:ot.createElement(ot.Fragment,null,"Restore to:"," ",ot.createElement(Qe,{color:nI.WHITE},truncateString2({text:d.prompt||"checkpoint",maxChars:50}))),footer:ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to confirm ·"," ",ot.createElement(GA,null,"Esc")," to go back")},ot.createElement(Je,{flexDirection:"column"},h.map((e,t)=>{const n=m===t,r=t===h.length-1;return ot.createElement(Je,{key:e.mode,flexDirection:"column"},ot.createElement(Je,{flexDirection:"row"},ot.createElement(Qe,{color:n?rI:void 0},n?`${qI} `:" "),ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:n?rI:nI.WHITE},e.label),ot.createElement(Qe,{color:nI.DIM},e.description))),!r&&ot.createElement(Qe,null," "))})));const f=r.slice(a,a+8);return ot.createElement(ZA,{title:"Rewind",subtitle:"Select a checkpoint to restore your session",gapAfterHeader:!1,footer:ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to select ·"," ",ot.createElement(GA,null,"Esc")," to cancel")},r.length>8&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",a+1,"-",Math.min(a+8,r.length)," ","of ",r.length)),ot.createElement(Je,{marginTop:1}),ot.createElement(Je,{flexDirection:"column"},f.map((e,t)=>{const n=a+t,s=o===n,i=e.filesModified.length,l=t===f.length-1,c=n===r.length-1;return ot.createElement(Je,{key:e.messageId,flexDirection:"column"},ot.createElement(Je,{flexDirection:"row"},ot.createElement(Qe,{color:s?rI:void 0},s?`${qI} `:" "),ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,{color:s?rI:nI.WHITE},truncateString2({text:e.prompt||"(no prompt)",maxChars:60})),ot.createElement(Qe,{color:nI.DIM}," • "),ot.createElement(Qe,{color:nI.DIM},getRelativeTimeString({timestamp:e.createdAt}),c&&" (latest)")),ot.createElement(Qe,{color:nI.DIM},r$(i)))),!l&&ot.createElement(Qe,null," "))})))},"RewindSelector");Ht(),Qx();var s$=["default","no-tools","user-only","labeled-only","all"],a$={default:"","no-tools":"[no-tools]","user-only":"[user]","labeled-only":"[labeled]",all:"[all]"};function nextFilterMode(e){const t=s$.indexOf(e);return s$[(t+1)%s$.length]}function previousFilterMode(e){const t=s$.indexOf(e);return s$[(t-1+s$.length)%s$.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 i$=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:!i$.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:a}=e,i=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!==i?l.push(" "):0===r?l.push(o?"└":"├"):1===r?l.push(connectorGlyph({folded:s,foldable:a})):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,a=t.length>1;function visit(e){const{node:t,parentId:i,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=a?Math.max(0,l-1):l;if(o.push({id:t.entry.id,entry:t.entry,parentId:i,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:a?1:0,justBranched:a,showConnector:a,isLast:n===t.length-1,gutters:[],isVirtualRootChild:a})}),{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:nI.DIM}}return{text:`user: ${normalizeRowText(messageText5(n))}`,color:nI.CYAN}}const r=messageText5(n).trim();return r?{text:`assistant: ${normalizeRowText(r)}`,color:nI.GREEN}:{text:"assistant: (no content)",color:nI.DIM}}return"compaction"===e.type?{text:`[compaction: ${Math.round(e.tokensBefore/1e3)}k tokens]`,color:nI.CYAN}:"branch_summary"===e.type?{text:`[branch summary]: ${normalizeRowText(e.summary)}`,color:nI.YELLOW}:"custom_message"===e.type?{text:`[${e.customType}]: ${normalizeRowText(extractTextFromMessageContent({content:e.content}))}`,color:nI.MAGENTA}:"custom"===e.type?{text:`[custom: ${e.customType}]`,color:nI.DIM}:"model_change"===e.type?{text:`[model: ${e.model}]`,color:nI.DIM}:"effort_change"===e.type?{text:`[effort: ${e.effort}]`,color:nI.DIM}:"label"===e.type?{text:`[label: ${e.label??"(cleared)"}]`,color:nI.DIM}:{text:e.name?`[title: ${e.name}]`:"[title: (empty)]",color:nI.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 l$={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=l$[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 c$=[{value:"none",label:"No summary"},{value:"summarize",label:"Summarize"},{value:"custom",label:"Summarize with custom prompt"}],d$=__name(({tree:e,currentLeafId:t,initialSelectedId:n,initialFilterMode:r,branchSummarySkipPrompt:o,onSelect:s,onAbortSummary:a,onCancel:i,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,O]=at(0),[L,D]=at(n??t??void 0),N=useTerminalHeight(),$=ct(()=>{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]),_=ct(()=>buildToolCallMap(e),[e]),F=ct(()=>{const e=new Set;let n=t;for(;null!==n;){e.add(n);const t=$.get(n);n=t?t.parentId:null}return e},[$,t]),U=ct(()=>reorderActiveFirst(buildVisibleNodes({nodes:e,mode:c,currentLeafId:t}),t),[e,c,t]),{rows:j,visibleChildrenIds:B}=ct(()=>flattenVisibleTree({roots:U,activePathIds:F,foldedNodes:p}),[U,F,p]),W=ct(()=>new Map(j.map(e=>[e.id,e])),[j]),H=ct(()=>u?j.filter(e=>matchesSearch(searchableText({entry:e.entry,label:e.label,toolCallMap:_}),u)):j,[j,u,_]);lt(()=>{if(0===H.length)return void A(0);let e=L;for(;e;){const t=H.findIndex(t=>t.id===e);if(t>=0)return void A(t);e=$.get(e)?.parentId}A(H.length-1)},[H,c,u,$]);const G=H[I]?.id,V=it(!1);lt(()=>{V.current?G&&D(G):V.current=!0},[G]);const z=N-1,K=Math.max(6,z-10);lt(()=>{O(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:$,entryId:q.id});isOnPathLocally({byId:$,ancestorId:t,targetId:e})||o?Y({entryId:q.id,summarize:!1}):(x(q.id),P(0),v("confirm-summary"))},"handleEnterInBrowse");tt((e,t)=>{if("summarizing"===w)return void(t.escape&&a());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(c$.length-1,e+1));if(t.return&&M){const e=c$[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 i();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 ot.createElement(ZA,{title:"/tree",gapAfterHeader:!1},ot.createElement(Qe,{color:nI.CYAN},"Summarizing abandoned branch… (Esc to cancel)"));if("confirm-summary"===w)return ot.createElement(ZA,{title:"/tree",subtitle:"You're leaving work behind on this branch. Summarize it before jumping?",hint:"enter confirm · esc back"},ot.createElement(Je,{flexDirection:"column"},c$.map((e,t)=>ot.createElement(Qe,{key:e.value,color:t===T?rI:nI.WHITE,bold:t===T},t===T?`${qI} `:" ",e.label))));if("custom-prompt"===w)return ot.createElement(ZA,{title:"/tree",subtitle:"Focus instructions for the summary:",gapAfterHeader:!1,hint:"enter confirm · esc back"},ot.createElement(TextInput,{value:b,focus:!0,prefix:`${qI} `,prefixColor:"cyan",onChange:E,onSubmit:X}));if("label"===w&&q)return ot.createElement(ZA,{title:"/tree",subtitle:"Label:",gapAfterHeader:!1,hint:"enter save (empty clears) · esc cancel"},ot.createElement(TextInput,{value:k,focus:!0,prefix:`${qI} `,prefixColor:"cyan",onChange:C,onSubmit:Q}));const Z=H.slice(R,R+K),ee=new Date,te=a$[c];return ot.createElement(Je,{flexDirection:"column",paddingLeft:1,width:"100%"},ot.createElement(Qe,{color:rI,bold:!0},"/tree"),ot.createElement(Je,{marginBottom:1,width:"100%"},ot.createElement(VI,{query:u,resultCount:u?H.length:void 0,placeholder:"Type to search…"})),0===H.length?ot.createElement(Je,{marginBottom:1},ot.createElement(YO,{message:"No entries found"})):ot.createElement(Je,{flexDirection:"column"},Z.map((e,t)=>{const n=R+t===I,{text:r,color:o}=describeRow(e.entry,_);return ot.createElement(Qe,{key:e.id,backgroundColor:n?TI:void 0,bold:n,wrap:"truncate-end"},n?`${qI} `:" ",ot.createElement(Qe,{color:EI},e.prefix),e.isActivePath?ot.createElement(Qe,{color:rI},"• "):null,void 0!==e.label?ot.createElement(Qe,{color:nI.YELLOW},"[",e.label,"]"," "):null,y&&e.labelTimestamp?ot.createElement(Qe,{color:nI.DIM},formatLabelTimestamp(e.labelTimestamp,ee)," "):null,ot.createElement(Qe,{color:o},r))})),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"(",0===H.length?0:I+1,"/",H.length,")",te?` ${te}`:"",y?" [+label time]":"")),ot.createElement(Je,{flexDirection:"column"},ot.createElement(HA,null,"↑/↓ move · ←/→ page · tab / alt+←/→ branch · shift+L label · shift+T label time"),ot.createElement(HA,null,"filters ctrl+d/t/u/l/a · cycle ctrl+o · type to search · rebind via ~/.commandcode/keybindings.json")))},"TreeSelector");Ht(),Qx();var u$=[{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."}],m$=['/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"'],p$=__name(({onCancel:e})=>(tt((t,n)=>{n.escape&&e()}),ot.createElement(Je,{flexDirection:"column",paddingLeft:2,paddingRight:2},ot.createElement(Je,{marginBottom:1,flexDirection:"column"},ot.createElement(Qe,{bold:!0,color:rI},"Use"),ot.createElement(Je,{paddingLeft:2,flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},'/design <mode> "target or request"'),ot.createElement(Qe,{color:nI.DIM},'/design "freeform request" also works. The closest mode is inferred.'))),ot.createElement(Je,{marginBottom:1,flexDirection:"column"},ot.createElement(Qe,{bold:!0,color:rI},"Modes"),ot.createElement(Je,{paddingLeft:2,flexDirection:"column"},Kh.map(e=>ot.createElement(Je,{key:e.name,columnGap:2},ot.createElement(Je,{width:18,flexShrink:0},ot.createElement(Qe,{color:nI.CYAN},"/design ",e.name)),ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},e.description)))))),ot.createElement(Je,{marginBottom:1,marginTop:1,flexDirection:"column"},ot.createElement(Qe,{bold:!0,color:rI},"Working rules"),ot.createElement(Je,{paddingLeft:2,flexDirection:"column"},u$.map(e=>ot.createElement(Je,{key:e.label,columnGap:2},ot.createElement(Je,{width:16,flexShrink:0},ot.createElement(Qe,{color:nI.CYAN},e.label)),ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},e.desc)))))),ot.createElement(Je,{marginBottom:1,marginTop:1,flexDirection:"column"},ot.createElement(Qe,{bold:!0,color:rI},"Quick examples:"),ot.createElement(Je,{paddingLeft:2,flexDirection:"column"},m$.map(e=>ot.createElement(Qe,{key:e,color:nI.DIM},e)))),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Press Esc to close. Type /design help anytime to return.")))),"DesignGuide");Ht(),Qx(),Ht(),Ht();var g$=__name(({error:e,traceId:t})=>ot.createElement(Je,{padding:1},ot.createElement(qO,{title:"Error initializing onboarding:"},e,t&&ot.createElement(Qe,{color:nI.DIM},"\n\n","Trace ID: ",t),"\n\n","Continuing without onboarding...")),"OnboardingError");Ht(),Ht();var h$=__name(()=>ot.createElement(Qe,null,"Skip"),"SkipOptionText"),f$=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[o,s]=at(1);return tt((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())}),ot.createElement(Je,{flexDirection:"column",borderStyle:"single",borderColor:oI.TEXT,paddingX:1,paddingY:0},ot.createElement(Qe,{color:oI.TEXT,bold:!0},"Build Your Coding Taste"),ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Qe,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,null,"Analyze"," ",1===e?"that session":"those sessions"," ","to build your coding taste package?"))),ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,{color:1===o?oI.TEXT:nI.GRAY},1===o?pt.pointer:" "," 1. Yes, learn (recommended)")),ot.createElement(Je,null,ot.createElement(Qe,{color:2===o?oI.TEXT:nI.GRAY},2===o?pt.pointer:" "," 2."," ",ot.createElement(h$,null)))),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"↑↓ · "),ot.createElement(Qe,{color:vI.CODE},"enter"),ot.createElement(Qe,{color:nI.DIM}," ok · "),ot.createElement(Qe,{color:vI.CODE},"esc"),ot.createElement(Qe,{color:nI.DIM}," skip · "),ot.createElement(Qe,{color:vI.CODE},"n"),ot.createElement(Qe,{color:nI.DIM}," never")))},"ImportChoice"),y$=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onSkip:a})=>"asking"===e?t&&"has_sessions"===t.reason?ot.createElement(f$,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:a}):null:"learning"===e?ot.createElement(fL,{onComplete:r,onCancel:a,onError:o,onErrorDismiss:s}):null,"OnboardingStepRenderer"),S$=__name(({onComplete:e,autoLearn:t=!1})=>{lt(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,traceId:o,isLoading:s}=nL({autoLearn:t,onShouldSkip:e}),{step:a,setStep:i}=rL({conditions:n,autoLearn:t}),{handleImportStart:l,handleImportComplete:c,handleImportError:d,handleErrorDismiss:u,handleSkip:m}=oL({onStepChange:__name(e=>{i(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${a}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),s?null:r?ot.createElement(g$,{error:r,traceId:o}):"done"===a||"asking"!==a&&"learning"!==a?null:ot.createElement(y$,{step:a,conditions:n,onImportStart:l,onImportComplete:c,onImportError:d,onErrorDismiss:u,onSkip:m})},"TasteOnboarding");Ht(),Qx();var w$=[{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 v$=__name(({onSelect:e,onCancel:t})=>{const[n]=at(()=>getCliTheme()),[r]=at(()=>resolveCliTheme("auto")),o=ct(()=>w$.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");tt((e,n)=>{n.escape&&t()});const a=o.findIndex(e=>e.value===n),i=o.find(e=>e.value===n)?.label??`${n} theme`;return ot.createElement(ZA,{title:"Select a theme",subtitle:`Choose the color palette for this terminal · currently ${i}`,footer:ot.createElement(Qe,{italic:!0,color:nI.DIM},"Press ",ot.createElement(Qe,{bold:!0},"Esc")," to cancel")},ot.createElement(SelectInput,{items:o,onSelect:s,initialIndex:a>=0?a:0,indicatorComponent:WL,itemComponent:({isSelected:e,label:t})=>{const r=o.findIndex(e=>e.label===t),s=o[r],a=s?.value===n,i=r===o.length-1;return ot.createElement(Je,{flexDirection:"column",marginBottom:i?0:1},ot.createElement(Je,null,ot.createElement(HL,{isSelected:e,isActive:a,idleColor:nI.DIM},` ${r+1}. ${s?.label??t}`),a&&ot.createElement(VL,null)),ot.createElement(zL,null,s?.description??""))}}))},"ThemeSelector"),k$=st(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:o,setStaticKey:s,transcriptMode:a,tasteOnboardingEntryId:i,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:O,showThemeSelector:L,authComponentInfo:D,status:N,currentProvider:$,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:ae,questionPanel:ie,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:Oe,handleAuthSuccess:Le,handleAuthCancel:De,showDesignGuide:Ne,setShowDesignGuide:$e}){const _e=ct(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Fe=dt(()=>$e(!1),[$e]),Ue=useTerminalWidth(),[je,Be]=at(!1),[We,He]=at(!1),Ge=it(null);Ge.current=r?Ge.current??Date.now():null;const Ve=ct(()=>"off"===a?_e:projectTranscriptWindow({feed:_e,mode:a}),[_e,a]),ze=ct(()=>"off"===a?0:Math.max(0,_e.length-Ve.length),[_e.length,Ve.length,a]),Ke=ct(()=>0===ze?Ve:Ve.filter(e=>"user"!==e.role),[Ve,ze]),qe=dt(()=>Ce(!1),[Ce]),Ye=dt(()=>ve(!1),[ve]),Xe=dt(()=>ke(!1),[ke]),Ze=dt(()=>be(!1),[be]),et=dt(()=>Se(!0),[Se]),tt=dt(()=>we(!1),[we]),nt=dt(()=>{hardResetForResize(),s(e=>e+1)},[s]),rt=!("off"!==a||ae||ie||le||w||v||k||D||C||b||E||T||P||I||A||R||O||L||Ne||i),st=$O(Z),lt=st?st.getEffort():null;return ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(DN,{staticKey:o,feed:Ke,showHeader:!0,expandedToolOutput:"off"!==a,currentModel:_,currentEffort:lt,currentProvider:$,hiddenCount:ze}),i&&ot.createElement(S$,{onComplete:se,autoLearn:l}),c&&ot.createElement(TasteSkipMessage,null),d&&ot.createElement(ZdrPausedMessage,null),u&&ot.createElement(ModelNoticeMessage,{text:u}),t.map(e=>e.metadata?.isAgent?ot.createElement($N,{key:e.id,entry:e}):ot.createElement(Je,{key:e.id,marginBottom:1,width:"90%"},ot.createElement(FeedEntryView,{entry:e,expandedToolOutput:"off"!==a}))),ot.createElement(RetryMessage,{attempt:m}),"off"===a&&!i&&!We&&ot.createElement(TodoPanel,{active:r}),le,ie,ae,"off"!==a&&ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},"─".repeat(Ue))),ot.createElement(Je,{paddingRight:1},ot.createElement(Qe,{backgroundColor:lI.BG,color:lI.FG,bold:!0},`${QI}DETAILED TRANSCRIPT${QI}`),ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{bold:!0},"ctrl+o"),ot.createElement(Qe,{color:nI.DIM}," to toggle"),ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{bold:!0},db?"ctrl+y":"ctrl+e"),ot.createElement(Qe,{color:nI.DIM}," ","to"," ","limited"===a?"show all":"collapse"),ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{bold:!0},"esc"),ot.createElement(Qe,{color:nI.DIM}," to exit"))),rt&&ot.createElement(ot.Fragment,null,ot.createElement(BackgroundTasksPanel,{onExpandedChange:Be}),ot.createElement(TodosManagerPanel,{sessionId:Z,onExpandedChange:He}),ot.createElement(vN,{queuedMessages:n,sessionId:Z,isProcessing:r,processingStartedAt:Ge.current,executionState:X,status:N,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:$,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&&ot.createElement(Je,{marginY:1},ot.createElement(n$,{onSelect:Te,onCancel:Pe,sessionId:Z})),v&&ot.createElement(Je,{marginY:1},ot.createElement(ID,{onSelect:Me,onCancel:xe,currentModel:_,currentProvider:$,refreshBanner:nt,sessionId:Z})),k&&ot.createElement(Je,{marginY:1},ot.createElement(KN,{currentModel:_,sessionId:Z,onClose:tt,refreshBanner:nt})),Ne&&ot.createElement(Je,{marginY:1},ot.createElement(p$,{onCancel:Fe})),O&&ot.createElement(Je,{marginY:1},ot.createElement(ZD,{onSelect:Ie,onCancel:Ae})),L&&ot.createElement(Je,{marginY:1},ot.createElement(v$,{onSelect:Re,onCancel:Oe})),E&&ot.createElement(Je,{marginY:1},ot.createElement(VD,{onCancel:qe})),C&&ot.createElement(Je,{marginY:1},ot.createElement(EN,{onClose:Ye})),b&&ot.createElement(Je,{marginY:1},ot.createElement(bN,{onClose:Xe,mcp:$O(Z)?.mcp})),T&&$O(Z)&&ot.createElement(Je,{marginY:1},ot.createElement(o$,{checkpoints:[...$O(Z).listCheckpoints()],onSelect:ce,onCancel:de})),P&&$O(Z)&&ot.createElement(Je,{marginY:1},ot.createElement(d$,{tree:$O(Z).getSessionTree(),currentLeafId:$O(Z).getSessionLeafId(),initialFilterMode:M,branchSummarySkipPrompt:x,onSelect:ue,onAbortSummary:ge,onCancel:me,onLabelChange:pe})),D&&ot.createElement(Je,{marginY:1},ot.createElement(D.Component,{onSuccess:Le,onCancel:De})),I&&ot.createElement(Je,{marginY:1},ot.createElement(kN,{onComplete:he,onCancel:fe})),R&&ot.createElement(Je,{marginY:1},ot.createElement(bD,{onClose:Ze})))},"MainView"));function useFeatureModelCatalog(){const[e,t]=at(()=>getCachedBillingContext());lt(()=>{if(e)return;let n=!0;return getBillingContext().then(e=>{n&&t(e)}),()=>{n=!1}},[e]);const n=useCustomModelsReady(),r=ct(()=>buildCatalogModelPickerGroups(),[n]),o=ct(()=>filterModelPickerGroupsByPlan({groups:r,billing:e}),[r,e]),s=ct(()=>flattenModelPickerGroups(o).map(e=>({id:e.model.id,label:getModelDisplayName(e.model.id)})),[o]);return{groups:o,catalog:s,resolved:null!==e}}Ht(),Ht(),Qx(),Ht(),Qx(),__name(useFeatureModelCatalog,"useFeatureModelCatalog"),Ht(),Qx();var C$=__name(({featureLabel:e,defaultLabel:t,currentModelId:n,modelFilter:r,onPick:o,onBack:s})=>{const[a,i]=at(""),{groups:l,resolved:c}=useFeatureModelCatalog(),d=ct(()=>r?l.map(e=>({...e,models:e.models.filter(e=>r(e))})).filter(e=>e.models.length>0):l,[l,r]),u=ct(()=>filterModelPickerGroups(d,a),[d,a]),m=ct(()=>getModelLabelColumnWidth(d.flatMap(e=>e.models),{showDefaultBadge:!1}),[d]),p=ct(()=>[{kind:"reset"},...flattenModelPickerGroups(u).map(e=>({kind:"model",providerId:e.providerId,model:e.model}))],[u]),g=ct(()=>{if(!n)return 0;const e=p.findIndex(e=>"model"===e.kind&&e.model.id===n);return e>=0?e:0},[p,n]),{cursor:h}=useListNavigation({items:p,initialIndex:g,searchCursorIndex:1,searchQuery:a,onSearchChange:i,onSelect:__name(e=>{c&&o("reset"===e.kind?void 0:e.model.id)},"onSelect"),onCancel:s}),[f,y]=at(0),S=useTerminalHeight()-1,w=Math.max(4,S-13-2*u.length);lt(()=>{y(e=>clampScrollOffset({cursor:h,total:p.length,maxVisible:w,currentOffset:e}))},[h,p.length,w]);const v=f,k=f+w,C=0===v,b=windowModelGroups({groups:u,firstSectionBase:1,windowStart:v,windowEnd:k}),E=p.length>w;return ot.createElement(ZA,{title:`${e} › select model`,subtitle:ot.createElement(ot.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:ot.createElement(Qe,{italic:!0,color:nI.DIM},"type to search · ↑/↓ navigate · enter select",a?" · esc to clear":" · esc back")},isCmdZdrEnabled()&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.YELLOW},"Your pick is saved but stays paused until CMD_ZDR is unset.")),ot.createElement(Je,{marginBottom:2,flexDirection:"column",width:"100%"},ot.createElement(VI,{query:a,resultCount:a?p.length-1:void 0,placeholder:"Type to search models..."})),c?ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"column"},C&&ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{bold:!0,dimColor:!0},"Default"),ot.createElement(Je,null,ot.createElement(Qe,{backgroundColor:0===h?TI:void 0,color:n?nI.WHITE:nI.GREEN},t," "),!n&&ot.createElement(Qe,{color:nI.GREEN},pt.tick))),b.map(({group:e,groupWindow:t},r)=>ot.createElement(Je,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:0!==r||C?1:0},ot.createElement(Qe,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>ot.createElement(PD,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===h,isCurrent:r.id===n,showProviderLabel:!1,showDefaultBadge:!1,labelColumnWidth:m}))))),E&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",v+1,"–",Math.min(k,p.length)," of"," ",p.length,v>0?" · ↑ more":"",k<p.length?" · ↓ more":""))):ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},"Loading available models…")))},"FeatureModelPicker"),b$="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===wm}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="",a=0,i=!1;for(;a<r.length;){let e=r[a];e.length>t&&(r.splice(a,1,e.slice(0,t),e.slice(t)),e=r[a]);const l=s?`${s} ${e}`:e;if(l.length<=t)s=l,a+=1;else if(o.push(s),s="",o.length===n){i=!0;break}}if(!i)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 E$=__name(({onClose:e,staticKey:t,loadTasteStatus:n})=>{const[r,o]=at([]),s=isByok({model:getConfiguredModel()}),[a,i]=at(!0),[l,c]=at(""),[d,u]=at(null),{catalog:m}=useFeatureModelCatalog(),p=dt(()=>listConfigSettings({modelCatalog:m,isByok:isByok}).then(e=>o(e)),[m]);lt(()=>{let e=!0;return listConfigSettings({modelCatalog:m,isByok:isByok}).then(t=>{e&&o(t)}).finally(()=>{e&&i(!1)}),()=>{e=!1}},[m]);const g=ct(()=>filterConfigSettings({settings:r,query:l}),[r,l]),h=ct(()=>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!==wm||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??Pm}),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:!a&&null===d,validate:__name(e=>s&&isTasteRow(e)?b$: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(b$);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=ct(()=>E?clampDescriptionLines({text:E.description,width:Math.max(20,b-2),maxLines:2}):[],[E,b]);if(d?.featureModelKey){const e=im.find(e=>e.key===d.featureModelKey),t="string"==typeof d.currentValue&&d.currentValue!==Pm?d.currentValue:void 0;return ot.createElement(C$,{featureLabel:d.label,defaultLabel:e?getFeatureDefaultLabel({meta:e,getModelDisplayName:getModelDisplayName}):"",currentModelId:t,modelFilter:"vision"===d.featureModelKey?e=>modelSupportsVision(e.id):void 0,onBack:()=>u(null),onPick:e=>{S(d,e)}})}return a?ot.createElement(ZA,{key:t,title:"Settings",gapAfterHeader:!1},ot.createElement(VO,{label:"Loading settings"})):ot.createElement(ZA,{title:"Settings",footer:ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(Je,{flexDirection:"column",height:2,width:"100%"},T.map((e,t)=>ot.createElement(Qe,{key:t,color:nI.DIM,wrap:"truncate-end"},e))),ot.createElement(VA,{marginTop:0,hints:["type to filter","↑↓ navigate","enter to change","tab to reset",l?"esc to clear":"esc to close"]}))},ot.createElement(Je,{marginBottom:1,flexDirection:"column",width:"100%"},ot.createElement(VI,{query:l,resultCount:l?g.length:void 0,placeholder:"Search settings..."})),0===g.length?ot.createElement(Je,{marginY:1},ot.createElement(Qe,{color:nI.GRAY},'No settings match "',l,'"')):ot.createElement(Je,{flexDirection:"column"},g.map((e,t)=>{const n=t===w?TI:void 0,r=!l&&startsNewGroup(g,t);return ot.createElement(ot.Fragment,{key:e.id},r&&ot.createElement(Je,{marginTop:0===t?0:1},ot.createElement(Qe,{color:nI.DIM,bold:!0},e.group)),ot.createElement(Je,null,ot.createElement(Qe,{color:e.locked||s&&isTasteRow(e)?nI.DIM:nI.WHITE,backgroundColor:n},e.label.padEnd(h)),ot.createElement(Qe,{color:e.locked||s&&isTasteRow(e)?nI.DIM:nI.GREEN,backgroundColor:n},formatSettingValue(e)),(e.locked||s&&isTasteRow(e))&&ot.createElement(Qe,{color:nI.DIM,backgroundColor:n},s&&isTasteRow(e)?" (unavailable on BYOK)":" (locked by settings.local.json)")))})),v&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.GRAY},v)))},"SettingsConfig");function SettingsConfigView({staticKey:e,onClose:t,loadTasteStatus:n}){return ot.useEffect(()=>{hardResetForResize()},[]),ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(E$,{onClose:t,staticKey:e,loadTasteStatus:n})))}function categoryColor(e){return isFatalWarningCategory(e)?nI.RED:nI.YELLOW}__name(SettingsConfigView,"SettingsConfigView"),Ht(),Ht(),Qx(),Ht(),Ht(),Qx(),__name(categoryColor,"categoryColor");var T$=formatSkillWarningsAsMarkdown;async function copyAllWarnings(e,t){try{const{writeClipboardText:n}=await Promise.resolve().then(()=>(Qx(),Jx));if(!await n(T$(e)))throw new Error("clipboard unavailable");const r=e.length;t({text:`Copied ${r} issue${1===r?"":"s"} to clipboard`,color:nI.GREEN})}catch{t({text:"Clipboard write failed",color:nI.YELLOW})}}__name(copyAllWarnings,"copyAllWarnings");var P$=__name(({warnings:e,onClose:t,isActive:n=!0})=>{const r=groupWarnings(e),o=e.length>0,[s,a]=at(null),i=it(null),l=it(!0);lt(()=>()=>{l.current=!1,i.current&&(clearTimeout(i.current),i.current=null)},[]);const c=__name(e=>{l.current&&(i.current&&clearTimeout(i.current),a(e),i.current=setTimeout(()=>{l.current&&(a(null),i.current=null)},3e3))},"showStatus");return tt((n,r)=>r.escape||" "===n&&o?(cA(),void t()):void("c"===n&&o&&copyAllWarnings(e,c)),{isActive:n}),ot.createElement(Je,{flexDirection:"column",paddingX:0,width:"100%"},ot.createElement(Je,null,ot.createElement(Qe,{color:rI,bold:!0},"Skills"," "),ot.createElement(Qe,{color:nI.DIM},"› "),ot.createElement(Qe,{color:rI,bold:!0},"Skipped"," "),ot.createElement(Qe,{color:nI.WHITE},e.length)),o&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM},"Press c to copy all issues")),o?ot.createElement(Je,{flexDirection:"column"},r.map(e=>ot.createElement(Je,{key:e.category,flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,{color:categoryColor(e.category)},e.category)),e.items.map(e=>ot.createElement(Je,{key:e.path,flexDirection:"column",marginBottom:1},ot.createElement(Je,{paddingLeft:2},ot.createElement(BI,{url:p(e.path).href,text:skillIdentifier(e.path),color:nI.WHITE})),ot.createElement(Je,{paddingLeft:4},ot.createElement(Qe,{color:nI.WHITE},e.reason))))))):ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"No issues — every skill loaded.")),s&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:s.color},s.text)),ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},o?"c copy all issues · esc back to skills":"esc back to skills")))},"SkillsConfigIssues"),M$=[],x$=__name(({warnings:e=M$,onClose:t})=>{const[n,r]=at("list");return tt((o,s)=>{"list"===n&&(s.escape&&t?t():" "===o&&!s.ctrl&&!s.meta&&e.length>0&&r("issues"))},{isActive:"list"===n}),"issues"===n?ot.createElement(P$,{warnings:e,onClose:()=>r("list"),isActive:!0}):ot.createElement(Je,{flexDirection:"column",paddingX:0,width:"100%"},ot.createElement(Je,null,ot.createElement(Qe,{color:rI,bold:!0},"Skills"),e.length>0&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:nI.YELLOW},e.length," skipped"))),ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM},"No skills found")),ot.createElement(Qe,{color:nI.DIM},"Create skills in:"),ot.createElement(Qe,{color:nI.DIM}," ","~/",".commandcode","/","skills","/ (user)"),ot.createElement(Qe,{color:nI.DIM}," ","~/.agents/","skills","/ (user, .agents)"),ot.createElement(Qe,{color:nI.DIM}," ",".commandcode","/","skills","/ (project)"),ot.createElement(Qe,{color:nI.DIM}," ",".agents/","skills","/ (project, .agents)"),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},e.length>0&&"space to view issues · ","Press ",ot.createElement(Qe,{bold:!0},"Esc")," to close")))},"SkillsConfigEmpty");Ht();var I$=__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");Ht();var A$=__name(({title:e,subtitle:t,skills:n,baseIndex:r,cursor:o,disabled:s})=>ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Je,null,ot.createElement(Qe,{color:pI,bold:!0},e," "),ot.createElement(Qe,{color:pI},t)),n.map((e,t)=>{const n=r+t===o,a=s.has(e.label),i=n?TI:void 0;return ot.createElement(Je,{key:e.filePath},ot.createElement(Qe,{color:a?nI.DIM:nI.GREEN,backgroundColor:i},a?"[off] ":"[on] "),ot.createElement(Qe,{color:a?nI.DIM:nI.WHITE,backgroundColor:i},e.label),e.fromAgents&&ot.createElement(Qe,{color:nI.DIM,backgroundColor:i}," [.agents]"),ot.createElement(Qe,{color:nI.DIM,backgroundColor:i}," · ~",e.estimatedTokens," tokens "))})),"SkillSection"),R$=__name(({onClose:e})=>{const[t,n]=at([]),[r,o]=at([]),[s,a]=at(!0),[i,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=it(!1);lt(()=>{__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{a(!1)}},"load")()},[]);const T=ct(()=>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),O=Math.max(4,A-14-2*R),L=__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");lt(()=>{"issues"===w&&d("")},[w]);const D="list"===w&&t.length>0,{cursor:N}=useListNavigation({items:I,onSelect:L,onCancel:e,searchQuery:c,onSearchChange:d,initialIndex:0,isActive:D});if(lt(()=>{C(e=>clampScrollOffset({cursor:N,total:I.length,maxVisible:O,currentOffset:e}))},[N,I.length,O]),tt((t,n)=>{if(!n.tab)return;const r=I[N];r&&(async()=>{try{await xt([{file:r.filePath,line:1}]),e()}catch(e){if(e instanceof Error&&e.message.includes("$EDITOR environment variable"))return void l(I$());l(e instanceof Error?e.message:"Failed to open skill in editor")}})()},{isActive:D}),tt((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 ot.createElement(ZA,{title:"Skills",gapAfterHeader:!1},ot.createElement(Qe,{color:nI.DIM},"Loading skills..."));if(i)return ot.createElement(ZA,{title:"Skills",titleColor:nI.RED,gapAfterHeader:!1,footer:ot.createElement(Qe,{italic:!0,color:nI.DIM},"Press ",ot.createElement(Qe,{bold:!0},"Esc")," to close")},ot.createElement(Qe,{color:nI.DIM},i));if(0===t.length)return ot.createElement(x$,{warnings:r,onClose:e});if("issues"===w)return ot.createElement(P$,{warnings:r,onClose:()=>v("list"),isActive:!0});const $=t.filter(e=>u.has(e.label)).length,_=k,F=k+O,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>O;return ot.createElement(ZA,{title:"Skills",titleSuffix:ot.createElement(ot.Fragment,null," ",t.length," skill",1===t.length?"":"s",$>0&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:nI.YELLOW},$," off")),r.length>0&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:nI.YELLOW},r.length," skipped"))),subtitle:getSkillPickerNoProjectNotice(h),footer:ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{italic:!0,color:nI.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"),ot.createElement(Qe,{color:nI.DIM},"add skills:"," ",ot.createElement(Qe,{color:nI.CYAN},getBinaryCommand()," skills add ","<owner/repo>")))},ot.createElement(Je,{marginBottom:1,flexDirection:"column",width:"100%"},ot.createElement(VI,{query:c,resultCount:c?I.length:void 0,placeholder:"Type to search skills..."})),0===I.length?ot.createElement(Je,{marginY:1},ot.createElement(Qe,{color:nI.GRAY},'No skills match "',c,'"')):ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"column"},U.rows.length>0&&ot.createElement(A$,{title:"Project skills",subtitle:"(.commandcode/skills or .agents/skills)",skills:U.rows,baseIndex:U.baseIndex,cursor:N,disabled:u}),j.rows.length>0&&ot.createElement(A$,{title:"User skills",subtitle:"(~/.commandcode/skills or ~/.agents/skills)",skills:j.rows,baseIndex:j.baseIndex,cursor:N,disabled:u}),B.rows.length>0&&ot.createElement(A$,{title:"Bundled skills",subtitle:"(ships with Command Code)",skills:B.rows,baseIndex:B.baseIndex,cursor:N,disabled:u})),W&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",_+1,"–",Math.min(F,I.length)," of"," ",I.length,_>0?" · ↑ more":"",F<I.length?" · ↓ more":""))),y&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.YELLOW},y)))},"SkillsConfig");function SkillsConfigView({staticKey:e,onClose:t}){return ot.useEffect(()=>{hardResetForResize()},[]),ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(R$,{onClose:t,staticKey:e})))}__name(SkillsConfigView,"SkillsConfigView"),Ht(),Ht(),Qx();var O$=[{scope:"project",label:"This project"},{scope:"global",label:"User"}],L$=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=at(!0),[s,a]=at(void 0),[i,l]=at(void 0),[c,d]=at(!0),u=isProjectTasteToggleLocked(i),m=dt(async()=>{try{const e=await getTasteLearningSettings();o(e.global),a(e.project),l(e.projectSource)}catch{}},[]);lt(()=>{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:i});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(()=>a(t.value),()=>a(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:i});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(()=>a(void 0),()=>a(n),()=>clearProjectTasteLearning())},"resetRow"),{cursor:y}=useListNavigation({items:O$,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 ot.createElement(ZA,{key:n,title:"Taste Learning",gapAfterHeader:!1},ot.createElement(VO,{label:"Loading configuration"}));const S=__name(e=>!g&&("project"===e.scope?s??r:r),"valueFor");return ot.createElement(ZA,{key:n,title:"Taste Learning",subtitle:g?ip:"Learn from your interactions.",hint:g?"esc to close":"↑/↓ navigate · enter to toggle · r reset to default · esc to close"},O$.map((e,t)=>{const n=t===y,r=S(e),o=g||"project"===e.scope&&u;return ot.createElement(Je,{key:e.scope},ot.createElement(Qe,{color:n?nI.CYAN:nI.GRAY},n?`${pt.pointer} `:" "),ot.createElement(Qe,{color:n?nI.CYAN:nI.WHITE},e.label.padEnd(16)),ot.createElement(Qe,{color:r?nI.GREEN:nI.DIM},r?"enabled":"disabled"),o?ot.createElement(Qe,{color:nI.DIM}," ",g?"(unavailable on BYOK)":"(set in settings.local.json)"):null)}),ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},"Taste data stored in .commandcode/taste/taste.md"),u?ot.createElement(Qe,{color:nI.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 ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(L$,{onClose:t,onSettingsChange:n,staticKey:e})))}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 a=n>0?Math.min(100,t/n*100):0,i=getUsageColor(a),l=buildBlockBar({percentage:a,width:o}),c=r>s?` · resets in ${formatDuration(r-s)}`:"";return ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},e.padEnd(7)," "),ot.createElement(Qe,{color:i},l.filled),ot.createElement(Qe,{color:pI},l.empty),ot.createElement(Qe,{bold:!0,color:i},` ${Math.round(a)}%`),ot.createElement(Qe,{color:nI.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?nI.RED:"warning"===t?nI.YELLOW:void 0}__name(TasteConfigView,"TasteConfigView"),Ht(),Ht(),Qx(),__name(fetchUsageData2,"fetchUsageData"),__name(getAuthKey2,"getAuthKey"),__name(WindowLimitMeter,"WindowLimitMeter"),__name(getProgressBarWidth,"getProgressBarWidth"),__name(getDaysColor,"getDaysColor");var D$=__name(({plan:e,status:t})=>ot.createElement(Je,{marginBottom:0},ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:nI.BLUE,color:"#f4f4f4",bold:!0},`${QI}USAGE${QI}`)),e&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,null," "),ot.createElement(Qe,{color:nI.GRAY},`${e.name} Plan`)),t&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:"active"===t?nI.GREEN:nI.YELLOW},t))),"UsageBadge"),N$=__name(({showRetry:e})=>ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,e&&ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"r")," to retry · "),"Press ",ot.createElement(GA,null,"Esc")," to close")),"UsageFooter"),$$=__name(({onClose:e})=>{const[t,n]=at("loading"),[r,o]=at(null),[s,a]=at(!1),i=getProgressBarWidth({terminalWidth:useTerminalWidth()}),l=dt(async e=>{try{a(!1);const t=await fetchUsageData2();if(e.aborted)return;if(!t.whoami){const e=t.errors.some(isAuthErrorMessage);return a(e),void n("error")}o(t),n("loaded")}catch{if(e.aborted)return;n("error")}},[]),c=ot.useRef(null);tt((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)}}),lt(()=>{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 ot.createElement(Je,{flexDirection:"column",paddingX:0,width:"100%"},ot.createElement(D$,{plan:m,status:u?.status??null}),ot.createElement(VO,null),ot.createElement(N$,null));if("error"===t)return ot.createElement(Je,{flexDirection:"column",paddingX:0,width:"100%"},ot.createElement(D$,{plan:m,status:u?.status??null}),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},s?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),ot.createElement(N$,{showRetry:!s}));if(!r)return null;const p=d?.hasBillingData??!1,g=d?.usageUrl??null;if(!p)return ot.createElement(Je,{flexDirection:"column",paddingX:0,width:"100%"},ot.createElement(D$,{plan:m,status:u?.status??null}),ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(YO,{message:"No billing data found."}),g&&ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},"Visit "),ot.createElement(BI,{url:g,text:"Studio",color:nI.CYAN}),ot.createElement(Qe,{color:nI.DIM}," for usage details."))),ot.createElement(N$,null));const h=d?.windowLimits??null,f=d?.summary??null,y=d?.now??Date.now(),S=d?.credits,w=S?.totalRemaining??0,v=S?.usagePercent??0,k=Boolean(S?.hasCreditsInfo),C=d?.daysLeft??null,b=getDaysColor(C),E=getUsageColor(v),T=buildBlockBar({percentage:v,width:i});return ot.createElement(Je,{flexDirection:"column",paddingX:0,width:"100%"},ot.createElement(Je,{marginBottom:1},ot.createElement(D$,{plan:m,status:u?.status??null})),k?ot.createElement(Je,null,ot.createElement(Qe,{color:E},T.filled),ot.createElement(Qe,{color:pI},T.empty),ot.createElement(Qe,{bold:!0,color:E},` ${Math.round(v)}% used`)):ot.createElement(Qe,{color:nI.DIM},"Plan details unavailable"),k&&ot.createElement(Je,null,u?.currentPeriodEnd&&ot.createElement(Qe,{color:nI.DIM},"Cycle: "),ot.createElement(Qe,null,formatCredits(w)),ot.createElement(Qe,{color:nI.DIM}," left"),f&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,null,f.totalCount.toLocaleString()),ot.createElement(Qe,{color:nI.DIM}," requests")),null!==C&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.DIM}," · "),0===C?ot.createElement(Qe,{color:b},"renewal today"):ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:b},`${C} day${1===C?"":"s"}`),ot.createElement(Qe,{color:nI.DIM}," to renewal")))),h?.limited&&ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Usage limits"),h.fiveHour&&ot.createElement(WindowLimitMeter,{label:"5-hour",used:h.fiveHour.used,cap:h.fiveHour.cap,resetAt:h.fiveHour.resetAt,width:i,now:y}),h.weekly&&ot.createElement(Je,{marginTop:h.fiveHour?1:0,flexDirection:"column"},ot.createElement(WindowLimitMeter,{label:"Weekly",used:h.weekly.used,cap:h.weekly.cap,resetAt:h.weekly.resetAt,width:i,now:y}))),g&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Full breakdown at "),ot.createElement(BI,{url:g,text:d?.usageUrlDisplay??g,color:nI.CYAN})),ot.createElement(N$,null))},"UsageOverlay");function UsageView({staticKey:e,onClose:t}){return ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement($$,{onClose:t})))}__name(UsageView,"UsageView"),Ht(),Qx(),Ht(),Qx(),Ht();var _$="@last";function shortenHomePath(e){const t=W();return e.startsWith(t)?`~${e.slice(t.length)}`:e}__name(shortenHomePath,"shortenHomePath");var F$={approved:{label:`${pt.tick} approved`,color:nI.GREEN},"not-implemented":{label:`${pt.circleDotted} set aside`,color:nI.YELLOW},pending:{label:`${pt.dot} pending`,color:nI.DIM}},U$=createNodeRuntime(),j$={"?":"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:nI.GREEN,bold:!1,italic:!1};const t={color:nI.WHITE,bold:!1,italic:!1};if(!e.style)return t;switch(e.style.role){case"heading":return{color:vI.HEADING,bold:!0,italic:!1};case"code":case"code-fence":return{color:vI.CODE,bold:!1,italic:!1};case"quote":return{color:nI.DIM,bold:!1,italic:!0};case"table":return{color:nI.CYAN,bold:!1,italic:!1};default:return t}}__name(lineStyleProps,"lineStyleProps");var B$=__name(({plan:e,variant:t="browse",fallbackContent:n,onBack:r,onSubmitFeedback:o,onExecute:s,onAutoAccept:a})=>{const[i,l]=at(null),[c,d]=at(e.annotations),[u,m]=at(!1);lt(()=>{u||d(e.annotations)},[e.annotations,u]);const[p,g]=at({kind:"line",lineNumber:1}),[h,f]=at(null),[y,S]=at(null),[w,v]=at(null),[k,C]=at(!1),[b,E]=at(0),[T,P]=at(null),M=useTerminalHeight(),x=useTerminalWidth();lt(()=>{__name(async()=>{const t=await readPlanContent({runtime:U$,filePath:e.filePath})??n??null;l(null===t?[]:splitPlanLines(t))},"load")()},[e.filePath,n]);const I=e.version??1;lt(()=>{I<=1||!e.filePath||readPlanVersionSnapshot({runtime:U$,filePath:e.filePath,version:I-1}).then(P).catch(()=>{})},[I,e.filePath]);const A=ct(()=>null!==T&&null!==i?diffPlanChangedLines({previous:T,current:i}):new Set,[T,i]),R=c.length,O=ct(()=>{const e={id:"feedback",label:`Submit review (${R})`,chord:"ctrl+r",color:nI.CYAN,hint:"agent revises the plan, returns it for review"};return"approval"===t?[...R>0?[e]:[],{id:"auto-accept",label:"Approve",chord:"ctrl+a",color:nI.GREEN,hint:R>0?"executes the plan · comments go along as notes":"executes the plan"},{id:"cancel",label:"Cancel",chord:"esc",color:nI.YELLOW,hint:""}]:[...R>0?[e]:[],{id:"execute",label:"Execute plan",chord:"ctrl+e",color:nI.GREEN,hint:"executes the plan as written"},{id:"cancel",label:"Back",chord:"esc",color:nI.YELLOW,hint:""}]},[t,R]),L=ct(()=>h?c.filter(e=>e.line!==h.line):c,[c,h]),D=ct(()=>buildPlanReaderRows({lines:i??[],annotations:L}),[i,L]),N=ct(()=>classifyPlanLines(i??[]),[i]),$=i?.length??0,_=resolvePlanWrapWidth(Math.max(20,x-7-2)),F=ct(()=>buildPlanReaderDisplayRows({rows:D,width:_}),[D,_]),U=getPlanReaderCursorDisplaySpan({displayRows:F,cursor:p}),j=M-1,B=Math.max(4,j-10-7),W=h?1:0,H=-1===U.first?F.length-1:U.first,G=-1===U.last?F.length-1:U.last+W;lt(()=>{E(e=>{const t=clampScrollOffset({cursor:Math.max(0,G),total:F.length+W,maxVisible:B,currentOffset:e});return clampScrollOffset({cursor:Math.max(0,H),total:F.length+W,maxVisible:B,currentOffset:t})})},[H,G,F.length,W,B]),lt(()=>{g(e=>snapPlanReaderCursor({cursor:e,lineCount:$,actions:[]}))},[$]),lt(()=>{g(e=>"action"!==e.kind||O.some(t=>t.id===e.id)?e:{kind:"line",lineNumber:Math.max(1,$)})},[O,$]);const V=__name(t=>{m(!0),d(t),e.filePath&&setPlanAnnotations({runtime:U$,filePath:e.filePath,annotations:t}).catch(()=>v("Failed to save comments to disk"))},"persistAnnotations"),z="line"===p.kind?c.find(e=>e.line===p.lineNumber):void 0,K=__name(()=>{if(0===c.length||!i)return;const t=buildPlanAnnotationsPrompt({title:e.title,filePath:e.filePath||"(plan not saved to a file yet)",lines:i,annotations:c});e.filePath&&snapshotPlanVersion({runtime:U$,filePath:e.filePath}).catch(()=>{}),V([]),o(t)},"submitFeedback"),q=__name(t=>{if(t&&c.length>0&&i){const t=buildPlanApprovalNotesPrompt({title:e.title,...e.filePath?{filePath:e.filePath}:{},lines:i,annotations:c});return V([]),void a?.(t)}V([]),a?.()},"approve"),Y=__name(()=>{"approval"===t&&(R>0?S({kind:"approve",choice:"notes"}):q(!1))},"requestApprove"),J=__name(()=>{R>0&&!e.filePath?S({kind:"cancel"}):r()},"requestCancel"),Q=__name(t=>{"feedback"!==t?"execute"!==t?"auto-accept"!==t?"cancel"===t&&J():Y():(s??o)(buildPlanExecutePrompt({title:e.title,filePath:e.filePath||e.fileName})):K()},"runAction"),X=__name(()=>{e.filePath?(C(!0),openFileInEditor(e.filePath).then(async()=>{const t=await readPlanContent({runtime:U$,filePath:e.filePath});null!==t&&l(splitPlanLines(t))}).catch(e=>v(e instanceof Error?e.message:"Failed to open the editor")).finally(()=>{C(!1),hardResetForResize()})):v("This plan is not saved to a file yet")},"openExternalEditor"),Z=__name(e=>{"line"!==p.kind||p.lineNumber<1||p.lineNumber>$||f({line:p.lineNumber,value:e||(z?.text??""),hadExisting:void 0!==z})},"openDraft"),ee=__name(e=>{h&&(V(upsertPlanAnnotation({annotations:c,line:h.line,text:e,createdAt:(new Date).toISOString()})),f(null))},"commitDraft"),te=ct(()=>{const e=new Set;for(const t of c)e.add(t.line);for(const t of A)e.add(t);return[...e].sort((e,t)=>e-t)},[c,A]),ne=__name(e=>{if(0===te.length)return;const t="line"===p.kind?p.lineNumber:$+1,n="next"===e?te.find(e=>e>t)??te[0]:[...te].reverse().find(e=>e<t)??te[te.length-1];void 0!==n&&g({kind:"line",lineNumber:n})},"jumpMarked");tt((e,t)=>{t.escape&&f(null)},{isActive:null!==h}),tt((e,t)=>{if(y)if(t.escape)S(null);else if("approve"===y.kind&&(t.leftArrow||t.rightArrow||t.tab))S({kind:"approve",choice:"notes"===y.choice?"original":"notes"});else if(t.return){if("approve"===y.kind)return S(null),void q("notes"===y.choice);S(null),r()}},{isActive:null!==y}),tt((e,n)=>{if(n.escape)return void J();if(n.upArrow||n.downArrow)return v(null),void g(e=>{if("action"===e.kind){const t=O.findIndex(t=>t.id===e.id);if(n.upArrow){if(t<=0&&$>0)return{kind:"line",lineNumber:$};const n=O[Math.max(0,t-1)];return n?{kind:"action",id:n.id}:e}const r=O[Math.min(O.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>=$){const t=O[0];return t?{kind:"action",id:t.id}:e}return{kind:"line",lineNumber:e.lineNumber+1}});if(n.pageUp||n.pageDown)return v(null),void g(e=>"action"===e.kind&&n.pageDown?e:movePlanReaderCursorByPage({displayRows:F,cursor:e,direction:n.pageDown?"down":"up",pageRows:Math.max(1,B-1)}));if(n.home||n.end)return v(null),void($>0&&g({kind:"line",lineNumber:n.home?1:$}));if(n.leftArrow||n.rightArrow){if("action"!==p.kind)return;const e=O.findIndex(e=>e.id===p.id);if(-1===e)return;const t=n.leftArrow?Math.max(0,e-1):Math.min(O.length-1,e+1),r=O[t];return void(r&&g({kind:"action",id:r.id}))}if(n.ctrl&&"r"===e)return void K();if(n.ctrl&&"a"===e&&"approval"===t)return void Y();if(n.ctrl&&"e"===e&&"browse"===t)return void Q("execute");if(n.ctrl&&"g"===e)return void X();if(n.ctrl&&"n"===e)return void ne("next");if(n.ctrl&&"p"===e)return void ne("previous");if(n.return)return"action"===p.kind?void Q(p.id):void Z("");const r=j$[e];"line"!==p.kind||!r||n.ctrl||n.meta?"line"===p.kind&&e.length>0&&!n.ctrl&&!n.meta&&Z(e):V(upsertPlanAnnotation({annotations:c,line:p.lineNumber,text:z?.text===r?"":r,createdAt:(new Date).toISOString()}))},{isActive:null===h&&null===y&&null!==i&&!k});const re=F$[e.status],oe=b,se=b+B-W,ae=F.slice(oe,se),ie=h?h.hadExisting?"enter to keep · clear + enter removes · esc keep as was":"enter to pin · esc discard":y?"approve"===y.kind?"←/→ choose · enter confirm · esc back":"enter discard · esc back":"action"===p.kind?"↑/↓ choose · enter to run":["type + enter to comment",...te.length>0?["ctrl+n/p jump "+(A.size>0?"changes":"comments")]:[],"quick: ? why x cut ! risky","ctrl+g $EDITOR"].join(" · ");return ot.createElement(ZA,{title:"approval"===t?`Plan review: ${e.title}`:e.title,titleSuffix:"approval"===t?ot.createElement(ot.Fragment,null," ","· ",shortenHomePath(e.filePath)||e.fileName," · v",e.version??1):ot.createElement(ot.Fragment,null," ","· ",shortenHomePath(e.filePath)||e.fileName," · v",e.version??1," ",ot.createElement(Qe,{color:re.color},re.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:ot.createElement(Qe,{italic:!0,color:nI.DIM},ie)},null===i?ot.createElement(Qe,{color:nI.DIM},"Loading plan..."):0===$?ot.createElement(Qe,{color:nI.DIM},"Plan file is empty or missing on disk."):ot.createElement(Je,{flexDirection:"column"},ae.map((e,t)=>{const n=oe+t,{row:r}=e;if("action"===r.kind)return null;if("annotation"===r.kind)return ot.createElement(Je,{key:`annotation-${r.lineNumber}-${n}`},ot.createElement(Qe,{color:nI.DIMMER}," ".repeat(5)),ot.createElement(Qe,{backgroundColor:oI.BADGE_BG,color:oI.BADGE_FG}," ",e.isFirstSegment?"↳ ":" ",e.text," "));const o="line"===p.kind&&p.lineNumber===r.lineNumber,s=lineStyleProps({style:N[r.lineNumber-1],changed:A.has(r.lineNumber)}),a=F[n+1],i=!a||"line"!==a.row.kind||a.row.lineNumber!==r.lineNumber,l=n===se-1,c=null!==h&&h.line===r.lineNumber&&(i||l);return ot.createElement(ot.Fragment,{key:`line-${r.lineNumber}-${n}`},ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIMMER},e.isFirstSegment?String(r.lineNumber).padStart(4," "):" "," "),ot.createElement(Qe,{color:r.hasAnnotation?nI.CYAN:nI.DIMMER},e.isFirstSegment&&r.hasAnnotation?`${pt.bullet} `:" "),ot.createElement(Qe,{color:s.color,bold:s.bold,italic:s.italic,backgroundColor:o?TI:void 0},e.text||" ")),c&&h&&ot.createElement(Je,null,ot.createElement(Qe,{color:nI.CYAN}," ┃ ",pt.bullet," "),ot.createElement(TextInput,{value:h.value,onChange:e=>f(t=>t?{...t,value:e}:t),onSubmit:ee,placeholder:"Type your comment…",focus:null!==h,stripBracketedPaste:!0})))})),ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(RI,{dividerColor:nI.DIMMER}),ot.createElement(Je,null,ot.createElement(Qe,{bold:!0,backgroundColor:oI.BADGE_BG,color:nI.WHITE}," REVIEW "),ot.createElement(Qe,{color:nI.DIM},R>0&&` ${R} pending comment${1===R?"":"s"}`,I>1&&` · round ${I}${A.size>0?` · ${A.size} line${1===A.size?"":"s"} changed`:""}`)),y?"approve"===y.kind?ot.createElement(Je,null,ot.createElement(Qe,{bold:!0,color:nI.GREEN},"Approve"," "),ot.createElement(Qe,{color:"notes"===y.choice?nI.WHITE:nI.DIM,backgroundColor:"notes"===y.choice?TI:void 0},"notes"===y.choice?"(•)":"( )"," ","with ",R," comment",1===R?"":"s"," as notes"),ot.createElement(Qe,{color:nI.DIMMER}," "),ot.createElement(Qe,{color:"original"===y.choice?nI.WHITE:nI.DIM,backgroundColor:"original"===y.choice?TI:void 0},"original"===y.choice?"(•)":"( )"," ","original plan · discard comments")):ot.createElement(Je,null,ot.createElement(Qe,{color:nI.YELLOW},"Discard ",R," pending comment",1===R?"":"s"," and exit review?")):O.map(e=>{const t="action"===p.kind&&p.id===e.id;return ot.createElement(Je,{key:e.id},ot.createElement(Qe,{bold:!0,color:e.color,backgroundColor:t?TI:void 0},t?`${pt.pointer} ${e.label} `:e.label),ot.createElement(Qe,{color:nI.DIM}," ",e.chord),e.hint&&ot.createElement(Qe,{color:nI.DIMMER}," ",e.hint))}),w&&ot.createElement(Qe,{color:nI.YELLOW},w)))},"PlanReader"),W$=createNodeRuntime();function PlanApprovalView({staticKey:e,planContent:t,planFilePath:n,onAutoAccept:r,onCancel:o,onSendFeedback:s}){lt(()=>{hardResetForResize()},[]);const[a,i]=at(null);lt(()=>{n&&listPlans({runtime:W$}).then(e=>i(e.find(e=>e.filePath===n)??null)).catch(()=>{})},[n]);const l=ct(()=>{if(a)return a;const e=n?.split("/").pop()??"plan.md";return{fileName:e,filePath:n??"",title:derivePlanTitle({content:t,fileName:e}),status:"pending",createdAt:"",updatedAt:"",annotations:[]}},[a,n,t]);return ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(B$,{plan:l,variant:"approval",fallbackContent:t,onBack:o,onSubmitFeedback:s,onAutoAccept:r})))}__name(PlanApprovalView,"PlanApprovalView"),Ht(),Ht(),Qx();var H$=Date.now(),G$=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 V$=__name(({sessionId:e,target:t,onClose:n,onSubmitFeedback:r,onExecute:o})=>{const[s,a]=at([]),[i,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=it(!1);lt(()=>{__name(async()=>{try{const[n,r]=await Promise.all([listPlans({runtime:G$,sessionId:e,sessionStartMs:H$}),listPlans({runtime:G$})]);if(a([...n]),l([...r]),t&&!E.current)if(E.current=!0,t===_$){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:i,P=ct(()=>{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(lt(()=>{v(e=>clampScrollOffset({cursor:A,total:P.length,maxVisible:x,currentOffset:e}))},[A,P.length,x]),tt((e,t)=>{(t.leftArrow||t.rightArrow)&&(g(e=>"session"===e?"all":"session"),v(0))},{isActive:I}),h)return ot.createElement(B$,{plan:h,onBack:()=>{f(null),C(e=>e+1)},onSubmitFeedback:r,onExecute:o});if(c)return ot.createElement(ZA,{title:"Plans",gapAfterHeader:!1},ot.createElement(Qe,{color:nI.DIM},"Loading plans..."));if(u)return ot.createElement(ZA,{title:"Plans",titleColor:nI.RED,gapAfterHeader:!1,hint:"Esc to close"},ot.createElement(Qe,{color:nI.DIM},u));const R=w,O=w+x,L=P.slice(R,O),D=P.length>x;return ot.createElement(ZA,{title:"Plans",titleSuffix:ot.createElement(ot.Fragment,null," ",P.length," plan",1===P.length?"":"s"),subtitle:ot.createElement(ot.Fragment,null,ot.createElement(Qe,{bold:"session"===p,color:"session"===p?zA:nI.DIM},"This session"),ot.createElement(Qe,{color:nI.DIMMER},` ${pt.triangleLeftSmall} ${pt.triangleRightSmall} `),ot.createElement(Qe,{bold:"all"===p,color:"all"===p?zA:nI.DIM},"All plans")),footer:ot.createElement(Qe,{italic:!0,color:nI.DIM},"type to search · ↑/↓ navigate · ←/→ switch tab · enter to open",y?" · esc to clear":" · esc to close")},ot.createElement(Je,{marginBottom:1,flexDirection:"column",width:"100%"},ot.createElement(VI,{query:y,resultCount:y?P.length:void 0,placeholder:"Type to search plans..."})),0===P.length?ot.createElement(Je,{marginY:1},ot.createElement(Qe,{color:nI.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.")):ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"column"},L.map((e,t)=>{const n=R+t===A,r=F$[e.status];return ot.createElement(Je,{key:e.fileName},ot.createElement(Qe,{color:n?YA:nI.GRAY},n?`${pt.pointer} `:" "),ot.createElement(Qe,{bold:n,color:n?YA:nI.WHITE},e.title),ot.createElement(Qe,{color:r.color}," ",r.label),(e.version??1)>1&&ot.createElement(Qe,{color:nI.DIM}," ","v",e.version),e.annotations.length>0&&ot.createElement(Qe,{color:nI.CYAN}," ",e.annotations.length," comment",1===e.annotations.length?"":"s"),ot.createElement(Qe,{color:nI.DIM}," ",formatRelativeTimeShort({timestamp:e.updatedAt})))})),D&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",R+1,"–",Math.min(O,P.length)," of"," ",P.length,R>0?" · ↑ more":"",O<P.length?" · ↓ more":""))))},"PlansScreen");function PlansView({staticKey:e,sessionId:t,target:n,onClose:r,onSubmitFeedback:o,onExecute:s}){return ot.useEffect(()=>{hardResetForResize()},[]),ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(V$,{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:nI.DIM,o=e.userRenamed&&e.title?e.title:null;return o?ot.createElement(Qe,{color:n},`${o} `,ot.createElement(Qe,{color:r},`· ${e.forkProvenance}`)):ot.createElement(Qe,{color:r},e.forkProvenance)}__name(PlansView,"PlansView"),Ht(),Ht(),Qx(),Ht(),__name(ForkSummary,"ForkSummary");var z$=__name((e,t)=>e.padEnd(t),"padCell"),K$=__name(e=>e instanceof Error&&e.message?e.message:"Unknown error","getActionErrorMessage");function resolveRowColor(e){return e.isDeletePending?nI.RED:e.isCurrentSession?rI:e.isSelected?nI.WHITE:nI.GRAY}function renderRowSummary(e){const{session:t,isSelected:n,nameColor:r}=e;if(t.forkProvenance)return ot.createElement(ForkSummary,{session:t,isSelected:n,nameColor:r});const o=getSessionSummary({session:t});return t.userRenamed&&t.title?ot.createElement(Qe,{color:r},o):o}__name(resolveRowColor,"resolveRowColor"),__name(renderRowSummary,"renderRowSummary");var q$=["recent","created","messages"],Y$={recent:"Recent",created:"Created",messages:"Messages"};function nextSortMode(e){const t=q$.indexOf(e);return q$[(t+1)%q$.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 J$=__name(({onSelectSession:e,onClose:t,currentSessionId:n})=>{const[r,o]=at([]),[s,a]=at(0),[i,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,O]=at(""),[L,D]=at(null),[N]=at(()=>getCurrentGitBranch()),[$]=at(()=>resolveProjectBaseDir()),_=useTerminalHeight(),F=Math.max(6,_-19),U=dt(async()=>{d(!0);const e=await listCommandSessions();o(e),d(!1)},[]);lt(()=>{U()},[U]),lt(()=>{if(!y)return;const e=setTimeout(()=>S(null),3e3);return()=>clearTimeout(e)},[y]);const j=dt(async e=>{try{const t=getCommandSessionRuntime(),{method:n}=await deleteSessionV3({runtime:t,baseDir:$,id:e});g(!1),f(null),a(0),l(0),S("trash"===n?"Session moved to trash":"Session deleted"),await U()}catch(e){g(!1),f(`Failed to delete session: ${K$(e)}`)}},[U,$]),B=dt(async e=>{const t=I;if(t)try{const n=getCommandSessionRuntime();await renameSessionFile({runtime:n,cwd:n.cwd(),baseDir:$,id:t,name:e}),x("list"),A(null),D(null),await U()}catch(e){D(`Failed to rename session: ${K$(e)}`)}else x("list")},[I,U,$]),W=filterSessionsByBranch({sessions:r,branchFilter:u,currentBranch:N}),H=T?W.filter(e=>e.userRenamed):W,G=sortSessions(w?H.filter(e=>matchesSearch2(e,w)):H,b);if(lt(()=>{a(e=>Math.min(e,Math.max(0,G.length-1)))},[G.length]),tt((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),O(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),a(0),void l(0)):o.escape?w?(v(""),a(0),void l(0)):void t():isCtrlKey({inputChar:r,key:o,letter:"b",ctrlCode:2})?(m(e=>!e),a(0),void l(0)):void(o.upArrow?a(e=>{const t=Math.max(0,e-1);return t<i&&l(t),t}):o.downArrow?a(e=>{const t=Math.min(G.length-1,e+1);return t>=i+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)),a(0),l(0)):!o.ctrl&&!o.meta&&!o.tab&&r&&1===r.length&&r>=" "&&(v(e=>e+r),a(0),l(0)));E(e=>nextSortMode(e))}}}),c)return ot.createElement(Je,{flexDirection:"column",paddingLeft:2},ot.createElement(VO,{label:"Loading sessions"}));if(0===r.length)return ot.createElement(Je,{flexDirection:"column",paddingLeft:2},ot.createElement(YO,{message:"No previous sessions found",hint:"Press Esc to go back"}));const V=G.slice(i,i+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:N});return ot.createElement(ZA,{title:"Resume Session",subtitle:`Sort: ${Y$[b]} · Name: ${T?"Named":"All"} · Branch: ${u?N??"unknown":"All"}`},ot.createElement(Je,{marginBottom:1,width:"100%"},ot.createElement(VI,{query:w,resultCount:w?G.length:void 0,placeholder:"Type to search sessions..."})),ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:pI,bold:!0},z$("#",6),z$("Modified",12),z$("Git Branch",22),z$("Messages",12),"Summary",k?" · Path":"")),0===G.length?ot.createElement(Je,{marginBottom:1},ot.createElement(YO,{message:q.text,hint:q.hint})):ot.createElement(Je,{flexDirection:"column"},V.map((e,t)=>{const r=i+t,o=s===r,a=p&&o,l=a?void 0:nI.YELLOW,c=resolveRowColor({isDeletePending:a,isCurrentSession:e.id===n,isSelected:o}),d=truncateString2({text:e.gitBranch||"-",maxChars:20}),u=k?toRelativePath(`${$}/${e.id}.jsonl`):null;return ot.createElement(Qe,{key:e.id,color:c,backgroundColor:o?TI:void 0,bold:o,wrap:"truncate-end"},z$(`${r+1}.`,6),z$(formatRelativeTimeShort({timestamp:e.lastModified}),12),z$(d,22),z$(String(e.messageCount),12),renderRowSummary({session:e,isSelected:o,nameColor:l}),u?ot.createElement(Qe,{color:nI.DIM},` ${u}`):null," ")})),ot.createElement(Je,{marginTop:1}),"rename"===M&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.CYAN},"Rename: "),ot.createElement(TextInput,{value:R,onChange:O,onSubmit:B,singleLine:!0,stripBracketedPaste:!0})),L&&ot.createElement(Je,{marginBottom:1},ot.createElement(zO,{glyph:!1},L)),K&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.RED},K)),h&&ot.createElement(Je,{marginBottom:1},ot.createElement(zO,{glyph:!1},h)),y&&ot.createElement(Je,{marginBottom:1},ot.createElement(KO,{glyph:!1},y)),G.length>F&&ot.createElement(Qe,{color:nI.DIM},"Showing ",i+1,"–",Math.min(i+F,G.length)," ","of ",G.length,i>0?" · ↑ more":"",i+F<G.length?" · ↓ more":""),ot.createElement(VA,{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"),Q$=st(__name(function SessionView2({onSelectSession:e,onClose:t,currentSessionId:n}){return ot.createElement(J$,{onSelectSession:e,onClose:t,currentSessionId:n})},"SessionView"));Ht(),Ht();var X$=__name(({onTrust:e,onExit:t})=>{const{exit:n}=nt(),[r,o]=at(1),s=process.cwd(),a=W(),i=a&&s.startsWith(a)?`~${s.slice(a.length)}`:s;return tt((s,a)=>{if(a.upArrow||a.downArrow)o(1===r?2:1);else{if(a.return)return 1===r?void e():(t(),void n());if("1"!==s)return"2"===s?(t(),void n()):void((a.escape||a.ctrl&&"c"===s)&&(t(),n()));e()}}),ot.createElement(ZA,{title:"Do you trust the files in this folder?",subtitle:i,hint:"↑/↓ to navigate · enter to select · esc to exit"},ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Je,null,ot.createElement(WL,{isSelected:1===r}),ot.createElement(HL,{isSelected:1===r,idleColor:QA}," ","1. Yes, proceed")),ot.createElement(Je,null,ot.createElement(WL,{isSelected:2===r}),ot.createElement(HL,{isSelected:2===r,idleColor:QA}," ","2. No, exit"))))},"TrustPrompt"),Z$=st(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(X$,{onTrust:t,onExit:n}))},"TrustView"));Ht(),Ht();var e_=new Map;function enqueueAgentSlashCommand(e){const t=e_.get(e.sessionId);t?t.push(e.command):e_.set(e.sessionId,[e.command])}function drainAgentSlashCommands(e){const t=e_.get(e.sessionId);return t&&0!==t.length?(e_.delete(e.sessionId),t):[]}function useAgentSlashCommandQueue({sessionId:e,isCmdCodeBusy:t,onCommand:n}){const r=it(!1);lt(()=>{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),[a,i]=at(!1),[l,c]=at(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,authComponentInfo:o,setAuthComponentInfo:s,showProviderNotification:a,setShowProviderNotification:i,premiumCreditsExhausted:l,setPremiumCreditsExhausted:c,providerNotificationTimer:it(null),modelNotificationTimer:it(null)}}__name(enqueueAgentSlashCommand,"enqueueAgentSlashCommand"),__name(drainAgentSlashCommands,"drainAgentSlashCommands"),__name(useAgentSlashCommandQueue,"useAgentSlashCommandQueue"),Ht(),Qx(),__name(useAuth,"useAuth"),Ht(),Qx();var t_=__name(()=>{const[e,t]=at({isExecuting:!1,currentCommand:null});return{executeBash:dt(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");Ht(),Ht(),Qx(),Ht(),Qx();var n_={detectIDE:NC,isIdeIpcConnected:__name(async e=>{const t=VC(),n=await t.connect(e);return t.disconnect(),n},"isIdeIpcConnected"),log:dlog,platform:__name(()=>process.platform,"platform")};Ht();var r_=null,o_={};function requestReload(e){r_=e}function discardPendingReload(){r_=null}function consumePendingReload(){const e=r_;return r_=null,e}function setOriginalInvocation(e){o_=e}function getOriginalInvocation(){return o_}function resolveProviderOrReport(e){return resolveCommandProviderId(e.provider)||(e.setFeed(t=>[...t,gg(`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,gg("Provider login is not available here.")]):void t(t=>[...t,lg(`${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,lg(s.message)])}function handleLoginComplete({success:e,message:t,setShowLoginOverlay:n,setFeed:r,setStatus:o}){if(n(!1),!e)return r(e=>[...e,gg(t)]),void o("Ready...");r(e=>[...e,lg(t)]),invalidateBillingContext(),o("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,lg("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,lg(`${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,lg(n?`Logged out of ${r}`:`No saved ${r} credential found`)])}catch(n){const r=n instanceof Error?n.message:"Unknown error";t(t=>[...t,gg(`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?gg(s.notice.message):lg(s.notice.message)])}function parseChangelogVersions(e){return e.split(/^(?=## )/m).map(e=>e.trim()).filter(e=>e.startsWith("## "))}function findChangelogPath(e){let t=r(m(e));for(let e=0;e<6;e++){const e=n(t,"CHANGELOG.md");if(I(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,lg("No changelog available in this build.")]);const o=parseChangelogVersions(A(r,"utf8"));if(0===o.length)return void e(e=>[...e,lg("The changelog is empty.")]);const s="all"===t.trim().toLowerCase()?o.length:10,a=o.slice(0,s).join("\n\n"),i=o.length-s,l=i>0?`\n\n_…and ${i} earlier releases · /changelog all_`:"";e(e=>[...e,pg(`**What's new**\n\n${a}${l}`)])}async function releaseHarness(e){if(e){try{await($O(e)?.flush())}catch{}_O(e)}}async function handleSelectSession({selectedSessionId:e,previousSessionId:t,sessionLoadIdRef:n,setFeed:r,setLiveEntries:o,setSessionId:s,setShowSessionSelector:a,setSessionLoaded:i,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),a(!1),i(!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([gg(g.message)]),a(!1),i(!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);$O(e)?.applyTodoUserEdit({todos:h}),g.bannerModelChanged||isWrappedChild()?hardResetForResize():cA(),l(e=>e+1)}__name(requestReload,"requestReload"),__name(discardPendingReload,"discardPendingReload"),__name(consumePendingReload,"consumePendingReload"),__name(setOriginalInvocation,"setOriginalInvocation"),__name(getOriginalInvocation,"getOriginalInvocation"),Ht(),Qx(),__name(resolveProviderOrReport,"resolveProviderOrReport"),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Ht(),Qx(),__name(parseChangelogVersions,"parseChangelogVersions"),__name(findChangelogPath,"findChangelogPath"),__name(handleChangelog,"handleChangelog"),Ht(),Qx(),Ht(),Qx(),__name(releaseHarness,"releaseHarness"),__name(handleSelectSession,"handleSelectSession");var s_="Nothing to clone yet.";async function handleCloneCommand(e){const t=$O(e.sessionId);if(t)try{const n=await t.cloneSession();if(!n)return void e.setFeed(e=>[...e,lg(s_)]);e.setFeed(e=>[...e,lg(`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,gg("Couldn't clone the session (storage error). Staying on the current session.")])}else e.setFeed(e=>[...e,lg(s_)])}async function handleCompactCommand({sessionId:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:o,setStaticKey:s}){try{r(!0),n("Compacting conversation...");const a=await NO({sessionId:e,baseUrl:getApiBaseUrl()}),i=await a.compact();cA(),s(e=>e+1);const l=buildCompactCommandNotice(i);t(e=>[...e,lg(l.message)]),r(!1),n("Ready..."),o(buildPostCompactContextUsage())}catch(e){t(t=>[...t,gg(buildCompactErrorNotice(e).message)]),r(!1),n("Ready...")}}__name(handleCloneCommand,"handleCloneCommand"),Ht(),Qx(),__name(handleCompactCommand,"handleCompactCommand"),Ht(),Qx();var a_=__name(e=>{const t=e.metadata?.blockOf;return"string"==typeof t?t:e.id},"groupIdOf"),i_=__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=a_(n),o=[];for(let n=t;n>=0;n--){const t=e[n];if(!t||"assistant"!==t.role||a_(t)!==r)break;const s=i_(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,lg("Nothing to copy yet — no reply in this session.")]);const r=await writeClipboardText(n),o=n.length.toLocaleString("en-US");t(e=>[...e,lg(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?Lg(o):null;if(!s)return!1;const a=projectUserEdits(s);return a.every(e=>"completed"===e.status)?(clearSessionTodos(),a.length>0&&routeHarnessFeedEntry({entry:{...t,output:JSON.stringify(a)},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,...a}=e.metadata??{};r.push({...e,id:`${e.id}-block-${n}`,input:o,metadata:{...a,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),a=buildBlockEntries(e,o,s.newlyCompleted);a.length>0&&t(e=>[...e,...a]);const i={...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,i];const r=[...t];return r[n]=i,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 a=buildBlockEntries(e,o,s.remaining);a.length>0&&t(e=>[...e,...a])}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:a,displayMessage:i,isAutomated:l,isMeta:c,hiddenMessages:d,isGoalContinuation:u,isGoalBootstrap:m,suppressUserEcho:p,feed:g,setFeed:h,setLiveEntries:f,isCmdCodeBusy:y,setIsCmdCodeBusy:S,setQueuedMessages:w,setStatus:v,setInteractionTokens:k,updateStatus:C,setUpdateStatus:b,billingLink:E,setBillingLink:T,currentModel:P,currentProvider:M,premiumCreditsExhausted:x,setPremiumCreditsExhausted:I,setCurrentModel:A,sessionId:R,isSubmittingRef:O,setInput:L,setStaticKey:D,executeBash:N}=e,$=resolveSubmitStartPlan({role:t,input:n,isCmdCodeBusy:y,isSubmitting:O.current,displayMessage:i,isAutomated:l,isMeta:c,hiddenMessages:d,images:r,ideContext:s,ideHint:a});if("skip"===$.kind&&!n.length)return $.outcome;if(C&&b(null),k(0),"skip"===$.kind)return $.outcome;if("bash"===$.kind){O.current=!0;const e=mg(n);return h([...g,e]),L(""),await N(n,e=>{h(e)},()=>{cA(),D(e=>e+1)}),O.current=!1,"completed"}if("queue"===$.kind)return w(e=>[...e,$.queuedMessage]),l||L(""),$.outcome;O.current=!0;const _=await runModInputInterception(e);if("handled"===_.action){O.current=!1;const e=_.message;return e&&h(t=>[...t,lg(e)]),"skipped"}const F="transform"===_.action?_.text:n;await loadCustomProviderModels();const U=await checkOAuthSetupRequired({currentProvider:M??null,isByokModel:isByok({model:P??""}),providerAuthHeaders:providerAuthHeaders});if(U)return O.current=!1,v(U),h(e=>[...e,gg(U)]),"skipped";S(!0),v(Tg()),l||L("");let j=!1,B=null,W=null,H=null,G=0;const V=createSubmitGoalSupervisor(e);let z=null;const K=resolvePremiumCreditsPreflight({premiumCreditsExhausted:x,currentModel:P});if(K.blocked)return j=!0,v(K.status),h(e=>[...e,lg(K.message)]),S(!1),O.current=!1,K.outcome;try{z=await V.getGoalTurnBudget();const e=await NO({sessionId:R,baseUrl:getApiBaseUrl()});if(m&&!isCommandGoalLoopArmed(R))return"skipped";const t=clipboardImagesToUserContent(r),n=s?`${s}\n\n${F}`:F,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}:{}}:{},...a?{ideHint:a}:{}};trackFirstMessage();const u=await runHarnessTurnIntoFeed({harness:e,input:F,turnUserInput:l,runQuery:runHarnessQuery,setFeed:h,setLiveEntries:f,displayMessage:i,suppressUserEcho:p,additionalContent:hiddenMessagesToUserContent(d),inputMeta:$.inputMeta,maxTurns:z?.remainingTurns,onRoundTrip:__name(e=>{G=e},"onRoundTrip"),echoMetadata:Object.keys(c).length>0?c:void 0,setStatus:v,onInteractionTokens:k,onRunError:__name(e=>{W=e},"onRunError"),routeEntry:createBlockCommittingRouter({setFeed:h,setLiveEntries:f}),scrubGoalCompleteMarker:isCommandGoalLoopArmed(R)});if(W){const e=P?byokProviderId({model:P}):void 0;throw formatRunError(W,e?{byokProvider:e}:void 0)}return H=u.finalText,G=u.turnCount,"completed"}catch(e){const t=resolveSubmitErrorAction({error:e,sessionId:R});if("interrupted"===t.kind)return j=!0,t.outcome;if(trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"submit_error"}),context:{component:xo.SUBMIT,heading:"Prompt submission failed",code:t.kind}}),j=!0,B=t.goalErrorKind,"insufficient-credits"===t.kind){v(t.status);const e=await getBillingLink({billingLink:E,setBillingLink:T});return h(t=>[...t,gg(buildInsufficientCreditsSubmitActionMessage({billingUrl:e}))]),t.outcome}if("premium-credits-exhausted"===t.kind)return I?.(!0),A?.(t.fallbackModelId),cA(),D(e=>e+1),v(t.status),h(e=>[...e,lg(t.message)]),t.outcome;v(t.status);const n="info"===t.renderKind?lg(t.message):gg(t.message);return h(e=>[...e,n]),t.outcome}finally{S(!1),j||v("Ready..."),O.current=!1,await V.afterTurn({assistantText:j?null:H,errorKind:j?B:null,isGoalContinuation:u,turnsUsed:G,goalStartedAt:z?.startedAt})}return"skipped"}function emitGoalNotice(e,t){e(e=>[...e,lg(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=>($O(t)??await NO({sessionId:t,baseUrl:getApiBaseUrl()})).verifyGoal(e),"verifyCompletion"),getEvidence:__name(()=>{const e=$O(t);return e?harnessRecentToolEvidence(e):""},"getEvidence"),emitCompletion:__name(e=>{n(t=>[...t,lg("",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,gg(Sk)]);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:a}=o.command;if("completed"===s&&a&&isDesignMode(a)){const t=getDesignModeSuggestions(a);t&&e.setPendingDesignSuggestion?.(t)}}catch(t){e.setFeed(e=>[...e,gg(buildDesignSkillLoadErrorMessage(t))])}}__name(findLastAssistantText,"findLastAssistantText"),__name(handleCopy,"handleCopy"),Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),__name(getAuthKey3,"getAuthKey"),__name(trackFirstMessage,"trackFirstMessage"),Ht(),Qx(),__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"),Ht(),Qx();var l_="Nothing to export yet — the transcript is created on the first message.",c_=new Set(["html","jsonl","md"]);function matchFormatKeyword(e){const t=e.toLowerCase();return c_.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=i(t)?t:s(e.cwd,t);if(I(o)&&N(o).isDirectory())return{kind:"target",format:"html",path:n(o,defaultExportFilename(e.sessionId,"html"))};const a=d(o).toLowerCase();return a?".html"===a?{kind:"target",format:"html",path:o}:".jsonl"===a?{kind:"target",format:"jsonl",path:o}:".md"===a?{kind:"target",format:"md",path:o}:{kind:"unknown-extension",extension:a}:{kind:"target",format:"html",path:n(o,defaultExportFilename(e.sessionId,"html"))}}function exportedMessage(e){const t=toRelativePath(e.path),n=It.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(I(t)){try{F(t,e.target)}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,lg(`Export failed: ${n}`)])}e.setFeed(t=>[...t,lg(exportedMessage({path:e.target,formatLabel:"JSONL"}))])}else e.setFeed(e=>[...e,lg(l_)])}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,lg(`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,lg(`Export failed: ${n}`)])}e.setFeed(t=>[...t,lg(exportedMessage({path:e.target,formatLabel:"HTML"}))])}else e.setFeed(e=>[...e,lg(l_)])}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,lg(`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,lg(`Export failed: ${n}`)])}e.setFeed(t=>[...t,lg(exportedMessage({path:e.target,formatLabel:"Markdown"}))])}else e.setFeed(e=>[...e,lg(l_)])}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,lg(`Unknown export extension "${r.extension}". Supported export formats: .html, .jsonl, .md`)])}async function handleForkCommand(e,t){const n=$O(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,cg({name:r.title})])}catch{e.setFeed(e=>[...e,gg(Sh)])}else e.setFeed(e=>[...e,"error"===r.notice.kind?gg(r.notice.message):lg(r.notice.message)])}function setMode(e,t){e.permissionModeRef.current=t,e.setPermissionMode(t),$O(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,lg(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"),Ht(),Qx(),__name(handleForkCommand,"handleForkCommand"),Ht(),Qx(),__name(setMode,"setMode"),__name(handlePlanCommand,"handlePlanCommand"),Ht(),Qx();var d_=[{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"},{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 d_){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,pg(buildHotkeysMarkdown())])}async function handleImportCommand({setFeed:e},t=""){const n=resolveAgentImportSourceArg(t);if(!n.ok)return void e(e=>[...e,gg(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,lg("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,lg(formatAgentImportSummary(o))])}catch(t){e(e=>[...e,gg(`Import failed: ${t instanceof Error?t.message:"unknown error"}`)])}}function setMode2(e,t){e.permissionModeRef.current=t,e.setPermissionMode(t),$O(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,lg(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?gg(t.notice.message):lg(t.notice.message)]),"renamed"===t.kind){e.setRenamedTerminalTitle(t.name);try{(e.harness??await NO({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 NO({sessionId:e,baseUrl:getApiBaseUrl()}),o=await r.regenerateTitle();if(!o)return void t(e=>[...e,lg("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,lg("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=$O(e.sessionId)?.getSessionStats().name,n=t?null:await loadCommandSessionMeta({sessionId:e.sessionId}).catch(()=>null),r=t??n?.title;e.setFeed(e=>[...e,lg(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=$O(e),o=resolveRewindCommand({hasActiveConversation:Boolean(r),checkpointCount:r?.listCheckpoints().length??0});"notice"!==o.kind?n(!0):t(e=>[...e,"error"===o.notice.kind?gg(o.notice.message):lg(o.notice.message)])}async function handleRewindSelect({messageId:e,mode:t,sessionId:n,setFeed:r,setStatus:o,setShowRewindSelector:s,setStaticKey:a,setInput:i}){s(!1);const l=$O(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)}),cA(),a(e=>e+1),c.promptToRestore&&i(c.promptToRestore),r(e=>[...e,lg(c.notice.message)]),void o(c.statusMessage);r(e=>[...e,"error"===c.notice.kind?gg(c.notice.message):lg(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,lg("No active session.")]);const r=n(getProjectSessionDir({env:process.env,cwd:getCurrentWorkingDirectory()}),`${e}.jsonl`),o=formatSessionFileLine({absolutePath:r,exists:I(r),linksSupported:It.isSupported});t(t=>[...t,lg(`Session ID: ${e}\nCurrent session file: ${r}`,{isSessionFile:!0,sessionFileId:e,sessionFileLine:o})])}__name(buildHotkeysMarkdown,"buildHotkeysMarkdown"),__name(handleHotkeys,"handleHotkeys"),Ht(),Qx(),__name(handleImportCommand,"handleImportCommand"),Ht(),Qx(),__name(setMode2,"setMode"),__name(handleModeCommand,"handleModeCommand"),Ht(),Qx(),__name(applyRenameResult,"applyRenameResult"),__name(autoRenameSession,"autoRenameSession"),__name(handleRenameCommand,"handleRenameCommand"),__name(handleNameCommand,"handleNameCommand"),Ht(),Qx(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),Ht(),Qx(),__name(compactTranscriptPath,"compactTranscriptPath"),__name(formatSessionFileLine,"formatSessionFileLine"),__name(handleSessionFile,"handleSessionFile"),Ht(),Qx();var u_=Te(h),m_=/https:\/\/gist\.github\.com\/\S+/;function parseGistUrl(e){const t=m_.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 u_("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 I(r)?(F(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:a=writeClipboardText}=e.deps??{},i=__name(t=>e.setFeed(e=>[...e,lg(t)]),"info");if(!t("gh"))return void i("Requires the GitHub CLI (gh) — https://cli.github.com");const l=await resolveShareGistFormat(e.rawFormatArg);if(!l)return void i(`Unknown gist format "${(e.rawFormatArg??"").trim()}". Supported gist formats: html, jsonl, md`);let c;try{c=await ie(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 i("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 i(`gh gist create did not return a URL: ${d.trim()}`);await a(u),i(`Shared session gist: ${It.isSupported?createOSC8Link(u,u,!1):u}`)}catch(e){const t=execErrorText(e);i(/auth/i.test(t)?`${t} — run gh auth login`:`Share failed: ${t}`)}finally{c&&await ee(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()}),a=await createCommandSessionShareLink({client:s,sessionId:e,existingShareInfo:t,harness:e?$O(e):void 0,projectRoot:global.COMMAND_CODE_CWD||process.cwd()});"no-session"!==a.status&&"error"!==a.status?(n(a.shareInfo),await copyOrFallback(a.shareInfo.url,r)&&(r(""),o(!0),setTimeout(()=>{o(!1)},shareNotificationDurationMs(a.status)))):r(a.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()}),a=await deleteCommandSessionShareLink({client:s,sessionId:e,shareInfo:t,harness:e?$O(e):void 0});if("no-session"!==a.status){if("not-shared"===a.status)return o(a.message),void setTimeout(()=>o(""),Vv);if("error"===a.status)return r(a.message),void setTimeout(()=>r(""),Vv);o(a.message),r(""),n(null),setTimeout(()=>{o("")},Vv)}else r(a.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,lg(`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,lg(`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,lg(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=$O(e),a=resolveTreeCommand({hasActiveConversation:Boolean(s),treeEntryCount:s?.getSessionTree().length??0});if("notice"===a.kind)return void t(e=>[...e,"error"===a.notice.kind?gg(a.notice.message):lg(a.notice.message)]);const[i,l]=await Promise.all([getTreeFilterMode(),getBranchSummarySkipPrompt()]);r(i),o(l),n(!0)}async function handleTreeSelect({entryId:e,summarize:t,customInstructions:n,sessionId:r,setFeed:o,setShowTreeSelector:s,setStaticKey:a,setInput:i}){const l=$O(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,lg("Already at this point")]),{aborted:!1}):(s(!1),o(reconstructFeedFromMessages(harnessSessionMessages(l))),cA(),a(e=>e+1),r.editorText&&i(r.editorText),o(e=>[...e,lg("Navigated to selected point")]),{aborted:!1})}catch(e){return o(t=>[...t,gg(`Failed to navigate: ${actionErrorMessage(e)}`)]),{aborted:!1}}}function handleTreeCancel({setShowTreeSelector:e}){e(!1)}function handleTreeAbortSummary({sessionId:e}){$O(e)?.abortBranchSummary()}function handleTreeLabel({entryId:e,label:t,sessionId:n,setFeed:r}){const o=$O(n);if(o)try{o.setTreeLabel({targetId:e,label:t})}catch(e){r(t=>[...t,gg(`Failed to set label: ${actionErrorMessage(e)}`)])}}function announceCompletedUpdate({fromVersion:e,toVersion:t}){console.log(bt.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:xo.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"),Ht(),Qx(),__name(loadPersistedTraceIds,"loadPersistedTraceIds"),__name(handleTrace,"handleTrace"),Ht(),Qx(),__name(actionErrorMessage,"actionErrorMessage"),__name(handleTreeCommand,"handleTreeCommand"),__name(handleTreeSelect,"handleTreeSelect"),__name(handleTreeCancel,"handleTreeCancel"),__name(handleTreeAbortSummary,"handleTreeAbortSummary"),__name(handleTreeLabel,"handleTreeLabel"),Ht(),Qx(),Ht(),Qx(),__name(announceCompletedUpdate,"announceCompletedUpdate"),__name(trackUpdateFailure,"trackUpdateFailure");var p_={createLifecycleEventClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createLifecycleEventClient"),isTelemetryEnabled:isTelemetryEnabled,log:dlog,onCompletedUpdate:announceCompletedUpdate,trackUpdateFailure:trackUpdateFailure},g_={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"),a=await runTuiUpdateCommand({state:g_,host:p_,copy:{binCommand:`${getBinaryCommand()}`,updateCommand:"npm i -g command-code"},emit:s});trackTuiUpdateCommandTelemetry(a),"error"!==a.level?e(e=>[...e,lg(a.message,a.metadata)]):e(e=>[...e,gg(a.message)])}function tildeHome(e){const t=B.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function formatWorktreePathLine(e){return` ${gt.dim(pt.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,a=createWorktree({spec:"string"==typeof e?e.trim():void 0,cwd:o});if(!a.ok)return{ok:!1,error:a.error};try{process.chdir(a.target.worktreePath),global.COMMAND_CODE_CWD=a.target.worktreePath}catch(e){return{ok:!1,error:`couldn't enter worktree: ${e instanceof Error?e.message:String(e)}`}}if(r&&a.created&&markAutoCreatedWorktree({worktreePath:a.target.worktreePath,branch:a.target.branch,baseSha:a.baseSha,mainRoot:s}),!n){const e=a.created?"Created":"Entered",t=a.created?gt.dim(` (branch ${a.target.branch}${a.usedRemote?", from origin":""})`):"",n=a.created&&a.copiedFiles>0?gt.dim(` · copied ${a.copiedFiles} file(s)`):"",r=a.created&&a.copyFailedFiles.length>0?gt.dim(` · ${a.copyFailedFiles.length} include copy failure(s)`):"";process.stdout.write(`${gt.cyan(pt.squareSmallFilled)} ${e} worktree ${gt.bold(a.target.name)}${t}${n}${r}\n${formatWorktreePathLine(a.target.worktreePath)}\n`)}return dlog(`[worktree] entered ${a.target.worktreePath} (created=${a.created})`),{ok:!0,name:a.target.name,path:a.target.worktreePath}}__name(handleUpdateCommand,"handleUpdateCommand"),Ht(),Qx(),Ht(),Qx(),__name(tildeHome,"tildeHome"),__name(formatWorktreePathLine,"formatWorktreePathLine"),__name(enterWorktreeFromFlag,"enterWorktreeFromFlag");var h_=__name((e,t)=>e.setFeed(e=>[...e,lg(t)]),"info"),f_=__name((e,t)=>e.setFeed(e=>[...e,gg(t)]),"error");function renderList(e,n){const r=listWorktrees(e);return 0===r.length?"No worktrees found.":["Worktrees:",...r.map(r=>{const o=samePath(r.path,e)?"●":"○",s=t.relative(n,r.path),a=r.isMain?".":s&&!s.startsWith("..")?s:tildeHome(r.path);return` ${o} ${r.isMain?`${a} (main)`:a}${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 f_(e,"/worktree requires a git repository.");const r=getMainWorktreeRoot(n)??n,o=t[0]?.toLowerCase();if(!o||"list"===o||"ls"===o)return void h_(e,renderList(n,r));if("remove"===o||"rm"===o){const o=t[1];return o?void await handleRemove(e,o,n,r):void f_(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(samePath(s.worktreePath,r))return void f_(e,"Can't remove the worktree you're in. Switch away first, then remove it.");if(!listWorktrees(r).some(e=>samePath(e.path,s.worktreePath)))return void f_(e,`No worktree named "${n}".`);const a=removeWorktree({worktreePath:s.worktreePath,cwd:r,deleteBranch:isManagedWorktreePath(s.worktreePath,o)?s.branch:void 0});a.ok?h_(e,`Removed worktree "${n}".`):f_(e,`Couldn't remove "${n}": ${a.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 f_(e,`Couldn't create worktree: ${r.error}`);if(samePath(r.target.worktreePath,n))return void h_(e,`Already in worktree "${r.target.name}".`);const o=r.created?"Created":"Reusing",s=r.created&&r.copiedFiles>0?` (copied ${r.copiedFiles} file(s))`:"",a=r.created&&r.copyFailedFiles.length>0?` (${r.copyFailedFiles.length} include copy failure(s))`:"";h_(e,`${o} worktree "${r.target.name}"${s}${a}. Switching… (a fresh session starts in the worktree; this one stays resumable).`),await($O(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,pg(Ng)])}async function handleTerminalSetupCommand({setFeed:e}){const t=ig("/terminal-setup"),n=setupVSCodeTerminal(),r=fg(n.message,!n.success,n.details),o=fg("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);e(e=>[...e,t,r,o])}async function handleIDESetupCommand({setFeed:e}){const t=await runIdeSetup({host:n_,moduleUrl:import.meta.url}),n=yg(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:a,setContextUsage:i,setInteractionTokens:l,sessionId:c,setSessionId:d,clearSessionPermissions:u}){e([]),t([]),n([]),clearSessionTodos(),clearShellTasks(),cA(),r(null),o(!1),s(""),await deleteCommandSessionShareInfo({sessionId:c}).catch(()=>{});const m=$O(c);m?.stopBackgroundLearning(),await(m?.flush().catch(()=>{})),_O(c),setNextSessionStartSource("clear"),d(crypto.randomUUID()),u(),a(e=>e+1),i(null),l(0)}async function handleInitCommand({setFeed:e}){const t=await resolveInitMemoryCommand({projectRoot:process.cwd()});e(e=>[...e,lg(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,lg(s.notice.message,s.notice.metadata)]),o&&"notice"===s.status&&"cleared"===s.notice.metadata?.goalNoticeKind&&$O(e.sessionId)?.requestStopAfterTurn(),"start"===s.status&&await runGoalTurn(e,s.goalText,n,r)}async function openExternalSlashCommandTarget({setFeed:e,target:t}){e(e=>[...e,lg(`Opening ${createOSC8Link(t.url,t.noticeLabel,!1)} in your browser…`)]);try{await Tt(t.url,{wait:!1,background:!0})}catch{const{fallback:n}=t;if("info"===n.kind)return void e(e=>[...e,lg(n.message)]);e(e=>[...e,gg("Failed to open browser"),pg(createOSC8Link(t.url,n.label,!1))])}}function handleLearnCommand({setAutoLearnTaste:e,setShowTasteOnboarding:t,setTasteOnboardingEntryId:n,setFeed:r}){e(!0),t(!0);const o=hg();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,lg(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,lg("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,gg(`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:a,positionalArgs:i}=o;if("/exit"===s||"/quit"===s)return discardPendingReload(),t.setShouldExit(!0),{status:"handled"};if("/reload"===s)return await($O(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=a.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:a,positionalArgs:i,command:e}),{status:"handled"};if("/skills"===s)return t.setShowSkillsConfig(!0),{status:"handled"};if("/plans"===s)return t.setPlansTarget(a.trim()||null),t.setShowPlansView(!0),{status:"handled"};if("/plan-review"===s)return t.setPlansTarget(_$),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,a),{status:"handled"};if("/effort"===s)return await handleEffortCommand(t,a),{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,a.trim()||void 0),{status:"handled"};if("/worktree"===s)return await handleWorktreeCommand(t,i),{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,a),{status:"handled"};if("/goal"===s)return await handleGoalCommand(t,a,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:a,setFeed:t.setFeed,setShowLoginOverlay:t.setShowLoginOverlay,setAuthComponentInfo:t.setAuthComponentInfo}),t.setInput(""),{status:"handled"};if("/logout"===s)return await handleLogoutCommand({provider:a,setFeed:t.setFeed,setRetryAttempt:t.setRetryAttempt,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),t.setInput(""),{status:"handled"};if("/courses"===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:a});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:a,currentModel:t.currentModel,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/changelog"===s)return handleChangelog({setFeed:t.setFeed,rawArguments:a}),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,lg("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:a.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:a.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,a),{status:"handled"};if("/plan"===s)return await handlePlanCommand({rawArguments:a,ctx:t}),{status:"handled"};if("/mode"===s||s.startsWith("/mode:")){const e=s.startsWith("/mode:")?s.slice(6):a;return await handleModeCommand({rawArguments:e,ctx:t}),{status:"handled"}}if("/review"===s){const e=await resolveReviewSlashCommand({rawArguments:a});return"missing-gh"===e.status?(t.setFeed(t=>[...t,lg(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=$O(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:a}),n=e?.message;n&&t.setFeed(e=>[...e,lg(n)]),e?.prompt&&await submitAutomatedSlashTurn({turn:buildAutomatedSlashTurn({commandName:c,rawArguments:a,fullPrompt:e.prompt}),ctx:t})}catch(e){t.setFeed(t=>[...t,gg(`Mod command /${c} failed: ${e instanceof Error?e.message:String(e)}`)])}return{status:"handled"}}const d=await resolveCustomSlashTurn({runtime:createNodeRuntime(),commandName:s,rawArguments:a,positionalArgs:i});if(d)return await submitAutomatedSlashTurn({turn:d,ctx:t}),{status:"handled"};return await handleSkillCommand({commandName:s,command:e,rawArguments:a,positionalArgs:i,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,lg(s.message)]),{status:"handled"}):"load-error"===s.status?(o.setFeed(e=>[...e,gg(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:a,permissionState:i,terminalTitleState:l,isSubmittingRef:c,executeBash:d,setInput:u}){const m=ct(()=>({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:i.setPermissionMode,permissionModeRef:i.permissionModeRef,clearSessionPermissions:i.clearSessionPermissions,setShouldExit:a.setShouldExit,setInput:u,isSubmittingRef:c,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,executeBash:d,setRenamedTerminalTitle:l.setRenamedTerminalTitle}),[e,t,n,r,o,s,a,i,l,c,d,u]),p=it(m);return p.current=m,{commandCtx:m,onCommand:dt((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"),Ht(),Qx();var y_=Ko,S_=qo;function useCreditWarning({interactionTokens:e,currentModel:t}){const[n,r]=at(null),o=it(null),s=it(null),a=it(null),i=dt(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),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{r(null),a.current=null},y_)}catch{}},[]);return lt(()=>{if(0!==e&&!isLocalOnly()&&!isByok({model:t}))return s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{i(),s.current=null},S_),()=>{s.current&&clearTimeout(s.current)}},[e,t,i]),lt(()=>()=>{a.current&&clearTimeout(a.current),s.current&&clearTimeout(s.current)},[]),{creditWarning:n}}function useCronWakeup({onSubmit:e}){const t=it(e);lt(()=>{t.current=e},[e]),lt(()=>{const e=subscribeCronFire(e=>{t.current(buildCronWakeupSubmission(e))});return()=>{e()}},[])}function useExit(){const[e,t]=at(!1),[n,r]=at(null),o=it(null),s=it(0),a=it(null),i=dt(()=>{o.current=null,r(null),a.current&&(clearTimeout(a.current),a.current=null)},[]);return{shouldExit:e,setShouldExit:t,pendingExitKey:n,setPendingExitKey:r,pendingExitKeyRef:o,lastExitKeyTimeRef:s,exitConfirmationTimeoutRef:a,resetPendingExitKey:i}}__name(useCreditWarning,"useCreditWarning"),Ht(),Qx(),__name(useCronWakeup,"useCronWakeup"),Ht(),__name(useExit,"useExit"),Ht(),Qx(),Ht(),Qx();var w_="1"===process.env.CMD_TEST_INJECT_LIVE_ENTRY;function makeInjectedShellEntry(e,t,n,r={}){return{...ug("shell_command",t,{status:n}),id:e,...r}}function buildInjectedLiveEntry(){return w_?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 v_="1"===process.env.CMD_TEST_INJECT_STREAM,k_="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?Sg(t,{id:k_,status:"running"}):"tool"===e?{...ug("shell_command",t,{status:"running"}),id:k_}:"agent"===e?{...wg({name:"Task",input:t}),id:k_}:{...dg(t),id:k_,metadata:{status:"running"}}}function makeStreamFinalEntry(e,t){return"reasoning"===e?Sg(t,{id:k_}):"tool"===e||"agent"===e?{...ug("shell_command",t,{}),id:k_,output:"done"}:{...dg(t),id:k_}}function maybeStartInjectedStream(e){if(!v_)return;const{setFeed:t,setLiveEntries:n,setIsCmdCodeBusy:r}=e,o=streamRole(),s=buildStreamFrames(buildStreamContent(streamContentKind())),a=streamTickMs();r(!0);const i=createBlockCommittingRouter({setFeed:t,setLiveEntries:n});i(makeStreamRunningEntry(o,s[0]??""));let l=0;const c=setInterval(()=>{if(l+=1,l<s.length)return void i(makeStreamRunningEntry(o,s[l]??""));clearInterval(c);const e=s[s.length-1]??"";i(makeStreamFinalEntry(o,e)),r(!1)},a);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 C_="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 b_=(()=>{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(!C_)return;const t=createBlockCommittingRouter({setFeed:e.setFeed,setLiveEntries:e.setLiveEntries});let n=0;const r=setInterval(()=>{const e=b_[n];e?(t({...ug("todo_write",Ag("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 E_=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(E_)||E_<=0)return;const{setFeed:t}=e;let n=0;const r=setInterval(()=>{const e=n===E_-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=dt(e=>{t(t=>applyFeedRetention("function"==typeof e?e(t):e))},[]);lt(()=>{trimStaticBuffer()},[e]);const[r,o]=at(()=>{const e=buildInjectedLiveEntry();return e?[e]:[]}),[s,a]=at([]),[i,l]=at(w_),c=it([]),d=dt(e=>{const t="function"==typeof e?e(c.current):e;c.current=t,a(t)},[]);return lt(()=>maybeStartInjectedTurns({setFeed:n}),[n]),lt(()=>maybeStartInjectedStream({setFeed:n,setLiveEntries:o,setIsCmdCodeBusy:l}),[]),lt(()=>maybeStartInjectedTodos({setFeed:n,setLiveEntries:o}),[]),{feed:e,setFeed:n,liveEntries:r,setLiveEntries:o,queuedMessages:s,setQueuedMessages:d,isCmdCodeBusy:i,setIsCmdCodeBusy:l,queuedMessagesRef:c}}function useKeyboard({showTasteConfig:e,showSkillsConfig:t,showSettingsConfig:n,showProviderSelector:r,showModelSelector:o,showEffortSelector:s,showMemorySelector:a,showMcpManager:i,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:O,setRetryAttempt:L,setStatus:D,pendingExitKey:N,setPendingExitKey:$,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(()=>{interruptActiveTurn(),clearCommandGoalIfActive(z);const e=P.length>0;if(O(!1),L(null),R([]),D(jf),!e){const e=J(Uf);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");tt((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(N&&j());if(e||t||n||r||o||s||a||i||g||l||c||d||u||m||p)return void(N&&j());if(""===P||M.ctrl&&"c"===P){if(T)return void Q();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",$("ctrl-c"),U.current&&clearTimeout(U.current),void(U.current=setTimeout(()=>{_.current=null,$(null),U.current=null},2e3)))}if(keybindingMatches(I,"app.tools.expand",P,M)){if(H?.params.planContent)return;return cA(),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 cA(),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 cA(),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&&Q()}})}function useHandlers({resume:e,feedState:t,onboarding:n,uiOverlays:r,exitState:o,pendingOps:s,permissionState:a,statusState:i,authState:l,sessionId:c,loadTasteStatus:d,loadCurrentProvider:u,setInput:m}){const p=dt(()=>{a.setPermissionMode(e=>{const t=cyclePermissionMode({current:e,dangerouslySkipPermissions:a.dangerouslySkipPermissions}),n=resolvePendingPromptOnModeChange(t,{pendingIsRisky:void 0!==s.pendingPermission?.params?.risk});return n&&s.pendingPermission&&("approve"===n&&a.respondToPrompt(GE),s.pendingPermission.resolve("approve"===n),s.setPendingPermission(null)),$O(c)?.setPermissionMode({mode:t}),t})},[a.setPermissionMode,a.respondToPrompt,a.dangerouslySkipPermissions,s.pendingPermission,s.setPendingPermission,c]),g=dt(()=>{a.setPermissionMode(e=>{const t="bypass"===e?e:"auto-accept";return $O(c)?.setPermissionMode({mode:t}),t})},[a.setPermissionMode,c]),h=dt(()=>{const e=!t.isCmdCodeBusy&&!s.pendingPermission&&!s.pendingQuestion,n=($O(c)?.listCheckpoints().length??0)>0;e&&n&&r.setShowRewindSelector(!0)},[t.isCmdCodeBusy,s.pendingPermission,s.pendingQuestion,r.setShowRewindSelector,c]),f=dt(t=>{n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),t?.skipped&&r.setShowTasteSkipBanner(!0),e&&r.setShowSessionSelector(!0)},[e,n,r]),y=dt(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=dt(()=>{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:i.setRetryAttempt,setStatus:i.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:a.respondToPrompt,createErrorEntry:gg}),{handleToggleAutoAccept:p,handleEnableAutoAccept:g,handleDoubleEscapeEmpty:h,handleTasteOnboardingComplete:f,handleTrust:y,handleNoTrust:S}}__name(testTurnChars,"testTurnChars"),__name(testTurnTickMs,"testTurnTickMs"),__name(makeInjectedTurnEntry,"makeInjectedTurnEntry"),__name(maybeStartInjectedTurns,"maybeStartInjectedTurns"),__name(useFeed,"useFeed"),Ht(),Qx(),Ht(),Qx(),__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Ht(),Qx(),Ht(),Qx();var T_,P_=[],M_=[];function setModPathsOverride(e){P_=e}function setModOptionsOverride(e){M_=e}function loadCommandModHost(e={}){return T_||(T_=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:P_,builtins:commandBuiltinMods()});for(const e of M_){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 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(setModPathsOverride,"setModPathsOverride"),__name(setModOptionsOverride,"setModOptionsOverride"),__name(loadCommandModHost,"loadCommandModHost"),__name(buildHost,"buildHost"),Ht(),__name(resolveExternalModelChange,"resolveExternalModelChange"),Ht(),__name(raceAnswerAgainstAbort,"raceAnswerAgainstAbort"),Ht();var x_={},I_={};function setStartupSessionOptions(e){x_=void 0===e.persist?{}:{persist:e.persist},I_={...e.sessionFilePath?{sessionFilePath:e.sessionFilePath}:{},...e.name?{name:e.name}:{}}}function getStickyStartupSessionOptions(){return x_}function consumeStartupSessionOverrides(){const e=I_;return I_={},e}function buildInteraction({permissionsService:e,permissionModeRef:t,setPendingQuestion:n,setStatus:r}){return{confirmTool:__name(async({toolName:n,input:r,description:o,risk:s,explain:a,signal:i})=>{if(!e)return"allow";if(i?.aborted)return"deny";const l=__name(e=>raceAnswerAgainstAbort(e.then(e=>e.allowed?"allow":"deny"),i),"withInterrupt"),c=buildToolPermissionRequest({toolName:n,input:r,description:o,...void 0!==s?{risk:s}:{},...void 0!==a?{explain:a}:{}});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:a,setPermissionMode:i,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=it(f);v.current=f;const k=it(null),C=it(!1),b=it(w);b.current=w;const E=dt(()=>{hardResetForResize(),S?.(e=>e+1)},[S]),T=dt(e=>{v.current=e,y?.(e),E()},[E,y]);lt(()=>{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=it(null),R=__name(()=>{A.current?.(),A.current=null},"releaseRebuildBarrier");lt(()=>onHarnessSessionRebuild(t=>{if(t===e)return new Promise(e=>{A.current?.(),A.current=e,I(e=>e+1)})}),[e]);const O=it(a.current),L=it(null);return lt(()=>{if(!o||n)return void R();const t=__name(()=>Boolean(l)||a.current!==O.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=ig(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}]}:{input:t}}))},"drainQueuedMessages"),P=await loadCommandModHost(),x=await NO({sessionId:e,baseUrl:getApiBaseUrl(),...t()?{permissionMode:a.current}:{},dangerouslySkipPermissions:c,drainQueuedMessages:w,peekQueuedMessageCount:__name(()=>p?.current?.length??0,"peekQueuedMessageCount"),interaction:buildInteraction({permissionsService:s,permissionModeRef:a,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()!==a.current&&(t()?x.setPermissionMode({mode:a.current}):(a.current=x.getPermissionMode(),i?.(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,lg(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 a.current=e.mode,void i?.(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("notice"!==e.type||!m)return;const t=tasteNoticeToFeedEntry(e);t&&m(e=>[...e,t])}),M(!0),L.current!==e&&(L.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,lg(n.join("\n"))])}).catch(()=>{}))})(),()=>{S=!0,f?.(),y?.()}},[e,t,n,o,s,a,i,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:a,skipOnboarding:i,sessionId:l,sessionTitleHolder:c}){lt(()=>{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(),FO()])}catch{}try{e()}catch{process.exit(0)}})())},[n.shouldExit,e]),lt(()=>()=>{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)},[]),lt(()=>{(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]),lt(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(Tg())},Dg);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),lt(()=>{i||triggerTasteOnboarding({projectTrusted:s.projectTrusted,onboardingComplete:s.onboardingComplete,isOnboardingMode:s.showTasteOnboarding,tasteOnboardingCheckedRef:s.tasteOnboardingCheckedRef,setIsOnboardingMode:s.setShowTasteOnboarding})},[s.projectTrusted,s.onboardingComplete,s.showTasteOnboarding,i]),lt(()=>{if(s.showTasteOnboarding&&!s.tasteOnboardingEntryId){const e=hg();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(ko),t(!1)}}function handleCompactModeCancel({setShowCompactModeSelector:e}){e(!1)}__name(setStartupSessionOptions,"setStartupSessionOptions"),__name(getStickyStartupSessionOptions,"getStickyStartupSessionOptions"),__name(consumeStartupSessionOverrides,"consumeStartupSessionOverrides"),__name(buildInteraction,"buildInteraction"),__name(useHarness,"useHarness"),Ht(),Qx(),__name(useLifecycle,"useLifecycle"),Ht(),Qx(),Ht(),Qx(),__name(handleCompactModeSelect,"handleCompactModeSelect"),__name(handleCompactModeCancel,"handleCompactModeCancel");var A_=__name(e=>{},"noopBool");function useMainActionCallbacks({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,setInput:s}){const a=it({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,setInput:s});a.current={feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,setInput:s};const i=dt(e=>{const{feedState:t,sessionState:n,statusState:r,uiOverlays:o,authState:s}=a.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=dt(({messageId:e,mode:t})=>{const{feedState:n,sessionState:r,statusState:o,uiOverlays:s,setInput:i}=a.current;handleRewindSelect({messageId:e,mode:t,sessionId:r.sessionId,setFeed:n.setFeed,setStatus:o.setStatus,setShowRewindSelector:s.setShowRewindSelector,setStaticKey:s.setStaticKey,setInput:i})},[]),c=dt(()=>{handleRewindCancel({setShowRewindSelector:a.current.uiOverlays.setShowRewindSelector})},[]),d=dt(e=>{const{feedState:t,sessionState:n,uiOverlays:r,setInput:o}=a.current;return handleTreeSelect({...e,sessionId:n.sessionId,setFeed:t.setFeed,setShowTreeSelector:r.setShowTreeSelector,setStaticKey:r.setStaticKey,setInput:o})},[]),u=dt(()=>{handleTreeCancel({setShowTreeSelector:a.current.uiOverlays.setShowTreeSelector})},[]),m=dt(e=>{const{feedState:t,sessionState:n}=a.current;handleTreeLabel({...e,sessionId:n.sessionId,setFeed:t.setFeed})},[]),p=dt(()=>{handleTreeAbortSummary({sessionId:a.current.sessionState.sessionId})},[]),g=dt((e,t)=>{const{feedState:n,statusState:r,uiOverlays:o}=a.current;handleLoginComplete({success:e,message:t,setShowLoginOverlay:o.setShowLoginOverlay,setFeed:n.setFeed,setStatus:r.setStatus})},[]),h=dt(()=>{const{feedState:e,statusState:t,uiOverlays:n}=a.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),f=__name(e=>{const t=a.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=dt(e=>{const{authState:t,sessionState:n,statusState:r,uiOverlays:o}=a.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=a.current.sessionState.sessionId;t&&await saveCommandSessionMeta({sessionId:t,meta:{model:e}}),a.current.authState.setCurrentModel(e),a.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=a.current.authState.currentProvider??await getConfiguredProvider()??ro.COMMAND;return e===ro.COMMAND?cr:defaultModelForLane({activeLane:e})??cr},"resolveOrphanFallback"),w=dt(()=>{handleProviderCancel({setShowProviderSelector:a.current.uiOverlays.setShowProviderSelector})},[]),v=dt((e,t)=>{const{authState:n,sessionState:r,statusState:o,uiOverlays:s,feedState:i}=a.current;handleModelSelect({modelId:e,provider:t,setCurrentModel:n.setCurrentModel,setShowModelSelector:s.setShowModelSelector,setStatus:o.setStatus,modelNotificationTimer:n.modelNotificationTimer,setShowModelNotification:A_,setCurrentProvider:n.setCurrentProvider,setStaticKey:s.setStaticKey,sessionId:r.sessionId,setFeed:i.setFeed,setContextUsage:o.setContextUsage,setModelNotice:s.setModelNotice})},[]),k=dt(()=>{handleModelCancel({setShowModelSelector:a.current.uiOverlays.setShowModelSelector})},[]),C=dt(e=>{const{statusState:t,uiOverlays:n}=a.current;handleCompactModeSelect({mode:e,setShowCompactModeSelector:n.setShowCompactModeSelector,setStatus:t.setStatus})},[]),b=dt(()=>{handleCompactModeCancel({setShowCompactModeSelector:a.current.uiOverlays.setShowCompactModeSelector})},[]),E=dt(e=>{const{statusState:t,uiOverlays:n}=a.current;handleThemeSelect({theme:e,setShowThemeSelector:n.setShowThemeSelector,setStatus:t.setStatus,setStaticKey:n.setStaticKey})},[]),T=dt(()=>{handleThemeCancel({setShowThemeSelector:a.current.uiOverlays.setShowThemeSelector})},[]),P=dt(()=>{const{authState:e,sessionState:t,statusState:n,uiOverlays:r}=a.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=dt(()=>{handleAuthCancel({setAuthComponentInfo:a.current.authState.setAuthComponentInfo})},[]);return{onSelectSession:i,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=it(e);lt(()=>{t.current=e},[e]),lt(()=>{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),[a,i]=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:a,setShowTasteOnboarding:i,onboardingComplete:l,setOnboardingComplete:c,tasteOnboardingEntryId:d,setTasteOnboardingEntryId:u,autoLearnTaste:m,setAutoLearnTaste:p,tasteOnboardingCheckedRef:it(!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"),Ht(),Qx(),__name(useMonitorOutputWakeup,"useMonitorOutputWakeup"),Ht(),__name(useOnboarding,"useOnboarding"),Ht(),__name(usePendingOps,"usePendingOps"),Ht(),Qx(),Ht(),Qx(),__name(resolvePermissionSettingsPath,"resolvePermissionSettingsPath");var R_=__name((e={})=>{const{projectRoot:t,local:n=!1,onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:a}=e,i=t||process.cwd(),l=it({onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:a}),[c,d]=at(null),u=it(null),[m,p]=at(null),[g,h]=at(!1);return lt(()=>{l.current={onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:a}},[r,o,s,a]),lt(()=>{const e=resolvePermissionSettingsPath({projectRoot:i,local:n}),t=createPermissionsService(i,{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,i]),{requestPermission:dt(async e=>{if(!c)return{allowed:!0};const t=await c.requestPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),requestShellPermission:dt(async e=>{if(!c)return{allowed:!0};const t=await c.requestShellPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),requestGenericPermission:dt(async e=>{if(!c)return{allowed:!0};const t=await c.requestGenericPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),respondToPrompt:dt(e=>{u.current?.respond(e)&&(p(null),h(!1))},[]),clearSessionPermissions:dt(()=>{c?.clearSessionPermissions()},[c]),clearProjectPermissions:dt(()=>{c?.clearProjectPermissions()},[c]),setAutoApprove:dt((e,t)=>{c?.setAutoApprove(e,t)},[c]),setEnabled:dt(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,a]=at(()=>e||(n?"bypass":"default")),i=it(s);lt(()=>{i.current=s},[s]);const{requestShellPermission:l,service:c,respondToPrompt:d,clearSessionPermissions:u,setEnabled:m}=R_({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 lt(()=>{c&&applyAutoAcceptMode({enabled:s,service:c})},[s,c]),{permissionMode:s,setPermissionMode:a,permissionModeRef:i,permissionsService:c,respondToPrompt:d,clearSessionPermissions:u,dangerouslySkipPermissions:n}}function useQueuedMessageFlush({isCmdCodeBusy:e,queuedMessages:t,queuedMessagesRef:n,setQueuedMessages:r,isSubmittingRef:o,onSubmit:s}){const a=it(s);lt(()=>{a.current=s},[s]);const i=t.length>0;lt(()=>{if(!i||e)return;const t=setInterval(()=>{if(o.current)return;const e=n.current[0];e&&(r(e=>e.slice(1)),a.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.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)},[i,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:it(null)}}__name(usePermissionMode,"usePermissionMode"),Ht(),__name(useQueuedMessageFlush,"useQueuedMessageFlush"),Ht(),__name(useSession,"useSession"),Ht(),Qx(),Ht(),Qx();var O_=createOSC8Link("https://commandcode.ai/docs/hooks","Docs ↗",!1);function buildHookStartupEntries(e){const t=buildHookStartupMessages(e).map(e=>({...e}));if(0===t.length)return[];const n=t[t.length-1];return n.message=`${n.message} ${O_}`,t.map(e=>e.isHookWarning?lg(e.message,{isHookWarning:!0}):lg(e.message))}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:a,sessionState:i,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=dt(async()=>{try{const e=await isTasteLearningEnabled();l.setTasteLearningOn(e),e&&await initTasteDir({runtime:createNodeRuntime()})}catch{}},[l.setTasteLearningOn]),k=dt(async()=>{const e=await getConfiguredProvider();c.setCurrentProvider(e)},[c.setCurrentProvider]),C=dt(()=>{},[]),b=dt(e=>{handleSelectSession({selectedSessionId:e,sessionLoadIdRef:i.sessionLoadIdRef,setFeed:a.setFeed,setLiveEntries:a.setLiveEntries,setSessionId:i.setSessionId,setShowSessionSelector:u.setShowSessionSelector,setSessionLoaded:i.setSessionLoaded,setStaticKey:u.setStaticKey,setShareInfo:l.setShareInfo,setCurrentModel:c.setCurrentModel})},[i,a,u,l,c.setCurrentModel]),E=dt(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]);lt(()=>{(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=it(!1);lt(()=>{T.current||d.projectTrusted&&0!==getCommandZdrPausedFeatures().length&&(T.current=!0,u.setShowZdrNotice(!0))},[d.projectTrusted,u.setShowZdrNotice]);const P=it(null);lt(()=>{d.projectTrusted&&c.currentModel!==P.current&&(P.current=c.currentModel,u.setModelNotice(getModelNotice(c.currentModel)??null))},[d.projectTrusted,c.currentModel,u.setModelNotice]);const M=it(null);lt(()=>{if(!p||!d.projectTrusted)return;const e=i.sessionId;if(M.current===e)return;const t=$O(e);if(!t)return;M.current=e;const n=buildHookStartupEntries(t.hookSettingsWarnings);0!==n.length&&a.setFeed(e=>[...e,...n])},[p,d.projectTrusted,i.sessionId,a.setFeed]),lt(()=>{if(!d.projectTrusted)return;const e=createCommandHistoryManager();return f.current=e,e.init(),()=>{e.cleanup()}},[d.projectTrusted,f]),lt(()=>{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]),lt(()=>{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:a.feed,setFeed:a.setFeed,setLiveEntries:a.setLiveEntries,isCmdCodeBusy:a.isCmdCodeBusy,setIsCmdCodeBusy:a.setIsCmdCodeBusy,setQueuedMessages:a.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:i.sessionId,isSubmittingRef:g,setInput:S,setStaticKey:u.setStaticKey,executeBash:y})},"submitAsUserMessage")}))},[o,d.projectTrusted,d.checkingProject,u.showSessionSelector,p,i.sessionId,c.currentProvider,w]);const x=it(null);x.current={feed:a.feed,setFeed:a.setFeed,setLiveEntries:a.setLiveEntries,isCmdCodeBusy:a.isCmdCodeBusy,setIsCmdCodeBusy:a.setIsCmdCodeBusy,setQueuedMessages:a.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:i.sessionId,isSubmittingRef:g,setInput:S,setStaticKey:u.setStaticKey,executeBash:y,role:"",input:""};const I=dt(async({role:e,input:t,images:n,imageTokenPaths:r,ideContext:o,ideHint:s,displayMessage:a,isAutomated:i,isMeta:l,hiddenMessages:c})=>{u.setShowTasteSkipBanner(!1),u.setShowZdrNotice(!1),u.setModelNotice(null),await handleSubmit({...x.current,role:e,input:t,images:n,imageTokenPaths:r,ideContext:o,ideHint:s,displayMessage:a,isAutomated:i,isMeta:l,hiddenMessages:c})},[u.setShowTasteSkipBanner,u.setShowZdrNotice,u.setModelNotice]);return{loadTasteStatus:v,loadCurrentProvider:k,initializeMcpInBackground:C,onSubmit:I}}function useStatus(e){const[t,n]=at("Ready..."),r=it(!1),[o,s]=at(""),a=it(null),[i,l]=at(null),c=it(i),[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);lt(()=>{c.current=i},[i]),lt(()=>{if(!E)return;const e=setTimeout(()=>{T(null)},3e4);return()=>clearTimeout(e)},[E]);const P=__name(e=>{a.current&&clearTimeout(a.current),s(e),a.current=setTimeout(()=>{s(""),a.current=null},5e3)},"showHintMessage");return{status:t,setStatus:n,pinnedStatusRef:r,hintMessage:o,setHintMessage:s,hintTimerRef:a,shareInfo:i,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}){const n=it(process.cwd()),r=it(e),o=it(null),s=dt(e=>{o.current=e,setTerminalTitle(formatSessionTabTitle({sessionTitle:e,projectDir:n.current}))},[]),a=dt(e=>{(async()=>{const t=await loadCommandSessionMeta({sessionId:e});r.current===e&&t?.title&&t.title!==o.current&&s(t.title)})()},[s]);lt(()=>{r.current=e,s(null),a(e)},[e,s,a]);const i=it(t);lt(()=>{const n=i.current;i.current=t,t!==n&&reassertTerminalTitle(),!t&&n&&(o.current||a(e))},[t,e,a]),lt(()=>{if(!process.stderr.isTTY)return;const e=setInterval(reassertTerminalTitle,5e3);return()=>{clearInterval(e)}},[]);const l=dt(e=>{s(e)},[s]);return{setRenamedTerminalTitle:l,applyGeneratedTitle:l}}function useUiOverlays(){const[e,t]=at(!1),[n,r]=at(!1),[o,s]=at(!1),[a,i]=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),[O,L]=at(!1),[D,N]=at(!1),[$,_]=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),[ae,ie]=at(null),[le,ce]=at("off"),de="off"!==le,ue=dt(e=>{hardResetForResize(),te(e=>e+1),e(!1)},[]);return{showFileList:e,setShowFileList:t,showAgentsConfig:n,setShowAgentsConfig:r,showTasteConfig:o,setShowTasteConfig:s,showSkillsConfig:a,setShowSkillsConfig:i,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:O,setShowLoginOverlay:L,showCompactModeSelector:D,setShowCompactModeSelector:N,showContextView:$,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:ae,setModelNotice:ie,transcriptMode:le,setTranscriptMode:ce,expandedToolOutput:de,showDesignGuide:J,setShowDesignGuide:Q,pendingDesignSuggestion:X,setPendingDesignSuggestion:Z}}__name(buildHookStartupEntries,"buildHookStartupEntries"),__name(submitInitialPrompt,"submitInitialPrompt"),__name(useStartup,"useStartup"),Ht(),__name(useStatus,"useStatus"),Ht(),Qx(),__name(useTerminalTitle,"useTerminalTitle"),Ht(),__name(useUiOverlays,"useUiOverlays");var L_=__name(({resume:e=!1,resumeSessionId:t,continue:n=!1,trust:r=!1,dangerouslySkipPermissions:o=!1,updateStatus:s,updateFailedInfo:a,initialPrompt:i,skipOnboarding:l=!1,initialPermissionMode:c,local:d=!1,sessionTitleHolder:u})=>{const{exit:m}=nt(),{stdout:p}=Ze();usePasteRouter(),lt(()=>{isLocalOnly()||prefetchBillingContext()},[]);const[g,h]=at(""),[f,y]=at(""),S=it(!1),w=it(!1),v=it(null),k=useUiOverlays(),C=useFeed(),b=useSession(),E=useStatus(s),T=useAuth(),P=usePendingOps(),M=useOnboarding(),x=useExit(),{executeBash:I,executionState:A}=t_(),R=usePermissionMode({initialPermissionMode:c,local:d,dangerouslySkipPermissions:o,setPendingPermission:P.setPendingPermission,setStatus:E.setStatus}),O=useTerminalTitle({sessionId:b.sessionId,isCmdCodeBusy:C.isCmdCodeBusy}),{ready:L}=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:D}=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:D}),lt(()=>{k.planBreadcrumbPending&&!C.isCmdCodeBusy&&(k.setPlanBreadcrumbPending(!1),C.setFeed(e=>[...e,pg("Plan saved — run /plans to review, annotate, or execute it anytime.")]))},[k.planBreadcrumbPending,k.setPlanBreadcrumbPending,C.isCmdCodeBusy,C.setFeed]);const{loadTasteStatus:N,loadCurrentProvider:$,onSubmit:_}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:i,stdout:p,feedState:C,sessionState:b,statusState:E,authState:T,onboarding:M,uiOverlays:k,permissionState:R,harnessReady:L,isSubmittingRef:S,initialPromptSubmittedRef:w,historyManagerRef:v,executeBash:I,setInput:h,onCommand:D});useMonitorOutputWakeup({onSubmit:_}),useCronWakeup({onSubmit:_}),useQueuedMessageFlush({isCmdCodeBusy:C.isCmdCodeBusy,queuedMessages:C.queuedMessages,queuedMessagesRef:C.queuedMessagesRef,setQueuedMessages:C.setQueuedMessages,isSubmittingRef:S,onSubmit:_}),useLifecycle({exit:m,feedState:C,exitState:x,statusState:E,authState:T,onboarding:M,uiOverlays:k,skipOnboarding:l,sessionId:b.sessionId,sessionTitleHolder:u});const{handleToggleAutoAccept:F,handleEnableAutoAccept:U,handleDoubleEscapeEmpty:j,handleTasteOnboardingComplete:B,handleTrust:W,handleNoTrust:H}=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")}),G=useMainActionCallbacks({feedState:C,sessionState:b,statusState:E,authState:T,uiOverlays:k,setInput:h}),{creditWarning:V}=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:G,onSubmit:_,onCommand:D,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,updateFailedInfo:a,creditWarning:V,handleTrust:W,handleNoTrust:H,handleToggleAutoAccept:F,handleEnableAutoAccept:U,handleDoubleEscapeEmpty:j,handleTasteOnboardingComplete:B,loadTasteStatus:N})},"InteractiveCLI");function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:a,pendingOps:i,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(a.shouldExit)return null;if(s.checkingProject)return null;if(s.showTrustPrompt)return ot.createElement(Z$,{staticKey:o.staticKey,onTrust:v,onExit:k});if(o.showSessionSelector)return ot.createElement(Q$,{onSelectSession:u.onSelectSession,onClose:()=>o.closeFullScreenOverlay(o.setShowSessionSelector),currentSessionId:t.sessionId});if(!s.projectTrusted)return null;const M=o.pendingDesignSuggestion?ot.createElement(fD,{suggestion:o.pendingDesignSuggestion,onSelect:e=>{p(`/design ${e}`)},onClose:()=>o.setPendingDesignSuggestion(null)}):null,x=i.pendingQuestion?.params.exitPlanMode?i.pendingQuestion:null,I=i.pendingQuestion&&!x?ot.createElement(QuestionView,{pendingQuestion:i.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,dangerouslySkipPermissions:l.dangerouslySkipPermissions,setPendingQuestion:i.setPendingQuestion,setStatus:n.setStatus,setStaticKey:o.setStaticKey}):null,A=i.pendingPermission?ot.createElement(aD,{pendingPermission:i.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:i.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]}]}),i.setPendingQuestion(null),hardResetForResize(),o.setStaticKey(e=>e+1)},"resolveApproval");return ot.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 ot.createElement(TasteConfigView,{staticKey:o.staticKey,onClose:()=>R(o.setShowTasteConfig),loadTasteStatus:P});if(o.showSkillsConfig)return ot.createElement(SkillsConfigView,{staticKey:o.staticKey,onClose:()=>R(o.setShowSkillsConfig)});if(o.showSettingsConfig)return ot.createElement(SettingsConfigView,{staticKey:o.staticKey,onClose:()=>R(o.setShowSettingsConfig),loadTasteStatus:P});if(o.showUsageOverlay)return ot.createElement(UsageView,{staticKey:o.staticKey,onClose:()=>R(o.setShowUsageOverlay)});if(o.showContextView)return ot.createElement(ContextConfigView,{staticKey:o.staticKey,sessionId:t.sessionId,onClose:()=>R(o.setShowContextView),setInput:h});if(o.showStatusView)return ot.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 ot.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"),$O(t.sessionId)?.setPermissionMode({mode:"auto-accept"})),e(n)}})}return ot.createElement(k$,{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:a.pendingExitKey,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,tasteLearningOn:n.tasteLearningOn,historyManagerRef:c,executionState:d,sessionId:t.sessionId,onSubmit:m,onCommand:p,onToggleAutoAccept:C,onResetPendingExitKey:a.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"),Qx(),Ht();var D_=__name(({worktreePath:e,warning:t,onChoice:n})=>{const[r,o]=at(1);return tt((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)}),ot.createElement(ZA,{title:"Exiting worktree session",subtitle:t,hint:"Enter to confirm · Esc to cancel"},ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,{color:1===r?nI.CYAN:nI.GRAY},1===r?pt.pointer:" "," 1. Keep worktree"," ",ot.createElement(Qe,{color:nI.GRAY},"Stays at ",tildeHome(e)))),ot.createElement(Je,null,ot.createElement(Qe,{color:2===r?nI.CYAN:nI.GRAY},2===r?pt.pointer:" "," 2. Remove worktree"," ",ot.createElement(Qe,{color:nI.GRAY},"All changes and commits will be lost.")))))},"WorktreeExitPrompt");function promptWorktreeExit(e){return new Promise(t=>{const{unmount:n}=et(ot.createElement(D_,{worktreePath:e.worktreePath,warning:e.warning,onChoice:e=>{n(),t(e)}}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})})}function canRespawn(){if(process.versions.bun)return!1;const e=process.argv[1];return"string"==typeof e&&e.length>0}async function writeReloadHandoff(e){const t=process.env[IT];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(){try{process.stdin.isTTY&&process.stdin.setRawMode(!1)}catch{}try{process.stdout.write("[?25h")}catch{}}__name(promptWorktreeExit,"promptWorktreeExit"),Ht(),Qx(),__name(canRespawn,"canRespawn"),__name(writeReloadHandoff,"writeReloadHandoff"),__name(consumeReloadHandoff,"consumeReloadHandoff"),__name(restoreTerminal,"restoreTerminal");var N_=gt.hex(nI.DIM);function printReloadFallbackHint(){process.stdout.write(N_("Couldn't restart automatically in this build — exiting instead.\n"))}async function shutdownWrapperRuntime(){try{await Promise.allSettled([disconnectAllMcpServers(),FO()])}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();const s=y(process.execPath,[process.argv[1],...t],{stdio:"inherit",env:{...process.env,[IT]:r,[AT]:String(process.pid)}});let a,i;try{[a,i]=await new Promise((e,t)=>{s.once("exit",(t,n)=>e([t,n])),s.once("error",t)})}catch(e){restoreTerminal(),process.stderr.write(N_(`\nCouldn't relaunch Command Code: ${e.message}\n`)),await z.rm(n,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}if(a!==xT){if(restoreTerminal(),await z.rm(n,{recursive:!0,force:!0}).catch(()=>{}),i){const e=B.constants.signals[i];process.exit(e?128+e:1)}process.exit(a??1)}else o=await consumeReloadHandoff(r)??o}}async function handlePendingReload(e){canRespawn()?(isWrappedChild()&&(await writeReloadHandoff(e),process.exit(xT)),await runRelaunchLoop(e)):printReloadFallbackHint()}__name(printReloadFallbackHint,"printReloadFallbackHint"),__name(shutdownWrapperRuntime,"shutdownWrapperRuntime"),__name(runRelaunchLoop,"runRelaunchLoop"),__name(handlePendingReload,"handlePendingReload");var $_=__name(e=>e.replace(/\x1B\[[0-9;]*[A-Za-z]/g,"").replace(/[\x00-\x1F\x7F]/g," ").trim(),"sanitizeTitleForOutput"),__=gt.hex(nI.DIM),F_=__name(()=>{const e=getInvokedCommandName();return"win32"===process.platform&&"cmd"===e?"cmdc":e},"getResumeCommandName"),U_=__name((e,t)=>{const n=F_(),r=we([e]),o=t?`cd ${we([t])} && ${n} --resume ${r}`:`${n} --resume ${r}`;return`${__("Resume this session with:")}\n${__(o)}\n`},"formatResumeHint"),j_=__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"),B_=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),W_=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),H_=__name(e=>e.permissionMode?e.permissionMode:e.plan?"plan":void 0,"resolveInitialPermissionMode"),G_=__name(({options:e,resumeSessionId:t,sessionTitleHolder:n})=>{const r=H_(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"),V_=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),z_=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),K_=__name(()=>{z_()},"initializeTerminal"),q_=__name(()=>{process.on("SIGINT",()=>{})},"swallowSigintDuringShutdown"),Y_=__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"),J_=__name(async(e={})=>{const t=j_(process.stdin.isTTY);let n,o;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),K_(),"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(),a=await listAllSessionsV3({runtime:t}),i=getProjectSessionDir({env:t.env(),cwd:t.cwd()}),l=resolveSessionRefFlag({ref:e.session,isExistingFile:__name(e=>I(e),"isExistingFile"),listSessionIds:__name(()=>a.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(a.find(e=>e.id===l.sessionId)?.path??"");n=c(d,".jsonl"),r(d)!==i&&(o=d)}if(B_(e)&&!n){const e=await isCommandProjectSessionInitialized(),t=e?await listCommandSessions():[],n=W_({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}if(e.forkSession){const t=await Y_({resumeSessionId:n,useContinue:Boolean(e.continue)});t&&(n=t,e.continue=!1)}await applyStartupTheme(),startEarlyInputCapture(),setStartupSessionOptions({...!1===e.session?{persist:!1}:{},...o?{sessionFilePath:o}:{},...e.name?{name:e.name}:{}});const a={},i=G_({options:e,resumeSessionId:n,sessionTitleHolder:a}),l=V_(),d=et(ot.createElement(L_,{...i}),l);registerInkControl({clear:d.clear,stdout:process.stdout,instance:await resolveInkInstance(process.stdout)}),await d.waitUntilExit(),clearTerminalTitle(),q_();const u=consumePendingReload();u&&await handlePendingReload(u);const m=await(a.loadTitle?.())??null,p=Boolean(m);let g;const h=getAutoCreatedWorktree();if(h){const e=worktreeHasWork(h.worktreePath,h.baseSha);let t="auto";if(e||p){const n=worktreeChangeCount(h.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:h.worktreePath,warning:r})}const n=finalizeAutoCreatedWorktree(t);if(n.worktreePath){const e=__(createOSC8Link(fileUrl(n.worktreePath),tildeHome(n.worktreePath),!1));if(n.removed){const n="auto"===t?"Removed empty worktree":"Removed worktree";process.stdout.write(`${__(n)}\n${e}\n\n`)}else if(n.kept){g=n.worktreePath;const t=n.reason&&"kept"!==n.reason?` (${n.reason})`:"";process.stdout.write(`${__(`Kept worktree${t}`)}\n${e}\n\n`)}}}const f=a.sessionId;if(f&&await commandSessionExists(f)){const e=m?$_(m):"";process.stdout.write(U_(e||f,g))}},"interactiveMode");Ht(),Qx(),Ht();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 Q_=__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)=>{M.writeFileSync(e,t)}),r=t(),o=[],s=[],a=new Map,i=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=Q_(o.length+1);return o.push(t),t},"currentTurn"),m=__name(e=>{const n=u(),r=a.get(e.toolCallId);void 0!==r&&(n.toolDurationMs+=t()-r,a.delete(e.toolCallId));const o=i.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 a.set(e.toolCallId,t()),i.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(Q_(e.turnNumber))},"onEvent"),g=__name(()=>{const e={};let n=0,a=0,i=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&&a++;i+=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:a},tokens:{input:i,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 X_=null,Z_=!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(Z_)return;Z_=!0;const e=__name(e=>{X_?.abort(),process.stderr.write(`\n${e}\n`),process.exit(Rb.INTERRUPTED)},"handleTermination");process.on("SIGINT",()=>e("Interrupted.")),process.on("SIGTERM",()=>e("Terminated.")),process.stdout.on("error",e=>{"EPIPE"===e.code&&process.exit(Rb.SUCCESS),process.stderr.write(`Error writing to stdout: ${e.message}\n`),process.exit(Rb.ERROR)})}async function printMode(e={}){trackCommand({command:"print"}),setupSignalHandlers(),X_=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:a,resumeState:i,sessionFilePath:l})=>{const c=await createHarnessSession({sessionId:t,baseUrl:getApiBaseUrl(),entrypoint:r,headless:o,maxTurns:s,mods:a,dangerouslySkipPermissions:e.dangerouslySkipPermissions,permissionMode:resolveLaunchPermissionMode(e),...n.forceEnabledTools?{forceEnabledTools:n.forceEnabledTools}:{},modHost:await loadCommandModHost({projectMods:Boolean(e.dangerouslySkipPermissions)}),resumeState:i,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)]),process.exit(o.exitCode)}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(`${pt.cross} Authentication failed. Please try again with: ${getBinaryCommand()} login`)},"onAuthFailed"),onLoginError:__name(e=>{console.error(`${pt.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:cr,groups:[...getModelGroupsInOrder(),...customModelListGroups()]})}async function printModelList(){await loadCustomProviderModels();const e=Boolean(process.stdout.isTTY)&&void 0===process.env.NO_COLOR;process.stdout.write(`${formatModelList({color:e})}\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(resolveLaunchPermissionMode,"resolveLaunchPermissionMode"),__name(getAuthKey4,"getAuthKey"),__name(readStdin,"readStdin"),__name(writeOutput,"writeOutput"),__name(setupSignalHandlers,"setupSignalHandlers"),__name(printMode,"printMode"),Ht(),Qx(),__name(ensureAuthenticated,"ensureAuthenticated"),Ht(),Qx(),__name(suggestModel,"suggestModel"),__name(formatModelList,"formatModelList"),__name(printModelList,"printModelList"),__name(resolveModelFlagOrExit,"resolveModelFlagOrExit"),Ht(),Qx();var eF=!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(),FO()])}catch{}}function handleShutdownSignal(){eF||(eF=!0,abandonPendingCommandSpan(),Promise.allSettled([disconnectMcpServers(),shutdownTelemetry()]).finally(()=>{process.exit(0)}))}async function shutdownAndExit(e=0){eF=!0,abandonPendingCommandSpan();try{await Promise.allSettled([disconnectMcpServers(),shutdownTelemetry(Fn)])}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 tF=__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)yf.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?await resolveModelFlagOrExit({model:t.model}):void 0,a=o?.modelId,i=t,l=__name(e=>{process.stderr.write(`${e.message}\n`),e.ok||process.exit(1)},"applySettingResult");for(const e of OL){const t=i[e.key];"string"==typeof t&&l(await e.apply(t,{model:a}))}const c=i.config;if(Array.isArray(c))for(const e of c)"string"==typeof e&&l(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,o?.providerId),setGoalMaxTurnsOverride(t.maxTurns);const d=parseInteractivePromptArgument(e);await tF();const u=buildInteractiveRuntimeOptions(t),m=resolveInteractiveLaunchConfig({options:t,runtimeOptions:u,initialPrompt:d});setOriginalInvocation({trust:u.trust,dangerouslySkipPermissions:u.dangerouslySkipPermissions,skipOnboarding:u.skipOnboarding,maxTurns:t.maxTurns,skillPaths:n,skillDiscovery:r}),await installKeybindingsFromConfig({runtime:getCommandConfigRuntime()}),await J_(m),await shutdownAndExit(0)}__name(interactiveModeAction,"interactiveModeAction"),Ht(),Qx(),Ht(),Qx();var nF={connected:gt.green("✔"),installed:gt.green("✔"),up_to_date:gt.green("✔"),needs_reload:gt.yellow("◌"),failed:gt.red("✖"),not_in_ide:gt.yellow("◌")};function formatSetupResult(e){const{prefix:t,ide:n,suffix:r}=getIDESetupStatusHeadline(e.status,e.ide),o=`${t}${n??""}${r}`;return["",`${nF[e.status]} ${o}`,...(e.details??[]).map(e=>gt.dim(` ${e}`)),""]}__name(formatSetupResult,"formatSetupResult"),globalThis.COMMAND_CODE_CWD=process.cwd();var rF=__name(()=>process.cwd(),"getCwd"),oF=__name(()=>process.argv.slice(2),"getArgs"),sF=__name(()=>{const e=rF(),t=oF(),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(){sF();const e=resolveCliStartupPlan({args:oF()});if(e.shouldRunIdeSetup){const e=await runIdeSetup({host:n_,moduleUrl:import.meta.url});formatSetupResult(e).forEach(e=>console.log(e)),process.exit("failed"===e.status?1:0)}e.shouldRunAutoUpdate&&runCliStartupPendingUpdates({plan:e,host:p_}),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:p_}),scheduleCliStartupIdeAutoInstall({host:n_,moduleUrl:import.meta.url})}__name(getAuthKey6,"getAuthKey"),__name(preRun,"preRun"),Ht(),Qx();var aF=Object.fromEntries(Object.entries(sv).map(([e,t])=>[t,e])),iF=new Set(KR.map(e=>e.id));function formatProviderModule(e){return iF.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=aF[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 KR){if(s.has(e.id))continue;if(!1===e.discoverable)continue;const n=aF[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=[bt.bold("Providers available for login/logout"),""];for(const r of e){const e=r.authenticated?bt.green("logged in"):bt.dim("not logged in"),o=r.installed?"":bt.dim(" (not installed, installs on first login)");n.push(bt.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: ${bt.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(bt.yellow("Provider load errors"));for(const e of t.errors)console.log(`${bt.yellow(e.id)}: ${e.error}`)}}__name(formatProviderModule,"formatProviderModule"),__name(buildProviderLoginRows,"buildProviderLoginRows"),__name(formatProviderLoginRows,"formatProviderLoginRows"),__name(providersAction,"providersAction");var lF=new je("providers").description("List providers available for login/logout").option("--json","Output providers as JSON for automation").action(providersAction);function stopAllSpinners({state:e}){e.workingSpinner&&(e.workingSpinner.stop(),e.workingSpinner=null),e.currentSpinner&&(e.currentSpinner.stop(),e.currentSpinner=null)}function renderStatusAction({action:e,state:t}){if("replayed_setup"!==e.type)return"setup_step"===e.type?(t.currentSpinner&&t.currentSpinner.succeed(),void(t.currentSpinner=Pt({stream:process.stderr,text:e.message}).start())):"running"===e.type?(t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),void(t.workingSpinner||(t.workingSpinner=Pt({stream:process.stderr}).start()))):"completed"===e.type?(t.workingSpinner&&(t.workingSpinner.succeed("Session completed"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),void(e.prUrl&&console.error(`PR: ${bt.cyan(e.prUrl)}`))):"failed"===e.type?(t.workingSpinner&&(t.workingSpinner.fail(e.message),t.workingSpinner=null),void(t.currentSpinner&&(t.currentSpinner.fail(e.message),t.currentSpinner=null))):"timed_out"===e.type?(t.workingSpinner&&(t.workingSpinner.fail("Session timed out"),t.workingSpinner=null),void(t.currentSpinner&&(t.currentSpinner.fail("Timed out"),t.currentSpinner=null))):void("cancelled"===e.type&&(stopAllSpinners({state:t}),console.error(`\n${bt.yellow("Cancelled.")}`)));e.message&&t.workingSpinner&&(t.workingSpinner.text=e.message)}function setupInputHandling({callbacks:e}){const t=__name(t=>{3!==t[0]?4===t[0]&&e.onDetach():e.onCancel()},"onStdinData"),n=process.rawListeners("SIGINT").slice();return process.removeAllListeners("SIGINT"),process.stdin.isTTY?(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",t),process.on("SIGINT",()=>{})):process.on("SIGINT",()=>e.onCancel()),()=>{process.stdin.isTTY&&(process.stdin.removeListener("data",t),process.stdin.setRawMode(!1),process.stdin.pause()),process.removeAllListeners("SIGINT");for(const e of n)process.on("SIGINT",e)}}function setupResizeForwarding({handle:e}){const t=__name(()=>{e.sendResize({cols:process.stdout.columns,rows:process.stdout.rows})},"onResize");return process.stdout.on("resize",t),()=>process.stdout.removeListener("resize",t)}async function streamSession({sessionId:e,lastEventId:t=0,isResume:n=!1}){const r={currentSpinner:null,workingSpinner:null},o=await streamSandboxSession({sessionId:e,lastEventId:t,isResume:n,getTerminalSize:__name(()=>({cols:process.stdout.columns,rows:process.stdout.rows}),"getTerminalSize"),callbacks:{onOpen:__name(({isResume:t})=>{r.currentSpinner&&(r.currentSpinner.stop(),r.currentSpinner=null),console.error(""),console.error(`${bt.yellow("[Ctrl+C]")} ${bt.dim("stop")} ${bt.yellow("[Ctrl+D]")} ${bt.dim("detach")}`),console.error(`${bt.dim("Session:")} ${bt.gray(e)}`),console.error(""),t&&(r.workingSpinner=Pt({stream:process.stderr}).start())},"onOpen"),onStatus:__name(({action:e})=>renderStatusAction({action:e,state:r}),"onStatus"),onPty:__name(({content:e})=>{r.workingSpinner&&r.workingSpinner.stop(),process.stdout.write(e),r.workingSpinner&&r.workingSpinner.start()},"onPty"),onErrorEvent:__name(({message:e})=>{r.currentSpinner&&(r.currentSpinner.fail(),r.currentSpinner=null),console.error(`${pt.cross} ${bt.red(e)}`)},"onErrorEvent"),onDetached:__name(()=>{stopAllSpinners({state:r}),console.error(`\n${bt.yellow("Detached.")} Session still running.`),console.error(`Resume with: ${bt.cyan(`${getBinaryCommand()} --experimental sandbox --id ${e}`)}`)},"onDetached"),onCancelled:__name(()=>{stopAllSpinners({state:r}),console.error(`\n${bt.yellow("Sandbox stopped.")}`)},"onCancelled"),onDisconnected:__name(()=>{stopAllSpinners({state:r}),console.error(`\n${bt.yellow("Disconnected.")} Session still running.`),console.error(`Resume with: ${bt.cyan(`${getBinaryCommand()} --experimental sandbox --id ${e}`)}`)},"onDisconnected"),onConnectionError:__name(()=>{r.currentSpinner&&(r.currentSpinner.fail("Connection error"),r.currentSpinner=null)},"onConnectionError")}});n&&(r.currentSpinner=Pt({stream:process.stderr,text:"Reconnecting..."}).start());const s=setupResizeForwarding({handle:o}),a=setupInputHandling({callbacks:{onCancel:o.cancel,onDetach:o.detach}});process.once("SIGTERM",o.detach);try{await o.done}finally{s(),a(),process.removeListener("SIGTERM",o.detach)}}async function askQuestion(e){const t=At.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.question(e,e=>{t.close(),n(e)})})}async function sandboxMode({prompt:e,resume:t}){t&&(await streamSession({sessionId:t,isResume:!0}),process.exit(0)),await ensureAuthenticated()||process.exit(1);const n=validateSandboxGitRepo({run:__name(({command:e})=>S(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"run")});n.isClean||console.error(bt.yellow("Warning: You have uncommitted changes. The sandbox clones from remote, so local changes won't be included."));const r=await readSandboxConfigFiles({runtime:getCommandConfigRuntime(),authFilePath:getAuthFile(),configFilePath:getConfigFile()}),o=e||await askQuestion(`${bt.bold("What do you want to do?")}\n${bt.cyan(">")} `);if(!o.trim())return void console.error(bt.yellow("No prompt provided. Aborting."));const s=truncateSandboxPrompt(o),a=Pt({stream:process.stderr,text:"Starting sandbox session..."}).start();try{const e=await startSandboxSession({client:createApiClient({baseUrl:getApiBaseUrl()}),request:{repoUrl:n.repoUrl,branch:n.branch,prompt:s,configFiles:r}});a.succeed("Sandbox started"),await streamSession({sessionId:e.sessionId,prompt:s}),process.exit(0)}catch(e){a.fail("Failed to start sandbox session");const t=classifySandboxStartFailure({error:e});if("unauthorized"===t.kind&&(console.error(bt.red(`\nAuthentication failed. Try logging in again: ${getBinaryCommand()} login`)),process.exit(1)),"github_app_not_installed"===t.kind){const e=bt.cyan(bt.underline(n.repoUrl)),t=bt.cyan(bt.underline("https://github.com/apps/command-code-ai/installations/new"));console.error(`\n${bt.red("✖")} Command Code GitHub App isn't installed on ${e}`),console.error(` Install it here: ${t}`),console.error(bt.dim(" Then run this command again.")),process.exit(1)}console.error(bt.red(`\n${t.message}`)),process.exit(1)}}function createSandboxCommand(){return new je("sandbox").description("Run a task autonomously in a sandbox").argument("[prompt]","Task description").option("--id <sessionId>","Resume an existing sandbox session").enablePositionalOptions().action(async(e,t)=>{try{await sandboxMode({prompt:e,resume:t.id})}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(bt.red(t)),process.exit(1)}})}Ht(),Ht(),Qx(),Ht(),Qx(),__name(stopAllSpinners,"stopAllSpinners"),__name(renderStatusAction,"renderStatusAction"),__name(setupInputHandling,"setupInputHandling"),__name(setupResizeForwarding,"setupResizeForwarding"),__name(streamSession,"streamSession"),__name(askQuestion,"askQuestion"),__name(sandboxMode,"sandboxMode"),__name(createSandboxCommand,"createSandboxCommand"),Ht(),Ht(),Qx();var cF=[`${bt.dim("Usage:")}`,` ${bt.cyan(`${getBinaryCommand()} skills add`)} ${bt.white("<owner/repo>")}`,"",`${bt.dim("Examples:")}`,` ${bt.cyan(`${getBinaryCommand()} skills add`)} ${bt.white("acme/my-skills")} ${bt.dim("# single-skill repo")}`,` ${bt.cyan(`${getBinaryCommand()} skills add`)} ${bt.white("acme/skills/path/to/skill")} ${bt.dim("# specific path in repo")}`,` ${bt.cyan(`${getBinaryCommand()} skills add`)} ${bt.white("acme/multi-skills -s my-skill")} ${bt.dim("# pick one from multi-skill repo")}`,` ${bt.cyan(`${getBinaryCommand()} skills add`)} ${bt.white("acme/repo@branch")} ${bt.dim("# specific branch")}`,` ${bt.cyan(`${getBinaryCommand()} skills add`)} ${bt.white("acme/repo --global")} ${bt.dim("# install to ~/.commandcode/skills/")}`],dF=__name((e,t)=>`${bt.green(pt.tick)} Installed ${bt.cyan(e)} ${bt.dim(`${pt.arrowRight} ${t}/`)}`,"formatInstalled"),uF=__name(e=>`${bt.red(pt.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(uF(t.message)),console.log(""),t.message.startsWith("Invalid repository")&&(console.log(`Expected format: ${bt.cyan("owner/repo")} or ${bt.cyan("owner/repo/path")}`),console.log("")),cF.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=Pt({text:`Fetching ${bt.cyan(e)}...`,color:"cyan"});try{let a=[];s.start();const i=await discoverCommandSkills(e,{keepTempDir:!0}),{skills:l,tempDir:c}=i;o=c,s.stop();const d=planSkillInstallSelection({skills:l,requestedSkillName:t.skill,interactive:n,repoInput:e});if("empty"===d.kind&&(console.error(uF(`No skills found in ${bt.cyan(e)}`)),console.log(bt.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(o,1)),"missing-requested-skill"===d.kind)return console.error(uF(`Skill "${d.requestedSkillName}" not found in ${bt.cyan(d.repoInput)}`)),console.log(""),console.log(bt.dim("Available skills:")),d.availableSkillNames.forEach(e=>console.log(` ${bt.cyan(e)}`)),void await cleanupAndExit(o,1);if("prompt"===d.kind){const t=await ze({message:`Select skills to install from ${e}`,options:[...d.options],required:!0});"symbol"==typeof t&&(console.log(bt.dim("Cancelled")),await cleanupAndExit(o,0)),a=resolvePromptedSkillSelection({skills:l,selectedNames:t})}let u;"selected"===d.kind&&(a=d.skills);const m=await installSelectedCommandSkills({repoInput:e,skills:a,global:t.global,force:t.force,cachedTempDir:o,onSkillStart:__name(e=>{u=Pt({text:`Installing ${bt.cyan(e.name)}...`,color:"cyan"}),u.start()},"onSkillStart"),onSkillInstalled:__name(e=>{u?.stop(),console.log(dF(e.name,r))},"onSkillInstalled"),onSkillFailed:__name(({skillName:e,message:t})=>{u?.stop(),console.error(uF(`Failed to install "${e}"`)),console.log(bt.dim(` ${t}`))},"onSkillFailed")});await cleanupAndExit(o,m.exitCode)}catch(e){s.stop();const t=e instanceof Error?e.message:String(e);console.error(uF(t)),await cleanupAndExit(o,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction2,"addAction");var mF=new je("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${cF.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(uF("No repository specified.")),console.log(""),cF.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction2);Ht(),Qx();var pF=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${bt.cyan(e)} ${bt.dim(`· ${n}`)}`},"formatSkillLine"),gF=__name((e,t)=>`${bt.bold(bt.white(e))} ${bt.dim(`(${t})`)}`,"formatSectionHeader"),hF=__name(e=>{if(0!==e.warningCount){console.log(""),console.log(`${bt.bold(bt.yellow("Skipped"))} ${bt.dim(`(${e.warningCount})`)}`);for(const t of e.warningGroups){console.log(""),console.log(` ${bt.bold(t.category)} ${bt.dim(`(${t.items.length})`)}`);for(const e of t.items)console.log(` ${bt.bold(skillIdentifier(e.path))}`),console.log(` ${bt.dim(e.reason)}`)}}},"printWarnings"),fF=__name(e=>{const t=["",bt.dim("No skills installed."),"",bt.dim("Looking in:")];for(const n of e.lookupPaths)t.push(bt.dim(` ${n.path} ${bt.white(`(${n.label})`)}`));return t.push("",`Install a skill: ${bt.cyan(e.installCommand)} ${bt.dim(e.installPlaceholder)}`,""),t},"formatEmptyHint"),yF=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),SF=__name(e=>{e&&(console.log(""),console.log(bt.dim(e.replace("--debug",bt.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()}`});yF(fF(t));for(const e of s.sections)console.log(gF(e.title,e.skills.length)),e.skills.forEach(e=>{console.log(pF(e.name,e.description))}),console.log("");e&&(hF({warningCount:s.warningCount,warningGroups:s.warningGroups}),s.warningCount>0&&console.log("")),e||(SF(s.debugHint),console.log("")),process.exit(0)}console.log(""),console.log(heading({text:"Skills",sub:bt.dim(`${s.userInstalledTotal} installed`)}));for(const e of s.sections)console.log(""),console.log(gF(e.title,e.skills.length)),e.skills.forEach(e=>{console.log(pF(e.name,e.description))});e&&hF({warningCount:s.warningCount,warningGroups:s.warningGroups}),e||SF(s.debugHint),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${bt.red(pt.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction2,"listAction");var wF=new je("list").description("List all installed skills. Run with -d/--debug to also see why any skills were skipped.").action(listAction2);Ht(),Qx();var vF=__name((e,t)=>`${bt.green(pt.tick)} Removed ${bt.cyan(e)} from ${t} skills`,"formatRemoved"),kF=__name(e=>`${bt.red(pt.cross)} ${e}`,"formatError"),CF=__name((e,t)=>{let n=e;for(const e of t)n=n.replace(e,bt.cyan(e));return bt.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(kF(o)),console.log(CF(getSkillListCommandHint({binCommand:`${getBinaryCommand()}`}),[`${getBinaryCommand()} skills list`])),process.exit(1)),!t.yes&&n){const t=await Ke({message:`Remove ${bt.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(bt.dim("Cancelled")),process.exit(0))}await removeCommandSkill({skillName:e,global:t.global}),console.log(vF(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(kF(o.message)),"not-found"===o.kind)for(const t of o.hints)console.log(CF(t,[`${getBinaryCommand()} skills remove ${e} --global`,`${getBinaryCommand()} skills list`]));process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction2,"removeAction");var bF=new je("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),EF=new je("skills").description("Manage skills from GitHub repositories").addCommand(mF).addCommand(bF).addCommand(wF);Ht(),Qx(),Ht(),Qx(),Ht(),Ht(),Qx();var TF=[pt.bullet,pt.squareSmallFilled,pt.lozenge,pt.star,pt.triangleRight,pt.triangleUp];Ht(),Qx(),Ht();var PF=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return PF.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"),Ht(),Qx(),Ht(),Ht();var MF=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),o=e.learningCount>0;return ot.createElement(Je,{flexDirection:"column",marginLeft:3},ot.createElement(Je,{marginBottom:1,flexDirection:"row"},ot.createElement(Qe,{color:nI.DIM},YI),ot.createElement(Je,{marginLeft:2},ot.createElement(Qe,{color:oI.TEXT},o?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),ot.createElement(Je,{flexDirection:"column",marginLeft:1},ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},pt.pointerSmall," Taste stored in"," "),ot.createElement(BI,{url:fileUrl(e.storage),text:r||".commandcode/taste/taste.md",color:nI.CYAN})),ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},pt.pointerSmall," Share your coding taste:"," ",ot.createElement(Qe,{color:nI.CYAN},"npx taste push --all")))),ot.createElement(Je,{marginTop:1,marginLeft:1},ot.createElement(Qe,{color:nI.DIM},o?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Ht();var xF=__name(({message:e})=>ot.createElement(qO,null,e),"RepoLearnErrorPanel");Ht();var IF=__name(({done:e,error:t})=>t?ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Esc")," to exit")):e?ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to continue")):ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"Esc to cancel")),"RepoLearnFooter");Ht(),Qx();var AF=__name(({insights:e,insightCount:t})=>0===e.length?null:ot.createElement(Je,{flexDirection:"column",marginTop:1,marginLeft:4},ot.createElement(Qe,{color:nI.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>ot.createElement(Qe,{key:`${t}-${e}`,color:nI.DIM},TF[t%TF.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Ht(),Qx();var RF=__name(({status:e})=>"active"===e?ot.createElement(Je,null,ot.createElement(Qe,{color:nI.YELLOW},ot.createElement(vt,{type:"dots"})),ot.createElement(Qe,null," ")):"complete"===e?ot.createElement(Qe,{color:lI.BG},pt.square," "):ot.createElement(Qe,{color:nI.DIM},pt.circle," "),"StepStatusIndicator");function getStepLabelColor(e,t){return"complete"===e?nI.WHITE:t?nI.YELLOW:nI.DIM}__name(getStepLabelColor,"getStepLabelColor");var OF=__name(({steps:e,currentMessage:t})=>ot.createElement(Je,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return ot.createElement(Je,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},ot.createElement(Je,null,ot.createElement(Je,{marginRight:1},ot.createElement(RF,{status:e.status})),ot.createElement(Qe,{bold:n,color:getStepLabelColor(e.status,n)},e.label)),n&&t?ot.createElement(Je,{marginLeft:3},ot.createElement(Qe,{color:nI.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Ht();var LF=__name(({isComplete:e,hasError:t})=>t?ot.createElement(Qe,{color:nI.DIM},"learning interrupted"):e?ot.createElement(Qe,{color:oI.TEXT},"learned your coding taste"):ot.createElement(GI,null),"TastePillStatus"),DF=__name(({isComplete:e,hasError:t})=>ot.createElement(Je,{flexDirection:"column",marginTop:1,marginBottom:0},ot.createElement(ZI,null),ot.createElement(Je,{marginTop:0},ot.createElement(Qe,{color:nI.DIM},YI),ot.createElement(Je,{marginLeft:2},ot.createElement(LF,{isComplete:e,hasError:t})))),"RepoLearnTastePill");Ht();var NF=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=ct(()=>RA(n),[n]);return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(PI,null,r.trimEnd())),e?ot.createElement(Qe,{color:nI.WHITE},e):ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.WHITE},"Learning your coding taste from"," ",ot.createElement(Qe,{bold:!0,color:nI.CYAN},t??"repository")),ot.createElement(Qe,{color:nI.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function useRepoLearnState(e){const t=e??TM,[n,r]=at(()=>createRepoLearnProjection({stepOrder:t})),o=it(null),[s,a]=at(null),i=dt(()=>{o.current=Date.now()},[]),l=dt(e=>{r(t=>({...t,showLogin:e}))},[]);return lt(()=>{const e=__name(()=>{r(createRepoLearnProjection({stepOrder:t})),o.current=null,a(null)},"handleReset"),n=__name(e=>{r(t=>reduceRepoLearnEvent({state:t,event:e}))},"handleEvent"),s=__name(()=>{r(e=>completeRepoLearnProjection({state:e})),o.current&&a(Math.round((Date.now()-o.current)/1e3))},"handleComplete");return am.on("reset",e),am.on("new-event",n),am.on("learning-complete",s),()=>{am.off("reset",e),am.off("new-event",n),am.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:i}}function StatusPanel({error:e,done:t,summary:n,elapsedSeconds:r,insights:o,insightCount:s}){return e?ot.createElement(xF,{message:e}):t?ot.createElement(MF,{summary:n,elapsedSeconds:r}):ot.createElement(AF,{insights:o,insightCount:s})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:o}){const s=useRepoLearnState(n),a=it(!1);return lt(()=>{a.current||(a.current=!0,s.markStarted(),e().catch(()=>{}))},[e,s.markStarted]),tt((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?ot.createElement(Je,{flexDirection:"column"},ot.createElement(NF,{text:r,repoName:o}),ot.createElement(kN,{onComplete:(e,t)=>{s.setShowLogin(!1),e?am.resolveAuth():am.rejectAuth(t)},onCancel:()=>{s.setShowLogin(!1),am.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):ot.createElement(Je,{flexDirection:"column"},ot.createElement(NF,{text:r,repoName:o}),ot.createElement(DF,{isComplete:s.done&&!s.error,hasError:Boolean(s.error)}),ot.createElement(OF,{steps:s.steps,currentMessage:s.currentMessage}),ot.createElement(StatusPanel,{error:s.error,done:s.done,summary:s.summary,elapsedSeconds:s.elapsedSeconds,insights:s.insights,insightCount:s.insightCount}),ot.createElement(IF,{done:s.done,error:s.error}))}async function runRepoLearnProgress(e){return await applyStartupTheme(),withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{am.reset();const r=new AbortController;let o,s,a=!1,i=!1;const l=__name(async()=>{try{o=await e.runTask(r.signal)}catch(e){r.signal.aborted||(s=e,am.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),am.markLearningComplete())}},"handleRunTask"),c=__name(({published:e,cancelled:l})=>{i||(i=!0,a=e,r.abort(),d.unmount(),am.reset(),s?n(s):t({result:o,published:a,cancelled:l}))},"handleExit"),d=et(ot.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:c}));d.waitUntilExit().catch(e=>{am.reset(),n(e)})})}function getAuthKey7(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function logLearnSummary(e){const{summary:t}=e;console.log(gt.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("")}Ht(),Qx(),__name(useRepoLearnState,"useRepoLearnState"),__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),__name(getAuthKey7,"getAuthKey"),__name(logLearnSummary,"logLearnSummary");var $F=__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 je("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",$F("--max-commits"),200).addOption(new Be("--max-signals <number>","Maximum diff signals to extract").default(50).argParser($F("--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 a;const i=__name(()=>{a?.().finally(()=>process.exit(130))},"sigintHandler");process.once("SIGINT",i);let l=!1;try{const i=__name(async r=>{const{summary:o,resolved:i}=await runLearnPipeline({runtime:t,reporter:am,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 a=i?.cleanup,o},"runTask");if(r){const e=n?void 0:[...PM];({cancelled:l}=await runRepoLearnProgress({runTask:i,repoName:o,stepOrder:e}))}else logLearnSummary({summary:await i((new AbortController).signal)})}finally{process.off("SIGINT",i),a&&await a()}r&&!l||process.exit(0),cA(),await J_({skipOnboarding:!0}),await shutdownAndExit(0)}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Ht(),Qx(),Ht(),Qx();var _F=gt.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(`${gt.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?`${gt.dim(t[1])}${gt.green(t[2])}${gt.white(t[3]??"")}${t[4]?gt.dim(t[4]):""}`:gt.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${gt.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 FF=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){const n=buildPackageUrl({owner:e,packageName:t});return It(`commandcode.ai/${e}/${t}`,n,{fallback:FF})}function getProfileLink(e){const t=buildProfileUrl2(e);return It(`commandcode.ai/${e}`,t,{fallback:FF})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return Rt(e,n,{trim:!1})}function logMergeReviewTip(){console.log(gt.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}function handleResultErrors(e){for(const t of e){const e=normalizeTasteResultError(t);console.error(`${gt.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(gt.red(`Error: ${t}`)),await flushAndExit(1)}}}function formatSingleIssue(e,t){const n=[`${e.line?gt.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(gt.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`${gt.green(e)} ${gt.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?gt.red(t.summary):gt.yellow(t.summary),"",...formatIssueGroup(r,gt.red,gt.bold(gt.red("Errors:"))),...formatIssueGroup(o,gt.yellow,gt.bold(gt.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"),Ht(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var UF=createTasteLintService({runtime:createNodeRuntime(),formatValidationIssues:formatValidationIssues});function createLintCommand(){return new je("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 ${gt.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(`${gt.green(pt.tick)} All ${gt.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(gt.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(gt.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 UF.lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(gt.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Ht(),Qx();var jF={};__export(jF,{downloadPackage:()=>downloadPackage,downloadRemotePackage:()=>downloadRemotePackage,getAllPackages:()=>getAllPackages,getPackage:()=>getPackage,listPackages:()=>listPackages,writePackage:()=>writePackage,writePackages:()=>writePackages}),Ht(),Qx();var BF=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: cmd 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:xo.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:a,categoryContents:i}=await readProjectUploadFiles({runtime:BF,packages:t});return storage().writePackages({projectName:n,owner:r,isPublic:o,overwrite:s,rootContent:a,categoryContents:i,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 WF=createNodeRuntime(),HF=createTasteLocalStorage({runtime:WF,target:"local-project"}),GF=createTasteLocalStorage({runtime:WF,target:"local-global"});function list(e){return createTasteListService({runtime:WF,localProject:HF,localGlobal:GF,remote:jF}).list(e)}function getUserName(){return getCommandAuthUserName({runtime:getCommandConfigRuntime(),path:getAuthFile()})}function createListCommand(){return new je("list").alias("ls").option("-g, --global","List global packages").addOption(new Be("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Be("--staging","Use staging environment").hideHelp()).description(`List available packages ${gt.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}function formatPackageLine(e){return` ${gt.white(e.name)}${e.publicBadge?gt.green(e.publicBadge):""}${e.starsBadge?gt.yellow(e.starsBadge):""}${e.downloadsBadge?gt.gray(e.downloadsBadge):""}${e.padding}${gt.dim.gray(e.statsLabel)}`}function validateListOptions(e){exitWithTasteCliValidation(validateTasteListCliOptions(e))}async function fetchPackages({options:e}){const t=resolveTasteListStorage(e),n=e.remote?Pt(`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${_F} Packages`),console.log(`${gt.gray("⎿")} ${gt.dim(t)}\n`);const n=projectTasteListView({packages:e,symbols:{star:pt.star,arrowDown:pt.arrowDown}});for(const e of n.rows)console.log(formatPackageLine(e));console.log(gt.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(gt.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"),Ht(),Qx(),Ht(),Qx();var VF=createNodeRuntime(),zF=createTasteLocalStorage({runtime:VF,target:"local-project"}),KF=createTasteLocalStorage({runtime:VF,target:"local-global"});async function open7(e){try{const t=await createTasteOpenService({runtime:VF,localProject:zF,localGlobal:KF,remote:jF}).resolveOpen(e);return t.success?(await xt([{file:t.filePath,line:t.lineNumber}]),t):t}catch(e){return classifyTasteOpenError({error:e,platform:be.platform})}}function createOpenCommand(){return new je("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 ${gt.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 Tt(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${gt.green(pt.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(`${gt.green(pt.tick)} Opened ${gt.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"),Ht(),Qx(),Ht(),Qx(),Ht();var qF=null,YF=!1;function setActiveSpinner(e){qF=e}function stopActiveSpinner(e){qF&&(qF.stop(e),qF=null)}function setPrompted(e){YF=e}function wasPrompted(){return YF}function logResult(e){if(wasPrompted())return He.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{summary:t,sourceName:n}=e,r=wasPrompted()?"":`${pt.tick} `,o=t.detailPath?gt.dim(`\n ${shortenPath(t.detailPath)}`):"";return"single-replaced"===t.variant?`${gt.green(r)}Replaced ${gt.green(`'${t.packageName}'`)} taste package in project`+o:"single-merged"===t.variant?`${gt.green(r)}Pulled ${gt.green(`'${t.packageName}'`)} taste package from ${n} ${gt.gray(`(${t.mergeParts.join(", ")})`)}`+o:`${gt.green(r)}Pulled ${gt.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(`${gt.green("Pulled")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`,wasPrompted()?4:0)),t.overwritten.length>0&&r.push(wrapLine(`${gt.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`,wasPrompted()?4:0)),t.skipped.length>0&&r.push(wrapLine(`${gt.dim("Skipped")} (${t.skipped.length}) ${gt.dim(t.skipped.join(", "))}`,wasPrompted()?4:0)),wasPrompted())return r.length>0&&He.log.message(r.join("\n")),He.outro(`${t.totalLabel} from ${n}`),void setPrompted(!1);console.log(`${gt.green(pt.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(gt.yellow(o.message))}function beginPrompt(e,t){stopActiveSpinner(),He.intro(gt.dim(e)),t&&He.log.message(gt.dim(t)),setPrompted(!0)}function handleCancel(e){He.isCancel(e)&&(He.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=He.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=He.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),He.log.warn(e.nonInteractive.warning),e.nonInteractive.strategy;if(beginPrompt(`${e.title.prefix}${gt.green(e.title.emphasis)}${e.title.suffix}`,e.existsMessage),He.log.message(`${e.context.firstLine}\n${e.context.secondLine}${e.context.secondLineNote?` ${gt.dim(e.context.secondLineNote)}`:""}`),e.reviewLink){const t=It(e.reviewLink.text,e.reviewLink.url,{fallback:__name((e,t)=>t,"fallback")});He.log.info(`${e.reviewLink.prefix}${gt.cyan(t)} ${gt.dim(e.reviewLink.note)}`)}const t=await He.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"),Ht(),Qx(),Ht(),Qx(),__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 JF=createNodeRuntime(),QF=createTasteLocalStorage({runtime:JF,target:"local-project"}),XF=createTasteLocalStorage({runtime:JF,target:"local-global"});function service(){return createTastePullService({localProject:QF,localGlobal:XF,remote:jF,getDestinationPath:__name(e=>resolveTastePackageDestinationPathForRuntime({runtime:JF,...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 je("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 Be("--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 Be("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${gt.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(Pt("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(Pt("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 He.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?gt.dim(`\n ${shortenPath(e)}`):""}function renderPushSummary(e){const t=wasPrompted()?"":`${pt.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?` ${gt.gray(`(${e.replacedLabel})`)}`:"";return void logResult2(`${gt.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?` ${gt.gray(`(${e.mergeParts.join(", ")})`)}`:"";return void logResult2(`${gt.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(`${gt.green(t)}Pushed ${gt.green(e.count)} taste packages ${gt.green(`(${e.packages.join(", ")})`)} to ${e.targetName}`)):logResult2(`${gt.green(t)}Pushed ${gt.green(`'${e.packageName}'`)} taste package to ${e.locationLabel}`+formatDetailPath(e.detailPath)):logResult2(`${gt.green(t)}Pushed ${gt.green(`'${e.packageName}'`)} taste package to ${e.locationLabel} ${gt.gray(`(${e.mergeParts.join(", ")})`)}`+formatDetailPath(e.detailPath)):logResult2(`${gt.green(t)}Replaced ${gt.green(`'${e.packageName}'`)} taste package in ${e.locationLabel}`+formatDetailPath(e.detailPath))}else logResult2(`${gt.green(t)}Pushed ${e.packageCountLabel} to ${formatAllLocation(e.location)}`)}else logResult2(`${gt.green(t)}Pushed ${e.packageCountLabel} to remote`);else logResult2(`${gt.green(t)}Skipped ${e.packageCountLabel}`)}function logPushUrls(e){for(const t of collectTastePushRemoteLinks(e))console.log(gt.gray(` ${getPackageLink(t)}`))}function logConflictSummary(e){const t=projectTastePushOutcome(e.result),n=[];t.succeeded.length>0&&n.push(wrapLine(`${gt.green("Merged")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`,4)),t.overwritten.length>0&&n.push(wrapLine(`${gt.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`,4)),t.skipped.length>0&&n.push(wrapLine(`${gt.dim("Skipped")} (${t.skipped.length}) ${gt.dim(t.skipped.join(", "))}`,4)),n.length>0&&He.log.message(n.join("\n")),He.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(`${gt.green("Pushed")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`)),t.overwritten.length>0&&n.push(wrapLine(`${gt.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`)),t.skipped.length>0&&n.push(wrapLine(`${gt.dim("Skipped")} (${t.skipped.length}) ${gt.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"),Ht(),Qx(),Ht(),Qx(),__name(logResult2,"logResult"),__name(formatAllLocation,"formatAllLocation"),__name(formatDetailPath,"formatDetailPath"),__name(renderPushSummary,"renderPushSummary"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Ht(),Qx();var ZF=createNodeRuntime(),eU=createTasteLocalStorage({runtime:ZF,target:"local-project"}),tU=createTasteLocalStorage({runtime:ZF,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:eU,localGlobal:tU,remote:jF,getUserOwner:getUserOwner,getProjectName:__name(()=>e.basename(process.cwd()),"getProjectName"),getDestinationPath:__name(e=>resolveTastePackageDestinationPathForRuntime({runtime:ZF,...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 He.select({message:"Owner",options:[...r],initialValue:o});return He.isCancel(s)&&(He.cancel("Operation cancelled"),process.exit(0)),s}__name(getUserOwner,"getUserOwner"),__name(service2,"service"),__name(push,"push"),__name(pushRemote,"pushRemote"),Ht(),Qx(),__name(promptOwnerSelection,"promptOwnerSelection");var nU=createNodeRuntime(),rU=createTasteLocalStorage({runtime:nU,target:"local-project"});function loadUserNamespaces(){return fetchUserNamespaces({client:createApiClient({baseUrl:getApiBaseUrl()})})}function createPushCommand(){return new je("push").description(`Push taste packages to remote ${gt.dim("(commandcode.ai)")} or global ${gt.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 Be("--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 Be("--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 rU.getAllPackages()).some(t=>t.category===e),"hasLocalPackage"),loadNamespaces:loadUserNamespaces,prompt:{onPromptStart:__name(({packageName:e})=>{He.intro(gt.dim(`pushing ${e}`)),setPrompted(!0),t=He.spinner(),t.start("Resolving")},"onPromptStart"),onPackageMissing:__name(({packageName:e})=>{t?.error("Failed"),He.outro(gt.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 rU.getAllPackages()).length),r=e.basename(process.cwd()),o=resolveTasteStrategyLabel({strategy:t.route.strategy,isRemote:!0});console.log(gt.dim(` Pushing ${n} to ${r} (remote)${o}`)),console.log(""),setActiveSpinner(Pt("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=He.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Pt("Pushing taste package").start())}async function pushGlobal(e){const t=await rU.getAllPackages(),n=formatTastePackageCount(e.route.packages.length>0?e.route.packages.length:t.length),r=shortenPath(getTastePathForRuntime({runtime:nU,target:"local-global"})),o=resolveTasteStrategyLabel({strategy:e.route.strategy});console.log(gt.dim(` Pushing ${n} to ${r}${o}`)),console.log(""),setActiveSpinner(Pt("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(`${gt.green(pt.tick)} Taste learning is on${whereFor(e)}. New preferences are saved and reused across sessions.`)}function reportDisabled(e){const t=getBinaryCommand();console.log(`${gt.green(pt.tick)} Taste learning is off${whereFor(e)}. Turn it back on with ${gt.cyan(`${t} taste enable`)}.`)}function createEnableCommand(){return new je("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 je("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 je("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"),Ht(),Qx(),__name(scopeOf,"scopeOf"),__name(whereFor,"whereFor"),__name(applyTasteLearning,"applyTasteLearning"),__name(reportEnabled,"reportEnabled"),__name(reportDisabled,"reportDisabled"),__name(createEnableCommand,"createEnableCommand"),__name(createDisableCommand,"createDisableCommand"),__name(createTasteCommand,"createTasteCommand"),Ht(),Qx();var oU=`${getBinaryCommand()}`;function formatVersion(e,t,n=!1){const r=n?bt.bold(bt.green(t)):bt.white(t);return`${bt.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(`${oU} update`,bt.bold(bt.green(`${oU} update`))))}function showUpdateSuccessHint(e){for(const t of e.detailLines)console.log(bt.dim(t.replace(oU,bt.cyan(oU))))}function showManualUpdateHint(e){const[t,n]=e.manualUpdateLines;t&&console.log(bt.dim(t)),n&&console.log(bt.cyan(n))}function showCheckFailure(e){for(const t of e.detailLines)console.log(bt.dim(t))}function renderUpdateEvent(e,t){if("type"in e)"updating"===e.type&&(t.text=e.text.replace("→",pt.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(`${bt.green(pt.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=Pt("Checking for updates...").start(),n=await runCliUpdateCommand({checkOnly:e.checkOnly,host:p_,copy:{binCommand:oU,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:xo.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 sU=new je("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})}Ht(),Qx(),__name(getAuthKey9,"getAuthKey");var aU=__name((e,t)=>`${pt.info} ${e}: ${bt.cyan(t)}`,"formatInfoLine"),iU=__name(e=>bt.bold(`${e}:`),"formatSectionHeader"),lU=__name(e=>bt.red(e),"formatError"),cU=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),dU=__name((e,t)=>["",iU(e),...t.map(e=>aU(e.label,e.value))],"buildSection"),uU=__name(e=>dU("User Information",projectWhoamiUserRows(e)),"buildUserOutput"),mU=__name(e=>dU("Organization",projectWhoamiOrgRows(e)),"buildOrgOutput"),pU=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),gU=__name((e,t)=>{pU(uU(e)),t&&pU(mU(t)),console.log("")},"displayUserInfo");async function whoamiAction(){const e=Pt("Fetching user information...").start();try{hasCommandApiKey(await getAuthKey9())||(e.fail(lU(Kt)),process.exit(1));const t=await getAuthenticatedEntity({client:createApiClient({baseUrl:getApiBaseUrl()})});isAuthenticatedEntityLoaded(t)||(e.fail(lU(qt)),process.exit(1)),e.succeed("User information loaded"),gU(t.user,t.org)}catch(t){e.fail(lU(`Error: ${cU(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var hU=new je("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 fU=createProgram();fU.action(interactiveModeAction),fU.addCommand(hO),fU.addCommand(TO),fU.addCommand(hU),fU.addCommand(sU),fU.addCommand(gO),fU.addCommand(pO),fU.addCommand(createTasteCommand()),fU.addCommand(createMcpCommand()),fU.addCommand(yL),fU.addCommand(lO),fU.addCommand(tO),fU.addCommand(iO),fU.addCommand(lF),fU.addCommand(EF),fU.addCommand(PL),isExperimentalEnabled()&&fU.addCommand(createSandboxCommand()),setupCommanderHooks(fU),fU.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(handleStdoutError,"handleStdoutError"),__name(handleStderrError,"handleStderrError"),__name(handleUnhandledErrors,"handleUnhandledErrors"),Ht(),Qx(),Ht(),Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),Ht();var BL=pt.pointer,WL=__name(({isSelected:e,backgroundColor:t})=>ot.createElement(Qe,{color:e?YA:QA,backgroundColor:t,bold:e&&isLightTheme()},e?BL:" "),"OverlayCaret"),HL=__name(({isSelected:e,isActive:t,idleColor:n=JA,backgroundColor:r,children:o})=>ot.createElement(Qe,{color:e?YA:t?XA:n,backgroundColor:r,bold:e&&isLightTheme()},o),"OverlayOptionText"),GL=__name(({isSelected:e,label:t})=>ot.createElement(HL,{isSelected:e}," ",t),"OverlayOptionItem"),VL=__name(({backgroundColor:e})=>ot.createElement(Qe,{color:XA,backgroundColor:e}," ",pt.tick),"OverlayActiveTick"),zL=__name(({indent:e=4,children:t})=>ot.createElement(Qe,{color:KA}," ".repeat(e),t),"OverlayOptionDescription"),KL=__name(({isSelected:e,idleColor:t=nI.GRAY,selectedColor:n=nI.WHITE,bold:r,children:o})=>ot.createElement(Qe,{color:e?n:t,backgroundColor:e?TI:void 0,bold:r??e},o),"OverlayBarText"),qL=__name(({isSelected:e,label:t})=>ot.createElement(KL,{isSelected:e}," ",t," "),"OverlayBarItem"),YL=__name(()=>null,"OverlayBarIndicator");Ht();var JL=createOSC8Link("https://commandcode.ai/docs/permissions#permission-modes","Docs ↗",!1),QL=__name(({hint:e})=>ot.createElement(Qe,{italic:!0,color:nI.DIM},e," · Run ",ot.createElement(Qe,{color:nI.WHITE},"cmd --yolo")," to bypass all permissions (",JL,")"),"PermissionFooter"),XL=__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 ot.createElement(ZA,{title:"Tool Permission",subtitle:ot.createElement(Qe,{wrap:"wrap"},"Command Code needs to run ",ot.createElement(Qe,{color:YA},e.toolName),"."),footer:ot.createElement(QL,{hint:"↑/↓ navigate · enter select"})},e.risk&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{bold:!0,color:nI.RED,wrap:"wrap"},pt.warning," ",getRiskDisplay(e.risk))),e.description&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM,italic:!0},e.description)),ot.createElement(SelectInput,{items:r.map((e,t)=>({label:`${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:n,indicatorComponent:WL,itemComponent:GL}))},"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?YI:JI).join("\n")}Ht(),Qx(),Ht(),Qx(),Ht(),__name(buildTreeConnectors,"buildTreeConnectors");var ZL=Ct()?"⟳":"*",eD=" │ ";function DiffWordSegments({segments:e,type:t,paired:n,dimDiff:r,language:o,highlightOptions:s}){const a="removed"===t?iI.REMOVED_HIGHLIGHT_BG:iI.ADDED_HIGHLIGHT_BG,i=[];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?i.push(ot.createElement(Qe,{key:u,backgroundColor:a,dimColor:r},d)):n?i.push(ot.createElement(Qe,{key:u,color:nI.WHITE,dimColor:r},d)):i.push(ot.createElement(Qe,{key:u,color:"removed"===t?iI.REMOVED_TEXT:iI.ADDED_TEXT,dimColor:r},d))}return i}function DiffRow({background:e,prefix:t,wrap:n="wrap",children:r}){return ot.createElement(Je,{width:"100%",backgroundColor:e},ot.createElement(Je,{flexShrink:0},t),ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{wrap:n},r)))}function renderDiffLine({line:e,dimDiff:t,language:n,highlightOptions:r}){if("skip"===e.kind)return ot.createElement(Je,{key:e.key,width:"100%"},ot.createElement(Qe,{color:iI.LINE_NUM,dimColor:t},e.spacer,eD,e.label));if("context"===e.kind)return ot.createElement(DiffRow,{key:e.key,prefix:ot.createElement(Qe,{color:iI.LINE_NUM,dimColor:t}," "+e.lineNumberLabel+eD)},ot.createElement(Qe,{color:nI.WHITE,dimColor:t}," ",highlightSyntax(e.text,n,r)));const o="removed"===e.kind,s=o?iI.REMOVED_TEXT:iI.ADDED_TEXT,a=o?iI.REMOVED_BG:iI.ADDED_BG;return ot.createElement(DiffRow,{key:e.key,background:a,prefix:ot.createElement(Qe,null,ot.createElement(Qe,{color:s,dimColor:t}," "+e.lineNumberLabel),ot.createElement(Qe,{color:iI.LINE_NUM,dimColor:t},eD),ot.createElement(Qe,{color:s,dimColor:t},o?"- ":"+ "))},ot.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?ot.createElement(Qe,{color:nI.RED},"Rejected update to",ot.createElement(Qe,{color:nI.RED},` ${e.filePath}`)):ot.createElement(Qe,{color:nI.GRAY},"Updated"," ",ot.createElement(Qe,{color:nI.WHITE,bold:!0},e.filePath)," ","with"," ",e.additions>0&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:uI.SUCCESS},e.additions)," ","addition",1!==e.additions?"s":"",e.removals>0?" and ":""),e.removals>0&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:uI.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:a=1,dimDiff:i=!1,maxLines:l}){const c=projectEditDiffView({oldValue:e,newValue:t,filePath:n,permissionDenied:r,showMetadata:o,startLine:a,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:ot.createElement(Je,{flexDirection:"column"},ot.createElement(DiffMetadata,{metadata:c.metadata}),ot.createElement(Je,{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:i,language:u,highlightOptions:m})))),isTruncated:c.isTruncated,totalLines:c.totalLines}}function resolveTodoTextStyle(e){return"completed"===e?{textColor:uI.SUCCESS,strikethrough:!0}:"in_progress"===e?{textColor:uI.IN_PROGRESS,strikethrough:!1}:{textColor:nI.WHITE,strikethrough:!1}}function TodoChecklist({todos:e}){return ot.createElement(Je,{flexDirection:"column"},e.map((e,t)=>{const n="completed"===e.status?pt.checkboxOn:pt.checkboxOff,{textColor:r,strikethrough:o}=resolveTodoTextStyle(e.status),s="in_progress"===e.status&&e.activeForm?`${e.activeForm}…`:e.content;return ot.createElement(Je,{key:e.id||t,flexDirection:"row"},ot.createElement(Je,{width:2},ot.createElement(Qe,{color:r},n)),ot.createElement(Qe,{color:r,bold:"in_progress"===e.status,strikethrough:o},s))}))}function formatTodosForDisplay(e){const t=Lg(e);return t?ot.createElement(TodoChecklist,{todos:t}):ot.createElement(Qe,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 ot.createElement(BracketWrap,null,t?e:ot.createElement(Markdown,null,e))}function ReadToolInlineSummaryRow({summary:e}){return e?.dimText?ot.createElement(Qe,{dimColor:!0}," ",e.dimText):null}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:o}){if(e)return{symbolColor:nI.YELLOW,symbol:pt.arrowRight};if(t)return{symbolColor:nI.RED,symbol:pt.square};if(n)return{symbolColor:sI,symbol:"✻"};if(r&&o){const e=Lg(o),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?uI.SUCCESS:uI.WARNING,symbol:pt.square}}return{symbolColor:lI.BG,symbol:pt.square}}function ToolHeader({isThinking:e,isTasteFile:t,tasteCategory:n,name:r,summaryMatch:o,expandedOutput:s,expandKey:a,input:i,output:l}){if(e){const e=estimateReasoningSeconds(i||l||"");return ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:sI},`Thought for ${e} second${1!==e?"s":""}`," "),!s&&ot.createElement(BracketWrap,{color:nI.DIM},`${a}+o to expand`))}if(t)return ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:oI.BADGE_BG,color:oI.BADGE_FG,bold:!0},XI)),ot.createElement(Qe,null," ","Using your taste"," ",n?"package of ":"packages",n&&ot.createElement(Qe,{bold:!0},n)));let c=r;return"READ[n]"===r&&o&&(c=`READ[${Number(o[1])}]`),ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:lI.BG,color:lI.FG,bold:!0},`${QI}${c}${QI}`))}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?ot.createElement(Qe,{color:nI.GRAY},"Running (",s,")"):"interrupted"===e||n===Uf?ot.createElement(Qe,{color:nI.GRAY,wrap:"wrap"},"Interrupted"):"error"===e||t?ot.createElement(Qe,{color:nI.RED,wrap:"wrap"},n," (",s,")"):ot.createElement(ot.Fragment,null,ot.createElement(Qe,{wrap:"wrap"},"Done"),ot.createElement(Qe,{color:nI.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:a,remainingLines:i}=truncateToVisualLines({output:o,maxVisualLines:"Question"===t?$c:Dc,maxChars:"Question"===t?1/0:Wc}),l=a&&"Question"!==t;return{text:s,isTruncated:l,remainingLines:i,truncationMsg:l?i>0?ot.createElement(BracketedText,{text:`... +${i} lines [${r}+o to expand]`,color:nI.DIM}):ot.createElement(BracketedText,{text:`... [${r}+o to expand]`,color:nI.DIM}):null}}function renderTruncatedOutput({output:e,name:t,expandedOutput:n,expandKey:r}){const{text:o,isTruncated:s,truncationMsg:a}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r});return s?ot.createElement(ot.Fragment,null,o,"\n",a):o}function renderEditFileDiff({input:e,metadata:t,expandedOutput:n,isPermissionDenied:r,output:o,expandKey:s}){const a=n?void 0:_c,{diffContent:i,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:a}),d=c-_c;return ot.createElement(Je,{flexDirection:"column"},i,l&&ot.createElement(Je,{marginTop:1},ot.createElement(BracketedText,{text:`… (${d} more ${1===d?"line":"lines"}) [${s}+o to expand]`,color:nI.DIM})),r&&o&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.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()),a=projectWriteFileContentView({filePath:e,content:t.content,totalLines:t.totalLines,expandedOutput:n,expandKey:r});return a.empty?ot.createElement(Qe,{color:nI.GRAY},"Created"," ",ot.createElement(Qe,{color:nI.WHITE,bold:!0},a.filePath)," ","(empty file)"):ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.GRAY},"Created"," ",ot.createElement(Qe,{color:nI.WHITE,bold:!0},a.filePath)," ","(",a.totalLinesLabel,")"),ot.createElement(Je,{marginTop:1,flexDirection:"column"},a.visibleLines.map(e=>ot.createElement(DiffRow,{key:e.lineNumber,background:iI.ADDED_BG,wrap:"truncate-end",prefix:ot.createElement(Qe,null,ot.createElement(Qe,{color:iI.ADDED_TEXT}," "+e.lineNumberLabel),ot.createElement(Qe,{color:iI.LINE_NUM},eD))},ot.createElement(Qe,{color:iI.ADDED_TEXT},highlightSyntax(e.text,o,s))))),a.isTruncated&&a.moreLinesLabel&&ot.createElement(Je,{marginTop:1},ot.createElement(BracketedText,{text:a.expandHint?`… (${a.moreLinesLabel}) ${a.expandHint}`:`… (${a.moreLinesLabel})`,color:nI.DIM})))}function renderOutputContent({isTodos:e,isThinking:t,isEditFile:n,isWriteFile:r,metadata:o,output:s,expandedOutput:a,isPermissionDenied:i,input:l,hasError:c,name:d,expandKey:u,showTreeConnector:m,closesFrame:p}){if(e)return formatTodosForDisplay(s);if(t){if(!a)return null;const e=l||s;return ot.createElement(Je,{width:"100%",flexDirection:"column"},ot.createElement(Qe,null," "),ot.createElement(Qe,{color:sI,wrap:"wrap",italic:!0},e))}const g=p?YI:JI;if(n&&"string"==typeof o?.oldValue&&"string"==typeof o?.newValue){const e=renderEditFileDiff({input:l,metadata:o,expandedOutput:a,isPermissionDenied:i,output:s,expandKey:u});return m?ot.createElement(Je,{columnGap:1},ot.createElement(Qe,{color:EI},g," "),e):e}if(r&&o&&"content"in o){const e=renderWriteFileContent({input:l,metadata:o,expandedOutput:a,expandKey:u});return m?ot.createElement(Je,{columnGap:1},ot.createElement(Qe,{color:EI},g," "),e):e}return m?renderTextWithLongConnector({output:s,name:d,expandedOutput:a,expandKey:u,hasError:c,closesFrame:p}):ot.createElement(Je,{width:"100%"},ot.createElement(Qe,{color:c?nI.RED:"",wrap:"wrap"},renderTruncatedOutput({output:s,name:d,expandedOutput:a,expandKey:u})))}function renderTextWithLongConnector({output:e,name:t,expandedOutput:n,expandKey:r,hasError:o,closesFrame:s}){const{text:a,isTruncated:i,truncationMsg:l}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}),c=o?nI.RED:void 0,d=buildTreeConnectors(a,{isTruncated:i,closesFrame:s}),u=s?YI:JI;return ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(Je,{columnGap:1,width:"100%"},ot.createElement(Qe,{color:EI},d),ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:c,wrap:"wrap"},a))),i&&ot.createElement(Je,{columnGap:1},ot.createElement(Qe,{color:EI},u," "),l))}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:a=!1}){const i="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=!i&&!l&&!m,f="ctrl",y=!0===s?.isAgent,S=computeDisplayInput({input:t,isAgent:y,isShell:"SHELL"===e,expandedOutput:a}),w=!i&&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||i&&t)&&!m&&(!y||x)&&(!u||o)),{symbolColor:A,symbol:R}=resolveSymbol({isPending:r,hasError:o,isThinking:i,isTodos:l,output:n}),O=s?.preHookLines,L=s?.postHookLines,D=Boolean(O?.length),N=Boolean(L?.length),$=Boolean(s?.hookOutcome),_=r&&!y&&!$,F=!$&&!_,U=I&&!N&&!$&&!_,j=D&&!I&&!N&&!$&&!_;return ot.createElement(Je,null,i&&ot.createElement(Qe,{color:A},R),ot.createElement(Je,{flexDirection:"column",marginLeft:i?1:0},ot.createElement(Je,null,ot.createElement(ToolHeader,{isThinking:i,isTasteFile:m,tasteCategory:p,name:M,summaryMatch:T,expandedOutput:a,expandKey:f,input:t,output:n}),w&&ot.createElement(Qe,null," ",formatToolInput({input:S,isShell:"SHELL"===e})),ot.createElement(ReadToolInlineSummaryRow,{summary:P}),E>0&&ot.createElement(Qe,{dimColor:!0},` ${ZL}${E>1?` ${E}`:""}`)),y&&("running"===v||n)&&ot.createElement(Je,{columnGap:1,marginLeft:h?1:0},h&&ot.createElement(Qe,{color:EI},YI," "),ot.createElement(AgentStatus,{agentStatus:v,hasError:o,output:n,elapsedSeconds:C,tokensUsed:k})),ot.createElement(HookLines,{lines:O,showTreeConnector:h,closesFrame:j}),I&&renderOutputWithRepairNotes({output:x?stripAgentUsageTrailer(n??""):n??"",isTodos:l,isThinking:i,isEditFile:c,isWriteFile:d,metadata:s,expandedOutput:a||x,isPermissionDenied:g,input:t,hasError:o,name:e,expandKey:f,showTreeConnector:h,closesFrame:U}),ot.createElement(HookLines,{lines:L,showTreeConnector:h,closesFrame:F}),ot.createElement(HookOutcome,{outcome:s?.hookOutcome,showTreeConnector:h}),_&&ot.createElement(Je,{columnGap:1,marginLeft:1},ot.createElement(Qe,{color:EI},YI," "),ot.createElement(Qe,{color:nI.GRAY},"Processing…"))))}function renderOutputWithRepairNotes({output:e,isTodos:t,isThinking:n,isEditFile:r,isWriteFile:o,metadata:s,expandedOutput:a,isPermissionDenied:i,input:l,hasError:c,name:d,expandKey:u,showTreeConnector:m,closesFrame:p}){const{body:g}=extractRepairNotes(e);return ot.createElement(Je,{marginLeft:m?1:0},renderOutputContent({isTodos:t,isThinking:n,isEditFile:r,isWriteFile:o,metadata:s,output:g,expandedOutput:a,isPermissionDenied:i,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 ot.createElement(Je,{flexDirection:"column",marginLeft:t?1:0},e.map((e,t)=>{const o=n&&t===r?YI:JI;return ot.createElement(Je,{key:t,columnGap:1},ot.createElement(Qe,{color:EI},o),ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},e)))}))}function HookOutcome({outcome:e,showTreeConnector:t}){if(!e)return null;const n="stop"===e.kind?nI.YELLOW:nI.RED;return ot.createElement(Je,{columnGap:1,marginLeft:t?1:0},ot.createElement(Qe,{color:EI},YI),ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{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 tD=createNodeRuntime(),nD=__name(({label:e,isSelected:t})=>e.includes("[shift+tab]")?ot.createElement(ot.Fragment,null,e.split("[shift+tab]")[0],ot.createElement(BracketWrap,{color:t?YA:JA,bold:!0},"shift+tab")):e.includes("(")?ot.createElement(ot.Fragment,null,e.split("(")[0],ot.createElement(Qe,{color:nI.GRAY},"(",e.split("(")[1])):e,"ChoiceLabel"),rD=__name(({request:e,onResponse:t,onEnableAutoAccept:n})=>{const[r]=at(0),[o,s]=at(1);lt(()=>{"edit"===e.action&&e.oldContent&&e.filePath&&resolveEditStartLine({runtime:tD,filePath:e.filePath,oldContent:e.oldContent}).then(e=>{void 0!==e&&s(e)}).catch(()=>{})},[e.filePath,e.oldContent,e.action]);const a=getPermissionChoicesForRisk({choices:zE,risk:e.risk}),i=__name(e=>{const r=a.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 ot.createElement(ZA,{title:`${d()}${"edit"===e.action?` ${c}`:""}`,footer:ot.createElement(QL,{hint:"↑/↓ navigate · enter select"})},"edit"===e.action&&e.oldContent&&e.newContent&&ot.createElement(Je,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c,marginLeft:0,startLine:o}).diffContent),e.risk&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{bold:!0,color:nI.RED,wrap:"wrap"},pt.warning," ",getRiskDisplay(e.risk))),ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{bold:!0},"Do you want to ",l()," ",ot.createElement(Qe,{color:YA},c),"?")),ot.createElement(SelectInput,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:i,initialIndex:r,indicatorComponent:WL,itemComponent:({label:e,isSelected:t})=>ot.createElement(HL,{isSelected:t},ot.createElement(nD,{label:e,isSelected:t}))}))},"PermissionPrompt");Ht(),Qx();var oD=db?"ctrl+y":"ctrl+e",sD=__name(({request:e,onResponse:t})=>{const[n]=at(0),[r,o]=at({phase:"idle"}),s=e.description??("done"===r.phase?r.explanation:void 0),a=void 0!==e.explain&&void 0===e.description&&"done"!==r.phase;tt((t,n)=>{a&&"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 i=getPermissionChoicesForRisk({choices:getShellPermissionChoices({command:e.command,...void 0!==e.args?{args:e.args}:{}}),risk:e.risk}),l=__name(e=>{const n=i.find(t=>t.value===e.value);n&&t(n)},"handleSelect");return ot.createElement(ZA,{title:"Execute Shell Command",subtitle:ot.createElement(Qe,{wrap:"wrap"},"Command Code needs to execute ",ot.createElement(Qe,{color:YA},getCommandDisplay(e)),"."),footer:ot.createElement(QL,{hint:a?`↑/↓ navigate · enter select · ${oD} explain`:"↑/↓ navigate · enter select"})},e.risk&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{bold:!0,color:nI.RED,wrap:"wrap"},pt.warning," ",getRiskDisplay(e.risk))),e.workingDirectory&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.GRAY},"Working directory: ",e.workingDirectory)),s&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM,italic:!0},s)),a&&"idle"===r.phase&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM,italic:!0},"Press"," ",ot.createElement(BracketWrap,{color:nI.DIM,bold:!0},oD)," ","to explain this command")),"loading"===r.phase&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM,italic:!0},ot.createElement(vt,{type:"dots"})," Explaining this command…")),"failed"===r.phase&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM,italic:!0},"Couldn't generate an explanation — press"," ",oD," to retry")),ot.createElement(SelectInput,{items:i.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:n,indicatorComponent:WL,itemComponent:({label:e,isSelected:t})=>ot.createElement(HL,{isSelected:t},e.includes("[shift+tab]")?ot.createElement(ot.Fragment,null,e.split("[shift+tab]")[0],ot.createElement(BracketWrap,{color:t?YA:JA,bold:!0},"shift+tab")):e)}))},"ShellPermissionPrompt");function handlePermissionResponse({choice:e,resolve:t,setPendingPermission:n,respondToPrompt:r,setStatus:o,permissionMode:s,showHintMessage:a,allowedStatus:i,deniedStatus:l}){r(e);const c="no"!==e.value;t(c),n(null),c?(o(i),"default"===s&&a("Use shift+tab to enable auto-accept")):o(l)}__name(handlePermissionResponse,"handlePermissionResponse");var aD=st(__name(function PermissionView2({pendingPermission:e,permissionMode:t,setPendingPermission:n,setStatus:r,respondToPrompt:o,showHintMessage:s,handleEnableAutoAccept:a}){const i={resolve:e.resolve,setPendingPermission:n,respondToPrompt:o,setStatus:r,permissionMode:t,showHintMessage:s};if("shell_command"===e.toolName){const t=e.params;return ot.createElement(Je,{marginY:1},ot.createElement(sD,{request:t,onResponse:e=>handlePermissionResponse({...i,choice:e,allowedStatus:"Shell command allowed",deniedStatus:"Shell command denied"})}))}if("kill_shell"===e.toolName){const t=buildKillShellPermissionRequest(e.params);return ot.createElement(Je,{marginY:1},ot.createElement(sD,{request:t,onResponse:e=>handlePermissionResponse({...i,choice:e,allowedStatus:"Process termination allowed",deniedStatus:"Process termination denied"})}))}if(isGenericToolRequest(e.params)){const t=e.params;return ot.createElement(Je,{marginY:1},ot.createElement(XL,{request:t,onResponse:e=>handlePermissionResponse({...i,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 ot.createElement(Je,{marginY:1},ot.createElement(rD,{request:l,onResponse:e=>handlePermissionResponse({...i,choice:e,allowedStatus:"File operation allowed",deniedStatus:"File operation denied"}),onEnableAutoAccept:a}))},"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}=Ze(),s=trimPlanMarkdown(e,getCollapsedPlanMaxLines(o?.rows)),a=s.hiddenLineCount>0,i=r?e:s.visible,l=1!==s.hiddenLineCount?"s":"",c=`… +${s.hiddenLineCount} more line${l} · ctrl+o to expand`;return ot.createElement(ZA,{title:"Plan",titleSuffix:n?` · ${t.basename(n)}`:void 0,gapAfterHeader:!1,hint:a?r?"ctrl+o to collapse":c:void 0},ot.createElement(Je,{marginTop:1},ot.createElement(Markdown,null,i)))}__name(isGenericToolRequest,"isGenericToolRequest"),__name(isFileEditRequest,"isFileEditRequest"),Ht(),Qx(),Ht(),Qx(),__name(PlanPanel,"PlanPanel"),Ht(),Qx();var iD=__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 `,a="─".repeat(Math.max(0,70-s.length));return ot.createElement(Je,{flexDirection:"column",marginTop:1,paddingLeft:4},ot.createElement(Qe,{italic:!0,color:nI.DIM},"Preview"),ot.createElement(Qe,{color:nI.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 ot.createElement(Qe,{key:t},ot.createElement(Qe,{color:nI.DIM},"│ "),ot.createElement(Qe,{color:nI.GRAY},n),ot.createElement(Qe,{color:nI.DIM},`${r} │`))}),r>0?ot.createElement(Qe,{color:nI.YELLOW},`├${s}${a}┤`):null,ot.createElement(Qe,{color:nI.DIM},`└${o}┘`))},"OptionPreview"),lD=[{label:"1. Submit",value:"submit"},{label:"2. Cancel",value:"cancel"}],cD=__name(({checked:e})=>e?ot.createElement(Qe,{color:nI.GREEN},"[",pt.tick,"] "):ot.createElement(Qe,{color:nI.DIM},"[ ] "),"MultiSelectCheckbox"),dD=__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"),uD=__name((e,t)=>{const n=new Set(e);return n.has(t)?(n.delete(t),n):(n.add(t),n)},"toggleLabel"),mD=__name((e,t)=>e?{indicator:pt.bullet,color:YA}:t?{indicator:pt.tick,color:nI.GREEN}:{indicator:pt.circle,color:nI.GRAY},"getTabMarker"),pD=__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,a)=>{const i=a===t&&!r,l=n.has(a),{indicator:c,color:d}=mD(i,l);s.push(ot.createElement(Qe,{key:a},ot.createElement(Qe,{color:d},c),ot.createElement(Qe,{color:i?YA:void 0}," ",o.header),a<e.length-1?ot.createElement(Qe,{color:nI.DIM}," | "):null))}),!o){const e=r;s.push(ot.createElement(Qe,{key:"review"},ot.createElement(Qe,{color:nI.DIM}," | "),ot.createElement(Qe,{color:e?YA:nI.GRAY},e?pt.bullet:pt.circle),ot.createElement(Qe,{color:e?YA:void 0,bold:e}," ","Review")))}return ot.createElement(Je,null,s)},"TabIndicator"),gD=__name(({questions:e,onResponse:t,hideCustomInput:n=!1,compact:r=!1})=>{const[o,s]=at(0),[a,i]=at(new Map),l=it(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=it(null);null===P.current&&(P.current=new Map);const M=it(null);null===M.current&&(M.current=new Map);const[x,I]=at(!1),[A,R]=at(""),[,O]=at(0),L=e[o],D=L?.multiSelect??!1,N=a.get(o),$=L?[...L.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description,...void 0!==e.preview?{preview:e.preview}:{}}))]:[],_=$.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),F=new Map(_.map((e,t)=>[e.label,$[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(!N||0===N.length)return 0;const e=N[0],t=L.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),H=__name(e=>{if(f)return;if(D){const t=dD(e.value,L.options.length-1);if(null===t)return;const n=L.options[t]?.label||"";return void p(e=>uD(e,n))}const t=dD(e.value,L.options.length-1);if(null===t)return;y(!0);const n=L.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(L.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(i(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 a=e.findIndex((e,t)=>!r.has(t));-1!==a&&(j(a),s(a)),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(),a=e.multiSelect||1!==n.length?void 0:e.options.find(e=>e.label===n[0]);return{questionIndex:t,selectedOptions:o,...a?.preview?{preview:a.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}]),O(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),i(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=dD(g.value,L.options.length-1);if(null===e)return;const t=L.options[e]?.label||"";p(e=>uD(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),i(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(tt((e,t)=>{if(x)t.escape?J():t.ctrl&&"v"===e?Q():t.ctrl&&"g"===e&&X(A,R);else if(t.ctrl&&"v"===e&&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()}}),!L&&!S)return null;if(S)return ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(RI,{dividerColor:qA}),ot.createElement(Je,{marginBottom:1},ot.createElement(pD,{questions:e,currentIndex:e.length,answeredQuestions:new Set(a.keys()),isReviewPage:!0})),e.some((e,t)=>!a.get(t)?.length)&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.YELLOW},"⚠ You have not answered all questions")),e.map((e,t)=>ot.createElement(Je,{key:t,marginBottom:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},t+1,". ",e.question),ot.createElement(Qe,{color:nI.GREEN}," ",a.get(t)?.join(", ")||"No answer"))),ot.createElement(SelectInput,{items:lD,onSelect:B,initialIndex:0,indicatorComponent:WL,itemComponent:GL}),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{italic:!0,color:nI.DIM},pt.arrowLeft," to go back and edit")));const se=r&&1===e.length;return ot.createElement(Je,{flexDirection:"column",width:"100%"},!se&&ot.createElement(RI,{dividerColor:qA}),!se&&ot.createElement(Je,{marginBottom:1},ot.createElement(pD,{questions:e,currentIndex:o,answeredQuestions:new Set(a.keys()),isReviewPage:!1,hideReview:n})),ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{bold:!0,color:zA},L.question)),v||E||x?ot.createElement(Je,{flexDirection:"column"},_.map((e,t)=>{const n=F.get(e.label),r=D&&n&&m.has(n.label),o=!D&&n&&N?.includes(n.label),s=r||o;return ot.createElement(Je,{key:e.value,flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,null," "),ot.createElement(HL,{isActive:s,idleColor:nI.GRAY}," ",t+1,"."," "),D&&ot.createElement(cD,{checked:s}),ot.createElement(HL,{isActive:s,idleColor:nI.GRAY},n?.label||""),!D&&s&&ot.createElement(VL,null)),n?.description&&ot.createElement(Je,null,ot.createElement(Qe,null," "),ot.createElement(zL,{indent:D?7:4},n.description)))})):ot.createElement(SelectInput,{key:`${o}-${C??"default"}`,items:_,initialIndex:C??W(),onSelect:H,onHighlight:h,indicatorComponent:WL,itemComponent:({label:e,isSelected:t})=>{const n=F.get(e),r=D&&n&&m.has(n.label),o=!D&&n&&N?.includes(n.label),s=r||o,a=e.match(/^\s*(\d+)\.\s*(.*)$/),i=a?.[1]||"",l=a?.[2]||e;return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(HL,{isSelected:t,isActive:s}," ",i,"."," "),D&&ot.createElement(cD,{checked:s}),ot.createElement(HL,{isSelected:t,isActive:s},l),!D&&s&&ot.createElement(VL,null)),n?.description&&ot.createElement(zL,{indent:D?7:4},n.description))}}),!v&&!E&&(()=>{const e=(g?F.get(g.label):void 0)??$[C??W()];return e?.preview?ot.createElement(iD,{preview:e.preview}):null})(),!n&&ot.createElement(Je,null,ot.createElement(WL,{isSelected:v}),ot.createElement(HL,{isSelected:v}," ",_.length+1,"."," "),D&&ot.createElement(cD,{checked:m.has(d.trim())}),ot.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?ot.createElement(Je,null,ot.createElement(WL,{isSelected:!0}),ot.createElement(HL,{isSelected:!0}," ","notes:"," "),ot.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?ot.createElement(Je,null,ot.createElement(Qe,{italic:!0,color:nI.DIM}," ","notes: ",e)):null})(),(M.current?.get(o)??[]).map((e,t)=>ot.createElement(Je,{key:t},ot.createElement(Qe,{color:nI.DIM}," ","[Image #",t+1," attached —"," ",e.mediaType,"]"))),D&&ot.createElement(Je,null,ot.createElement(WL,{isSelected:E}),ot.createElement(HL,{isSelected:E}," ",o===e.length-1?"Submit":"Next")),e.length>1&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{italic:!0,color:nI.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[a,i]=at(!1),l=e.params.planContent;return tt((e,t)=>{l&&getIsExpandToolShortcut(t,e)&&i(e=>!e)}),ot.createElement(Je,{marginY:1,flexDirection:"column"},l&&ot.createElement(Je,{marginBottom:1},ot.createElement(PlanPanel,{content:l,filePath:e.params.planFilePath,expanded:a})),ot.createElement(gD,{questions:e.params.questions,hideCustomInput:e.params.hideCustomInput,compact:e.params.compact,onResponse:a=>{const i=resolvePlanModeAnswerTransition({answer:a.answers[0]?.selectedOptions[0]||"",exitPlanMode:e.params.exitPlanMode,enterPlanMode:e.params.enterPlanMode,dangerouslySkipPermissions:n});i&&t(i),e.resolve(a),r(null),o("Answers submitted"),hardResetForResize(),s(e=>e+1)}}))}__name(QuestionView,"QuestionView"),Ht(),Qx();var hD="__skip__",fD=__name(({suggestion:e,onSelect:t,onClose:n})=>{const{completedMode:r,primary:o,secondary:s,description:a}=e,i=[...o.map(e=>({label:e,value:e,isPrimary:!0})),...s.map(e=>({label:e,value:e,isPrimary:!1})),{label:"skip",value:hD,isPrimary:!1}],l=new Map(i.map(e=>[e.label,e]));tt((e,t)=>{t.escape&&n()});const c=__name(e=>{e.value!==hD?(t(e.value),n()):n()},"handleSelect");return ot.createElement(ZA,{title:`/design ${r} complete`,titleSuffix:` · ${a}`,hint:"Enter to run · Esc to dismiss"},ot.createElement(SelectInput,{items:i,onSelect:c,indicatorComponent:YL,itemComponent:({label:e,isSelected:t})=>{const n=l.get(e),r=n?.value===hD,o=n?.isPrimary??!1,s=r?"run /design manually":Yh[e]??"";return ot.createElement(Je,{flexDirection:"column"},ot.createElement(KL,{isSelected:t,idleColor:o?nI.WHITE:nI.DIM},r?" skip ":` /design ${e} `),s&&ot.createElement(KL,{isSelected:t,idleColor:nI.DIM,bold:!1},` ${s} `))}}))},"DesignModeSelector");function getUsageToneColor(e){return"danger"===e?nI.RED:"warning"===e?nI.YELLOW:nI.GREEN}function getDistanceToneColor(e){return"danger"===e?nI.RED:"warning"===e?nI.YELLOW:nI.GRAY}function ContextProgress({view:e,progressBarWidth:t}){const n=getUsageToneColor(e.tone),r=buildBlockBar({percentage:e.percentage,width:t});return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{marginBottom:1},ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:nI.BLUE,color:"#f4f4f4",bold:!0},`${QI}CONTEXT${QI}`)),ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:nI.GRAY},e.modelLabel)),ot.createElement(Je,null,ot.createElement(Qe,{color:n},r.filled),ot.createElement(Qe,{color:pI},r.empty),ot.createElement(Qe,{bold:!0,color:n},` ${e.percentageLabel}`)),ot.createElement(Je,null,ot.createElement(Qe,null,e.tokensUsedLabel),ot.createElement(Qe,{color:nI.GRAY},` / ${e.tokenLimitLabel}`),ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:n},e.tokensRemainingLabel),ot.createElement(Qe,{color:nI.GRAY}," remaining"),e.isEstimated&&ot.createElement(Qe,{color:nI.DIM}," (estimated)")))}function CompactionDistance({view:e}){if(!e)return null;const t=getDistanceToneColor(e.tone);return ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:t},e.tokensAwayLabel),ot.createElement(Qe,{color:nI.DIM},e.label))}function BreakdownRow({item:e,labelWidth:t}){return ot.createElement(Je,null,ot.createElement(Qe,null,e.name.padEnd(t)),ot.createElement(Qe,{bold:!0},e.paddedValue),ot.createElement(Qe,{color:nI.GRAY}," tokens"),e.detail&&ot.createElement(Qe,{color:nI.DIM},` · ${e.detail}`))}function ContextBreakdown({view:e,labelWidth:t}){return 0===e.rows.length?null:ot.createElement(Je,{flexDirection:"column",marginTop:1},e.rows.map(e=>ot.createElement(BreakdownRow,{key:e.name,item:e,labelWidth:t})))}function ContextTips({tips:e}){return 0===e.length?null:ot.createElement(Je,{flexDirection:"column",marginTop:1},e.map(e=>ot.createElement(Je,{key:e},ot.createElement(Qe,{color:nI.CYAN},pt.pointer),ot.createElement(Qe,{color:nI.GRAY}," ",e))))}function ContextMessage({analysis:e}){const t=projectContextView(e,{terminalWidth:useTerminalWidth(),modelDisplayName:getModelDisplayName(e.model)});return ot.createElement(Je,{flexDirection:"column",paddingTop:1},ot.createElement(ContextProgress,{view:t.progress,progressBarWidth:t.layout.progressBarWidth}),ot.createElement(CompactionDistance,{view:t.compactionDistance}),ot.createElement(ContextBreakdown,{view:t.breakdown,labelWidth:t.layout.labelWidth}),ot.createElement(ContextTips,{tips:t.tips}))}function ContextConfigView({staticKey:e,sessionId:t,onClose:n,setInput:r}){const[o,s]=at(null),[a,i]=at(null);return lt(()=>{let e=!0;return __name(async()=>{const n=$O(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&&i("Failed to analyze context.")}else e&&i("No active conversation. Start chatting first.")},"load")(),()=>{e=!1}},[t]),tt((e,t)=>{t.escape&&(r(""),n())}),ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(ContextBody,{error:a,analysis:o}),ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Esc")," to return to conversation"))))}function ContextBody({error:e,analysis:t}){return e?ot.createElement(ZA,{title:"Context",gapAfterHeader:!1},ot.createElement(Qe,{color:nI.DIM},e)):t?ot.createElement(ContextMessage,{analysis:t}):ot.createElement(ZA,{title:"Context",gapAfterHeader:!1},ot.createElement(VO,{label:"Loading context analysis"}))}Ht(),Qx(),Ht(),Qx(),__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"),Ht(),Ht(),Qx(),Ht(),Qx();var yD="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?$O(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 SD=__name(({label:e,value:t,valueColor:n,dimValue:r})=>ot.createElement(Je,null,ot.createElement(Qe,{dimColor:!0},`${e}:`.padEnd(14)),r?ot.createElement(Qe,{dimColor:!0},t):ot.createElement(Qe,{color:n},t)),"Row");function StatusMessage({statusData:e}){const t=projectStatusView(e,{profileBaseUrl:"https://commandcode.ai"}),n=t.account.authenticated?pt.tick:pt.cross,r=t.account.authenticated?nI.WHITE:uI.ERROR;return ot.createElement(Je,{flexDirection:"column",paddingX:0},ot.createElement(Je,null,ot.createElement(Qe,{color:rI,bold:!0},"Command Code"," "),ot.createElement(Qe,{dimColor:!0},t.versionText)),ot.createElement(Je,null,ot.createElement(Qe,{dimColor:!0},"Visit "),ot.createElement(BI,{url:yD,text:yD,color:nI.CYAN}),ot.createElement(Qe,{dimColor:!0}," for usage and billing")),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{dimColor:!0},"Account:".padEnd(14)),t.account.username&&t.account.profileUrl?ot.createElement(ot.Fragment,null,ot.createElement(BI,{url:t.account.profileUrl,text:t.account.label,color:nI.CYAN}),ot.createElement(Qe,{color:r}," ",n)):t.account.authenticated?ot.createElement(ot.Fragment,null,ot.createElement(Qe,null,t.account.label),ot.createElement(Qe,{color:r}," ",n)):ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:uI.WARNING},t.account.label),ot.createElement(Qe,{color:r}," ",n),ot.createElement(Qe,{dimColor:!0}," — run "),ot.createElement(Qe,{bold:!0},t.account.loginHint))),ot.createElement(SD,{label:"Model",value:t.model.value}),ot.createElement(SD,{label:"Branch",value:t.branch.value,dimValue:t.branch.dim}),t.worktree?ot.createElement(SD,{label:"Worktree",value:t.worktree.value}):null,t.repository?ot.createElement(Je,null,ot.createElement(Qe,{dimColor:!0},"Repository:".padEnd(14)),ot.createElement(BI,{url:t.repository.url,text:t.repository.text,color:nI.CYAN}),t.pullRequest?ot.createElement(ot.Fragment,null,ot.createElement(Qe,{dimColor:!0}," · "),ot.createElement(BI,{url:t.pullRequest.url,text:t.pullRequest.text,color:t.pullRequest.open?nI.CYAN:nI.GRAY}),ot.createElement(Qe,{dimColor:!0}," ","(",t.pullRequest.stateLabel,")")):null):t.pullRequest?ot.createElement(Je,null,ot.createElement(Qe,{dimColor:!0},"Pull Request:".padEnd(14)),ot.createElement(BI,{url:t.pullRequest.url,text:t.pullRequest.text,color:t.pullRequest.open?nI.CYAN:nI.GRAY}),ot.createElement(Qe,{dimColor:!0}," (",t.pullRequest.stateLabel,")")):null,ot.createElement(SD,{label:"Taste",value:t.taste.value,dimValue:t.taste.dim}),ot.createElement(SD,{label:"Directory",value:t.directory.value}),ot.createElement(SD,{label:"Skills",value:t.skills.value,dimValue:t.skills.dim}),ot.createElement(SD,{label:"Agents",value:t.agents.value,dimValue:t.agents.dim}),ot.createElement(SD,{label:"System",value:t.system.value}),t.proxy?ot.createElement(SD,{label:"Proxy",value:t.proxy.value}):null)}function StatusBody({state:e}){return"ready"===e.phase?ot.createElement(StatusMessage,{statusData:e.data}):"error"===e.phase?ot.createElement(Qe,{dimColor:!0},"Could not load status: ",e.message):ot.createElement(Qe,{dimColor:!0},"Gathering status…")}function StatusConfigView({staticKey:e,sessionId:t,onClose:n,setInput:r}){const[o,s]=at({phase:"loading"});return lt(()=>{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]),tt((e,t)=>{t.escape&&(r(""),n())}),ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(StatusBody,{state:o}),ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Esc")," to return to conversation"))))}__name(StatusMessage,"StatusMessage"),__name(StatusBody,"StatusBody"),__name(StatusConfigView,"StatusConfigView"),Ht(),Qx(),Qx(),Ht(),Qx();var{addDirectory:wD,formatDirectoryForDisplay:vD,getAdditionalDirectories:kD,removeAdditionalDirectory:CD}=yf,bD=__name(({onClose:e})=>{const[t,n]=at(""),[r,o]=at(null),[s,a]=at([]),[i,l]=at(()=>kD()),[c,d]=at(()=>({zone:"input",suggestionIndex:0,activeDirIndex:0})),[u,m]=at(0);lt(()=>{a(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),m(0)},[t]),lt(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const p=__name(e=>{const t=wD(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(kD()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),g=__name(e=>{if(!CD(e))return o({tone:"error",text:`${vD(e)} is no longer in workspace scope`}),void l(kD());o({tone:"success",text:`Removed ${vD(e)} from directory scope`}),l(kD()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");tt((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&&i[c.activeDirIndex])g(i[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:i.length})):r.upArrow&&d(e=>moveAddDirFocusUp(e,{suggestionCount:s.length,activeDirCount:i.length}))}}}),lt(()=>{"suggestions"===c.zone&&m(e=>getAdjustedSuggestionOffset({selectedIndex:c.suggestionIndex,currentOffset:e,maxVisible:jx,totalSuggestions:s.length}))},[c,s.length]),lt(()=>{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>=i.length?{...e,zone:"input",activeDirIndex:Math.max(0,i.length-1)}:e)},[s.length,i.length]);const h=s.slice(u,u+jx),f=getAddDirFooterText({focusZone:c.zone});return ot.createElement(ZA,{title:"Add directory to workspace",subtitle:ot.createElement(Qe,{color:nI.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),footer:ot.createElement(Qe,{italic:!0,color:nI.DIM},ot.createElement(BracketedText,{text:f,color:nI.DIM})),gapAfterHeader:!1},ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.GRAY},"Added directories"),0===i.length?ot.createElement(Qe,{color:nI.GRAY}," None yet"):i.map((e,t)=>{const n="active-dir"===c.zone&&c.activeDirIndex===t;return ot.createElement(Je,{key:e},ot.createElement(Qe,null," "),ot.createElement(WL,{isSelected:n}),ot.createElement(HL,{isSelected:n,isActive:!0}," ",vD(e)))})),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{bold:!0,color:nI.WHITE},"Path")),ot.createElement(Je,null,ot.createElement(TextInput,{value:t,focus:"input"===c.zone,prefix:`${"input"===c.zone?pt.pointer:" "} `,prefixColor:"input"===c.zone?YA:nI.GRAY,onChange:e=>{n(e),o(null)},onSubmit:p})),!t&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:{error:nI.RED,warning:nI.YELLOW,success:nI.GREEN}[r.tone]},r.text)),s.length>0&&ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Qe,{color:nI.GRAY},"Suggestions"),h.map((e,t)=>{const n=u+t,r="suggestions"===c.zone&&c.suggestionIndex===n;return ot.createElement(Je,{key:e},ot.createElement(Qe,null," "),ot.createElement(WL,{isSelected:r}),ot.createElement(HL,{isSelected:r,idleColor:nI.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")}}Ht(),Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),Ht(),Ht(),Qx(),Ht(),Qx(),__name(createBillingTransport,"createBillingTransport");var ED=null;function getBilling(){return ED||(ED=createBilling({transport:createBillingTransport()})),ED}function getCachedBillingContext(){return ED?.getCached()??null}function getBillingContext(){return getBilling().get()}function prefetchBillingContext(){getBilling().prefetch()}function invalidateBillingContext(){ED=null}function buildLaneModelPickerGroups(){const e=filterModelGroupsByRegisteredModules(VR).filter(e=>e.providerId!==ro.COMMAND);return[...buildModelPickerGroups({normalModeGroups:zR}),...e,...buildCustomModelPickerGroups()]}function buildCatalogModelPickerGroups(){return[...buildModelPickerGroups({normalModeGroups:zR}),...buildCustomModelPickerGroups()]}function laneServesModel(e){if(e.activeLane===ro.COMMAND)return!0;const t=_o[e.activeLane]?.supportedModelProviders;if(!t)return!0;const n=Object.values(OR).find(t=>t.id===e.modelId);return!n||laneSupportsModel(t,n)}function laneModelCount(e){return e.laneId===ro.COMMAND?zR.reduce((e,t)=>e+t.models.length,0):VR.find(t=>t.providerId===e.laneId)?.models.length??0}function defaultModelForLane(e){const t=filterModelGroupsByRegisteredModules(VR),n=t.filter(t=>t.providerId===e.activeLane),r=n.length>0?n:t.filter(e=>e.providerId===ro.COMMAND);return r[0]?.models[0]?.id}function useCustomModelsReady(e){const[t,n]=at(!1);return lt(()=>{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"),Ht(),Qx(),__name(buildLaneModelPickerGroups,"buildLaneModelPickerGroups"),__name(buildCatalogModelPickerGroups,"buildCatalogModelPickerGroups"),__name(laneServesModel,"laneServesModel"),__name(laneModelCount,"laneModelCount"),__name(defaultModelForLane,"defaultModelForLane"),Ht(),__name(useCustomModelsReady,"useCustomModelsReady"),Ht(),Qx();var TD=__name((e,t)=>{const n=t&&e.id===BR?" (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,TD(n,t)+2),32)}__name(getModelLabelColumnWidth,"getModelLabelColumnWidth");var PD=__name(({model:e,providerId:t,isHighlighted:n,isCurrent:r,showProviderLabel:o,showDefaultBadge:s=!0,labelColumnWidth:a=32})=>{const i=_o[t],l=o??i?.showProviderLabelInSelector??!1,c=e.vendorLabel??WR[e.provider],d=s&&e.id===BR,u="free"===e.badge,m=d?`${e.label} (default)`:e.label,p=u?" (FREE)":"",g=" ".repeat(Math.max(2,a-m.length-p.length)),h=n?TI:void 0,f=e.description?`${l?`${c} · `:""}${e.description}`:"",y=useTerminalWidth()>=a+38&&f;return ot.createElement(Je,null,ot.createElement(Qe,{backgroundColor:h,color:r?nI.GREEN:nI.WHITE,bold:r},m),u&&ot.createElement(Qe,{backgroundColor:h,color:nI.GREEN,bold:!0},p),y&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{backgroundColor:h},g),ot.createElement(Qe,{backgroundColor:h,color:nI.DIM},f)),ot.createElement(Qe,{backgroundColor:h,color:nI.GREEN},r?` ${pt.tick} `:" "))},"ModelRow");Ht(),Qx();var MD=__name((e,t)=>`${e+1}. ${t}`,"labelText"),xD=__name(({modelLabel:e,supportedEfforts:t,currentEffort:n,onSelect:r,onCancel:o})=>{const s=ct(()=>buildEffortPickerRows(t),[t]),a=ct(()=>{if(void 0===n)return 0;const e=s.findIndex(e=>e.value===n);return e>=0?e:0},[s,n]),i=ct(()=>Math.max(...s.map((e,t)=>MD(t,e.label).length))+4,[s]),{cursor:l}=useListNavigation({items:s,onSelect:__name(e=>r(e.value),"onSelect"),onCancel:o,initialIndex:a,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,selectByNumber:!0});return ot.createElement(ZA,{title:`Select reasoning effort for ${e}`,hint:"↑/↓ navigate · enter to select · esc to go back"},ot.createElement(Je,{flexDirection:"column"},s.map((e,t)=>{const r=t===l,o=e.value===n;return ot.createElement(Je,{key:e.label},ot.createElement(Qe,{color:r||!o?nI.WHITE:nI.GREEN,backgroundColor:r?TI:void 0,bold:r||o},MD(t,e.label).padEnd(i)),ot.createElement(Qe,{color:r?nI.WHITE:nI.DIM,backgroundColor:r?TI:void 0},e.description," "),o&&ot.createElement(Qe,{color:nI.GREEN}," ",pt.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}]:[]})}Ht(),Qx(),__name(windowModelGroups,"windowModelGroups");var ID=__name(({onSelect:e,onCancel:t,currentModel:n,currentProvider:r,planId:o,purchasedCredits:s=0,freeCredits:a=0,refreshBanner:i,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??ro.COMMAND,v=useCustomModelsReady(d),k=ct(()=>buildLaneModelPickerGroups(),[v]),C=ct(()=>filterModelPickerGroupsByAuth({groups:k,authResolvedProviders:y,unauthedProviders:h}),[k,y,h]),b=ct(()=>filterModelPickerGroups(C,u),[C,u]),E=ct(()=>{const e=new Set(C.map(e=>`${e.providerId}:${e.label}`));return k.filter(t=>!e.has(`${t.providerId}:${t.label}`))},[k,C]),T=ct(()=>filterModelPickerGroups(E,u),[E,u]),P=ct(()=>flattenModelPickerGroups(b),[b]),M=ct(()=>{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=ct(()=>getModelLabelColumnWidth(k.flatMap(e=>e.models)),[k]),[I,A]=at(0),R=useTerminalHeight()-1,O=Math.max(4,R-16-2*b.length),L=void 0!==o,D=ct(()=>L?null:getCachedBillingContext(),[L]),[N,$]=at(D),[_,F]=at(!L&&!D);lt(()=>{if(L)return;if(N)return;let e=!0;return getBillingContext().then(t=>{e&&($(t),F(!1))}),()=>{e=!1}},[L,N]);const U=!L&&!0===N?.fetchFailed,j=L?o:N?.planId??null,B=L?s:N?.purchasedCredits??0,W=L?a:N?.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")});lt(()=>{A(e=>clampScrollOffset({cursor:q,total:P.length,maxVisible:O,currentOffset:e}))},[q,P.length,O]);const Q=it(!1),X=__name(t=>{if(!z||Q.current)return;Q.current=!0;const{model:r,providerId:o}=z,s=getReasoningEffort(r.id),a=t!==s,l=r.id===n;(async()=>{try{a&&(await setReasoningEffort({modelId:r.id,effort:t}),l&&i?.())}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(lt(()=>{if(_)return;if(Y!==jE)return;const e=P[q];J(e&&!U?getModelPickerAccessError({model:e.model,billing:{planId:j,purchasedCredits:B,freeCredits:W}}):null)},[_,U,Y,J,P,q,j,B,W]),lt(()=>{(async()=>{const e=await getConfiguredProvider();e&&e!==ro.COMMAND&&g(e)})()},[]),lt(()=>{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 ot.createElement(xD,{modelLabel:z.model.label,supportedEfforts:e,currentEffort:getReasoningEffort(z.model.id),onSelect:X,onCancel:Z})}const ee=I,te=I+O,ne=windowModelGroups({groups:b,firstSectionBase:0,windowStart:ee,windowEnd:te}),re=P.length>O;return ot.createElement(ZA,{title:"Select model",subtitle:l??"Pick a model - Command Code, your signed-in lanes, and custom providers. Sets the default for new sessions; other open sessions are unaffected.",footer:ot.createElement(Qe,{italic:!0,color:nI.DIM},"type to search · ↑/↓ navigate · shift+↑/↓ jump provider · enter to select",u?" · esc to clear":" · esc to cancel")},ot.createElement(Je,{marginBottom:2,flexDirection:"column",width:"100%"},ot.createElement(VI,{query:u,resultCount:u?P.length:void 0,placeholder:"Type to search models..."})),0===P.length?ot.createElement(Je,{marginY:1},ot.createElement(Qe,{color:nI.GRAY},T.length>0?"Provider login required. Run /connect to authenticate.":`No models match "${u}"`)):ot.createElement(Je,{flexDirection:"column"},ne.map(({group:e,groupWindow:t},r)=>ot.createElement(Je,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:r>0?1:0},ot.createElement(Qe,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>ot.createElement(PD,{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&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",ee+1,"–",Math.min(te,P.length)," of ",P.length,ee>0?" · ↑ more":"",te<P.length?" · ↓ more":"")),Y&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.GRAY},Y)))},"ModelSelector"),AD=__name(e=>{if(!e)return"Inherit from session";for(const t of zR)for(const n of t.models)if(n.id===e)return n.label;return e},"agentModelLabel"),RD=[{value:"inherit",label:"1. Inherit from session (default)"},{value:"pick",label:"2. Pick a specific model"}],OD=__name(({selectedModel:e,onSelect:t})=>{const[n,r]=at("choice"),[o,s]=at(e?1:0);return tt((e,n)=>{if(n.upArrow)s(e=>Math.max(0,e-1));else if(n.downArrow)s(e=>Math.min(RD.length-1,e+1));else if("1"!==e)if("2"!==e){if(n.return){const e=RD[o];if(!e)return;"inherit"===e.value?t(null):r("picker")}}else r("picker");else t(null)},{isActive:"choice"===n}),"picker"===n?ot.createElement(ID,{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}):ot.createElement(Je,{flexDirection:"column"},RD.map((e,t)=>{const n=t===o;return ot.createElement(Je,{key:e.value},ot.createElement(Qe,{color:n?nI.WHITE:nI.GRAY,backgroundColor:n?TI:void 0,bold:n},n?">":" "," ",e.label))}),e&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.GRAY},"Currently pinned: ",AD(e))),ot.createElement(VA,{hints:["↑↓ navigate","Enter to select","Inherit follows /model; pinned agents keep their own model and prompt cache"]}))},"AgentModelSelector"),LD=__name(({config:e,onSaveComplete:t,viewOnly:n=!1})=>{const[r,o]=at("idle"),[s,a]=at(""),i=__name(async()=>{if(!e.location||!e.agentType||!e.sysPrompt)return o("error"),void a("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:py,model:e.model}),t(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");tt((e,t)=>{n||!t.return||"idle"!==r&&"error"!==r||i()});const l=formatAgentToolAccessForDisplay({access:[...e.selectedTools],allToolNames:py,displayNameByToolName:fy,displayNameToToolName:yy}),c=e.location&&e.agentType?getAgentDisplayPath({location:e.location,name:e.agentType}):"";return ot.createElement(Je,{flexDirection:"column",gap:1},ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{gap:1},ot.createElement(Qe,{color:nI.WHITE,bold:!0},"Name:"),ot.createElement(Qe,{color:nI.GRAY},e.agentType)),ot.createElement(Je,{gap:1},ot.createElement(Qe,{color:nI.WHITE,bold:!0},"Location:"),ot.createElement(Qe,{color:nI.GRAY},c)),ot.createElement(Je,{gap:1},ot.createElement(Qe,{color:nI.WHITE,bold:!0},"Tools:"),ot.createElement(Qe,{color:nI.GRAY},l)),ot.createElement(Je,{gap:1},ot.createElement(Qe,{color:nI.WHITE,bold:!0},"Model:"),ot.createElement(Qe,{color:nI.GRAY},AD(e.model)))),ot.createElement(Je,{gap:1},ot.createElement(Qe,{color:nI.WHITE,bold:!0},"Description"),ot.createElement(Qe,{color:nI.GRAY},"(Tells ","Command Code"," when to use this agent):")),ot.createElement(Qe,{color:nI.GRAY},e.ccToolDefinition),ot.createElement(Je,{gap:1},ot.createElement(Qe,{color:nI.WHITE,bold:!0},"System Prompt:")),ot.createElement(Qe,{color:nI.GRAY},e.sysPrompt),!n&&ot.createElement(Je,{marginTop:1},"idle"===r&&ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to save ·"," ",ot.createElement(GA,null,"Esc")," to cancel"),"saving"===r&&ot.createElement(Qe,{color:nI.YELLOW},"Saving agent…"),"saved"===r&&ot.createElement(KO,null,s),"error"===r&&ot.createElement(Je,{flexDirection:"column"},ot.createElement(zO,null,"Error: ",s),ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to retry"))))},"AgentSummary"),DD=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],ND=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=at("menu"),a=new Set(resolveAgentToolSelection({access:e.tools,allToolNames:py,displayNameToToolName:yy})),i={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:a,model:e.model??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 tt((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=DD[r];e&&d(e)}}),"view"===o?ot.createElement(ZA,{title:e.name,gapAfterHeader:!1,footer:ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to go back")},ot.createElement(LD,{config:i,onSaveComplete:()=>s("menu"),viewOnly:!0})):"edit"===o?ot.createElement(ZA,{title:e.name,gapAfterHeader:!1},ot.createElement(Qe,{color:nI.YELLOW},"Edit functionality coming soon..."),ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Esc")," to go back")):"delete"===o?ot.createElement(ZA,{title:"Delete agent",subtitle:`Are you sure you want to delete the agent ${e.name}?`},ot.createElement(Je,null,ot.createElement(SelectInput,{items:DD,onSelect:d,indicatorComponent:YL,itemComponent:qL}))):ot.createElement(ZA,{title:e.name,footer:ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"↑↓")," to navigate ·"," ",ot.createElement(GA,null,"Enter")," to select · ",ot.createElement(GA,null,"Esc")," ","to go back")},ot.createElement(SelectInput,{items:l,onSelect:c,indicatorComponent:YL,itemComponent:qL}))},"AgentDetails");Ht();var $D="https://commandcode.ai/docs/core-concepts/custom-agents",_D=__name(({onDone:e})=>(tt((t,n)=>{n.return&&e()}),ot.createElement(ZA,{title:"Create agents with Command Code",gapAfterHeader:!1,boxProps:{gap:1}},ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.GRAY},"Ask Command Code to create or update subagents for you, e.g."),ot.createElement(Qe,{color:nI.GRAY}," ",pt.pointerSmall," “create a code-reviewer subagent that reviews diffs for bugs”"),ot.createElement(Qe,{color:nI.GRAY}," ",pt.pointerSmall," “make a changelog agent that uses a fast model”")),ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.GRAY},"Or edit the files directly:"),ot.createElement(Qe,{color:nI.GRAY}," • .commandcode/agents/ (this project)"),ot.createElement(Qe,{color:nI.GRAY}," • ~/.commandcode/agents/ (all projects)")),ot.createElement(Qe,{color:nI.GRAY},"Docs: ",$D),ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to go back and just ask"))),"AskCommandCodeGuide"),FD=__name(({handleSelect:e,createdAgentName:t})=>{const[n,r]=at([]),[o,s]=at([]),[a,i]=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();lt(()=>{__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"}))),i(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})}),a.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)+(a.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,...a].find(e=>e.filePath===t.value);r&&(p(r),h(!0))},"handleAgentSelect");if(tt((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}),lt(()=>{y(e=>Math.min(e,Math.max(0,k.length-1)))},[k.length]),lt(()=>{w(e=>clampScrollOffset({cursor:f,total:k.length,maxVisible:P,currentOffset:e}))},[f,k.length,P]),l)return ot.createElement(VO,{label:"Loading agents"});if(g&&m){const e=isBuiltinAgentPath(m.filePath);return ot.createElement(ND,{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 O=null;return ot.createElement(ZA,{title:"Agents",titleSuffix:C>0?` (${C} agent${C>1?"s":""})`:" (No custom agents)"},t&&ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{color:nI.GREEN,dimColor:!0},"Created agent: ",t)),ot.createElement(Je,{flexDirection:"column"},A.map((e,t)=>{const n=x+t,r=E(n),o="action"!==r&&r!==O;O=r;const s=n===f,a="user"===r?"User agents":"project"===r?"Project agents":"Default agents (read-only)";return ot.createElement(ot.Fragment,{key:e.value},o&&ot.createElement(Je,{marginTop:0===t?0:1},ot.createElement(Qe,{color:pI,bold:!0},a)),ot.createElement(Je,null,ot.createElement(Qe,{color:s?nI.WHITE:nI.GRAY,backgroundColor:s?TI:void 0,bold:s},s?"> ":" ",e.label," ")))})),R&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",x+1,"–",Math.min(I,k.length)," of ",k.length,x>0?" · ↑ more":"",I<k.length?" · ↓ more":"")),ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(VA,{hints:["↑↓ navigate","Enter to select","Esc to close"],marginTop:0}),ot.createElement(Qe,{color:nI.DIM},"Agents live in .commandcode/agents/ (project) and ~/.commandcode/agents/ (all projects) — edit the files directly anytime."),ot.createElement(Qe,{color:nI.DIM},"Docs: ",$D)))},"ManageAgents");Ht(),Qx(),Ht(),Ht();var UD=[{label:"1. Project (.commandcode/agents/)",value:"project"},{label:"2. Personal (~/.commandcode/agents/)",value:"personal"}],jD=__name(({onSelect:e})=>ot.createElement(SelectInput,{items:UD,onSelect:t=>{"project"!==t.value&&"personal"!==t.value||e(t.value)},indicatorComponent:WL,itemComponent:GL}),"LocationSelector");Ht(),Qx();var BD=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:a,onAgentTypeSubmit:i,onSysPromptSubmit:l,onCCToolDefinitionSubmit:c})=>{const d=t?validateAgentName({name:t,displayNameByToolName:fy}):null,u=usePasteAwareChange({onChange:s}),m=usePasteAwareChange({onChange:a});return"agentType"===e?ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.WHITE},"Enter a unique identifier for your agent:"),"tool_conflict"===d?.issue&&ot.createElement(Qe,{color:nI.RED},pt.warning," This name conflicts with an existing tool name. Please choose a different name."),"reserved"===d?.issue&&ot.createElement(Qe,{color:nI.RED},pt.warning," This name is reserved. Reserved names: ",xS.join(", "))),ot.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{canSubmitAgentManualStep({manualStep:"agentType",config:{agentType:t,sysPrompt:n,ccToolDefinition:r}})&&i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.WHITE},"Enter the system prompt for your agent:"),ot.createElement(Qe,{color:nI.GRAY},"Be comprehensive for best results.")),ot.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?ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.WHITE},"When should ","Command Code"," use this agent?"),ot.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");Ht(),Qx();var WD=__name((e,t)=>e?"[x]":"[ ]","categoryCheckbox"),HD=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=at(!1),[a,i]=at(0),[l,c]=at(0),d=useTerminalHeight(),u=ct(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),by.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:"}),py.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=by.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t)),s=r?.tools.some(t=>e.has(t));return{label:`${WD(Boolean(o),Boolean(s))} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${fy[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[a]?.value??0;lt(()=>{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 tt((e,l)=>{if(l.upArrow)return void i(e=>{const t=e-1;return t<0?p.length-1:t});if(l.downArrow)return void i(e=>{const t=e+1;return t>=p.length?0:t});if(!l.return&&" "!==e)return;const c=p[a];if(!c)return;const d=u[c.value];if(d){if("continue"!==d.type)return"toggle"===d.type?(s(!o),void i(0)):void("category"!==d.type?"tool"===d.type&&t(d.value):n(d.value));r()}}),ot.createElement(Je,{flexDirection:"column"},S.map(e=>{const t=p.findIndex(t=>t.value===e.value),n=-1!==t&&t===a;if("divider"===e.type)return ot.createElement(Je,{key:`divider-${e.value}`},ot.createElement(Qe,{color:nI.GRAY}," ",e.label));if("spacer"===e.type)return ot.createElement(Je,{key:`spacer-${e.value}`,height:1});if("label"===e.type)return ot.createElement(Je,{key:`label-${e.value}`},ot.createElement(Qe,{color:nI.GRAY}," ",e.label));const r="continue"===e.type;return ot.createElement(Je,{key:`item-${e.value}`},ot.createElement(Qe,{color:n?nI.WHITE:nI.GRAY,bold:r&&n},n?">":" "," ",e.label))}),w&&ot.createElement(Je,null,ot.createElement(Qe,{color:nI.GRAY}," ","Showing ",f+1,"–",Math.min(y,m.length)," of"," ",m.length,f>0?" · ↑ more":"",y<m.length?" · ↓ more":"")),ot.createElement(Je,{marginTop:1},e.size===py.length&&ot.createElement(Qe,{color:nI.GRAY},"All tools selected"),e.size>0&&e.size<py.length&&ot.createElement(Qe,{color:nI.GRAY},e.size," tools selected"),0===e.size&&ot.createElement(Qe,{color:nI.GRAY},"No tools selected")))},"ToolsSelector"),GD=__name(({onComplete:e})=>{const[t,n]=at(createAgentCreationState),{step:r,manualStep:o,config:s}=t,a=__name(e=>n(t=>reduceAgentCreation({state:t,event:e})),"dispatch"),i=__name(t=>{a({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":"summary"===r?"Confirm and save":""},"getSubText"),c=__name(e=>{a({type:"select_location",location:e}),a({type:"select_method",method:"manual"})},"handleLocationSelect");return ot.createElement(ZA,{title:"Create new agent",subtitle:l()},ot.createElement(Je,null,"location"===r&&ot.createElement(jD,{onSelect:c}),"configuration"===r&&ot.createElement(Je,{flexDirection:"column",gap:1},ot.createElement(BD,{step:o,agentType:s.agentType,sysPrompt:s.sysPrompt,ccToolDefinition:s.ccToolDefinition,onAgentTypeChange:e=>a({type:"set_agent_type",value:e}),onSysPromptChange:e=>a({type:"set_sys_prompt",value:e}),onCCToolDefinitionChange:e=>a({type:"set_cc_tool_definition",value:e}),onAgentTypeSubmit:()=>a({type:"submit_agent_type"}),onSysPromptSubmit:()=>a({type:"submit_sys_prompt"}),onCCToolDefinitionSubmit:()=>a({type:"submit_cc_tool_definition"})})),"tools"===r&&ot.createElement(HD,{selectedTools:s.selectedTools,onToggleTool:e=>a({type:"toggle_tool",tool:e}),onToggleCategory:e=>a({type:"toggle_category",category:e}),onComplete:()=>a({type:"complete_tools"})}),"model"===r&&ot.createElement(OD,{selectedModel:s.model,onSelect:e=>a({type:"select_model",model:e})}),"summary"===r&&ot.createElement(LD,{config:s,onSaveComplete:i})))},"AgentNew"),VD=__name(({onCancel:e})=>{const[t,n]=at(null),[r,o]=at(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return tt((t,n)=>{n.escape&&e()}),ot.createElement(Je,{width:"100%",flexDirection:"column"},null===t&&ot.createElement(FD,{handleSelect:s,createdAgentName:r}),"ask_command_code"===t&&ot.createElement(_D,{onDone:e}),"create_new_agent"===t&&ot.createElement(GD,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");function isToggleShortcut(e,t){return""===e||!0===t.ctrl&&"b"===e}Ht(),Qx(),__name(isToggleShortcut,"isToggleShortcut");var zD=new Set;function requestBackgroundTasksExpand(){for(const e of zD)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),a=r%60;return o>0?`${o}h ${s}m ${a}s`:s>0?`${s}m ${a}s`:`${a}s`}function useShellTaskSnapshot(){const[e,t]=at(()=>listShellTasks({includeStopped:!0}));return lt(()=>{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 KD=getShellTaskLabel,qD=getShellTaskStatusText,YD=getVisibleShellTasks,JD=latestShellTaskOutputLines,QD={running:nI.CYAN,completed:nI.GREEN,failed:nI.RED,"auto-stopped":nI.YELLOW,stopped:nI.GRAY};function getStatusColor(e){return QD[getShellTaskStatusTone(e)]}function TaskRow({task:e,selected:t}){const n=truncateString2({text:KD(e),maxChars:56}),r=t?TI:void 0;return ot.createElement(Je,null,ot.createElement(WL,{isSelected:t,backgroundColor:r}),ot.createElement(Qe,{color:t?YA:void 0,backgroundColor:r}," ",n),ot.createElement(Qe,{color:nI.DIM,backgroundColor:r}," ","(",qD(e),")"))}function TaskGroup({title:e,tasks:t,selectedTaskId:n}){return 0===t.length?null:ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Qe,{color:nI.DIM,bold:!0},e," (",t.length,")"),t.map(e=>ot.createElement(TaskRow,{key:e.id,task:e,selected:e.id===n})))}function TaskDetailsBody({task:e,output:t}){const n=JD(t,10),r=formatTaskRuntime(e);return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,{bold:!0},"Status: "),ot.createElement(Qe,{color:getStatusColor(e)},qD(e))),void 0!==r&&ot.createElement(Je,null,ot.createElement(Qe,{bold:!0},"Runtime: "),ot.createElement(Qe,null,r)),ot.createElement(Je,null,ot.createElement(Qe,{bold:!0},"Script: "),ot.createElement(Qe,{wrap:"wrap"},e.command)),ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Qe,{bold:!0},"Output:"),ot.createElement(Je,{flexDirection:"column",borderStyle:"single",borderColor:nI.DIM,paddingX:1},n.length>0?n.map((t,n)=>ot.createElement(Qe,{key:`${e.id}-${n}`},truncateString2({text:t,maxChars:100}))):ot.createElement(Qe,{color:nI.DIM},"No output yet.")),ot.createElement(Qe,{italic:!0,color:nI.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,a]=at("list"),[i,l]=at(0),[c,d]=at(""),u=ct(()=>YD(t),[t]),m=u[i]??u[0];lt(()=>{e?.(r)},[r,e]),lt(()=>{const e=__name(()=>{a("list"),o(!0)},"listener");return zD.add(e),()=>{zD.delete(e)}},[]),lt(()=>{if(0===u.length)return o(!1),a("list"),void l(0);l(e=>Math.min(e,Math.max(0,u.length-1)))},[u.length]),lt(()=>{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),a("list")},"closePanel");if(tt((e,t)=>isToggleShortcut(e,t)&&(n.length>0||r)?(a("list"),void o(e=>!e)):r?"details"===s?t.leftArrow?void a("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?a("details"):"x"===e&&"running"===m?.status&&stopShellTaskById(m.id))):void 0,{isActive:n.length>0||r}),!r)return null;if("details"===s&&m)return ot.createElement(ZA,{title:"monitor"===m.kind?"Monitor details":"Shell details",titleColor:nI.CYAN,ruleColor:nI.CYAN,subtitle:truncateString2({text:KD(m),maxChars:80}),hint:"← to go back · Esc/Enter/Space to close · x to stop",boxProps:{marginTop:1,marginBottom:1}},ot.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 ot.createElement(ZA,{title:"Background",titleColor:nI.CYAN,ruleColor:nI.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?ot.createElement(ot.Fragment,null,ot.createElement(TaskGroup,{title:"Monitors",tasks:g,selectedTaskId:m?.id}),ot.createElement(TaskGroup,{title:"Shells",tasks:h,selectedTaskId:m?.id})):ot.createElement(Je,{flexDirection:"column",marginTop:1},u.map(e=>ot.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"),Ht(),Qx();var XD=[{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."}],ZD=__name(({onSelect:e,onCancel:t})=>{const[n,r]=at(null);lt(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(tt((e,n)=>{n.escape&&t()}),null===n)return null;const s=XD.findIndex(e=>e.value===n);return ot.createElement(ZA,{title:"Select a compact mode to compact sessions",subtitle:"Choose how Command Code handles automatic context compaction.",footer:ot.createElement(Qe,{italic:!0,color:nI.DIM},"Press ",ot.createElement(Qe,{bold:!0},"Esc")," to cancel")},ot.createElement(SelectInput,{items:XD,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:YL,itemComponent:({isSelected:e,label:t})=>{const r=XD.find(e=>e.label===t),o=r?.value===n,s=XD.findIndex(e=>e.label===t);return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(KL,{isSelected:e,idleColor:o?nI.GREEN:nI.WHITE,bold:e||o},` ${s+1}. ${r?.label??t} `),o&&ot.createElement(VL,null)),ot.createElement(KL,{isSelected:e,idleColor:nI.DIM,bold:!1},` ${r?.description??""} `))}}))},"CompactModeSelector");Ht(),Ht(),Qx();var eN=["·","○","◇","☆","✧","☆","◇","○","⌘"],tN=[12,5,4,4,4,4,4,5,16],nN=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<tN.length;e++)if(n+=tN[e],t<n)return eN[e];const r=t-58;n=0;for(let e=0;e<nN.length;e++)if(n+=nN[e],r<n)return eN[7-e];return eN[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=ct(()=>e.split(""),[e]),o=__name(e=>{const n=e-(t-5);return n>=0&&n<kI.length?kI[n]:CI},"getCharColor");return ot.createElement(Qe,null,r.map((e,t)=>ot.createElement(Qe,{key:`${t}:${e}`,color:o(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return ot.createElement(Qe,{color:t??rI,bold:!0},`${getWaveSymbol(e)} `)}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var rN=formatStatusTokenCount,oN=formatElapsedMs,sN=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=at(0),[s,a]=at(n),i=it(n);i.current=n;const l=getTerminalWidth(),[c,d]=at(()=>l>=72?"all":l>=42?"medium":"none");lt(()=>{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]),lt(()=>{const e=setInterval(()=>{o(e=>(e+1)%88),a(e=>{const t=i.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 lA.statusRender({width:l,layoutMode:c,status:e,frame:r}),ot.createElement(Je,{width:l,height:1,paddingLeft:0,marginLeft:0},ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:cI.BG,color:cI.FG}," "),ot.createElement(Qe,{backgroundColor:cI.BG},ot.createElement(CMDIcon,{frame:4*r,color:cI.FG})),ot.createElement(ShimmerText,{text:e,offset:u,bg:cI.BG}),ot.createElement(Qe,{backgroundColor:cI.BG,color:cI.FG}," ")),m&&ot.createElement(Je,{columnGap:1,marginLeft:1},ot.createElement(Qe,{bold:!0,color:nI.GRAY},"esc"),ot.createElement(Qe,{color:nI.DIM},"to interrupt"),ot.createElement(Qe,{color:nI.DIM},"•"),ot.createElement(Qe,{color:nI.DIM},oN(t)),ot.createElement(Qe,{color:nI.DIM},"•"),ot.createElement(Qe,{color:nI.GRAY},pt.arrowDown),ot.createElement(Qe,{color:nI.DIM},rN(Math.round(s)))),p&&ot.createElement(Je,{marginLeft:1},ot.createElement(Qe,{color:nI.DIM},rN(Math.round(s)))))},"Status");function useExternalEditor({input:e,setInput:t,setInputKey:n,detectedContent:r,setDetectedContent:o,onEditorClose:s}){const[a,i]=at(!1),[l,c]=at(null),d=dt(async()=>{if(!a){i(!0),c(null);try{const a=resolvePastedTextTokens({input:e.replace(/\n+$/,""),detectedContent:r}),i=await openInEditor(a);t(i),o([]),n(e=>e+1),s?.()}catch(e){if(e instanceof Lh)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{i(!1)}}},[e,t,n,r,o,s,a]),u=dt(()=>{c(null)},[]);return{isEditorOpen:a,editorError:l,handleOpenInEditor:d,clearEditorError:u}}Ht(),Qx(),Ht(),Qx(),__name(useExternalEditor,"useExternalEditor"),Ht(),Qx();var aN=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=at(null),[s,a]=at(!1),[i,l]=at({visible:!1,type:"connected"}),c=it(null);null===c.current&&(c.current=eb({onConnectedChange:a,onContext:o,onIndicatorChange:l}));const d=c.current;lt(()=>{d.setPaused(n)},[d,n]),lt(()=>{if(t)return d.start(),()=>{d.stop()}},[t,d]);const u=NC(),m=u?sb[u]??"IDE":"IDE",p={visible:i.visible,message:"connected"===i.type?`${m} ${pt.tick}`:"run /ide",type:i.type};return{context:r,connected:s,refresh:d.refresh,connectionIndicator:p}},"useVSCodeContext");Ht(),Qx();var iN=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=at(null),o=it(!1);return lt(()=>{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=it([]),s=it(""),a=it(!1),i=it(null),l=it(!1),c=it("");return lt(()=>{if(l.current)return l.current=!1,void(c.current=e);if(e===c.current)return;const t=c.current;return c.current=e,a.current||(s.current=t,a.current=!0),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{a.current=!1,i.current=null,pushEntry(o.current,s.current)},400),()=>{i.current&&(clearTimeout(i.current),i.current=null)}},[e]),{commitUndo:__name(()=>{a.current&&commitBurst({stack:o.current,burstStart:s.current,inBurst:a,timer:i});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})}Ht(),__name(pushEntry,"pushEntry"),__name(commitBurst,"commitBurst"),__name(useUndoStack,"useUndoStack"),Ht(),Qx(),__name(getCommandHintLayout,"getCommandHintLayout"),__name(getModelHintText,"getModelHintText"),Ht(),Qx();var lN=createNodeRuntime(),cN=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=at(()=>process.cwd()),[a,i]=at([]),[l,c]=at(0),[d,u]=at(0),m=n.trim()?15:10;lt(()=>{invalidateFileIndex()},[]),lt(()=>{let e=!1;return __name(async()=>{if(n.trim()){const t=await searchFiles({runtime:lN,searchTerm:n,basePath:process.cwd()});if(e)return;return i(t),c(0),void u(0)}try{const t=await browseDirectory({runtime:lN,dirPath:r,basePath:process.cwd()});if(e)return;i(t),c(0),u(0)}catch{}},"run")(),()=>{e=!0}},[r,n]),tt((r,i)=>{if(i.escape)t();else if(i.upArrow)c(e=>{const t=Math.max(0,e-1);return t<d&&u(t),t});else if(i.downArrow)c(e=>{const t=Math.min(a.length-1,e+1);return t>=d+m&&u(t-m+1),t});else{if(i.rightArrow){const e=a[l];if(!e)return;return void(e.isDirectory&&!n.trim()&&o(s(e.path)))}if(i.return){const t=a[l];if(!t)return;return void e(t.path)}}});const p=a.slice(d,d+m);return ot.createElement(Je,{flexDirection:"column",paddingLeft:1},ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM},n.trim()?`Searching for: "${n}"`:`Files: ${r}`)),0===p.length?ot.createElement(YO,{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 ot.createElement(Qe,{key:e.path,color:o?YA:nI.DIM,bold:o&&isLightTheme()},e.isDirectory?`${r}/`:r)}),ot.createElement(VA,{hints:["↑↓ navigate",!n.trim()&&"→ to open folder","Enter to select","Esc to close"]}))},"FileList");Ht(),Qx();var dN=__name(()=>ot.createElement(Je,{paddingRight:3},ot.createElement(Qe,{color:nI.DIM,wrap:"truncate"},pt.pointerSmall," ","stashed")),"StashBadge"),uN=__name(({tasteLearningOn:e,byokSession:t,showSeparator:n=!0})=>{if(null==e)return null;const r=e&&t;return ot.createElement(ot.Fragment,null,n&&ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:e&&!r?oI.TEXT:nI.DIM},r?"taste off (byok)":"taste "+(e?"on":"off")))},"TasteStateBadge");function useBackgroundTasksSummary(){const[e,t]=at(()=>formatShellTaskCounts(listShellTasks({includeStopped:!1})));return lt(()=>{const e=setInterval(__name(()=>t(formatShellTaskCounts(listShellTasks({includeStopped:!1}))),"refresh"),1e3);return()=>clearInterval(e)},[]),e}__name(useBackgroundTasksSummary,"useBackgroundTasksSummary");var mN=__name(({showSeparator:e=!0,armed:t=!1})=>{const n=useBackgroundTasksSummary();return n?ot.createElement(ot.Fragment,null,e&&ot.createElement(Qe,{color:nI.DIM}," · "),t?ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.CYAN,inverse:!0},` ${n} `),ot.createElement(Qe,{color:nI.DIM}," · Enter to open")):ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.CYAN},n),ot.createElement(Qe,{color:nI.DIM}," · ↓ to manage"))):null},"BackgroundTasksBadge"),pN=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?ot.createElement(ot.Fragment,null,t&&ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:"connected"===e.type?nI.GREEN:nI.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),gN=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="default",prInfo:o,contextUsage:s,connectionIndicator:a,pendingExitKey:i,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})=>{const C=e>=60;return ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r&&"bypass"!==r&&"dont-ask"!==r||i?ot.createElement(Je,{flexDirection:"row",justifyContent:"space-between",width:e-1},ot.createElement(Je,{flexDirection:"row",columnGap:0},n&&!i?ot.createElement(Qe,{color:mI},t):ot.createElement(jI,{mode:r,pendingExitKey:i}),!i&&ot.createElement(WI,{prInfo:o}),!i&&ot.createElement(pN,{indicator:a}),!i&&C&&ot.createElement(uN,{tasteLearningOn:w,byokSession:v}),!i&&ot.createElement(mN,{armed:k})),(C||S)&&ot.createElement(Je,{flexDirection:"column",alignItems:"flex-end"},S?ot.createElement(dN,null):null,!S&&C&&s&&ot.createElement(AI,{usage:s}))):ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"row",justifyContent:"space-between",width:e-1},ot.createElement(jI,{mode:r}),S?ot.createElement(dN,null):null),ot.createElement(Je,{flexDirection:"row",justifyContent:"space-between",width:e-1},ot.createElement(Je,{flexDirection:"row",columnGap:0},ot.createElement(Qe,{color:n?mI:nI.DIM},t),ot.createElement(WI,{prInfo:o}),ot.createElement(pN,{indicator:a}),C&&ot.createElement(uN,{tasteLearningOn:w,byokSession:v}),ot.createElement(mN,{armed:k})),ot.createElement(Je,{flexDirection:"row",columnGap:2},C&&s&&ot.createElement(AI,{usage:s})))),(l||c||u&&d)&&ot.createElement(Je,{flexDirection:"row",columnGap:1},l&&ot.createElement(Qe,null,pt.tick," ","Command Code"," updated:"," ",ot.createElement(Qe,{color:nI.DIM},"v",l.updatedFrom),ot.createElement(Qe,{color:nI.DIM}," ",pt.arrowRight," "),ot.createElement(Qe,null,"v",l.updatedTo)),!l&&c&&ot.createElement(Qe,{color:nI.YELLOW,dimColor:!0},pt.info," Update available:"," ",c.currentVersion," ",pt.arrowRight," ",c.latestVersion),u&&d&&ot.createElement(Qe,{color:nI.GREEN,dimColor:!0},pt.bullet," Provider:"," ",getProviderDisplayName(d)))),m&&ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,{color:nI.GREEN},"! for bash mode")),g&&p&&ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,{color:rI},"SHARED: ",p.url," (copied to clipboard)")),h&&ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,{color:h.includes("NOT SHARED")?nI.RED:rI},h)),f&&ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,{color:rI},f)),y&&ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,{color:nI.YELLOW},pt.warning," ",y)))},"BottomIndicator"),hN=["","","[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 fN=__name(()=>ot.createElement(Je,{flexDirection:"column",paddingLeft:1},ot.createElement(Qe,{color:nI.DIM,bold:!0},"Available Shortcuts:"),ot.createElement(Je,{columnGap:4},ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},"! for bash mode"),ot.createElement(Qe,{color:nI.DIM},"/ for commands"),ot.createElement(Qe,{color:nI.DIM},"@ for file paths"),ot.createElement(Qe,{color:nI.DIM},getModeToggleShortcutHint()," to toggle auto-accept")),ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},"double tap esc to clear input"),ot.createElement(Qe,{color:nI.DIM},"ctrl + j / shift + ⏎ for newline"),ot.createElement(Qe,{color:nI.DIM},"ctrl + g to open in editor"),ot.createElement(Qe,{color:nI.DIM},"ctrl + z to undo"),ot.createElement(Qe,{color:nI.DIM},"ctrl + s to stash prompt")))),"ShortcutMenu"),yN=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:s,setShowFileList:i,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:O=!1,ideContextEnabled:L=!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=it(0),q=it(0),[Y,J]=at([]),[Q,X]=at([]),[Z,ee]=at(null),te=it(!1),ne=it(!1),[re,oe]=at(!1),se=it(!1),ae=dt(e=>{se.current=e,oe(e)},[]),ie=it(!1),le=it(void 0),[ce,de]=at(-1),[ue,me]=at(""),pe=it(0),{commitUndo:ge}=useUndoStack({input:e,setInput:n,initialCursorRef:le,incrementInputKey:__name(()=>$(e=>e+1),"incrementInputKey")}),{isEditorOpen:he,editorError:fe,handleOpenInEditor:ye,clearEditorError:Se}=useExternalEditor({input:e,setInput:n,setInputKey:$,detectedContent:Y,setDetectedContent:J,onEditorClose:__name(()=>{te.current=!1},"onEditorClose")}),we=ct(()=>shouldCollapsePastedText(),[]),{handlePaste:ve,resetPasteState:ke,isPasting:Ce}=useBracketedPaste({input:e,setInput:n,setDetectedImages:X,setDetectedContent:J,incrementInputKey:__name(()=>$(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{le.current=e},"setInitialCursor"),collapsePastedText:we,nextImageNumber:nextImagePasteNumber(Q)}),be=it(()=>{});be.current=t=>{he||(async()=>{const n=pe.current,r=e.slice(0,n),o=e.slice(n);await ve(`${r}[200~${t}[201~${o}`)&&(ie.current=!0)})()},lt(()=>registerPasteConsumer(e=>be.current(e)),[]);const Ee=it(new Map),Te=ct(()=>{const e=Ee.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 Ee.current=t,n},[Q]),{skills:Pe,customMenuItems:Me}=useSlashMenuData(),xe=ct(()=>{const e=resolveSlashMenuItems({searchQuery:"",customMenuItems:Me,skills:Pe,showProviderCommand:!0,showTerminalSetupCommand:isVSCodeTerminal2()});return new Set([...e.map(e=>e.command),...Pe.map(e=>buildSkillNamespacedCommand(e.name))])},[Pe,Me]),Ie=dt(e=>xe.has(e),[xe]),{context:Ae,connected:Re,refresh:Oe,connectionIndicator:Le}=aN({enabled:L,paused:O}),{stdout:De}=Ze(),Ne=De?.columns??80,{pr:$e}=iN();lt(()=>{const e=s||B;I?.(e)},[s,B,I]),lt(()=>{if(!ie.current)return;ie.current=!1;const t=sf(e);!B&&t.showCommandMenu||(W(t.showCommandMenu),G(t.showCommandMenu?t.commandSearchQuery:""))},[e,B]);const _e=dt(()=>{X([])},[]),Fe=dt(()=>{W(!1),z(null)},[]),Ue=dt(()=>{Fe(),G(""),i(!1),c(""),de(-1),me(""),le.current=void 0,$(e=>e+1)},[Fe,c,i]),je=dt(t=>!(null===Z||!t?.replaceCurrentInput&&e.trim().length>0||(te.current=!0,n(Z),ee(null),Ue(),setTimeout(()=>{te.current=!1},0),0)),[e,Ue,n,Z]),Be=dt(()=>{n(""),j(!1),Fe(),G(""),J([]),_e(),ke(),de(-1),me(""),$(e=>e+1)},[n,ke,_e,Fe]),We=dt(()=>{te.current=!0;const{text:t,cursor:r}=insertTextAt(e,pe.current,"\n");n(t),le.current=r,$(e=>e+1),setTimeout(()=>{te.current=!1},0)},[e,n]);tt(async(t,r)=>{if(se.current&&!r.downArrow&&!r.return&&"\r"!==t&&(ae(!1),r.upArrow))return;if(r.upArrow){if(s||B)return;const t=e.indexOf("\n"),r=-1===t||pe.current<=t;if(0!==e.length&&-1===ce&&!r)return;const o=M?.count()??0;if(0===o)return;-1===ce&&me(e);const a=Math.min(ce+1,o-1);return void(a!==ce&&(de(a),n(M?.getAt(a)||""),$(e=>e+1)))}if(r.downArrow){if(s||B)return;if(-1===ce){const t=e.lastIndexOf("\n"),n=-1===t||pe.current>t;return void((0===e.length||n)&&listShellTasks().some(e=>"running"===e.status)&&ae(!0))}const t=e.lastIndexOf("\n");if(!(-1===t||pe.current>t))return;const r=ce-1;return de(r),n(-1===r?ue:M?.getAt(r)||""),void $(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void _e();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return te.current=!0,void ye();if(isCtrlKey({inputChar:t,key:r,letter:"s",ctrlCode:19})){const t=e.trim().length>0;if(!t&&null===Z)return;if(!t&&je())return;te.current=!0;const r=Z??"";return ee(t?e:null),n(r),Ue(),void setTimeout(()=>{te.current=!1},0)}if(getIsExpandToolShortcut(r,t))return te.current=!0,n(e),$(e=>e+1),void setTimeout(()=>{te.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Ce()}))return ne.current=!0,We(),void setTimeout(()=>{ne.current=!1},0);if(r.meta&&"w"===t)return te.current=!0,void Be();const o=r.ctrl&&"v"===t||hN.includes(t),a=r.meta&&"v"===t;if(o||a){if(o&&"darwin"===process.platform){const t=e;te.current=!0;const r=await detectClipboardImage();if(r){const e=nextImagePasteNumber(Q),{text:o,cursor:s}=insertTextAt(t,pe.current,imagePasteToken(e));X(t=>[...t,{imageNumber:e,image:r}]),n(o),le.current=s,$(e=>e+1)}return void(te.current=!1)}}else if(!r.ctrl&&!r.meta||"u"!==t)if(r.ctrl&&"z"===t?.toLowerCase())ge();else{if(r.escape){if(B)return;const t=Date.now();return t-K.current<500?(e.length>0?Be():A?.(),K.current=0,q.current=0,F(!1),void j(!1)):(K.current=t,_||U||(q.current=t),F(!1),void j(!1))}_&&(r.backspace||r.delete)&&0===e.length&&F(!1)}});const He=dt(async t=>{if(he)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void R?.();const o=processBracketedPaste(t),a=findInsertion({before:e,after:t}),d=null!==a&&looksLikeDroppedImagePath(a.text);if((o.isPasteStart||o.isPasteEnd||d||Ce())&&await ve(t))return void(ie.current=!0);if(te.current)return void(te.current=!1);-1!==ce&&de(-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 $(e=>e+1);if("!"===m&&!U)return F(!1),j(!0),n(""),void $(e=>e+1)}const p=sf(t),g=t.length<e.length&&!e.startsWith(t),h=!g&&t.length<e.length,f=t.length===e.length+1||h,y=af({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&&i(S.showFileList),S.query!==l&&c(S.query),_&&(t!==e||t.length<e.length)&&F(!1),fe&&Se(),0===t.length&&(j(!1),Fe(),G(""),J([]),c(""),ke()),n(t)},[_,e,n,s,i,l,c,B,H,U,ce,ve,ke,Ce,R,fe,Se,he,Fe]),Ge=dt(async()=>{if(Oe(),q.current=0,_)return void F(!1);const r=e.trim(),o=!U&&r.startsWith("/");let s=r;!U&&Y.length>0&&(s=resolvePastedTextTokens({input:s,detectedContent:Y}));const a=U?[]:resolvePastedImageTokens({input:r,images:Q}),i={};if(!U)for(const e of Q){if(!r.includes(imagePasteToken(e.imageNumber)))continue;const t=Te.get(e.imageNumber);t&&(i[e.imageNumber]=t)}const l=Object.keys(i).length>0,c=Ae?KC(Ae):void 0;if(o&&d&&(n(""),"handled"===(await d(s,a,c)).status))return M?.add(s),j(!1),Fe(),G(""),_e(),J([]),de(-1),me(""),void je({replaceCurrentInput:!0});de(-1),me(""),s.length>0&&M?.add(s);const u=buildIdeContextHint({ideContext:Ae});t({input:s,role:U?"bash":"user",images:a,ideContext:c,ideHint:u,imageTokenPaths:l?i:void 0}),j(!1),Fe(),G(""),_e(),J([]),je({replaceCurrentInput:!0})},[t,d,_,e,U,Q,Te,Y,M,Oe,Ae,_e,Fe,je,n]),Ve=dt(t=>{const r=a(process.cwd(),t),o=r.includes(" ")?`"${r}"`:r,d=buildFileMentionInput({currentInput:e,mentionPath:o,isSearchMode:s&&""!==l});n(d),i(!1),c(""),$(e=>e+1)},[n,i,e,s,l,c]),ze=dt(()=>{i(!1),c("")},[i,c]),Ke=dt(e=>{const t=ef.has(e),r="/design"===e.trimEnd();if(t||r){const t=e.trimEnd();return n(t+" "),G(t.substring(1)+" "),void $(e=>e+1)}Fe(),G(""),n(e+" "),$(e=>e+1)},[n,Fe]),qe=dt(t=>{if("/design help"===t)return Fe(),G(""),n(""),$(e=>e+1),M?.add(t),void d?.("/design help");if(Zh.has(t))return Fe(),G(""),M?.add(t),de(-1),me(""),n(""),$(e=>e+1),void d?.(t);const r=ef.has(t),o=da.has(t),s=ua.has(t);if(r)Ke(t);else{if(Fe(),G(""),!o&&!s&&e!==t)return n(t+" "),void $(e=>e+1);M?.add(t),de(-1),me(""),n(""),$(e=>e+1),d?.(t)}},[d,n,e,M,Ke,Fe]),Ye=dt(()=>{Fe(),G(""),de(-1),me(""),$(e=>e+1)},[Fe]),Xe=dt(e=>{pe.current=e,le.current=void 0},[]),et=ct(()=>formatSlashCommandInputHint({value:e,selectedCommand:B?V:null}),[e,B,V]),nt=Boolean(et)&&!x,rt=ct(()=>{const t=$e&&("OPEN"===$e.state||"MERGED"===$e.state);return"auto-accept"===E||"plan"===E||"bypass"===E||"dont-ask"===E||Re||t?!_:!_&&0===e.length&&!U},[_,e,U,E,Re,$e]),st=null!==Z,ut=__name(()=>_||s||B?0:nt||rt||x||U?3:4,"getBottomMargin");return ot.createElement(Je,{width:"100%",flexDirection:"column",marginBottom:ut()},ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(Qe,{color:U?nI.GREEN:nI.GRAY},pt.line.repeat(Ne)),(()=>{const t=__name(()=>{if(se.current&&(ae(!1),listShellTasks().some(e=>"running"===e.status)))requestBackgroundTasksExpand();else{if(!ne.current)return Date.now()-q.current<100?(q.current=0,void We()):void(s||B||he||Ge());ne.current=!1}},"handleTextInputSubmit"),n=__name(n=>ot.createElement(TextInput,{key:N,value:e,placeholder:he?"Save and close the editor to continue...":o,onChange:He,onSubmit:t,showCursor:!he&&r,onCursorChange:Xe,initialCursor:le.current,prefix:`${U?"!":pt.pointer} `,prefixColor:U?nI.GREEN:nI.WHITE,singleLine:n?.singleLine,maxWidth:n?.maxWidth,imageTokenLinks:Te,isRecognizedSlashCommand:Ie,disablePasteRouting:!0}),"renderTextInput"),a=B?"/model"===V&&C?getModelHintText(C):et:null,i=a?getCommandHintLayout({text:a,terminalWidth:Ne}):null;return i?ot.createElement(Je,{flexDirection:"row",width:"100%"},ot.createElement(Je,{width:25},n({singleLine:!0,maxWidth:25})),ot.createElement(Je,{width:i.descriptionWidth},ot.createElement(Qe,{color:nI.DIM,wrap:"truncate"},i.text))):n()})(),ot.createElement(Qe,{color:U?nI.GREEN:nI.GRAY},pt.line.repeat(Ne))),_&&ot.createElement(fN,null),s&&ot.createElement(cN,{onSelectFile:Ve,onClose:ze,searchQuery:l}),B&&ot.createElement(xI,{onSelectCommand:qe,onInsertCommand:Ke,onSubmitSearch:Ge,onClose:Ye,searchQuery:H,onSelectedCommandChange:z}),!B&&!s&&nt&&ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM,wrap:"truncate"},et)),!B&&!s&&!nt&&(rt||x||st)&&ot.createElement(gN,{termWidth:Ne,indicatorText:getIdeInputIndicatorText(Re,Ae,Ne),isIDEIndicator:hasIdeInputIndicatorContext(Re,Ae),permissionMode:E,prInfo:$e,contextUsage:u,tasteLearningOn:m,byokSession:isByok({model:C??""}),connectionIndicator:Le,pendingExitKey:x,updateStatus:w,updateFailedInfo:v,currentProvider:k,showProviderInfo:b,isBashMode:U,shareInfo:g,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,creditWarning:S,hasStashedPrompt:st,backgroundTasksArmed:re}),fe&&ot.createElement(Je,{paddingLeft:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.YELLOW},fe)),D)},"InputBox");Ht(),Qx();var SN=__name(()=>{const[e,t]=at([]);return lt(()=>subscribeModStatus(t),[]),0===e.length?null:ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,{wrap:"truncate"},e.map(e=>e.text).join(" ")))},"ModStatusLine");Ht(),Qx();var wN=__name(({messages:e})=>{const t=countVisibleQueuedMessages(e);if(0===t)return null;const n=getQueuedDisplayRows(e);return ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Je,{marginBottom:0},ot.createElement(Qe,{color:aI,inverse:!0},` Queued (${t}) `)),n.map(e=>ot.createElement(Je,{key:e.text},ot.createElement(Qe,{color:nI.DIM},pt.pointerSmall," "),ot.createElement(Qe,{color:nI.DIM},truncateString2({text:e.count>1?`${e.text} (${e.count})`:e.text,maxChars:80})))))},"QueuedMessages");function useWorkedDuration(e,t){const n=it(null),[r,o]=at(null);return lt(()=>{n.current=null,o(null)},[t]),lt(()=>{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:ot.createElement(Je,{marginLeft:1,marginBottom:1},ot.createElement(Qe,{color:nI.DIM},`✻ Worked for ${formatElapsedMs(e)}`))}Ht(),Qx(),__name(useWorkedDuration,"useWorkedDuration"),__name(WorkedDurationNote,"WorkedDurationNote");var vN=ot.memo(({queuedMessages:e,isProcessing:t,processingStartedAt:n=null,executionState:r,status:o,input:s,setInput:a,onSubmit:i,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:O,onDoubleEscapeEmpty:L,retryAttempt:D,onAltP:N,inputActive:$=!0,inactiveHint:_,sessionId:F})=>{const[U,j]=at(()=>null===n?0:Date.now()-n),B=it(s),W=t||r.isExecuting,H=useWorkedDuration(W,F);return lt(()=>{R&&s!==B.current&&s.length>0&&O?.(),B.current=s},[s,R,O]),lt(()=>{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]),ot.createElement(Je,{flexDirection:"column"},ot.createElement(wN,{messages:e}),ot.createElement(Je,{flexDirection:"row",justifyContent:"space-between"},ot.createElement(Je,{flexDirection:"column"},W&&null===D&&ot.createElement(sN,{tokens:p,timeElapsed:U,status:r.isExecuting?`Executing: ${r.currentCommand}`:o}),!W&&ot.createElement(WorkedDurationNote,{durationMs:H}),W&&null===D&&I&&ot.createElement(Je,{marginLeft:1},ot.createElement(Qe,{color:nI.DIM}," ","⎿"," ","Tip: ",I)))),$?ot.createElement(yN,{input:s,setInput:a,onSubmit:i,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:L,onAltP:N,isProcessing:t,footer:ot.createElement(SN,null)}):ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{marginLeft:1},ot.createElement(HA,null,_??"Background focused · ↑/↓ to select · Enter to view · x to stop · ←/Esc to go back to feed")),ot.createElement(SN,null)))});Ht();var kN=__name(({onComplete:e,onCancel:t})=>{const{authState:n,statusMessage:r,browserUrl:o,apiKeyInput:s,setApiKeyInput:a,handleApiKeySubmit:i,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 tt((e,t)=>{t.ctrl&&"c"===e&&l()}),ot.createElement(tR,{authState:n,statusMessage:r,browserUrl:o,apiKeyInput:s,setApiKeyInput:a,handleApiKeySubmit:i})},"LoginOverlay");function getStatusTextColor(e){return"connected"===e?nI.GREEN:"connecting"===e||"authenticated"===e?nI.CYAN:"requires_auth"===e?nI.YELLOW:nI.GRAY}Ht(),Qx(),__name(getStatusTextColor,"getStatusTextColor");var CN=__name((e,t)=>{const n=__name((e,n)=>ot.createElement(Qe,{color:e,backgroundColor:t},n),"icon");return"connected"===e?n(nI.GREEN,pt.tick):"connecting"===e?n(nI.CYAN,pt.circle):"authenticated"===e?n(nI.CYAN,pt.tick):"requires_auth"===e?n(nI.YELLOW,pt.warning):"error"===e?n(nI.RED,pt.cross):n(nI.GRAY,pt.circle)},"getStatusIcon"),bN=__name(({onClose:e,mcp:t})=>{const[n,r]=at([]),[o,s]=at(!0),[a,i]=at(0),[l,c]=at("list"),[d,u]=at(null),[m,p]=at(0),g=useTerminalHeight(),h=dt(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]);lt(()=>{h()},[h]),lt(()=>{if(t)return t.onChange(()=>{h()})},[t,h]);const f=ct(()=>[...orderMcpManagerServers(n)],[n]),y=f[a]??null,S=g-1,w=ct(()=>new Set(f.map(e=>e.scope)).size,[f]),v=Math.max(4,S-8-2*w);lt(()=>{p(e=>clampScrollOffset({cursor:a,total:f.length,maxVisible:v,currentOffset:e}))},[a,f.length,v]),tt((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&&(i(e=>Math.max(0,e-1)),u(null)),n.downArrow){if(0===f.length)return;const e=Math.max(0,f.length-1);i(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:nI.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:y.name,enabled:!0,scope:y.scope}))return void u({text:`${pt.cross} Failed to enable ${y.name}, server may no longer exist in ${y.scope} scope`,color:nI.YELLOW});await h(),u({text:`${pt.tick} Enabled ${y.name}`,color:nI.GREEN})}catch(e){u({text:`${pt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:nI.RED})}}else{u({text:`Disabling ${y.name}...`,color:nI.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:y.name,enabled:!1,scope:y.scope}))return void u({text:`${pt.cross} Failed to disable ${y.name}, server may no longer exist in ${y.scope} scope`,color:nI.YELLOW});await disconnectMcpServer({name:y.name,registry:t}),await h(),u({text:`${pt.tick} Disabled ${y.name}`,color:nI.GREEN})}catch(e){u({text:`${pt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:nI.RED})}}else c("confirm-remove");else{u({text:`Authenticating ${y.name}...`,color:nI.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:nI.YELLOW});"success"===e.kind?(u({text:`${pt.tick} Authenticated with ${y.name}`,color:nI.GREEN}),await h()):u({text:`${pt.cross} Auth failed: ${e.message}`,color:nI.RED})}catch(e){u({text:`${pt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:nI.RED})}}else{u({text:`Connecting ${y.name}...`,color:nI.CYAN,loading:!0});try{await connectMcpServer({name:y.name,registry:t}),u({text:`${pt.tick} Connected to ${y.name}`,color:nI.GREEN}),await h()}catch(e){u({text:`${pt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:nI.RED})}}else u({text:"Already authenticated",color:nI.GREEN});else u({text:"Already connected",color:nI.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(),i(e=>Math.min(e,Math.max(0,f.length-2)))}catch(e){u({text:`${pt.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:nI.RED}),c("actions")}else c("actions")},"handleRemoveConfirm");if(o)return ot.createElement(ZA,{title:"Manage MCP servers"},ot.createElement(Qe,{color:nI.DIM},"Loading..."));if("confirm-remove"===l&&y)return ot.createElement(ZA,{title:`Remove ${y.name}?`,titleColor:nI.RED,hint:"↑↓ navigate · Enter to select · Esc to cancel"},ot.createElement(Qe,{color:nI.DIM},"This will remove the server from ",y.scope," ","config."),ot.createElement(Je,{marginTop:1},ot.createElement(SelectInput,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:C,indicatorComponent:YL,itemComponent:qL})));if("actions"===l&&y){const e=buildMcpManagerActionItems(y);return ot.createElement(ZA,{title:y.name,hint:"↑↓ navigate · Enter to select · Esc to go back"},ot.createElement(Je,null,CN(y.status),ot.createElement(Qe,{color:nI.DIM}," ",getMcpManagerStatusText(y))),ot.createElement(Je,{marginTop:1},ot.createElement(SelectInput,{items:[...e],onSelect:k,indicatorComponent:YL,itemComponent:qL})),d&&ot.createElement(Je,{marginTop:1},d.loading&&ot.createElement(Qe,{color:d.color},ot.createElement(vt,{type:"dots"})," "),ot.createElement(Qe,{color:d.color},d.text)))}let b=null;const E=m,T=m+v,P=f.slice(E,T),M=f.length>v;return ot.createElement(ZA,{title:"Manage MCP servers",hint:0===n.length?"Esc to close":"↑↓ navigate · Enter to select · Esc to close"},ot.createElement(Qe,{color:nI.DIM},n.length," ",1===n.length?"server":"servers"),0===n.length?ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},"No MCP servers configured."),ot.createElement(Qe,{color:nI.DIM},'Use "',getBinaryCommand(),' mcp add" to add a server.'),ot.createElement(BI,{url:"https://commandcode.ai/docs/mcp",text:"View MCP Docs ↗",color:nI.CYAN,dimColor:!0})):ot.createElement(Je,{marginTop:1,flexDirection:"column"},P.map((e,t)=>{const n=E+t,r=e.scope!==b;b=e.scope;const o=n===a;return ot.createElement(ot.Fragment,{key:e.name},r&&ot.createElement(Je,{marginTop:0===t?0:1},ot.createElement(Qe,{bold:!0},getMcpManagerScopeLabel(e.scope)),ot.createElement(Qe,{color:nI.DIM}," ","(",getMcpManagerScopePath(e.scope),")")),ot.createElement(Je,null,ot.createElement(Qe,{color:o?nI.WHITE:void 0,backgroundColor:o?TI:void 0,bold:o},e.name),ot.createElement(Qe,{color:nI.DIM,backgroundColor:o?TI:void 0}," · "),CN(e.status,o?TI:void 0),ot.createElement(Qe,{color:getStatusTextColor(e.status),backgroundColor:o?TI:void 0}," ",getMcpManagerStatusText(e)," ")))})),M&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",E+1,"–",Math.min(T,f.length)," of"," ",f.length,E>0?" · ↑ more":"",T<f.length?" · ↓ more":"")),d&&ot.createElement(Je,{marginTop:1},d.loading&&ot.createElement(Qe,{color:d.color},ot.createElement(vt,{type:"dots"})," "),ot.createElement(Qe,{color:d.color},d.text)))},"McpManager");Ht(),Qx();var EN=__name(({onClose:e})=>{const[t,n]=at([]),[r,o]=at(0),[s,a]=at(!0),[i,l]=at(null);lt(()=>{__name(async()=>{try{const e=await discoverCommandMemoryFiles(process.cwd());n(e),a(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),a(!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(tt((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 ot.createElement(ZA,{title:"Select memory to edit:"},ot.createElement(Qe,{color:nI.DIM},"Loading memory files..."));if(i)return ot.createElement(ZA,{title:"Select memory to edit:"},ot.createElement(Qe,{color:nI.RED},pt.cross," ",i));const u=projectMemorySelectorOptions(d);return ot.createElement(ZA,{title:"Select memory to edit:",hint:"↑/↓ to navigate · enter to edit · esc to cancel"},ot.createElement(Je,{columnGap:4},ot.createElement(Je,{flexDirection:"column"},u.map((e,t)=>ot.createElement(Je,{key:e.label},ot.createElement(WL,{isSelected:r===t}),ot.createElement(HL,{isSelected:r===t,idleColor:QA}," ",e.label)))),ot.createElement(Je,{flexDirection:"column"},u.map((e,t)=>ot.createElement(HL,{key:e.label,isSelected:r===t,idleColor:QA},e.description)))))},"MemorySelector");function linkImageTokens(e,t){if(!t)return e;const n=new RegExp(CT.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)?nI.DIM:nI.RED,s=r?getSpecialUserMessageContent({content:e,billingUrl:Go}):linkImageTokens(e,n);return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{backgroundColor:r?void 0:gI.BG,paddingRight:1},ot.createElement(Qe,{color:r?o:gI.POINTER,bold:!r},pt.pointer),ot.createElement(Je,{marginLeft:1},ot.createElement(Qe,{color:r?o:gI.FG,wrap:"wrap"},s))),t&&!r&&ot.createElement(Je,{marginLeft:2},ot.createElement(Qe,{color:EI},YI),ot.createElement(Qe,{color:nI.DIM}," ","Selected ",t.lines," ",1===t.lines?"line":"lines"," from"," ",t.file," in ",t.ide)))}Ht(),Qx(),Ht(),Qx(),__name(linkImageTokens,"linkImageTokens"),__name(UserMessage,"UserMessage");var TN=pt.squareSmallFilled;function goalStatusGlyph(e){return"completed"===e?pt.tick:"paused"===e?"⏸":"idle"===e?pt.circle:TN}function goalStatusHeadColor(e){return"completed"===e?nI.GREEN:"paused"===e?nI.YELLOW:nI.DIM}function goalNoticeGlyph(e){return"cleared"===e?pt.tick:"none"===e?pt.circle:"paused"===e?"⏸":TN}function AutoCompactMessage({content:e}){return ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},TN," ",e))}function ZdrPausedMessage(){return ot.createElement(Je,{marginTop:1,marginBottom:1},ot.createElement(Qe,null,ot.createElement(Qe,{color:nI.DIM},TN," "),ot.createElement(Qe,{color:nI.DIM},"Per-task model overrides reverted to ZDR safe defaults. Run"," "),ot.createElement(Qe,{color:vI.CODE},"/config"),ot.createElement(Qe,{color:nI.DIM}," to review · esc to dismiss")))}function ModelNoticeMessage({text:e}){return ot.createElement(Je,{marginTop:1,marginBottom:1},ot.createElement(Qe,null,ot.createElement(Qe,{color:nI.DIM},TN," "),ot.createElement(Qe,{color:nI.DIM},e),ot.createElement(Qe,{color:nI.DIM}," · esc to dismiss")))}function TasteSkipMessage(){return ot.createElement(Je,{marginTop:1,marginBottom:1},ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:oI.BADGE_BG,color:oI.BADGE_FG,bold:!0},XI)),ot.createElement(Qe,{color:nI.DIM}," Skipped. Run "),ot.createElement(Qe,{color:vI.CODE},"/learn-taste"),ot.createElement(Qe,{color:nI.DIM}," or "),ot.createElement(Qe,{color:vI.CODE},"cmd learn-taste"),ot.createElement(Qe,{color:nI.DIM}," anytime."))}function TasteNoticeMessage({notice:e}){const t=e.path?`${tasteDirForRoot({projectRoot:process.cwd()})}/${e.path}`:null;return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:oI.BADGE_BG,color:oI.BADGE_FG,bold:!0},XI)),ot.createElement(Qe,{color:oI.TEXT}," ",e.label)),ot.createElement(Je,{columnGap:1,marginLeft:1},ot.createElement(Qe,{color:EI},YI),ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{wrap:"wrap"},e.text,e.confidence&&ot.createElement(Qe,{color:nI.DIM},` [Confidence ${e.confidence}]`)))),e.path&&t&&ot.createElement(Je,{marginLeft:3},ot.createElement(BI,{url:fileUrl(t),text:e.path,color:nI.DIM})))}function SkillLoadedMessage({name:e}){return ot.createElement(Je,null,ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:lI.BG,color:lI.FG,bold:!0},`${QI}SKILL${QI}`)),ot.createElement(Qe,null," ",e),ot.createElement(Qe,{color:nI.DIM}," loaded"))}function HookWarningMessage({content:e}){return ot.createElement(Je,null,ot.createElement(Qe,{color:nI.YELLOW},pt.warning),ot.createElement(Je,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.YELLOW},e)))}function HookLineMessage({content:e}){return ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},` ${e}`))}function HookLineContinuationMessage({content:e}){return ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},` ${e}`))}function HookFrameMessage({lines:e,header:t}){return ot.createElement(Je,{flexDirection:"column"},void 0!==t&&ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},` ${t}`)),e.map((e,t)=>ot.createElement(Je,{key:t,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},e.primary?` └ ${e.text}`:` ${e.text}`))))}function GoalLineMessage({content:e,subline:t}){return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:EI},YI),ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"}," ",e)),t?ot.createElement(Je,{marginLeft:4,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"},t)):null)}function GoalAcceptMessage({command:e,acceptLine:t,hint:n}){return ot.createElement(Je,{flexDirection:"column"},ot.createElement(UserMessage,{content:e}),ot.createElement(GoalLineMessage,{content:t,subline:n}))}function GoalCompleteMessage({elapsed:e,turns:t,goal:n}){const r=`${t} ${1===t?"turn":"turns"}`;return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,null,ot.createElement(Qe,{color:nI.GREEN},pt.tick," Goal achieved"),ot.createElement(Qe,{color:nI.DIM},` (${e} · ${r})`))),ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"},"Goal: ",n)))}function GoalStatusMessage({state:e,headline:t,goal:n,detail:r,hint:o}){const s=goalStatusGlyph(e),a=goalStatusHeadColor(e);return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:a},s," ",t)),ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"},n)),r?ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"},r)):null,o?ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},o)):null)}function BranchResultMessage({title:e}){return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},e?ot.createElement(Qe,null,ot.createElement(Qe,{color:nI.GREEN},"⑂ Forked."),ot.createElement(Qe,null," You're now in "),ot.createElement(Qe,{bold:!0},'"',e,'"')):ot.createElement(Qe,null,ot.createElement(Qe,{color:nI.GREEN},"⑂ Forked."),ot.createElement(Qe,null," You're now in the new session"))),ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},"Original session saved · /resume to switch back")))}function SessionFileMessage({sessionId:e,fileLine:t}){return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},TN," Session ID: "),ot.createElement(Qe,null,e)),ot.createElement(Je,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:EI},YI," "),ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"},t)))}function InfoMessage({content:e,metadata:t}){if(t?.isTasteSkip)return ot.createElement(TasteSkipMessage,null);if(t?.tasteNotice)return ot.createElement(TasteNoticeMessage,{notice:t.tasteNotice});if(t?.skillLoaded)return ot.createElement(SkillLoadedMessage,{name:t.skillLoaded.name});if(t?.isAutoCompact)return ot.createElement(AutoCompactMessage,{content:e});if(t?.hookFrame&&t.hookFrame.length>0)return ot.createElement(HookFrameMessage,{lines:t.hookFrame,header:t.hookFrameHeader});if(t?.isHookLine)return ot.createElement(HookLineMessage,{content:e});if(t?.isHookLineContinuation)return ot.createElement(HookLineContinuationMessage,{content:e});if(t?.isHookWarning)return ot.createElement(HookWarningMessage,{content:e});if(t?.isSuccess)return ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.GREEN},pt.tick," ",e));if(t?.isGoalAccept)return ot.createElement(GoalAcceptMessage,{command:e,acceptLine:t.goalAcceptLine??"",hint:t.goalSubline});if(t?.isGoalComplete)return ot.createElement(GoalCompleteMessage,{elapsed:t.goalElapsed??"",turns:t.goalTurns??1,goal:t.goalText??""});if(t?.isGoalStatus)return ot.createElement(GoalStatusMessage,{state:t.goalState??"running",headline:t.goalHeadline??"",goal:t.goalText??"",detail:t.goalDetail,hint:t.goalSubline});if(t?.isBranchResult)return ot.createElement(BranchResultMessage,{title:t.branchTitle});if(t?.isSessionFile)return ot.createElement(SessionFileMessage,{sessionId:t.sessionFileId??"",fileLine:t.sessionFileLine??""});if(t?.isGoalNotice){const n=goalNoticeGlyph(t.goalNoticeKind);return ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},n," ",e))}return t?.isGoalLine?ot.createElement(GoalLineMessage,{content:e,subline:t.goalSubline}):ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM},TN," ",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"),Ht(),Qx(),Ht(),Ht(),Ht(),Ht();var PN=/\[\^[^\]]+\]/;function splitMarkdownBlocks(e){return e?PN.test(e)?[e]:ft.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),a=[];let i=0;for(const o of s){const s=i+o.length;if(s<=e.length){if(e.slice(i,s)!==o)return n=!0,frozenAdvance(r)}else{if(i!==e.length)return n=!0,frozenAdvance(r);a.push(o),e+=o,isWhitespaceOnly2(o)||(t+=1)}i=s}return{newlyCompleted:a,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"),Ht();var MN=String.fromCharCode(8203),xN=new Set(["_","~","*","`"]),IN=/!?\[[^\]]*\]\([^)]*$/,AN=/!?\[[^\]]*$/;function isSpace(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function isOnlyMarkersOrSpace(e){for(const t of e)if(!isSpace(t)&&!xN.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 a=e[s];"\\"!==a?e.startsWith("```",s)?(r=!r,s+=2):r||("`"!==a?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(IN);if(void 0!==t?.index)return e.slice(0,t.index).trimEnd();const n=e.match(AN);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}${MN}`: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 RN=Ct()?"⠶":"#";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 ot.createElement(Je,null,n?ot.createElement(Je,{width:2,flexShrink:0}):ot.createElement(Qe,{color:hI},RN),ot.createElement(Je,{marginLeft:n?0:1,flexGrow:1,flexShrink:1,minWidth:0,flexDirection:"column"},ot.createElement(Markdown,{maxPhysicalRows:t?streamingMaxRows(r):void 0},o)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o=nI.GREEN,s=pt.tick,a="default",i=t||"(No output)";n&&(o=nI.YELLOW,s=pt.arrowRight,a=nI.YELLOW,i="Executing…"),r&&(o=nI.RED,s=pt.cross,a=nI.RED);const l=ct(()=>buildTreeConnectors(i),[i]);return ot.createElement(Je,null,ot.createElement(Qe,{color:o},s),ot.createElement(Je,{flexDirection:"column",marginLeft:1},ot.createElement(Je,null,ot.createElement(Qe,{color:nI.GRAY},"$ "),ot.createElement(Qe,{color:o,bold:!0},e)),ot.createElement(Je,{columnGap:1,marginLeft:1},ot.createElement(Qe,{color:EI},l),ot.createElement(Qe,{color:a,wrap:"wrap"},i))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?nI.YELLOW:void 0,o=ct(()=>buildTreeConnectors(e),[e]);return ot.createElement(Je,{flexDirection:"column",marginBottom:0,marginTop:-1},ot.createElement(Je,{columnGap:1},ot.createElement(Qe,{color:EI},o),ot.createElement(Je,{flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:r},e))),t&&ot.createElement(Je,{marginLeft:3},ot.createElement(Qe,{color:nI.DIM},"See ",t)))}function ErrorMessage({content:e}){return isInterruptedByUserMessage(e)?ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},pt.pointer),ot.createElement(Je,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Qe,{color:nI.DIM,wrap:"wrap"},jf))):ot.createElement(Je,null,ot.createElement(Qe,{color:nI.RED},pt.warning),ot.createElement(Je,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},ot.createElement(Markdown,{color:nI.RED},e)))}__name(streamingMaxRows,"streamingMaxRows"),__name(AssistantMessage,"AssistantMessage"),Ht(),__name(BashMessage,"BashMessage"),Ht(),__name(CommandResultMessage,"CommandResultMessage"),Ht(),Qx(),__name(ErrorMessage,"ErrorMessage"),Ht(),Qx();var ON={connected:{char:pt.tick,color:nI.GREEN},installed:{char:pt.tick,color:nI.GREEN},up_to_date:{char:pt.tick,color:nI.GREEN},needs_reload:{char:pt.circle,color:nI.YELLOW},failed:{char:pt.cross,color:nI.RED},not_in_ide:{char:pt.circle,color:nI.YELLOW}};function IDEStatusMessage({status:e,ide:t,details:n}){const{prefix:r,ide:o,suffix:s}=getIDESetupStatusHeadline(e,t),a=ON[e];return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,null,ot.createElement(Qe,{color:a.color},a.char),ot.createElement(Qe,null," ",r),o&&ot.createElement(Qe,{color:nI.CYAN},o),s&&ot.createElement(Qe,null,s))),n?.map(e=>ot.createElement(Qe,{key:e,color:nI.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 ot.createElement(Je,{flexDirection:"column",width:"90%"},ot.createElement(Je,null,ot.createElement(Qe,{color:sI},"✻"," "),ot.createElement(Qe,{color:sI},o.showExpandHint?`${o.headerLabel} `:o.headerLabel),o.showExpandHint&&ot.createElement(BracketWrap,{color:nI.DIM},o.expandHint)),o.showBody&&o.hiddenAboveLabel&&ot.createElement(Je,{marginLeft:2},ot.createElement(Qe,{color:nI.DIM},o.hiddenAboveLabel)),o.showBody&&ot.createElement(Je,{marginLeft:2,flexDirection:"column"},ot.createElement(Qe,{color:sI,wrap:"wrap",italic:!0},o.bodyText)))}__name(IDEStatusMessage,"IDEStatusMessage"),Ht(),Qx(),__name(reasoningBodyColumns,"reasoningBodyColumns"),__name(ReasoningMessage,"ReasoningMessage"),Ht(),Qx(),Ht(),Qx();function HelpMessage(){const e=getInvokedCommandName(),t=ct(()=>getVisibleSlashCommands(),[]);return ot.createElement(Je,{flexDirection:"column",paddingY:1},ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Je,null,ot.createElement(Qe,{bold:!0},"Command Code"),ot.createElement(Qe,{color:nI.GRAY}," v","1.32.2-rc.0")),ot.createElement(Qe,{color:nI.GRAY},Hs)),ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{bold:!0},"Usage"),ot.createElement(Je,{paddingLeft:2},ot.createElement(Qe,null,e," <command> [options]"))),ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{bold:!0},"Options"),ot.createElement(Je,{flexDirection:"column",paddingLeft:2},Ys.map(t=>ot.createElement(Je,{key:t.key},ot.createElement(Qe,null,t.key.replace(/^cmd/,e).padEnd(Gs)),ot.createElement(Qe,{color:nI.GRAY},t.description))))),ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{bold:!0},"Commands"),ot.createElement(Je,{flexDirection:"column",paddingLeft:2},Qs.map(t=>ot.createElement(Je,{key:t.key},ot.createElement(Qe,null,t.key.replace(/^cmd/,e).padEnd(Gs)),ot.createElement(Qe,{color:nI.GRAY},t.description))))),ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{bold:!0},"Slash Commands"),ot.createElement(Je,{flexDirection:"column",paddingLeft:2},t.map(e=>ot.createElement(Je,{key:e.key},ot.createElement(Qe,null,e.key.padEnd(Gs)),ot.createElement(Qe,{color:nI.GRAY},e.description))))),ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{bold:!0},"Keyboard Shortcuts"),ot.createElement(Je,{flexDirection:"column",paddingLeft:2},qs.map(e=>ot.createElement(Je,{key:e.key},ot.createElement(Qe,null,e.key.padEnd(Gs)),ot.createElement(Qe,{color:nI.GRAY},e.description))))),ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Qe,{bold:!0},"Examples"),ot.createElement(Je,{flexDirection:"column",paddingLeft:2},Zs.map(t=>ot.createElement(Je,{key:t.key},ot.createElement(Qe,null,t.key.replace(/^cmd/,e).padEnd(Gs)),ot.createElement(Qe,{color:nI.GRAY},t.description))))),ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.CYAN},pt.pointer),ot.createElement(Qe,{color:nI.GRAY}," ",Vs.replace(/cmd/,e))),ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{bold:!0},"Links"),ot.createElement(Je,{flexDirection:"column",paddingLeft:2},Xs.map(e=>ot.createElement(Je,{key:e.key},ot.createElement(Qe,null,e.key.padEnd(Gs)),ot.createElement(Qe,{color:nI.CYAN},e.description))))))}function SystemMessage({content:e}){return isHelpSystemEntryContent(e)?ot.createElement(HelpMessage,null):ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{wrap:"wrap"},ot.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 ot.createElement(UserMessage,{content:e.input,ideHint:t,imageTokenPaths:n})}return"assistant"===e.role?ot.createElement(AssistantMessage,{content:e.input,isStreaming:"running"===e.metadata?.status,continuation:!0===e.metadata?.continuation}):"reasoning"===e.role?ot.createElement(ReasoningMessage,{content:e.input,expandedOutput:t,expandKey:"ctrl",isStreaming:"running"===e.metadata?.status}):"tool"===e.role?ot.createElement(ToolMessage,{name:Mg(e.name||""),input:e.input,output:e.output||"",isPending:bg(e),hasError:Cg(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?ot.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:bg(e),hasError:Cg(e)}):"system"===e.role?ot.createElement(SystemMessage,{content:e.input}):"info"===e.role?ot.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?ot.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?ot.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?ot.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 LN=__name(e=>getModelShortName({modelId:e,findModelById:findModelById}),"getModelShortName");function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages [${db?"ctrl+y":"ctrl+e"} to expand more] `,r=Math.max(0,Math.floor((t-n.length)/2)),o="─".repeat(r);return ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:pI},o),ot.createElement(BracketedText,{text:n,color:pI}),ot.createElement(Qe,{color:pI},o))}__name(TranscriptDivider,"TranscriptDivider");var DN=ot.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o,currentEffort:s=null,currentProvider:a,hiddenCount:i=0})=>{const l=i>0?{role:"transcript-divider",count:i}:null,c=[...t?["header"]:[],...l?[l]:[],...e],d=useTerminalWidth(),u=ct(()=>RA(d),[d]),m=ct(()=>$A(d),[d]),p=ct(()=>getPackageJson(import.meta.url).version||"0.0.0",[]),g=ct(()=>getGitHeaderInfo(),[]),h=ct(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),f=o?LN(o):"sonnet-4.6",y=Boolean(o&&byokProviderId({model:o}))?"":" · taste-1",S=ct(()=>{if(!o)return"";if(!modelSupportsReasoningEffort(o))return"";const e=null===s?getReasoningEffort(o):s;return e?` with ${e} effort`:""},[s,o,n]),w=ct(()=>{const e=o?byokProviderId({model:o}):void 0;return e?` · ${e} (byok)`:a&&a!==ro.COMMAND?` · ${getProviderShortName(a)} (byok)`:""},[o,a,n]);return ot.createElement(Xe,{items:c,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return ot.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:d});if("header"===e)return"compact"===m?ot.createElement(Je,{key:"header",marginBottom:1,flexDirection:"row"},ot.createElement(Je,{width:DA,flexShrink:0},ot.createElement(PI,null,LA)),ot.createElement(Je,{flexDirection:"column",marginLeft:2},ot.createElement(Je,null,ot.createElement(Qe,{bold:!0},"Command Code"),ot.createElement(Qe,{color:pI}," ","v",p)),ot.createElement(Qe,{color:pI},"models: ",f,S,y,w),ot.createElement(Qe,{color:pI},h,g&&g.isLocal&&g.branch&&` (${g.branch})`))):ot.createElement(Je,{key:"header",marginBottom:1,flexDirection:"column"},ot.createElement(PI,null,u.trimEnd()),ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Je,null,ot.createElement(Qe,{color:pI},"# "),ot.createElement(Qe,{bold:!0},"Command Code"),ot.createElement(Qe,{color:pI}," v",p)),ot.createElement(Qe,{color:pI},"# models: ",f,S,y,w),ot.createElement(Je,null,ot.createElement(Qe,{color:pI},"# ",h,g&&g.isLocal&&g.branch&&ot.createElement(Qe,{color:pI}," ","(branch:"," ",g.branch,")")))));const t=e,n=renderFeedEntry(t,r);return ot.createElement(Je,{key:t.id,paddingBottom:1,width:"90%"},n)})});Ht(),Qx();var NN=st(__name(function LiveAgentStatusInner2({entry:e}){const t=Mg(e.name||"Agent"),n=summarizeAgentTaskInput(e.input||""),r=e.metadata?.tokensUsed||0,o=e.metadata?.elapsedSeconds||0,s=e.metadata?.recentTools||[],[a,i]=at(".");return lt(()=>{const e=setInterval(()=>{i(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),ot.createElement(Je,{flexDirection:"column",marginBottom:1,width:"90%"},ot.createElement(Je,null,ot.createElement(Qe,{backgroundColor:dI.BG,color:dI.FG,bold:!0},` ${t} `),n&&ot.createElement(Qe,null," (",n,")")),ot.createElement(Je,{columnGap:1,marginLeft:1},ot.createElement(Qe,null,"⎿"," "),ot.createElement(Qe,{color:nI.GRAY},"Running (",formatTime3(o)," |"," ",formatTokens(r),")",a)),s.length>0&&ot.createElement(Je,{flexDirection:"column",marginLeft:1},s.map((e,t)=>{const n=Mg(e.name);return ot.createElement(Je,{key:t,columnGap:1},ot.createElement(Qe,{color:nI.GRAY},"⎿"),ot.createElement(Qe,{color:nI.GRAY}," ",n),e.input&&ot.createElement(Qe,{color:nI.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),$N=st(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:ot.createElement(NN,{entry:e})},"LiveAgentStatus"));Ht(),Ht(),Qx();var _N=[],FN=_N,UN=!1,jN=null,BN="",WN=new Set,HN=new Set,GN=new Set;function shapeOf(e){return e.map(e=>e.content.replace(/\d+/g,"#")).join("\0")}function emit2(){for(const e of GN)e()}function cancelPeek(){jN&&clearTimeout(jN),jN=null,UN=!1}function armPeek(){jN&&clearTimeout(jN),UN=!0,jN=setTimeout(()=>{jN=null,UN=!1,emit2()},5e3),jN.unref?.()}function projectUserEdits(e){return e.filter(e=>!WN.has(e.content)).map(e=>"completed"!==e.status&&HN.has(e.content)?{...e,status:"completed"}:e)}function setSessionTodos(e){const t=projectUserEdits(e);if(t.length>0&&HN.size>0&&t.every(e=>"completed"===e.status))return void clearSessionTodos();const n=shapeOf(t),r=n!==BN;(r||JSON.stringify(t)!==JSON.stringify(FN))&&(FN=t.length>0?t:_N,BN=n,FN.length>0&&r&&armPeek(),emit2())}function adoptSettled(e){FN=e.length>0?[...e]:_N,BN=shapeOf(FN),cancelPeek(),emit2()}function seedSessionTodos(e){WN.clear(),HN.clear(),adoptSettled(e)}function removeSessionTodoAt(e){const t=FN[e];return t&&WN.add(t.content),adoptSettled(FN.filter((t,n)=>n!==e)),FN}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?Lg(r):null;if(o){if(o.every(e=>"completed"===e.status))break;return seedSessionTodos(o),FN}}return clearSessionTodos(),_N}function clearSessionTodos(){(FN!==_N||UN||0!==WN.size||0!==HN.size)&&(FN=_N,BN="",WN.clear(),HN.clear(),cancelPeek(),emit2())}function getSessionTodos(){return FN}function isTodoPanelCollapsed(){return!UN}function completeSessionTodoAt(e){const t=FN[e];return t&&HN.add(t.content),adoptSettled(FN.map((t,n)=>n===e?{...t,status:"completed"}:t)),FN}function completeAllSessionTodos(){const e=FN.map(e=>e.content);for(const t of e)HN.add(t);return adoptSettled(_N),e}function subscribe(e){return GN.add(e),()=>GN.delete(e)}function useSessionTodos(){return mt(subscribe,getSessionTodos)}function useTodoPanelCollapsed(){return mt(subscribe,isTodoPanelCollapsed)}function usePausedLabel(e){const[t,n]=at(!e);return lt(()=>{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`,a=n?currentTaskLabel(t):null;return ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(Je,null,ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:lI.BG,color:lI.FG,bold:!0},`${QI}TODOS${QI}`)),ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,null," ",ot.createElement(BracketWrap,null,s))),a&&ot.createElement(Je,{flexShrink:1,minWidth:0},ot.createElement(Qe,{color:r?nI.DIM:uI.IN_PROGRESS,bold:!r,wrap:"truncate-end"},` ${a}${r?" (paused)":""}`)),ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,null," ",ot.createElement(BracketWrap,{color:nI.DIM},n?"ctrl+x to expand":"ctrl+x to manage")))),!n&&ot.createElement(CappedChecklist,{todos:t}))}function CappedChecklist({todos:e}){const{foldedDone:t,visible:n,hiddenTail:r}=projectVisibleTodos(e);return ot.createElement(Je,{flexDirection:"column"},t>0&&ot.createElement(Je,{flexDirection:"row"},ot.createElement(Je,{width:2},ot.createElement(Qe,{color:uI.SUCCESS},pt.checkboxOn)),ot.createElement(Qe,{color:uI.SUCCESS,strikethrough:!0},t," completed")),ot.createElement(TodoChecklist,{todos:n}),r>0&&ot.createElement(Qe,{color:nI.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"),Ht();var VN=new Set,zN=!1;function isTodosManagerOpen(){return zN}function requestTodosManagerOpen(){for(const e of VN)e()}function statusColor(e){return"completed"===e?nI.GREEN:"in_progress"===e?nI.CYAN:nI.WHITE}function TodoRow({todo:e,selected:t}){const n="completed"===e.status?pt.checkboxOn:pt.checkboxOff,r=t?TI:void 0;return ot.createElement(Je,null,ot.createElement(WL,{isSelected:t,backgroundColor:r}),ot.createElement(Qe,{color:statusColor(e.status),backgroundColor:r}," ",n),ot.createElement(Qe,{color:t?YA:statusColor(e.status),strikethrough:"completed"===e.status,backgroundColor:r,wrap:"truncate-end"}," ",e.content),"in_progress"===e.status&&ot.createElement(Qe,{color:nI.DIM,backgroundColor:r}," ","(in progress)"))}function TodosManagerPanel({sessionId:e,onExpandedChange:t}){const n=useSessionTodos(),[r,o]=at(!1),[s,a]=at(0);lt(()=>(zN=r,t?.(r),()=>{zN=!1,t?.(!1)}),[r,t]),lt(()=>{const e=__name(()=>{a(0),o(!0)},"listener");return VN.add(e),()=>{VN.delete(e)}},[]),lt(()=>{if(0===n.length)return o(!1),void a(0);a(e=>Math.min(e,n.length-1))},[n.length]);const i=__name(t=>{$O(e)?.applyTodoUserEdit(t)},"syncHarness");if(tt((e,t)=>{if(t.escape||t.leftArrow||t.ctrl&&"x"===e||""===e)o(!1);else if(0!==n.length)if(t.upArrow)a(e=>Math.max(0,e-1));else if(t.downArrow)a(e=>Math.min(n.length-1,e+1));else{if("c"===e){const e=n[s];return void i({todos:completeSessionTodoAt(s),...e?{completedContents:[e.content]}:{}})}if("x"===e){const e=n[s];return void i({todos:removeSessionTodoAt(s),...e?{removedContents:[e.content]}:{}})}"a"===e&&i({todos:[],completedContents:completeAllSessionTodos()})}},{isActive:r}),!r)return null;const l=n.filter(e=>"completed"===e.status).length;return ot.createElement(ZA,{title:"Todos",subtitle:l>0?`${n.length} items · ${l} done`:`${n.length} items`,gapAfterHeader:!1,boxProps:{marginTop:1,marginBottom:1}},ot.createElement(Je,{flexDirection:"column",marginTop:1},n.map((e,t)=>ot.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"),Ht(),Qx(),Qx();var KN=__name(({currentModel:e,onClose:t,refreshBanner:n,sessionId:r})=>{const o=customReasoningEfforts(e)??getSupportedEfforts(e)??[],s=findModelById(e)?.label??getModelDisplayName(e),a=it(!1),i=__name(o=>{if(a.current)return;a.current=!0;const s=o!==getReasoningEffort(e);(async()=>{try{s&&(await setReasoningEffort({modelId:e,effort:o}),n(),void 0!==o&&r&&$O(r)?.recordEffortChange({model:e,effort:o}))}catch(e){dlog(`[Effort] Failed to persist reasoning effort: ${e}`)}finally{t()}})()},"handleSelect"),l=__name(()=>{a.current||t()},"handleCancel");return ot.createElement(xD,{modelLabel:s,supportedEfforts:o,currentEffort:getReasoningEffort(e),onSelect:i,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})}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 q(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 te(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??""))).map(([e,t])=>{const n=isPlainObject8(t.limit)?t.limit:void 0;return{id:e,..."string"==typeof t.name&&t.name?{name:t.name}:{},...void 0!==asPositive(n?.context)?{contextWindow:asPositive(n?.context)}:{},...void 0!==asPositive(n?.output)?{maxOutput:asPositive(n?.output)}:{}}}):[]}Ht(),Qx(),Ht(),Qx(),__name(store,"store"),__name(getCustomProviderKeyState,"getCustomProviderKeyState"),__name(getConfiguredKeyReference,"getConfiguredKeyReference"),__name(storeCustomProviderKey,"storeCustomProviderKey"),__name(getStoredKeyPreview,"getStoredKeyPreview"),__name(getStoredKeyToken,"getStoredKeyToken"),__name(clearCustomProviderKey,"clearCustomProviderKey"),Ht(),Qx(),Ht(),__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 qN=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(qN.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 a=curateModels(s.record.models);if(0===a.length)return null;const i=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,...i?{envVar:i}:{},models:a}}__name(listModelsDevProviders,"listModelsDevProviders"),__name(findModelsDevProvider,"findModelsDevProvider"),Ht();var YN=[{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}],JN=[{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"}],QN=/^[a-z0-9._-]+$/;function hostOf2(e){try{return new URL(e).hostname.toLowerCase()}catch{return}}function fallbackProviderSuggestions(){return[...JN,...YN]}async function loadProviderSuggestions(e){let t=[];try{t=await listModelsDevProviders(e?.fetchImpl?{fetchImpl:e.fetchImpl}:void 0)}catch{}const n=t.filter(e=>QN.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"),Ht();var XN=["/chat/completions","/completions","/responses","/messages","/models"];function normalizeEndpointInput(e){let t=e.trim().replace(/\/+$/,"");for(const e of XN)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),a=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!==a?{maxOutput:a}:{}})}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=nI.DIM}){const t=`${W()}/.commandcode/providers.json`;return ot.createElement(BI,{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}:{}}))}function cardKeyLine(e){return"stored"===e.keyState?ot.createElement(Qe,null,"key ",ot.createElement(Qe,{color:nI.GREEN},e.keyPreview)," ",ot.createElement(Qe,{color:nI.GREEN},"✓")," stored in auth.json",e.configuredReference?` · overrides ${e.configuredReference}`:""):"configured"===e.keyState?ot.createElement(Qe,null,"key ",e.configuredReference??"set"):"keyless"===e.keyState?ot.createElement(Qe,null,"no key — the endpoint asks for none"):ot.createElement(Qe,{color:nI.YELLOW},"no key yet, requests fail until one is added")}function cardHints(e){const t=[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"u")," update models"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"d")," delete"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," close")];return"stored"===e?[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," save"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"r")," replace key"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"c")," clear"),...t]:"missing"===e?[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," add key"),...t]:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"r")," store key"),...t]}function CustomProviderKeyEntry({providerId:e,providerName:t,keyState:n,keyPreview:r,configuredReference:o,onClose:s,onOpenModels:a,sessionId:i,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);ot.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(i?{sessionId:i}: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(i?{sessionId:i}: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");tt((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 a?.()):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?ot.createElement(ot.Fragment,null,S.baseURL," · ",S.modelCount," ",1===S.modelCount?"model":"models"," · config:"," ",ot.createElement(BI,{url:`file://${W()}/.commandcode/providers.json`,text:"providers.json",color:nI.DIM})):void 0;if("card"===m){const e=cardKeyLine({keyState:n,keyPreview:r,configuredReference:o}),s=cardHints(n);return ot.createElement(ZA,{title:t,titleSuffix:ot.createElement(Qe,{color:nI.DIM}," (byok)"),subtitle:T,footer:ot.createElement(VA,{hints:s,marginTop:0})},ot.createElement(Je,null,e))}return"confirm-remove"===m?ot.createElement(ZA,{title:`Remove ${t}?`,subtitle:"Its entry, models, and stored key go with it",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"y")," remove"),"any other key keeps it"]})},ot.createElement(Qe,null,"Deletes the entry from ",ot.createElement(ProvidersJsonLink,null)," and clears its stored key.")):"removing"===m||"updating-models"===m?ot.createElement(ZA,{title:t,rule:!1},ot.createElement(Qe,null,"removing"===m?`Removing '${e}'…`:`Refetching models for '${e}'…`)):"removed"===m?ot.createElement(ZA,{title:`${t} removed`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," close")]})},ot.createElement(Qe,{color:nI.DIM},"Provider deleted from ",ot.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?ot.createElement(ZA,{title:t,subtitle:T,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," back"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," close")]})},ot.createElement(Qe,{color:nI.GREEN},"Models updated — ",v?.count??0," declared from"," ",v?.source??"the refetch",".")):"saved"===m?ot.createElement(ZA,{title:`Key saved for ${t}`,subtitle:"Stored in ~/.commandcode/auth.json",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," pick a model"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," close")]})}):"cleared"===m?ot.createElement(ZA,{title:`Stored key cleared for ${t}`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," close")]})},ot.createElement(Qe,{color:nI.DIM},"Its models stay listed",o?" — the providers.json key applies again":"; requests will need a key again")):"error"===m?ot.createElement(ZA,{title:`Could not update ${t}`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," close")]})},ot.createElement(Qe,{color:nI.DIM},g??'Check that ~/.commandcode is writable, or set "apiKey" to a "$ENV_VAR" reference in providers.json')):ot.createElement(ZA,{title:`API key for ${t}`,subtitle:`Saved to ~/.commandcode/auth.json under '${e}'. requests go straight to this provider with your key`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," save"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," back")]})},ot.createElement(Je,{borderStyle:"single",borderColor:nI.YELLOW,paddingX:1,width:"100%"},ot.createElement(Qe,{color:nI.DIM},"key: "),ot.createElement(Je,{flexGrow:1},ot.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 ot.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 ot.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 ZN=[{value:"openai-completions",label:"OpenAI-compatible",detail:"/chat/completions · Ollama, vLLM, LM Studio, most hosted APIs"},{value:"anthropic-messages",label:"Anthropic wire",detail:"/v1/messages · endpoints speaking the Claude Messages API"}],e$=[["{",""],[' "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`:e.anthropicWire?"The Messages API root · /v1 is added on the wire when missing":"The API root requests go to · most end in /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,a]=at("openai-completions"),[i,l]=at(""),[c,d]=at(""),[u,m]=at(""),[p,g]=at("id"),[h,f]=at(()=>fallbackProviderSuggestions());ot.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=ot.useRef(null),P=ot.useRef("api"),M=ot.useRef([]),[x,I]=at(void 0),[A,R]=at(0),[O,L]=at(void 0),D=""===c.trim(),N=idStepMatches({phase:p,query:r,providers:h}),$=__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");tt((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&&!i||"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)&&a(e=>"openai-completions"===e?"anthropic-messages":"openai-completions"),void(o.return&&$("endpoint"))):"done"===p&&o.return?(e(),void t?.()):void("error"===p&&o.return&&e());(o.upArrow||o.downArrow)&&N.length>0&&v(e=>{const t=N.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:N[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),a(e.wire),l(e.baseURL),v(null),void $("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&&(a(n.wire),l(n.baseURL)),$("api")},"submitId"),j=__name(()=>{const{url:e,stripped:t}=normalizeEndpointInput(i);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),$("key")}else C("http:// or https:// URLs only.")},"submitEndpoint"),B=__name(async()=>{g("probing");const e=c.trim();let t=await probeProviderModels({baseURL:i,...e?{apiKey:e}:{}});t.ok||"anthropic-messages"!==s||i.endsWith("/v1")||(t=await probeProviderModels({baseURL:`${i}/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 L("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:i,api:s,keyless:D,models:toNewProviderModels(e)}),R(e.length),await refreshCustomProviderModels(n?{sessionId:n}:void 0),g("done")}catch(e){L(e instanceof Error?e.message:String(e)),g("error")}},"writeEntry"),V=k?ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.RED},k)):null,z=r.trim()?`Add a provider · ${r.trim().toLowerCase()}`:"Add a provider";if("saving"===p||"probing"===p)return ot.createElement(ZA,{title:z,rule:!1},ot.createElement(Qe,null,"probing"===p?`Asking ${i} which models it serves…`:`Writing '${r}' to ~/.commandcode/providers.json…`));if("done"===p)return ot.createElement(ZA,{title:`'${r}' is set up`,subtitle:`${A} ${1===A?"model":"models"} declared${D?" · keyless endpoint":" · key stored in auth.json"}`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," pick a model"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," close")]})},ot.createElement(Qe,{color:nI.DIM},"Provider added to ",ot.createElement(ProvidersJsonLink,null),". Edit it anytime, it reloads live."));if("error"===p)return ot.createElement(ZA,{title:`Adding '${r}' didn't finish`,footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," close")]})},ot.createElement(Qe,{color:nI.DIM},O));if("help"===p)return ot.createElement(ZA,{title:"Adding a provider: the short version",footer:ot.createElement(Je,{flexDirection:"column"},ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,"docs:"," ",ot.createElement(BI,{url:"https://commandcode.ai/docs/byok",text:"commandcode.ai/docs/byok",color:nI.DIM})),"any key to go back"]}))},ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},"• provider id names the entry in ",ot.createElement(ProvidersJsonLink,null)," · models select as id/model"),ot.createElement(Qe,{color:nI.DIM},"• endpoint is the base URL requests go to · most end in /v1"),ot.createElement(Qe,{color:nI.DIM},"• pasted keys go to auth.json · providers.json only ever holds $ENV_VAR or !command references"),ot.createElement(Qe,{color:nI.DIM},"• no key needed? press enter on the empty key field (local servers)"),ot.createElement(Qe,{color:nI.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"),ot.createElement(Qe,{color:nI.DIM},"• the ",ot.createElement(ProvidersJsonLink,null)," file is yours · edit it anytime, it reloads live · manage it from /connect"),ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Qe,{color:nI.DIM},"what it writes:"),e$.map(([e,t])=>ot.createElement(Qe,{key:e},ot.createElement(Qe,{color:nI.CYAN}," ",e),t?ot.createElement(Qe,{color:nI.DIM}," ","// ",t):null)))));if("manual-models"===p)return ot.createElement(ZA,{title:z,subtitle:x?`Couldn't list models automatically — ${x}`:`Which models does ${r} serve?`,footer:ot.createElement(VA,{marginTop:0,hints:["comma-separated, exact ids",ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," save"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," back")]})},ot.createElement(Je,{borderStyle:"single",borderColor:nI.YELLOW,paddingX:1,width:"100%"},ot.createElement(Qe,{color:nI.DIM},"models: "),ot.createElement(Je,{flexGrow:1},ot.createElement(TextInput,{value:u,onChange:m,onSubmit:H,placeholder:"llama3.3:70b, qwen2.5-coder:32b",showCursor:!0}))));if("key"===p)return ot.createElement(ZA,{title:z,subtitle:"Keys live in ~/.commandcode/auth.json, never in providers.json",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," save"),"empty enter = keyless (local servers)",ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," back")]})},ot.createElement(Je,{borderStyle:"single",borderColor:nI.YELLOW,paddingX:1,width:"100%"},ot.createElement(Qe,{color:nI.DIM},"key: "),ot.createElement(Je,{flexGrow:1},ot.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 ot.createElement(ZA,{title:z,subtitle:"What does the endpoint speak?",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"↑/↓")," switch"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," continue"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"h")," help"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," back")]})},ot.createElement(Je,{flexDirection:"column"},ZN.map(e=>ot.createElement(Qe,{key:e.value},s===e.value?"❯ ":" ",ot.createElement(Qe,{bold:s===e.value},e.label),ot.createElement(Qe,{color:nI.DIM}," · ",e.detail)))));if("endpoint"===p){const e="anthropic-messages"===s,t=y&&i===y.baseURL;return ot.createElement(ZA,{title:z,subtitle:endpointSubtitle({prefilledName:t?y.name:void 0,anthropicWire:e}),footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," continue"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," back")]})},ot.createElement(Je,{borderStyle:"single",borderColor:nI.YELLOW,paddingX:1,width:"100%"},ot.createElement(Qe,{color:nI.DIM},"base URL: "),ot.createElement(Je,{flexGrow:1},ot.createElement(TextInput,{value:i,onChange:e=>{l(e),C(void 0),E(void 0)},onSubmit:j,placeholder:e?"https://api.example.com/anthropic":"http://localhost:11434/v1",showCursor:!0}))),b&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.YELLOW},b)),V)}const K=null===w?0:Math.min(Math.max(0,w-6+1),Math.max(0,N.length-6)),q=N.slice(K,K+6),Y=N.length-(K+q.length);return ot.createElement(ZA,{title:"Add a provider",subtitle:"Pick a known provider below, or type your own id.",footer:ot.createElement(VA,{marginTop:0,hints:[ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"↑/↓")," pick from the list"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"enter")," continue"),ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"esc")," close")]})},ot.createElement(Je,{borderStyle:"single",borderColor:nI.YELLOW,paddingX:1,width:"100%"},ot.createElement(Qe,{color:nI.DIM},"provider id: "),ot.createElement(Je,{flexGrow:1},ot.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&&ot.createElement(Je,{flexDirection:"column",marginTop:1},q.map((e,t)=>{const n=null!==w&&K+t===w;return ot.createElement(Je,{key:e.id},ot.createElement(WL,{isSelected:n}),ot.createElement(HL,{isSelected:n,idleColor:nI.DIM},` ${e.id}`),ot.createElement(Qe,{color:nI.DIM}," ","· ",e.baseURL))}),(K>0||Y>0)&&ot.createElement(Qe,{color:nI.DIM}," ",K>0?`↑ ${K} more · `:"",Y>0?`↓ ${Y} more`:"")))}__name(endpointSubtitle,"endpointSubtitle"),__name(idStepMatches,"idStepMatches"),__name(AddCustomProviderEntry,"AddCustomProviderEntry"),Ht(),Qx();var t$="__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},bT)}async function handleProviderSelect({provider:e,setCurrentProvider:t,setShowProviderSelector:n,setAuthComponentInfo:r,setStatus:o,setShowProviderNotification:s,providerNotificationTimer:a,setShowModelSelector:i,sessionId:l,onActiveModelOrphaned:c,onDiskDefaultOrphaned:d}){if(e===t$)return n(!1),r({provider:e,Component:makeAddCustomProviderEntry({...i?{onOpenModels:__name(()=>i(!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:i?()=>i(!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:a}),{switched:!0})}function handleProviderCancel({setShowProviderSelector:e}){e(!1)}async function handleAuthSuccess({authComponentInfo:e,setAuthComponentInfo:t,setShowProviderSelector:n,setCurrentProvider:r,setStatus:o,setShowProviderNotification:s,providerNotificationTimer:a,sessionId:i}){return e?(t(null),n(!1),r(e.provider),await invalidateHarnessForLaneSwitch(i),o(buildProviderAuthSuccessStatus(e.provider)),showProviderNotification({setShowProviderNotification:s,providerNotificationTimer:a}),{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 n$=__name(({onSelect:e,onCancel:t,sessionId:n})=>{const[r,o]=ot.useState(()=>getCustomProviderModelsSync()),[s,a]=ot.useState(()=>getCustomProviderWarningsSync()),[i,l]=ot.useState({});ot.useEffect(()=>{let e=!0;return(async()=>{const{providers:t}=await refreshCustomProviderModels(n?{sessionId:n}:void 0);if(!e)return;o(t),a(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]=ot.useState({});ot.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=i[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"===i[e.id]})),{label:"(BYOK) Add your own provider",value:t$,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 tt((e,n)=>{n.escape&&t()}),ot.createElement(ZA,{title:"Connect",subtitle:"Connect to AI providers and see currently connected providers",hint:"↑/↓ navigate · enter select · esc close"},ot.createElement(SelectInput,{items:p.map(e=>({label:e.label,value:e.value})),onSelect:f,initialIndex:0,indicatorComponent:WL,itemComponent:({isSelected:e,label:t})=>{const n=h.get(t??"");return ot.createElement(Je,null,ot.createElement(HL,{isSelected:e,...n?.notLive?{idleColor:nI.DIM}:{}},` ${(t??"").padEnd(g)}`,n?.status.startsWith("✓")?ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.GREEN},"✓"),n.status.slice(1)):n?.status??""))}}),s.length>0&&ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Qe,{color:nI.YELLOW},ot.createElement(ProvidersJsonLink,{color:nI.YELLOW})," needs attention —"," ",1===s.length?"one entry":"some entries"," ","did not load as written:"),s.slice(0,3).map(e=>ot.createElement(Qe,{key:e,color:nI.DIM}," ",e)),s.length>3&&ot.createElement(Qe,{color:nI.DIM}," ","… and"," ",s.length-3," more")))},"ProviderSelector");Ht(),Qx();var r$=__name(e=>0===e?"No code changes":`${e} file${e>1?"s":""} changed`,"formatFileCountLabel"),o$=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=ct(()=>[...e].sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),[e]),[o,s]=at(()=>Math.max(0,r.length-1)),[a,i]=at(()=>Math.max(0,r.length-8)),[l,c]=at("checkpoint"),[d,u]=at(null),[m,p]=at(0),g=ct(()=>hasCodeChangesToRestore({sortedCheckpoints:r,selectedCheckpoint:d}),[d,r]),h=ct(()=>g?pP:pP.filter(e=>"conversation"===e.mode),[g]);if(lt(()=>{if(r.length>0){const e=r.length-1;s(e),i(Math.max(0,r.length-8))}},[r.length,8]),tt((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<a&&i(t),t}):"checkpoint"===l&&g.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=a+8&&i(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 ot.createElement(ZA,{title:"Rewind",subtitle:"No checkpoints available. Start a conversation to create checkpoints.",gapAfterHeader:!1,footer:ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Esc")," to close")});if("mode"===l&&d)return ot.createElement(ZA,{title:"Rewind",subtitle:ot.createElement(ot.Fragment,null,"Restore to:"," ",ot.createElement(Qe,{color:nI.WHITE},truncateString2({text:d.prompt||"checkpoint",maxChars:50}))),footer:ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to confirm ·"," ",ot.createElement(GA,null,"Esc")," to go back")},ot.createElement(Je,{flexDirection:"column"},h.map((e,t)=>{const n=m===t,r=t===h.length-1;return ot.createElement(Je,{key:e.mode,flexDirection:"column"},ot.createElement(Je,{flexDirection:"row"},ot.createElement(Qe,{color:n?rI:void 0},n?`${qI} `:" "),ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{color:n?rI:nI.WHITE},e.label),ot.createElement(Qe,{color:nI.DIM},e.description))),!r&&ot.createElement(Qe,null," "))})));const f=r.slice(a,a+8);return ot.createElement(ZA,{title:"Rewind",subtitle:"Select a checkpoint to restore your session",gapAfterHeader:!1,footer:ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to select ·"," ",ot.createElement(GA,null,"Esc")," to cancel")},r.length>8&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",a+1,"-",Math.min(a+8,r.length)," ","of ",r.length)),ot.createElement(Je,{marginTop:1}),ot.createElement(Je,{flexDirection:"column"},f.map((e,t)=>{const n=a+t,s=o===n,i=e.filesModified.length,l=t===f.length-1,c=n===r.length-1;return ot.createElement(Je,{key:e.messageId,flexDirection:"column"},ot.createElement(Je,{flexDirection:"row"},ot.createElement(Qe,{color:s?rI:void 0},s?`${qI} `:" "),ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,{color:s?rI:nI.WHITE},truncateString2({text:e.prompt||"(no prompt)",maxChars:60})),ot.createElement(Qe,{color:nI.DIM}," • "),ot.createElement(Qe,{color:nI.DIM},getRelativeTimeString({timestamp:e.createdAt}),c&&" (latest)")),ot.createElement(Qe,{color:nI.DIM},r$(i)))),!l&&ot.createElement(Qe,null," "))})))},"RewindSelector");Ht(),Qx();var s$=["default","no-tools","user-only","labeled-only","all"],a$={default:"","no-tools":"[no-tools]","user-only":"[user]","labeled-only":"[labeled]",all:"[all]"};function nextFilterMode(e){const t=s$.indexOf(e);return s$[(t+1)%s$.length]}function previousFilterMode(e){const t=s$.indexOf(e);return s$[(t-1+s$.length)%s$.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 i$=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:!i$.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:a}=e,i=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!==i?l.push(" "):0===r?l.push(o?"└":"├"):1===r?l.push(connectorGlyph({folded:s,foldable:a})):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,a=t.length>1;function visit(e){const{node:t,parentId:i,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=a?Math.max(0,l-1):l;if(o.push({id:t.entry.id,entry:t.entry,parentId:i,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:a?1:0,justBranched:a,showConnector:a,isLast:n===t.length-1,gutters:[],isVirtualRootChild:a})}),{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:nI.DIM}}return{text:`user: ${normalizeRowText(messageText5(n))}`,color:nI.CYAN}}const r=messageText5(n).trim();return r?{text:`assistant: ${normalizeRowText(r)}`,color:nI.GREEN}:{text:"assistant: (no content)",color:nI.DIM}}return"compaction"===e.type?{text:`[compaction: ${Math.round(e.tokensBefore/1e3)}k tokens]`,color:nI.CYAN}:"branch_summary"===e.type?{text:`[branch summary]: ${normalizeRowText(e.summary)}`,color:nI.YELLOW}:"custom_message"===e.type?{text:`[${e.customType}]: ${normalizeRowText(extractTextFromMessageContent({content:e.content}))}`,color:nI.MAGENTA}:"custom"===e.type?{text:`[custom: ${e.customType}]`,color:nI.DIM}:"model_change"===e.type?{text:`[model: ${e.model}]`,color:nI.DIM}:"effort_change"===e.type?{text:`[effort: ${e.effort}]`,color:nI.DIM}:"label"===e.type?{text:`[label: ${e.label??"(cleared)"}]`,color:nI.DIM}:{text:e.name?`[title: ${e.name}]`:"[title: (empty)]",color:nI.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 l$={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=l$[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 c$=[{value:"none",label:"No summary"},{value:"summarize",label:"Summarize"},{value:"custom",label:"Summarize with custom prompt"}],d$=__name(({tree:e,currentLeafId:t,initialSelectedId:n,initialFilterMode:r,branchSummarySkipPrompt:o,onSelect:s,onAbortSummary:a,onCancel:i,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,O]=at(0),[L,D]=at(n??t??void 0),N=useTerminalHeight(),$=ct(()=>{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]),_=ct(()=>buildToolCallMap(e),[e]),F=ct(()=>{const e=new Set;let n=t;for(;null!==n;){e.add(n);const t=$.get(n);n=t?t.parentId:null}return e},[$,t]),U=ct(()=>reorderActiveFirst(buildVisibleNodes({nodes:e,mode:c,currentLeafId:t}),t),[e,c,t]),{rows:j,visibleChildrenIds:B}=ct(()=>flattenVisibleTree({roots:U,activePathIds:F,foldedNodes:p}),[U,F,p]),W=ct(()=>new Map(j.map(e=>[e.id,e])),[j]),H=ct(()=>u?j.filter(e=>matchesSearch(searchableText({entry:e.entry,label:e.label,toolCallMap:_}),u)):j,[j,u,_]);lt(()=>{if(0===H.length)return void A(0);let e=L;for(;e;){const t=H.findIndex(t=>t.id===e);if(t>=0)return void A(t);e=$.get(e)?.parentId}A(H.length-1)},[H,c,u,$]);const G=H[I]?.id,V=it(!1);lt(()=>{V.current?G&&D(G):V.current=!0},[G]);const z=N-1,K=Math.max(6,z-10);lt(()=>{O(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:$,entryId:q.id});isOnPathLocally({byId:$,ancestorId:t,targetId:e})||o?Y({entryId:q.id,summarize:!1}):(x(q.id),P(0),v("confirm-summary"))},"handleEnterInBrowse");tt((e,t)=>{if("summarizing"===w)return void(t.escape&&a());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(c$.length-1,e+1));if(t.return&&M){const e=c$[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 i();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 ot.createElement(ZA,{title:"/tree",gapAfterHeader:!1},ot.createElement(Qe,{color:nI.CYAN},"Summarizing abandoned branch… (Esc to cancel)"));if("confirm-summary"===w)return ot.createElement(ZA,{title:"/tree",subtitle:"You're leaving work behind on this branch. Summarize it before jumping?",hint:"enter confirm · esc back"},ot.createElement(Je,{flexDirection:"column"},c$.map((e,t)=>ot.createElement(Qe,{key:e.value,color:t===T?rI:nI.WHITE,bold:t===T},t===T?`${qI} `:" ",e.label))));if("custom-prompt"===w)return ot.createElement(ZA,{title:"/tree",subtitle:"Focus instructions for the summary:",gapAfterHeader:!1,hint:"enter confirm · esc back"},ot.createElement(TextInput,{value:b,focus:!0,prefix:`${qI} `,prefixColor:"cyan",onChange:E,onSubmit:X}));if("label"===w&&q)return ot.createElement(ZA,{title:"/tree",subtitle:"Label:",gapAfterHeader:!1,hint:"enter save (empty clears) · esc cancel"},ot.createElement(TextInput,{value:k,focus:!0,prefix:`${qI} `,prefixColor:"cyan",onChange:C,onSubmit:Q}));const Z=H.slice(R,R+K),ee=new Date,te=a$[c];return ot.createElement(Je,{flexDirection:"column",paddingLeft:1,width:"100%"},ot.createElement(Qe,{color:rI,bold:!0},"/tree"),ot.createElement(Je,{marginBottom:1,width:"100%"},ot.createElement(VI,{query:u,resultCount:u?H.length:void 0,placeholder:"Type to search…"})),0===H.length?ot.createElement(Je,{marginBottom:1},ot.createElement(YO,{message:"No entries found"})):ot.createElement(Je,{flexDirection:"column"},Z.map((e,t)=>{const n=R+t===I,{text:r,color:o}=describeRow(e.entry,_);return ot.createElement(Qe,{key:e.id,backgroundColor:n?TI:void 0,bold:n,wrap:"truncate-end"},n?`${qI} `:" ",ot.createElement(Qe,{color:EI},e.prefix),e.isActivePath?ot.createElement(Qe,{color:rI},"• "):null,void 0!==e.label?ot.createElement(Qe,{color:nI.YELLOW},"[",e.label,"]"," "):null,y&&e.labelTimestamp?ot.createElement(Qe,{color:nI.DIM},formatLabelTimestamp(e.labelTimestamp,ee)," "):null,ot.createElement(Qe,{color:o},r))})),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"(",0===H.length?0:I+1,"/",H.length,")",te?` ${te}`:"",y?" [+label time]":"")),ot.createElement(Je,{flexDirection:"column"},ot.createElement(HA,null,"↑/↓ move · ←/→ page · tab / alt+←/→ branch · shift+L label · shift+T label time"),ot.createElement(HA,null,"filters ctrl+d/t/u/l/a · cycle ctrl+o · type to search · rebind via ~/.commandcode/keybindings.json")))},"TreeSelector");Ht(),Qx();var u$=[{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."}],m$=['/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"'],p$=__name(({onCancel:e})=>(tt((t,n)=>{n.escape&&e()}),ot.createElement(Je,{flexDirection:"column",paddingLeft:2,paddingRight:2},ot.createElement(Je,{marginBottom:1,flexDirection:"column"},ot.createElement(Qe,{bold:!0,color:rI},"Use"),ot.createElement(Je,{paddingLeft:2,flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},'/design <mode> "target or request"'),ot.createElement(Qe,{color:nI.DIM},'/design "freeform request" also works. The closest mode is inferred.'))),ot.createElement(Je,{marginBottom:1,flexDirection:"column"},ot.createElement(Qe,{bold:!0,color:rI},"Modes"),ot.createElement(Je,{paddingLeft:2,flexDirection:"column"},Kh.map(e=>ot.createElement(Je,{key:e.name,columnGap:2},ot.createElement(Je,{width:18,flexShrink:0},ot.createElement(Qe,{color:nI.CYAN},"/design ",e.name)),ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},e.description)))))),ot.createElement(Je,{marginBottom:1,marginTop:1,flexDirection:"column"},ot.createElement(Qe,{bold:!0,color:rI},"Working rules"),ot.createElement(Je,{paddingLeft:2,flexDirection:"column"},u$.map(e=>ot.createElement(Je,{key:e.label,columnGap:2},ot.createElement(Je,{width:16,flexShrink:0},ot.createElement(Qe,{color:nI.CYAN},e.label)),ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},e.desc)))))),ot.createElement(Je,{marginBottom:1,marginTop:1,flexDirection:"column"},ot.createElement(Qe,{bold:!0,color:rI},"Quick examples:"),ot.createElement(Je,{paddingLeft:2,flexDirection:"column"},m$.map(e=>ot.createElement(Qe,{key:e,color:nI.DIM},e)))),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Press Esc to close. Type /design help anytime to return.")))),"DesignGuide");Ht(),Qx(),Ht(),Ht();var g$=__name(({error:e,traceId:t})=>ot.createElement(Je,{padding:1},ot.createElement(qO,{title:"Error initializing onboarding:"},e,t&&ot.createElement(Qe,{color:nI.DIM},"\n\n","Trace ID: ",t),"\n\n","Continuing without onboarding...")),"OnboardingError");Ht(),Ht();var h$=__name(()=>ot.createElement(Qe,null,"Skip"),"SkipOptionText"),f$=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[o,s]=at(1);return tt((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())}),ot.createElement(Je,{flexDirection:"column",borderStyle:"single",borderColor:oI.TEXT,paddingX:1,paddingY:0},ot.createElement(Qe,{color:oI.TEXT,bold:!0},"Build Your Coding Taste"),ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Qe,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,null,"Analyze"," ",1===e?"that session":"those sessions"," ","to build your coding taste package?"))),ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,{color:1===o?oI.TEXT:nI.GRAY},1===o?pt.pointer:" "," 1. Yes, learn (recommended)")),ot.createElement(Je,null,ot.createElement(Qe,{color:2===o?oI.TEXT:nI.GRAY},2===o?pt.pointer:" "," 2."," ",ot.createElement(h$,null)))),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"↑↓ · "),ot.createElement(Qe,{color:vI.CODE},"enter"),ot.createElement(Qe,{color:nI.DIM}," ok · "),ot.createElement(Qe,{color:vI.CODE},"esc"),ot.createElement(Qe,{color:nI.DIM}," skip · "),ot.createElement(Qe,{color:vI.CODE},"n"),ot.createElement(Qe,{color:nI.DIM}," never")))},"ImportChoice"),y$=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onSkip:a})=>"asking"===e?t&&"has_sessions"===t.reason?ot.createElement(f$,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:a}):null:"learning"===e?ot.createElement(fL,{onComplete:r,onCancel:a,onError:o,onErrorDismiss:s}):null,"OnboardingStepRenderer"),S$=__name(({onComplete:e,autoLearn:t=!1})=>{lt(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,traceId:o,isLoading:s}=nL({autoLearn:t,onShouldSkip:e}),{step:a,setStep:i}=rL({conditions:n,autoLearn:t}),{handleImportStart:l,handleImportComplete:c,handleImportError:d,handleErrorDismiss:u,handleSkip:m}=oL({onStepChange:__name(e=>{i(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${a}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),s?null:r?ot.createElement(g$,{error:r,traceId:o}):"done"===a||"asking"!==a&&"learning"!==a?null:ot.createElement(y$,{step:a,conditions:n,onImportStart:l,onImportComplete:c,onImportError:d,onErrorDismiss:u,onSkip:m})},"TasteOnboarding");Ht(),Qx();var w$=[{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 v$=__name(({onSelect:e,onCancel:t})=>{const[n]=at(()=>getCliTheme()),[r]=at(()=>resolveCliTheme("auto")),o=ct(()=>w$.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");tt((e,n)=>{n.escape&&t()});const a=o.findIndex(e=>e.value===n),i=o.find(e=>e.value===n)?.label??`${n} theme`;return ot.createElement(ZA,{title:"Select a theme",subtitle:`Choose the color palette for this terminal · currently ${i}`,footer:ot.createElement(Qe,{italic:!0,color:nI.DIM},"Press ",ot.createElement(Qe,{bold:!0},"Esc")," to cancel")},ot.createElement(SelectInput,{items:o,onSelect:s,initialIndex:a>=0?a:0,indicatorComponent:WL,itemComponent:({isSelected:e,label:t})=>{const r=o.findIndex(e=>e.label===t),s=o[r],a=s?.value===n,i=r===o.length-1;return ot.createElement(Je,{flexDirection:"column",marginBottom:i?0:1},ot.createElement(Je,null,ot.createElement(HL,{isSelected:e,isActive:a,idleColor:nI.DIM},` ${r+1}. ${s?.label??t}`),a&&ot.createElement(VL,null)),ot.createElement(zL,null,s?.description??""))}}))},"ThemeSelector"),k$=st(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:o,setStaticKey:s,transcriptMode:a,tasteOnboardingEntryId:i,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:O,showThemeSelector:L,authComponentInfo:D,status:N,currentProvider:$,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:ae,questionPanel:ie,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:Oe,handleAuthSuccess:Le,handleAuthCancel:De,showDesignGuide:Ne,setShowDesignGuide:$e}){const _e=ct(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Fe=dt(()=>$e(!1),[$e]),Ue=useTerminalWidth(),[je,Be]=at(!1),[We,He]=at(!1),Ge=it(null);Ge.current=r?Ge.current??Date.now():null;const Ve=ct(()=>"off"===a?_e:projectTranscriptWindow({feed:_e,mode:a}),[_e,a]),ze=ct(()=>"off"===a?0:Math.max(0,_e.length-Ve.length),[_e.length,Ve.length,a]),Ke=ct(()=>0===ze?Ve:Ve.filter(e=>"user"!==e.role),[Ve,ze]),qe=dt(()=>Ce(!1),[Ce]),Ye=dt(()=>ve(!1),[ve]),Xe=dt(()=>ke(!1),[ke]),Ze=dt(()=>be(!1),[be]),et=dt(()=>Se(!0),[Se]),tt=dt(()=>we(!1),[we]),nt=dt(()=>{hardResetForResize(),s(e=>e+1)},[s]),rt=!("off"!==a||ae||ie||le||w||v||k||D||C||b||E||T||P||I||A||R||O||L||Ne||i),st=$O(Z),lt=st?st.getEffort():null;return ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(DN,{staticKey:o,feed:Ke,showHeader:!0,expandedToolOutput:"off"!==a,currentModel:_,currentEffort:lt,currentProvider:$,hiddenCount:ze}),i&&ot.createElement(S$,{onComplete:se,autoLearn:l}),c&&ot.createElement(TasteSkipMessage,null),d&&ot.createElement(ZdrPausedMessage,null),u&&ot.createElement(ModelNoticeMessage,{text:u}),t.map(e=>e.metadata?.isAgent?ot.createElement($N,{key:e.id,entry:e}):ot.createElement(Je,{key:e.id,marginBottom:1,width:"90%"},ot.createElement(FeedEntryView,{entry:e,expandedToolOutput:"off"!==a}))),ot.createElement(RetryMessage,{attempt:m}),"off"===a&&!i&&!We&&ot.createElement(TodoPanel,{active:r}),le,ie,ae,"off"!==a&&ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},"─".repeat(Ue))),ot.createElement(Je,{paddingRight:1},ot.createElement(Qe,{backgroundColor:lI.BG,color:lI.FG,bold:!0},`${QI}DETAILED TRANSCRIPT${QI}`),ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{bold:!0},"ctrl+o"),ot.createElement(Qe,{color:nI.DIM}," to toggle"),ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{bold:!0},db?"ctrl+y":"ctrl+e"),ot.createElement(Qe,{color:nI.DIM}," ","to"," ","limited"===a?"show all":"collapse"),ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{bold:!0},"esc"),ot.createElement(Qe,{color:nI.DIM}," to exit"))),rt&&ot.createElement(ot.Fragment,null,ot.createElement(BackgroundTasksPanel,{onExpandedChange:Be}),ot.createElement(TodosManagerPanel,{sessionId:Z,onExpandedChange:He}),ot.createElement(vN,{queuedMessages:n,sessionId:Z,isProcessing:r,processingStartedAt:Ge.current,executionState:X,status:N,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:$,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&&ot.createElement(Je,{marginY:1},ot.createElement(n$,{onSelect:Te,onCancel:Pe,sessionId:Z})),v&&ot.createElement(Je,{marginY:1},ot.createElement(ID,{onSelect:Me,onCancel:xe,currentModel:_,currentProvider:$,refreshBanner:nt,sessionId:Z})),k&&ot.createElement(Je,{marginY:1},ot.createElement(KN,{currentModel:_,sessionId:Z,onClose:tt,refreshBanner:nt})),Ne&&ot.createElement(Je,{marginY:1},ot.createElement(p$,{onCancel:Fe})),O&&ot.createElement(Je,{marginY:1},ot.createElement(ZD,{onSelect:Ie,onCancel:Ae})),L&&ot.createElement(Je,{marginY:1},ot.createElement(v$,{onSelect:Re,onCancel:Oe})),E&&ot.createElement(Je,{marginY:1},ot.createElement(VD,{onCancel:qe})),C&&ot.createElement(Je,{marginY:1},ot.createElement(EN,{onClose:Ye})),b&&ot.createElement(Je,{marginY:1},ot.createElement(bN,{onClose:Xe,mcp:$O(Z)?.mcp})),T&&$O(Z)&&ot.createElement(Je,{marginY:1},ot.createElement(o$,{checkpoints:[...$O(Z).listCheckpoints()],onSelect:ce,onCancel:de})),P&&$O(Z)&&ot.createElement(Je,{marginY:1},ot.createElement(d$,{tree:$O(Z).getSessionTree(),currentLeafId:$O(Z).getSessionLeafId(),initialFilterMode:M,branchSummarySkipPrompt:x,onSelect:ue,onAbortSummary:ge,onCancel:me,onLabelChange:pe})),D&&ot.createElement(Je,{marginY:1},ot.createElement(D.Component,{onSuccess:Le,onCancel:De})),I&&ot.createElement(Je,{marginY:1},ot.createElement(kN,{onComplete:he,onCancel:fe})),R&&ot.createElement(Je,{marginY:1},ot.createElement(bD,{onClose:Ze})))},"MainView"));function useFeatureModelCatalog(){const[e,t]=at(()=>getCachedBillingContext());lt(()=>{if(e)return;let n=!0;return getBillingContext().then(e=>{n&&t(e)}),()=>{n=!1}},[e]);const n=useCustomModelsReady(),r=ct(()=>buildCatalogModelPickerGroups(),[n]),o=ct(()=>filterModelPickerGroupsByPlan({groups:r,billing:e}),[r,e]),s=ct(()=>flattenModelPickerGroups(o).map(e=>({id:e.model.id,label:getModelDisplayName(e.model.id)})),[o]);return{groups:o,catalog:s,resolved:null!==e}}Ht(),Ht(),Qx(),Ht(),Qx(),__name(useFeatureModelCatalog,"useFeatureModelCatalog"),Ht(),Qx();var C$=__name(({featureLabel:e,defaultLabel:t,currentModelId:n,modelFilter:r,onPick:o,onBack:s})=>{const[a,i]=at(""),{groups:l,resolved:c}=useFeatureModelCatalog(),d=ct(()=>r?l.map(e=>({...e,models:e.models.filter(e=>r(e))})).filter(e=>e.models.length>0):l,[l,r]),u=ct(()=>filterModelPickerGroups(d,a),[d,a]),m=ct(()=>getModelLabelColumnWidth(d.flatMap(e=>e.models),{showDefaultBadge:!1}),[d]),p=ct(()=>[{kind:"reset"},...flattenModelPickerGroups(u).map(e=>({kind:"model",providerId:e.providerId,model:e.model}))],[u]),g=ct(()=>{if(!n)return 0;const e=p.findIndex(e=>"model"===e.kind&&e.model.id===n);return e>=0?e:0},[p,n]),{cursor:h}=useListNavigation({items:p,initialIndex:g,searchCursorIndex:1,searchQuery:a,onSearchChange:i,onSelect:__name(e=>{c&&o("reset"===e.kind?void 0:e.model.id)},"onSelect"),onCancel:s}),[f,y]=at(0),S=useTerminalHeight()-1,w=Math.max(4,S-13-2*u.length);lt(()=>{y(e=>clampScrollOffset({cursor:h,total:p.length,maxVisible:w,currentOffset:e}))},[h,p.length,w]);const v=f,k=f+w,C=0===v,b=windowModelGroups({groups:u,firstSectionBase:1,windowStart:v,windowEnd:k}),E=p.length>w;return ot.createElement(ZA,{title:`${e} › select model`,subtitle:ot.createElement(ot.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:ot.createElement(Qe,{italic:!0,color:nI.DIM},"type to search · ↑/↓ navigate · enter select",a?" · esc to clear":" · esc back")},isCmdZdrEnabled()&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.YELLOW},"Your pick is saved but stays paused until CMD_ZDR is unset.")),ot.createElement(Je,{marginBottom:2,flexDirection:"column",width:"100%"},ot.createElement(VI,{query:a,resultCount:a?p.length-1:void 0,placeholder:"Type to search models..."})),c?ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"column"},C&&ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{bold:!0,dimColor:!0},"Default"),ot.createElement(Je,null,ot.createElement(Qe,{backgroundColor:0===h?TI:void 0,color:n?nI.WHITE:nI.GREEN},t," "),!n&&ot.createElement(Qe,{color:nI.GREEN},pt.tick))),b.map(({group:e,groupWindow:t},r)=>ot.createElement(Je,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:0!==r||C?1:0},ot.createElement(Qe,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>ot.createElement(PD,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===h,isCurrent:r.id===n,showProviderLabel:!1,showDefaultBadge:!1,labelColumnWidth:m}))))),E&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",v+1,"–",Math.min(k,p.length)," of"," ",p.length,v>0?" · ↑ more":"",k<p.length?" · ↓ more":""))):ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},"Loading available models…")))},"FeatureModelPicker"),b$="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===wm}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="",a=0,i=!1;for(;a<r.length;){let e=r[a];e.length>t&&(r.splice(a,1,e.slice(0,t),e.slice(t)),e=r[a]);const l=s?`${s} ${e}`:e;if(l.length<=t)s=l,a+=1;else if(o.push(s),s="",o.length===n){i=!0;break}}if(!i)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 E$=__name(({onClose:e,staticKey:t,loadTasteStatus:n})=>{const[r,o]=at([]),s=isByok({model:getConfiguredModel()}),[a,i]=at(!0),[l,c]=at(""),[d,u]=at(null),{catalog:m}=useFeatureModelCatalog(),p=dt(()=>listConfigSettings({modelCatalog:m,isByok:isByok}).then(e=>o(e)),[m]);lt(()=>{let e=!0;return listConfigSettings({modelCatalog:m,isByok:isByok}).then(t=>{e&&o(t)}).finally(()=>{e&&i(!1)}),()=>{e=!1}},[m]);const g=ct(()=>filterConfigSettings({settings:r,query:l}),[r,l]),h=ct(()=>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!==wm||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??Pm}),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:!a&&null===d,validate:__name(e=>s&&isTasteRow(e)?b$: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(b$);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=ct(()=>E?clampDescriptionLines({text:E.description,width:Math.max(20,b-2),maxLines:2}):[],[E,b]);if(d?.featureModelKey){const e=im.find(e=>e.key===d.featureModelKey),t="string"==typeof d.currentValue&&d.currentValue!==Pm?d.currentValue:void 0;return ot.createElement(C$,{featureLabel:d.label,defaultLabel:e?getFeatureDefaultLabel({meta:e,getModelDisplayName:getModelDisplayName}):"",currentModelId:t,modelFilter:"vision"===d.featureModelKey?e=>modelSupportsVision(e.id):void 0,onBack:()=>u(null),onPick:e=>{S(d,e)}})}return a?ot.createElement(ZA,{key:t,title:"Settings",gapAfterHeader:!1},ot.createElement(VO,{label:"Loading settings"})):ot.createElement(ZA,{title:"Settings",footer:ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(Je,{flexDirection:"column",height:2,width:"100%"},T.map((e,t)=>ot.createElement(Qe,{key:t,color:nI.DIM,wrap:"truncate-end"},e))),ot.createElement(VA,{marginTop:0,hints:["type to filter","↑↓ navigate","enter to change","tab to reset",l?"esc to clear":"esc to close"]}))},ot.createElement(Je,{marginBottom:1,flexDirection:"column",width:"100%"},ot.createElement(VI,{query:l,resultCount:l?g.length:void 0,placeholder:"Search settings..."})),0===g.length?ot.createElement(Je,{marginY:1},ot.createElement(Qe,{color:nI.GRAY},'No settings match "',l,'"')):ot.createElement(Je,{flexDirection:"column"},g.map((e,t)=>{const n=t===w?TI:void 0,r=!l&&startsNewGroup(g,t);return ot.createElement(ot.Fragment,{key:e.id},r&&ot.createElement(Je,{marginTop:0===t?0:1},ot.createElement(Qe,{color:nI.DIM,bold:!0},e.group)),ot.createElement(Je,null,ot.createElement(Qe,{color:e.locked||s&&isTasteRow(e)?nI.DIM:nI.WHITE,backgroundColor:n},e.label.padEnd(h)),ot.createElement(Qe,{color:e.locked||s&&isTasteRow(e)?nI.DIM:nI.GREEN,backgroundColor:n},formatSettingValue(e)),(e.locked||s&&isTasteRow(e))&&ot.createElement(Qe,{color:nI.DIM,backgroundColor:n},s&&isTasteRow(e)?" (unavailable on BYOK)":" (locked by settings.local.json)")))})),v&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.GRAY},v)))},"SettingsConfig");function SettingsConfigView({staticKey:e,onClose:t,loadTasteStatus:n}){return ot.useEffect(()=>{hardResetForResize()},[]),ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(E$,{onClose:t,staticKey:e,loadTasteStatus:n})))}function categoryColor(e){return isFatalWarningCategory(e)?nI.RED:nI.YELLOW}__name(SettingsConfigView,"SettingsConfigView"),Ht(),Ht(),Qx(),Ht(),Ht(),Qx(),__name(categoryColor,"categoryColor");var T$=formatSkillWarningsAsMarkdown;async function copyAllWarnings(e,t){try{const{writeClipboardText:n}=await Promise.resolve().then(()=>(Qx(),Jx));if(!await n(T$(e)))throw new Error("clipboard unavailable");const r=e.length;t({text:`Copied ${r} issue${1===r?"":"s"} to clipboard`,color:nI.GREEN})}catch{t({text:"Clipboard write failed",color:nI.YELLOW})}}__name(copyAllWarnings,"copyAllWarnings");var P$=__name(({warnings:e,onClose:t,isActive:n=!0})=>{const r=groupWarnings(e),o=e.length>0,[s,a]=at(null),i=it(null),l=it(!0);lt(()=>()=>{l.current=!1,i.current&&(clearTimeout(i.current),i.current=null)},[]);const c=__name(e=>{l.current&&(i.current&&clearTimeout(i.current),a(e),i.current=setTimeout(()=>{l.current&&(a(null),i.current=null)},3e3))},"showStatus");return tt((n,r)=>r.escape||" "===n&&o?(cA(),void t()):void("c"===n&&o&&copyAllWarnings(e,c)),{isActive:n}),ot.createElement(Je,{flexDirection:"column",paddingX:0,width:"100%"},ot.createElement(Je,null,ot.createElement(Qe,{color:rI,bold:!0},"Skills"," "),ot.createElement(Qe,{color:nI.DIM},"› "),ot.createElement(Qe,{color:rI,bold:!0},"Skipped"," "),ot.createElement(Qe,{color:nI.WHITE},e.length)),o&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM},"Press c to copy all issues")),o?ot.createElement(Je,{flexDirection:"column"},r.map(e=>ot.createElement(Je,{key:e.category,flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,{color:categoryColor(e.category)},e.category)),e.items.map(e=>ot.createElement(Je,{key:e.path,flexDirection:"column",marginBottom:1},ot.createElement(Je,{paddingLeft:2},ot.createElement(BI,{url:p(e.path).href,text:skillIdentifier(e.path),color:nI.WHITE})),ot.createElement(Je,{paddingLeft:4},ot.createElement(Qe,{color:nI.WHITE},e.reason))))))):ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"No issues — every skill loaded.")),s&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:s.color},s.text)),ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},o?"c copy all issues · esc back to skills":"esc back to skills")))},"SkillsConfigIssues"),M$=[],x$=__name(({warnings:e=M$,onClose:t})=>{const[n,r]=at("list");return tt((o,s)=>{"list"===n&&(s.escape&&t?t():" "===o&&!s.ctrl&&!s.meta&&e.length>0&&r("issues"))},{isActive:"list"===n}),"issues"===n?ot.createElement(P$,{warnings:e,onClose:()=>r("list"),isActive:!0}):ot.createElement(Je,{flexDirection:"column",paddingX:0,width:"100%"},ot.createElement(Je,null,ot.createElement(Qe,{color:rI,bold:!0},"Skills"),e.length>0&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:nI.YELLOW},e.length," skipped"))),ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.DIM},"No skills found")),ot.createElement(Qe,{color:nI.DIM},"Create skills in:"),ot.createElement(Qe,{color:nI.DIM}," ","~/",".commandcode","/","skills","/ (user)"),ot.createElement(Qe,{color:nI.DIM}," ","~/.agents/","skills","/ (user, .agents)"),ot.createElement(Qe,{color:nI.DIM}," ",".commandcode","/","skills","/ (project)"),ot.createElement(Qe,{color:nI.DIM}," ",".agents/","skills","/ (project, .agents)"),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},e.length>0&&"space to view issues · ","Press ",ot.createElement(Qe,{bold:!0},"Esc")," to close")))},"SkillsConfigEmpty");Ht();var I$=__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");Ht();var A$=__name(({title:e,subtitle:t,skills:n,baseIndex:r,cursor:o,disabled:s})=>ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Je,null,ot.createElement(Qe,{color:pI,bold:!0},e," "),ot.createElement(Qe,{color:pI},t)),n.map((e,t)=>{const n=r+t===o,a=s.has(e.label),i=n?TI:void 0;return ot.createElement(Je,{key:e.filePath},ot.createElement(Qe,{color:a?nI.DIM:nI.GREEN,backgroundColor:i},a?"[off] ":"[on] "),ot.createElement(Qe,{color:a?nI.DIM:nI.WHITE,backgroundColor:i},e.label),e.fromAgents&&ot.createElement(Qe,{color:nI.DIM,backgroundColor:i}," [.agents]"),ot.createElement(Qe,{color:nI.DIM,backgroundColor:i}," · ~",e.estimatedTokens," tokens "))})),"SkillSection"),R$=__name(({onClose:e})=>{const[t,n]=at([]),[r,o]=at([]),[s,a]=at(!0),[i,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=it(!1);lt(()=>{__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{a(!1)}},"load")()},[]);const T=ct(()=>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),O=Math.max(4,A-14-2*R),L=__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");lt(()=>{"issues"===w&&d("")},[w]);const D="list"===w&&t.length>0,{cursor:N}=useListNavigation({items:I,onSelect:L,onCancel:e,searchQuery:c,onSearchChange:d,initialIndex:0,isActive:D});if(lt(()=>{C(e=>clampScrollOffset({cursor:N,total:I.length,maxVisible:O,currentOffset:e}))},[N,I.length,O]),tt((t,n)=>{if(!n.tab)return;const r=I[N];r&&(async()=>{try{await xt([{file:r.filePath,line:1}]),e()}catch(e){if(e instanceof Error&&e.message.includes("$EDITOR environment variable"))return void l(I$());l(e instanceof Error?e.message:"Failed to open skill in editor")}})()},{isActive:D}),tt((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 ot.createElement(ZA,{title:"Skills",gapAfterHeader:!1},ot.createElement(Qe,{color:nI.DIM},"Loading skills..."));if(i)return ot.createElement(ZA,{title:"Skills",titleColor:nI.RED,gapAfterHeader:!1,footer:ot.createElement(Qe,{italic:!0,color:nI.DIM},"Press ",ot.createElement(Qe,{bold:!0},"Esc")," to close")},ot.createElement(Qe,{color:nI.DIM},i));if(0===t.length)return ot.createElement(x$,{warnings:r,onClose:e});if("issues"===w)return ot.createElement(P$,{warnings:r,onClose:()=>v("list"),isActive:!0});const $=t.filter(e=>u.has(e.label)).length,_=k,F=k+O,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>O;return ot.createElement(ZA,{title:"Skills",titleSuffix:ot.createElement(ot.Fragment,null," ",t.length," skill",1===t.length?"":"s",$>0&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:nI.YELLOW},$," off")),r.length>0&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:nI.YELLOW},r.length," skipped"))),subtitle:getSkillPickerNoProjectNotice(h),footer:ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,{italic:!0,color:nI.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"),ot.createElement(Qe,{color:nI.DIM},"add skills:"," ",ot.createElement(Qe,{color:nI.CYAN},getBinaryCommand()," skills add ","<owner/repo>")))},ot.createElement(Je,{marginBottom:1,flexDirection:"column",width:"100%"},ot.createElement(VI,{query:c,resultCount:c?I.length:void 0,placeholder:"Type to search skills..."})),0===I.length?ot.createElement(Je,{marginY:1},ot.createElement(Qe,{color:nI.GRAY},'No skills match "',c,'"')):ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"column"},U.rows.length>0&&ot.createElement(A$,{title:"Project skills",subtitle:"(.commandcode/skills or .agents/skills)",skills:U.rows,baseIndex:U.baseIndex,cursor:N,disabled:u}),j.rows.length>0&&ot.createElement(A$,{title:"User skills",subtitle:"(~/.commandcode/skills or ~/.agents/skills)",skills:j.rows,baseIndex:j.baseIndex,cursor:N,disabled:u}),B.rows.length>0&&ot.createElement(A$,{title:"Bundled skills",subtitle:"(ships with Command Code)",skills:B.rows,baseIndex:B.baseIndex,cursor:N,disabled:u})),W&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",_+1,"–",Math.min(F,I.length)," of"," ",I.length,_>0?" · ↑ more":"",F<I.length?" · ↓ more":""))),y&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.YELLOW},y)))},"SkillsConfig");function SkillsConfigView({staticKey:e,onClose:t}){return ot.useEffect(()=>{hardResetForResize()},[]),ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(R$,{onClose:t,staticKey:e})))}__name(SkillsConfigView,"SkillsConfigView"),Ht(),Ht(),Qx();var O$=[{scope:"project",label:"This project"},{scope:"global",label:"User"}],L$=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=at(!0),[s,a]=at(void 0),[i,l]=at(void 0),[c,d]=at(!0),u=isProjectTasteToggleLocked(i),m=dt(async()=>{try{const e=await getTasteLearningSettings();o(e.global),a(e.project),l(e.projectSource)}catch{}},[]);lt(()=>{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:i});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(()=>a(t.value),()=>a(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:i});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(()=>a(void 0),()=>a(n),()=>clearProjectTasteLearning())},"resetRow"),{cursor:y}=useListNavigation({items:O$,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 ot.createElement(ZA,{key:n,title:"Taste Learning",gapAfterHeader:!1},ot.createElement(VO,{label:"Loading configuration"}));const S=__name(e=>!g&&("project"===e.scope?s??r:r),"valueFor");return ot.createElement(ZA,{key:n,title:"Taste Learning",subtitle:g?ip:"Learn from your interactions.",hint:g?"esc to close":"↑/↓ navigate · enter to toggle · r reset to default · esc to close"},O$.map((e,t)=>{const n=t===y,r=S(e),o=g||"project"===e.scope&&u;return ot.createElement(Je,{key:e.scope},ot.createElement(Qe,{color:n?nI.CYAN:nI.GRAY},n?`${pt.pointer} `:" "),ot.createElement(Qe,{color:n?nI.CYAN:nI.WHITE},e.label.padEnd(16)),ot.createElement(Qe,{color:r?nI.GREEN:nI.DIM},r?"enabled":"disabled"),o?ot.createElement(Qe,{color:nI.DIM}," ",g?"(unavailable on BYOK)":"(set in settings.local.json)"):null)}),ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Qe,{color:nI.DIM},"Taste data stored in .commandcode/taste/taste.md"),u?ot.createElement(Qe,{color:nI.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 ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(L$,{onClose:t,onSettingsChange:n,staticKey:e})))}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 a=n>0?Math.min(100,t/n*100):0,i=getUsageColor(a),l=buildBlockBar({percentage:a,width:o}),c=r>s?` · resets in ${formatDuration(r-s)}`:"";return ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},e.padEnd(7)," "),ot.createElement(Qe,{color:i},l.filled),ot.createElement(Qe,{color:pI},l.empty),ot.createElement(Qe,{bold:!0,color:i},` ${Math.round(a)}%`),ot.createElement(Qe,{color:nI.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?nI.RED:"warning"===t?nI.YELLOW:void 0}__name(TasteConfigView,"TasteConfigView"),Ht(),Ht(),Qx(),__name(fetchUsageData2,"fetchUsageData"),__name(getAuthKey2,"getAuthKey"),__name(WindowLimitMeter,"WindowLimitMeter"),__name(getProgressBarWidth,"getProgressBarWidth"),__name(getDaysColor,"getDaysColor");var D$=__name(({plan:e,status:t})=>ot.createElement(Je,{marginBottom:0},ot.createElement(Je,{flexShrink:0},ot.createElement(Qe,{backgroundColor:nI.BLUE,color:"#f4f4f4",bold:!0},`${QI}USAGE${QI}`)),e&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,null," "),ot.createElement(Qe,{color:nI.GRAY},`${e.name} Plan`)),t&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,{color:"active"===t?nI.GREEN:nI.YELLOW},t))),"UsageBadge"),N$=__name(({showRetry:e})=>ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,e&&ot.createElement(ot.Fragment,null,ot.createElement(GA,null,"r")," to retry · "),"Press ",ot.createElement(GA,null,"Esc")," to close")),"UsageFooter"),$$=__name(({onClose:e})=>{const[t,n]=at("loading"),[r,o]=at(null),[s,a]=at(!1),i=getProgressBarWidth({terminalWidth:useTerminalWidth()}),l=dt(async e=>{try{a(!1);const t=await fetchUsageData2();if(e.aborted)return;if(!t.whoami){const e=t.errors.some(isAuthErrorMessage);return a(e),void n("error")}o(t),n("loaded")}catch{if(e.aborted)return;n("error")}},[]),c=ot.useRef(null);tt((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)}}),lt(()=>{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 ot.createElement(Je,{flexDirection:"column",paddingX:0,width:"100%"},ot.createElement(D$,{plan:m,status:u?.status??null}),ot.createElement(VO,null),ot.createElement(N$,null));if("error"===t)return ot.createElement(Je,{flexDirection:"column",paddingX:0,width:"100%"},ot.createElement(D$,{plan:m,status:u?.status??null}),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},s?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),ot.createElement(N$,{showRetry:!s}));if(!r)return null;const p=d?.hasBillingData??!1,g=d?.usageUrl??null;if(!p)return ot.createElement(Je,{flexDirection:"column",paddingX:0,width:"100%"},ot.createElement(D$,{plan:m,status:u?.status??null}),ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(YO,{message:"No billing data found."}),g&&ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},"Visit "),ot.createElement(BI,{url:g,text:"Studio",color:nI.CYAN}),ot.createElement(Qe,{color:nI.DIM}," for usage details."))),ot.createElement(N$,null));const h=d?.windowLimits??null,f=d?.summary??null,y=d?.now??Date.now(),S=d?.credits,w=S?.totalRemaining??0,v=S?.usagePercent??0,k=Boolean(S?.hasCreditsInfo),C=d?.daysLeft??null,b=getDaysColor(C),E=getUsageColor(v),T=buildBlockBar({percentage:v,width:i});return ot.createElement(Je,{flexDirection:"column",paddingX:0,width:"100%"},ot.createElement(Je,{marginBottom:1},ot.createElement(D$,{plan:m,status:u?.status??null})),k?ot.createElement(Je,null,ot.createElement(Qe,{color:E},T.filled),ot.createElement(Qe,{color:pI},T.empty),ot.createElement(Qe,{bold:!0,color:E},` ${Math.round(v)}% used`)):ot.createElement(Qe,{color:nI.DIM},"Plan details unavailable"),k&&ot.createElement(Je,null,u?.currentPeriodEnd&&ot.createElement(Qe,{color:nI.DIM},"Cycle: "),ot.createElement(Qe,null,formatCredits(w)),ot.createElement(Qe,{color:nI.DIM}," left"),f&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.DIM}," · "),ot.createElement(Qe,null,f.totalCount.toLocaleString()),ot.createElement(Qe,{color:nI.DIM}," requests")),null!==C&&ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.DIM}," · "),0===C?ot.createElement(Qe,{color:b},"renewal today"):ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:b},`${C} day${1===C?"":"s"}`),ot.createElement(Qe,{color:nI.DIM}," to renewal")))),h?.limited&&ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Usage limits"),h.fiveHour&&ot.createElement(WindowLimitMeter,{label:"5-hour",used:h.fiveHour.used,cap:h.fiveHour.cap,resetAt:h.fiveHour.resetAt,width:i,now:y}),h.weekly&&ot.createElement(Je,{marginTop:h.fiveHour?1:0,flexDirection:"column"},ot.createElement(WindowLimitMeter,{label:"Weekly",used:h.weekly.used,cap:h.weekly.cap,resetAt:h.weekly.resetAt,width:i,now:y}))),g&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Full breakdown at "),ot.createElement(BI,{url:g,text:d?.usageUrlDisplay??g,color:nI.CYAN})),ot.createElement(N$,null))},"UsageOverlay");function UsageView({staticKey:e,onClose:t}){return ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement($$,{onClose:t})))}__name(UsageView,"UsageView"),Ht(),Qx(),Ht(),Qx(),Ht();var _$="@last";function shortenHomePath(e){const t=W();return e.startsWith(t)?`~${e.slice(t.length)}`:e}__name(shortenHomePath,"shortenHomePath");var F$={approved:{label:`${pt.tick} approved`,color:nI.GREEN},"not-implemented":{label:`${pt.circleDotted} set aside`,color:nI.YELLOW},pending:{label:`${pt.dot} pending`,color:nI.DIM}},U$=createNodeRuntime(),j$={"?":"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:nI.GREEN,bold:!1,italic:!1};const t={color:nI.WHITE,bold:!1,italic:!1};if(!e.style)return t;switch(e.style.role){case"heading":return{color:vI.HEADING,bold:!0,italic:!1};case"code":case"code-fence":return{color:vI.CODE,bold:!1,italic:!1};case"quote":return{color:nI.DIM,bold:!1,italic:!0};case"table":return{color:nI.CYAN,bold:!1,italic:!1};default:return t}}__name(lineStyleProps,"lineStyleProps");var B$=__name(({plan:e,variant:t="browse",fallbackContent:n,onBack:r,onSubmitFeedback:o,onExecute:s,onAutoAccept:a})=>{const[i,l]=at(null),[c,d]=at(e.annotations),[u,m]=at(!1);lt(()=>{u||d(e.annotations)},[e.annotations,u]);const[p,g]=at({kind:"line",lineNumber:1}),[h,f]=at(null),[y,S]=at(null),[w,v]=at(null),[k,C]=at(!1),[b,E]=at(0),[T,P]=at(null),M=useTerminalHeight(),x=useTerminalWidth();lt(()=>{__name(async()=>{const t=await readPlanContent({runtime:U$,filePath:e.filePath})??n??null;l(null===t?[]:splitPlanLines(t))},"load")()},[e.filePath,n]);const I=e.version??1;lt(()=>{I<=1||!e.filePath||readPlanVersionSnapshot({runtime:U$,filePath:e.filePath,version:I-1}).then(P).catch(()=>{})},[I,e.filePath]);const A=ct(()=>null!==T&&null!==i?diffPlanChangedLines({previous:T,current:i}):new Set,[T,i]),R=c.length,O=ct(()=>{const e={id:"feedback",label:`Submit review (${R})`,chord:"ctrl+r",color:nI.CYAN,hint:"agent revises the plan, returns it for review"};return"approval"===t?[...R>0?[e]:[],{id:"auto-accept",label:"Approve",chord:"ctrl+a",color:nI.GREEN,hint:R>0?"executes the plan · comments go along as notes":"executes the plan"},{id:"cancel",label:"Cancel",chord:"esc",color:nI.YELLOW,hint:""}]:[...R>0?[e]:[],{id:"execute",label:"Execute plan",chord:"ctrl+e",color:nI.GREEN,hint:"executes the plan as written"},{id:"cancel",label:"Back",chord:"esc",color:nI.YELLOW,hint:""}]},[t,R]),L=ct(()=>h?c.filter(e=>e.line!==h.line):c,[c,h]),D=ct(()=>buildPlanReaderRows({lines:i??[],annotations:L}),[i,L]),N=ct(()=>classifyPlanLines(i??[]),[i]),$=i?.length??0,_=resolvePlanWrapWidth(Math.max(20,x-7-2)),F=ct(()=>buildPlanReaderDisplayRows({rows:D,width:_}),[D,_]),U=getPlanReaderCursorDisplaySpan({displayRows:F,cursor:p}),j=M-1,B=Math.max(4,j-10-7),W=h?1:0,H=-1===U.first?F.length-1:U.first,G=-1===U.last?F.length-1:U.last+W;lt(()=>{E(e=>{const t=clampScrollOffset({cursor:Math.max(0,G),total:F.length+W,maxVisible:B,currentOffset:e});return clampScrollOffset({cursor:Math.max(0,H),total:F.length+W,maxVisible:B,currentOffset:t})})},[H,G,F.length,W,B]),lt(()=>{g(e=>snapPlanReaderCursor({cursor:e,lineCount:$,actions:[]}))},[$]),lt(()=>{g(e=>"action"!==e.kind||O.some(t=>t.id===e.id)?e:{kind:"line",lineNumber:Math.max(1,$)})},[O,$]);const V=__name(t=>{m(!0),d(t),e.filePath&&setPlanAnnotations({runtime:U$,filePath:e.filePath,annotations:t}).catch(()=>v("Failed to save comments to disk"))},"persistAnnotations"),z="line"===p.kind?c.find(e=>e.line===p.lineNumber):void 0,K=__name(()=>{if(0===c.length||!i)return;const t=buildPlanAnnotationsPrompt({title:e.title,filePath:e.filePath||"(plan not saved to a file yet)",lines:i,annotations:c});e.filePath&&snapshotPlanVersion({runtime:U$,filePath:e.filePath}).catch(()=>{}),V([]),o(t)},"submitFeedback"),q=__name(t=>{if(t&&c.length>0&&i){const t=buildPlanApprovalNotesPrompt({title:e.title,...e.filePath?{filePath:e.filePath}:{},lines:i,annotations:c});return V([]),void a?.(t)}V([]),a?.()},"approve"),Y=__name(()=>{"approval"===t&&(R>0?S({kind:"approve",choice:"notes"}):q(!1))},"requestApprove"),J=__name(()=>{R>0&&!e.filePath?S({kind:"cancel"}):r()},"requestCancel"),Q=__name(t=>{"feedback"!==t?"execute"!==t?"auto-accept"!==t?"cancel"===t&&J():Y():(s??o)(buildPlanExecutePrompt({title:e.title,filePath:e.filePath||e.fileName})):K()},"runAction"),X=__name(()=>{e.filePath?(C(!0),openFileInEditor(e.filePath).then(async()=>{const t=await readPlanContent({runtime:U$,filePath:e.filePath});null!==t&&l(splitPlanLines(t))}).catch(e=>v(e instanceof Error?e.message:"Failed to open the editor")).finally(()=>{C(!1),hardResetForResize()})):v("This plan is not saved to a file yet")},"openExternalEditor"),Z=__name(e=>{"line"!==p.kind||p.lineNumber<1||p.lineNumber>$||f({line:p.lineNumber,value:e||(z?.text??""),hadExisting:void 0!==z})},"openDraft"),ee=__name(e=>{h&&(V(upsertPlanAnnotation({annotations:c,line:h.line,text:e,createdAt:(new Date).toISOString()})),f(null))},"commitDraft"),te=ct(()=>{const e=new Set;for(const t of c)e.add(t.line);for(const t of A)e.add(t);return[...e].sort((e,t)=>e-t)},[c,A]),ne=__name(e=>{if(0===te.length)return;const t="line"===p.kind?p.lineNumber:$+1,n="next"===e?te.find(e=>e>t)??te[0]:[...te].reverse().find(e=>e<t)??te[te.length-1];void 0!==n&&g({kind:"line",lineNumber:n})},"jumpMarked");tt((e,t)=>{t.escape&&f(null)},{isActive:null!==h}),tt((e,t)=>{if(y)if(t.escape)S(null);else if("approve"===y.kind&&(t.leftArrow||t.rightArrow||t.tab))S({kind:"approve",choice:"notes"===y.choice?"original":"notes"});else if(t.return){if("approve"===y.kind)return S(null),void q("notes"===y.choice);S(null),r()}},{isActive:null!==y}),tt((e,n)=>{if(n.escape)return void J();if(n.upArrow||n.downArrow)return v(null),void g(e=>{if("action"===e.kind){const t=O.findIndex(t=>t.id===e.id);if(n.upArrow){if(t<=0&&$>0)return{kind:"line",lineNumber:$};const n=O[Math.max(0,t-1)];return n?{kind:"action",id:n.id}:e}const r=O[Math.min(O.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>=$){const t=O[0];return t?{kind:"action",id:t.id}:e}return{kind:"line",lineNumber:e.lineNumber+1}});if(n.pageUp||n.pageDown)return v(null),void g(e=>"action"===e.kind&&n.pageDown?e:movePlanReaderCursorByPage({displayRows:F,cursor:e,direction:n.pageDown?"down":"up",pageRows:Math.max(1,B-1)}));if(n.home||n.end)return v(null),void($>0&&g({kind:"line",lineNumber:n.home?1:$}));if(n.leftArrow||n.rightArrow){if("action"!==p.kind)return;const e=O.findIndex(e=>e.id===p.id);if(-1===e)return;const t=n.leftArrow?Math.max(0,e-1):Math.min(O.length-1,e+1),r=O[t];return void(r&&g({kind:"action",id:r.id}))}if(n.ctrl&&"r"===e)return void K();if(n.ctrl&&"a"===e&&"approval"===t)return void Y();if(n.ctrl&&"e"===e&&"browse"===t)return void Q("execute");if(n.ctrl&&"g"===e)return void X();if(n.ctrl&&"n"===e)return void ne("next");if(n.ctrl&&"p"===e)return void ne("previous");if(n.return)return"action"===p.kind?void Q(p.id):void Z("");const r=j$[e];"line"!==p.kind||!r||n.ctrl||n.meta?"line"===p.kind&&e.length>0&&!n.ctrl&&!n.meta&&Z(e):V(upsertPlanAnnotation({annotations:c,line:p.lineNumber,text:z?.text===r?"":r,createdAt:(new Date).toISOString()}))},{isActive:null===h&&null===y&&null!==i&&!k});const re=F$[e.status],oe=b,se=b+B-W,ae=F.slice(oe,se),ie=h?h.hadExisting?"enter to keep · clear + enter removes · esc keep as was":"enter to pin · esc discard":y?"approve"===y.kind?"←/→ choose · enter confirm · esc back":"enter discard · esc back":"action"===p.kind?"↑/↓ choose · enter to run":["type + enter to comment",...te.length>0?["ctrl+n/p jump "+(A.size>0?"changes":"comments")]:[],"quick: ? why x cut ! risky","ctrl+g $EDITOR"].join(" · ");return ot.createElement(ZA,{title:"approval"===t?`Plan review: ${e.title}`:e.title,titleSuffix:"approval"===t?ot.createElement(ot.Fragment,null," ","· ",shortenHomePath(e.filePath)||e.fileName," · v",e.version??1):ot.createElement(ot.Fragment,null," ","· ",shortenHomePath(e.filePath)||e.fileName," · v",e.version??1," ",ot.createElement(Qe,{color:re.color},re.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:ot.createElement(Qe,{italic:!0,color:nI.DIM},ie)},null===i?ot.createElement(Qe,{color:nI.DIM},"Loading plan..."):0===$?ot.createElement(Qe,{color:nI.DIM},"Plan file is empty or missing on disk."):ot.createElement(Je,{flexDirection:"column"},ae.map((e,t)=>{const n=oe+t,{row:r}=e;if("action"===r.kind)return null;if("annotation"===r.kind)return ot.createElement(Je,{key:`annotation-${r.lineNumber}-${n}`},ot.createElement(Qe,{color:nI.DIMMER}," ".repeat(5)),ot.createElement(Qe,{backgroundColor:oI.BADGE_BG,color:oI.BADGE_FG}," ",e.isFirstSegment?"↳ ":" ",e.text," "));const o="line"===p.kind&&p.lineNumber===r.lineNumber,s=lineStyleProps({style:N[r.lineNumber-1],changed:A.has(r.lineNumber)}),a=F[n+1],i=!a||"line"!==a.row.kind||a.row.lineNumber!==r.lineNumber,l=n===se-1,c=null!==h&&h.line===r.lineNumber&&(i||l);return ot.createElement(ot.Fragment,{key:`line-${r.lineNumber}-${n}`},ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIMMER},e.isFirstSegment?String(r.lineNumber).padStart(4," "):" "," "),ot.createElement(Qe,{color:r.hasAnnotation?nI.CYAN:nI.DIMMER},e.isFirstSegment&&r.hasAnnotation?`${pt.bullet} `:" "),ot.createElement(Qe,{color:s.color,bold:s.bold,italic:s.italic,backgroundColor:o?TI:void 0},e.text||" ")),c&&h&&ot.createElement(Je,null,ot.createElement(Qe,{color:nI.CYAN}," ┃ ",pt.bullet," "),ot.createElement(TextInput,{value:h.value,onChange:e=>f(t=>t?{...t,value:e}:t),onSubmit:ee,placeholder:"Type your comment…",focus:null!==h,stripBracketedPaste:!0})))})),ot.createElement(Je,{flexDirection:"column",marginTop:1},ot.createElement(RI,{dividerColor:nI.DIMMER}),ot.createElement(Je,null,ot.createElement(Qe,{bold:!0,backgroundColor:oI.BADGE_BG,color:nI.WHITE}," REVIEW "),ot.createElement(Qe,{color:nI.DIM},R>0&&` ${R} pending comment${1===R?"":"s"}`,I>1&&` · round ${I}${A.size>0?` · ${A.size} line${1===A.size?"":"s"} changed`:""}`)),y?"approve"===y.kind?ot.createElement(Je,null,ot.createElement(Qe,{bold:!0,color:nI.GREEN},"Approve"," "),ot.createElement(Qe,{color:"notes"===y.choice?nI.WHITE:nI.DIM,backgroundColor:"notes"===y.choice?TI:void 0},"notes"===y.choice?"(•)":"( )"," ","with ",R," comment",1===R?"":"s"," as notes"),ot.createElement(Qe,{color:nI.DIMMER}," "),ot.createElement(Qe,{color:"original"===y.choice?nI.WHITE:nI.DIM,backgroundColor:"original"===y.choice?TI:void 0},"original"===y.choice?"(•)":"( )"," ","original plan · discard comments")):ot.createElement(Je,null,ot.createElement(Qe,{color:nI.YELLOW},"Discard ",R," pending comment",1===R?"":"s"," and exit review?")):O.map(e=>{const t="action"===p.kind&&p.id===e.id;return ot.createElement(Je,{key:e.id},ot.createElement(Qe,{bold:!0,color:e.color,backgroundColor:t?TI:void 0},t?`${pt.pointer} ${e.label} `:e.label),ot.createElement(Qe,{color:nI.DIM}," ",e.chord),e.hint&&ot.createElement(Qe,{color:nI.DIMMER}," ",e.hint))}),w&&ot.createElement(Qe,{color:nI.YELLOW},w)))},"PlanReader"),W$=createNodeRuntime();function PlanApprovalView({staticKey:e,planContent:t,planFilePath:n,onAutoAccept:r,onCancel:o,onSendFeedback:s}){lt(()=>{hardResetForResize()},[]);const[a,i]=at(null);lt(()=>{n&&listPlans({runtime:W$}).then(e=>i(e.find(e=>e.filePath===n)??null)).catch(()=>{})},[n]);const l=ct(()=>{if(a)return a;const e=n?.split("/").pop()??"plan.md";return{fileName:e,filePath:n??"",title:derivePlanTitle({content:t,fileName:e}),status:"pending",createdAt:"",updatedAt:"",annotations:[]}},[a,n,t]);return ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(B$,{plan:l,variant:"approval",fallbackContent:t,onBack:o,onSubmitFeedback:s,onAutoAccept:r})))}__name(PlanApprovalView,"PlanApprovalView"),Ht(),Ht(),Qx();var H$=Date.now(),G$=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 V$=__name(({sessionId:e,target:t,onClose:n,onSubmitFeedback:r,onExecute:o})=>{const[s,a]=at([]),[i,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=it(!1);lt(()=>{__name(async()=>{try{const[n,r]=await Promise.all([listPlans({runtime:G$,sessionId:e,sessionStartMs:H$}),listPlans({runtime:G$})]);if(a([...n]),l([...r]),t&&!E.current)if(E.current=!0,t===_$){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:i,P=ct(()=>{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(lt(()=>{v(e=>clampScrollOffset({cursor:A,total:P.length,maxVisible:x,currentOffset:e}))},[A,P.length,x]),tt((e,t)=>{(t.leftArrow||t.rightArrow)&&(g(e=>"session"===e?"all":"session"),v(0))},{isActive:I}),h)return ot.createElement(B$,{plan:h,onBack:()=>{f(null),C(e=>e+1)},onSubmitFeedback:r,onExecute:o});if(c)return ot.createElement(ZA,{title:"Plans",gapAfterHeader:!1},ot.createElement(Qe,{color:nI.DIM},"Loading plans..."));if(u)return ot.createElement(ZA,{title:"Plans",titleColor:nI.RED,gapAfterHeader:!1,hint:"Esc to close"},ot.createElement(Qe,{color:nI.DIM},u));const R=w,O=w+x,L=P.slice(R,O),D=P.length>x;return ot.createElement(ZA,{title:"Plans",titleSuffix:ot.createElement(ot.Fragment,null," ",P.length," plan",1===P.length?"":"s"),subtitle:ot.createElement(ot.Fragment,null,ot.createElement(Qe,{bold:"session"===p,color:"session"===p?zA:nI.DIM},"This session"),ot.createElement(Qe,{color:nI.DIMMER},` ${pt.triangleLeftSmall} ${pt.triangleRightSmall} `),ot.createElement(Qe,{bold:"all"===p,color:"all"===p?zA:nI.DIM},"All plans")),footer:ot.createElement(Qe,{italic:!0,color:nI.DIM},"type to search · ↑/↓ navigate · ←/→ switch tab · enter to open",y?" · esc to clear":" · esc to close")},ot.createElement(Je,{marginBottom:1,flexDirection:"column",width:"100%"},ot.createElement(VI,{query:y,resultCount:y?P.length:void 0,placeholder:"Type to search plans..."})),0===P.length?ot.createElement(Je,{marginY:1},ot.createElement(Qe,{color:nI.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.")):ot.createElement(ot.Fragment,null,ot.createElement(Je,{flexDirection:"column"},L.map((e,t)=>{const n=R+t===A,r=F$[e.status];return ot.createElement(Je,{key:e.fileName},ot.createElement(Qe,{color:n?YA:nI.GRAY},n?`${pt.pointer} `:" "),ot.createElement(Qe,{bold:n,color:n?YA:nI.WHITE},e.title),ot.createElement(Qe,{color:r.color}," ",r.label),(e.version??1)>1&&ot.createElement(Qe,{color:nI.DIM}," ","v",e.version),e.annotations.length>0&&ot.createElement(Qe,{color:nI.CYAN}," ",e.annotations.length," comment",1===e.annotations.length?"":"s"),ot.createElement(Qe,{color:nI.DIM}," ",formatRelativeTimeShort({timestamp:e.updatedAt})))})),D&&ot.createElement(Je,{marginTop:1},ot.createElement(Qe,{color:nI.DIM},"Showing ",R+1,"–",Math.min(O,P.length)," of"," ",P.length,R>0?" · ↑ more":"",O<P.length?" · ↓ more":""))))},"PlansScreen");function PlansView({staticKey:e,sessionId:t,target:n,onClose:r,onSubmitFeedback:o,onExecute:s}){return ot.useEffect(()=>{hardResetForResize()},[]),ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(Je,{flexDirection:"column",width:"100%"},ot.createElement(V$,{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:nI.DIM,o=e.userRenamed&&e.title?e.title:null;return o?ot.createElement(Qe,{color:n},`${o} `,ot.createElement(Qe,{color:r},`· ${e.forkProvenance}`)):ot.createElement(Qe,{color:r},e.forkProvenance)}__name(PlansView,"PlansView"),Ht(),Ht(),Qx(),Ht(),__name(ForkSummary,"ForkSummary");var z$=__name((e,t)=>e.padEnd(t),"padCell"),K$=__name(e=>e instanceof Error&&e.message?e.message:"Unknown error","getActionErrorMessage");function resolveRowColor(e){return e.isDeletePending?nI.RED:e.isCurrentSession?rI:e.isSelected?nI.WHITE:nI.GRAY}function renderRowSummary(e){const{session:t,isSelected:n,nameColor:r}=e;if(t.forkProvenance)return ot.createElement(ForkSummary,{session:t,isSelected:n,nameColor:r});const o=getSessionSummary({session:t});return t.userRenamed&&t.title?ot.createElement(Qe,{color:r},o):o}__name(resolveRowColor,"resolveRowColor"),__name(renderRowSummary,"renderRowSummary");var q$=["recent","created","messages"],Y$={recent:"Recent",created:"Created",messages:"Messages"};function nextSortMode(e){const t=q$.indexOf(e);return q$[(t+1)%q$.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 J$=__name(({onSelectSession:e,onClose:t,currentSessionId:n})=>{const[r,o]=at([]),[s,a]=at(0),[i,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,O]=at(""),[L,D]=at(null),[N]=at(()=>getCurrentGitBranch()),[$]=at(()=>resolveProjectBaseDir()),_=useTerminalHeight(),F=Math.max(6,_-19),U=dt(async()=>{d(!0);const e=await listCommandSessions();o(e),d(!1)},[]);lt(()=>{U()},[U]),lt(()=>{if(!y)return;const e=setTimeout(()=>S(null),3e3);return()=>clearTimeout(e)},[y]);const j=dt(async e=>{try{const t=getCommandSessionRuntime(),{method:n}=await deleteSessionV3({runtime:t,baseDir:$,id:e});g(!1),f(null),a(0),l(0),S("trash"===n?"Session moved to trash":"Session deleted"),await U()}catch(e){g(!1),f(`Failed to delete session: ${K$(e)}`)}},[U,$]),B=dt(async e=>{const t=I;if(t)try{const n=getCommandSessionRuntime();await renameSessionFile({runtime:n,cwd:n.cwd(),baseDir:$,id:t,name:e}),x("list"),A(null),D(null),await U()}catch(e){D(`Failed to rename session: ${K$(e)}`)}else x("list")},[I,U,$]),W=filterSessionsByBranch({sessions:r,branchFilter:u,currentBranch:N}),H=T?W.filter(e=>e.userRenamed):W,G=sortSessions(w?H.filter(e=>matchesSearch2(e,w)):H,b);if(lt(()=>{a(e=>Math.min(e,Math.max(0,G.length-1)))},[G.length]),tt((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),O(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),a(0),void l(0)):o.escape?w?(v(""),a(0),void l(0)):void t():isCtrlKey({inputChar:r,key:o,letter:"b",ctrlCode:2})?(m(e=>!e),a(0),void l(0)):void(o.upArrow?a(e=>{const t=Math.max(0,e-1);return t<i&&l(t),t}):o.downArrow?a(e=>{const t=Math.min(G.length-1,e+1);return t>=i+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)),a(0),l(0)):!o.ctrl&&!o.meta&&!o.tab&&r&&1===r.length&&r>=" "&&(v(e=>e+r),a(0),l(0)));E(e=>nextSortMode(e))}}}),c)return ot.createElement(Je,{flexDirection:"column",paddingLeft:2},ot.createElement(VO,{label:"Loading sessions"}));if(0===r.length)return ot.createElement(Je,{flexDirection:"column",paddingLeft:2},ot.createElement(YO,{message:"No previous sessions found",hint:"Press Esc to go back"}));const V=G.slice(i,i+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:N});return ot.createElement(ZA,{title:"Resume Session",subtitle:`Sort: ${Y$[b]} · Name: ${T?"Named":"All"} · Branch: ${u?N??"unknown":"All"}`},ot.createElement(Je,{marginBottom:1,width:"100%"},ot.createElement(VI,{query:w,resultCount:w?G.length:void 0,placeholder:"Type to search sessions..."})),ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:pI,bold:!0},z$("#",6),z$("Modified",12),z$("Git Branch",22),z$("Messages",12),"Summary",k?" · Path":"")),0===G.length?ot.createElement(Je,{marginBottom:1},ot.createElement(YO,{message:q.text,hint:q.hint})):ot.createElement(Je,{flexDirection:"column"},V.map((e,t)=>{const r=i+t,o=s===r,a=p&&o,l=a?void 0:nI.YELLOW,c=resolveRowColor({isDeletePending:a,isCurrentSession:e.id===n,isSelected:o}),d=truncateString2({text:e.gitBranch||"-",maxChars:20}),u=k?toRelativePath(`${$}/${e.id}.jsonl`):null;return ot.createElement(Qe,{key:e.id,color:c,backgroundColor:o?TI:void 0,bold:o,wrap:"truncate-end"},z$(`${r+1}.`,6),z$(formatRelativeTimeShort({timestamp:e.lastModified}),12),z$(d,22),z$(String(e.messageCount),12),renderRowSummary({session:e,isSelected:o,nameColor:l}),u?ot.createElement(Qe,{color:nI.DIM},` ${u}`):null," ")})),ot.createElement(Je,{marginTop:1}),"rename"===M&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.CYAN},"Rename: "),ot.createElement(TextInput,{value:R,onChange:O,onSubmit:B,singleLine:!0,stripBracketedPaste:!0})),L&&ot.createElement(Je,{marginBottom:1},ot.createElement(zO,{glyph:!1},L)),K&&ot.createElement(Je,{marginBottom:1},ot.createElement(Qe,{color:nI.RED},K)),h&&ot.createElement(Je,{marginBottom:1},ot.createElement(zO,{glyph:!1},h)),y&&ot.createElement(Je,{marginBottom:1},ot.createElement(KO,{glyph:!1},y)),G.length>F&&ot.createElement(Qe,{color:nI.DIM},"Showing ",i+1,"–",Math.min(i+F,G.length)," ","of ",G.length,i>0?" · ↑ more":"",i+F<G.length?" · ↓ more":""),ot.createElement(VA,{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"),Q$=st(__name(function SessionView2({onSelectSession:e,onClose:t,currentSessionId:n}){return ot.createElement(J$,{onSelectSession:e,onClose:t,currentSessionId:n})},"SessionView"));Ht(),Ht();var X$=__name(({onTrust:e,onExit:t})=>{const{exit:n}=nt(),[r,o]=at(1),s=process.cwd(),a=W(),i=a&&s.startsWith(a)?`~${s.slice(a.length)}`:s;return tt((s,a)=>{if(a.upArrow||a.downArrow)o(1===r?2:1);else{if(a.return)return 1===r?void e():(t(),void n());if("1"!==s)return"2"===s?(t(),void n()):void((a.escape||a.ctrl&&"c"===s)&&(t(),n()));e()}}),ot.createElement(ZA,{title:"Do you trust the files in this folder?",subtitle:i,hint:"↑/↓ to navigate · enter to select · esc to exit"},ot.createElement(Je,{flexDirection:"column"},ot.createElement(Qe,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),ot.createElement(Je,{marginTop:1},ot.createElement(Qe,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),ot.createElement(Je,{marginTop:1,flexDirection:"column"},ot.createElement(Je,null,ot.createElement(WL,{isSelected:1===r}),ot.createElement(HL,{isSelected:1===r,idleColor:QA}," ","1. Yes, proceed")),ot.createElement(Je,null,ot.createElement(WL,{isSelected:2===r}),ot.createElement(HL,{isSelected:2===r,idleColor:QA}," ","2. No, exit"))))},"TrustPrompt"),Z$=st(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return ot.createElement(ot.Fragment,null,ot.createElement(bA,{staticKey:e}),ot.createElement(X$,{onTrust:t,onExit:n}))},"TrustView"));Ht(),Ht();var e_=new Map;function enqueueAgentSlashCommand(e){const t=e_.get(e.sessionId);t?t.push(e.command):e_.set(e.sessionId,[e.command])}function drainAgentSlashCommands(e){const t=e_.get(e.sessionId);return t&&0!==t.length?(e_.delete(e.sessionId),t):[]}function useAgentSlashCommandQueue({sessionId:e,isCmdCodeBusy:t,onCommand:n}){const r=it(!1);lt(()=>{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),[a,i]=at(!1),[l,c]=at(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,authComponentInfo:o,setAuthComponentInfo:s,showProviderNotification:a,setShowProviderNotification:i,premiumCreditsExhausted:l,setPremiumCreditsExhausted:c,providerNotificationTimer:it(null),modelNotificationTimer:it(null)}}__name(enqueueAgentSlashCommand,"enqueueAgentSlashCommand"),__name(drainAgentSlashCommands,"drainAgentSlashCommands"),__name(useAgentSlashCommandQueue,"useAgentSlashCommandQueue"),Ht(),Qx(),__name(useAuth,"useAuth"),Ht(),Qx();var t_=__name(()=>{const[e,t]=at({isExecuting:!1,currentCommand:null});return{executeBash:dt(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");Ht(),Ht(),Qx(),Ht(),Qx();var n_={detectIDE:NC,isIdeIpcConnected:__name(async e=>{const t=VC(),n=await t.connect(e);return t.disconnect(),n},"isIdeIpcConnected"),log:dlog,platform:__name(()=>process.platform,"platform")};Ht();var r_=null,o_={};function requestReload(e){r_=e}function discardPendingReload(){r_=null}function consumePendingReload(){const e=r_;return r_=null,e}function setOriginalInvocation(e){o_=e}function getOriginalInvocation(){return o_}function resolveProviderOrReport(e){return resolveCommandProviderId(e.provider)||(e.setFeed(t=>[...t,gg(`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,gg("Provider login is not available here.")]):void t(t=>[...t,lg(`${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,lg(s.message)])}function handleLoginComplete({success:e,message:t,setShowLoginOverlay:n,setFeed:r,setStatus:o}){if(n(!1),!e)return r(e=>[...e,gg(t)]),void o("Ready...");r(e=>[...e,lg(t)]),invalidateBillingContext(),o("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,lg("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,lg(`${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,lg(n?`Logged out of ${r}`:`No saved ${r} credential found`)])}catch(n){const r=n instanceof Error?n.message:"Unknown error";t(t=>[...t,gg(`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?gg(s.notice.message):lg(s.notice.message)])}function parseChangelogVersions(e){return e.split(/^(?=## )/m).map(e=>e.trim()).filter(e=>e.startsWith("## "))}function findChangelogPath(e){let t=r(m(e));for(let e=0;e<6;e++){const e=n(t,"CHANGELOG.md");if(I(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,lg("No changelog available in this build.")]);const o=parseChangelogVersions(A(r,"utf8"));if(0===o.length)return void e(e=>[...e,lg("The changelog is empty.")]);const s="all"===t.trim().toLowerCase()?o.length:10,a=o.slice(0,s).join("\n\n"),i=o.length-s,l=i>0?`\n\n_…and ${i} earlier releases · /changelog all_`:"";e(e=>[...e,pg(`**What's new**\n\n${a}${l}`)])}async function releaseHarness(e){if(e){try{await($O(e)?.flush())}catch{}_O(e)}}async function handleSelectSession({selectedSessionId:e,previousSessionId:t,sessionLoadIdRef:n,setFeed:r,setLiveEntries:o,setSessionId:s,setShowSessionSelector:a,setSessionLoaded:i,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),a(!1),i(!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([gg(g.message)]),a(!1),i(!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);$O(e)?.applyTodoUserEdit({todos:h}),g.bannerModelChanged||isWrappedChild()?hardResetForResize():cA(),l(e=>e+1)}__name(requestReload,"requestReload"),__name(discardPendingReload,"discardPendingReload"),__name(consumePendingReload,"consumePendingReload"),__name(setOriginalInvocation,"setOriginalInvocation"),__name(getOriginalInvocation,"getOriginalInvocation"),Ht(),Qx(),__name(resolveProviderOrReport,"resolveProviderOrReport"),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Ht(),Qx(),__name(parseChangelogVersions,"parseChangelogVersions"),__name(findChangelogPath,"findChangelogPath"),__name(handleChangelog,"handleChangelog"),Ht(),Qx(),Ht(),Qx(),__name(releaseHarness,"releaseHarness"),__name(handleSelectSession,"handleSelectSession");var s_="Nothing to clone yet.";async function handleCloneCommand(e){const t=$O(e.sessionId);if(t)try{const n=await t.cloneSession();if(!n)return void e.setFeed(e=>[...e,lg(s_)]);e.setFeed(e=>[...e,lg(`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,gg("Couldn't clone the session (storage error). Staying on the current session.")])}else e.setFeed(e=>[...e,lg(s_)])}async function handleCompactCommand({sessionId:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:o,setStaticKey:s}){try{r(!0),n("Compacting conversation...");const a=await NO({sessionId:e,baseUrl:getApiBaseUrl()}),i=await a.compact();cA(),s(e=>e+1);const l=buildCompactCommandNotice(i);t(e=>[...e,lg(l.message)]),r(!1),n("Ready..."),o(buildPostCompactContextUsage())}catch(e){t(t=>[...t,gg(buildCompactErrorNotice(e).message)]),r(!1),n("Ready...")}}__name(handleCloneCommand,"handleCloneCommand"),Ht(),Qx(),__name(handleCompactCommand,"handleCompactCommand"),Ht(),Qx();var a_=__name(e=>{const t=e.metadata?.blockOf;return"string"==typeof t?t:e.id},"groupIdOf"),i_=__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=a_(n),o=[];for(let n=t;n>=0;n--){const t=e[n];if(!t||"assistant"!==t.role||a_(t)!==r)break;const s=i_(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,lg("Nothing to copy yet — no reply in this session.")]);const r=await writeClipboardText(n),o=n.length.toLocaleString("en-US");t(e=>[...e,lg(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?Lg(o):null;if(!s)return!1;const a=projectUserEdits(s);return a.every(e=>"completed"===e.status)?(clearSessionTodos(),a.length>0&&routeHarnessFeedEntry({entry:{...t,output:JSON.stringify(a)},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,...a}=e.metadata??{};r.push({...e,id:`${e.id}-block-${n}`,input:o,metadata:{...a,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),a=buildBlockEntries(e,o,s.newlyCompleted);a.length>0&&t(e=>[...e,...a]);const i={...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,i];const r=[...t];return r[n]=i,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 a=buildBlockEntries(e,o,s.remaining);a.length>0&&t(e=>[...e,...a])}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:a,displayMessage:i,isAutomated:l,isMeta:c,hiddenMessages:d,isGoalContinuation:u,isGoalBootstrap:m,suppressUserEcho:p,feed:g,setFeed:h,setLiveEntries:f,isCmdCodeBusy:y,setIsCmdCodeBusy:S,setQueuedMessages:w,setStatus:v,setInteractionTokens:k,updateStatus:C,setUpdateStatus:b,billingLink:E,setBillingLink:T,currentModel:P,currentProvider:M,premiumCreditsExhausted:x,setPremiumCreditsExhausted:I,setCurrentModel:A,sessionId:R,isSubmittingRef:O,setInput:L,setStaticKey:D,executeBash:N}=e,$=resolveSubmitStartPlan({role:t,input:n,isCmdCodeBusy:y,isSubmitting:O.current,displayMessage:i,isAutomated:l,isMeta:c,hiddenMessages:d,images:r,ideContext:s,ideHint:a});if("skip"===$.kind&&!n.length)return $.outcome;if(C&&b(null),k(0),"skip"===$.kind)return $.outcome;if("bash"===$.kind){O.current=!0;const e=mg(n);return h([...g,e]),L(""),await N(n,e=>{h(e)},()=>{cA(),D(e=>e+1)}),O.current=!1,"completed"}if("queue"===$.kind)return w(e=>[...e,$.queuedMessage]),l||L(""),$.outcome;O.current=!0;const _=await runModInputInterception(e);if("handled"===_.action){O.current=!1;const e=_.message;return e&&h(t=>[...t,lg(e)]),"skipped"}const F="transform"===_.action?_.text:n;await loadCustomProviderModels();const U=await checkOAuthSetupRequired({currentProvider:M??null,isByokModel:isByok({model:P??""}),providerAuthHeaders:providerAuthHeaders});if(U)return O.current=!1,v(U),h(e=>[...e,gg(U)]),"skipped";S(!0),v(Tg()),l||L("");let j=!1,B=null,W=null,H=null,G=0;const V=createSubmitGoalSupervisor(e);let z=null;const K=resolvePremiumCreditsPreflight({premiumCreditsExhausted:x,currentModel:P});if(K.blocked)return j=!0,v(K.status),h(e=>[...e,lg(K.message)]),S(!1),O.current=!1,K.outcome;try{z=await V.getGoalTurnBudget();const e=await NO({sessionId:R,baseUrl:getApiBaseUrl()});if(m&&!isCommandGoalLoopArmed(R))return"skipped";const t=clipboardImagesToUserContent(r),n=s?`${s}\n\n${F}`:F,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}:{}}:{},...a?{ideHint:a}:{}};trackFirstMessage();const u=await runHarnessTurnIntoFeed({harness:e,input:F,turnUserInput:l,runQuery:runHarnessQuery,setFeed:h,setLiveEntries:f,displayMessage:i,suppressUserEcho:p,additionalContent:hiddenMessagesToUserContent(d),inputMeta:$.inputMeta,maxTurns:z?.remainingTurns,onRoundTrip:__name(e=>{G=e},"onRoundTrip"),echoMetadata:Object.keys(c).length>0?c:void 0,setStatus:v,onInteractionTokens:k,onRunError:__name(e=>{W=e},"onRunError"),routeEntry:createBlockCommittingRouter({setFeed:h,setLiveEntries:f}),scrubGoalCompleteMarker:isCommandGoalLoopArmed(R)});if(W){const e=P?byokProviderId({model:P}):void 0;throw formatRunError(W,e?{byokProvider:e}:void 0)}return H=u.finalText,G=u.turnCount,"completed"}catch(e){const t=resolveSubmitErrorAction({error:e,sessionId:R});if("interrupted"===t.kind)return j=!0,t.outcome;if(trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"submit_error"}),context:{component:xo.SUBMIT,heading:"Prompt submission failed",code:t.kind}}),j=!0,B=t.goalErrorKind,"insufficient-credits"===t.kind){v(t.status);const e=await getBillingLink({billingLink:E,setBillingLink:T});return h(t=>[...t,gg(buildInsufficientCreditsSubmitActionMessage({billingUrl:e}))]),t.outcome}if("premium-credits-exhausted"===t.kind)return I?.(!0),A?.(t.fallbackModelId),cA(),D(e=>e+1),v(t.status),h(e=>[...e,lg(t.message)]),t.outcome;v(t.status);const n="info"===t.renderKind?lg(t.message):gg(t.message);return h(e=>[...e,n]),t.outcome}finally{S(!1),j||v("Ready..."),O.current=!1,await V.afterTurn({assistantText:j?null:H,errorKind:j?B:null,isGoalContinuation:u,turnsUsed:G,goalStartedAt:z?.startedAt})}return"skipped"}function emitGoalNotice(e,t){e(e=>[...e,lg(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=>($O(t)??await NO({sessionId:t,baseUrl:getApiBaseUrl()})).verifyGoal(e),"verifyCompletion"),getEvidence:__name(()=>{const e=$O(t);return e?harnessRecentToolEvidence(e):""},"getEvidence"),emitCompletion:__name(e=>{n(t=>[...t,lg("",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,gg(Sk)]);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:a}=o.command;if("completed"===s&&a&&isDesignMode(a)){const t=getDesignModeSuggestions(a);t&&e.setPendingDesignSuggestion?.(t)}}catch(t){e.setFeed(e=>[...e,gg(buildDesignSkillLoadErrorMessage(t))])}}__name(findLastAssistantText,"findLastAssistantText"),__name(handleCopy,"handleCopy"),Ht(),Qx(),Ht(),Qx(),Ht(),Qx(),__name(getAuthKey3,"getAuthKey"),__name(trackFirstMessage,"trackFirstMessage"),Ht(),Qx(),__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"),Ht(),Qx();var l_="Nothing to export yet — the transcript is created on the first message.",c_=new Set(["html","jsonl","md"]);function matchFormatKeyword(e){const t=e.toLowerCase();return c_.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=i(t)?t:s(e.cwd,t);if(I(o)&&N(o).isDirectory())return{kind:"target",format:"html",path:n(o,defaultExportFilename(e.sessionId,"html"))};const a=d(o).toLowerCase();return a?".html"===a?{kind:"target",format:"html",path:o}:".jsonl"===a?{kind:"target",format:"jsonl",path:o}:".md"===a?{kind:"target",format:"md",path:o}:{kind:"unknown-extension",extension:a}:{kind:"target",format:"html",path:n(o,defaultExportFilename(e.sessionId,"html"))}}function exportedMessage(e){const t=toRelativePath(e.path),n=It.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(I(t)){try{F(t,e.target)}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,lg(`Export failed: ${n}`)])}e.setFeed(t=>[...t,lg(exportedMessage({path:e.target,formatLabel:"JSONL"}))])}else e.setFeed(e=>[...e,lg(l_)])}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,lg(`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,lg(`Export failed: ${n}`)])}e.setFeed(t=>[...t,lg(exportedMessage({path:e.target,formatLabel:"HTML"}))])}else e.setFeed(e=>[...e,lg(l_)])}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,lg(`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,lg(`Export failed: ${n}`)])}e.setFeed(t=>[...t,lg(exportedMessage({path:e.target,formatLabel:"Markdown"}))])}else e.setFeed(e=>[...e,lg(l_)])}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,lg(`Unknown export extension "${r.extension}". Supported export formats: .html, .jsonl, .md`)])}async function handleForkCommand(e,t){const n=$O(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,cg({name:r.title})])}catch{e.setFeed(e=>[...e,gg(Sh)])}else e.setFeed(e=>[...e,"error"===r.notice.kind?gg(r.notice.message):lg(r.notice.message)])}function setMode(e,t){e.permissionModeRef.current=t,e.setPermissionMode(t),$O(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,lg(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"),Ht(),Qx(),__name(handleForkCommand,"handleForkCommand"),Ht(),Qx(),__name(setMode,"setMode"),__name(handlePlanCommand,"handlePlanCommand"),Ht(),Qx();var d_=[{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"},{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 d_){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,pg(buildHotkeysMarkdown())])}async function handleImportCommand({setFeed:e},t=""){const n=resolveAgentImportSourceArg(t);if(!n.ok)return void e(e=>[...e,gg(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,lg("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,lg(formatAgentImportSummary(o))])}catch(t){e(e=>[...e,gg(`Import failed: ${t instanceof Error?t.message:"unknown error"}`)])}}function setMode2(e,t){e.permissionModeRef.current=t,e.setPermissionMode(t),$O(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,lg(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?gg(t.notice.message):lg(t.notice.message)]),"renamed"===t.kind){e.setRenamedTerminalTitle(t.name);try{(e.harness??await NO({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 NO({sessionId:e,baseUrl:getApiBaseUrl()}),o=await r.regenerateTitle();if(!o)return void t(e=>[...e,lg("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,lg("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=$O(e.sessionId)?.getSessionStats().name,n=t?null:await loadCommandSessionMeta({sessionId:e.sessionId}).catch(()=>null),r=t??n?.title;e.setFeed(e=>[...e,lg(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=$O(e),o=resolveRewindCommand({hasActiveConversation:Boolean(r),checkpointCount:r?.listCheckpoints().length??0});"notice"!==o.kind?n(!0):t(e=>[...e,"error"===o.notice.kind?gg(o.notice.message):lg(o.notice.message)])}async function handleRewindSelect({messageId:e,mode:t,sessionId:n,setFeed:r,setStatus:o,setShowRewindSelector:s,setStaticKey:a,setInput:i}){s(!1);const l=$O(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)}),cA(),a(e=>e+1),c.promptToRestore&&i(c.promptToRestore),r(e=>[...e,lg(c.notice.message)]),void o(c.statusMessage);r(e=>[...e,"error"===c.notice.kind?gg(c.notice.message):lg(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,lg("No active session.")]);const r=n(getProjectSessionDir({env:process.env,cwd:getCurrentWorkingDirectory()}),`${e}.jsonl`),o=formatSessionFileLine({absolutePath:r,exists:I(r),linksSupported:It.isSupported});t(t=>[...t,lg(`Session ID: ${e}\nCurrent session file: ${r}`,{isSessionFile:!0,sessionFileId:e,sessionFileLine:o})])}__name(buildHotkeysMarkdown,"buildHotkeysMarkdown"),__name(handleHotkeys,"handleHotkeys"),Ht(),Qx(),__name(handleImportCommand,"handleImportCommand"),Ht(),Qx(),__name(setMode2,"setMode"),__name(handleModeCommand,"handleModeCommand"),Ht(),Qx(),__name(applyRenameResult,"applyRenameResult"),__name(autoRenameSession,"autoRenameSession"),__name(handleRenameCommand,"handleRenameCommand"),__name(handleNameCommand,"handleNameCommand"),Ht(),Qx(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),Ht(),Qx(),__name(compactTranscriptPath,"compactTranscriptPath"),__name(formatSessionFileLine,"formatSessionFileLine"),__name(handleSessionFile,"handleSessionFile"),Ht(),Qx();var u_=Te(h),m_=/https:\/\/gist\.github\.com\/\S+/;function parseGistUrl(e){const t=m_.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 u_("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 I(r)?(F(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:a=writeClipboardText}=e.deps??{},i=__name(t=>e.setFeed(e=>[...e,lg(t)]),"info");if(!t("gh"))return void i("Requires the GitHub CLI (gh) — https://cli.github.com");const l=await resolveShareGistFormat(e.rawFormatArg);if(!l)return void i(`Unknown gist format "${(e.rawFormatArg??"").trim()}". Supported gist formats: html, jsonl, md`);let c;try{c=await ie(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 i("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 i(`gh gist create did not return a URL: ${d.trim()}`);await a(u),i(`Shared session gist: ${It.isSupported?createOSC8Link(u,u,!1):u}`)}catch(e){const t=execErrorText(e);i(/auth/i.test(t)?`${t} — run gh auth login`:`Share failed: ${t}`)}finally{c&&await ee(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()}),a=await createCommandSessionShareLink({client:s,sessionId:e,existingShareInfo:t,harness:e?$O(e):void 0,projectRoot:global.COMMAND_CODE_CWD||process.cwd()});"no-session"!==a.status&&"error"!==a.status?(n(a.shareInfo),await copyOrFallback(a.shareInfo.url,r)&&(r(""),o(!0),setTimeout(()=>{o(!1)},shareNotificationDurationMs(a.status)))):r(a.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()}),a=await deleteCommandSessionShareLink({client:s,sessionId:e,shareInfo:t,harness:e?$O(e):void 0});if("no-session"!==a.status){if("not-shared"===a.status)return o(a.message),void setTimeout(()=>o(""),Vv);if("error"===a.status)return r(a.message),void setTimeout(()=>r(""),Vv);o(a.message),r(""),n(null),setTimeout(()=>{o("")},Vv)}else r(a.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,lg(`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,lg(`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,lg(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=$O(e),a=resolveTreeCommand({hasActiveConversation:Boolean(s),treeEntryCount:s?.getSessionTree().length??0});if("notice"===a.kind)return void t(e=>[...e,"error"===a.notice.kind?gg(a.notice.message):lg(a.notice.message)]);const[i,l]=await Promise.all([getTreeFilterMode(),getBranchSummarySkipPrompt()]);r(i),o(l),n(!0)}async function handleTreeSelect({entryId:e,summarize:t,customInstructions:n,sessionId:r,setFeed:o,setShowTreeSelector:s,setStaticKey:a,setInput:i}){const l=$O(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,lg("Already at this point")]),{aborted:!1}):(s(!1),o(reconstructFeedFromMessages(harnessSessionMessages(l))),cA(),a(e=>e+1),r.editorText&&i(r.editorText),o(e=>[...e,lg("Navigated to selected point")]),{aborted:!1})}catch(e){return o(t=>[...t,gg(`Failed to navigate: ${actionErrorMessage(e)}`)]),{aborted:!1}}}function handleTreeCancel({setShowTreeSelector:e}){e(!1)}function handleTreeAbortSummary({sessionId:e}){$O(e)?.abortBranchSummary()}function handleTreeLabel({entryId:e,label:t,sessionId:n,setFeed:r}){const o=$O(n);if(o)try{o.setTreeLabel({targetId:e,label:t})}catch(e){r(t=>[...t,gg(`Failed to set label: ${actionErrorMessage(e)}`)])}}function announceCompletedUpdate({fromVersion:e,toVersion:t}){console.log(bt.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:xo.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"),Ht(),Qx(),__name(loadPersistedTraceIds,"loadPersistedTraceIds"),__name(handleTrace,"handleTrace"),Ht(),Qx(),__name(actionErrorMessage,"actionErrorMessage"),__name(handleTreeCommand,"handleTreeCommand"),__name(handleTreeSelect,"handleTreeSelect"),__name(handleTreeCancel,"handleTreeCancel"),__name(handleTreeAbortSummary,"handleTreeAbortSummary"),__name(handleTreeLabel,"handleTreeLabel"),Ht(),Qx(),Ht(),Qx(),__name(announceCompletedUpdate,"announceCompletedUpdate"),__name(trackUpdateFailure,"trackUpdateFailure");var p_={createLifecycleEventClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createLifecycleEventClient"),isTelemetryEnabled:isTelemetryEnabled,log:dlog,onCompletedUpdate:announceCompletedUpdate,trackUpdateFailure:trackUpdateFailure},g_={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"),a=await runTuiUpdateCommand({state:g_,host:p_,copy:{binCommand:`${getBinaryCommand()}`,updateCommand:"npm i -g command-code"},emit:s});trackTuiUpdateCommandTelemetry(a),"error"!==a.level?e(e=>[...e,lg(a.message,a.metadata)]):e(e=>[...e,gg(a.message)])}function tildeHome(e){const t=B.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function formatWorktreePathLine(e){return` ${gt.dim(pt.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,a=createWorktree({spec:"string"==typeof e?e.trim():void 0,cwd:o});if(!a.ok)return{ok:!1,error:a.error};try{process.chdir(a.target.worktreePath),global.COMMAND_CODE_CWD=a.target.worktreePath}catch(e){return{ok:!1,error:`couldn't enter worktree: ${e instanceof Error?e.message:String(e)}`}}if(r&&a.created&&markAutoCreatedWorktree({worktreePath:a.target.worktreePath,branch:a.target.branch,baseSha:a.baseSha,mainRoot:s}),!n){const e=a.created?"Created":"Entered",t=a.created?gt.dim(` (branch ${a.target.branch}${a.usedRemote?", from origin":""})`):"",n=a.created&&a.copiedFiles>0?gt.dim(` · copied ${a.copiedFiles} file(s)`):"",r=a.created&&a.copyFailedFiles.length>0?gt.dim(` · ${a.copyFailedFiles.length} include copy failure(s)`):"";process.stdout.write(`${gt.cyan(pt.squareSmallFilled)} ${e} worktree ${gt.bold(a.target.name)}${t}${n}${r}\n${formatWorktreePathLine(a.target.worktreePath)}\n`)}return dlog(`[worktree] entered ${a.target.worktreePath} (created=${a.created})`),{ok:!0,name:a.target.name,path:a.target.worktreePath}}__name(handleUpdateCommand,"handleUpdateCommand"),Ht(),Qx(),Ht(),Qx(),__name(tildeHome,"tildeHome"),__name(formatWorktreePathLine,"formatWorktreePathLine"),__name(enterWorktreeFromFlag,"enterWorktreeFromFlag");var h_=__name((e,t)=>e.setFeed(e=>[...e,lg(t)]),"info"),f_=__name((e,t)=>e.setFeed(e=>[...e,gg(t)]),"error");function renderList(e,n){const r=listWorktrees(e);return 0===r.length?"No worktrees found.":["Worktrees:",...r.map(r=>{const o=samePath(r.path,e)?"●":"○",s=t.relative(n,r.path),a=r.isMain?".":s&&!s.startsWith("..")?s:tildeHome(r.path);return` ${o} ${r.isMain?`${a} (main)`:a}${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 f_(e,"/worktree requires a git repository.");const r=getMainWorktreeRoot(n)??n,o=t[0]?.toLowerCase();if(!o||"list"===o||"ls"===o)return void h_(e,renderList(n,r));if("remove"===o||"rm"===o){const o=t[1];return o?void await handleRemove(e,o,n,r):void f_(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(samePath(s.worktreePath,r))return void f_(e,"Can't remove the worktree you're in. Switch away first, then remove it.");if(!listWorktrees(r).some(e=>samePath(e.path,s.worktreePath)))return void f_(e,`No worktree named "${n}".`);const a=removeWorktree({worktreePath:s.worktreePath,cwd:r,deleteBranch:isManagedWorktreePath(s.worktreePath,o)?s.branch:void 0});a.ok?h_(e,`Removed worktree "${n}".`):f_(e,`Couldn't remove "${n}": ${a.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 f_(e,`Couldn't create worktree: ${r.error}`);if(samePath(r.target.worktreePath,n))return void h_(e,`Already in worktree "${r.target.name}".`);const o=r.created?"Created":"Reusing",s=r.created&&r.copiedFiles>0?` (copied ${r.copiedFiles} file(s))`:"",a=r.created&&r.copyFailedFiles.length>0?` (${r.copyFailedFiles.length} include copy failure(s))`:"";h_(e,`${o} worktree "${r.target.name}"${s}${a}. Switching… (a fresh session starts in the worktree; this one stays resumable).`),await($O(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,pg(Ng)])}async function handleTerminalSetupCommand({setFeed:e}){const t=ig("/terminal-setup"),n=setupVSCodeTerminal(),r=fg(n.message,!n.success,n.details),o=fg("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);e(e=>[...e,t,r,o])}async function handleIDESetupCommand({setFeed:e}){const t=await runIdeSetup({host:n_,moduleUrl:import.meta.url}),n=yg(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:a,setContextUsage:i,setInteractionTokens:l,sessionId:c,setSessionId:d,clearSessionPermissions:u}){e([]),t([]),n([]),clearSessionTodos(),clearShellTasks(),cA(),r(null),o(!1),s(""),await deleteCommandSessionShareInfo({sessionId:c}).catch(()=>{});const m=$O(c);m?.stopBackgroundLearning(),await(m?.flush().catch(()=>{})),_O(c),setNextSessionStartSource("clear"),d(crypto.randomUUID()),u(),a(e=>e+1),i(null),l(0)}async function handleInitCommand({setFeed:e}){const t=await resolveInitMemoryCommand({projectRoot:process.cwd()});e(e=>[...e,lg(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,lg(s.notice.message,s.notice.metadata)]),o&&"notice"===s.status&&"cleared"===s.notice.metadata?.goalNoticeKind&&$O(e.sessionId)?.requestStopAfterTurn(),"start"===s.status&&await runGoalTurn(e,s.goalText,n,r)}async function openExternalSlashCommandTarget({setFeed:e,target:t}){e(e=>[...e,lg(`Opening ${createOSC8Link(t.url,t.noticeLabel,!1)} in your browser…`)]);try{await Tt(t.url,{wait:!1,background:!0})}catch{const{fallback:n}=t;if("info"===n.kind)return void e(e=>[...e,lg(n.message)]);e(e=>[...e,gg("Failed to open browser"),pg(createOSC8Link(t.url,n.label,!1))])}}function handleLearnCommand({setAutoLearnTaste:e,setShowTasteOnboarding:t,setTasteOnboardingEntryId:n,setFeed:r}){e(!0),t(!0);const o=hg();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,lg(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,lg("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,gg(`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:a,positionalArgs:i}=o;if("/exit"===s||"/quit"===s)return discardPendingReload(),t.setShouldExit(!0),{status:"handled"};if("/reload"===s)return await($O(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=a.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:a,positionalArgs:i,command:e}),{status:"handled"};if("/skills"===s)return t.setShowSkillsConfig(!0),{status:"handled"};if("/plans"===s)return t.setPlansTarget(a.trim()||null),t.setShowPlansView(!0),{status:"handled"};if("/plan-review"===s)return t.setPlansTarget(_$),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,a),{status:"handled"};if("/effort"===s)return await handleEffortCommand(t,a),{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,a.trim()||void 0),{status:"handled"};if("/worktree"===s)return await handleWorktreeCommand(t,i),{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,a),{status:"handled"};if("/goal"===s)return await handleGoalCommand(t,a,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:a,setFeed:t.setFeed,setShowLoginOverlay:t.setShowLoginOverlay,setAuthComponentInfo:t.setAuthComponentInfo}),t.setInput(""),{status:"handled"};if("/logout"===s)return await handleLogoutCommand({provider:a,setFeed:t.setFeed,setRetryAttempt:t.setRetryAttempt,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),t.setInput(""),{status:"handled"};if("/courses"===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:a});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:a,currentModel:t.currentModel,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/changelog"===s)return handleChangelog({setFeed:t.setFeed,rawArguments:a}),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,lg("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:a.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:a.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,a),{status:"handled"};if("/plan"===s)return await handlePlanCommand({rawArguments:a,ctx:t}),{status:"handled"};if("/mode"===s||s.startsWith("/mode:")){const e=s.startsWith("/mode:")?s.slice(6):a;return await handleModeCommand({rawArguments:e,ctx:t}),{status:"handled"}}if("/review"===s){const e=await resolveReviewSlashCommand({rawArguments:a});return"missing-gh"===e.status?(t.setFeed(t=>[...t,lg(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=$O(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:a}),n=e?.message;n&&t.setFeed(e=>[...e,lg(n)]),e?.prompt&&await submitAutomatedSlashTurn({turn:buildAutomatedSlashTurn({commandName:c,rawArguments:a,fullPrompt:e.prompt}),ctx:t})}catch(e){t.setFeed(t=>[...t,gg(`Mod command /${c} failed: ${e instanceof Error?e.message:String(e)}`)])}return{status:"handled"}}const d=await resolveCustomSlashTurn({runtime:createNodeRuntime(),commandName:s,rawArguments:a,positionalArgs:i});if(d)return await submitAutomatedSlashTurn({turn:d,ctx:t}),{status:"handled"};return await handleSkillCommand({commandName:s,command:e,rawArguments:a,positionalArgs:i,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,lg(s.message)]),{status:"handled"}):"load-error"===s.status?(o.setFeed(e=>[...e,gg(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:a,permissionState:i,terminalTitleState:l,isSubmittingRef:c,executeBash:d,setInput:u}){const m=ct(()=>({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:i.setPermissionMode,permissionModeRef:i.permissionModeRef,clearSessionPermissions:i.clearSessionPermissions,setShouldExit:a.setShouldExit,setInput:u,isSubmittingRef:c,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,executeBash:d,setRenamedTerminalTitle:l.setRenamedTerminalTitle}),[e,t,n,r,o,s,a,i,l,c,d,u]),p=it(m);return p.current=m,{commandCtx:m,onCommand:dt((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"),Ht(),Qx();var y_=Ko,S_=qo;function useCreditWarning({interactionTokens:e,currentModel:t}){const[n,r]=at(null),o=it(null),s=it(null),a=it(null),i=dt(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),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{r(null),a.current=null},y_)}catch{}},[]);return lt(()=>{if(0!==e&&!isLocalOnly()&&!isByok({model:t}))return s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{i(),s.current=null},S_),()=>{s.current&&clearTimeout(s.current)}},[e,t,i]),lt(()=>()=>{a.current&&clearTimeout(a.current),s.current&&clearTimeout(s.current)},[]),{creditWarning:n}}function useCronWakeup({onSubmit:e}){const t=it(e);lt(()=>{t.current=e},[e]),lt(()=>{const e=subscribeCronFire(e=>{t.current(buildCronWakeupSubmission(e))});return()=>{e()}},[])}function useExit(){const[e,t]=at(!1),[n,r]=at(null),o=it(null),s=it(0),a=it(null),i=dt(()=>{o.current=null,r(null),a.current&&(clearTimeout(a.current),a.current=null)},[]);return{shouldExit:e,setShouldExit:t,pendingExitKey:n,setPendingExitKey:r,pendingExitKeyRef:o,lastExitKeyTimeRef:s,exitConfirmationTimeoutRef:a,resetPendingExitKey:i}}__name(useCreditWarning,"useCreditWarning"),Ht(),Qx(),__name(useCronWakeup,"useCronWakeup"),Ht(),__name(useExit,"useExit"),Ht(),Qx(),Ht(),Qx();var w_="1"===process.env.CMD_TEST_INJECT_LIVE_ENTRY;function makeInjectedShellEntry(e,t,n,r={}){return{...ug("shell_command",t,{status:n}),id:e,...r}}function buildInjectedLiveEntry(){return w_?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 v_="1"===process.env.CMD_TEST_INJECT_STREAM,k_="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?Sg(t,{id:k_,status:"running"}):"tool"===e?{...ug("shell_command",t,{status:"running"}),id:k_}:"agent"===e?{...wg({name:"Task",input:t}),id:k_}:{...dg(t),id:k_,metadata:{status:"running"}}}function makeStreamFinalEntry(e,t){return"reasoning"===e?Sg(t,{id:k_}):"tool"===e||"agent"===e?{...ug("shell_command",t,{}),id:k_,output:"done"}:{...dg(t),id:k_}}function maybeStartInjectedStream(e){if(!v_)return;const{setFeed:t,setLiveEntries:n,setIsCmdCodeBusy:r}=e,o=streamRole(),s=buildStreamFrames(buildStreamContent(streamContentKind())),a=streamTickMs();r(!0);const i=createBlockCommittingRouter({setFeed:t,setLiveEntries:n});i(makeStreamRunningEntry(o,s[0]??""));let l=0;const c=setInterval(()=>{if(l+=1,l<s.length)return void i(makeStreamRunningEntry(o,s[l]??""));clearInterval(c);const e=s[s.length-1]??"";i(makeStreamFinalEntry(o,e)),r(!1)},a);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 C_="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 b_=(()=>{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(!C_)return;const t=createBlockCommittingRouter({setFeed:e.setFeed,setLiveEntries:e.setLiveEntries});let n=0;const r=setInterval(()=>{const e=b_[n];e?(t({...ug("todo_write",Ag("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 E_=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(E_)||E_<=0)return;const{setFeed:t}=e;let n=0;const r=setInterval(()=>{const e=n===E_-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=dt(e=>{t(t=>applyFeedRetention("function"==typeof e?e(t):e))},[]);lt(()=>{trimStaticBuffer()},[e]);const[r,o]=at(()=>{const e=buildInjectedLiveEntry();return e?[e]:[]}),[s,a]=at([]),[i,l]=at(w_),c=it([]),d=dt(e=>{const t="function"==typeof e?e(c.current):e;c.current=t,a(t)},[]);return lt(()=>maybeStartInjectedTurns({setFeed:n}),[n]),lt(()=>maybeStartInjectedStream({setFeed:n,setLiveEntries:o,setIsCmdCodeBusy:l}),[]),lt(()=>maybeStartInjectedTodos({setFeed:n,setLiveEntries:o}),[]),{feed:e,setFeed:n,liveEntries:r,setLiveEntries:o,queuedMessages:s,setQueuedMessages:d,isCmdCodeBusy:i,setIsCmdCodeBusy:l,queuedMessagesRef:c}}function useKeyboard({showTasteConfig:e,showSkillsConfig:t,showSettingsConfig:n,showProviderSelector:r,showModelSelector:o,showEffortSelector:s,showMemorySelector:a,showMcpManager:i,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:O,setRetryAttempt:L,setStatus:D,pendingExitKey:N,setPendingExitKey:$,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(()=>{interruptActiveTurn(),clearCommandGoalIfActive(z);const e=P.length>0;if(O(!1),L(null),R([]),D(jf),!e){const e=J(Uf);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");tt((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(N&&j());if(e||t||n||r||o||s||a||i||g||l||c||d||u||m||p)return void(N&&j());if(""===P||M.ctrl&&"c"===P){if(T)return void Q();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",$("ctrl-c"),U.current&&clearTimeout(U.current),void(U.current=setTimeout(()=>{_.current=null,$(null),U.current=null},2e3)))}if(keybindingMatches(I,"app.tools.expand",P,M)){if(H?.params.planContent)return;return cA(),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 cA(),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 cA(),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&&Q()}})}function useHandlers({resume:e,feedState:t,onboarding:n,uiOverlays:r,exitState:o,pendingOps:s,permissionState:a,statusState:i,authState:l,sessionId:c,loadTasteStatus:d,loadCurrentProvider:u,setInput:m}){const p=dt(()=>{a.setPermissionMode(e=>{const t=cyclePermissionMode({current:e,dangerouslySkipPermissions:a.dangerouslySkipPermissions}),n=resolvePendingPromptOnModeChange(t,{pendingIsRisky:void 0!==s.pendingPermission?.params?.risk});return n&&s.pendingPermission&&("approve"===n&&a.respondToPrompt(GE),s.pendingPermission.resolve("approve"===n),s.setPendingPermission(null)),$O(c)?.setPermissionMode({mode:t}),t})},[a.setPermissionMode,a.respondToPrompt,a.dangerouslySkipPermissions,s.pendingPermission,s.setPendingPermission,c]),g=dt(()=>{a.setPermissionMode(e=>{const t="bypass"===e?e:"auto-accept";return $O(c)?.setPermissionMode({mode:t}),t})},[a.setPermissionMode,c]),h=dt(()=>{const e=!t.isCmdCodeBusy&&!s.pendingPermission&&!s.pendingQuestion,n=($O(c)?.listCheckpoints().length??0)>0;e&&n&&r.setShowRewindSelector(!0)},[t.isCmdCodeBusy,s.pendingPermission,s.pendingQuestion,r.setShowRewindSelector,c]),f=dt(t=>{n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),t?.skipped&&r.setShowTasteSkipBanner(!0),e&&r.setShowSessionSelector(!0)},[e,n,r]),y=dt(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=dt(()=>{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:i.setRetryAttempt,setStatus:i.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:a.respondToPrompt,createErrorEntry:gg}),{handleToggleAutoAccept:p,handleEnableAutoAccept:g,handleDoubleEscapeEmpty:h,handleTasteOnboardingComplete:f,handleTrust:y,handleNoTrust:S}}__name(testTurnChars,"testTurnChars"),__name(testTurnTickMs,"testTurnTickMs"),__name(makeInjectedTurnEntry,"makeInjectedTurnEntry"),__name(maybeStartInjectedTurns,"maybeStartInjectedTurns"),__name(useFeed,"useFeed"),Ht(),Qx(),Ht(),Qx(),__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Ht(),Qx(),Ht(),Qx();var T_,P_=[],M_=[];function setModPathsOverride(e){P_=e}function setModOptionsOverride(e){M_=e}function loadCommandModHost(e={}){return T_||(T_=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:P_,builtins:commandBuiltinMods()});for(const e of M_){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 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(setModPathsOverride,"setModPathsOverride"),__name(setModOptionsOverride,"setModOptionsOverride"),__name(loadCommandModHost,"loadCommandModHost"),__name(buildHost,"buildHost"),Ht(),__name(resolveExternalModelChange,"resolveExternalModelChange"),Ht(),__name(raceAnswerAgainstAbort,"raceAnswerAgainstAbort"),Ht();var x_={},I_={};function setStartupSessionOptions(e){x_=void 0===e.persist?{}:{persist:e.persist},I_={...e.sessionFilePath?{sessionFilePath:e.sessionFilePath}:{},...e.name?{name:e.name}:{}}}function getStickyStartupSessionOptions(){return x_}function consumeStartupSessionOverrides(){const e=I_;return I_={},e}function buildInteraction({permissionsService:e,permissionModeRef:t,setPendingQuestion:n,setStatus:r}){return{confirmTool:__name(async({toolName:n,input:r,description:o,risk:s,explain:a,signal:i})=>{if(!e)return"allow";if(i?.aborted)return"deny";const l=__name(e=>raceAnswerAgainstAbort(e.then(e=>e.allowed?"allow":"deny"),i),"withInterrupt"),c=buildToolPermissionRequest({toolName:n,input:r,description:o,...void 0!==s?{risk:s}:{},...void 0!==a?{explain:a}:{}});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:a,setPermissionMode:i,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=it(f);v.current=f;const k=it(null),C=it(!1),b=it(w);b.current=w;const E=dt(()=>{hardResetForResize(),S?.(e=>e+1)},[S]),T=dt(e=>{v.current=e,y?.(e),E()},[E,y]);lt(()=>{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=it(null),R=__name(()=>{A.current?.(),A.current=null},"releaseRebuildBarrier");lt(()=>onHarnessSessionRebuild(t=>{if(t===e)return new Promise(e=>{A.current?.(),A.current=e,I(e=>e+1)})}),[e]);const O=it(a.current),L=it(null);return lt(()=>{if(!o||n)return void R();const t=__name(()=>Boolean(l)||a.current!==O.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=ig(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}]}:{input:t}}))},"drainQueuedMessages"),P=await loadCommandModHost(),x=await NO({sessionId:e,baseUrl:getApiBaseUrl(),...t()?{permissionMode:a.current}:{},dangerouslySkipPermissions:c,drainQueuedMessages:w,peekQueuedMessageCount:__name(()=>p?.current?.length??0,"peekQueuedMessageCount"),interaction:buildInteraction({permissionsService:s,permissionModeRef:a,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()!==a.current&&(t()?x.setPermissionMode({mode:a.current}):(a.current=x.getPermissionMode(),i?.(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,lg(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 a.current=e.mode,void i?.(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("notice"!==e.type||!m)return;const t=tasteNoticeToFeedEntry(e);t&&m(e=>[...e,t])}),M(!0),L.current!==e&&(L.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,lg(n.join("\n"))])}).catch(()=>{}))})(),()=>{S=!0,f?.(),y?.()}},[e,t,n,o,s,a,i,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:a,skipOnboarding:i,sessionId:l,sessionTitleHolder:c}){lt(()=>{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(),FO()])}catch{}try{e()}catch{process.exit(0)}})())},[n.shouldExit,e]),lt(()=>()=>{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)},[]),lt(()=>{(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]),lt(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(Tg())},Dg);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),lt(()=>{i||triggerTasteOnboarding({projectTrusted:s.projectTrusted,onboardingComplete:s.onboardingComplete,isOnboardingMode:s.showTasteOnboarding,tasteOnboardingCheckedRef:s.tasteOnboardingCheckedRef,setIsOnboardingMode:s.setShowTasteOnboarding})},[s.projectTrusted,s.onboardingComplete,s.showTasteOnboarding,i]),lt(()=>{if(s.showTasteOnboarding&&!s.tasteOnboardingEntryId){const e=hg();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(ko),t(!1)}}function handleCompactModeCancel({setShowCompactModeSelector:e}){e(!1)}__name(setStartupSessionOptions,"setStartupSessionOptions"),__name(getStickyStartupSessionOptions,"getStickyStartupSessionOptions"),__name(consumeStartupSessionOverrides,"consumeStartupSessionOverrides"),__name(buildInteraction,"buildInteraction"),__name(useHarness,"useHarness"),Ht(),Qx(),__name(useLifecycle,"useLifecycle"),Ht(),Qx(),Ht(),Qx(),__name(handleCompactModeSelect,"handleCompactModeSelect"),__name(handleCompactModeCancel,"handleCompactModeCancel");var A_=__name(e=>{},"noopBool");function useMainActionCallbacks({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,setInput:s}){const a=it({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,setInput:s});a.current={feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,setInput:s};const i=dt(e=>{const{feedState:t,sessionState:n,statusState:r,uiOverlays:o,authState:s}=a.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=dt(({messageId:e,mode:t})=>{const{feedState:n,sessionState:r,statusState:o,uiOverlays:s,setInput:i}=a.current;handleRewindSelect({messageId:e,mode:t,sessionId:r.sessionId,setFeed:n.setFeed,setStatus:o.setStatus,setShowRewindSelector:s.setShowRewindSelector,setStaticKey:s.setStaticKey,setInput:i})},[]),c=dt(()=>{handleRewindCancel({setShowRewindSelector:a.current.uiOverlays.setShowRewindSelector})},[]),d=dt(e=>{const{feedState:t,sessionState:n,uiOverlays:r,setInput:o}=a.current;return handleTreeSelect({...e,sessionId:n.sessionId,setFeed:t.setFeed,setShowTreeSelector:r.setShowTreeSelector,setStaticKey:r.setStaticKey,setInput:o})},[]),u=dt(()=>{handleTreeCancel({setShowTreeSelector:a.current.uiOverlays.setShowTreeSelector})},[]),m=dt(e=>{const{feedState:t,sessionState:n}=a.current;handleTreeLabel({...e,sessionId:n.sessionId,setFeed:t.setFeed})},[]),p=dt(()=>{handleTreeAbortSummary({sessionId:a.current.sessionState.sessionId})},[]),g=dt((e,t)=>{const{feedState:n,statusState:r,uiOverlays:o}=a.current;handleLoginComplete({success:e,message:t,setShowLoginOverlay:o.setShowLoginOverlay,setFeed:n.setFeed,setStatus:r.setStatus})},[]),h=dt(()=>{const{feedState:e,statusState:t,uiOverlays:n}=a.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),f=__name(e=>{const t=a.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=dt(e=>{const{authState:t,sessionState:n,statusState:r,uiOverlays:o}=a.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=a.current.sessionState.sessionId;t&&await saveCommandSessionMeta({sessionId:t,meta:{model:e}}),a.current.authState.setCurrentModel(e),a.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=a.current.authState.currentProvider??await getConfiguredProvider()??ro.COMMAND;return e===ro.COMMAND?cr:defaultModelForLane({activeLane:e})??cr},"resolveOrphanFallback"),w=dt(()=>{handleProviderCancel({setShowProviderSelector:a.current.uiOverlays.setShowProviderSelector})},[]),v=dt((e,t)=>{const{authState:n,sessionState:r,statusState:o,uiOverlays:s,feedState:i}=a.current;handleModelSelect({modelId:e,provider:t,setCurrentModel:n.setCurrentModel,setShowModelSelector:s.setShowModelSelector,setStatus:o.setStatus,modelNotificationTimer:n.modelNotificationTimer,setShowModelNotification:A_,setCurrentProvider:n.setCurrentProvider,setStaticKey:s.setStaticKey,sessionId:r.sessionId,setFeed:i.setFeed,setContextUsage:o.setContextUsage,setModelNotice:s.setModelNotice})},[]),k=dt(()=>{handleModelCancel({setShowModelSelector:a.current.uiOverlays.setShowModelSelector})},[]),C=dt(e=>{const{statusState:t,uiOverlays:n}=a.current;handleCompactModeSelect({mode:e,setShowCompactModeSelector:n.setShowCompactModeSelector,setStatus:t.setStatus})},[]),b=dt(()=>{handleCompactModeCancel({setShowCompactModeSelector:a.current.uiOverlays.setShowCompactModeSelector})},[]),E=dt(e=>{const{statusState:t,uiOverlays:n}=a.current;handleThemeSelect({theme:e,setShowThemeSelector:n.setShowThemeSelector,setStatus:t.setStatus,setStaticKey:n.setStaticKey})},[]),T=dt(()=>{handleThemeCancel({setShowThemeSelector:a.current.uiOverlays.setShowThemeSelector})},[]),P=dt(()=>{const{authState:e,sessionState:t,statusState:n,uiOverlays:r}=a.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=dt(()=>{handleAuthCancel({setAuthComponentInfo:a.current.authState.setAuthComponentInfo})},[]);return{onSelectSession:i,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=it(e);lt(()=>{t.current=e},[e]),lt(()=>{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),[a,i]=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:a,setShowTasteOnboarding:i,onboardingComplete:l,setOnboardingComplete:c,tasteOnboardingEntryId:d,setTasteOnboardingEntryId:u,autoLearnTaste:m,setAutoLearnTaste:p,tasteOnboardingCheckedRef:it(!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"),Ht(),Qx(),__name(useMonitorOutputWakeup,"useMonitorOutputWakeup"),Ht(),__name(useOnboarding,"useOnboarding"),Ht(),__name(usePendingOps,"usePendingOps"),Ht(),Qx(),Ht(),Qx(),__name(resolvePermissionSettingsPath,"resolvePermissionSettingsPath");var R_=__name((e={})=>{const{projectRoot:t,local:n=!1,onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:a}=e,i=t||process.cwd(),l=it({onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:a}),[c,d]=at(null),u=it(null),[m,p]=at(null),[g,h]=at(!1);return lt(()=>{l.current={onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:a}},[r,o,s,a]),lt(()=>{const e=resolvePermissionSettingsPath({projectRoot:i,local:n}),t=createPermissionsService(i,{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,i]),{requestPermission:dt(async e=>{if(!c)return{allowed:!0};const t=await c.requestPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),requestShellPermission:dt(async e=>{if(!c)return{allowed:!0};const t=await c.requestShellPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),requestGenericPermission:dt(async e=>{if(!c)return{allowed:!0};const t=await c.requestGenericPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),respondToPrompt:dt(e=>{u.current?.respond(e)&&(p(null),h(!1))},[]),clearSessionPermissions:dt(()=>{c?.clearSessionPermissions()},[c]),clearProjectPermissions:dt(()=>{c?.clearProjectPermissions()},[c]),setAutoApprove:dt((e,t)=>{c?.setAutoApprove(e,t)},[c]),setEnabled:dt(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,a]=at(()=>e||(n?"bypass":"default")),i=it(s);lt(()=>{i.current=s},[s]);const{requestShellPermission:l,service:c,respondToPrompt:d,clearSessionPermissions:u,setEnabled:m}=R_({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 lt(()=>{c&&applyAutoAcceptMode({enabled:s,service:c})},[s,c]),{permissionMode:s,setPermissionMode:a,permissionModeRef:i,permissionsService:c,respondToPrompt:d,clearSessionPermissions:u,dangerouslySkipPermissions:n}}function useQueuedMessageFlush({isCmdCodeBusy:e,queuedMessages:t,queuedMessagesRef:n,setQueuedMessages:r,isSubmittingRef:o,onSubmit:s}){const a=it(s);lt(()=>{a.current=s},[s]);const i=t.length>0;lt(()=>{if(!i||e)return;const t=setInterval(()=>{if(o.current)return;const e=n.current[0];e&&(r(e=>e.slice(1)),a.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.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)},[i,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:it(null)}}__name(usePermissionMode,"usePermissionMode"),Ht(),__name(useQueuedMessageFlush,"useQueuedMessageFlush"),Ht(),__name(useSession,"useSession"),Ht(),Qx(),Ht(),Qx();var O_=createOSC8Link("https://commandcode.ai/docs/hooks","Docs ↗",!1);function buildHookStartupEntries(e){const t=buildHookStartupMessages(e).map(e=>({...e}));if(0===t.length)return[];const n=t[t.length-1];return n.message=`${n.message} ${O_}`,t.map(e=>e.isHookWarning?lg(e.message,{isHookWarning:!0}):lg(e.message))}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:a,sessionState:i,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=dt(async()=>{try{const e=await isTasteLearningEnabled();l.setTasteLearningOn(e),e&&await initTasteDir({runtime:createNodeRuntime()})}catch{}},[l.setTasteLearningOn]),k=dt(async()=>{const e=await getConfiguredProvider();c.setCurrentProvider(e)},[c.setCurrentProvider]),C=dt(()=>{},[]),b=dt(e=>{handleSelectSession({selectedSessionId:e,sessionLoadIdRef:i.sessionLoadIdRef,setFeed:a.setFeed,setLiveEntries:a.setLiveEntries,setSessionId:i.setSessionId,setShowSessionSelector:u.setShowSessionSelector,setSessionLoaded:i.setSessionLoaded,setStaticKey:u.setStaticKey,setShareInfo:l.setShareInfo,setCurrentModel:c.setCurrentModel})},[i,a,u,l,c.setCurrentModel]),E=dt(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]);lt(()=>{(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=it(!1);lt(()=>{T.current||d.projectTrusted&&0!==getCommandZdrPausedFeatures().length&&(T.current=!0,u.setShowZdrNotice(!0))},[d.projectTrusted,u.setShowZdrNotice]);const P=it(null);lt(()=>{d.projectTrusted&&c.currentModel!==P.current&&(P.current=c.currentModel,u.setModelNotice(getModelNotice(c.currentModel)??null))},[d.projectTrusted,c.currentModel,u.setModelNotice]);const M=it(null);lt(()=>{if(!p||!d.projectTrusted)return;const e=i.sessionId;if(M.current===e)return;const t=$O(e);if(!t)return;M.current=e;const n=buildHookStartupEntries(t.hookSettingsWarnings);0!==n.length&&a.setFeed(e=>[...e,...n])},[p,d.projectTrusted,i.sessionId,a.setFeed]),lt(()=>{if(!d.projectTrusted)return;const e=createCommandHistoryManager();return f.current=e,e.init(),()=>{e.cleanup()}},[d.projectTrusted,f]),lt(()=>{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]),lt(()=>{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:a.feed,setFeed:a.setFeed,setLiveEntries:a.setLiveEntries,isCmdCodeBusy:a.isCmdCodeBusy,setIsCmdCodeBusy:a.setIsCmdCodeBusy,setQueuedMessages:a.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:i.sessionId,isSubmittingRef:g,setInput:S,setStaticKey:u.setStaticKey,executeBash:y})},"submitAsUserMessage")}))},[o,d.projectTrusted,d.checkingProject,u.showSessionSelector,p,i.sessionId,c.currentProvider,w]);const x=it(null);x.current={feed:a.feed,setFeed:a.setFeed,setLiveEntries:a.setLiveEntries,isCmdCodeBusy:a.isCmdCodeBusy,setIsCmdCodeBusy:a.setIsCmdCodeBusy,setQueuedMessages:a.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:i.sessionId,isSubmittingRef:g,setInput:S,setStaticKey:u.setStaticKey,executeBash:y,role:"",input:""};const I=dt(async({role:e,input:t,images:n,imageTokenPaths:r,ideContext:o,ideHint:s,displayMessage:a,isAutomated:i,isMeta:l,hiddenMessages:c})=>{u.setShowTasteSkipBanner(!1),u.setShowZdrNotice(!1),u.setModelNotice(null),await handleSubmit({...x.current,role:e,input:t,images:n,imageTokenPaths:r,ideContext:o,ideHint:s,displayMessage:a,isAutomated:i,isMeta:l,hiddenMessages:c})},[u.setShowTasteSkipBanner,u.setShowZdrNotice,u.setModelNotice]);return{loadTasteStatus:v,loadCurrentProvider:k,initializeMcpInBackground:C,onSubmit:I}}function useStatus(e){const[t,n]=at("Ready..."),r=it(!1),[o,s]=at(""),a=it(null),[i,l]=at(null),c=it(i),[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);lt(()=>{c.current=i},[i]),lt(()=>{if(!E)return;const e=setTimeout(()=>{T(null)},3e4);return()=>clearTimeout(e)},[E]);const P=__name(e=>{a.current&&clearTimeout(a.current),s(e),a.current=setTimeout(()=>{s(""),a.current=null},5e3)},"showHintMessage");return{status:t,setStatus:n,pinnedStatusRef:r,hintMessage:o,setHintMessage:s,hintTimerRef:a,shareInfo:i,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}){const n=it(process.cwd()),r=it(e),o=it(null),s=dt(e=>{o.current=e,setTerminalTitle(formatSessionTabTitle({sessionTitle:e,projectDir:n.current}))},[]),a=dt(e=>{(async()=>{const t=await loadCommandSessionMeta({sessionId:e});r.current===e&&t?.title&&t.title!==o.current&&s(t.title)})()},[s]);lt(()=>{r.current=e,s(null),a(e)},[e,s,a]);const i=it(t);lt(()=>{const n=i.current;i.current=t,t!==n&&reassertTerminalTitle(),!t&&n&&(o.current||a(e))},[t,e,a]),lt(()=>{if(!process.stderr.isTTY)return;const e=setInterval(reassertTerminalTitle,5e3);return()=>{clearInterval(e)}},[]);const l=dt(e=>{s(e)},[s]);return{setRenamedTerminalTitle:l,applyGeneratedTitle:l}}function useUiOverlays(){const[e,t]=at(!1),[n,r]=at(!1),[o,s]=at(!1),[a,i]=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),[O,L]=at(!1),[D,N]=at(!1),[$,_]=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),[ae,ie]=at(null),[le,ce]=at("off"),de="off"!==le,ue=dt(e=>{hardResetForResize(),te(e=>e+1),e(!1)},[]);return{showFileList:e,setShowFileList:t,showAgentsConfig:n,setShowAgentsConfig:r,showTasteConfig:o,setShowTasteConfig:s,showSkillsConfig:a,setShowSkillsConfig:i,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:O,setShowLoginOverlay:L,showCompactModeSelector:D,setShowCompactModeSelector:N,showContextView:$,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:ae,setModelNotice:ie,transcriptMode:le,setTranscriptMode:ce,expandedToolOutput:de,showDesignGuide:J,setShowDesignGuide:Q,pendingDesignSuggestion:X,setPendingDesignSuggestion:Z}}__name(buildHookStartupEntries,"buildHookStartupEntries"),__name(submitInitialPrompt,"submitInitialPrompt"),__name(useStartup,"useStartup"),Ht(),__name(useStatus,"useStatus"),Ht(),Qx(),__name(useTerminalTitle,"useTerminalTitle"),Ht(),__name(useUiOverlays,"useUiOverlays");var L_=__name(({resume:e=!1,resumeSessionId:t,continue:n=!1,trust:r=!1,dangerouslySkipPermissions:o=!1,updateStatus:s,updateFailedInfo:a,initialPrompt:i,skipOnboarding:l=!1,initialPermissionMode:c,local:d=!1,sessionTitleHolder:u})=>{const{exit:m}=nt(),{stdout:p}=Ze();usePasteRouter(),lt(()=>{isLocalOnly()||prefetchBillingContext()},[]);const[g,h]=at(""),[f,y]=at(""),S=it(!1),w=it(!1),v=it(null),k=useUiOverlays(),C=useFeed(),b=useSession(),E=useStatus(s),T=useAuth(),P=usePendingOps(),M=useOnboarding(),x=useExit(),{executeBash:I,executionState:A}=t_(),R=usePermissionMode({initialPermissionMode:c,local:d,dangerouslySkipPermissions:o,setPendingPermission:P.setPendingPermission,setStatus:E.setStatus}),O=useTerminalTitle({sessionId:b.sessionId,isCmdCodeBusy:C.isCmdCodeBusy}),{ready:L}=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:D}=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:D}),lt(()=>{k.planBreadcrumbPending&&!C.isCmdCodeBusy&&(k.setPlanBreadcrumbPending(!1),C.setFeed(e=>[...e,pg("Plan saved — run /plans to review, annotate, or execute it anytime.")]))},[k.planBreadcrumbPending,k.setPlanBreadcrumbPending,C.isCmdCodeBusy,C.setFeed]);const{loadTasteStatus:N,loadCurrentProvider:$,onSubmit:_}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:i,stdout:p,feedState:C,sessionState:b,statusState:E,authState:T,onboarding:M,uiOverlays:k,permissionState:R,harnessReady:L,isSubmittingRef:S,initialPromptSubmittedRef:w,historyManagerRef:v,executeBash:I,setInput:h,onCommand:D});useMonitorOutputWakeup({onSubmit:_}),useCronWakeup({onSubmit:_}),useQueuedMessageFlush({isCmdCodeBusy:C.isCmdCodeBusy,queuedMessages:C.queuedMessages,queuedMessagesRef:C.queuedMessagesRef,setQueuedMessages:C.setQueuedMessages,isSubmittingRef:S,onSubmit:_}),useLifecycle({exit:m,feedState:C,exitState:x,statusState:E,authState:T,onboarding:M,uiOverlays:k,skipOnboarding:l,sessionId:b.sessionId,sessionTitleHolder:u});const{handleToggleAutoAccept:F,handleEnableAutoAccept:U,handleDoubleEscapeEmpty:j,handleTasteOnboardingComplete:B,handleTrust:W,handleNoTrust:H}=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")}),G=useMainActionCallbacks({feedState:C,sessionState:b,statusState:E,authState:T,uiOverlays:k,setInput:h}),{creditWarning:V}=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:G,onSubmit:_,onCommand:D,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,updateFailedInfo:a,creditWarning:V,handleTrust:W,handleNoTrust:H,handleToggleAutoAccept:F,handleEnableAutoAccept:U,handleDoubleEscapeEmpty:j,handleTasteOnboardingComplete:B,loadTasteStatus:N})},"InteractiveCLI");function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:a,pendingOps:i,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(a.shouldExit)return null;if(s.checkingProject)return null;if(s.showTrustPrompt)return ot.createElement(Z$,{staticKey:o.staticKey,onTrust:v,onExit:k});if(o.showSessionSelector)return ot.createElement(Q$,{onSelectSession:u.onSelectSession,onClose:()=>o.closeFullScreenOverlay(o.setShowSessionSelector),currentSessionId:t.sessionId});if(!s.projectTrusted)return null;const M=o.pendingDesignSuggestion?ot.createElement(fD,{suggestion:o.pendingDesignSuggestion,onSelect:e=>{p(`/design ${e}`)},onClose:()=>o.setPendingDesignSuggestion(null)}):null,x=i.pendingQuestion?.params.exitPlanMode?i.pendingQuestion:null,I=i.pendingQuestion&&!x?ot.createElement(QuestionView,{pendingQuestion:i.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,dangerouslySkipPermissions:l.dangerouslySkipPermissions,setPendingQuestion:i.setPendingQuestion,setStatus:n.setStatus,setStaticKey:o.setStaticKey}):null,A=i.pendingPermission?ot.createElement(aD,{pendingPermission:i.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:i.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]}]}),i.setPendingQuestion(null),hardResetForResize(),o.setStaticKey(e=>e+1)},"resolveApproval");return ot.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 ot.createElement(TasteConfigView,{staticKey:o.staticKey,onClose:()=>R(o.setShowTasteConfig),loadTasteStatus:P});if(o.showSkillsConfig)return ot.createElement(SkillsConfigView,{staticKey:o.staticKey,onClose:()=>R(o.setShowSkillsConfig)});if(o.showSettingsConfig)return ot.createElement(SettingsConfigView,{staticKey:o.staticKey,onClose:()=>R(o.setShowSettingsConfig),loadTasteStatus:P});if(o.showUsageOverlay)return ot.createElement(UsageView,{staticKey:o.staticKey,onClose:()=>R(o.setShowUsageOverlay)});if(o.showContextView)return ot.createElement(ContextConfigView,{staticKey:o.staticKey,sessionId:t.sessionId,onClose:()=>R(o.setShowContextView),setInput:h});if(o.showStatusView)return ot.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 ot.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"),$O(t.sessionId)?.setPermissionMode({mode:"auto-accept"})),e(n)}})}return ot.createElement(k$,{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:a.pendingExitKey,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,tasteLearningOn:n.tasteLearningOn,historyManagerRef:c,executionState:d,sessionId:t.sessionId,onSubmit:m,onCommand:p,onToggleAutoAccept:C,onResetPendingExitKey:a.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"),Qx(),Ht();var D_=__name(({worktreePath:e,warning:t,onChoice:n})=>{const[r,o]=at(1);return tt((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)}),ot.createElement(ZA,{title:"Exiting worktree session",subtitle:t,hint:"Enter to confirm · Esc to cancel"},ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,null,ot.createElement(Qe,{color:1===r?nI.CYAN:nI.GRAY},1===r?pt.pointer:" "," 1. Keep worktree"," ",ot.createElement(Qe,{color:nI.GRAY},"Stays at ",tildeHome(e)))),ot.createElement(Je,null,ot.createElement(Qe,{color:2===r?nI.CYAN:nI.GRAY},2===r?pt.pointer:" "," 2. Remove worktree"," ",ot.createElement(Qe,{color:nI.GRAY},"All changes and commits will be lost.")))))},"WorktreeExitPrompt");function promptWorktreeExit(e){return new Promise(t=>{const{unmount:n}=et(ot.createElement(D_,{worktreePath:e.worktreePath,warning:e.warning,onChoice:e=>{n(),t(e)}}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})})}function canRespawn(){if(process.versions.bun)return!1;const e=process.argv[1];return"string"==typeof e&&e.length>0}async function writeReloadHandoff(e){const t=process.env[IT];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(){try{process.stdin.isTTY&&process.stdin.setRawMode(!1)}catch{}try{process.stdout.write("[?25h")}catch{}}__name(promptWorktreeExit,"promptWorktreeExit"),Ht(),Qx(),__name(canRespawn,"canRespawn"),__name(writeReloadHandoff,"writeReloadHandoff"),__name(consumeReloadHandoff,"consumeReloadHandoff"),__name(restoreTerminal,"restoreTerminal");var N_=gt.hex(nI.DIM);function printReloadFallbackHint(){process.stdout.write(N_("Couldn't restart automatically in this build — exiting instead.\n"))}async function shutdownWrapperRuntime(){try{await Promise.allSettled([disconnectAllMcpServers(),FO()])}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();const s=y(process.execPath,[process.argv[1],...t],{stdio:"inherit",env:{...process.env,[IT]:r,[AT]:String(process.pid)}});let a,i;try{[a,i]=await new Promise((e,t)=>{s.once("exit",(t,n)=>e([t,n])),s.once("error",t)})}catch(e){restoreTerminal(),process.stderr.write(N_(`\nCouldn't relaunch Command Code: ${e.message}\n`)),await z.rm(n,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}if(a!==xT){if(restoreTerminal(),await z.rm(n,{recursive:!0,force:!0}).catch(()=>{}),i){const e=B.constants.signals[i];process.exit(e?128+e:1)}process.exit(a??1)}else o=await consumeReloadHandoff(r)??o}}async function handlePendingReload(e){canRespawn()?(isWrappedChild()&&(await writeReloadHandoff(e),process.exit(xT)),await runRelaunchLoop(e)):printReloadFallbackHint()}__name(printReloadFallbackHint,"printReloadFallbackHint"),__name(shutdownWrapperRuntime,"shutdownWrapperRuntime"),__name(runRelaunchLoop,"runRelaunchLoop"),__name(handlePendingReload,"handlePendingReload");var $_=__name(e=>e.replace(/\x1B\[[0-9;]*[A-Za-z]/g,"").replace(/[\x00-\x1F\x7F]/g," ").trim(),"sanitizeTitleForOutput"),__=gt.hex(nI.DIM),F_=__name(()=>{const e=getInvokedCommandName();return"win32"===process.platform&&"cmd"===e?"cmdc":e},"getResumeCommandName"),U_=__name((e,t)=>{const n=F_(),r=we([e]),o=t?`cd ${we([t])} && ${n} --resume ${r}`:`${n} --resume ${r}`;return`${__("Resume this session with:")}\n${__(o)}\n`},"formatResumeHint"),j_=__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"),B_=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),W_=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),H_=__name(e=>e.permissionMode?e.permissionMode:e.plan?"plan":void 0,"resolveInitialPermissionMode"),G_=__name(({options:e,resumeSessionId:t,sessionTitleHolder:n})=>{const r=H_(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"),V_=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),z_=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),K_=__name(()=>{z_()},"initializeTerminal"),q_=__name(()=>{process.on("SIGINT",()=>{})},"swallowSigintDuringShutdown"),Y_=__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"),J_=__name(async(e={})=>{const t=j_(process.stdin.isTTY);let n,o;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),K_(),"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(),a=await listAllSessionsV3({runtime:t}),i=getProjectSessionDir({env:t.env(),cwd:t.cwd()}),l=resolveSessionRefFlag({ref:e.session,isExistingFile:__name(e=>I(e),"isExistingFile"),listSessionIds:__name(()=>a.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(a.find(e=>e.id===l.sessionId)?.path??"");n=c(d,".jsonl"),r(d)!==i&&(o=d)}if(B_(e)&&!n){const e=await isCommandProjectSessionInitialized(),t=e?await listCommandSessions():[],n=W_({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}if(e.forkSession){const t=await Y_({resumeSessionId:n,useContinue:Boolean(e.continue)});t&&(n=t,e.continue=!1)}await applyStartupTheme(),startEarlyInputCapture(),setStartupSessionOptions({...!1===e.session?{persist:!1}:{},...o?{sessionFilePath:o}:{},...e.name?{name:e.name}:{}});const a={},i=G_({options:e,resumeSessionId:n,sessionTitleHolder:a}),l=V_(),d=et(ot.createElement(L_,{...i}),l);registerInkControl({clear:d.clear,stdout:process.stdout,instance:await resolveInkInstance(process.stdout)}),await d.waitUntilExit(),clearTerminalTitle(),q_();const u=consumePendingReload();u&&await handlePendingReload(u);const m=await(a.loadTitle?.())??null,p=Boolean(m);let g;const h=getAutoCreatedWorktree();if(h){const e=worktreeHasWork(h.worktreePath,h.baseSha);let t="auto";if(e||p){const n=worktreeChangeCount(h.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:h.worktreePath,warning:r})}const n=finalizeAutoCreatedWorktree(t);if(n.worktreePath){const e=__(createOSC8Link(fileUrl(n.worktreePath),tildeHome(n.worktreePath),!1));if(n.removed){const n="auto"===t?"Removed empty worktree":"Removed worktree";process.stdout.write(`${__(n)}\n${e}\n\n`)}else if(n.kept){g=n.worktreePath;const t=n.reason&&"kept"!==n.reason?` (${n.reason})`:"";process.stdout.write(`${__(`Kept worktree${t}`)}\n${e}\n\n`)}}}const f=a.sessionId;if(f&&await commandSessionExists(f)){const e=m?$_(m):"";process.stdout.write(U_(e||f,g))}},"interactiveMode");Ht(),Qx(),Ht();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 Q_=__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)=>{M.writeFileSync(e,t)}),r=t(),o=[],s=[],a=new Map,i=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=Q_(o.length+1);return o.push(t),t},"currentTurn"),m=__name(e=>{const n=u(),r=a.get(e.toolCallId);void 0!==r&&(n.toolDurationMs+=t()-r,a.delete(e.toolCallId));const o=i.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 a.set(e.toolCallId,t()),i.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(Q_(e.turnNumber))},"onEvent"),g=__name(()=>{const e={};let n=0,a=0,i=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&&a++;i+=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:a},tokens:{input:i,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 X_=null,Z_=!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(Z_)return;Z_=!0;const e=__name(e=>{X_?.abort(),process.stderr.write(`\n${e}\n`),process.exit(Rb.INTERRUPTED)},"handleTermination");process.on("SIGINT",()=>e("Interrupted.")),process.on("SIGTERM",()=>e("Terminated.")),process.stdout.on("error",e=>{"EPIPE"===e.code&&process.exit(Rb.SUCCESS),process.stderr.write(`Error writing to stdout: ${e.message}\n`),process.exit(Rb.ERROR)})}async function printMode(e={}){trackCommand({command:"print"}),setupSignalHandlers(),X_=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:a,resumeState:i,sessionFilePath:l})=>{const c=await createHarnessSession({sessionId:t,baseUrl:getApiBaseUrl(),entrypoint:r,headless:o,maxTurns:s,mods:a,dangerouslySkipPermissions:e.dangerouslySkipPermissions,permissionMode:resolveLaunchPermissionMode(e),...n.forceEnabledTools?{forceEnabledTools:n.forceEnabledTools}:{},modHost:await loadCommandModHost({projectMods:Boolean(e.dangerouslySkipPermissions)}),resumeState:i,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)]),process.exit(o.exitCode)}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(`${pt.cross} Authentication failed. Please try again with: ${getBinaryCommand()} login`)},"onAuthFailed"),onLoginError:__name(e=>{console.error(`${pt.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:cr,groups:[...getModelGroupsInOrder(),...customModelListGroups()]})}async function printModelList(){await loadCustomProviderModels();const e=Boolean(process.stdout.isTTY)&&void 0===process.env.NO_COLOR;process.stdout.write(`${formatModelList({color:e})}\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(resolveLaunchPermissionMode,"resolveLaunchPermissionMode"),__name(getAuthKey4,"getAuthKey"),__name(readStdin,"readStdin"),__name(writeOutput,"writeOutput"),__name(setupSignalHandlers,"setupSignalHandlers"),__name(printMode,"printMode"),Ht(),Qx(),__name(ensureAuthenticated,"ensureAuthenticated"),Ht(),Qx(),__name(suggestModel,"suggestModel"),__name(formatModelList,"formatModelList"),__name(printModelList,"printModelList"),__name(resolveModelFlagOrExit,"resolveModelFlagOrExit"),Ht(),Qx();var eF=!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(),FO()])}catch{}}function handleShutdownSignal(){eF||(eF=!0,abandonPendingCommandSpan(),Promise.allSettled([disconnectMcpServers(),shutdownTelemetry()]).finally(()=>{process.exit(0)}))}async function shutdownAndExit(e=0){eF=!0,abandonPendingCommandSpan();try{await Promise.allSettled([disconnectMcpServers(),shutdownTelemetry(Fn)])}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 tF=__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)yf.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?await resolveModelFlagOrExit({model:t.model}):void 0,a=o?.modelId,i=t,l=__name(e=>{process.stderr.write(`${e.message}\n`),e.ok||process.exit(1)},"applySettingResult");for(const e of OL){const t=i[e.key];"string"==typeof t&&l(await e.apply(t,{model:a}))}const c=i.config;if(Array.isArray(c))for(const e of c)"string"==typeof e&&l(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,o?.providerId),setGoalMaxTurnsOverride(t.maxTurns);const d=parseInteractivePromptArgument(e);await tF();const u=buildInteractiveRuntimeOptions(t),m=resolveInteractiveLaunchConfig({options:t,runtimeOptions:u,initialPrompt:d});setOriginalInvocation({trust:u.trust,dangerouslySkipPermissions:u.dangerouslySkipPermissions,skipOnboarding:u.skipOnboarding,maxTurns:t.maxTurns,skillPaths:n,skillDiscovery:r}),await installKeybindingsFromConfig({runtime:getCommandConfigRuntime()}),await J_(m),await shutdownAndExit(0)}__name(interactiveModeAction,"interactiveModeAction"),Ht(),Qx(),Ht(),Qx();var nF={connected:gt.green("✔"),installed:gt.green("✔"),up_to_date:gt.green("✔"),needs_reload:gt.yellow("◌"),failed:gt.red("✖"),not_in_ide:gt.yellow("◌")};function formatSetupResult(e){const{prefix:t,ide:n,suffix:r}=getIDESetupStatusHeadline(e.status,e.ide),o=`${t}${n??""}${r}`;return["",`${nF[e.status]} ${o}`,...(e.details??[]).map(e=>gt.dim(` ${e}`)),""]}__name(formatSetupResult,"formatSetupResult"),globalThis.COMMAND_CODE_CWD=process.cwd();var rF=__name(()=>process.cwd(),"getCwd"),oF=__name(()=>process.argv.slice(2),"getArgs"),sF=__name(()=>{const e=rF(),t=oF(),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(){sF();const e=resolveCliStartupPlan({args:oF()});if(e.shouldRunIdeSetup){const e=await runIdeSetup({host:n_,moduleUrl:import.meta.url});formatSetupResult(e).forEach(e=>console.log(e)),process.exit("failed"===e.status?1:0)}e.shouldRunAutoUpdate&&runCliStartupPendingUpdates({plan:e,host:p_}),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:p_}),scheduleCliStartupIdeAutoInstall({host:n_,moduleUrl:import.meta.url})}__name(getAuthKey6,"getAuthKey"),__name(preRun,"preRun"),Ht(),Qx();var aF=Object.fromEntries(Object.entries(sv).map(([e,t])=>[t,e])),iF=new Set(KR.map(e=>e.id));function formatProviderModule(e){return iF.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=aF[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 KR){if(s.has(e.id))continue;if(!1===e.discoverable)continue;const n=aF[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=[bt.bold("Providers available for login/logout"),""];for(const r of e){const e=r.authenticated?bt.green("logged in"):bt.dim("not logged in"),o=r.installed?"":bt.dim(" (not installed, installs on first login)");n.push(bt.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: ${bt.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(bt.yellow("Provider load errors"));for(const e of t.errors)console.log(`${bt.yellow(e.id)}: ${e.error}`)}}__name(formatProviderModule,"formatProviderModule"),__name(buildProviderLoginRows,"buildProviderLoginRows"),__name(formatProviderLoginRows,"formatProviderLoginRows"),__name(providersAction,"providersAction");var lF=new je("providers").description("List providers available for login/logout").option("--json","Output providers as JSON for automation").action(providersAction);function stopAllSpinners({state:e}){e.workingSpinner&&(e.workingSpinner.stop(),e.workingSpinner=null),e.currentSpinner&&(e.currentSpinner.stop(),e.currentSpinner=null)}function renderStatusAction({action:e,state:t}){if("replayed_setup"!==e.type)return"setup_step"===e.type?(t.currentSpinner&&t.currentSpinner.succeed(),void(t.currentSpinner=Pt({stream:process.stderr,text:e.message}).start())):"running"===e.type?(t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),void(t.workingSpinner||(t.workingSpinner=Pt({stream:process.stderr}).start()))):"completed"===e.type?(t.workingSpinner&&(t.workingSpinner.succeed("Session completed"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),void(e.prUrl&&console.error(`PR: ${bt.cyan(e.prUrl)}`))):"failed"===e.type?(t.workingSpinner&&(t.workingSpinner.fail(e.message),t.workingSpinner=null),void(t.currentSpinner&&(t.currentSpinner.fail(e.message),t.currentSpinner=null))):"timed_out"===e.type?(t.workingSpinner&&(t.workingSpinner.fail("Session timed out"),t.workingSpinner=null),void(t.currentSpinner&&(t.currentSpinner.fail("Timed out"),t.currentSpinner=null))):void("cancelled"===e.type&&(stopAllSpinners({state:t}),console.error(`\n${bt.yellow("Cancelled.")}`)));e.message&&t.workingSpinner&&(t.workingSpinner.text=e.message)}function setupInputHandling({callbacks:e}){const t=__name(t=>{3!==t[0]?4===t[0]&&e.onDetach():e.onCancel()},"onStdinData"),n=process.rawListeners("SIGINT").slice();return process.removeAllListeners("SIGINT"),process.stdin.isTTY?(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",t),process.on("SIGINT",()=>{})):process.on("SIGINT",()=>e.onCancel()),()=>{process.stdin.isTTY&&(process.stdin.removeListener("data",t),process.stdin.setRawMode(!1),process.stdin.pause()),process.removeAllListeners("SIGINT");for(const e of n)process.on("SIGINT",e)}}function setupResizeForwarding({handle:e}){const t=__name(()=>{e.sendResize({cols:process.stdout.columns,rows:process.stdout.rows})},"onResize");return process.stdout.on("resize",t),()=>process.stdout.removeListener("resize",t)}async function streamSession({sessionId:e,lastEventId:t=0,isResume:n=!1}){const r={currentSpinner:null,workingSpinner:null},o=await streamSandboxSession({sessionId:e,lastEventId:t,isResume:n,getTerminalSize:__name(()=>({cols:process.stdout.columns,rows:process.stdout.rows}),"getTerminalSize"),callbacks:{onOpen:__name(({isResume:t})=>{r.currentSpinner&&(r.currentSpinner.stop(),r.currentSpinner=null),console.error(""),console.error(`${bt.yellow("[Ctrl+C]")} ${bt.dim("stop")} ${bt.yellow("[Ctrl+D]")} ${bt.dim("detach")}`),console.error(`${bt.dim("Session:")} ${bt.gray(e)}`),console.error(""),t&&(r.workingSpinner=Pt({stream:process.stderr}).start())},"onOpen"),onStatus:__name(({action:e})=>renderStatusAction({action:e,state:r}),"onStatus"),onPty:__name(({content:e})=>{r.workingSpinner&&r.workingSpinner.stop(),process.stdout.write(e),r.workingSpinner&&r.workingSpinner.start()},"onPty"),onErrorEvent:__name(({message:e})=>{r.currentSpinner&&(r.currentSpinner.fail(),r.currentSpinner=null),console.error(`${pt.cross} ${bt.red(e)}`)},"onErrorEvent"),onDetached:__name(()=>{stopAllSpinners({state:r}),console.error(`\n${bt.yellow("Detached.")} Session still running.`),console.error(`Resume with: ${bt.cyan(`${getBinaryCommand()} --experimental sandbox --id ${e}`)}`)},"onDetached"),onCancelled:__name(()=>{stopAllSpinners({state:r}),console.error(`\n${bt.yellow("Sandbox stopped.")}`)},"onCancelled"),onDisconnected:__name(()=>{stopAllSpinners({state:r}),console.error(`\n${bt.yellow("Disconnected.")} Session still running.`),console.error(`Resume with: ${bt.cyan(`${getBinaryCommand()} --experimental sandbox --id ${e}`)}`)},"onDisconnected"),onConnectionError:__name(()=>{r.currentSpinner&&(r.currentSpinner.fail("Connection error"),r.currentSpinner=null)},"onConnectionError")}});n&&(r.currentSpinner=Pt({stream:process.stderr,text:"Reconnecting..."}).start());const s=setupResizeForwarding({handle:o}),a=setupInputHandling({callbacks:{onCancel:o.cancel,onDetach:o.detach}});process.once("SIGTERM",o.detach);try{await o.done}finally{s(),a(),process.removeListener("SIGTERM",o.detach)}}async function askQuestion(e){const t=At.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.question(e,e=>{t.close(),n(e)})})}async function sandboxMode({prompt:e,resume:t}){t&&(await streamSession({sessionId:t,isResume:!0}),process.exit(0)),await ensureAuthenticated()||process.exit(1);const n=validateSandboxGitRepo({run:__name(({command:e})=>S(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"run")});n.isClean||console.error(bt.yellow("Warning: You have uncommitted changes. The sandbox clones from remote, so local changes won't be included."));const r=await readSandboxConfigFiles({runtime:getCommandConfigRuntime(),authFilePath:getAuthFile(),configFilePath:getConfigFile()}),o=e||await askQuestion(`${bt.bold("What do you want to do?")}\n${bt.cyan(">")} `);if(!o.trim())return void console.error(bt.yellow("No prompt provided. Aborting."));const s=truncateSandboxPrompt(o),a=Pt({stream:process.stderr,text:"Starting sandbox session..."}).start();try{const e=await startSandboxSession({client:createApiClient({baseUrl:getApiBaseUrl()}),request:{repoUrl:n.repoUrl,branch:n.branch,prompt:s,configFiles:r}});a.succeed("Sandbox started"),await streamSession({sessionId:e.sessionId,prompt:s}),process.exit(0)}catch(e){a.fail("Failed to start sandbox session");const t=classifySandboxStartFailure({error:e});if("unauthorized"===t.kind&&(console.error(bt.red(`\nAuthentication failed. Try logging in again: ${getBinaryCommand()} login`)),process.exit(1)),"github_app_not_installed"===t.kind){const e=bt.cyan(bt.underline(n.repoUrl)),t=bt.cyan(bt.underline("https://github.com/apps/command-code-ai/installations/new"));console.error(`\n${bt.red("✖")} Command Code GitHub App isn't installed on ${e}`),console.error(` Install it here: ${t}`),console.error(bt.dim(" Then run this command again.")),process.exit(1)}console.error(bt.red(`\n${t.message}`)),process.exit(1)}}function createSandboxCommand(){return new je("sandbox").description("Run a task autonomously in a sandbox").argument("[prompt]","Task description").option("--id <sessionId>","Resume an existing sandbox session").enablePositionalOptions().action(async(e,t)=>{try{await sandboxMode({prompt:e,resume:t.id})}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(bt.red(t)),process.exit(1)}})}Ht(),Ht(),Qx(),Ht(),Qx(),__name(stopAllSpinners,"stopAllSpinners"),__name(renderStatusAction,"renderStatusAction"),__name(setupInputHandling,"setupInputHandling"),__name(setupResizeForwarding,"setupResizeForwarding"),__name(streamSession,"streamSession"),__name(askQuestion,"askQuestion"),__name(sandboxMode,"sandboxMode"),__name(createSandboxCommand,"createSandboxCommand"),Ht(),Ht(),Qx();var cF=[`${bt.dim("Usage:")}`,` ${bt.cyan(`${getBinaryCommand()} skills add`)} ${bt.white("<owner/repo>")}`,"",`${bt.dim("Examples:")}`,` ${bt.cyan(`${getBinaryCommand()} skills add`)} ${bt.white("acme/my-skills")} ${bt.dim("# single-skill repo")}`,` ${bt.cyan(`${getBinaryCommand()} skills add`)} ${bt.white("acme/skills/path/to/skill")} ${bt.dim("# specific path in repo")}`,` ${bt.cyan(`${getBinaryCommand()} skills add`)} ${bt.white("acme/multi-skills -s my-skill")} ${bt.dim("# pick one from multi-skill repo")}`,` ${bt.cyan(`${getBinaryCommand()} skills add`)} ${bt.white("acme/repo@branch")} ${bt.dim("# specific branch")}`,` ${bt.cyan(`${getBinaryCommand()} skills add`)} ${bt.white("acme/repo --global")} ${bt.dim("# install to ~/.commandcode/skills/")}`],dF=__name((e,t)=>`${bt.green(pt.tick)} Installed ${bt.cyan(e)} ${bt.dim(`${pt.arrowRight} ${t}/`)}`,"formatInstalled"),uF=__name(e=>`${bt.red(pt.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(uF(t.message)),console.log(""),t.message.startsWith("Invalid repository")&&(console.log(`Expected format: ${bt.cyan("owner/repo")} or ${bt.cyan("owner/repo/path")}`),console.log("")),cF.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=Pt({text:`Fetching ${bt.cyan(e)}...`,color:"cyan"});try{let a=[];s.start();const i=await discoverCommandSkills(e,{keepTempDir:!0}),{skills:l,tempDir:c}=i;o=c,s.stop();const d=planSkillInstallSelection({skills:l,requestedSkillName:t.skill,interactive:n,repoInput:e});if("empty"===d.kind&&(console.error(uF(`No skills found in ${bt.cyan(e)}`)),console.log(bt.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(o,1)),"missing-requested-skill"===d.kind)return console.error(uF(`Skill "${d.requestedSkillName}" not found in ${bt.cyan(d.repoInput)}`)),console.log(""),console.log(bt.dim("Available skills:")),d.availableSkillNames.forEach(e=>console.log(` ${bt.cyan(e)}`)),void await cleanupAndExit(o,1);if("prompt"===d.kind){const t=await ze({message:`Select skills to install from ${e}`,options:[...d.options],required:!0});"symbol"==typeof t&&(console.log(bt.dim("Cancelled")),await cleanupAndExit(o,0)),a=resolvePromptedSkillSelection({skills:l,selectedNames:t})}let u;"selected"===d.kind&&(a=d.skills);const m=await installSelectedCommandSkills({repoInput:e,skills:a,global:t.global,force:t.force,cachedTempDir:o,onSkillStart:__name(e=>{u=Pt({text:`Installing ${bt.cyan(e.name)}...`,color:"cyan"}),u.start()},"onSkillStart"),onSkillInstalled:__name(e=>{u?.stop(),console.log(dF(e.name,r))},"onSkillInstalled"),onSkillFailed:__name(({skillName:e,message:t})=>{u?.stop(),console.error(uF(`Failed to install "${e}"`)),console.log(bt.dim(` ${t}`))},"onSkillFailed")});await cleanupAndExit(o,m.exitCode)}catch(e){s.stop();const t=e instanceof Error?e.message:String(e);console.error(uF(t)),await cleanupAndExit(o,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction2,"addAction");var mF=new je("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${cF.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(uF("No repository specified.")),console.log(""),cF.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction2);Ht(),Qx();var pF=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${bt.cyan(e)} ${bt.dim(`· ${n}`)}`},"formatSkillLine"),gF=__name((e,t)=>`${bt.bold(bt.white(e))} ${bt.dim(`(${t})`)}`,"formatSectionHeader"),hF=__name(e=>{if(0!==e.warningCount){console.log(""),console.log(`${bt.bold(bt.yellow("Skipped"))} ${bt.dim(`(${e.warningCount})`)}`);for(const t of e.warningGroups){console.log(""),console.log(` ${bt.bold(t.category)} ${bt.dim(`(${t.items.length})`)}`);for(const e of t.items)console.log(` ${bt.bold(skillIdentifier(e.path))}`),console.log(` ${bt.dim(e.reason)}`)}}},"printWarnings"),fF=__name(e=>{const t=["",bt.dim("No skills installed."),"",bt.dim("Looking in:")];for(const n of e.lookupPaths)t.push(bt.dim(` ${n.path} ${bt.white(`(${n.label})`)}`));return t.push("",`Install a skill: ${bt.cyan(e.installCommand)} ${bt.dim(e.installPlaceholder)}`,""),t},"formatEmptyHint"),yF=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),SF=__name(e=>{e&&(console.log(""),console.log(bt.dim(e.replace("--debug",bt.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()}`});yF(fF(t));for(const e of s.sections)console.log(gF(e.title,e.skills.length)),e.skills.forEach(e=>{console.log(pF(e.name,e.description))}),console.log("");e&&(hF({warningCount:s.warningCount,warningGroups:s.warningGroups}),s.warningCount>0&&console.log("")),e||(SF(s.debugHint),console.log("")),process.exit(0)}console.log(""),console.log(heading({text:"Skills",sub:bt.dim(`${s.userInstalledTotal} installed`)}));for(const e of s.sections)console.log(""),console.log(gF(e.title,e.skills.length)),e.skills.forEach(e=>{console.log(pF(e.name,e.description))});e&&hF({warningCount:s.warningCount,warningGroups:s.warningGroups}),e||SF(s.debugHint),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${bt.red(pt.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction2,"listAction");var wF=new je("list").description("List all installed skills. Run with -d/--debug to also see why any skills were skipped.").action(listAction2);Ht(),Qx();var vF=__name((e,t)=>`${bt.green(pt.tick)} Removed ${bt.cyan(e)} from ${t} skills`,"formatRemoved"),kF=__name(e=>`${bt.red(pt.cross)} ${e}`,"formatError"),CF=__name((e,t)=>{let n=e;for(const e of t)n=n.replace(e,bt.cyan(e));return bt.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(kF(o)),console.log(CF(getSkillListCommandHint({binCommand:`${getBinaryCommand()}`}),[`${getBinaryCommand()} skills list`])),process.exit(1)),!t.yes&&n){const t=await Ke({message:`Remove ${bt.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(bt.dim("Cancelled")),process.exit(0))}await removeCommandSkill({skillName:e,global:t.global}),console.log(vF(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(kF(o.message)),"not-found"===o.kind)for(const t of o.hints)console.log(CF(t,[`${getBinaryCommand()} skills remove ${e} --global`,`${getBinaryCommand()} skills list`]));process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction2,"removeAction");var bF=new je("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),EF=new je("skills").description("Manage skills from GitHub repositories").addCommand(mF).addCommand(bF).addCommand(wF);Ht(),Qx(),Ht(),Qx(),Ht(),Ht(),Qx();var TF=[pt.bullet,pt.squareSmallFilled,pt.lozenge,pt.star,pt.triangleRight,pt.triangleUp];Ht(),Qx(),Ht();var PF=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return PF.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"),Ht(),Qx(),Ht(),Ht();var MF=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),o=e.learningCount>0;return ot.createElement(Je,{flexDirection:"column",marginLeft:3},ot.createElement(Je,{marginBottom:1,flexDirection:"row"},ot.createElement(Qe,{color:nI.DIM},YI),ot.createElement(Je,{marginLeft:2},ot.createElement(Qe,{color:oI.TEXT},o?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),ot.createElement(Je,{flexDirection:"column",marginLeft:1},ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},pt.pointerSmall," Taste stored in"," "),ot.createElement(BI,{url:fileUrl(e.storage),text:r||".commandcode/taste/taste.md",color:nI.CYAN})),ot.createElement(Je,null,ot.createElement(Qe,{color:nI.DIM},pt.pointerSmall," Share your coding taste:"," ",ot.createElement(Qe,{color:nI.CYAN},"npx taste push --all")))),ot.createElement(Je,{marginTop:1,marginLeft:1},ot.createElement(Qe,{color:nI.DIM},o?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Ht();var xF=__name(({message:e})=>ot.createElement(qO,null,e),"RepoLearnErrorPanel");Ht();var IF=__name(({done:e,error:t})=>t?ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Esc")," to exit")):e?ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"Press ",ot.createElement(GA,null,"Enter")," to continue")):ot.createElement(Je,{marginTop:1},ot.createElement(HA,null,"Esc to cancel")),"RepoLearnFooter");Ht(),Qx();var AF=__name(({insights:e,insightCount:t})=>0===e.length?null:ot.createElement(Je,{flexDirection:"column",marginTop:1,marginLeft:4},ot.createElement(Qe,{color:nI.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>ot.createElement(Qe,{key:`${t}-${e}`,color:nI.DIM},TF[t%TF.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Ht(),Qx();var RF=__name(({status:e})=>"active"===e?ot.createElement(Je,null,ot.createElement(Qe,{color:nI.YELLOW},ot.createElement(vt,{type:"dots"})),ot.createElement(Qe,null," ")):"complete"===e?ot.createElement(Qe,{color:lI.BG},pt.square," "):ot.createElement(Qe,{color:nI.DIM},pt.circle," "),"StepStatusIndicator");function getStepLabelColor(e,t){return"complete"===e?nI.WHITE:t?nI.YELLOW:nI.DIM}__name(getStepLabelColor,"getStepLabelColor");var OF=__name(({steps:e,currentMessage:t})=>ot.createElement(Je,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return ot.createElement(Je,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},ot.createElement(Je,null,ot.createElement(Je,{marginRight:1},ot.createElement(RF,{status:e.status})),ot.createElement(Qe,{bold:n,color:getStepLabelColor(e.status,n)},e.label)),n&&t?ot.createElement(Je,{marginLeft:3},ot.createElement(Qe,{color:nI.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Ht();var LF=__name(({isComplete:e,hasError:t})=>t?ot.createElement(Qe,{color:nI.DIM},"learning interrupted"):e?ot.createElement(Qe,{color:oI.TEXT},"learned your coding taste"):ot.createElement(GI,null),"TastePillStatus"),DF=__name(({isComplete:e,hasError:t})=>ot.createElement(Je,{flexDirection:"column",marginTop:1,marginBottom:0},ot.createElement(ZI,null),ot.createElement(Je,{marginTop:0},ot.createElement(Qe,{color:nI.DIM},YI),ot.createElement(Je,{marginLeft:2},ot.createElement(LF,{isComplete:e,hasError:t})))),"RepoLearnTastePill");Ht();var NF=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=ct(()=>RA(n),[n]);return ot.createElement(Je,{flexDirection:"column"},ot.createElement(Je,{flexDirection:"column",marginBottom:1},ot.createElement(PI,null,r.trimEnd())),e?ot.createElement(Qe,{color:nI.WHITE},e):ot.createElement(ot.Fragment,null,ot.createElement(Qe,{color:nI.WHITE},"Learning your coding taste from"," ",ot.createElement(Qe,{bold:!0,color:nI.CYAN},t??"repository")),ot.createElement(Qe,{color:nI.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function useRepoLearnState(e){const t=e??TM,[n,r]=at(()=>createRepoLearnProjection({stepOrder:t})),o=it(null),[s,a]=at(null),i=dt(()=>{o.current=Date.now()},[]),l=dt(e=>{r(t=>({...t,showLogin:e}))},[]);return lt(()=>{const e=__name(()=>{r(createRepoLearnProjection({stepOrder:t})),o.current=null,a(null)},"handleReset"),n=__name(e=>{r(t=>reduceRepoLearnEvent({state:t,event:e}))},"handleEvent"),s=__name(()=>{r(e=>completeRepoLearnProjection({state:e})),o.current&&a(Math.round((Date.now()-o.current)/1e3))},"handleComplete");return am.on("reset",e),am.on("new-event",n),am.on("learning-complete",s),()=>{am.off("reset",e),am.off("new-event",n),am.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:i}}function StatusPanel({error:e,done:t,summary:n,elapsedSeconds:r,insights:o,insightCount:s}){return e?ot.createElement(xF,{message:e}):t?ot.createElement(MF,{summary:n,elapsedSeconds:r}):ot.createElement(AF,{insights:o,insightCount:s})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:o}){const s=useRepoLearnState(n),a=it(!1);return lt(()=>{a.current||(a.current=!0,s.markStarted(),e().catch(()=>{}))},[e,s.markStarted]),tt((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?ot.createElement(Je,{flexDirection:"column"},ot.createElement(NF,{text:r,repoName:o}),ot.createElement(kN,{onComplete:(e,t)=>{s.setShowLogin(!1),e?am.resolveAuth():am.rejectAuth(t)},onCancel:()=>{s.setShowLogin(!1),am.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):ot.createElement(Je,{flexDirection:"column"},ot.createElement(NF,{text:r,repoName:o}),ot.createElement(DF,{isComplete:s.done&&!s.error,hasError:Boolean(s.error)}),ot.createElement(OF,{steps:s.steps,currentMessage:s.currentMessage}),ot.createElement(StatusPanel,{error:s.error,done:s.done,summary:s.summary,elapsedSeconds:s.elapsedSeconds,insights:s.insights,insightCount:s.insightCount}),ot.createElement(IF,{done:s.done,error:s.error}))}async function runRepoLearnProgress(e){return await applyStartupTheme(),withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{am.reset();const r=new AbortController;let o,s,a=!1,i=!1;const l=__name(async()=>{try{o=await e.runTask(r.signal)}catch(e){r.signal.aborted||(s=e,am.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),am.markLearningComplete())}},"handleRunTask"),c=__name(({published:e,cancelled:l})=>{i||(i=!0,a=e,r.abort(),d.unmount(),am.reset(),s?n(s):t({result:o,published:a,cancelled:l}))},"handleExit"),d=et(ot.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:c}));d.waitUntilExit().catch(e=>{am.reset(),n(e)})})}function getAuthKey7(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function logLearnSummary(e){const{summary:t}=e;console.log(gt.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("")}Ht(),Qx(),__name(useRepoLearnState,"useRepoLearnState"),__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),__name(getAuthKey7,"getAuthKey"),__name(logLearnSummary,"logLearnSummary");var $F=__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 je("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",$F("--max-commits"),200).addOption(new Be("--max-signals <number>","Maximum diff signals to extract").default(50).argParser($F("--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 a;const i=__name(()=>{a?.().finally(()=>process.exit(130))},"sigintHandler");process.once("SIGINT",i);let l=!1;try{const i=__name(async r=>{const{summary:o,resolved:i}=await runLearnPipeline({runtime:t,reporter:am,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 a=i?.cleanup,o},"runTask");if(r){const e=n?void 0:[...PM];({cancelled:l}=await runRepoLearnProgress({runTask:i,repoName:o,stepOrder:e}))}else logLearnSummary({summary:await i((new AbortController).signal)})}finally{process.off("SIGINT",i),a&&await a()}r&&!l||process.exit(0),cA(),await J_({skipOnboarding:!0}),await shutdownAndExit(0)}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Ht(),Qx(),Ht(),Qx();var _F=gt.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(`${gt.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?`${gt.dim(t[1])}${gt.green(t[2])}${gt.white(t[3]??"")}${t[4]?gt.dim(t[4]):""}`:gt.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${gt.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 FF=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){const n=buildPackageUrl({owner:e,packageName:t});return It(`commandcode.ai/${e}/${t}`,n,{fallback:FF})}function getProfileLink(e){const t=buildProfileUrl2(e);return It(`commandcode.ai/${e}`,t,{fallback:FF})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return Rt(e,n,{trim:!1})}function logMergeReviewTip(){console.log(gt.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}function handleResultErrors(e){for(const t of e){const e=normalizeTasteResultError(t);console.error(`${gt.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(gt.red(`Error: ${t}`)),await flushAndExit(1)}}}function formatSingleIssue(e,t){const n=[`${e.line?gt.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(gt.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`${gt.green(e)} ${gt.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?gt.red(t.summary):gt.yellow(t.summary),"",...formatIssueGroup(r,gt.red,gt.bold(gt.red("Errors:"))),...formatIssueGroup(o,gt.yellow,gt.bold(gt.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"),Ht(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var UF=createTasteLintService({runtime:createNodeRuntime(),formatValidationIssues:formatValidationIssues});function createLintCommand(){return new je("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 ${gt.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(`${gt.green(pt.tick)} All ${gt.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(gt.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(gt.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 UF.lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(gt.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Ht(),Qx();var jF={};__export(jF,{downloadPackage:()=>downloadPackage,downloadRemotePackage:()=>downloadRemotePackage,getAllPackages:()=>getAllPackages,getPackage:()=>getPackage,listPackages:()=>listPackages,writePackage:()=>writePackage,writePackages:()=>writePackages}),Ht(),Qx();var BF=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: cmd 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:xo.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:a,categoryContents:i}=await readProjectUploadFiles({runtime:BF,packages:t});return storage().writePackages({projectName:n,owner:r,isPublic:o,overwrite:s,rootContent:a,categoryContents:i,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 WF=createNodeRuntime(),HF=createTasteLocalStorage({runtime:WF,target:"local-project"}),GF=createTasteLocalStorage({runtime:WF,target:"local-global"});function list(e){return createTasteListService({runtime:WF,localProject:HF,localGlobal:GF,remote:jF}).list(e)}function getUserName(){return getCommandAuthUserName({runtime:getCommandConfigRuntime(),path:getAuthFile()})}function createListCommand(){return new je("list").alias("ls").option("-g, --global","List global packages").addOption(new Be("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Be("--staging","Use staging environment").hideHelp()).description(`List available packages ${gt.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}function formatPackageLine(e){return` ${gt.white(e.name)}${e.publicBadge?gt.green(e.publicBadge):""}${e.starsBadge?gt.yellow(e.starsBadge):""}${e.downloadsBadge?gt.gray(e.downloadsBadge):""}${e.padding}${gt.dim.gray(e.statsLabel)}`}function validateListOptions(e){exitWithTasteCliValidation(validateTasteListCliOptions(e))}async function fetchPackages({options:e}){const t=resolveTasteListStorage(e),n=e.remote?Pt(`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${_F} Packages`),console.log(`${gt.gray("⎿")} ${gt.dim(t)}\n`);const n=projectTasteListView({packages:e,symbols:{star:pt.star,arrowDown:pt.arrowDown}});for(const e of n.rows)console.log(formatPackageLine(e));console.log(gt.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(gt.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"),Ht(),Qx(),Ht(),Qx();var VF=createNodeRuntime(),zF=createTasteLocalStorage({runtime:VF,target:"local-project"}),KF=createTasteLocalStorage({runtime:VF,target:"local-global"});async function open7(e){try{const t=await createTasteOpenService({runtime:VF,localProject:zF,localGlobal:KF,remote:jF}).resolveOpen(e);return t.success?(await xt([{file:t.filePath,line:t.lineNumber}]),t):t}catch(e){return classifyTasteOpenError({error:e,platform:be.platform})}}function createOpenCommand(){return new je("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 ${gt.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 Tt(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${gt.green(pt.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(`${gt.green(pt.tick)} Opened ${gt.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"),Ht(),Qx(),Ht(),Qx(),Ht();var qF=null,YF=!1;function setActiveSpinner(e){qF=e}function stopActiveSpinner(e){qF&&(qF.stop(e),qF=null)}function setPrompted(e){YF=e}function wasPrompted(){return YF}function logResult(e){if(wasPrompted())return He.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{summary:t,sourceName:n}=e,r=wasPrompted()?"":`${pt.tick} `,o=t.detailPath?gt.dim(`\n ${shortenPath(t.detailPath)}`):"";return"single-replaced"===t.variant?`${gt.green(r)}Replaced ${gt.green(`'${t.packageName}'`)} taste package in project`+o:"single-merged"===t.variant?`${gt.green(r)}Pulled ${gt.green(`'${t.packageName}'`)} taste package from ${n} ${gt.gray(`(${t.mergeParts.join(", ")})`)}`+o:`${gt.green(r)}Pulled ${gt.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(`${gt.green("Pulled")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`,wasPrompted()?4:0)),t.overwritten.length>0&&r.push(wrapLine(`${gt.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`,wasPrompted()?4:0)),t.skipped.length>0&&r.push(wrapLine(`${gt.dim("Skipped")} (${t.skipped.length}) ${gt.dim(t.skipped.join(", "))}`,wasPrompted()?4:0)),wasPrompted())return r.length>0&&He.log.message(r.join("\n")),He.outro(`${t.totalLabel} from ${n}`),void setPrompted(!1);console.log(`${gt.green(pt.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(gt.yellow(o.message))}function beginPrompt(e,t){stopActiveSpinner(),He.intro(gt.dim(e)),t&&He.log.message(gt.dim(t)),setPrompted(!0)}function handleCancel(e){He.isCancel(e)&&(He.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=He.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=He.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),He.log.warn(e.nonInteractive.warning),e.nonInteractive.strategy;if(beginPrompt(`${e.title.prefix}${gt.green(e.title.emphasis)}${e.title.suffix}`,e.existsMessage),He.log.message(`${e.context.firstLine}\n${e.context.secondLine}${e.context.secondLineNote?` ${gt.dim(e.context.secondLineNote)}`:""}`),e.reviewLink){const t=It(e.reviewLink.text,e.reviewLink.url,{fallback:__name((e,t)=>t,"fallback")});He.log.info(`${e.reviewLink.prefix}${gt.cyan(t)} ${gt.dim(e.reviewLink.note)}`)}const t=await He.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"),Ht(),Qx(),Ht(),Qx(),__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 JF=createNodeRuntime(),QF=createTasteLocalStorage({runtime:JF,target:"local-project"}),XF=createTasteLocalStorage({runtime:JF,target:"local-global"});function service(){return createTastePullService({localProject:QF,localGlobal:XF,remote:jF,getDestinationPath:__name(e=>resolveTastePackageDestinationPathForRuntime({runtime:JF,...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 je("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 Be("--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 Be("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${gt.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(Pt("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(Pt("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 He.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?gt.dim(`\n ${shortenPath(e)}`):""}function renderPushSummary(e){const t=wasPrompted()?"":`${pt.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?` ${gt.gray(`(${e.replacedLabel})`)}`:"";return void logResult2(`${gt.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?` ${gt.gray(`(${e.mergeParts.join(", ")})`)}`:"";return void logResult2(`${gt.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(`${gt.green(t)}Pushed ${gt.green(e.count)} taste packages ${gt.green(`(${e.packages.join(", ")})`)} to ${e.targetName}`)):logResult2(`${gt.green(t)}Pushed ${gt.green(`'${e.packageName}'`)} taste package to ${e.locationLabel}`+formatDetailPath(e.detailPath)):logResult2(`${gt.green(t)}Pushed ${gt.green(`'${e.packageName}'`)} taste package to ${e.locationLabel} ${gt.gray(`(${e.mergeParts.join(", ")})`)}`+formatDetailPath(e.detailPath)):logResult2(`${gt.green(t)}Replaced ${gt.green(`'${e.packageName}'`)} taste package in ${e.locationLabel}`+formatDetailPath(e.detailPath))}else logResult2(`${gt.green(t)}Pushed ${e.packageCountLabel} to ${formatAllLocation(e.location)}`)}else logResult2(`${gt.green(t)}Pushed ${e.packageCountLabel} to remote`);else logResult2(`${gt.green(t)}Skipped ${e.packageCountLabel}`)}function logPushUrls(e){for(const t of collectTastePushRemoteLinks(e))console.log(gt.gray(` ${getPackageLink(t)}`))}function logConflictSummary(e){const t=projectTastePushOutcome(e.result),n=[];t.succeeded.length>0&&n.push(wrapLine(`${gt.green("Merged")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`,4)),t.overwritten.length>0&&n.push(wrapLine(`${gt.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`,4)),t.skipped.length>0&&n.push(wrapLine(`${gt.dim("Skipped")} (${t.skipped.length}) ${gt.dim(t.skipped.join(", "))}`,4)),n.length>0&&He.log.message(n.join("\n")),He.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(`${gt.green("Pushed")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`)),t.overwritten.length>0&&n.push(wrapLine(`${gt.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`)),t.skipped.length>0&&n.push(wrapLine(`${gt.dim("Skipped")} (${t.skipped.length}) ${gt.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"),Ht(),Qx(),Ht(),Qx(),__name(logResult2,"logResult"),__name(formatAllLocation,"formatAllLocation"),__name(formatDetailPath,"formatDetailPath"),__name(renderPushSummary,"renderPushSummary"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Ht(),Qx();var ZF=createNodeRuntime(),eU=createTasteLocalStorage({runtime:ZF,target:"local-project"}),tU=createTasteLocalStorage({runtime:ZF,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:eU,localGlobal:tU,remote:jF,getUserOwner:getUserOwner,getProjectName:__name(()=>e.basename(process.cwd()),"getProjectName"),getDestinationPath:__name(e=>resolveTastePackageDestinationPathForRuntime({runtime:ZF,...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 He.select({message:"Owner",options:[...r],initialValue:o});return He.isCancel(s)&&(He.cancel("Operation cancelled"),process.exit(0)),s}__name(getUserOwner,"getUserOwner"),__name(service2,"service"),__name(push,"push"),__name(pushRemote,"pushRemote"),Ht(),Qx(),__name(promptOwnerSelection,"promptOwnerSelection");var nU=createNodeRuntime(),rU=createTasteLocalStorage({runtime:nU,target:"local-project"});function loadUserNamespaces(){return fetchUserNamespaces({client:createApiClient({baseUrl:getApiBaseUrl()})})}function createPushCommand(){return new je("push").description(`Push taste packages to remote ${gt.dim("(commandcode.ai)")} or global ${gt.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 Be("--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 Be("--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 rU.getAllPackages()).some(t=>t.category===e),"hasLocalPackage"),loadNamespaces:loadUserNamespaces,prompt:{onPromptStart:__name(({packageName:e})=>{He.intro(gt.dim(`pushing ${e}`)),setPrompted(!0),t=He.spinner(),t.start("Resolving")},"onPromptStart"),onPackageMissing:__name(({packageName:e})=>{t?.error("Failed"),He.outro(gt.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 rU.getAllPackages()).length),r=e.basename(process.cwd()),o=resolveTasteStrategyLabel({strategy:t.route.strategy,isRemote:!0});console.log(gt.dim(` Pushing ${n} to ${r} (remote)${o}`)),console.log(""),setActiveSpinner(Pt("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=He.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Pt("Pushing taste package").start())}async function pushGlobal(e){const t=await rU.getAllPackages(),n=formatTastePackageCount(e.route.packages.length>0?e.route.packages.length:t.length),r=shortenPath(getTastePathForRuntime({runtime:nU,target:"local-global"})),o=resolveTasteStrategyLabel({strategy:e.route.strategy});console.log(gt.dim(` Pushing ${n} to ${r}${o}`)),console.log(""),setActiveSpinner(Pt("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(`${gt.green(pt.tick)} Taste learning is on${whereFor(e)}. New preferences are saved and reused across sessions.`)}function reportDisabled(e){const t=getBinaryCommand();console.log(`${gt.green(pt.tick)} Taste learning is off${whereFor(e)}. Turn it back on with ${gt.cyan(`${t} taste enable`)}.`)}function createEnableCommand(){return new je("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 je("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 je("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"),Ht(),Qx(),__name(scopeOf,"scopeOf"),__name(whereFor,"whereFor"),__name(applyTasteLearning,"applyTasteLearning"),__name(reportEnabled,"reportEnabled"),__name(reportDisabled,"reportDisabled"),__name(createEnableCommand,"createEnableCommand"),__name(createDisableCommand,"createDisableCommand"),__name(createTasteCommand,"createTasteCommand"),Ht(),Qx();var oU=`${getBinaryCommand()}`;function formatVersion(e,t,n=!1){const r=n?bt.bold(bt.green(t)):bt.white(t);return`${bt.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(`${oU} update`,bt.bold(bt.green(`${oU} update`))))}function showUpdateSuccessHint(e){for(const t of e.detailLines)console.log(bt.dim(t.replace(oU,bt.cyan(oU))))}function showManualUpdateHint(e){const[t,n]=e.manualUpdateLines;t&&console.log(bt.dim(t)),n&&console.log(bt.cyan(n))}function showCheckFailure(e){for(const t of e.detailLines)console.log(bt.dim(t))}function renderUpdateEvent(e,t){if("type"in e)"updating"===e.type&&(t.text=e.text.replace("→",pt.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(`${bt.green(pt.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=Pt("Checking for updates...").start(),n=await runCliUpdateCommand({checkOnly:e.checkOnly,host:p_,copy:{binCommand:oU,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:xo.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 sU=new je("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})}Ht(),Qx(),__name(getAuthKey9,"getAuthKey");var aU=__name((e,t)=>`${pt.info} ${e}: ${bt.cyan(t)}`,"formatInfoLine"),iU=__name(e=>bt.bold(`${e}:`),"formatSectionHeader"),lU=__name(e=>bt.red(e),"formatError"),cU=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),dU=__name((e,t)=>["",iU(e),...t.map(e=>aU(e.label,e.value))],"buildSection"),uU=__name(e=>dU("User Information",projectWhoamiUserRows(e)),"buildUserOutput"),mU=__name(e=>dU("Organization",projectWhoamiOrgRows(e)),"buildOrgOutput"),pU=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),gU=__name((e,t)=>{pU(uU(e)),t&&pU(mU(t)),console.log("")},"displayUserInfo");async function whoamiAction(){const e=Pt("Fetching user information...").start();try{hasCommandApiKey(await getAuthKey9())||(e.fail(lU(Kt)),process.exit(1));const t=await getAuthenticatedEntity({client:createApiClient({baseUrl:getApiBaseUrl()})});isAuthenticatedEntityLoaded(t)||(e.fail(lU(qt)),process.exit(1)),e.succeed("User information loaded"),gU(t.user,t.org)}catch(t){e.fail(lU(`Error: ${cU(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var hU=new je("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 fU=createProgram();fU.action(interactiveModeAction),fU.addCommand(hO),fU.addCommand(TO),fU.addCommand(hU),fU.addCommand(sU),fU.addCommand(gO),fU.addCommand(pO),fU.addCommand(createTasteCommand()),fU.addCommand(createMcpCommand()),fU.addCommand(yL),fU.addCommand(lO),fU.addCommand(tO),fU.addCommand(iO),fU.addCommand(lF),fU.addCommand(EF),fU.addCommand(PL),isExperimentalEnabled()&&fU.addCommand(createSandboxCommand()),setupCommanderHooks(fU),fU.parse();