command-code 1.72.2 → 1.72.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -11,6 +11,6 @@ import*as e from"path";import t,{join as n,dirname as r,parse as o,resolve as s,
11
11
  ░█▀▀░█▀▄▀█░█▀▄░
12
12
  ░█░░░█░▀░█░█░█░
13
13
  ░▀▀▀░▀░░░▀░▀▀░░
14
- `,mO=getMaxLineWidth(uO),pO=lO,gO=__name(e=>{const t=e??getTerminalWidth();return t>=iO?"full":t>=pO?"compact":"minimal"},"getHeaderLayout");new Set(["dark","light"]),Vt(),PR();var hO=!1;async function resolveStartupTheme(){return hO||(hO=!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=Jo}=e,[s,a]=ct("initializing"),[i,l]=ct("Starting authentication..."),[c,d]=ct(""),[u,m]=ct(null),p=dt(t),g=dt(n),h=dt(r);ut(()=>{p.current=t,g.current=n,h.current=r});const f=dt(null);f.current??=createAuthFlowController({timeoutMs:o,openBrowser:__name(e=>xt(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=pt(()=>{y.cancel()},[y]),w=pt(e=>y.submitApiKey(e),[y]);return ut(()=>(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]=ct(r??(e||"").length),a=dt(o),i=dt(e);ut(()=>{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=pt(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,transformPaste:a,deferEmptyPaste:i=!1}){const l=dt(!1),c=dt(a);c.current=a;const d=dt(i);d.current=i,ut(()=>{if(!e)return;const a=process.stdin,i=__name(e=>{o(!0);const t=clampCursor(e.cursor,e.value.length);r(e.value,t),setTimeout(()=>o(!1),0)},"emitStdinResult"),u=__name(e=>{const r=e.toString();if(s){const e=processBracketedPasteInput({input:r,value:t.current,cursor:n.current,transform:c.current});if(e.handled)return void(e.value===t.current&&d.current||i(e))}const o=processRawInput(r,t.current,n.current);o.handled&&i(o)},"handleRawInput");if(a.on("data",u),!l.current&&hasBufferedInput()){l.current=!0;const e=consumeBufferedInput();e&&u(Buffer.from(e))}return stopEarlyInputCapture(),()=>{a.off("data",u)}},[e,t,n,r,o,s])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:o,onUpdate:s,onSubmit:a}){ot((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=dt(e);return t.current=e,t}function useEchoAwareValueRef(e){const t=dt(e),n=dt([]),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:pt(e=>{n.current.push(e),n.current.length>64&&n.current.shift()},[])}}__name(resolveStartupTheme,"resolveStartupTheme"),__name(applyStartupTheme,"applyStartupTheme"),Vt(),Vt(),PR(),__name(useAuthFlow,"useAuthFlow"),Vt(),PR(),Vt(),PR(),Vt(),PR(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef"),__name(useEchoAwareValueRef,"useEchoAwareValueRef"),Vt(),PR();var fO=yt.hex(LR.DIM),yO=__name(e=>yt.hex(QR.CODE)(e),"accentHex"),SO=/^\/[A-Za-z0-9][\w/:-]*/,wO=/(^|\s)(@\S+)/g;function pastedTokenRanges(e,t){const n=[],r=new RegExp(bM.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(EM.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=SO.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(wO.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?Pt.inverse(" ")+"\n":Pt.inverse(t):t}return s}function renderTokenSpan(e,t,n,r,o,s="dim"){const a="accent"===s?yO:fO;return o&&r>=t&&r<n?a(e.slice(t,r))+Pt.inverse(e[r])+a(e.slice(r+1,n)):a(e.slice(t,n))}function renderPlaceholder(e,t){return t?0===e.length?Pt.inverse(" "):Pt.inverse(e[0])+fO(e.slice(1)):fO(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 Pt.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+=Pt.inverse(" ")),i}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(kt(e).length<=s)return e;const a=e.split(/(\s+)/);let i="",l=0,c=!0;for(const e of a){const t=kt(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=kt(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"),PR();var vO={white:Pt.white,green:Pt.green,red:Pt.red,blue:Pt.blue,yellow:Pt.yellow,cyan:Pt.cyan,magenta:Pt.magenta,gray:Pt.gray,grey:Pt.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,clipboardOnEmptyPaste:g=!1,collapsePastedText:h=!1,onPasteCollapsed:f,initialCursor:y,imageTokenLinks:S,isRecognizedSlashCommand:w}){const v=dt(!1),k=dt(0),{valueRef:C,noteEmittedValue:b}=useEchoAwareValueRef(e),E=useSyncedRef(s),T=useSyncedRef(f),{cursor:P,setCursor:M,cursorRef:x}=useCursorState({value:e,focus:n,showCursor:o,initialCursor:y});it.useEffect(()=>{i?.(P)},[P,i]);const I=pt((e,t)=>{M(t),e!==C.current&&(b(e),C.current=e,E.current(e))},[M,C,E,b]),A=pt(e=>{const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");return h&&isPasteWorthCollapsing({content:t,multiline:!0})?(T.current?.(t),pastedTextToken(t)):e},[h,T]),R=pt(e=>{v.current=e},[]),L=pt(()=>v.current||k.current>0,[]);useRawStdinHandler({focus:n,valueRef:C,cursorRef:x,onUpdate:I,setHandled:R,stripBracketedPaste:m,transformPaste:A,deferEmptyPaste:g}),it.useEffect(()=>{if(!n||p)return;let e=!0;const t=registerPasteConsumer(t=>{v.current||__name(async()=>{let n=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n");if(0===n.length){if(!g)return;k.current+=1;try{const e=await detectClipboardText();n=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}finally{k.current-=1}if(!e||!n)return}const r=A(n),o=insertTextAt(C.current,x.current,r);I(o.text,o.cursor)},"applyRoutedPaste")().catch(()=>{})});return()=>{e=!1,t()}},[n,p,g,A,C,x,I]),useInkInputHandler({focus:n,showCursor:o,valueRef:C,cursorRef:x,isHandledByStdin:L,onUpdate:I,onSubmit:a});const{stdout:O}=nt(),D=O?.columns??80,$=getMaskedValue(e,r),N=c?vO[c]:void 0,_=l?N?N(l):l:"",F=getDisplayValue($,t,P,o,n,S,w),U=l?.length??0,j=_+F;if(d){const e=j.replace(/\n/g," ");return null!=u?it.createElement(Ze,{width:u},it.createElement(et,{wrap:"truncate"},e)):it.createElement(et,{wrap:"truncate"},e)}const B=wrapWithIndent(j,D,U);return it.createElement(et,{wrap:"wrap"},B)}__name(TextInput,"TextInput"),Vt();var kO=__name(({children:e})=>it.createElement(et,{italic:!0,color:LR.DIM},e),"HintText"),CO=__name(({children:e})=>it.createElement(et,{bold:!0},e),"HintKey"),bO=__name(({hints:e,marginTop:t=1})=>{const n=e.filter(e=>null!=e&&!1!==e&&""!==e);return 0===n.length?null:it.createElement(Ze,{marginTop:t},it.createElement(kO,null,n.map((e,t)=>it.createElement(it.Fragment,{key:t},t>0&&" · ",e))))},"HintBar");Vt();var EO=OR,TO=LR.DIM,PO=LR.DIMMER,MO=OR,xO=LR.WHITE,IO=LR.GRAY,AO=LR.GREEN;function hasContent(e){return null!=e&&""!==e}__name(hasContent,"hasContent");var RO=__name(({title:e,titleSuffix:t,subtitle:n,children:r,hint:o,footer:s,rule:a=!0,titleColor:i=EO,ruleColor:l=PO,gapAfterHeader:c=!0,boxProps:d})=>{const u=hasContent(n);return it.createElement(Ze,{flexDirection:"column",width:"100%",...d},a&&it.createElement(iL,{dividerColor:l}),it.createElement(Ze,null,it.createElement(et,{bold:!0,color:i},e),hasContent(t)&&it.createElement(et,{color:TO},t)),u?it.createElement(Ze,{marginBottom:c?1:0},it.createElement(et,{color:TO},n)):c&&it.createElement(Ze,{marginBottom:1}),r,s?it.createElement(Ze,{marginTop:1},s):o?it.createElement(Ze,{marginTop:1},it.createElement(et,{italic:!0,color:TO},o)):null)},"Overlay"),LO=it.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 it.createElement(it.Fragment,null,s&&it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?LR.YELLOW:LR.GRAY,paddingX:1},it.createElement(et,{color:LR.DIM},"API Key: "),it.createElement(Ze,{flexGrow:1},it.createElement(TextInput,{value:n,onChange:r,onSubmit:o,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},getCommandAuthHelpText(e))),a&&it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(et,{color:LR.DIM},getCommandAuthUrlLabel(e)),it.createElement(yL,{url:t,text:t,color:LR.CYAN,dimColor:!0}))),"validating"===e&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"invalid_key"===e)&&it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"ctrl+c to cancel")))});LO.displayName="AuthInputSection";var OO=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s})=>{const a=__name(()=>"waiting_browser"===e?it.createElement(bt,{type:"dots"}):"browser_success"===e||"success"===e?it.createElement(et,{color:LR.GREEN},ft.tick):"denied"===e||"invalid_key"===e?it.createElement(et,{color:LR.RED},ft.cross):"manual_entry"===e?it.createElement(et,{color:LR.YELLOW},ft.arrowDown):"error"===e?it.createElement(et,{color:LR.RED},ft.warning):it.createElement(bt,{type:"dots"}),"getStatusIcon"),i=__name(()=>getCommandAuthStatusColor(e),"getStatusColor");return"browser_success"===e||"success"===e||"denied"===e?null:it.createElement(RO,{title:"Sign in to Command Code"},it.createElement(Ze,{marginBottom:1},it.createElement(Ze,{marginRight:1},a()),it.createElement(et,{color:i()},t)),it.createElement(LO,{authState:e,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s}))},"AuthFlowUI"),DO=__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 ot((e,t)=>{t.ctrl&&"c"===e&&i()}),it.createElement(OO,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a})},"LoginWithApiKey");Vt(),PR();var $O=getPackageJson(import.meta.url),NO="string"==typeof $O.version&&$O.version.trim()?$O.version:"unknown";function createApiClient(e){return createCommandApiClient({baseUrl:e.baseUrl,timeout:e.timeout,cliVersion:NO,deps:{getAuthKey:getAuthKey,getTraceId:getTraceId,getTelemetryEnv:getTelemetryEnv,trackApiCallStart:trackAPICallStart,cmdZdrEnabled:__name(()=>"1"===process.env.CMD_ZDR,"cmdZdrEnabled"),deepseekInternalEnabled:__name(()=>"1"===process.env.CMD_PROVIDER_DEEPSEEK_INTERNAL,"deepseekInternalEnabled")}})}function getAuthKey(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function isJevFree(e=Date.now()){return e<=Date.parse("2026-09-24T23:59:59Z")}function isLingFlashFreeEnded(e=new Date){return e.getTime()>=Date.parse("2026-08-03T13:00:00Z")}__name(createApiClient,"createApiClient"),__name(getAuthKey,"getAuthKey"),Vt(),PR(),Vt(),Vt(),__name(isJevFree,"isJevFree"),Vt(),__name(isLingFlashFreeEnded,"isLingFlashFreeEnded"),Vt();var _O={GENERATE:"/alpha/agent/generate"},FO={RECORD:"/alpha/fingerprint/record"},UO={START:"/alpha/sandbox/start",SESSIONS:"/alpha/sandbox/sessions"},jO={CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",APPEND:"/alpha/share/append"},BO={CREATE:"/alpha/devrel-thread/create",DELETE:"/alpha/devrel-thread/delete",UPDATE:"/alpha/devrel-thread/update"},WO={GET:"/alpha/taste/:projectSlug",UPDATE:"/alpha/taste/:projectSlug/update",DELETE:"/alpha/taste/:projectSlug",LEARN:"/alpha/learn"},HO={CREDITS:"/alpha/billing/credits",SUBSCRIPTIONS:"/alpha/billing/subscriptions"},GO={SUMMARY:"/alpha/usage/summary"},VO={TRACK:"/alpha/lifecycle-events"},zO={GET:/\/internal\/orgs\/[a-zA-Z0-9_-]+/,FOLLOW:/\/internal\/orgs\/[a-zA-Z0-9-]+\/follow/,FOLLOWERS:/\/internal\/orgs\/[a-zA-Z0-9-]+\/followers/},KO={FOLLOW:/\/internal\/users\/[a-zA-Z0-9-]+\/follow/,FOLLOWERS:/\/internal\/users\/[a-zA-Z0-9-]+\/followers/,FOLLOWING:/\/internal\/users\/[a-zA-Z0-9-]+\/following/},qO={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/}),_O.GENERATE,FO.RECORD,UO.START,UO.SESSIONS,jO.CREATE,jO.DELETE,jO.APPEND,BO.CREATE,BO.DELETE,BO.UPDATE,WO.LEARN,WO.DELETE,WO.GET,WO.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"}),HO.CREDITS,HO.SUBSCRIPTIONS,GO.SUMMARY,VO.TRACK,Object.values(zO),Object.values(KO),Object.values(qO.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 YO="anthropic",QO="openai",JO="baseten",XO="vercel-ai-gateway",ZO="cloudflare-ai-gateway",eD="cmd-ai",tD="openrouter",nD="alibaba",rD="alibaba-intl",oD="novita",sD="morph",aD="wafer",iD="longcat",lD="tencent",cD="terminal",dD=XO,uD={[YO]:[{id:"anthropic:claude-sonnet-5-5",provider:"Anthropic",category:"opensource",promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:4,cacheHitCost:.2},{id:"anthropic:claude-sonnet-5",provider:"Anthropic",category:"premium",promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:4,cacheHitCost:.2},{id:"anthropic:claude-sonnet-4-20250514",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-sonnet-4-5-20250929",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-opus-4-5-20251101",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-sonnet-4-6",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-fable-5-1",provider:"Anthropic",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:20,cacheHitCost:.25},{id:"anthropic:claude-fable-5",provider:"Anthropic",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:20,cacheHitCost:1},{id:"anthropic:claude-opus-5-5",provider:"Anthropic",category:"premium",promptCost:4,completionCost:20,cacheWrite5mCost:5,cacheWrite1hCost:8,cacheHitCost:.2},{id:"anthropic:claude-opus-5",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-8",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-7",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-6",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-haiku-4-5-20251001",provider:"Anthropic",category:"premium",promptCost:1,completionCost:5,cacheWrite5mCost:1.25,cacheWrite1hCost:2,cacheHitCost:.1}],[QO]:[{id:"openai:gpt-6-astra",provider:"OpenAI",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:0,cacheHitCost:1,contextTiers:[{maxInputTokens:272e3,promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:0,cacheHitCost:1},{promptCost:20,completionCost:75,cacheWrite5mCost:25,cacheWrite1hCost:0,cacheHitCost:2}]},{id:"openai:gpt-6.1-sol",provider:"OpenAI",category:"premium",promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.1,contextTiers:[{maxInputTokens:272e3,promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.1},{promptCost:4,completionCost:15,cacheWrite5mCost:5,cacheWrite1hCost:0,cacheHitCost:.2}]},{id:"openai:gpt-6-sol",provider:"OpenAI",category:"premium",promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.2,contextTiers:[{maxInputTokens:272e3,promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.2},{promptCost:4,completionCost:15,cacheWrite5mCost:5,cacheWrite1hCost:0,cacheHitCost:.4}]},{id:"openai:gpt-6-luna",provider:"OpenAI",category:"opensource",promptCost:.1,completionCost:.5,cacheWrite5mCost:.125,cacheWrite1hCost:0,cacheHitCost:.01,contextTiers:[{maxInputTokens:272e3,promptCost:.1,completionCost:.5,cacheWrite5mCost:.125,cacheWrite1hCost:0,cacheHitCost:.01},{promptCost:.2,completionCost:.75,cacheWrite5mCost:.25,cacheWrite1hCost:0,cacheHitCost:.02}]},{id:"openai:gpt-5.5",provider:"OpenAI",category:"premium",promptCost:5,completionCost:30,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.4",provider:"OpenAI",category:"premium",promptCost:2.5,completionCost:15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.25},{id:"openai:gpt-5.3-codex",provider:"OpenAI",category:"premium",promptCost:2,completionCost:8,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.4-mini",provider:"OpenAI",category:"premium",promptCost:.75,completionCost:4.5,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.075},{id:"openai:gpt-5.6-sol",provider:"OpenAI",category:"premium",promptCost:5,completionCost:30,cacheWrite5mCost:6.25,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.6-terra",provider:"OpenAI",category:"premium",promptCost:2,completionCost:12,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.2},{id:"openai:gpt-5.6-luna",provider:"OpenAI",category:"premium",promptCost:.2,completionCost:1.2,cacheWrite5mCost:.25,cacheWrite1hCost:0,cacheHitCost:.02}],[JO]:[{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}],[oD]:[{id:"novita:moonshotai/Kimi-K3",provider:"Novita",category:"opensource",promptCost:3,completionCost:15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.3},{id:"novita:zai-org/GLM-5.3",provider:"Novita",category:"opensource",promptCost:1.4,completionCost:4.4,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.26},{id:"novita:deepseek/deepseek-v4.1-flash",provider:"Novita",category:"opensource",promptCost:.15,completionCost:.6,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.003},{id:"novita:deepseek/deepseek-v4-flash",provider:"Novita",category:"opensource",promptCost:.15,completionCost:.6,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.003},{id:"novita:z-ai/glm-5.3-flash",provider:"Novita",category:"opensource",promptCost:.15,completionCost:.5,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.03},{id:"novita:inclusionai/ling-3.1-flash:free",provider:"Novita",category:"opensource",promptCost:0,completionCost:0,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0}],[XO]:[],[tD]:[]};Se.enum(["owner","admin","member"]);var mD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,pD="chatComplete",gD="responses",hD="MiniMaxAI/MiniMax-M3-Free",fD={SONNET_5_5:{id:"claude-sonnet-5-5",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Sonnet 5.5",name:"Claude Sonnet 5.5",description:"best combo of speed & intelligence (recommended)",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},SONNET_5:{id:"claude-sonnet-5",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Sonnet 5",name:"Claude Sonnet 5",description:"prev Sonnet, still fast & capable",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},SONNET_4_6:{id:"claude-sonnet-4-6",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Sonnet 4.6",name:"Claude Sonnet 4.6",description:"older Sonnet, still fast & capable",reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},FABLE_5_1:{id:"claude-fable-5-1",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Fable 5.1",name:"Claude Fable 5.1",description:"most capable for demanding reasoning & long-horizon agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},FABLE_5:{id:"claude-fable-5",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Fable 5",name:"Claude Fable 5",description:"prev Fable, still strong for deep reasoning & agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_5_5:{id:"claude-opus-5-5",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Opus 5.5",name:"Claude Opus 5.5",description:"most intelligent Opus for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_5:{id:"claude-opus-5",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Opus 5",name:"Claude Opus 5",description:"prev flagship, still strong for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_4_8:{id:"claude-opus-4-8",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Opus 4.8",name:"Claude Opus 4.8",description:"older Opus, still strong for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_4_7:{id:"claude-opus-4-7",inputModalities:["text","image"],provider:YO,spec:pD,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:YO,spec:pD,label:"Claude Haiku 4.5",name:"Claude Haiku 4.5",description:"fastest & most compact, great for quick tasks",contextWindow:2e5},GPT_6_ASTRA:{id:"gpt-6-astra",inputModalities:["text","image"],provider:QO,spec:gD,label:"GPT-6 Astra",name:"GPT-6 Astra",description:"most capable OpenAI model for demanding reasoning & agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_6_1_SOL:{id:"gpt-6.1-sol",inputModalities:["text","image"],provider:QO,spec:gD,label:"GPT-6.1 Sol",name:"GPT-6.1 Sol",description:"near-Astra performance for complex work at a lower cost",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_6_SOL:{id:"gpt-6-sol",inputModalities:["text","image"],provider:QO,spec:gD,label:"GPT-6 Sol",name:"GPT-6 Sol",description:"built for complex coding & agentic workflows",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_6_LUNA:{id:"gpt-6-luna",inputModalities:["text","image"],provider:QO,spec:gD,label:"GPT-6 Luna",name:"GPT-6 Luna",description:"most efficient OpenAI model for focused, high-volume tasks",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_5_6_SOL:{id:"gpt-5.6-sol",inputModalities:["text","image"],provider:XO,spec:gD,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:XO,spec:gD,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:XO,spec:gD,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:QO,spec:gD,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:QO,spec:gD,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:QO,spec:gD,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:QO,spec:gD,label:"GPT-5.4 Mini",name:"GPT-5.4 Mini",description:"fast, cost-effective model for everyday tasks",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:4e5},MINIMAX_M3_PROMO_FREE:{id:hD,inputModalities:["text","image"],provider:dD,spec:pD,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",badge:"free",hidden:!0,reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},DEEPSEEK_V4_PRO:{id:"deepseek/deepseek-v4-pro",inputModalities:["text"],provider:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,label:"DeepSeek V4 Flash Vision (exp)",name:"DeepSeek V4 Flash Vision (exp)",description:"fast hybrid-attention reasoning with vision",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},DEEPSEEK_V4_FLASH_FAST:{id:"deepseek/deepseek-v4-flash-fast",inputModalities:["text"],provider:dD,spec:pD,label:"DeepSeek V4 Flash Fast",name:"DeepSeek V4 Flash Fast",description:"low-latency V4 Flash deployment",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},DEEPSEEK_V4_1_FLASH:{id:"deepseek/deepseek-v4.1-flash",inputModalities:["text","image"],provider:dD,spec:pD,label:"DeepSeek V4.1 Flash",name:"DeepSeek V4.1 Flash",description:"V4.1 hybrid-attention reasoning with vision",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},DEEPSEEK_V4_1_FLASH_FAST:{id:"deepseek/deepseek-v4.1-flash-fast",inputModalities:["text","image"],provider:dD,spec:pD,label:"DeepSeek V4.1 Flash Fast",name:"DeepSeek V4.1 Flash Fast",description:"High throughput V4.1 Flash",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},KIMI_K3:{id:"moonshotai/Kimi-K3",inputModalities:["text","image"],provider:dD,spec:pD,label:"Kimi K3",name:"Kimi K3",description:"long-horizon coding & knowledge work with 1M context",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},KIMI_K2_7_CODE:{id:"moonshotai/Kimi-K2.7-Code",inputModalities:["text","image"],provider:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,label:"Kimi K2.5",name:"Kimi K2.5",description:"multimodal frontend coding",contextWindow:256e3},GLM_5_3_FLASH:{id:"z-ai/glm-5.3-flash",inputModalities:["text","image"],provider:dD,spec:pD,label:"GLM-5.3 Flash",name:"GLM-5.3 Flash",description:"fast, affordable GLM coding with 1M context",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1048576,maxOutputTokens:131072},GLM_5_3_FLASHX:{id:"z-ai/glm-5.3-flashx",inputModalities:["text","image"],provider:dD,spec:pD,label:"GLM-5.3 FlashX",name:"GLM-5.3 FlashX",description:"high-speed GLM-5.3 Flash with 1M context",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6,maxOutputTokens:131072},GLM_5_3:{id:"zai-org/GLM-5.3",inputModalities:["text"],provider:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,label:"GLM-5.1",name:"GLM-5.1",description:"long-horizon autonomous coding agent"},GLM_5:{id:"zai-org/GLM-5",inputModalities:["text"],provider:dD,spec:pD,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:dD,spec:pD,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},MINIMAX_M2_7:{id:"MiniMaxAI/MiniMax-M2.7",inputModalities:["text"],provider:dD,spec:pD,label:"MiniMax M2.7",name:"MiniMax M2.7",description:"end-to-end software engineering agent"},MINIMAX_M3_FREE:{id:"minimax/minimax-m3-free",inputModalities:["text","image"],provider:dD,spec:pD,label:"MiniMax M3",name:"MiniMax M3 (Free)",description:"frontier coding, agents & native multimodality",badge:"free",hidden:!0,reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},MINIMAX_M2_7_FREE:{id:"minimax/minimax-m2.7-free",inputModalities:["text"],provider:dD,spec:pD,label:"MiniMax M2.7",name:"MiniMax M2.7 (Free)",description:"end-to-end software engineering agent",badge:"free",hidden:!0,contextWindow:197e3},MINIMAX_M2_5:{id:"MiniMaxAI/MiniMax-M2.5",inputModalities:["text"],provider:dD,spec:pD,label:"MiniMax M2.5",name:"MiniMax M2.5",description:"cross-platform full-stack agentic dev",contextWindow:2e5},XIAOMI_MIMO_V2_6_PRO:{id:"xiaomi/mimo-v2.6-pro",inputModalities:["text","image"],provider:dD,spec:pD,label:"MiMo V2.6 Pro",name:"MiMo V2.6 Pro",description:"flagship multimodal agentic coding with 1M context",contextWindow:1048576},XIAOMI_MIMO_V2_6_PRO_ULTRASPEED:{id:"xiaomi/mimo-v2.6-pro-ultraspeed",inputModalities:["text","image"],provider:dD,spec:pD,label:"MiMo V2.6 Pro UltraSpeed",name:"MiMo V2.6 Pro UltraSpeed",description:"low-latency serving tier of MiMo V2.6 Pro",contextWindow:1048576},XIAOMI_MIMO_V2_6_FLASH:{id:"xiaomi/mimo-v2.6-flash",inputModalities:["text","image"],provider:dD,spec:pD,label:"MiMo V2.6 Flash",name:"MiMo V2.6 Flash",description:"efficient multimodal agentic coding with 1M context",contextWindow:1048576},XIAOMI_MIMO_V2_5_PRO:{id:"xiaomi/mimo-v2.5-pro",inputModalities:["text"],provider:dD,spec:pD,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:dD,spec:pD,label:"MiMo V2.5",name:"MiMo V2.5",description:"efficient long-context agentic coding",contextWindow:1e6},QWEN_3_8_OMNI_FLASH:{id:"Qwen/Qwen3.8-Omni-Flash",inputModalities:["text","image"],provider:dD,spec:pD,label:"Qwen 3.8 Omni Flash",name:"Qwen 3.8 Omni Flash",description:"omni-modal understanding & multimedia agentic work",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6,maxOutputTokens:131072},QWEN_3_8_MAX_0902:{id:"Qwen/Qwen3.8-Max-0902",inputModalities:["text","image"],provider:dD,spec:pD,label:"Qwen 3.8 Max 0902",name:"Qwen 3.8 Max 0902",description:"upgraded Qwen 3.8 Max: stronger coding & agentic tool use",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6},QWEN_3_8_MAX:{id:"Qwen/Qwen3.8-Max",inputModalities:["text","image"],provider:dD,spec:pD,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:dD,spec:pD,label:"Qwen 3.8 27B",name:"Qwen 3.8 27B",description:"compact vision-language coding & agentic work",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:262144,maxOutputTokens:32768},QWEN_3_8_FLASH:{id:"Qwen/Qwen3.8-Flash",inputModalities:["text","image"],provider:dD,spec:pD,label:"Qwen 3.8 Flash",name:"Qwen 3.8 Flash",description:"fast low-cost agentic coding & reasoning",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6},QWEN_3_7_MAX:{id:"Qwen/Qwen3.7-Max",inputModalities:["text"],provider:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,label:"Qwen 3.6 Plus",name:"Qwen 3.6 Plus",description:"agentic coding & reasoning",reasoning:!0},LONGCAT_2:{id:"meituan/LongCat-2.0",inputModalities:["text"],provider:dD,spec:pD,label:"LongCat 2.0",name:"LongCat 2.0",description:"trillion-parameter agentic coding with 1M context",reasoning:!0,contextWindow:1048576},LONGCAT_2_FREE:{id:"meituan/LongCat-2.0:free",inputModalities:["text"],provider:dD,spec:pD,label:"LongCat 2.0",name:"LongCat 2.0 (Free)",description:"trillion-parameter agentic coding with 1M context",badge:"free",hidden:!0,reasoning:!0,contextWindow:1048576},STEP_5_PREVIEW:{id:"stepfun/Step-5-Preview",inputModalities:["text","image"],provider:dD,spec:pD,label:"Step 5 Preview",name:"Step 5 Preview",description:"600B sparse-MoE agentic coding with 1M context",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},STEP_3_7_FLASH:{id:"stepfun/Step-3.7-Flash",inputModalities:["text","image"],provider:dD,spec:pD,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:dD,spec:pD,label:"Step 3.5 Flash",name:"Step 3.5 Flash",description:"fast sparse-MoE agentic reasoning",reasoning:!0,contextWindow:262144},TENCENT_HY3:{id:"tencent/Hy3",inputModalities:["text"],provider:dD,spec:pD,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:dD,spec:pD,label:"Tencent Hy3",name:"Tencent Hy3",description:"sparse-MoE reasoning & agentic tool use",reasoning:!0,contextWindow:262144},TENCENT_HY4_PREVIEW:{id:"tencent/hy4-preview",inputModalities:["text"],provider:dD,spec:pD,label:"Tencent Hy4 Preview",name:"Tencent Hy4 Preview",description:"agentic coding & sustained multi-step tool use",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1048576},GEMINI_3_8_FLASH:{id:"google/gemini-3.8-flash",inputModalities:["text","image"],provider:XO,spec:pD,label:"Gemini 3.8 Flash",name:"Gemini 3.8 Flash",description:"newest Gemini Flash, improved core reasoning",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},GEMINI_3_7_FLASH:{id:"google/gemini-3.7-flash",inputModalities:["text","image"],provider:tD,spec:pD,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:XO,spec:pD,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:XO,spec:pD,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:XO,spec:pD,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:XO,spec:pD,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:XO,spec:pD,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:dD,spec:pD,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:dD,spec:pD,label:"Inkling",name:"Inkling",description:"multimodal MoE reasoning",reasoning:!0,contextWindow:256e3},INKLING_SMALL:{id:"thinkingmachines/inkling-small",inputModalities:["text","image"],provider:dD,spec:pD,label:"Inkling Small",name:"Inkling Small",description:"lightweight MoE reasoning at lower cost and latency",reasoning:!0,contextWindow:1e6},SPACE_BUNNY_ALPHA:{id:"stealth/space-bunny-alpha",inputModalities:["text","image"],provider:tD,spec:pD,label:"Space Bunny Alpha",name:"Space Bunny Alpha",description:"stealth model with 1M context",vendorLabel:"Stealth",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6,maxOutputTokens:524288},PIXEL_CANARY:{id:"stealth/pixel-canary",inputModalities:["text","image"],provider:dD,spec:pD,label:"Pixel Canary",name:"Pixel Canary",description:"stealth coding model for web and mobile apps",vendorLabel:"Stealth",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:262144,maxOutputTokens:131072},LAGUNA_S_2_1_FREE:{id:"poolside/laguna-s-2.1-free",inputModalities:["text"],provider:dD,spec:pD,label:"Laguna S 2.1",name:"Laguna S 2.1",description:"open-weight agentic coding and long-horizon work",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods",reasoning:!0,contextWindow:256e3,maxOutputTokens:32768},LING_3_0_FLASH_FREE:{id:"inclusionai/ling-3.0-flash-free",inputModalities:["text"],provider:dD,spec:pD,label:"Ling 3.0 Flash",name:"Ling 3.0 Flash",description:"fast lightweight-MoE coding & agentic work",badge:"free",reasoning:!0,get hidden(){return isLingFlashFreeEnded()},contextWindow:256e3,maxOutputTokens:32768},LING_3_0_FLASH_SANTE_FREE:{id:"inclusionai/ling-3.0-flash-sante:free",inputModalities:["text"],provider:dD,spec:pD,label:"Ling 3.0 Flash Sante",name:"Ling 3.0 Flash Sante",description:"health & medicine tuned lightweight-MoE, still strong on code",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods. 100 requests a day per account",reasoning:!0,contextWindow:262144,maxOutputTokens:32768},LING_3_1_FLASH_FREE:{id:"inclusionai/ling-3.1-flash:free",inputModalities:["text"],provider:dD,spec:pD,label:"Ling 3.1 Flash",name:"Ling 3.1 Flash",description:"hybrid-reasoning MoE for coding & tool-using agents",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods. 100 requests a day per account",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:262144,maxOutputTokens:32768},MUSE_SPARK_1_1:{id:"meta/muse-spark-1.1",inputModalities:["text","image"],provider:XO,spec:pD,label:"Muse Spark 1.1",name:"Muse Spark 1.1",description:"agentic performance, tool use, and computer use",vendorLabel:"Meta",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},MUSE_SPARK_1_2:{id:"meta/muse-spark-1.2",inputModalities:["text","image"],provider:XO,spec:pD,label:"Muse Spark 1.2",name:"Muse Spark 1.2",description:"coding-optimized for agentic workflows and large codebases",vendorLabel:"Meta",notice:"{name} is going through upstream inference issues at {vendor}, not Command Code. Expect slower responses and occasional rate limits.",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},MUSE_SPARK_1_2_CONTRIBUTOR:{id:"meta/muse-spark-1.2-contributor",inputModalities:["text","image"],provider:XO,spec:pD,label:"Muse Spark 1.2 Contributor",name:"Muse Spark 1.2 Contributor",description:"Muse Spark 1.2 at ~95% off",vendorLabel:"Meta",notice:"{name} is going through upstream inference issues at {vendor}, not Command Code. Expect slower responses and occasional rate limits.",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},MUSE_SPARK_1_3:{id:"meta/muse-spark-1.3",inputModalities:["text","image"],provider:XO,spec:pD,label:"Muse Spark 1.3",name:"Muse Spark 1.3",description:"multimodal reasoning for long-horizon agentic and coding workflows",vendorLabel:"Meta",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1048576},MUSE_SPARK_1_3_CONTRIBUTOR:{id:"meta/muse-spark-1.3-contributor",inputModalities:["text","image"],provider:XO,spec:pD,label:"Muse Spark 1.3 Contributor",name:"Muse Spark 1.3 Contributor",description:"Muse Spark 1.3 at up to 95% off",vendorLabel:"Meta",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},GROK_4_5:{id:"xai/grok-4.5",inputModalities:["text","image"],provider:XO,spec:pD,label:"Grok 4.5",name:"Grok 4.5",description:"smartest model for coding, agentic tasks, knowledge work",vendorLabel:"xAI",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:5e5},GROK_4_6:{id:"xai/grok-4.6",inputModalities:["text","image"],provider:XO,spec:pD,label:"Grok 4.6",name:"Grok 4.6",description:"frontier performance on coding, knowledge work, and STEM",vendorLabel:"xAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:5e5},GROK_4_7:{id:"xai/grok-4.7",inputModalities:["text","image"],provider:XO,spec:pD,label:"Grok 4.7",name:"Grok 4.7",description:"coding and knowledge work, built for multi-hour tasks",vendorLabel:"xAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:5e5}},yD=[{canonicalId:"zai-org/GLM-5",providers:{[XO]:"zai/glm-5",[JO]:"zai-org/GLM-5"}},{canonicalId:"zai-org/GLM-5.3",providers:{[oD]:"zai-org/glm-5.3",[XO]:"zai/glm-5.3"}},{canonicalId:"zai-org/GLM-5.2",providers:{[nD]:"glm-5.2",[XO]:"zai/glm-5.2"}},{canonicalId:"poolside/laguna-s-2.1-free",providers:{[XO]:"poolside/laguna-s-2.1-free"}},{canonicalId:"inclusionai/ling-3.0-flash-free",providers:{[XO]:"inclusionai/ling-3.0-flash-free"}},{canonicalId:"inclusionai/ling-3.0-flash-sante:free",providers:{[tD]:"inclusionai/ling-3.0-flash-sante:free"}},{canonicalId:"inclusionai/ling-3.1-flash:free",providers:{[oD]:"inclusionai/ling-3.1-flash"}},{canonicalId:"zai-org/GLM-5.2-Fast",providers:{[XO]:"zai/glm-5.2-fast"}},{canonicalId:"zai-org/GLM-5.1",providers:{[XO]:"zai/glm-5.1"}},{canonicalId:"moonshotai/Kimi-K3",providers:{[oD]:"moonshotai/kimi-k3",[XO]:"moonshotai/kimi-k3"}},{canonicalId:"moonshotai/Kimi-K2.5",providers:{[XO]:"moonshotai/kimi-k2.5",[JO]:"moonshotai/Kimi-K2.5",[ZO]:"workers-ai/@cf/moonshotai/kimi-k2.5"}},{canonicalId:"moonshotai/Kimi-K2.6",providers:{[XO]:"moonshotai/kimi-k2.6",[JO]:"moonshotai/Kimi-K2.6",[ZO]:"workers-ai/@cf/moonshotai/kimi-k2.6"}},{canonicalId:"moonshotai/Kimi-K2.7-Code",providers:{[nD]:"kimi-k2.7-code",[XO]:"moonshotai/kimi-k2.7-code"}},{canonicalId:"moonshotai/Kimi-K2.7-Code-Highspeed",providers:{[XO]:"moonshotai/kimi-k2.7-code-highspeed"}},{canonicalId:"MiniMaxAI/MiniMax-M2.5",providers:{[XO]:"minimax/minimax-m2.5",[JO]:"MiniMaxAI/MiniMax-M2.5"}},{canonicalId:"deepseek/deepseek-v4-pro",providers:{[XO]:"deepseek/deepseek-v4-pro"}},{canonicalId:"deepseek/deepseek-v4-flash",providers:{[XO]:"deepseek/deepseek-v4.1-flash",[oD]:"deepseek/deepseek-v4.1-flash",[sD]:"morph-dsv4flash",[cD]:"deepseek-v4-flash-0731"}},{canonicalId:"deepseek/deepseek-v4-flash-vision-exp",providers:{[XO]:"deepseek/deepseek-v4.1-flash"}},{canonicalId:"deepseek/deepseek-v4.1-flash",providers:{[oD]:"deepseek/deepseek-v4.1-flash",[XO]:"deepseek/deepseek-v4.1-flash"}},{canonicalId:"deepseek/deepseek-v4.1-flash-fast",providers:{[XO]:"deepseek/deepseek-v4.1-flash"}},{canonicalId:"deepseek/deepseek-v4-flash-fast",providers:{[aD]:"DeepSeek-V4-Flash-0731-Fast"}},{canonicalId:"Qwen/Qwen3.6-Max-Preview",providers:{[XO]:"alibaba/qwen-3.6-max-preview"}},{canonicalId:"Qwen/Qwen3.6-Plus",providers:{[nD]:"qwen3.6-plus",[XO]:"alibaba/qwen3.6-plus"}},{canonicalId:"Qwen/Qwen3.7-Max",providers:{[nD]:"qwen3.7-max",[XO]:"alibaba/qwen3.7-max"}},{canonicalId:"Qwen/Qwen3.7-Plus",providers:{[nD]:"qwen3.7-plus",[XO]:"alibaba/qwen3.7-plus"}},{canonicalId:"Qwen/Qwen3.8-Max-0902",providers:{[nD]:"qwen3.8-max-0902"}},{canonicalId:"Qwen/Qwen3.8-Omni-Flash",providers:{[XO]:"alibaba/qwen3.8-omni-flash"}},{canonicalId:"Qwen/Qwen3.8-Max",providers:{[nD]:"qwen3.8-max",[XO]:"alibaba/qwen3.8-max"}},{canonicalId:"Qwen/Qwen3.8-27B",providers:{[XO]:"alibaba/qwen3.8-27b"}},{canonicalId:"Qwen/Qwen3.8-Flash",providers:{[rD]:"qwen3.8-flash"}},{canonicalId:"Qwen/Qwen3.7-Flash",providers:{[XO]:"alibaba/qwen3.7-flash"}},{canonicalId:"MiniMaxAI/MiniMax-M3",providers:{[XO]:"minimax/minimax-m3"}},{canonicalId:hD,providers:{[XO]:"minimax/minimax-m3"}},{canonicalId:"MiniMaxAI/MiniMax-M2.7",providers:{[XO]:"minimax/minimax-m2.7"}},{canonicalId:"meituan/LongCat-2.0",providers:{[iD]:"LongCat-2.0"}},{canonicalId:"stepfun/Step-5-Preview",providers:{[XO]:"stepfun/step-5-preview"}},{canonicalId:"stealth/pixel-canary",providers:{[XO]:"stealth/pixel-canary"}},{canonicalId:"stepfun/Step-3.7-Flash",providers:{[XO]:"stepfun/step-3.7-flash"}},{canonicalId:"stepfun/Step-3.5-Flash",providers:{[XO]:"stepfun/step-3.5-flash",[tD]:"stepfun/step-3.5-flash"}},{canonicalId:"z-ai/glm-5.3-flash",providers:{[oD]:"zai-org/glm-5.3-flash",[XO]:"zai/glm-5.3-flash"}},{canonicalId:"z-ai/glm-5.3-flashx",providers:{[XO]:"zai/glm-5.3-flashx"}},{canonicalId:"gpt-5.6-sol",providers:{[XO]:"openai/gpt-5.6-sol"}},{canonicalId:"gpt-5.6-terra",providers:{[XO]:"openai/gpt-5.6-terra"}},{canonicalId:"gpt-5.6-luna",providers:{[XO]:"openai/gpt-5.6-luna"}},{canonicalId:"stealth/space-bunny-alpha",providers:{[tD]:"stealth/space-bunny-alpha"}},{canonicalId:"tencent/Hy3",providers:{[tD]:"tencent/hy3:free"}},{canonicalId:"tencent/hy3-paid",providers:{[XO]:"tencent/hy3"}},{canonicalId:"tencent/hy4-preview",providers:{[lD]:"hy4-preview"}},{canonicalId:"xiaomi/mimo-v2.6-pro",providers:{[XO]:"xiaomi/mimo-v2.6-pro"}},{canonicalId:"xiaomi/mimo-v2.6-pro-ultraspeed",providers:{[XO]:"xiaomi/mimo-v2.6-pro-ultraspeed"}},{canonicalId:"xiaomi/mimo-v2.6-flash",providers:{[XO]:"xiaomi/mimo-v2.6-flash"}},{canonicalId:"xiaomi/mimo-v2.5-pro",providers:{[XO]:"xiaomi/mimo-v2.5-pro"}},{canonicalId:"xiaomi/mimo-v2.5",providers:{[XO]:"xiaomi/mimo-v2.5"}},{canonicalId:"google/gemini-3.8-flash",providers:{[XO]:"google/gemini-3.8-flash"}},{canonicalId:"google/gemini-3.7-flash",providers:{[tD]:"google/gemini-3.7-flash"}},{canonicalId:"google/gemini-3.6-flash",providers:{[XO]:"google/gemini-3.6-flash"}},{canonicalId:"google/gemini-3.5-flash",providers:{[XO]:"google/gemini-3.5-flash"}},{canonicalId:"google/gemini-3.5-flash-lite",providers:{[XO]:"google/gemini-3.5-flash-lite"}},{canonicalId:"google/gemini-3.1-flash-lite",providers:{[XO]:"google/gemini-3.1-flash-lite"}},{canonicalId:"nvidia/nemotron-3-ultra-550b-a55b",providers:{[XO]:"nvidia/nemotron-3-ultra-550b-a55b"}},{canonicalId:"thinkingmachines/inkling",providers:{[XO]:"thinkingmachines/inkling"}},{canonicalId:"thinkingmachines/inkling-small",providers:{[XO]:"thinkingmachines/inkling-small"}},{canonicalId:"sakana/fugu-ultra",providers:{[XO]:"sakana/fugu-ultra"}},{canonicalId:"xai/grok-4.5",providers:{[XO]:"xai/grok-4.5"}},{canonicalId:"xai/grok-4.6",providers:{[XO]:"xai/grok-4.6"}},{canonicalId:"xai/grok-4.7",providers:{[XO]:"xai/grok-4.7"}},{canonicalId:"meta/muse-spark-1.1",providers:{[XO]:"meta/muse-spark-1.1"}},{canonicalId:"meta/muse-spark-1.2",providers:{[XO]:"meta/muse-spark-1.2"}},{canonicalId:"meta/muse-spark-1.2-contributor",providers:{[XO]:"meta/muse-spark-1.2-contributor"}},{canonicalId:"meta/muse-spark-1.3",providers:{[XO]:"meta/muse-spark-1.3"}},{canonicalId:"meta/muse-spark-1.3-contributor",providers:{[XO]:"meta/muse-spark-1.3-contributor"}}],SD="2026-08-16T16:00:00Z",wD=[{startHourUtc:1,endHourUtc:4},{startHourUtc:6,endHourUtc:10}],vD=[1,2,3,4,5],kD=["2026-09-25","2026-09-26","2026-09-27","2026-10-01","2026-10-02","2026-10-03","2026-10-04","2026-10-05","2026-10-06","2026-10-07"],CD={effectiveFrom:SD,peakWindowsUtc:wD,peakDaysUtc:vD,offPeakDatesUtc:kD,peak:{promptCost:.44,completionCost:1.32,cacheReadCost:.014},offPeak:{promptCost:.22,completionCost:.66,cacheReadCost:.007}},bD=new Set([fD.GLM_5_2_FAST.id,fD.DEEPSEEK_V4_1_FLASH_FAST.id,fD.MINIMAX_M3.id,fD.MINIMAX_M3_FREE.id,fD.STEP_3_7_FLASH.id,fD.STEP_5_PREVIEW.id,fD.PIXEL_CANARY.id,fD.XIAOMI_MIMO_V2_6_PRO.id,fD.XIAOMI_MIMO_V2_6_PRO_ULTRASPEED.id,fD.XIAOMI_MIMO_V2_6_FLASH.id,fD.FUGU_ULTRA.id,fD.GROK_4_5.id,fD.GROK_4_6.id,fD.MUSE_SPARK_1_1.id,fD.MUSE_SPARK_1_2.id,fD.MUSE_SPARK_1_2_CONTRIBUTOR.id,fD.MUSE_SPARK_1_3.id,fD.MUSE_SPARK_1_3_CONTRIBUTOR.id,fD.LAGUNA_S_2_1_FREE.id,fD.QWEN_3_8_MAX_0902.id,fD.LONGCAT_2.id,fD.GLM_5_3_FLASHX.id,fD.SPACE_BUNNY_ALPHA.id]),ED=[{canonicalId:"zai-org/GLM-5",gatewaySlug:"zai/glm-5",order:["deepinfra","fireworks","togetherai","parasail","bedrock"],providers:{deepinfra:{slug:"deepinfra",promptCost:.8,completionCost:2.56,cacheReadCost:.16},fireworks:{slug:"fireworks",promptCost:1,completionCost:3.2,cacheReadCost:.2},togetherai:{slug:"togetherai",promptCost:1,completionCost:3.2,cacheReadCost:0},parasail:{slug:"parasail",promptCost:1,completionCost:3.2,cacheReadCost:0},bedrock:{slug:"bedrock",promptCost:1,completionCost:3.2,cacheReadCost:0}}},{canonicalId:"zai-org/GLM-5.2",gatewaySlug:"zai/glm-5.2",order:["novita","deepinfra"],providers:{novita:{slug:"novita",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},deepinfra:{slug:"deepinfra",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},zai:{slug:"zai",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},fireworks:{slug:"fireworks",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{canonicalId:"zai-org/GLM-5.3",gatewaySlug:"zai/glm-5.3",order:["digitalocean"],providers:{digitalocean:{slug:"digitalocean",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{canonicalId:"z-ai/glm-5.3-flash",gatewaySlug:"zai/glm-5.3-flash",order:["zai"],providers:{zai:{slug:"zai",promptCost:.15,completionCost:.5,cacheReadCost:.03}}},{canonicalId:"z-ai/glm-5.3-flashx",gatewaySlug:"zai/glm-5.3-flashx",order:["zai"],providers:{zai:{slug:"zai",promptCost:.37,completionCost:1.25,cacheReadCost:.075}}},{canonicalId:"zai-org/GLM-5.2-Fast",gatewaySlug:"zai/glm-5.2-fast",order:["wafer"],providers:{wafer:{slug:"wafer",promptCost:3,completionCost:10.25,cacheReadCost:.5}}},{canonicalId:"zai-org/GLM-5.1",gatewaySlug:"zai/glm-5.1",order:["deepinfra","fireworks"],providers:{deepinfra:{slug:"deepinfra",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},fireworks:{slug:"fireworks",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{canonicalId:"moonshotai/Kimi-K3",gatewaySlug:"moonshotai/kimi-k3",order:["moonshotai"],providers:{moonshotai:{slug:"moonshotai",promptCost:3,completionCost:15,cacheReadCost:.3}}},{canonicalId:"moonshotai/Kimi-K2.5",gatewaySlug:"moonshotai/kimi-k2.5",order:["moonshotai","fireworks","bedrock","togetherai"],providers:{fireworks:{slug:"fireworks",promptCost:.6,completionCost:3,cacheReadCost:.1},bedrock:{slug:"bedrock",promptCost:.6,completionCost:3,cacheReadCost:.1},togetherai:{slug:"togetherai",promptCost:.5,completionCost:2.8,cacheReadCost:0},moonshotai:{slug:"moonshotai",promptCost:.6,completionCost:3,cacheReadCost:.1}}},{canonicalId:"moonshotai/Kimi-K2.6",gatewaySlug:"moonshotai/kimi-k2.6",order:["moonshotai","fireworks"],providers:{moonshotai:{slug:"moonshotai",promptCost:.95,completionCost:4,cacheReadCost:.16},fireworks:{slug:"fireworks",promptCost:.95,completionCost:4,cacheReadCost:.16}}},{canonicalId:"moonshotai/Kimi-K2.7-Code",gatewaySlug:"moonshotai/kimi-k2.7-code",order:["moonshotai"],providers:{moonshotai:{slug:"moonshotai",promptCost:.95,completionCost:4,cacheReadCost:.19}}},{canonicalId:"moonshotai/Kimi-K2.7-Code-Highspeed",gatewaySlug:"moonshotai/kimi-k2.7-code-highspeed",order:["moonshotai"],providers:{moonshotai:{slug:"moonshotai",promptCost:1.9,completionCost:8,cacheReadCost:.38}}},{canonicalId:"MiniMaxAI/MiniMax-M2.5",gatewaySlug:"minimax/minimax-m2.5",order:["deepinfra","parasail","nebius","bedrock"],providers:{deepinfra:{slug:"deepinfra",promptCost:.3,completionCost:1.2,cacheReadCost:.03},parasail:{slug:"parasail",promptCost:.3,completionCost:1.2,cacheReadCost:0},nebius:{slug:"nebius",promptCost:.3,completionCost:1.2,cacheReadCost:0},bedrock:{slug:"bedrock",promptCost:.3,completionCost:1.2,cacheReadCost:0}}},{canonicalId:"deepseek/deepseek-v4-pro",gatewaySlug:"deepseek/deepseek-v4-pro",order:["deepseek"],providers:{deepseek:{slug:"deepseek",promptCost:.435,completionCost:.87,cacheReadCost:.003625,timeOfDay:{effectiveFrom:SD,peakWindowsUtc:wD,peakDaysUtc:vD,offPeakDatesUtc:kD,peak:{promptCost:1.32,completionCost:3.96,cacheReadCost:.044},offPeak:{promptCost:.66,completionCost:1.98,cacheReadCost:.022}}},fireworks:{slug:"fireworks",promptCost:1.74,completionCost:3.48,cacheReadCost:.0145}}},{canonicalId:"deepseek/deepseek-v4-flash",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],zdr:{gatewaySlug:"deepseek/deepseek-v4-flash",only:["baseten","fireworks","deepinfra"]},providers:{deepseek:{slug:"deepseek",promptCost:.14,completionCost:.28,cacheReadCost:.0028,timeOfDay:{effectiveFrom:SD,peakWindowsUtc:wD,peakDaysUtc:vD,offPeakDatesUtc:kD,peak:{promptCost:.3,completionCost:1.2,cacheReadCost:.006},offPeak:{promptCost:.15,completionCost:.6,cacheReadCost:.003}}},baseten:{slug:"baseten",promptCost:.13,completionCost:.26,cacheReadCost:.028},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007},deepinfra:{slug:"deepinfra",promptCost:.08,completionCost:.18,cacheReadCost:.016}}},{canonicalId:"deepseek/deepseek-v4-flash-vision-exp",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],zdr:{gatewaySlug:"deepseek/deepseek-v4.1-flash",only:["fireworks","deepinfra"]},providers:{deepseek:{slug:"deepseek",promptCost:.15,completionCost:.6,cacheReadCost:.003,timeOfDay:{effectiveFrom:SD,peakWindowsUtc:wD,peakDaysUtc:vD,offPeakDatesUtc:kD,peak:{promptCost:.3,completionCost:1.2,cacheReadCost:.006},offPeak:{promptCost:.15,completionCost:.6,cacheReadCost:.003}}},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007},deepinfra:{slug:"deepinfra",promptCost:.2,completionCost:.6,cacheReadCost:.006}}},{canonicalId:"deepseek/deepseek-v4.1-flash",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],providers:{deepseek:{slug:"deepseek",promptCost:.15,completionCost:.6,cacheReadCost:.003,timeOfDay:{effectiveFrom:SD,peakWindowsUtc:wD,peakDaysUtc:vD,offPeakDatesUtc:kD,peak:{promptCost:.3,completionCost:1.2,cacheReadCost:.006},offPeak:{promptCost:.15,completionCost:.6,cacheReadCost:.003}}},novita:{slug:"novita",promptCost:.3,completionCost:1.2,cacheReadCost:.006},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007},deepinfra:{slug:"deepinfra",promptCost:.2,completionCost:.6,cacheReadCost:.006},morph:{slug:"morph",promptCost:.3,completionCost:1.2,cacheReadCost:.03},baseten:{slug:"baseten",promptCost:.3,completionCost:1.2,cacheReadCost:.03},wafer:{slug:"wafer",promptCost:.3,completionCost:1.2,cacheReadCost:.01},modal:{slug:"modal",promptCost:.3,completionCost:1.2,cacheReadCost:.03}}},{canonicalId:"deepseek/deepseek-v4.1-flash-fast",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],zdr:{gatewaySlug:"deepseek/deepseek-v4.1-flash",only:["deepseek"]},providers:{deepseek:{slug:"deepseek",promptCost:.16,completionCost:.58,cacheReadCost:.016,timeOfDay:{effectiveFrom:SD,peakWindowsUtc:wD,peakDaysUtc:vD,offPeakDatesUtc:kD,peak:{promptCost:.32,completionCost:1.16,cacheReadCost:.032},offPeak:{promptCost:.16,completionCost:.58,cacheReadCost:.016}}},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007}}},{canonicalId:"Qwen/Qwen3.6-Max-Preview",gatewaySlug:"alibaba/qwen-3.6-max-preview",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:1.3,completionCost:7.8,cacheReadCost:.26,cacheWriteCost:1.63}}},{canonicalId:"Qwen/Qwen3.6-Plus",gatewaySlug:"alibaba/qwen3.6-plus",order:["fireworks"],providers:{fireworks:{slug:"fireworks",promptCost:.5,completionCost:3,cacheReadCost:.1}}},{canonicalId:"Qwen/Qwen3.7-Max",gatewaySlug:"alibaba/qwen3.7-max",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:2.5,completionCost:7.5,cacheReadCost:.5,cacheWriteCost:3.13}}},{canonicalId:"Qwen/Qwen3.7-Plus",gatewaySlug:"alibaba/qwen3.7-plus",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:.4,completionCost:1.6,cacheReadCost:.08,cacheWriteCost:.5}}},{canonicalId:"Qwen/Qwen3.8-Omni-Flash",gatewaySlug:"alibaba/qwen3.8-omni-flash",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:.15,completionCost:.47,cacheReadCost:.016}}},{canonicalId:"Qwen/Qwen3.8-Max",gatewaySlug:"alibaba/qwen3.8-max",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:2,completionCost:6,cacheReadCost:.25,cacheWriteCost:2.5}}},{canonicalId:"Qwen/Qwen3.8-27B",gatewaySlug:"alibaba/qwen3.8-27b",order:["runinfra"],providers:{runinfra:{slug:"runinfra",promptCost:.4,completionCost:3,cacheReadCost:.04},deepinfra:{slug:"deepinfra",promptCost:.4,completionCost:3,cacheReadCost:.04}}},{canonicalId:"Qwen/Qwen3.7-Flash",gatewaySlug:"alibaba/qwen3.7-flash",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:.03,completionCost:.13,cacheReadCost:.006,cacheWriteCost:.038}}},{canonicalId:"MiniMaxAI/MiniMax-M3",gatewaySlug:"minimax/minimax-m3",order:["minimax"],providers:{minimax:{slug:"minimax",promptCost:.3,completionCost:1.2,cacheReadCost:.06}}},{canonicalId:hD,gatewaySlug:"minimax/minimax-m3",order:["minimax"],providers:{minimax:{slug:"minimax",promptCost:.3,completionCost:1.2,cacheReadCost:.06}}},{canonicalId:"MiniMaxAI/MiniMax-M2.7",gatewaySlug:"minimax/minimax-m2.7",order:["fireworks","togetherai"],providers:{fireworks:{slug:"fireworks",promptCost:.3,completionCost:1.2,cacheReadCost:.06},togetherai:{slug:"togetherai",promptCost:.3,completionCost:1.2,cacheReadCost:0}}},{canonicalId:"xiaomi/mimo-v2.6-pro",gatewaySlug:"xiaomi/mimo-v2.6-pro",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.435,completionCost:.87,cacheReadCost:.0036}}},{canonicalId:"xiaomi/mimo-v2.6-pro-ultraspeed",gatewaySlug:"xiaomi/mimo-v2.6-pro-ultraspeed",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:4.35,completionCost:8.7,cacheReadCost:.036}}},{canonicalId:"xiaomi/mimo-v2.6-flash",gatewaySlug:"xiaomi/mimo-v2.6-flash",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.14,completionCost:.28,cacheReadCost:.0028}}},{canonicalId:"xiaomi/mimo-v2.5-pro",gatewaySlug:"xiaomi/mimo-v2.5-pro",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.435,completionCost:.87,cacheReadCost:.0036}}},{canonicalId:"xiaomi/mimo-v2.5",gatewaySlug:"xiaomi/mimo-v2.5",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.14,completionCost:.28,cacheReadCost:.0028}}},{canonicalId:"stepfun/Step-5-Preview",gatewaySlug:"stepfun/step-5-preview",order:["stepfun"],providers:{stepfun:{slug:"stepfun",promptCost:1,completionCost:2.7,cacheReadCost:.05}}},{canonicalId:"stealth/pixel-canary",gatewaySlug:"stealth/pixel-canary",order:["stealth"],providers:{stealth:{slug:"stealth",promptCost:0,completionCost:0,cacheReadCost:0}}},{canonicalId:"stepfun/Step-3.5-Flash",gatewaySlug:"stepfun/step-3.5-flash",order:["deepinfra"],providers:{deepinfra:{slug:"deepinfra",promptCost:.09,completionCost:.3,cacheReadCost:.02}}},{canonicalId:"stepfun/Step-3.7-Flash",gatewaySlug:"stepfun/step-3.7-flash",order:["stepfun"],providers:{stepfun:{slug:"stepfun",promptCost:.2,completionCost:1.15,cacheReadCost:.04}}},{canonicalId:"gpt-5.6-sol",gatewaySlug:"openai/gpt-5.6-sol",order:["openai"],providers:{openai:{slug:"openai",promptCost:5,completionCost:30,cacheReadCost:.5,cacheWriteCost:6.25},azure:{slug:"azure",promptCost:5,completionCost:30,cacheReadCost:.5,cacheWriteCost:6.25},bedrock:{slug:"bedrock",promptCost:5,completionCost:30,cacheReadCost:.5,cacheWriteCost:6.25}}},{canonicalId:"gpt-5.6-terra",gatewaySlug:"openai/gpt-5.6-terra",order:["openai"],providers:{openai:{slug:"openai",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5},azure:{slug:"azure",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5},bedrock:{slug:"bedrock",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5}}},{canonicalId:"gpt-5.6-luna",gatewaySlug:"openai/gpt-5.6-luna",order:["openai"],providers:{openai:{slug:"openai",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25},azure:{slug:"azure",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25},bedrock:{slug:"bedrock",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25}}},{canonicalId:"google/gemini-3.8-flash",gatewaySlug:"google/gemini-3.8-flash",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:1.5,completionCost:7.5,cacheReadCost:.15}}},{canonicalId:"google/gemini-3.6-flash",gatewaySlug:"google/gemini-3.6-flash",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:1.5,completionCost:7.5,cacheReadCost:.15}}},{canonicalId:"google/gemini-3.5-flash",gatewaySlug:"google/gemini-3.5-flash",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:1.5,completionCost:9,cacheReadCost:.15}}},{canonicalId:"google/gemini-3.5-flash-lite",gatewaySlug:"google/gemini-3.5-flash-lite",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:.3,completionCost:2.5,cacheReadCost:.03}}},{canonicalId:"google/gemini-3.1-flash-lite",gatewaySlug:"google/gemini-3.1-flash-lite",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:.25,completionCost:1.5,cacheReadCost:.03}}},{canonicalId:"nvidia/nemotron-3-ultra-550b-a55b",gatewaySlug:"nvidia/nemotron-3-ultra-550b-a55b",order:["baseten","deepinfra"],providers:{baseten:{slug:"baseten",promptCost:.6,completionCost:2.4,cacheReadCost:.12},deepinfra:{slug:"deepinfra",promptCost:.5,completionCost:2.5,cacheReadCost:.15}}},{canonicalId:"thinkingmachines/inkling",gatewaySlug:"thinkingmachines/inkling",order:["baseten"],providers:{baseten:{slug:"baseten",promptCost:1,completionCost:4.05,cacheReadCost:.17}}},{canonicalId:"thinkingmachines/inkling-small",gatewaySlug:"thinkingmachines/inkling-small",order:["baseten"],providers:{baseten:{slug:"baseten",promptCost:.5,completionCost:1.2,cacheReadCost:.1}}},{canonicalId:"sakana/fugu-ultra",gatewaySlug:"sakana/fugu-ultra",order:["sakana"],providers:{sakana:{slug:"sakana",promptCost:5,completionCost:30,cacheReadCost:.5}}},{canonicalId:"xai/grok-4.5",gatewaySlug:"xai/grok-4.5",order:["xai"],providers:{xai:{slug:"xai",promptCost:2,completionCost:6,cacheReadCost:.5}}},{canonicalId:"xai/grok-4.6",gatewaySlug:"xai/grok-4.6",order:["xai"],providers:{xai:{slug:"xai",promptCost:2,completionCost:6,cacheReadCost:.5}}},{canonicalId:"xai/grok-4.7",gatewaySlug:"xai/grok-4.7",order:["xai"],providers:{xai:{slug:"xai",promptCost: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:"meta/muse-spark-1.3",gatewaySlug:"meta/muse-spark-1.3",order:["meta"],providers:{meta:{slug:"meta",promptCost:1.25,completionCost:4.25,cacheReadCost:.15}}},{canonicalId:"meta/muse-spark-1.3-contributor",gatewaySlug:"meta/muse-spark-1.3-contributor",order:["meta"],providers:{meta:{slug:"meta",promptCost:.1,completionCost:.2,cacheReadCost:.002}}},{canonicalId:"tencent/hy3-paid",gatewaySlug:"tencent/hy3",order:["novita"],providers:{novita:{slug:"novita",promptCost:.14,completionCost:.58,cacheReadCost:.035},deepinfra:{slug:"deepinfra",promptCost:.14,completionCost:.58,cacheReadCost:.035}}},{canonicalId:"poolside/laguna-s-2.1-free",gatewaySlug:"poolside/laguna-s-2.1-free",order:["poolside"],providers:{poolside:{slug:"poolside",promptCost:0,completionCost:0,cacheReadCost:0}}},{canonicalId:"inclusionai/ling-3.0-flash-free",gatewaySlug:"inclusionai/ling-3.0-flash-free",order:["novita"],providers:{novita:{slug:"novita",promptCost:0,completionCost:0,cacheReadCost:0}}}],TD=[{canonicalId:"Qwen/Qwen3.8-Max-0902",slug:"qwen3.8-max-0902",promptCost:2,completionCost:6,cacheReadCost:.25},{canonicalId:"Qwen/Qwen3.8-Max",slug:"qwen3.8-max",promptCost:2,completionCost:6,cacheReadCost:.25},{canonicalId:"Qwen/Qwen3.7-Max",slug:"qwen3.7-max",promptCost:2.5,completionCost:7.5,cacheReadCost:.5},{canonicalId:"Qwen/Qwen3.7-Plus",slug:"qwen3.7-plus",promptCost:.4,completionCost:1.6,cacheReadCost:.08,contextTiers:[{maxInputTokens:256e3,promptCost:.4,completionCost:1.6,cacheReadCost:.08},{promptCost:1.2,completionCost:4.8,cacheReadCost:.24}]},{canonicalId:"Qwen/Qwen3.6-Plus",slug:"qwen3.6-plus",promptCost:.5,completionCost:3,cacheReadCost:.1,contextTiers:[{maxInputTokens:256e3,promptCost:.5,completionCost:3,cacheReadCost:.1},{promptCost:2,completionCost:6,cacheReadCost:.2}]},{canonicalId:"zai-org/GLM-5.2",slug:"glm-5.2",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},{canonicalId:"moonshotai/Kimi-K2.7-Code",slug:"kimi-k2.7-code",promptCost:.95,completionCost:4,cacheReadCost:.19},{canonicalId:"Qwen/Qwen3.8-Flash",slug:"qwen3.8-flash",promptCost:.16,completionCost:.47,cacheReadCost:.016}],PD=[{canonicalId:"deepseek/deepseek-v4-flash",slug:"morph-dsv4flash",promptCost:.14,completionCost:.28,cacheReadCost:.0028,timeOfDay:CD}],MD=[{canonicalId:"deepseek/deepseek-v4-flash-fast",slug:"DeepSeek-V4-Flash-0731-Fast",promptCost:.28,completionCost:.56,cacheReadCost:.07}],xD=[{canonicalId:"meituan/LongCat-2.0",slug:"LongCat-2.0",promptCost:.3,completionCost:1.2,cacheReadCost:.006}],ID={promptCost:.834,completionCost:2.501,cacheReadCost:.042},AD=[{canonicalId:"tencent/hy4-preview",slug:"hy4-preview",...ID}],RD=[{canonicalId:"stepfun/Step-3.5-Flash",openrouterSlug:"stepfun/step-3.5-flash",order:["siliconflow"],providers:{siliconflow:{slug:"siliconflow",promptCost:.1,completionCost:.3,zdr:!0,noTraining:!0}}},{canonicalId:"stealth/space-bunny-alpha",openrouterSlug:"stealth/space-bunny-alpha",order:["stealth"],providers:{stealth:{slug:"stealth",promptCost:0,completionCost:0,zdr:!1,noTraining:!1}}},{canonicalId:"tencent/Hy3",openrouterSlug:"tencent/hy3:free",order:["novita"],providers:{novita:{slug:"novita",promptCost:0,completionCost:0,zdr:!1,noTraining:!1}}},{canonicalId:"inclusionai/ling-3.0-flash-sante:free",openrouterSlug:"inclusionai/ling-3.0-flash-sante:free",order:["novita"],providers:{novita:{slug:"novita",promptCost:0,completionCost:0,zdr:!0,noTraining:!0}}},{canonicalId:"tencent/hy4-preview",openrouterSlug:"tencent/hy4-preview",order:["tencent"],providers:{tencent:{slug:"tencent",...ID,zdr:!0,noTraining:!0}}},{canonicalId:"gpt-5.6-terra",openrouterSlug:"openai/gpt-5.6-terra",order:["openai"],providers:{openai:{slug:"openai",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5,zdr:!1,noTraining:!0}}},{canonicalId:"gpt-5.6-luna",openrouterSlug:"openai/gpt-5.6-luna",order:["openai"],providers:{openai:{slug:"openai",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25,zdr:!1,noTraining:!0}}},{canonicalId:"google/gemini-3.7-flash",openrouterSlug:"google/gemini-3.7-flash",order:["google-vertex"],providers:{"google-vertex":{slug:"google-vertex",promptCost:1.5,completionCost:7.5,cacheReadCost:.15,cacheWriteCost:.08334,zdr:!0,noTraining:!0}}}],LD={"claude-sonnet-4-20250514":fD.SONNET_4_6.id,"claude-sonnet-4-5-20250929":fD.SONNET_4_6.id,"claude-opus-4-5-20251101":fD.OPUS_4_7.id,"claude-opus-4-6":fD.OPUS_4_7.id,"claude-haiku-4-5":fD.HAIKU_4_5.id},OD=fD.DEEPSEEK_V4_FLASH.id,DD={[YO]:"Anthropic",[QO]:"OpenAI",[JO]:"Open Source",[XO]:"Open Source",[eD]:"Open Source",[tD]:"Open Source"},$D=["Open Source","Stealth","Anthropic","OpenAI","Google"],ND={"command-code":{id:"command-code",label:"Command Code",shortLabel:"cmd",description:"recommended",supportedModelProviders:[YO,QO,eD,JO,XO,tD],requiresAuth:!1,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!0},anthropic:{id:"anthropic",label:"Anthropic",shortLabel:"anth",description:"Claude Pro/Max",supportedModelProviders:[YO],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!1},"github-copilot":{id:"github-copilot",label:"GitHub Copilot",shortLabel:"copilot",description:"Copilot subscription",supportedModelProviders:[YO,QO],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!0},codex:{id:"codex",label:"OpenAI ChatGPT/Codex",shortLabel:"openai",description:"ChatGPT Pro/Plus subscription",supportedModelProviders:[QO],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(fD).filter(e=>!e.hidden),n=[];for(const r of Object.values(ND)){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 _D=buildModelGroups("co"),FD=buildModelGroups("normal");function formatColoredUserSuffix(e){return isGenericUserName(e)?"":formatUserSuffix(e).replace(e,Pt.cyan(e))}function getStartedLine(){return`${Pt.dim("Run")} ${Pt.cyan(getBinaryCommand())} ${Pt.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 ${Pt.cyan(r)}`:"",i=[`${Pt.green(ft.tick)} ${Pt.bold("Logged in")}${s}${a}`];return o&&i.push(` ${Pt.yellow(ft.warning)} ${Pt.yellow(o)}`),i.push("",`${Pt.dim("API key stored in")} ${Pt.cyan(`~/.commandcode/${n}`)}`,getStartedLine()),i.join("\n")}function formatAlreadyLoggedInStyled(e){const t=formatColoredUserSuffix(e);return[`${Pt.green(ft.tick)} ${Pt.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"),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt();var UD=[{id:"copilot",package:"@byokkit/cmd-provider-copilot",version:"0.1.2",displayName:"GitHub Copilot"},{id:"openai",package:"@byokkit/cmd-provider-openai",version:"0.1.4",displayName:"OpenAI"},{id:"anthropic",package:"@byokkit/cmd-provider-anthropic",version:"0.1.3",displayName:"Anthropic",discoverable:!1}];function builtinProviderPackage(e){return UD.find(t=>t.id===e)}function builtinPackageForSpecifier(e){return builtinProviderPackage(e)??UD.find(t=>t.package===e)}__name(builtinProviderPackage,"builtinProviderPackage"),__name(builtinPackageForSpecifier,"builtinPackageForSpecifier");var jD=new Map;function isProviderWorkspaceDevMode(){return"local"===getApiEnv()}function workspaceDistEntry(e){const t=e.replace(/^@[^/]+\//,"").replace(/^cmd-/,""),o=r(p(import.meta.url)),a=s(o,n("../..",t,"dist","index.js"));return A(a)?a:void 0}function devWorkspaceProviderEntry(e){if(isProviderWorkspaceDevMode())return workspaceDistEntry(e)}__name(isProviderWorkspaceDevMode,"isProviderWorkspaceDevMode"),__name(workspaceDistEntry,"workspaceDistEntry"),__name(devWorkspaceProviderEntry,"devWorkspaceProviderEntry");var BD=__name(async e=>{const t=builtinProviderPackage(e.moduleId);if(!t)return;const n=jD.get(e.moduleId);if(n)return n;const r=!1===t.discoverable,o=devWorkspaceProviderEntry(t.package)??(r?await resolveManuallyInstalledProviderEntry({runtime:createNodeRuntime(),pkg:t.package}):void 0),s=o?coerceProviderModule(await import(g(o).href)):await loadProviderModuleFromPackage({runtime:createNodeRuntime(),pkg:t.package,version:t.version,install:e.install,...e.onInstallStart?{onInstallStart:e.onInstallStart}:{}});return o&&dlog("[ProviderPackages] workspace/local provider",{pkg:t.package,entry:o}),s&&jD.set(e.moduleId,s),s},"realLoader");function loadBuiltinProviderModule(e){return BD(e)}async function loadInstalledBuiltinProviderModules(){const e=UD.map(e=>e.id),t=[];for(const n of e)try{const e=await loadBuiltinProviderModule({moduleId:n,install:!1});e&&t.push(e)}catch(e){dlog("[ProviderPackages] installed provider failed to load",{moduleId:n,error:e instanceof Error?e.message:String(e)})}return t}function uniqueProviderModules(e){const t=new Map;for(const n of e)t.has(n.id)||t.set(n.id,n);return[...t.values()]}async function importProviderModule(e,n,r=!1,o){if(e.startsWith(".")||t.isAbsolute(e))return import(g(t.resolve(n,e)).href);const s=builtinPackageForSpecifier(e);if(s)return{default:await loadBuiltinProviderModule({moduleId:s.id,install:r,onInstallStart:__name(({pkg:e})=>dlog("[ProviderPackages] installing settings provider",{pkg:e}),"onInstallStart")})};if(isNpmPackageSpecifier(e)){const t=createNodeRuntime();if(r&&!o)throw new Error(`Provider package '${e}' requires an explicit semver "version" in user settings before it can be installed`);const n=r?(await ensureProviderPackage({runtime:t,pkg:e,version:o,onInstallStart:__name(({pkg:e})=>dlog("[ProviderPackages] installing settings provider",{pkg:e}),"onInstallStart")})).entry:await resolveInstalledProviderEntry({runtime:t,pkg:e});if(!n)throw new Error(`Provider package '${e}' is not installed; run its explicit login/install flow first`);return import(g(n).href)}return import(e)}async function loadInstalledProviderModules(){const e=createNodeRuntime(),t=createConfigStore({config:await loadCommandCodeConfig({runtime:e}),runtime:e}).getProviders(),n=await loadInstalledBuiltinProviderModules(),r=await loadProviderModules({entries:t,builtins:n,importModule:__name(t=>importProviderModule(t,e.cwd()),"importModule")}),o={};for(const[e,n]of Object.entries(t))o[e]=n.module??n.npm??e;return{modules:uniqueProviderModules([...n,...r.modules]),errors:r.errors,sources:o}}async function settingsProviderSpecifier(e){const t=createNodeRuntime(),n=createConfigStore({config:await loadCommandCodeConfig({runtime:t}),runtime:t}).getProviders()[e];if(!n||!0===n.disabled)return;const r=n.module??n.npm;return r&&r!==e?{specifier:r,version:n.version}:void 0}async function loadSettingsProviderModule(e,t){const n=await settingsProviderSpecifier(e);if(n)return coerceProviderModule(await importProviderModule(n.specifier,createNodeRuntime().cwd(),t,n.version))}__name(loadBuiltinProviderModule,"loadBuiltinProviderModule"),__name(loadInstalledBuiltinProviderModules,"loadInstalledBuiltinProviderModules"),__name(uniqueProviderModules,"uniqueProviderModules"),__name(importProviderModule,"importProviderModule"),__name(loadInstalledProviderModules,"loadInstalledProviderModules"),__name(settingsProviderSpecifier,"settingsProviderSpecifier"),__name(loadSettingsProviderModule,"loadSettingsProviderModule");var WD=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:Ak});async function providerAuthHeaders(e){return WD.providerAuthHeaders(e)}async function hasProviderCredential(e){return WD.hasProviderCredential(e)}async function providerLogin(e){return WD.login(e)}async function providerLogout(e){return WD.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=ns[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(Pt.yellow(` ${e}`)),console.log()}function printLoginLink(e){console.log(),console.log(Pt.dim(" Login: ")+createOSC8Link(e,"Open auth page ↗")),console.log()}async function openAuthPage(e,t){await xt(e,t).catch(()=>{console.log(Pt.dim(` Could not auto-open browser. Open: ${e}`))})}async function confirmOpenAfterCode(){const e=await Qe({message:"Press Enter to open GitHub and paste the code there.",active:"Open",inactive:"Cancel",initialValue:!0});if(Je(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)?Pt.dim(" (copied)"):"";console.log(` ${Pt.yellow("Logging into Copilot, use this code:")} ${Pt.bold(t)}${n}`),console.log()}async function performProviderAuth(e){const{provider:t}=e,n=getProviderDisplayName(t);try{let e=!0;const r=t===fo.COPILOT;if(!r){const t=await Qe({message:`Open browser to sign in with ${n}?`,initialValue:!0});if(Je(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(` ${Pt.dim(ft.circleFilled)} ${Pt.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 Xe({message:t.prompt.label,mask:"*"});if(Je(e)||!String(e).trim())throw new Error("No authorization code provided");return{code:String(e).trim()}}console.log(` ${Pt.dim(ft.circleFilled)} ${Pt.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 HD=__name(({message:e})=>it.createElement(it.Fragment,null,it.createElement(et,{color:LR.CYAN},it.createElement(bt,{type:"dots"})),it.createElement(et,null," ",e)),"LoadingIndicator"),GD=__name(({message:e})=>it.createElement(it.Fragment,null,it.createElement(et,{color:LR.GREEN},ft.tick),it.createElement(et,null," ",e)),"SuccessIndicator"),VD=__name(({children:e})=>it.createElement(Ze,{flexDirection:"column"},it.createElement(et,null," "),it.createElement(Ze,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"),ze.intro(heading({text:"Command Code Authentication"}))}function showLoginCancelMessage(e){Ke(`${ft.cross} ${e}`)}function printMessage(e){console.log(""),console.log(e),console.log("")}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=rt(it.createElement(DO,{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 zD=__name(({env:e,onComplete:t})=>{const[n,r]=ct("checking"),[o,s]=ct(null);return ut(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),ut(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),it.createElement(VD,null,"checking"===n&&it.createElement(HD,{message:"Checking authentication status..."}),"logged_in"===n&&it.createElement(GD,{message:"Authenticated"}),"not_logged_in"===n&&it.createElement(GD,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=rt(it.createElement(zD,{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||(Ke(`${ft.cross} Login failed: ${e.error}`),process.exit(1)),qe(Pt.green(`${ft.tick} ${e.message}`)),process.exit(0)}await runLogin(),process.exit(0)}catch(e){isUserCancellation(e)&&process.exit(0),console.error(`${ft.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(performProviderLogin,"performProviderLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction");var KD=new He("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:$o})}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()})}Vt(),PR(),__name(performLogout,"performLogout"),__name(performProviderLogout,"performProviderLogout"),__name(readLogoutUserName,"readLogoutUserName");var qD=__name(({userName:e})=>{const t=e?`Logging out ${e}...`:"Logging out...";return it.createElement(it.Fragment,null,it.createElement(et,{color:LR.CYAN},it.createElement(bt,{type:"dots"})),it.createElement(et,null," ",t))},"LoadingIndicator"),YD=__name(({userName:e,wasAuthenticated:t})=>{const n=!1===t?"Not currently authenticated":formatLogoutSuccess(e);return it.createElement(it.Fragment,null,it.createElement(et,{color:LR.GREEN},ft.tick),it.createElement(et,null," ",n))},"SuccessIndicator"),QD=__name(({errorMessage:e})=>it.createElement(it.Fragment,null,it.createElement(et,{color:LR.RED},ft.cross),it.createElement(et,{color:LR.RED}," Logout failed: ",e)),"ErrorIndicator"),JD=__name(({status:e,errorMessage:t,userName:n,wasAuthenticated:r})=>"loading"===e?it.createElement(qD,{userName:n}):"success"===e?it.createElement(YD,{userName:n,wasAuthenticated:r}):it.createElement(QD,{errorMessage:t}),"StatusDisplay"),XD=__name(({onComplete:e,userName:t})=>{const[n,r]=ct("loading"),[o,s]=ct(""),[a,i]=ct(null);return ut(()=>{performLogout().then(e=>{i(e),e.success?r("success"):(s(e.error||"Unknown error"),r("error"))})},[]),ut(()=>{if(("success"===n||"error"===n)&&a){const t=setTimeout(()=>e(a),100);return()=>clearTimeout(t)}},[n,a,e]),it.createElement(Ze,{flexDirection:"column"},it.createElement(et,null," "),it.createElement(Ze,null,it.createElement(JD,{status:n,errorMessage:o,userName:t,wasAuthenticated:a?.wasAuthenticated})))},"LogoutSpinner");function printWarnings(e){0!==e.length&&(console.warn(Pt.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(Pt.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}=rt(it.createElement(XD,{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(`${ft.cross} ${e.error}`),process.exit(1)),console.log(`${ft.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 ZD=new He("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=It("Checking authentication status...").start();try{const e=getApiEnv(),n=await checkAuthStatus(e);n.error&&(t.fail(Pt.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(t.fail(Pt.red("Not authenticated")),console.log(""),console.log(`${Pt.dim("Run")} ${Pt.cyan(`${getBinaryCommand()} auth login`)} ${Pt.dim("to authenticate.")}`),console.log(""),process.exit(1));const r=isGenericCommandAuthUserName(n.userName)?"":` as ${Pt.cyan(n.userName)}`;t.succeed("Authentication verified"),console.log(`${Pt.green(ft.tick)} ${Pt.bold("Authenticated")}${r}`),console.log(` ${Pt.dim("Provider:")} ${Pt.cyan("Command Code")}`),n.fromEnv&&console.log(` ${Pt.dim("Source:")} ${Pt.cyan(`$${$o}`)} ${Pt.dim("(env var)")}`),console.log(""),process.exit(0)}catch(e){t.fail(Pt.red(`Status check failed: ${e instanceof Error?e.message:"Unknown error"}`)),process.exit(1)}}Vt(),PR(),__name(checkAuthStatus,"checkAuthStatus"),__name(buildStatusJson,"buildStatusJson"),__name(statusAction,"statusAction");var e$=new He("status").description("Show authentication status").option("--json","Output status as JSON for automation").allowUnknownOption().allowExcessArguments().action(statusAction);function parseValue(e){try{const t=JSON.parse(e);if("string"==typeof t||"boolean"==typeof t||"number"==typeof t)return t}catch{}return e}function rowValue(e){return e.currentValue}function rowMatchesScope(e,t){return"effective"===t||e.scope===t}function printValue(e,t){console.log(t?JSON.stringify(e,null,2):String(e))}function liveApplyInfo(e){return e===Op?{liveSessionReloadsOnNextRound:!1,message:"This sets the default model for new sessions. Use /model to change the running session."}:{liveSessionReloadsOnNextRound:!0,message:"A running session picks this up at the start of its next round."}}function unknownKeyMessage(e,t){const n=e.suggest({raw:t});return 0===n.length?`Unknown configuration setting: ${t}`:`Unknown configuration setting: ${t}. Did you mean: ${n.join(", ")}?`}async function createRegistry(){const e=getCommandConfigRuntime(),t=await loadCommandCodeConfig({runtime:e});let n=normalizePermissionMode(t.permissions?.defaultMode)??normalizePermissionMode(t.permissionMode)??"default";return createConfigToolRegistry({runtime:e,listModelIds:__name(()=>listKnownModelIds(),"listModelIds"),model:{current:__name(()=>getConfiguredModel(),"current"),set:__name(async({model:e})=>persistDefaultModel({model:e}),"set")},permissionMode:{current:__name(()=>n,"current"),set:__name(async({mode:t})=>{await updateUserSettings({runtime:e,patch:{permissions:{defaultMode:t}}}),n=t},"set")}})}function withCommonOptions(e){return e.addOption(new Ge("--scope <scope>","Configuration scope").choices(["effective","user","project"]).default("effective")).option("--json","Print machine-readable JSON")}new He("auth").description("Manage authentication with Command Code").addCommand(KD).addCommand(ZD).addCommand(e$),Vt(),PR(),__name(parseValue,"parseValue"),__name(rowValue,"rowValue"),__name(rowMatchesScope,"rowMatchesScope"),__name(printValue,"printValue"),__name(liveApplyInfo,"liveApplyInfo"),__name(unknownKeyMessage,"unknownKeyMessage"),__name(createRegistry,"createRegistry"),__name(withCommonOptions,"withCommonOptions");var t$=withCommonOptions(new He("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})`)}),n$=withCommonOptions(new He("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)}),r$=withCommonOptions(new He("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=liveApplyInfo(i.id),c={id:i.id,previousValue:i.previousValue,newValue:i.newValue,scope:n.scope,liveSessionReloaded:!1,liveSessionReloadsOnNextRound:l.liveSessionReloadsOnNextRound};n.json?printValue(c,!0):(console.log(`${i.id}: ${JSON.stringify(i.previousValue)} -> ${JSON.stringify(i.newValue)} (${n.scope})`),console.log(l.message))}),o$=new He("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=liveApplyInfo(a.id),l={id:a.id,previousValue:a.previousValue,newValue:a.newValue,scope:s.scope,liveSessionReloaded:!1,liveSessionReloadsOnNextRound:i.liveSessionReloadsOnNextRound};t.json?printValue(l,!0):(console.log(`${a.id}: ${JSON.stringify(a.previousValue)} -> ${JSON.stringify(a.newValue)} (default, ${s.scope})`),console.log(i.message))}),s$=new He("config").description("Inspect and update validated configuration settings").addCommand(t$).addCommand(n$).addCommand(r$).addCommand(o$);async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=It("Opening the GitHub issue…").start();try{await xt(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("")}}Vt(),PR(),__name(openGitHubIssue,"openGitHubIssue");var a$=new He("feedback").alias("issue").description("Report a bug or share feedback — opens a GitHub issue").argument("[title]","Optional issue title").action(openGitHubIssue);Vt();var i$=new He("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});Vt(),Vt(),PR(),Vt(),PR();var l$=__name(({icon:e,label:t,children:n})=>it.createElement(et,null,it.createElement(et,{color:LR.CYAN},e," "),it.createElement(et,{color:LR.DIM},t.padEnd(12)),n),"Row"),c$=__name(({title:e})=>it.createElement(et,null,it.createElement(et,{color:LR.GRAY},"───"),it.createElement(et,{color:LR.WHITE}," ",e," "),it.createElement(et,{color:LR.GRAY},"─".repeat(35))),"Header"),d$=__name(({title:e,marginTop:t=0,children:n})=>it.createElement(Ze,{flexDirection:"column",marginTop:t},it.createElement(c$,{title:e}),it.createElement(Ze,{flexDirection:"column",paddingY:1},n)),"Section"),u$=__name(({host:e,systemInfo:t})=>it.createElement(d$,{title:"System Information"},it.createElement(l$,{icon:ft.bullet,label:"Version"},it.createElement(et,{color:LR.GREEN},t.version)),it.createElement(l$,{icon:ft.bullet,label:"Date"},it.createElement(et,null,formatDate())),it.createElement(l$,{icon:ft.pointer,label:"Platform"},it.createElement(et,{color:LR.GREEN},t.os),it.createElement(et,{color:LR.DIM}," ","(",e.platform,", ",e.arch,")")),it.createElement(l$,{icon:ft.triangleUp,label:"Hostname"},it.createElement(et,null,e.hostname)),it.createElement(l$,{icon:ft.bullet,label:"User"},it.createElement(et,{color:LR.YELLOW},e.username)),it.createElement(l$,{icon:ft.bullet,label:"CPUs"},it.createElement(et,{color:LR.MAGENTA},e.cpus.length," cores")),it.createElement(l$,{icon:ft.bullet,label:"Memory"},it.createElement(et,{color:LR.CYAN},e.totalMemoryGb," GB")),it.createElement(l$,{icon:ft.play,label:"Uptime"},it.createElement(et,null,formatUptime(e.uptimeSeconds))),it.createElement(l$,{icon:ft.arrowRight,label:"Home"},it.createElement(et,{color:LR.DIM},e.homeDir)),it.createElement(l$,{icon:ft.pointer,label:"Shell"},it.createElement(et,null,t.shell)),it.createElement(l$,{icon:ft.bullet,label:"Node"},it.createElement(et,{color:LR.GREEN},e.nodeVersion)),it.createElement(l$,{icon:ft.pointer,label:"Terminal"},it.createElement(et,{color:LR.CYAN},t.terminal)),it.createElement(l$,{icon:ft.bullet,label:"IDE"},it.createElement(et,null,t.ide))),"SystemInfoSection"),m$=__name(({cpus:e})=>it.createElement(d$,{title:"CPU Details",marginTop:1},e.map((e,t)=>it.createElement(l$,{key:t,icon:ft.bullet,label:`Core ${t}`},it.createElement(et,null,e.model),it.createElement(et,{color:LR.YELLOW}," @ ",e.speedMHz," MHz")))),"CPUDetailsSection"),p$=__name(({addresses:e})=>it.createElement(d$,{title:"Network",marginTop:1},e.map((e,t)=>it.createElement(l$,{key:`${e.interfaceName}-${t}`,icon:ft.bullet,label:e.interfaceName},it.createElement(et,{color:LR.GREEN},e.address)))),"NetworkSection"),g$=__name(({host:e,verbose:t,systemInfo:n})=>it.createElement(Ze,{flexDirection:"column"},it.createElement(et,null,"System Information"),it.createElement(et,null,"─".repeat(40)),it.createElement(et,null,"Version ",n.version),it.createElement(et,null,"Date ",formatDate()),it.createElement(et,null,"Platform ",n.os," (",e.platform,", ",e.arch,")"),it.createElement(et,null,"Hostname ",e.hostname),it.createElement(et,null,"User ",e.username),it.createElement(et,null,"CPUs ",e.cpus.length," cores"),it.createElement(et,null,"Memory ",e.totalMemoryGb," GB"),it.createElement(et,null,"Uptime ",formatUptime(e.uptimeSeconds)),it.createElement(et,null,"Home ",e.homeDir),it.createElement(et,null,"Shell ",n.shell),it.createElement(et,null,"Node ",e.nodeVersion),it.createElement(et,null,"Terminal ",n.terminal),it.createElement(et,null,"IDE ",n.ide),t&&it.createElement(it.Fragment,null,it.createElement(et,null,"\n","CPU Details"),it.createElement(et,null,"─".repeat(40)),e.cpus.map((e,t)=>it.createElement(et,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speedMHz," MHz")),it.createElement(et,null,"\n","Network"),it.createElement(et,null,"─".repeat(40)),e.externalIpv4.map((e,t)=>it.createElement(et,{key:`${e.interfaceName}-${t}`},e.interfaceName.padEnd(12),e.address)))),"PlainTextInfo"),h$=__name(({host:e,verbose:t,systemInfo:n})=>it.createElement(Ze,{flexDirection:"column"},it.createElement(u$,{host:e,systemInfo:n}),t&&it.createElement(m$,{cpus:e.cpus}),t&&it.createElement(p$,{addresses:e.externalIpv4})),"StyledInfo"),f$=__name(({verbose:e=!1,text:t=!1,systemInfo:n})=>{const{exit:r}=st();ut(()=>{const e=setTimeout(()=>r(),50);return()=>clearTimeout(e)},[r]);const o=mt(()=>collectHostDiagnostics(),[]);return t?it.createElement(g$,{host:o,verbose:e,systemInfo:n}):it.createElement(h$,{host:o,verbose:e,systemInfo:n})},"InfoUI");async function runInfo(e){await applyStartupTheme();const t=getSystemInfo(),{waitUntilExit:n}=rt(it.createElement(f$,{verbose:e.verbose,text:e.text,systemInfo:t}));await n()}__name(runInfo,"runInfo");var y$=new He("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)}`}Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt(),Vt(),__name(formatUsd,"formatUsd");var S$=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatShortDateUtc(e){const t=S$[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 w$={"zai-org/GLM-5":{inputCost:1,outputCost:3.2,cacheReadCost:.2},"zai-org/GLM-5.2":{inputCost:1.4,outputCost:4.4,cacheReadCost:.26}};function advertisedBandOf(e,t){const n=e.timeOfDay;return n?t<Date.parse(n.effectiveFrom)?e:n.offPeak:e}function primaryUpstreamOf(e,t){const n=e.order[0],r=n?e.providers[n]:void 0;if(!r)throw new Error(`display-pricing: billing entry "${t}" has no primary upstream in its \`order\``);return r}__name(advertisedBandOf,"advertisedBandOf"),__name(primaryUpstreamOf,"primaryUpstreamOf");var v$={inputCost:.042,outputCost:0,cacheReadCost:0};function jevBilledRates(e){return isJevFree(e)?{inputCost:0,outputCost:0,cacheReadCost:0}:v$}function getDisplayRates(e,t=Date.now()){const n=w$[e];if(n)return n;if("typesafe/jev"===e)return jevBilledRates(t);const r=Object.values(uD).flat().find(t=>t.id===e);if(r)return{inputCost:r.promptCost,outputCost:r.completionCost,cacheReadCost:r.cacheHitCost??0,...null!=r.cacheWrite5mCost&&{cacheWriteCost:r.cacheWrite5mCost},...null!=r.cacheWrite1hCost&&{cacheWrite1hCost:r.cacheWrite1hCost}};const o=ED.find(t=>t.canonicalId===e);if(o)return toDisplayRates(advertisedBandOf(primaryUpstreamOf(o,e),t));const s=RD.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=TD.find(t=>t.canonicalId===e);if(a)return{inputCost:a.promptCost,outputCost:a.completionCost,cacheReadCost:a.cacheReadCost};const i=PD.find(t=>t.canonicalId===e);if(i)return{inputCost:i.promptCost,outputCost:i.completionCost,cacheReadCost:i.cacheReadCost};const l=MD.find(t=>t.canonicalId===e);if(l)return{inputCost:l.promptCost,outputCost:l.completionCost,cacheReadCost:l.cacheReadCost};const c=xD.find(t=>t.canonicalId===e);if(c)return{inputCost:c.promptCost,outputCost:c.completionCost,cacheReadCost:c.cacheReadCost};const d=AD.find(t=>t.canonicalId===e);if(d)return{inputCost:d.promptCost,outputCost:d.completionCost,cacheReadCost:d.cacheReadCost};const u=uD[oD]?.find(t=>t.id===`${oD}:${e}`);if(u)return{inputCost:u.promptCost,outputCost:u.completionCost,cacheReadCost:u.cacheHitCost??0};throw new Error(`display-pricing: unknown billing id "${e}": not in MODELS (bare or novita-prefixed), GATEWAY_MODEL_PRICING, OPENROUTER_MODEL_PRICING, ALIBABA_MODEL_PRICING, MORPH_MODEL_PRICING, WAFER_MODEL_PRICING, LONGCAT_MODEL_PRICING, TENCENT_MODEL_PRICING, or the decision model (JEV_MODEL_ID)`)}function toDisplayRates(e){return{inputCost:e.promptCost,outputCost:e.completionCost,cacheReadCost:e.cacheReadCost??0,...null!=e.cacheWriteCost&&{cacheWriteCost:e.cacheWriteCost}}}function getDisplayTimeOfDay(e){if(w$[e])return;const t=ED.find(t=>t.canonicalId===e),n=t?.order[0],r=n?t?.providers[n]?.timeOfDay:void 0;if(!r)return;const o=peakHoursPerDay(r.peakWindowsUtc);return{effective:r.effectiveFrom,peak:toDisplayRates(r.peak),offPeak:toDisplayRates(r.offPeak),peakWindowsUtc:r.peakWindowsUtc,peakDaysUtc:r.peakDaysUtc,peakHoursPerDay:o,offPeakHoursPerDay:24-o}}function timeOfDayNote(e){const t=`${formatUsd(e.offPeak.inputCost)}/${formatUsd(e.offPeak.outputCost)}`,n=`${formatUsd(e.peak.inputCost)}/${formatUsd(e.peak.outputCost)}`;return`From ${formatShortDateUtc(e.effective)}: ${t} off-peak, ${n} peak (${e.peakHoursPerDay}h/day)`}function timeOfDayScheduledChanges(){const e={};for(const t of ED){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(fD).find(t=>t.id===e)}function getModelNotice(e){const t=findModelById(e);if(!t?.notice)return;const n=t.vendorLabel??DD[t.provider]??"the upstream provider";return t.notice.replaceAll("{name}",t.name).replaceAll("{vendor}",n)}function getProviderFromModel(e){return findModelById(e)?.provider??YO}function getAllModelOptions(){return Object.values(fD)}function getModelGroupLabel(e){return e.vendorLabel??DD[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[...$D.filter(e=>t.has(e)),...[...t.keys()].filter(e=>!$D.includes(e))].map(e=>({label:e,models:t.get(e)}))}function getModelGroupsInOrder(){return groupModelsByDisplayOrder(getAllModelOptions().filter(e=>!e.hidden))}function resolveKnownModelId2(e){const t=getCanonicalModelId(e);return findModelById(t)?t:void 0}function modelSupportsVision(e){const t=findModelById(getCanonicalModelId(e));return!t?.inputModalities||t.inputModalities.includes("image")}function modelSupportsZdr(e){return!bD.has(getCanonicalModelId(e))}__name(jevBilledRates,"jevBilledRates"),__name(getDisplayRates,"getDisplayRates"),__name(toDisplayRates,"toDisplayRates"),__name(getDisplayTimeOfDay,"getDisplayTimeOfDay"),__name(timeOfDayNote,"timeOfDayNote"),__name(timeOfDayScheduledChanges,"timeOfDayScheduledChanges"),timeOfDayScheduledChanges(),Vt(),__name(findModelById,"findModelById"),__name(getModelNotice,"getModelNotice"),__name(getProviderFromModel,"getProviderFromModel"),__name(getAllModelOptions,"getAllModelOptions"),__name(getModelGroupLabel,"getModelGroupLabel"),__name(groupModelsByDisplayOrder,"groupModelsByDisplayOrder"),__name(getModelGroupsInOrder,"getModelGroupsInOrder"),__name(resolveKnownModelId2,"resolveKnownModelId"),__name(modelSupportsVision,"modelSupportsVision"),__name(modelSupportsZdr,"modelSupportsZdr");var k$=/[-@]\d{8}$/,C$="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=(LD[e.toLowerCase()]??e).toLowerCase(),n=Object.values(fD).find(e=>e.id.toLowerCase()===t);if(n)return n.id;const r=yD.find(e=>e.canonicalId.toLowerCase()===t)??yD.find(e=>ossEntryMatches(e,t));return r?.canonicalId}function getCanonicalModelId(e){if(!e)return e;const t=e.startsWith(C$)?e.slice(C$.length):e,n=tryResolveCanonical2(t);if(n)return n;const r=t.replace(k$,"");return r===t?t:tryResolveCanonical2(r)??t}function getModelDisplayName(e){const t=getCanonicalModelId(e),n=Object.values(fD).find(e=>e.id===t);return n?.name??e}__name(ossEntryMatches,"ossEntryMatches"),__name(tryResolveCanonical2,"tryResolveCanonical"),__name(getCanonicalModelId,"getCanonicalModelId"),__name(getModelDisplayName,"getModelDisplayName"),Vt(),PR();var b$=null;function setRegisteredProviderModules(e){b$=new Set(e.modules.map(e=>e.id))}function isProviderLaneRegistered(e){const t=b$;if(!t)return!0;if(!rs[e.providerId]?.requiresAuth)return!0;const n=Ak[e.providerId]??e.providerId;return t.has(n)}function isProviderLaneListable(e){if(!rs[e.providerId]?.requiresAuth)return!0;const t=Ak[e.providerId]??e.providerId,n=builtinProviderPackage(t);return!(!n||!1===n.discoverable)||(b$?.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 E$=getPackageJson(import.meta.url),T$="string"==typeof E$.version&&E$.version.trim()?E$.version:"unknown",P$=new Set(Object.values(Ak));function selectActiveOAuthProviderModules(e){const t=e.provider?Ak[e.provider]:void 0;return e.modules.filter(e=>!P$.has(e.id)||e.id===t)}async function restoreSelectedOAuthProviderModule(e){if(!e.provider)return;if(e.disabled)return;const t=Ak[e.provider];if(!t)return;if(e.modules.some(e=>e.id===t))return;if(!await e.hasCredential(e.provider))return;const n=await e.loadModule(t);if(!n)throw new Error(`No installed or user-registered provider package is available for '${t}'`);e.modules.push(n)}function estimateSessionCostUsd(e){try{const t=getDisplayRates(e.model),{inputTokens:n,outputTokens:r,cacheReadTokens:o,cacheWriteTokens:s,cacheWriteTokens1h:a=0}=e.usage,i=Math.max(0,n-o-s),l=Math.min(a,s),c=s-l,d=t.cacheWriteCost??0,u=t.cacheWrite1hCost??d;return(i*t.inputCost+r*t.outputCost+o*t.cacheReadCost+c*d+l*u)/1e6}catch{return}}async function createHarnessSession(e){const t=e.runtime??createNodeRuntime(),n=await loadCommandCodeConfig({runtime:t}),r=e.configStore??createConfigStore({config:n,runtime:t,modelOverride:getModelOverride(),modelOverrideProvider:getModelOverrideProvider()});if(!e.configStore&&void 0===getModelOverride())try{const t=await loadCommandSessionMeta({sessionId:e.sessionId});t?.model&&(await loadCustomProviderModels(),(void 0!==resolveKnownModelId2(t.model)||isByok({model:t.model}))&&r.setSessionModel({model:t.model,...void 0!==t.modelProvider?{provider:t.modelProvider}:{}}))}catch{}const o=e.providerModules??e.modHost?.providerModules(),s=new Set((await loadProvidersConfig({runtime:t})).disabledProviderIds),a=[...o??[...await loadInstalledBuiltinProviderModules()]].filter(e=>!s.has(e.id)),i=(await loadUserConfig({runtime:t,path:legacyUserConfigPath({runtime:t})})).provider,l=i?Ak[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 '${getBinaryCommand()} 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??T$,providerModules:u,providerBinding:{provider:i??null},importProviderModule:e.importProviderModule??(t=>importProviderModule(t,e.runtime?.cwd()??process.cwd())),estimateCostUsd:e.estimateCostUsd??estimateSessionCostUsd})}__name(selectActiveOAuthProviderModules,"selectActiveOAuthProviderModules"),__name(restoreSelectedOAuthProviderModule,"restoreSelectedOAuthProviderModule"),__name(estimateSessionCostUsd,"estimateSessionCostUsd"),__name(createHarnessSession,"createHarnessSession");var M$=createHarnessSessionManager({createSession:createHarnessSession}),x$=M$.getHarnessForSession,I$=M$.getResolvedHarness,A$=M$.forgetHarnessSession,R$=M$.disposeAllHarnessSessions,L$=new Set;function onHarnessSessionRebuild(e){return L$.add(e),()=>L$.delete(e)}async function rebuildHarnessSession(e){try{await(I$(e)?.flush())}catch{}A$(e);const t=[];for(const n of L$){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 O$=null,D$=null,$$=[],N$=null,_$=!1;async function loadFromConfig(){const e=await loadProvidersConfig({runtime:createNodeRuntime()});return $$=e.warnings,N$=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 O$||(diskLoadsBlocked()?O$=[]:loadIntoCache())}function loadIntoCache(){return D$??=loadFromConfig().then(e=>(O$=e,e)).catch(()=>O$=[]),D$}async function refreshCustomProviderModels(e){if(diskLoadsBlocked())return O$??=[],{providers:O$,changed:!1};const t=null!==O$?N$:null;O$=null,D$=null;const n=await loadIntoCache();null!==t&&t!==N$&&(_$=!0);const r=_$;return _$&&e?.sessionId&&(await rebuildHarnessSession(e.sessionId),_$=!1),{providers:n,changed:r}}function seedSnapshotSync(){if(null===O$&&!process.env.VITEST)try{const e=x.readFileSync(`${H()}/.commandcode/providers.json`,"utf8"),t=parseProvidersConfig(JSON.parse(e));$$=t.warnings,N$=JSON.stringify({providers:t.providers,disabled:t.disabledProviderIds}),O$=t.providers.map(e=>({id:e.id,name:e.name??e.id,models:e.models}))}catch{}}function getCustomProviderModelsSync(){return O$||(seedSnapshotSync(),O$||(loadCustomProviderModels(),[]))}function getCustomProviderWarningsSync(){return $$}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){if(resolveKnownModelId2(e))return;const t=getCustomProviderModelsSync(),n=findQualified(t,e);return n?n.providerId:findDeclared(t,e)?.providerId}async function resolveSelectableModel(e){const t=e.trim();if(!t)return;const n=await loadCustomProviderModels(),r=resolveKnownModelId2(t);if(r)return{modelId:r};const o=t.indexOf("/");if(o>0){const e=t.slice(0,o).toLowerCase();if(n.some(t=>t.id===e))return findDeclared(n,t)??findQualified(n,t)}const s=resolveModelInput({model:t,models:getAllModelOptions()});return s?{modelId:s}:findDeclared(n,t)??findQualified(n,t)}function customProvidersDeclaring(e){const t=e.trim().toLowerCase();return getCustomProviderModelsSync().filter(e=>e.models.some(e=>e.id.toLowerCase()===t)).map(e=>e.id)}function customContextWindow(e){return declaredCustomModel(e)?.contextWindow}function customReasoningEfforts(e){return declaredCustomModel(e)?.reasoningEfforts}function declaredCustomModel(e){const t=getCustomProviderModelsSync(),n=findDeclared(t,e),r=n?void 0:findQualified(t,e),o=n??r;if(!o||o.warning)return;const s=t.find(e=>e.id===o.providerId);if(!s)return;const 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"),Vt(),Vt(),Vt(),PR(),Vt(),Vt();var F$=__name(({label:e="Loading",spinner:t=!1})=>it.createElement(et,{color:LR.DIM},t&&it.createElement(it.Fragment,null,it.createElement(bt,{type:"dots"})," "),e,"…"),"LoadingLine"),U$=__name(({children:e,glyph:t=!0})=>it.createElement(et,{color:LR.RED},t&&`${ft.cross} `,e),"ErrorLine"),j$=__name(({children:e,glyph:t=!0})=>it.createElement(et,{color:LR.GREEN},t&&`${ft.tick} `,e),"SuccessLine"),B$=__name(({title:e="Oops, something went wrong:",children:t})=>it.createElement(Ze,{flexDirection:"column",borderStyle:"single",borderColor:LR.RED,paddingX:2,paddingY:1,marginTop:1},it.createElement(et,{color:LR.RED,bold:!0},e),it.createElement(Ze,{marginTop:1},it.createElement(et,null,t))),"ErrorPanel"),W$=__name(({message:e,hint:t})=>it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.GRAY},e),t?it.createElement(et,{color:LR.DIM},t):null),"EmptyState"),H$=__name(({error:e,traceId:t})=>it.createElement(Ze,{marginBottom:2},it.createElement(B$,null,e,t&&it.createElement(et,{color:LR.DIM},"\n\n","Trace ID: ",t))),"ErrorSection");async function runTasteImport(e={}){const t=await runOnboardingImportWithEvents({events:up,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}))}}Vt(),Vt(),PR(),Vt(),PR(),__name(runTasteImport,"runTasteImport");var G$={isImporting:!1,waitingForInput:!1,error:null},V$=__name(e=>{const t=dt(null),n=dt(e);n.current=e;const[r,o]=ct({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null}),s=pt(()=>{const e=t.current;!e||e.isAborted()||(e.finishCancelled(),o(e=>({...e,...G$})))},[]);return ut(()=>{const e=createOnboardingImportLifecycle({events:up});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,...G$}));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");Vt();var z$,K$,q$=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{ot((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");function getRuntime(){return z$??=createNodeRuntime()}function getStore(){return K$??=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")}Vt(),PR(),Vt(),PR(),__name(getRuntime,"getRuntime"),__name(getStore,"getStore"),__name(checkOnboardingConditions2,"checkOnboardingConditions"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(markOnboardingSkipped2,"markOnboardingSkipped"),__name(dismissOnboardingForeverForProject,"dismissOnboardingForeverForProject"),__name(triggerTasteOnboarding,"triggerTasteOnboarding");var Y$=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=ct(null),[o,s]=ct(null),[a,i]=ct(void 0),l=dt(!1);return ut(()=>{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:qo.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");Vt(),PR();var Q$=__name(({conditions:e,autoLearn:t})=>{const[n,r]=ct("checking"),o=dt(!1);return ut(()=>{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]),ut(()=>{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{up.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{up.reset(),e()}}Vt(),PR(),Vt(),PR(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var J$=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=dt(n),o=pt(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=pt(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),a=pt(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),i=pt(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=pt(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");Vt(),PR();var X$=__name(e=>{const[t,n]=ct(()=>createTasteImportProjection({initialSteps:e})),r=pt(e=>{n(t=>({...t,importError:e}))},[]);return ut(()=>{const t=__name(()=>{n(resetTasteImportProjection({initialSteps:e}))},"handleReset"),r=__name(e=>{n(t=>reduceTasteImportEvent({state:t,event:e}))},"handleNewEvent");return up.on("reset",t),up.on("new-event",r),()=>{up.off("reset",t),up.off("new-event",r)}},[e]),{steps:t.steps,importError:t.importError,importTraceId:t.importTraceId,setImportError:r}},"useProgressEvents");Vt(),Vt(),Vt();var Z$=__name(({isImporting:e=!1,waitingForInput:t=!1})=>it.createElement(it.Fragment,null,e&&it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Esc to cancel")),t&&it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to continue"))),"HelpTextSection");Vt(),Vt(),Vt(),Vt();var eN=__name(()=>{const[e,t]=ct(!0);return ut(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),it.createElement(et,{color:LR.YELLOW},e?ft.circleFilled:ft.circle)},"PulsingDot");Vt();var tN=[ft.bullet,ft.squareSmallFilled,ft.lozenge,ft.star,ft.triangleRight,ft.triangleUp,ft.circleFilled,ft.pointer],nN=__name(e=>String(e).padStart(3," "),"padNum"),rN=__name(e=>tN[e%tN.length],"getSymbol"),oN=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${nN(t)} ↓${nN(n)} (↑↓ scroll)`,"buildStatusLine"),sN=__name(({insights:e})=>{const[t,n]=ct(0),[r,o]=ct(!0),s=e.length,a=s>10,i=Math.max(0,s-10),l=r&&a?i:t;if(ot((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 it.createElement(Ze,{flexDirection:"column",marginLeft:4,marginBottom:0},a&&it.createElement(et,{color:LR.DIM},oN(s,d,u,r)),c.map((e,t)=>{const n=l+t;return it.createElement(Ze,{key:n,marginBottom:0},it.createElement(et,{color:LR.DIM},rN(n)," ",e))}))},"ScrollableInsights");function getLabelColor(e,t){return e?LR.WHITE:t?LR.YELLOW:LR.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 aN=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:a,isAllComplete:i,summary:l,warning:c})=>{if(a)return it.createElement(Ze,{flexDirection:"column",marginBottom:0},it.createElement(IL,null),it.createElement(Ze,{marginTop:0},it.createElement(et,{color:LR.DIM},TL),it.createElement(Ze,{marginLeft:2},i?it.createElement(et,{color:DR.TEXT},"learned your coding taste"):it.createElement(vL,null))));const d=__name(()=>r?it.createElement(et,{color:FR.BG},ft.square):n?it.createElement(eN,null):it.createElement(et,{color:LR.DIM},ft.circle),"getStatusIcon"),u=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||u?it.createElement(Ze,{flexDirection:"column",marginBottom:0},(n||r)&&it.createElement(Ze,{marginBottom:0},it.createElement(Ze,{marginRight:1},d()),it.createElement(et,{color:getLabelColor(r,n)},e)),r&&t&&(!l||0===l.learningCount)&&it.createElement(Ze,{marginLeft:3,marginBottom:0},it.createElement(et,{color:LR.DIM},t)),o.length>0&&it.createElement(Ze,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map(e=>it.createElement(et,{key:e,color:LR.DIM},`${ft.bullet} ${e}`))),s.length>0&&it.createElement(sN,{insights:s}),r&&l&&l.learningCount>0&&it.createElement(Ze,{flexDirection:"column",marginLeft:1,marginBottom:0},it.createElement(Ze,{marginBottom:1,flexDirection:"row"},it.createElement(et,null,TL),it.createElement(Ze,{marginLeft:2},it.createElement(et,{color:DR.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",formatCategorySuffix(l.categories)))),it.createElement(Ze,{flexDirection:"column",marginLeft:1},it.createElement(et,{color:LR.DIM},ft.pointerSmall," Stored in ",l.storage),it.createElement(et,{color:LR.DIM},"Command Code automatically uses & updates taste files."))),r&&c&&it.createElement(Ze,{flexDirection:"column",marginLeft:1,marginBottom:0},c.split("\n").map(e=>it.createElement(et,{key:e,color:LR.YELLOW},`${ft.warning} ${e}`)))):null},"StepItem"),iN=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return it.createElement(Ze,{flexDirection:"column",marginBottom:1},e.map((e,n)=>it.createElement(Ze,{key:e.id,marginLeft:0===n?0:3},it.createElement(aN,{label:e.label,message:e.message,active:e.active,complete:e.complete,items:e.items,insights:e.insights,summary:e.summary,warning:e.warning,isIntro:0===n,isAllComplete:t}))))},"StepsSection"),lN=__name(({steps:e})=>it.createElement(iN,{steps:e}),"ProgressSection"),cN=__name(({onComplete:e,onCancel:t,onError:n,onErrorDismiss:r})=>{const{steps:o,importError:s,importTraceId:a}=X$(UI),{isImporting:i,waitingForInput:l,error:c,cancelImport:d}=V$(n);return q$({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}),it.createElement(Ze,{flexDirection:"column",padding:1},s&&it.createElement(H$,{error:s,traceId:a}),!s&&it.createElement(lN,{steps:o}),it.createElement(Z$,{isImporting:i,waitingForInput:l}))},"ImportProgress");async function runLearnTaste(){await applyStartupTheme();const{unmount:e}=rt(it.createElement(cN,{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 dN=new He("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(gg),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:qo.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 He("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 Ge("-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(yt.gray("Checking server authentication requirements..."));const t=await checkCommandMcpServerAuthRequirements(e);return t.requiresAuth&&console.log(yt.cyan("Server requires OAuth authentication.")),t},"checkServerAuthRequirements"),registerOAuthClient:__name(async e=>(console.log(yt.gray("Registering OAuth client...")),registerCommandMcpOAuthClient({registrationEndpoint:e.registrationEndpoint,clientName:e.clientName,redirectUris:[...e.redirectUris]})),"registerOAuthClient"),performOAuthFlow:__name(async e=>{console.log(yt.gray("A browser window will open for authentication.\n"));const t=await performCommandMcpOAuthFlow(e.serverName,e.serverUrl,{authorizationUrl:e.config.authorizationUrl,tokenUrl:e.config.tokenUrl,clientId:e.config.clientId,clientSecret:e.config.clientSecret,scopes:e.config.scopes?[...e.config.scopes]:void 0,resource:e.config.resource},{onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),onStatus:__name(e=>{console.log(yt.gray(` ${e}`))},"onStatus")});for(const e of s.warnings)console.log(yt.yellow(`Warning: ${e}`));"success"===s.authStatus&&console.log(yt.green("✓ Successfully authenticated")),"failed"===s.authStatus&&(console.log(yt.yellow(`Warning: Authentication failed: ${s.authError}`)),console.log(yt.gray(`You can retry with: ${getBinaryCommand()} mcp auth ${e}`)),console.log(yt.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?yt.yellow(a):yt.green(a)),console.log(yt.gray(` ${formatMcpCommandSummary(s.serverConfig)}`)),console.log(""),console.log(yt.cyan("Next steps:")),console.log(yt.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 _T)if(console.error(yt.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(yt.gray(`Usage: ${t.cliName} mcp add --transport stdio <name> -- <command> [args...]`)),void console.error(yt.gray(` or: ${t.cliName} mcp add <name> <command> [args...]`))):void("stdio-command-is-url"!==e.code?"insecure-oauth-url"===e.code&&(console.error(yt.gray("OAuth requires https:// (http:// is only allowed for loopback hosts: localhost, 127.0.0.1, [::1]).")),console.error(yt.gray("Switch the URL to https:// or use a non-OAuth server."))):e.suggestedCommand&&console.error(yt.gray(`Did you mean: ${e.suggestedCommand}`)));console.error(yt.gray(`Usage: ${t.cliName} mcp add --transport http <name> <url>`))}else console.error(yt.gray("Valid options: stdio, http"));else console.error(yt.gray(NT));else console.error(yt.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(yt.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function addJsonMcpCommand(){const e=new He("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 Ge("-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(yt.cyan("Starting OAuth authentication...")),console.log(yt.gray("A browser window will open for authentication.\n"));const t=await performCommandMcpOAuthFlow(e.serverName,e.serverUrl,{authorizationUrl:e.config.authorizationUrl,tokenUrl:e.config.tokenUrl,clientId:e.config.clientId,clientSecret:e.config.clientSecret,scopes:e.config.scopes?[...e.config.scopes]:void 0,resource:e.config.resource},{port:e.port,onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),onStatus:__name(e=>{console.log(yt.gray(` ${e}`))},"onStatus")});"success"===o.authStatus&&console.log(yt.green(`\n✓ Successfully authenticated with '${e}'`)),"failed"===o.authStatus&&(console.error(yt.yellow(`\nWarning: Authentication failed: ${o.authError}`)),console.error(yt.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(yt.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?yt.yellow(s):yt.green(s)),console.log(yt.gray(` ${formatMcpCommandSummary(o.serverConfig)}`)),console.log(""),console.log(yt.cyan("Next steps:")),console.log(yt.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 _T)if(console.error(yt.red(`Error: ${e.message}`)),"invalid-name"!==e.code){if("invalid-json"===e.code)return console.error(yt.gray("Make sure to quote the JSON string properly")),void console.error(yt.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(yt.gray(` ${t.path.join(".")}: ${t.message}`));else"missing-http-url"!==e.code&&e.code}else console.error(yt.gray(NT));else console.error(yt.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function authMcpCommand(){const e=new He("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(yt.red("Error: Server name is required")),console.error(yt.gray(`Usage: ${n} mcp auth <server>`)),console.error(yt.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(yt.green(`✓ Cleared authentication for '${e}'`)):void console.log(yt.yellow(`No authentication stored for '${e}'`));console.log(yt.cyan(`Authenticating with '${e}'...`)),console.log(yt.gray("A browser window will open for authentication.\n")),await authenticateConfiguredMcpServer({serverName:e,getMcpServer:getMcpServer,performOAuthFlow:__name(async e=>{const t=await performCommandMcpOAuthFlow(e.serverName,e.serverUrl,{authorizationUrl:e.config.authorizationUrl,tokenUrl:e.config.tokenUrl,clientId:e.config.clientId,clientSecret:e.config.clientSecret,scopes:e.config.scopes?[...e.config.scopes]:void 0,resource:e.config.resource},{onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),discoverAndAuthenticate:discoverAndAuthenticateCommandMcpServer,onStatus:__name(e=>{console.log(yt.gray(` ${e}`))},"onStatus")}),console.log(yt.green(`\n✓ Successfully authenticated with '${e}'`)),console.log(yt.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(yt.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=t.expired?yt.yellow("expired"):yt.green("valid");console.log(` ${t.serverName}: ${e}`)}console.log("")}else console.log(yt.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(yt.yellow(`Authentication for '${e}' has expired`)),void(t.hasRefreshToken&&console.log(yt.gray(" A refresh token is available for re-authentication")));console.log(yt.green(`Authentication for '${e}' is valid`)),"number"==typeof t.expiresInMinutes&&console.log(yt.gray(` Expires in ${t.expiresInMinutes} minutes`)),t.scope&&console.log(yt.gray(` Scopes: ${t.scope}`))}else console.log(yt.yellow(`No authentication stored for '${e}'`))}function printMcpAuthError(e,t){if(e instanceof _T)return"server-not-found"===e.code?(console.error(yt.red(`Error: ${e.message}`)),void console.error(yt.gray(`Use "${t.cliName} mcp list" to see configured servers`))):"auth-failed"===e.code?(console.error(yt.red(`\nError: ${e.message}`)),void(t.serverName&&console.log(yt.gray(`Try again with "${t.cliName} mcp auth ${t.serverName}"`)))):void console.error(yt.red(`Error: ${e.message}`));console.error(yt.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function getMcpCommand(){const e=new He("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(yt.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${yt.dim("Scope:")} ${r}`),console.log(` ${yt.dim("Transport:")} ${n.transport}`),console.log(` ${yt.dim("Status:")} ${n.enabled?yt.green("enabled"):yt.gray("disabled")}`),"http"===n.transport){if(console.log(` ${yt.dim("URL:")} ${n.url}`),t.headers.length>0){console.log(` ${yt.dim("Headers:")}`);for(const e of t.headers)console.log(` ${e.key}: ${e.value}`)}}else console.log(` ${yt.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${yt.dim("Args:")} ${n.args.join(" ")}`);if(t.env.length>0){console.log(` ${yt.dim("Environment:")}`);for(const e of t.env)console.log(` ${e.key}=${e.value}`)}console.log("")}catch(e){e instanceof _T&&(console.error(yt.red(`Error: ${e.message}`)),process.exit(1)),console.error(yt.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function formatAuthIcon(e){return"authenticated"===e||"static"===e?yt.green(ft.tick):"missing"===e?yt.red(ft.cross):yt.gray("-")}function listMcpCommand(){const e=new He("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(yt.yellow("\nNo MCP servers configured\n")),console.log(yt.gray("Add a server with:")),console.log(yt.gray(` ${getBinaryCommand()} mcp add --transport http <name> <url>`)),console.log(yt.gray(` ${getBinaryCommand()} mcp add --transport stdio <name> -- <command>`)),void console.log(yt.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(yt.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(yt.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.enabled?yt.green("enabled"):yt.gray("disabled"),s=formatAuthIcon(o.authStatus);console.log(` ${yt.white(o.name.padEnd(t))} ${yt.cyan(o.transport.padEnd(n))} ${yt.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(yt.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(yt.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new He("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Ge("-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(yt.green(`✓ Removed MCP server '${e}' from ${n.scopeLabel} config`))}catch(e){e instanceof _T&&(console.error(yt.red(`Error: ${e.message}`)),process.exit(1)),console.error(yt.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new He("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(H(),e);return!n||n.startsWith("..")||i(n)?e:`~${l}${n}`}Vt(),Vt(),PR(),Vt(),PR(),__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),__name(addMcpCommand,"addMcpCommand"),__name(printMcpAddError,"printMcpAddError"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),__name(printCollectError,"printCollectError"),Vt(),PR(),__name(addJsonMcpCommand,"addJsonMcpCommand"),__name(printMcpAddJsonError,"printMcpAddJsonError"),Vt(),PR(),__name(authMcpCommand,"authMcpCommand"),__name(printAuthList,"printAuthList"),__name(printAuthStatus,"printAuthStatus"),__name(printMcpAuthError,"printMcpAuthError"),Vt(),PR(),__name(getMcpCommand,"getMcpCommand"),Vt(),PR(),__name(formatAuthIcon,"formatAuthIcon"),__name(listMcpCommand,"listMcpCommand"),Vt(),PR(),__name(removeMcpCommand,"removeMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Vt(),Vt(),PR(),Vt(),PR(),__name(shortenModPath,"shortenModPath");var uN=__name(e=>e.split(H()).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(Pt.dim(`Installing ${t.kind} mod source ${Pt.reset(Pt.cyan(e))} (${r})…`));const o=await installModSource({runtime:n,source:e,scope:r}),s=await createModPathShortener(n);console.log(`${Pt.green(ft.tick)} Installed ${Pt.cyan(o.identity)}`),o.installedPath&&console.log(Pt.dim(` ${s(o.installedPath)}`)),console.log(Pt.dim(` Recorded in ${s(o.settingsPath)}`))}catch(e){console.error(`${Pt.red(ft.cross)} ${uN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}__name(createModPathShortener,"createModPathShortener"),__name(addAction,"addAction");var mN=new He("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);Vt(),PR(),Vt(),Vt(),Vt();var pN={running:0,waitingPermission:0,waitingQuestion:0,compacting:0};function bump(e,t){return Math.max(0,e+t)}function nextLifecycle(e,t){return"run_start"===t.type?{...e,running:e.running+1}:"run_end"===t.type?{...e,running:bump(e.running,-1)}:"compaction_start"===t.type?{...e,compacting:e.compacting+1}:"compaction_done"===t.type?{...e,compacting:bump(e.compacting,-1)}:"interaction_requested"===t.type?"permission"===t.kind?{...e,waitingPermission:e.waitingPermission+1}:{...e,waitingQuestion:e.waitingQuestion+1}:"interaction_resolved"===t.type?"permission"===t.kind?{...e,waitingPermission:bump(e.waitingPermission,-1)}:{...e,waitingQuestion:bump(e.waitingQuestion,-1)}:e}function reportFor(e){return e.waitingPermission>0?{state:"blocked",message:"permission"}:e.waitingQuestion>0?{state:"blocked",message:"question"}:e.running>0||e.compacting>0?{state:"working"}:{state:"idle"}}function reportKey(e){return`${e.state}:${e.message??""}`}__name(bump,"bump"),__name(nextLifecycle,"nextLifecycle"),__name(reportFor,"reportFor"),__name(reportKey,"reportKey"),Vt(),Vt();var gN=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`,"g");function sanitizeTitleForOutput(e){const t=e.replace(gN,"");let n="";for(const e of t){const t=e.codePointAt(0)??0;n+=t<=31||t>=127&&t<=159?" ":e}return n.replace(/\s{2,}/g," ").trim()}__name(sanitizeTitleForOutput,"sanitizeTitleForOutput");var hN="cmd",fN=`custom:${hN}`,yN="CMD_HERDR_PANE_OWNER";function resolveHerdrConfig(e){const t=e.CMD_HERDR?.trim().toLowerCase();if("0"===t||"false"===t)return null;if("1"!==e.HERDR_ENV?.trim())return null;if(e[yN])return null;const n=e.HERDR_SOCKET_PATH?.trim(),r=e.HERDR_PANE_ID?.trim();return n&&r?{socketPath:n,paneId:r}:null}function releasedPaneOwnerEnv(e,t){return e[yN]===String(t)?{[yN]:void 0}:{}}function claimHerdrPane(e){e[yN]=String(process.pid)}function clampBytes(e,t){if(!e)return;const n=sanitizeTitleForOutput(e);return n?Buffer.from(n,"utf-8").subarray(0,t).toString("utf-8").replace(/�$/,""):void 0}function clampText(e){if(!e)return;const t=sanitizeTitleForOutput(e);if(!t)return;const n=Array.from(t);return n.length<=80?t:n.slice(0,80).join("")}function metadataParams(e){const t=clampText(e.title),n=clampText(e.displayAgent),r=Object.fromEntries(Object.entries(e.tokens??{}).flatMap(([e,t])=>{const n=clampText(t);return n?[[e,n]]:[]}));return{...t?{title:t}:{},...!t&&e.clearTitle?{clear_title:!0}:{},...n?{display_agent:n}:{},...Object.keys(r).length>0?{tokens:r}:{}}}function buildHerdrLine(e){const{id:t,seq:n,paneId:r,request:o}=e,s={id:String(t)},a={pane_id:r,source:fN,agent:hN,seq:n};if("report"===o.kind){const e=clampBytes(o.message,32);return`${JSON.stringify({...s,method:"pane.report_agent",params:{...a,state:o.state,...e?{message:e}:{}}})}\n`}return"session"===o.kind?`${JSON.stringify({...s,method:"pane.report_agent_session",params:{...a,agent_session_id:o.sessionId}})}\n`:"metadata"===o.kind?`${JSON.stringify({...s,method:"pane.report_metadata",params:{...a,...metadataParams(o.metadata)}})}\n`:"paneRename"===o.kind?`${JSON.stringify({...s,method:"pane.rename",params:{pane_id:r,label:o.label}})}\n`:"agentRename"===o.kind?`${JSON.stringify({...s,method:"agent.rename",params:{target:r,name:o.name}})}\n`:`${JSON.stringify({...s,method:"pane.release_agent",params:a})}\n`}function herdrSocketEndpoint(e){const{socketPath:t,platform:n=process.platform}=e;return"win32"===n?`\\\\.\\pipe\\${t}`:t}function sendHerdrLine(e){const t=e.timeoutMs??250;return new Promise(n=>{let r=!1;const o=fe.createConnection(herdrSocketEndpoint({socketPath:e.socketPath})),s=__name(()=>{r||(r=!0,clearTimeout(a),o.destroy(),n())},"finish"),a=setTimeout(s,t);a.unref?.(),o.setEncoding("utf-8"),o.on("connect",()=>{o.write(e.line)}),o.on("data",e=>{e.includes("\n")&&s()}),o.on("error",s),o.on("close",s)})}__name(resolveHerdrConfig,"resolveHerdrConfig"),__name(releasedPaneOwnerEnv,"releasedPaneOwnerEnv"),__name(claimHerdrPane,"claimHerdrPane"),__name(clampBytes,"clampBytes"),__name(clampText,"clampText"),__name(metadataParams,"metadataParams"),__name(buildHerdrLine,"buildHerdrLine"),__name(herdrSocketEndpoint,"herdrSocketEndpoint"),__name(sendHerdrLine,"sendHerdrLine");var SN={enabled:!1,reportState:__name(()=>{},"reportState"),reportSession:__name(()=>{},"reportSession"),reportMetadata:__name(()=>{},"reportMetadata"),announce:__name(()=>{},"announce"),release:__name(()=>Promise.resolve(),"release")};function createHerdrReporter(e){const{config:t}=e;if(!t)return SN;const n=e.send??sendHerdrLine,r=e.now??Date.now;let o=1,s=1e3*r(),a=Promise.resolve(),i=0;const l=__name(e=>{const n=o;return o+=1,s+=1,buildHerdrLine({id:n,seq:s,paneId:t.paneId,request:e})},"nextLine"),c=__name(e=>{const r=l(e),o=i;return a=a.then(()=>o!==i?Promise.resolve():n({socketPath:t.socketPath,line:r})).catch(()=>{}),a},"enqueue");return{enabled:!0,reportState:__name((e,t)=>{c({kind:"report",state:e,message:t})},"reportState"),reportSession:__name(e=>{e&&c({kind:"session",sessionId:e})},"reportSession"),reportMetadata:__name(e=>{c({kind:"metadata",metadata:e})},"reportMetadata"),announce:__name(()=>{c({kind:"paneRename",label:hN}),c({kind:"agentRename",name:hN})},"announce"),release:__name(()=>{const e=l({kind:"release"});return i+=1,n({socketPath:t.socketPath,line:e}).catch(()=>{})},"release")}}__name(createHerdrReporter,"createHerdrReporter");var wN=["run_start","run_end","interaction_requested","interaction_resolved","compaction_start","compaction_done"];function isHostEvent(e){return"session_start"===e.type||"session_shutdown"===e.type}function createHerdrMod(e={}){return t=>{const n=e.env??process.env,r=void 0!==e.config?e.config:resolveHerdrConfig(n),o=e.reporter??createHerdrReporter({config:r});r&&claimHerdrPane(n);let s=pN,a=null,i=null,l=null,c=null;if(t.addCommand({name:"herdr",description:"Show herdr reporting status for this pane",handler:__name(()=>{if(!o.enabled)return{message:["herdr: not reporting.","This session was not launched by herdr (HERDR_ENV, HERDR_SOCKET_PATH and","HERDR_PANE_ID must all be set), or CMD_HERDR=0 disabled it."].join("\n")};const e=reportFor(s);return{message:[`herdr: reporting to pane ${r?.paneId??"unknown"}`,` state ${e.state}${e.message?` (${e.message})`:""}`,` session ${i??"not yet started"}`,` model ${l??"not yet requested"}`,"","Control herdr from here — split panes, start other agents,","wait for them to finish:"," npx skills add herdrdev/herdr --skill herdr"].join("\n")}},"handler")}),!o.enabled)return;const d=__name(()=>{const e=reportFor(s),t=reportKey(e);t!==a&&(a=t,o.reportState(e.state,e.message))},"flushState"),u=__name(()=>{o.reportMetadata({...c?{title:c}:{clearTitle:!0},displayAgent:l?`cmd · ${l}`:"cmd",...l?{tokens:{model:l}}:{}})},"flushMetadata"),m=__name(e=>{e&&e!==i&&(i=e,o.reportSession(i))},"reportSessionOnce");t.hooks({onSessionStart:__name(({sessionId:e})=>{s=pN,a=null,i=null,l=null,c=null,o.announce(),m(e),u(),d()},"onSessionStart"),onSessionEnd:__name(()=>o.release(),"onSessionEnd")});for(const e of wN)t.on(e,e=>{isHostEvent(e)||(s=nextLifecycle(s,e),"run_start"===e.type&&m(e.sessionId),d())});t.on("session_titled",e=>{"session_titled"===e.type&&e.title!==c&&(c=e.title,u())}),t.on("model_request_start",e=>{"model_request_start"===e.type&&e.model!==l&&(l=e.model,u())})}}__name(isHostEvent,"isHostEvent"),__name(createHerdrMod,"createHerdrMod");var vN=createHerdrMod();function providerMod(e){return{name:`provider-${e.id}`,factory:__name(async t=>{try{const n=await loadBuiltinProviderModule({moduleId:e.id,install:!1});n&&t.addProvider(n)}catch(t){dlog("[ProviderPackages] builtin provider mod skipped",{pkg:e.package,error:t instanceof Error?t.message:String(t)})}},"factory")}}function providerBuiltinMods(){return UD.map(providerMod)}function updateNoticeMod(e){try{const t=readUpdatesConfig().pending;if(!t?.targetVersion)return;const n=getPackageJson(import.meta.url).version;if(t.targetVersion===n)return;e.ui.notify(`update available: v${t.targetVersion} (installing in the background — a restart applies it)`)}catch{}}function commandBuiltinMods(){return[...providerBuiltinMods(),{name:"update-notice",factory:updateNoticeMod},{name:"herdr",factory:vN}]}Vt(),PR(),__name(providerMod,"providerMod"),__name(providerBuiltinMods,"providerBuiltinMods"),Vt(),PR(),__name(updateNoticeMod,"updateNoticeMod"),__name(commandBuiltinMods,"commandBuiltinMods");var kN={user:"user settings",projectShared:"project settings",projectLocal:"project-local settings"};function conflictAction(e){const{name:t,file:n}=e;return"user"===n.scope?`To enable it at the user level, run: ${getBinaryCommand()} mods enable ${t} -g`:"projectShared"===n.scope?`To enable it at the project level, run: ${getBinaryCommand()} mods enable ${t}`:`Remove "${t}" from "mods.disabled" in that file, then run this again.`}function toggleReport(e){const{name:t,enabled:n,global:r,includeProject:o,settingsPath:s,disabledIn:a}=e,[i]=a;if(n&&i)return{conflict:!0,headline:`${t} is still disabled`,detail:`Your ${kN[i.scope]} (${i.path}) disable it.`,action:conflictAction({name:t,file:i})};const l=`${n?"Enabled":"Disabled"} ${t} at the ${r?"user":"project"} level`;return r||o?{conflict:!1,headline:l,detail:`Saved to ${s} · applies from your next session (or /reload)`}:{conflict:!1,headline:l,detail:`Saved to ${s} · applies once you start Command Code in this project`,action:`To ${n?"enable":"disable"} at user level: ${getBinaryCommand()} mods ${n?"enable":"disable"} ${t} -g`}}function notBuiltinHint(e){const{name:t,enabled:n}=e;if(n&&!commandBuiltinMods().some(e=>e.name===t))return`${t} is not a built-in mod, so this only lifts a disable — it does not install anything (${getBinaryCommand()} mods add does)`}async function toggleAction(e){const{name:t,enabled:n,options:r}=e,o=createNodeRuntime();try{const e=await setModEnabledInSettings({runtime:o,scope:r.global?"user":"projectShared",name:t,enabled:n}),s=await createModPathShortener(o),a=await isCommandProjectSessionInitialized(),i=await modDisabledSettingsFiles({runtime:o,includeProject:!0,name:t}),l=toggleReport({name:t,enabled:n,global:!0===r.global,includeProject:a,settingsPath:s(e),disabledIn:i.map(e=>({...e,path:s(e.path)}))});if(l.conflict)return console.error(`${Pt.yellow(ft.warning)} ${l.headline}`),console.error(Pt.dim(` ${l.detail}`)),l.action&&console.error(Pt.dim(` ${l.action}`)),void(process.exitCode=1);console.log(`${Pt.green(ft.tick)} ${l.headline}`),console.log(Pt.dim(` ${l.detail}`));const c=notBuiltinHint({name:t,enabled:n});c&&console.log(Pt.dim(` ${c}`)),l.action&&console.log(Pt.dim(` ${l.action}`))}catch(e){console.error(`${Pt.red(ft.cross)} ${uN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}__name(conflictAction,"conflictAction"),__name(toggleReport,"toggleReport"),__name(notBuiltinHint,"notBuiltinHint"),__name(toggleAction,"toggleAction");var CN=new He("enable").description("Switch a mod on by name — how opt-in built-ins are turned on").argument("<name>","mod name (e.g. update-notice)").option("-g, --global","write user scope instead of project").action((e,t)=>toggleAction({name:e,enabled:!0,options:t})),bN=new He("disable").description("Switch a mod off by name without uninstalling it").argument("<name>","mod name from `mods list` (or a built-in)").option("-g, --global","write user scope instead of project").action((e,t)=>toggleAction({name:e,enabled:!1,options:t}));function builtinState(e){const{builtin:t,disabled:n,enabled:r}=e;return n.has(t.name)?"disabled":!1!==t.defaultEnabled||r.has(t.name)?"enabled":`off by default · \`${getBinaryCommand()} mods enable ${t.name}\``}Vt(),PR(),__name(builtinState,"builtinState");var EN=__name((e,t,n)=>` ${Pt.cyan(e)} ${Pt.dim(`· ${t} · ${n}`)}`,"formatModLine"),TN=__name((e,t)=>`${Pt.bold(Pt.white(e))} ${Pt.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=new Set(r.enabled),l=await modsDirectoryPath({runtime:t,scope:"project"}),c=await modsDirectoryPath({runtime:t,scope:"user"}),d=l?s(l,"..",".."):void 0,u=["project","user","package","path"].flatMap(e=>r.entries.filter(t=>t.source===e));console.log(""),console.log(`${Pt.bold(Pt.white("Mods"))} ${Pt.dim(`(${r.entries.length})`)}`),0===r.entries.length&&(console.log(""),console.log(Pt.dim(" No mods loaded. Looking in:")),l&&console.log(Pt.dim(` ${shortenModPath(l,d)} ${Pt.white("(project)")}`)),c&&console.log(Pt.dim(` ${shortenModPath(c,void 0)} ${Pt.white("(user)")}`)),console.log(""),console.log(Pt.dim(` Drop a .ts file in one (\`${getBinaryCommand()} mods open --user\`) or install a package: \`${getBinaryCommand()} mods add <source>\`.`)));for(const e of u)console.log(EN(e.name,scopeFor({entry:e,sources:o}),detailFor({entry:e,sources:o,projectRoot:d,disabled:a})));if(!0===e.builtin){const e=commandBuiltinMods();console.log(""),console.log(TN("Built-in",e.length));for(const t of e)console.log(EN(t.name,"builtin",builtinState({builtin:t,disabled:a,enabled:i})))}const m=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(TN("Package sources",t.length));for(const e of t){m.add(e.source);const t=e.installed?Pt.yellow("installed, but provides no mods"):Pt.yellow(`not installed — run \`${getBinaryCommand()} mods update\``);console.log(EN(e.identity,e.scope,t))}}}const p=r.warnings.filter(e=>!m.has(e.path));if(p.length>0){console.log(""),console.log(`${Pt.bold(Pt.yellow("Warnings"))} ${Pt.dim(`(${p.length})`)}`);for(const e of p)console.log(` ${Pt.cyan(shortenModPath(e.path,d))} ${Pt.dim(`· ${e.reason}`)}`)}console.log("")}__name(scopeFor,"scopeFor"),__name(detailFor,"detailFor"),__name(listAction,"listAction");var PN=new He("list").alias("ls").description("List the mods a session loads, and where each one comes from").addOption(new Ge("--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 xt(o);const a=await createModPathShortener(t);console.log(`${Pt.green(ft.tick)} Opened ${Pt.cyan(a(o))} ${Pt.dim(`· ${s}`)}`)}catch(e){console.error(`${Pt.red(ft.cross)} ${uN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}Vt(),PR(),__name(openAction,"openAction");var MN=new He("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(`${Pt.red(ft.cross)} ${Pt.cyan(e)} is a built-in mod — it cannot be removed. Add it to ${Pt.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(`${Pt.yellow(ft.warning)} ${Pt.cyan(o.target)} is not configured (${o.scope} scope) — nothing to remove`);const s=await createModPathShortener(n);console.log(`${Pt.green(ft.tick)} Removed ${Pt.cyan(o.target)} ${Pt.dim(`· ${o.scope}`)}`),o.sourceIdentity&&o.sourceIdentity!==o.target&&console.log(Pt.dim(` Removed its source ${o.sourceIdentity}`)),o.alsoRemoved&&o.alsoRemoved.length>0&&console.log(Pt.dim(` That source also provided ${o.alsoRemoved.join(", ")}`)),o.removedPath&&console.log(Pt.dim(` Deleted ${s(o.removedPath)}`)),o.removedFromSettings&&o.settingsPath&&console.log(Pt.dim(` Updated ${s(o.settingsPath)}`))}catch(e){console.error(`${Pt.red(ft.cross)} ${uN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}Vt(),PR(),__name(removeAction,"removeAction");var xN=new He("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(`${Pt.green(ft.tick)} ${Pt.cyan(e)}`);for(const e of t.failures)console.error(`${Pt.red(ft.cross)} ${e.source} ${Pt.dim(`· ${e.reason}`)}`);0===t.updated.length&&0===t.failures.length&&console.log(Pt.dim("No mod package sources configured.")),t.failures.length>0&&process.exit(1)}Vt(),PR(),__name(updateAction,"updateAction");var IN=new He("update").alias("up").description("Reinstall and reconcile every configured mod package").action(updateAction),AN=new He("mods").description("Manage mods — loadable extensions from npm, git, or local paths").addCommand(mN).addCommand(xN).addCommand(PN).addCommand(IN).addCommand(MN).addCommand(CN).addCommand(bN);function resolveBundledRipgrepPath(){try{const e=Ct(import.meta.url),{rgPath:t}=e("@vscode/ripgrep");if("string"==typeof t&&t.length>0&&A(t))return t}catch{}}function registerBundledRipgrep(){if(process.env[pc])return;const e=resolveBundledRipgrepPath();void 0!==e&&(process.env[pc]=e)}Vt(),PR(),__name(resolveBundledRipgrepPath,"resolveBundledRipgrepPath"),__name(registerBundledRipgrep,"registerBundledRipgrep"),Vt(),PR(),Vt();var RN=["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!!RN.some(e=>r.includes(`write ${e}`))||"write"===("string"==typeof t.syscall?t.syscall:"")&&RN.includes(n)}__name(asErrnoLike,"asErrnoLike"),__name(isBenignStreamWriteError,"isBenignStreamWriteError"),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt();var LN={enabled:!1,requestedSessionId:null,baseBranch:null,connection:null};function enableSandboxMode(e){LN.enabled=!0,LN.requestedSessionId=e.sessionId??null,LN.baseBranch=e.baseBranch??null}function getRequestedSandboxBase(){return LN.baseBranch}function isSandboxMode(){return LN.enabled}function getRequestedSandboxSessionId(){return LN.requestedSessionId}function setSandboxConnection(e){LN.connection=e}function getSandboxConnection(){return LN.connection}__name(enableSandboxMode,"enableSandboxMode"),__name(getRequestedSandboxBase,"getRequestedSandboxBase"),__name(isSandboxMode,"isSandboxMode"),__name(getRequestedSandboxSessionId,"getRequestedSandboxSessionId"),__name(setSandboxConnection,"setSandboxConnection"),__name(getSandboxConnection,"getSandboxConnection");var ON="Running the task in the sandbox",DN=null;function setAdoptedTurn(e){DN=e}function hasAdoptedTurn(){return null!==DN}function takeAdoptedTurn(){const e=DN;return DN=null,e}__name(setAdoptedTurn,"setAdoptedTurn"),__name(hasAdoptedTurn,"hasAdoptedTurn"),__name(takeAdoptedTurn,"takeAdoptedTurn");var $N=!1;function interruptSandboxTurn(e){$N=!0,e.request({method:"turn/interrupt"}).catch(()=>{})}function takeInterruptWanted(){const e=$N;return $N=!1,e}__name(interruptSandboxTurn,"interruptSandboxTurn"),__name(takeInterruptWanted,"takeInterruptWanted");var NN=null;function openSandboxConnectionOnce(e){return NN||(NN=e()),NN}__name(openSandboxConnectionOnce,"openSandboxConnectionOnce");var _N=new Set(["rewind","tree","fork","clone","share","compact","mcp","plan","mode","worktree","rename","resume","goal","pr-comments","reload","clear","loop","rc","init","import","memory","learn-taste","add-dir","connect","sessions","name","unshare","session-file","context","todos","trace"]);function sandboxBashMessage(){return LN.enabled?"! commands are not supported in a sandbox session yet.":null}function sandboxGateMessage(e){return LN.enabled&&_N.has(e)?`/${e} is not supported in a sandbox session yet.`:null}function sandboxModelFor(e){if(e)return byokProviderId({model:e})?void 0:e}function sandboxEffortFor(e){if(!e||!sandboxModelFor(e))return;const t=getReasoningEffort(e);return t&&(customReasoningEfforts(e)??getSupportedEfforts(e)??[]).includes(String(t))?String(t):void 0}async function tellSandboxEffort(e){const t=getSandboxConnection();if(!t||void 0===e.effort)return{ok:!0};const n=(await t.request({method:"session/set_effort",params:{effort:e.effort}}).catch(e=>({error:{message:String(e)}}))).error;return n?{ok:!1,message:sandboxRefusal({failure:n,command:"/effort",what:"effort"})}:{ok:!0}}function sandboxRefusal(e){const{failure:t,command:n,what:r}=e;return t.code===PT.TURN_ACTIVE?`The sandbox is working on a turn; run ${n} again once it has finished.`:`The sandbox kept its ${r}: ${(t.message??"the change was refused").replace(/^Error: /,"").replace(/\.$/,"")}.`}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=I$(e.sessionId),a=s?s.getEffort():r,i=await tellSandboxEffort({effort:t});return i.ok?(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,hh(`Reasoning effort set to ${t}.`)])):void e.setFeed(e=>[...e,hh(i.message)])}if(r.length>0)return void e.setFeed(e=>[...e,hh(`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,hh(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=dt(!1);return pt(async e=>{const o=processBracketedPaste(e),s=n??t,a=__name(async()=>{r.current=!1;const e=await detectClipboardTextNative();e?s(e):o.cleanedContent&&s(o.cleanedContent)},"applyPastedText");if(!o.isPasteStart||r.current)r.current&&!o.isPasteEnd||(r.current&&o.isPasteEnd?await 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(sandboxBashMessage,"sandboxBashMessage"),__name(sandboxGateMessage,"sandboxGateMessage"),__name(sandboxModelFor,"sandboxModelFor"),__name(sandboxEffortFor,"sandboxEffortFor"),__name(tellSandboxEffort,"tellSandboxEffort"),__name(sandboxRefusal,"sandboxRefusal"),__name(handleEffortCommand,"handleEffortCommand"),__name(applyEffortSetting,"applyEffortSetting"),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt(),PR(),__name(usePasteAwareChange,"usePasteAwareChange"),__name(extractDeviceCode2,"extractDeviceCode");var FN=__name(({providerId:e,onSuccess:t,onCancel:n,onFailure:r})=>{const o=getProviderDisplayName(e),[s,a]=ct("confirm"),[i,l]=ct(""),[c,d]=ct(""),[u,m]=ct(""),[p,g]=ct(""),[h,f]=ct(null),y=dt(!1),S=dt(!0),w=dt(!1),v=dt(null),k=dt(null),C=dt(null),b=dt(!1);ut(()=>()=>{S.current=!1,v.current&&clearTimeout(v.current),C.current=null},[]);const E=pt(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;xt(e.authUrl,t).catch(()=>{S.current&&f(`Failed to open browser. Please manually open: ${e.authUrl}`)})},300))},[]),T=pt(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===fo.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"),xt(t.url).catch(()=>{S.current&&f(`Failed to open browser. Please manually open: ${t.url}`)}),e({})}})},[e,E]),P=dt(()=>{});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=pt(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(ot((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===fo.COPILOT?"This will get a GitHub sign-in code.":`This will open your browser to sign in with ${o}.`;return it.createElement(RO,{title:`Sign in to ${o}`,subtitle:t,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"y"),"/",it.createElement(CO,null,"enter")," ","continue"),it.createElement(it.Fragment,null,it.createElement(CO,null,"n"),"/",it.createElement(CO,null,"esc")," ","cancel")]})})}return"connecting"===s?it.createElement(RO,{title:`Sign in to ${o}`,subtitle:"Getting sign-in code…",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," cancel")]})}):"paste"===s?it.createElement(RO,{title:`Sign in to ${o}`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," submit"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," cancel")]})},i&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},"Login: "),it.createElement(yL,{url:i,text:"Open auth page ↗",color:LR.CYAN})),c&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},c)),h&&it.createElement(Ze,{marginBottom:1},it.createElement(U$,null,h)),it.createElement(Ze,null,it.createElement(et,null,u||"Authorization code",": "),it.createElement(TextInput,{mask:"*",focus:!0,value:p,onChange:x,onSubmit:I,placeholder:"Paste code here..."}))):"open-browser"===s?it.createElement(RO,{title:`Sign in to ${o}`,subtitle:e===fo.COPILOT?"Press enter to open GitHub and paste the code there":"Press enter to open your browser",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," cancel")]})},c&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0,color:LR.GREEN},c)),i&&e!==fo.COPILOT&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},"Login: "),it.createElement(yL,{url:i,text:"Open auth page ↗",color:LR.CYAN}))):"waiting"===s?it.createElement(RO,{title:`Sign in to ${o}`,subtitle:"Waiting for authorization…",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," cancel")]})},c&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0,color:LR.GREEN},c)),i&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},"Open: "),it.createElement(yL,{url:i,text:"Open auth page ↗",color:LR.CYAN}))):"error"===s?it.createElement(RO,{title:`Sign in to ${o}`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," back")]})},it.createElement(U$,null,h)):null},"ProviderAuth");function makeProviderAuthComponent(e){const t=__name(({onSuccess:t,onCancel:n})=>it.createElement(FN,{providerId:e,onSuccess:t,onCancel:n}),"Bound");return t.displayName=`ProviderAuth(${e})`,t}__name(makeProviderAuthComponent,"makeProviderAuthComponent");var UN=Object.fromEntries(Object.entries(rs).map(([e,t])=>[e,{...t}]));function getProviderConfig(e){return UN[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=getSandboxConnection(),S=null!==y&&void 0!==sandboxModelFor(e),w=null!==y&&null!==await getProviderAuthState(g);if(y&&S&&!w){const t=(await y.request({method:"session/set_model",params:{model:e}}).catch(e=>({error:{message:String(e)}}))).error;if(t)return u?.(e=>[...e,hh(sandboxRefusal({failure:t,command:"/model",what:"model"}))]),void o(!1)}const v=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"===v.status)return s(v.message),void o(!1);if(d&&g&&g!==f&&await rebuildHarnessSession(d),r(e),v.modelChanged&&(hardResetForResize(),c(e=>e+1)),o(!1),s(v.statusMessage),v.modelChanged&&p?.(getModelNotice(e)??null),y&&!S)u?.(t=>[...t,hh(`${e} is a custom model this machine serves; the sandbox keeps its current model.`)]);else if(y){const t=await tellSandboxEffort({effort:sandboxEffortFor(e)});t.ok||u?.(e=>[...e,hh(t.message)])}if(v.modelChanged){const t=await reconcileCommandModelSelection({modelId:e,...void 0!==h?{routeProvider:h}:{},modelName:v.modelName,previousModel:v.previousModel,harness:d?I$(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,hh(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,hh(`Unknown model "${n}" — opening the model picker so you can choose.`)]),void e.setShowModelSelector(!0);r.warning&&e.setFeed(e=>[...e,hh(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&&(UL(),hardResetForResize(),r(e=>e+1)),n(buildThemeStatusMessage(e))}catch{n(Io)}}function handleThemeCancel({setShowThemeSelector:e}){e(!1)}async function handleThemeCommand(e,t){const n=t.trim().toLowerCase();n?uo.includes(n)?await handleThemeSelect({theme:n,setShowThemeSelector:e.setShowThemeSelector,setStatus:e.setStatus,setStaticKey:e.setStaticKey}):e.setFeed(e=>[...e,hh(`Unknown theme "${n}". Options: ${uo.join(", ")}.`)]):e.setShowThemeSelector(!0)}async function applyThemeSetting(e){const t=e.trim().toLowerCase();return t?uo.includes(t)?(await setCliTheme({theme:t}),{ok:!0,message:`Theme set to ${t}.`}):{ok:!1,message:`Unknown theme "${e.trim()}". Options: ${uo.join(", ")}.`}:{ok:!1,message:"Provide a theme, e.g. --theme auto."}}UN.anthropic&&(UN.anthropic.authComponent=makeProviderAuthComponent(fo.ANTHROPIC),UN.anthropic.checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:fo.ANTHROPIC});return!!e}),UN["github-copilot"]&&(UN["github-copilot"].authComponent=makeProviderAuthComponent(fo.COPILOT),UN["github-copilot"].checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:fo.COPILOT});return!!e}),UN.codex&&(UN.codex.authComponent=makeProviderAuthComponent(fo.CODEX),UN.codex.checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:fo.CODEX});return!!e}),__name(getProviderConfig,"getProviderConfig"),__name(getProviderAuthState,"getProviderAuthState"),__name(handleModelSelect,"handleModelSelect"),__name(handleModelCancel,"handleModelCancel"),__name(handleModelCommand,"handleModelCommand"),__name(applyModelSetting,"applyModelSetting"),Vt(),PR(),__name(handleThemeSelect,"handleThemeSelect"),__name(handleThemeCancel,"handleThemeCancel"),__name(handleThemeCommand,"handleThemeCommand"),__name(applyThemeSetting,"applyThemeSetting");var jN=[{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")}],BN=__name(e=>`--${e.key} <${e.valueHint}>`,"flagSpecOf"),WN=jN.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=jN.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"),Vt(),PR();var HN=["default","standard","plan","accept-edits","auto-accept","yolo","bypass","dont-ask"];function parsePermissionModeOption(e){const t=HN.includes(e)?normalizePermissionMode(e):void 0;if(!t)throw new Ve(`Allowed choices are ${HN.join(", ")}.`);return t}__name(parsePermissionModeOption,"parsePermissionModeOption");var GN=getPackageJson(import.meta.url),VN=__name((e,t=[])=>[...t,e],"collectAddDir"),zN=__name((e,t=[])=>[...t,e],"collectConfig");function displayCustomHelp(){const e=GN.version,t=getInvokedCommandName(),n=getVisibleSlashCommands();console.log(),console.log(yt.bold("Command Code")+yt.gray(` v${e}`)),console.log(yt.gray(va)),console.log(),console.log(yt.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(yt.bold("Options"));for(const e of Pa){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(ka)+yt.gray(e.description))}console.log(),console.log(yt.bold("Commands"));for(const e of xa){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(ka)+yt.gray(e.description))}console.log(),console.log(yt.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(ka)+yt.gray(e.description));console.log(),console.log(yt.bold("Keyboard Shortcuts"));for(const e of Ta)console.log(" "+e.key.padEnd(ka)+yt.gray(e.description));console.log(),console.log(yt.bold("Examples"));for(const e of Aa){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(ka)+yt.gray(e.description))}console.log(),console.log(yt.cyan("❯")+" "+yt.gray(Ca.replace(/cmd/,t))),console.log(),console.log(yt.bold("Links"));for(const e of Ia)console.log(" "+e.key.padEnd(ka)+yt.cyan(e.description));console.log()}function createProgram(){const e=new He;e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(GN.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 Ge("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Ge("--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 Ge("--accept-edits","Start in accept edits mode").implies({permissionMode:"auto-accept"})).addOption(new Ge("--auto-accept").implies({permissionMode:"auto-accept"}).hideHelp()).addOption(new Ge("--permission-mode <mode>","Set permission mode").choices(HN).argParser(parsePermissionModeOption)).option("--skip-onboarding","Skip taste onboarding (for non-interactive/automated runs)").option("-p, --print [query]","Run in non-interactive mode, output response and exit").option("--max-turns <number>",`Max agentic turns (model API round trips): print mode limit (default ${Sa}); interactive mode sets the /goal turn budget (default 100)`,e=>{const t=parseInt(e,10);if(isNaN(t)||t<1)throw new Ve("--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",VN,[]).addOption(new Ge("--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",ba).option("--no-auto-update","Disable automatic background updates for this run").option("--add-dir <directory>","Add directory to workspace context",VN,[]).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)",VN,[]).option("--mod-option <name=value>","Set a mod-declared flag value (repeatable)",VN,[]).option("--skill <path>","Load extra skills from a path (a skill directory or a directory of skills); repeatable",VN,[]).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 Ge("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Ge("--experimental","Enable experimental features").hideHelp()).addOption(new Ge("-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 Ge("--local","Use local server").hideHelp()).addOption(new Ge("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption();for(const t of WN)e.option(BN(t),t.description);return e.option("--config <key=value>","Set a setting headlessly, e.g. --config theme=dark (repeatable)",zN),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram");var KN=new Map([["--rpc",null],["--sandbox","optional"],["--base","required"]]);function firstOperand(e){const{tokens:t,valueFlags:n}=e;for(let e=0;e<t.length;e++){const r=t[e]??"";if(!r.startsWith("-")||"-"===r)return r;if(r.includes("="))continue;const o=n.get(r),s=t[e+1];("required"===o||"optional"===o&&void 0!==s&&!s.startsWith("-"))&&e++}return null}function wantsExperimentalRootFlags(e){if(!isExperimentalEnabled())return!1;const t=e.argv.indexOf("--"),n=(-1===t?e.argv:e.argv.slice(0,t)).slice(2);if(!n.includes("--experimental"))return!1;const r=firstOperand({tokens:n,valueFlags:new Map([...e.valueFlags,...KN])});return null===r||!e.subcommands.has(r)}function valueKind(e){return e.required?"required":e.optional?"optional":null}function rootValueFlags(e){const t=new Map;for(const n of e.options){const e=valueKind(n);n.long&&t.set(n.long,e),n.short&&t.set(n.short,e)}return t}function addExperimentalRootOptions(e){const t=new Set(e.commands.flatMap(e=>[e.name(),...e.aliases()]));wantsExperimentalRootFlags({argv:process.argv,subcommands:t,valueFlags:rootValueFlags(e)})&&e.option("--rpc","Experimental: serve one session as newline-delimited JSON-RPC on stdin/stdout").option("--sandbox [sessionIdOrMessage]","Experimental: run the agent in a cloud sandbox. A session id reopens that session; anything else is the first message. With -p: start the task (or send a follow-up to <id>) and print the session id").option("--base <branch>","With --sandbox: the branch a new session works from (default: the repo default branch)")}__name(firstOperand,"firstOperand"),__name(wantsExperimentalRootFlags,"wantsExperimentalRootFlags"),__name(valueKind,"valueKind"),__name(rootValueFlags,"rootValueFlags"),__name(addExperimentalRootOptions,"addExperimentalRootOptions");var qN=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!==qN&&(recordError({span:qN,error:sanitizeErrorForTelemetry({error:e,label:"command_error"})}),qN.end(),qN=null)}function abandonPendingCommandSpan(){null!==qN&&(qN.setAttribute("cmd.command.outcome","abandoned"),qN.end(),qN=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);qN=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!==qN&&(endSpan({span:qN,status:"success"}),qN=null)})}__name(commandPath,"commandPath"),__name(flagNames,"flagNames"),__name(failPendingCommandSpan,"failPendingCommandSpan"),__name(abandonPendingCommandSpan,"abandonPendingCommandSpan"),__name(setupCommanderHooks,"setupCommanderHooks");var{red:YN,yellow:QN,dim:JN}=yt;function printErrorDetails(e,t){if(console.log(`${At.error} ${YN(t)}`),console.log(`${At.error} ${YN("ERROR →")} ${e.name}`),console.log(`${At.info} ${YN("REASON →")} ${e.message}`),console.log(`${At.info} ${YN("ERROR STACK ↓ \n")} ${e.stack}\n`),!isTelemetryInitialized())return;const n=getDisplayTraceId();console.log(`${At.info} ${JN(`Trace ID: ${n}`)}`),console.log(`${JN(" Share this ID with support to help debug your issue.")}\n`)}__name(printErrorDetails,"printErrorDetails");var XN=__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(`${At.warning} ${QN(t)}\n`),r&&printErrorDetails(n,t),!o)return!1;process.exit(0)}},"handleError");Vt(),PR();var ZN,e_,t_=[],n_=[];function setModPathsOverride(e){t_=e}function setModOptionsOverride(e){n_=e}function loadCommandModHost(e={}){return ZN||(ZN=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:t_,builtins:commandBuiltinMods()});for(const e of n_){const t=e.indexOf("=");t<=0?dlog(`[mods] ignoring malformed --mod-option "${e}"`):n.setFlagValue({name:e.slice(0,t),value:e.slice(t+1)})}for(const e of n.warnings())dlog(`[mods] ${e.path}: ${e.reason}`);return setActiveModHost(n),setRegisteredProviderModules({modules:n.providerModules()}),n}catch(e){return void dlog(`[mods] host construction failed: ${e instanceof Error?e.message:String(e)}`)}}function disposeCommandModHost(){return e_??=ZN?runModHostTeardown({host:ZN}):Promise.resolve(),e_}function exitAfterModHostTeardown(e){disposeCommandModHost().finally(()=>{process.exit(e)})}async function runModHostTeardown(e){const t=__name(async()=>{const t=await e.host;t&&(t.dispose(),await t.settle())},"teardown");try{await Promise.race([t(),new Promise(t=>{const n=setTimeout(t,e.graceMs??300);n.unref?.()})])}catch(e){dlog(`[mods] teardown failed: ${e instanceof Error?e.message:String(e)}`)}}function handleStdoutError(e){if(!isBenignStreamWriteError(e))throw e;exitAfterModHostTeardown(0)}function handleStderrError(e){if(!isBenignStreamWriteError(e))throw e}function handleUnhandledErrors(){process.stdout.on("error",handleStdoutError),process.stderr.on("error",handleStderrError),process.on("unhandledRejection",e=>{const t=e instanceof Error?e:new Error(String(e));trackError({error:sanitizeErrorForTelemetry({error:t,label:"unhandled_rejection"}),context:{component:qo.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),XN({heading:Mt`CRITICAL: Unhandled Promise Rejection!
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:qo.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),XN({heading:Mt`CRITICAL: Uncaught Exception!
16
- This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:e,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})})}__name(setModPathsOverride,"setModPathsOverride"),__name(setModOptionsOverride,"setModOptionsOverride"),__name(loadCommandModHost,"loadCommandModHost"),__name(buildHost,"buildHost"),__name(disposeCommandModHost,"disposeCommandModHost"),__name(exitAfterModHostTeardown,"exitAfterModHostTeardown"),__name(runModHostTeardown,"runModHostTeardown"),__name(handleStdoutError,"handleStdoutError"),__name(handleStderrError,"handleStderrError"),__name(handleUnhandledErrors,"handleUnhandledErrors"),Vt(),PR(),Vt(),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt();var r_=ft.pointer,o_=__name(({isSelected:e,backgroundColor:t})=>it.createElement(et,{color:e?MO:IO,backgroundColor:t,bold:e&&isLightTheme()},e?r_:" "),"OverlayCaret"),s_=__name(({isSelected:e,isActive:t,idleColor:n=xO,backgroundColor:r,children:o})=>it.createElement(et,{color:e?MO:t?AO:n,backgroundColor:r,bold:e&&isLightTheme()},o),"OverlayOptionText"),a_=__name(({isSelected:e,label:t})=>it.createElement(s_,{isSelected:e}," ",t),"OverlayOptionItem"),i_=__name(({backgroundColor:e})=>it.createElement(et,{color:AO,backgroundColor:e}," ",ft.tick),"OverlayActiveTick"),l_=__name(({indent:e=4,children:t})=>it.createElement(et,{color:TO}," ".repeat(e),t),"OverlayOptionDescription"),c_=__name(({isSelected:e,idleColor:t=LR.GRAY,selectedColor:n=LR.WHITE,bold:r,children:o})=>it.createElement(et,{color:e?n:t,backgroundColor:e?tL:void 0,bold:r??e},o),"OverlayBarText"),d_=__name(({isSelected:e,label:t})=>it.createElement(c_,{isSelected:e}," ",t," "),"OverlayBarItem"),u_=__name(()=>null,"OverlayBarIndicator");Vt();var m_=createOSC8Link("https://commandcode.ai/docs/permissions#permission-modes","Docs ↗",!1),p_=__name(({hint:e})=>it.createElement(et,{italic:!0,color:LR.DIM},e," · Run ",it.createElement(et,{color:LR.WHITE},"cmd --yolo")," to bypass all permissions (",m_,")"),"PermissionFooter"),g_=__name(({request:e,onResponse:t})=>{const[n]=ct(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 it.createElement(RO,{title:"Tool Permission",subtitle:it.createElement(et,{wrap:"wrap"},"Command Code needs to run ",it.createElement(et,{color:MO},e.toolName),"."),footer:it.createElement(p_,{hint:"↑/↓ navigate · enter select"})},e.risk&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0,color:LR.RED,wrap:"wrap"},ft.warning," ",getRiskDisplay(e.risk))),e.description&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM,italic:!0},e.description)),it.createElement(SelectInput,{items:r.map((e,t)=>({label:`${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:n,indicatorComponent:o_,itemComponent:a_}))},"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?TL:PL).join("\n")}Vt(),PR(),Vt(),PR(),Vt(),__name(buildTreeConnectors,"buildTreeConnectors");var h_=Tt()?"⟳":"*",f_=" │ ";function DiffWordSegments({segments:e,type:t,paired:n,dimDiff:r,language:o,highlightOptions:s}){const a="removed"===t?_R.REMOVED_HIGHLIGHT_BG:_R.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(it.createElement(et,{key:u,backgroundColor:a,dimColor:r},d)):n?i.push(it.createElement(et,{key:u,color:LR.WHITE,dimColor:r},d)):i.push(it.createElement(et,{key:u,color:"removed"===t?_R.REMOVED_TEXT:_R.ADDED_TEXT,dimColor:r},d))}return i}function DiffRow({background:e,prefix:t,wrap:n="wrap",children:r}){return it.createElement(Ze,{width:"100%",backgroundColor:e},it.createElement(Ze,{flexShrink:0},t),it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{wrap:n},r)))}function renderDiffLine({line:e,dimDiff:t,language:n,highlightOptions:r}){if("skip"===e.kind)return it.createElement(Ze,{key:e.key,width:"100%"},it.createElement(et,{color:_R.LINE_NUM,dimColor:t},e.spacer,f_,e.label));if("context"===e.kind)return it.createElement(DiffRow,{key:e.key,prefix:it.createElement(et,{color:_R.LINE_NUM,dimColor:t}," "+e.lineNumberLabel+f_)},it.createElement(et,{color:LR.WHITE,dimColor:t}," ",highlightSyntax(e.text,n,r)));const o="removed"===e.kind,s=o?_R.REMOVED_TEXT:_R.ADDED_TEXT,a=o?_R.REMOVED_BG:_R.ADDED_BG;return it.createElement(DiffRow,{key:e.key,background:a,prefix:it.createElement(et,null,it.createElement(et,{color:s,dimColor:t}," "+e.lineNumberLabel),it.createElement(et,{color:_R.LINE_NUM,dimColor:t},f_),it.createElement(et,{color:s,dimColor:t},o?"- ":"+ "))},it.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?it.createElement(et,{color:LR.RED},"Rejected update to",it.createElement(et,{color:LR.RED},` ${e.filePath}`)):it.createElement(et,{color:LR.GRAY},"Updated"," ",it.createElement(et,{color:LR.WHITE,bold:!0},e.filePath)," ","with"," ",e.additions>0&&it.createElement(it.Fragment,null,it.createElement(et,{color:BR.SUCCESS},e.additions)," ","addition",1!==e.additions?"s":"",e.removals>0?" and ":""),e.removals>0&&it.createElement(it.Fragment,null,it.createElement(et,{color:BR.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:it.createElement(Ze,{flexDirection:"column"},it.createElement(DiffMetadata,{metadata:c.metadata}),it.createElement(Ze,{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:BR.SUCCESS,strikethrough:!0}:"in_progress"===e?{textColor:BR.IN_PROGRESS,strikethrough:!1}:{textColor:LR.WHITE,strikethrough:!1}}function TodoChecklist({todos:e}){return it.createElement(Ze,{flexDirection:"column"},e.map((e,t)=>{const n="completed"===e.status?ft.checkboxOn:ft.checkboxOff,{textColor:r,strikethrough:o}=resolveTodoTextStyle(e.status),s="in_progress"===e.status&&e.activeForm?`${e.activeForm}…`:e.content;return it.createElement(Ze,{key:e.id||t,flexDirection:"row"},it.createElement(Ze,{width:2},it.createElement(et,{color:r},n)),it.createElement(et,{color:r,bold:"in_progress"===e.status,strikethrough:o},s))}))}function formatTodosForDisplay(e){const t=jh(e);return t?it.createElement(TodoChecklist,{todos:t}):it.createElement(et,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 it.createElement(BracketWrap,null,t?e:it.createElement(Markdown,null,e))}function ReadToolInlineSummaryRow({summary:e}){return e?.dimText?it.createElement(et,{dimColor:!0}," ",e.dimText):null}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:o}){if(e)return{symbolColor:LR.YELLOW,symbol:ft.arrowRight};if(t)return{symbolColor:LR.RED,symbol:ft.square};if(n)return{symbolColor:$R,symbol:"✻"};if(r&&o){const e=jh(o),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?BR.SUCCESS:BR.WARNING,symbol:ft.square}}return{symbolColor:FR.BG,symbol:ft.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 it.createElement(it.Fragment,null,it.createElement(et,{color:$R},`Thought for ${e} second${1!==e?"s":""}`," "),!s&&it.createElement(BracketWrap,{color:LR.DIM},`${a}+o to expand`))}if(t)return it.createElement(it.Fragment,null,it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:DR.BADGE_BG,color:DR.BADGE_FG,bold:!0},xL)),it.createElement(et,null," ","Using your taste"," ",n?"package of ":"packages",n&&it.createElement(et,{bold:!0},n)));let c=r;return"READ[n]"===r&&o&&(c=`READ[${Number(o[1])}]`),it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:FR.BG,color:FR.FG,bold:!0},`${ML}${c}${ML}`))}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?it.createElement(et,{color:LR.GRAY},"Running (",s,")"):"background"===e?it.createElement(et,{color:LR.GRAY},"Running in background"):"interrupted"===e||n===oS?it.createElement(et,{color:LR.GRAY,wrap:"wrap"},"Interrupted"):"error"===e||t?it.createElement(et,{color:LR.RED,wrap:"wrap"},n," (",s,")"):it.createElement(it.Fragment,null,it.createElement(et,{wrap:"wrap"},"Done"),it.createElement(et,{color:LR.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?Bd:Ud,maxChars:"Question"===t?1/0:Kd}),l=a&&"Question"!==t;return{text:s,isTruncated:l,remainingLines:i,truncationMsg:l?i>0?it.createElement(BracketedText,{text:`... +${i} lines [${r}+o to expand]`,color:LR.DIM}):it.createElement(BracketedText,{text:`... [${r}+o to expand]`,color:LR.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?it.createElement(it.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:Wd,{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-Wd;return it.createElement(Ze,{flexDirection:"column"},i,l&&it.createElement(Ze,{marginTop:1},it.createElement(BracketedText,{text:`… (${d} more ${1===d?"line":"lines"}) [${s}+o to expand]`,color:LR.DIM})),r&&o&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.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?it.createElement(et,{color:LR.GRAY},"Created"," ",it.createElement(et,{color:LR.WHITE,bold:!0},a.filePath)," ","(empty file)"):it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.GRAY},"Created"," ",it.createElement(et,{color:LR.WHITE,bold:!0},a.filePath)," ","(",a.totalLinesLabel,")"),it.createElement(Ze,{marginTop:1,flexDirection:"column"},a.visibleLines.map(e=>it.createElement(DiffRow,{key:e.lineNumber,background:_R.ADDED_BG,wrap:"truncate-end",prefix:it.createElement(et,null,it.createElement(et,{color:_R.ADDED_TEXT}," "+e.lineNumberLabel),it.createElement(et,{color:_R.LINE_NUM},f_))},it.createElement(et,{color:_R.ADDED_TEXT},highlightSyntax(e.text,o,s))))),a.isTruncated&&a.moreLinesLabel&&it.createElement(Ze,{marginTop:1},it.createElement(BracketedText,{text:a.expandHint?`… (${a.moreLinesLabel}) ${a.expandHint}`:`… (${a.moreLinesLabel})`,color:LR.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 it.createElement(Ze,{width:"100%",flexDirection:"column"},it.createElement(et,null," "),it.createElement(et,{color:$R,wrap:"wrap",italic:!0},e))}const g=p?TL:PL;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?it.createElement(Ze,{columnGap:1},it.createElement(et,{color:eL},g," "),e):e}if(r&&o&&"content"in o){const e=renderWriteFileContent({input:l,metadata:o,expandedOutput:a,expandKey:u});return m?it.createElement(Ze,{columnGap:1},it.createElement(et,{color:eL},g," "),e):e}return m?renderTextWithLongConnector({output:s,name:d,expandedOutput:a,expandKey:u,hasError:c,closesFrame:p}):it.createElement(Ze,{width:"100%"},it.createElement(et,{color:c?LR.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?LR.RED:void 0,d=buildTreeConnectors(a,{isTruncated:i,closesFrame:s}),u=s?TL:PL;return it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(Ze,{columnGap:1,width:"100%"},it.createElement(et,{color:eL},d),it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:c,wrap:"wrap"},a))),i&&it.createElement(Ze,{columnGap:1},it.createElement(et,{color:eL},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}),L=s?.preHookLines,O=s?.postHookLines,D=Boolean(L?.length),$=Boolean(O?.length),N=Boolean(s?.hookOutcome),_=r&&!y&&!N,F=!N&&!_,U=I&&!$&&!N&&!_,j=D&&!I&&!$&&!N&&!_;return it.createElement(Ze,null,i&&it.createElement(et,{color:A},R),it.createElement(Ze,{flexDirection:"column",marginLeft:i?1:0},it.createElement(Ze,null,it.createElement(ToolHeader,{isThinking:i,isTasteFile:m,tasteCategory:p,name:M,summaryMatch:T,expandedOutput:a,expandKey:f,input:t,output:n}),w&&it.createElement(et,null," ",formatToolInput({input:S,isShell:"SHELL"===e})),it.createElement(ReadToolInlineSummaryRow,{summary:P}),E>0&&it.createElement(et,{dimColor:!0},` ${h_}${E>1?` ${E}`:""}`)),y&&("running"===v||"background"===v||"done"===v||"error"===v||n)&&it.createElement(Ze,{columnGap:1,marginLeft:h?1:0},h&&it.createElement(et,{color:eL},TL," "),it.createElement(AgentStatus,{agentStatus:v,hasError:o,output:n,elapsedSeconds:C,tokensUsed:k})),it.createElement(HookLines,{lines:L,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}),it.createElement(HookLines,{lines:O,showTreeConnector:h,closesFrame:F}),it.createElement(HookOutcome,{outcome:s?.hookOutcome,showTreeConnector:h}),_&&it.createElement(Ze,{columnGap:1,marginLeft:1},it.createElement(et,{color:eL},TL," "),it.createElement(et,{color:LR.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 it.createElement(Ze,{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 it.createElement(Ze,{flexDirection:"column",marginLeft:t?1:0},e.map((e,t)=>{const o=n&&t===r?TL:PL;return it.createElement(Ze,{key:t,columnGap:1},it.createElement(et,{color:eL},o),it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},e)))}))}function HookOutcome({outcome:e,showTreeConnector:t}){if(!e)return null;const n="stop"===e.kind?LR.YELLOW:LR.RED;return it.createElement(Ze,{columnGap:1,marginLeft:t?1:0},it.createElement(et,{color:eL},TL),it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{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 y_=createNodeRuntime(),S_=__name(({label:e,isSelected:t})=>e.includes("[shift+tab]")?it.createElement(it.Fragment,null,e.split("[shift+tab]")[0],it.createElement(BracketWrap,{color:t?MO:xO,bold:!0},"shift+tab")):e.includes("(")?it.createElement(it.Fragment,null,e.split("(")[0],it.createElement(et,{color:LR.GRAY},"(",e.split("(")[1])):e,"ChoiceLabel"),w_=__name(({request:e,onResponse:t,onEnableAutoAccept:n})=>{const[r]=ct(0),[o,s]=ct(1);ut(()=>{"edit"===e.action&&e.oldContent&&e.filePath&&resolveEditStartLine({runtime:y_,filePath:e.filePath,oldContent:e.oldContent}).then(e=>{void 0!==e&&s(e)}).catch(()=>{})},[e.filePath,e.oldContent,e.action]);const a=getPermissionChoicesForRisk({choices:fM,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 it.createElement(RO,{title:`${d()}${"edit"===e.action?` ${c}`:""}`,footer:it.createElement(p_,{hint:"↑/↓ navigate · enter select"})},"edit"===e.action&&e.oldContent&&e.newContent&&it.createElement(Ze,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c,marginLeft:0,startLine:o}).diffContent),e.risk&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0,color:LR.RED,wrap:"wrap"},ft.warning," ",getRiskDisplay(e.risk))),it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0},"Do you want to ",l()," ",it.createElement(et,{color:MO},c),"?")),it.createElement(SelectInput,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:i,initialIndex:r,indicatorComponent:o_,itemComponent:({label:e,isSelected:t})=>it.createElement(s_,{isSelected:t},it.createElement(S_,{label:e,isSelected:t}))}))},"PermissionPrompt");Vt(),PR();var v_=BE?"ctrl+y":"ctrl+e",k_=__name(({request:e,onResponse:t})=>{const[n]=ct(0),[r,o]=ct({phase:"idle"}),s=e.description??("done"===r.phase?r.explanation:void 0),a=void 0!==e.explain&&void 0===e.description&&"done"!==r.phase;ot((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 it.createElement(RO,{title:"Execute Shell Command",subtitle:it.createElement(et,{wrap:"wrap"},"Command Code needs to execute ",it.createElement(et,{color:MO},getCommandDisplay(e)),"."),footer:it.createElement(p_,{hint:a?`↑/↓ navigate · enter select · ${v_} explain`:"↑/↓ navigate · enter select"})},e.risk&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0,color:LR.RED,wrap:"wrap"},ft.warning," ",getRiskDisplay(e.risk))),e.workingDirectory&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.GRAY},"Working directory: ",e.workingDirectory)),s&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM,italic:!0},s)),a&&"idle"===r.phase&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM,italic:!0},"Press"," ",it.createElement(BracketWrap,{color:LR.DIM,bold:!0},v_)," ","to explain this command")),"loading"===r.phase&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM,italic:!0},it.createElement(bt,{type:"dots"})," Explaining this command…")),"failed"===r.phase&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM,italic:!0},"Couldn't generate an explanation — press"," ",v_," to retry")),it.createElement(SelectInput,{items:i.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:n,indicatorComponent:o_,itemComponent:({label:e,isSelected:t})=>it.createElement(s_,{isSelected:t},e.includes("[shift+tab]")?it.createElement(it.Fragment,null,e.split("[shift+tab]")[0],it.createElement(BracketWrap,{color:t?MO:xO,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 accept edits")):o(l)}__name(handlePermissionResponse,"handlePermissionResponse");var C_=lt(__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 it.createElement(Ze,{marginY:1},it.createElement(k_,{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 it.createElement(Ze,{marginY:1},it.createElement(k_,{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 it.createElement(Ze,{marginY:1},it.createElement(g_,{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 it.createElement(Ze,{marginY:1},it.createElement(w_,{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}=nt(),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 it.createElement(RO,{title:"Plan",titleSuffix:n?` · ${t.basename(n)}`:void 0,gapAfterHeader:!1,hint:a?r?"ctrl+o to collapse":c:void 0},it.createElement(Ze,{marginTop:1},it.createElement(Markdown,null,i)))}__name(isGenericToolRequest,"isGenericToolRequest"),__name(isFileEditRequest,"isFileEditRequest"),Vt(),PR(),Vt(),PR(),__name(PlanPanel,"PlanPanel"),Vt(),PR();var b_=__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 it.createElement(Ze,{flexDirection:"column",marginTop:1,paddingLeft:4},it.createElement(et,{italic:!0,color:LR.DIM},"Preview"),it.createElement(et,{color:LR.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 it.createElement(et,{key:t},it.createElement(et,{color:LR.DIM},"│ "),it.createElement(et,{color:LR.GRAY},n),it.createElement(et,{color:LR.DIM},`${r} │`))}),r>0?it.createElement(et,{color:LR.YELLOW},`├${s}${a}┤`):null,it.createElement(et,{color:LR.DIM},`└${o}┘`))},"OptionPreview"),E_=[{label:"1. Submit",value:"submit"},{label:"2. Cancel",value:"cancel"}],T_=__name(({checked:e})=>e?it.createElement(et,{color:LR.GREEN},"[",ft.tick,"] "):it.createElement(et,{color:LR.DIM},"[ ] "),"MultiSelectCheckbox"),P_=__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"),M_=__name((e,t)=>{const n=new Set(e);return n.has(t)?(n.delete(t),n):(n.add(t),n)},"toggleLabel"),x_=__name((e,t)=>e?{indicator:ft.bullet,color:MO}:t?{indicator:ft.tick,color:LR.GREEN}:{indicator:ft.circle,color:LR.GRAY},"getTabMarker"),I_=__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}=x_(i,l);s.push(it.createElement(et,{key:a},it.createElement(et,{color:d},c),it.createElement(et,{color:i?MO:void 0}," ",o.header),a<e.length-1?it.createElement(et,{color:LR.DIM}," | "):null))}),!o){const e=r;s.push(it.createElement(et,{key:"review"},it.createElement(et,{color:LR.DIM}," | "),it.createElement(et,{color:e?MO:LR.GRAY},e?ft.bullet:ft.circle),it.createElement(et,{color:e?MO:void 0,bold:e}," ","Review")))}return it.createElement(Ze,null,s)},"TabIndicator"),A_=__name(({questions:e,onResponse:t,hideCustomInput:n=!1,compact:r=!1})=>{const[o,s]=ct(0),[a,i]=ct(new Map),l=dt(null);null===l.current&&(l.current=new Map);const c=l.current,[d,u]=ct(""),[m,p]=ct(new Set),[g,h]=ct(null),[f,y]=ct(!1),[S,w]=ct(!1),[v,k]=ct(!1),[C,b]=ct(null),[E,T]=ct(!1),P=dt(null);null===P.current&&(P.current=new Map);const M=dt(null);null===M.current&&(M.current=new Map);const[x,I]=ct(!1),[A,R]=ct(""),[,L]=ct(0),O=e[o],D=O?.multiSelect??!1,$=a.get(o),N=O?[...O.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description,...void 0!==e.preview?{preview:e.preview}:{}}))]:[],_=N.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),F=new Map(_.map((e,t)=>[e.label,N[t]])),U=__name((e,t)=>{t.size>0?c.set(e,Array.from(t)):c.delete(e)},"saveOrClearMultiAnswer"),j=__name(t=>{const n=e[t],r=c.get(t);if(n?.multiSelect&&r){p(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));return void u(e||"")}if(p(new Set),!n?.multiSelect&&1===r?.length){const e=r[0],t=!n?.options.some(t=>t.label===e);return void u(t&&e?e:"")}u("")},"restoreInputsForQuestion"),B=__name(e=>{"submit"!==e.value?"cancel"===e.value&&t({answers:[]}):q()},"handleReviewSelect"),W=__name(()=>{if(!$||0===$.length)return 0;const e=$[0],t=O.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),H=__name(e=>{if(f)return;if(D){const t=P_(e.value,O.options.length-1);if(null===t)return;const n=O.options[t]?.label||"";return void p(e=>M_(e,n))}const t=P_(e.value,O.options.length-1);if(null===t)return;y(!0);const n=O.options[t]?.label||"";z([n])},"handleSelect"),G=__name(()=>{if(f)return;y(!0);const e=Array.from(m);z(e)},"handleMultiSelectDone"),V=__name(()=>{if(f)return;const e=d.trim();if(e){if(D){const t=new Set(O.options.map(e=>e.label));return void p(n=>{const r=new Set;return n.forEach(e=>{t.has(e)&&r.add(e)}),r.add(e),r})}y(!0),z([e])}},"handleOtherSubmit"),z=__name(t=>{c.set(o,t);const r=new Map(c);if(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"),Q=__name(()=>{P.current&&(A.trim()?P.current.set(o,A):P.current.delete(o)),I(!1)},"saveNotesAndClose"),J=__name(async()=>{try{const e=await detectClipboardImage();if(!e)return;const t=M.current?.get(o)??[];M.current?.set(o,[...t,{data:e.data,mediaType:e.mediaType}]),L(e=>e+1)}catch{}},"pasteClipboardImageIntoQuestion"),X=__name(async(e,t)=>{try{const n=await openInEditor(e);n!==e&&t(n)}catch{}},"editExternally"),Z=__name(e=>{w(!1),s(e),T(!1),k(!1),b(null),j(e)},"editQuestion"),ee=__name(t=>{t<0||t>=e.length||(D&&(U(o,m),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=P_(g.value,O.options.length-1);if(null===e)return;const t=O.options[e]?.label||"";p(e=>M_(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(ot((e,t)=>{const r="v"===e&&(t.ctrl||t.meta&&"darwin"!==process.platform);if(x)t.escape?Q():r?J():t.ctrl&&"g"===e&&X(A,R);else if(r&&v)J();else if(t.ctrl&&"g"===e&&v)X(d,u);else{if(" "===e&&D&&!v&&te(),"d"!==e||!D||v||S||G(),!(v||S||f||n)){if("n"===e)return R(P.current?.get(o)??""),void I(!0);if("c"===e)return void Y()}S||f||ne(t),re(t),t.escape&&oe()}}),!O&&!S)return null;if(S)return it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(iL,{dividerColor:PO}),it.createElement(Ze,{marginBottom:1},it.createElement(I_,{questions:e,currentIndex:e.length,answeredQuestions:new Set(a.keys()),isReviewPage:!0})),e.some((e,t)=>!a.get(t)?.length)&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.YELLOW},"⚠ You have not answered all questions")),e.map((e,t)=>it.createElement(Ze,{key:t,marginBottom:1,flexDirection:"column"},it.createElement(et,{color:LR.DIM},t+1,". ",e.question),it.createElement(et,{color:LR.GREEN}," ",a.get(t)?.join(", ")||"No answer"))),it.createElement(SelectInput,{items:E_,onSelect:B,initialIndex:0,indicatorComponent:o_,itemComponent:a_}),it.createElement(Ze,{marginTop:1},it.createElement(et,{italic:!0,color:LR.DIM},ft.arrowLeft," to go back and edit")));const se=r&&1===e.length;return it.createElement(Ze,{flexDirection:"column",width:"100%"},!se&&it.createElement(iL,{dividerColor:PO}),!se&&it.createElement(Ze,{marginBottom:1},it.createElement(I_,{questions:e,currentIndex:o,answeredQuestions:new Set(a.keys()),isReviewPage:!1,hideReview:n})),it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0,color:EO},O.question)),v||E||x?it.createElement(Ze,{flexDirection:"column"},_.map((e,t)=>{const n=F.get(e.label),r=D&&n&&m.has(n.label),o=!D&&n&&$?.includes(n.label),s=r||o;return it.createElement(Ze,{key:e.value,flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,null," "),it.createElement(s_,{isActive:s,idleColor:LR.GRAY}," ",t+1,"."," "),D&&it.createElement(T_,{checked:s}),it.createElement(s_,{isActive:s,idleColor:LR.GRAY},n?.label||""),!D&&s&&it.createElement(i_,null)),n?.description&&it.createElement(Ze,null,it.createElement(et,null," "),it.createElement(l_,{indent:D?7:4},n.description)))})):it.createElement(SelectInput,{key:`${o}-${C??"default"}`,items:_,initialIndex:C??W(),onSelect:H,onHighlight:h,indicatorComponent:o_,itemComponent:({label:e,isSelected:t})=>{const n=F.get(e),r=D&&n&&m.has(n.label),o=!D&&n&&$?.includes(n.label),s=r||o,a=e.match(/^\s*(\d+)\.\s*(.*)$/),i=a?.[1]||"",l=a?.[2]||e;return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(s_,{isSelected:t,isActive:s}," ",i,"."," "),D&&it.createElement(T_,{checked:s}),it.createElement(s_,{isSelected:t,isActive:s},l),!D&&s&&it.createElement(i_,null)),n?.description&&it.createElement(l_,{indent:D?7:4},n.description))}}),!v&&!E&&(()=>{const e=(g?F.get(g.label):void 0)??N[C??W()];return e?.preview?it.createElement(b_,{preview:e.preview}):null})(),!n&&it.createElement(Ze,null,it.createElement(o_,{isSelected:v}),it.createElement(s_,{isSelected:v}," ",_.length+1,"."," "),D&&it.createElement(T_,{checked:m.has(d.trim())}),it.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?it.createElement(Ze,null,it.createElement(o_,{isSelected:!0}),it.createElement(s_,{isSelected:!0}," ","notes:"," "),it.createElement(TextInput,{value:A,onChange:R,onSubmit:Q,placeholder:"Add notes on this design…",focus:x,stripBracketedPaste:!0})):(()=>{const e=P.current?.get(o)?.trim();return e?it.createElement(Ze,null,it.createElement(et,{italic:!0,color:LR.DIM}," ","notes: ",e)):null})(),(M.current?.get(o)??[]).map((e,t)=>it.createElement(Ze,{key:t},it.createElement(et,{color:LR.DIM}," ","[Image #",t+1," attached —"," ",e.mediaType,"]"))),D&&it.createElement(Ze,null,it.createElement(o_,{isSelected:E}),it.createElement(s_,{isSelected:E}," ",o===e.length-1?"Submit":"Next")),e.length>1&&it.createElement(Ze,{marginTop:1},it.createElement(et,{italic:!0,color:LR.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]=ct(!1),l=e.params.planContent;return ot((e,t)=>{l&&getIsExpandToolShortcut(t,e)&&i(e=>!e)}),it.createElement(Ze,{marginY:1,flexDirection:"column"},l&&it.createElement(Ze,{marginBottom:1},it.createElement(PlanPanel,{content:l,filePath:e.params.planFilePath,expanded:a})),it.createElement(A_,{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"),Vt(),PR();var R_="__skip__",L_=__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:R_,isPrimary:!1}],l=new Map(i.map(e=>[e.label,e]));ot((e,t)=>{t.escape&&n()});const c=__name(e=>{e.value!==R_?(t(e.value),n()):n()},"handleSelect");return it.createElement(RO,{title:`/design ${r} complete`,titleSuffix:` · ${a}`,hint:"Enter to run · Esc to dismiss"},it.createElement(SelectInput,{items:i,onSelect:c,indicatorComponent:u_,itemComponent:({label:e,isSelected:t})=>{const n=l.get(e),r=n?.value===R_,o=n?.isPrimary??!1,s=r?"run /design manually":wy[e]??"";return it.createElement(Ze,{flexDirection:"column"},it.createElement(c_,{isSelected:t,idleColor:o?LR.WHITE:LR.DIM},r?" skip ":` /design ${e} `),s&&it.createElement(c_,{isSelected:t,idleColor:LR.DIM,bold:!1},` ${s} `))}}))},"DesignModeSelector");function getUsageToneColor(e){return"danger"===e?LR.RED:"warning"===e?LR.YELLOW:LR.GREEN}function getDistanceToneColor(e){return"danger"===e?LR.RED:"warning"===e?LR.YELLOW:LR.GRAY}function ContextProgress({view:e,progressBarWidth:t}){const n=getUsageToneColor(e.tone),r=buildBlockBar({percentage:e.percentage,width:t});return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{marginBottom:1},it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:LR.BLUE,color:"#f4f4f4",bold:!0},`${ML}CONTEXT${ML}`)),it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:LR.GRAY},e.modelLabel)),it.createElement(Ze,null,it.createElement(et,{color:n},r.filled),it.createElement(et,{color:HR},r.empty),it.createElement(et,{bold:!0,color:n},` ${e.percentageLabel}`)),it.createElement(Ze,null,it.createElement(et,null,e.tokensUsedLabel),it.createElement(et,{color:LR.GRAY},` / ${e.tokenLimitLabel}`),it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:n},e.tokensRemainingLabel),it.createElement(et,{color:LR.GRAY}," remaining"),e.isEstimated&&it.createElement(et,{color:LR.DIM}," (estimated)")))}function CompactionDistance({view:e}){if(!e)return null;const t=getDistanceToneColor(e.tone);return it.createElement(Ze,{marginTop:1},it.createElement(et,{color:t},e.tokensAwayLabel),it.createElement(et,{color:LR.DIM},e.label))}function BreakdownRow({item:e,labelWidth:t}){return it.createElement(Ze,null,it.createElement(et,null,e.name.padEnd(t)),it.createElement(et,{bold:!0},e.paddedValue),it.createElement(et,{color:LR.GRAY}," tokens"),e.detail&&it.createElement(et,{color:LR.DIM},` · ${e.detail}`))}function ContextBreakdown({view:e,labelWidth:t}){return 0===e.rows.length?null:it.createElement(Ze,{flexDirection:"column",marginTop:1},e.rows.map(e=>it.createElement(BreakdownRow,{key:e.name,item:e,labelWidth:t})))}function ContextTips({tips:e}){return 0===e.length?null:it.createElement(Ze,{flexDirection:"column",marginTop:1},e.map(e=>it.createElement(Ze,{key:e},it.createElement(et,{color:LR.CYAN},ft.pointer),it.createElement(et,{color:LR.GRAY}," ",e))))}function ContextMessage({analysis:e}){const t=projectContextView(e,{terminalWidth:useTerminalWidth(),modelDisplayName:getModelDisplayName(e.model)});return it.createElement(Ze,{flexDirection:"column",paddingTop:1},it.createElement(ContextProgress,{view:t.progress,progressBarWidth:t.layout.progressBarWidth}),it.createElement(CompactionDistance,{view:t.compactionDistance}),it.createElement(ContextBreakdown,{view:t.breakdown,labelWidth:t.layout.labelWidth}),it.createElement(ContextTips,{tips:t.tips}))}function ContextConfigView({staticKey:e,sessionId:t,onClose:n,setInput:r}){const[o,s]=ct(null),[a,i]=ct(null);return ut(()=>{let e=!0;return __name(async()=>{const n=I$(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]),ot((e,t)=>{t.escape&&(r(""),n())}),it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(ContextBody,{error:a,analysis:o}),it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Press ",it.createElement(CO,null,"Esc")," to return to conversation"))))}function ContextBody({error:e,analysis:t}){return e?it.createElement(RO,{title:"Context",gapAfterHeader:!1},it.createElement(et,{color:LR.DIM},e)):t?it.createElement(ContextMessage,{analysis:t}):it.createElement(RO,{title:"Context",gapAfterHeader:!1},it.createElement(F$,{label:"Loading context analysis"}))}Vt(),PR(),Vt(),PR(),__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"),Vt(),Vt(),PR(),Vt(),PR();var O_="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?I$(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 D_=__name(({label:e,value:t,valueColor:n,dimValue:r})=>it.createElement(Ze,null,it.createElement(et,{dimColor:!0},`${e}:`.padEnd(14)),r?it.createElement(et,{dimColor:!0},t):it.createElement(et,{color:n},t)),"Row");function StatusMessage({statusData:e}){const t=projectStatusView(e,{profileBaseUrl:"https://commandcode.ai"}),n=t.account.authenticated?ft.tick:ft.cross,r=t.account.authenticated?LR.WHITE:BR.ERROR;return it.createElement(Ze,{flexDirection:"column",paddingX:0},it.createElement(Ze,null,it.createElement(et,{color:OR,bold:!0},"Command Code"," "),it.createElement(et,{dimColor:!0},t.versionText)),it.createElement(Ze,null,it.createElement(et,{dimColor:!0},"Visit "),it.createElement(yL,{url:O_,text:O_,color:LR.CYAN}),it.createElement(et,{dimColor:!0}," for usage and billing")),it.createElement(Ze,{marginTop:1},it.createElement(et,{dimColor:!0},"Account:".padEnd(14)),t.account.username&&t.account.profileUrl?it.createElement(it.Fragment,null,it.createElement(yL,{url:t.account.profileUrl,text:t.account.label,color:LR.CYAN}),it.createElement(et,{color:r}," ",n)):t.account.authenticated?it.createElement(it.Fragment,null,it.createElement(et,null,t.account.label),it.createElement(et,{color:r}," ",n)):it.createElement(it.Fragment,null,it.createElement(et,{color:BR.WARNING},t.account.label),it.createElement(et,{color:r}," ",n),it.createElement(et,{dimColor:!0}," — run "),it.createElement(et,{bold:!0},t.account.loginHint))),it.createElement(D_,{label:"Model",value:t.model.value}),it.createElement(D_,{label:"Branch",value:t.branch.value,dimValue:t.branch.dim}),t.worktree?it.createElement(D_,{label:"Worktree",value:t.worktree.value}):null,t.repository?it.createElement(Ze,null,it.createElement(et,{dimColor:!0},"Repository:".padEnd(14)),it.createElement(yL,{url:t.repository.url,text:t.repository.text,color:LR.CYAN}),t.pullRequest?it.createElement(it.Fragment,null,it.createElement(et,{dimColor:!0}," · "),it.createElement(yL,{url:t.pullRequest.url,text:t.pullRequest.text,color:t.pullRequest.open?LR.CYAN:LR.GRAY}),it.createElement(et,{dimColor:!0}," ","(",t.pullRequest.stateLabel,")")):null):t.pullRequest?it.createElement(Ze,null,it.createElement(et,{dimColor:!0},"Pull Request:".padEnd(14)),it.createElement(yL,{url:t.pullRequest.url,text:t.pullRequest.text,color:t.pullRequest.open?LR.CYAN:LR.GRAY}),it.createElement(et,{dimColor:!0}," (",t.pullRequest.stateLabel,")")):null,it.createElement(D_,{label:"Taste",value:t.taste.value,dimValue:t.taste.dim}),it.createElement(D_,{label:"Directory",value:t.directory.value}),it.createElement(D_,{label:"Skills",value:t.skills.value,dimValue:t.skills.dim}),it.createElement(D_,{label:"Agents",value:t.agents.value,dimValue:t.agents.dim}),it.createElement(D_,{label:"System",value:t.system.value}),t.proxy?it.createElement(D_,{label:"Proxy",value:t.proxy.value}):null)}function StatusBody({state:e}){return"ready"===e.phase?it.createElement(StatusMessage,{statusData:e.data}):"error"===e.phase?it.createElement(et,{dimColor:!0},"Could not load status: ",e.message):it.createElement(et,{dimColor:!0},"Gathering status…")}function StatusConfigView({staticKey:e,sessionId:t,onClose:n,setInput:r}){const[o,s]=ct({phase:"loading"});return ut(()=>{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]),ot((e,t)=>{t.escape&&(r(""),n())}),it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(StatusBody,{state:o}),it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Press ",it.createElement(CO,null,"Esc")," to return to conversation"))))}__name(StatusMessage,"StatusMessage"),__name(StatusBody,"StatusBody"),__name(StatusConfigView,"StatusConfigView"),Vt(),PR(),PR(),Vt(),PR();var{addDirectory:$_,formatDirectoryForDisplay:N_,getAdditionalDirectories:__,removeAdditionalDirectory:F_}=Vy,U_=__name(({onClose:e})=>{const[t,n]=ct(""),[r,o]=ct(null),[s,a]=ct([]),[i,l]=ct(()=>__()),[c,d]=ct(()=>({zone:"input",suggestionIndex:0,activeDirIndex:0})),[u,m]=ct(0);ut(()=>{a(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),m(0)},[t]),ut(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const p=__name(e=>{const t=$_(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(__()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),g=__name(e=>{if(!F_(e))return o({tone:"error",text:`${N_(e)} is no longer in workspace scope`}),void l(__());o({tone:"success",text:`Removed ${N_(e)} from directory scope`}),l(__()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");ot((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}))}}}),ut(()=>{"suggestions"===c.zone&&m(e=>getAdjustedSuggestionOffset({selectedIndex:c.suggestionIndex,currentOffset:e,maxVisible:hR,totalSuggestions:s.length}))},[c,s.length]),ut(()=>{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+hR),f=getAddDirFooterText({focusZone:c.zone});return it.createElement(RO,{title:"Add directory to workspace",subtitle:it.createElement(et,{color:LR.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),footer:it.createElement(et,{italic:!0,color:LR.DIM},it.createElement(BracketedText,{text:f,color:LR.DIM})),gapAfterHeader:!1},it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(et,{color:LR.GRAY},"Added directories"),0===i.length?it.createElement(et,{color:LR.GRAY}," None yet"):i.map((e,t)=>{const n="active-dir"===c.zone&&c.activeDirIndex===t;return it.createElement(Ze,{key:e},it.createElement(et,null," "),it.createElement(o_,{isSelected:n}),it.createElement(s_,{isSelected:n,isActive:!0}," ",N_(e)))})),it.createElement(Ze,{marginTop:1},it.createElement(et,{bold:!0,color:LR.WHITE},"Path")),it.createElement(Ze,null,it.createElement(TextInput,{value:t,focus:"input"===c.zone,prefix:`${"input"===c.zone?ft.pointer:" "} `,prefixColor:"input"===c.zone?MO:LR.GRAY,onChange:e=>{n(e),o(null)},onSubmit:p})),!t&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:{error:LR.RED,warning:LR.YELLOW,success:LR.GREEN}[r.tone]},r.text)),s.length>0&&it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.GRAY},"Suggestions"),h.map((e,t)=>{const n=u+t,r="suggestions"===c.zone&&c.suggestionIndex===n;return it.createElement(Ze,{key:e},it.createElement(et,null," "),it.createElement(o_,{isSelected:r}),it.createElement(s_,{isSelected:r,idleColor:LR.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")}}Vt(),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt(),Vt(),PR(),Vt(),PR(),__name(createBillingTransport,"createBillingTransport");var j_=null;function getBilling(){return j_||(j_=createBilling({transport:createBillingTransport()})),j_}function getCachedBillingContext(){return j_?.getCached()??null}function getBillingContext(){return getBilling().get()}function prefetchBillingContext(){getBilling().prefetch()}function invalidateBillingContext(){j_=null}function buildLaneModelPickerGroups(){const e=filterModelGroupsByRegisteredModules(_D).filter(e=>e.providerId!==fo.COMMAND);return[...buildModelPickerGroups({normalModeGroups:FD}),...e,...buildCustomModelPickerGroups()]}function buildCatalogModelPickerGroups(){return[...buildModelPickerGroups({normalModeGroups:FD}),...buildCustomModelPickerGroups()]}function laneServesModel(e){if(e.activeLane===fo.COMMAND)return!0;const t=ns[e.activeLane]?.supportedModelProviders;if(!t)return!0;const n=Object.values(fD).find(t=>t.id===e.modelId);return!n||laneSupportsModel(t,n)}function laneModelCount(e){return e.laneId===fo.COMMAND?FD.reduce((e,t)=>e+t.models.length,0):_D.find(t=>t.providerId===e.laneId)?.models.length??0}function defaultModelForLane(e){const t=filterModelGroupsByRegisteredModules(_D),n=t.filter(t=>t.providerId===e.activeLane),r=n.length>0?n:t.filter(e=>e.providerId===fo.COMMAND);return r[0]?.models[0]?.id}async function resolveProviderAuth(e){const t=await Promise.all([...new Set(e)].map(async e=>{const t=getProviderConfig(e);if(!t?.requiresAuth)return null;if(!t.checkAuth)return{providerId:e,authed:!0};try{return{providerId:e,authed:await t.checkAuth()}}catch{return{providerId:e,authed:!1}}})),n=new Set,r=new Set;for(const e of t)e&&(n.add(e.providerId),e.authed||r.add(e.providerId));return{authResolvedProviders:n,unauthedProviders:r}}function useCustomModelsReady(e){const[t,n]=ct(!1);return ut(()=>{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"),Vt(),PR(),__name(buildLaneModelPickerGroups,"buildLaneModelPickerGroups"),__name(buildCatalogModelPickerGroups,"buildCatalogModelPickerGroups"),__name(laneServesModel,"laneServesModel"),__name(laneModelCount,"laneModelCount"),__name(defaultModelForLane,"defaultModelForLane"),Vt(),__name(resolveProviderAuth,"resolveProviderAuth"),Vt(),__name(useCustomModelsReady,"useCustomModelsReady"),Vt(),PR();var B_=__name((e,t)=>{const n=t&&e.id===OD?" (default)":"",r="free"===e.badge?" (FREE)":"";return e.label.length+n.length+r.length},"renderedLabelLength");function getModelLabelColumnWidth(e,{showDefaultBadge:t=!0}={}){return e.reduce((e,n)=>Math.max(e,B_(n,t)+2),32)}__name(getModelLabelColumnWidth,"getModelLabelColumnWidth");var W_=__name(({model:e,providerId:t,isHighlighted:n,isCurrent:r,showProviderLabel:o,showDefaultBadge:s=!0,labelColumnWidth:a=32})=>{const i=ns[t],l=o??i?.showProviderLabelInSelector??!1,c=e.vendorLabel??DD[e.provider],d=s&&e.id===OD,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?tL:void 0,f=e.description?`${l?`${c} · `:""}${e.description}`:"",y=useTerminalWidth()>=a+38&&f;return it.createElement(Ze,null,it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:h,color:r?LR.GREEN:LR.WHITE,bold:r},m),u&&it.createElement(et,{backgroundColor:h,color:LR.GREEN,bold:!0},p),y&&it.createElement(et,{backgroundColor:h},g)),y&&it.createElement(Ze,{flexShrink:1},it.createElement(et,{backgroundColor:h,color:LR.DIM,wrap:"truncate-end"},f)),it.createElement(et,{backgroundColor:h,color:LR.GREEN},r?` ${ft.tick} `:" "))},"ModelRow");Vt(),PR();var H_=__name((e,t)=>`${e+1}. ${t}`,"labelText"),G_=__name(({modelLabel:e,supportedEfforts:t,currentEffort:n,onSelect:r,onCancel:o})=>{const s=mt(()=>buildEffortPickerRows(t),[t]),a=mt(()=>{if(void 0===n)return 0;const e=s.findIndex(e=>e.value===n);return e>=0?e:0},[s,n]),i=mt(()=>Math.max(...s.map((e,t)=>H_(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 it.createElement(RO,{title:`Select reasoning effort for ${e}`,hint:"↑/↓ navigate · enter to select · esc to go back"},it.createElement(Ze,{flexDirection:"column"},s.map((e,t)=>{const r=t===l,o=e.value===n;return it.createElement(Ze,{key:e.label},it.createElement(et,{color:r||!o?LR.WHITE:LR.GREEN,backgroundColor:r?tL:void 0,bold:r||o},H_(t,e.label).padEnd(i)),it.createElement(et,{color:r?LR.WHITE:LR.DIM,backgroundColor:r?tL:void 0},e.description," "),o&&it.createElement(et,{color:LR.GREEN}," ",ft.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}]:[]})}Vt(),PR(),__name(windowModelGroups,"windowModelGroups");var V_=__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]=ct(""),[p,g]=ct(null),[h,f]=ct(()=>new Set),[y,S]=ct(()=>new Set),w=r??p??fo.COMMAND,v=useCustomModelsReady(d),k=mt(()=>buildLaneModelPickerGroups(),[v]),C=mt(()=>filterModelPickerGroupsByAuth({groups:k,authResolvedProviders:y,unauthedProviders:h}),[k,y,h]),b=mt(()=>filterModelPickerGroups(C,u),[C,u]),E=mt(()=>{const e=new Set(C.map(e=>`${e.providerId}:${e.label}`));return k.filter(t=>!e.has(`${t.providerId}:${t.label}`))},[k,C]),T=mt(()=>filterModelPickerGroups(E,u),[E,u]),P=mt(()=>flattenModelPickerGroups(b),[b]),M=mt(()=>{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=mt(()=>getModelLabelColumnWidth(k.flatMap(e=>e.models)),[k]),[I,A]=ct(0),R=useTerminalHeight()-1,L=Math.max(4,R-16-2*b.length),O=void 0!==o,D=mt(()=>O?null:getCachedBillingContext(),[O]),[$,N]=ct(D),[_,F]=ct(!O&&!D);ut(()=>{if(O)return;if($)return;let e=!0;return getBillingContext().then(t=>{e&&(N(t),F(!1))}),()=>{e=!1}},[O,$]);const U=!O&&!0===$?.fetchFailed,j=O?o:$?.planId??null,B=O?s:$?.purchasedCredits??0,W=O?a:$?.freeCredits??0,H=n?Math.max(0,P.findIndex(e=>e.model.id===n)):0,[G,V]=ct("model"),[z,K]=ct(null),{cursor:q,error:Y,setError:Q}=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")});ut(()=>{A(e=>clampScrollOffset({cursor:q,total:P.length,maxVisible:L,currentOffset:e}))},[q,P.length,L]);const J=dt(!1),X=__name(t=>{if(!z||J.current)return;J.current=!0;const{model:r,providerId:o}=z,s=getReasoningEffort(r.id),a=t!==s,l=r.id===n;(async()=>{try{if(a&&(await setReasoningEffort({modelId:r.id,effort:t}),l)){const e=await tellSandboxEffort({effort:t});e.ok||dlog(`[Model] ${e.message}`),i?.()}}catch(e){dlog(`[Model] Failed to persist reasoning effort: ${e}`)}finally{e(r.id,o)}})()},"handleEffortSelect"),Z=__name(()=>{J.current||(K(null),V("model"))},"handleEffortCancel");if(ut(()=>{if(_)return;if(Y!==QP)return;const e=P[q];Q(e&&!U?getModelPickerAccessError({model:e.model,providerId:e.providerId,billing:{planId:j,purchasedCredits:B,freeCredits:W}}):null)},[_,U,Y,Q,P,q,j,B,W]),ut(()=>{(async()=>{const e=await getConfiguredProvider();e&&e!==fo.COMMAND&&g(e)})()},[]),ut(()=>{let e=!0;return(async()=>{const t=await resolveProviderAuth(k.map(e=>e.providerId));e&&(S(t.authResolvedProviders),f(t.unauthedProviders))})(),()=>{e=!1}},[k]),"effort"===G&&z){const e=z.model.reasoningEfforts??getSupportedEfforts(z.model.id)??[];return it.createElement(G_,{modelLabel:z.model.label,supportedEfforts:e,currentEffort:getReasoningEffort(z.model.id),onSelect:X,onCancel:Z})}const ee=I,te=I+L,ne=windowModelGroups({groups:b,firstSectionBase:0,windowStart:ee,windowEnd:te}),re=P.length>L;return it.createElement(RO,{title:"Select model",subtitle:l??"Switch between the available models. Sets the default for new sessions; other open sessions are unaffected.",footer:it.createElement(et,{italic:!0,color:LR.DIM},"type to search · ↑/↓ navigate · shift+↑/↓ jump provider · enter to select",u?" · esc to clear":" · esc to cancel")},it.createElement(Ze,{marginBottom:2,flexDirection:"column",width:"100%"},it.createElement(kL,{query:u,resultCount:u?P.length:void 0,placeholder:"Type to search models..."})),0===P.length?it.createElement(Ze,{marginY:1},it.createElement(et,{color:LR.GRAY},T.length>0?"Provider login required. Run /connect to authenticate.":`No models match "${u}"`)):it.createElement(Ze,{flexDirection:"column"},ne.map(({group:e,groupWindow:t},r)=>it.createElement(Ze,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:r>0?1:0},it.createElement(et,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>it.createElement(W_,{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&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",ee+1,"–",Math.min(te,P.length)," of ",P.length,ee>0?" · ↑ more":"",te<P.length?" · ↓ more":"")),Y&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.GRAY},Y)))},"ModelSelector"),z_=__name(e=>{if(!e)return"Inherit from session";for(const t of FD)for(const n of t.models)if(n.id===e)return n.label;return e},"agentModelLabel"),K_=[{value:"inherit",label:"1. Inherit from session (default)"},{value:"pick",label:"2. Pick a specific model"}],q_=__name(({selectedModel:e,onSelect:t})=>{const[n,r]=ct("choice"),[o,s]=ct(e?1:0);return ot((e,n)=>{if(n.upArrow)s(e=>Math.max(0,e-1));else if(n.downArrow)s(e=>Math.min(K_.length-1,e+1));else if("1"!==e)if("2"!==e){if(n.return){const e=K_[o];if(!e)return;"inherit"===e.value?t(null):r("picker")}}else r("picker");else t(null)},{isActive:"choice"===n}),"picker"===n?it.createElement(V_,{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}):it.createElement(Ze,{flexDirection:"column"},K_.map((e,t)=>{const n=t===o;return it.createElement(Ze,{key:e.value},it.createElement(et,{color:n?LR.WHITE:LR.GRAY,backgroundColor:n?tL:void 0,bold:n},n?">":" "," ",e.label))}),e&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.GRAY},"Currently pinned: ",z_(e))),it.createElement(bO,{hints:["↑↓ navigate","Enter to select","Inherit follows /model; pinned agents keep their own model and prompt cache"]}))},"AgentModelSelector"),Y_=__name(({config:e,onSaveComplete:t,viewOnly:n=!1})=>{const[r,o]=ct("idle"),[s,a]=ct(""),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:LS,model:e.model,reasoningEffort:e.reasoningEffort}),t(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");ot((e,t)=>{n||!t.return||"idle"!==r&&"error"!==r||i()});const l=formatAgentToolAccessForDisplay({access:[...e.selectedTools],allToolNames:LS,displayNameByToolName:$S,displayNameToToolName:NS}),c=e.location&&e.agentType?getAgentDisplayPath({location:e.location,name:e.agentType}):"";return it.createElement(Ze,{flexDirection:"column",gap:1},it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"Name:"),it.createElement(et,{color:LR.GRAY},e.agentType)),it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"Location:"),it.createElement(et,{color:LR.GRAY},c)),it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"Tools:"),it.createElement(et,{color:LR.GRAY},l)),it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"Model:"),it.createElement(et,{color:LR.GRAY},z_(e.model))),it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"Reasoning effort:"),it.createElement(et,{color:LR.GRAY},e.reasoningEffort??"model default"))),it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"Description"),it.createElement(et,{color:LR.GRAY},"(Tells ","Command Code"," when to use this agent):")),it.createElement(et,{color:LR.GRAY},e.ccToolDefinition),it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"System Prompt:")),it.createElement(et,{color:LR.GRAY},e.sysPrompt),!n&&it.createElement(Ze,{marginTop:1},"idle"===r&&it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to save ·"," ",it.createElement(CO,null,"Esc")," to cancel"),"saving"===r&&it.createElement(et,{color:LR.YELLOW},"Saving agent…"),"saved"===r&&it.createElement(j$,null,s),"error"===r&&it.createElement(Ze,{flexDirection:"column"},it.createElement(U$,null,"Error: ",s),it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to retry"))))},"AgentSummary"),Q_=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],J_=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=ct("menu"),a=new Set(resolveAgentToolSelection({access:e.tools,allToolNames:LS,displayNameToToolName:NS})),i={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:a,model:e.model??null,reasoningEffort:e.reasoningEffort??null},l=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],c=__name(e=>{"back"!==e.value?"view"!==e.value?"edit"!==e.value?"delete"===e.value&&s("delete"):s("edit"):s("view"):t()},"handleMenuSelect"),d=__name(async r=>{if("confirm-delete"===r.value)try{await deleteAgentDefinition({runtime:createNodeRuntime(),filePath:e.filePath}),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return ot((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=Q_[r];e&&d(e)}}),"view"===o?it.createElement(RO,{title:e.name,gapAfterHeader:!1,footer:it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to go back")},it.createElement(Y_,{config:i,onSaveComplete:()=>s("menu"),viewOnly:!0})):"edit"===o?it.createElement(RO,{title:e.name,gapAfterHeader:!1},it.createElement(et,{color:LR.YELLOW},"Edit functionality coming soon..."),it.createElement(kO,null,"Press ",it.createElement(CO,null,"Esc")," to go back")):"delete"===o?it.createElement(RO,{title:"Delete agent",subtitle:`Are you sure you want to delete the agent ${e.name}?`},it.createElement(Ze,null,it.createElement(SelectInput,{items:Q_,onSelect:d,indicatorComponent:u_,itemComponent:d_}))):it.createElement(RO,{title:e.name,footer:it.createElement(kO,null,"Press ",it.createElement(CO,null,"↑↓")," to navigate ·"," ",it.createElement(CO,null,"Enter")," to select · ",it.createElement(CO,null,"Esc")," ","to go back")},it.createElement(SelectInput,{items:l,onSelect:c,indicatorComponent:u_,itemComponent:d_}))},"AgentDetails");Vt();var X_="https://commandcode.ai/docs/core-concepts/custom-agents",Z_=__name(({onDone:e})=>(ot((t,n)=>{n.return&&e()}),it.createElement(RO,{title:"Create agents with Command Code",gapAfterHeader:!1,boxProps:{gap:1}},it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.GRAY},"Ask Command Code to create or update subagents for you, e.g."),it.createElement(et,{color:LR.GRAY}," ",ft.pointerSmall," “create a code-reviewer subagent that reviews diffs for bugs”"),it.createElement(et,{color:LR.GRAY}," ",ft.pointerSmall," “make a changelog agent that uses a fast model”")),it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.GRAY},"Or edit the files directly:"),it.createElement(et,{color:LR.GRAY}," • .commandcode/agents/ (this project)"),it.createElement(et,{color:LR.GRAY}," • ~/.commandcode/agents/ (all projects)")),it.createElement(et,{color:LR.GRAY},"Docs: ",X_),it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to go back and just ask"))),"AskCommandCodeGuide"),eF=__name(({handleSelect:e,createdAgentName:t})=>{const[n,r]=ct([]),[o,s]=ct([]),[a,i]=ct([]),[l,c]=ct(!0),[d,u]=ct(!1),[m,p]=ct(null),[g,h]=ct(!1),[f,y]=ct(0),[S,w]=ct(0),v=useTerminalHeight();ut(()=>{__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(ot((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}),ut(()=>{y(e=>Math.min(e,Math.max(0,k.length-1)))},[k.length]),ut(()=>{w(e=>clampScrollOffset({cursor:f,total:k.length,maxVisible:P,currentOffset:e}))},[f,k.length,P]),l)return it.createElement(F$,{label:"Loading agents"});if(g&&m){const e=isBuiltinAgentPath(m.filePath);return it.createElement(J_,{agent:m,onBack:()=>{h(!1),p(null)},setRevalidateAgent:u,isReadOnly:e})}const x=S,I=S+P,A=k.slice(x,I),R=k.length>P;let L=null;return it.createElement(RO,{title:"Agents",titleSuffix:C>0?` (${C} agent${C>1?"s":""})`:" (No custom agents)"},t&&it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{color:LR.GREEN,dimColor:!0},"Created agent: ",t)),it.createElement(Ze,{flexDirection:"column"},A.map((e,t)=>{const n=x+t,r=E(n),o="action"!==r&&r!==L;L=r;const s=n===f,a="user"===r?"User agents":"project"===r?"Project agents":"Default agents (read-only)";return it.createElement(it.Fragment,{key:e.value},o&&it.createElement(Ze,{marginTop:0===t?0:1},it.createElement(et,{color:HR,bold:!0},a)),it.createElement(Ze,null,it.createElement(et,{color:s?LR.WHITE:LR.GRAY,backgroundColor:s?tL:void 0,bold:s},s?"> ":" ",e.label," ")))})),R&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",x+1,"–",Math.min(I,k.length)," of ",k.length,x>0?" · ↑ more":"",I<k.length?" · ↓ more":"")),it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(bO,{hints:["↑↓ navigate","Enter to select","Esc to close"],marginTop:0}),it.createElement(et,{color:LR.DIM},"Agents live in .commandcode/agents/ (project) and ~/.commandcode/agents/ (all projects) — edit the files directly anytime."),it.createElement(et,{color:LR.DIM},"Docs: ",X_)))},"ManageAgents");Vt(),PR(),Vt(),Vt(),PR();var tF=__name(({model:e,selectedEffort:t,onSelect:n,onBack:r})=>{const o=(e?getSupportedEfforts(e):null)??[];return it.createElement(G_,{modelLabel:z_(e),supportedEfforts:o,currentEffort:t??void 0,onSelect:e=>n(e??null),onCancel:r})},"AgentEffortSelector");Vt();var nF=[{label:"1. Project (.commandcode/agents/)",value:"project"},{label:"2. Personal (~/.commandcode/agents/)",value:"personal"}],rF=__name(({onSelect:e})=>it.createElement(SelectInput,{items:nF,onSelect:t=>{"project"!==t.value&&"personal"!==t.value||e(t.value)},indicatorComponent:o_,itemComponent:a_}),"LocationSelector");Vt(),PR();var oF=__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:$S}):null,u=usePasteAwareChange({onChange:s}),m=usePasteAwareChange({onChange:a});return"agentType"===e?it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.WHITE},"Enter a unique identifier for your agent:"),"tool_conflict"===d?.issue&&it.createElement(et,{color:LR.RED},ft.warning," This name conflicts with an existing tool name. Please choose a different name."),"reserved"===d?.issue&&it.createElement(et,{color:LR.RED},ft.warning," This name is reserved. Reserved names: ",Yw.join(", "))),it.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?it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.WHITE},"Enter the system prompt for your agent:"),it.createElement(et,{color:LR.GRAY},"Be comprehensive for best results.")),it.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?it.createElement(it.Fragment,null,it.createElement(et,{color:LR.WHITE},"When should ","Command Code"," use this agent?"),it.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");Vt(),PR();var sF=__name((e,t)=>e?"[x]":"[ ]","categoryCheckbox"),aF=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=ct(!1),[a,i]=ct(0),[l,c]=ct(0),d=useTerminalHeight(),u=mt(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),WS.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:"}),LS.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=WS.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t)),s=r?.tools.some(t=>e.has(t));return{label:`${sF(Boolean(o),Boolean(s))} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${$S[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;ut(()=>{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 ot((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()}}),it.createElement(Ze,{flexDirection:"column"},S.map(e=>{const t=p.findIndex(t=>t.value===e.value),n=-1!==t&&t===a;if("divider"===e.type)return it.createElement(Ze,{key:`divider-${e.value}`},it.createElement(et,{color:LR.GRAY}," ",e.label));if("spacer"===e.type)return it.createElement(Ze,{key:`spacer-${e.value}`,height:1});if("label"===e.type)return it.createElement(Ze,{key:`label-${e.value}`},it.createElement(et,{color:LR.GRAY}," ",e.label));const r="continue"===e.type;return it.createElement(Ze,{key:`item-${e.value}`},it.createElement(et,{color:n?LR.WHITE:LR.GRAY,bold:r&&n},n?">":" "," ",e.label))}),w&&it.createElement(Ze,null,it.createElement(et,{color:LR.GRAY}," ","Showing ",f+1,"–",Math.min(y,m.length)," of"," ",m.length,f>0?" · ↑ more":"",y<m.length?" · ↓ more":"")),it.createElement(Ze,{marginTop:1},e.size===LS.length&&it.createElement(et,{color:LR.GRAY},"All tools selected"),e.size>0&&e.size<LS.length&&it.createElement(et,{color:LR.GRAY},e.size," tools selected"),0===e.size&&it.createElement(et,{color:LR.GRAY},"No tools selected")))},"ToolsSelector"),iF=__name(({onComplete:e})=>{const[t,n]=ct(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":"effort"===r?"Select reasoning effort":"summary"===r?"Confirm and save":""},"getSubText"),c=__name(e=>{a({type:"select_location",location:e}),a({type:"select_method",method:"manual"})},"handleLocationSelect");return it.createElement(RO,{title:"Create new agent",subtitle:l()},it.createElement(Ze,null,"location"===r&&it.createElement(rF,{onSelect:c}),"configuration"===r&&it.createElement(Ze,{flexDirection:"column",gap:1},it.createElement(oF,{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&&it.createElement(aF,{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&&it.createElement(q_,{selectedModel:s.model,onSelect:e=>a({type:"select_model",model:e})}),"effort"===r&&it.createElement(tF,{model:s.model,selectedEffort:s.reasoningEffort??null,onSelect:e=>a({type:"select_effort",effort:e}),onBack:()=>a({type:"back"})}),"summary"===r&&it.createElement(Y_,{config:s,onSaveComplete:i})))},"AgentNew"),lF=__name(({onCancel:e})=>{const[t,n]=ct(null),[r,o]=ct(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return ot((t,n)=>{n.escape&&e()}),it.createElement(Ze,{width:"100%",flexDirection:"column"},null===t&&it.createElement(eF,{handleSelect:s,createdAgentName:r}),"ask_command_code"===t&&it.createElement(Z_,{onDone:e}),"create_new_agent"===t&&it.createElement(iF,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");function isToggleShortcut(e,t){return""===e||!0===t.ctrl&&"b"===e}Vt(),PR(),__name(isToggleShortcut,"isToggleShortcut");var cF=new Set;function requestBackgroundTasksExpand(){for(const e of cF)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]=ct(()=>listShellTasks({includeStopped:!0}));return ut(()=>{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 dF=getShellTaskLabel,uF=getShellTaskStatusText,mF=getVisibleShellTasks,pF=latestShellTaskOutputLines,gF={running:LR.CYAN,completed:LR.GREEN,failed:LR.RED,"auto-stopped":LR.YELLOW,stopped:LR.GRAY};function getStatusColor(e){return gF[getShellTaskStatusTone(e)]}function TaskRow({task:e,selected:t}){const n=truncateString2({text:dF(e),maxChars:56}),r=t?tL:void 0;return it.createElement(Ze,null,it.createElement(o_,{isSelected:t,backgroundColor:r}),it.createElement(et,{color:t?MO:void 0,backgroundColor:r}," ",n),it.createElement(et,{color:LR.DIM,backgroundColor:r}," ","(",uF(e),")"))}function TaskGroup({title:e,tasks:t,selectedTaskId:n}){return 0===t.length?null:it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.DIM,bold:!0},e," (",t.length,")"),t.map(e=>it.createElement(TaskRow,{key:e.id,task:e,selected:e.id===n})))}function TaskDetailsBody({task:e,output:t}){const n=pF(t,10),r=formatTaskRuntime(e);return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,{bold:!0},"Status: "),it.createElement(et,{color:getStatusColor(e)},uF(e))),void 0!==r&&it.createElement(Ze,null,it.createElement(et,{bold:!0},"Runtime: "),it.createElement(et,null,r)),it.createElement(Ze,null,it.createElement(et,{bold:!0},"Script: "),it.createElement(et,{wrap:"wrap"},e.command)),it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{bold:!0},"Output:"),it.createElement(Ze,{flexDirection:"column",borderStyle:"single",borderColor:LR.DIM,paddingX:1},n.length>0?n.map((t,n)=>it.createElement(et,{key:`${e.id}-${n}`},truncateString2({text:t,maxChars:100}))):it.createElement(et,{color:LR.DIM},"No output yet.")),it.createElement(et,{italic:!0,color:LR.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]=ct(!1),[s,a]=ct("list"),[i,l]=ct(0),[c,d]=ct(""),u=mt(()=>mF(t),[t]),m=u[i]??u[0];ut(()=>{e?.(r)},[r,e]),ut(()=>{const e=__name(()=>{a("list"),o(!0)},"listener");return cF.add(e),()=>{cF.delete(e)}},[]),ut(()=>{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]),ut(()=>{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(ot((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 it.createElement(RO,{title:"monitor"===m.kind?"Monitor details":"Shell details",titleColor:LR.CYAN,ruleColor:LR.CYAN,subtitle:truncateString2({text:dF(m),maxChars:80}),hint:"← to go back · Esc/Enter/Space to close · x to stop",boxProps:{marginTop:1,marginBottom:1}},it.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 it.createElement(RO,{title:"Background",titleColor:LR.CYAN,ruleColor:LR.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?it.createElement(it.Fragment,null,it.createElement(TaskGroup,{title:"Monitors",tasks:g,selectedTaskId:m?.id}),it.createElement(TaskGroup,{title:"Shells",tasks:h,selectedTaskId:m?.id})):it.createElement(Ze,{flexDirection:"column",marginTop:1},u.map(e=>it.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"),Vt(),PR();var hF=[{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."}],fF=__name(({onSelect:e,onCancel:t})=>{const[n,r]=ct(null);ut(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(ot((e,n)=>{n.escape&&t()}),null===n)return null;const s=hF.findIndex(e=>e.value===n);return it.createElement(RO,{title:"Select a compact mode to compact sessions",subtitle:"Choose how Command Code handles automatic context compaction.",footer:it.createElement(et,{italic:!0,color:LR.DIM},"Press ",it.createElement(et,{bold:!0},"Esc")," to cancel")},it.createElement(SelectInput,{items:hF,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:u_,itemComponent:({isSelected:e,label:t})=>{const r=hF.find(e=>e.label===t),o=r?.value===n,s=hF.findIndex(e=>e.label===t);return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(c_,{isSelected:e,idleColor:o?LR.GREEN:LR.WHITE,bold:e||o},` ${s+1}. ${r?.label??t} `),o&&it.createElement(i_,null)),it.createElement(c_,{isSelected:e,idleColor:LR.DIM,bold:!1},` ${r?.description??""} `))}}))},"CompactModeSelector");Vt(),Vt(),Vt(),PR();var yF=["·","○","◇","☆","✧","☆","◇","○","⌘"],SF=[12,5,4,4,4,4,4,5,16],wF=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<SF.length;e++)if(n+=SF[e],t<n)return yF[e];const r=t-58;n=0;for(let e=0;e<wF.length;e++)if(n+=wF[e],r<n)return yF[7-e];return yF[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=mt(()=>e.split(""),[e]),o=__name(e=>{const n=e-(t-5);return n>=0&&n<JR.length?JR[n]:XR},"getCharColor");return it.createElement(et,null,r.map((e,t)=>it.createElement(et,{key:`${t}:${e}`,color:o(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return it.createElement(et,{color:t??OR,bold:!0},`${getWaveSymbol(e)} `)}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var vF=formatStatusTokenCount,kF=formatElapsedMs,CF=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=ct(0),[s,a]=ct(n),i=dt(n);i.current=n;const l=getTerminalWidth(),[c,d]=ct(()=>l>=72?"all":l>=42?"medium":"none");ut(()=>{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]),ut(()=>{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 FL.statusRender({width:l,layoutMode:c,status:e,frame:r}),it.createElement(Ze,{width:l,height:1,paddingLeft:0,marginLeft:0},it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:UR.BG,color:UR.FG}," "),it.createElement(et,{backgroundColor:UR.BG},it.createElement(CMDIcon,{frame:4*r,color:UR.FG})),it.createElement(ShimmerText,{text:e,offset:u,bg:UR.BG}),it.createElement(et,{backgroundColor:UR.BG,color:UR.FG}," ")),m&&it.createElement(Ze,{columnGap:1,marginLeft:1},it.createElement(et,{bold:!0,color:LR.GRAY},"esc"),it.createElement(et,{color:LR.DIM},"to interrupt"),it.createElement(et,{color:LR.DIM},"•"),it.createElement(et,{color:LR.DIM},kF(t)),it.createElement(et,{color:LR.DIM},"•"),it.createElement(et,{color:LR.GRAY},ft.arrowDown),it.createElement(et,{color:LR.DIM},vF(Math.round(s)))),p&&it.createElement(Ze,{marginLeft:1},it.createElement(et,{color:LR.DIM},vF(Math.round(s)))))},"Status");function ShimmerLine({text:e}){const[t,n]=ct(0);return ut(()=>{const e=setInterval(()=>n(e=>e+1),80);return()=>clearInterval(e)},[]),it.createElement(Ze,{marginLeft:1},it.createElement(ShimmerText,{text:e,offset:t%(e.length+10)}))}function useExternalEditor({input:e,setInput:t,setInputKey:n,detectedContent:r,setDetectedContent:o,onEditorClose:s}){const[a,i]=ct(!1),[l,c]=ct(null),d=pt(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 ry)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=pt(()=>{c(null)},[]);return{isEditorOpen:a,editorError:l,handleOpenInEditor:d,clearEditorError:u}}__name(ShimmerLine,"ShimmerLine"),Vt(),PR(),Vt(),PR(),__name(useExternalEditor,"useExternalEditor"),Vt(),PR();var bF=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=ct(null),[s,a]=ct(!1),[i,l]=ct({visible:!1,type:"connected"}),c=dt(null);null===c.current&&(c.current=RE({onConnectedChange:a,onContext:o,onIndicatorChange:l}));const d=c.current;ut(()=>{d.setPaused(n)},[d,n]),ut(()=>{if(t)return d.start(),()=>{d.stop()}},[t,d]);const u=mE(),m=u?NE[u]??"IDE":"IDE",p={visible:i.visible,message:"connected"===i.type?`${m} ${ft.tick}`:"run /ide",type:i.type};return{context:r,connected:s,refresh:d.refresh,connectionIndicator:p}},"useVSCodeContext");Vt(),PR();var EF=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=ct(null),o=dt(!1);return ut(()=>{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=dt([]),s=dt(""),a=dt(!1),i=dt(null),l=dt(!1),c=dt("");return ut(()=>{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})}Vt(),__name(pushEntry,"pushEntry"),__name(commitBurst,"commitBurst"),__name(useUndoStack,"useUndoStack"),Vt(),PR(),__name(getCommandHintLayout,"getCommandHintLayout"),__name(getModelHintText,"getModelHintText"),Vt(),PR();var TF=createNodeRuntime(),PF=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=ct(()=>process.cwd()),[a,i]=ct([]),[l,c]=ct(0),[d,u]=ct(0),m=n.trim()?15:10;ut(()=>{invalidateFileIndex()},[]),ut(()=>{let e=!1;return __name(async()=>{if(n.trim()){const t=await searchFiles({runtime:TF,searchTerm:n,basePath:process.cwd()});if(e)return;return i(t),c(0),void u(0)}try{const t=await browseDirectory({runtime:TF,dirPath:r,basePath:process.cwd()});if(e)return;i(t),c(0),u(0)}catch{}},"run")(),()=>{e=!0}},[r,n]),ot((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 it.createElement(Ze,{flexDirection:"column",paddingLeft:1},it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},n.trim()?`Searching for: "${n}"`:`Files: ${r}`)),0===p.length?it.createElement(W$,{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 it.createElement(et,{key:e.path,color:o?MO:LR.DIM,bold:o&&isLightTheme()},e.isDirectory?`${r}/`:r)}),it.createElement(bO,{hints:["↑↓ navigate",!n.trim()&&"→ to open folder","Enter to select","Esc to close"]}))},"FileList");Vt(),PR();var MF=__name(()=>it.createElement(Ze,{paddingRight:3},it.createElement(et,{color:LR.DIM,wrap:"truncate"},ft.pointerSmall," ","stashed")),"StashBadge"),xF=__name(({hint:e})=>it.createElement(Ze,{paddingRight:1},it.createElement(et,{color:LR.DIM,wrap:"truncate"},e)),"PasteKeyHint"),IF=__name(({tasteLearningOn:e,byokSession:t,showSeparator:n=!0})=>{if(null==e)return null;const r=e&&t;return it.createElement(it.Fragment,null,n&&it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:e&&!r?DR.TEXT:LR.DIM},r?"taste off (byok)":"taste "+(e?"on":"off")))},"TasteStateBadge");function useBackgroundTasksSummary(){const[e,t]=ct(()=>formatShellTaskCounts(listShellTasks({includeStopped:!1})));return ut(()=>{const e=setInterval(__name(()=>t(formatShellTaskCounts(listShellTasks({includeStopped:!1}))),"refresh"),1e3);return()=>clearInterval(e)},[]),e}__name(useBackgroundTasksSummary,"useBackgroundTasksSummary");var AF=__name(({showSeparator:e=!0,armed:t=!1})=>{const n=useBackgroundTasksSummary();return n?it.createElement(it.Fragment,null,e&&it.createElement(et,{color:LR.DIM}," · "),t?it.createElement(it.Fragment,null,it.createElement(et,{color:LR.CYAN,inverse:!0},` ${n} `),it.createElement(et,{color:LR.DIM}," · Enter to open")):it.createElement(it.Fragment,null,it.createElement(et,{color:LR.CYAN},n),it.createElement(et,{color:LR.DIM}," · ↓ to manage"))):null},"BackgroundTasksBadge"),RF=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?it.createElement(it.Fragment,null,t&&it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:"connected"===e.type?LR.GREEN:LR.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),LF=__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,pasteKeyHint:C})=>{const b=e>=60,E=C&&e>=90?C:null;return it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r&&"bypass"!==r&&"dont-ask"!==r||i?it.createElement(Ze,{flexDirection:"row",justifyContent:"space-between",width:e-1},it.createElement(Ze,{flexDirection:"row",columnGap:0},n&&!i?it.createElement(et,{color:WR},t):it.createElement(fL,{mode:r,pendingExitKey:i}),!i&&it.createElement(SL,{prInfo:o}),!i&&it.createElement(RF,{indicator:a}),!i&&b&&it.createElement(IF,{tasteLearningOn:w,byokSession:v}),!i&&it.createElement(AF,{armed:k})),(b||S||E)&&it.createElement(Ze,{flexDirection:"column",alignItems:"flex-end"},!S&&E&&it.createElement(xF,{hint:E}),S?it.createElement(MF,null):null,!S&&b&&s&&it.createElement(aL,{usage:s}))):it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"row",justifyContent:"space-between",width:e-1},it.createElement(fL,{mode:r}),S&&it.createElement(MF,null),!S&&E&&it.createElement(xF,{hint:E})),it.createElement(Ze,{flexDirection:"row",justifyContent:"space-between",width:e-1},it.createElement(Ze,{flexDirection:"row",columnGap:0},it.createElement(et,{color:n?WR:LR.DIM},t),it.createElement(SL,{prInfo:o}),it.createElement(RF,{indicator:a}),b&&it.createElement(IF,{tasteLearningOn:w,byokSession:v}),it.createElement(AF,{armed:k})),it.createElement(Ze,{flexDirection:"row",columnGap:2},b&&s&&it.createElement(aL,{usage:s})))),(l||c||u&&d)&&it.createElement(Ze,{flexDirection:"row",columnGap:1},l&&it.createElement(et,null,ft.tick," ","Command Code"," updated:"," ",it.createElement(et,{color:LR.DIM},"v",l.updatedFrom),it.createElement(et,{color:LR.DIM}," ",ft.arrowRight," "),it.createElement(et,null,"v",l.updatedTo)),!l&&c&&it.createElement(et,{color:LR.YELLOW,dimColor:!0},ft.info," Update available:"," ",c.currentVersion," ",ft.arrowRight," ",c.latestVersion),u&&d&&it.createElement(et,{color:LR.GREEN,dimColor:!0},ft.bullet," Provider:"," ",getProviderDisplayName(d)))),m&&it.createElement(Ze,{paddingLeft:2},it.createElement(et,{color:LR.GREEN},"! for bash mode")),g&&p&&it.createElement(Ze,{paddingLeft:2},it.createElement(et,{color:OR},"SHARED: ",p.url," (copied to clipboard)")),h&&it.createElement(Ze,{paddingLeft:2},it.createElement(et,{color:h.includes("NOT SHARED")?LR.RED:OR},h)),f&&it.createElement(Ze,{paddingLeft:2},it.createElement(et,{color:OR},f)),y&&it.createElement(Ze,{paddingLeft:2},it.createElement(et,{color:LR.YELLOW},ft.warning," ",y)))},"BottomIndicator");Vt();var OF=[["rc","token"],["rc","user"]];function carriesSecretArgument(e){const[t,n,...r]=e.trim().replace(/^\//,"").split(/\s+/).filter(Boolean);return void 0!==t&&void 0!==n&&0!==r.length&&OF.some(([e,r])=>e===t.toLowerCase()&&r===n.toLowerCase())}function useClipboardPasteKey(e){const{latestInputRef:t,cursorPositionRef:n,detectedImagesRef:r,setDetectedImages:o,setInput:s,incrementInputKey:a,setInitialCursor:i,handlePaste:l,onTextPasted:c,showClipboardNotice:d,clearClipboardNotice:u,showPasteKeyHint:m}=e,p=pt(e=>{const l=nextImagePasteNumber(r.current),{text:c,cursor:d}=insertTextAt(t.current,n.current,imagePasteToken(l)),u=[...r.current,{imageNumber:l,image:e}];r.current=u,o(u),s(c),t.current=c,n.current=d,i(d),a()},[n,r,a,t,o,i,s]),g=pt(async e=>{const r=stripEmbeddedPasteEndMarker(e),o=t.current,s=n.current,a=o.slice(0,s),i=o.slice(s);await l(`${a}[200~${r}[201~${i}`)&&c()},[n,l,t,c]);return pt(async()=>{const e=setTimeout(()=>{d("Reading clipboard…",{sticky:!0})},150);try{const t=await probeClipboardImage();if(t.image)return p(t.image),clearTimeout(e),void u();const n=t.text??await detectClipboardText();if(clearTimeout(e),n)return u(),void await g(n);d(describeClipboardImageMiss({environment:t.environment,attempted:t.attempted})),m()}catch{clearTimeout(e),u()}},[u,p,g,d,m])}__name(carriesSecretArgument,"carriesSecretArgument"),Vt(),PR(),__name(useClipboardPasteKey,"useClipboardPasteKey");var DF=["","","[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 $F=__name(({pasteKeyAdvice:e})=>it.createElement(Ze,{flexDirection:"column",paddingLeft:1},it.createElement(et,{color:LR.DIM,bold:!0},"Available Shortcuts:"),it.createElement(Ze,{columnGap:4},it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.DIM},"! for bash mode"),it.createElement(et,{color:LR.DIM},"/ for commands"),it.createElement(et,{color:LR.DIM},"@ for file paths"),it.createElement(et,{color:LR.DIM},getModeToggleShortcutHint()," to toggle accept edits")),it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.DIM},"double tap esc to clear input"),it.createElement(et,{color:LR.DIM},getNewlineShortcutHint()," for newline"),it.createElement(et,{color:LR.DIM},"ctrl + g to open in editor"),it.createElement(et,{color:LR.DIM},"ctrl + z to undo"),it.createElement(et,{color:LR.DIM},"ctrl + s to stash prompt"),it.createElement(et,{color:LR.DIM},spacedKey(e.key)," to paste image"),e.textOnlyKey&&it.createElement(et,{color:LR.DIM},spacedKey(e.textOnlyKey)," pastes text only in ",e.terminal)))),"ShortcutMenu");function spacedKey(e){return e.split("+").join(" + ")}function currentPasteKeyAdvice(){return pasteImageKeyAdvice({terminal:detectTerminal({env:process.env}),environment:currentClipboardEnvironment()})}__name(spacedKey,"spacedKey"),__name(currentPasteKeyAdvice,"currentPasteKeyAdvice");var NF=__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:L=!1,ideContextEnabled:O=!0,footer:D})=>{const[$,N]=ct(0),[_,F]=ct(!1),[U,j]=ct(!1),[B,W]=ct(!1),[H,G]=ct(""),[V,z]=ct(null),K=dt(0),q=dt(0),[Y,Q]=ct([]),[J,X]=ct([]),[Z,ee]=ct(null),[te,ne]=ct(null),re=dt(null),oe=pt(()=>{re.current&&(clearTimeout(re.current),re.current=null),ne(null)},[]),se=pt((e,t)=>{re.current&&(clearTimeout(re.current),re.current=null),ne(e),t?.sticky||(re.current=setTimeout(()=>{re.current=null,ne(null)},5e3))},[]);ut(()=>()=>{re.current&&clearTimeout(re.current)},[]);const ae=mt(currentPasteKeyAdvice,[]),ie=mt(()=>formatPasteImageKeyHint(ae),[ae]),[le,ce]=ct(()=>ie?Date.now():null);ut(()=>{if(null===le)return;const e=setTimeout(()=>{ce(null)},2e4);return()=>clearTimeout(e)},[le]);const de=pt(()=>{ie&&ce(Date.now())},[ie]),ue=dt(!1),me=dt(!1),[pe,ge]=ct(!1),he=dt(!1),fe=pt(e=>{he.current=e,ge(e)},[]),ye=dt(!1),Se=dt(void 0),[we,ve]=ct(-1),[ke,Ce]=ct(""),be=dt(0),Ee=dt(e);Ee.current=e;const Te=dt(J);Te.current=J;const{commitUndo:Pe}=useUndoStack({input:e,setInput:n,initialCursorRef:Se,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey")}),{isEditorOpen:Me,editorError:xe,handleOpenInEditor:Ie,clearEditorError:Ae}=useExternalEditor({input:e,setInput:n,setInputKey:N,detectedContent:Y,setDetectedContent:Q,onEditorClose:__name(()=>{ue.current=!1},"onEditorClose")}),Re=mt(()=>shouldCollapsePastedText(),[]),{handlePaste:Le,resetPasteState:Oe,isPasting:De}=useBracketedPaste({input:e,setInput:n,setDetectedImages:X,setDetectedContent:Q,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{Se.current=e},"setInitialCursor"),collapsePastedText:Re,nextImageNumber:nextImagePasteNumber(J),onPasteMiss:__name(e=>{se(describeClipboardImageMiss({environment:e.environment,attempted:e.attempted})),de()},"onPasteMiss")}),$e=useClipboardPasteKey({latestInputRef:Ee,cursorPositionRef:be,detectedImagesRef:Te,setDetectedImages:X,setInput:n,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{Se.current=e},"setInitialCursor"),handlePaste:Le,onTextPasted:__name(()=>{ye.current=!0},"onTextPasted"),showClipboardNotice:se,clearClipboardNotice:oe,showPasteKeyHint:de}),Ne=dt(()=>{});Ne.current=t=>{Me||(async()=>{const n=be.current,r=e.slice(0,n),o=e.slice(n),s=stripEmbeddedPasteEndMarker(t);await Le(`${r}[200~${s}[201~${o}`)&&(ye.current=!0)})()},ut(()=>registerPasteConsumer(e=>Ne.current(e)),[]);const _e=dt(new Map),Fe=mt(()=>{const e=_e.current,t=new Map,n=new Map;for(const r of J){const o=e.has(r)?e.get(r)??null:saveTempImage(r.image,r.imageNumber);t.set(r,o),n.set(r.imageNumber,o)}return _e.current=t,n},[J]),{skills:Ue,customMenuItems:je}=useSlashMenuData(),Be=mt(()=>{const e=resolveSlashMenuItems({searchQuery:"",customMenuItems:je,skills:Ue,showProviderCommand:!0,showTerminalSetupCommand:isVSCodeTerminal2()});return new Set([...e.map(e=>e.command),...Ue.map(e=>buildSkillNamespacedCommand(e.name))])},[Ue,je]),We=pt(e=>Be.has(e),[Be]),{context:He,connected:Ge,refresh:Ve,connectionIndicator:ze}=bF({enabled:O,paused:L}),{stdout:Ke}=nt(),qe=Ke?.columns??80,{pr:Ye}=EF();ut(()=>{const e=s||B;I?.(e)},[s,B,I]),ut(()=>{if(!ye.current)return;ye.current=!1;const t=Iy(e);!B&&t.showCommandMenu||(W(t.showCommandMenu),G(t.showCommandMenu?t.commandSearchQuery:""))},[e,B]);const Qe=pt(()=>{X([])},[]),Je=pt(()=>{W(!1),z(null)},[]),Xe=pt(()=>{Je(),G(""),i(!1),c(""),ve(-1),Ce(""),Se.current=void 0,N(e=>e+1)},[Je,c,i]),tt=pt(t=>!(null===Z||!t?.replaceCurrentInput&&e.trim().length>0||(ue.current=!0,n(Z),ee(null),Xe(),setTimeout(()=>{ue.current=!1},0),0)),[e,Xe,n,Z]),rt=pt(()=>{n(""),j(!1),Je(),G(""),Q([]),Qe(),Oe(),ve(-1),Ce(""),N(e=>e+1)},[n,Oe,Qe,Je]),st=pt(e=>{ue.current=!0,n(e.text),Se.current=e.cursor,N(e=>e+1),setTimeout(()=>{ue.current=!1},0)},[n]),at=pt(()=>{st(insertTextAt(e,be.current,"\n"))},[e,st]);ot(async(t,r)=>{if(he.current&&!r.downArrow&&!r.return&&"\r"!==t&&(fe(!1),r.upArrow))return;if(r.upArrow){if(s||B)return;const t=e.indexOf("\n"),r=-1===t||be.current<=t;if(0!==e.length&&-1===we&&!r)return;const o=M?.count()??0;if(0===o)return;-1===we&&Ce(e);const a=Math.min(we+1,o-1);return void(a!==we&&(ve(a),n(M?.getAt(a)||""),N(e=>e+1)))}if(r.downArrow){if(s||B)return;if(-1===we){const t=e.lastIndexOf("\n"),n=-1===t||be.current>t;return void((0===e.length||n)&&listShellTasks().some(e=>"running"===e.status)&&fe(!0))}const t=e.lastIndexOf("\n");if(!(-1===t||be.current>t))return;const r=we-1;return ve(r),n(-1===r?ke:M?.getAt(r)||""),void N(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void Qe();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return ue.current=!0,void Ie();if(isCtrlKey({inputChar:t,key:r,letter:"s",ctrlCode:19})){const t=e.trim().length>0;if(!t&&null===Z)return;if(!t&&tt())return;ue.current=!0;const r=Z??"";return ee(t?e:null),n(r),Xe(),void setTimeout(()=>{ue.current=!1},0)}if(getIsExpandToolShortcut(r,t))return ue.current=!0,n(e),N(e=>e+1),void setTimeout(()=>{ue.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:De()}))return me.current=!0,at(),void setTimeout(()=>{me.current=!1},0);if(r.meta&&"w"===t)return ue.current=!0,void rt();const o=r.ctrl&&"v"===t.toLowerCase()||DF.includes(t),a=r.meta&&"v"===t.toLowerCase();if(o||a){if(Me)return;return ue.current=!0,setTimeout(()=>{ue.current=!1},0),void await $e()}if(!r.ctrl&&!r.meta||"u"!==t)if(r.ctrl&&"z"===t?.toLowerCase())Pe();else{if(r.escape){if(B)return;const t=Date.now();return t-K.current<500?(e.length>0?rt():A?.(),K.current=0,q.current=0,F(!1),void j(!1)):(K.current=t,_||U||(q.current=t),F(!1),void j(!1))}if(_&&(r.backspace||r.delete)&&0===e.length)F(!1);else if(r.return&&!r.shift&&!r.ctrl&&!r.meta){if(he.current&&(fe(!1),listShellTasks().some(e=>"running"===e.status)))return void requestBackgroundTasksExpand();if(me.current)return void(me.current=!1);if(Date.now()-q.current<100)return q.current=0,void at();if(s)return;if(B)return;if(Me)return;const e=applyBackslashNewline(Ee.current,be.current);return e?void st(e):void await gt(Ee.current)}}});const lt=pt(async t=>{if(Me)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||De())&&await Le(t))return void(ye.current=!0);if(ue.current)return void(ue.current=!1);-1!==we&&ve(-1),X(e=>{if(0===e.length)return e;const n=prunePastedImages({input:t,images:e});return n===e?e:[...n]});const u=1===t.length,m=t.slice(-1);if(u){if("?"===m&&!_)return F(!0),n(""),void N(e=>e+1);if("!"===m&&!U)return F(!1),j(!0),n(""),void N(e=>e+1)}const p=Iy(t),g=t.length<e.length&&!e.startsWith(t),h=!g&&t.length<e.length,f=t.length===e.length+1||h,y=Ay({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),xe&&Ae(),0===t.length&&(j(!1),Je(),G(""),Q([]),c(""),Oe()),n(t)},[_,e,n,s,i,l,c,B,H,U,we,Le,Oe,De,R,xe,Ae,Me,Je]),gt=pt(async(r=e)=>{if(Ve(),q.current=0,_)return void F(!1);const o=r.trim(),s=!U&&o.startsWith("/");let a=o;!U&&Y.length>0&&(a=resolvePastedTextTokens({input:a,detectedContent:Y}));const i=U?[]:resolvePastedImageTokens({input:o,images:J}),l={};if(!U)for(const e of J){if(!o.includes(imagePasteToken(e.imageNumber)))continue;const t=Fe.get(e.imageNumber);t&&(l[e.imageNumber]=t)}const c=Object.keys(l).length>0,u=He?EE(He):void 0;if(s&&d&&(n(""),"handled"===(await d(a,i,u)).status))return carriesSecretArgument(a)||M?.add(a),j(!1),Je(),G(""),Qe(),Q([]),ve(-1),Ce(""),void tt({replaceCurrentInput:!0});ve(-1),Ce(""),a.length>0&&!carriesSecretArgument(a)&&M?.add(a);const m=buildIdeContextHint({ideContext:He});t({input:a,role:U?"bash":"user",images:i,ideContext:u,ideHint:m,imageTokenPaths:c?l:void 0}),j(!1),Je(),G(""),Qe(),Q([]),tt({replaceCurrentInput:!0})},[t,d,_,e,U,J,Fe,Y,M,Ve,He,Qe,Je,tt,n]),ht=pt(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(""),N(e=>e+1)},[n,i,e,s,l,c]),yt=pt(()=>{i(!1),c("")},[i,c]),St=pt(e=>{const t=Ey.has(e),r="/design"===e.trimEnd();if(t||r){const t=e.trimEnd();return n(t+" "),G(t.substring(1)+" "),void N(e=>e+1)}Je(),G(""),n(e+" "),N(e=>e+1)},[n,Je]),wt=pt(t=>{if("/design help"===t)return Je(),G(""),n(""),N(e=>e+1),M?.add(t),void d?.("/design help");if(by.has(t))return Je(),G(""),M?.add(t),ve(-1),Ce(""),n(""),N(e=>e+1),void d?.(t);const r=Ey.has(t),o=Ba.has(t),s=Wa.has(t);if(r)St(t);else{if(Je(),G(""),!o&&!s&&e!==t)return n(t+" "),void N(e=>e+1);M?.add(t),ve(-1),Ce(""),n(""),N(e=>e+1),d?.(t)}},[d,n,e,M,St,Je]),vt=pt(()=>{Je(),G(""),ve(-1),Ce(""),N(e=>e+1)},[Je]),kt=pt(e=>{be.current=e,Se.current=void 0},[]),Ct=mt(()=>formatSlashCommandInputHint({value:e,selectedCommand:B?V:null}),[e,B,V]),bt=Boolean(Ct)&&!x,Et=mt(()=>{const t=Ye&&("OPEN"===Ye.state||"MERGED"===Ye.state);return"auto-accept"===E||"plan"===E||"bypass"===E||"dont-ask"===E||Ge||t?!_:!_&&0===e.length&&!U},[_,e,U,E,Ge,Ye]),Tt=null!==Z,Pt=__name(()=>_||s||B?0:bt||Et||x||U?3:4,"getBottomMargin");return it.createElement(Ze,{width:"100%",flexDirection:"column",marginBottom:Pt()},it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(et,{color:U?LR.GREEN:LR.GRAY},ft.line.repeat(qe)),(()=>{const t=__name(t=>it.createElement(TextInput,{key:$,value:e,placeholder:Me?"Save and close the editor to continue...":o,onChange:lt,showCursor:!Me&&r,onCursorChange:kt,initialCursor:Se.current,prefix:`${U?"!":ft.pointer} `,prefixColor:U?LR.GREEN:LR.WHITE,singleLine:t?.singleLine,maxWidth:t?.maxWidth,imageTokenLinks:Fe,isRecognizedSlashCommand:We,disablePasteRouting:!0}),"renderTextInput"),n=B?"/model"===V&&C?getModelHintText(C):Ct:null,s=n?getCommandHintLayout({text:n,terminalWidth:qe}):null;return s?it.createElement(Ze,{flexDirection:"row",width:"100%"},it.createElement(Ze,{width:25},t({singleLine:!0,maxWidth:25})),it.createElement(Ze,{width:s.descriptionWidth},it.createElement(et,{color:LR.DIM,wrap:"truncate"},s.text))):t()})(),it.createElement(et,{color:U?LR.GREEN:LR.GRAY},ft.line.repeat(qe))),_&&it.createElement($F,{pasteKeyAdvice:ae}),s&&it.createElement(PF,{onSelectFile:ht,onClose:yt,searchQuery:l}),B&&it.createElement(oL,{onSelectCommand:wt,onInsertCommand:St,onSubmitSearch:gt,onClose:vt,searchQuery:H,onSelectedCommandChange:z}),!B&&!s&&bt&&it.createElement(Ze,null,it.createElement(et,{color:LR.DIM,wrap:"truncate"},Ct)),!B&&!s&&!bt&&(Et||x||Tt)&&it.createElement(LF,{termWidth:qe,indicatorText:getIdeInputIndicatorText(Ge,He,qe),isIDEIndicator:hasIdeInputIndicatorContext(Ge,He),permissionMode:E,prInfo:Ye,contextUsage:u,tasteLearningOn:m,byokSession:isByok({model:C??""}),connectionIndicator:ze,pendingExitKey:x,updateStatus:w,updateFailedInfo:v,currentProvider:k,showProviderInfo:b,isBashMode:U,shareInfo:g,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,creditWarning:S,hasStashedPrompt:Tt,backgroundTasksArmed:pe,pasteKeyHint:null!==le&&0===J.length?ie:null}),xe&&it.createElement(Ze,{paddingLeft:1,flexDirection:"column"},it.createElement(et,{color:LR.YELLOW},xe)),!xe&&te&&it.createElement(Ze,{paddingLeft:1},it.createElement(et,{color:LR.DIM,wrap:"truncate"},te)),D)},"InputBox");Vt(),PR();var _F=__name(()=>{const[e,t]=ct([]);return ut(()=>subscribeModStatus(t),[]),0===e.length?null:it.createElement(Ze,{paddingLeft:2},it.createElement(et,{wrap:"truncate"},e.map(e=>e.text).join(" ")))},"ModStatusLine");Vt(),PR();var FF=__name(({messages:e})=>{const t=countVisibleQueuedMessages(e);if(0===t)return null;const n=getQueuedDisplayRows(e);return it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(Ze,{marginBottom:0},it.createElement(et,{color:NR,inverse:!0},` Queued (${t}) `)),n.map(e=>it.createElement(Ze,{key:e.text},it.createElement(et,{color:LR.DIM},ft.pointerSmall," "),it.createElement(et,{color:LR.DIM},truncateString2({text:e.count>1?`${e.text} (${e.count})`:e.text,maxChars:80})))))},"QueuedMessages");function useWorkedDuration(e,t){const n=dt(null),[r,o]=ct(null);return ut(()=>{n.current=null,o(null)},[t]),ut(()=>{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:it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},`✻ Worked for ${formatElapsedMs(e)}`))}Vt(),PR(),__name(useWorkedDuration,"useWorkedDuration"),__name(WorkedDurationNote,"WorkedDurationNote");var UF=it.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:L,onDoubleEscapeEmpty:O,retryAttempt:D,onAltP:$,inputActive:N=!0,inactiveHint:_,sessionId:F})=>{const[U,j]=ct(()=>null===n?0:Date.now()-n),B=dt(s),W=t||r.isExecuting,H=t&&isSandboxMode()&&null===getSandboxConnection(),G=useWorkedDuration(W&&!H,F);return ut(()=>{R&&s!==B.current&&s.length>0&&L?.(),B.current=s},[s,R,L]),ut(()=>{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]),it.createElement(Ze,{flexDirection:"column"},it.createElement(FF,{messages:e}),it.createElement(Ze,{flexDirection:"row",justifyContent:"space-between"},it.createElement(Ze,{flexDirection:"column"},H&&it.createElement(ShimmerLine,{text:"Connecting to the sandbox…"}),W&&!H&&null===D&&it.createElement(CF,{tokens:p,timeElapsed:U,status:r.isExecuting?`Executing: ${r.currentCommand}`:o}),!W&&it.createElement(WorkedDurationNote,{durationMs:G}),W&&!H&&null===D&&I&&it.createElement(Ze,{marginLeft:1},it.createElement(et,{color:LR.DIM}," ","⎿"," ","Tip: ",I)))),N?it.createElement(NF,{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:O,onAltP:$,isProcessing:t,footer:it.createElement(_F,null)}):it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{marginLeft:1},it.createElement(kO,null,_??"Background focused · ↑/↓ to select · Enter to view · x to stop · ←/Esc to go back to feed")),it.createElement(_F,null)))});Vt();var jF=__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 ot((e,t)=>{t.ctrl&&"c"===e&&l()}),it.createElement(OO,{authState:n,statusMessage:r,browserUrl:o,apiKeyInput:s,setApiKeyInput:a,handleApiKeySubmit:i})},"LoginOverlay");function getStatusTextColor(e){return"connected"===e?LR.GREEN:"connecting"===e||"authenticated"===e?LR.CYAN:"requires_auth"===e?LR.YELLOW:LR.GRAY}Vt(),PR(),__name(getStatusTextColor,"getStatusTextColor");var BF=__name((e,t)=>{const n=__name((e,n)=>it.createElement(et,{color:e,backgroundColor:t},n),"icon");return"connected"===e?n(LR.GREEN,ft.tick):"connecting"===e?n(LR.CYAN,ft.circle):"authenticated"===e?n(LR.CYAN,ft.tick):"requires_auth"===e?n(LR.YELLOW,ft.warning):"error"===e?n(LR.RED,ft.cross):n(LR.GRAY,ft.circle)},"getStatusIcon"),WF=__name(({onClose:e,mcp:t})=>{const[n,r]=ct([]),[o,s]=ct(!0),[a,i]=ct(0),[l,c]=ct("list"),[d,u]=ct(null),[m,p]=ct(0),g=useTerminalHeight(),h=pt(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]);ut(()=>{h()},[h]),ut(()=>{if(t)return t.onChange(()=>{h()})},[t,h]);const f=mt(()=>[...orderMcpManagerServers(n)],[n]),y=f[a]??null,S=g-1,w=mt(()=>new Set(f.map(e=>e.scope)).size,[f]),v=Math.max(4,S-8-2*w);ut(()=>{p(e=>clampScrollOffset({cursor:a,total:f.length,maxVisible:v,currentOffset:e}))},[a,f.length,v]),ot((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:LR.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:y.name,enabled:!0,scope:y.scope}))return void u({text:`${ft.cross} Failed to enable ${y.name}, server may no longer exist in ${y.scope} scope`,color:LR.YELLOW});await h(),u({text:`${ft.tick} Enabled ${y.name}`,color:LR.GREEN})}catch(e){u({text:`${ft.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:LR.RED})}}else{u({text:`Disabling ${y.name}...`,color:LR.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:y.name,enabled:!1,scope:y.scope}))return void u({text:`${ft.cross} Failed to disable ${y.name}, server may no longer exist in ${y.scope} scope`,color:LR.YELLOW});await disconnectMcpServer({name:y.name,registry:t}),await h(),u({text:`${ft.tick} Disabled ${y.name}`,color:LR.GREEN})}catch(e){u({text:`${ft.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:LR.RED})}}else c("confirm-remove");else{u({text:`Authenticating ${y.name}...`,color:LR.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:LR.YELLOW});"success"===e.kind?(u({text:`${ft.tick} Authenticated with ${y.name}`,color:LR.GREEN}),await h()):u({text:`${ft.cross} Auth failed: ${e.message}`,color:LR.RED})}catch(e){u({text:`${ft.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:LR.RED})}}else{u({text:`Connecting ${y.name}...`,color:LR.CYAN,loading:!0});try{await connectMcpServer({name:y.name,registry:t}),u({text:`${ft.tick} Connected to ${y.name}`,color:LR.GREEN}),await h()}catch(e){u({text:`${ft.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:LR.RED})}}else u({text:"Already authenticated",color:LR.GREEN});else u({text:"Already connected",color:LR.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:`${ft.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:LR.RED}),c("actions")}else c("actions")},"handleRemoveConfirm");if(o)return it.createElement(RO,{title:"Manage MCP servers"},it.createElement(et,{color:LR.DIM},"Loading..."));if("confirm-remove"===l&&y)return it.createElement(RO,{title:`Remove ${y.name}?`,titleColor:LR.RED,hint:"↑↓ navigate · Enter to select · Esc to cancel"},it.createElement(et,{color:LR.DIM},"This will remove the server from ",y.scope," ","config."),it.createElement(Ze,{marginTop:1},it.createElement(SelectInput,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:C,indicatorComponent:u_,itemComponent:d_})));if("actions"===l&&y){const e=buildMcpManagerActionItems(y);return it.createElement(RO,{title:y.name,hint:"↑↓ navigate · Enter to select · Esc to go back"},it.createElement(Ze,null,BF(y.status),it.createElement(et,{color:LR.DIM}," ",getMcpManagerStatusText(y))),it.createElement(Ze,{marginTop:1},it.createElement(SelectInput,{items:[...e],onSelect:k,indicatorComponent:u_,itemComponent:d_})),d&&it.createElement(Ze,{marginTop:1},d.loading&&it.createElement(et,{color:d.color},it.createElement(bt,{type:"dots"})," "),it.createElement(et,{color:d.color},d.text)))}let b=null;const E=m,T=m+v,P=f.slice(E,T),M=f.length>v;return it.createElement(RO,{title:"Manage MCP servers",hint:0===n.length?"Esc to close":"↑↓ navigate · Enter to select · Esc to close"},it.createElement(et,{color:LR.DIM},n.length," ",1===n.length?"server":"servers"),0===n.length?it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(et,{color:LR.DIM},"No MCP servers configured."),it.createElement(et,{color:LR.DIM},'Use "',getBinaryCommand(),' mcp add" to add a server.'),it.createElement(yL,{url:"https://commandcode.ai/docs/mcp",text:"View MCP Docs ↗",color:LR.CYAN,dimColor:!0})):it.createElement(Ze,{marginTop:1,flexDirection:"column"},P.map((e,t)=>{const n=E+t,r=e.scope!==b;b=e.scope;const o=n===a;return it.createElement(it.Fragment,{key:e.name},r&&it.createElement(Ze,{marginTop:0===t?0:1},it.createElement(et,{bold:!0},getMcpManagerScopeLabel(e.scope)),it.createElement(et,{color:LR.DIM}," ","(",getMcpManagerScopePath(e.scope),")")),it.createElement(Ze,null,it.createElement(et,{color:o?LR.WHITE:void 0,backgroundColor:o?tL:void 0,bold:o},e.name),it.createElement(et,{color:LR.DIM,backgroundColor:o?tL:void 0}," · "),BF(e.status,o?tL:void 0),it.createElement(et,{color:getStatusTextColor(e.status),backgroundColor:o?tL:void 0}," ",getMcpManagerStatusText(e)," ")))})),M&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",E+1,"–",Math.min(T,f.length)," of"," ",f.length,E>0?" · ↑ more":"",T<f.length?" · ↓ more":"")),d&&it.createElement(Ze,{marginTop:1},d.loading&&it.createElement(et,{color:d.color},it.createElement(bt,{type:"dots"})," "),it.createElement(et,{color:d.color},d.text)))},"McpManager");Vt(),PR();var HF=__name(({onClose:e})=>{const[t,n]=ct([]),[r,o]=ct(0),[s,a]=ct(!0),[i,l]=ct(null);ut(()=>{__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(ot((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 it.createElement(RO,{title:"Select memory to edit:"},it.createElement(et,{color:LR.DIM},"Loading memory files..."));if(i)return it.createElement(RO,{title:"Select memory to edit:"},it.createElement(et,{color:LR.RED},ft.cross," ",i));const u=projectMemorySelectorOptions(d);return it.createElement(RO,{title:"Select memory to edit:",hint:"↑/↓ to navigate · enter to edit · esc to cancel"},it.createElement(Ze,{columnGap:4},it.createElement(Ze,{flexDirection:"column"},u.map((e,t)=>it.createElement(Ze,{key:e.label},it.createElement(o_,{isSelected:r===t}),it.createElement(s_,{isSelected:r===t,idleColor:IO}," ",e.label)))),it.createElement(Ze,{flexDirection:"column"},u.map((e,t)=>it.createElement(s_,{key:e.label,isSelected:r===t,idleColor:IO},e.description)))))},"MemorySelector");function linkImageTokens(e,t){if(!t)return e;const n=new RegExp(EM.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)?LR.DIM:LR.RED,s=r?getSpecialUserMessageContent({content:e,billingUrl:cs}):linkImageTokens(e,n);return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{backgroundColor:r?void 0:GR.BG,paddingRight:1},it.createElement(et,{color:r?o:GR.POINTER,bold:!r},ft.pointer),it.createElement(Ze,{marginLeft:1},it.createElement(et,{color:r?o:GR.FG,wrap:"wrap"},s))),t&&!r&&it.createElement(Ze,{marginLeft:2},it.createElement(et,{color:eL},TL),it.createElement(et,{color:LR.DIM}," ","Selected ",t.lines," ",1===t.lines?"line":"lines"," from"," ",t.file," in ",t.ide)))}Vt(),PR(),Vt(),PR(),__name(linkImageTokens,"linkImageTokens"),__name(UserMessage,"UserMessage");var GF=ft.squareSmallFilled;function goalStatusGlyph(e){return"completed"===e?ft.tick:"paused"===e?"⏸":"idle"===e?ft.circle:GF}function goalStatusHeadColor(e){return"completed"===e?LR.GREEN:"paused"===e?LR.YELLOW:LR.DIM}function goalNoticeGlyph(e){return"cleared"===e?ft.tick:"none"===e?ft.circle:"paused"===e?"⏸":GF}function AutoCompactMessage({content:e}){return it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},GF," ",e))}function ZdrPausedMessage(){return it.createElement(Ze,{marginTop:1,marginBottom:1},it.createElement(et,null,it.createElement(et,{color:LR.DIM},GF," "),it.createElement(et,{color:LR.DIM},"Per-task model overrides reverted to ZDR safe defaults. Run"," "),it.createElement(et,{color:QR.CODE},"/config"),it.createElement(et,{color:LR.DIM}," to review · esc to dismiss")))}function ModelNoticeMessage({text:e}){return it.createElement(Ze,{marginTop:1,marginBottom:1},it.createElement(et,null,it.createElement(et,{color:LR.DIM},GF," "),it.createElement(et,{color:LR.DIM},e),it.createElement(et,{color:LR.DIM}," · esc to dismiss")))}function TasteSkipMessage(){return it.createElement(Ze,{marginTop:1,marginBottom:1},it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:DR.BADGE_BG,color:DR.BADGE_FG,bold:!0},xL)),it.createElement(et,{color:LR.DIM}," Skipped. Run "),it.createElement(et,{color:QR.CODE},"/learn-taste"),it.createElement(et,{color:LR.DIM}," or "),it.createElement(et,{color:QR.CODE},"cmd learn-taste"),it.createElement(et,{color:LR.DIM}," anytime."))}function TasteNoticeMessage({notice:e}){const t=e.path?`${tasteDirForRoot({projectRoot:process.cwd()})}/${e.path}`:null;return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:DR.BADGE_BG,color:DR.BADGE_FG,bold:!0},xL)),it.createElement(et,{color:DR.TEXT}," ",e.label)),it.createElement(Ze,{columnGap:1,marginLeft:1},it.createElement(et,{color:eL},TL),it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{wrap:"wrap"},e.text,e.confidence&&it.createElement(et,{color:LR.DIM},` [Confidence ${e.confidence}]`)))),e.path&&t&&it.createElement(Ze,{marginLeft:3},it.createElement(yL,{url:fileUrl(t),text:e.path,color:LR.DIM})))}function SkillLoadedMessage({name:e}){return it.createElement(Ze,null,it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:FR.BG,color:FR.FG,bold:!0},`${ML}SKILL${ML}`)),it.createElement(et,null," ",e),it.createElement(et,{color:LR.DIM}," loaded"))}function HookWarningMessage({content:e}){return it.createElement(Ze,null,it.createElement(et,{color:LR.YELLOW},ft.warning),it.createElement(Ze,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.YELLOW},e)))}function HookLineMessage({content:e}){return it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},` ${e}`))}function HookLineContinuationMessage({content:e}){return it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},` ${e}`))}function HookFrameMessage({lines:e,header:t}){return it.createElement(Ze,{flexDirection:"column"},void 0!==t&&it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},` ${t}`)),e.map((e,t)=>it.createElement(Ze,{key:t,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},e.primary?` └ ${e.text}`:` ${e.text}`))))}function GoalLineMessage({content:e,subline:t}){return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:eL},TL),it.createElement(et,{color:LR.DIM,wrap:"wrap"}," ",e)),t?it.createElement(Ze,{marginLeft:4,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM,wrap:"wrap"},t)):null)}function GoalAcceptMessage({command:e,acceptLine:t,hint:n}){return it.createElement(Ze,{flexDirection:"column"},it.createElement(UserMessage,{content:e}),it.createElement(GoalLineMessage,{content:t,subline:n}))}function GoalCompleteMessage({elapsed:e,turns:t,goal:n}){const r=`${t} ${1===t?"turn":"turns"}`;return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,null,it.createElement(et,{color:LR.GREEN},ft.tick," Goal achieved"),it.createElement(et,{color:LR.DIM},` (${e} · ${r})`))),it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.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 it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:a},s," ",t)),it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM,wrap:"wrap"},n)),r?it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM,wrap:"wrap"},r)):null,o?it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},o)):null)}function BranchResultMessage({title:e}){return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},e?it.createElement(et,null,it.createElement(et,{color:LR.GREEN},"⑂ Forked."),it.createElement(et,null," You're now in "),it.createElement(et,{bold:!0},'"',e,'"')):it.createElement(et,null,it.createElement(et,{color:LR.GREEN},"⑂ Forked."),it.createElement(et,null," You're now in the new session"))),it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},"Original session saved · /resume to switch back")))}function SessionFileMessage({sessionId:e,fileLine:t}){return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},GF," Session ID: "),it.createElement(et,null,e)),it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:eL},TL," "),it.createElement(et,{color:LR.DIM,wrap:"wrap"},t)))}function InfoMessage({content:e,metadata:t}){if(t?.isTasteSkip)return it.createElement(TasteSkipMessage,null);if(t?.tasteNotice)return it.createElement(TasteNoticeMessage,{notice:t.tasteNotice});if(t?.skillLoaded)return it.createElement(SkillLoadedMessage,{name:t.skillLoaded.name});if(t?.isAutoCompact)return it.createElement(AutoCompactMessage,{content:e});if(t?.hookFrame&&t.hookFrame.length>0)return it.createElement(HookFrameMessage,{lines:t.hookFrame,header:t.hookFrameHeader});if(t?.isHookLine)return it.createElement(HookLineMessage,{content:e});if(t?.isHookLineContinuation)return it.createElement(HookLineContinuationMessage,{content:e});if(t?.isHookWarning)return it.createElement(HookWarningMessage,{content:e});if(t?.isSuccess)return it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.GREEN},ft.tick," ",e));if(t?.isGoalAccept)return it.createElement(GoalAcceptMessage,{command:e,acceptLine:t.goalAcceptLine??"",hint:t.goalSubline});if(t?.isGoalComplete)return it.createElement(GoalCompleteMessage,{elapsed:t.goalElapsed??"",turns:t.goalTurns??1,goal:t.goalText??""});if(t?.isGoalStatus)return it.createElement(GoalStatusMessage,{state:t.goalState??"running",headline:t.goalHeadline??"",goal:t.goalText??"",detail:t.goalDetail,hint:t.goalSubline});if(t?.isBranchResult)return it.createElement(BranchResultMessage,{title:t.branchTitle});if(t?.isSessionFile)return it.createElement(SessionFileMessage,{sessionId:t.sessionFileId??"",fileLine:t.sessionFileLine??""});if(t?.isGoalNotice){const n=goalNoticeGlyph(t.goalNoticeKind);return it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},n," ",e))}return t?.isGoalLine?it.createElement(GoalLineMessage,{content:e,subline:t.goalSubline}):it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},GF," ",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"),Vt(),PR(),Vt(),Vt(),Vt(),Vt();var VF=/\[\^[^\]]+\]/;function splitMarkdownBlocks(e){return e?VF.test(e)?[e]:wt.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"),Vt();var zF=String.fromCharCode(8203),KF=new Set(["_","~","*","`"]),qF=/!?\[[^\]]*\]\([^)]*$/,YF=/!?\[[^\]]*$/;function isSpace(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function isOnlyMarkersOrSpace(e){for(const t of e)if(!isSpace(t)&&!KF.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(qF);if(void 0!==t?.index)return e.slice(0,t.index).trimEnd();const n=e.match(YF);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}${zF}`: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 QF=Tt()?"⠶":"#";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 it.createElement(Ze,null,n?it.createElement(Ze,{width:2,flexShrink:0}):it.createElement(et,{color:VR},QF),it.createElement(Ze,{marginLeft:n?0:1,flexGrow:1,flexShrink:1,minWidth:0,flexDirection:"column"},it.createElement(Markdown,{maxPhysicalRows:t?streamingMaxRows(r):void 0},o)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o=LR.GREEN,s=ft.tick,a="default",i=t||"(No output)";n&&(o=LR.YELLOW,s=ft.arrowRight,a=LR.YELLOW,i="Executing…"),r&&(o=LR.RED,s=ft.cross,a=LR.RED);const l=mt(()=>buildTreeConnectors(i),[i]);return it.createElement(Ze,null,it.createElement(et,{color:o},s),it.createElement(Ze,{flexDirection:"column",marginLeft:1},it.createElement(Ze,null,it.createElement(et,{color:LR.GRAY},"$ "),it.createElement(et,{color:o,bold:!0},e)),it.createElement(Ze,{columnGap:1,marginLeft:1},it.createElement(et,{color:eL},l),it.createElement(et,{color:a,wrap:"wrap"},i))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?LR.YELLOW:void 0,o=mt(()=>buildTreeConnectors(e),[e]);return it.createElement(Ze,{flexDirection:"column",marginBottom:0,marginTop:-1},it.createElement(Ze,{columnGap:1},it.createElement(et,{color:eL},o),it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:r},e))),t&&it.createElement(Ze,{marginLeft:3},it.createElement(et,{color:LR.DIM},"See ",t)))}function ErrorMessage({content:e}){return isInterruptedByUserMessage(e)?it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},ft.pointer),it.createElement(Ze,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM,wrap:"wrap"},sS))):it.createElement(Ze,null,it.createElement(et,{color:LR.RED},ft.warning),it.createElement(Ze,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(Markdown,{color:LR.RED},e)))}__name(streamingMaxRows,"streamingMaxRows"),__name(AssistantMessage,"AssistantMessage"),Vt(),__name(BashMessage,"BashMessage"),Vt(),__name(CommandResultMessage,"CommandResultMessage"),Vt(),PR(),__name(ErrorMessage,"ErrorMessage"),Vt(),PR();var JF={connected:{char:ft.tick,color:LR.GREEN},installed:{char:ft.tick,color:LR.GREEN},up_to_date:{char:ft.tick,color:LR.GREEN},needs_reload:{char:ft.circle,color:LR.YELLOW},failed:{char:ft.cross,color:LR.RED},not_in_ide:{char:ft.circle,color:LR.YELLOW}};function IDEStatusMessage({status:e,ide:t,details:n}){const{prefix:r,ide:o,suffix:s}=getIDESetupStatusHeadline(e,t),a=JF[e];return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,null,it.createElement(et,{color:a.color},a.char),it.createElement(et,null," ",r),o&&it.createElement(et,{color:LR.CYAN},o),s&&it.createElement(et,null,s))),n?.map(e=>it.createElement(et,{key:e,color:LR.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:Fe});return it.createElement(Ze,{flexDirection:"column",width:"90%"},it.createElement(Ze,null,it.createElement(et,{color:$R},"✻"," "),it.createElement(et,{color:$R},o.showExpandHint?`${o.headerLabel} `:o.headerLabel),o.showExpandHint&&it.createElement(BracketWrap,{color:LR.DIM},o.expandHint)),o.showBody&&o.hiddenAboveLabel&&it.createElement(Ze,{marginLeft:2},it.createElement(et,{color:LR.DIM},o.hiddenAboveLabel)),o.showBody&&it.createElement(Ze,{marginLeft:2,flexDirection:"column"},it.createElement(et,{color:$R,wrap:"wrap",italic:!0},o.bodyText)))}__name(IDEStatusMessage,"IDEStatusMessage"),Vt(),PR(),__name(reasoningBodyColumns,"reasoningBodyColumns"),__name(ReasoningMessage,"ReasoningMessage"),Vt(),PR(),Vt(),PR();function HelpMessage(){const e=getInvokedCommandName(),t=mt(()=>getVisibleSlashCommands(),[]);return it.createElement(Ze,{flexDirection:"column",paddingY:1},it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(Ze,null,it.createElement(et,{bold:!0},"Command Code"),it.createElement(et,{color:LR.GRAY}," v","1.72.2")),it.createElement(et,{color:LR.GRAY},va)),it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{bold:!0},"Usage"),it.createElement(Ze,{paddingLeft:2},it.createElement(et,null,e," <command> [options]"))),it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{bold:!0},"Options"),it.createElement(Ze,{flexDirection:"column",paddingLeft:2},Pa.map(t=>it.createElement(Ze,{key:t.key},it.createElement(et,null,t.key.replace(/^cmd/,e).padEnd(ka)),it.createElement(et,{color:LR.GRAY},t.description))))),it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{bold:!0},"Commands"),it.createElement(Ze,{flexDirection:"column",paddingLeft:2},xa.map(t=>it.createElement(Ze,{key:t.key},it.createElement(et,null,t.key.replace(/^cmd/,e).padEnd(ka)),it.createElement(et,{color:LR.GRAY},t.description))))),it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{bold:!0},"Slash Commands"),it.createElement(Ze,{flexDirection:"column",paddingLeft:2},t.map(e=>it.createElement(Ze,{key:e.key},it.createElement(et,null,e.key.padEnd(ka)),it.createElement(et,{color:LR.GRAY},e.description))))),it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{bold:!0},"Keyboard Shortcuts"),it.createElement(Ze,{flexDirection:"column",paddingLeft:2},Ta.map(e=>it.createElement(Ze,{key:e.key},it.createElement(et,null,e.key.padEnd(ka)),it.createElement(et,{color:LR.GRAY},e.description))))),it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{bold:!0},"Examples"),it.createElement(Ze,{flexDirection:"column",paddingLeft:2},Aa.map(t=>it.createElement(Ze,{key:t.key},it.createElement(et,null,t.key.replace(/^cmd/,e).padEnd(ka)),it.createElement(et,{color:LR.GRAY},t.description))))),it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.CYAN},ft.pointer),it.createElement(et,{color:LR.GRAY}," ",Ca.replace(/cmd/,e))),it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{bold:!0},"Links"),it.createElement(Ze,{flexDirection:"column",paddingLeft:2},Ia.map(e=>it.createElement(Ze,{key:e.key},it.createElement(et,null,e.key.padEnd(ka)),it.createElement(et,{color:LR.CYAN},e.description))))))}function SystemMessage({content:e}){return isHelpSystemEntryContent(e)?it.createElement(HelpMessage,null):it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{wrap:"wrap"},it.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 it.createElement(UserMessage,{content:e.input,ideHint:t,imageTokenPaths:n})}return"assistant"===e.role?it.createElement(AssistantMessage,{content:e.input,isStreaming:"running"===e.metadata?.status,continuation:!0===e.metadata?.continuation}):"reasoning"===e.role?it.createElement(ReasoningMessage,{content:e.input,expandedOutput:t,expandKey:"ctrl",isStreaming:"running"===e.metadata?.status}):"tool"===e.role?it.createElement(ToolMessage,{name:Dh(e.name||""),input:e.input,output:e.output||"",isPending:Ah(e),hasError:Ih(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?it.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:Ah(e),hasError:Ih(e)}):"system"===e.role?it.createElement(SystemMessage,{content:e.input}):"info"===e.role?it.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?it.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?it.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?it.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 XF=__name(e=>getModelShortName({modelId:e,findModelById:findModelById}),"getModelShortName");function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages [${BE?"ctrl+y":"ctrl+e"} to expand more] `,r=Math.max(0,Math.floor((t-n.length)/2)),o="─".repeat(r);return it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:HR},o),it.createElement(BracketedText,{text:n,color:HR}),it.createElement(et,{color:HR},o))}__name(TranscriptDivider,"TranscriptDivider");var ZF=it.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=mt(()=>cO(d),[d]),m=mt(()=>gO(d),[d]),p=mt(()=>getPackageJson(import.meta.url).version||"0.0.0",[]),g=mt(()=>getGitHeaderInfo(),[]),h=__name(e=>isSandboxMode()?`(base: ${e})`:`(branch: ${e})`,"branchLabel"),f=mt(()=>{if(isSandboxMode())return"cloud sandbox";const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),y=o?XF(o):"sonnet-4.6",S=Boolean(o&&byokProviderId({model:o}))||isSandboxMode()?"":" · taste-1",w=isSandboxMode()?"model":"models",v=mt(()=>{if(!o)return"";if(!modelSupportsReasoningEffort(o))return"";const e=null===s?getReasoningEffort(o):s;return e?` with ${e} effort`:""},[s,o,n]),k=mt(()=>{const e=o?byokProviderId({model:o}):void 0;return e?` · ${e} (byok)`:a&&a!==fo.COMMAND?` · ${getProviderShortName(a)} (byok)`:""},[o,a,n]);return it.createElement(tt,{items:c,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return it.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:d});if("header"===e)return"compact"===m?it.createElement(Ze,{key:"header",marginBottom:1,flexDirection:"row"},it.createElement(Ze,{width:mO,flexShrink:0},it.createElement(nL,null,uO)),it.createElement(Ze,{flexDirection:"column",marginLeft:2},it.createElement(Ze,null,it.createElement(et,{bold:!0},"Command Code"),it.createElement(et,{color:HR}," ","v",p)),it.createElement(et,{color:HR},w,": ",y,v,S,k),it.createElement(et,{color:HR},f,g&&g.isLocal&&g.branch&&` (${g.branch})`))):it.createElement(Ze,{key:"header",marginBottom:1,flexDirection:"column"},it.createElement(nL,null,u.trimEnd()),it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(Ze,null,it.createElement(et,{color:HR},"# "),it.createElement(et,{bold:!0},"Command Code"),it.createElement(et,{color:HR}," v",p)),it.createElement(et,{color:HR},"# ",w,": ",y,v,S,k),it.createElement(Ze,null,it.createElement(et,{color:HR},"# ",f,g&&g.isLocal&&g.branch&&it.createElement(et,{color:HR}," ",h(g.branch))))));const t=e,n=renderFeedEntry(t,r);return it.createElement(Ze,{key:t.id,paddingBottom:1,width:"90%"},n)})});Vt(),PR();var eU=lt(__name(function LiveAgentStatusInner2({entry:e}){const t=Dh(e.name||"Agent"),n=summarizeAgentTaskInput(e.input||""),r=e.metadata?.tokensUsed||0,o=e.metadata?.elapsedSeconds||0,s=e.metadata?.recentTools||[],[a,i]=ct(".");return ut(()=>{const e=setInterval(()=>{i(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),it.createElement(Ze,{flexDirection:"column",marginBottom:1,width:"90%"},it.createElement(Ze,null,it.createElement(et,{backgroundColor:jR.BG,color:jR.FG,bold:!0},` ${t} `),n&&it.createElement(et,null," (",n,")")),it.createElement(Ze,{columnGap:1,marginLeft:1},it.createElement(et,null,"⎿"," "),it.createElement(et,{color:LR.GRAY},"Running (",formatTime3(o)," |"," ",formatTokens(r),")",a)),s.length>0&&it.createElement(Ze,{flexDirection:"column",marginLeft:1},s.map((e,t)=>{const n=Dh(e.name);return it.createElement(Ze,{key:t,columnGap:1},it.createElement(et,{color:LR.GRAY},"⎿"),it.createElement(et,{color:LR.GRAY}," ",n),e.input&&it.createElement(et,{color:LR.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),tU=lt(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:it.createElement(eU,{entry:e})},"LiveAgentStatus"));Vt(),Vt(),PR();var nU=[],rU=nU,oU=!1,sU=null,aU="",iU=new Set,lU=new Set,cU=new Set;function shapeOf(e){return e.map(e=>e.content.replace(/\d+/g,"#")).join("\0")}function emit2(){for(const e of cU)e()}function cancelPeek(){sU&&clearTimeout(sU),sU=null,oU=!1}function armPeek(){sU&&clearTimeout(sU),oU=!0,sU=setTimeout(()=>{sU=null,oU=!1,emit2()},5e3),sU.unref?.()}function projectUserEdits(e){return e.filter(e=>!iU.has(e.content)).map(e=>"completed"!==e.status&&lU.has(e.content)?{...e,status:"completed"}:e)}function setSessionTodos(e){const t=projectUserEdits(e);if(t.length>0&&lU.size>0&&t.every(e=>"completed"===e.status))return void clearSessionTodos();const n=shapeOf(t),r=n!==aU;(r||JSON.stringify(t)!==JSON.stringify(rU))&&(rU=t.length>0?t:nU,aU=n,rU.length>0&&r&&armPeek(),emit2())}function adoptSettled(e){rU=e.length>0?[...e]:nU,aU=shapeOf(rU),cancelPeek(),emit2()}function seedSessionTodos(e){iU.clear(),lU.clear(),adoptSettled(e)}function removeSessionTodoAt(e){const t=rU[e];return t&&iU.add(t.content),adoptSettled(rU.filter((t,n)=>n!==e)),rU}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?jh(r):null;if(o){if(o.every(e=>"completed"===e.status))break;return seedSessionTodos(o),rU}}return clearSessionTodos(),nU}function clearSessionTodos(){(rU!==nU||oU||0!==iU.size||0!==lU.size)&&(rU=nU,aU="",iU.clear(),lU.clear(),cancelPeek(),emit2())}function getSessionTodos(){return rU}function isTodoPanelCollapsed(){return!oU}function completeSessionTodoAt(e){const t=rU[e];return t&&lU.add(t.content),adoptSettled(rU.map((t,n)=>n===e?{...t,status:"completed"}:t)),rU}function completeAllSessionTodos(){const e=rU.map(e=>e.content);for(const t of e)lU.add(t);return adoptSettled(nU),e}function subscribe(e){return cU.add(e),()=>cU.delete(e)}function useSessionTodos(){return ht(subscribe,getSessionTodos)}function useTodoPanelCollapsed(){return ht(subscribe,isTodoPanelCollapsed)}function usePausedLabel(e){const[t,n]=ct(!e);return ut(()=>{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 it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(Ze,null,it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:FR.BG,color:FR.FG,bold:!0},`${ML}TODOS${ML}`)),it.createElement(Ze,{flexShrink:0},it.createElement(et,null," ",it.createElement(BracketWrap,null,s))),a&&it.createElement(Ze,{flexShrink:1,minWidth:0},it.createElement(et,{color:r?LR.DIM:BR.IN_PROGRESS,bold:!r,wrap:"truncate-end"},` ${a}${r?" (paused)":""}`)),it.createElement(Ze,{flexShrink:0},it.createElement(et,null," ",it.createElement(BracketWrap,{color:LR.DIM},n?"ctrl+x to expand":"ctrl+x to manage")))),!n&&it.createElement(CappedChecklist,{todos:t}))}function CappedChecklist({todos:e}){const{foldedDone:t,visible:n,hiddenTail:r}=projectVisibleTodos(e);return it.createElement(Ze,{flexDirection:"column"},t>0&&it.createElement(Ze,{flexDirection:"row"},it.createElement(Ze,{width:2},it.createElement(et,{color:BR.SUCCESS},ft.checkboxOn)),it.createElement(et,{color:BR.SUCCESS,strikethrough:!0},t," completed")),it.createElement(TodoChecklist,{todos:n}),r>0&&it.createElement(et,{color:LR.DIM},` … +${r} more`))}function projectTasteFeedVisibility(e){return e.showTasteLearningInFeed?[...e.feed]:e.feed.filter(e=>void 0===e.metadata?.tasteNotice)}__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"),Vt(),__name(projectTasteFeedVisibility,"projectTasteFeedVisibility"),Vt();var dU=new Set,uU=!1;function isTodosManagerOpen(){return uU}function requestTodosManagerOpen(){for(const e of dU)e()}function statusColor(e){return"completed"===e?LR.GREEN:"in_progress"===e?LR.CYAN:LR.WHITE}function TodoRow({todo:e,selected:t}){const n="completed"===e.status?ft.checkboxOn:ft.checkboxOff,r=t?tL:void 0;return it.createElement(Ze,null,it.createElement(o_,{isSelected:t,backgroundColor:r}),it.createElement(et,{color:statusColor(e.status),backgroundColor:r}," ",n),it.createElement(et,{color:t?MO:statusColor(e.status),strikethrough:"completed"===e.status,backgroundColor:r,wrap:"truncate-end"}," ",e.content),"in_progress"===e.status&&it.createElement(et,{color:LR.DIM,backgroundColor:r}," ","(in progress)"))}function TodosManagerPanel({sessionId:e,onExpandedChange:t}){const n=useSessionTodos(),[r,o]=ct(!1),[s,a]=ct(0);ut(()=>(uU=r,t?.(r),()=>{uU=!1,t?.(!1)}),[r,t]),ut(()=>{const e=__name(()=>{a(0),o(!0)},"listener");return dU.add(e),()=>{dU.delete(e)}},[]),ut(()=>{if(0===n.length)return o(!1),void a(0);a(e=>Math.min(e,n.length-1))},[n.length]);const i=__name(t=>{I$(e)?.applyTodoUserEdit(t)},"syncHarness");if(ot((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 it.createElement(RO,{title:"Todos",subtitle:l>0?`${n.length} items · ${l} done`:`${n.length} items`,gapAfterHeader:!1,boxProps:{marginTop:1,marginBottom:1}},it.createElement(Ze,{flexDirection:"column",marginTop:1},n.map((e,t)=>it.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"),Vt(),PR(),PR();var mU=__name(({currentModel:e,onClose:t,refreshBanner:n,sessionId:r})=>{const o=customReasoningEfforts(e)??getSupportedEfforts(e)??[],s=findModelById(e)?.label??getModelDisplayName(e),a=dt(!1),i=__name(o=>{if(a.current)return;a.current=!0;const s=o!==getReasoningEffort(e);(async()=>{try{if(s){const t=await tellSandboxEffort({effort:o});if(!t.ok)return void dlog(`[Effort] ${t.message}`);await setReasoningEffort({modelId:e,effort:o}),n(),void 0!==o&&r&&I$(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 it.createElement(G_,{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})}Vt(),PR(),Vt(),PR(),__name(store,"store"),__name(getCustomProviderKeyState,"getCustomProviderKeyState"),__name(getConfiguredKeyReference,"getConfiguredKeyReference"),__name(storeCustomProviderKey,"storeCustomProviderKey"),__name(getStoredKeyPreview,"getStoredKeyPreview"),__name(getStoredKeyToken,"getStoredKeyToken"),__name(clearCustomProviderKey,"clearCustomProviderKey"),Vt(),PR(),Vt();var pU={"@ai-sdk/openai":"openai-responses","@ai-sdk/anthropic":"anthropic-messages","@ai-sdk/openai-compatible":"openai-completions"};function modelOverrides(e){if(!isPlainObject8(e))return{};const t=e.provider;if(!isPlainObject8(t))return{};if("string"!=typeof t.npm)return{};const n=pU[t.npm];if(void 0===n)return;const r="string"==typeof t.api&&t.api.startsWith("https://")&&!t.api.includes("${")?t.api.replace(/\/+$/,""):void 0;return{api:n,...void 0!==r?{baseURL:r}:{}}}function cachePath(){return n(H(),".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 ae(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 ee(r(t),{recursive:!0}),await q(t,JSON.stringify({fetchedAt:Date.now(),data:e}))}catch{}}async function fetchCatalog(e){const t=new AbortController,n=setTimeout(()=>t.abort(),6e3);try{const n=await e("https://models.dev/api.json",{headers:{accept:"application/json"},signal:t.signal});if(!n.ok)return null;const r=await n.json();return isPlainObject8(r)?r:null}catch{return null}finally{clearTimeout(n)}}async function loadCatalog(e){const t=await readCache();if(t?.fresh)return t.data;const n=await fetchCatalog(e);return n?(await writeCache(n),n):t?.data??null}function asPositive(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}function urlParts(e){try{const t=new URL(e);return{host:t.hostname.toLowerCase(),path:t.pathname.replace(/\/+$/,"")||"/"}}catch{return}}function recordContains(e,t){if(e===t)return!0;const n="/"===e?"/":`${e}/`;return t.startsWith(n)}function curateModels(e){return isPlainObject8(e)?Object.entries(e).filter(e=>isPlainObject8(e[1])).filter(([,e])=>"deprecated"!==e.status).filter(([,e])=>{const t=isPlainObject8(e.modalities)?e.modalities.output:void 0;return!Array.isArray(t)||t.includes("text")}).sort(([,e],[,t])=>String(t.release_date??"").localeCompare(String(e.release_date??""))).flatMap(([e,t])=>{const n=modelOverrides(t);if(void 0===n)return[];const r=isPlainObject8(t.limit)?t.limit:void 0;return{id:e,...n,..."string"==typeof t.name&&t.name?{name:t.name}:{},...void 0!==asPositive(r?.context)?{contextWindow:asPositive(r?.context)}:{},...void 0!==asPositive(r?.output)?{maxOutput:asPositive(r?.output)}:{}}}):[]}__name(modelOverrides,"modelOverrides"),__name(cachePath,"cachePath"),__name(isPlainObject8,"isPlainObject"),__name(readCache,"readCache"),__name(writeCache,"writeCache"),__name(fetchCatalog,"fetchCatalog"),__name(loadCatalog,"loadCatalog"),__name(asPositive,"asPositive"),__name(urlParts,"urlParts"),__name(recordContains,"recordContains"),__name(curateModels,"curateModels");var gU=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(gU.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"),Vt();var hU=[{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}],fU=[{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"}],yU=/^[a-z0-9._-]+$/;function hostOf2(e){try{return new URL(e).hostname.toLowerCase()}catch{return}}function fallbackProviderSuggestions(){return[...fU,...hU]}async function loadProviderSuggestions(e){let t=[];try{t=await listModelsDevProviders(e?.fetchImpl?{fetchImpl:e.fetchImpl}:void 0)}catch{}const n=t.filter(e=>yU.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"),Vt();var SU=["/chat/completions","/completions","/responses","/messages","/models"];function normalizeEndpointInput(e){let t=e.trim().replace(/\/+$/,"");for(const e of SU)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=LR.DIM}){const t=`${H()}/.commandcode/providers.json`;return it.createElement(yL,{url:`file://${t}`,text:"~/.commandcode/providers.json",color:e})}function toNewProviderModels(e){return e.map(e=>({id:e.id,...e.name?{name:e.name}:{},...void 0!==e.contextWindow?{contextWindow:e.contextWindow}:{},...void 0!==e.maxOutput?{maxOutput:e.maxOutput}:{},...e.api?{api:e.api}:{},...e.baseURL?{baseURL:e.baseURL}:{}}))}function cardKeyLine(e){return"stored"===e.keyState?it.createElement(et,null,"key ",it.createElement(et,{color:LR.GREEN},e.keyPreview)," ",it.createElement(et,{color:LR.GREEN},"✓")," stored in auth.json",e.configuredReference?` · overrides ${e.configuredReference}`:""):"configured"===e.keyState?it.createElement(et,null,"key ",e.configuredReference??"set"):"keyless"===e.keyState?it.createElement(et,null,"no key — the endpoint asks for none"):it.createElement(et,{color:LR.YELLOW},"no key yet, requests fail until one is added")}function cardHints(e){const t=[it.createElement(it.Fragment,null,it.createElement(CO,null,"u")," update models"),it.createElement(it.Fragment,null,it.createElement(CO,null,"d")," delete"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," close")];return"stored"===e?[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," save"),it.createElement(it.Fragment,null,it.createElement(CO,null,"r")," replace key"),it.createElement(it.Fragment,null,it.createElement(CO,null,"c")," clear"),...t]:"missing"===e?[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," add key"),...t]:[it.createElement(it.Fragment,null,it.createElement(CO,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]=ct(""),[m,p]=ct("card"),[g,h]=ct(void 0),[f,y]=ct(!1),[S,w]=ct(void 0),[v,k]=ct(void 0);it.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");ot((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?it.createElement(it.Fragment,null,S.baseURL," · ",S.modelCount," ",1===S.modelCount?"model":"models"," · config:"," ",it.createElement(yL,{url:`file://${H()}/.commandcode/providers.json`,text:"providers.json",color:LR.DIM})):void 0;if("card"===m){const e=cardKeyLine({keyState:n,keyPreview:r,configuredReference:o}),s=cardHints(n);return it.createElement(RO,{title:t,titleSuffix:it.createElement(et,{color:LR.DIM}," (byok)"),subtitle:T,footer:it.createElement(bO,{hints:s,marginTop:0})},it.createElement(Ze,null,e))}return"confirm-remove"===m?it.createElement(RO,{title:`Remove ${t}?`,subtitle:"Its entry, models, and stored key go with it",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"y")," remove"),"any other key keeps it"]})},it.createElement(et,null,"Deletes the entry from ",it.createElement(ProvidersJsonLink,null)," and clears its stored key.")):"removing"===m||"updating-models"===m?it.createElement(RO,{title:t,rule:!1},it.createElement(et,null,"removing"===m?`Removing '${e}'…`:`Refetching models for '${e}'…`)):"removed"===m?it.createElement(RO,{title:`${t} removed`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," close")]})},it.createElement(et,{color:LR.DIM},"Provider deleted from ",it.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?it.createElement(RO,{title:t,subtitle:T,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," back"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," close")]})},it.createElement(et,{color:LR.GREEN},"Models updated — ",v?.count??0," declared from"," ",v?.source??"the refetch",".")):"saved"===m?it.createElement(RO,{title:`Key saved for ${t}`,subtitle:"Stored in ~/.commandcode/auth.json",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," pick a model"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," close")]})}):"cleared"===m?it.createElement(RO,{title:`Stored key cleared for ${t}`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," close")]})},it.createElement(et,{color:LR.DIM},"Its models stay listed",o?" — the providers.json key applies again":"; requests will need a key again")):"error"===m?it.createElement(RO,{title:`Could not update ${t}`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," close")]})},it.createElement(et,{color:LR.DIM},g??'Check that ~/.commandcode is writable, or set "apiKey" to a "$ENV_VAR" reference in providers.json')):it.createElement(RO,{title:`API key for ${t}`,subtitle:`Saved to ~/.commandcode/auth.json under '${e}'. requests go straight to this provider with your key`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," save"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," back")]})},it.createElement(Ze,{borderStyle:"single",borderColor:LR.YELLOW,paddingX:1,width:"100%"},it.createElement(et,{color:LR.DIM},"key: "),it.createElement(Ze,{flexGrow:1},it.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 it.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 it.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 wU=[{value:"openai-completions",label:"OpenAI-compatible",detail:"/chat/completions · Ollama, vLLM, LM Studio, most hosted APIs"},{value:"openai-responses",label:"OpenAI Responses",detail:"/responses · endpoints speaking the OpenAI Responses API"},{value:"anthropic-messages",label:"Anthropic wire",detail:"/v1/messages · endpoints speaking the Claude Messages API"}];function cycleWire(e){const t=wU.findIndex(t=>t.value===e.current),n=wU.length,r=((e.forward?t+1:t-1)+n)%n;return wU[r]?.value??e.current}__name(cycleWire,"cycleWire");var vU=[["{",""],[' "provider": {',""],[' "openrouter": {',"the id you typed"],[' "baseURL": "https://openrouter.ai/api/v1",',"API root, no route"],[' "apiKey": "$OPENROUTER_API_KEY",',"reference — never a raw key"],[' "models": { "openai/gpt-5.6": {} }',"edit anytime, reloads live"],[" }",""],[" }",""],["}",""]];function endpointSubtitle(e){return e.prefilledName?`Prefilled for ${e.prefilledName} — edit it or press enter to accept`:"anthropic-messages"===e.wire?"The Messages API root · /v1 is added on the wire when missing":"openai-responses"===e.wire?"The API root requests go to · /responses is added on the wire":"The API root requests go to · most end in /v1"}function endpointPlaceholder(e){return"anthropic-messages"===e?"https://api.example.com/anthropic":"openai-responses"===e?"https://api.example.com/v1":"http://localhost:11434/v1"}function idStepMatches(e){return"id"!==e.phase?[]:e.query.trim()?matchKnownProviders({query:e.query,providers:e.providers,limit:e.providers.length}):e.providers}function AddCustomProviderEntry({onClose:e,onOpenModels:t,sessionId:n}){const[r,o]=ct(""),[s,a]=ct("openai-completions"),[i,l]=ct(""),[c,d]=ct(""),[u,m]=ct(""),[p,g]=ct("id"),[h,f]=ct(()=>fallbackProviderSuggestions());it.useEffect(()=>{let e=!0;return loadProviderSuggestions().then(t=>{e&&t.length>0&&f(t)}),()=>{e=!1}},[]);const[y,S]=ct(void 0),[w,v]=ct(null),[k,C]=ct(void 0),[b,E]=ct(void 0),T=it.useRef(null),P=it.useRef("api"),M=it.useRef([]),[x,I]=ct(void 0),[A,R]=ct(0),[L,O]=ct(void 0),D=""===c.trim(),$=idStepMatches({phase:p,query:r,providers:h}),N=__name(e=>{M.current.push(p),g(e)},"goTo"),_=__name((e,t)=>{M.current.push(e),g(t)},"arriveFrom"),F=__name(()=>{const t=M.current.pop();C(void 0),E(void 0),t?g(t):e()},"goBack");ot((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=>cycleWire({current:e,forward:!0===o.downArrow})),void(o.return&&N("endpoint"))):"done"===p&&o.return?(e(),void t?.()):void("error"===p&&o.return&&e());(o.upArrow||o.downArrow)&&$.length>0&&v(e=>{const t=$.length-1;if(null===e)return o.downArrow?0:t;const n=e+(o.downArrow?1:-1);return n<0?t:n>t?0:n})}}else g(P.current)});const U=__name(()=>{const e=null===w?void 0:$[w];if(e)return getCustomProviderModelsSync().some(t=>t.id===e.id)?void C(`'${e.id}' already exists — select it in /connect to manage it.`):(C(void 0),o(e.id),S(e),a(e.wire),l(e.baseURL),v(null),void N("api"));const t=r.trim().toLowerCase();if(!t)return;if(!isValidProviderId(t))return void C("Lowercase letters, digits, dots, dashes and underscores only.");if(isReservedProviderId(t))return void C(`'${t}' is a built-in subscription lane — try '${t}-api'.`);if(getCustomProviderModelsSync().some(e=>e.id===t))return void C(`'${t}' already exists — select it in /connect to manage it.`);C(void 0),o(t);const n=findKnownProvider({id:t,providers:h});S(n),n&&(a(n.wire),l(n.baseURL)),N("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),N("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 O("The key could not be stored — check that ~/.commandcode is writable."),void g("error")}g("probing");const t=await T.current??null;t&&t.models.length>0?await G(t.models):await B()},"submitKey"),H=__name(()=>{const e=u.split(",").map(e=>e.trim()).filter(Boolean);0!==e.length&&G(e.map(e=>({id:e})))},"submitManualIds"),G=__name(async e=>{g("saving");try{await addUserProviderEntry({runtime:createNodeRuntime(),id:r,baseURL:i,api:s,keyless:D,models:toNewProviderModels(e)}),R(e.length),await refreshCustomProviderModels(n?{sessionId:n}:void 0),g("done")}catch(e){O(e instanceof Error?e.message:String(e)),g("error")}},"writeEntry"),V=k?it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.RED},k)):null,z=r.trim()?`Add a provider · ${r.trim().toLowerCase()}`:"Add a provider";if("saving"===p||"probing"===p)return it.createElement(RO,{title:z,rule:!1},it.createElement(et,null,"probing"===p?`Asking ${i} which models it serves…`:`Writing '${r}' to ~/.commandcode/providers.json…`));if("done"===p)return it.createElement(RO,{title:`'${r}' is set up`,subtitle:`${A} ${1===A?"model":"models"} declared${D?" · keyless endpoint":" · key stored in auth.json"}`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," pick a model"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," close")]})},it.createElement(et,{color:LR.DIM},"Provider added to ",it.createElement(ProvidersJsonLink,null),". Edit it anytime, it reloads live."));if("error"===p)return it.createElement(RO,{title:`Adding '${r}' didn't finish`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," close")]})},it.createElement(et,{color:LR.DIM},L));if("help"===p)return it.createElement(RO,{title:"Adding a provider: the short version",footer:it.createElement(Ze,{flexDirection:"column"},it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,"docs:"," ",it.createElement(yL,{url:"https://commandcode.ai/docs/byok",text:"commandcode.ai/docs/byok",color:LR.DIM})),"any key to go back"]}))},it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.DIM},"• provider id names the entry in ",it.createElement(ProvidersJsonLink,null)," · models select as id/model"),it.createElement(et,{color:LR.DIM},"• endpoint is the base URL requests go to · most end in /v1"),it.createElement(et,{color:LR.DIM},"• pasted keys go to auth.json · providers.json only ever holds $ENV_VAR or !command references"),it.createElement(et,{color:LR.DIM},"• no key needed? press enter on the empty key field (local servers)"),it.createElement(et,{color:LR.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"),it.createElement(et,{color:LR.DIM},"• the ",it.createElement(ProvidersJsonLink,null)," file is yours · edit it anytime, it reloads live · manage it from /connect"),it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.DIM},"what it writes:"),vU.map(([e,t])=>it.createElement(et,{key:e},it.createElement(et,{color:LR.CYAN}," ",e),t?it.createElement(et,{color:LR.DIM}," ","// ",t):null)))));if("manual-models"===p)return it.createElement(RO,{title:z,subtitle:x?`Couldn't list models automatically — ${x}`:`Which models does ${r} serve?`,footer:it.createElement(bO,{marginTop:0,hints:["comma-separated, exact ids",it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," save"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," back")]})},it.createElement(Ze,{borderStyle:"single",borderColor:LR.YELLOW,paddingX:1,width:"100%"},it.createElement(et,{color:LR.DIM},"models: "),it.createElement(Ze,{flexGrow:1},it.createElement(TextInput,{value:u,onChange:m,onSubmit:H,placeholder:"llama3.3:70b, qwen2.5-coder:32b",showCursor:!0}))));if("key"===p)return it.createElement(RO,{title:z,subtitle:"Keys live in ~/.commandcode/auth.json, never in providers.json",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," save"),"empty enter = keyless (local servers)",it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," back")]})},it.createElement(Ze,{borderStyle:"single",borderColor:LR.YELLOW,paddingX:1,width:"100%"},it.createElement(et,{color:LR.DIM},"key: "),it.createElement(Ze,{flexGrow:1},it.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 it.createElement(RO,{title:z,subtitle:"What does the endpoint speak?",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"↑/↓")," switch"),it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," continue"),it.createElement(it.Fragment,null,it.createElement(CO,null,"h")," help"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," back")]})},it.createElement(Ze,{flexDirection:"column"},wU.map(e=>it.createElement(et,{key:e.value},s===e.value?"❯ ":" ",it.createElement(et,{bold:s===e.value},e.label),it.createElement(et,{color:LR.DIM}," · ",e.detail)))));if("endpoint"===p){const e=y&&i===y.baseURL;return it.createElement(RO,{title:z,subtitle:endpointSubtitle({prefilledName:e?y.name:void 0,wire:s}),footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," continue"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," back")]})},it.createElement(Ze,{borderStyle:"single",borderColor:LR.YELLOW,paddingX:1,width:"100%"},it.createElement(et,{color:LR.DIM},"base URL: "),it.createElement(Ze,{flexGrow:1},it.createElement(TextInput,{value:i,onChange:e=>{l(e),C(void 0),E(void 0)},onSubmit:j,placeholder:endpointPlaceholder(s),showCursor:!0}))),b&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.YELLOW},b)),V)}const K=null===w?0:Math.min(Math.max(0,w-6+1),Math.max(0,$.length-6)),q=$.slice(K,K+6),Y=$.length-(K+q.length);return it.createElement(RO,{title:"Add a provider",subtitle:"Pick a known provider below, or type your own id.",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"↑/↓")," pick from the list"),it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," continue"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," close")]})},it.createElement(Ze,{borderStyle:"single",borderColor:LR.YELLOW,paddingX:1,width:"100%"},it.createElement(et,{color:LR.DIM},"provider id: "),it.createElement(Ze,{flexGrow:1},it.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&&it.createElement(Ze,{flexDirection:"column",marginTop:1},q.map((e,t)=>{const n=null!==w&&K+t===w;return it.createElement(Ze,{key:e.id},it.createElement(o_,{isSelected:n}),it.createElement(s_,{isSelected:n,idleColor:LR.DIM},` ${e.id}`),it.createElement(et,{color:LR.DIM}," ","· ",e.baseURL))}),(K>0||Y>0)&&it.createElement(et,{color:LR.DIM}," ",K>0?`↑ ${K} more · `:"",Y>0?`↓ ${Y} more`:"")))}__name(endpointSubtitle,"endpointSubtitle"),__name(endpointPlaceholder,"endpointPlaceholder"),__name(idStepMatches,"idStepMatches"),__name(AddCustomProviderEntry,"AddCustomProviderEntry"),Vt(),PR();var kU="__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},qM)}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===kU)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 CU=__name(({onSelect:e,onCancel:t,sessionId:n})=>{const[r,o]=it.useState(()=>getCustomProviderModelsSync()),[s,a]=it.useState(()=>getCustomProviderWarningsSync()),[i,l]=it.useState({});it.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]=it.useState({});it.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:kU,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 ot((e,n)=>{n.escape&&t()}),it.createElement(RO,{title:"Connect",subtitle:"Connect to AI providers and see currently connected providers",hint:"↑/↓ navigate · enter select · esc close"},it.createElement(SelectInput,{items:p.map(e=>({label:e.label,value:e.value})),onSelect:f,initialIndex:0,indicatorComponent:o_,itemComponent:({isSelected:e,label:t})=>{const n=h.get(t??"");return it.createElement(Ze,null,it.createElement(s_,{isSelected:e,...n?.notLive?{idleColor:LR.DIM}:{}},` ${(t??"").padEnd(g)}`,n?.status.startsWith("✓")?it.createElement(it.Fragment,null,it.createElement(et,{color:LR.GREEN},"✓"),n.status.slice(1)):n?.status??""))}}),s.length>0&&it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.YELLOW},it.createElement(ProvidersJsonLink,{color:LR.YELLOW})," needs attention —"," ",1===s.length?"one entry":"some entries"," ","did not load as written:"),s.slice(0,3).map(e=>it.createElement(et,{key:e,color:LR.DIM}," ",e)),s.length>3&&it.createElement(et,{color:LR.DIM}," ","… and"," ",s.length-3," more")))},"ProviderSelector");Vt(),PR();var bU=__name(e=>0===e?"No code changes":`${e} file${e>1?"s":""} changed`,"formatFileCountLabel"),EU=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=mt(()=>[...e].sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),[e]),[o,s]=ct(()=>Math.max(0,r.length-1)),[a,i]=ct(()=>Math.max(0,r.length-8)),[l,c]=ct("checkpoint"),[d,u]=ct(null),[m,p]=ct(0),g=mt(()=>hasCodeChangesToRestore({sortedCheckpoints:r,selectedCheckpoint:d}),[d,r]),h=mt(()=>g?Fx:Fx.filter(e=>"conversation"===e.mode),[g]);if(ut(()=>{if(r.length>0){const e=r.length-1;s(e),i(Math.max(0,r.length-8))}},[r.length,8]),ot((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 it.createElement(RO,{title:"Rewind",subtitle:"No checkpoints available. Start a conversation to create checkpoints.",gapAfterHeader:!1,footer:it.createElement(kO,null,"Press ",it.createElement(CO,null,"Esc")," to close")});if("mode"===l&&d)return it.createElement(RO,{title:"Rewind",subtitle:it.createElement(it.Fragment,null,"Restore to:"," ",it.createElement(et,{color:LR.WHITE},truncateString2({text:d.prompt||"checkpoint",maxChars:50}))),footer:it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to confirm ·"," ",it.createElement(CO,null,"Esc")," to go back")},it.createElement(Ze,{flexDirection:"column"},h.map((e,t)=>{const n=m===t,r=t===h.length-1;return it.createElement(Ze,{key:e.mode,flexDirection:"column"},it.createElement(Ze,{flexDirection:"row"},it.createElement(et,{color:n?OR:void 0},n?`${EL} `:" "),it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:n?OR:LR.WHITE},e.label),it.createElement(et,{color:LR.DIM},e.description))),!r&&it.createElement(et,null," "))})));const f=r.slice(a,a+8);return it.createElement(RO,{title:"Rewind",subtitle:"Select a checkpoint to restore your session",gapAfterHeader:!1,footer:it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to select ·"," ",it.createElement(CO,null,"Esc")," to cancel")},r.length>8&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",a+1,"-",Math.min(a+8,r.length)," ","of ",r.length)),it.createElement(Ze,{marginTop:1}),it.createElement(Ze,{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 it.createElement(Ze,{key:e.messageId,flexDirection:"column"},it.createElement(Ze,{flexDirection:"row"},it.createElement(et,{color:s?OR:void 0},s?`${EL} `:" "),it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,{color:s?OR:LR.WHITE},truncateString2({text:e.prompt||"(no prompt)",maxChars:60})),it.createElement(et,{color:LR.DIM}," • "),it.createElement(et,{color:LR.DIM},getRelativeTimeString({timestamp:e.createdAt}),c&&" (latest)")),it.createElement(et,{color:LR.DIM},bU(i)))),!l&&it.createElement(et,null," "))})))},"RewindSelector");Vt(),PR();var TU=["default","no-tools","user-only","labeled-only","all"],PU={default:"","no-tools":"[no-tools]","user-only":"[user]","labeled-only":"[labeled]",all:"[all]"};function nextFilterMode(e){const t=TU.indexOf(e);return TU[(t+1)%TU.length]}function previousFilterMode(e){const t=TU.indexOf(e);return TU[(t-1+TU.length)%TU.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 MU=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:!MU.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:LR.DIM}}return{text:`user: ${normalizeRowText(messageText5(n))}`,color:LR.CYAN}}const r=messageText5(n).trim();return r?{text:`assistant: ${normalizeRowText(r)}`,color:LR.GREEN}:{text:"assistant: (no content)",color:LR.DIM}}return"compaction"===e.type?{text:`[compaction: ${Math.round(e.tokensBefore/1e3)}k tokens]`,color:LR.CYAN}:"branch_summary"===e.type?{text:`[branch summary]: ${normalizeRowText(e.summary)}`,color:LR.YELLOW}:"custom_message"===e.type?{text:`[${e.customType}]: ${normalizeRowText(extractTextFromMessageContent({content:e.content}))}`,color:LR.MAGENTA}:"custom"===e.type?{text:`[custom: ${e.customType}]`,color:LR.DIM}:"model_change"===e.type?{text:`[model: ${e.model}]`,color:LR.DIM}:"effort_change"===e.type?{text:`[effort: ${e.effort}]`,color:LR.DIM}:"label"===e.type?{text:`[label: ${e.label??"(cleared)"}]`,color:LR.DIM}:{text:e.name?`[title: ${e.name}]`:"[title: (empty)]",color:LR.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 xU={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=xU[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 IU=[{value:"none",label:"No summary"},{value:"summarize",label:"Summarize"},{value:"custom",label:"Summarize with custom prompt"}],AU=__name(({tree:e,currentLeafId:t,initialSelectedId:n,initialFilterMode:r,branchSummarySkipPrompt:o,onSelect:s,onAbortSummary:a,onCancel:i,onLabelChange:l})=>{const[c,d]=ct(r),[u,m]=ct(""),[p,g]=ct(()=>new Set),h=__name(e=>{d(e),g(new Set)},"applyFilterMode"),f=__name(e=>{h(t=>t===e?"default":e)},"toggleFilterMode"),[y,S]=ct(!1),[w,v]=ct("browse"),[k,C]=ct(""),[b,E]=ct(""),[T,P]=ct(0),[M,x]=ct(null),[I,A]=ct(0),[R,L]=ct(0),[O,D]=ct(n??t??void 0),$=useTerminalHeight(),N=mt(()=>{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]),_=mt(()=>buildToolCallMap(e),[e]),F=mt(()=>{const e=new Set;let n=t;for(;null!==n;){e.add(n);const t=N.get(n);n=t?t.parentId:null}return e},[N,t]),U=mt(()=>reorderActiveFirst(buildVisibleNodes({nodes:e,mode:c,currentLeafId:t}),t),[e,c,t]),{rows:j,visibleChildrenIds:B}=mt(()=>flattenVisibleTree({roots:U,activePathIds:F,foldedNodes:p}),[U,F,p]),W=mt(()=>new Map(j.map(e=>[e.id,e])),[j]),H=mt(()=>u?j.filter(e=>matchesSearch(searchableText({entry:e.entry,label:e.label,toolCallMap:_}),u)):j,[j,u,_]);ut(()=>{if(0===H.length)return void A(0);let e=O;for(;e;){const t=H.findIndex(t=>t.id===e);if(t>=0)return void A(t);e=N.get(e)?.parentId}A(H.length-1)},[H,c,u,N]);const G=H[I]?.id,V=dt(!1);ut(()=>{V.current?G&&D(G):V.current=!0},[G]);const z=$-1,K=Math.max(6,z-10);ut(()=>{L(e=>clampScrollOffset({cursor:I,total:H.length,maxVisible:K,currentOffset:e}))},[I,H.length,K]);const q=H[I],Y=__name(e=>{D(e.entryId),e.summarize?(v("summarizing"),s(e).then(e=>{e.aborted&&v("browse")})):s(e)},"commitSelection"),Q=__name(()=>{if(!q)return;D(q.id);const{targetId:e}=resolveTargetLocally({byId:N,entryId:q.id});isOnPathLocally({byId:N,ancestorId:t,targetId:e})||o?Y({entryId:q.id,summarize:!1}):(x(q.id),P(0),v("confirm-summary"))},"handleEnterInBrowse");ot((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(IU.length-1,e+1));if(t.return&&M){const e=IU[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)Q();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 J=__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 it.createElement(RO,{title:"/tree",gapAfterHeader:!1},it.createElement(et,{color:LR.CYAN},"Summarizing abandoned branch… (Esc to cancel)"));if("confirm-summary"===w)return it.createElement(RO,{title:"/tree",subtitle:"You're leaving work behind on this branch. Summarize it before jumping?",hint:"enter confirm · esc back"},it.createElement(Ze,{flexDirection:"column"},IU.map((e,t)=>it.createElement(et,{key:e.value,color:t===T?OR:LR.WHITE,bold:t===T},t===T?`${EL} `:" ",e.label))));if("custom-prompt"===w)return it.createElement(RO,{title:"/tree",subtitle:"Focus instructions for the summary:",gapAfterHeader:!1,hint:"enter confirm · esc back"},it.createElement(TextInput,{value:b,focus:!0,prefix:`${EL} `,prefixColor:"cyan",onChange:E,onSubmit:X}));if("label"===w&&q)return it.createElement(RO,{title:"/tree",subtitle:"Label:",gapAfterHeader:!1,hint:"enter save (empty clears) · esc cancel"},it.createElement(TextInput,{value:k,focus:!0,prefix:`${EL} `,prefixColor:"cyan",onChange:C,onSubmit:J}));const Z=H.slice(R,R+K),ee=new Date,te=PU[c];return it.createElement(Ze,{flexDirection:"column",paddingLeft:1,width:"100%"},it.createElement(et,{color:OR,bold:!0},"/tree"),it.createElement(Ze,{marginBottom:1,width:"100%"},it.createElement(kL,{query:u,resultCount:u?H.length:void 0,placeholder:"Type to search…"})),0===H.length?it.createElement(Ze,{marginBottom:1},it.createElement(W$,{message:"No entries found"})):it.createElement(Ze,{flexDirection:"column"},Z.map((e,t)=>{const n=R+t===I,{text:r,color:o}=describeRow(e.entry,_);return it.createElement(et,{key:e.id,backgroundColor:n?tL:void 0,bold:n,wrap:"truncate-end"},n?`${EL} `:" ",it.createElement(et,{color:eL},e.prefix),e.isActivePath?it.createElement(et,{color:OR},"• "):null,void 0!==e.label?it.createElement(et,{color:LR.YELLOW},"[",e.label,"]"," "):null,y&&e.labelTimestamp?it.createElement(et,{color:LR.DIM},formatLabelTimestamp(e.labelTimestamp,ee)," "):null,it.createElement(et,{color:o},r))})),it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"(",0===H.length?0:I+1,"/",H.length,")",te?` ${te}`:"",y?" [+label time]":"")),it.createElement(Ze,{flexDirection:"column"},it.createElement(kO,null,"↑/↓ move · ←/→ page · tab / alt+←/→ branch · shift+L label · shift+T label time"),it.createElement(kO,null,"filters ctrl+d/t/u/l/a · cycle ctrl+o · type to search · rebind via ~/.commandcode/keybindings.json")))},"TreeSelector");Vt(),PR();var RU=[{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."}],LU=['/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"'],OU=__name(({onCancel:e})=>(ot((t,n)=>{n.escape&&e()}),it.createElement(Ze,{flexDirection:"column",paddingLeft:2,paddingRight:2},it.createElement(Ze,{marginBottom:1,flexDirection:"column"},it.createElement(et,{bold:!0,color:OR},"Use"),it.createElement(Ze,{paddingLeft:2,flexDirection:"column"},it.createElement(et,{color:LR.DIM},'/design <mode> "target or request"'),it.createElement(et,{color:LR.DIM},'/design "freeform request" also works. The closest mode is inferred.'))),it.createElement(Ze,{marginBottom:1,flexDirection:"column"},it.createElement(et,{bold:!0,color:OR},"Modes"),it.createElement(Ze,{paddingLeft:2,flexDirection:"column"},yy.map(e=>it.createElement(Ze,{key:e.name,columnGap:2},it.createElement(Ze,{width:18,flexShrink:0},it.createElement(et,{color:LR.CYAN},"/design ",e.name)),it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},e.description)))))),it.createElement(Ze,{marginBottom:1,marginTop:1,flexDirection:"column"},it.createElement(et,{bold:!0,color:OR},"Working rules"),it.createElement(Ze,{paddingLeft:2,flexDirection:"column"},RU.map(e=>it.createElement(Ze,{key:e.label,columnGap:2},it.createElement(Ze,{width:16,flexShrink:0},it.createElement(et,{color:LR.CYAN},e.label)),it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},e.desc)))))),it.createElement(Ze,{marginBottom:1,marginTop:1,flexDirection:"column"},it.createElement(et,{bold:!0,color:OR},"Quick examples:"),it.createElement(Ze,{paddingLeft:2,flexDirection:"column"},LU.map(e=>it.createElement(et,{key:e,color:LR.DIM},e)))),it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Press Esc to close. Type /design help anytime to return.")))),"DesignGuide");Vt(),PR(),Vt(),Vt();var DU=__name(({error:e,traceId:t})=>it.createElement(Ze,{padding:1},it.createElement(B$,{title:"Error initializing onboarding:"},e,t&&it.createElement(et,{color:LR.DIM},"\n\n","Trace ID: ",t),"\n\n","Continuing without onboarding...")),"OnboardingError");Vt(),Vt();var $U=__name(()=>it.createElement(et,null,"Skip"),"SkipOptionText"),NU=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[o,s]=ct(1);return ot((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())}),it.createElement(Ze,{flexDirection:"column",borderStyle:"single",borderColor:DR.TEXT,paddingX:1,paddingY:0},it.createElement(et,{color:DR.TEXT,bold:!0},"Build Your Coding Taste"),it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(et,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),it.createElement(Ze,{marginTop:1},it.createElement(et,null,"Analyze"," ",1===e?"that session":"those sessions"," ","to build your coding taste package?"))),it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,{color:1===o?DR.TEXT:LR.GRAY},1===o?ft.pointer:" "," 1. Yes, learn (recommended)")),it.createElement(Ze,null,it.createElement(et,{color:2===o?DR.TEXT:LR.GRAY},2===o?ft.pointer:" "," 2."," ",it.createElement($U,null)))),it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"↑↓ · "),it.createElement(et,{color:QR.CODE},"enter"),it.createElement(et,{color:LR.DIM}," ok · "),it.createElement(et,{color:QR.CODE},"esc"),it.createElement(et,{color:LR.DIM}," skip · "),it.createElement(et,{color:QR.CODE},"n"),it.createElement(et,{color:LR.DIM}," never")))},"ImportChoice"),_U=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onSkip:a})=>"asking"===e?t&&"has_sessions"===t.reason?it.createElement(NU,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:a}):null:"learning"===e?it.createElement(cN,{onComplete:r,onCancel:a,onError:o,onErrorDismiss:s}):null,"OnboardingStepRenderer"),FU=__name(({onComplete:e,autoLearn:t=!1})=>{ut(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,traceId:o,isLoading:s}=Y$({autoLearn:t,onShouldSkip:e}),{step:a,setStep:i}=Q$({conditions:n,autoLearn:t}),{handleImportStart:l,handleImportComplete:c,handleImportError:d,handleErrorDismiss:u,handleSkip:m}=J$({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?it.createElement(DU,{error:r,traceId:o}):"done"===a||"asking"!==a&&"learning"!==a?null:it.createElement(_U,{step:a,conditions:n,onImportStart:l,onImportComplete:c,onImportError:d,onErrorDismiss:u,onSkip:m})},"TasteOnboarding");Vt(),PR();var UU=[{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 jU=__name(({onSelect:e,onCancel:t})=>{const[n]=ct(()=>getCliTheme()),[r]=ct(()=>resolveCliTheme("auto")),o=mt(()=>UU.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");ot((e,n)=>{n.escape&&t()});const a=o.findIndex(e=>e.value===n),i=o.find(e=>e.value===n)?.label??`${n} theme`;return it.createElement(RO,{title:"Select a theme",subtitle:`Choose the color palette for this terminal · currently ${i}`,footer:it.createElement(et,{italic:!0,color:LR.DIM},"Press ",it.createElement(et,{bold:!0},"Esc")," to cancel")},it.createElement(SelectInput,{items:o,onSelect:s,initialIndex:a>=0?a:0,indicatorComponent:o_,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 it.createElement(Ze,{flexDirection:"column",marginBottom:i?0:1},it.createElement(Ze,null,it.createElement(s_,{isSelected:e,isActive:a,idleColor:LR.DIM},` ${r+1}. ${s?.label??t}`),a&&it.createElement(i_,null)),it.createElement(l_,null,s?.description??""))}}))},"ThemeSelector");function remoteLockPath(){return n(H(),".commandcode","remote-host.json")}Vt(),Vt(),__name(remoteLockPath,"remoteLockPath");var BU=__name(e=>"object"==typeof e&&null!==e,"isRecord"),WU=__name(e=>"string"==typeof e&&""!==e?e:void 0,"asString"),HU=__name(e=>BU(e)&&"EEXIST"===e.code,"isAlreadyExists");function parseLock(e){let t;try{t=JSON.parse(e)}catch{return}if(!BU(t))return;const n=t.pid,r=WU(t.cwd),o=WU(t.sessionId);return"number"==typeof n&&Number.isInteger(n)&&!(n<=0)&&r&&o?{pid:n,cwd:r,sessionId:o,startedAt:WU(t.startedAt)??"unknown",label:WU(t.label)}:void 0}__name(parseLock,"parseLock");var GU=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive");async function readLock(e){try{return parseLock(await ae(e,"utf8"))}catch{return}}async function readRemoteLock(e=remoteLockPath()){const t=await readLock(e);if(t&&GU(t.pid))return t}async function acquireRemoteLock(e,t=remoteLockPath()){await ee(r(t),{recursive:!0});const n=JSON.stringify(e,null,2);for(let r=0;r<3;r+=1){try{return await q(t,n,{flag:"wx",mode:384}),{ok:!0}}catch(e){if(!HU(e))throw e}const r=await readLock(t);if(r&&r.pid!==e.pid&&GU(r.pid))return{ok:!1,holder:r};await Z(t,{force:!0}).catch(()=>{})}return{ok:!1,holder:await readLock(t)}}async function takeoverRemoteLock(e,t=remoteLockPath()){await ee(r(t),{recursive:!0}),await q(t,JSON.stringify(e,null,2),{mode:384})}function watchRemoteLock(e){const t=e.path??remoteLockPath(),n=c(t);let o,s,a=!1;const i=__name(()=>{a=!0,o?.close(),s&&clearInterval(s)},"finish"),l=__name(()=>{if(a)return;let n;try{n=parseLock(R(t,"utf8"))}catch{n=void 0}n?.pid!==e.pid&&(i(),e.onLost())},"check");try{o=U(r(t),(e,t)=>{null!==t&&t!==n||l()})}catch{}return s=setInterval(l,e.pollMs??2e3),s.unref?.(),i}async function releaseRemoteLock(e=process.pid,t=remoteLockPath()){const n=await readLock(t);n&&n.pid!==e||await Z(t,{force:!0}).catch(()=>{})}function releaseRemoteLockSync(e=process.pid,t=remoteLockPath()){try{const n=parseLock(R(t,"utf8"));if(n&&n.pid!==e)return;_(t)}catch{}}__name(readLock,"readLock"),__name(readRemoteLock,"readRemoteLock"),__name(acquireRemoteLock,"acquireRemoteLock"),__name(takeoverRemoteLock,"takeoverRemoteLock"),__name(watchRemoteLock,"watchRemoteLock"),__name(releaseRemoteLock,"releaseRemoteLock"),__name(releaseRemoteLockSync,"releaseRemoteLockSync"),Vt();var VU=["telegram","discord"],zU={telegram:{token:"CMD_TELEGRAM_BOT_TOKEN",user:"CMD_TELEGRAM_USER",channel:"CMD_TELEGRAM_CHANNEL"},discord:{token:"CMD_DISCORD_BOT_TOKEN",user:"CMD_DISCORD_USER",channel:"CMD_DISCORD_CHANNEL"}};function remoteConfigPath(){return n(H(),".commandcode","auth.json")}__name(remoteConfigPath,"remoteConfigPath");var KU=__name(e=>"object"==typeof e&&null!==e,"isRecord"),qU=__name(e=>"string"==typeof e&&""!==e?e:void 0,"asString");async function readAuthDocument(e){let t;try{t=await ae(e,"utf8")}catch{return{ok:!0,data:{}}}try{const e=JSON.parse(t);return KU(e)?{ok:!0,data:e}:{ok:!1}}catch{return{ok:!1}}}__name(readAuthDocument,"readAuthDocument");var YU="remoteControl",QU=["rc"],JU=__name((e,t)=>{const n=[YU,...QU].map(t=>KU(e[t])?e[t]:void 0).map(e=>KU(e?.[t])?e[t]:void 0).find(e=>void 0!==e),r=KU(e[t])?e[t]:void 0,o=n??r??{};return{token:qU(o.token),allowedUserId:qU(o.allowedUserId),channelId:qU(o.channelId)}},"providerOf"),XU=__name(e=>[...QU,...VU].filter(t=>t in e),"staleKeys"),ZU=__name(e=>Boolean(e.token)||Boolean(e.allowedUserId)||Boolean(e.channelId),"isConfigured");async function loadRemoteConfig(e=remoteConfigPath()){const t=await readAuthDocument(e);if(!t.ok)return{};const n={};for(const e of VU){const r=JU(t.data,e);ZU(r)&&(n[e]=r)}return n}async function updateRemoteProviderConfig(e,t,n=remoteConfigPath()){const r=await readAuthDocument(n);if(!r.ok)throw new Error(`${n} is not valid JSON, so it will not be overwritten. Fix or remove the file, then try again.`);const o=await loadRemoteConfig(n),s=o[e];await writeAuthDocument(n,r.data,{...o,[e]:{token:t.token??s?.token,allowedUserId:t.allowedUserId??s?.allowedUserId,channelId:t.channelId??s?.channelId}})}async function migrateRemoteConfig(e=remoteConfigPath()){const t=await readAuthDocument(e);return!(!t.ok||0===XU(t.data).length||(await writeAuthDocument(e,t.data,await loadRemoteConfig(e)),0))}async function writeAuthDocument(e,t,n){const o=n??{},s=KU(t[YU])?t[YU]:{},a={...t,[YU]:{...s,...o}};for(const e of XU(a))delete a[e];const i=JSON.stringify(a,null,2);await ee(r(e),{recursive:!0});const l=`${e}.tmp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;await q(l,i,{mode:384});try{await re(l,e)}catch(e){throw await Z(l).catch(()=>{}),e}}function resolveRemoteSettings(e,t=process.env,n="telegram"){const r=zU[n],o=e[n];return{token:qU(t[r.token])??o?.token,allowedUserId:qU(t[r.user])??o?.allowedUserId,channelId:qU(t[r.channel])??o?.channelId}}function resolveDefaultProvider(e){if(e.active)return e.active;const t=e.env??process.env,n=VU.filter(n=>void 0!==resolveRemoteSettings(e.config,t,n).token);return 1===n.length?n[0]??"telegram":"telegram"}__name(loadRemoteConfig,"loadRemoteConfig"),__name(updateRemoteProviderConfig,"updateRemoteProviderConfig"),__name(migrateRemoteConfig,"migrateRemoteConfig"),__name(writeAuthDocument,"writeAuthDocument"),__name(resolveRemoteSettings,"resolveRemoteSettings"),__name(resolveDefaultProvider,"resolveDefaultProvider"),Vt();var ej={setTimeout(e,t){const n=setTimeout(e,t);return n.unref?.(),n},clearTimeout(e){clearTimeout(e)},now:__name(()=>Date.now(),"now"),random:__name(()=>Math.random(),"random")};Vt();var tj=__name(e=>e.split("@",1)[0]??e,"stripBotSuffix");function parseRemoteCommand(e){const t=e.trim();if(!t.startsWith("/"))return;const[n="",...r]=t.split(/\s+/),o=tj(n.slice(1)).toLowerCase(),s=r.join(" ").trim();return""!==o?"stop"===o?{kind:"stop"}:"help"===o||"start"===o?{kind:"help"}:"status"===o?{kind:"status"}:{kind:"slash",name:o,argument:s}:void 0}__name(parseRemoteCommand,"parseRemoteCommand");function encodePermissionCallback(e){return`p:${e.id}:${e.allow?"a":"d"}`}function parsePermissionCallback(e){if(!e.startsWith("p:"))return;const[t,n]=e.slice(2).split(":"),r=Number(t);return!Number.isInteger(r)||r<0||"a"!==n&&"d"!==n?void 0:{id:r,allow:"a"===n}}__name(encodePermissionCallback,"encodePermissionCallback"),__name(parsePermissionCallback,"parsePermissionCallback");function encodeQuestionCallback(e){return`q:${e.id}:${e.questionIndex}:${e.optionIndex}`}function parseQuestionCallback(e){if(!e.startsWith("q:"))return;const t=e.slice(2).split(":");if(3!==t.length)return;const[n,r,o]=t.map(Number),s=__name(e=>void 0!==e&&Number.isInteger(e)&&e>=0,"valid");return s(n)&&s(r)&&s(o)?{id:n,questionIndex:r,optionIndex:o}:void 0}__name(encodeQuestionCallback,"encodeQuestionCallback"),__name(parseQuestionCallback,"parseQuestionCallback");function encodeValueCallback(e){return`v:${e.command}:${e.value}`}function parseValueCallback(e){if(!e.startsWith("v:"))return;const t=e.slice(2),n=t.indexOf(":");if(n<=0)return;const r=t.slice(0,n),o=t.slice(n+1).trim();return""===o?void 0:{command:r,value:o}}__name(encodeValueCallback,"encodeValueCallback"),__name(parseValueCallback,"parseValueCallback"),Vt();var nj,rj=new Set,oj=new Set,sj=new Set,aj=new Set;function subscribeRemoteMessage(e){return rj.add(e),()=>{rj.delete(e)}}function subscribeRemoteChoice(e){return oj.add(e),()=>{oj.delete(e)}}function emitRemoteChoice(e){for(const t of oj)t(e)}function emitRemoteMessage(e){for(const t of rj)t(e)}function subscribeLocalPrompt(e){return sj.add(e),()=>{sj.delete(e)}}function emitLocalPrompt(e){for(const t of sj)t(e)}function subscribeRemoteStopped(e){return aj.add(e),()=>{aj.delete(e)}}function emitRemoteStopped(){for(const e of aj)e()}function getActiveRemote(){return nj}function setActiveRemote(e){nj&&(nj.bridge.stop(),emitRemoteStopped()),nj=e}function clearActiveRemote(){nj?.bridge.stop(),nj=void 0,emitRemoteStopped()}__name(subscribeRemoteMessage,"subscribeRemoteMessage"),__name(subscribeRemoteChoice,"subscribeRemoteChoice"),__name(emitRemoteChoice,"emitRemoteChoice"),__name(emitRemoteMessage,"emitRemoteMessage"),__name(subscribeLocalPrompt,"subscribeLocalPrompt"),__name(emitLocalPrompt,"emitLocalPrompt"),__name(subscribeRemoteStopped,"subscribeRemoteStopped"),__name(emitRemoteStopped,"emitRemoteStopped"),__name(getActiveRemote,"getActiveRemote"),__name(setActiveRemote,"setActiveRemote"),__name(clearActiveRemote,"clearActiveRemote");var ij=__name(e=>new Promise(t=>{const n=setTimeout(t,e);n.unref?.()}),"graceElapsed");async function shutdownActiveRemote(){const e=nj;e&&(nj=void 0,e.bridge.stop(),emitRemoteStopped(),await Promise.race([e.bridge.announce(e.farewell),ij(1500)]))}__name(shutdownActiveRemote,"shutdownActiveRemote"),Vt();var lj=__name(e=>e instanceof Error?e.message:String(e),"errorMessage");Vt();var cj="```";function openingFence(e,t){if(e.startsWith(cj))return t?void 0:e.trimEnd()}function splitLongLine(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function splitForChat(e,t){if(e.length<=t)return[e];const n=[];let r,o,s=[],a=0;const i=__name(()=>{if(0===s.length)return;const e=r?[cj]:[];n.push([...s,...e].join("\n")),o=r,s=[],a=0},"flush"),l=__name(()=>{void 0!==o&&(s=[o],a=o.length+1,o=void 0)},"startChunk");for(const n of e.split("\n")){const e=t-(r?4:0);for(const t of n.length>e?splitLongLine(n,e):[n]){s.length>0&&a+t.length+1>e&&(i(),l()),s.push(t),a+=t.length+1;const n=openingFence(t,void 0!==r);n?r=n:t.startsWith(cj)&&(r=void 0)}}return i(),n.filter(e=>""!==e)}__name(openingFence,"openingFence"),__name(splitLongLine,"splitLongLine"),__name(splitForChat,"splitForChat"),Vt();var dj=__name(e=>"object"==typeof e&&null!==e,"isRecord"),uj=__name(e=>"string"==typeof e?e:void 0,"asString"),mj="Thinking";function renderBlock(e){const t=e.suffix?`${e.header} · ${e.suffix}`:e.header,n=e.lines??[];if(0===n.length)return t;const r=n.slice(0,3),o=n.length-r.length,s=r.map(e=>`│ ${e}`);if(o>0)return[t,...s,`└ +${o} more lines`].join("\n");const a=s.pop();return[t,...s,`└${a?.slice(1)??""}`].join("\n")}function createReplyStream(e,t={}){let n=e;const r=t.clock??ej;let o="",s=!0,a=!1,i=mj;const l=r.now();let c,d=0;const u=[],m=new Map;function renderStatus(e){const n=Math.floor((r.now()-l)/1e3),o=n<60?`${n}s`:`${Math.floor(n/60)}m ${n%60}s`,s=[n>=1?`${e}… ${o}`:`${e}…`,...d>0?[`↓ ${d}`]:[]].join(" · ");return t.formatStatus?.(s)??`✻ ${s}`}function scheduleTick(){void 0!==c&&r.clearTimeout(c),c=r.setTimeout(()=>{s&&void 0!==i&&(n.update(compose(o)),scheduleTick())},1e4)}function stopTick(){void 0!==c&&(r.clearTimeout(c),c=void 0)}function toolLog(){if(0===u.length)return"";const e=Math.max(0,u.length-40);return`\`\`\`\n${[...e>0?[`… ${e} earlier call(s)`]:[],...e>0?u.slice(-40):u].join("\n")}\n\`\`\`\n\n`}function compose(e){const t=void 0===i?[]:[renderStatus(i)];return[toolLog().trimEnd(),e,...t].filter(e=>""!==e).join("\n\n")}function setStatus(e){i=e,void 0===e?stopTick():scheduleTick(),n.update(compose(o))}function pushBlock(e){u.push(renderBlock(e)),n.update(compose(o))}function abandon(){s=!1,i=void 0,stopTick(),n.cancel()}function retarget(e){s&&(n=e,n.update(compose(o)),void 0!==i&&scheduleTick())}function close(e){s=!1,i=void 0,stopTick(),n.finish(compose(e))}function onEvent(e){if(s)if(a=!0,"run_start"!==e.type){if("model_request_end"===e.type){const t=dj(e.usage)?e.usage:void 0,n=t?.outputTokens;return void("number"==typeof n&&(d+=n))}if("thinking_start"!==e.type)if("message_start"!==e.type){if("text_delta"===e.type)return o+=uj(e.delta)??"",i=void 0,void n.update(compose(o));if("tool_queued"===e.type){const n=uj(e.toolName),r=uj(e.toolCallId);if(!n||!r||!t.summarizeCall)return;return void m.set(r,t.summarizeCall({toolName:n,input:dj(e.input)?e.input:{}}))}if("tool_running"===e.type){const n=uj(e.toolName);return void setStatus(uj(e.description)??(n?t.describeTool?.(n)??n:void 0)??"Working")}if("tool_completed"!==e.type&&"tool_errored"!==e.type||(i=""===o?mj:void 0),"tool_completed"===e.type){const n=uj(e.toolCallId),r=uj(e.toolName),o=n?m.get(n):void 0;if(n&&m.delete(n),!o||!r)return;const s=t.summarizeResult?.({toolName:r,result:e.result});return void pushBlock({header:o.header,suffix:s?.suffix??o.suffix,lines:s?.lines})}if("tool_errored"===e.type){const t=uj(e.toolCallId),n=t?m.get(t):void 0;if(t&&m.delete(t),!n)return;return void pushBlock({header:n.header,lines:[uj(e.error)??"failed"]})}if("run_end"===e.type){const t=dj(e.result)?e.result:{};return void close(uj(t.finalText)||o)}if("interrupted"!==e.type){if("run_error"===e.type){const t=dj(e.error)?e.error:{};close(`Run failed: ${uj(t.message)??"unknown error"}`)}}else close(`${o}\n\n⏹ Interrupted.`.trim())}else o="";else setStatus(mj)}else setStatus(mj)}return __name(renderStatus,"renderStatus"),__name(scheduleTick,"scheduleTick"),__name(stopTick,"stopTick"),__name(toolLog,"toolLog"),__name(compose,"compose"),__name(setStatus,"setStatus"),__name(pushBlock,"pushBlock"),__name(abandon,"abandon"),__name(retarget,"retarget"),__name(close,"close"),__name(onEvent,"onEvent"),n.update(compose(o)),scheduleTick(),{onEvent:onEvent,isOpen:__name(()=>s,"isOpen"),hasEvents:__name(()=>a,"hasEvents"),abandon:abandon,retarget:retarget}}function fenceFor2(e){const t=[...e.matchAll(/`+/g)].reduce((e,t)=>Math.max(e,t[0].length),0);return"`".repeat(Math.max(3,t+1))}function getRemoteMessageLabel(e){const[t=""]=e.text.split("\n",1);return t.length>60?`${t.slice(0,59)}…`:t}__name(renderBlock,"renderBlock"),__name(createReplyStream,"createReplyStream"),Vt(),__name(fenceFor2,"fenceFor"),__name(getRemoteMessageLabel,"getRemoteMessageLabel");var pj=__name(e=>e.userName??`user ${e.userId}`,"senderOf"),gj=__name((e,t)=>`Remote message from ${e} (${t}). Carry out the request below.`,"instructionsFor");function buildRemoteSubmission(e){const t=e.platform??"Telegram",n=pj(e),r=fenceFor2(e.text);return{role:"user",input:[gj(t,n),"",r,e.text,r].join("\n"),displayMessage:`${t} (${n}): ${getRemoteMessageLabel(e)}`,isAutomated:!0,isMeta:!0,isRelayed:!0}}__name(buildRemoteSubmission,"buildRemoteSubmission"),Vt(),Vt();var hj="input",fj=__name(e=>"string"==typeof e?e:void 0,"asString"),yj=__name(e=>"object"==typeof e&&null!==e,"isRecord"),Sj=__name(e=>"string"==typeof e?e:"number"==typeof e?String(e):void 0,"asId");function toApiError2(e,t,n){const r=yj(n)&&"string"==typeof n.message?n.message:`HTTP ${t}`,o=yj(n)&&"number"==typeof n.retry_after?Math.ceil(1e3*n.retry_after):void 0;return Object.assign(new Error(`Discord ${e} failed: ${r}`),{retryable:429===t||t>=500,retryAfterMs:o})}__name(toApiError2,"toApiError");var wj=__name(e=>e.length<=5&&e.every(e=>e.length<=5),"fitsButtonGrid"),vj=__name(e=>({type:1,components:e.map(e=>({type:2,style:2,label:e.text.slice(0,80),custom_id:e.data.slice(0,100)}))}),"buttonRow");function selectRows(e){const t=[];for(let n=0;n<e.length&&t.length<5;n+=25){const r=e.slice(n,n+25),o=e.length>25;t.push({type:1,components:[{type:3,custom_id:`select-${String(t.length)}`,placeholder:o?`Choose one (${String(n+1)}–${String(n+r.length)})`:"Choose one",options:r.map(e=>({label:e.text.slice(0,100),value:e.data.slice(0,100)}))}]})}return t}__name(selectRows,"selectRows");var kj=__name(e=>e&&0!==e.length?{components:wj(e)?e.map(vj):selectRows(e.flat())}:{},"componentsBody");function createDiscordClient(e){const t=e.fetchFn??fetch,n=e.sleep??(e=>new Promise(t=>setTimeout(t,e)));async function call(r,o,s){let a;for(let i=0;i<3;i+=1){const l=await t(`https://discord.com/api/v10${o}`,{method:r,headers:{authorization:`Bot ${e.token}`,"content-type":"application/json"},...void 0===s?{}:{body:JSON.stringify(s)}});if(204===l.status)return;const c=await l.json().catch(()=>({}));if(l.ok)return c;const d=toApiError2(o,l.status,c);if(!d.retryable)throw d;a=d,await n(d.retryAfterMs??500*2**i)}throw a}__name(call,"call");const r=__name((e,t)=>{const n=yj(e)?Sj(e.id):void 0;if(!n)throw new Error(`Discord ${t}: malformed response`);return n},"messageIdOf");return{async createThread({channelId:e,name:t}){const n=await call("POST",`/channels/${e}/threads`,{name:t.slice(0,100),type:11,auto_archive_duration:1440});return r(n,"createThread")},async renameThread({channelId:e,name:t}){await call("PATCH",`/channels/${e}`,{name:t.slice(0,100)})},async sendMessage({channelId:e,text:t,buttons:n}){const o=await call("POST",`/channels/${e}/messages`,{content:t,...kj(n)});return r(o,"sendMessage")},async editMessage({channelId:e,messageId:t,text:n}){await call("PATCH",`/channels/${e}/messages/${t}`,{content:n})},async deleteMessage({channelId:e,messageId:t}){await call("DELETE",`/channels/${e}/messages/${t}`)},async replyToInteraction({interactionId:e,token:t,text:n}){await call("POST",`/interactions/${e}/${t}/callback`,{type:4,data:{content:n,flags:64}})},async guildOfChannel(e){const t=await call("GET",`/channels/${e}`),n=yj(t)?Sj(t.guild_id):void 0;if(!n)throw new Error("Discord guildOfChannel: not a server channel");return n},async publishCommands({applicationId:e,guildId:t,commands:n}){await call("PUT",`/applications/${e}/guilds/${t}/commands`,n.map(e=>({type:1,name:e.name,description:e.description.slice(0,100),...e.argument?{options:[{type:3,name:hj,description:e.argument.slice(0,100),required:!1}]}:{}})))},async ackInteraction({interactionId:e,token:t}){await call("POST",`/interactions/${e}/${t}/callback`,{type:6})}}}function parseDiscordMessage(e){if(!yj(e))return;const t=yj(e.author)?e.author:void 0,n=Sj(e.id),r=Sj(e.channel_id),o=Sj(t?.id);return n&&r&&o?{messageId:n,channelId:r,userId:o,userName:"string"==typeof t?.username?t.username:void 0,text:"string"==typeof e.content?e.content:"",fromBot:!0===t?.bot}:void 0}function parseDiscordInteraction(e){if(!yj(e)||3!==e.type)return;const t=yj(e.data)?e.data:void 0,n=yj(e.message)?e.message:void 0,r=Sj(e.id),o=interactionChannelId(e),s=interactionUserId(e),a=Array.isArray(t?.values)?fj(t.values[0]):void 0;if(!r||!o||!s)return;if("string"!=typeof e.token)return;const i=a??fj(t?.custom_id);return void 0!==i?{interactionId:r,token:e.token,channelId:o,messageId:Sj(n?.id),userId:s,data:i}:void 0}function interactionChannelId(e){const t=yj(e.channel)?e.channel:void 0;return Sj(e.channel_id)??Sj(t?.id)}function interactionUserId(e){const t=yj(e.member)?e.member:void 0,n=yj(e.user)?e.user:yj(t?.user)?t.user:void 0;return Sj(n?.id)}function parseDiscordCommand(e){if(!yj(e)||2!==e.type)return;const t=yj(e.data)?e.data:void 0,n=Sj(e.id),r=interactionChannelId(e),o=interactionUserId(e);if(!n||!r||!o)return;if("string"!=typeof e.token)return;if("string"!=typeof t?.name)return;const s=(Array.isArray(t.options)?t.options:[]).find(e=>yj(e)&&e.name===hj);return{interactionId:n,token:e.token,channelId:r,userId:o,name:t.name,value:"string"==typeof s?.value?s.value:""}}function createDiscordReply(e){const{client:t,channelId:n}=e,r=e.prefix??"",o=e.clock??ej,s=e.onLog??(()=>{}),a=[],i=[];let l,c="",d="",u=Number.NEGATIVE_INFINITY,m=!1,p=Promise.resolve();const g=__name(e=>""===r?e:`${r}\n\n${e}`,"label");async function deliver(r){const o=splitForChat(g(r),2e3);for(const[r,s]of o.entries()){if(i[r]===s)continue;const o=a[r];if(void 0===o){const o=await t.sendMessage({channelId:n,text:s});a[r]=o,e.onSent?.(o)}else await t.editMessage({channelId:n,messageId:o,text:s});i[r]=s}}function enqueueSend(e){const t=d;d=e,u=o.now(),p=p.then(()=>deliver(e)).catch(e=>{d=t,s(`reply failed: ${lj(e)}`)})}function flushLater(){if(void 0!==l)return;const e=Math.max(0,1e3-(o.now()-u));l=o.setTimeout(()=>{l=void 0,c!==d&&enqueueSend(c)},e)}return __name(deliver,"deliver"),__name(enqueueSend,"enqueueSend"),__name(flushLater,"flushLater"),{cancel(){m=!0,void 0!==l&&(o.clearTimeout(l),l=void 0)},update(e){m||(c=e,e!==d&&(o.now()-u>=1e3?enqueueSend(e):flushLater()))},async finish(e){m||(c=""===e?"(no text reply)":e,void 0!==l&&(o.clearTimeout(l),l=void 0),await p,c!==d&&enqueueSend(c),await p)}}}__name(createDiscordClient,"createDiscordClient"),__name(parseDiscordMessage,"parseDiscordMessage"),__name(parseDiscordInteraction,"parseDiscordInteraction"),__name(interactionChannelId,"interactionChannelId"),__name(interactionUserId,"interactionUserId"),__name(parseDiscordCommand,"parseDiscordCommand"),Vt(),__name(createDiscordReply,"createDiscordReply");var Cj=__name(e=>e.length<=2e3?e:`${e.slice(0,1999)}…`,"clipToDiscordLimit");function createDiscordBridge(e){const{client:t,allowedUserId:n,onMessage:r}=e,o=e.clock??ej,s=e.onLog??(()=>{});let a,i,l=e.threadName;const c=[];function threadId(){return i??=t.createThread({channelId:e.channelId,name:e.threadName??"Command Code"}).then(e=>(a=e,e)),i}__name(threadId,"threadId");const d=__name(e=>e===a,"isOurs");async function deliver(e){try{const n=await t.sendMessage({channelId:e.channelId,text:Cj(e.text),buttons:e.buttons});c.push({channelId:e.channelId,messageId:n})}catch(e){const t=lj(e);s(t.includes("403")?`note failed: ${t}. The bot needs "Send Messages in Threads" in that channel`:`note failed: ${t}`)}}function handleMessage(e){const t=parseDiscordMessage(e);t&&(""!==t.text?t.fromBot||d(t.channelId)&&(t.userId===n?r({chatId:t.channelId,userId:t.userId,userName:t.userName,text:t.text,platform:"Discord"}):s(`refused message from unauthorized user ${t.userId}`)):d(t.channelId)&&!t.fromBot&&s("message arrived with no content. Is MESSAGE CONTENT INTENT on in the developer portal?"))}function acknowledge(e){return t.ackInteraction({interactionId:e.interactionId,token:e.token}).catch(e=>{s(`interaction ack failed: ${lj(e)}`)})}function handleCommand2(e){const t=parseDiscordCommand(e);if(!t)return!1;if(!d(t.channelId))return!0;const o=`/${t.name}${t.value?` ${t.value}`:""}`;return t.userId!==n?(s(`refused command from unauthorized user ${t.userId}`),reply(t,"Not authorized for this session."),!0):(reply(t,`Running ${o}`),r({chatId:t.channelId,userId:t.userId,userName:void 0,text:o,platform:"Discord"}),!0)}function reply(e,n){return t.replyToInteraction({interactionId:e.interactionId,token:e.token,text:n}).catch(e=>{s(`command reply failed: ${lj(e)}`)})}async function publishCommands(n){const r=e.commands??[];if(0!==r.length)try{const o=await t.guildOfChannel(e.channelId);await t.publishCommands({applicationId:n,guildId:o,commands:r}),s(`registered ${r.length} slash command(s)`)}catch(e){const t=lj(e);s(t.includes("Missing Access")||t.includes("403")?`slash commands not registered: ${t}. Re-invite the bot with the applications.commands scope`:`slash commands not registered: ${t}`)}}function handleInteraction(r){const o=parseDiscordInteraction(r);o&&d(o.channelId)&&(acknowledge(o),o.userId===n?e.onChoice?.({chatId:o.channelId,userId:o.userId,data:o.data,acknowledge:__name(async()=>{},"acknowledge"),dismiss:__name(async()=>{if(o.messageId)try{await t.deleteMessage({channelId:o.channelId,messageId:o.messageId})}catch(e){s(`message delete failed: ${lj(e)}`)}},"dismiss")}):s(`refused interaction from unauthorized ${o.userId}`))}__name(deliver,"deliver"),__name(handleMessage,"handleMessage"),__name(acknowledge,"acknowledge"),__name(handleCommand2,"handleCommand"),__name(reply,"reply"),__name(publishCommands,"publishCommands"),__name(handleInteraction,"handleInteraction");const u=e.connect({onDispatch:__name(({type:e,data:t})=>{if("MESSAGE_CREATE"===e)return handleMessage(t);"INTERACTION_CREATE"===e&&(handleCommand2(t)||handleInteraction(t))},"onDispatch"),onReady:__name(({applicationId:t})=>{threadId().then(()=>e.onReady?.({skippedUpdates:0}),t=>e.onFatal?.(`could not open a thread in that channel. Check the id, and that the bot can Create Public Threads there (${lj(t)})`)),t?publishCommands(t):s("no application id in READY, so slash commands are not registered")},"onReady"),onFatal:__name(t=>e.onFatal?.(t),"onFatal")});return{start:__name(()=>u.start(),"start"),stop:__name(()=>u.stop(),"stop"),isRunning:__name(()=>u.isRunning(),"isRunning"),openReply:__name(n=>{const r="function"==typeof e.label?e.label():e.label;return void 0!==r&&r!==l&&(l=r,threadId().then(e=>t.renameThread({channelId:e,name:r})).catch(e=>{s(`thread rename failed: ${lj(e)}`)})),createDiscordReply({client:t,channelId:n,prefix:r,onSent:__name(e=>c.push({channelId:n,messageId:e}),"onSent"),onLog:s,clock:o})},"openReply"),sendNote:__name((e,t)=>{deliver({channelId:e,text:t})},"sendNote"),sendChoices:__name(e=>{deliver({channelId:e.chatId,text:e.text,buttons:e.buttons})},"sendChoices"),announce:__name(async e=>{const t=await threadId().catch(()=>{});t&&await deliver({channelId:t,text:e})},"announce"),get ownerChatId(){return a},clearSentMessages:__name(async()=>{const e=[...c].reverse();c.length=0;let n=0;for(const r of e)try{await t.deleteMessage(r),n+=1}catch{}return n},"clearSentMessages")}}__name(createDiscordBridge,"createDiscordBridge"),Vt();var bj=__name(e=>`\`${e.replaceAll("`","")}\``,"code"),Ej=__name(e=>`⌘ Command Code · ${e.repo}`,"title");function discordConnectBanner(e){const{info:t,note:n}=e,r=[bj(`v${t.version}`),bj(t.model),...t.branch?[bj(t.branch)]:[]].join(" · ");return[`## ${Ej(t)}`,r,"-# Slash commands work in this thread. /help lists them.",...n?[`-# ${n}`]:[]].join("\n")}__name(discordConnectBanner,"discordConnectBanner");var Tj=__name(e=>[`## ⚪ ${Ej(e)} · ended`,"-# Messages sent from now on are skipped when a session reconnects."].join("\n"),"discordFarewell"),Pj=__name(e=>`-# ✻ ${e}`,"discordStatusLine"),Mj=__name(e=>`-# ⌘ ${e.repo}${e.branch?` · ${e.branch}`:""} · ${e.model}`,"discordReplyLabel"),xj=__name(e=>[`## ${Ej(e.info)}${e.info.branch?` · ${e.info.branch}`:""}`,`${bj(`v${e.info.version}`)} · ${bj(e.info.model)}`,`-# ${e.mode}`].join("\n"),"discordStatus");Vt();var Ij={4004:"that bot token is not valid",4010:"invalid shard",4011:"this bot is in too many servers to run unsharded",4012:"invalid API version",4013:"invalid intents",4014:"the MESSAGE CONTENT intent is off. Turn it on in the Discord developer portal, under Bot → Privileged Gateway Intents"},Aj=__name(e=>"object"==typeof e&&null!==e,"isRecord");function createDiscordGateway(e){const t=e.clock??ej,n=e.onLog??(()=>{}),r=e.createSocket??(e=>new WebSocket(e));let o,s,a,i,l,c,d=!1,u=0,m=0,p=!1;const g=__name(()=>{void 0!==s&&t.clearTimeout(s),void 0!==a&&t.clearTimeout(a),s=void 0,a=void 0},"clearTimers"),h=__name(e=>{try{o?.send(JSON.stringify(e))}catch(e){n(`gateway send failed: ${String(e)}`)}},"send");function backoffMs2(){const e=Math.min(m-1,5);return Math.min(1e3*2**e,3e4)+Math.floor(500*t.random())}function scheduleHeartbeat(e,r){s=t.setTimeout(()=>{if(d&&r===u){if(p)return n("gateway heartbeat not acknowledged, reconnecting"),void o?.close(4e3);p=!0,h({op:1,d:c??null}),scheduleHeartbeat(e,r)}},e)}function identify(){h(i&&void 0!==c?{op:6,d:{token:e.token,session_id:i,seq:c}}:{op:2,d:{token:e.token,intents:33280,properties:{os:process.platform,browser:"commandcode",device:"commandcode"}}})}function handleDispatch(t,r){if("READY"===t&&Aj(r)){m=0,i="string"==typeof r.session_id?r.session_id:void 0,l="string"==typeof r.resume_gateway_url?`${r.resume_gateway_url}/?v=10&encoding=json`:void 0,n("gateway ready");const t=Aj(r.application)?r.application:void 0,o=Aj(r.user)?r.user:void 0;return void e.onReady?.({applicationId:"string"==typeof t?.id?t.id:"string"==typeof o?.id?o.id:void 0})}if("RESUMED"===t)return m=0,void n("gateway resumed");e.onDispatch({type:t,data:r})}function handleFrame(e,r){if(!d||r!==u)return;let a;try{a=JSON.parse("string"==typeof e?e:String(e))}catch{return}if(Aj(a)){if("number"==typeof a.s&&(c=a.s),10===a.op&&Aj(a.d)){const e="number"==typeof a.d.heartbeat_interval?a.d.heartbeat_interval:41250;return p=!1,s=t.setTimeout(()=>{d&&r===u&&(p=!0,h({op:1,d:c??null}),scheduleHeartbeat(e,r))},Math.floor(e*t.random())),void identify()}if(11!==a.op)return 7===a.op?(n("gateway asked us to reconnect"),void o?.close(4e3)):9===a.op?(!0!==a.d&&(i=void 0,c=void 0,l=void 0),n("gateway invalidated the session"),void o?.close(4e3)):void(0===a.op&&"string"==typeof a.t&&handleDispatch(a.t,a.d));p=!1}}function connect(t){if(!d||t!==u)return;g();const s=i&&l?l:"wss://gateway.discord.gg/?v=10&encoding=json";let a;try{a=r(s)}catch(e){return n(`gateway connect failed: ${String(e)}`),void scheduleReconnect(t)}o=a,a.onopen=()=>n("gateway socket open"),a.onmessage=e=>handleFrame(e.data,t),a.onerror=()=>n("gateway socket error"),a.onclose=r=>{if(!d||t!==u)return;const o=Ij[r.code];if(o)return d=!1,g(),n(`gateway closed fatally (${r.code}): ${o}`),void e.onFatal?.(o);4007!==r.code&&4009!==r.code||(i=void 0,c=void 0,l=void 0),n(`gateway closed (${r.code})`),scheduleReconnect(t)}}function scheduleReconnect(e){d&&e===u&&(g(),m+=1,a=t.setTimeout(()=>connect(e),backoffMs2()))}return __name(backoffMs2,"backoffMs"),__name(scheduleHeartbeat,"scheduleHeartbeat"),__name(identify,"identify"),__name(handleDispatch,"handleDispatch"),__name(handleFrame,"handleFrame"),__name(connect,"connect"),__name(scheduleReconnect,"scheduleReconnect"),{start(){d||(d=!0,u+=1,m=0,connect(u))},stop(){d=!1,u+=1,g();try{o?.close(1e3)}catch{}o=void 0,i=void 0,c=void 0,l=void 0},isRunning:__name(()=>d,"isRunning")}}__name(createDiscordGateway,"createDiscordGateway"),Vt(),Vt();var Rj={"content-type":"application/json"},Lj=__name(e=>e instanceof Error&&"retryable"in e,"isTelegramApiError");function toApiError3(e,t,n){const r=Uj(n)?n:{},o=Uj(r.parameters)?r.parameters:{},s="string"==typeof r.description?r.description:`Telegram API error (HTTP ${t})`;return Object.assign(new Error(`${e}: ${s}`),{retryable:429===t||t>=500,retryAfterMs:"number"==typeof o.retry_after?1e3*o.retry_after:void 0})}__name(toApiError3,"toApiError");var Oj=__name(e=>!Lj(e)||e.retryable,"isRetryableFailure"),Dj=__name((e,t)=>Lj(e)&&void 0!==e.retryAfterMs?e.retryAfterMs:500*2**t,"retryDelayMs"),$j=__name(e=>e instanceof Error&&e.message.includes("message is not modified"),"isNotModifiedError"),Nj=__name(e=>e instanceof Error&&/can'?t parse entities/i.test(e.message),"isParseEntitiesError"),_j=__name(e=>e instanceof Error&&/chat not found/i.test(e.message),"isChatMissingError"),Fj=__name(e=>e instanceof Error&&/message to edit not found|message can'?t be edited/i.test(e.message),"isMessageGoneError"),Uj=__name(e=>"object"==typeof e&&null!==e,"isRecord"),jj=__name(e=>"string"==typeof e?e:"number"==typeof e?String(e):void 0,"asId");function parseMessage2(e){if(!Uj(e))return;const t=Uj(e.chat)?e.chat:void 0,n=Uj(e.from)?e.from:void 0,r=e.message_id,o=jj(t?.id),s=jj(n?.id);return"number"==typeof r&&o&&s?{messageId:r,chatId:o,userId:s,userName:"string"==typeof n?.username?n.username:void 0,text:"string"==typeof e.text?e.text:""}:void 0}function parseCallback(e){if(!Uj(e))return;const t=Uj(e.from)?e.from:void 0,n=Uj(e.message)?e.message:void 0,r=Uj(n?.chat)?n.chat:void 0,o=jj(e.id),s=jj(r?.id),a=jj(t?.id);return o&&s&&a&&"string"==typeof e.data&&"number"==typeof n?.message_id?{callbackId:o,chatId:s,userId:a,userName:"string"==typeof t?.username?t.username:void 0,data:e.data,messageId:n.message_id}:void 0}function parseUpdates(e){if(!Array.isArray(e))return[];const t=[];for(const n of e)Uj(n)&&"number"==typeof n.update_id&&t.push({updateId:n.update_id,message:parseMessage2(n.message),callback:parseCallback(n.callback_query)});return t}__name(parseMessage2,"parseMessage"),__name(parseCallback,"parseCallback"),__name(parseUpdates,"parseUpdates");var Bj=__name(e=>e?{parse_mode:e}:{},"parseModeBody"),Wj=__name(e=>e&&e.length>0?{reply_markup:{inline_keyboard:e.map(e=>e.map(e=>({text:e.text,callback_data:e.data})))}}:{},"replyMarkupBody");function defaultSleep3(e){return new Promise(t=>{const n=setTimeout(t,e);n.unref?.()})}function createTelegramClient(e){const t=e.fetchFn??fetch,n=e.sleep??defaultSleep3,r=`https://api.telegram.org/bot${e.token}`;async function call(e){const{method:n,body:o,signal:s=null}=e,a=await t(`${r}/${n}`,o instanceof FormData?{method:"POST",body:o,signal:s}:{method:"POST",body:JSON.stringify(o),headers:Rj,signal:s}),i=await a.json().catch(()=>{});if(Uj(i)&&!0===i.ok)return i.result;throw toApiError3(n,a.status,i)}async function callWithRetry(e){for(let t=0;;t+=1)try{return await call(e)}catch(e){const r=t>=2;if(!Oj(e)||r)throw e;await n(Dj(e,t))}}return __name(call,"call"),__name(callWithRetry,"callWithRetry"),{getUpdates:async({offset:e,timeoutSeconds:t,signal:n})=>parseUpdates(await call({method:"getUpdates",body:{offset:e,timeout:t,allowed_updates:["message","callback_query"]},signal:n})),async sendMessage({chatId:e,text:t,parseMode:n,buttons:r}){const o=parseMessage2(await callWithRetry({method:"sendMessage",body:{chat_id:e,text:t,...Bj(n),...Wj(r)}}));if(!o)throw new Error("sendMessage: malformed Telegram response");return o.messageId},async answerCallback({callbackId:e,text:t}){await callWithRetry({method:"answerCallbackQuery",body:{callback_query_id:e,...void 0===t?{}:{text:t}}})},async deleteMessage({chatId:e,messageId:t}){await callWithRetry({method:"deleteMessage",body:{chat_id:e,message_id:t}})},async editMessageText({chatId:e,messageId:t,text:n,parseMode:r}){try{await callWithRetry({method:"editMessageText",body:{chat_id:e,message_id:t,text:n,...Bj(r)}})}catch(e){if($j(e))return;throw e}}}}__name(defaultSleep3,"defaultSleep"),__name(createTelegramClient,"createTelegramClient"),Vt();var Hj=/```[\w+-]*\n?[\s\S]*?```|`[^`\n]+`/g,Gj=/^```[\w+-]*\n?([\s\S]*?)```$/,Vj=/^`([^`\n]+)`$/,zj=/^#{1,6}[ \t]+(.+)$/gm,Kj=/\*\*([^\n]+?)\*\*/g,qj=/~~([^\n]+?)~~/g,Yj=/\[([^\]\n]+)\]\(([^)\s]+)\)/g,Qj=__name(e=>/^https?:\/\//i.test(e),"isWebUrl"),Jj=__name(e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),"escapeHtml");function splitCodeRuns(e){const t=[];let n=0;for(const r of e.matchAll(Hj)){const o=r.index;void 0!==o&&(o>n&&t.push({isCode:!1,value:e.slice(n,o)}),t.push({isCode:!0,value:r[0]}),n=o+r[0].length)}return n<e.length&&t.push({isCode:!1,value:e.slice(n)}),t}function codeBody(e){const t=Gj.exec(e);return t?(t[1]??"").replace(/\n$/,""):Vj.exec(e)?.[1]}__name(splitCodeRuns,"splitCodeRuns"),__name(codeBody,"codeBody");var Xj=__name(e=>{const t=codeBody(e);return void 0===t?Jj(e):e.startsWith("```")?`<pre><code>${Jj(t)}</code></pre>`:`<code>${Jj(t)}</code>`},"codeToHtml"),Zj=__name(e=>Jj(e).replace(zj,"<b>$1</b>").replace(Kj,"<b>$1</b>").replace(qj,"<s>$1</s>").replace(Yj,(e,t,n)=>Qj(n)?`<a href="${n}">${t}</a>`:e),"proseToHtml");function toTelegramHtml(e){return splitCodeRuns(e).map(e=>e.isCode?Xj(e.value):Zj(e.value)).join("")}__name(toTelegramHtml,"toTelegramHtml");var eB=__name(e=>e.replace(zj,"$1").replace(Kj,"$1").replace(qj,"$1").replace(Yj,(e,t,n)=>Qj(n)?`${t} (${n})`:e),"proseToPlain");function stripMarkdown(e){return splitCodeRuns(e).map(e=>e.isCode?codeBody(e.value)??e.value:eB(e.value)).join("")}__name(stripMarkdown,"stripMarkdown");var tB=__name(e=>`\`${e.replaceAll("`","")}\``,"code"),nB=__name(e=>`⌘ Command Code · ${e.repo}`,"title");function telegramConnectBanner(e){const{info:t,note:n}=e,r=[tB(`v${t.version}`),tB(t.model),...t.branch?[tB(t.branch)]:[]].join(" · ");return[`# ${nB(t)}`,r,...n?["",n]:[]].join("\n")}__name(telegramConnectBanner,"telegramConnectBanner");var rB=__name(e=>[`# ⚪ ${nB(e)} · ended`,"Messages sent from now on are skipped when a session reconnects."].join("\n"),"telegramFarewell"),oB=__name(e=>`⌘ ${e.repo}${e.branch?` · ${e.branch}`:""} · ${e.model}`,"telegramReplyLabel"),sB=__name(e=>[`# ${nB(e.info)}${e.info.branch?` · ${e.info.branch}`:""}`,`${tB(`v${e.info.version}`)} · ${tB(e.info.model)}`,e.mode].join("\n"),"telegramStatus");Vt();var aB=__name(e=>e.length<=4096?e:`${e.slice(0,4095)}…`,"clipToMessageLimit");function createRemoteReply(e){const{client:t,chatId:n}=e,r=e.prefix??"",o=e.clock??ej,s=e.onLog??(()=>{}),a=e.onSendFailure??(e=>{s(`reply send failed: ${lj(e)}`)}),i=[],l=[];let c,d="",u="",m=Number.NEGATIVE_INFINITY,p=!1,g=Promise.resolve();const h=__name(e=>""===r?e:`${r}\n\n${e}`,"label");async function sendChunk(e){try{return await t.sendMessage({chatId:n,text:toTelegramHtml(e),parseMode:"HTML"})}catch(r){if(!Nj(r))throw r;return s(`html rejected, sending plain: ${lj(r)}`),t.sendMessage({chatId:n,text:stripMarkdown(e)})}}async function editChunk(e,r){try{return await t.editMessageText({chatId:n,messageId:e,text:toTelegramHtml(r),parseMode:"HTML"}),!0}catch(o){if(Fj(o))return!1;if(!Nj(o))throw o;return s(`html rejected, editing plain: ${lj(o)}`),await t.editMessageText({chatId:n,messageId:e,text:stripMarkdown(r)}),!0}}async function post(t,n){const r=await sendChunk(n);i[t]=r,e.onSent?.(r)}async function send(e){const t=splitForChat(e,4096);for(const[e,n]of t.entries()){if(l[e]===n)continue;const t=i[e];void 0===t?await post(e,n):await editChunk(t,n)||await post(e,n),l[e]=n}}function enqueueSend(e){const t=u;u=e,m=o.now(),g=g.then(()=>send(e)).catch(n=>{u===e&&(u=t),a(n)})}function flush(){if(c=void 0,""===d)return;const e=h(d);e!==u&&enqueueSend(e)}function update(e){if(p)return;if(d=e,void 0!==c)return;const t=Math.max(0,m+1e3-o.now());c=o.setTimeout(flush,t)}function cancel5(){p=!0,void 0!==c&&o.clearTimeout(c),c=void 0}async function finish(e){if(p)return;void 0!==c&&o.clearTimeout(c),c=void 0;const t=h(""===e?"(no text reply)":e);await g,t!==u&&enqueueSend(t),await g}return __name(sendChunk,"sendChunk"),__name(editChunk,"editChunk"),__name(post,"post"),__name(send,"send"),__name(enqueueSend,"enqueueSend"),__name(flush,"flush"),__name(update,"update"),__name(cancel5,"cancel"),__name(finish,"finish"),{update:update,finish:finish,cancel:cancel5}}function createSendFailureReporter(e){let t=!1;function report(n){_j(n)?t||(t=!0,e("waiting on Telegram: message your bot once. a bot cannot text you first, and everything held posts when you do")):e(`send failed: ${lj(n)}`)}return __name(report,"report"),{report:report,reset:__name(()=>{t=!1},"reset")}}function createRemoteBridge(e){const{client:t,allowedUserId:n,onMessage:r}=e,o=e.clock??ej,s=e.onLog??(()=>{}),a=createSendFailureReporter(s);let i,l,c=!1,d=0,u=0,m=0,p=!1;function backoffMs2(){const e=Math.min(m-1,5);return Math.min(1e3*2**e,3e4)+Math.floor(250*o.random())}__name(backoffMs2,"backoffMs");const g=[],h=__name(e=>{g.push(e)},"track");async function clearSentMessages(){const e=[...g].reverse();g.length=0;let r=0;for(const o of e)try{await t.deleteMessage({chatId:n,messageId:o}),r+=1}catch{}return r}async function deliverMarkdown(e){try{return h(await t.sendMessage({chatId:e.chatId,text:aB(toTelegramHtml(e.text)),parseMode:"HTML",buttons:e.buttons})),!0}catch(e){if(!Nj(e))return a.report(e),!1;s("note HTML rejected, retrying as plain text")}try{return h(await t.sendMessage({chatId:e.chatId,text:aB(stripMarkdown(e.text)),buttons:e.buttons})),!0}catch(e){return a.report(e),!1}}__name(clearSentMessages,"clearSentMessages"),__name(deliverMarkdown,"deliverMarkdown");const f=__name((e,t)=>deliverMarkdown({chatId:e,text:t}),"deliverNote");function sendNote(e,t){f(e,t)}function sendChoices(e){deliverMarkdown(e)}async function acknowledge(e,n){try{await t.answerCallback({callbackId:e,text:n})}catch(e){s(`callback answer failed: ${lj(e)}`)}}async function dismiss(e,n){try{await t.deleteMessage({chatId:e,messageId:n})}catch(e){s(`message delete failed: ${lj(e)}`)}}let y;function flushAnnouncement(e){const t=y;void 0!==t&&(y=void 0,f(e,t))}function deliver(e){""!==e.text&&(e.userId===n?(a.reset(),flushAnnouncement(e.chatId),r({chatId:e.chatId,userId:e.userId,userName:e.userName,text:e.text})):s(`refused message from unauthorized user ${e.userId}`))}function deliverChoice(t){if(t.userId!==n)return s(`refused callback from unauthorized user ${t.userId}`),void acknowledge(t.callbackId,"Not authorized.");e.onChoice?.({chatId:t.chatId,userId:t.userId,data:t.data,acknowledge:__name(e=>acknowledge(t.callbackId,e),"acknowledge"),dismiss:__name(()=>dismiss(t.chatId,t.messageId),"dismiss")})}function schedule(e,t){c&&e===d&&(i=o.setTimeout(()=>{tick(e)},t))}async function tick(e){if(c&&e===d){l=new AbortController;try{const n=await t.getUpdates({offset:u,timeoutSeconds:30,signal:l.signal});if(!c||e!==d)return;m=0,p&&(p=!1,s("Telegram reconnected"));for(const e of n)e.updateId>=u&&(u=e.updateId+1),e.message&&deliver(e.message),e.callback&&deliverChoice(e.callback);schedule(e,0)}catch(t){if(!c||e!==d)return;m+=1,p||(p=!0,s(`Telegram unreachable: ${lj(t)}. retrying`)),schedule(e,backoffMs2())}}}async function drainBacklog(e){let n=0;for(let r=0;r<20;r+=1){if(!c||e!==d)return n;l=new AbortController;try{const e=await t.getUpdates({offset:u,timeoutSeconds:0,signal:l.signal});if(0===e.length)return n;for(const t of e)t.updateId>=u&&(u=t.updateId+1);n+=e.length}catch(e){return s(`backlog drain failed: ${lj(e)}`),n}}return n}function start(){if(c)return;c=!0,d+=1,m=0,p=!1,s("remote bridge started");const t=d;drainBacklog(t).then(n=>{c&&t===d&&(n>0&&s(`skipped ${n} queued update(s)`),e.onReady?.({skippedUpdates:n}),schedule(t,0))})}function stop(){c&&(c=!1,d+=1,void 0!==i&&o.clearTimeout(i),i=void 0,l?.abort(),l=void 0,s("remote bridge stopped"))}return __name(sendNote,"sendNote"),__name(sendChoices,"sendChoices"),__name(acknowledge,"acknowledge"),__name(dismiss,"dismiss"),__name(flushAnnouncement,"flushAnnouncement"),__name(deliver,"deliver"),__name(deliverChoice,"deliverChoice"),__name(schedule,"schedule"),__name(tick,"tick"),__name(drainBacklog,"drainBacklog"),__name(start,"start"),__name(stop,"stop"),{start:start,stop:stop,isRunning:__name(()=>c,"isRunning"),openReply:__name(n=>createRemoteReply({client:t,chatId:n,prefix:"function"==typeof e.label?e.label():e.label,onSent:h,onLog:s,onSendFailure:a.report,clock:o}),"openReply"),sendNote:sendNote,sendChoices:sendChoices,clearSentMessages:clearSentMessages,announce:__name(async e=>{await f(n,e)||(y=e)},"announce"),ownerChatId:n}}async function greetTelegramChat(e){const t=e.client??createTelegramClient({token:e.token});try{return await t.sendMessage({chatId:e.chatId,text:"Setup done. This is where Command Code answers."}),{kind:"greeted"}}catch(e){return _j(e)?{kind:"not-started"}:{kind:"failed",reason:lj(e)}}}__name(createRemoteReply,"createRemoteReply"),Vt(),__name(createSendFailureReporter,"createSendFailureReporter"),__name(createRemoteBridge,"createRemoteBridge"),Vt(),__name(greetTelegramChat,"greetTelegramChat"),Vt(),PR(),Vt(),PR(),Vt();var iB=new Map,lB=new Set;function subscribeAgentSlashCommands(e){return lB.add(e),()=>{lB.delete(e)}}function enqueueAgentSlashCommand(e){const t={command:e.command,source:e.source??"agent"},n=iB.get(e.sessionId);n?n.push(t):iB.set(e.sessionId,[t]);for(const e of[...lB])e()}function drainAgentSlashCommands(e){const t=iB.get(e.sessionId);return t&&0!==t.length?(iB.delete(e.sessionId),t):[]}function hasAgentSlashCommands(e){return(iB.get(e.sessionId)?.length??0)>0}__name(subscribeAgentSlashCommands,"subscribeAgentSlashCommands"),__name(enqueueAgentSlashCommand,"enqueueAgentSlashCommand"),__name(drainAgentSlashCommands,"drainAgentSlashCommands"),__name(hasAgentSlashCommands,"hasAgentSlashCommands");var cB=__name(e=>"remote"===e?"remote":"agent","originOf"),dB="Only you can run /rc — connecting the bot or changing who may use it is yours to decide, not mine. /rc status and /rc disconnect still work.";function refuseAgentSlashCommand(e){const[t,n]=e.trim().replace(/^\//,"").split(/\s+/);if("rc"===t&&"status"!==n&&"off"!==n&&"disconnect"!==n)return dB}__name(refuseAgentSlashCommand,"refuseAgentSlashCommand"),Vt(),PR(),Vt(),PR();var uB=__name(e=>Buffer.byteLength(e,"utf8")<=64,"fits"),mB=__name((e,t)=>e===t?"✓ ":"","mark");function chunk(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([...e.slice(n,n+2)]);return t}function buildRemoteModelMenu(e){const t=[];for(const n of e.groups)for(const r of n.models){const n=encodeValueCallback({command:"model",value:r.id});uB(n)&&t.push({text:`${mB(r.id,e.currentModel)}${r.name}`,data:n})}return 0===e.groups.length?{text:"Provider login required. Run /connect to authenticate.",buttons:[]}:{text:["Select model","Pick one, or send /model <id>"].join("\n").trimEnd(),buttons:chunk(t)}}async function resolveRemoteModelMenu(e){const t=buildLaneModelPickerGroups(),[n,r]=await Promise.all([getBillingContext(),resolveProviderAuth(t.map(e=>e.providerId))]);return buildRemoteModelMenu({currentModel:e,groups:filterModelPickerGroupsByPlan({groups:filterModelPickerGroupsByAuth({groups:t,...r}),billing:n})})}__name(chunk,"chunk"),__name(buildRemoteModelMenu,"buildRemoteModelMenu"),__name(resolveRemoteModelMenu,"resolveRemoteModelMenu");var pB=__name((e,t)=>e===t?"✓ ":"","mark");async function effortMenu(){const e=getConfiguredModel(),t=getSupportedEfforts(e);if(!t||0===t.length)return{text:"This model has no reasoning effort to set.",buttons:[]};const n=getReasoningEffort(e);return{text:`Reasoning effort\nTap one, or send /effort <level>\n\n${t.join(", ")}`,buttons:[t.map(e=>({text:`${pB(e,n)}${e}`,data:encodeValueCallback({command:"effort",value:e})}))]}}__name(effortMenu,"effortMenu");var gB=__name(e=>{const t=getSupportedEfforts(getConfiguredModel());return t&&0!==t.length?t.includes(e.toLowerCase())?void 0:`"${e}" is not a level. Try: ${t.join(", ")}.`:"This model has no reasoning effort to set."},"rejectEffort");function cliSummary(e){const t=ja.find(t=>t.command===`/${e}`);return t?.description??e}__name(cliSummary,"cliSummary");var hB=[{name:"model",summary:cliSummary("model"),argument:"a model id, or leave empty for the list",menu:__name(()=>resolveRemoteModelMenu(getConfiguredModel()),"menu")},{name:"effort",summary:cliSummary("effort"),argument:"a level, or leave empty for the list",menu:effortMenu,reject:gB},{name:"compact",summary:cliSummary("compact"),menu:__name(async()=>({text:"Compacting…",buttons:[]}),"menu")},{name:"clear",summary:cliSummary("clear"),menu:__name(async()=>({text:"Cleared.",buttons:[]}),"menu")}],fB=[{name:"status",summary:"this session, its model, and whether it asks first"},{name:"stop",summary:"interrupt whatever it is doing"},{name:"help",summary:"what you can send"}],yB=new Map(hB.map(e=>[e.name,e])),SB=__name(e=>yB.get(e.toLowerCase()),"findRemoteCommand"),wB=new Set(["model","effort"]),vB=__name(e=>wB.has(e),"needsMenu"),kB=__name(()=>[...hB.map(({name:e,summary:t,argument:n})=>({name:e,summary:t,argument:n})),...fB],"listRemoteCommands");function buildRemoteHelp(){return["What you can send","",...kB().map(e=>`/${e.name}: ${e.summary}`),"","Anything else is a prompt for the agent."].join("\n")}__name(buildRemoteHelp,"buildRemoteHelp");var CB="Not set up yet. Run /rc and it walks you through it.",bB=dB,EB=__name(e=>void 0!==e.origin&&"user"!==e.origin,"isUntrustedDispatch"),TB=__name(e=>"remote"===e.origin?"/rc only works at the terminal. The bot cannot reconfigure itself from the chat. /status and /stop work from here.":bB,"untrustedRefusal");function info(e,t){e.setFeed(e=>[...e,hh(t)])}__name(info,"info");var PB=__name(()=>getModelShortName({modelId:getConfiguredModel(),findModelById:findModelById}),"shortModelName");function shortPath(e){const t=e.split("/").filter(Boolean);return t.length<=2?e:`…/${t.slice(-2).join("/")}`}function sessionLabel(){const e=process.cwd(),t=getCurrentBranch({cwd:e}),n=getPackageJson(import.meta.url).version||"0.0.0",r=`${c(e)}${t?` (${t})`:""}`;return[`Command Code v${n}`,PB(),r].join(" · ")}function sessionInfo(){const e=process.cwd();return{version:getPackageJson(import.meta.url).version||"0.0.0",model:PB(),repo:c(e),branch:getCurrentBranch({cwd:e})||void 0}}__name(shortPath,"shortPath"),__name(sessionLabel,"sessionLabel"),__name(sessionInfo,"sessionInfo");var MB=__name(e=>"discord"===e?"Discord":"Telegram","platformName"),xB={on:"default",default:"default","auto-accept":"auto-accept",bypass:"bypass",yolo:"bypass"};function modeBehaviour(e){return"bypass"===e?"it never asks before editing files or running commands":"auto-accept"===e?"it edits files on its own, and asks in the chat before running commands":"it asks you in the chat before each new tool"}__name(modeBehaviour,"modeBehaviour");var IB=/failed|rejected|unauthorized|not acknowledged|no content|waiting on|reconnected/i,AB=__name(e=>t=>{IB.test(t)&&info(e,`Remote: ${t}`)},"bridgeLogger"),RB=__name(e=>{const t=Date.parse(e);if(Number.isNaN(t))return"unknown";const n=Math.max(0,Math.round((Date.now()-t)/6e4));return n<1?"just now":n<60?`${n}m ago`:`${Math.round(n/60)}h ago`},"sinceLabel");function describeLockHolder(e){return[e.label??"Command Code",` ${shortPath(e.cwd)}`,` started ${RB(e.startedAt)} · pid ${e.pid}`].join("\n")}function applyPermissionMode(e,t){const n=e.permissionModeRef.current;return e.permissionModeRef.current=t,e.setPermissionMode(t),I$(e.sessionId)?.setPermissionMode({mode:t}),n}__name(describeLockHolder,"describeLockHolder"),__name(applyPermissionMode,"applyPermissionMode");var LB,OB,DB=__name(()=>new Promise(e=>{const t=setTimeout(e,400);t.unref?.()}),"handoverPause");function takeRcSelectorStep(){const e=LB;return LB=void 0,e}__name(takeRcSelectorStep,"takeRcSelectorStep");var $B=!1;function registerExitRelease(){$B||($B=!0,process.once("exit",()=>{releaseRemoteLockSync()}))}async function buildRcStatusMessage(e){const t=getActiveRemote(),n=await UB(),r=resolveRemoteSettings(await loadRemoteConfig(),process.env,n),o=await readRemoteLock(),s=!t&&o&&o.pid!==process.pid?["","Another session has the bot:",describeLockHolder(o),"Run /rc to take it over."]:[];return["Remote control: "+(t?`on via ${t.platform} in ${modeLabel(t.mode)} mode, ${modeBehaviour(t.mode)}`:"off"),...t&&e?[` ${sessionLabel()}`]:[],` ${MB(n)} token: ${r.token?"configured":"not set"} · allowed user: ${r.allowedUserId??"not set"}`,` credentials: ${remoteConfigPath()}`,...s].join("\n")}__name(registerExitRelease,"registerExitRelease"),__name(buildRcStatusMessage,"buildRcStatusMessage");var NB=__name(e=>"discord"===e?Tj(sessionInfo()):rB(sessionInfo()),"farewellFor");function stopRemote(e,t={}){const n=getActiveRemote();if(!n)return void info(e,"Remote control is not running.");if(n.restoreMode&&applyPermissionMode(e,n.restoreMode),OB?.(),OB=void 0,!t.clearChat)return shutdownActiveRemote(),releaseRemoteLock(),void info(e,"Remote control stopped.");const{bridge:r}=n;clearActiveRemote(),(async()=>{const t=await r.clearSentMessages();getActiveRemote()||await releaseRemoteLock(),info(e,0===t?"Remote control stopped. Nothing of mine left in the chat.":`Remote control stopped, and ${t} message(s) cleared from the chat. Your own messages stay, because a bot can only delete its own, and only for 48 hours.`)})()}__name(stopRemote,"stopRemote");var _B=__name(e=>({pid:process.pid,cwd:process.cwd(),sessionId:e,startedAt:(new Date).toISOString(),label:sessionLabel()}),"lockInfoFor");function surrenderRemote(e){const t=getActiveRemote();t&&(t.restoreMode&&applyPermissionMode(e,t.restoreMode),shutdownActiveRemote(),info(e,"Remote control moved to another session, which took over the bot. Run /rc here to take it back."))}function buildBridge(e){const t={allowedUserId:e.allowedUserId,onMessage:emitRemoteMessage,onChoice:emitRemoteChoice,onLog:e.onLog,label:__name(()=>"discord"===e.provider?Mj(sessionInfo()):oB(sessionInfo()),"label")},n=__name(e=>e>0?`Skipped ${e} message(s) queued while no session was connected.`:void 0,"skippedNote"),r=__name((t,r)=>{const o="discord"===e.provider?discordConnectBanner:telegramConnectBanner;t.announce(o({info:sessionInfo(),note:n(r)}))},"announceReady");if("discord"===e.provider){const n=createDiscordClient({token:e.token}),o=createDiscordBridge({...t,client:n,channelId:e.channelId??"",threadName:sessionLabel(),commands:kB().map(e=>({name:e.name,description:e.summary,argument:e.argument})),connect:__name(t=>createDiscordGateway({token:e.token,onDispatch:t.onDispatch,onReady:t.onReady,onFatal:t.onFatal,onLog:e.onLog}),"connect"),onFatal:e.onFatal,onReady:__name(({skippedUpdates:e})=>r(o,e),"onReady")});return o}const o=createRemoteBridge({...t,client:createTelegramClient({token:e.token}),onReady:__name(({skippedUpdates:e})=>r(o,e),"onReady")});return o}__name(surrenderRemote,"surrenderRemote"),__name(buildBridge,"buildBridge");var FB=__name(e=>"telegram"===e,"needsExclusiveBot");async function claimBot(e,t){const n=_B(e.sessionId);if(OB?.(),OB=void 0,t)await takeoverRemoteLock(n),await DB();else{const t=await acquireRemoteLock(n);if(!t.ok)return info(e,t.holder?`The bot is attached to another session:\n${describeLockHolder(t.holder)}\n\nRun /rc and pick "Take it over" to move it here.`:"The bot is attached to another session. Run /rc to take it over."),!1}return registerExitRelease(),OB=watchRemoteLock({pid:process.pid,onLost:__name(()=>surrenderRemote(e),"onLost")}),!0}__name(claimBot,"claimBot");var UB=__name(async()=>resolveDefaultProvider({config:await loadRemoteConfig(),active:getActiveRemote()?.provider}),"defaultProvider");async function startRemote(e,t,n={}){const r=n.provider??await UB(),o=resolveRemoteSettings(await loadRemoteConfig(),process.env,r);if(!o.token||!o.allowedUserId)return info(e,CB),!1;if("discord"===r&&!o.channelId)return info(e,CB),!1;if(FB(r)&&!await claimBot(e,!0===n.takeover))return!1;const s=buildBridge({provider:r,token:o.token,allowedUserId:o.allowedUserId,channelId:o.channelId,onLog:AB(e),onFatal:__name(t=>{info(e,`Discord disconnected: ${t}`),stopRemote(e)},"onFatal")}),a=getActiveRemote()?.restoreMode??e.permissionModeRef.current;return applyPermissionMode(e,t),setActiveRemote({bridge:s,mode:t,provider:r,platform:MB(r),farewell:NB(r),restoreMode:a}),s.start(),info(e,`Remote control is on. Send a message here or on ${MB(r)} to continue, or /rc to disconnect.`),!0}async function restartActiveRemote(e){const t=getActiveRemote();t&&(info(e,"Restarting remote control with the new settings…"),await startRemote(e,t.mode,{provider:t.provider}))}function disconnect(e,t){const n=getActiveRemote();n?t.provider&&t.provider!==n.provider?info(e,`${MB(t.provider)} is not connected, ${n.platform} is. Run /rc ${n.provider} off to stop that one.`):t.clear||EB(e)?stopRemote(e,{clearChat:t.clear}):(LB="stopping",e.setShowRcSelector(!0)):info(e,"Remote control is not running.")}async function handleRcCommand(e,t){await migrateRemoteConfig().catch(()=>{});const[n,r,o]=t.trim().split(/\s+/).filter(Boolean);if(!n)return EB(e)?void info(e,TB(e)):void e.setShowRcSelector(!0);if("status"===n)return void info(e,await buildRcStatusMessage(e.sessionId));if("off"===n||"disconnect"===n)return void disconnect(e,{clear:"clear"===r});const s=VU.find(e=>e===n);if(s)return"off"===r||"disconnect"===r?void disconnect(e,{provider:s,clear:"clear"===o}):void info(e,`Try /rc ${s} off, or /rc to connect.`);if(EB(e))return void info(e,TB(e));const a=xB[n];if(a)await startRemote(e,a);else{if("token"===n){if(!r)return void info(e,"Provide the bot token: /rc token <bot-token>");const t=await UB();return await updateRemoteProviderConfig(t,{token:r}),info(e,`${MB(t)} bot token saved to ${remoteConfigPath()}.`),void await restartActiveRemote(e)}if("user"===n){const t=await UB();return r&&/^\d+$/.test(r)?(await updateRemoteProviderConfig(t,{allowedUserId:r}),info(e,`Allowed ${MB(t)} user set to ${r}.`),void await restartActiveRemote(e)):void info(e,"discord"===t?"Provide your numeric Discord id: /rc user <id>. In Discord, turn on Settings → Developer → Developer Mode, then right-click your name → Copy User ID.":"Provide your numeric Telegram id: /rc user <id>. Message @userinfobot on Telegram and it replies with the number.")}info(e,`Unknown /rc argument "${n}". Try: /rc · /rc status · /rc default · /rc auto-accept · /rc yolo · /rc off · /rc telegram off · /rc discord off · /rc token <bot-token> · /rc user <id>`)}}__name(startRemote,"startRemote"),__name(restartActiveRemote,"restartActiveRemote"),__name(disconnect,"disconnect"),__name(handleRcCommand,"handleRcCommand"),Vt();var jB=/("[^"]+"|(?:[\w-]+\.)+(?:com|org|net|io|dev|me|app)(?:\/[\w\-./]*)?|(?<![\w./])\/[\w-]+|@[\w-]+)/g,BB=__name(e=>/^[\w-]+\./.test(e),"isAddress");function urlFor(e,t){return BB(e)?`https://${e}`:e.startsWith("@")&&"telegram"===t?`https://t.me/${e.slice(1)}`:""}function splitStepTokens(e,t="telegram"){return e.split(jB).map((e,n)=>{const r=n%2==1,o=r?urlFor(e,t):"";return{text:e,isToken:r,...""===o?{}:{url:o}}}).filter(e=>""!==e.text)}__name(urlFor,"urlFor"),__name(splitStepTokens,"splitStepTokens");var WB={telegram:"Telegram",discord:"Discord"},HB=[{label:"Telegram",value:"telegram",description:"Drive this session from a Telegram bot."},{label:"Discord",value:"discord",description:"A thread per session, so several can run at once."}],GB=[{label:modeLabel("default"),value:"default",description:"Asks before each new tool. Approve or Deny in the chat."},{label:modeLabel("auto-accept"),value:"auto-accept",description:"Reads and writes files. Asks before running commands."},{label:modeLabel("bypass"),value:"bypass",description:"Dangerously bypasses every permission. Never asks."}],VB={label:"Disconnect",value:"off",description:"Stop the bot. The session keeps running here."},zB=[{label:"Take it over",value:"takeover",description:"That session disconnects, this one takes the bot."},{label:"Leave it alone",value:"cancel",description:"That session keeps the bot."}],KB=[{label:"Disconnect",value:"stop",description:"Keep the chat history."},{label:"Disconnect and clear all chat history",value:"stop-clear",description:"Delete the bot's messages. Yours stay."}],qB=__name(e=>t=>/^\d+$/.test(t)?void 0:`${e} is digits only.`,"digitsOnly"),YB={telegram:[{key:"token",title:"create the bot",steps:["1. Open Telegram and search for @BotFather","2. Send it /newbot","3. It asks for a name, then a username. Any name will do;",' the username has to end in "bot" (e.g. yourname_cmd_bot)',"4. It replies with a token. Copy it and paste it here"],reject:__name(e=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(e)?void 0:"That does not look like a bot token. It is a number, a colon, then a long string.","reject")},{key:"allowedUserId",title:"say who may use it",steps:["1. In Telegram, search for @userinfobot","2. Send it /start","3. It replies with your user ID. Paste that number here"],reject:qB("Your Telegram id")}],discord:[{key:"token",title:"create the bot",steps:["1. Open discord.com/developers/applications and log in",'2. Top right: click "New Application". Give it any name,',' tick the terms box, click "Create"','3. In the left sidebar, click "Bot"','4. Click "Reset Token", confirm, then "Copy". Discord shows'," a token once. If you lose it, reset it again",'5. Still on that page, scroll to "Privileged Gateway Intents"',' and turn ON "Message Content Intent". Click "Save Changes"',"6. Paste the token here"],reject:__name(e=>/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{20,}$/.test(e)?void 0:ZB,"reject")},{key:"allowedUserId",title:"say who may use it",steps:["1. In the Discord app (not the portal): click the gear by",' your name → "Developer" → turn ON "Developer Mode"','2. Right-click your own name in any chat → "Copy User ID"',"3. Paste that number here"],reject:qB("Your Discord id")},{key:"channelId",title:"invite the bot, then pick its channel",steps:['1. Back in the portal, left sidebar: "OAuth2"','2. Under "OAuth2 URL Generator", tick TWO scopes:',' "bot" and "applications.commands"','3. A "Bot Permissions" box opens underneath. Tick four:',' "View Channels", "Send Messages",',' "Create Public Threads", "Send Messages in Threads"','4. At the bottom, copy the "Generated URL". Open it in a',' browser, choose your server, click "Authorize"',"5. Back in Discord, right-click the channel the bot should",' post in → "Copy Channel ID"',"6. Paste that number here","","Every /rc opens its own thread in that channel, so several","sessions can run on one bot at the same time."],reject:qB("A channel id")}]},QB=["1. Open Telegram and find the bot you just made","2. Send it /start","","A bot cannot text you first, so this is what creates the chat."],JB=[{label:"Done, check it",value:"greet-check",description:"Sends a message back, so you see it works."},{label:"Skip",value:"greet-skip",description:"Nothing reaches Telegram until you do it."}],XB=__name(e=>YB[e].length+("telegram"===e?1:0),"stepCount"),ZB="That does not look like a bot token. It has three parts separated by dots, so make sure you copied the Bot token, not the Application ID.",eW=__name(({line:e,provider:t})=>it.createElement(et,{color:LR.GRAY},splitStepTokens(e,t).map((e,t)=>{const n=`${e.text}:${String(t)}`;return e.url?it.createElement(yL,{key:n,url:e.url,text:e.text,color:OR}):it.createElement(et,{key:n,color:e.isToken?OR:void 0,bold:e.isToken},e.text)})),"StepLine"),tW=__name(({lines:e,provider:t})=>it.createElement(Ze,{flexDirection:"column",marginBottom:1},e.map((e,n)=>""===e?it.createElement(Ze,{key:`gap-${String(n)}`,height:1}):it.createElement(eW,{key:e,line:e,provider:t}))),"Steps"),nW=__name(({options:e,onSelect:t})=>it.createElement(SelectInput,{items:e.map(e=>({label:e.label,value:e.value})),onSelect:t,indicatorComponent:o_,itemComponent:({isSelected:t,label:n})=>{const r=e.findIndex(e=>e.label===n),o=e[r],s=r===e.length-1;return it.createElement(Ze,{flexDirection:"column",marginBottom:s?0:1},it.createElement(s_,{isSelected:t},` ${r+1}. ${o?.label??n}`),it.createElement(l_,null,o?.description??""))}}),"OptionList"),rW=__name(({remoteActive:e,onSelect:t,onCancel:n})=>{const[r,o]=ct(()=>takeRcSelectorStep()??"platform"),[s,a]=ct(""),[i,l]=ct(null),[c,d]=ct(null),[u,m]=ct(void 0),[p,g]=ct("telegram"),[h,f]=ct(0),[y,S]=ct(void 0);ut(()=>{let e=!0;return loadRemoteConfig().then(t=>{e&&S(t)}),readRemoteLock().then(t=>{e&&m(t?.pid===process.pid?void 0:t)}),()=>{e=!1}},[]);const w=__name(e=>{if(!y)return;const t=resolveRemoteSettings(y,process.env,e);return YB[e].every(e=>Boolean(t[e.key]))},"isConfigured"),v=__name(e=>{if(!y)return 0;const t=resolveRemoteSettings(y,process.env,e),n=YB[e].findIndex(e=>!t[e.key]);return-1===n?0:n},"firstMissingField");ot((e,t)=>{t.escape&&("platform"!==r?(o("platform"),l(null),a("")):n())});const k=__name(t=>e?[...t,VB]:t,"withStop"),C=__name(e=>"held"===e?zB:"stopping"===e?KB:"greet"===e?JB:k("platform"===e?HB:GB),"optionsFor")(r),b=__name(e=>!0===w(e)?"mode":(f(v(e)),"field"),"afterSetup"),E=__name(r=>{if("telegram"===r.value||"discord"===r.value){const t=r.value;return g(t),d(null),void o("telegram"!==t||void 0===u||e?b(t):"held")}if("cancel"!==r.value)if("takeover"!==r.value)if("off"!==r.value){if("greet-check"!==r.value)return"greet-skip"===r.value?(d(null),void o("mode")):void("stop"!==r.value&&"stop-clear"!==r.value?t({kind:"start",provider:p,mode:r.value,takeover:void 0!==u}):t({kind:"stop",clearChat:"stop-clear"===r.value}));x()}else o("stopping");else o(b(p));else n()},"handleSelect"),T=__name((e,t)=>{updateRemoteProviderConfig(p,e).then(()=>{l(null),a(""),o(t)},e=>{l(`Could not save: ${String(e)}`)})},"save"),P=__name(e=>{l(e),a("")},"reject"),M=__name(e=>{const t=YB[p],n=t[h];if(!n)return;const r=e.trim(),o=n.reject(r);if(o)return void P(o);const s=h===t.length-1,a="telegram"===p?"greet":"mode";T({[n.key]:r},s?a:"field"),s||f(h+1)},"submitField"),x=__name(()=>{d("Sending a message to your bot…"),loadRemoteConfig().then(e=>{const t=resolveRemoteSettings(e,process.env,"telegram"),{token:n,allowedUserId:r}=t;return n&&r?greetTelegramChat({token:n,chatId:r}):{kind:"failed",reason:"the credentials are not saved"}}).then(e=>{if("greeted"===e.kind)return d(null),void o("mode");d("not-started"===e.kind?"Telegram has no chat yet. Send your bot /start, then try again.":`Telegram refused: ${e.reason}`)})},"checkGreeting");if("greet"===r)return it.createElement(RO,{title:"Remote control",subtitle:`${WB.telegram} · step ${XB("telegram")} of ${XB("telegram")} · open the chat`,footer:it.createElement(et,{italic:!0,color:LR.DIM},"Press ",it.createElement(et,{bold:!0},"Esc")," to go back"),gapAfterHeader:!1},it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(tW,{lines:QB,provider:"telegram"}),it.createElement(nW,{options:JB,onSelect:E}),c&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.YELLOW},c))));if("field"===r){const e=YB[p][h];return e?it.createElement(RO,{title:"Remote control",subtitle:`${WB[p]} · step ${h+1} of ${XB(p)} · ${e.title}`,footer:it.createElement(et,{italic:!0,color:LR.DIM},"Press ",it.createElement(et,{bold:!0},"Esc")," to go back"),gapAfterHeader:!1},it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(tW,{lines:e.steps,provider:p}),it.createElement(Ze,null,it.createElement(TextInput,{value:s,focus:!0,prefix:`${ft.pointer} `,prefixColor:MO,onChange:e=>{a(e),l(null)},onSubmit:M})),i&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.RED},i)))):it.createElement(Ze,null)}const I=__name(t=>"held"===t?"Another session has the bot":"stopping"===t?"Clear the chat on the way out?":"mode"===t?"Which permission mode?":"Run this session from a chat app · currently "+(e?"on":"off"),"subtitleFor");return it.createElement(RO,{title:"Remote control",subtitle:I(r),footer:it.createElement(et,{italic:!0,color:LR.DIM},"Press ",it.createElement(et,{bold:!0},"Esc")," to"," ","platform"===r?"cancel":"go back")},"held"===r&&u&&it.createElement(Ze,{flexDirection:"column",marginBottom:1},describeLockHolder(u).split("\n").map(e=>it.createElement(et,{key:e,color:LR.GRAY},e)),it.createElement(et,{color:LR.GRAY},"Telegram allows one session per bot, so only one can have it.")),it.createElement(nW,{options:C,onSelect:E}),c&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.YELLOW},c)))},"RcSelector"),oW=lt(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:o,setStaticKey:s,transcriptMode:a,tasteOnboardingEntryId:i,autoLearnTaste:l,showTasteSkipBanner:c,showTasteLearningInFeed:d,showZdrNotice:u,modelNotice:m,retryAttempt:p,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,showFileList:S,setShowFileList:w,showProviderSelector:v,showModelSelector:k,showEffortSelector:C,showMemorySelector:b,showMcpManager:E,showAgentsConfig:T,showRewindSelector:P,showTreeSelector:M,treeFilterMode:x,treeBranchSummarySkipPrompt:I,showLoginOverlay:A,showUsageOverlay:R,showAddDirModal:L,showCompactModeSelector:O,showThemeSelector:D,showRcSelector:$,authComponentInfo:N,status:_,currentProvider:F,currentModel:U,showProviderNotification:j,shareInfo:B,showShareNotification:W,unshareNotificationMessage:H,updateStatus:G,updateFailedInfo:V,creditWarning:z,permissionMode:K,hintMessage:q,pendingExitKey:Y,interactionTokens:Q,contextUsage:J,tasteLearningOn:X,historyManagerRef:Z,executionState:ee,sessionId:te,onSubmit:ne,onCommand:re,onToggleAutoAccept:oe,onResetPendingExitKey:se,onDoubleEscapeEmpty:ae,onTasteOnboardingComplete:ie,permissionPanel:le,questionPanel:ce,designSuggestionPanel:de,onRewindSelect:ue,onRewindCancel:me,onTreeSelect:pe,onTreeCancel:ge,onTreeLabel:he,onTreeAbortSummary:fe,onLoginComplete:ye,onLoginCancel:Se,setShowProviderSelector:we,setShowModelSelector:ve,setShowEffortSelector:ke,setShowMemorySelector:Ce,setShowMcpManager:be,setShowAgentsConfig:Ee,setShowAddDirModal:Te,setShowUsageOverlay:Pe,handleProviderSelect:Me,handleProviderCancel:xe,handleModelSelect:Ie,handleModelCancel:Ae,handleCompactModeSelect:Re,handleCompactModeCancel:Le,handleThemeSelect:Oe,handleThemeCancel:De,handleRcSelect:$e,handleRcCancel:Ne,handleAuthSuccess:_e,handleAuthCancel:Fe,showDesignGuide:Ue,setShowDesignGuide:je}){const Be=mt(()=>projectTasteFeedVisibility({feed:e.filter(e=>"taste-onboarding"!==e.role),showTasteLearningInFeed:d}),[e,d]),We=pt(()=>je(!1),[je]),He=useTerminalWidth(),[Ge,Ve]=ct(!1),[ze,Ke]=ct(!1),qe=dt(null);qe.current=r?qe.current??Date.now():null;const Ye=mt(()=>"off"===a?Be:projectTranscriptWindow({feed:Be,mode:a}),[Be,a]),Qe=mt(()=>"off"===a?0:Math.max(0,Be.length-Ye.length),[Be.length,Ye.length,a]),Je=mt(()=>0===Qe?Ye:Ye.filter(e=>"user"!==e.role),[Ye,Qe]),Xe=pt(()=>Ee(!1),[Ee]),tt=pt(()=>Ce(!1),[Ce]),nt=pt(()=>be(!1),[be]),rt=pt(()=>Te(!1),[Te]),ot=pt(()=>ve(!0),[ve]),st=pt(()=>ke(!1),[ke]),at=pt(()=>{hardResetForResize(),s(e=>e+1)},[s]),lt=!("off"!==a||le||ce||de||v||k||C||N||b||E||T||P||M||A||R||L||O||D||$||Ue||i),ut=I$(te),gt=ut?ut.getEffort():null;return it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(ZF,{staticKey:o,feed:Je,showHeader:!0,expandedToolOutput:"off"!==a,currentModel:U,currentEffort:gt,currentProvider:F,hiddenCount:Qe}),i&&it.createElement(FU,{onComplete:ie,autoLearn:l}),c&&it.createElement(TasteSkipMessage,null),u&&it.createElement(ZdrPausedMessage,null),m&&it.createElement(ModelNoticeMessage,{text:m}),t.map(e=>e.metadata?.isAgent?it.createElement(tU,{key:e.id,entry:e}):it.createElement(Ze,{key:e.id,marginBottom:1,width:"90%"},it.createElement(FeedEntryView,{entry:e,expandedToolOutput:"off"!==a}))),it.createElement(RetryMessage,{attempt:p}),"off"===a&&!i&&!ze&&it.createElement(TodoPanel,{active:r}),de,ce,le,"off"!==a&&it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},"─".repeat(He))),it.createElement(Ze,{paddingRight:1},it.createElement(et,{backgroundColor:FR.BG,color:FR.FG,bold:!0},`${ML}DETAILED TRANSCRIPT${ML}`),it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{bold:!0},"ctrl+o"),it.createElement(et,{color:LR.DIM}," to toggle"),it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{bold:!0},BE?"ctrl+y":"ctrl+e"),it.createElement(et,{color:LR.DIM}," ","to"," ","limited"===a?"show all":"collapse"),it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{bold:!0},"esc"),it.createElement(et,{color:LR.DIM}," to exit"))),lt&&it.createElement(it.Fragment,null,it.createElement(BackgroundTasksPanel,{onExpandedChange:Ve}),it.createElement(TodosManagerPanel,{sessionId:te,onExpandedChange:Ke}),it.createElement(UF,{queuedMessages:n,sessionId:te,isProcessing:r,processingStartedAt:qe.current,executionState:ee,status:_,input:g,setInput:h,onSubmit:ne,showFileList:S,setShowFileList:w,fileSearchQuery:f,setFileSearchQuery:y,onCommand:re,outputTokens:Q,contextUsage:J,tasteLearningOn:X,shareInfo:B,showShareNotification:W,unshareNotificationMessage:H,updateStatus:G,updateFailedInfo:V,creditWarning:z,currentProvider:F,currentModel:U,showProviderInfo:j,permissionMode:K,onToggleAutoAccept:oe,hintMessage:q,historyManager:Z.current,pendingExitKey:Y,onResetPendingExitKey:se,onDoubleEscapeEmpty:ae,retryAttempt:p,onAltP:ot,renderKey:o,inputActive:!Ge&&!ze,inactiveHint:ze?"Todos focused · ↑/↓ to select · c to complete · x to remove · a all done · Esc to go back to feed":void 0})),v&&it.createElement(Ze,{marginY:1},it.createElement(CU,{onSelect:Me,onCancel:xe,sessionId:te})),k&&it.createElement(Ze,{marginY:1},it.createElement(V_,{onSelect:Ie,onCancel:Ae,currentModel:U,currentProvider:F,refreshBanner:at,sessionId:te})),C&&it.createElement(Ze,{marginY:1},it.createElement(mU,{currentModel:U,sessionId:te,onClose:st,refreshBanner:at})),Ue&&it.createElement(Ze,{marginY:1},it.createElement(OU,{onCancel:We})),O&&it.createElement(Ze,{marginY:1},it.createElement(fF,{onSelect:Re,onCancel:Le})),D&&it.createElement(Ze,{marginY:1},it.createElement(jU,{onSelect:Oe,onCancel:De})),$&&it.createElement(Ze,{marginY:1},it.createElement(rW,{remoteActive:void 0!==getActiveRemote(),onSelect:$e,onCancel:Ne})),T&&it.createElement(Ze,{marginY:1},it.createElement(lF,{onCancel:Xe})),b&&it.createElement(Ze,{marginY:1},it.createElement(HF,{onClose:tt})),E&&it.createElement(Ze,{marginY:1},it.createElement(WF,{onClose:nt,mcp:I$(te)?.mcp})),P&&I$(te)&&it.createElement(Ze,{marginY:1},it.createElement(EU,{checkpoints:[...I$(te).listCheckpoints()],onSelect:ue,onCancel:me})),M&&I$(te)&&it.createElement(Ze,{marginY:1},it.createElement(AU,{tree:I$(te).getSessionTree(),currentLeafId:I$(te).getSessionLeafId(),initialFilterMode:x,branchSummarySkipPrompt:I,onSelect:pe,onAbortSummary:fe,onCancel:ge,onLabelChange:he})),N&&it.createElement(Ze,{marginY:1},it.createElement(N.Component,{onSuccess:_e,onCancel:Fe})),A&&it.createElement(Ze,{marginY:1},it.createElement(jF,{onComplete:ye,onCancel:Se})),L&&it.createElement(Ze,{marginY:1},it.createElement(U_,{onClose:rt})))},"MainView"));function useFeatureModelCatalog(){const[e,t]=ct(()=>getCachedBillingContext());ut(()=>{if(e)return;let n=!0;return getBillingContext().then(e=>{n&&t(e)}),()=>{n=!1}},[e]);const n=useCustomModelsReady(),r=mt(()=>buildCatalogModelPickerGroups(),[n]),o=mt(()=>filterModelPickerGroupsByPlan({groups:r,billing:e}),[r,e]),s=mt(()=>flattenModelPickerGroups(o).map(e=>({id:e.model.id,label:getModelDisplayName(e.model.id)})),[o]);return{groups:o,catalog:s,resolved:null!==e}}Vt(),Vt(),PR(),Vt(),PR(),__name(useFeatureModelCatalog,"useFeatureModelCatalog"),Vt(),PR();var sW=["Listing only models with a zero-data-retention upstream."];function wrappedRowCount(e){const t=Math.max(1,e.width),n=e.text.split(/\s+/).filter(Boolean);if(0===n.length)return 1;let r=1,o=0;for(const e of n){if(e.length>t){o>0&&(r+=1),r+=Math.ceil(e.length/t)-1,o=e.length%t||t;continue}const n=0===o?e.length:e.length+1;o+n<=t?o+=n:(r+=1,o=e.length)}return r}function zdrBannerRowCount(e){return sW.reduce((t,n)=>t+wrappedRowCount({text:n,width:e}),0)+1}function narrowGroups(e){return e.groups.map(t=>({...t,models:t.models.filter(e.accepts)})).filter(e=>e.models.length>0)}__name(wrappedRowCount,"wrappedRowCount"),__name(zdrBannerRowCount,"zdrBannerRowCount"),__name(narrowGroups,"narrowGroups");var aW=__name(({featureLabel:e,defaultLabel:t,currentModelId:n,modelFilter:r,onPick:o,onBack:s})=>{const[a,i]=ct(""),{groups:l,resolved:c}=useFeatureModelCatalog(),d=isCmdZdrEnabled(),u=mt(()=>r||d?narrowGroups({groups:l,accepts:__name(e=>!(r&&!r(e)||d&&!modelSupportsZdr(e.id)),"accepts")}):l,[l,r,d]),m=mt(()=>filterModelPickerGroups(u,a),[u,a]),p=mt(()=>getModelLabelColumnWidth(u.flatMap(e=>e.models),{showDefaultBadge:!1}),[u]),g=mt(()=>[{kind:"reset"},...flattenModelPickerGroups(m).map(e=>({kind:"model",providerId:e.providerId,model:e.model}))],[m]),h=mt(()=>{if(!n)return 0;const e=g.findIndex(e=>"model"===e.kind&&e.model.id===n);return e>=0?e:0},[g,n]),{cursor:f}=useListNavigation({items:g,initialIndex:h,searchCursorIndex:1,searchQuery:a,onSearchChange:i,onSelect:__name(e=>{c&&o("reset"===e.kind?void 0:e.model.id)},"onSelect"),onCancel:s}),[y,S]=ct(0),w=useTerminalHeight(),v=useTerminalWidth(),k=w-1,C=d?zdrBannerRowCount(v):0,b=Math.max(4,k-13-C-2*m.length);ut(()=>{S(e=>clampScrollOffset({cursor:f,total:g.length,maxVisible:b,currentOffset:e}))},[f,g.length,b]);const E=y,T=y+b,P=0===E,M=windowModelGroups({groups:m,firstSectionBase:1,windowStart:E,windowEnd:T}),x=g.length>b;return it.createElement(RO,{title:`${e} › select model`,subtitle:it.createElement(it.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:it.createElement(et,{italic:!0,color:LR.DIM},"type to search · ↑/↓ navigate · enter select",a?" · esc to clear":" · esc back")},d&&it.createElement(Ze,{marginBottom:1,flexDirection:"column"},sW.map(e=>it.createElement(et,{key:e,color:LR.YELLOW},e))),it.createElement(Ze,{marginBottom:2,flexDirection:"column",width:"100%"},it.createElement(kL,{query:a,resultCount:a?g.length-1:void 0,placeholder:"Type to search models..."})),c?it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"column"},P&&it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{bold:!0,dimColor:!0},"Default"),it.createElement(Ze,null,it.createElement(et,{backgroundColor:0===f?tL:void 0,color:n?LR.WHITE:LR.GREEN},t," "),!n&&it.createElement(et,{color:LR.GREEN},ft.tick))),M.map(({group:e,groupWindow:t},r)=>it.createElement(Ze,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:0!==r||P?1:0},it.createElement(et,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>it.createElement(W_,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===f,isCurrent:r.id===n,showProviderLabel:!1,showDefaultBadge:!1,labelColumnWidth:p}))))),x&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",E+1,"–",Math.min(T,g.length)," of"," ",g.length,E>0?" · ↑ more":"",T<g.length?" · ↓ more":""))):it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},"Loading available models…")))},"FeatureModelPicker"),iW="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===Tp}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 lW=__name(({onClose:e,staticKey:t,loadTasteStatus:n,onShowTasteLearningInFeedChange:r})=>{const[o,s]=ct([]),a=isByok({model:getConfiguredModel()}),[i,l]=ct(!0),[c,d]=ct(""),[u,m]=ct(null),{catalog:p}=useFeatureModelCatalog(),g=pt(()=>listConfigSettings({modelCatalog:p,isByok:isByok}).then(e=>s(e)),[p]);ut(()=>{let e=!0;return listConfigSettings({modelCatalog:p,isByok:isByok}).then(t=>{e&&s(t)}).finally(()=>{e&&l(!1)}),()=>{e=!1}},[p]);const h=mt(()=>filterConfigSettings({settings:o,query:c}),[o,c]),f=mt(()=>o.reduce((e,t)=>Math.max(e,t.label.length),0)+2,[o]),y=__name((e,t)=>{"theme"!==e.id||"string"!=typeof t?"taste-learning"!==e.id&&e.id!==Tp?e.id===bp&&"boolean"==typeof t&&r(t):n():applyTuiTheme(resolveCliTheme(t))},"applyLiveSideEffect"),S=__name(async e=>{if(e.featureModelKey)return void m(e);const t=nextSettingValue(e),n=o;s(n=>n.map(n=>n.id===e.id?{...n,currentValue:t}:n));try{await updateConfigSetting({id:e.id,value:t}),y(e,t)}catch{s(n)}},"selectSetting"),w=__name(async(e,t)=>{try{await updateConfigSetting({id:e.id,value:t??Lp}),await g()}catch{}m(null)},"pickFeatureModel"),{cursor:v,error:k,setError:C}=useListNavigation({items:[...h],onSelect:__name(e=>{S(e)},"onSelect"),onReset:__name(e=>{b(e)},"onReset"),onCancel:e,searchQuery:c,onSearchChange:d,isActive:!i&&null===u,validate:__name(e=>a&&isTasteRow(e)?iW:e.locked?`${e.label} is locked by settings.local.json — edit that file to change it.`:null,"validate")}),b=__name(async e=>{if(a&&isTasteRow(e))return void C(iW);if(e.locked)return void C(`${e.label} is locked by settings.local.json — edit that file to change it.`);if(e.currentValue===e.defaultValue)return void C(`${e.label} is already at its default.`);if(e.featureModelKey){try{await updateConfigSetting({id:e.id,value:e.defaultValue}),await g()}catch{}return}const t=o;s(t=>t.map(t=>t.id===e.id?{...t,currentValue:e.defaultValue}:t));try{await updateConfigSetting({id:e.id,value:e.defaultValue}),y(e,e.defaultValue)}catch{s(t)}},"resetSetting"),E=useTerminalWidth(),T=h[v],P=mt(()=>T?clampDescriptionLines({text:T.description,width:Math.max(20,E-2),maxLines:2}):[],[T,E]);if(u?.featureModelKey){const e=mp.find(e=>e.key===u.featureModelKey),t="string"==typeof u.currentValue&&u.currentValue!==Lp?u.currentValue:void 0;return it.createElement(aW,{featureLabel:u.label,defaultLabel:e?getFeatureDefaultLabel({meta:e,getModelDisplayName:getModelDisplayName,zdrEnabled:isCmdZdrEnabled()}):"",currentModelId:t,modelFilter:"vision"===u.featureModelKey?e=>modelSupportsVision(e.id):void 0,onBack:()=>m(null),onPick:e=>{w(u,e)}})}return i?it.createElement(RO,{key:t,title:"Settings",gapAfterHeader:!1},it.createElement(F$,{label:"Loading settings"})):it.createElement(RO,{title:"Settings",footer:it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(Ze,{flexDirection:"column",height:2,width:"100%"},P.map((e,t)=>it.createElement(et,{key:t,color:LR.DIM,wrap:"truncate-end"},e))),it.createElement(bO,{marginTop:0,hints:["type to filter","↑↓ navigate","enter to change","tab to reset",c?"esc to clear":"esc to close"]}))},it.createElement(Ze,{marginBottom:1,flexDirection:"column",width:"100%"},it.createElement(kL,{query:c,resultCount:c?h.length:void 0,placeholder:"Search settings..."})),0===h.length?it.createElement(Ze,{marginY:1},it.createElement(et,{color:LR.GRAY},'No settings match "',c,'"')):it.createElement(Ze,{flexDirection:"column"},h.map((e,t)=>{const n=t===v?tL:void 0,r=!c&&startsNewGroup(h,t);return it.createElement(it.Fragment,{key:e.id},r&&it.createElement(Ze,{marginTop:0===t?0:1},it.createElement(et,{color:LR.DIM,bold:!0},e.group)),it.createElement(Ze,null,it.createElement(et,{color:e.locked||a&&isTasteRow(e)?LR.DIM:LR.WHITE,backgroundColor:n},e.label.padEnd(f)),it.createElement(et,{color:e.locked||a&&isTasteRow(e)?LR.DIM:LR.GREEN,backgroundColor:n},formatSettingValue(e)),(e.locked||a&&isTasteRow(e))&&it.createElement(et,{color:LR.DIM,backgroundColor:n},a&&isTasteRow(e)?" (unavailable on BYOK)":" (locked by settings.local.json)")))})),k&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.GRAY},k)))},"SettingsConfig");function SettingsConfigView({staticKey:e,onClose:t,loadTasteStatus:n,onShowTasteLearningInFeedChange:r}){return it.useEffect(()=>{hardResetForResize()},[]),it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(lW,{onClose:t,staticKey:e,loadTasteStatus:n,onShowTasteLearningInFeedChange:r})))}function categoryColor(e){return isFatalWarningCategory(e)?LR.RED:LR.YELLOW}__name(SettingsConfigView,"SettingsConfigView"),Vt(),Vt(),PR(),Vt(),Vt(),PR(),__name(categoryColor,"categoryColor");var cW=formatSkillWarningsAsMarkdown;async function copyAllWarnings(e,t){try{const{writeClipboardText:n}=await Promise.resolve().then(()=>(PR(),TR));if(!await n(cW(e)))throw new Error("clipboard unavailable");const r=e.length;t({text:`Copied ${r} issue${1===r?"":"s"} to clipboard`,color:LR.GREEN})}catch{t({text:"Clipboard write failed",color:LR.YELLOW})}}__name(copyAllWarnings,"copyAllWarnings");var dW=__name(({warnings:e,onClose:t,isActive:n=!0})=>{const r=groupWarnings(e),o=e.length>0,[s,a]=ct(null),i=dt(null),l=dt(!0);ut(()=>()=>{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 ot((n,r)=>r.escape||" "===n&&o?(UL(),void t()):void("c"===n&&o&&copyAllWarnings(e,c)),{isActive:n}),it.createElement(Ze,{flexDirection:"column",paddingX:0,width:"100%"},it.createElement(Ze,null,it.createElement(et,{color:OR,bold:!0},"Skills"," "),it.createElement(et,{color:LR.DIM},"› "),it.createElement(et,{color:OR,bold:!0},"Skipped"," "),it.createElement(et,{color:LR.WHITE},e.length)),o&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},"Press c to copy all issues")),o?it.createElement(Ze,{flexDirection:"column"},r.map(e=>it.createElement(Ze,{key:e.category,flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,{color:categoryColor(e.category)},e.category)),e.items.map(e=>it.createElement(Ze,{key:e.path,flexDirection:"column",marginBottom:1},it.createElement(Ze,{paddingLeft:2},it.createElement(yL,{url:g(e.path).href,text:skillIdentifier(e.path),color:LR.WHITE})),it.createElement(Ze,{paddingLeft:4},it.createElement(et,{color:LR.WHITE},e.reason))))))):it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"No issues — every skill loaded.")),s&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:s.color},s.text)),it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(et,{color:LR.DIM},o?"c copy all issues · esc back to skills":"esc back to skills")))},"SkillsConfigIssues"),uW=[],mW=__name(({warnings:e=uW,onClose:t})=>{const[n,r]=ct("list");return ot((o,s)=>{"list"===n&&(s.escape&&t?t():" "===o&&!s.ctrl&&!s.meta&&e.length>0&&r("issues"))},{isActive:"list"===n}),"issues"===n?it.createElement(dW,{warnings:e,onClose:()=>r("list"),isActive:!0}):it.createElement(Ze,{flexDirection:"column",paddingX:0,width:"100%"},it.createElement(Ze,null,it.createElement(et,{color:OR,bold:!0},"Skills"),e.length>0&&it.createElement(it.Fragment,null,it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:LR.YELLOW},e.length," skipped"))),it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},"No skills found")),it.createElement(et,{color:LR.DIM},"Create skills in:"),it.createElement(et,{color:LR.DIM}," ","~/",".commandcode","/","skills","/ (user)"),it.createElement(et,{color:LR.DIM}," ","~/.agents/","skills","/ (user, .agents)"),it.createElement(et,{color:LR.DIM}," ",".commandcode","/","skills","/ (project)"),it.createElement(et,{color:LR.DIM}," ",".agents/","skills","/ (project, .agents)"),it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},e.length>0&&"space to view issues · ","Press ",it.createElement(et,{bold:!0},"Esc")," to close")))},"SkillsConfigEmpty");Vt();var pW=__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");Vt();var gW=__name(({title:e,subtitle:t,skills:n,baseIndex:r,cursor:o,disabled:s})=>it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(Ze,null,it.createElement(et,{color:HR,bold:!0},e," "),it.createElement(et,{color:HR},t)),n.map((e,t)=>{const n=r+t===o,a=s.has(e.label),i=n?tL:void 0;return it.createElement(Ze,{key:e.filePath},it.createElement(et,{color:a?LR.DIM:LR.GREEN,backgroundColor:i},a?"[off] ":"[on] "),it.createElement(et,{color:a?LR.DIM:LR.WHITE,backgroundColor:i},e.label),e.fromAgents&&it.createElement(et,{color:LR.DIM,backgroundColor:i}," [.agents]"),it.createElement(et,{color:LR.DIM,backgroundColor:i}," · ~",e.estimatedTokens," tokens "))})),"SkillSection"),hW=__name(({onClose:e})=>{const[t,n]=ct([]),[r,o]=ct([]),[s,a]=ct(!0),[i,l]=ct(null),[c,d]=ct(""),[u,m]=ct(new Set),[p,g]=ct(new Map),[h,f]=ct(!1),[y,S]=ct(null),[w,v]=ct("list"),[k,C]=ct(0),b=useTerminalHeight(),E=dt(!1);ut(()=>{__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=mt(()=>filterSkillPickerRowsForQuery({rows:t,searchQuery:c}),[t,c]),P=T.sections.project,M=T.sections.user,x=T.sections.bundled,I=T.rows,A=b-1,R=(P.length>0?1:0)+(M.length>0?1:0)+(x.length>0?1:0),L=Math.max(4,A-14-2*R),O=__name(async e=>{if(E.current)return;const t=getSkillTogglePolicy({skillName:e.label,disabled:u,disabledScopes:p,noProjectRoot:h});if(!t.allowed)return void S(t.notice);E.current=!0;const n=new Set(u);t.enabling&&n.delete(e.label),t.enabling||n.add(e.label),m(n),S(null);try{const n=await setCommandSkillEnabled(e.label,t.enabling),r=new Map(p);t.enabling&&r.delete(e.label),t.enabling||r.set(e.label,n),g(r),S(getSkillPickerNoProjectWriteNotice(n))}catch(e){m(u),S(`Failed to save: ${e instanceof Error?e.message:String(e)}`)}finally{E.current=!1}},"toggleSkill");ut(()=>{"issues"===w&&d("")},[w]);const D="list"===w&&t.length>0,{cursor:$}=useListNavigation({items:I,onSelect:O,onCancel:e,searchQuery:c,onSearchChange:d,initialIndex:0,isActive:D});if(ut(()=>{C(e=>clampScrollOffset({cursor:$,total:I.length,maxVisible:L,currentOffset:e}))},[$,I.length,L]),ot((t,n)=>{if(!n.tab)return;const r=I[$];r&&(async()=>{try{await Rt([{file:r.filePath,line:1}]),e()}catch(e){if(e instanceof Error&&e.message.includes("$EDITOR environment variable"))return void l(pW());l(e instanceof Error?e.message:"Failed to open skill in editor")}})()},{isActive:D}),ot((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 it.createElement(RO,{title:"Skills",gapAfterHeader:!1},it.createElement(et,{color:LR.DIM},"Loading skills..."));if(i)return it.createElement(RO,{title:"Skills",titleColor:LR.RED,gapAfterHeader:!1,footer:it.createElement(et,{italic:!0,color:LR.DIM},"Press ",it.createElement(et,{bold:!0},"Esc")," to close")},it.createElement(et,{color:LR.DIM},i));if(0===t.length)return it.createElement(mW,{warnings:r,onClose:e});if("issues"===w)return it.createElement(dW,{warnings:r,onClose:()=>v("list"),isActive:!0});const N=t.filter(e=>u.has(e.label)).length,_=k,F=k+L,U=sliceSectionForWindow({section:P,sectionBase:0,windowStart:_,windowEnd:F}),j=sliceSectionForWindow({section:M,sectionBase:P.length,windowStart:_,windowEnd:F}),B=sliceSectionForWindow({section:x,sectionBase:P.length+M.length,windowStart:_,windowEnd:F}),W=I.length>L;return it.createElement(RO,{title:"Skills",titleSuffix:it.createElement(it.Fragment,null," ",t.length," skill",1===t.length?"":"s",N>0&&it.createElement(it.Fragment,null,it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:LR.YELLOW},N," off")),r.length>0&&it.createElement(it.Fragment,null,it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:LR.YELLOW},r.length," skipped"))),subtitle:getSkillPickerNoProjectNotice(h),footer:it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{italic:!0,color:LR.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"),it.createElement(et,{color:LR.DIM},"add skills:"," ",it.createElement(et,{color:LR.CYAN},getBinaryCommand()," skills add ","<owner/repo>")))},it.createElement(Ze,{marginBottom:1,flexDirection:"column",width:"100%"},it.createElement(kL,{query:c,resultCount:c?I.length:void 0,placeholder:"Type to search skills..."})),0===I.length?it.createElement(Ze,{marginY:1},it.createElement(et,{color:LR.GRAY},'No skills match "',c,'"')):it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"column"},U.rows.length>0&&it.createElement(gW,{title:"Project skills",subtitle:"(.commandcode/skills or .agents/skills)",skills:U.rows,baseIndex:U.baseIndex,cursor:$,disabled:u}),j.rows.length>0&&it.createElement(gW,{title:"User skills",subtitle:"(~/.commandcode/skills or ~/.agents/skills)",skills:j.rows,baseIndex:j.baseIndex,cursor:$,disabled:u}),B.rows.length>0&&it.createElement(gW,{title:"Bundled skills",subtitle:"(ships with Command Code)",skills:B.rows,baseIndex:B.baseIndex,cursor:$,disabled:u})),W&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",_+1,"–",Math.min(F,I.length)," of"," ",I.length,_>0?" · ↑ more":"",F<I.length?" · ↓ more":""))),y&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.YELLOW},y)))},"SkillsConfig");function SkillsConfigView({staticKey:e,onClose:t}){return it.useEffect(()=>{hardResetForResize()},[]),it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(hW,{onClose:t,staticKey:e})))}__name(SkillsConfigView,"SkillsConfigView"),Vt(),Vt(),PR();var fW=[{kind:"scope",scope:"project",label:"This project"},{kind:"scope",scope:"global",label:"User"},{kind:"feed",label:"Show in feed"}],yW=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=ct(!0),[s,a]=ct(void 0),[i,l]=ct(void 0),[c,d]=ct(!0),[u,m]=ct(!0),p=isProjectTasteToggleLocked(i),g=pt(async()=>{try{const[e,t]=await Promise.all([getTasteLearningSettings(),getShowTasteLearningInFeed()]);o(e.global),a(e.project),l(e.projectSource),d(t)}catch{}},[]);ut(()=>{g().finally(()=>m(!1))},[g]);const h=__name(async(e,n,r)=>{e();try{await r(),t?.(),await g()}catch(e){n()}},"persist"),f=isByok({model:getConfiguredModel()}),y=__name(e=>{if(f)return;const t=resolveTasteScopeToggle({scope:e.scope,globalEnabled:r,projectOverride:s,projectSource:i});if("locked"===t.kind)return;if("global"===t.scope)return h(()=>o(t.value),()=>o(!t.value),()=>setTasteLearning({tasteLearning:t.value,scope:"global"}));const n=s;return h(()=>a(t.value),()=>a(n),()=>setTasteLearning({tasteLearning:t.value,scope:"project"}))},"toggleRow"),S=__name(e=>{if(f)return;const t=resolveTasteScopeReset({scope:e.scope,globalEnabled:r,projectOverride:s,projectSource:i});if("noop"===t.kind)return;if("save-global"===t.kind)return h(()=>o(!0),()=>o(!1),()=>setTasteLearning({tasteLearning:!0,scope:"global"}));const n=s;return h(()=>a(void 0),()=>a(n),()=>clearProjectTasteLearning())},"resetRow"),w=__name(()=>{if(f)return;const e=!c;return h(()=>d(e),()=>d(!e),()=>setShowTasteLearningInFeed({show:e}))},"toggleFeed"),v=__name(()=>{if(!f&&!c)return h(()=>d(!0),()=>d(!1),()=>setShowTasteLearningInFeed({show:!0}))},"resetFeed"),k=__name(e=>"feed"===e.kind?w():y(e),"handleToggle"),C=__name(e=>"feed"===e.kind?v():S(e),"handleReset"),{cursor:b}=useListNavigation({items:fW,onSelect:__name(e=>{k(e)},"onSelect"),onReset:__name(e=>{C(e)},"onReset"),onCancel:e,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,isActive:!u});if(u)return it.createElement(RO,{key:n,title:"Taste Learning",gapAfterHeader:!1},it.createElement(F$,{label:"Loading configuration"}));const E=__name(e=>!f&&("feed"===e.kind?c:"project"===e.scope?s??r:r),"valueFor");return it.createElement(RO,{key:n,title:"Taste Learning",subtitle:f?gg:"Learn from your interactions.",hint:f?"esc to close":"↑/↓ navigate · enter to toggle · r reset to default · esc to close"},fW.map((e,t)=>{const n=t===b,r=E(e),o=f||"scope"===e.kind&&"project"===e.scope&&p;return it.createElement(Ze,{key:"feed"===e.kind?"feed":e.scope,marginTop:"feed"===e.kind?1:0},it.createElement(et,{color:n?LR.CYAN:LR.GRAY},n?`${ft.pointer} `:" "),it.createElement(et,{color:n?LR.CYAN:LR.WHITE},e.label.padEnd(16)),it.createElement(et,{color:r?LR.GREEN:LR.DIM},r?"enabled":"disabled"),o?it.createElement(et,{color:LR.DIM}," ",f?"(unavailable on BYOK)":"(set in settings.local.json)"):null)}),it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(et,{color:LR.DIM},'"Show in feed" only hides the notices — learning stays on.'),it.createElement(et,{color:LR.DIM},"Taste data stored in .commandcode/taste/taste.md"),p?it.createElement(et,{color:LR.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 it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(yW,{onClose:t,onSettingsChange:n,staticKey:e})))}function OrgLimitMeter({row:e,width:t,marginTop:n}){const r=e.reached?LR.RED:getUsageColor(e.pct),o=buildBlockBar({percentage:e.pct,width:t});return it.createElement(Ze,{flexDirection:"column",marginTop:n},it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},`${e.label} `),it.createElement(et,{color:r},o.filled),it.createElement(et,{color:HR},o.empty),it.createElement(et,{bold:!0,color:r},` ${Math.round(e.pct)}%`)),it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},`${" ".repeat(e.label.length+1)}${e.detail}`)))}function OrgLimitsSection({limits:e,width:t,now:n}){const r=projectOrgSpendLimitRows({limits:e,now:n});return 0===r.length?null:it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.DIM},"Spend limits"),r.map((e,n)=>it.createElement(OrgLimitMeter,{key:e.label,row:e,width:t,marginTop:0===n?0:1})))}function fetchUsageData2(){return fetchUsageData({getAuthKey:getAuthKey2,getApiBaseUrl:getApiBaseUrl,createRequest:__name(({baseUrl:e})=>createApiClient({baseUrl:e}),"createRequest")})}function getAuthKey2(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function WindowLimitMeter({label:e,used:t,cap:n,resetAt:r,width:o,now:s}){const 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 it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},e.padEnd(7)," "),it.createElement(et,{color:i},l.filled),it.createElement(et,{color:HR},l.empty),it.createElement(et,{bold:!0,color:i},` ${Math.round(a)}%`),it.createElement(et,{color:LR.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?LR.RED:"warning"===t?LR.YELLOW:void 0}__name(TasteConfigView,"TasteConfigView"),Vt(),Vt(),PR(),Vt(),PR(),Vt(),__name(OrgLimitMeter,"OrgLimitMeter"),__name(OrgLimitsSection,"OrgLimitsSection"),__name(fetchUsageData2,"fetchUsageData"),__name(getAuthKey2,"getAuthKey"),__name(WindowLimitMeter,"WindowLimitMeter"),__name(getProgressBarWidth,"getProgressBarWidth"),__name(getDaysColor,"getDaysColor");var SW=__name(({plan:e,status:t})=>it.createElement(Ze,{marginBottom:0},it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:LR.BLUE,color:"#f4f4f4",bold:!0},`${ML}USAGE${ML}`)),e&&it.createElement(it.Fragment,null,it.createElement(et,null," "),it.createElement(et,{color:LR.GRAY},`${e.name} Plan`)),t&&it.createElement(it.Fragment,null,it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:"active"===t?LR.GREEN:LR.YELLOW},t))),"UsageBadge"),wW=__name(()=>it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.YELLOW},"Running low? Keep going:"),it.createElement(et,null,it.createElement(et,{bold:!0},"/extra "),it.createElement(et,{color:LR.DIM},"pay-as-you-go at API cost, zero markup")),it.createElement(et,null,it.createElement(et,{bold:!0},"/upgrade "),it.createElement(et,{color:LR.DIM},"bigger limits"))),"ExtraUsageCallout"),vW=__name(({showRetry:e})=>it.createElement(Ze,{marginTop:1},it.createElement(kO,null,e&&it.createElement(it.Fragment,null,it.createElement(CO,null,"r")," to retry · "),"Press ",it.createElement(CO,null,"Esc")," to close")),"UsageFooter"),kW=__name(({onClose:e})=>{const[t,n]=ct("loading"),[r,o]=ct(null),[s,a]=ct(!1),i=getProgressBarWidth({terminalWidth:useTerminalWidth()}),l=pt(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=it.useRef(null);ot((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)}}),ut(()=>{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 it.createElement(Ze,{flexDirection:"column",paddingX:0,width:"100%"},it.createElement(SW,{plan:m,status:u?.status??null}),it.createElement(F$,null),it.createElement(vW,null));if("error"===t)return it.createElement(Ze,{flexDirection:"column",paddingX:0,width:"100%"},it.createElement(SW,{plan:m,status:u?.status??null}),it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},s?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),it.createElement(vW,{showRetry:!s}));if(!r)return null;const p=d?.hasBillingData??!1,g=d?.usageUrl??null,h=d?.orgLimits??[],f=d?.now??Date.now();if(!p)return it.createElement(Ze,{flexDirection:"column",paddingX:0,width:"100%"},it.createElement(SW,{plan:m,status:u?.status??null}),it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(W$,{message:"No billing data found."}),g&&it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},"Visit "),it.createElement(yL,{url:g,text:"Studio",color:LR.CYAN}),it.createElement(et,{color:LR.DIM}," for usage details."))),it.createElement(OrgLimitsSection,{limits:h,width:i,now:f}),it.createElement(vW,null));const y=d?.windowLimits??null,S=d?.sandboxMinutes??null,w=!0===d?.sandboxAccess&&null!==S&&(S.limitMinutes>0||S.usedMinutes>0),v=d?.summary??null,k=d?.credits,C=k?.usagePercent??0,b=Boolean(k?.hasCreditsInfo),E=(k?.purchasedRemaining??0)+(k?.freeRemaining??0),T=d?.daysLeft??null,P=getDaysColor(T),M=b&&shouldNudgeExtraUsage({usagePercent:C,windows:[y?.fiveHour,y?.weekly]}),x=getUsageColor(C),I=buildBlockBar({percentage:C,width:i});return it.createElement(Ze,{flexDirection:"column",paddingX:0,width:"100%"},it.createElement(Ze,{marginBottom:1},it.createElement(SW,{plan:m,status:u?.status??null})),b?it.createElement(Ze,null,it.createElement(et,{color:x},I.filled),it.createElement(et,{color:HR},I.empty),it.createElement(et,{bold:!0,color:x},` ${Math.round(C)}% used`)):it.createElement(et,{color:LR.DIM},"Plan details unavailable"),b&&it.createElement(Ze,null,v&&it.createElement(it.Fragment,null,it.createElement(et,null,v.totalCount.toLocaleString()),it.createElement(et,{color:LR.DIM},"billing-period"===v.periodBasis?" requests this month":" requests")),null!==T&&it.createElement(it.Fragment,null,v&&it.createElement(et,{color:LR.DIM}," · "),0===T?it.createElement(et,{color:P},"renews today"):it.createElement(it.Fragment,null,it.createElement(et,{color:P},`${T} day${1===T?"":"s"}`),it.createElement(et,{color:LR.DIM}," to renew"))),E>0&&it.createElement(it.Fragment,null,(v||null!==T)&&it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:LR.DIM},"Extra Credits: "),it.createElement(et,null,formatCredits(E)))),y?.limited&&it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.DIM},"Usage limits"),y.fiveHour&&it.createElement(WindowLimitMeter,{label:"5-hour",used:y.fiveHour.used,cap:y.fiveHour.cap,resetAt:y.fiveHour.resetAt,width:i,now:f}),y.weekly&&it.createElement(Ze,{marginTop:y.fiveHour?1:0,flexDirection:"column"},it.createElement(WindowLimitMeter,{label:"Weekly",used:y.weekly.used,cap:y.weekly.cap,resetAt:y.weekly.resetAt,width:i,now:f}))),M&&it.createElement(wW,null),w&&it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.DIM},"Sandbox minutes"),S.limitMinutes>0?it.createElement(WindowLimitMeter,{label:"Month",used:S.usedMinutes,cap:S.limitMinutes,resetAt:S.resetAt,width:i,now:f}):it.createElement(et,null,`${S.usedMinutes} min used this month, billed per minute`)),it.createElement(OrgLimitsSection,{limits:h,width:i,now:f}),g&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Full breakdown at "),it.createElement(yL,{url:g,text:d?.usageUrlDisplay??g,color:LR.CYAN})),it.createElement(vW,null))},"UsageOverlay");function UsageView({staticKey:e,onClose:t}){return it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(kW,{onClose:t})))}__name(UsageView,"UsageView"),Vt(),PR(),Vt(),PR(),Vt();var CW="@last";function shortenHomePath(e){const t=H();return e.startsWith(t)?`~${e.slice(t.length)}`:e}__name(shortenHomePath,"shortenHomePath");var bW={approved:{label:`${ft.tick} approved`,color:LR.GREEN},"not-implemented":{label:`${ft.circleDotted} set aside`,color:LR.YELLOW},pending:{label:`${ft.dot} pending`,color:LR.DIM}},EW=createNodeRuntime(),TW={"?":"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:LR.GREEN,bold:!1,italic:!1};const t={color:LR.WHITE,bold:!1,italic:!1};if(!e.style)return t;switch(e.style.role){case"heading":return{color:QR.HEADING,bold:!0,italic:!1};case"code":case"code-fence":return{color:QR.CODE,bold:!1,italic:!1};case"quote":return{color:LR.DIM,bold:!1,italic:!0};case"table":return{color:LR.CYAN,bold:!1,italic:!1};default:return t}}__name(lineStyleProps,"lineStyleProps");var PW=__name(({plan:e,variant:t="browse",fallbackContent:n,onBack:r,onSubmitFeedback:o,onExecute:s,onAutoAccept:a})=>{const[i,l]=ct(null),[c,d]=ct(e.annotations),[u,m]=ct(!1);ut(()=>{u||d(e.annotations)},[e.annotations,u]);const[p,g]=ct({kind:"line",lineNumber:1}),[h,f]=ct(null),y=dt([]),S=mt(()=>shouldCollapsePastedText(),[]),[w,v]=ct(null),[k,C]=ct(null),[b,E]=ct(!1),[T,P]=ct(0),[M,x]=ct(null),I=useTerminalHeight(),A=useTerminalWidth();ut(()=>{__name(async()=>{const t=await readPlanContent({runtime:EW,filePath:e.filePath})??n??null;l(null===t?[]:splitPlanLines(t))},"load")()},[e.filePath,n]);const R=e.version??1;ut(()=>{R<=1||!e.filePath||readPlanVersionSnapshot({runtime:EW,filePath:e.filePath,version:R-1}).then(x).catch(()=>{})},[R,e.filePath]);const L=mt(()=>null!==M&&null!==i?diffPlanChangedLines({previous:M,current:i}):new Set,[M,i]),O=c.length,D=mt(()=>{const e={id:"feedback",label:`Submit review (${O})`,chord:"ctrl+r",color:LR.CYAN,hint:"agent revises the plan, returns it for review"};return"approval"===t?[...O>0?[e]:[],{id:"auto-accept",label:"Approve",chord:"ctrl+a",color:LR.GREEN,hint:O>0?"executes the plan · comments go along as notes":"executes the plan"},{id:"cancel",label:"Cancel",chord:"esc",color:LR.YELLOW,hint:""}]:[...O>0?[e]:[],{id:"execute",label:"Execute plan",chord:"ctrl+e",color:LR.GREEN,hint:"executes the plan as written"},{id:"cancel",label:"Back",chord:"esc",color:LR.YELLOW,hint:""}]},[t,O]),$=mt(()=>h?c.filter(e=>e.line!==h.line):c,[c,h]),N=mt(()=>buildPlanReaderRows({lines:i??[],annotations:$}),[i,$]),_=mt(()=>classifyPlanLines(i??[]),[i]),F=i?.length??0,U=resolvePlanWrapWidth(Math.max(20,A-7-2)),j=mt(()=>buildPlanReaderDisplayRows({rows:N,width:U}),[N,U]),B=getPlanReaderCursorDisplaySpan({displayRows:j,cursor:p}),W=I-1,H=Math.max(4,W-10-7),G=h?1:0,V=-1===B.first?j.length-1:B.first,z=-1===B.last?j.length-1:B.last+G;ut(()=>{P(e=>{const t=clampScrollOffset({cursor:Math.max(0,z),total:j.length+G,maxVisible:H,currentOffset:e});return clampScrollOffset({cursor:Math.max(0,V),total:j.length+G,maxVisible:H,currentOffset:t})})},[V,z,j.length,G,H]),ut(()=>{g(e=>snapPlanReaderCursor({cursor:e,lineCount:F,actions:[]}))},[F]),ut(()=>{g(e=>"action"!==e.kind||D.some(t=>t.id===e.id)?e:{kind:"line",lineNumber:Math.max(1,F)})},[D,F]);const K=__name(t=>{m(!0),d(t),e.filePath&&setPlanAnnotations({runtime:EW,filePath:e.filePath,annotations:t}).catch(()=>C("Failed to save comments to disk"))},"persistAnnotations"),q="line"===p.kind?c.find(e=>e.line===p.lineNumber):void 0,Y=__name(()=>{if(0===c.length||!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:EW,filePath:e.filePath}).catch(()=>{}),K([]),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 K([]),void a?.(t)}K([]),a?.()},"approve"),J=__name(()=>{"approval"===t&&(O>0?v({kind:"approve",choice:"notes"}):Q(!1))},"requestApprove"),X=__name(()=>{O>0&&!e.filePath?v({kind:"cancel"}):r()},"requestCancel"),Z=__name(t=>{"feedback"!==t?"execute"!==t?"auto-accept"!==t?"cancel"===t&&X():J():(s??o)(buildPlanExecutePrompt({title:e.title,filePath:e.filePath||e.fileName})):Y()},"runAction"),ee=__name(()=>{e.filePath?(E(!0),openFileInEditor(e.filePath).then(async()=>{const t=await readPlanContent({runtime:EW,filePath:e.filePath});null!==t&&l(splitPlanLines(t))}).catch(e=>C(e instanceof Error?e.message:"Failed to open the editor")).finally(()=>{E(!1),hardResetForResize()})):C("This plan is not saved to a file yet")},"openExternalEditor"),te=__name(e=>{"line"!==p.kind||p.lineNumber<1||p.lineNumber>F||(y.current=e?[]:q?.pastes??[],f({line:p.lineNumber,value:e||(q?.text??""),hadExisting:void 0!==q}))},"openDraft"),ne=__name(e=>{h&&(K(upsertPlanAnnotation({annotations:c,line:h.line,text:e,createdAt:(new Date).toISOString(),pastes:y.current})),y.current=[],f(null))},"commitDraft"),re=mt(()=>{const e=new Set;for(const t of c)e.add(t.line);for(const t of L)e.add(t);return[...e].sort((e,t)=>e-t)},[c,L]),oe=__name(e=>{if(0===re.length)return;const t="line"===p.kind?p.lineNumber:F+1,n="next"===e?re.find(e=>e>t)??re[0]:[...re].reverse().find(e=>e<t)??re[re.length-1];void 0!==n&&g({kind:"line",lineNumber:n})},"jumpMarked");ot((e,t)=>{t.escape&&f(null)},{isActive:null!==h}),ot((e,t)=>{if(w)if(t.escape)v(null);else if("approve"===w.kind&&(t.leftArrow||t.rightArrow||t.tab))v({kind:"approve",choice:"notes"===w.choice?"original":"notes"});else if(t.return){if("approve"===w.kind)return v(null),void Q("notes"===w.choice);v(null),r()}},{isActive:null!==w}),ot((e,n)=>{if(n.escape)return void X();if(n.upArrow||n.downArrow)return C(null),void g(e=>{if("action"===e.kind){const t=D.findIndex(t=>t.id===e.id);if(n.upArrow){if(t<=0&&F>0)return{kind:"line",lineNumber:F};const n=D[Math.max(0,t-1)];return n?{kind:"action",id:n.id}:e}const r=D[Math.min(D.length-1,t+1)];return r?{kind:"action",id:r.id}:e}if(n.upArrow)return{kind:"line",lineNumber:Math.max(1,e.lineNumber-1)};if(e.lineNumber>=F){const t=D[0];return t?{kind:"action",id:t.id}:e}return{kind:"line",lineNumber:e.lineNumber+1}});if(n.pageUp||n.pageDown)return C(null),void g(e=>"action"===e.kind&&n.pageDown?e:movePlanReaderCursorByPage({displayRows:j,cursor:e,direction:n.pageDown?"down":"up",pageRows:Math.max(1,H-1)}));if(n.home||n.end)return C(null),void(F>0&&g({kind:"line",lineNumber:n.home?1:F}));if(n.leftArrow||n.rightArrow){if("action"!==p.kind)return;const e=D.findIndex(e=>e.id===p.id);if(-1===e)return;const t=n.leftArrow?Math.max(0,e-1):Math.min(D.length-1,e+1),r=D[t];return void(r&&g({kind:"action",id:r.id}))}if(n.ctrl&&"r"===e)return void Y();if(n.ctrl&&"a"===e&&"approval"===t)return void J();if(n.ctrl&&"e"===e&&"browse"===t)return void Z("execute");if(n.ctrl&&"g"===e)return void ee();if(n.ctrl&&"n"===e)return void oe("next");if(n.ctrl&&"p"===e)return void oe("previous");if(n.return)return"action"===p.kind?void Z(p.id):void te("");const r=TW[e];"line"!==p.kind||!r||n.ctrl||n.meta?"line"===p.kind&&e.length>0&&!n.ctrl&&!n.meta&&te(e):K(upsertPlanAnnotation({annotations:c,line:p.lineNumber,text:q?.text===r?"":r,createdAt:(new Date).toISOString()}))},{isActive:null===h&&null===w&&null!==i&&!b});const se=bW[e.status],ae=T,ie=T+H-G,le=j.slice(ae,ie),ce=h?h.hadExisting?"enter to keep · clear + enter removes · esc keep as was":"enter to pin · esc discard":w?"approve"===w.kind?"←/→ choose · enter confirm · esc back":"enter discard · esc back":"action"===p.kind?"↑/↓ choose · enter to run":["type + enter to comment",...re.length>0?["ctrl+n/p jump "+(L.size>0?"changes":"comments")]:[],"quick: ? why x cut ! risky","ctrl+g $EDITOR"].join(" · ");return it.createElement(RO,{title:"approval"===t?`Plan review: ${e.title}`:e.title,titleSuffix:"approval"===t?it.createElement(it.Fragment,null," ","· ",shortenHomePath(e.filePath)||e.fileName," · v",e.version??1):it.createElement(it.Fragment,null," ","· ",shortenHomePath(e.filePath)||e.fileName," · v",e.version??1," ",it.createElement(et,{color:se.color},se.label)),subtitle:"approval"===t?"Review the plan like a PR — type on any line to comment, enter pins it under the line.":void 0,footer:it.createElement(et,{italic:!0,color:LR.DIM},ce)},null===i?it.createElement(et,{color:LR.DIM},"Loading plan..."):0===F?it.createElement(et,{color:LR.DIM},"Plan file is empty or missing on disk."):it.createElement(Ze,{flexDirection:"column"},le.map((e,t)=>{const n=ae+t,{row:r}=e;if("action"===r.kind)return null;if("annotation"===r.kind)return it.createElement(Ze,{key:`annotation-${r.lineNumber}-${n}`},it.createElement(et,{color:LR.DIMMER}," ".repeat(5)),it.createElement(et,{backgroundColor:DR.BADGE_BG,color:DR.BADGE_FG}," ",e.isFirstSegment?"↳ ":" ",e.text," "));const o="line"===p.kind&&p.lineNumber===r.lineNumber,s=lineStyleProps({style:_[r.lineNumber-1],changed:L.has(r.lineNumber)}),a=j[n+1],i=!a||"line"!==a.row.kind||a.row.lineNumber!==r.lineNumber,l=n===ie-1,c=null!==h&&h.line===r.lineNumber&&(i||l);return it.createElement(it.Fragment,{key:`line-${r.lineNumber}-${n}`},it.createElement(Ze,null,it.createElement(et,{color:LR.DIMMER},e.isFirstSegment?String(r.lineNumber).padStart(4," "):" "," "),it.createElement(et,{color:r.hasAnnotation?LR.CYAN:LR.DIMMER},e.isFirstSegment&&r.hasAnnotation?`${ft.bullet} `:" "),it.createElement(et,{color:s.color,bold:s.bold,italic:s.italic,backgroundColor:o?tL:void 0},e.text||" ")),c&&h&&it.createElement(Ze,null,it.createElement(et,{color:LR.CYAN}," ┃ ",ft.bullet," "),it.createElement(TextInput,{value:h.value,onChange:e=>{y.current=prunePlanAnnotationPastes(e,y.current),f(t=>t?{...t,value:e}:t)},onSubmit:ne,placeholder:"Type your comment…",focus:null!==h,stripBracketedPaste:!0,clipboardOnEmptyPaste:!0,collapsePastedText:S,onPasteCollapsed:e=>{y.current=[...y.current,e]}})))})),it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(iL,{dividerColor:LR.DIMMER}),it.createElement(Ze,null,it.createElement(et,{bold:!0,backgroundColor:DR.BADGE_BG,color:LR.WHITE}," REVIEW "),it.createElement(et,{color:LR.DIM},O>0&&` ${O} pending comment${1===O?"":"s"}`,R>1&&` · round ${R}${L.size>0?` · ${L.size} line${1===L.size?"":"s"} changed`:""}`)),w?"approve"===w.kind?it.createElement(Ze,null,it.createElement(et,{bold:!0,color:LR.GREEN},"Approve"," "),it.createElement(et,{color:"notes"===w.choice?LR.WHITE:LR.DIM,backgroundColor:"notes"===w.choice?tL:void 0},"notes"===w.choice?"(•)":"( )"," ","with ",O," comment",1===O?"":"s"," as notes"),it.createElement(et,{color:LR.DIMMER}," "),it.createElement(et,{color:"original"===w.choice?LR.WHITE:LR.DIM,backgroundColor:"original"===w.choice?tL:void 0},"original"===w.choice?"(•)":"( )"," ","original plan · discard comments")):it.createElement(Ze,null,it.createElement(et,{color:LR.YELLOW},"Discard ",O," pending comment",1===O?"":"s"," and exit review?")):D.map(e=>{const t="action"===p.kind&&p.id===e.id;return it.createElement(Ze,{key:e.id},it.createElement(et,{bold:!0,color:e.color,backgroundColor:t?tL:void 0},t?`${ft.pointer} ${e.label} `:e.label),it.createElement(et,{color:LR.DIM}," ",e.chord),e.hint&&it.createElement(et,{color:LR.DIMMER}," ",e.hint))}),k&&it.createElement(et,{color:LR.YELLOW},k)))},"PlanReader"),MW=createNodeRuntime();function PlanApprovalView({staticKey:e,planContent:t,planFilePath:n,onAutoAccept:r,onCancel:o,onSendFeedback:s}){ut(()=>{hardResetForResize()},[]);const[a,i]=ct(null);ut(()=>{n&&listPlans({runtime:MW}).then(e=>i(e.find(e=>e.filePath===n)??null)).catch(()=>{})},[n]);const l=mt(()=>{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 it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(PW,{plan:l,variant:"approval",fallbackContent:t,onBack:o,onSubmitFeedback:s,onAutoAccept:r})))}__name(PlanApprovalView,"PlanApprovalView"),Vt(),Vt(),PR();var xW=Date.now(),IW=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 AW=__name(({sessionId:e,target:t,onClose:n,onSubmitFeedback:r,onExecute:o})=>{const[s,a]=ct([]),[i,l]=ct([]),[c,d]=ct(!0),[u,m]=ct(null),[p,g]=ct("session"),[h,f]=ct(null),[y,S]=ct(""),[w,v]=ct(0),[k,C]=ct(0),b=useTerminalHeight(),E=dt(!1);ut(()=>{__name(async()=>{try{const[n,r]=await Promise.all([listPlans({runtime:IW,sessionId:e,sessionStartMs:xW}),listPlans({runtime:IW})]);if(a([...n]),l([...r]),t&&!E.current)if(E.current=!0,t===CW){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=mt(()=>{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(ut(()=>{v(e=>clampScrollOffset({cursor:A,total:P.length,maxVisible:x,currentOffset:e}))},[A,P.length,x]),ot((e,t)=>{(t.leftArrow||t.rightArrow)&&(g(e=>"session"===e?"all":"session"),v(0))},{isActive:I}),h)return it.createElement(PW,{plan:h,onBack:()=>{f(null),C(e=>e+1)},onSubmitFeedback:r,onExecute:o});if(c)return it.createElement(RO,{title:"Plans",gapAfterHeader:!1},it.createElement(et,{color:LR.DIM},"Loading plans..."));if(u)return it.createElement(RO,{title:"Plans",titleColor:LR.RED,gapAfterHeader:!1,hint:"Esc to close"},it.createElement(et,{color:LR.DIM},u));const R=w,L=w+x,O=P.slice(R,L),D=P.length>x;return it.createElement(RO,{title:"Plans",titleSuffix:it.createElement(it.Fragment,null," ",P.length," plan",1===P.length?"":"s"),subtitle:it.createElement(it.Fragment,null,it.createElement(et,{bold:"session"===p,color:"session"===p?EO:LR.DIM},"This session"),it.createElement(et,{color:LR.DIMMER},` ${ft.triangleLeftSmall} ${ft.triangleRightSmall} `),it.createElement(et,{bold:"all"===p,color:"all"===p?EO:LR.DIM},"All plans")),footer:it.createElement(et,{italic:!0,color:LR.DIM},"type to search · ↑/↓ navigate · ←/→ switch tab · enter to open",y?" · esc to clear":" · esc to close")},it.createElement(Ze,{marginBottom:1,flexDirection:"column",width:"100%"},it.createElement(kL,{query:y,resultCount:y?P.length:void 0,placeholder:"Type to search plans..."})),0===P.length?it.createElement(Ze,{marginY:1},it.createElement(et,{color:LR.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.")):it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"column"},O.map((e,t)=>{const n=R+t===A,r=bW[e.status];return it.createElement(Ze,{key:e.fileName},it.createElement(et,{color:n?MO:LR.GRAY},n?`${ft.pointer} `:" "),it.createElement(et,{bold:n,color:n?MO:LR.WHITE},e.title),it.createElement(et,{color:r.color}," ",r.label),(e.version??1)>1&&it.createElement(et,{color:LR.DIM}," ","v",e.version),e.annotations.length>0&&it.createElement(et,{color:LR.CYAN}," ",e.annotations.length," comment",1===e.annotations.length?"":"s"),it.createElement(et,{color:LR.DIM}," ",formatRelativeTimeShort({timestamp:e.updatedAt})))})),D&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",R+1,"–",Math.min(L,P.length)," of"," ",P.length,R>0?" · ↑ more":"",L<P.length?" · ↓ more":""))))},"PlansScreen");function PlansView({staticKey:e,sessionId:t,target:n,onClose:r,onSubmitFeedback:o,onExecute:s}){return it.useEffect(()=>{hardResetForResize()},[]),it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(AW,{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:LR.DIM,o=e.userRenamed&&e.title?e.title:null;return o?it.createElement(et,{color:n},`${o} `,it.createElement(et,{color:r},`· ${e.forkProvenance}`)):it.createElement(et,{color:r},e.forkProvenance)}__name(PlansView,"PlansView"),Vt(),Vt(),PR(),Vt(),__name(ForkSummary,"ForkSummary");var RW=__name((e,t)=>e.padEnd(t),"padCell"),LW=__name(e=>e instanceof Error&&e.message?e.message:"Unknown error","getActionErrorMessage");function resolveRowColor(e){return e.isDeletePending?LR.RED:e.isCurrentSession?OR:e.isSelected?LR.WHITE:LR.GRAY}function renderRowSummary(e){const{session:t,isSelected:n,nameColor:r}=e;if(t.forkProvenance)return it.createElement(ForkSummary,{session:t,isSelected:n,nameColor:r});const o=getSessionSummary({session:t});return t.userRenamed&&t.title?it.createElement(et,{color:r},o):o}__name(resolveRowColor,"resolveRowColor"),__name(renderRowSummary,"renderRowSummary");var OW=["recent","created","messages"],DW={recent:"Recent",created:"Created",messages:"Messages"};function nextSortMode(e){const t=OW.indexOf(e);return OW[(t+1)%OW.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 $W=__name(({onSelectSession:e,onClose:t,currentSessionId:n})=>{const[r,o]=ct([]),[s,a]=ct(0),[i,l]=ct(0),[c,d]=ct(!0),[u,m]=ct(!1),[p,g]=ct(!1),[h,f]=ct(null),[y,S]=ct(null),[w,v]=ct(""),[k,C]=ct(!1),[b,E]=ct("recent"),[T,P]=ct(!1),[M,x]=ct("list"),[I,A]=ct(null),[R,L]=ct(""),[O,D]=ct(null),[$]=ct(()=>getCurrentGitBranch()),[N]=ct(()=>resolveProjectBaseDir()),_=useTerminalHeight(),F=Math.max(6,_-19),U=pt(async()=>{d(!0);const e=await listCommandSessions();o(e),d(!1)},[]);ut(()=>{U()},[U]),ut(()=>{if(!y)return;const e=setTimeout(()=>S(null),3e3);return()=>clearTimeout(e)},[y]);const j=pt(async e=>{try{const t=getCommandSessionRuntime(),{method:n}=await deleteSessionV3({runtime:t,baseDir:N,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: ${LW(e)}`)}},[U,N]),B=pt(async e=>{const t=I;if(t)try{const n=getCommandSessionRuntime();await renameSessionFile({runtime:n,cwd:n.cwd(),baseDir:N,id:t,name:e}),x("list"),A(null),D(null),await U()}catch(e){D(`Failed to rename session: ${LW(e)}`)}else x("list")},[I,U,N]),W=filterSessionsByBranch({sessions:r,branchFilter:u,currentBranch:$}),H=T?W.filter(e=>e.userRenamed):W,G=sortSessions(w?H.filter(e=>matchesSearch2(e,w)):H,b);if(ut(()=>{a(e=>Math.min(e,Math.max(0,G.length-1)))},[G.length]),ot((r,o)=>{if("rename"===M)return o.escape?(x("list"),void A(null)):void 0;if(p){if(!o.return)return void g(!1);if(G.length>0&&s<G.length){const e=G[s];j(e.id)}}else{if(o.delete||isCtrlKey({inputChar:r,key:o,letter:"d",ctrlCode:4})){if(0===G.length)return;return G[s]?.id===n?void f("Cannot delete the current session"):(f(null),void g(!0))}if(isCtrlKey({inputChar:r,key:o,letter:"r",ctrlCode:18})){if(c)return;const e=G[s];if(!e)return;return D(null),L(e.title??""),A(e.id),void x("rename")}if(isCtrlKey({inputChar:r,key:o,letter:"p",ctrlCode:16}))C(e=>!e);else{if(!isCtrlKey({inputChar:r,key:o,letter:"s",ctrlCode:19}))return isCtrlKey({inputChar:r,key:o,letter:"n",ctrlCode:14})?(P(e=>!e),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 it.createElement(Ze,{flexDirection:"column",paddingLeft:2},it.createElement(F$,{label:"Loading sessions"}));if(0===r.length)return it.createElement(Ze,{flexDirection:"column",paddingLeft:2},it.createElement(W$,{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:$});return it.createElement(RO,{title:"Resume Session",subtitle:`Sort: ${DW[b]} · Name: ${T?"Named":"All"} · Branch: ${u?$??"unknown":"All"}`},it.createElement(Ze,{marginBottom:1,width:"100%"},it.createElement(kL,{query:w,resultCount:w?G.length:void 0,placeholder:"Type to search sessions..."})),it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:HR,bold:!0},RW("#",6),RW("Modified",12),RW("Git Branch",22),RW("Messages",12),"Summary",k?" · Path":"")),0===G.length?it.createElement(Ze,{marginBottom:1},it.createElement(W$,{message:q.text,hint:q.hint})):it.createElement(Ze,{flexDirection:"column"},V.map((e,t)=>{const r=i+t,o=s===r,a=p&&o,l=a?void 0:LR.YELLOW,c=resolveRowColor({isDeletePending:a,isCurrentSession:e.id===n,isSelected:o}),d=truncateString2({text:e.gitBranch||"-",maxChars:20}),u=k?toRelativePath(`${N}/${e.id}.jsonl`):null;return it.createElement(et,{key:e.id,color:c,backgroundColor:o?tL:void 0,bold:o,wrap:"truncate-end"},RW(`${r+1}.`,6),RW(formatRelativeTimeShort({timestamp:e.lastModified}),12),RW(d,22),RW(String(e.messageCount),12),renderRowSummary({session:e,isSelected:o,nameColor:l}),u?it.createElement(et,{color:LR.DIM},` ${u}`):null," ")})),it.createElement(Ze,{marginTop:1}),"rename"===M&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.CYAN},"Rename: "),it.createElement(TextInput,{value:R,onChange:L,onSubmit:B,singleLine:!0,stripBracketedPaste:!0})),O&&it.createElement(Ze,{marginBottom:1},it.createElement(U$,{glyph:!1},O)),K&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.RED},K)),h&&it.createElement(Ze,{marginBottom:1},it.createElement(U$,{glyph:!1},h)),y&&it.createElement(Ze,{marginBottom:1},it.createElement(j$,{glyph:!1},y)),G.length>F&&it.createElement(et,{color:LR.DIM},"Showing ",i+1,"–",Math.min(i+F,G.length)," ","of ",G.length,i>0?" · ↑ more":"",i+F<G.length?" · ↓ more":""),it.createElement(bO,{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"),NW=lt(__name(function SessionView2({onSelectSession:e,onClose:t,currentSessionId:n}){return it.createElement($W,{onSelectSession:e,onClose:t,currentSessionId:n})},"SessionView"));Vt(),Vt();var _W=__name(({onTrust:e,onExit:t})=>{const{exit:n}=st(),[r,o]=ct(1),s=process.cwd(),a=H(),i=a&&s.startsWith(a)?`~${s.slice(a.length)}`:s;return ot((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()}}),it.createElement(RO,{title:"Do you trust the files in this folder?",subtitle:i,hint:"↑/↓ to navigate · enter to select · esc to exit"},it.createElement(Ze,{flexDirection:"column"},it.createElement(et,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),it.createElement(Ze,{marginTop:1},it.createElement(et,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(Ze,null,it.createElement(o_,{isSelected:1===r}),it.createElement(s_,{isSelected:1===r,idleColor:IO}," ","1. Yes, proceed")),it.createElement(Ze,null,it.createElement(o_,{isSelected:2===r}),it.createElement(s_,{isSelected:2===r,idleColor:IO}," ","2. No, exit"))))},"TrustPrompt"),FW=lt(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(_W,{onTrust:t,onExit:n}))},"TrustView"));function useAgentSlashCommandQueue({sessionId:e,isCmdCodeBusy:t,onCommand:n}){const r=dt(!1),o=dt(()=>{});o.current=()=>{if(t||r.current)return;const s=drainAgentSlashCommands({sessionId:e});0!==s.length&&(r.current=!0,(async()=>{try{for(const e of s)await n(e.command,void 0,void 0,cB(e.source))}finally{r.current=!1}hasAgentSlashCommands({sessionId:e})&&o.current()})())},ut(()=>{o.current()},[t,e,n]),ut(()=>subscribeAgentSlashCommands(()=>{o.current()}),[])}function useAuth(){const[e,t]=ct(()=>getConfiguredProviderSync()),[n,r]=ct(()=>getConfiguredModel()),[o,s]=ct(null),[a,i]=ct(!1),[l,c]=ct(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,authComponentInfo:o,setAuthComponentInfo:s,showProviderNotification:a,setShowProviderNotification:i,premiumCreditsExhausted:l,setPremiumCreditsExhausted:c,providerNotificationTimer:dt(null),modelNotificationTimer:dt(null)}}Vt(),__name(useAgentSlashCommandQueue,"useAgentSlashCommandQueue"),Vt(),PR(),__name(useAuth,"useAuth"),Vt(),PR();var UW=__name(()=>{const[e,t]=ct({isExecuting:!1,currentCommand:null});return{executeBash:pt(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");Vt(),Vt(),PR(),Vt(),PR();var jW={detectIDE:mE,isIdeIpcConnected:__name(async e=>{const t=CE(),n=await t.connect(e);return t.disconnect(),n},"isIdeIpcConnected"),log:dlog,platform:__name(()=>process.platform,"platform")};Vt();var BW=null,WW={};function requestReload(e){BW=e}function discardPendingReload(){BW=null}function consumePendingReload(){const e=BW;return BW=null,e}function setOriginalInvocation(e){WW=e}function getOriginalInvocation(){return WW}function resolveProviderOrReport(e){return resolveCommandProviderId(e.provider)||(e.setFeed(t=>[...t,kh(`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,kh("Provider login is not available here.")]):void t(t=>[...t,hh(`${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,hh(s.message)])}function handleLoginComplete({success:e,message:t,setShowLoginOverlay:n,setFeed:r,setStatus:o}){if(n(!1),!e)return r(e=>[...e,kh(t)]),void o("Ready...");r(e=>[...e,hh(t)]),invalidateBillingContext(),o("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,hh("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,hh(`${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,hh(n?`Logged out of ${r}`:`No saved ${r} credential found`)])}catch(n){const r=n instanceof Error?n.message:"Unknown error";t(t=>[...t,kh(`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?kh(s.notice.message):hh(s.notice.message)])}function parseChangelogVersions(e){return e.split(/^(?=## )/m).map(e=>e.trim()).filter(e=>e.startsWith("## "))}function findChangelogPath(e){let t=r(p(e));for(let e=0;e<6;e++){const e=n(t,"CHANGELOG.md");if(A(e))return e;const o=r(t);if(o===t)return null;t=o}return null}function handleChangelog({setFeed:e,rawArguments:t="",moduleUrl:n}){const r=findChangelogPath(n??import.meta.url);if(!r)return void e(e=>[...e,hh("No changelog available in this build.")]);const o=parseChangelogVersions(R(r,"utf8"));if(0===o.length)return void e(e=>[...e,hh("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,vh(`**What's new**\n\n${a}${l}`)])}async function releaseHarness(e){if(e){try{await(I$(e)?.flush())}catch{}A$(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([kh(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);I$(e)?.applyTodoUserEdit({todos:h}),g.bannerModelChanged||isWrappedChild()?hardResetForResize():UL(),l(e=>e+1)}__name(requestReload,"requestReload"),__name(discardPendingReload,"discardPendingReload"),__name(consumePendingReload,"consumePendingReload"),__name(setOriginalInvocation,"setOriginalInvocation"),__name(getOriginalInvocation,"getOriginalInvocation"),Vt(),PR(),__name(resolveProviderOrReport,"resolveProviderOrReport"),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Vt(),PR(),__name(parseChangelogVersions,"parseChangelogVersions"),__name(findChangelogPath,"findChangelogPath"),__name(handleChangelog,"handleChangelog"),Vt(),PR(),Vt(),PR(),__name(releaseHarness,"releaseHarness"),__name(handleSelectSession,"handleSelectSession");var HW="Nothing to clone yet.";async function handleCloneCommand(e){const t=I$(e.sessionId);if(t)try{const n=await t.cloneSession();if(!n)return void e.setFeed(e=>[...e,hh(HW)]);e.setFeed(e=>[...e,hh(`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,kh("Couldn't clone the session (storage error). Staying on the current session.")])}else e.setFeed(e=>[...e,hh(HW)])}async function handleCompactCommand({sessionId:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:o,setStaticKey:s}){try{r(!0),n("Compacting conversation...");const a=await x$({sessionId:e,baseUrl:getApiBaseUrl()}),i=await a.compact();UL(),s(e=>e+1);const l=buildCompactCommandNotice(i);t(e=>[...e,hh(l.message)]),r(!1),n("Ready..."),o(buildPostCompactContextUsage())}catch(e){t(t=>[...t,kh(buildCompactErrorNotice(e).message)]),r(!1),n("Ready...")}}__name(handleCloneCommand,"handleCloneCommand"),Vt(),PR(),__name(handleCompactCommand,"handleCompactCommand"),Vt(),PR();var GW=__name(e=>{const t=e.metadata?.blockOf;return"string"==typeof t?t:e.id},"groupIdOf"),VW=__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=GW(n),o=[];for(let n=t;n>=0;n--){const t=e[n];if(!t||"assistant"!==t.role||GW(t)!==r)break;const s=VW(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,hh("Nothing to copy yet — no reply in this session.")]);const r=await writeClipboardText(n),o=n.length.toLocaleString("en-US");t(e=>[...e,hh(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?jh(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")}function rehydrate(e){if("run_error"!==e.type)return e;const t=e.error??{};return{type:"run_error",error:"number"==typeof t.status?hn.generate(t.status,{error:{message:t.message,code:t.code}},t.message??"Run failed",void 0):Object.assign(new Error(t.message??"Run failed"),{name:t.name??"Error"})}}function createSandboxRunQuery(e){return async({input:t,onEvent:n,additionalContent:r,maxTurns:o})=>{const s=new Map,a=new Map;let i=null,l=null,c=-1,d=!1;const u=e.onAgentEvent(e=>{"run_error"===e.type&&(d=!0),n?.(rehydrate(e))}),m=e.onNotification(e=>{if("turn/completed"!==e.method)return;const t=e.params;s.set(t.turnId,t),a.get(t.turnId)?.(t)}),p=e.onEnded(t=>{l=t,c=e.streamNumber(),i?.(t)}),g=e.onGap(()=>{e.request({method:"session/state"}).then(e=>{const t=e.result?.busy;if(!1===t)for(const[e,t]of a)t({turnId:e,stopReason:"end_turn",finalText:"",turnCount:0}),a.delete(e)}).catch(()=>{})}),h=__name(t=>{const n=s.get(t);if(n)return Promise.resolve(n);const r=__name(e=>new Error(`The turn did not finish: ${e}.`),"unfinished");return l&&c===e.streamNumber()?Promise.reject(r(l)):new Promise((e,n)=>{a.set(t,e),i=__name(e=>n(r(e)),"ended")})},"awaitTurn"),f=__name(async(t,n)=>{takeInterruptWanted();const r=await e.request({method:"turn/start",params:{input:t,...n?.length?{additionalContent:n}:{},...void 0===o?{}:{maxTurns:o}}}),s=r.error;if(s)throw new Error(s.message??"The sandbox refused the turn");return takeInterruptWanted()&&e.request({method:"turn/interrupt"}).catch(()=>{}),h(r.result.turnId)},"start"),y=__name(async t=>{const n=await e.request({method:"session/state"}).catch(()=>null),r=n?.result;return void 0===r||!0===r.busy&&r.turnId===t.turnId||s.has(t.turnId)?h(t.turnId):(await t.reload().catch(()=>{}),{turnId:t.turnId,stopReason:"end_turn",finalText:"",turnCount:0})},"watchAdopted"),S=t===ON?takeAdoptedTurn():null;try{let e=S?await y(S):await f(t,r);for(;e.leftover?.length&&"interrupted"!==e.stopReason;)e=await f(joinLeftover(e.leftover));return e.error&&!d&&n?.(rehydrate({type:"run_error",error:e.error})),await(S?.afterward().catch(()=>{})),{finalText:e.finalText,stopReason:e.stopReason,turnCount:e.turnCount}}finally{u(),m(),p(),g()}}}function joinLeftover(e){const t=[];for(const n of e)"string"==typeof n?t.push({type:"text",text:n}):t.push(...n);return t.every(e=>"text"===e.type)?t.map(e=>e.text).join("\n\n"):t}async function steerSandbox(e){const t=(e.images??[]).map(e=>({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})),n=t.length>0?[...t,{type:"text",text:e.input}]:e.input;return void 0===(await e.connection.request({method:"turn/steer",params:{input:n}})).error}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,source:d,isRelayed:u,hiddenMessages:m,isGoalContinuation:p,isGoalBootstrap:g,suppressUserEcho:h,feed:f,setFeed:y,setLiveEntries:S,isCmdCodeBusy:w,setIsCmdCodeBusy:v,setQueuedMessages:k,setStatus:C,setInteractionTokens:b,updateStatus:E,setUpdateStatus:T,billingLink:P,setBillingLink:M,currentModel:x,currentProvider:I,premiumCreditsExhausted:A,setPremiumCreditsExhausted:R,setCurrentModel:L,sessionId:O,isSubmittingRef:D,setInput:$,setStaticKey:N,executeBash:_}=e,F=resolveSubmitStartPlan({role:t,input:n,isCmdCodeBusy:w,isSubmitting:D.current,displayMessage:i,isAutomated:l,isMeta:c,source:d,isRelayed:u,hiddenMessages:m,images:r,ideContext:s,ideHint:a});if("skip"===F.kind&&!n.length)return F.outcome;if(E&&T(null),b(0),"skip"===F.kind)return F.outcome;if("bash"===F.kind){const e=sandboxBashMessage();if(e)return y([...f,hh(e)]),$(""),"completed";D.current=!0;const t=wh(n);return y([...f,t]),$(""),await _(n,e=>{y(e)},()=>{UL(),N(e=>e+1)}),D.current=!1,"completed"}if("queue"===F.kind){const e=getSandboxConnection();return e&&!c&&await steerSandbox({connection:e,input:n,...r?{images:r}:{}}).catch(()=>!1)?(y(e=>[...e,gh(n)]),l||$(""),F.outcome):(k(e=>[...e,F.queuedMessage]),l||$(""),F.outcome)}D.current=!0;const U=await runModInputInterception(e);if("handled"===U.action){D.current=!1;const e=U.message;return e&&y(t=>[...t,hh(e)]),"skipped"}const j="transform"===U.action?U.text:n;await loadCustomProviderModels();const B=isSandboxMode()?null:await checkOAuthSetupRequired({currentProvider:I??null,isByokModel:isByok({model:x??""}),providerAuthHeaders:providerAuthHeaders});if(B)return D.current=!1,C(B),y(e=>[...e,kh(B)]),"skipped";v(!0),C(Lh()),l||$("");let W=!1,H=null,G=null,V=null,z=0;const K=createSubmitGoalSupervisor(e);let q=null;const Y=resolvePremiumCreditsPreflight({premiumCreditsExhausted:A,currentModel:x});if(Y.blocked)return W=!0,C(Y.status),y(e=>[...e,hh(Y.message)]),v(!1),D.current=!1,Y.outcome;try{q=await K.getGoalTurnBudget();const e=getSandboxConnection();if(isSandboxMode()&&!e)return y(e=>[...e,hh('The sandbox is not connected yet. Wait for the "Connected to sandbox" line (or its error), then send again.')]),D.current=!1,"completed";const t=e?null:await x$({sessionId:O,baseUrl:getApiBaseUrl()});if(g&&!isCommandGoalLoopArmed(O))return"skipped";const n=clipboardImagesToUserContent(r),l=s?`${s}\n\n${j}`:j,c=n.length>0?[...n,{type:"text",text:l}]:s?[{type:"text",text:l}]:void 0,d={...r&&r.length>0?{images:r,...o?{imageTokenPaths:o}:{}}:{},...a?{ideHint:a}:{}};trackFirstMessage();const u=await runHarnessTurnIntoFeed({harness:t,input:j,turnUserInput:c,runQuery:e?createSandboxRunQuery(e):e=>runHarnessQuery({...e,harness:e.harness}),setFeed:y,setLiveEntries:S,displayMessage:i,suppressUserEcho:h,additionalContent:hiddenMessagesToUserContent(m),inputMeta:F.inputMeta,maxTurns:q?.remainingTurns,onRoundTrip:__name(e=>{z=e},"onRoundTrip"),echoMetadata:Object.keys(d).length>0?d:void 0,setStatus:C,onInteractionTokens:b,onRunError:__name(e=>{G=e},"onRunError"),routeEntry:createBlockCommittingRouter({setFeed:y,setLiveEntries:S}),scrubGoalCompleteMarker:isCommandGoalLoopArmed(O)});if(G){const e=x?byokProviderId({model:x}):void 0;throw formatRunError(G,e?{byokProvider:e}:void 0)}return V=u.finalText,z=u.turnCount,"completed"}catch(e){const t=resolveSubmitErrorAction({error:e,sessionId:O});if("interrupted"===t.kind)return W=!0,t.outcome;if(trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"submit_error"}),context:{component:qo.SUBMIT,heading:"Prompt submission failed",code:t.kind}}),W=!0,H=t.goalErrorKind,"insufficient-credits"===t.kind){C(t.status);const e=await getBillingLink({billingLink:P,setBillingLink:M});return y(t=>[...t,kh(buildInsufficientCreditsSubmitActionMessage({billingUrl:e}))]),t.outcome}if("premium-credits-exhausted"===t.kind)return R?.(!0),L?.(t.fallbackModelId),UL(),N(e=>e+1),C(t.status),y(e=>[...e,hh(t.message)]),t.outcome;C(t.status);const n="info"===t.renderKind?hh(t.message):kh(t.message);return y(e=>[...e,n]),t.outcome}finally{v(!1),W||C("Ready..."),D.current=!1,await K.afterTurn({assistantText:W?null:V,errorKind:W?H:null,isGoalContinuation:p,turnsUsed:z,goalStartedAt:q?.startedAt})}return"skipped"}function emitGoalNotice(e,t){e(e=>[...e,hh(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=>(I$(t)??await x$({sessionId:t,baseUrl:getApiBaseUrl()})).verifyGoal(e),"verifyCompletion"),getEvidence:__name(()=>{const e=I$(t);return e?harnessRecentToolEvidence(e):""},"getEvidence"),emitCompletion:__name(e=>{n(t=>[...t,hh("",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,kh(qC)]);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,kh(buildDesignSkillLoadErrorMessage(t))])}}__name(findLastAssistantText,"findLastAssistantText"),__name(handleCopy,"handleCopy"),Vt(),PR(),Vt(),PR(),Vt(),PR(),__name(getAuthKey3,"getAuthKey"),__name(trackFirstMessage,"trackFirstMessage"),Vt(),PR(),__name(isWhitespaceOnly3,"isWhitespaceOnly"),__name(routeTodoWriteEntry,"routeTodoWriteEntry"),__name(createBlockCommittingRouter,"createBlockCommittingRouter"),Vt(),PR(),__name(rehydrate,"rehydrate"),__name(createSandboxRunQuery,"createSandboxRunQuery"),__name(joinLeftover,"joinLeftover"),__name(steerSandbox,"steerSandbox"),__name(getBillingLink,"getBillingLink"),__name(runModInputInterception,"runModInputInterception"),__name(handleSubmit,"handleSubmit"),__name(emitGoalNotice,"emitGoalNotice"),__name(createSubmitGoalSupervisor,"createSubmitGoalSupervisor"),__name(handleDesignCommand,"handleDesignCommand"),Vt(),PR();var zW="Nothing to export yet — the transcript is created on the first message.",KW=new Set(["html","jsonl","md"]);function matchFormatKeyword(e){const t=e.toLowerCase();return KW.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(A(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=Lt.isSupported?createOSC8Link(fileUrl(e.path),t,!1):t;return`Exported ${e.formatLabel} session to ${n}`}async function buildSessionHtmlExport(e){const{messages:t}=await loadCommandSessionMessages({sessionId:e.sessionId});if(0===t.length)return null;const n=await loadCommandUserRenamedTitle({sessionId:e.sessionId})??e.sessionId;return renderSessionHtml({messages:fromV2(t.map(e=>e.message)),title:n,sessionId:e.sessionId,exportedAt:(new Date).toISOString(),...e.currentModel?{model:e.currentModel}:{}})}async function buildSessionMarkdownExport(e){const{messages:t}=await loadCommandSessionMessages({sessionId:e.sessionId});if(0===t.length)return null;const n=await loadCommandUserRenamedTitle({sessionId:e.sessionId})??e.sessionId;return renderSessionMarkdown({messages:fromV2(t.map(e=>e.message)),title:n,sessionId:e.sessionId,exportedAt:(new Date).toISOString(),...e.currentModel?{model:e.currentModel}:{}})}async function exportJsonl(e){const t=n(getProjectSessionDir({env:process.env,cwd:e.cwd}),`${e.sessionId}.jsonl`);if(A(t)){try{j(t,e.target)}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,hh(`Export failed: ${n}`)])}e.setFeed(t=>[...t,hh(exportedMessage({path:e.target,formatLabel:"JSONL"}))])}else e.setFeed(e=>[...e,hh(zW)])}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,hh(`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,hh(`Export failed: ${n}`)])}e.setFeed(t=>[...t,hh(exportedMessage({path:e.target,formatLabel:"HTML"}))])}else e.setFeed(e=>[...e,hh(zW)])}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,hh(`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,hh(`Export failed: ${n}`)])}e.setFeed(t=>[...t,hh(exportedMessage({path:e.target,formatLabel:"Markdown"}))])}else e.setFeed(e=>[...e,hh(zW)])}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,hh(`Unknown export extension "${r.extension}". Supported export formats: .html, .jsonl, .md`)])}async function handleForkCommand(e,t){const n=I$(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,fh({name:r.title})])}catch{e.setFeed(e=>[...e,kh(Uf)])}else e.setFeed(e=>[...e,"error"===r.notice.kind?kh(r.notice.message):hh(r.notice.message)])}function setMode(e,t){e.permissionModeRef.current=t,e.setPermissionMode(t),I$(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,hh(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"),Vt(),PR(),__name(handleForkCommand,"handleForkCommand"),Vt(),PR(),__name(setMode,"setMode"),__name(handlePlanCommand,"handlePlanCommand"),Vt(),PR();var qW=[{title:"Composing",rows:[{keys:"Enter",action:"Send the prompt"},{keys:"Shift+Enter / Alt+Enter",action:"Insert a newline"},{keys:"Ctrl+G",action:"Edit the prompt in $EDITOR"},{keys:"Ctrl+S",action:"Stash / restore the current prompt"},{keys:"↑ / ↓",action:"Browse prompt history"},{keys:"@",action:"Mention a file (fuzzy search)"},{keys:"/",action:"Open the command menu"},{keys:"!",action:"Bash mode — run a shell command"}]},{title:"While it works",rows:[{keys:"Esc",action:"Interrupt the current turn"},{keys:"Type + Enter",action:"Queue a steering message"},{keys:"Ctrl+X",action:"Open the todo manager (/todos) for the current plan"}]},{title:"Transcript",rows:[{keys:"Ctrl+O",action:"Toggle expanded tool output"},{keys:"Ctrl+E / Ctrl+Y",action:"Toggle the full transcript"}]},{title:"Session & modes",rows:[{keys:"Shift+Tab",action:"Cycle mode: standard → accept edits → plan → yolo"},{keys:"Alt+P",action:"Quick model switch"},{keys:"Esc Esc",action:"Rewind to a checkpoint"},{keys:"Ctrl+C Ctrl+C",action:"Exit"}]}];function buildHotkeysMarkdown(){const e=["**Keyboard shortcuts**"];for(const t of qW){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,vh(buildHotkeysMarkdown())])}async function handleImportCommand({setFeed:e},t=""){const n=resolveAgentImportSourceArg(t);if(!n.ok)return void e(e=>[...e,kh(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,hh("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,hh(formatAgentImportSummary(o))])}catch(t){e(e=>[...e,kh(`Import failed: ${t instanceof Error?t.message:"unknown error"}`)])}}function setMode2(e,t){e.permissionModeRef.current=t,e.setPermissionMode(t),I$(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,hh(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?kh(t.notice.message):hh(t.notice.message)]),"renamed"===t.kind){e.setRenamedTerminalTitle(t.name);try{(e.harness??await x$({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 x$({sessionId:e,baseUrl:getApiBaseUrl()}),o=await r.regenerateTitle();if(!o)return void t(e=>[...e,hh("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,hh("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=I$(e.sessionId)?.getSessionStats().name,n=t?null:await loadCommandSessionMeta({sessionId:e.sessionId}).catch(()=>null),r=t??n?.title;e.setFeed(e=>[...e,hh(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=I$(e),o=resolveRewindCommand({hasActiveConversation:Boolean(r),checkpointCount:r?.listCheckpoints().length??0});"notice"!==o.kind?n(!0):t(e=>[...e,"error"===o.notice.kind?kh(o.notice.message):hh(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=I$(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)}),UL(),a(e=>e+1),c.promptToRestore&&i(c.promptToRestore),r(e=>[...e,hh(c.notice.message)]),void o(c.statusMessage);r(e=>[...e,"error"===c.notice.kind?kh(c.notice.message):hh(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,hh("No active session.")]);const r=n(getProjectSessionDir({env:process.env,cwd:getCurrentWorkingDirectory()}),`${e}.jsonl`),o=formatSessionFileLine({absolutePath:r,exists:A(r),linksSupported:Lt.isSupported});t(t=>[...t,hh(`Session ID: ${e}\nCurrent session file: ${r}`,{isSessionFile:!0,sessionFileId:e,sessionFileLine:o})])}__name(buildHotkeysMarkdown,"buildHotkeysMarkdown"),__name(handleHotkeys,"handleHotkeys"),Vt(),PR(),__name(handleImportCommand,"handleImportCommand"),Vt(),PR(),__name(setMode2,"setMode"),__name(handleModeCommand,"handleModeCommand"),Vt(),PR(),__name(applyRenameResult,"applyRenameResult"),__name(autoRenameSession,"autoRenameSession"),__name(handleRenameCommand,"handleRenameCommand"),__name(handleNameCommand,"handleNameCommand"),Vt(),PR(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),Vt(),PR(),__name(compactTranscriptPath,"compactTranscriptPath"),__name(formatSessionFileLine,"formatSessionFileLine"),__name(handleSessionFile,"handleSessionFile"),Vt(),PR();var YW=xe(f),QW=/https:\/\/gist\.github\.com\/\S+/;function parseGistUrl(e){const t=QW.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 YW("gh",["gist","create",e,"--desc","Command Code session"],{encoding:"utf8"});return{stdout:String(t)}}async function resolveShareGistFormat(e){const t=(e??"").trim();return t?matchFormatKeyword(t):resolveConfiguredExportFormat((await loadUserConfig()).defaultShareGistFormat)}async function writeGistPayload(e){const t=n(e.tempDir,`command-code-session-${e.sessionId.slice(0,8)}.${e.format}`);if("jsonl"===e.format){const r=n(getProjectSessionDir({env:process.env,cwd:getCurrentWorkingDirectory()}),`${e.sessionId}.jsonl`);return A(r)?(j(r,t),t):null}if("md"===e.format){const n=await e.buildMarkdownExport({sessionId:e.sessionId,currentModel:e.currentModel});return n?(await q(t,n,"utf8"),t):null}const r=await e.buildHtmlExport({sessionId:e.sessionId,currentModel:e.currentModel});return r?(await q(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,hh(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 le(n(G(),"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: ${Lt.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 Z(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?I$(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?I$(e):void 0});if("no-session"!==a.status){if("not-shared"===a.status)return o(a.message),void setTimeout(()=>o(""),fC);if("error"===a.status)return r(a.message),void setTimeout(()=>r(""),fC);o(a.message),r(""),n(null),setTimeout(()=>{o("")},fC)}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,hh(`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,hh(`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,hh(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=I$(e),a=resolveTreeCommand({hasActiveConversation:Boolean(s),treeEntryCount:s?.getSessionTree().length??0});if("notice"===a.kind)return void t(e=>[...e,"error"===a.notice.kind?kh(a.notice.message):hh(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=I$(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,hh("Already at this point")]),{aborted:!1}):(s(!1),o(reconstructFeedFromMessages(harnessSessionMessages(l))),UL(),a(e=>e+1),r.editorText&&i(r.editorText),o(e=>[...e,hh("Navigated to selected point")]),{aborted:!1})}catch(e){return o(t=>[...t,kh(`Failed to navigate: ${actionErrorMessage(e)}`)]),{aborted:!1}}}function handleTreeCancel({setShowTreeSelector:e}){e(!1)}function handleTreeAbortSummary({sessionId:e}){I$(e)?.abortBranchSummary()}function handleTreeLabel({entryId:e,label:t,sessionId:n,setFeed:r}){const o=I$(n);if(o)try{o.setTreeLabel({targetId:e,label:t})}catch(e){r(t=>[...t,kh(`Failed to set label: ${actionErrorMessage(e)}`)])}}function announceCompletedUpdate({fromVersion:e,toVersion:t}){console.log(Pt.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:qo.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"),Vt(),PR(),__name(loadPersistedTraceIds,"loadPersistedTraceIds"),__name(handleTrace,"handleTrace"),Vt(),PR(),__name(actionErrorMessage,"actionErrorMessage"),__name(handleTreeCommand,"handleTreeCommand"),__name(handleTreeSelect,"handleTreeSelect"),__name(handleTreeCancel,"handleTreeCancel"),__name(handleTreeAbortSummary,"handleTreeAbortSummary"),__name(handleTreeLabel,"handleTreeLabel"),Vt(),PR(),Vt(),PR(),__name(announceCompletedUpdate,"announceCompletedUpdate"),__name(trackUpdateFailure,"trackUpdateFailure");var JW={createLifecycleEventClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createLifecycleEventClient"),isTelemetryEnabled:isTelemetryEnabled,log:dlog,onCompletedUpdate:announceCompletedUpdate,trackUpdateFailure:trackUpdateFailure},XW={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:XW,host:JW,copy:{binCommand:`${getBinaryCommand()}`,updateCommand:"npm i -g command-code"},emit:s});trackTuiUpdateCommandTelemetry(a),"error"!==a.level?e(e=>[...e,hh(a.message,a.metadata)]):e(e=>[...e,kh(a.message)])}function tildeHome(e){const t=W.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function formatWorktreePathLine(e){return` ${yt.dim(ft.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?yt.dim(` (branch ${a.target.branch}${a.usedRemote?", from origin":""})`):"",n=a.created&&a.copiedFiles>0?yt.dim(` · copied ${a.copiedFiles} file(s)`):"",r=a.created&&a.copyFailedFiles.length>0?yt.dim(` · ${a.copyFailedFiles.length} include copy failure(s)`):"";process.stdout.write(`${yt.cyan(ft.squareSmallFilled)} ${e} worktree ${yt.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"),Vt(),PR(),Vt(),PR(),__name(tildeHome,"tildeHome"),__name(formatWorktreePathLine,"formatWorktreePathLine"),__name(enterWorktreeFromFlag,"enterWorktreeFromFlag");var ZW=__name((e,t)=>e.setFeed(e=>[...e,hh(t)]),"info"),eH=__name((e,t)=>e.setFeed(e=>[...e,kh(t)]),"error");function renderList(e,n){const r=listWorktrees(e);return 0===r.length?"No worktrees found.":["Worktrees:",...r.map(r=>{const o=samePath2(r.path,e)?"●":"○",s=t.relative(n,r.path),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 eH(e,"/worktree requires a git repository.");const r=getMainWorktreeRoot(n)??n,o=t[0]?.toLowerCase();if(!o||"list"===o||"ls"===o)return void ZW(e,renderList(n,r));if("remove"===o||"rm"===o){const o=t[1];return o?void await handleRemove(e,o,n,r):void eH(e,"Usage: /worktree remove <name>")}const s="new"===o||"create"===o||"add"===o?t[1]:t[0];await handleSwitch(e,s,n)}async function handleRemove(e,n,r,o){const s=resolveTarget(n,o);if(samePath2(s.worktreePath,r))return void eH(e,"Can't remove the worktree you're in. Switch away first, then remove it.");if(!listWorktrees(r).some(e=>samePath2(e.path,s.worktreePath)))return void eH(e,`No worktree named "${n}".`);const a=removeWorktree({worktreePath:s.worktreePath,cwd:r,deleteBranch:isManagedWorktreePath(s.worktreePath,o)?s.branch:void 0});a.ok?ZW(e,`Removed worktree "${n}".`):eH(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 eH(e,`Couldn't create worktree: ${r.error}`);if(samePath2(r.target.worktreePath,n))return void ZW(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))`:"";ZW(e,`${o} worktree "${r.target.name}"${s}${a}. Switching… (a fresh session starts in the worktree; this one stays resumable).`),await(I$(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,vh(Wh)])}async function handleTerminalSetupCommand({setFeed:e}){const t=gh("/terminal-setup"),n=setupVSCodeTerminal(),r=bh(n.message,!n.success,n.details),o=bh("Terminal tab titles need no setup — titles are set automatically via standard escape sequences (VS Code 1.117+ honors them out of the box).",!1),s=isKittyKeyboardActive()?[bh("Shift+Enter already works natively in this terminal (kitty keyboard protocol) — the VS Code keybindings only apply inside a VS Code-family terminal.",!1)]:[];e(e=>[...e,t,r,o,...s])}async function handleIDESetupCommand({setFeed:e}){const t=await runIdeSetup({host:jW,moduleUrl:import.meta.url}),n=Eh(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(),UL(),r(null),o(!1),s(""),await deleteCommandSessionShareInfo({sessionId:c}).catch(()=>{});const m=I$(c);m?.stopBackgroundLearning(),await(m?.flush().catch(()=>{})),A$(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,hh(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,hh(s.notice.message,s.notice.metadata)]),o&&"notice"===s.status&&"cleared"===s.notice.metadata?.goalNoticeKind&&I$(e.sessionId)?.requestStopAfterTurn(),"start"===s.status&&await runGoalTurn(e,s.goalText,n,r)}async function openExternalSlashCommandTarget({setFeed:e,target:t}){e(e=>[...e,hh(`Opening ${createOSC8Link(t.url,t.noticeLabel,!1)} in your browser…`)]);try{await xt(t.url,{wait:!1,background:!0})}catch{const{fallback:n}=t;if("info"===n.kind)return void e(e=>[...e,hh(n.message)]);e(e=>[...e,kh("Failed to open browser"),vh(createOSC8Link(t.url,n.label,!1))])}}function handleLearnCommand({setAutoLearnTaste:e,setShowTasteOnboarding:t,setTasteOnboardingEntryId:n,setFeed:r}){e(!0),t(!0);const o=Ch();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}),s=sandboxGateMessage(e.trim().split(/\s+/)[0]?.split(":")[0]?.replace(/^\//,"")??"");if(s)return t.setFeed(e=>[...e,hh(s)]),{status:"handled"};if("blocked"===o.kind)return t.setFeed(e=>[...e,hh(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,hh("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,kh(`No skill named "${o.skillName}". Run /skills to see what is installed.`)]),{status:"handled"})}if("unknown"===o.kind)return{status:"unknown"};const{commandName:a,rawArguments:i,positionalArgs:l}=o;if("/exit"===a||"/quit"===a)return discardPendingReload(),t.setShouldExit(!0),{status:"handled"};if("/reload"===a)return await(I$(t.sessionId)?.flush().catch(()=>{})),requestReload(buildReloadCarryoverState({sessionId:t.sessionId,permissionMode:t.permissionModeRef.current})),t.setShouldExit(!0),{status:"handled"};if("/clear"===a)return await handleClearCommand(t),{status:"handled"};if("/help"===a)return await handleHelpCommand(t),{status:"handled"};if("/share"===a){const e=i.trim();return"gist"===e||e.startsWith("gist ")?(await handleShareGistCommand({sessionId:t.sessionId,currentModel:t.currentModel,rawFormatArg:e.slice(4).trim(),setFeed:t.setFeed}),{status:"handled"}):(await handleShareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setShowShareNotification:t.setShowShareNotification}),{status:"handled"})}if("/unshare"===a)return await handleUnshareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setUnshareNotificationMessage:t.setUnshareNotificationMessage}),{status:"handled"};if("/taste"===a)return t.setShowTasteConfig(!0),{status:"handled"};if("/learn-taste"===a)return handleLearnCommand(t),{status:"handled"};if("/design"===a)return await handleDesignCommand({ctx:t,rawArguments:i,positionalArgs:l,command:e}),{status:"handled"};if("/skills"===a)return t.setShowSkillsConfig(!0),{status:"handled"};if("/plans"===a)return t.setPlansTarget(i.trim()||null),t.setShowPlansView(!0),{status:"handled"};if("/plan-review"===a)return t.setPlansTarget(CW),t.setShowPlansView(!0),{status:"handled"};if("/config"===a)return t.setShowSettingsConfig(!0),{status:"handled"};if("/connect"===a)return t.setShowProviderSelector(!0),{status:"handled"};if("/model"===a)return await handleModelCommand(t,i),{status:"handled"};if("/effort"===a)return await handleEffortCommand(t,i),{status:"handled"};if("/memory"===a)return t.setShowMemorySelector(!0),{status:"handled"};if("/resume"===a||"/sessions"===a)return t.setShowSessionSelector(!0),{status:"handled"};if("/fork"===a)return await handleForkCommand(t,i.trim()||void 0),{status:"handled"};if("/worktree"===a)return await handleWorktreeCommand(t,l),{status:"handled"};if("/clone"===a)return await handleCloneCommand(t),{status:"handled"};if("/init"===a)return await handleInitCommand(t),{status:"handled"};if("/import"===a)return await handleImportCommand(t,i),{status:"handled"};if("/goal"===a)return await handleGoalCommand(t,i,n,r),{status:"handled"};if("/agents"===a)return t.setShowAgentsConfig(!0),{status:"handled"};if("/mcp"===a)return t.setShowMcpManager(!0),{status:"handled"};if("/compact"===a)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"===a)return t.setShowCompactModeSelector(!0),{status:"handled"};if("/update"===a)return t.setInput(""),await handleUpdateCommand({setFeed:t.setFeed,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setUpdateStatus:t.setUpdateStatus,pinnedStatusRef:t.pinnedStatusRef}),{status:"handled"};if("/context"===a)return t.setShowContextView(!0),{status:"handled"};if("/rewind"===a)return handleRewindCommand({sessionId:t.sessionId,setFeed:t.setFeed,setShowRewindSelector:t.setShowRewindSelector}),{status:"handled"};if("/tree"===a)return await handleTreeCommand({sessionId:t.sessionId,setFeed:t.setFeed,setShowTreeSelector:t.setShowTreeSelector,setTreeFilterMode:t.setTreeFilterMode,setTreeBranchSummarySkipPrompt:t.setTreeBranchSummarySkipPrompt}),{status:"handled"};if("/login"===a)return await handleLoginCommand({provider:i,setFeed:t.setFeed,setShowLoginOverlay:t.setShowLoginOverlay,setAuthComponentInfo:t.setAuthComponentInfo}),t.setInput(""),{status:"handled"};if("/logout"===a)return await handleLogoutCommand({provider:i,setFeed:t.setFeed,setRetryAttempt:t.setRetryAttempt,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),t.setInput(""),{status:"handled"};if("/learn"===a){const e=resolveExternalSlashCommandTarget({commandName:a});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),{status:"handled"}}if("/feedback"===a){const e=resolveExternalSlashCommandTarget({commandName:a,rawArguments:i});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),t.setInput(""),{status:"handled"}}if("/trace"===a)return await handleTrace({setFeed:t.setFeed,sessionId:t.sessionId}),t.setInput(""),{status:"handled"};if("/copy"===a)return await handleCopy({feed:t.feed,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/export"===a)return await handleExport({sessionId:t.sessionId,rawPath:i,currentModel:t.currentModel,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/changelog"===a)return handleChangelog({setFeed:t.setFeed,rawArguments:i}),t.setInput(""),{status:"handled"};if("/hotkeys"===a)return handleHotkeys({setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/todos"===a)return 0===getSessionTodos().length?t.setFeed(e=>[...e,hh("No todos in this session yet.")]):requestTodosManagerOpen(),t.setInput(""),{status:"handled"};if("/session-file"===a)return handleSessionFile({sessionId:t.sessionId,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/terminal-setup"===a)return await handleTerminalSetupCommand(t),{status:"handled"};if("/ide"===a)return await handleIDESetupCommand(t),{status:"handled"};if("/add-dir"===a)return t.setShowAddDirModal(!0),{status:"handled"};if("/rename"===a)return await handleRenameCommand({name:i.trim(),sessionId:t.sessionId,setFeed:t.setFeed,setRenamedTerminalTitle:t.setRenamedTerminalTitle,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),t.setInput(""),{status:"handled"};if("/name"===a)return await handleNameCommand({name:i.trim(),sessionId:t.sessionId,setFeed:t.setFeed,setRenamedTerminalTitle:t.setRenamedTerminalTitle}),t.setInput(""),{status:"handled"};if("/usage"===a)return t.setShowUsageOverlay(!0),{status:"handled"};if("/theme"===a)return await handleThemeCommand(t,i),{status:"handled"};if("/rc"===a)return await handleRcCommand(t,i),{status:"handled"};if("/plan"===a)return await handlePlanCommand({rawArguments:i,ctx:t}),{status:"handled"};if("/mode"===a||a.startsWith("/mode:")){const e=a.startsWith("/mode:")?a.slice(6):i;return await handleModeCommand({rawArguments:e,ctx:t}),{status:"handled"}}if("/review"===a){const e=await resolveReviewSlashCommand({rawArguments:i});return"missing-gh"===e.status?(t.setFeed(t=>[...t,hh(e.message,e.metadata)]),t.setInput(""),{status:"handled"}):(await submitAutomatedSlashTurn({turn:e.turn,ctx:t}),{status:"handled"})}if("/pr-comments"===a){await submitAutomatedSlashTurn({turn:buildPrCommentsSlashTurn(),ctx:t});const e=I$(t.sessionId),n=resolvePrCommentsFollowUpInput(e?harnessSessionMessages(e):[]);return n&&t.setInput(n),{status:"handled"}}if("/status"===a)return t.setShowStatusView(!0),{status:"handled"};if("/upgrade"===a){const e=resolveExternalSlashCommandTarget({commandName:a,billingUrl:await getBillingLink({billingLink:t.billingLink,setBillingLink:t.setBillingLink})});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),{status:"handled"}}if("/extra"===a){const e=resolveExternalSlashCommandTarget({commandName:a,billingUrl:await getBillingLink({billingLink:t.billingLink,setBillingLink:t.setBillingLink})});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),{status:"handled"}}const c=getActiveModHost(),d=a.slice(1);if(c?.commands().some(e=>e.name===d)){try{const e=await c.runCommand({name:d,args:i}),n=e?.message;n&&t.setFeed(e=>[...e,hh(n)]),e?.prompt&&await submitAutomatedSlashTurn({turn:buildAutomatedSlashTurn({commandName:d,rawArguments:i,fullPrompt:e.prompt}),ctx:t})}catch(e){t.setFeed(t=>[...t,kh(`Mod command /${d} failed: ${e instanceof Error?e.message:String(e)}`)])}return{status:"handled"}}const u=await resolveCustomSlashTurn({runtime:createNodeRuntime(),commandName:a,rawArguments:i,positionalArgs:l});if(u)return await submitAutomatedSlashTurn({turn:u,ctx:t}),{status:"handled"};return await handleSkillCommand({commandName:a,command:e,rawArguments:i,positionalArgs:l,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,hh(s.message)]),{status:"handled"}):"load-error"===s.status?(o.setFeed(e=>[...e,kh(s.message)]),{status:"handled"}):(await submitAutomatedSlashTurn({turn:s.turn,ctx:o}),{status:"handled"})}__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"),Vt();var tH=new Set(["info","error"]),nH=__name(e=>{if(!tH.has(e.role))return;const t="string"==typeof e.input?e.input.trim():"";return""===t?void 0:t},"spokenText");function echoFeedToChat(e){if("remote"!==e.origin)return e.setFeed;const t=getActiveRemote(),n=t?.bridge.ownerChatId;if(!t||void 0===n)return e.setFeed;const r=new Set;return o=>{e.setFeed(e=>{const s="function"==typeof o?o(e):o;for(const o of s.slice(e.length)){const e=nH(o);void 0===e||r.has(o.id)||(r.add(o.id),t.bridge.sendNote(n,e))}return s})}}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=mt(()=>({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,setShowRcSelector:o.setShowRcSelector,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=dt(m);return p.current=m,{commandCtx:m,onCommand:pt((e,t,n,r)=>handleCommand(e,{...p.current,...r?{origin:r}:{},setFeed:echoFeedToChat({setFeed:p.current.setFeed,origin:r})},t,n),[])}}__name(echoFeedToChat,"echoFeedToChat"),__name(useCommandCtx,"useCommandCtx"),Vt(),PR();var rH=ms,oH=ps;function useCreditWarning({interactionTokens:e,currentModel:t}){const[n,r]=ct(null),o=dt(null),s=dt(null),a=dt(null),i=pt(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},rH)}catch{}},[]);return ut(()=>{if(0!==e&&!isLocalOnly()&&!isByok({model:t}))return s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{i(),s.current=null},oH),()=>{s.current&&clearTimeout(s.current)}},[e,t,i]),ut(()=>()=>{a.current&&clearTimeout(a.current),s.current&&clearTimeout(s.current)},[]),{creditWarning:n}}__name(useCreditWarning,"useCreditWarning"),Vt(),PR();var sH=createNodeRuntime();function useCronWakeup({sessionId:e,onSubmit:t}){const n=dt(t),r=dt(e),o=dt(Promise.resolve());ut(()=>{n.current=t},[t]),ut(()=>{r.current=e},[e]),ut(()=>{const e=subscribeCronFire(e=>{o.current=o.current.catch(()=>{}).then(async()=>{const t="loop"===e.kind||!0===e.loopOwned,o=I$(r.current);if(t&&o&&!o.hasScheduledTask({id:e.taskId}))return;const s=await buildScheduledTaskWakeupSubmission({event:e,runtime:sH});await n.current(s)}),o.current.catch(()=>{})});return()=>{e()}},[])}function useExit(){const[e,t]=ct(!1),[n,r]=ct(null),o=dt(null),s=dt(0),a=dt(null),i=pt(()=>{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(useCronWakeup,"useCronWakeup"),Vt(),__name(useExit,"useExit"),Vt(),PR(),Vt(),PR();var aH="1"===process.env.CMD_TEST_INJECT_LIVE_ENTRY;function makeInjectedShellEntry(e,t,n,r={}){return{...Sh("shell_command",t,{status:n}),id:e,...r}}function buildInjectedLiveEntry(){return aH?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 iH="1"===process.env.CMD_TEST_INJECT_STREAM,lH="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?Th(t,{id:lH,status:"running"}):"tool"===e?{...Sh("shell_command",t,{status:"running"}),id:lH}:"agent"===e?{...Ph({name:"Task",input:t}),id:lH}:{...yh(t),id:lH,metadata:{status:"running"}}}function makeStreamFinalEntry(e,t){return"reasoning"===e?Th(t,{id:lH}):"tool"===e||"agent"===e?{...Sh("shell_command",t,{}),id:lH,output:"done"}:{...yh(t),id:lH}}function maybeStartInjectedStream(e){if(!iH)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 cH="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 dH=(()=>{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(!cH)return;const t=createBlockCommittingRouter({setFeed:e.setFeed,setLiveEntries:e.setLiveEntries});let n=0;const r=setInterval(()=>{const e=dH[n];e?(t({...Sh("todo_write",_h("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 uH=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(uH)||uH<=0)return;const{setFeed:t}=e;let n=0;const r=setInterval(()=>{const e=n===uH-1,o=makeInjectedTurnEntry(n,e);t(e=>[...e,o]),n+=1,e&&clearInterval(r)},testTurnTickMs());return()=>clearInterval(r)}function useFeed(){const[e,t]=ct(()=>buildInjectedFeed()),n=pt(e=>{t(t=>applyFeedRetention("function"==typeof e?e(t):e))},[]);ut(()=>{trimStaticBuffer()},[e]);const[r,o]=ct(()=>{const e=buildInjectedLiveEntry();return e?[e]:[]}),[s,a]=ct([]),[i,l]=ct(aH),c=dt([]),d=pt(e=>{const t="function"==typeof e?e(c.current):e;c.current=t,a(t)},[]);return ut(()=>maybeStartInjectedTurns({setFeed:n}),[n]),ut(()=>maybeStartInjectedStream({setFeed:n,setLiveEntries:o,setIsCmdCodeBusy:l}),[]),ut(()=>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:L,setRetryAttempt:O,setStatus:D,pendingExitKey:$,setPendingExitKey:N,pendingExitKeyRef:_,lastExitKeyTimeRef:F,exitConfirmationTimeoutRef:U,resetPendingExitKey:j,pendingPermission:B,setPendingPermission:W,pendingQuestion:H,setPendingQuestion:G,setShouldExit:V,sessionId:z,handleToggleAutoAccept:K,handleDoubleEscapeEmpty:q,respondToPrompt:Y,createErrorEntry:Q}){const J=__name(()=>{I$(z)?.cancelLoops().then(e=>{if(0===e)return;const t=1===e?"task":"tasks";A(n=>[...n,hh(`Loop stopped · ${e} scheduled ${t} cancelled`,{isGoalNotice:!0,goalNoticeKind:"cleared"})])})},"cancelLoopsAndNotify"),X=__name(()=>{const e=getSandboxConnection();e?interruptSandboxTurn(e):interruptActiveTurn(),clearCommandGoalIfActive(z),J();const t=P.length>0;if(L(!1),O(null),R([]),D(sS),!t){const e=Q(oS);A(t=>[...t,e])}if(M.current.length>0){const e=M.current.filter(e=>!0!==e.isRelayed),t=M.current.filter(e=>!0===e.isRelayed);if(e.length>0){const t=formatQueuedMessagesForRequeue(e);x(e=>mergeRequeuedInput({queuedText:t,currentInput:e}))}I(t),M.current=t}},"handleInterrupt");ot((P,M)=>{const I=getKeybindings();if(keybindingMatches(I,"app.permission.cycle",P,M)||""===P||M.meta&&"m"===P)return void K();if(y&&M.escape)return void S(!1);if(w&&M.escape)return void v(!1);if(k&&M.escape)return void C(null);if(isTodosManagerOpen())return void($&&j());if(e||t||n||r||o||s||a||i||g||l||c||d||u||m||p)return void($&&j());const A=""===P||M.ctrl&&"c"===P,R=isSandboxMode()&&null===getSandboxConnection();if(A){if(T&&!R)return void X();const e=Date.now(),t=e-F.current;return F.current=e,"ctrl-c"===_.current&&t<2e3?(U.current&&(clearTimeout(U.current),U.current=null),void V(!0)):(x(()=>""),_.current="ctrl-c",N("ctrl-c"),U.current&&clearTimeout(U.current),void(U.current=setTimeout(()=>{_.current=null,N(null),U.current=null},2e3)))}if(keybindingMatches(I,"app.tools.expand",P,M)){if(H?.params.planContent)return;return UL(),E("off"===b?"limited":"off"),void f(e=>e+1)}const L=isCtrlKey({inputChar:P,key:M,letter:"e",ctrlCode:5})||isCtrlKey({inputChar:P,key:M,letter:"y",ctrlCode:25}),O=null!==B&&"function"==typeof B.params?.explain;if("off"!==b&&L&&!O)return UL(),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 UL(),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||R?J():X()}})}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=pt(()=>{isSandboxMode()?t.setFeed(e=>[...e,hh("Permissions are bypassed in a sandbox session; the mode cannot be changed here yet.")]):a.setPermissionMode(e=>{const t=cyclePermissionMode({current:e,disableBypass:I$(c)?.isBypassDisabled()??!0}),n=resolvePendingPromptOnModeChange(t,{pendingIsRisky:void 0!==s.pendingPermission?.params?.risk});return n&&s.pendingPermission&&("approve"===n&&a.respondToPrompt(gM),s.pendingPermission.resolve("approve"===n),s.setPendingPermission(null)),I$(c)?.setPermissionMode({mode:t}),t})},[a.setPermissionMode,a.respondToPrompt,s.pendingPermission,s.setPendingPermission,c]),g=pt(()=>{a.setPermissionMode(e=>{const t="bypass"===e?e:"auto-accept";return I$(c)?.setPermissionMode({mode:t}),t})},[a.setPermissionMode,c]),h=pt(()=>{const e=!t.isCmdCodeBusy&&!s.pendingPermission&&!s.pendingQuestion,n=(I$(c)?.listCheckpoints().length??0)>0;e&&n&&r.setShowRewindSelector(!0)},[t.isCmdCodeBusy,s.pendingPermission,s.pendingQuestion,r.setShowRewindSelector,c]),f=pt(t=>{n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),t?.skipped&&r.setShowTasteSkipBanner(!0),e&&r.setShowSessionSelector(!0)},[e,n,r]),y=pt(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=pt(()=>{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:kh}),{handleToggleAutoAccept:p,handleEnableAutoAccept:g,handleDoubleEscapeEmpty:h,handleTasteOnboardingComplete:f,handleTrust:y,handleNoTrust:S}}function runGit2(e){return S(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}function warnAboutPromptTruncation(e){const t=e.trim().length;t<=Ox||console.error(Pt.yellow(`Warning: prompt is ${t} characters; only the first ${Ox} are sent.`))}function warnAboutLocalOnlyWork(e){e||console.error(Pt.yellow("Warning: local changes are not included (the sandbox works from the repo on GitHub)."))}function runSandboxStartPreflight(e){if(e.baseBranch&&!isValidSandboxBranchName(e.baseBranch))throw new Error("Invalid --base branch name.");warnAboutPromptTruncation(e.prompt);const t=validateSandboxGitRepo({run:__name(({command:e})=>runGit2(e),"run")});return warnAboutLocalOnlyWork(t.isClean),{repoUrl:t.repoUrl}}function createSandboxTransport(){const e=createApiClient({baseUrl:getApiBaseUrl(),timeout:3e5});return{post:__name(t=>e.post({endpoint:t.route,body:t.body}),"post"),get:__name(t=>e.get({endpoint:t.route}),"get")}}function deadlineFor(e){return"session/set_model"===e||"session/set_effort"===e?6e5:3e4}__name(testTurnChars,"testTurnChars"),__name(testTurnTickMs,"testTurnTickMs"),__name(makeInjectedTurnEntry,"makeInjectedTurnEntry"),__name(maybeStartInjectedTurns,"maybeStartInjectedTurns"),__name(useFeed,"useFeed"),Vt(),PR(),PR(),Vt(),PR(),__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Vt(),PR(),Vt(),PR(),Vt(),PR(),__name(runGit2,"runGit"),__name(warnAboutPromptTruncation,"warnAboutPromptTruncation"),__name(warnAboutLocalOnlyWork,"warnAboutLocalOnlyWork"),__name(runSandboxStartPreflight,"runSandboxStartPreflight"),Vt(),PR(),__name(createSandboxTransport,"createSandboxTransport"),__name(deadlineFor,"deadlineFor");var mH="deadline";function withDeadline(e){return new Promise((t,n)=>{const r=setTimeout(()=>n(new Error(mH)),e.ms);e.promise.then(e=>{clearTimeout(r),t(e)},e=>{clearTimeout(r),n(e)})})}function isDeadline(e){return e instanceof Error&&e.message===mH}async function authHeaders(){const e=await getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env});if(!e)throw new Error("Not authenticated.");return{authorization:`Bearer ${e}`}}function isNotRunning(e){const t=e?.status;return 409===t}__name(withDeadline,"withDeadline"),__name(isDeadline,"isDeadline"),__name(authHeaders,"authHeaders"),__name(isNotRunning,"isNotRunning");var pH=__name(e=>new Promise(t=>setTimeout(t,e)),"sleep");async function openSandboxConnection(e){const t=createSandboxClient({transport:createSandboxTransport()}),n=(e.sessionId?{sessionId:e.sessionId}:await startSession2({client:t,model:e.model,effort:e.effort,...e.baseBranch?{baseBranch:e.baseBranch}:{}})).sessionId,r=!e.sessionId,o={model:e.model,effort:e.effort};let s=await t.status({sessionId:n});("rpc"!==s.mode||isTerminalSandboxTaskStatus(s.status)&&!1===s.boxUp)&&await reopen({client:t,sessionId:n,...o});const a=new Set,i=new Set,l=new Set,c=new Set,d=new Map,u=__name(()=>{const e=Date.now()-5e3;for(const[t,n]of d)n.sentAt>e||(n.reject(new Error("No answer from the sandbox: events were lost.")),d.delete(t))},"failStalePending");let m=0;const p=`${process.pid}-${Date.now().toString(36)}`;let g=!1,h=0;const f=new Set,y=__name(()=>{h=Date.now();for(const e of[...f])e()},"markProcessUp"),S=__name(e=>new Promise(t=>{if(h>=e)return void t();const n=__name(()=>{clearTimeout(r),f.delete(n),t()},"wake"),r=setTimeout(n,2e3);f.add(n)}),"untilProcessUp"),w=__name(e=>{"hello"===e.method&&y();const t=e.id;if("string"==typeof t&&d.has(t))return d.get(t)?.resolve(e),void d.delete(t);if("string"==typeof e.method)for(const t of i)t(e)},"onRpcFrame"),v=__name(e=>{for(const[t,n]of d)n.reject(new Error(`No answer from the sandbox: ${e}.`)),d.delete(t);for(const t of l)t(e)},"failWaiters"),k=__name(e=>{g||(C=null),v(e?`the sandbox reported ${e}`:"the stream ended")},"settleEnd");let C=null,b=0,E=0,T=0;function attach(){T++;const t=streamSandboxTask({sessionId:n,isReattach:!0,...b>0?{lastEventId:b}:{},getBaseUrl:getApiBaseUrl,getAuthHeaders:authHeaders,maxReconnects:8,callbacks:{onAgentEvent:__name(({event:e})=>{for(const t of a)t(e)},"onAgentEvent"),onRpcFrame:__name(({frame:e})=>w(e),"onRpcFrame"),onGap:__name(()=>{u();for(const e of c)e();e.onGap?.()},"onGap"),onStatus:__name(({action:t})=>{"running"===t.type&&y(),"failed"===t.type&&(A=t.message,v(t.message)),e.onStatus?.(t)},"onStatus"),onDisconnected:__name(()=>e.onDisconnected?.(),"onDisconnected")}});return t.done.then(e=>{if(C!==t)return;const n=t.getLastEventId()>b;if(b=t.getLastEventId(),E=n?0:E+1,null===e&&!g&&E<=2)return C=null,void setTimeout(()=>{P()},1e3);k(e)},()=>{C===t&&(b=t.getLastEventId(),k(null))}),t}__name(attach,"attach");const P=__name(async()=>{if(g)return;const e=await t.status({sessionId:n}).catch(()=>null);e&&!1!==e.boxUp?await x().catch(()=>{}):k(null)},"reattachIfUp");let M=null;const x=__name(()=>C?Promise.resolve():(M||(M=(async()=>{s=await t.status({sessionId:n}),isTerminalSandboxTaskStatus(s.status)&&!1===s.boxUp&&(await reopen({client:t,sessionId:n,...o}),b=0),C=attach(),await R()})().finally(()=>{M=null})),M),"ensureUp"),I=__name((e,t)=>{"session/set_model"===e&&"string"==typeof t.model&&(o.model=t.model,o.effort=void 0),"session/set_effort"===e&&"string"==typeof t.effort&&(o.effort=t.effort)},"remember");let A=null;const R=__name(async()=>{const e=Date.now()+24e4,a=Date.now();let i=!1;for(;Date.now()<e;){const e=`${p}:probe-${++m}`,l=Date.now(),c=new Promise((t,n)=>d.set(e,{resolve:t,reject:n,sentAt:Date.now()}));c.catch(()=>{});try{return await t.input({sessionId:n,frame:probeFrame(e)}),void await withDeadline({promise:c,ms:2e4})}catch(c){if(d.delete(e),!isNotRunning(c)&&!isDeadline(c))throw c;if(await S(l),s=await t.status({sessionId:n}),!1!==s.boxUp){!i&&!r&&Date.now()-a>45e3&&isTerminalSandboxTaskStatus(s.status)&&(i=!0,await t.continueTask({sessionId:n,prompt:"",mode:"rpc",restart:!0,...o.model?{model:o.model}:{},...o.effort?{effort:o.effort}:{}}),b=0,C?.detach(),C=attach());continue}if(A||i)throw new Error(A??"The sandbox stopped before its process was ready.");i=!0,await reopen({client:t,sessionId:n,...o}),b=0,C?.detach(),C=attach()}}throw new Error("The sandbox did not come up in time.")},"waitReady"),L=__name(async({method:e,params:r})=>{await x();const o=`${p}:${++m}`,s={jsonrpc:"2.0",id:o,method:e,params:r??{}},a=new Promise((e,t)=>d.set(o,{resolve:e,reject:t,sentAt:Date.now()}));a.catch(()=>{});try{await t.input({sessionId:n,frame:s})}catch(e){if(!isNotRunning(e))throw d.delete(o),e;C&&(b=C.getLastEventId()),C?.detach(),C=null;try{await x(),await t.input({sessionId:n,frame:s})}catch(e){throw d.delete(o),e}}const i=setTimeout(()=>{const e=d.get(o);e&&(d.delete(o),e.reject(new Error("No answer from the sandbox: its agent process is not responding.")))},deadlineFor(e)),l=await a.finally(()=>clearTimeout(i));return void 0===l.error&&I(e,r??{}),l},"request");return C=attach(),await R(),{sessionId:n,summary:__name(()=>s,"summary"),request:L,onAgentEvent:__name(e=>(a.add(e),()=>a.delete(e)),"onAgentEvent"),onNotification:__name(e=>(i.add(e),()=>i.delete(e)),"onNotification"),onEnded:__name(e=>(l.add(e),()=>l.delete(e)),"onEnded"),onGap:__name(e=>(c.add(e),()=>c.delete(e)),"onGap"),streamNumber:__name(()=>T,"streamNumber"),close:__name(()=>{g=!0,C?.detach()},"close")}}function probeFrame(e){return{jsonrpc:"2.0",id:e,method:"session/state",params:{}}}async function startSession2(e){const t=runSandboxStartPreflight({prompt:"",...e.baseBranch?{baseBranch:e.baseBranch}:{}});return{sessionId:(await e.client.start({repoUrl:t.repoUrl,prompt:"",mode:"rpc",...e.baseBranch?{baseBranch:e.baseBranch}:{},...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{}})).sessionId}}async function reopen(e){const t=__name(()=>e.client.continueTask({sessionId:e.sessionId,prompt:"",mode:"rpc",...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{}}),"attempt");try{await t()}catch(e){if(!isNotRunning(e))throw e;await pH(3e3),await t()}}async function adoptRunningTurn(e){const{connection:t}=e,n=__name(n=>alignModel({connection:t,...n?{state:n}:{},...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{}}),"align"),r=await readState(t);return!0===r?.busy&&r.turnId?(setAdoptedTurn({turnId:r.turnId,afterward:__name(async()=>n((await readState(t))?.session),"afterward"),reload:e.reload}),!0):(await n(r?.session),!1)}async function readState(e){const t=await e.request({method:"session/state"}).catch(()=>null);return t?.result}async function alignModel(e){const{connection:t,state:n,model:r,effort:o}=e;if(n?.model&&r){if(n.model!==r){const e=await t.request({method:"session/set_model",params:{model:r}}).catch(()=>null);if(!e||e.error)return}o&&n.effort!==o&&await t.request({method:"session/set_effort",params:{effort:o}}).catch(()=>null)}}async function loadSandboxFeed(e){const t=createSandboxClient({transport:createSandboxTransport()}),{lines:n}=await t.transcript({sessionId:e.sessionId});return reconstructFeedFromMessages(displayMessagesFromV3Lines(n))}async function rebuildFeedAfterGap(e){let t=null;e.setFeed(e=>(t=e,e));const n=e.load??loadSandboxFeed,r=await n({sessionId:e.sessionId});e.setFeed(e=>e===t?r: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(openSandboxConnection,"openSandboxConnection"),__name(probeFrame,"probeFrame"),__name(startSession2,"startSession"),__name(reopen,"reopen"),Vt(),__name(adoptRunningTurn,"adoptRunningTurn"),__name(readState,"readState"),__name(alignModel,"alignModel"),Vt(),PR(),__name(loadSandboxFeed,"loadSandboxFeed"),__name(rebuildFeedAfterGap,"rebuildFeedAfterGap"),Vt(),__name(resolveExternalModelChange,"resolveExternalModelChange"),Vt(),__name(raceAnswerAgainstAbort,"raceAnswerAgainstAbort"),Vt();var gH={},hH={};function setStartupSessionOptions(e){gH=void 0===e.persist?{}:{persist:e.persist},hH={...e.sessionFilePath?{sessionFilePath:e.sessionFilePath}:{},...e.name?{name:e.name}:{}}}function getStickyStartupSessionOptions(){return gH}function consumeStartupSessionOverrides(){const e=hH;return hH={},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,setConnecting:v,onFatal:k}){const C=dt(f);C.current=f;const b=dt(null),E=dt(!1),T=dt(w);T.current=w;const P=pt(()=>{hardResetForResize(),S?.(e=>e+1)},[S]),M=pt(e=>{C.current=e,y?.(e),P()},[P,y]);ut(()=>{if(w)return;const e=b.current,t=E.current;b.current=null,E.current=!1,(null!==e||t)&&(null===e||e===C.current?t&&P():M(e))},[w,M,P]);const[x,I]=ct(!1),[A,R]=ct(0),L=dt(null),O=__name(()=>{L.current?.(),L.current=null},"releaseRebuildBarrier");ut(()=>onHarnessSessionRebuild(t=>{if(t===e)return new Promise(e=>{L.current?.(),L.current=e,R(e=>e+1)})}),[e]);const D=dt(a.current),$=dt(null);return ut(()=>{if(isSandboxMode()){O();let e=!1;return(async()=>{u?.("Connecting to the sandbox"),v?.(!0);const t=getRequestedSandboxSessionId();let n=t;const r=await openSandboxConnectionOnce(()=>openSandboxConnection({sessionId:t,...getRequestedSandboxBase()?{baseBranch:getRequestedSandboxBase()??""}:{},...sandboxModelFor(f)?{model:sandboxModelFor(f)}:{},...sandboxEffortFor(f)?{effort:sandboxEffortFor(f)}:{},onStatus:__name(e=>{"setup_step"!==e.type&&"replayed_setup"!==e.type||u?.(e.message??"Starting the sandbox"),"running"===e.type&&u?.(Lh())},"onStatus"),onGap:__name(()=>{const e=getSandboxConnection()?.sessionId??n;e&&m&&rebuildFeedAfterGap({sessionId:e,setFeed:m}).catch(()=>{})},"onGap")}));if(!e){if(n=r.sessionId,setSandboxConnection(r),f&&!sandboxModelFor(f)&&m?.(e=>[...e,hh(`${f} is a custom model this machine serves; the sandbox runs its default model instead.`)]),t){const t=await loadSandboxFeed({sessionId:r.sessionId}).catch(()=>null);t&&!e&&m?.(()=>t)}u?.(""),m?.(e=>[...e,hh(`Connected to sandbox ${r.sessionId.slice(0,8)} (${r.summary().repoUrl.replace("https://github.com/","")}, branch ${r.summary().branch??"?"})`)]),await adoptRunningTurn({connection:r,...sandboxModelFor(f)?{model:sandboxModelFor(f)}:{},...sandboxEffortFor(f)?{effort:sandboxEffortFor(f)}:{},reload:__name(()=>loadSandboxFeed({sessionId:r.sessionId}).then(e=>m?.(()=>e)).catch(()=>{}),"reload")}),v?.(!1),I(!0)}})().catch(t=>{e||(u?.(""),v?.(!1),m?.(e=>[...e,kh(`Sandbox: ${t instanceof Error?t.message:String(t)}`)]),setTimeout(()=>k?.(),400))}),()=>{e=!0}}if(!o||n)return void O();const t=__name(()=>Boolean(l)||a.current!==D.current,"userChoseMode");let y,S,w=!1;return(async()=>{const n=consumeStartupSessionOverrides(),{persist:o}=getStickyStartupSessionOptions(),l=await loadResumeAgentState({sessionId:e,...n.sessionFilePath?{baseDir:r(n.sessionFilePath)}:{}});if(w)return;const f=__name(()=>{const e=p?.current??[];if(0===e.length)return[];const t=e.filter(e=>!0!==e.isRelayed),n=e.filter(e=>!0===e.isRelayed);return 0===t.length?[]:(p&&(p.current=n),g?.(()=>n),m?.(e=>[...e,...t.flatMap(e=>{if(e.isMeta)return[];const t=gh(e.displayMessage??e.input);return e.ideHint&&(t.metadata={ideHint:e.ideHint}),[t]})]),t.map(e=>{const t=e.ideContext?`${e.ideContext}\n\n${e.input}`:e.input;return e.images&&0!==e.images.length?{input:[...clipboardImagesToUserContent(e.images),{type:"text",text:t}],...e.source?{source:e.source}:{}}:{input:t,...e.source?{source:e.source}:{}}}))},"drainQueuedMessages"),v=await loadCommandModHost(),k=await x$({sessionId:e,baseUrl:getApiBaseUrl(),...t()?{permissionMode:a.current}:{},dangerouslySkipPermissions:c,drainQueuedMessages:f,peekQueuedMessageCount:__name(()=>(p?.current??[]).filter(e=>!0!==e.isRelayed).length,"peekQueuedMessageCount"),interaction:buildInteraction({permissionsService:s,permissionModeRef:a,setPendingQuestion:d,setStatus:u}),requestSlashCommand:__name(({command:t})=>{const n=refuseAgentSlashCommand(t);return n?{status:"unavailable",message:n}:(enqueueAgentSlashCommand({sessionId:e,command:t}),{status:"accepted"})},"requestSlashCommand"),resumeState:l,modHost:v,...void 0!==o?{persist:o}:{},...n.sessionFilePath?{sessionFilePath:n.sessionFilePath}:{},ideBridge:createLocalIdeBridge()}).catch(()=>{});if(O(),w||!k)return;n.name&&k.setSessionName(n.name),k.getPermissionMode()!==a.current&&(t()?k.setPermissionMode({mode:a.current}):(a.current=k.getPermissionMode(),i?.(k.getPermissionMode())));const x=k.getModel(),A=x!==C.current;A&&M(x),A||k.getEffort()===getReasoningEffort(x)||P(),v&&m&&(v.setEntrySink(e=>{m(t=>[...t,hh(e.join("\n"))])}),S=__name(()=>v.setEntrySink(void 0),"clearModEntrySink")),y=k.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(T.current?E.current=!0:P());const t=resolveExternalModelChange({setting:e.setting,value:e.value,currentModel:C.current});return void(t&&(T.current?b.current=t.modelId:M(t.modelId)))}if("subagent_stop"===e.type){if(!m)return;return void m(t=>settleBackgroundAgentRow({entries:t,toolCallId:e.toolCallId,tokensUsed:e.tokensUsed,...e.status?{status:e.status}:{}}))}if("notice"!==e.type||!m)return;const t=tasteNoticeToFeedEntry(e);t&&m(e=>[...e,t])}),I(!0),$.current!==e&&($.current=e,k.fireSessionStartHooks({source:consumeNextSessionStartSource()}).then(e=>{if(w||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,hh(n.join("\n"))])}).catch(()=>{}))})(),()=>{w=!0,y?.(),S?.()}},[e,t,n,o,s,a,i,l,c,d,u,y,M,A,P]),{ready:x}}function useLifecycle({exit:e,feedState:t,exitState:n,statusState:r,authState:o,onboarding:s,uiOverlays:a,skipOnboarding:i,sessionId:l,sessionTitleHolder:c}){ut(()=>{n.shouldExit&&(isSandboxMode()&&getSandboxConnection()?.close(),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),releaseRemoteLockSync(),c&&(c.loadTitle=()=>loadCommandUserRenamedTitle({sessionId:l}),c.sessionId=l),(async()=>{try{await Promise.allSettled([shutdownActiveRemote(),disconnectAllMcpServers(),R$()])}catch{}try{e()}catch{process.exit(0)}})())},[n.shouldExit,e]),ut(()=>()=>{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)},[]),ut(()=>{(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]),ut(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(Lh())},Bh);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),ut(()=>{i||isSandboxMode()||triggerTasteOnboarding({projectTrusted:s.projectTrusted,onboardingComplete:s.onboardingComplete,isOnboardingMode:s.showTasteOnboarding,tasteOnboardingCheckedRef:s.tasteOnboardingCheckedRef,setIsOnboardingMode:s.setShowTasteOnboarding})},[s.projectTrusted,s.onboardingComplete,s.showTasteOnboarding,i]),ut(()=>{if(s.showTasteOnboarding&&!s.tasteOnboardingEntryId){const e=Ch();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(Oo),t(!1)}}function handleCompactModeCancel({setShowCompactModeSelector:e}){e(!1)}__name(setStartupSessionOptions,"setStartupSessionOptions"),__name(getStickyStartupSessionOptions,"getStickyStartupSessionOptions"),__name(consumeStartupSessionOverrides,"consumeStartupSessionOverrides"),__name(buildInteraction,"buildInteraction"),__name(useHarness,"useHarness"),Vt(),PR(),__name(useLifecycle,"useLifecycle"),Vt(),PR(),Vt(),PR(),__name(handleCompactModeSelect,"handleCompactModeSelect"),__name(handleCompactModeCancel,"handleCompactModeCancel");var fH=__name(e=>{},"noopBool");function useMainActionCallbacks({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,permissionState:s,setInput:a}){const i=dt({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,permissionState:s,setInput:a});i.current={feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,permissionState:s,setInput:a};const l=pt(e=>{const{feedState:t,sessionState:n,statusState:r,uiOverlays:o,authState:s}=i.current;handleSelectSession({selectedSessionId:e,previousSessionId:n.sessionId,sessionLoadIdRef:n.sessionLoadIdRef,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:n.setSessionId,setShowSessionSelector:o.setShowSessionSelector,setSessionLoaded:n.setSessionLoaded,setStaticKey:o.setStaticKey,setShareInfo:r.setShareInfo,setCurrentModel:s.setCurrentModel,inTuiResume:!0})},[]),c=pt(({messageId:e,mode:t})=>{const{feedState:n,sessionState:r,statusState:o,uiOverlays:s,setInput:a}=i.current;handleRewindSelect({messageId:e,mode:t,sessionId:r.sessionId,setFeed:n.setFeed,setStatus:o.setStatus,setShowRewindSelector:s.setShowRewindSelector,setStaticKey:s.setStaticKey,setInput:a})},[]),d=pt(()=>{handleRewindCancel({setShowRewindSelector:i.current.uiOverlays.setShowRewindSelector})},[]),u=pt(e=>{const{feedState:t,sessionState:n,uiOverlays:r,setInput:o}=i.current;return handleTreeSelect({...e,sessionId:n.sessionId,setFeed:t.setFeed,setShowTreeSelector:r.setShowTreeSelector,setStaticKey:r.setStaticKey,setInput:o})},[]),m=pt(()=>{handleTreeCancel({setShowTreeSelector:i.current.uiOverlays.setShowTreeSelector})},[]),p=pt(e=>{const{feedState:t,sessionState:n}=i.current;handleTreeLabel({...e,sessionId:n.sessionId,setFeed:t.setFeed})},[]),g=pt(()=>{handleTreeAbortSummary({sessionId:i.current.sessionState.sessionId})},[]),h=pt((e,t)=>{const{feedState:n,statusState:r,uiOverlays:o}=i.current;handleLoginComplete({success:e,message:t,setShowLoginOverlay:o.setShowLoginOverlay,setFeed:n.setFeed,setStatus:r.setStatus})},[]),f=pt(()=>{const{feedState:e,statusState:t,uiOverlays:n}=i.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),y=__name(e=>{const t=i.current.authState.currentModel;if(dlog("[LaneSwitch] autoSwitchModelForLane",{provider:e,model:t}),laneServesModel({activeLane:e,modelId:t}))return;const n=defaultModelForLane({activeLane:e});dlog("[LaneSwitch] fallback",{fallback:n}),n&&k(n,e)},"autoSwitchModelForLane"),S=pt(e=>{const{authState:t,sessionState:n,statusState:r,uiOverlays:o}=i.current;handleProviderSelect({provider:e,setCurrentProvider:t.setCurrentProvider,setShowProviderSelector:o.setShowProviderSelector,setAuthComponentInfo:t.setAuthComponentInfo,setStatus:r.setStatus,setShowProviderNotification:t.setShowProviderNotification,providerNotificationTimer:t.providerNotificationTimer,setShowModelSelector:o.setShowModelSelector,sessionId:n.sessionId,onActiveModelOrphaned:__name(async()=>{{const e=await w();dlog("[LaneSwitch] orphaned → lane default",{fallback:e}),clearModelOverride(),setSessionModel(e),await persistDefaultModel({model:e});const t=i.current.sessionState.sessionId;t&&await saveCommandSessionMeta({sessionId:t,meta:{model:e}}),i.current.authState.setCurrentModel(e),i.current.uiOverlays.setStaticKey(e=>e+1)}},"onActiveModelOrphaned"),onDiskDefaultOrphaned:__name(async()=>{await persistDefaultModel({model:await w()})},"onDiskDefaultOrphaned")}).then(({switched:t})=>{t&&y(e)})},[]),w=__name(async()=>{const e=i.current.authState.currentProvider??await getConfiguredProvider()??fo.COMMAND;return e===fo.COMMAND?gr:defaultModelForLane({activeLane:e})??gr},"resolveOrphanFallback"),v=pt(()=>{handleProviderCancel({setShowProviderSelector:i.current.uiOverlays.setShowProviderSelector})},[]),k=pt((e,t)=>{const{authState:n,sessionState:r,statusState:o,uiOverlays:s,feedState:a}=i.current;handleModelSelect({modelId:e,provider:t,setCurrentModel:n.setCurrentModel,setShowModelSelector:s.setShowModelSelector,setStatus:o.setStatus,modelNotificationTimer:n.modelNotificationTimer,setShowModelNotification:fH,setCurrentProvider:n.setCurrentProvider,setStaticKey:s.setStaticKey,sessionId:r.sessionId,setFeed:a.setFeed,setContextUsage:o.setContextUsage,setModelNotice:s.setModelNotice})},[]),C=pt(()=>{handleModelCancel({setShowModelSelector:i.current.uiOverlays.setShowModelSelector})},[]),b=pt(e=>{const{statusState:t,uiOverlays:n}=i.current;handleCompactModeSelect({mode:e,setShowCompactModeSelector:n.setShowCompactModeSelector,setStatus:t.setStatus})},[]),E=pt(()=>{handleCompactModeCancel({setShowCompactModeSelector:i.current.uiOverlays.setShowCompactModeSelector})},[]),T=pt(e=>{const{statusState:t,uiOverlays:n}=i.current;handleThemeSelect({theme:e,setShowThemeSelector:n.setShowThemeSelector,setStatus:t.setStatus,setStaticKey:n.setStaticKey})},[]),P=pt(()=>{handleThemeCancel({setShowThemeSelector:i.current.uiOverlays.setShowThemeSelector})},[]),M=pt(e=>{const{feedState:t,uiOverlays:n,sessionState:r,permissionState:o}=i.current;n.setShowRcSelector(!1);const s={setFeed:t.setFeed,setShowRcSelector:n.setShowRcSelector,sessionId:r.sessionId,permissionModeRef:o.permissionModeRef,setPermissionMode:o.setPermissionMode};"stop"!==e.kind?startRemote(s,e.mode,{provider:e.provider,takeover:e.takeover}):stopRemote(s,{clearChat:e.clearChat})},[]),x=pt(()=>{i.current.uiOverlays.setShowRcSelector(!1)},[]),I=pt(()=>{const{authState:e,sessionState:t,statusState:n,uiOverlays:r}=i.current;handleAuthSuccess({authComponentInfo:e.authComponentInfo,setAuthComponentInfo:e.setAuthComponentInfo,setShowProviderSelector:r.setShowProviderSelector,setCurrentProvider:e.setCurrentProvider,setStatus:n.setStatus,setShowProviderNotification:e.setShowProviderNotification,providerNotificationTimer:e.providerNotificationTimer,sessionId:t.sessionId}).then(({switchedProvider:e})=>{e&&y(e)})},[]),A=pt(()=>{handleAuthCancel({setAuthComponentInfo:i.current.authState.setAuthComponentInfo})},[]);return{onSelectSession:l,onRewindSelect:c,onRewindCancel:d,onTreeSelect:u,onTreeCancel:m,onTreeLabel:p,onTreeAbortSummary:g,onLoginComplete:h,onLoginCancel:f,handleProviderSelect:S,handleProviderCancel:v,handleModelSelect:k,handleModelCancel:C,handleCompactModeSelect:b,handleCompactModeCancel:E,handleThemeSelect:T,handleThemeCancel:P,handleRcSelect:M,handleRcCancel:x,handleAuthSuccess:I,handleAuthCancel:A}}function useMonitorOutputWakeup({onSubmit:e}){const t=dt(e);ut(()=>{t.current=e},[e]),ut(()=>{const e=subscribeMonitorCheck(e=>{t.current(buildMonitorWakeupSubmission(e))});return()=>{e()}},[])}function useOnboarding(){const[e,t]=ct(!1),[n,r]=ct(!1),[o,s]=ct(!0),[a,i]=ct(!1),[l,c]=ct(!1),[d,u]=ct(null),[m,p]=ct(!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:dt(!1)}}function usePendingOps(){const[e,t]=ct(null),[n,r]=ct(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"),Vt(),PR(),__name(useMonitorOutputWakeup,"useMonitorOutputWakeup"),Vt(),__name(useOnboarding,"useOnboarding"),Vt(),__name(usePendingOps,"usePendingOps"),Vt(),PR(),Vt(),PR(),__name(resolvePermissionSettingsPath,"resolvePermissionSettingsPath");var yH=__name((e={})=>{const{projectRoot:t,local:n=!1,onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:a}=e,i=t||process.cwd(),l=dt({onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:a}),[c,d]=ct(null),u=dt(null),[m,p]=ct(null),[g,h]=ct(!1);return ut(()=>{l.current={onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:a}},[r,o,s,a]),ut(()=>{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:pt(async e=>{if(!c)return{allowed:!0};const t=await c.requestPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),requestShellPermission:pt(async e=>{if(!c)return{allowed:!0};const t=await c.requestShellPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),requestGenericPermission:pt(async e=>{if(!c)return{allowed:!0};const t=await c.requestGenericPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),respondToPrompt:pt(e=>{u.current?.respond(e)&&(p(null),h(!1))},[]),clearSessionPermissions:pt(()=>{c?.clearSessionPermissions()},[c]),clearProjectPermissions:pt(()=>{c?.clearProjectPermissions()},[c]),setAutoApprove:pt((e,t)=>{c?.setAutoApprove(e,t)},[c]),setEnabled:pt(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]=ct(()=>e||(n?"bypass":"default")),i=dt(s);ut(()=>{i.current=s},[s]);const{requestShellPermission:l,service:c,respondToPrompt:d,clearSessionPermissions:u,setEnabled:m}=yH({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 ut(()=>{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=dt(s);ut(()=>{a.current=s},[s]);const i=t.length>0;ut(()=>{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.source?{source:e.source}:{},...void 0!==e.isRelayed?{isRelayed:e.isRelayed}:{},...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])}__name(usePermissionMode,"usePermissionMode"),Vt(),__name(useQueuedMessageFlush,"useQueuedMessageFlush"),Vt(),PR(),Vt(),PR();var SH={shell_command:"Run a command",kill_shell:"Kill a running process",edit_file:"Edit a file",write_file:"Write a file",read_file:"Read a file",read_directory:"List a directory",web_fetch:"Fetch a URL",web_search:"Search the web"};function actionLabel(e){return SH[e]??$S[e]??e}__name(actionLabel,"actionLabel");var wH=__name(e=>e.length>500?`${e.slice(0,500)}…`:e,"clip"),vH=__name(e=>"string"==typeof e&&""!==e.trim()?e:void 0,"asText");function isRedundantDescription(e,t){return!!e.startsWith("Execute shell command:")||void 0!==t&&(e===t||e.includes(t))}__name(isRedundantDescription,"isRedundantDescription");var kH=__name(e=>"object"==typeof e&&null!==e?e:{},"fieldsOf"),CH=__name(e=>{const t=kH(e).risk;if(void 0===t)return{flagged:!1};const n=vH(kH(t).detail);return void 0===n?{flagged:!0}:{flagged:!0,detail:n}},"riskOf");function describePrompt(e){const t=kH(e.params),n=vH(t.command)??vH(t.filePath),r=vH(t.description),o=r&&isRedundantDescription(r,n)?void 0:r,s=CH(e.params);return["⏸ **Approve?**","",actionLabel(e.toolName),...n?["",`\`\`\`\n${wH(n)}\n\`\`\``]:[],...o?[o]:[],...s.flagged?["",`⚠️ ${s.detail??"flagged as risky"}`]:[]].join("\n")}__name(describePrompt,"describePrompt"),Vt();var bH=__name((e,t)=>e.length>t?`${e.slice(0,t-1)}…`:e,"clip");function buildQuestionMessage(e){const{question:t}=e,n=[e.position?`❓ **${t.header??"Question"}** (${e.position.index} of ${e.position.total})`:`❓ **${t.header??"Question"}**`,"",t.question,""],r=[];return t.options.forEach((t,o)=>{const s=o+1;n.push(t.description?`${s}. ${t.label}: ${bH(t.description,120)}`:`${s}. ${t.label}`),r.push({text:`${s}. ${bH(t.label,40)}`,data:encodeQuestionCallback({id:e.id,questionIndex:e.questionIndex,optionIndex:o})})}),t.multiSelect&&n.push("","Pick one here, or answer at the terminal for several."),{text:n.join("\n"),buttons:r.map(e=>[e])}}function planStreamTarget(e){return e?.isOpen()&&e.hasEvents()?"follow":"replace"}function planRemoteMessage(e){const t=planStreamTarget(e);return"follow"===t?{target:t,note:"⏳ Queued. It goes in after the answer above."}:{target:t}}__name(buildQuestionMessage,"buildQuestionMessage"),Vt(),__name(planStreamTarget,"planStreamTarget"),__name(planRemoteMessage,"planRemoteMessage"),Vt(),PR();var EH=__name((e,t)=>e.length>t?`${e.slice(0,t-1)}…`:e,"clip");function summarizeToolCall(e){const t=Dh(e.toolName);let n="";try{n=_h(e.toolName,e.input)}catch{n=""}return{header:n?`${t} [${EH(n.replace(/\s+/g," ").trim(),90)}]`:t}}__name(summarizeToolCall,"summarizeToolCall");var TH=__name(e=>"object"==typeof e&&null!==e,"isRecord");function textOfType(e,t){if(!Array.isArray(e))return[];const n=[];for(const r of e)TH(r)&&r.type===t&&"string"==typeof r.value&&n.push(r.value);return n}__name(textOfType,"textOfType");var PH=__name(e=>textOfType(e,"text").join("\n"),"resultText"),MH=__name(e=>textOfType(e,"error-text").join("\n").split("\n").map(e=>e.trimEnd()).filter(e=>""!==e),"errorText"),xH=__name(e=>`${e} line${1===e?"":"s"}`,"countLabel");function summarizeToolResult(e){const t=MH(e.result);if(t.length>0)return{header:"",lines:t.map(e=>EH(e,100))};const n=PH(e.result).split("\n").map(e=>e.trimEnd()).filter(e=>""!==e);return 0===n.length?{header:""}:{header:"",suffix:xH(n.length)}}__name(summarizeToolResult,"summarizeToolResult");var IH=__name(e=>({describeTool:actionLabel,summarizeCall:summarizeToolCall,summarizeResult:summarizeToolResult,..."Discord"===e?{formatStatus:Pj}:{}}),"replyStreamOptions"),AH=__name(e=>e.length>300?`${e.slice(0,300)}…`:e,"clipEcho"),RH={label:"No",value:"no",description:"Deny this action",scope:void 0};async function requestModelSwitch(e){const t=getModelDisplayName(e.modelId),n=await getBillingContext(),r=checkModelAccess({model:{id:e.modelId,name:t},planId:n.planId,purchasedCredits:n.purchasedCredits,freeCredits:n.freeCredits});return r.allowed?(enqueueAgentSlashCommand({sessionId:e.sessionId,command:`/model ${e.modelId}`,source:"remote"}),{switched:!0,message:`Switching to ${t}.`}):{switched:!1,message:r.errorMessage??`${t} is not on your plan.`}}function describeSession(){const e=getActiveRemote(),t=e?`${modeLabel(e.mode)} — ${modeBehaviour(e.mode)}`:"not connected";return("Discord"===e?.platform?xj:sB)({info:sessionInfo(),mode:t})}async function applyRemoteValue(e){if("model"===e.name){const t=resolveKnownModelId2(e.value);return t?(await requestModelSwitch({sessionId:e.sessionId,modelId:t})).message:`Unknown model "${e.value}". Send /model for the list.`}const t=SB(e.name),n=t?.reject?.(e.value);return n||(enqueueAgentSlashCommand({sessionId:e.sessionId,command:`/${e.name} ${e.value}`.trim(),source:"remote"}),`Set ${e.name} to ${e.value}.`)}async function runRemoteCommand({command:e,chatId:t,sessionId:n,bridge:r}){if("stop"===e.kind)return interruptActiveTurn(),void r.sendNote(t,"Interrupted.");if("help"===e.kind)return void r.sendNote(t,buildRemoteHelp());if("status"===e.kind)return void r.sendNote(t,describeSession());const o=SB(e.name);if(o){if(""===e.argument){const e=await o.menu();return vB(o.name)||enqueueAgentSlashCommand({sessionId:n,command:`/${o.name}`,source:"remote"}),void r.sendChoices({chatId:t,text:e.text,buttons:e.buttons})}r.sendNote(t,await applyRemoteValue({sessionId:n,name:o.name,value:e.argument}))}else r.sendNote(t,`/${e.name} doesn't work from the chat. Send /help for what does, or send it without the slash to make it a prompt.`)}function answerPermission(e,t,n){const r=e.prompts.get(n.id);if(!r||r!==e.livePermission)return e.prompts.delete(n.id),t.acknowledge("That prompt is no longer waiting."),void t.dismiss();e.prompts.delete(n.id),e.respondToPrompt(n.allow?gM:RH),r.resolve(n.allow),e.clearPendingPermission(),t.acknowledge(n.allow?"Approved":"Denied"),t.dismiss()}function answerQuestion(e,t,n){const r=e.questions.get(n.id),o=r?.pending.params.questions[n.questionIndex],s=o?.options[n.optionIndex];if(!r||!s||r.pending!==e.liveQuestion)return e.questions.delete(n.id),t.acknowledge("That question is already answered."),void t.dismiss();r.answers.set(n.questionIndex,s.label),t.acknowledge(s.label),t.dismiss();const a=r.pending.params.questions.length-r.answers.size;a>0?e.bridge.sendNote(t.chatId,`Noted: ${s.label}. ${a} left.`):(e.questions.delete(n.id),e.resolveQuestionBatch(r),e.bridge.sendNote(t.chatId,`Answered: ${s.label}`))}async function answerValue(e,t,n){const r=await applyRemoteValue({sessionId:e.sessionId,name:n.command,value:n.value}).catch(e=>`That failed: ${lj(e)}`);await t.acknowledge(r),t.dismiss(),e.bridge.sendNote(t.chatId,r)}function handleChoice(e,t){const n=parsePermissionCallback(t.data);if(n)return void answerPermission(e,t,n);const r=parseQuestionCallback(t.data);if(r)return void answerQuestion(e,t,r);const o=parseValueCallback(t.data);if(!o||!SB(o.command))return t.acknowledge("That menu is out of date."),void t.dismiss();answerValue(e,t,o)}function useRemoteBridge({sessionId:e,harnessReady:t,onSubmit:n,pendingPermission:r,setPendingPermission:o,respondToPrompt:s,pendingQuestion:a,setPendingQuestion:i,setPermissionMode:l,dangerouslySkipPermissions:c}){const d=dt(n),u=dt(s),m=dt(o),p=dt(i),g=dt(l),h=dt(null),f=dt(null),y=dt([]),S=dt(null),w=dt(null),v=dt(null),k=dt(new Map),C=dt(0),b=dt(null),E=dt(new Map),T=dt(0);d.current=n,u.current=s,m.current=o,p.current=i,g.current=l,S.current=r,w.current=a;const P=dt(()=>{});P.current=e=>{const{params:t}=e.pending,n=t.questions.map((t,n)=>({questionIndex:n,selectedOptions:[e.answers.get(n)??""]})),r=resolvePlanModeAnswerTransition({answer:n[0]?.selectedOptions[0]??"",exitPlanMode:t.exitPlanMode,enterPlanMode:t.enterPlanMode,dangerouslySkipPermissions:c});r&&g.current(r),e.pending.resolve({answers:n}),p.current(null)};const M=__name((e,t)=>{const n=getActiveRemote();if(!n)return;const r=h.current;if("follow"===planStreamTarget(r))return t?(f.current=e,void r?.retarget(n.bridge.openReply(e))):void y.current.push(e);f.current=e,r?.abandon(),h.current=createReplyStream(n.bridge.openReply(e),IH(n.platform))},"openStream");ut(()=>{const t=[subscribeRemoteMessage(t=>{const n=getActiveRemote();if(!n)return;const r=parseRemoteCommand(t.text);if(r)return void runRemoteCommand({command:r,chatId:t.chatId,sessionId:e,bridge:n.bridge}).catch(e=>{n.bridge.sendNote(t.chatId,`That command failed: ${lj(e)}`)});const o=planRemoteMessage(h.current);o.note&&n.bridge.sendNote(t.chatId,o.note),M(t.chatId,!1),d.current(buildRemoteSubmission(t))}),subscribeRemoteChoice(t=>{const n=getActiveRemote();n&&handleChoice({sessionId:e,bridge:n.bridge,prompts:k.current,questions:E.current,livePermission:S.current,liveQuestion:w.current,respondToPrompt:u.current,clearPendingPermission:__name(()=>m.current(null),"clearPendingPermission"),resolveQuestionBatch:P.current},t)}),subscribeRemoteStopped(()=>{h.current?.abandon(),h.current=null,f.current=null,y.current=[],k.current.clear(),E.current.clear(),v.current=null,b.current=null}),subscribeLocalPrompt(({text:e})=>{const t=getActiveRemote();if(!t)return;const n=t.bridge.ownerChatId;void 0!==n&&(t.bridge.sendNote(n,`💻 ${AH(e)}`),M(n,!0))})];return()=>{for(const e of t)e()}},[e]),ut(()=>{const t=I$(e);if(t)return t.events.subscribe(e=>{if("run_start"===e.type&&null===h.current){const e=y.current.shift();void 0!==e&&M(e,!1)}const t=h.current;t&&(t.onEvent(e),t.isOpen()||(h.current=null,f.current=null))})},[e,t]),ut(()=>{if(r||(v.current=null,k.current.clear()),a||(b.current=null,E.current.clear()),!r&&!a)return;const e=getActiveRemote(),t=f.current;if(e&&null!==t&&h.current?.isOpen()){if(r&&v.current!==r){v.current=r;const n=C.current;C.current+=1,k.current.set(n,r),e.bridge.sendChoices({chatId:t,text:describePrompt(r),buttons:[[{text:"✅ Approve",data:encodePermissionCallback({id:n,allow:!0})},{text:"⛔️ Deny",data:encodePermissionCallback({id:n,allow:!1})}]]})}if(a&&b.current!==a){b.current=a;const n=T.current;T.current+=1,E.current.set(n,{pending:a,answers:new Map});const r=a.params.questions.length;a.params.questions.forEach((o,s)=>{const a=buildQuestionMessage({id:n,questionIndex:s,question:o,...r>1?{position:{index:s+1,total:r}}:{}});e.bridge.sendChoices({chatId:t,text:a.text,buttons:a.buttons})})}}},[r,a])}function useSession(){const[e,t]=ct(()=>crypto.randomUUID()),[n,r]=ct(!1);return{sessionId:e,setSessionId:t,sessionLoaded:n,setSessionLoaded:r,sessionLoadIdRef:dt(null)}}__name(requestModelSwitch,"requestModelSwitch"),__name(describeSession,"describeSession"),__name(applyRemoteValue,"applyRemoteValue"),__name(runRemoteCommand,"runRemoteCommand"),__name(answerPermission,"answerPermission"),__name(answerQuestion,"answerQuestion"),__name(answerValue,"answerValue"),__name(handleChoice,"handleChoice"),__name(useRemoteBridge,"useRemoteBridge"),Vt(),__name(useSession,"useSession"),Vt(),PR(),Vt(),PR();var LH=createOSC8Link("https://commandcode.ai/docs/hooks","Docs ↗",!1),OH=createOSC8Link("https://commandcode.ai/docs/core-concepts/custom-agents","Docs ↗",!1);function buildStartupWarningEntries(e){const t=[];for(const n of e.fileLevelMessages)t.push({message:n,isFileLevel:!0});if(e.summaryLine&&t.push({message:e.summaryLine,isFileLevel:!1}),0===t.length)return[];const n=t[t.length-1];return n.message=`${n.message} ${e.docsLink}`,t.map(t=>t.isFileLevel?hh(t.message,e.fileLevelMetadata):hh(t.message))}function buildHookStartupEntries(e){const t=buildHookStartupMessages(e),n=t.find(e=>!e.isHookWarning);return buildStartupWarningEntries({fileLevelMessages:t.filter(e=>e.isHookWarning).map(e=>e.message),summaryLine:n?.message??null,docsLink:LH,fileLevelMetadata:{isHookWarning:!0}})}function buildAgentStartupEntries(e){return buildStartupWarningEntries({fileLevelMessages:[],summaryLine:summarizeAgentConfigWarnings(e),docsLink:OH})}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=pt(async()=>{try{const e=!isSandboxMode()&&await isTasteLearningEnabled();l.setTasteLearningOn(e),e&&await initTasteDir({runtime:createNodeRuntime()})}catch{}},[l.setTasteLearningOn]),k=pt(async()=>{const e=await getConfiguredProvider();c.setCurrentProvider(e)},[c.setCurrentProvider]),C=pt(()=>{},[]),b=pt(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=pt(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]);ut(()=>{(async()=>{if(isSandboxMode())return d.setProjectTrusted(!0),d.setCheckingProject(!1),v(),k(),void loadCustomProviderModels();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=dt(!1);ut(()=>{T.current||d.projectTrusted&&0!==getCommandZdrPausedFeatures().length&&(T.current=!0,u.setShowZdrNotice(!0))},[d.projectTrusted,u.setShowZdrNotice]);const P=dt(null);ut(()=>{d.projectTrusted&&c.currentModel!==P.current&&(P.current=c.currentModel,u.setModelNotice(getModelNotice(c.currentModel)??null))},[d.projectTrusted,c.currentModel,u.setModelNotice]);const M=dt(null);ut(()=>{if(!p||!d.projectTrusted)return;const e=i.sessionId;if(M.current===e)return;const t=I$(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]);const x=dt(null);ut(()=>{if(!p||!d.projectTrusted)return;const e=i.sessionId;if(x.current===e)return;const t=I$(e);if(!t)return;x.current=e;const n=buildAgentStartupEntries(t.agentConfigWarnings);0!==n.length&&a.setFeed(e=>[...e,...n])},[p,d.projectTrusted,i.sessionId,a.setFeed]),ut(()=>{if(!d.projectTrusted)return;const e=createCommandHistoryManager();return f.current=e,e.init(),()=>{e.cleanup()}},[d.projectTrusted,f]),ut(()=>{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]);const[I,A]=ct(!1);ut(()=>{!o||hasAdoptedTurn()||I||!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,I]);const R=dt(null);R.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 L=dt(!1);ut(()=>{p&&!L.current&&hasAdoptedTurn()&&(L.current=!0,A(!0),handleSubmit({...R.current,role:"user",input:ON,suppressUserEcho:!0,isAutomated:!0}).finally(()=>{takeAdoptedTurn(),A(!1)}))},[p]);const O=pt(async({role:e,input:t,images:n,imageTokenPaths:r,ideContext:o,ideHint:s,displayMessage:a,isAutomated:i,isMeta:l,source:c,isRelayed:d,hiddenMessages:m})=>{u.setShowTasteSkipBanner(!1),u.setShowZdrNotice(!1),u.setModelNotice(null),i||"bash"===e||emitLocalPrompt({text:a??t}),await handleSubmit({...R.current,role:e,input:t,images:n,imageTokenPaths:r,ideContext:o,ideHint:s,displayMessage:a,isAutomated:i,isMeta:l,source:c,isRelayed:d,hiddenMessages:m})},[u.setShowTasteSkipBanner,u.setShowZdrNotice,u.setModelNotice]);return{loadTasteStatus:v,loadCurrentProvider:k,initializeMcpInBackground:C,onSubmit:O}}function useStatus(e){const[t,n]=ct("Ready..."),r=dt(!1),[o,s]=ct(""),a=dt(null),[i,l]=ct(null),c=dt(i),[d,u]=ct(null),[m,p]=ct(!1),[g,h]=ct(""),[f,y]=ct(null),[S,w]=ct(0),[v,k]=ct(null),[C,b]=ct(null),[E,T]=ct(e??null);ut(()=>{c.current=i},[i]),ut(()=>{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,modelLabel:n=null}){const r=dt(process.cwd()),o=dt(e),s=dt(null),a=dt(n);a.current=n;const i=pt(e=>{s.current=e,setTerminalTitle(formatSessionTabTitle({sessionTitle:e,projectDir:r.current,modelLabel:a.current}))},[]),l=pt(e=>{(async()=>{const t=await loadCommandSessionMeta({sessionId:e});o.current===e&&t?.title&&t.title!==s.current&&i(t.title)})()},[i]);ut(()=>{o.current=e,i(null),l(e)},[e,i,l]);const c=dt(!0);ut(()=>{c.current?c.current=!1:i(s.current)},[n,i]);const d=dt(t);ut(()=>{const n=d.current;d.current=t,t!==n&&reassertTerminalTitle(),!t&&n&&(s.current||l(e))},[t,e,l]),ut(()=>{if(!process.stderr.isTTY)return;const e=setInterval(reassertTerminalTitle,5e3);return()=>{clearInterval(e)}},[]);const u=pt(e=>{i(e)},[i]);return{setRenamedTerminalTitle:u,applyGeneratedTitle:u}}function useUiOverlays(){const[e,t]=ct(!1),[n,r]=ct(!1),[o,s]=ct(!1),[a,i]=ct(!1),[l,c]=ct(!1),[d,u]=ct(!1),[m,p]=ct(!1),[g,h]=ct(!1),[f,y]=ct(!1),[S,w]=ct(!1),[v,k]=ct(!1),[C,b]=ct(!1),[E,T]=ct(!1),[P,M]=ct(!1),[x,I]=ct("default"),[A,R]=ct(!1),[L,O]=ct(!1),[D,$]=ct(!1),[N,_]=ct(!1),[F,U]=ct(!1),[j,B]=ct(!1),[W,H]=ct(null),[G,V]=ct(!1),[z,K]=ct(!1),[q,Y]=ct(!1),[Q,J]=ct(!1),[X,Z]=ct(!1),[ee,te]=ct(null),[ne,re]=ct(0),[oe,se]=ct(!1),[ae,ie]=ct(!1),[le,ce]=ct(null),[de,ue]=ct("off"),me="off"!==de,pe=pt(e=>{hardResetForResize(),re(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:L,setShowLoginOverlay:O,showCompactModeSelector:D,setShowCompactModeSelector:$,showContextView:N,setShowContextView:_,showStatusView:F,setShowStatusView:U,showPlansView:j,setShowPlansView:B,plansTarget:W,setPlansTarget:H,planBreadcrumbPending:G,setPlanBreadcrumbPending:V,showUsageOverlay:z,setShowUsageOverlay:K,showThemeSelector:q,setShowThemeSelector:Y,showRcSelector:Q,setShowRcSelector:J,staticKey:ne,setStaticKey:re,closeFullScreenOverlay:pe,showTasteSkipBanner:oe,setShowTasteSkipBanner:se,showZdrNotice:ae,setShowZdrNotice:ie,modelNotice:le,setModelNotice:ce,transcriptMode:de,setTranscriptMode:ue,expandedToolOutput:me,showDesignGuide:X,setShowDesignGuide:Z,pendingDesignSuggestion:ee,setPendingDesignSuggestion:te}}__name(buildStartupWarningEntries,"buildStartupWarningEntries"),__name(buildHookStartupEntries,"buildHookStartupEntries"),__name(buildAgentStartupEntries,"buildAgentStartupEntries"),__name(submitInitialPrompt,"submitInitialPrompt"),__name(useStartup,"useStartup"),Vt(),__name(useStatus,"useStatus"),Vt(),PR(),__name(useTerminalTitle,"useTerminalTitle"),Vt(),__name(useUiOverlays,"useUiOverlays");var DH=__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}=st(),{stdout:p}=nt();usePasteRouter(),ut(()=>{isLocalOnly()||prefetchBillingContext()},[]);const[g,h]=ct(""),[f,y]=ct(""),[S,w]=ct(!1),v=dt(!1),k=dt(!1),C=dt(null);ut(()=>{let e=!0;return loadUserConfig().then(t=>{e&&w(!1!==t.showTasteLearningInFeed)}).catch(()=>{e&&w(!0)}),()=>{e=!1}},[]);const b=useUiOverlays(),E=useFeed(),T=useSession(),P=useStatus(s),M=useAuth(),x=usePendingOps(),I=useOnboarding(),A=useExit(),{executeBash:R,executionState:L}=UW(),O=usePermissionMode({initialPermissionMode:c,local:d,dangerouslySkipPermissions:o,setPendingPermission:x.setPendingPermission,setStatus:P.setStatus}),D=mt(()=>getModelShortName({modelId:M.currentModel,findModelById:findModelById}),[M.currentModel]),$=useTerminalTitle({sessionId:T.sessionId,isCmdCodeBusy:E.isCmdCodeBusy,modelLabel:D}),{ready:N}=useHarness({sessionId:T.sessionId,sessionLoaded:T.sessionLoaded,showSessionSelector:b.showSessionSelector,projectTrusted:I.projectTrusted,setConnecting:E.setIsCmdCodeBusy,onFatal:__name(()=>{process.exitCode=1,A.setShouldExit(!0)},"onFatal"),permissionsService:O.permissionsService,permissionModeRef:O.permissionModeRef,setPermissionMode:O.setPermissionMode,permissionModeExplicit:Boolean(c)||o,dangerouslySkipPermissions:O.dangerouslySkipPermissions,setPendingQuestion:x.setPendingQuestion,setStatus:P.setStatus,setFeed:E.setFeed,queuedMessagesRef:E.queuedMessagesRef,setQueuedMessages:E.setQueuedMessages,onSessionTitled:$.applyGeneratedTitle,currentModel:M.currentModel,setCurrentModel:M.setCurrentModel,setStaticKey:b.setStaticKey,isCmdCodeBusy:E.isCmdCodeBusy}),{onCommand:_}=useCommandCtx({feedState:E,sessionState:T,statusState:P,authState:M,uiOverlays:b,onboarding:I,exitState:A,permissionState:O,terminalTitleState:$,isSubmittingRef:v,executeBash:R,setInput:h});useAgentSlashCommandQueue({sessionId:T.sessionId,isCmdCodeBusy:E.isCmdCodeBusy,onCommand:_}),ut(()=>{b.planBreadcrumbPending&&!E.isCmdCodeBusy&&(b.setPlanBreadcrumbPending(!1),E.setFeed(e=>[...e,vh("Plan saved — run /plans to review, annotate, or execute it anytime.")]))},[b.planBreadcrumbPending,b.setPlanBreadcrumbPending,E.isCmdCodeBusy,E.setFeed]);const{loadTasteStatus:F,loadCurrentProvider:U,onSubmit:j}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:i,stdout:p,feedState:E,sessionState:T,statusState:P,authState:M,onboarding:I,uiOverlays:b,permissionState:O,harnessReady:N,isSubmittingRef:v,initialPromptSubmittedRef:k,historyManagerRef:C,executeBash:R,setInput:h,onCommand:_});useMonitorOutputWakeup({onSubmit:j}),useCronWakeup({sessionId:T.sessionId,onSubmit:j}),useRemoteBridge({sessionId:T.sessionId,harnessReady:N,onSubmit:j,pendingPermission:x.pendingPermission,setPendingPermission:x.setPendingPermission,respondToPrompt:O.respondToPrompt,pendingQuestion:x.pendingQuestion,setPendingQuestion:x.setPendingQuestion,setPermissionMode:O.setPermissionMode,dangerouslySkipPermissions:O.dangerouslySkipPermissions}),useQueuedMessageFlush({isCmdCodeBusy:E.isCmdCodeBusy,queuedMessages:E.queuedMessages,queuedMessagesRef:E.queuedMessagesRef,setQueuedMessages:E.setQueuedMessages,isSubmittingRef:v,onSubmit:j}),useLifecycle({exit:m,feedState:E,exitState:A,statusState:P,authState:M,onboarding:I,uiOverlays:b,skipOnboarding:l,sessionId:T.sessionId,sessionTitleHolder:u});const{handleToggleAutoAccept:B,handleEnableAutoAccept:W,handleDoubleEscapeEmpty:H,handleTasteOnboardingComplete:G,handleTrust:V,handleNoTrust:z}=useHandlers({resume:e,feedState:E,onboarding:I,uiOverlays:b,exitState:A,pendingOps:x,permissionState:O,statusState:P,authState:M,sessionId:T.sessionId,loadTasteStatus:F,loadCurrentProvider:U,setInput:__name(e=>h(e),"setInput")}),K=useMainActionCallbacks({feedState:E,sessionState:T,statusState:P,authState:M,uiOverlays:b,permissionState:O,setInput:h}),{creditWarning:q}=useCreditWarning({interactionTokens:P.interactionTokens,currentModel:M.currentModel});return renderView({feedState:E,sessionState:T,statusState:P,authState:M,uiOverlays:b,onboarding:I,exitState:A,pendingOps:x,permissionState:O,historyManagerRef:C,executionState:L,actionCallbacks:K,onSubmit:j,onCommand:_,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,updateFailedInfo:a,creditWarning:q,handleTrust:V,handleNoTrust:z,handleToggleAutoAccept:B,handleEnableAutoAccept:W,handleDoubleEscapeEmpty:H,handleTasteOnboardingComplete:G,loadTasteStatus:F,showTasteLearningInFeed:S,setShowTasteLearningInFeed:w})},"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,showTasteLearningInFeed:M,setShowTasteLearningInFeed:x}){if(a.shouldExit)return null;if(s.checkingProject)return null;if(s.showTrustPrompt)return it.createElement(FW,{staticKey:o.staticKey,onTrust:v,onExit:k});if(o.showSessionSelector)return it.createElement(NW,{onSelectSession:u.onSelectSession,onClose:()=>o.closeFullScreenOverlay(o.setShowSessionSelector),currentSessionId:t.sessionId});if(!s.projectTrusted)return null;const I=o.pendingDesignSuggestion?it.createElement(L_,{suggestion:o.pendingDesignSuggestion,onSelect:e=>{p(`/design ${e}`)},onClose:()=>o.setPendingDesignSuggestion(null)}):null,A=i.pendingQuestion?.params.exitPlanMode?i.pendingQuestion:null,R=i.pendingQuestion&&!A?it.createElement(QuestionView,{pendingQuestion:i.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,dangerouslySkipPermissions:l.dangerouslySkipPermissions,setPendingQuestion:i.setPendingQuestion,setStatus:n.setStatus,setStaticKey:o.setStaticKey}):null,L=i.pendingPermission?it.createElement(C_,{pendingPermission:i.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:i.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleEnableAutoAccept:b}):null,{closeFullScreenOverlay:O}=o;if(A){const e=__name(e=>{const t=resolvePlanModeAnswerTransition({answer:e,exitPlanMode:!0,dangerouslySkipPermissions:l.dangerouslySkipPermissions});t&&l.setPermissionMode(t),A.resolve({answers:[{questionIndex:0,selectedOptions:[e]}]}),i.setPendingQuestion(null),hardResetForResize(),o.setStaticKey(e=>e+1)},"resolveApproval");return it.createElement(PlanApprovalView,{staticKey:o.staticKey,planContent:A.params.planContent,planFilePath:A.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 it.createElement(TasteConfigView,{staticKey:o.staticKey,onClose:()=>O(o.setShowTasteConfig),loadTasteStatus:P});if(o.showSkillsConfig)return it.createElement(SkillsConfigView,{staticKey:o.staticKey,onClose:()=>O(o.setShowSkillsConfig)});if(o.showSettingsConfig)return it.createElement(SettingsConfigView,{staticKey:o.staticKey,onClose:()=>O(o.setShowSettingsConfig),loadTasteStatus:P,onShowTasteLearningInFeedChange:x});if(o.showUsageOverlay)return it.createElement(UsageView,{staticKey:o.staticKey,onClose:()=>O(o.setShowUsageOverlay)});if(o.showContextView)return it.createElement(ContextConfigView,{staticKey:o.staticKey,sessionId:t.sessionId,onClose:()=>O(o.setShowContextView),setInput:h});if(o.showStatusView)return it.createElement(StatusConfigView,{staticKey:o.staticKey,sessionId:t.sessionId,onClose:()=>O(o.setShowStatusView),setInput:h});if(o.showPlansView){const e=__name(e=>{o.setPlansTarget(null),O(o.setShowPlansView),m({role:"user",input:e})},"submitFromPlans");return it.createElement(PlansView,{staticKey:o.staticKey,sessionId:t.sessionId,target:o.plansTarget,onClose:()=>{o.setPlansTarget(null),O(o.setShowPlansView)},onSubmitFeedback:e,onExecute:n=>{"plan"===l.permissionModeRef.current&&(l.permissionModeRef.current="auto-accept",l.setPermissionMode("auto-accept"),I$(t.sessionId)?.setPermissionMode({mode:"auto-accept"})),e(n)}})}return it.createElement(oW,{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,showTasteLearningInFeed:M,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,showRcSelector:o.showRcSelector,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:L,questionPanel:R,designSuggestionPanel:I,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,handleRcSelect:u.handleRcSelect,handleRcCancel:u.handleRcCancel,handleAuthSuccess:u.handleAuthSuccess,handleAuthCancel:u.handleAuthCancel,showDesignGuide:o.showDesignGuide,setShowDesignGuide:o.setShowDesignGuide})}__name(renderView,"renderView"),Vt();var $H=__name(()=>{const e=getInvokedCommandName();return"win32"===process.platform&&"cmd"===e?"cmdc":e},"getResumeCommandName");PR(),Vt();var NH=__name(({worktreePath:e,warning:t,onChoice:n})=>{const[r,o]=ct(1);return ot((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)}),it.createElement(RO,{title:"Exiting worktree session",subtitle:t,hint:"Enter to confirm · Esc to cancel"},it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,{color:1===r?LR.CYAN:LR.GRAY},1===r?ft.pointer:" "," 1. Keep worktree"," ",it.createElement(et,{color:LR.GRAY},"Stays at ",tildeHome(e)))),it.createElement(Ze,null,it.createElement(et,{color:2===r?LR.CYAN:LR.GRAY},2===r?ft.pointer:" "," 2. Remove worktree"," ",it.createElement(et,{color:LR.GRAY},"All changes and commits will be lost.")))))},"WorktreeExitPrompt");function promptWorktreeExit(e){return new Promise(t=>{const{unmount:n}=rt(it.createElement(NH,{worktreePath:e.worktreePath,warning:e.warning,onChoice:e=>{n(),t(e)}}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})})}function clearedHandoffEnv(e=process.env,t=process.pid){return{...releasedPaneOwnerEnv(e,t)}}function canRespawn(){if(process.versions.bun)return!1;const e=process.argv[1];return"string"==typeof e&&e.length>0}function resetTerminalForRespawn(){process.stdout.isTTY&&UL()}async function writeReloadHandoff(e){const t=process.env[ex];if(t)try{await K.writeFile(t,serializeReloadCarryover(e))}catch{}}async function consumeReloadHandoff(e){try{return parseReloadCarryover(await K.readFile(e,"utf-8"))}catch{return null}finally{await K.unlink(e).catch(()=>{})}}function restoreTerminal({signal:e=null}={}){try{process.stdin.isTTY&&process.stdin.setRawMode(!1)}catch{}try{process.stdout.write("[?25h")}catch{}if(e)try{popKittyKeyboardProtocol()}catch{}}__name(promptWorktreeExit,"promptWorktreeExit"),Vt(),PR(),__name(clearedHandoffEnv,"clearedHandoffEnv"),__name(canRespawn,"canRespawn"),__name(resetTerminalForRespawn,"resetTerminalForRespawn"),__name(writeReloadHandoff,"writeReloadHandoff"),__name(consumeReloadHandoff,"consumeReloadHandoff"),__name(restoreTerminal,"restoreTerminal");var _H=yt.hex(LR.DIM);function printReloadFallbackHint(){process.stdout.write(_H("Couldn't restart automatically in this build — exiting instead.\n"))}async function shutdownWrapperRuntime(){try{await Promise.allSettled([disconnectAllMcpServers(),R$(),disposeCommandModHost()])}catch{}try{await shutdownTelemetry()}catch{}process.removeAllListeners("SIGINT"),process.removeAllListeners("SIGTERM"),process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{}),process.stdin.pause()}async function runRelaunchLoop(e){await shutdownWrapperRuntime();const n=await K.mkdtemp(t.join(W.tmpdir(),"cmd-reload-")),r=t.join(n,"handoff.json");let o=e;for(;;){const e=await commandSessionTranscriptExists(o.sessionId),t=buildRelaunchArgs({invocation:getOriginalInvocation(),request:o,resumable:e,argv:process.argv.slice(2)});clearTerminalTitle(),resetTerminalForRespawn();const s=w(process.execPath,[process.argv[1],...t],{stdio:"inherit",env:{...process.env,[ex]:r,[tx]:String(process.pid),...clearedHandoffEnv()}});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(_H(`\nCouldn't relaunch Command Code: ${e.message}\n`)),await K.rm(n,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}if(a!==ZM){if(restoreTerminal({signal:i}),await K.rm(n,{recursive:!0,force:!0}).catch(()=>{}),i){const e=W.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),await disposeCommandModHost(),process.exit(ZM)),await runRelaunchLoop(e)):printReloadFallbackHint()}__name(printReloadFallbackHint,"printReloadFallbackHint"),__name(shutdownWrapperRuntime,"shutdownWrapperRuntime"),__name(runRelaunchLoop,"runRelaunchLoop"),__name(handlePendingReload,"handlePendingReload"),Vt(),PR();var FH=["disambiguateEscapeCodes"];async function resolveKittyKeyboard(e={}){const t=e.env??process.env,n=e.probe??queryKittyKeyboardSupport,r=!isVSCodeTerminal2({env:t})&&await n();return setKittyKeyboardActive(r),{mode:r?"enabled":"disabled",flags:FH}}__name(resolveKittyKeyboard,"resolveKittyKeyboard");var UH=yt.hex(LR.DIM),jH=__name((e,t)=>{const n=$H(),r=be([e]),o=t?`cd ${be([t])} && ${n} --resume ${r}`:`${n} --resume ${r}`;return`${UH("Resume this session with:")}\n${UH(o)}\n`},"formatResumeHint"),BH=__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"),WH=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),HH=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),GH=__name(e=>e.permissionMode?e.permissionMode:e.plan?"plan":void 0,"resolveInitialPermissionMode"),VH=__name(({options:e,resumeSessionId:t,sessionTitleHolder:n})=>{const r=GH(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"),zH=__name(e=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1,kittyKeyboard:e}),"getInkRenderOptions"),KH=!1,qH=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode(),!KH&&isKittyKeyboardActive()&&popKittyKeyboardProtocol()})},"setupBracketedPasteMode"),YH=__name(()=>{qH()},"initializeTerminal"),QH=__name(()=>{process.on("SIGINT",()=>{})},"swallowSigintDuringShutdown"),JH=__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"),XH=__name(async(e={})=>{const t=BH(process.stdin.isTTY);let n,o;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),YH(),"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=>A(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(WH(e)&&!n){const e=await isCommandProjectSessionInitialized(),t=e?await listCommandSessions():[],n=HH({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}if(e.forkSession){const t=await JH({resumeSessionId:n,useContinue:Boolean(e.continue)});t&&(n=t,e.continue=!1)}await applyStartupTheme();const a=await resolveKittyKeyboard();startEarlyInputCapture(),setStartupSessionOptions({...!1===e.session?{persist:!1}:{},...o?{sessionFilePath:o}:{},...e.name?{name:e.name}:{}});const i={},l=VH({options:e,resumeSessionId:n,sessionTitleHolder:i}),d=zH(a),u=rt(it.createElement(DH,{...l}),d);registerInkControl({clear:u.clear,stdout:process.stdout,instance:await resolveInkInstance(process.stdout)}),await u.waitUntilExit(),KH=!0,clearTerminalTitle(),QH();const m=consumePendingReload();m&&await handlePendingReload(m);const p=await(i.loadTitle?.())??null,g=Boolean(p);let h;const f=getAutoCreatedWorktree();if(f){const e=worktreeHasWork(f.worktreePath,f.baseSha);let t="auto";if(e||g){const n=worktreeChangeCount(f.worktreePath),r=e?n>0?`You have ${n} uncommitted file${1===n?"":"s"}. These will be lost if you remove the worktree.`:"This worktree has commits that are not on your main branch. They will be lost if you remove it.":null;t=await promptWorktreeExit({worktreePath:f.worktreePath,warning:r})}const n=finalizeAutoCreatedWorktree(t);if(n.worktreePath){const e=UH(createOSC8Link(fileUrl(n.worktreePath),tildeHome(n.worktreePath),!1));if(n.removed){const n="auto"===t?"Removed empty worktree":"Removed worktree";process.stdout.write(`${UH(n)}\n${e}\n\n`)}else if(n.kept){h=n.worktreePath;const t=n.reason&&"kept"!==n.reason?` (${n.reason})`:"";process.stdout.write(`${UH(`Kept worktree${t}`)}\n${e}\n\n`)}}}if(isSandboxMode()){const e=getSandboxConnection()?.sessionId;return void(e&&process.stdout.write(`${UH("Reopen this sandbox with:")}\n${UH(`${$H()} --experimental --sandbox ${e}`)}\n`))}const y=i.sessionId;if(y&&await commandSessionExists(y)){const e=p?sanitizeTitleForOutput(p):"";process.stdout.write(jH(e||y,h))}},"interactiveMode");function modelAndEffort(e){const t=sandboxModelFor(e??getConfiguredModel()),n=sandboxEffortFor(t);return{...t?{model:t}:{},...n?{effort:n}:{}}}function openCommand2(e){return`${$H()} --experimental --sandbox ${e}`}async function startWithTask(e){const t=runSandboxStartPreflight({prompt:e.task,...e.baseBranch?{baseBranch:e.baseBranch}:{}});return(await e.client.start({repoUrl:t.repoUrl,prompt:e.task,mode:"rpc",...e.baseBranch?{baseBranch:e.baseBranch}:{},...modelAndEffort(e.model)})).sessionId}function refusal(e){const t=e.error;return t?t.message??"refused":null}async function sendToLiveBox(e){const t=await openSandboxConnection({sessionId:e.sessionId,...modelAndEffort(e.model)});try{const n=void 0!==e.model||!0===e.effortGiven?modelAndEffort(e.model):{};if(e.model&&n.model){const e=refusal(await t.request({method:"session/set_model",params:{model:n.model}}));if(e)throw new Error(`The sandbox kept its model: ${e}.`)}if(n.effort){const e=refusal(await t.request({method:"session/set_effort",params:{effort:n.effort}}));if(e)throw new Error(`The sandbox kept its effort: ${e}.`)}const r=refusal(await t.request({method:"turn/start",params:{input:e.task,headless:!0}}));if(r)throw new Error(`The sandbox did not take the task: ${r}.`)}finally{t.close()}}async function sendFollowUp(e){const{client:t,sessionId:n,task:r}=e,o=await t.status({sessionId:n});if("running"===o.status)throw new Error(`A task is already running in ${n.slice(0,8)}\nConnect: ${openCommand2(n)}`);!1===o.boxUp||"rpc"!==o.mode?await t.continueTask({sessionId:n,prompt:r,mode:"rpc",...modelAndEffort(e.model)}):await sendToLiveBox({sessionId:n,task:r,...e.model?{model:e.model}:{},...e.effortGiven?{effortGiven:!0}:{}})}async function runSandboxPrint(e){warnAboutPromptTruncation(e.task);const t=truncateSandboxPrompt(e.task);if(!t)throw new Error('Give the task: cmd -p --sandbox "task", or cmd -p --sandbox <id> "task" for a follow-up.');if(e.sessionId&&e.baseBranch)throw new Error("--base applies to a new session only; a follow-up stays on its branch.");const n=createSandboxClient({transport:createSandboxTransport()}),r=e.sessionId?(await sendFollowUp({client:n,sessionId:e.sessionId,task:t,...e.model?{model:e.model}:{},...e.effortGiven?{effortGiven:!0}:{}}),e.sessionId):await startWithTask({client:n,task:t,...e.baseBranch?{baseBranch:e.baseBranch}:{},...e.model?{model:e.model}:{}});process.stdout.write(`${r}\n`),process.stderr.write(Pt.dim(`${e.sessionId?"Sent to sandbox":"Sandbox started"}\nConnect: ${openCommand2(r)}\n`))}Vt(),PR(),__name(modelAndEffort,"modelAndEffort"),__name(openCommand2,"openCommand"),__name(startWithTask,"startWithTask"),__name(refusal,"refusal"),__name(sendToLiveBox,"sendToLiveBox"),__name(sendFollowUp,"sendFollowUp"),__name(runSandboxPrint,"runSandboxPrint"),Vt(),PR(),Vt();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 ZH=__name(e=>({turnNumber:e,apiDurationMs:0,toolCalls:[],toolDurationMs:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}),"newTurn");function createBenchmarkCollector(e){const t=e.now??Date.now,n=e.writeFile??((e,t)=>{x.writeFileSync(e,t)}),r=t(),o=[],s=[],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=ZH(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(ZH(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 eG=null,tG=!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(tG)return;tG=!0;const e=__name(e=>{eG?.abort(),process.stderr.write(`\n${e}\n`),exitAfterModHostTeardown(lT.INTERRUPTED)},"handleTermination");process.on("SIGINT",()=>e("Interrupted.")),process.on("SIGTERM",()=>e("Terminated."))}async function printMode(e={}){trackCommand({command:"print"}),setupSignalHandlers(),eG=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)]),exitAfterModHostTeardown(o.exitCode)}function resolveLaunchPermissionMode2(e){return e.permissionMode?e.permissionMode:e.plan?"plan":e.dangerouslySkipPermissions?"bypass":void 0}async function isAuthenticated(){return null!==await getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}async function rpcMode(e={}){let t;trackCommand({command:"rpc"}),await isAuthenticated()||(process.stderr.write(CT),process.exit(lT.AUTH_ERROR)),e.model&&setModelOverride(e.model);try{t=await resolvePrintSession(e)}catch(e){const t=e instanceof Error?e.message:String(e);process.stderr.write(`Error: ${t}\n`),process.exit(lT.ERROR)}t.warning&&process.stderr.write(`${t.warning}\n`);const n=await resolvePrintResumeState({sessionId:t.sessionId,priorMessages:t.priorMessages,...t.sessionFilePath?{sessionFilePath:t.sessionFilePath}:{}}),r=await getConfiguredProvider(),o=null!=r&&"command-code"!==r;await runRpcMode({sessionId:t.sessionId,...o?{modelSwitchRefusal:`this session runs on the ${r} provider; start a new one with --model to use another model`}:{},stdin:process.stdin,writeLine:__name(e=>{process.stdout.write(`${e}\n`)},"writeLine"),dangerouslySkipPermissions:e.dangerouslySkipPermissions,createHarness:__name(async({sessionId:r,mods:o,drainQueuedMessages:s,peekQueuedMessageCount:a})=>{const i=await createHarnessSession({sessionId:r,baseUrl:getApiBaseUrl(),entrypoint:resolvePrintHarnessEntrypoint(t.entrypoint),headless:!0,mods:o,drainQueuedMessages:s,peekQueuedMessageCount:a,dangerouslySkipPermissions:e.dangerouslySkipPermissions,permissionMode:resolveLaunchPermissionMode2(e),modHost:await loadCommandModHost({projectMods:Boolean(e.dangerouslySkipPermissions)}),resumeState:n,persist:e.persist,...t.sessionFilePath?{sessionFilePath:t.sessionFilePath}:{},ideBridge:createLocalIdeBridge()});return e.name&&i.setSessionName(e.name),i},"createHarness")}),await new Promise(e=>{process.stdout.write("",()=>e())}),exitAfterModHostTeardown(lT.SUCCESS)}__name(resolveLaunchPermissionMode,"resolveLaunchPermissionMode"),__name(getAuthKey4,"getAuthKey"),__name(readStdin,"readStdin"),__name(writeOutput,"writeOutput"),__name(setupSignalHandlers,"setupSignalHandlers"),__name(printMode,"printMode"),Vt(),PR(),__name(resolveLaunchPermissionMode2,"resolveLaunchPermissionMode"),__name(isAuthenticated,"isAuthenticated"),__name(rpcMode,"rpcMode"),Vt(),PR();var nG=getPackageJson(import.meta.url),rG="string"==typeof nG.version&&nG.version.trim()?nG.version:"unknown";function createSystemOneTransport(){const e=b();return createNodeTransport({baseUrl:getApiBaseUrl(),headers:__name(()=>resolveCommandAuthHeaders({sessionId:e,cliVersion:rG}),"headers")})}function readStdinText(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("timeout reading from stdin"))},3e4);r.unref?.(),process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n)}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}function systemOneUsageHint(e){return`Run it headlessly: cmd -p '{"state": "...", "questions": {"<name>": {"type": "noul", "instructions": "..."}}}' -m ${e}`}async function runSystemOnePrint(e){const t=e.now??Date.now,n=t(),r="json"===e.outputFormat,o=__name((o,s,a=`Error: ${o}\n`)=>r?{exitCode:s,stderrText:a,stdoutText:`${safeJsonStringify({type:"result",subtype:"error",model:e.model,durationMs:t()-n,error:o})}\n`}:{exitCode:s,stderrText:a},"fail");let s=e.query;if(void 0===s||""===s.trim()){if(e.stdinIsTTY)return o(`no request given. ${systemOneUsageHint(e.model)}, or pipe the JSON on stdin`,lT.ERROR);try{s=await e.readStdin()}catch(e){return o(`could not read stdin: ${e instanceof Error?e.message:String(e)}`,lT.ERROR)}}const a=parseSystemOneQuery(s);if(!a.ok)return o(a.error,lT.ERROR);const i=await runSystemOne({transport:e.transport,model:e.model,request:a.request,...e.signal?{signal:e.signal}:{}});if(!i.ok&&"bad-response"===i.kind)return o(i.error,lT.SERVER_ERROR);if(!i.ok){const e=classifyPrintModeError(i.error);return o(e.stderrText.replace(/^\s*Error: /,"").trim(),e.exitCode,e.stderrText)}const{response:l}=i;if(!r){const t={model:l.model??e.model,answers:l.answers,usage:l.usage??{}};return{exitCode:lT.SUCCESS,stdoutText:`${JSON.stringify(t,null,2)}\n`}}const c=safeJsonStringify({type:"result",subtype:"success",model:l.model??e.model,answers:l.answers,usage:l.usage??{},durationMs:t()-n});return{exitCode:lT.SUCCESS,stdoutText:`${c}\n`}}async function ensureAuthenticated(){return ensureCommandAuthenticated({runLogin:__name(async()=>{await runLogin()},"runLogin"),getAuthKey:__name(()=>getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env}),"getAuthKey"),onAuthFailed:__name(()=>{console.error(`${ft.cross} Authentication failed. Please try again with: ${getBinaryCommand()} login`)},"onAuthFailed"),onLoginError:__name(e=>{console.error(`${ft.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:gr,groups:[...getModelGroupsInOrder(),...customModelListGroups()]})}function formatSystemOneModelNote(){const e=["Decision models (headless only)"],t=isJevFree()?"free through September 24, 2026":"$0.042 per 1M input tokens, everything else free";for(const n of XP)e.push(`${n} typed questions in, probabilities out, ${t} — ${systemOneUsageHint(n)}`);return e.join("\n")}async function printModelList(){await loadCustomProviderModels();const e=Boolean(process.stdout.isTTY)&&void 0===process.env.NO_COLOR;process.stdout.write(`${formatModelList({color:e})}\n`),process.stdout.write(`\n${formatSystemOneModelNote()}\n`);const t=getCustomProviderWarningsSync();t.length>0&&process.stderr.write(`\nproviders.json needs attention — ${1===t.length?"one entry":"some entries"} did not load as written:\n${t.map(e=>` ${e}`).join("\n")}\n`)}async function resolveModelFlagOrExit({model:e}){const t=await resolveSelectableModel(e);if(t){if(t.warning&&process.stderr.write(`Note: ${t.warning}\n`),!t.providerId){const e=customProvidersDeclaring(t.modelId);e.length>0&&process.stderr.write(`Note: "${t.modelId}" routes via Command Code; your providers.json also declares it — use ${e.map(e=>`"${e}/${t.modelId}"`).join(" or ")} to route there instead.\n`)}return{modelId:t.modelId,...void 0!==t.providerId?{providerId:t.providerId}:{}}}const n=suggestModel(e),r=n?` Did you mean "${n}"?`:"";process.stderr.write(`Error: unknown model "${e}".${r}\nRun "${getBinaryCommand()} --list-models" to see all available models\n`),process.exit(1)}__name(createSystemOneTransport,"createSystemOneTransport"),__name(readStdinText,"readStdinText"),__name(systemOneUsageHint,"systemOneUsageHint"),__name(runSystemOnePrint,"runSystemOnePrint"),Vt(),PR(),__name(ensureAuthenticated,"ensureAuthenticated"),Vt(),PR(),__name(suggestModel,"suggestModel"),__name(formatModelList,"formatModelList"),__name(formatSystemOneModelNote,"formatSystemOneModelNote"),__name(printModelList,"printModelList"),__name(resolveModelFlagOrExit,"resolveModelFlagOrExit"),Vt(),PR();var oG=!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:B.platform(),arch:B.arch()})}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync(),releaseRemoteLockSync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}async function disconnectMcpServers(){try{await Promise.allSettled([disconnectAllMcpServers(),R$()])}catch{}}function handleShutdownSignal(){oG||(oG=!0,abandonPendingCommandSpan(),Promise.allSettled([shutdownActiveRemote(),disconnectMcpServers(),disposeCommandModHost(),shutdownTelemetry()]).finally(()=>{process.exit(0)}))}async function shutdownAndExit(e=0){oG=!0,abandonPendingCommandSpan();try{await Promise.allSettled([shutdownActiveRemote(),disconnectMcpServers(),disposeCommandModHost(),shutdownTelemetry(jn)])}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=B.platform(),r=B.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 sG=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth");function sandboxRequested(e){return void 0!==e.sandbox&&!1!==e.sandbox}function sandboxValue(e){return"string"==typeof e.sandbox?e.sandbox.trim():""}async function requireSandboxBypassAllowed(){isBypassPermissionsDisabled(await loadCommandCodeConfig({runtime:getCommandConfigRuntime()}))&&(process.stderr.write("Sandbox sessions run without permission prompts, which your settings disable (permissions.disableBypass).\n"),process.exit(1))}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)Vy.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||!0===t.rpc;e||Boolean(t.trust||t.dangerouslySkipPermissions)||await isCommandProjectSessionInitialized()||(console.error(`Worktree error: this directory isn't trusted yet. Run \`${getInvokedCommandName()}\` here once to trust it, then retry with --worktree.`),process.exit(1));const n=enterWorktreeFromFlag(t.worktree,{quiet:e,track:!e});n.ok||(console.error(`Worktree error: ${n.error}`),process.exit(1)),await initializeCommandProjectSessions()}const o=t.model?resolveSystemOneModel(t.model):void 0;if(o){void 0===t.print&&(process.stderr.write(`Error: ${o} is a decision model (TypeSafe System One): it answers typed questions with probabilities, not chat, so it has no interactive mode. ${systemOneUsageHint(o)}\n`),process.exit(1)),await sG(),trackCommand({command:"print"});const n=await runSystemOnePrint({model:o,query:extractPrintModeQuery({print:t.print,prompt:e}),outputFormat:t.outputFormat,stdinIsTTY:Boolean(process.stdin.isTTY),readStdin:readStdinText,transport:createSystemOneTransport()});n.stderrText&&process.stderr.write(n.stderrText),n.stdoutText&&process.stdout.write(n.stdoutText),await shutdownAndExit(n.exitCode)}const a=t.model?await resolveModelFlagOrExit({model:t.model}):void 0,i=a?.modelId,l=t,c=__name(e=>{process.stderr.write(`${e.message}\n`),e.ok||process.exit(1)},"applySettingResult");for(const e of WN){const t=l[e.key];"string"==typeof t&&c(await e.apply(t,{model:i}))}const d=l.config;if(Array.isArray(d))for(const e of d)"string"==typeof e&&c(await applyConfigSetting(e));if((t.dangerouslySkipPermissions||"bypass"===t.permissionMode)&&isBypassPermissionsDisabled(await loadCommandCodeConfig({runtime:getCommandConfigRuntime()}))&&(process.stderr.write("Bypass permissions are disabled by settings (permissions.disableBypass); continuing with normal permission prompts.\n"),t.dangerouslySkipPermissions=!1,"bypass"===t.permissionMode&&(t.permissionMode=void 0)),t.rpc)return void await rpcMode({dangerouslySkipPermissions:t.dangerouslySkipPermissions,plan:t.plan,permissionMode:t.permissionMode,model:i,resume:t.resume,continue:t.continue,..."string"==typeof t.session?{session:t.session}:{},forkSession:t.forkSession,name:t.name,persist:!1!==t.session&&void 0});if(void 0!==t.print&&sandboxRequested(t)){await requireSandboxBypassAllowed(),await sG();const n=sandboxValue(t),r=mD.test(n)?n:null,o=extractPrintModeQuery({print:t.print,prompt:e});return void await runSandboxPrint({sessionId:r,task:r?o:n||o,...t.base?{baseBranch:t.base}:{},...i?{model:i}:{},..."string"==typeof l.effort?{effortGiven:!0}:{}}).catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)})}if(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:i,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})}i&&setModelOverride(i,a?.providerId),setGoalMaxTurnsOverride(t.maxTurns);const u=parseInteractivePromptArgument((sandboxRequested(t)&&!mD.test(sandboxValue(t))?sandboxValue(t):"")||e);await sG();const m=buildInteractiveRuntimeOptions(t),p=resolveInteractiveLaunchConfig({options:t,runtimeOptions:m,initialPrompt:u});if(setOriginalInvocation({trust:m.trust,dangerouslySkipPermissions:m.dangerouslySkipPermissions,skipOnboarding:m.skipOnboarding,maxTurns:t.maxTurns,skillPaths:n,skillDiscovery:r}),await installKeybindingsFromConfig({runtime:getCommandConfigRuntime()}),sandboxRequested(t)){const e=sandboxValue(t),n=mD.test(e)?e:null;return n&&t.base&&(process.stderr.write("--base applies to a new session only; a reopened one stays on its branch.\n"),process.exit(1)),await requireSandboxBypassAllowed(),enableSandboxMode({sessionId:n,...t.base?{baseBranch:t.base}:{}}),await XH({...p,dangerouslySkipPermissions:!0}),void await shutdownAndExit(Number(process.exitCode??0))}await XH(p),await shutdownAndExit(0)}__name(sandboxRequested,"sandboxRequested"),__name(sandboxValue,"sandboxValue"),__name(requireSandboxBypassAllowed,"requireSandboxBypassAllowed"),__name(interactiveModeAction,"interactiveModeAction"),Vt(),PR(),Vt(),PR();var aG={connected:yt.green("✔"),installed:yt.green("✔"),up_to_date:yt.green("✔"),needs_reload:yt.yellow("◌"),failed:yt.red("✖"),not_in_ide:yt.yellow("◌")};function formatSetupResult(e){const{prefix:t,ide:n,suffix:r}=getIDESetupStatusHeadline(e.status,e.ide),o=`${t}${n??""}${r}`;return["",`${aG[e.status]} ${o}`,...(e.details??[]).map(e=>yt.dim(` ${e}`)),""]}__name(formatSetupResult,"formatSetupResult"),globalThis.COMMAND_CODE_CWD=process.cwd();var iG=__name(()=>process.cwd(),"getCwd"),lG=__name(()=>process.argv.slice(2),"getArgs"),cG=__name(()=>{const e=iG(),t=lG(),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(){cG();const e=resolveCliStartupPlan({args:lG()});if(e.shouldRunIdeSetup){const e=await runIdeSetup({host:jW,moduleUrl:import.meta.url});formatSetupResult(e).forEach(e=>console.log(e)),process.exit("failed"===e.status?1:0)}e.shouldRunAutoUpdate&&runCliStartupPendingUpdates({plan:e,host:JW}),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:JW}),scheduleCliStartupIdeAutoInstall({host:jW,moduleUrl:import.meta.url})}__name(getAuthKey6,"getAuthKey"),__name(preRun,"preRun"),Vt(),PR();var dG=Object.fromEntries(Object.entries(Ak).map(([e,t])=>[t,e])),uG=new Set(UD.map(e=>e.id));function formatProviderModule(e){return uG.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=dG[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 UD){if(s.has(e.id))continue;if(!1===e.discoverable)continue;const n=dG[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=[Pt.bold("Providers available for login/logout"),""];for(const r of e){const e=r.authenticated?Pt.green("logged in"):Pt.dim("not logged in"),o=r.installed?"":Pt.dim(" (not installed, installs on first login)");n.push(Pt.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: ${Pt.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(Pt.yellow("Provider load errors"));for(const e of t.errors)console.log(`${Pt.yellow(e.id)}: ${e.error}`)}}__name(formatProviderModule,"formatProviderModule"),__name(buildProviderLoginRows,"buildProviderLoginRows"),__name(formatProviderLoginRows,"formatProviderLoginRows"),__name(providersAction,"providersAction");var mG=new He("providers").description("List providers available for login/logout").option("--json","Output providers as JSON for automation").action(providersAction);function assertSessionId(e){mD.test(e)||(console.error(Pt.red(`Invalid session id: ${e}`)),console.error(Pt.dim(`Find it with: ${getBinaryCommand()} --experimental sandbox list`)),process.exit(1))}function client(){return createSandboxClient({transport:createSandboxTransport()})}function printTaskSummary(e){console.error(`${Pt.dim("Status:")} ${e.status}`),e.prUrl&&console.error(`PR: ${Pt.cyan(e.prUrl)}`),e.error&&console.error(Pt.red(e.error)),console.error(Pt.dim(`Open it with: ${getBinaryCommand()} --experimental --sandbox ${e.sessionId}`))}async function statusSandboxTask(e){assertSessionId(e),printTaskSummary(await client().status({sessionId:e}))}async function stopSandboxTask(e){assertSessionId(e);const{status:t}=await client().cancel({sessionId:e});"cancelled"===t?console.error(Pt.yellow("Session stopped.")):console.error(Pt.yellow(`Session already ${t.replace("_"," ")}.`))}async function listSandboxTasks(){const{sessions:e}=await client().list();if(0!==e.length){console.log(Pt.dim(`${"SESSION".padEnd(38)}${"STATUS".padEnd(12)}${"AGE".padEnd(12)}REPO`));for(const t of e){const e=t.repoUrl.replace(/^https:\/\/github\.com\//,""),n=formatRelativeTimeShort({timestamp:t.createdAt});console.log(`${t.sessionId.padEnd(38)}${t.status.padEnd(12)}${n.padEnd(12)}${Pt.dim(e)}`)}}else console.error("No sandbox sessions yet.")}function run3(e){e().catch(e=>{const t=e instanceof Error?e.message:"Unknown error";console.error(Pt.red(t)),process.exit(1)})}function createSandboxCommand(){const e=new He("sandbox").description("Manage your cloud sandbox sessions").action(()=>{console.log(["Work in a sandbox:"," cmd --experimental --sandbox open a new session (the TUI)"," cmd --experimental --sandbox <id> reopen a session",' cmd --experimental --sandbox "message" open a new session with a first message',' cmd --experimental -p --sandbox "task" run one task, print the session id',' cmd --experimental -p --sandbox <id> "task" send a follow-up task',"Manage sessions:"," cmd --experimental sandbox list | status <id> | stop <id>"].join("\n"))});return e.command("list").description("List your sandbox sessions").action(()=>run3(listSandboxTasks)),e.command("status").description("Show a session summary").argument("<sessionId>").action(e=>run3(()=>statusSandboxTask(e))),e.command("stop").description("Stop a running session").argument("<sessionId>").action(e=>run3(()=>stopSandboxTask(e))),e}Vt(),Vt(),PR(),__name(assertSessionId,"assertSessionId"),__name(client,"client"),__name(printTaskSummary,"printTaskSummary"),__name(statusSandboxTask,"statusSandboxTask"),__name(stopSandboxTask,"stopSandboxTask"),__name(listSandboxTasks,"listSandboxTasks"),__name(run3,"run"),__name(createSandboxCommand,"createSandboxCommand"),Vt(),Vt(),PR();var pG=[`${Pt.dim("Usage:")}`,` ${Pt.cyan(`${getBinaryCommand()} skills add`)} ${Pt.white("<owner/repo>")}`,"",`${Pt.dim("Examples:")}`,` ${Pt.cyan(`${getBinaryCommand()} skills add`)} ${Pt.white("acme/my-skills")} ${Pt.dim("# single-skill repo")}`,` ${Pt.cyan(`${getBinaryCommand()} skills add`)} ${Pt.white("acme/skills/path/to/skill")} ${Pt.dim("# specific path in repo")}`,` ${Pt.cyan(`${getBinaryCommand()} skills add`)} ${Pt.white("acme/multi-skills -s my-skill")} ${Pt.dim("# pick one from multi-skill repo")}`,` ${Pt.cyan(`${getBinaryCommand()} skills add`)} ${Pt.white("acme/repo@branch")} ${Pt.dim("# specific branch")}`,` ${Pt.cyan(`${getBinaryCommand()} skills add`)} ${Pt.white("acme/repo --global")} ${Pt.dim("# install to ~/.commandcode/skills/")}`],gG=__name((e,t)=>`${Pt.green(ft.tick)} Installed ${Pt.cyan(e)} ${Pt.dim(`${ft.arrowRight} ${t}/`)}`,"formatInstalled"),hG=__name(e=>`${Pt.red(ft.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(hG(t.message)),console.log(""),t.message.startsWith("Invalid repository")&&(console.log(`Expected format: ${Pt.cyan("owner/repo")} or ${Pt.cyan("owner/repo/path")}`),console.log("")),pG.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=It({text:`Fetching ${Pt.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(hG(`No skills found in ${Pt.cyan(e)}`)),console.log(Pt.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(o,1)),"missing-requested-skill"===d.kind)return console.error(hG(`Skill "${d.requestedSkillName}" not found in ${Pt.cyan(d.repoInput)}`)),console.log(""),console.log(Pt.dim("Available skills:")),d.availableSkillNames.forEach(e=>console.log(` ${Pt.cyan(e)}`)),void await cleanupAndExit(o,1);if("prompt"===d.kind){const t=await Ye({message:`Select skills to install from ${e}`,options:[...d.options],required:!0});"symbol"==typeof t&&(console.log(Pt.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=It({text:`Installing ${Pt.cyan(e.name)}...`,color:"cyan"}),u.start()},"onSkillStart"),onSkillInstalled:__name(e=>{u?.stop(),console.log(gG(e.name,r))},"onSkillInstalled"),onSkillFailed:__name(({skillName:e,message:t})=>{u?.stop(),console.error(hG(`Failed to install "${e}"`)),console.log(Pt.dim(` ${t}`))},"onSkillFailed")});await cleanupAndExit(o,m.exitCode)}catch(e){s.stop();const t=e instanceof Error?e.message:String(e);console.error(hG(t)),await cleanupAndExit(o,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction2,"addAction");var fG=new He("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${pG.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(hG("No repository specified.")),console.log(""),pG.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction2);Vt(),PR();var yG=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${Pt.cyan(e)} ${Pt.dim(`· ${n}`)}`},"formatSkillLine"),SG=__name((e,t)=>`${Pt.bold(Pt.white(e))} ${Pt.dim(`(${t})`)}`,"formatSectionHeader"),wG=__name(e=>{if(0!==e.warningCount){console.log(""),console.log(`${Pt.bold(Pt.yellow("Skipped"))} ${Pt.dim(`(${e.warningCount})`)}`);for(const t of e.warningGroups){console.log(""),console.log(` ${Pt.bold(t.category)} ${Pt.dim(`(${t.items.length})`)}`);for(const e of t.items)console.log(` ${Pt.bold(skillIdentifier(e.path))}`),console.log(` ${Pt.dim(e.reason)}`)}}},"printWarnings"),vG=__name(e=>{const t=["",Pt.dim("No skills installed."),"",Pt.dim("Looking in:")];for(const n of e.lookupPaths)t.push(Pt.dim(` ${n.path} ${Pt.white(`(${n.label})`)}`));return t.push("",`Install a skill: ${Pt.cyan(e.installCommand)} ${Pt.dim(e.installPlaceholder)}`,""),t},"formatEmptyHint"),kG=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),CG=__name(e=>{e&&(console.log(""),console.log(Pt.dim(e.replace("--debug",Pt.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()}`});kG(vG(t));for(const e of s.sections)console.log(SG(e.title,e.skills.length)),e.skills.forEach(e=>{console.log(yG(e.name,e.description))}),console.log("");e&&(wG({warningCount:s.warningCount,warningGroups:s.warningGroups}),s.warningCount>0&&console.log("")),e||(CG(s.debugHint),console.log("")),process.exit(0)}console.log(""),console.log(heading({text:"Skills",sub:Pt.dim(`${s.userInstalledTotal} installed`)}));for(const e of s.sections)console.log(""),console.log(SG(e.title,e.skills.length)),e.skills.forEach(e=>{console.log(yG(e.name,e.description))});e&&wG({warningCount:s.warningCount,warningGroups:s.warningGroups}),e||CG(s.debugHint),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${Pt.red(ft.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction2,"listAction");var bG=new He("list").description("List all installed skills. Run with -d/--debug to also see why any skills were skipped.").action(listAction2);Vt(),PR();var EG=__name((e,t)=>`${Pt.green(ft.tick)} Removed ${Pt.cyan(e)} from ${t} skills`,"formatRemoved"),TG=__name(e=>`${Pt.red(ft.cross)} ${e}`,"formatError"),PG=__name((e,t)=>{let n=e;for(const e of t)n=n.replace(e,Pt.cyan(e));return Pt.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(TG(o)),console.log(PG(getSkillListCommandHint({binCommand:`${getBinaryCommand()}`}),[`${getBinaryCommand()} skills list`])),process.exit(1)),!t.yes&&n){const t=await Qe({message:`Remove ${Pt.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(Pt.dim("Cancelled")),process.exit(0))}await removeCommandSkill({skillName:e,global:t.global}),console.log(EG(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(TG(o.message)),"not-found"===o.kind)for(const t of o.hints)console.log(PG(t,[`${getBinaryCommand()} skills remove ${e} --global`,`${getBinaryCommand()} skills list`]));process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction2,"removeAction");var MG=new He("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),xG=new He("skills").description("Manage skills from GitHub repositories").addCommand(fG).addCommand(MG).addCommand(bG);Vt(),PR(),Vt(),PR(),Vt(),Vt(),PR();var IG=[ft.bullet,ft.squareSmallFilled,ft.lozenge,ft.star,ft.triangleRight,ft.triangleUp];Vt(),PR(),Vt();var AG=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return AG.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"),Vt(),PR(),Vt(),Vt();var RG=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),o=e.learningCount>0;return it.createElement(Ze,{flexDirection:"column",marginLeft:3},it.createElement(Ze,{marginBottom:1,flexDirection:"row"},it.createElement(et,{color:LR.DIM},TL),it.createElement(Ze,{marginLeft:2},it.createElement(et,{color:DR.TEXT},o?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),it.createElement(Ze,{flexDirection:"column",marginLeft:1},it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},ft.pointerSmall," Taste stored in"," "),it.createElement(yL,{url:fileUrl(e.storage),text:r||".commandcode/taste/taste.md",color:LR.CYAN})),it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},ft.pointerSmall," Share your coding taste:"," ",it.createElement(et,{color:LR.CYAN},"npx taste push --all")))),it.createElement(Ze,{marginTop:1,marginLeft:1},it.createElement(et,{color:LR.DIM},o?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Vt();var LG=__name(({message:e})=>it.createElement(B$,null,e),"RepoLearnErrorPanel");Vt();var OG=__name(({done:e,error:t})=>t?it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Press ",it.createElement(CO,null,"Esc")," to exit")):e?it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to continue")):it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Esc to cancel")),"RepoLearnFooter");Vt(),PR();var DG=__name(({insights:e,insightCount:t})=>0===e.length?null:it.createElement(Ze,{flexDirection:"column",marginTop:1,marginLeft:4},it.createElement(et,{color:LR.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>it.createElement(et,{key:`${t}-${e}`,color:LR.DIM},IG[t%IG.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Vt(),PR();var $G=__name(({status:e})=>"active"===e?it.createElement(Ze,null,it.createElement(et,{color:LR.YELLOW},it.createElement(bt,{type:"dots"})),it.createElement(et,null," ")):"complete"===e?it.createElement(et,{color:FR.BG},ft.square," "):it.createElement(et,{color:LR.DIM},ft.circle," "),"StepStatusIndicator");function getStepLabelColor(e,t){return"complete"===e?LR.WHITE:t?LR.YELLOW:LR.DIM}__name(getStepLabelColor,"getStepLabelColor");var NG=__name(({steps:e,currentMessage:t})=>it.createElement(Ze,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return it.createElement(Ze,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},it.createElement(Ze,null,it.createElement(Ze,{marginRight:1},it.createElement($G,{status:e.status})),it.createElement(et,{bold:n,color:getStepLabelColor(e.status,n)},e.label)),n&&t?it.createElement(Ze,{marginLeft:3},it.createElement(et,{color:LR.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Vt();var _G=__name(({isComplete:e,hasError:t})=>t?it.createElement(et,{color:LR.DIM},"learning interrupted"):e?it.createElement(et,{color:DR.TEXT},"learned your coding taste"):it.createElement(vL,null),"TastePillStatus"),FG=__name(({isComplete:e,hasError:t})=>it.createElement(Ze,{flexDirection:"column",marginTop:1,marginBottom:0},it.createElement(IL,null),it.createElement(Ze,{marginTop:0},it.createElement(et,{color:LR.DIM},TL),it.createElement(Ze,{marginLeft:2},it.createElement(_G,{isComplete:e,hasError:t})))),"RepoLearnTastePill");Vt();var UG=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=mt(()=>cO(n),[n]);return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(nL,null,r.trimEnd())),e?it.createElement(et,{color:LR.WHITE},e):it.createElement(it.Fragment,null,it.createElement(et,{color:LR.WHITE},"Learning your coding taste from"," ",it.createElement(et,{bold:!0,color:LR.CYAN},t??"repository")),it.createElement(et,{color:LR.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function useRepoLearnState(e){const t=e??OI,[n,r]=ct(()=>createRepoLearnProjection({stepOrder:t})),o=dt(null),[s,a]=ct(null),i=pt(()=>{o.current=Date.now()},[]),l=pt(e=>{r(t=>({...t,showLogin:e}))},[]);return ut(()=>{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 up.on("reset",e),up.on("new-event",n),up.on("learning-complete",s),()=>{up.off("reset",e),up.off("new-event",n),up.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?it.createElement(LG,{message:e}):t?it.createElement(RG,{summary:n,elapsedSeconds:r}):it.createElement(DG,{insights:o,insightCount:s})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:o}){const s=useRepoLearnState(n),a=dt(!1);return ut(()=>{a.current||(a.current=!0,s.markStarted(),e().catch(()=>{}))},[e,s.markStarted]),ot((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?it.createElement(Ze,{flexDirection:"column"},it.createElement(UG,{text:r,repoName:o}),it.createElement(jF,{onComplete:(e,t)=>{s.setShowLogin(!1),e?up.resolveAuth():up.rejectAuth(t)},onCancel:()=>{s.setShowLogin(!1),up.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):it.createElement(Ze,{flexDirection:"column"},it.createElement(UG,{text:r,repoName:o}),it.createElement(FG,{isComplete:s.done&&!s.error,hasError:Boolean(s.error)}),it.createElement(NG,{steps:s.steps,currentMessage:s.currentMessage}),it.createElement(StatusPanel,{error:s.error,done:s.done,summary:s.summary,elapsedSeconds:s.elapsedSeconds,insights:s.insights,insightCount:s.insightCount}),it.createElement(OG,{done:s.done,error:s.error}))}async function runRepoLearnProgress(e){return await applyStartupTheme(),withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{up.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,up.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),up.markLearningComplete())}},"handleRunTask"),c=__name(({published:e,cancelled:l})=>{i||(i=!0,a=e,r.abort(),d.unmount(),up.reset(),s?n(s):t({result:o,published:a,cancelled:l}))},"handleExit"),d=rt(it.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:c}));d.waitUntilExit().catch(e=>{up.reset(),n(e)})})}function getAuthKey7(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function logLearnSummary(e){const{summary:t}=e;console.log(yt.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("")}Vt(),PR(),__name(useRepoLearnState,"useRepoLearnState"),__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),__name(getAuthKey7,"getAuthKey"),__name(logLearnSummary,"logLearnSummary");var jG=__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 He("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",jG("--max-commits"),200).addOption(new Ge("--max-signals <number>","Maximum diff signals to extract").default(50).argParser(jG("--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:up,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:[...DI];({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),UL(),await XH({skipOnboarding:!0}),await shutdownAndExit(0)}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Vt(),PR(),Vt(),PR();var BG=yt.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(`${yt.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?`${yt.dim(t[1])}${yt.green(t[2])}${yt.white(t[3]??"")}${t[4]?yt.dim(t[4]):""}`:yt.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${yt.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 WG=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){const n=buildPackageUrl({owner:e,packageName:t});return Lt(`commandcode.ai/${e}/${t}`,n,{fallback:WG})}function getProfileLink(e){const t=buildProfileUrl2(e);return Lt(`commandcode.ai/${e}`,t,{fallback:WG})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return Ot(e,n,{trim:!1})}function logMergeReviewTip(){console.log(yt.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}function handleResultErrors(e){for(const t of e){const e=normalizeTasteResultError(t);console.error(`${yt.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(yt.red(`Error: ${t}`)),await flushAndExit(1)}}}function formatSingleIssue(e,t){const n=[`${e.line?yt.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(yt.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`${yt.green(e)} ${yt.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?yt.red(t.summary):yt.yellow(t.summary),"",...formatIssueGroup(r,yt.red,yt.bold(yt.red("Errors:"))),...formatIssueGroup(o,yt.yellow,yt.bold(yt.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"),Vt(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var HG=createTasteLintService({runtime:createNodeRuntime(),formatValidationIssues:formatValidationIssues});function createLintCommand(){return new He("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 ${yt.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(`${yt.green(ft.tick)} All ${yt.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(yt.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(yt.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 HG.lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(yt.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Vt(),PR();var GG={};__export(GG,{downloadPackage:()=>downloadPackage,downloadRemotePackage:()=>downloadRemotePackage,getAllPackages:()=>getAllPackages,getPackage:()=>getPackage,listPackages:()=>listPackages,writePackage:()=>writePackage,writePackages:()=>writePackages}),Vt(),PR();var VG=createNodeRuntime();function getAuthKey8(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}async function requireAuthKey(){const e=await getAuthKey8();if(!e)throw new Error(`No API key found. Please authenticate with: ${getBinaryCommand()} login`);return e}function storage(){return createTasteRemoteStorage({transport:createNodeTransport({baseUrl:getApiBaseUrl()}),requireAuthKey:requireAuthKey,getAuthKey:getAuthKey8,getAuthenticatedEntity:__name(()=>getAuthenticatedEntity({client:createApiClient({baseUrl:getApiBaseUrl()})}),"getAuthenticatedEntity"),trackError:__name(({error:e,label:t,heading:n,context:r})=>trackError({error:sanitizeErrorForTelemetry({error:e,label:t}),context:{component:qo.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:VG,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 zG=createNodeRuntime(),KG=createTasteLocalStorage({runtime:zG,target:"local-project"}),qG=createTasteLocalStorage({runtime:zG,target:"local-global"});function list(e){return createTasteListService({runtime:zG,localProject:KG,localGlobal:qG,remote:GG}).list(e)}function getUserName(){return getCommandAuthUserName({runtime:getCommandConfigRuntime(),path:getAuthFile()})}function createListCommand(){return new He("list").alias("ls").option("-g, --global","List global packages").addOption(new Ge("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Ge("--staging","Use staging environment").hideHelp()).description(`List available packages ${yt.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}function formatPackageLine(e){return` ${yt.white(e.name)}${e.publicBadge?yt.green(e.publicBadge):""}${e.starsBadge?yt.yellow(e.starsBadge):""}${e.downloadsBadge?yt.gray(e.downloadsBadge):""}${e.padding}${yt.dim.gray(e.statsLabel)}`}function validateListOptions(e){exitWithTasteCliValidation(validateTasteListCliOptions(e))}async function fetchPackages({options:e}){const t=resolveTasteListStorage(e),n=e.remote?It(`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${BG} Packages`),console.log(`${yt.gray("⎿")} ${yt.dim(t)}\n`);const n=projectTasteListView({packages:e,symbols:{star:ft.star,arrowDown:ft.arrowDown}});for(const e of n.rows)console.log(formatPackageLine(e));console.log(yt.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(yt.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"),Vt(),PR(),Vt(),PR();var YG=createNodeRuntime(),QG=createTasteLocalStorage({runtime:YG,target:"local-project"}),JG=createTasteLocalStorage({runtime:YG,target:"local-global"});async function open7(e){try{const t=await createTasteOpenService({runtime:YG,localProject:QG,localGlobal:JG,remote:GG}).resolveOpen(e);return t.success?(await Rt([{file:t.filePath,line:t.lineNumber}]),t):t}catch(e){return classifyTasteOpenError({error:e,platform:Pe.platform})}}function createOpenCommand(){return new He("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 ${yt.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 xt(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${yt.green(ft.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(`${yt.green(ft.tick)} Opened ${yt.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"),Vt(),PR(),Vt(),PR(),Vt();var XG=null,ZG=!1;function setActiveSpinner(e){XG=e}function stopActiveSpinner(e){XG&&(XG.stop(e),XG=null)}function setPrompted(e){ZG=e}function wasPrompted(){return ZG}function logResult(e){if(wasPrompted())return ze.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{summary:t,sourceName:n}=e,r=wasPrompted()?"":`${ft.tick} `,o=t.detailPath?yt.dim(`\n ${shortenPath(t.detailPath)}`):"";return"single-replaced"===t.variant?`${yt.green(r)}Replaced ${yt.green(`'${t.packageName}'`)} taste package in project`+o:"single-merged"===t.variant?`${yt.green(r)}Pulled ${yt.green(`'${t.packageName}'`)} taste package from ${n} ${yt.gray(`(${t.mergeParts.join(", ")})`)}`+o:`${yt.green(r)}Pulled ${yt.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(`${yt.green("Pulled")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`,wasPrompted()?4:0)),t.overwritten.length>0&&r.push(wrapLine(`${yt.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`,wasPrompted()?4:0)),t.skipped.length>0&&r.push(wrapLine(`${yt.dim("Skipped")} (${t.skipped.length}) ${yt.dim(t.skipped.join(", "))}`,wasPrompted()?4:0)),wasPrompted())return r.length>0&&ze.log.message(r.join("\n")),ze.outro(`${t.totalLabel} from ${n}`),void setPrompted(!1);console.log(`${yt.green(ft.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(yt.yellow(o.message))}function beginPrompt(e,t){stopActiveSpinner(),ze.intro(yt.dim(e)),t&&ze.log.message(yt.dim(t)),setPrompted(!0)}function handleCancel(e){ze.isCancel(e)&&(ze.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=ze.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=ze.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),ze.log.warn(e.nonInteractive.warning),e.nonInteractive.strategy;if(beginPrompt(`${e.title.prefix}${yt.green(e.title.emphasis)}${e.title.suffix}`,e.existsMessage),ze.log.message(`${e.context.firstLine}\n${e.context.secondLine}${e.context.secondLineNote?` ${yt.dim(e.context.secondLineNote)}`:""}`),e.reviewLink){const t=Lt(e.reviewLink.text,e.reviewLink.url,{fallback:__name((e,t)=>t,"fallback")});ze.log.info(`${e.reviewLink.prefix}${yt.cyan(t)} ${yt.dim(e.reviewLink.note)}`)}const t=await ze.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"),Vt(),PR(),Vt(),PR(),__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 eV=createNodeRuntime(),tV=createTasteLocalStorage({runtime:eV,target:"local-project"}),nV=createTasteLocalStorage({runtime:eV,target:"local-global"});function service(){return createTastePullService({localProject:tV,localGlobal:nV,remote:GG,getDestinationPath:__name(e=>resolveTastePackageDestinationPathForRuntime({runtime:eV,...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 He("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 Ge("--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 Ge("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${yt.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(It("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(It("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 ze.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?yt.dim(`\n ${shortenPath(e)}`):""}function renderPushSummary(e){const t=wasPrompted()?"":`${ft.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?` ${yt.gray(`(${e.replacedLabel})`)}`:"";return void logResult2(`${yt.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?` ${yt.gray(`(${e.mergeParts.join(", ")})`)}`:"";return void logResult2(`${yt.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(`${yt.green(t)}Pushed ${yt.green(e.count)} taste packages ${yt.green(`(${e.packages.join(", ")})`)} to ${e.targetName}`)):logResult2(`${yt.green(t)}Pushed ${yt.green(`'${e.packageName}'`)} taste package to ${e.locationLabel}`+formatDetailPath(e.detailPath)):logResult2(`${yt.green(t)}Pushed ${yt.green(`'${e.packageName}'`)} taste package to ${e.locationLabel} ${yt.gray(`(${e.mergeParts.join(", ")})`)}`+formatDetailPath(e.detailPath)):logResult2(`${yt.green(t)}Replaced ${yt.green(`'${e.packageName}'`)} taste package in ${e.locationLabel}`+formatDetailPath(e.detailPath))}else logResult2(`${yt.green(t)}Pushed ${e.packageCountLabel} to ${formatAllLocation(e.location)}`)}else logResult2(`${yt.green(t)}Pushed ${e.packageCountLabel} to remote`);else logResult2(`${yt.green(t)}Skipped ${e.packageCountLabel}`)}function logPushUrls(e){for(const t of collectTastePushRemoteLinks(e))console.log(yt.gray(` ${getPackageLink(t)}`))}function logConflictSummary(e){const t=projectTastePushOutcome(e.result),n=[];t.succeeded.length>0&&n.push(wrapLine(`${yt.green("Merged")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`,4)),t.overwritten.length>0&&n.push(wrapLine(`${yt.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`,4)),t.skipped.length>0&&n.push(wrapLine(`${yt.dim("Skipped")} (${t.skipped.length}) ${yt.dim(t.skipped.join(", "))}`,4)),n.length>0&&ze.log.message(n.join("\n")),ze.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(`${yt.green("Pushed")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`)),t.overwritten.length>0&&n.push(wrapLine(`${yt.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`)),t.skipped.length>0&&n.push(wrapLine(`${yt.dim("Skipped")} (${t.skipped.length}) ${yt.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"),Vt(),PR(),Vt(),PR(),__name(logResult2,"logResult"),__name(formatAllLocation,"formatAllLocation"),__name(formatDetailPath,"formatDetailPath"),__name(renderPushSummary,"renderPushSummary"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Vt(),PR();var rV=createNodeRuntime(),oV=createTasteLocalStorage({runtime:rV,target:"local-project"}),sV=createTasteLocalStorage({runtime:rV,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:oV,localGlobal:sV,remote:GG,getUserOwner:getUserOwner,getProjectName:__name(()=>e.basename(process.cwd()),"getProjectName"),getDestinationPath:__name(e=>resolveTastePackageDestinationPathForRuntime({runtime:rV,...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 ze.select({message:"Owner",options:[...r],initialValue:o});return ze.isCancel(s)&&(ze.cancel("Operation cancelled"),process.exit(0)),s}__name(getUserOwner,"getUserOwner"),__name(service2,"service"),__name(push,"push"),__name(pushRemote,"pushRemote"),Vt(),PR(),__name(promptOwnerSelection,"promptOwnerSelection");var aV=createNodeRuntime(),iV=createTasteLocalStorage({runtime:aV,target:"local-project"});function loadUserNamespaces(){return fetchUserNamespaces({client:createApiClient({baseUrl:getApiBaseUrl()})})}function createPushCommand(){return new He("push").description(`Push taste packages to remote ${yt.dim("(commandcode.ai)")} or global ${yt.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 Ge("--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 Ge("--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 iV.getAllPackages()).some(t=>t.category===e),"hasLocalPackage"),loadNamespaces:loadUserNamespaces,prompt:{onPromptStart:__name(({packageName:e})=>{ze.intro(yt.dim(`pushing ${e}`)),setPrompted(!0),t=ze.spinner(),t.start("Resolving")},"onPromptStart"),onPackageMissing:__name(({packageName:e})=>{t?.error("Failed"),ze.outro(yt.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 iV.getAllPackages()).length),r=e.basename(process.cwd()),o=resolveTasteStrategyLabel({strategy:t.route.strategy,isRemote:!0});console.log(yt.dim(` Pushing ${n} to ${r} (remote)${o}`)),console.log(""),setActiveSpinner(It("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=ze.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(It("Pushing taste package").start())}async function pushGlobal(e){const t=await iV.getAllPackages(),n=formatTastePackageCount(e.route.packages.length>0?e.route.packages.length:t.length),r=shortenPath(getTastePathForRuntime({runtime:aV,target:"local-global"})),o=resolveTasteStrategyLabel({strategy:e.route.strategy});console.log(yt.dim(` Pushing ${n} to ${r}${o}`)),console.log(""),setActiveSpinner(It("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(`${yt.green(ft.tick)} Taste learning is on${whereFor(e)}. New preferences are saved and reused across sessions.`)}function reportDisabled(e){const t=getBinaryCommand();console.log(`${yt.green(ft.tick)} Taste learning is off${whereFor(e)}. Turn it back on with ${yt.cyan(`${t} taste enable`)}.`)}function createEnableCommand(){return new He("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 He("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 He("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"),Vt(),PR(),__name(scopeOf,"scopeOf"),__name(whereFor,"whereFor"),__name(applyTasteLearning,"applyTasteLearning"),__name(reportEnabled,"reportEnabled"),__name(reportDisabled,"reportDisabled"),__name(createEnableCommand,"createEnableCommand"),__name(createDisableCommand,"createDisableCommand"),__name(createTasteCommand,"createTasteCommand"),Vt(),PR();var lV=`${getBinaryCommand()}`;function formatVersion(e,t,n=!1){const r=n?Pt.bold(Pt.green(t)):Pt.white(t);return`${Pt.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(`${lV} update`,Pt.bold(Pt.green(`${lV} update`))))}function showUpdateSuccessHint(e){for(const t of e.detailLines)console.log(Pt.dim(t.replace(lV,Pt.cyan(lV))))}function showManualUpdateHint(e){const[t,n]=e.manualUpdateLines;t&&console.log(Pt.dim(t)),n&&console.log(Pt.cyan(n))}function showCheckFailure(e){for(const t of e.detailLines)console.log(Pt.dim(t))}function renderUpdateEvent(e,t){if("type"in e)"updating"===e.type&&(t.text=e.text.replace("→",ft.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(`${Pt.green(ft.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=It("Checking for updates...").start(),n=await runCliUpdateCommand({checkOnly:e.checkOnly,host:JW,copy:{binCommand:lV,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:qo.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 cV=new He("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})}Vt(),PR(),__name(getAuthKey9,"getAuthKey");var dV=__name((e,t)=>`${ft.info} ${e}: ${Pt.cyan(t)}`,"formatInfoLine"),uV=__name(e=>Pt.bold(`${e}:`),"formatSectionHeader"),mV=__name(e=>Pt.red(e),"formatError"),pV=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),gV=__name((e,t)=>["",uV(e),...t.map(e=>dV(e.label,e.value))],"buildSection"),hV=__name(e=>gV("User Information",projectWhoamiUserRows(e)),"buildUserOutput"),fV=__name(e=>gV("Organization",projectWhoamiOrgRows(e)),"buildOrgOutput"),yV=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),SV=__name((e,t)=>{yV(hV(e)),t&&yV(fV(t)),console.log("")},"displayUserInfo");async function whoamiAction(){const e=It("Fetching user information...").start();try{hasCommandApiKey(await getAuthKey9())||(e.fail(mV(Yt)),process.exit(1));const t=await getAuthenticatedEntity({client:createApiClient({baseUrl:getApiBaseUrl()})});isAuthenticatedEntityLoaded(t)||(e.fail(mV(Qt)),process.exit(1)),e.succeed("User information loaded"),SV(t.user,t.org)}catch(t){e.fail(mV(`Error: ${pV(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var wV=new He("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 vV=createProgram();vV.action(interactiveModeAction),vV.addCommand(i$),vV.addCommand(y$),vV.addCommand(wV),vV.addCommand(cV),vV.addCommand(a$),vV.addCommand(s$),vV.addCommand(createTasteCommand()),vV.addCommand(createMcpCommand()),vV.addCommand(dN),vV.addCommand(e$),vV.addCommand(KD),vV.addCommand(ZD),vV.addCommand(mG),vV.addCommand(xG),vV.addCommand(AN),isExperimentalEnabled()&&vV.addCommand(createSandboxCommand()),addExperimentalRootOptions(vV),setupCommanderHooks(vV),vV.parse();
14
+ `,mO=getMaxLineWidth(uO),pO=lO,gO=__name(e=>{const t=e??getTerminalWidth();return t>=iO?"full":t>=pO?"compact":"minimal"},"getHeaderLayout");new Set(["dark","light"]),Vt(),PR();var hO=!1;async function resolveStartupTheme(){return hO||(hO=!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=Jo}=e,[s,a]=ct("initializing"),[i,l]=ct("Starting authentication..."),[c,d]=ct(""),[u,m]=ct(null),p=dt(t),g=dt(n),h=dt(r);ut(()=>{p.current=t,g.current=n,h.current=r});const f=dt(null);f.current??=createAuthFlowController({timeoutMs:o,openBrowser:__name(e=>xt(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=pt(()=>{y.cancel()},[y]),w=pt(e=>y.submitApiKey(e),[y]);return ut(()=>(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]=ct(r??(e||"").length),a=dt(o),i=dt(e);ut(()=>{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=pt(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,transformPaste:a,deferEmptyPaste:i=!1}){const l=dt(!1),c=dt(a);c.current=a;const d=dt(i);d.current=i,ut(()=>{if(!e)return;const a=process.stdin,i=__name(e=>{o(!0);const t=clampCursor(e.cursor,e.value.length);r(e.value,t),setTimeout(()=>o(!1),0)},"emitStdinResult"),u=__name(e=>{const r=e.toString();if(s){const e=processBracketedPasteInput({input:r,value:t.current,cursor:n.current,transform:c.current});if(e.handled)return void(e.value===t.current&&d.current||i(e))}const o=processRawInput(r,t.current,n.current);o.handled&&i(o)},"handleRawInput");if(a.on("data",u),!l.current&&hasBufferedInput()){l.current=!0;const e=consumeBufferedInput();e&&u(Buffer.from(e))}return stopEarlyInputCapture(),()=>{a.off("data",u)}},[e,t,n,r,o,s])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:o,onUpdate:s,onSubmit:a}){ot((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=dt(e);return t.current=e,t}function useEchoAwareValueRef(e){const t=dt(e),n=dt([]),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:pt(e=>{n.current.push(e),n.current.length>64&&n.current.shift()},[])}}__name(resolveStartupTheme,"resolveStartupTheme"),__name(applyStartupTheme,"applyStartupTheme"),Vt(),Vt(),PR(),__name(useAuthFlow,"useAuthFlow"),Vt(),PR(),Vt(),PR(),Vt(),PR(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef"),__name(useEchoAwareValueRef,"useEchoAwareValueRef"),Vt(),PR();var fO=yt.hex(LR.DIM),yO=__name(e=>yt.hex(QR.CODE)(e),"accentHex"),SO=/^\/[A-Za-z0-9][\w/:-]*/,wO=/(^|\s)(@\S+)/g;function pastedTokenRanges(e,t){const n=[],r=new RegExp(bM.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(EM.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=SO.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(wO.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?Pt.inverse(" ")+"\n":Pt.inverse(t):t}return s}function renderTokenSpan(e,t,n,r,o,s="dim"){const a="accent"===s?yO:fO;return o&&r>=t&&r<n?a(e.slice(t,r))+Pt.inverse(e[r])+a(e.slice(r+1,n)):a(e.slice(t,n))}function renderPlaceholder(e,t){return t?0===e.length?Pt.inverse(" "):Pt.inverse(e[0])+fO(e.slice(1)):fO(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 Pt.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+=Pt.inverse(" ")),i}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(kt(e).length<=s)return e;const a=e.split(/(\s+)/);let i="",l=0,c=!0;for(const e of a){const t=kt(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=kt(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"),PR();var vO={white:Pt.white,green:Pt.green,red:Pt.red,blue:Pt.blue,yellow:Pt.yellow,cyan:Pt.cyan,magenta:Pt.magenta,gray:Pt.gray,grey:Pt.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,clipboardOnEmptyPaste:g=!1,collapsePastedText:h=!1,onPasteCollapsed:f,initialCursor:y,imageTokenLinks:S,isRecognizedSlashCommand:w}){const v=dt(!1),k=dt(0),{valueRef:C,noteEmittedValue:b}=useEchoAwareValueRef(e),E=useSyncedRef(s),T=useSyncedRef(f),{cursor:P,setCursor:M,cursorRef:x}=useCursorState({value:e,focus:n,showCursor:o,initialCursor:y});it.useEffect(()=>{i?.(P)},[P,i]);const I=pt((e,t)=>{M(t),e!==C.current&&(b(e),C.current=e,E.current(e))},[M,C,E,b]),A=pt(e=>{const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");return h&&isPasteWorthCollapsing({content:t,multiline:!0})?(T.current?.(t),pastedTextToken(t)):e},[h,T]),R=pt(e=>{v.current=e},[]),L=pt(()=>v.current||k.current>0,[]);useRawStdinHandler({focus:n,valueRef:C,cursorRef:x,onUpdate:I,setHandled:R,stripBracketedPaste:m,transformPaste:A,deferEmptyPaste:g}),it.useEffect(()=>{if(!n||p)return;let e=!0;const t=registerPasteConsumer(t=>{v.current||__name(async()=>{let n=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n");if(0===n.length){if(!g)return;k.current+=1;try{const e=await detectClipboardText();n=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}finally{k.current-=1}if(!e||!n)return}const r=A(n),o=insertTextAt(C.current,x.current,r);I(o.text,o.cursor)},"applyRoutedPaste")().catch(()=>{})});return()=>{e=!1,t()}},[n,p,g,A,C,x,I]),useInkInputHandler({focus:n,showCursor:o,valueRef:C,cursorRef:x,isHandledByStdin:L,onUpdate:I,onSubmit:a});const{stdout:O}=nt(),D=O?.columns??80,$=getMaskedValue(e,r),N=c?vO[c]:void 0,_=l?N?N(l):l:"",F=getDisplayValue($,t,P,o,n,S,w),U=l?.length??0,j=_+F;if(d){const e=j.replace(/\n/g," ");return null!=u?it.createElement(Ze,{width:u},it.createElement(et,{wrap:"truncate"},e)):it.createElement(et,{wrap:"truncate"},e)}const B=wrapWithIndent(j,D,U);return it.createElement(et,{wrap:"wrap"},B)}__name(TextInput,"TextInput"),Vt();var kO=__name(({children:e})=>it.createElement(et,{italic:!0,color:LR.DIM},e),"HintText"),CO=__name(({children:e})=>it.createElement(et,{bold:!0},e),"HintKey"),bO=__name(({hints:e,marginTop:t=1})=>{const n=e.filter(e=>null!=e&&!1!==e&&""!==e);return 0===n.length?null:it.createElement(Ze,{marginTop:t},it.createElement(kO,null,n.map((e,t)=>it.createElement(it.Fragment,{key:t},t>0&&" · ",e))))},"HintBar");Vt();var EO=OR,TO=LR.DIM,PO=LR.DIMMER,MO=OR,xO=LR.WHITE,IO=LR.GRAY,AO=LR.GREEN;function hasContent(e){return null!=e&&""!==e}__name(hasContent,"hasContent");var RO=__name(({title:e,titleSuffix:t,subtitle:n,children:r,hint:o,footer:s,rule:a=!0,titleColor:i=EO,ruleColor:l=PO,gapAfterHeader:c=!0,boxProps:d})=>{const u=hasContent(n);return it.createElement(Ze,{flexDirection:"column",width:"100%",...d},a&&it.createElement(iL,{dividerColor:l}),it.createElement(Ze,null,it.createElement(et,{bold:!0,color:i},e),hasContent(t)&&it.createElement(et,{color:TO},t)),u?it.createElement(Ze,{marginBottom:c?1:0},it.createElement(et,{color:TO},n)):c&&it.createElement(Ze,{marginBottom:1}),r,s?it.createElement(Ze,{marginTop:1},s):o?it.createElement(Ze,{marginTop:1},it.createElement(et,{italic:!0,color:TO},o)):null)},"Overlay"),LO=it.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 it.createElement(it.Fragment,null,s&&it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?LR.YELLOW:LR.GRAY,paddingX:1},it.createElement(et,{color:LR.DIM},"API Key: "),it.createElement(Ze,{flexGrow:1},it.createElement(TextInput,{value:n,onChange:r,onSubmit:o,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},getCommandAuthHelpText(e))),a&&it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(et,{color:LR.DIM},getCommandAuthUrlLabel(e)),it.createElement(yL,{url:t,text:t,color:LR.CYAN,dimColor:!0}))),"validating"===e&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"invalid_key"===e)&&it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"ctrl+c to cancel")))});LO.displayName="AuthInputSection";var OO=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s})=>{const a=__name(()=>"waiting_browser"===e?it.createElement(bt,{type:"dots"}):"browser_success"===e||"success"===e?it.createElement(et,{color:LR.GREEN},ft.tick):"denied"===e||"invalid_key"===e?it.createElement(et,{color:LR.RED},ft.cross):"manual_entry"===e?it.createElement(et,{color:LR.YELLOW},ft.arrowDown):"error"===e?it.createElement(et,{color:LR.RED},ft.warning):it.createElement(bt,{type:"dots"}),"getStatusIcon"),i=__name(()=>getCommandAuthStatusColor(e),"getStatusColor");return"browser_success"===e||"success"===e||"denied"===e?null:it.createElement(RO,{title:"Sign in to Command Code"},it.createElement(Ze,{marginBottom:1},it.createElement(Ze,{marginRight:1},a()),it.createElement(et,{color:i()},t)),it.createElement(LO,{authState:e,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s}))},"AuthFlowUI"),DO=__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 ot((e,t)=>{t.ctrl&&"c"===e&&i()}),it.createElement(OO,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a})},"LoginWithApiKey");Vt(),PR();var $O=getPackageJson(import.meta.url),NO="string"==typeof $O.version&&$O.version.trim()?$O.version:"unknown";function createApiClient(e){return createCommandApiClient({baseUrl:e.baseUrl,timeout:e.timeout,cliVersion:NO,deps:{getAuthKey:getAuthKey,getTraceId:getTraceId,getTelemetryEnv:getTelemetryEnv,trackApiCallStart:trackAPICallStart,cmdZdrEnabled:__name(()=>"1"===process.env.CMD_ZDR,"cmdZdrEnabled"),deepseekInternalEnabled:__name(()=>"1"===process.env.CMD_PROVIDER_DEEPSEEK_INTERNAL,"deepseekInternalEnabled")}})}function getAuthKey(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function isJevFree(e=Date.now()){return e<=Date.parse("2026-09-24T23:59:59Z")}function isLingFlashFreeEnded(e=new Date){return e.getTime()>=Date.parse("2026-08-03T13:00:00Z")}__name(createApiClient,"createApiClient"),__name(getAuthKey,"getAuthKey"),Vt(),PR(),Vt(),Vt(),__name(isJevFree,"isJevFree"),Vt(),__name(isLingFlashFreeEnded,"isLingFlashFreeEnded"),Vt();var _O={GENERATE:"/alpha/agent/generate"},FO={RECORD:"/alpha/fingerprint/record"},UO={START:"/alpha/sandbox/start",SESSIONS:"/alpha/sandbox/sessions"},jO={CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",APPEND:"/alpha/share/append"},BO={CREATE:"/alpha/devrel-thread/create",DELETE:"/alpha/devrel-thread/delete",UPDATE:"/alpha/devrel-thread/update"},WO={GET:"/alpha/taste/:projectSlug",UPDATE:"/alpha/taste/:projectSlug/update",DELETE:"/alpha/taste/:projectSlug",LEARN:"/alpha/learn"},HO={CREDITS:"/alpha/billing/credits",SUBSCRIPTIONS:"/alpha/billing/subscriptions"},GO={SUMMARY:"/alpha/usage/summary"},VO={TRACK:"/alpha/lifecycle-events"},zO={GET:/\/internal\/orgs\/[a-zA-Z0-9_-]+/,FOLLOW:/\/internal\/orgs\/[a-zA-Z0-9-]+\/follow/,FOLLOWERS:/\/internal\/orgs\/[a-zA-Z0-9-]+\/followers/},KO={FOLLOW:/\/internal\/users\/[a-zA-Z0-9-]+\/follow/,FOLLOWERS:/\/internal\/users\/[a-zA-Z0-9-]+\/followers/,FOLLOWING:/\/internal\/users\/[a-zA-Z0-9-]+\/following/},qO={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/}),_O.GENERATE,FO.RECORD,UO.START,UO.SESSIONS,jO.CREATE,jO.DELETE,jO.APPEND,BO.CREATE,BO.DELETE,BO.UPDATE,WO.LEARN,WO.DELETE,WO.GET,WO.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"}),HO.CREDITS,HO.SUBSCRIPTIONS,GO.SUMMARY,VO.TRACK,Object.values(zO),Object.values(KO),Object.values(qO.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 YO="anthropic",QO="openai",JO="baseten",XO="vercel-ai-gateway",ZO="cloudflare-ai-gateway",eD="cmd-ai",tD="openrouter",nD="alibaba",rD="alibaba-intl",oD="novita",sD="morph",aD="wafer",iD="longcat",lD="tencent",cD="terminal",dD=XO,uD={[YO]:[{id:"anthropic:claude-sonnet-5-5",provider:"Anthropic",category:"opensource",promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:4,cacheHitCost:.2},{id:"anthropic:claude-sonnet-5",provider:"Anthropic",category:"premium",promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:4,cacheHitCost:.2},{id:"anthropic:claude-sonnet-4-20250514",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-sonnet-4-5-20250929",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-opus-4-5-20251101",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-sonnet-4-6",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-fable-5-1",provider:"Anthropic",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:20,cacheHitCost:.25},{id:"anthropic:claude-fable-5",provider:"Anthropic",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:20,cacheHitCost:1},{id:"anthropic:claude-opus-5-5",provider:"Anthropic",category:"premium",promptCost:4,completionCost:20,cacheWrite5mCost:5,cacheWrite1hCost:8,cacheHitCost:.2},{id:"anthropic:claude-opus-5",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-8",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-7",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-6",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-haiku-4-5-20251001",provider:"Anthropic",category:"premium",promptCost:1,completionCost:5,cacheWrite5mCost:1.25,cacheWrite1hCost:2,cacheHitCost:.1}],[QO]:[{id:"openai:gpt-6-astra",provider:"OpenAI",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:0,cacheHitCost:1,contextTiers:[{maxInputTokens:272e3,promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:0,cacheHitCost:1},{promptCost:20,completionCost:75,cacheWrite5mCost:25,cacheWrite1hCost:0,cacheHitCost:2}]},{id:"openai:gpt-6.1-sol",provider:"OpenAI",category:"premium",promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.1,contextTiers:[{maxInputTokens:272e3,promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.1},{promptCost:4,completionCost:15,cacheWrite5mCost:5,cacheWrite1hCost:0,cacheHitCost:.2}]},{id:"openai:gpt-6-sol",provider:"OpenAI",category:"premium",promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.2,contextTiers:[{maxInputTokens:272e3,promptCost:2,completionCost:10,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.2},{promptCost:4,completionCost:15,cacheWrite5mCost:5,cacheWrite1hCost:0,cacheHitCost:.4}]},{id:"openai:gpt-6-luna",provider:"OpenAI",category:"opensource",promptCost:.1,completionCost:.5,cacheWrite5mCost:.125,cacheWrite1hCost:0,cacheHitCost:.01,contextTiers:[{maxInputTokens:272e3,promptCost:.1,completionCost:.5,cacheWrite5mCost:.125,cacheWrite1hCost:0,cacheHitCost:.01},{promptCost:.2,completionCost:.75,cacheWrite5mCost:.25,cacheWrite1hCost:0,cacheHitCost:.02}]},{id:"openai:gpt-5.5",provider:"OpenAI",category:"premium",promptCost:5,completionCost:30,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.4",provider:"OpenAI",category:"premium",promptCost:2.5,completionCost:15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.25},{id:"openai:gpt-5.3-codex",provider:"OpenAI",category:"premium",promptCost:2,completionCost:8,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.4-mini",provider:"OpenAI",category:"premium",promptCost:.75,completionCost:4.5,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.075},{id:"openai:gpt-5.6-sol",provider:"OpenAI",category:"premium",promptCost:5,completionCost:30,cacheWrite5mCost:6.25,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.6-terra",provider:"OpenAI",category:"premium",promptCost:2,completionCost:12,cacheWrite5mCost:2.5,cacheWrite1hCost:0,cacheHitCost:.2},{id:"openai:gpt-5.6-luna",provider:"OpenAI",category:"premium",promptCost:.2,completionCost:1.2,cacheWrite5mCost:.25,cacheWrite1hCost:0,cacheHitCost:.02}],[JO]:[{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}],[oD]:[{id:"novita:moonshotai/Kimi-K3",provider:"Novita",category:"opensource",promptCost:3,completionCost:15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.3},{id:"novita:zai-org/GLM-5.3",provider:"Novita",category:"opensource",promptCost:1.4,completionCost:4.4,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.26},{id:"novita:deepseek/deepseek-v4.1-flash",provider:"Novita",category:"opensource",promptCost:.15,completionCost:.6,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.003},{id:"novita:deepseek/deepseek-v4-flash",provider:"Novita",category:"opensource",promptCost:.15,completionCost:.6,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.003},{id:"novita:z-ai/glm-5.3-flash",provider:"Novita",category:"opensource",promptCost:.15,completionCost:.5,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.03},{id:"novita:inclusionai/ling-3.1-flash:free",provider:"Novita",category:"opensource",promptCost:0,completionCost:0,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0}],[XO]:[],[tD]:[]};Se.enum(["owner","admin","member"]);var mD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,pD="chatComplete",gD="responses",hD="MiniMaxAI/MiniMax-M3-Free",fD={SONNET_5_5:{id:"claude-sonnet-5-5",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Sonnet 5.5",name:"Claude Sonnet 5.5",description:"best combo of speed & intelligence (recommended)",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},SONNET_5:{id:"claude-sonnet-5",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Sonnet 5",name:"Claude Sonnet 5",description:"prev Sonnet, still fast & capable",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},SONNET_4_6:{id:"claude-sonnet-4-6",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Sonnet 4.6",name:"Claude Sonnet 4.6",description:"older Sonnet, still fast & capable",reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},FABLE_5_1:{id:"claude-fable-5-1",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Fable 5.1",name:"Claude Fable 5.1",description:"most capable for demanding reasoning & long-horizon agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},FABLE_5:{id:"claude-fable-5",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Fable 5",name:"Claude Fable 5",description:"prev Fable, still strong for deep reasoning & agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_5_5:{id:"claude-opus-5-5",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Opus 5.5",name:"Claude Opus 5.5",description:"most intelligent Opus for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_5:{id:"claude-opus-5",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Opus 5",name:"Claude Opus 5",description:"prev flagship, still strong for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_4_8:{id:"claude-opus-4-8",inputModalities:["text","image"],provider:YO,spec:pD,label:"Claude Opus 4.8",name:"Claude Opus 4.8",description:"older Opus, still strong for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_4_7:{id:"claude-opus-4-7",inputModalities:["text","image"],provider:YO,spec:pD,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:YO,spec:pD,label:"Claude Haiku 4.5",name:"Claude Haiku 4.5",description:"fastest & most compact, great for quick tasks",contextWindow:2e5},GPT_6_ASTRA:{id:"gpt-6-astra",inputModalities:["text","image"],provider:QO,spec:gD,label:"GPT-6 Astra",name:"GPT-6 Astra",description:"most capable OpenAI model for demanding reasoning & agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_6_1_SOL:{id:"gpt-6.1-sol",inputModalities:["text","image"],provider:QO,spec:gD,label:"GPT-6.1 Sol",name:"GPT-6.1 Sol",description:"near-Astra performance for complex work at a lower cost",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_6_SOL:{id:"gpt-6-sol",inputModalities:["text","image"],provider:QO,spec:gD,label:"GPT-6 Sol",name:"GPT-6 Sol",description:"built for complex coding & agentic workflows",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_6_LUNA:{id:"gpt-6-luna",inputModalities:["text","image"],provider:QO,spec:gD,label:"GPT-6 Luna",name:"GPT-6 Luna",description:"most efficient OpenAI model for focused, high-volume tasks",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:105e4},GPT_5_6_SOL:{id:"gpt-5.6-sol",inputModalities:["text","image"],provider:XO,spec:gD,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:XO,spec:gD,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:XO,spec:gD,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:QO,spec:gD,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:QO,spec:gD,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:QO,spec:gD,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:QO,spec:gD,label:"GPT-5.4 Mini",name:"GPT-5.4 Mini",description:"fast, cost-effective model for everyday tasks",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:4e5},MINIMAX_M3_PROMO_FREE:{id:hD,inputModalities:["text","image"],provider:dD,spec:pD,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",badge:"free",hidden:!0,reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},DEEPSEEK_V4_PRO:{id:"deepseek/deepseek-v4-pro",inputModalities:["text"],provider:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,label:"DeepSeek V4 Flash Vision (exp)",name:"DeepSeek V4 Flash Vision (exp)",description:"fast hybrid-attention reasoning with vision",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},DEEPSEEK_V4_FLASH_FAST:{id:"deepseek/deepseek-v4-flash-fast",inputModalities:["text"],provider:dD,spec:pD,label:"DeepSeek V4 Flash Fast",name:"DeepSeek V4 Flash Fast",description:"low-latency V4 Flash deployment",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},DEEPSEEK_V4_1_FLASH:{id:"deepseek/deepseek-v4.1-flash",inputModalities:["text","image"],provider:dD,spec:pD,label:"DeepSeek V4.1 Flash",name:"DeepSeek V4.1 Flash",description:"V4.1 hybrid-attention reasoning with vision",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},DEEPSEEK_V4_1_FLASH_FAST:{id:"deepseek/deepseek-v4.1-flash-fast",inputModalities:["text","image"],provider:dD,spec:pD,label:"DeepSeek V4.1 Flash Fast",name:"DeepSeek V4.1 Flash Fast",description:"High throughput V4.1 Flash",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},KIMI_K3:{id:"moonshotai/Kimi-K3",inputModalities:["text","image"],provider:dD,spec:pD,label:"Kimi K3",name:"Kimi K3",description:"long-horizon coding & knowledge work with 1M context",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6},KIMI_K2_7_CODE:{id:"moonshotai/Kimi-K2.7-Code",inputModalities:["text","image"],provider:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,label:"Kimi K2.5",name:"Kimi K2.5",description:"multimodal frontend coding",contextWindow:256e3},GLM_5_3_FLASH:{id:"z-ai/glm-5.3-flash",inputModalities:["text","image"],provider:dD,spec:pD,label:"GLM-5.3 Flash",name:"GLM-5.3 Flash",description:"fast, affordable GLM coding with 1M context",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1048576,maxOutputTokens:131072},GLM_5_3_FLASHX:{id:"z-ai/glm-5.3-flashx",inputModalities:["text","image"],provider:dD,spec:pD,label:"GLM-5.3 FlashX",name:"GLM-5.3 FlashX",description:"high-speed GLM-5.3 Flash with 1M context",reasoning:!0,reasoningEfforts:["low","high","max"],contextWindow:1e6,maxOutputTokens:131072},GLM_5_3:{id:"zai-org/GLM-5.3",inputModalities:["text"],provider:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,label:"GLM-5.1",name:"GLM-5.1",description:"long-horizon autonomous coding agent"},GLM_5:{id:"zai-org/GLM-5",inputModalities:["text"],provider:dD,spec:pD,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:dD,spec:pD,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},MINIMAX_M2_7:{id:"MiniMaxAI/MiniMax-M2.7",inputModalities:["text"],provider:dD,spec:pD,label:"MiniMax M2.7",name:"MiniMax M2.7",description:"end-to-end software engineering agent"},MINIMAX_M3_FREE:{id:"minimax/minimax-m3-free",inputModalities:["text","image"],provider:dD,spec:pD,label:"MiniMax M3",name:"MiniMax M3 (Free)",description:"frontier coding, agents & native multimodality",badge:"free",hidden:!0,reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},MINIMAX_M2_7_FREE:{id:"minimax/minimax-m2.7-free",inputModalities:["text"],provider:dD,spec:pD,label:"MiniMax M2.7",name:"MiniMax M2.7 (Free)",description:"end-to-end software engineering agent",badge:"free",hidden:!0,contextWindow:197e3},MINIMAX_M2_5:{id:"MiniMaxAI/MiniMax-M2.5",inputModalities:["text"],provider:dD,spec:pD,label:"MiniMax M2.5",name:"MiniMax M2.5",description:"cross-platform full-stack agentic dev",contextWindow:2e5},XIAOMI_MIMO_V2_6_PRO:{id:"xiaomi/mimo-v2.6-pro",inputModalities:["text","image"],provider:dD,spec:pD,label:"MiMo V2.6 Pro",name:"MiMo V2.6 Pro",description:"flagship multimodal agentic coding with 1M context",contextWindow:1048576},XIAOMI_MIMO_V2_6_PRO_ULTRASPEED:{id:"xiaomi/mimo-v2.6-pro-ultraspeed",inputModalities:["text","image"],provider:dD,spec:pD,label:"MiMo V2.6 Pro UltraSpeed",name:"MiMo V2.6 Pro UltraSpeed",description:"low-latency serving tier of MiMo V2.6 Pro",contextWindow:1048576},XIAOMI_MIMO_V2_6_FLASH:{id:"xiaomi/mimo-v2.6-flash",inputModalities:["text","image"],provider:dD,spec:pD,label:"MiMo V2.6 Flash",name:"MiMo V2.6 Flash",description:"efficient multimodal agentic coding with 1M context",contextWindow:1048576},XIAOMI_MIMO_V2_5_PRO:{id:"xiaomi/mimo-v2.5-pro",inputModalities:["text"],provider:dD,spec:pD,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:dD,spec:pD,label:"MiMo V2.5",name:"MiMo V2.5",description:"efficient long-context agentic coding",contextWindow:1e6},QWEN_3_8_OMNI_FLASH:{id:"Qwen/Qwen3.8-Omni-Flash",inputModalities:["text","image"],provider:dD,spec:pD,label:"Qwen 3.8 Omni Flash",name:"Qwen 3.8 Omni Flash",description:"omni-modal understanding & multimedia agentic work",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6,maxOutputTokens:131072},QWEN_3_8_MAX_0902:{id:"Qwen/Qwen3.8-Max-0902",inputModalities:["text","image"],provider:dD,spec:pD,label:"Qwen 3.8 Max 0902",name:"Qwen 3.8 Max 0902",description:"upgraded Qwen 3.8 Max: stronger coding & agentic tool use",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6},QWEN_3_8_MAX:{id:"Qwen/Qwen3.8-Max",inputModalities:["text","image"],provider:dD,spec:pD,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:dD,spec:pD,label:"Qwen 3.8 27B",name:"Qwen 3.8 27B",description:"compact vision-language coding & agentic work",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:262144,maxOutputTokens:32768},QWEN_3_8_FLASH:{id:"Qwen/Qwen3.8-Flash",inputModalities:["text","image"],provider:dD,spec:pD,label:"Qwen 3.8 Flash",name:"Qwen 3.8 Flash",description:"fast low-cost agentic coding & reasoning",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:1e6},QWEN_3_7_MAX:{id:"Qwen/Qwen3.7-Max",inputModalities:["text"],provider:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,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:dD,spec:pD,label:"Qwen 3.6 Plus",name:"Qwen 3.6 Plus",description:"agentic coding & reasoning",reasoning:!0},LONGCAT_2:{id:"meituan/LongCat-2.0",inputModalities:["text"],provider:dD,spec:pD,label:"LongCat 2.0",name:"LongCat 2.0",description:"trillion-parameter agentic coding with 1M context",reasoning:!0,contextWindow:1048576},LONGCAT_2_FREE:{id:"meituan/LongCat-2.0:free",inputModalities:["text"],provider:dD,spec:pD,label:"LongCat 2.0",name:"LongCat 2.0 (Free)",description:"trillion-parameter agentic coding with 1M context",badge:"free",hidden:!0,reasoning:!0,contextWindow:1048576},STEP_5_PREVIEW:{id:"stepfun/Step-5-Preview",inputModalities:["text","image"],provider:dD,spec:pD,label:"Step 5 Preview",name:"Step 5 Preview",description:"600B sparse-MoE agentic coding with 1M context",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},STEP_3_7_FLASH:{id:"stepfun/Step-3.7-Flash",inputModalities:["text","image"],provider:dD,spec:pD,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:dD,spec:pD,label:"Step 3.5 Flash",name:"Step 3.5 Flash",description:"fast sparse-MoE agentic reasoning",reasoning:!0,contextWindow:262144},TENCENT_HY3:{id:"tencent/Hy3",inputModalities:["text"],provider:dD,spec:pD,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:dD,spec:pD,label:"Tencent Hy3",name:"Tencent Hy3",description:"sparse-MoE reasoning & agentic tool use",reasoning:!0,contextWindow:262144},TENCENT_HY4_PREVIEW:{id:"tencent/hy4-preview",inputModalities:["text"],provider:dD,spec:pD,label:"Tencent Hy4 Preview",name:"Tencent Hy4 Preview",description:"agentic coding & sustained multi-step tool use",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1048576},GEMINI_3_8_FLASH:{id:"google/gemini-3.8-flash",inputModalities:["text","image"],provider:XO,spec:pD,label:"Gemini 3.8 Flash",name:"Gemini 3.8 Flash",description:"newest Gemini Flash, improved core reasoning",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},GEMINI_3_7_FLASH:{id:"google/gemini-3.7-flash",inputModalities:["text","image"],provider:tD,spec:pD,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:XO,spec:pD,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:XO,spec:pD,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:XO,spec:pD,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:XO,spec:pD,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:XO,spec:pD,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:dD,spec:pD,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:dD,spec:pD,label:"Inkling",name:"Inkling",description:"multimodal MoE reasoning",reasoning:!0,contextWindow:256e3},INKLING_SMALL:{id:"thinkingmachines/inkling-small",inputModalities:["text","image"],provider:dD,spec:pD,label:"Inkling Small",name:"Inkling Small",description:"lightweight MoE reasoning at lower cost and latency",reasoning:!0,contextWindow:1e6},SPACE_BUNNY_ALPHA:{id:"stealth/space-bunny-alpha",inputModalities:["text","image"],provider:tD,spec:pD,label:"Space Bunny Alpha",name:"Space Bunny Alpha",description:"stealth model with 1M context",vendorLabel:"Stealth",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6,maxOutputTokens:524288},PIXEL_CANARY:{id:"stealth/pixel-canary",inputModalities:["text","image"],provider:dD,spec:pD,label:"Pixel Canary",name:"Pixel Canary",description:"stealth coding model for web and mobile apps",vendorLabel:"Stealth",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods",reasoning:!0,reasoningEfforts:["low","medium","xhigh"],contextWindow:262144,maxOutputTokens:131072},LAGUNA_S_2_1_FREE:{id:"poolside/laguna-s-2.1-free",inputModalities:["text"],provider:dD,spec:pD,label:"Laguna S 2.1",name:"Laguna S 2.1",description:"open-weight agentic coding and long-horizon work",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods",reasoning:!0,contextWindow:256e3,maxOutputTokens:32768},LING_3_0_FLASH_FREE:{id:"inclusionai/ling-3.0-flash-free",inputModalities:["text"],provider:dD,spec:pD,label:"Ling 3.0 Flash",name:"Ling 3.0 Flash",description:"fast lightweight-MoE coding & agentic work",badge:"free",reasoning:!0,get hidden(){return isLingFlashFreeEnded()},contextWindow:256e3,maxOutputTokens:32768},LING_3_0_FLASH_SANTE_FREE:{id:"inclusionai/ling-3.0-flash-sante:free",inputModalities:["text"],provider:dD,spec:pD,label:"Ling 3.0 Flash Sante",name:"Ling 3.0 Flash Sante",description:"health & medicine tuned lightweight-MoE, still strong on code",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods. 100 requests a day per account",reasoning:!0,contextWindow:262144,maxOutputTokens:32768},LING_3_1_FLASH_FREE:{id:"inclusionai/ling-3.1-flash:free",inputModalities:["text"],provider:dD,spec:pD,label:"Ling 3.1 Flash",name:"Ling 3.1 Flash",description:"hybrid-reasoning MoE for coding & tool-using agents",badge:"free",notice:"{name} is free and uses shared capacity, so limits may apply during busy periods. 100 requests a day per account",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:262144,maxOutputTokens:32768},MUSE_SPARK_1_1:{id:"meta/muse-spark-1.1",inputModalities:["text","image"],provider:XO,spec:pD,label:"Muse Spark 1.1",name:"Muse Spark 1.1",description:"agentic performance, tool use, and computer use",vendorLabel:"Meta",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},MUSE_SPARK_1_2:{id:"meta/muse-spark-1.2",inputModalities:["text","image"],provider:XO,spec:pD,label:"Muse Spark 1.2",name:"Muse Spark 1.2",description:"coding-optimized for agentic workflows and large codebases",vendorLabel:"Meta",notice:"{name} is going through upstream inference issues at {vendor}, not Command Code. Expect slower responses and occasional rate limits.",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},MUSE_SPARK_1_2_CONTRIBUTOR:{id:"meta/muse-spark-1.2-contributor",inputModalities:["text","image"],provider:XO,spec:pD,label:"Muse Spark 1.2 Contributor",name:"Muse Spark 1.2 Contributor",description:"Muse Spark 1.2 at ~95% off",vendorLabel:"Meta",notice:"{name} is going through upstream inference issues at {vendor}, not Command Code. Expect slower responses and occasional rate limits.",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},MUSE_SPARK_1_3:{id:"meta/muse-spark-1.3",inputModalities:["text","image"],provider:XO,spec:pD,label:"Muse Spark 1.3",name:"Muse Spark 1.3",description:"multimodal reasoning for long-horizon agentic and coding workflows",vendorLabel:"Meta",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1048576},MUSE_SPARK_1_3_CONTRIBUTOR:{id:"meta/muse-spark-1.3-contributor",inputModalities:["text","image"],provider:XO,spec:pD,label:"Muse Spark 1.3 Contributor",name:"Muse Spark 1.3 Contributor",description:"Muse Spark 1.3 at up to 95% off",vendorLabel:"Meta",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:1048576},GROK_4_5:{id:"xai/grok-4.5",inputModalities:["text","image"],provider:XO,spec:pD,label:"Grok 4.5",name:"Grok 4.5",description:"smartest model for coding, agentic tasks, knowledge work",vendorLabel:"xAI",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:5e5},GROK_4_6:{id:"xai/grok-4.6",inputModalities:["text","image"],provider:XO,spec:pD,label:"Grok 4.6",name:"Grok 4.6",description:"frontier performance on coding, knowledge work, and STEM",vendorLabel:"xAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:5e5},GROK_4_7:{id:"xai/grok-4.7",inputModalities:["text","image"],provider:XO,spec:pD,label:"Grok 4.7",name:"Grok 4.7",description:"coding and knowledge work, built for multi-hour tasks",vendorLabel:"xAI",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:5e5}},yD=[{canonicalId:"zai-org/GLM-5",providers:{[XO]:"zai/glm-5",[JO]:"zai-org/GLM-5"}},{canonicalId:"zai-org/GLM-5.3",providers:{[oD]:"zai-org/glm-5.3",[XO]:"zai/glm-5.3"}},{canonicalId:"zai-org/GLM-5.2",providers:{[nD]:"glm-5.2",[XO]:"zai/glm-5.2"}},{canonicalId:"poolside/laguna-s-2.1-free",providers:{[XO]:"poolside/laguna-s-2.1-free"}},{canonicalId:"inclusionai/ling-3.0-flash-free",providers:{[XO]:"inclusionai/ling-3.0-flash-free"}},{canonicalId:"inclusionai/ling-3.0-flash-sante:free",providers:{[tD]:"inclusionai/ling-3.0-flash-sante:free"}},{canonicalId:"inclusionai/ling-3.1-flash:free",providers:{[oD]:"inclusionai/ling-3.1-flash"}},{canonicalId:"zai-org/GLM-5.2-Fast",providers:{[XO]:"zai/glm-5.2-fast"}},{canonicalId:"zai-org/GLM-5.1",providers:{[XO]:"zai/glm-5.1"}},{canonicalId:"moonshotai/Kimi-K3",providers:{[oD]:"moonshotai/kimi-k3",[XO]:"moonshotai/kimi-k3"}},{canonicalId:"moonshotai/Kimi-K2.5",providers:{[XO]:"moonshotai/kimi-k2.5",[JO]:"moonshotai/Kimi-K2.5",[ZO]:"workers-ai/@cf/moonshotai/kimi-k2.5"}},{canonicalId:"moonshotai/Kimi-K2.6",providers:{[XO]:"moonshotai/kimi-k2.6",[JO]:"moonshotai/Kimi-K2.6",[ZO]:"workers-ai/@cf/moonshotai/kimi-k2.6"}},{canonicalId:"moonshotai/Kimi-K2.7-Code",providers:{[nD]:"kimi-k2.7-code",[XO]:"moonshotai/kimi-k2.7-code"}},{canonicalId:"moonshotai/Kimi-K2.7-Code-Highspeed",providers:{[XO]:"moonshotai/kimi-k2.7-code-highspeed"}},{canonicalId:"MiniMaxAI/MiniMax-M2.5",providers:{[XO]:"minimax/minimax-m2.5",[JO]:"MiniMaxAI/MiniMax-M2.5"}},{canonicalId:"deepseek/deepseek-v4-pro",providers:{[XO]:"deepseek/deepseek-v4-pro"}},{canonicalId:"deepseek/deepseek-v4-flash",providers:{[XO]:"deepseek/deepseek-v4.1-flash",[oD]:"deepseek/deepseek-v4.1-flash",[sD]:"morph-dsv4flash",[cD]:"deepseek-v4-flash-0731"}},{canonicalId:"deepseek/deepseek-v4-flash-vision-exp",providers:{[XO]:"deepseek/deepseek-v4.1-flash"}},{canonicalId:"deepseek/deepseek-v4.1-flash",providers:{[oD]:"deepseek/deepseek-v4.1-flash",[XO]:"deepseek/deepseek-v4.1-flash"}},{canonicalId:"deepseek/deepseek-v4.1-flash-fast",providers:{[XO]:"deepseek/deepseek-v4.1-flash"}},{canonicalId:"deepseek/deepseek-v4-flash-fast",providers:{[aD]:"DeepSeek-V4-Flash-0731-Fast"}},{canonicalId:"Qwen/Qwen3.6-Max-Preview",providers:{[XO]:"alibaba/qwen-3.6-max-preview"}},{canonicalId:"Qwen/Qwen3.6-Plus",providers:{[nD]:"qwen3.6-plus",[XO]:"alibaba/qwen3.6-plus"}},{canonicalId:"Qwen/Qwen3.7-Max",providers:{[nD]:"qwen3.7-max",[XO]:"alibaba/qwen3.7-max"}},{canonicalId:"Qwen/Qwen3.7-Plus",providers:{[nD]:"qwen3.7-plus",[XO]:"alibaba/qwen3.7-plus"}},{canonicalId:"Qwen/Qwen3.8-Max-0902",providers:{[nD]:"qwen3.8-max-0902"}},{canonicalId:"Qwen/Qwen3.8-Omni-Flash",providers:{[XO]:"alibaba/qwen3.8-omni-flash"}},{canonicalId:"Qwen/Qwen3.8-Max",providers:{[nD]:"qwen3.8-max",[XO]:"alibaba/qwen3.8-max"}},{canonicalId:"Qwen/Qwen3.8-27B",providers:{[XO]:"alibaba/qwen3.8-27b"}},{canonicalId:"Qwen/Qwen3.8-Flash",providers:{[rD]:"qwen3.8-flash"}},{canonicalId:"Qwen/Qwen3.7-Flash",providers:{[XO]:"alibaba/qwen3.7-flash"}},{canonicalId:"MiniMaxAI/MiniMax-M3",providers:{[XO]:"minimax/minimax-m3"}},{canonicalId:hD,providers:{[XO]:"minimax/minimax-m3"}},{canonicalId:"MiniMaxAI/MiniMax-M2.7",providers:{[XO]:"minimax/minimax-m2.7"}},{canonicalId:"meituan/LongCat-2.0",providers:{[iD]:"LongCat-2.0"}},{canonicalId:"stepfun/Step-5-Preview",providers:{[XO]:"stepfun/step-5-preview"}},{canonicalId:"stealth/pixel-canary",providers:{[XO]:"stealth/pixel-canary"}},{canonicalId:"stepfun/Step-3.7-Flash",providers:{[XO]:"stepfun/step-3.7-flash"}},{canonicalId:"stepfun/Step-3.5-Flash",providers:{[XO]:"stepfun/step-3.5-flash",[tD]:"stepfun/step-3.5-flash"}},{canonicalId:"z-ai/glm-5.3-flash",providers:{[oD]:"zai-org/glm-5.3-flash",[XO]:"zai/glm-5.3-flash"}},{canonicalId:"z-ai/glm-5.3-flashx",providers:{[XO]:"zai/glm-5.3-flashx"}},{canonicalId:"gpt-5.6-sol",providers:{[XO]:"openai/gpt-5.6-sol"}},{canonicalId:"gpt-5.6-terra",providers:{[XO]:"openai/gpt-5.6-terra"}},{canonicalId:"gpt-5.6-luna",providers:{[XO]:"openai/gpt-5.6-luna"}},{canonicalId:"stealth/space-bunny-alpha",providers:{[tD]:"stealth/space-bunny-alpha"}},{canonicalId:"tencent/Hy3",providers:{[tD]:"tencent/hy3:free"}},{canonicalId:"tencent/hy3-paid",providers:{[XO]:"tencent/hy3"}},{canonicalId:"tencent/hy4-preview",providers:{[lD]:"hy4-preview"}},{canonicalId:"xiaomi/mimo-v2.6-pro",providers:{[XO]:"xiaomi/mimo-v2.6-pro"}},{canonicalId:"xiaomi/mimo-v2.6-pro-ultraspeed",providers:{[XO]:"xiaomi/mimo-v2.6-pro-ultraspeed"}},{canonicalId:"xiaomi/mimo-v2.6-flash",providers:{[XO]:"xiaomi/mimo-v2.6-flash"}},{canonicalId:"xiaomi/mimo-v2.5-pro",providers:{[XO]:"xiaomi/mimo-v2.5-pro"}},{canonicalId:"xiaomi/mimo-v2.5",providers:{[XO]:"xiaomi/mimo-v2.5"}},{canonicalId:"google/gemini-3.8-flash",providers:{[XO]:"google/gemini-3.8-flash"}},{canonicalId:"google/gemini-3.7-flash",providers:{[tD]:"google/gemini-3.7-flash"}},{canonicalId:"google/gemini-3.6-flash",providers:{[XO]:"google/gemini-3.6-flash"}},{canonicalId:"google/gemini-3.5-flash",providers:{[XO]:"google/gemini-3.5-flash"}},{canonicalId:"google/gemini-3.5-flash-lite",providers:{[XO]:"google/gemini-3.5-flash-lite"}},{canonicalId:"google/gemini-3.1-flash-lite",providers:{[XO]:"google/gemini-3.1-flash-lite"}},{canonicalId:"nvidia/nemotron-3-ultra-550b-a55b",providers:{[XO]:"nvidia/nemotron-3-ultra-550b-a55b"}},{canonicalId:"thinkingmachines/inkling",providers:{[XO]:"thinkingmachines/inkling"}},{canonicalId:"thinkingmachines/inkling-small",providers:{[XO]:"thinkingmachines/inkling-small"}},{canonicalId:"sakana/fugu-ultra",providers:{[XO]:"sakana/fugu-ultra"}},{canonicalId:"xai/grok-4.5",providers:{[XO]:"xai/grok-4.5"}},{canonicalId:"xai/grok-4.6",providers:{[XO]:"xai/grok-4.6"}},{canonicalId:"xai/grok-4.7",providers:{[XO]:"xai/grok-4.7"}},{canonicalId:"meta/muse-spark-1.1",providers:{[XO]:"meta/muse-spark-1.1"}},{canonicalId:"meta/muse-spark-1.2",providers:{[XO]:"meta/muse-spark-1.2"}},{canonicalId:"meta/muse-spark-1.2-contributor",providers:{[XO]:"meta/muse-spark-1.2-contributor"}},{canonicalId:"meta/muse-spark-1.3",providers:{[XO]:"meta/muse-spark-1.3"}},{canonicalId:"meta/muse-spark-1.3-contributor",providers:{[XO]:"meta/muse-spark-1.3-contributor"}}],SD="2026-08-16T16:00:00Z",wD=[{startHourUtc:1,endHourUtc:4},{startHourUtc:6,endHourUtc:10}],vD=[1,2,3,4,5],kD=["2026-09-25","2026-09-26","2026-09-27","2026-10-01","2026-10-02","2026-10-03","2026-10-04","2026-10-05","2026-10-06","2026-10-07"],CD={effectiveFrom:SD,peakWindowsUtc:wD,peakDaysUtc:vD,offPeakDatesUtc:kD,peak:{promptCost:.44,completionCost:1.32,cacheReadCost:.014},offPeak:{promptCost:.22,completionCost:.66,cacheReadCost:.007}},bD=new Set([fD.GLM_5_2_FAST.id,fD.DEEPSEEK_V4_1_FLASH_FAST.id,fD.MINIMAX_M3.id,fD.MINIMAX_M3_FREE.id,fD.STEP_3_7_FLASH.id,fD.STEP_5_PREVIEW.id,fD.PIXEL_CANARY.id,fD.XIAOMI_MIMO_V2_6_PRO.id,fD.XIAOMI_MIMO_V2_6_PRO_ULTRASPEED.id,fD.XIAOMI_MIMO_V2_6_FLASH.id,fD.FUGU_ULTRA.id,fD.GROK_4_5.id,fD.GROK_4_6.id,fD.MUSE_SPARK_1_1.id,fD.MUSE_SPARK_1_2.id,fD.MUSE_SPARK_1_2_CONTRIBUTOR.id,fD.MUSE_SPARK_1_3.id,fD.MUSE_SPARK_1_3_CONTRIBUTOR.id,fD.LAGUNA_S_2_1_FREE.id,fD.QWEN_3_8_MAX_0902.id,fD.LONGCAT_2.id,fD.GLM_5_3_FLASHX.id,fD.SPACE_BUNNY_ALPHA.id]),ED=[{canonicalId:"zai-org/GLM-5",gatewaySlug:"zai/glm-5",order:["deepinfra","fireworks","togetherai","parasail","bedrock"],providers:{deepinfra:{slug:"deepinfra",promptCost:.8,completionCost:2.56,cacheReadCost:.16},fireworks:{slug:"fireworks",promptCost:1,completionCost:3.2,cacheReadCost:.2},togetherai:{slug:"togetherai",promptCost:1,completionCost:3.2,cacheReadCost:0},parasail:{slug:"parasail",promptCost:1,completionCost:3.2,cacheReadCost:0},bedrock:{slug:"bedrock",promptCost:1,completionCost:3.2,cacheReadCost:0}}},{canonicalId:"zai-org/GLM-5.2",gatewaySlug:"zai/glm-5.2",order:["novita","deepinfra"],providers:{novita:{slug:"novita",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},deepinfra:{slug:"deepinfra",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},zai:{slug:"zai",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},fireworks:{slug:"fireworks",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{canonicalId:"zai-org/GLM-5.3",gatewaySlug:"zai/glm-5.3",order:["digitalocean"],providers:{digitalocean:{slug:"digitalocean",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{canonicalId:"z-ai/glm-5.3-flash",gatewaySlug:"zai/glm-5.3-flash",order:["zai"],providers:{zai:{slug:"zai",promptCost:.15,completionCost:.5,cacheReadCost:.03}}},{canonicalId:"z-ai/glm-5.3-flashx",gatewaySlug:"zai/glm-5.3-flashx",order:["zai"],providers:{zai:{slug:"zai",promptCost:.37,completionCost:1.25,cacheReadCost:.075}}},{canonicalId:"zai-org/GLM-5.2-Fast",gatewaySlug:"zai/glm-5.2-fast",order:["wafer"],providers:{wafer:{slug:"wafer",promptCost:3,completionCost:10.25,cacheReadCost:.5}}},{canonicalId:"zai-org/GLM-5.1",gatewaySlug:"zai/glm-5.1",order:["deepinfra","fireworks"],providers:{deepinfra:{slug:"deepinfra",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},fireworks:{slug:"fireworks",promptCost:1.4,completionCost:4.4,cacheReadCost:.26}}},{canonicalId:"moonshotai/Kimi-K3",gatewaySlug:"moonshotai/kimi-k3",order:["moonshotai"],providers:{moonshotai:{slug:"moonshotai",promptCost:3,completionCost:15,cacheReadCost:.3}}},{canonicalId:"moonshotai/Kimi-K2.5",gatewaySlug:"moonshotai/kimi-k2.5",order:["moonshotai","fireworks","bedrock","togetherai"],providers:{fireworks:{slug:"fireworks",promptCost:.6,completionCost:3,cacheReadCost:.1},bedrock:{slug:"bedrock",promptCost:.6,completionCost:3,cacheReadCost:.1},togetherai:{slug:"togetherai",promptCost:.5,completionCost:2.8,cacheReadCost:0},moonshotai:{slug:"moonshotai",promptCost:.6,completionCost:3,cacheReadCost:.1}}},{canonicalId:"moonshotai/Kimi-K2.6",gatewaySlug:"moonshotai/kimi-k2.6",order:["moonshotai","fireworks"],providers:{moonshotai:{slug:"moonshotai",promptCost:.95,completionCost:4,cacheReadCost:.16},fireworks:{slug:"fireworks",promptCost:.95,completionCost:4,cacheReadCost:.16}}},{canonicalId:"moonshotai/Kimi-K2.7-Code",gatewaySlug:"moonshotai/kimi-k2.7-code",order:["moonshotai"],providers:{moonshotai:{slug:"moonshotai",promptCost:.95,completionCost:4,cacheReadCost:.19}}},{canonicalId:"moonshotai/Kimi-K2.7-Code-Highspeed",gatewaySlug:"moonshotai/kimi-k2.7-code-highspeed",order:["moonshotai"],providers:{moonshotai:{slug:"moonshotai",promptCost:1.9,completionCost:8,cacheReadCost:.38}}},{canonicalId:"MiniMaxAI/MiniMax-M2.5",gatewaySlug:"minimax/minimax-m2.5",order:["deepinfra","parasail","nebius","bedrock"],providers:{deepinfra:{slug:"deepinfra",promptCost:.3,completionCost:1.2,cacheReadCost:.03},parasail:{slug:"parasail",promptCost:.3,completionCost:1.2,cacheReadCost:0},nebius:{slug:"nebius",promptCost:.3,completionCost:1.2,cacheReadCost:0},bedrock:{slug:"bedrock",promptCost:.3,completionCost:1.2,cacheReadCost:0}}},{canonicalId:"deepseek/deepseek-v4-pro",gatewaySlug:"deepseek/deepseek-v4-pro",order:["deepseek"],providers:{deepseek:{slug:"deepseek",promptCost:.435,completionCost:.87,cacheReadCost:.003625,timeOfDay:{effectiveFrom:SD,peakWindowsUtc:wD,peakDaysUtc:vD,offPeakDatesUtc:kD,peak:{promptCost:1.32,completionCost:3.96,cacheReadCost:.044},offPeak:{promptCost:.66,completionCost:1.98,cacheReadCost:.022}}},fireworks:{slug:"fireworks",promptCost:1.74,completionCost:3.48,cacheReadCost:.0145}}},{canonicalId:"deepseek/deepseek-v4-flash",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],zdr:{gatewaySlug:"deepseek/deepseek-v4-flash",only:["baseten","fireworks","deepinfra"]},providers:{deepseek:{slug:"deepseek",promptCost:.14,completionCost:.28,cacheReadCost:.0028,timeOfDay:{effectiveFrom:SD,peakWindowsUtc:wD,peakDaysUtc:vD,offPeakDatesUtc:kD,peak:{promptCost:.3,completionCost:1.2,cacheReadCost:.006},offPeak:{promptCost:.15,completionCost:.6,cacheReadCost:.003}}},baseten:{slug:"baseten",promptCost:.13,completionCost:.26,cacheReadCost:.028},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007},deepinfra:{slug:"deepinfra",promptCost:.08,completionCost:.18,cacheReadCost:.016}}},{canonicalId:"deepseek/deepseek-v4-flash-vision-exp",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],zdr:{gatewaySlug:"deepseek/deepseek-v4.1-flash",only:["fireworks","deepinfra"]},providers:{deepseek:{slug:"deepseek",promptCost:.15,completionCost:.6,cacheReadCost:.003,timeOfDay:{effectiveFrom:SD,peakWindowsUtc:wD,peakDaysUtc:vD,offPeakDatesUtc:kD,peak:{promptCost:.3,completionCost:1.2,cacheReadCost:.006},offPeak:{promptCost:.15,completionCost:.6,cacheReadCost:.003}}},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007},deepinfra:{slug:"deepinfra",promptCost:.2,completionCost:.6,cacheReadCost:.006}}},{canonicalId:"deepseek/deepseek-v4.1-flash",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],providers:{deepseek:{slug:"deepseek",promptCost:.15,completionCost:.6,cacheReadCost:.003,timeOfDay:{effectiveFrom:SD,peakWindowsUtc:wD,peakDaysUtc:vD,offPeakDatesUtc:kD,peak:{promptCost:.3,completionCost:1.2,cacheReadCost:.006},offPeak:{promptCost:.15,completionCost:.6,cacheReadCost:.003}}},novita:{slug:"novita",promptCost:.3,completionCost:1.2,cacheReadCost:.006},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007},deepinfra:{slug:"deepinfra",promptCost:.2,completionCost:.6,cacheReadCost:.006},morph:{slug:"morph",promptCost:.3,completionCost:1.2,cacheReadCost:.03},baseten:{slug:"baseten",promptCost:.3,completionCost:1.2,cacheReadCost:.03},wafer:{slug:"wafer",promptCost:.3,completionCost:1.2,cacheReadCost:.01},modal:{slug:"modal",promptCost:.3,completionCost:1.2,cacheReadCost:.03}}},{canonicalId:"deepseek/deepseek-v4.1-flash-fast",gatewaySlug:"deepseek/deepseek-v4.1-flash",order:["deepseek"],zdr:{gatewaySlug:"deepseek/deepseek-v4.1-flash",only:["deepseek"]},providers:{deepseek:{slug:"deepseek",promptCost:.16,completionCost:.58,cacheReadCost:.016,timeOfDay:{effectiveFrom:SD,peakWindowsUtc:wD,peakDaysUtc:vD,offPeakDatesUtc:kD,peak:{promptCost:.32,completionCost:1.16,cacheReadCost:.032},offPeak:{promptCost:.16,completionCost:.58,cacheReadCost:.016}}},fireworks:{slug:"fireworks",promptCost:.22,completionCost:.66,cacheReadCost:.007}}},{canonicalId:"Qwen/Qwen3.6-Max-Preview",gatewaySlug:"alibaba/qwen-3.6-max-preview",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:1.3,completionCost:7.8,cacheReadCost:.26,cacheWriteCost:1.63}}},{canonicalId:"Qwen/Qwen3.6-Plus",gatewaySlug:"alibaba/qwen3.6-plus",order:["fireworks"],providers:{fireworks:{slug:"fireworks",promptCost:.5,completionCost:3,cacheReadCost:.1}}},{canonicalId:"Qwen/Qwen3.7-Max",gatewaySlug:"alibaba/qwen3.7-max",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:2.5,completionCost:7.5,cacheReadCost:.5,cacheWriteCost:3.13}}},{canonicalId:"Qwen/Qwen3.7-Plus",gatewaySlug:"alibaba/qwen3.7-plus",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:.4,completionCost:1.6,cacheReadCost:.08,cacheWriteCost:.5}}},{canonicalId:"Qwen/Qwen3.8-Omni-Flash",gatewaySlug:"alibaba/qwen3.8-omni-flash",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:.15,completionCost:.47,cacheReadCost:.016}}},{canonicalId:"Qwen/Qwen3.8-Max",gatewaySlug:"alibaba/qwen3.8-max",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:2,completionCost:6,cacheReadCost:.25,cacheWriteCost:2.5}}},{canonicalId:"Qwen/Qwen3.8-27B",gatewaySlug:"alibaba/qwen3.8-27b",order:["runinfra"],providers:{runinfra:{slug:"runinfra",promptCost:.4,completionCost:3,cacheReadCost:.04},deepinfra:{slug:"deepinfra",promptCost:.4,completionCost:3,cacheReadCost:.04}}},{canonicalId:"Qwen/Qwen3.7-Flash",gatewaySlug:"alibaba/qwen3.7-flash",order:["alibaba"],providers:{alibaba:{slug:"alibaba",promptCost:.03,completionCost:.13,cacheReadCost:.006,cacheWriteCost:.038}}},{canonicalId:"MiniMaxAI/MiniMax-M3",gatewaySlug:"minimax/minimax-m3",order:["minimax"],providers:{minimax:{slug:"minimax",promptCost:.3,completionCost:1.2,cacheReadCost:.06}}},{canonicalId:hD,gatewaySlug:"minimax/minimax-m3",order:["minimax"],providers:{minimax:{slug:"minimax",promptCost:.3,completionCost:1.2,cacheReadCost:.06}}},{canonicalId:"MiniMaxAI/MiniMax-M2.7",gatewaySlug:"minimax/minimax-m2.7",order:["fireworks","togetherai"],providers:{fireworks:{slug:"fireworks",promptCost:.3,completionCost:1.2,cacheReadCost:.06},togetherai:{slug:"togetherai",promptCost:.3,completionCost:1.2,cacheReadCost:0}}},{canonicalId:"xiaomi/mimo-v2.6-pro",gatewaySlug:"xiaomi/mimo-v2.6-pro",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.435,completionCost:.87,cacheReadCost:.0036}}},{canonicalId:"xiaomi/mimo-v2.6-pro-ultraspeed",gatewaySlug:"xiaomi/mimo-v2.6-pro-ultraspeed",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:4.35,completionCost:8.7,cacheReadCost:.036}}},{canonicalId:"xiaomi/mimo-v2.6-flash",gatewaySlug:"xiaomi/mimo-v2.6-flash",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.14,completionCost:.28,cacheReadCost:.0028}}},{canonicalId:"xiaomi/mimo-v2.5-pro",gatewaySlug:"xiaomi/mimo-v2.5-pro",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.435,completionCost:.87,cacheReadCost:.0036}}},{canonicalId:"xiaomi/mimo-v2.5",gatewaySlug:"xiaomi/mimo-v2.5",order:["xiaomi"],providers:{xiaomi:{slug:"xiaomi",promptCost:.14,completionCost:.28,cacheReadCost:.0028}}},{canonicalId:"stepfun/Step-5-Preview",gatewaySlug:"stepfun/step-5-preview",order:["stepfun"],providers:{stepfun:{slug:"stepfun",promptCost:1,completionCost:2.7,cacheReadCost:.05}}},{canonicalId:"stealth/pixel-canary",gatewaySlug:"stealth/pixel-canary",order:["stealth"],providers:{stealth:{slug:"stealth",promptCost:0,completionCost:0,cacheReadCost:0}}},{canonicalId:"stepfun/Step-3.5-Flash",gatewaySlug:"stepfun/step-3.5-flash",order:["deepinfra"],providers:{deepinfra:{slug:"deepinfra",promptCost:.09,completionCost:.3,cacheReadCost:.02}}},{canonicalId:"stepfun/Step-3.7-Flash",gatewaySlug:"stepfun/step-3.7-flash",order:["stepfun"],providers:{stepfun:{slug:"stepfun",promptCost:.2,completionCost:1.15,cacheReadCost:.04}}},{canonicalId:"gpt-5.6-sol",gatewaySlug:"openai/gpt-5.6-sol",order:["openai"],providers:{openai:{slug:"openai",promptCost:5,completionCost:30,cacheReadCost:.5,cacheWriteCost:6.25},azure:{slug:"azure",promptCost:5,completionCost:30,cacheReadCost:.5,cacheWriteCost:6.25},bedrock:{slug:"bedrock",promptCost:5,completionCost:30,cacheReadCost:.5,cacheWriteCost:6.25}}},{canonicalId:"gpt-5.6-terra",gatewaySlug:"openai/gpt-5.6-terra",order:["openai"],providers:{openai:{slug:"openai",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5},azure:{slug:"azure",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5},bedrock:{slug:"bedrock",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5}}},{canonicalId:"gpt-5.6-luna",gatewaySlug:"openai/gpt-5.6-luna",order:["openai"],providers:{openai:{slug:"openai",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25},azure:{slug:"azure",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25},bedrock:{slug:"bedrock",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25}}},{canonicalId:"google/gemini-3.8-flash",gatewaySlug:"google/gemini-3.8-flash",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:1.5,completionCost:7.5,cacheReadCost:.15}}},{canonicalId:"google/gemini-3.6-flash",gatewaySlug:"google/gemini-3.6-flash",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:1.5,completionCost:7.5,cacheReadCost:.15}}},{canonicalId:"google/gemini-3.5-flash",gatewaySlug:"google/gemini-3.5-flash",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:1.5,completionCost:9,cacheReadCost:.15}}},{canonicalId:"google/gemini-3.5-flash-lite",gatewaySlug:"google/gemini-3.5-flash-lite",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:.3,completionCost:2.5,cacheReadCost:.03}}},{canonicalId:"google/gemini-3.1-flash-lite",gatewaySlug:"google/gemini-3.1-flash-lite",order:["vertex"],providers:{vertex:{slug:"vertex",promptCost:.25,completionCost:1.5,cacheReadCost:.03}}},{canonicalId:"nvidia/nemotron-3-ultra-550b-a55b",gatewaySlug:"nvidia/nemotron-3-ultra-550b-a55b",order:["baseten","deepinfra"],providers:{baseten:{slug:"baseten",promptCost:.6,completionCost:2.4,cacheReadCost:.12},deepinfra:{slug:"deepinfra",promptCost:.5,completionCost:2.5,cacheReadCost:.15}}},{canonicalId:"thinkingmachines/inkling",gatewaySlug:"thinkingmachines/inkling",order:["baseten"],providers:{baseten:{slug:"baseten",promptCost:1,completionCost:4.05,cacheReadCost:.17}}},{canonicalId:"thinkingmachines/inkling-small",gatewaySlug:"thinkingmachines/inkling-small",order:["baseten"],providers:{baseten:{slug:"baseten",promptCost:.5,completionCost:1.2,cacheReadCost:.1}}},{canonicalId:"sakana/fugu-ultra",gatewaySlug:"sakana/fugu-ultra",order:["sakana"],providers:{sakana:{slug:"sakana",promptCost:5,completionCost:30,cacheReadCost:.5}}},{canonicalId:"xai/grok-4.5",gatewaySlug:"xai/grok-4.5",order:["xai"],providers:{xai:{slug:"xai",promptCost:2,completionCost:6,cacheReadCost:.5}}},{canonicalId:"xai/grok-4.6",gatewaySlug:"xai/grok-4.6",order:["xai"],providers:{xai:{slug:"xai",promptCost:2,completionCost:6,cacheReadCost:.5}}},{canonicalId:"xai/grok-4.7",gatewaySlug:"xai/grok-4.7",order:["xai"],providers:{xai:{slug:"xai",promptCost: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:"meta/muse-spark-1.3",gatewaySlug:"meta/muse-spark-1.3",order:["meta"],providers:{meta:{slug:"meta",promptCost:1.25,completionCost:4.25,cacheReadCost:.15}}},{canonicalId:"meta/muse-spark-1.3-contributor",gatewaySlug:"meta/muse-spark-1.3-contributor",order:["meta"],providers:{meta:{slug:"meta",promptCost:.1,completionCost:.2,cacheReadCost:.002}}},{canonicalId:"tencent/hy3-paid",gatewaySlug:"tencent/hy3",order:["novita"],providers:{novita:{slug:"novita",promptCost:.14,completionCost:.58,cacheReadCost:.035},deepinfra:{slug:"deepinfra",promptCost:.14,completionCost:.58,cacheReadCost:.035}}},{canonicalId:"poolside/laguna-s-2.1-free",gatewaySlug:"poolside/laguna-s-2.1-free",order:["poolside"],providers:{poolside:{slug:"poolside",promptCost:0,completionCost:0,cacheReadCost:0}}},{canonicalId:"inclusionai/ling-3.0-flash-free",gatewaySlug:"inclusionai/ling-3.0-flash-free",order:["novita"],providers:{novita:{slug:"novita",promptCost:0,completionCost:0,cacheReadCost:0}}}],TD=[{canonicalId:"Qwen/Qwen3.8-Max-0902",slug:"qwen3.8-max-0902",promptCost:2,completionCost:6,cacheReadCost:.25},{canonicalId:"Qwen/Qwen3.8-Max",slug:"qwen3.8-max",promptCost:2,completionCost:6,cacheReadCost:.25},{canonicalId:"Qwen/Qwen3.7-Max",slug:"qwen3.7-max",promptCost:2.5,completionCost:7.5,cacheReadCost:.5},{canonicalId:"Qwen/Qwen3.7-Plus",slug:"qwen3.7-plus",promptCost:.4,completionCost:1.6,cacheReadCost:.08,contextTiers:[{maxInputTokens:256e3,promptCost:.4,completionCost:1.6,cacheReadCost:.08},{promptCost:1.2,completionCost:4.8,cacheReadCost:.24}]},{canonicalId:"Qwen/Qwen3.6-Plus",slug:"qwen3.6-plus",promptCost:.5,completionCost:3,cacheReadCost:.1,contextTiers:[{maxInputTokens:256e3,promptCost:.5,completionCost:3,cacheReadCost:.1},{promptCost:2,completionCost:6,cacheReadCost:.2}]},{canonicalId:"zai-org/GLM-5.2",slug:"glm-5.2",promptCost:1.4,completionCost:4.4,cacheReadCost:.26},{canonicalId:"moonshotai/Kimi-K2.7-Code",slug:"kimi-k2.7-code",promptCost:.95,completionCost:4,cacheReadCost:.19},{canonicalId:"Qwen/Qwen3.8-Flash",slug:"qwen3.8-flash",promptCost:.16,completionCost:.47,cacheReadCost:.016}],PD=[{canonicalId:"deepseek/deepseek-v4-flash",slug:"morph-dsv4flash",promptCost:.14,completionCost:.28,cacheReadCost:.0028,timeOfDay:CD}],MD=[{canonicalId:"deepseek/deepseek-v4-flash-fast",slug:"DeepSeek-V4-Flash-0731-Fast",promptCost:.28,completionCost:.56,cacheReadCost:.07}],xD=[{canonicalId:"meituan/LongCat-2.0",slug:"LongCat-2.0",promptCost:.3,completionCost:1.2,cacheReadCost:.006}],ID={promptCost:.834,completionCost:2.501,cacheReadCost:.042},AD=[{canonicalId:"tencent/hy4-preview",slug:"hy4-preview",...ID}],RD=[{canonicalId:"stepfun/Step-3.5-Flash",openrouterSlug:"stepfun/step-3.5-flash",order:["siliconflow"],providers:{siliconflow:{slug:"siliconflow",promptCost:.1,completionCost:.3,zdr:!0,noTraining:!0}}},{canonicalId:"stealth/space-bunny-alpha",openrouterSlug:"stealth/space-bunny-alpha",order:["stealth"],providers:{stealth:{slug:"stealth",promptCost:0,completionCost:0,zdr:!1,noTraining:!1}}},{canonicalId:"tencent/Hy3",openrouterSlug:"tencent/hy3:free",order:["novita"],providers:{novita:{slug:"novita",promptCost:0,completionCost:0,zdr:!1,noTraining:!1}}},{canonicalId:"inclusionai/ling-3.0-flash-sante:free",openrouterSlug:"inclusionai/ling-3.0-flash-sante:free",order:["novita"],providers:{novita:{slug:"novita",promptCost:0,completionCost:0,zdr:!0,noTraining:!0}}},{canonicalId:"tencent/hy4-preview",openrouterSlug:"tencent/hy4-preview",order:["tencent"],providers:{tencent:{slug:"tencent",...ID,zdr:!0,noTraining:!0}}},{canonicalId:"gpt-5.6-terra",openrouterSlug:"openai/gpt-5.6-terra",order:["openai"],providers:{openai:{slug:"openai",promptCost:2,completionCost:12,cacheReadCost:.2,cacheWriteCost:2.5,zdr:!1,noTraining:!0}}},{canonicalId:"gpt-5.6-luna",openrouterSlug:"openai/gpt-5.6-luna",order:["openai"],providers:{openai:{slug:"openai",promptCost:.2,completionCost:1.2,cacheReadCost:.02,cacheWriteCost:.25,zdr:!1,noTraining:!0}}},{canonicalId:"google/gemini-3.7-flash",openrouterSlug:"google/gemini-3.7-flash",order:["google-vertex"],providers:{"google-vertex":{slug:"google-vertex",promptCost:1.5,completionCost:7.5,cacheReadCost:.15,cacheWriteCost:.08334,zdr:!0,noTraining:!0}}}],LD={"claude-sonnet-4-20250514":fD.SONNET_4_6.id,"claude-sonnet-4-5-20250929":fD.SONNET_4_6.id,"claude-opus-4-5-20251101":fD.OPUS_4_7.id,"claude-opus-4-6":fD.OPUS_4_7.id,"claude-haiku-4-5":fD.HAIKU_4_5.id},OD=fD.DEEPSEEK_V4_FLASH.id,DD={[YO]:"Anthropic",[QO]:"OpenAI",[JO]:"Open Source",[XO]:"Open Source",[eD]:"Open Source",[tD]:"Open Source"},$D=["Open Source","Stealth","Anthropic","OpenAI","Google"],ND={"command-code":{id:"command-code",label:"Command Code",shortLabel:"cmd",description:"recommended",supportedModelProviders:[YO,QO,eD,JO,XO,tD],requiresAuth:!1,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!0},anthropic:{id:"anthropic",label:"Anthropic",shortLabel:"anth",description:"Claude Pro/Max",supportedModelProviders:[YO],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!1},"github-copilot":{id:"github-copilot",label:"GitHub Copilot",shortLabel:"copilot",description:"Copilot subscription",supportedModelProviders:[YO,QO],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!0},codex:{id:"codex",label:"OpenAI ChatGPT/Codex",shortLabel:"openai",description:"ChatGPT Pro/Plus subscription",supportedModelProviders:[QO],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(fD).filter(e=>!e.hidden),n=[];for(const r of Object.values(ND)){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 _D=buildModelGroups("co"),FD=buildModelGroups("normal");function formatColoredUserSuffix(e){return isGenericUserName(e)?"":formatUserSuffix(e).replace(e,Pt.cyan(e))}function getStartedLine(){return`${Pt.dim("Run")} ${Pt.cyan(getBinaryCommand())} ${Pt.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 ${Pt.cyan(r)}`:"",i=[`${Pt.green(ft.tick)} ${Pt.bold("Logged in")}${s}${a}`];return o&&i.push(` ${Pt.yellow(ft.warning)} ${Pt.yellow(o)}`),i.push("",`${Pt.dim("API key stored in")} ${Pt.cyan(`~/.commandcode/${n}`)}`,getStartedLine()),i.join("\n")}function formatAlreadyLoggedInStyled(e){const t=formatColoredUserSuffix(e);return[`${Pt.green(ft.tick)} ${Pt.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"),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt();var UD=[{id:"copilot",package:"@byokkit/cmd-provider-copilot",version:"0.1.2",displayName:"GitHub Copilot"},{id:"openai",package:"@byokkit/cmd-provider-openai",version:"0.1.4",displayName:"OpenAI"},{id:"anthropic",package:"@byokkit/cmd-provider-anthropic",version:"0.1.3",displayName:"Anthropic",discoverable:!1}];function builtinProviderPackage(e){return UD.find(t=>t.id===e)}function builtinPackageForSpecifier(e){return builtinProviderPackage(e)??UD.find(t=>t.package===e)}__name(builtinProviderPackage,"builtinProviderPackage"),__name(builtinPackageForSpecifier,"builtinPackageForSpecifier");var jD=new Map;function isProviderWorkspaceDevMode(){return"local"===getApiEnv()}function workspaceDistEntry(e){const t=e.replace(/^@[^/]+\//,"").replace(/^cmd-/,""),o=r(p(import.meta.url)),a=s(o,n("../..",t,"dist","index.js"));return A(a)?a:void 0}function devWorkspaceProviderEntry(e){if(isProviderWorkspaceDevMode())return workspaceDistEntry(e)}__name(isProviderWorkspaceDevMode,"isProviderWorkspaceDevMode"),__name(workspaceDistEntry,"workspaceDistEntry"),__name(devWorkspaceProviderEntry,"devWorkspaceProviderEntry");var BD=__name(async e=>{const t=builtinProviderPackage(e.moduleId);if(!t)return;const n=jD.get(e.moduleId);if(n)return n;const r=!1===t.discoverable,o=devWorkspaceProviderEntry(t.package)??(r?await resolveManuallyInstalledProviderEntry({runtime:createNodeRuntime(),pkg:t.package}):void 0),s=o?coerceProviderModule(await import(g(o).href)):await loadProviderModuleFromPackage({runtime:createNodeRuntime(),pkg:t.package,version:t.version,install:e.install,...e.onInstallStart?{onInstallStart:e.onInstallStart}:{}});return o&&dlog("[ProviderPackages] workspace/local provider",{pkg:t.package,entry:o}),s&&jD.set(e.moduleId,s),s},"realLoader");function loadBuiltinProviderModule(e){return BD(e)}async function loadInstalledBuiltinProviderModules(){const e=UD.map(e=>e.id),t=[];for(const n of e)try{const e=await loadBuiltinProviderModule({moduleId:n,install:!1});e&&t.push(e)}catch(e){dlog("[ProviderPackages] installed provider failed to load",{moduleId:n,error:e instanceof Error?e.message:String(e)})}return t}function uniqueProviderModules(e){const t=new Map;for(const n of e)t.has(n.id)||t.set(n.id,n);return[...t.values()]}async function importProviderModule(e,n,r=!1,o){if(e.startsWith(".")||t.isAbsolute(e))return import(g(t.resolve(n,e)).href);const s=builtinPackageForSpecifier(e);if(s)return{default:await loadBuiltinProviderModule({moduleId:s.id,install:r,onInstallStart:__name(({pkg:e})=>dlog("[ProviderPackages] installing settings provider",{pkg:e}),"onInstallStart")})};if(isNpmPackageSpecifier(e)){const t=createNodeRuntime();if(r&&!o)throw new Error(`Provider package '${e}' requires an explicit semver "version" in user settings before it can be installed`);const n=r?(await ensureProviderPackage({runtime:t,pkg:e,version:o,onInstallStart:__name(({pkg:e})=>dlog("[ProviderPackages] installing settings provider",{pkg:e}),"onInstallStart")})).entry:await resolveInstalledProviderEntry({runtime:t,pkg:e});if(!n)throw new Error(`Provider package '${e}' is not installed; run its explicit login/install flow first`);return import(g(n).href)}return import(e)}async function loadInstalledProviderModules(){const e=createNodeRuntime(),t=createConfigStore({config:await loadCommandCodeConfig({runtime:e}),runtime:e}).getProviders(),n=await loadInstalledBuiltinProviderModules(),r=await loadProviderModules({entries:t,builtins:n,importModule:__name(t=>importProviderModule(t,e.cwd()),"importModule")}),o={};for(const[e,n]of Object.entries(t))o[e]=n.module??n.npm??e;return{modules:uniqueProviderModules([...n,...r.modules]),errors:r.errors,sources:o}}async function settingsProviderSpecifier(e){const t=createNodeRuntime(),n=createConfigStore({config:await loadCommandCodeConfig({runtime:t}),runtime:t}).getProviders()[e];if(!n||!0===n.disabled)return;const r=n.module??n.npm;return r&&r!==e?{specifier:r,version:n.version}:void 0}async function loadSettingsProviderModule(e,t){const n=await settingsProviderSpecifier(e);if(n)return coerceProviderModule(await importProviderModule(n.specifier,createNodeRuntime().cwd(),t,n.version))}__name(loadBuiltinProviderModule,"loadBuiltinProviderModule"),__name(loadInstalledBuiltinProviderModules,"loadInstalledBuiltinProviderModules"),__name(uniqueProviderModules,"uniqueProviderModules"),__name(importProviderModule,"importProviderModule"),__name(loadInstalledProviderModules,"loadInstalledProviderModules"),__name(settingsProviderSpecifier,"settingsProviderSpecifier"),__name(loadSettingsProviderModule,"loadSettingsProviderModule");var WD=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:Ak});async function providerAuthHeaders(e){return WD.providerAuthHeaders(e)}async function hasProviderCredential(e){return WD.hasProviderCredential(e)}async function providerLogin(e){return WD.login(e)}async function providerLogout(e){return WD.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=ns[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(Pt.yellow(` ${e}`)),console.log()}function printLoginLink(e){console.log(),console.log(Pt.dim(" Login: ")+createOSC8Link(e,"Open auth page ↗")),console.log()}async function openAuthPage(e,t){await xt(e,t).catch(()=>{console.log(Pt.dim(` Could not auto-open browser. Open: ${e}`))})}async function confirmOpenAfterCode(){const e=await Qe({message:"Press Enter to open GitHub and paste the code there.",active:"Open",inactive:"Cancel",initialValue:!0});if(Je(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)?Pt.dim(" (copied)"):"";console.log(` ${Pt.yellow("Logging into Copilot, use this code:")} ${Pt.bold(t)}${n}`),console.log()}async function performProviderAuth(e){const{provider:t}=e,n=getProviderDisplayName(t);try{let e=!0;const r=t===fo.COPILOT;if(!r){const t=await Qe({message:`Open browser to sign in with ${n}?`,initialValue:!0});if(Je(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(` ${Pt.dim(ft.circleFilled)} ${Pt.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 Xe({message:t.prompt.label,mask:"*"});if(Je(e)||!String(e).trim())throw new Error("No authorization code provided");return{code:String(e).trim()}}console.log(` ${Pt.dim(ft.circleFilled)} ${Pt.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 HD=__name(({message:e})=>it.createElement(it.Fragment,null,it.createElement(et,{color:LR.CYAN},it.createElement(bt,{type:"dots"})),it.createElement(et,null," ",e)),"LoadingIndicator"),GD=__name(({message:e})=>it.createElement(it.Fragment,null,it.createElement(et,{color:LR.GREEN},ft.tick),it.createElement(et,null," ",e)),"SuccessIndicator"),VD=__name(({children:e})=>it.createElement(Ze,{flexDirection:"column"},it.createElement(et,null," "),it.createElement(Ze,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"),ze.intro(heading({text:"Command Code Authentication"}))}function showLoginCancelMessage(e){Ke(`${ft.cross} ${e}`)}function printMessage(e){console.log(""),console.log(e),console.log("")}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=rt(it.createElement(DO,{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 zD=__name(({env:e,onComplete:t})=>{const[n,r]=ct("checking"),[o,s]=ct(null);return ut(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),ut(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),it.createElement(VD,null,"checking"===n&&it.createElement(HD,{message:"Checking authentication status..."}),"logged_in"===n&&it.createElement(GD,{message:"Authenticated"}),"not_logged_in"===n&&it.createElement(GD,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=rt(it.createElement(zD,{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||(Ke(`${ft.cross} Login failed: ${e.error}`),process.exit(1)),qe(Pt.green(`${ft.tick} ${e.message}`)),process.exit(0)}await runLogin(),process.exit(0)}catch(e){isUserCancellation(e)&&process.exit(0),console.error(`${ft.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(performProviderLogin,"performProviderLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction");var KD=new He("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:$o})}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()})}Vt(),PR(),__name(performLogout,"performLogout"),__name(performProviderLogout,"performProviderLogout"),__name(readLogoutUserName,"readLogoutUserName");var qD=__name(({userName:e})=>{const t=e?`Logging out ${e}...`:"Logging out...";return it.createElement(it.Fragment,null,it.createElement(et,{color:LR.CYAN},it.createElement(bt,{type:"dots"})),it.createElement(et,null," ",t))},"LoadingIndicator"),YD=__name(({userName:e,wasAuthenticated:t})=>{const n=!1===t?"Not currently authenticated":formatLogoutSuccess(e);return it.createElement(it.Fragment,null,it.createElement(et,{color:LR.GREEN},ft.tick),it.createElement(et,null," ",n))},"SuccessIndicator"),QD=__name(({errorMessage:e})=>it.createElement(it.Fragment,null,it.createElement(et,{color:LR.RED},ft.cross),it.createElement(et,{color:LR.RED}," Logout failed: ",e)),"ErrorIndicator"),JD=__name(({status:e,errorMessage:t,userName:n,wasAuthenticated:r})=>"loading"===e?it.createElement(qD,{userName:n}):"success"===e?it.createElement(YD,{userName:n,wasAuthenticated:r}):it.createElement(QD,{errorMessage:t}),"StatusDisplay"),XD=__name(({onComplete:e,userName:t})=>{const[n,r]=ct("loading"),[o,s]=ct(""),[a,i]=ct(null);return ut(()=>{performLogout().then(e=>{i(e),e.success?r("success"):(s(e.error||"Unknown error"),r("error"))})},[]),ut(()=>{if(("success"===n||"error"===n)&&a){const t=setTimeout(()=>e(a),100);return()=>clearTimeout(t)}},[n,a,e]),it.createElement(Ze,{flexDirection:"column"},it.createElement(et,null," "),it.createElement(Ze,null,it.createElement(JD,{status:n,errorMessage:o,userName:t,wasAuthenticated:a?.wasAuthenticated})))},"LogoutSpinner");function printWarnings(e){0!==e.length&&(console.warn(Pt.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(Pt.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}=rt(it.createElement(XD,{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(`${ft.cross} ${e.error}`),process.exit(1)),console.log(`${ft.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 ZD=new He("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=It("Checking authentication status...").start();try{const e=getApiEnv(),n=await checkAuthStatus(e);n.error&&(t.fail(Pt.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(t.fail(Pt.red("Not authenticated")),console.log(""),console.log(`${Pt.dim("Run")} ${Pt.cyan(`${getBinaryCommand()} auth login`)} ${Pt.dim("to authenticate.")}`),console.log(""),process.exit(1));const r=isGenericCommandAuthUserName(n.userName)?"":` as ${Pt.cyan(n.userName)}`;t.succeed("Authentication verified"),console.log(`${Pt.green(ft.tick)} ${Pt.bold("Authenticated")}${r}`),console.log(` ${Pt.dim("Provider:")} ${Pt.cyan("Command Code")}`),n.fromEnv&&console.log(` ${Pt.dim("Source:")} ${Pt.cyan(`$${$o}`)} ${Pt.dim("(env var)")}`),console.log(""),process.exit(0)}catch(e){t.fail(Pt.red(`Status check failed: ${e instanceof Error?e.message:"Unknown error"}`)),process.exit(1)}}Vt(),PR(),__name(checkAuthStatus,"checkAuthStatus"),__name(buildStatusJson,"buildStatusJson"),__name(statusAction,"statusAction");var e$=new He("status").description("Show authentication status").option("--json","Output status as JSON for automation").allowUnknownOption().allowExcessArguments().action(statusAction);function parseValue(e){try{const t=JSON.parse(e);if("string"==typeof t||"boolean"==typeof t||"number"==typeof t)return t}catch{}return e}function rowValue(e){return e.currentValue}function rowMatchesScope(e,t){return"effective"===t||e.scope===t}function printValue(e,t){console.log(t?JSON.stringify(e,null,2):String(e))}function liveApplyInfo(e){return e===Op?{liveSessionReloadsOnNextRound:!1,message:"This sets the default model for new sessions. Use /model to change the running session."}:{liveSessionReloadsOnNextRound:!0,message:"A running session picks this up at the start of its next round."}}function unknownKeyMessage(e,t){const n=e.suggest({raw:t});return 0===n.length?`Unknown configuration setting: ${t}`:`Unknown configuration setting: ${t}. Did you mean: ${n.join(", ")}?`}async function createRegistry(){const e=getCommandConfigRuntime(),t=await loadCommandCodeConfig({runtime:e});let n=normalizePermissionMode(t.permissions?.defaultMode)??normalizePermissionMode(t.permissionMode)??"default";return createConfigToolRegistry({runtime:e,listModelIds:__name(()=>listKnownModelIds(),"listModelIds"),model:{current:__name(()=>getConfiguredModel(),"current"),set:__name(async({model:e})=>persistDefaultModel({model:e}),"set")},permissionMode:{current:__name(()=>n,"current"),set:__name(async({mode:t})=>{await updateUserSettings({runtime:e,patch:{permissions:{defaultMode:t}}}),n=t},"set")}})}function withCommonOptions(e){return e.addOption(new Ge("--scope <scope>","Configuration scope").choices(["effective","user","project"]).default("effective")).option("--json","Print machine-readable JSON")}new He("auth").description("Manage authentication with Command Code").addCommand(KD).addCommand(ZD).addCommand(e$),Vt(),PR(),__name(parseValue,"parseValue"),__name(rowValue,"rowValue"),__name(rowMatchesScope,"rowMatchesScope"),__name(printValue,"printValue"),__name(liveApplyInfo,"liveApplyInfo"),__name(unknownKeyMessage,"unknownKeyMessage"),__name(createRegistry,"createRegistry"),__name(withCommonOptions,"withCommonOptions");var t$=withCommonOptions(new He("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})`)}),n$=withCommonOptions(new He("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)}),r$=withCommonOptions(new He("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=liveApplyInfo(i.id),c={id:i.id,previousValue:i.previousValue,newValue:i.newValue,scope:n.scope,liveSessionReloaded:!1,liveSessionReloadsOnNextRound:l.liveSessionReloadsOnNextRound};n.json?printValue(c,!0):(console.log(`${i.id}: ${JSON.stringify(i.previousValue)} -> ${JSON.stringify(i.newValue)} (${n.scope})`),console.log(l.message))}),o$=new He("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=liveApplyInfo(a.id),l={id:a.id,previousValue:a.previousValue,newValue:a.newValue,scope:s.scope,liveSessionReloaded:!1,liveSessionReloadsOnNextRound:i.liveSessionReloadsOnNextRound};t.json?printValue(l,!0):(console.log(`${a.id}: ${JSON.stringify(a.previousValue)} -> ${JSON.stringify(a.newValue)} (default, ${s.scope})`),console.log(i.message))}),s$=new He("config").description("Inspect and update validated configuration settings").addCommand(t$).addCommand(n$).addCommand(r$).addCommand(o$);async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=It("Opening the GitHub issue…").start();try{await xt(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("")}}Vt(),PR(),__name(openGitHubIssue,"openGitHubIssue");var a$=new He("feedback").alias("issue").description("Report a bug or share feedback — opens a GitHub issue").argument("[title]","Optional issue title").action(openGitHubIssue);Vt();var i$=new He("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});Vt(),Vt(),PR(),Vt(),PR();var l$=__name(({icon:e,label:t,children:n})=>it.createElement(et,null,it.createElement(et,{color:LR.CYAN},e," "),it.createElement(et,{color:LR.DIM},t.padEnd(12)),n),"Row"),c$=__name(({title:e})=>it.createElement(et,null,it.createElement(et,{color:LR.GRAY},"───"),it.createElement(et,{color:LR.WHITE}," ",e," "),it.createElement(et,{color:LR.GRAY},"─".repeat(35))),"Header"),d$=__name(({title:e,marginTop:t=0,children:n})=>it.createElement(Ze,{flexDirection:"column",marginTop:t},it.createElement(c$,{title:e}),it.createElement(Ze,{flexDirection:"column",paddingY:1},n)),"Section"),u$=__name(({host:e,systemInfo:t})=>it.createElement(d$,{title:"System Information"},it.createElement(l$,{icon:ft.bullet,label:"Version"},it.createElement(et,{color:LR.GREEN},t.version)),it.createElement(l$,{icon:ft.bullet,label:"Date"},it.createElement(et,null,formatDate())),it.createElement(l$,{icon:ft.pointer,label:"Platform"},it.createElement(et,{color:LR.GREEN},t.os),it.createElement(et,{color:LR.DIM}," ","(",e.platform,", ",e.arch,")")),it.createElement(l$,{icon:ft.triangleUp,label:"Hostname"},it.createElement(et,null,e.hostname)),it.createElement(l$,{icon:ft.bullet,label:"User"},it.createElement(et,{color:LR.YELLOW},e.username)),it.createElement(l$,{icon:ft.bullet,label:"CPUs"},it.createElement(et,{color:LR.MAGENTA},e.cpus.length," cores")),it.createElement(l$,{icon:ft.bullet,label:"Memory"},it.createElement(et,{color:LR.CYAN},e.totalMemoryGb," GB")),it.createElement(l$,{icon:ft.play,label:"Uptime"},it.createElement(et,null,formatUptime(e.uptimeSeconds))),it.createElement(l$,{icon:ft.arrowRight,label:"Home"},it.createElement(et,{color:LR.DIM},e.homeDir)),it.createElement(l$,{icon:ft.pointer,label:"Shell"},it.createElement(et,null,t.shell)),it.createElement(l$,{icon:ft.bullet,label:"Node"},it.createElement(et,{color:LR.GREEN},e.nodeVersion)),it.createElement(l$,{icon:ft.pointer,label:"Terminal"},it.createElement(et,{color:LR.CYAN},t.terminal)),it.createElement(l$,{icon:ft.bullet,label:"IDE"},it.createElement(et,null,t.ide))),"SystemInfoSection"),m$=__name(({cpus:e})=>it.createElement(d$,{title:"CPU Details",marginTop:1},e.map((e,t)=>it.createElement(l$,{key:t,icon:ft.bullet,label:`Core ${t}`},it.createElement(et,null,e.model),it.createElement(et,{color:LR.YELLOW}," @ ",e.speedMHz," MHz")))),"CPUDetailsSection"),p$=__name(({addresses:e})=>it.createElement(d$,{title:"Network",marginTop:1},e.map((e,t)=>it.createElement(l$,{key:`${e.interfaceName}-${t}`,icon:ft.bullet,label:e.interfaceName},it.createElement(et,{color:LR.GREEN},e.address)))),"NetworkSection"),g$=__name(({host:e,verbose:t,systemInfo:n})=>it.createElement(Ze,{flexDirection:"column"},it.createElement(et,null,"System Information"),it.createElement(et,null,"─".repeat(40)),it.createElement(et,null,"Version ",n.version),it.createElement(et,null,"Date ",formatDate()),it.createElement(et,null,"Platform ",n.os," (",e.platform,", ",e.arch,")"),it.createElement(et,null,"Hostname ",e.hostname),it.createElement(et,null,"User ",e.username),it.createElement(et,null,"CPUs ",e.cpus.length," cores"),it.createElement(et,null,"Memory ",e.totalMemoryGb," GB"),it.createElement(et,null,"Uptime ",formatUptime(e.uptimeSeconds)),it.createElement(et,null,"Home ",e.homeDir),it.createElement(et,null,"Shell ",n.shell),it.createElement(et,null,"Node ",e.nodeVersion),it.createElement(et,null,"Terminal ",n.terminal),it.createElement(et,null,"IDE ",n.ide),t&&it.createElement(it.Fragment,null,it.createElement(et,null,"\n","CPU Details"),it.createElement(et,null,"─".repeat(40)),e.cpus.map((e,t)=>it.createElement(et,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speedMHz," MHz")),it.createElement(et,null,"\n","Network"),it.createElement(et,null,"─".repeat(40)),e.externalIpv4.map((e,t)=>it.createElement(et,{key:`${e.interfaceName}-${t}`},e.interfaceName.padEnd(12),e.address)))),"PlainTextInfo"),h$=__name(({host:e,verbose:t,systemInfo:n})=>it.createElement(Ze,{flexDirection:"column"},it.createElement(u$,{host:e,systemInfo:n}),t&&it.createElement(m$,{cpus:e.cpus}),t&&it.createElement(p$,{addresses:e.externalIpv4})),"StyledInfo"),f$=__name(({verbose:e=!1,text:t=!1,systemInfo:n})=>{const{exit:r}=st();ut(()=>{const e=setTimeout(()=>r(),50);return()=>clearTimeout(e)},[r]);const o=mt(()=>collectHostDiagnostics(),[]);return t?it.createElement(g$,{host:o,verbose:e,systemInfo:n}):it.createElement(h$,{host:o,verbose:e,systemInfo:n})},"InfoUI");async function runInfo(e){await applyStartupTheme();const t=getSystemInfo(),{waitUntilExit:n}=rt(it.createElement(f$,{verbose:e.verbose,text:e.text,systemInfo:t}));await n()}__name(runInfo,"runInfo");var y$=new He("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)}`}Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt(),Vt(),__name(formatUsd,"formatUsd");var S$=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatShortDateUtc(e){const t=S$[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 w$={"zai-org/GLM-5":{inputCost:1,outputCost:3.2,cacheReadCost:.2},"zai-org/GLM-5.2":{inputCost:1.4,outputCost:4.4,cacheReadCost:.26}};function advertisedBandOf(e,t){const n=e.timeOfDay;return n?t<Date.parse(n.effectiveFrom)?e:n.offPeak:e}function primaryUpstreamOf(e,t){const n=e.order[0],r=n?e.providers[n]:void 0;if(!r)throw new Error(`display-pricing: billing entry "${t}" has no primary upstream in its \`order\``);return r}__name(advertisedBandOf,"advertisedBandOf"),__name(primaryUpstreamOf,"primaryUpstreamOf");var v$={inputCost:.042,outputCost:0,cacheReadCost:0};function jevBilledRates(e){return isJevFree(e)?{inputCost:0,outputCost:0,cacheReadCost:0}:v$}function getDisplayRates(e,t=Date.now()){const n=w$[e];if(n)return n;if("typesafe/jev"===e)return jevBilledRates(t);const r=Object.values(uD).flat().find(t=>t.id===e);if(r)return{inputCost:r.promptCost,outputCost:r.completionCost,cacheReadCost:r.cacheHitCost??0,...null!=r.cacheWrite5mCost&&{cacheWriteCost:r.cacheWrite5mCost},...null!=r.cacheWrite1hCost&&{cacheWrite1hCost:r.cacheWrite1hCost}};const o=ED.find(t=>t.canonicalId===e);if(o)return toDisplayRates(advertisedBandOf(primaryUpstreamOf(o,e),t));const s=RD.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=TD.find(t=>t.canonicalId===e);if(a)return{inputCost:a.promptCost,outputCost:a.completionCost,cacheReadCost:a.cacheReadCost};const i=PD.find(t=>t.canonicalId===e);if(i)return{inputCost:i.promptCost,outputCost:i.completionCost,cacheReadCost:i.cacheReadCost};const l=MD.find(t=>t.canonicalId===e);if(l)return{inputCost:l.promptCost,outputCost:l.completionCost,cacheReadCost:l.cacheReadCost};const c=xD.find(t=>t.canonicalId===e);if(c)return{inputCost:c.promptCost,outputCost:c.completionCost,cacheReadCost:c.cacheReadCost};const d=AD.find(t=>t.canonicalId===e);if(d)return{inputCost:d.promptCost,outputCost:d.completionCost,cacheReadCost:d.cacheReadCost};const u=uD[oD]?.find(t=>t.id===`${oD}:${e}`);if(u)return{inputCost:u.promptCost,outputCost:u.completionCost,cacheReadCost:u.cacheHitCost??0};throw new Error(`display-pricing: unknown billing id "${e}": not in MODELS (bare or novita-prefixed), GATEWAY_MODEL_PRICING, OPENROUTER_MODEL_PRICING, ALIBABA_MODEL_PRICING, MORPH_MODEL_PRICING, WAFER_MODEL_PRICING, LONGCAT_MODEL_PRICING, TENCENT_MODEL_PRICING, or the decision model (JEV_MODEL_ID)`)}function toDisplayRates(e){return{inputCost:e.promptCost,outputCost:e.completionCost,cacheReadCost:e.cacheReadCost??0,...null!=e.cacheWriteCost&&{cacheWriteCost:e.cacheWriteCost}}}function getDisplayTimeOfDay(e){if(w$[e])return;const t=ED.find(t=>t.canonicalId===e),n=t?.order[0],r=n?t?.providers[n]?.timeOfDay:void 0;if(!r)return;const o=peakHoursPerDay(r.peakWindowsUtc);return{effective:r.effectiveFrom,peak:toDisplayRates(r.peak),offPeak:toDisplayRates(r.offPeak),peakWindowsUtc:r.peakWindowsUtc,peakDaysUtc:r.peakDaysUtc,peakHoursPerDay:o,offPeakHoursPerDay:24-o}}function timeOfDayNote(e){const t=`${formatUsd(e.offPeak.inputCost)}/${formatUsd(e.offPeak.outputCost)}`,n=`${formatUsd(e.peak.inputCost)}/${formatUsd(e.peak.outputCost)}`;return`From ${formatShortDateUtc(e.effective)}: ${t} off-peak, ${n} peak (${e.peakHoursPerDay}h/day)`}function timeOfDayScheduledChanges(){const e={};for(const t of ED){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(fD).find(t=>t.id===e)}function getModelNotice(e){const t=findModelById(e);if(!t?.notice)return;const n=t.vendorLabel??DD[t.provider]??"the upstream provider";return t.notice.replaceAll("{name}",t.name).replaceAll("{vendor}",n)}function getProviderFromModel(e){return findModelById(e)?.provider??YO}function getAllModelOptions(){return Object.values(fD)}function getModelGroupLabel(e){return e.vendorLabel??DD[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[...$D.filter(e=>t.has(e)),...[...t.keys()].filter(e=>!$D.includes(e))].map(e=>({label:e,models:t.get(e)}))}function getModelGroupsInOrder(){return groupModelsByDisplayOrder(getAllModelOptions().filter(e=>!e.hidden))}function resolveKnownModelId2(e){const t=getCanonicalModelId(e);return findModelById(t)?t:void 0}function modelSupportsVision(e){const t=findModelById(getCanonicalModelId(e));return!t?.inputModalities||t.inputModalities.includes("image")}function modelSupportsZdr(e){return!bD.has(getCanonicalModelId(e))}__name(jevBilledRates,"jevBilledRates"),__name(getDisplayRates,"getDisplayRates"),__name(toDisplayRates,"toDisplayRates"),__name(getDisplayTimeOfDay,"getDisplayTimeOfDay"),__name(timeOfDayNote,"timeOfDayNote"),__name(timeOfDayScheduledChanges,"timeOfDayScheduledChanges"),timeOfDayScheduledChanges(),Vt(),__name(findModelById,"findModelById"),__name(getModelNotice,"getModelNotice"),__name(getProviderFromModel,"getProviderFromModel"),__name(getAllModelOptions,"getAllModelOptions"),__name(getModelGroupLabel,"getModelGroupLabel"),__name(groupModelsByDisplayOrder,"groupModelsByDisplayOrder"),__name(getModelGroupsInOrder,"getModelGroupsInOrder"),__name(resolveKnownModelId2,"resolveKnownModelId"),__name(modelSupportsVision,"modelSupportsVision"),__name(modelSupportsZdr,"modelSupportsZdr");var k$=/[-@]\d{8}$/,C$="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=(LD[e.toLowerCase()]??e).toLowerCase(),n=Object.values(fD).find(e=>e.id.toLowerCase()===t);if(n)return n.id;const r=yD.find(e=>e.canonicalId.toLowerCase()===t)??yD.find(e=>ossEntryMatches(e,t));return r?.canonicalId}function getCanonicalModelId(e){if(!e)return e;const t=e.startsWith(C$)?e.slice(C$.length):e,n=tryResolveCanonical2(t);if(n)return n;const r=t.replace(k$,"");return r===t?t:tryResolveCanonical2(r)??t}function getModelDisplayName(e){const t=getCanonicalModelId(e),n=Object.values(fD).find(e=>e.id===t);return n?.name??e}__name(ossEntryMatches,"ossEntryMatches"),__name(tryResolveCanonical2,"tryResolveCanonical"),__name(getCanonicalModelId,"getCanonicalModelId"),__name(getModelDisplayName,"getModelDisplayName"),Vt(),PR();var b$=null;function setRegisteredProviderModules(e){b$=new Set(e.modules.map(e=>e.id))}function isProviderLaneRegistered(e){const t=b$;if(!t)return!0;if(!rs[e.providerId]?.requiresAuth)return!0;const n=Ak[e.providerId]??e.providerId;return t.has(n)}function isProviderLaneListable(e){if(!rs[e.providerId]?.requiresAuth)return!0;const t=Ak[e.providerId]??e.providerId,n=builtinProviderPackage(t);return!(!n||!1===n.discoverable)||(b$?.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 E$=getPackageJson(import.meta.url),T$="string"==typeof E$.version&&E$.version.trim()?E$.version:"unknown",P$=new Set(Object.values(Ak));function selectActiveOAuthProviderModules(e){const t=e.provider?Ak[e.provider]:void 0;return e.modules.filter(e=>!P$.has(e.id)||e.id===t)}async function restoreSelectedOAuthProviderModule(e){if(!e.provider)return;if(e.disabled)return;const t=Ak[e.provider];if(!t)return;if(e.modules.some(e=>e.id===t))return;if(!await e.hasCredential(e.provider))return;const n=await e.loadModule(t);if(!n)throw new Error(`No installed or user-registered provider package is available for '${t}'`);e.modules.push(n)}function estimateSessionCostUsd(e){try{const t=getDisplayRates(e.model),{inputTokens:n,outputTokens:r,cacheReadTokens:o,cacheWriteTokens:s,cacheWriteTokens1h:a=0}=e.usage,i=Math.max(0,n-o-s),l=Math.min(a,s),c=s-l,d=t.cacheWriteCost??0,u=t.cacheWrite1hCost??d;return(i*t.inputCost+r*t.outputCost+o*t.cacheReadCost+c*d+l*u)/1e6}catch{return}}async function createHarnessSession(e){const t=e.runtime??createNodeRuntime(),n=await loadCommandCodeConfig({runtime:t}),r=e.configStore??createConfigStore({config:n,runtime:t,modelOverride:getModelOverride(),modelOverrideProvider:getModelOverrideProvider()});if(!e.configStore&&void 0===getModelOverride())try{const t=await loadCommandSessionMeta({sessionId:e.sessionId});t?.model&&(await loadCustomProviderModels(),(void 0!==resolveKnownModelId2(t.model)||isByok({model:t.model}))&&r.setSessionModel({model:t.model,...void 0!==t.modelProvider?{provider:t.modelProvider}:{}}))}catch{}const o=e.providerModules??e.modHost?.providerModules(),s=new Set((await loadProvidersConfig({runtime:t})).disabledProviderIds),a=[...o??[...await loadInstalledBuiltinProviderModules()]].filter(e=>!s.has(e.id)),i=(await loadUserConfig({runtime:t,path:legacyUserConfigPath({runtime:t})})).provider,l=i?Ak[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 '${getBinaryCommand()} 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??T$,providerModules:u,providerBinding:{provider:i??null},importProviderModule:e.importProviderModule??(t=>importProviderModule(t,e.runtime?.cwd()??process.cwd())),estimateCostUsd:e.estimateCostUsd??estimateSessionCostUsd})}__name(selectActiveOAuthProviderModules,"selectActiveOAuthProviderModules"),__name(restoreSelectedOAuthProviderModule,"restoreSelectedOAuthProviderModule"),__name(estimateSessionCostUsd,"estimateSessionCostUsd"),__name(createHarnessSession,"createHarnessSession");var M$=createHarnessSessionManager({createSession:createHarnessSession}),x$=M$.getHarnessForSession,I$=M$.getResolvedHarness,A$=M$.forgetHarnessSession,R$=M$.disposeAllHarnessSessions,L$=new Set;function onHarnessSessionRebuild(e){return L$.add(e),()=>L$.delete(e)}async function rebuildHarnessSession(e){try{await(I$(e)?.flush())}catch{}A$(e);const t=[];for(const n of L$){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 O$=null,D$=null,$$=[],N$=null,_$=!1;async function loadFromConfig(){const e=await loadProvidersConfig({runtime:createNodeRuntime()});return $$=e.warnings,N$=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 O$||(diskLoadsBlocked()?O$=[]:loadIntoCache())}function loadIntoCache(){return D$??=loadFromConfig().then(e=>(O$=e,e)).catch(()=>O$=[]),D$}async function refreshCustomProviderModels(e){if(diskLoadsBlocked())return O$??=[],{providers:O$,changed:!1};const t=null!==O$?N$:null;O$=null,D$=null;const n=await loadIntoCache();null!==t&&t!==N$&&(_$=!0);const r=_$;return _$&&e?.sessionId&&(await rebuildHarnessSession(e.sessionId),_$=!1),{providers:n,changed:r}}function seedSnapshotSync(){if(null===O$&&!process.env.VITEST)try{const e=x.readFileSync(`${H()}/.commandcode/providers.json`,"utf8"),t=parseProvidersConfig(JSON.parse(e));$$=t.warnings,N$=JSON.stringify({providers:t.providers,disabled:t.disabledProviderIds}),O$=t.providers.map(e=>({id:e.id,name:e.name??e.id,models:e.models}))}catch{}}function getCustomProviderModelsSync(){return O$||(seedSnapshotSync(),O$||(loadCustomProviderModels(),[]))}function getCustomProviderWarningsSync(){return $$}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){if(resolveKnownModelId2(e))return;const t=getCustomProviderModelsSync(),n=findQualified(t,e);return n?n.providerId:findDeclared(t,e)?.providerId}async function resolveSelectableModel(e){const t=e.trim();if(!t)return;const n=await loadCustomProviderModels(),r=resolveKnownModelId2(t);if(r)return{modelId:r};const o=t.indexOf("/");if(o>0){const e=t.slice(0,o).toLowerCase();if(n.some(t=>t.id===e))return findDeclared(n,t)??findQualified(n,t)}const s=resolveModelInput({model:t,models:getAllModelOptions()});return s?{modelId:s}:findDeclared(n,t)??findQualified(n,t)}function customProvidersDeclaring(e){const t=e.trim().toLowerCase();return getCustomProviderModelsSync().filter(e=>e.models.some(e=>e.id.toLowerCase()===t)).map(e=>e.id)}function customContextWindow(e){return declaredCustomModel(e)?.contextWindow}function customReasoningEfforts(e){return declaredCustomModel(e)?.reasoningEfforts}function declaredCustomModel(e){const t=getCustomProviderModelsSync(),n=findDeclared(t,e),r=n?void 0:findQualified(t,e),o=n??r;if(!o||o.warning)return;const s=t.find(e=>e.id===o.providerId);if(!s)return;const 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"),Vt(),Vt(),Vt(),PR(),Vt(),Vt();var F$=__name(({label:e="Loading",spinner:t=!1})=>it.createElement(et,{color:LR.DIM},t&&it.createElement(it.Fragment,null,it.createElement(bt,{type:"dots"})," "),e,"…"),"LoadingLine"),U$=__name(({children:e,glyph:t=!0})=>it.createElement(et,{color:LR.RED},t&&`${ft.cross} `,e),"ErrorLine"),j$=__name(({children:e,glyph:t=!0})=>it.createElement(et,{color:LR.GREEN},t&&`${ft.tick} `,e),"SuccessLine"),B$=__name(({title:e="Oops, something went wrong:",children:t})=>it.createElement(Ze,{flexDirection:"column",borderStyle:"single",borderColor:LR.RED,paddingX:2,paddingY:1,marginTop:1},it.createElement(et,{color:LR.RED,bold:!0},e),it.createElement(Ze,{marginTop:1},it.createElement(et,null,t))),"ErrorPanel"),W$=__name(({message:e,hint:t})=>it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.GRAY},e),t?it.createElement(et,{color:LR.DIM},t):null),"EmptyState"),H$=__name(({error:e,traceId:t})=>it.createElement(Ze,{marginBottom:2},it.createElement(B$,null,e,t&&it.createElement(et,{color:LR.DIM},"\n\n","Trace ID: ",t))),"ErrorSection");async function runTasteImport(e={}){const t=await runOnboardingImportWithEvents({events:up,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}))}}Vt(),Vt(),PR(),Vt(),PR(),__name(runTasteImport,"runTasteImport");var G$={isImporting:!1,waitingForInput:!1,error:null},V$=__name(e=>{const t=dt(null),n=dt(e);n.current=e;const[r,o]=ct({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null}),s=pt(()=>{const e=t.current;!e||e.isAborted()||(e.finishCancelled(),o(e=>({...e,...G$})))},[]);return ut(()=>{const e=createOnboardingImportLifecycle({events:up});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,...G$}));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");Vt();var z$,K$,q$=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{ot((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");function getRuntime(){return z$??=createNodeRuntime()}function getStore(){return K$??=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")}Vt(),PR(),Vt(),PR(),__name(getRuntime,"getRuntime"),__name(getStore,"getStore"),__name(checkOnboardingConditions2,"checkOnboardingConditions"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(markOnboardingSkipped2,"markOnboardingSkipped"),__name(dismissOnboardingForeverForProject,"dismissOnboardingForeverForProject"),__name(triggerTasteOnboarding,"triggerTasteOnboarding");var Y$=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=ct(null),[o,s]=ct(null),[a,i]=ct(void 0),l=dt(!1);return ut(()=>{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:qo.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");Vt(),PR();var Q$=__name(({conditions:e,autoLearn:t})=>{const[n,r]=ct("checking"),o=dt(!1);return ut(()=>{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]),ut(()=>{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{up.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{up.reset(),e()}}Vt(),PR(),Vt(),PR(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var J$=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=dt(n),o=pt(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=pt(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),a=pt(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),i=pt(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=pt(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");Vt(),PR();var X$=__name(e=>{const[t,n]=ct(()=>createTasteImportProjection({initialSteps:e})),r=pt(e=>{n(t=>({...t,importError:e}))},[]);return ut(()=>{const t=__name(()=>{n(resetTasteImportProjection({initialSteps:e}))},"handleReset"),r=__name(e=>{n(t=>reduceTasteImportEvent({state:t,event:e}))},"handleNewEvent");return up.on("reset",t),up.on("new-event",r),()=>{up.off("reset",t),up.off("new-event",r)}},[e]),{steps:t.steps,importError:t.importError,importTraceId:t.importTraceId,setImportError:r}},"useProgressEvents");Vt(),Vt(),Vt();var Z$=__name(({isImporting:e=!1,waitingForInput:t=!1})=>it.createElement(it.Fragment,null,e&&it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Esc to cancel")),t&&it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to continue"))),"HelpTextSection");Vt(),Vt(),Vt(),Vt();var eN=__name(()=>{const[e,t]=ct(!0);return ut(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),it.createElement(et,{color:LR.YELLOW},e?ft.circleFilled:ft.circle)},"PulsingDot");Vt();var tN=[ft.bullet,ft.squareSmallFilled,ft.lozenge,ft.star,ft.triangleRight,ft.triangleUp,ft.circleFilled,ft.pointer],nN=__name(e=>String(e).padStart(3," "),"padNum"),rN=__name(e=>tN[e%tN.length],"getSymbol"),oN=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${nN(t)} ↓${nN(n)} (↑↓ scroll)`,"buildStatusLine"),sN=__name(({insights:e})=>{const[t,n]=ct(0),[r,o]=ct(!0),s=e.length,a=s>10,i=Math.max(0,s-10),l=r&&a?i:t;if(ot((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 it.createElement(Ze,{flexDirection:"column",marginLeft:4,marginBottom:0},a&&it.createElement(et,{color:LR.DIM},oN(s,d,u,r)),c.map((e,t)=>{const n=l+t;return it.createElement(Ze,{key:n,marginBottom:0},it.createElement(et,{color:LR.DIM},rN(n)," ",e))}))},"ScrollableInsights");function getLabelColor(e,t){return e?LR.WHITE:t?LR.YELLOW:LR.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 aN=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:a,isAllComplete:i,summary:l,warning:c})=>{if(a)return it.createElement(Ze,{flexDirection:"column",marginBottom:0},it.createElement(IL,null),it.createElement(Ze,{marginTop:0},it.createElement(et,{color:LR.DIM},TL),it.createElement(Ze,{marginLeft:2},i?it.createElement(et,{color:DR.TEXT},"learned your coding taste"):it.createElement(vL,null))));const d=__name(()=>r?it.createElement(et,{color:FR.BG},ft.square):n?it.createElement(eN,null):it.createElement(et,{color:LR.DIM},ft.circle),"getStatusIcon"),u=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||u?it.createElement(Ze,{flexDirection:"column",marginBottom:0},(n||r)&&it.createElement(Ze,{marginBottom:0},it.createElement(Ze,{marginRight:1},d()),it.createElement(et,{color:getLabelColor(r,n)},e)),r&&t&&(!l||0===l.learningCount)&&it.createElement(Ze,{marginLeft:3,marginBottom:0},it.createElement(et,{color:LR.DIM},t)),o.length>0&&it.createElement(Ze,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map(e=>it.createElement(et,{key:e,color:LR.DIM},`${ft.bullet} ${e}`))),s.length>0&&it.createElement(sN,{insights:s}),r&&l&&l.learningCount>0&&it.createElement(Ze,{flexDirection:"column",marginLeft:1,marginBottom:0},it.createElement(Ze,{marginBottom:1,flexDirection:"row"},it.createElement(et,null,TL),it.createElement(Ze,{marginLeft:2},it.createElement(et,{color:DR.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",formatCategorySuffix(l.categories)))),it.createElement(Ze,{flexDirection:"column",marginLeft:1},it.createElement(et,{color:LR.DIM},ft.pointerSmall," Stored in ",l.storage),it.createElement(et,{color:LR.DIM},"Command Code automatically uses & updates taste files."))),r&&c&&it.createElement(Ze,{flexDirection:"column",marginLeft:1,marginBottom:0},c.split("\n").map(e=>it.createElement(et,{key:e,color:LR.YELLOW},`${ft.warning} ${e}`)))):null},"StepItem"),iN=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return it.createElement(Ze,{flexDirection:"column",marginBottom:1},e.map((e,n)=>it.createElement(Ze,{key:e.id,marginLeft:0===n?0:3},it.createElement(aN,{label:e.label,message:e.message,active:e.active,complete:e.complete,items:e.items,insights:e.insights,summary:e.summary,warning:e.warning,isIntro:0===n,isAllComplete:t}))))},"StepsSection"),lN=__name(({steps:e})=>it.createElement(iN,{steps:e}),"ProgressSection"),cN=__name(({onComplete:e,onCancel:t,onError:n,onErrorDismiss:r})=>{const{steps:o,importError:s,importTraceId:a}=X$(UI),{isImporting:i,waitingForInput:l,error:c,cancelImport:d}=V$(n);return q$({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}),it.createElement(Ze,{flexDirection:"column",padding:1},s&&it.createElement(H$,{error:s,traceId:a}),!s&&it.createElement(lN,{steps:o}),it.createElement(Z$,{isImporting:i,waitingForInput:l}))},"ImportProgress");async function runLearnTaste(){await applyStartupTheme();const{unmount:e}=rt(it.createElement(cN,{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 dN=new He("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(gg),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:qo.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 He("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 Ge("-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(yt.gray("Checking server authentication requirements..."));const t=await checkCommandMcpServerAuthRequirements(e);return t.requiresAuth&&console.log(yt.cyan("Server requires OAuth authentication.")),t},"checkServerAuthRequirements"),registerOAuthClient:__name(async e=>(console.log(yt.gray("Registering OAuth client...")),registerCommandMcpOAuthClient({registrationEndpoint:e.registrationEndpoint,clientName:e.clientName,redirectUris:[...e.redirectUris]})),"registerOAuthClient"),performOAuthFlow:__name(async e=>{console.log(yt.gray("A browser window will open for authentication.\n"));const t=await performCommandMcpOAuthFlow(e.serverName,e.serverUrl,{authorizationUrl:e.config.authorizationUrl,tokenUrl:e.config.tokenUrl,clientId:e.config.clientId,clientSecret:e.config.clientSecret,scopes:e.config.scopes?[...e.config.scopes]:void 0,resource:e.config.resource},{onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),onStatus:__name(e=>{console.log(yt.gray(` ${e}`))},"onStatus")});for(const e of s.warnings)console.log(yt.yellow(`Warning: ${e}`));"success"===s.authStatus&&console.log(yt.green("✓ Successfully authenticated")),"failed"===s.authStatus&&(console.log(yt.yellow(`Warning: Authentication failed: ${s.authError}`)),console.log(yt.gray(`You can retry with: ${getBinaryCommand()} mcp auth ${e}`)),console.log(yt.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?yt.yellow(a):yt.green(a)),console.log(yt.gray(` ${formatMcpCommandSummary(s.serverConfig)}`)),console.log(""),console.log(yt.cyan("Next steps:")),console.log(yt.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 _T)if(console.error(yt.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(yt.gray(`Usage: ${t.cliName} mcp add --transport stdio <name> -- <command> [args...]`)),void console.error(yt.gray(` or: ${t.cliName} mcp add <name> <command> [args...]`))):void("stdio-command-is-url"!==e.code?"insecure-oauth-url"===e.code&&(console.error(yt.gray("OAuth requires https:// (http:// is only allowed for loopback hosts: localhost, 127.0.0.1, [::1]).")),console.error(yt.gray("Switch the URL to https:// or use a non-OAuth server."))):e.suggestedCommand&&console.error(yt.gray(`Did you mean: ${e.suggestedCommand}`)));console.error(yt.gray(`Usage: ${t.cliName} mcp add --transport http <name> <url>`))}else console.error(yt.gray("Valid options: stdio, http"));else console.error(yt.gray(NT));else console.error(yt.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(yt.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function addJsonMcpCommand(){const e=new He("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 Ge("-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(yt.cyan("Starting OAuth authentication...")),console.log(yt.gray("A browser window will open for authentication.\n"));const t=await performCommandMcpOAuthFlow(e.serverName,e.serverUrl,{authorizationUrl:e.config.authorizationUrl,tokenUrl:e.config.tokenUrl,clientId:e.config.clientId,clientSecret:e.config.clientSecret,scopes:e.config.scopes?[...e.config.scopes]:void 0,resource:e.config.resource},{port:e.port,onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),onStatus:__name(e=>{console.log(yt.gray(` ${e}`))},"onStatus")});"success"===o.authStatus&&console.log(yt.green(`\n✓ Successfully authenticated with '${e}'`)),"failed"===o.authStatus&&(console.error(yt.yellow(`\nWarning: Authentication failed: ${o.authError}`)),console.error(yt.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(yt.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?yt.yellow(s):yt.green(s)),console.log(yt.gray(` ${formatMcpCommandSummary(o.serverConfig)}`)),console.log(""),console.log(yt.cyan("Next steps:")),console.log(yt.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 _T)if(console.error(yt.red(`Error: ${e.message}`)),"invalid-name"!==e.code){if("invalid-json"===e.code)return console.error(yt.gray("Make sure to quote the JSON string properly")),void console.error(yt.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(yt.gray(` ${t.path.join(".")}: ${t.message}`));else"missing-http-url"!==e.code&&e.code}else console.error(yt.gray(NT));else console.error(yt.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function authMcpCommand(){const e=new He("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(yt.red("Error: Server name is required")),console.error(yt.gray(`Usage: ${n} mcp auth <server>`)),console.error(yt.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(yt.green(`✓ Cleared authentication for '${e}'`)):void console.log(yt.yellow(`No authentication stored for '${e}'`));console.log(yt.cyan(`Authenticating with '${e}'...`)),console.log(yt.gray("A browser window will open for authentication.\n")),await authenticateConfiguredMcpServer({serverName:e,getMcpServer:getMcpServer,performOAuthFlow:__name(async e=>{const t=await performCommandMcpOAuthFlow(e.serverName,e.serverUrl,{authorizationUrl:e.config.authorizationUrl,tokenUrl:e.config.tokenUrl,clientId:e.config.clientId,clientSecret:e.config.clientSecret,scopes:e.config.scopes?[...e.config.scopes]:void 0,resource:e.config.resource},{onStatus:e.onStatus});return{success:t.success,token:t.tokens,error:t.error}},"performOAuthFlow"),discoverAndAuthenticate:discoverAndAuthenticateCommandMcpServer,onStatus:__name(e=>{console.log(yt.gray(` ${e}`))},"onStatus")}),console.log(yt.green(`\n✓ Successfully authenticated with '${e}'`)),console.log(yt.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(yt.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=t.expired?yt.yellow("expired"):yt.green("valid");console.log(` ${t.serverName}: ${e}`)}console.log("")}else console.log(yt.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(yt.yellow(`Authentication for '${e}' has expired`)),void(t.hasRefreshToken&&console.log(yt.gray(" A refresh token is available for re-authentication")));console.log(yt.green(`Authentication for '${e}' is valid`)),"number"==typeof t.expiresInMinutes&&console.log(yt.gray(` Expires in ${t.expiresInMinutes} minutes`)),t.scope&&console.log(yt.gray(` Scopes: ${t.scope}`))}else console.log(yt.yellow(`No authentication stored for '${e}'`))}function printMcpAuthError(e,t){if(e instanceof _T)return"server-not-found"===e.code?(console.error(yt.red(`Error: ${e.message}`)),void console.error(yt.gray(`Use "${t.cliName} mcp list" to see configured servers`))):"auth-failed"===e.code?(console.error(yt.red(`\nError: ${e.message}`)),void(t.serverName&&console.log(yt.gray(`Try again with "${t.cliName} mcp auth ${t.serverName}"`)))):void console.error(yt.red(`Error: ${e.message}`));console.error(yt.red(`Error: ${e instanceof Error?e.message:String(e)}`))}function getMcpCommand(){const e=new He("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(yt.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${yt.dim("Scope:")} ${r}`),console.log(` ${yt.dim("Transport:")} ${n.transport}`),console.log(` ${yt.dim("Status:")} ${n.enabled?yt.green("enabled"):yt.gray("disabled")}`),"http"===n.transport){if(console.log(` ${yt.dim("URL:")} ${n.url}`),t.headers.length>0){console.log(` ${yt.dim("Headers:")}`);for(const e of t.headers)console.log(` ${e.key}: ${e.value}`)}}else console.log(` ${yt.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${yt.dim("Args:")} ${n.args.join(" ")}`);if(t.env.length>0){console.log(` ${yt.dim("Environment:")}`);for(const e of t.env)console.log(` ${e.key}=${e.value}`)}console.log("")}catch(e){e instanceof _T&&(console.error(yt.red(`Error: ${e.message}`)),process.exit(1)),console.error(yt.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function formatAuthIcon(e){return"authenticated"===e||"static"===e?yt.green(ft.tick):"missing"===e?yt.red(ft.cross):yt.gray("-")}function listMcpCommand(){const e=new He("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(yt.yellow("\nNo MCP servers configured\n")),console.log(yt.gray("Add a server with:")),console.log(yt.gray(` ${getBinaryCommand()} mcp add --transport http <name> <url>`)),console.log(yt.gray(` ${getBinaryCommand()} mcp add --transport stdio <name> -- <command>`)),void console.log(yt.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(yt.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(yt.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.enabled?yt.green("enabled"):yt.gray("disabled"),s=formatAuthIcon(o.authStatus);console.log(` ${yt.white(o.name.padEnd(t))} ${yt.cyan(o.transport.padEnd(n))} ${yt.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(yt.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(yt.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new He("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Ge("-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(yt.green(`✓ Removed MCP server '${e}' from ${n.scopeLabel} config`))}catch(e){e instanceof _T&&(console.error(yt.red(`Error: ${e.message}`)),process.exit(1)),console.error(yt.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new He("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(H(),e);return!n||n.startsWith("..")||i(n)?e:`~${l}${n}`}Vt(),Vt(),PR(),Vt(),PR(),__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),__name(addMcpCommand,"addMcpCommand"),__name(printMcpAddError,"printMcpAddError"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),__name(printCollectError,"printCollectError"),Vt(),PR(),__name(addJsonMcpCommand,"addJsonMcpCommand"),__name(printMcpAddJsonError,"printMcpAddJsonError"),Vt(),PR(),__name(authMcpCommand,"authMcpCommand"),__name(printAuthList,"printAuthList"),__name(printAuthStatus,"printAuthStatus"),__name(printMcpAuthError,"printMcpAuthError"),Vt(),PR(),__name(getMcpCommand,"getMcpCommand"),Vt(),PR(),__name(formatAuthIcon,"formatAuthIcon"),__name(listMcpCommand,"listMcpCommand"),Vt(),PR(),__name(removeMcpCommand,"removeMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Vt(),Vt(),PR(),Vt(),PR(),__name(shortenModPath,"shortenModPath");var uN=__name(e=>e.split(H()).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(Pt.dim(`Installing ${t.kind} mod source ${Pt.reset(Pt.cyan(e))} (${r})…`));const o=await installModSource({runtime:n,source:e,scope:r}),s=await createModPathShortener(n);console.log(`${Pt.green(ft.tick)} Installed ${Pt.cyan(o.identity)}`),o.installedPath&&console.log(Pt.dim(` ${s(o.installedPath)}`)),console.log(Pt.dim(` Recorded in ${s(o.settingsPath)}`))}catch(e){console.error(`${Pt.red(ft.cross)} ${uN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}__name(createModPathShortener,"createModPathShortener"),__name(addAction,"addAction");var mN=new He("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);Vt(),PR(),Vt(),Vt(),Vt();var pN={running:0,waitingPermission:0,waitingQuestion:0,compacting:0};function bump(e,t){return Math.max(0,e+t)}function nextLifecycle(e,t){return"run_start"===t.type?{...e,running:e.running+1}:"run_end"===t.type?{...e,running:bump(e.running,-1)}:"compaction_start"===t.type?{...e,compacting:e.compacting+1}:"compaction_done"===t.type?{...e,compacting:bump(e.compacting,-1)}:"interaction_requested"===t.type?"permission"===t.kind?{...e,waitingPermission:e.waitingPermission+1}:{...e,waitingQuestion:e.waitingQuestion+1}:"interaction_resolved"===t.type?"permission"===t.kind?{...e,waitingPermission:bump(e.waitingPermission,-1)}:{...e,waitingQuestion:bump(e.waitingQuestion,-1)}:e}function reportFor(e){return e.waitingPermission>0?{state:"blocked",message:"permission"}:e.waitingQuestion>0?{state:"blocked",message:"question"}:e.running>0||e.compacting>0?{state:"working"}:{state:"idle"}}function reportKey(e){return`${e.state}:${e.message??""}`}__name(bump,"bump"),__name(nextLifecycle,"nextLifecycle"),__name(reportFor,"reportFor"),__name(reportKey,"reportKey"),Vt(),Vt();var gN=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`,"g");function sanitizeTitleForOutput(e){const t=e.replace(gN,"");let n="";for(const e of t){const t=e.codePointAt(0)??0;n+=t<=31||t>=127&&t<=159?" ":e}return n.replace(/\s{2,}/g," ").trim()}__name(sanitizeTitleForOutput,"sanitizeTitleForOutput");var hN="cmd",fN=`custom:${hN}`,yN="CMD_HERDR_PANE_OWNER";function resolveHerdrConfig(e){const t=e.CMD_HERDR?.trim().toLowerCase();if("0"===t||"false"===t)return null;if("1"!==e.HERDR_ENV?.trim())return null;if(e[yN])return null;const n=e.HERDR_SOCKET_PATH?.trim(),r=e.HERDR_PANE_ID?.trim();return n&&r?{socketPath:n,paneId:r}:null}function releasedPaneOwnerEnv(e,t){return e[yN]===String(t)?{[yN]:void 0}:{}}function claimHerdrPane(e){e[yN]=String(process.pid)}function clampBytes(e,t){if(!e)return;const n=sanitizeTitleForOutput(e);return n?Buffer.from(n,"utf-8").subarray(0,t).toString("utf-8").replace(/�$/,""):void 0}function clampText(e){if(!e)return;const t=sanitizeTitleForOutput(e);if(!t)return;const n=Array.from(t);return n.length<=80?t:n.slice(0,80).join("")}function metadataParams(e){const t=clampText(e.title),n=clampText(e.displayAgent),r=Object.fromEntries(Object.entries(e.tokens??{}).flatMap(([e,t])=>{const n=clampText(t);return n?[[e,n]]:[]}));return{...t?{title:t}:{},...!t&&e.clearTitle?{clear_title:!0}:{},...n?{display_agent:n}:{},...Object.keys(r).length>0?{tokens:r}:{}}}function buildHerdrLine(e){const{id:t,seq:n,paneId:r,request:o}=e,s={id:String(t)},a={pane_id:r,source:fN,agent:hN,seq:n};if("report"===o.kind){const e=clampBytes(o.message,32);return`${JSON.stringify({...s,method:"pane.report_agent",params:{...a,state:o.state,...e?{message:e}:{}}})}\n`}return"session"===o.kind?`${JSON.stringify({...s,method:"pane.report_agent_session",params:{...a,agent_session_id:o.sessionId}})}\n`:"metadata"===o.kind?`${JSON.stringify({...s,method:"pane.report_metadata",params:{...a,...metadataParams(o.metadata)}})}\n`:"paneRename"===o.kind?`${JSON.stringify({...s,method:"pane.rename",params:{pane_id:r,label:o.label}})}\n`:"agentRename"===o.kind?`${JSON.stringify({...s,method:"agent.rename",params:{target:r,name:o.name}})}\n`:`${JSON.stringify({...s,method:"pane.release_agent",params:a})}\n`}function herdrSocketEndpoint(e){const{socketPath:t,platform:n=process.platform}=e;return"win32"===n?`\\\\.\\pipe\\${t}`:t}function sendHerdrLine(e){const t=e.timeoutMs??250;return new Promise(n=>{let r=!1;const o=fe.createConnection(herdrSocketEndpoint({socketPath:e.socketPath})),s=__name(()=>{r||(r=!0,clearTimeout(a),o.destroy(),n())},"finish"),a=setTimeout(s,t);a.unref?.(),o.setEncoding("utf-8"),o.on("connect",()=>{o.write(e.line)}),o.on("data",e=>{e.includes("\n")&&s()}),o.on("error",s),o.on("close",s)})}__name(resolveHerdrConfig,"resolveHerdrConfig"),__name(releasedPaneOwnerEnv,"releasedPaneOwnerEnv"),__name(claimHerdrPane,"claimHerdrPane"),__name(clampBytes,"clampBytes"),__name(clampText,"clampText"),__name(metadataParams,"metadataParams"),__name(buildHerdrLine,"buildHerdrLine"),__name(herdrSocketEndpoint,"herdrSocketEndpoint"),__name(sendHerdrLine,"sendHerdrLine");var SN={enabled:!1,reportState:__name(()=>{},"reportState"),reportSession:__name(()=>{},"reportSession"),reportMetadata:__name(()=>{},"reportMetadata"),announce:__name(()=>{},"announce"),release:__name(()=>Promise.resolve(),"release")};function createHerdrReporter(e){const{config:t}=e;if(!t)return SN;const n=e.send??sendHerdrLine,r=e.now??Date.now;let o=1,s=1e3*r(),a=Promise.resolve(),i=0;const l=__name(e=>{const n=o;return o+=1,s+=1,buildHerdrLine({id:n,seq:s,paneId:t.paneId,request:e})},"nextLine"),c=__name(e=>{const r=l(e),o=i;return a=a.then(()=>o!==i?Promise.resolve():n({socketPath:t.socketPath,line:r})).catch(()=>{}),a},"enqueue");return{enabled:!0,reportState:__name((e,t)=>{c({kind:"report",state:e,message:t})},"reportState"),reportSession:__name(e=>{e&&c({kind:"session",sessionId:e})},"reportSession"),reportMetadata:__name(e=>{c({kind:"metadata",metadata:e})},"reportMetadata"),announce:__name(()=>{c({kind:"paneRename",label:hN}),c({kind:"agentRename",name:hN})},"announce"),release:__name(()=>{const e=l({kind:"release"});return i+=1,n({socketPath:t.socketPath,line:e}).catch(()=>{})},"release")}}__name(createHerdrReporter,"createHerdrReporter");var wN=["run_start","run_end","interaction_requested","interaction_resolved","compaction_start","compaction_done"];function isHostEvent(e){return"session_start"===e.type||"session_shutdown"===e.type}function createHerdrMod(e={}){return t=>{const n=e.env??process.env,r=void 0!==e.config?e.config:resolveHerdrConfig(n),o=e.reporter??createHerdrReporter({config:r});r&&claimHerdrPane(n);let s=pN,a=null,i=null,l=null,c=null;if(t.addCommand({name:"herdr",description:"Show herdr reporting status for this pane",handler:__name(()=>{if(!o.enabled)return{message:["herdr: not reporting.","This session was not launched by herdr (HERDR_ENV, HERDR_SOCKET_PATH and","HERDR_PANE_ID must all be set), or CMD_HERDR=0 disabled it."].join("\n")};const e=reportFor(s);return{message:[`herdr: reporting to pane ${r?.paneId??"unknown"}`,` state ${e.state}${e.message?` (${e.message})`:""}`,` session ${i??"not yet started"}`,` model ${l??"not yet requested"}`,"","Control herdr from here — split panes, start other agents,","wait for them to finish:"," npx skills add herdrdev/herdr --skill herdr"].join("\n")}},"handler")}),!o.enabled)return;const d=__name(()=>{const e=reportFor(s),t=reportKey(e);t!==a&&(a=t,o.reportState(e.state,e.message))},"flushState"),u=__name(()=>{o.reportMetadata({...c?{title:c}:{clearTitle:!0},displayAgent:l?`cmd · ${l}`:"cmd",...l?{tokens:{model:l}}:{}})},"flushMetadata"),m=__name(e=>{e&&e!==i&&(i=e,o.reportSession(i))},"reportSessionOnce");t.hooks({onSessionStart:__name(({sessionId:e})=>{s=pN,a=null,i=null,l=null,c=null,o.announce(),m(e),u(),d()},"onSessionStart"),onSessionEnd:__name(()=>o.release(),"onSessionEnd")});for(const e of wN)t.on(e,e=>{isHostEvent(e)||(s=nextLifecycle(s,e),"run_start"===e.type&&m(e.sessionId),d())});t.on("session_titled",e=>{"session_titled"===e.type&&e.title!==c&&(c=e.title,u())}),t.on("model_request_start",e=>{"model_request_start"===e.type&&e.model!==l&&(l=e.model,u())})}}__name(isHostEvent,"isHostEvent"),__name(createHerdrMod,"createHerdrMod");var vN=createHerdrMod();function providerMod(e){return{name:`provider-${e.id}`,factory:__name(async t=>{try{const n=await loadBuiltinProviderModule({moduleId:e.id,install:!1});n&&t.addProvider(n)}catch(t){dlog("[ProviderPackages] builtin provider mod skipped",{pkg:e.package,error:t instanceof Error?t.message:String(t)})}},"factory")}}function providerBuiltinMods(){return UD.map(providerMod)}function updateNoticeMod(e){try{const t=readUpdatesConfig().pending;if(!t?.targetVersion)return;const n=getPackageJson(import.meta.url).version;if(t.targetVersion===n)return;e.ui.notify(`update available: v${t.targetVersion} (installing in the background — a restart applies it)`)}catch{}}function commandBuiltinMods(){return[...providerBuiltinMods(),{name:"update-notice",factory:updateNoticeMod},{name:"herdr",factory:vN}]}Vt(),PR(),__name(providerMod,"providerMod"),__name(providerBuiltinMods,"providerBuiltinMods"),Vt(),PR(),__name(updateNoticeMod,"updateNoticeMod"),__name(commandBuiltinMods,"commandBuiltinMods");var kN={user:"user settings",projectShared:"project settings",projectLocal:"project-local settings"};function conflictAction(e){const{name:t,file:n}=e;return"user"===n.scope?`To enable it at the user level, run: ${getBinaryCommand()} mods enable ${t} -g`:"projectShared"===n.scope?`To enable it at the project level, run: ${getBinaryCommand()} mods enable ${t}`:`Remove "${t}" from "mods.disabled" in that file, then run this again.`}function toggleReport(e){const{name:t,enabled:n,global:r,includeProject:o,settingsPath:s,disabledIn:a}=e,[i]=a;if(n&&i)return{conflict:!0,headline:`${t} is still disabled`,detail:`Your ${kN[i.scope]} (${i.path}) disable it.`,action:conflictAction({name:t,file:i})};const l=`${n?"Enabled":"Disabled"} ${t} at the ${r?"user":"project"} level`;return r||o?{conflict:!1,headline:l,detail:`Saved to ${s} · applies from your next session (or /reload)`}:{conflict:!1,headline:l,detail:`Saved to ${s} · applies once you start Command Code in this project`,action:`To ${n?"enable":"disable"} at user level: ${getBinaryCommand()} mods ${n?"enable":"disable"} ${t} -g`}}function notBuiltinHint(e){const{name:t,enabled:n}=e;if(n&&!commandBuiltinMods().some(e=>e.name===t))return`${t} is not a built-in mod, so this only lifts a disable — it does not install anything (${getBinaryCommand()} mods add does)`}async function toggleAction(e){const{name:t,enabled:n,options:r}=e,o=createNodeRuntime();try{const e=await setModEnabledInSettings({runtime:o,scope:r.global?"user":"projectShared",name:t,enabled:n}),s=await createModPathShortener(o),a=await isCommandProjectSessionInitialized(),i=await modDisabledSettingsFiles({runtime:o,includeProject:!0,name:t}),l=toggleReport({name:t,enabled:n,global:!0===r.global,includeProject:a,settingsPath:s(e),disabledIn:i.map(e=>({...e,path:s(e.path)}))});if(l.conflict)return console.error(`${Pt.yellow(ft.warning)} ${l.headline}`),console.error(Pt.dim(` ${l.detail}`)),l.action&&console.error(Pt.dim(` ${l.action}`)),void(process.exitCode=1);console.log(`${Pt.green(ft.tick)} ${l.headline}`),console.log(Pt.dim(` ${l.detail}`));const c=notBuiltinHint({name:t,enabled:n});c&&console.log(Pt.dim(` ${c}`)),l.action&&console.log(Pt.dim(` ${l.action}`))}catch(e){console.error(`${Pt.red(ft.cross)} ${uN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}__name(conflictAction,"conflictAction"),__name(toggleReport,"toggleReport"),__name(notBuiltinHint,"notBuiltinHint"),__name(toggleAction,"toggleAction");var CN=new He("enable").description("Switch a mod on by name — how opt-in built-ins are turned on").argument("<name>","mod name (e.g. update-notice)").option("-g, --global","write user scope instead of project").action((e,t)=>toggleAction({name:e,enabled:!0,options:t})),bN=new He("disable").description("Switch a mod off by name without uninstalling it").argument("<name>","mod name from `mods list` (or a built-in)").option("-g, --global","write user scope instead of project").action((e,t)=>toggleAction({name:e,enabled:!1,options:t}));function builtinState(e){const{builtin:t,disabled:n,enabled:r}=e;return n.has(t.name)?"disabled":!1!==t.defaultEnabled||r.has(t.name)?"enabled":`off by default · \`${getBinaryCommand()} mods enable ${t.name}\``}Vt(),PR(),__name(builtinState,"builtinState");var EN=__name((e,t,n)=>` ${Pt.cyan(e)} ${Pt.dim(`· ${t} · ${n}`)}`,"formatModLine"),TN=__name((e,t)=>`${Pt.bold(Pt.white(e))} ${Pt.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=new Set(r.enabled),l=await modsDirectoryPath({runtime:t,scope:"project"}),c=await modsDirectoryPath({runtime:t,scope:"user"}),d=l?s(l,"..",".."):void 0,u=["project","user","package","path"].flatMap(e=>r.entries.filter(t=>t.source===e));console.log(""),console.log(`${Pt.bold(Pt.white("Mods"))} ${Pt.dim(`(${r.entries.length})`)}`),0===r.entries.length&&(console.log(""),console.log(Pt.dim(" No mods loaded. Looking in:")),l&&console.log(Pt.dim(` ${shortenModPath(l,d)} ${Pt.white("(project)")}`)),c&&console.log(Pt.dim(` ${shortenModPath(c,void 0)} ${Pt.white("(user)")}`)),console.log(""),console.log(Pt.dim(` Drop a .ts file in one (\`${getBinaryCommand()} mods open --user\`) or install a package: \`${getBinaryCommand()} mods add <source>\`.`)));for(const e of u)console.log(EN(e.name,scopeFor({entry:e,sources:o}),detailFor({entry:e,sources:o,projectRoot:d,disabled:a})));if(!0===e.builtin){const e=commandBuiltinMods();console.log(""),console.log(TN("Built-in",e.length));for(const t of e)console.log(EN(t.name,"builtin",builtinState({builtin:t,disabled:a,enabled:i})))}const m=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(TN("Package sources",t.length));for(const e of t){m.add(e.source);const t=e.installed?Pt.yellow("installed, but provides no mods"):Pt.yellow(`not installed — run \`${getBinaryCommand()} mods update\``);console.log(EN(e.identity,e.scope,t))}}}const p=r.warnings.filter(e=>!m.has(e.path));if(p.length>0){console.log(""),console.log(`${Pt.bold(Pt.yellow("Warnings"))} ${Pt.dim(`(${p.length})`)}`);for(const e of p)console.log(` ${Pt.cyan(shortenModPath(e.path,d))} ${Pt.dim(`· ${e.reason}`)}`)}console.log("")}__name(scopeFor,"scopeFor"),__name(detailFor,"detailFor"),__name(listAction,"listAction");var PN=new He("list").alias("ls").description("List the mods a session loads, and where each one comes from").addOption(new Ge("--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 xt(o);const a=await createModPathShortener(t);console.log(`${Pt.green(ft.tick)} Opened ${Pt.cyan(a(o))} ${Pt.dim(`· ${s}`)}`)}catch(e){console.error(`${Pt.red(ft.cross)} ${uN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}Vt(),PR(),__name(openAction,"openAction");var MN=new He("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(`${Pt.red(ft.cross)} ${Pt.cyan(e)} is a built-in mod — it cannot be removed. Add it to ${Pt.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(`${Pt.yellow(ft.warning)} ${Pt.cyan(o.target)} is not configured (${o.scope} scope) — nothing to remove`);const s=await createModPathShortener(n);console.log(`${Pt.green(ft.tick)} Removed ${Pt.cyan(o.target)} ${Pt.dim(`· ${o.scope}`)}`),o.sourceIdentity&&o.sourceIdentity!==o.target&&console.log(Pt.dim(` Removed its source ${o.sourceIdentity}`)),o.alsoRemoved&&o.alsoRemoved.length>0&&console.log(Pt.dim(` That source also provided ${o.alsoRemoved.join(", ")}`)),o.removedPath&&console.log(Pt.dim(` Deleted ${s(o.removedPath)}`)),o.removedFromSettings&&o.settingsPath&&console.log(Pt.dim(` Updated ${s(o.settingsPath)}`))}catch(e){console.error(`${Pt.red(ft.cross)} ${uN(e instanceof Error?e.message:String(e))}`),process.exit(1)}}Vt(),PR(),__name(removeAction,"removeAction");var xN=new He("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(`${Pt.green(ft.tick)} ${Pt.cyan(e)}`);for(const e of t.failures)console.error(`${Pt.red(ft.cross)} ${e.source} ${Pt.dim(`· ${e.reason}`)}`);0===t.updated.length&&0===t.failures.length&&console.log(Pt.dim("No mod package sources configured.")),t.failures.length>0&&process.exit(1)}Vt(),PR(),__name(updateAction,"updateAction");var IN=new He("update").alias("up").description("Reinstall and reconcile every configured mod package").action(updateAction),AN=new He("mods").description("Manage mods — loadable extensions from npm, git, or local paths").addCommand(mN).addCommand(xN).addCommand(PN).addCommand(IN).addCommand(MN).addCommand(CN).addCommand(bN);function resolveBundledRipgrepPath(){try{const e=Ct(import.meta.url),{rgPath:t}=e("@vscode/ripgrep");if("string"==typeof t&&t.length>0&&A(t))return t}catch{}}function registerBundledRipgrep(){if(process.env[pc])return;const e=resolveBundledRipgrepPath();void 0!==e&&(process.env[pc]=e)}Vt(),PR(),__name(resolveBundledRipgrepPath,"resolveBundledRipgrepPath"),__name(registerBundledRipgrep,"registerBundledRipgrep"),Vt(),PR(),Vt();var RN=["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!!RN.some(e=>r.includes(`write ${e}`))||"write"===("string"==typeof t.syscall?t.syscall:"")&&RN.includes(n)}__name(asErrnoLike,"asErrnoLike"),__name(isBenignStreamWriteError,"isBenignStreamWriteError"),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt();var LN={enabled:!1,requestedSessionId:null,baseBranch:null,connection:null};function enableSandboxMode(e){LN.enabled=!0,LN.requestedSessionId=e.sessionId??null,LN.baseBranch=e.baseBranch??null}function getRequestedSandboxBase(){return LN.baseBranch}function isSandboxMode(){return LN.enabled}function getRequestedSandboxSessionId(){return LN.requestedSessionId}function setSandboxConnection(e){LN.connection=e}function getSandboxConnection(){return LN.connection}__name(enableSandboxMode,"enableSandboxMode"),__name(getRequestedSandboxBase,"getRequestedSandboxBase"),__name(isSandboxMode,"isSandboxMode"),__name(getRequestedSandboxSessionId,"getRequestedSandboxSessionId"),__name(setSandboxConnection,"setSandboxConnection"),__name(getSandboxConnection,"getSandboxConnection");var ON="Running the task in the sandbox",DN=null;function setAdoptedTurn(e){DN=e}function hasAdoptedTurn(){return null!==DN}function takeAdoptedTurn(){const e=DN;return DN=null,e}__name(setAdoptedTurn,"setAdoptedTurn"),__name(hasAdoptedTurn,"hasAdoptedTurn"),__name(takeAdoptedTurn,"takeAdoptedTurn");var $N=!1;function interruptSandboxTurn(e){$N=!0,e.request({method:"turn/interrupt"}).catch(()=>{})}function takeInterruptWanted(){const e=$N;return $N=!1,e}__name(interruptSandboxTurn,"interruptSandboxTurn"),__name(takeInterruptWanted,"takeInterruptWanted");var NN=!1;function setSandboxConnecting(e){NN=e}function isSandboxConnecting(){return NN}__name(setSandboxConnecting,"setSandboxConnecting"),__name(isSandboxConnecting,"isSandboxConnecting");var _N=null;function openSandboxConnectionOnce(e){return _N||(_N=e()),_N}__name(openSandboxConnectionOnce,"openSandboxConnectionOnce");var FN=new Set(["rewind","tree","fork","clone","share","compact","mcp","plan","mode","worktree","rename","resume","goal","pr-comments","reload","clear","loop","rc","init","import","memory","learn-taste","add-dir","connect","sessions","name","unshare","session-file","context","todos","trace"]);function sandboxBashMessage(){return LN.enabled?"! commands are not supported in a sandbox session yet.":null}function sandboxGateMessage(e){return LN.enabled&&FN.has(e)?`/${e} is not supported in a sandbox session yet.`:null}function sandboxModelFor(e){if(e)return byokProviderId({model:e})?void 0:e}function sandboxEffortFor(e){if(!e||!sandboxModelFor(e))return;const t=getReasoningEffort(e);return t&&(customReasoningEfforts(e)??getSupportedEfforts(e)??[]).includes(String(t))?String(t):void 0}async function tellSandboxEffort(e){const t=getSandboxConnection();if(!t||void 0===e.effort)return{ok:!0};const n=(await t.request({method:"session/set_effort",params:{effort:e.effort}}).catch(e=>({error:{message:String(e)}}))).error;return n?{ok:!1,message:sandboxRefusal({failure:n,command:"/effort",what:"effort"})}:{ok:!0}}function sandboxRefusal(e){const{failure:t,command:n,what:r}=e;return t.code===PT.TURN_ACTIVE?`The sandbox is working on a turn; run ${n} again once it has finished.`:`The sandbox kept its ${r}: ${(t.message??"the change was refused").replace(/^Error: /,"").replace(/\.$/,"")}.`}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=I$(e.sessionId),a=s?s.getEffort():r,i=await tellSandboxEffort({effort:t});return i.ok?(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,hh(`Reasoning effort set to ${t}.`)])):void e.setFeed(e=>[...e,hh(i.message)])}if(r.length>0)return void e.setFeed(e=>[...e,hh(`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,hh(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=dt(!1);return pt(async e=>{const o=processBracketedPaste(e),s=n??t,a=__name(async()=>{r.current=!1;const e=await detectClipboardTextNative();e?s(e):o.cleanedContent&&s(o.cleanedContent)},"applyPastedText");if(!o.isPasteStart||r.current)r.current&&!o.isPasteEnd||(r.current&&o.isPasteEnd?await 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(sandboxBashMessage,"sandboxBashMessage"),__name(sandboxGateMessage,"sandboxGateMessage"),__name(sandboxModelFor,"sandboxModelFor"),__name(sandboxEffortFor,"sandboxEffortFor"),__name(tellSandboxEffort,"tellSandboxEffort"),__name(sandboxRefusal,"sandboxRefusal"),__name(handleEffortCommand,"handleEffortCommand"),__name(applyEffortSetting,"applyEffortSetting"),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt(),PR(),__name(usePasteAwareChange,"usePasteAwareChange"),__name(extractDeviceCode2,"extractDeviceCode");var UN=__name(({providerId:e,onSuccess:t,onCancel:n,onFailure:r})=>{const o=getProviderDisplayName(e),[s,a]=ct("confirm"),[i,l]=ct(""),[c,d]=ct(""),[u,m]=ct(""),[p,g]=ct(""),[h,f]=ct(null),y=dt(!1),S=dt(!0),w=dt(!1),v=dt(null),k=dt(null),C=dt(null),b=dt(!1);ut(()=>()=>{S.current=!1,v.current&&clearTimeout(v.current),C.current=null},[]);const E=pt(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;xt(e.authUrl,t).catch(()=>{S.current&&f(`Failed to open browser. Please manually open: ${e.authUrl}`)})},300))},[]),T=pt(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===fo.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"),xt(t.url).catch(()=>{S.current&&f(`Failed to open browser. Please manually open: ${t.url}`)}),e({})}})},[e,E]),P=dt(()=>{});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=pt(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(ot((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===fo.COPILOT?"This will get a GitHub sign-in code.":`This will open your browser to sign in with ${o}.`;return it.createElement(RO,{title:`Sign in to ${o}`,subtitle:t,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"y"),"/",it.createElement(CO,null,"enter")," ","continue"),it.createElement(it.Fragment,null,it.createElement(CO,null,"n"),"/",it.createElement(CO,null,"esc")," ","cancel")]})})}return"connecting"===s?it.createElement(RO,{title:`Sign in to ${o}`,subtitle:"Getting sign-in code…",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," cancel")]})}):"paste"===s?it.createElement(RO,{title:`Sign in to ${o}`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," submit"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," cancel")]})},i&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},"Login: "),it.createElement(yL,{url:i,text:"Open auth page ↗",color:LR.CYAN})),c&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},c)),h&&it.createElement(Ze,{marginBottom:1},it.createElement(U$,null,h)),it.createElement(Ze,null,it.createElement(et,null,u||"Authorization code",": "),it.createElement(TextInput,{mask:"*",focus:!0,value:p,onChange:x,onSubmit:I,placeholder:"Paste code here..."}))):"open-browser"===s?it.createElement(RO,{title:`Sign in to ${o}`,subtitle:e===fo.COPILOT?"Press enter to open GitHub and paste the code there":"Press enter to open your browser",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," cancel")]})},c&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0,color:LR.GREEN},c)),i&&e!==fo.COPILOT&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},"Login: "),it.createElement(yL,{url:i,text:"Open auth page ↗",color:LR.CYAN}))):"waiting"===s?it.createElement(RO,{title:`Sign in to ${o}`,subtitle:"Waiting for authorization…",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," cancel")]})},c&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0,color:LR.GREEN},c)),i&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},"Open: "),it.createElement(yL,{url:i,text:"Open auth page ↗",color:LR.CYAN}))):"error"===s?it.createElement(RO,{title:`Sign in to ${o}`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," back")]})},it.createElement(U$,null,h)):null},"ProviderAuth");function makeProviderAuthComponent(e){const t=__name(({onSuccess:t,onCancel:n})=>it.createElement(UN,{providerId:e,onSuccess:t,onCancel:n}),"Bound");return t.displayName=`ProviderAuth(${e})`,t}__name(makeProviderAuthComponent,"makeProviderAuthComponent");var jN=Object.fromEntries(Object.entries(rs).map(([e,t])=>[e,{...t}]));function getProviderConfig(e){return jN[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=getSandboxConnection(),S=null!==y&&void 0!==sandboxModelFor(e),w=null!==y&&null!==await getProviderAuthState(g);if(y&&S&&!w){const t=(await y.request({method:"session/set_model",params:{model:e}}).catch(e=>({error:{message:String(e)}}))).error;if(t)return u?.(e=>[...e,hh(sandboxRefusal({failure:t,command:"/model",what:"model"}))]),void o(!1)}const v=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"===v.status)return s(v.message),void o(!1);if(d&&g&&g!==f&&await rebuildHarnessSession(d),r(e),v.modelChanged&&(hardResetForResize(),c(e=>e+1)),o(!1),s(v.statusMessage),v.modelChanged&&p?.(getModelNotice(e)??null),y&&!S)u?.(t=>[...t,hh(`${e} is a custom model this machine serves; the sandbox keeps its current model.`)]);else if(y){const t=await tellSandboxEffort({effort:sandboxEffortFor(e)});t.ok||u?.(e=>[...e,hh(t.message)])}if(v.modelChanged){const t=await reconcileCommandModelSelection({modelId:e,...void 0!==h?{routeProvider:h}:{},modelName:v.modelName,previousModel:v.previousModel,harness:d?I$(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,hh(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,hh(`Unknown model "${n}" — opening the model picker so you can choose.`)]),void e.setShowModelSelector(!0);r.warning&&e.setFeed(e=>[...e,hh(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&&(UL(),hardResetForResize(),r(e=>e+1)),n(buildThemeStatusMessage(e))}catch{n(Io)}}function handleThemeCancel({setShowThemeSelector:e}){e(!1)}async function handleThemeCommand(e,t){const n=t.trim().toLowerCase();n?uo.includes(n)?await handleThemeSelect({theme:n,setShowThemeSelector:e.setShowThemeSelector,setStatus:e.setStatus,setStaticKey:e.setStaticKey}):e.setFeed(e=>[...e,hh(`Unknown theme "${n}". Options: ${uo.join(", ")}.`)]):e.setShowThemeSelector(!0)}async function applyThemeSetting(e){const t=e.trim().toLowerCase();return t?uo.includes(t)?(await setCliTheme({theme:t}),{ok:!0,message:`Theme set to ${t}.`}):{ok:!1,message:`Unknown theme "${e.trim()}". Options: ${uo.join(", ")}.`}:{ok:!1,message:"Provide a theme, e.g. --theme auto."}}jN.anthropic&&(jN.anthropic.authComponent=makeProviderAuthComponent(fo.ANTHROPIC),jN.anthropic.checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:fo.ANTHROPIC});return!!e}),jN["github-copilot"]&&(jN["github-copilot"].authComponent=makeProviderAuthComponent(fo.COPILOT),jN["github-copilot"].checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:fo.COPILOT});return!!e}),jN.codex&&(jN.codex.authComponent=makeProviderAuthComponent(fo.CODEX),jN.codex.checkAuth=async()=>{const{token:e}=await providerAuthHeaders({provider:fo.CODEX});return!!e}),__name(getProviderConfig,"getProviderConfig"),__name(getProviderAuthState,"getProviderAuthState"),__name(handleModelSelect,"handleModelSelect"),__name(handleModelCancel,"handleModelCancel"),__name(handleModelCommand,"handleModelCommand"),__name(applyModelSetting,"applyModelSetting"),Vt(),PR(),__name(handleThemeSelect,"handleThemeSelect"),__name(handleThemeCancel,"handleThemeCancel"),__name(handleThemeCommand,"handleThemeCommand"),__name(applyThemeSetting,"applyThemeSetting");var BN=[{key:"model",apply:__name(e=>applyModelSetting(e),"apply")},{key:"effort",valueHint:"level",description:"Set reasoning effort for the session (e.g. low, medium, high) — depends on the model",apply:__name((e,t)=>applyEffortSetting(e,t),"apply")},{key:"theme",valueHint:"theme",description:"Set the color theme (dark or light)",apply:__name(e=>applyThemeSetting(e),"apply")}],WN=__name(e=>`--${e.key} <${e.valueHint}>`,"flagSpecOf"),HN=BN.filter(e=>void 0!==e.valueHint&&void 0!==e.description);async function applyConfigSetting(e){const t=e.indexOf("=");if(t<1)return{ok:!1,message:"Use --config key=value, e.g. --config theme=dark."};const n=e.slice(0,t).trim().toLowerCase(),r=e.slice(t+1).trim(),o=BN.find(e=>e.key===n);if(o)return o.apply(r);const s="true"===r||"false"!==r&&r;try{return await updateConfigSetting({id:n,value:s}),{ok:!0,message:`Set ${n} = ${r}.`}}catch(e){return{ok:!1,message:e instanceof Error?e.message:`Could not set config "${n}".`}}}__name(applyConfigSetting,"applyConfigSetting"),Vt(),PR();var GN=["default","standard","plan","accept-edits","auto-accept","yolo","bypass","dont-ask"];function parsePermissionModeOption(e){const t=GN.includes(e)?normalizePermissionMode(e):void 0;if(!t)throw new Ve(`Allowed choices are ${GN.join(", ")}.`);return t}__name(parsePermissionModeOption,"parsePermissionModeOption");var VN=getPackageJson(import.meta.url),zN=__name((e,t=[])=>[...t,e],"collectAddDir"),KN=__name((e,t=[])=>[...t,e],"collectConfig");function displayCustomHelp(){const e=VN.version,t=getInvokedCommandName(),n=getVisibleSlashCommands();console.log(),console.log(yt.bold("Command Code")+yt.gray(` v${e}`)),console.log(yt.gray(va)),console.log(),console.log(yt.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(yt.bold("Options"));for(const e of Pa){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(ka)+yt.gray(e.description))}console.log(),console.log(yt.bold("Commands"));for(const e of xa){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(ka)+yt.gray(e.description))}console.log(),console.log(yt.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(ka)+yt.gray(e.description));console.log(),console.log(yt.bold("Keyboard Shortcuts"));for(const e of Ta)console.log(" "+e.key.padEnd(ka)+yt.gray(e.description));console.log(),console.log(yt.bold("Examples"));for(const e of Aa){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(ka)+yt.gray(e.description))}console.log(),console.log(yt.cyan("❯")+" "+yt.gray(Ca.replace(/cmd/,t))),console.log(),console.log(yt.bold("Links"));for(const e of Ia)console.log(" "+e.key.padEnd(ka)+yt.cyan(e.description));console.log()}function createProgram(){const e=new He;e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(VN.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 Ge("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Ge("--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 Ge("--accept-edits","Start in accept edits mode").implies({permissionMode:"auto-accept"})).addOption(new Ge("--auto-accept").implies({permissionMode:"auto-accept"}).hideHelp()).addOption(new Ge("--permission-mode <mode>","Set permission mode").choices(GN).argParser(parsePermissionModeOption)).option("--skip-onboarding","Skip taste onboarding (for non-interactive/automated runs)").option("-p, --print [query]","Run in non-interactive mode, output response and exit").option("--max-turns <number>",`Max agentic turns (model API round trips): print mode limit (default ${Sa}); interactive mode sets the /goal turn budget (default 100)`,e=>{const t=parseInt(e,10);if(isNaN(t)||t<1)throw new Ve("--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",zN,[]).addOption(new Ge("--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",ba).option("--no-auto-update","Disable automatic background updates for this run").option("--add-dir <directory>","Add directory to workspace context",zN,[]).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)",zN,[]).option("--mod-option <name=value>","Set a mod-declared flag value (repeatable)",zN,[]).option("--skill <path>","Load extra skills from a path (a skill directory or a directory of skills); repeatable",zN,[]).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 Ge("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Ge("--experimental","Enable experimental features").hideHelp()).addOption(new Ge("-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 Ge("--local","Use local server").hideHelp()).addOption(new Ge("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption();for(const t of HN)e.option(WN(t),t.description);return e.option("--config <key=value>","Set a setting headlessly, e.g. --config theme=dark (repeatable)",KN),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram");var qN=new Map([["--rpc",null],["--sandbox","optional"],["--base","required"]]);function firstOperand(e){const{tokens:t,valueFlags:n}=e;for(let e=0;e<t.length;e++){const r=t[e]??"";if(!r.startsWith("-")||"-"===r)return r;if(r.includes("="))continue;const o=n.get(r),s=t[e+1];("required"===o||"optional"===o&&void 0!==s&&!s.startsWith("-"))&&e++}return null}function wantsExperimentalRootFlags(e){if(!isExperimentalEnabled())return!1;const t=e.argv.indexOf("--"),n=(-1===t?e.argv:e.argv.slice(0,t)).slice(2);if(!n.includes("--experimental"))return!1;const r=firstOperand({tokens:n,valueFlags:new Map([...e.valueFlags,...qN])});return null===r||!e.subcommands.has(r)}function valueKind(e){return e.required?"required":e.optional?"optional":null}function rootValueFlags(e){const t=new Map;for(const n of e.options){const e=valueKind(n);n.long&&t.set(n.long,e),n.short&&t.set(n.short,e)}return t}function addExperimentalRootOptions(e){const t=new Set(e.commands.flatMap(e=>[e.name(),...e.aliases()]));wantsExperimentalRootFlags({argv:process.argv,subcommands:t,valueFlags:rootValueFlags(e)})&&e.option("--rpc","Experimental: serve one session as newline-delimited JSON-RPC on stdin/stdout").option("--sandbox [sessionIdOrMessage]","Experimental: run the agent in a cloud sandbox. A session id reopens that session; anything else is the first message. With -p: start the task (or send a follow-up to <id>) and print the session id").option("--base <branch>","With --sandbox: the branch a new session works from (default: the repo default branch)")}__name(firstOperand,"firstOperand"),__name(wantsExperimentalRootFlags,"wantsExperimentalRootFlags"),__name(valueKind,"valueKind"),__name(rootValueFlags,"rootValueFlags"),__name(addExperimentalRootOptions,"addExperimentalRootOptions");var YN=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!==YN&&(recordError({span:YN,error:sanitizeErrorForTelemetry({error:e,label:"command_error"})}),YN.end(),YN=null)}function abandonPendingCommandSpan(){null!==YN&&(YN.setAttribute("cmd.command.outcome","abandoned"),YN.end(),YN=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);YN=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!==YN&&(endSpan({span:YN,status:"success"}),YN=null)})}__name(commandPath,"commandPath"),__name(flagNames,"flagNames"),__name(failPendingCommandSpan,"failPendingCommandSpan"),__name(abandonPendingCommandSpan,"abandonPendingCommandSpan"),__name(setupCommanderHooks,"setupCommanderHooks");var{red:QN,yellow:JN,dim:XN}=yt;function printErrorDetails(e,t){if(console.log(`${At.error} ${QN(t)}`),console.log(`${At.error} ${QN("ERROR →")} ${e.name}`),console.log(`${At.info} ${QN("REASON →")} ${e.message}`),console.log(`${At.info} ${QN("ERROR STACK ↓ \n")} ${e.stack}\n`),!isTelemetryInitialized())return;const n=getDisplayTraceId();console.log(`${At.info} ${XN(`Trace ID: ${n}`)}`),console.log(`${XN(" Share this ID with support to help debug your issue.")}\n`)}__name(printErrorDetails,"printErrorDetails");var ZN=__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(`${At.warning} ${JN(t)}\n`),r&&printErrorDetails(n,t),!o)return!1;process.exit(0)}},"handleError");Vt(),PR();var e_,t_,n_=[],r_=[];function setModPathsOverride(e){n_=e}function setModOptionsOverride(e){r_=e}function loadCommandModHost(e={}){return e_||(e_=buildHost(e))}async function buildHost(e){try{const t=createNodeRuntime(),n=createModHost({runtime:t}),r=!1!==e.projectMods&&await isCommandProjectSessionInitialized();await loadMods({runtime:t,host:n,includeProject:r,extraPaths:n_,builtins:commandBuiltinMods()});for(const e of r_){const t=e.indexOf("=");t<=0?dlog(`[mods] ignoring malformed --mod-option "${e}"`):n.setFlagValue({name:e.slice(0,t),value:e.slice(t+1)})}for(const e of n.warnings())dlog(`[mods] ${e.path}: ${e.reason}`);return setActiveModHost(n),setRegisteredProviderModules({modules:n.providerModules()}),n}catch(e){return void dlog(`[mods] host construction failed: ${e instanceof Error?e.message:String(e)}`)}}function disposeCommandModHost(){return t_??=e_?runModHostTeardown({host:e_}):Promise.resolve(),t_}function exitAfterModHostTeardown(e){disposeCommandModHost().finally(()=>{process.exit(e)})}async function runModHostTeardown(e){const t=__name(async()=>{const t=await e.host;t&&(t.dispose(),await t.settle())},"teardown");try{await Promise.race([t(),new Promise(t=>{const n=setTimeout(t,e.graceMs??300);n.unref?.()})])}catch(e){dlog(`[mods] teardown failed: ${e instanceof Error?e.message:String(e)}`)}}function handleStdoutError(e){if(!isBenignStreamWriteError(e))throw e;exitAfterModHostTeardown(0)}function handleStderrError(e){if(!isBenignStreamWriteError(e))throw e}function handleUnhandledErrors(){process.stdout.on("error",handleStdoutError),process.stderr.on("error",handleStderrError),process.on("unhandledRejection",e=>{const t=e instanceof Error?e:new Error(String(e));trackError({error:sanitizeErrorForTelemetry({error:t,label:"unhandled_rejection"}),context:{component:qo.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),ZN({heading:Mt`CRITICAL: Unhandled Promise Rejection!
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:qo.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),ZN({heading:Mt`CRITICAL: Uncaught Exception!
16
+ This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:e,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})})}__name(setModPathsOverride,"setModPathsOverride"),__name(setModOptionsOverride,"setModOptionsOverride"),__name(loadCommandModHost,"loadCommandModHost"),__name(buildHost,"buildHost"),__name(disposeCommandModHost,"disposeCommandModHost"),__name(exitAfterModHostTeardown,"exitAfterModHostTeardown"),__name(runModHostTeardown,"runModHostTeardown"),__name(handleStdoutError,"handleStdoutError"),__name(handleStderrError,"handleStderrError"),__name(handleUnhandledErrors,"handleUnhandledErrors"),Vt(),PR(),Vt(),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt();var o_=ft.pointer,s_=__name(({isSelected:e,backgroundColor:t})=>it.createElement(et,{color:e?MO:IO,backgroundColor:t,bold:e&&isLightTheme()},e?o_:" "),"OverlayCaret"),a_=__name(({isSelected:e,isActive:t,idleColor:n=xO,backgroundColor:r,children:o})=>it.createElement(et,{color:e?MO:t?AO:n,backgroundColor:r,bold:e&&isLightTheme()},o),"OverlayOptionText"),i_=__name(({isSelected:e,label:t})=>it.createElement(a_,{isSelected:e}," ",t),"OverlayOptionItem"),l_=__name(({backgroundColor:e})=>it.createElement(et,{color:AO,backgroundColor:e}," ",ft.tick),"OverlayActiveTick"),c_=__name(({indent:e=4,children:t})=>it.createElement(et,{color:TO}," ".repeat(e),t),"OverlayOptionDescription"),d_=__name(({isSelected:e,idleColor:t=LR.GRAY,selectedColor:n=LR.WHITE,bold:r,children:o})=>it.createElement(et,{color:e?n:t,backgroundColor:e?tL:void 0,bold:r??e},o),"OverlayBarText"),u_=__name(({isSelected:e,label:t})=>it.createElement(d_,{isSelected:e}," ",t," "),"OverlayBarItem"),m_=__name(()=>null,"OverlayBarIndicator");Vt();var p_=createOSC8Link("https://commandcode.ai/docs/permissions#permission-modes","Docs ↗",!1),g_=__name(({hint:e})=>it.createElement(et,{italic:!0,color:LR.DIM},e," · Run ",it.createElement(et,{color:LR.WHITE},"cmd --yolo")," to bypass all permissions (",p_,")"),"PermissionFooter"),h_=__name(({request:e,onResponse:t})=>{const[n]=ct(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 it.createElement(RO,{title:"Tool Permission",subtitle:it.createElement(et,{wrap:"wrap"},"Command Code needs to run ",it.createElement(et,{color:MO},e.toolName),"."),footer:it.createElement(g_,{hint:"↑/↓ navigate · enter select"})},e.risk&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0,color:LR.RED,wrap:"wrap"},ft.warning," ",getRiskDisplay(e.risk))),e.description&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM,italic:!0},e.description)),it.createElement(SelectInput,{items:r.map((e,t)=>({label:`${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:n,indicatorComponent:s_,itemComponent:i_}))},"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?TL:PL).join("\n")}Vt(),PR(),Vt(),PR(),Vt(),__name(buildTreeConnectors,"buildTreeConnectors");var f_=Tt()?"⟳":"*",y_=" │ ";function DiffWordSegments({segments:e,type:t,paired:n,dimDiff:r,language:o,highlightOptions:s}){const a="removed"===t?_R.REMOVED_HIGHLIGHT_BG:_R.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(it.createElement(et,{key:u,backgroundColor:a,dimColor:r},d)):n?i.push(it.createElement(et,{key:u,color:LR.WHITE,dimColor:r},d)):i.push(it.createElement(et,{key:u,color:"removed"===t?_R.REMOVED_TEXT:_R.ADDED_TEXT,dimColor:r},d))}return i}function DiffRow({background:e,prefix:t,wrap:n="wrap",children:r}){return it.createElement(Ze,{width:"100%",backgroundColor:e},it.createElement(Ze,{flexShrink:0},t),it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{wrap:n},r)))}function renderDiffLine({line:e,dimDiff:t,language:n,highlightOptions:r}){if("skip"===e.kind)return it.createElement(Ze,{key:e.key,width:"100%"},it.createElement(et,{color:_R.LINE_NUM,dimColor:t},e.spacer,y_,e.label));if("context"===e.kind)return it.createElement(DiffRow,{key:e.key,prefix:it.createElement(et,{color:_R.LINE_NUM,dimColor:t}," "+e.lineNumberLabel+y_)},it.createElement(et,{color:LR.WHITE,dimColor:t}," ",highlightSyntax(e.text,n,r)));const o="removed"===e.kind,s=o?_R.REMOVED_TEXT:_R.ADDED_TEXT,a=o?_R.REMOVED_BG:_R.ADDED_BG;return it.createElement(DiffRow,{key:e.key,background:a,prefix:it.createElement(et,null,it.createElement(et,{color:s,dimColor:t}," "+e.lineNumberLabel),it.createElement(et,{color:_R.LINE_NUM,dimColor:t},y_),it.createElement(et,{color:s,dimColor:t},o?"- ":"+ "))},it.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?it.createElement(et,{color:LR.RED},"Rejected update to",it.createElement(et,{color:LR.RED},` ${e.filePath}`)):it.createElement(et,{color:LR.GRAY},"Updated"," ",it.createElement(et,{color:LR.WHITE,bold:!0},e.filePath)," ","with"," ",e.additions>0&&it.createElement(it.Fragment,null,it.createElement(et,{color:BR.SUCCESS},e.additions)," ","addition",1!==e.additions?"s":"",e.removals>0?" and ":""),e.removals>0&&it.createElement(it.Fragment,null,it.createElement(et,{color:BR.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:it.createElement(Ze,{flexDirection:"column"},it.createElement(DiffMetadata,{metadata:c.metadata}),it.createElement(Ze,{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:BR.SUCCESS,strikethrough:!0}:"in_progress"===e?{textColor:BR.IN_PROGRESS,strikethrough:!1}:{textColor:LR.WHITE,strikethrough:!1}}function TodoChecklist({todos:e}){return it.createElement(Ze,{flexDirection:"column"},e.map((e,t)=>{const n="completed"===e.status?ft.checkboxOn:ft.checkboxOff,{textColor:r,strikethrough:o}=resolveTodoTextStyle(e.status),s="in_progress"===e.status&&e.activeForm?`${e.activeForm}…`:e.content;return it.createElement(Ze,{key:e.id||t,flexDirection:"row"},it.createElement(Ze,{width:2},it.createElement(et,{color:r},n)),it.createElement(et,{color:r,bold:"in_progress"===e.status,strikethrough:o},s))}))}function formatTodosForDisplay(e){const t=jh(e);return t?it.createElement(TodoChecklist,{todos:t}):it.createElement(et,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 it.createElement(BracketWrap,null,t?e:it.createElement(Markdown,null,e))}function ReadToolInlineSummaryRow({summary:e}){return e?.dimText?it.createElement(et,{dimColor:!0}," ",e.dimText):null}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:o}){if(e)return{symbolColor:LR.YELLOW,symbol:ft.arrowRight};if(t)return{symbolColor:LR.RED,symbol:ft.square};if(n)return{symbolColor:$R,symbol:"✻"};if(r&&o){const e=jh(o),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?BR.SUCCESS:BR.WARNING,symbol:ft.square}}return{symbolColor:FR.BG,symbol:ft.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 it.createElement(it.Fragment,null,it.createElement(et,{color:$R},`Thought for ${e} second${1!==e?"s":""}`," "),!s&&it.createElement(BracketWrap,{color:LR.DIM},`${a}+o to expand`))}if(t)return it.createElement(it.Fragment,null,it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:DR.BADGE_BG,color:DR.BADGE_FG,bold:!0},xL)),it.createElement(et,null," ","Using your taste"," ",n?"package of ":"packages",n&&it.createElement(et,{bold:!0},n)));let c=r;return"READ[n]"===r&&o&&(c=`READ[${Number(o[1])}]`),it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:FR.BG,color:FR.FG,bold:!0},`${ML}${c}${ML}`))}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?it.createElement(et,{color:LR.GRAY},"Running (",s,")"):"background"===e?it.createElement(et,{color:LR.GRAY},"Running in background"):"interrupted"===e||n===oS?it.createElement(et,{color:LR.GRAY,wrap:"wrap"},"Interrupted"):"error"===e||t?it.createElement(et,{color:LR.RED,wrap:"wrap"},n," (",s,")"):it.createElement(it.Fragment,null,it.createElement(et,{wrap:"wrap"},"Done"),it.createElement(et,{color:LR.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?Bd:Ud,maxChars:"Question"===t?1/0:Kd}),l=a&&"Question"!==t;return{text:s,isTruncated:l,remainingLines:i,truncationMsg:l?i>0?it.createElement(BracketedText,{text:`... +${i} lines [${r}+o to expand]`,color:LR.DIM}):it.createElement(BracketedText,{text:`... [${r}+o to expand]`,color:LR.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?it.createElement(it.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:Wd,{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-Wd;return it.createElement(Ze,{flexDirection:"column"},i,l&&it.createElement(Ze,{marginTop:1},it.createElement(BracketedText,{text:`… (${d} more ${1===d?"line":"lines"}) [${s}+o to expand]`,color:LR.DIM})),r&&o&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.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?it.createElement(et,{color:LR.GRAY},"Created"," ",it.createElement(et,{color:LR.WHITE,bold:!0},a.filePath)," ","(empty file)"):it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.GRAY},"Created"," ",it.createElement(et,{color:LR.WHITE,bold:!0},a.filePath)," ","(",a.totalLinesLabel,")"),it.createElement(Ze,{marginTop:1,flexDirection:"column"},a.visibleLines.map(e=>it.createElement(DiffRow,{key:e.lineNumber,background:_R.ADDED_BG,wrap:"truncate-end",prefix:it.createElement(et,null,it.createElement(et,{color:_R.ADDED_TEXT}," "+e.lineNumberLabel),it.createElement(et,{color:_R.LINE_NUM},y_))},it.createElement(et,{color:_R.ADDED_TEXT},highlightSyntax(e.text,o,s))))),a.isTruncated&&a.moreLinesLabel&&it.createElement(Ze,{marginTop:1},it.createElement(BracketedText,{text:a.expandHint?`… (${a.moreLinesLabel}) ${a.expandHint}`:`… (${a.moreLinesLabel})`,color:LR.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 it.createElement(Ze,{width:"100%",flexDirection:"column"},it.createElement(et,null," "),it.createElement(et,{color:$R,wrap:"wrap",italic:!0},e))}const g=p?TL:PL;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?it.createElement(Ze,{columnGap:1},it.createElement(et,{color:eL},g," "),e):e}if(r&&o&&"content"in o){const e=renderWriteFileContent({input:l,metadata:o,expandedOutput:a,expandKey:u});return m?it.createElement(Ze,{columnGap:1},it.createElement(et,{color:eL},g," "),e):e}return m?renderTextWithLongConnector({output:s,name:d,expandedOutput:a,expandKey:u,hasError:c,closesFrame:p}):it.createElement(Ze,{width:"100%"},it.createElement(et,{color:c?LR.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?LR.RED:void 0,d=buildTreeConnectors(a,{isTruncated:i,closesFrame:s}),u=s?TL:PL;return it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(Ze,{columnGap:1,width:"100%"},it.createElement(et,{color:eL},d),it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:c,wrap:"wrap"},a))),i&&it.createElement(Ze,{columnGap:1},it.createElement(et,{color:eL},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}),L=s?.preHookLines,O=s?.postHookLines,D=Boolean(L?.length),$=Boolean(O?.length),N=Boolean(s?.hookOutcome),_=r&&!y&&!N,F=!N&&!_,U=I&&!$&&!N&&!_,j=D&&!I&&!$&&!N&&!_;return it.createElement(Ze,null,i&&it.createElement(et,{color:A},R),it.createElement(Ze,{flexDirection:"column",marginLeft:i?1:0},it.createElement(Ze,null,it.createElement(ToolHeader,{isThinking:i,isTasteFile:m,tasteCategory:p,name:M,summaryMatch:T,expandedOutput:a,expandKey:f,input:t,output:n}),w&&it.createElement(et,null," ",formatToolInput({input:S,isShell:"SHELL"===e})),it.createElement(ReadToolInlineSummaryRow,{summary:P}),E>0&&it.createElement(et,{dimColor:!0},` ${f_}${E>1?` ${E}`:""}`)),y&&("running"===v||"background"===v||"done"===v||"error"===v||n)&&it.createElement(Ze,{columnGap:1,marginLeft:h?1:0},h&&it.createElement(et,{color:eL},TL," "),it.createElement(AgentStatus,{agentStatus:v,hasError:o,output:n,elapsedSeconds:C,tokensUsed:k})),it.createElement(HookLines,{lines:L,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}),it.createElement(HookLines,{lines:O,showTreeConnector:h,closesFrame:F}),it.createElement(HookOutcome,{outcome:s?.hookOutcome,showTreeConnector:h}),_&&it.createElement(Ze,{columnGap:1,marginLeft:1},it.createElement(et,{color:eL},TL," "),it.createElement(et,{color:LR.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 it.createElement(Ze,{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 it.createElement(Ze,{flexDirection:"column",marginLeft:t?1:0},e.map((e,t)=>{const o=n&&t===r?TL:PL;return it.createElement(Ze,{key:t,columnGap:1},it.createElement(et,{color:eL},o),it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},e)))}))}function HookOutcome({outcome:e,showTreeConnector:t}){if(!e)return null;const n="stop"===e.kind?LR.YELLOW:LR.RED;return it.createElement(Ze,{columnGap:1,marginLeft:t?1:0},it.createElement(et,{color:eL},TL),it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{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 S_=createNodeRuntime(),w_=__name(({label:e,isSelected:t})=>e.includes("[shift+tab]")?it.createElement(it.Fragment,null,e.split("[shift+tab]")[0],it.createElement(BracketWrap,{color:t?MO:xO,bold:!0},"shift+tab")):e.includes("(")?it.createElement(it.Fragment,null,e.split("(")[0],it.createElement(et,{color:LR.GRAY},"(",e.split("(")[1])):e,"ChoiceLabel"),v_=__name(({request:e,onResponse:t,onEnableAutoAccept:n})=>{const[r]=ct(0),[o,s]=ct(1);ut(()=>{"edit"===e.action&&e.oldContent&&e.filePath&&resolveEditStartLine({runtime:S_,filePath:e.filePath,oldContent:e.oldContent}).then(e=>{void 0!==e&&s(e)}).catch(()=>{})},[e.filePath,e.oldContent,e.action]);const a=getPermissionChoicesForRisk({choices:fM,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 it.createElement(RO,{title:`${d()}${"edit"===e.action?` ${c}`:""}`,footer:it.createElement(g_,{hint:"↑/↓ navigate · enter select"})},"edit"===e.action&&e.oldContent&&e.newContent&&it.createElement(Ze,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c,marginLeft:0,startLine:o}).diffContent),e.risk&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0,color:LR.RED,wrap:"wrap"},ft.warning," ",getRiskDisplay(e.risk))),it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0},"Do you want to ",l()," ",it.createElement(et,{color:MO},c),"?")),it.createElement(SelectInput,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:i,initialIndex:r,indicatorComponent:s_,itemComponent:({label:e,isSelected:t})=>it.createElement(a_,{isSelected:t},it.createElement(w_,{label:e,isSelected:t}))}))},"PermissionPrompt");Vt(),PR();var k_=BE?"ctrl+y":"ctrl+e",C_=__name(({request:e,onResponse:t})=>{const[n]=ct(0),[r,o]=ct({phase:"idle"}),s=e.description??("done"===r.phase?r.explanation:void 0),a=void 0!==e.explain&&void 0===e.description&&"done"!==r.phase;ot((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 it.createElement(RO,{title:"Execute Shell Command",subtitle:it.createElement(et,{wrap:"wrap"},"Command Code needs to execute ",it.createElement(et,{color:MO},getCommandDisplay(e)),"."),footer:it.createElement(g_,{hint:a?`↑/↓ navigate · enter select · ${k_} explain`:"↑/↓ navigate · enter select"})},e.risk&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0,color:LR.RED,wrap:"wrap"},ft.warning," ",getRiskDisplay(e.risk))),e.workingDirectory&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.GRAY},"Working directory: ",e.workingDirectory)),s&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM,italic:!0},s)),a&&"idle"===r.phase&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM,italic:!0},"Press"," ",it.createElement(BracketWrap,{color:LR.DIM,bold:!0},k_)," ","to explain this command")),"loading"===r.phase&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM,italic:!0},it.createElement(bt,{type:"dots"})," Explaining this command…")),"failed"===r.phase&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM,italic:!0},"Couldn't generate an explanation — press"," ",k_," to retry")),it.createElement(SelectInput,{items:i.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:n,indicatorComponent:s_,itemComponent:({label:e,isSelected:t})=>it.createElement(a_,{isSelected:t},e.includes("[shift+tab]")?it.createElement(it.Fragment,null,e.split("[shift+tab]")[0],it.createElement(BracketWrap,{color:t?MO:xO,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 accept edits")):o(l)}__name(handlePermissionResponse,"handlePermissionResponse");var b_=lt(__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 it.createElement(Ze,{marginY:1},it.createElement(C_,{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 it.createElement(Ze,{marginY:1},it.createElement(C_,{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 it.createElement(Ze,{marginY:1},it.createElement(h_,{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 it.createElement(Ze,{marginY:1},it.createElement(v_,{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}=nt(),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 it.createElement(RO,{title:"Plan",titleSuffix:n?` · ${t.basename(n)}`:void 0,gapAfterHeader:!1,hint:a?r?"ctrl+o to collapse":c:void 0},it.createElement(Ze,{marginTop:1},it.createElement(Markdown,null,i)))}__name(isGenericToolRequest,"isGenericToolRequest"),__name(isFileEditRequest,"isFileEditRequest"),Vt(),PR(),Vt(),PR(),__name(PlanPanel,"PlanPanel"),Vt(),PR();var E_=__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 it.createElement(Ze,{flexDirection:"column",marginTop:1,paddingLeft:4},it.createElement(et,{italic:!0,color:LR.DIM},"Preview"),it.createElement(et,{color:LR.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 it.createElement(et,{key:t},it.createElement(et,{color:LR.DIM},"│ "),it.createElement(et,{color:LR.GRAY},n),it.createElement(et,{color:LR.DIM},`${r} │`))}),r>0?it.createElement(et,{color:LR.YELLOW},`├${s}${a}┤`):null,it.createElement(et,{color:LR.DIM},`└${o}┘`))},"OptionPreview"),T_=[{label:"1. Submit",value:"submit"},{label:"2. Cancel",value:"cancel"}],P_=__name(({checked:e})=>e?it.createElement(et,{color:LR.GREEN},"[",ft.tick,"] "):it.createElement(et,{color:LR.DIM},"[ ] "),"MultiSelectCheckbox"),M_=__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"),x_=__name((e,t)=>{const n=new Set(e);return n.has(t)?(n.delete(t),n):(n.add(t),n)},"toggleLabel"),I_=__name((e,t)=>e?{indicator:ft.bullet,color:MO}:t?{indicator:ft.tick,color:LR.GREEN}:{indicator:ft.circle,color:LR.GRAY},"getTabMarker"),A_=__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}=I_(i,l);s.push(it.createElement(et,{key:a},it.createElement(et,{color:d},c),it.createElement(et,{color:i?MO:void 0}," ",o.header),a<e.length-1?it.createElement(et,{color:LR.DIM}," | "):null))}),!o){const e=r;s.push(it.createElement(et,{key:"review"},it.createElement(et,{color:LR.DIM}," | "),it.createElement(et,{color:e?MO:LR.GRAY},e?ft.bullet:ft.circle),it.createElement(et,{color:e?MO:void 0,bold:e}," ","Review")))}return it.createElement(Ze,null,s)},"TabIndicator"),R_=__name(({questions:e,onResponse:t,hideCustomInput:n=!1,compact:r=!1})=>{const[o,s]=ct(0),[a,i]=ct(new Map),l=dt(null);null===l.current&&(l.current=new Map);const c=l.current,[d,u]=ct(""),[m,p]=ct(new Set),[g,h]=ct(null),[f,y]=ct(!1),[S,w]=ct(!1),[v,k]=ct(!1),[C,b]=ct(null),[E,T]=ct(!1),P=dt(null);null===P.current&&(P.current=new Map);const M=dt(null);null===M.current&&(M.current=new Map);const[x,I]=ct(!1),[A,R]=ct(""),[,L]=ct(0),O=e[o],D=O?.multiSelect??!1,$=a.get(o),N=O?[...O.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description,...void 0!==e.preview?{preview:e.preview}:{}}))]:[],_=N.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),F=new Map(_.map((e,t)=>[e.label,N[t]])),U=__name((e,t)=>{t.size>0?c.set(e,Array.from(t)):c.delete(e)},"saveOrClearMultiAnswer"),j=__name(t=>{const n=e[t],r=c.get(t);if(n?.multiSelect&&r){p(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));return void u(e||"")}if(p(new Set),!n?.multiSelect&&1===r?.length){const e=r[0],t=!n?.options.some(t=>t.label===e);return void u(t&&e?e:"")}u("")},"restoreInputsForQuestion"),B=__name(e=>{"submit"!==e.value?"cancel"===e.value&&t({answers:[]}):q()},"handleReviewSelect"),W=__name(()=>{if(!$||0===$.length)return 0;const e=$[0],t=O.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),H=__name(e=>{if(f)return;if(D){const t=M_(e.value,O.options.length-1);if(null===t)return;const n=O.options[t]?.label||"";return void p(e=>x_(e,n))}const t=M_(e.value,O.options.length-1);if(null===t)return;y(!0);const n=O.options[t]?.label||"";z([n])},"handleSelect"),G=__name(()=>{if(f)return;y(!0);const e=Array.from(m);z(e)},"handleMultiSelectDone"),V=__name(()=>{if(f)return;const e=d.trim();if(e){if(D){const t=new Set(O.options.map(e=>e.label));return void p(n=>{const r=new Set;return n.forEach(e=>{t.has(e)&&r.add(e)}),r.add(e),r})}y(!0),z([e])}},"handleOtherSubmit"),z=__name(t=>{c.set(o,t);const r=new Map(c);if(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"),Q=__name(()=>{P.current&&(A.trim()?P.current.set(o,A):P.current.delete(o)),I(!1)},"saveNotesAndClose"),J=__name(async()=>{try{const e=await detectClipboardImage();if(!e)return;const t=M.current?.get(o)??[];M.current?.set(o,[...t,{data:e.data,mediaType:e.mediaType}]),L(e=>e+1)}catch{}},"pasteClipboardImageIntoQuestion"),X=__name(async(e,t)=>{try{const n=await openInEditor(e);n!==e&&t(n)}catch{}},"editExternally"),Z=__name(e=>{w(!1),s(e),T(!1),k(!1),b(null),j(e)},"editQuestion"),ee=__name(t=>{t<0||t>=e.length||(D&&(U(o,m),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=M_(g.value,O.options.length-1);if(null===e)return;const t=O.options[e]?.label||"";p(e=>x_(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(ot((e,t)=>{const r="v"===e&&(t.ctrl||t.meta&&"darwin"!==process.platform);if(x)t.escape?Q():r?J():t.ctrl&&"g"===e&&X(A,R);else if(r&&v)J();else if(t.ctrl&&"g"===e&&v)X(d,u);else{if(" "===e&&D&&!v&&te(),"d"!==e||!D||v||S||G(),!(v||S||f||n)){if("n"===e)return R(P.current?.get(o)??""),void I(!0);if("c"===e)return void Y()}S||f||ne(t),re(t),t.escape&&oe()}}),!O&&!S)return null;if(S)return it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(iL,{dividerColor:PO}),it.createElement(Ze,{marginBottom:1},it.createElement(A_,{questions:e,currentIndex:e.length,answeredQuestions:new Set(a.keys()),isReviewPage:!0})),e.some((e,t)=>!a.get(t)?.length)&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.YELLOW},"⚠ You have not answered all questions")),e.map((e,t)=>it.createElement(Ze,{key:t,marginBottom:1,flexDirection:"column"},it.createElement(et,{color:LR.DIM},t+1,". ",e.question),it.createElement(et,{color:LR.GREEN}," ",a.get(t)?.join(", ")||"No answer"))),it.createElement(SelectInput,{items:T_,onSelect:B,initialIndex:0,indicatorComponent:s_,itemComponent:i_}),it.createElement(Ze,{marginTop:1},it.createElement(et,{italic:!0,color:LR.DIM},ft.arrowLeft," to go back and edit")));const se=r&&1===e.length;return it.createElement(Ze,{flexDirection:"column",width:"100%"},!se&&it.createElement(iL,{dividerColor:PO}),!se&&it.createElement(Ze,{marginBottom:1},it.createElement(A_,{questions:e,currentIndex:o,answeredQuestions:new Set(a.keys()),isReviewPage:!1,hideReview:n})),it.createElement(Ze,{marginBottom:1},it.createElement(et,{bold:!0,color:EO},O.question)),v||E||x?it.createElement(Ze,{flexDirection:"column"},_.map((e,t)=>{const n=F.get(e.label),r=D&&n&&m.has(n.label),o=!D&&n&&$?.includes(n.label),s=r||o;return it.createElement(Ze,{key:e.value,flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,null," "),it.createElement(a_,{isActive:s,idleColor:LR.GRAY}," ",t+1,"."," "),D&&it.createElement(P_,{checked:s}),it.createElement(a_,{isActive:s,idleColor:LR.GRAY},n?.label||""),!D&&s&&it.createElement(l_,null)),n?.description&&it.createElement(Ze,null,it.createElement(et,null," "),it.createElement(c_,{indent:D?7:4},n.description)))})):it.createElement(SelectInput,{key:`${o}-${C??"default"}`,items:_,initialIndex:C??W(),onSelect:H,onHighlight:h,indicatorComponent:s_,itemComponent:({label:e,isSelected:t})=>{const n=F.get(e),r=D&&n&&m.has(n.label),o=!D&&n&&$?.includes(n.label),s=r||o,a=e.match(/^\s*(\d+)\.\s*(.*)$/),i=a?.[1]||"",l=a?.[2]||e;return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(a_,{isSelected:t,isActive:s}," ",i,"."," "),D&&it.createElement(P_,{checked:s}),it.createElement(a_,{isSelected:t,isActive:s},l),!D&&s&&it.createElement(l_,null)),n?.description&&it.createElement(c_,{indent:D?7:4},n.description))}}),!v&&!E&&(()=>{const e=(g?F.get(g.label):void 0)??N[C??W()];return e?.preview?it.createElement(E_,{preview:e.preview}):null})(),!n&&it.createElement(Ze,null,it.createElement(s_,{isSelected:v}),it.createElement(a_,{isSelected:v}," ",_.length+1,"."," "),D&&it.createElement(P_,{checked:m.has(d.trim())}),it.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?it.createElement(Ze,null,it.createElement(s_,{isSelected:!0}),it.createElement(a_,{isSelected:!0}," ","notes:"," "),it.createElement(TextInput,{value:A,onChange:R,onSubmit:Q,placeholder:"Add notes on this design…",focus:x,stripBracketedPaste:!0})):(()=>{const e=P.current?.get(o)?.trim();return e?it.createElement(Ze,null,it.createElement(et,{italic:!0,color:LR.DIM}," ","notes: ",e)):null})(),(M.current?.get(o)??[]).map((e,t)=>it.createElement(Ze,{key:t},it.createElement(et,{color:LR.DIM}," ","[Image #",t+1," attached —"," ",e.mediaType,"]"))),D&&it.createElement(Ze,null,it.createElement(s_,{isSelected:E}),it.createElement(a_,{isSelected:E}," ",o===e.length-1?"Submit":"Next")),e.length>1&&it.createElement(Ze,{marginTop:1},it.createElement(et,{italic:!0,color:LR.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]=ct(!1),l=e.params.planContent;return ot((e,t)=>{l&&getIsExpandToolShortcut(t,e)&&i(e=>!e)}),it.createElement(Ze,{marginY:1,flexDirection:"column"},l&&it.createElement(Ze,{marginBottom:1},it.createElement(PlanPanel,{content:l,filePath:e.params.planFilePath,expanded:a})),it.createElement(R_,{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"),Vt(),PR();var L_="__skip__",O_=__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:L_,isPrimary:!1}],l=new Map(i.map(e=>[e.label,e]));ot((e,t)=>{t.escape&&n()});const c=__name(e=>{e.value!==L_?(t(e.value),n()):n()},"handleSelect");return it.createElement(RO,{title:`/design ${r} complete`,titleSuffix:` · ${a}`,hint:"Enter to run · Esc to dismiss"},it.createElement(SelectInput,{items:i,onSelect:c,indicatorComponent:m_,itemComponent:({label:e,isSelected:t})=>{const n=l.get(e),r=n?.value===L_,o=n?.isPrimary??!1,s=r?"run /design manually":wy[e]??"";return it.createElement(Ze,{flexDirection:"column"},it.createElement(d_,{isSelected:t,idleColor:o?LR.WHITE:LR.DIM},r?" skip ":` /design ${e} `),s&&it.createElement(d_,{isSelected:t,idleColor:LR.DIM,bold:!1},` ${s} `))}}))},"DesignModeSelector");function getUsageToneColor(e){return"danger"===e?LR.RED:"warning"===e?LR.YELLOW:LR.GREEN}function getDistanceToneColor(e){return"danger"===e?LR.RED:"warning"===e?LR.YELLOW:LR.GRAY}function ContextProgress({view:e,progressBarWidth:t}){const n=getUsageToneColor(e.tone),r=buildBlockBar({percentage:e.percentage,width:t});return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{marginBottom:1},it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:LR.BLUE,color:"#f4f4f4",bold:!0},`${ML}CONTEXT${ML}`)),it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:LR.GRAY},e.modelLabel)),it.createElement(Ze,null,it.createElement(et,{color:n},r.filled),it.createElement(et,{color:HR},r.empty),it.createElement(et,{bold:!0,color:n},` ${e.percentageLabel}`)),it.createElement(Ze,null,it.createElement(et,null,e.tokensUsedLabel),it.createElement(et,{color:LR.GRAY},` / ${e.tokenLimitLabel}`),it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:n},e.tokensRemainingLabel),it.createElement(et,{color:LR.GRAY}," remaining"),e.isEstimated&&it.createElement(et,{color:LR.DIM}," (estimated)")))}function CompactionDistance({view:e}){if(!e)return null;const t=getDistanceToneColor(e.tone);return it.createElement(Ze,{marginTop:1},it.createElement(et,{color:t},e.tokensAwayLabel),it.createElement(et,{color:LR.DIM},e.label))}function BreakdownRow({item:e,labelWidth:t}){return it.createElement(Ze,null,it.createElement(et,null,e.name.padEnd(t)),it.createElement(et,{bold:!0},e.paddedValue),it.createElement(et,{color:LR.GRAY}," tokens"),e.detail&&it.createElement(et,{color:LR.DIM},` · ${e.detail}`))}function ContextBreakdown({view:e,labelWidth:t}){return 0===e.rows.length?null:it.createElement(Ze,{flexDirection:"column",marginTop:1},e.rows.map(e=>it.createElement(BreakdownRow,{key:e.name,item:e,labelWidth:t})))}function ContextTips({tips:e}){return 0===e.length?null:it.createElement(Ze,{flexDirection:"column",marginTop:1},e.map(e=>it.createElement(Ze,{key:e},it.createElement(et,{color:LR.CYAN},ft.pointer),it.createElement(et,{color:LR.GRAY}," ",e))))}function ContextMessage({analysis:e}){const t=projectContextView(e,{terminalWidth:useTerminalWidth(),modelDisplayName:getModelDisplayName(e.model)});return it.createElement(Ze,{flexDirection:"column",paddingTop:1},it.createElement(ContextProgress,{view:t.progress,progressBarWidth:t.layout.progressBarWidth}),it.createElement(CompactionDistance,{view:t.compactionDistance}),it.createElement(ContextBreakdown,{view:t.breakdown,labelWidth:t.layout.labelWidth}),it.createElement(ContextTips,{tips:t.tips}))}function ContextConfigView({staticKey:e,sessionId:t,onClose:n,setInput:r}){const[o,s]=ct(null),[a,i]=ct(null);return ut(()=>{let e=!0;return __name(async()=>{const n=I$(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]),ot((e,t)=>{t.escape&&(r(""),n())}),it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(ContextBody,{error:a,analysis:o}),it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Press ",it.createElement(CO,null,"Esc")," to return to conversation"))))}function ContextBody({error:e,analysis:t}){return e?it.createElement(RO,{title:"Context",gapAfterHeader:!1},it.createElement(et,{color:LR.DIM},e)):t?it.createElement(ContextMessage,{analysis:t}):it.createElement(RO,{title:"Context",gapAfterHeader:!1},it.createElement(F$,{label:"Loading context analysis"}))}Vt(),PR(),Vt(),PR(),__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"),Vt(),Vt(),PR(),Vt(),PR();var D_="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?I$(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 $_=__name(({label:e,value:t,valueColor:n,dimValue:r})=>it.createElement(Ze,null,it.createElement(et,{dimColor:!0},`${e}:`.padEnd(14)),r?it.createElement(et,{dimColor:!0},t):it.createElement(et,{color:n},t)),"Row");function StatusMessage({statusData:e}){const t=projectStatusView(e,{profileBaseUrl:"https://commandcode.ai"}),n=t.account.authenticated?ft.tick:ft.cross,r=t.account.authenticated?LR.WHITE:BR.ERROR;return it.createElement(Ze,{flexDirection:"column",paddingX:0},it.createElement(Ze,null,it.createElement(et,{color:OR,bold:!0},"Command Code"," "),it.createElement(et,{dimColor:!0},t.versionText)),it.createElement(Ze,null,it.createElement(et,{dimColor:!0},"Visit "),it.createElement(yL,{url:D_,text:D_,color:LR.CYAN}),it.createElement(et,{dimColor:!0}," for usage and billing")),it.createElement(Ze,{marginTop:1},it.createElement(et,{dimColor:!0},"Account:".padEnd(14)),t.account.username&&t.account.profileUrl?it.createElement(it.Fragment,null,it.createElement(yL,{url:t.account.profileUrl,text:t.account.label,color:LR.CYAN}),it.createElement(et,{color:r}," ",n)):t.account.authenticated?it.createElement(it.Fragment,null,it.createElement(et,null,t.account.label),it.createElement(et,{color:r}," ",n)):it.createElement(it.Fragment,null,it.createElement(et,{color:BR.WARNING},t.account.label),it.createElement(et,{color:r}," ",n),it.createElement(et,{dimColor:!0}," — run "),it.createElement(et,{bold:!0},t.account.loginHint))),it.createElement($_,{label:"Model",value:t.model.value}),it.createElement($_,{label:"Branch",value:t.branch.value,dimValue:t.branch.dim}),t.worktree?it.createElement($_,{label:"Worktree",value:t.worktree.value}):null,t.repository?it.createElement(Ze,null,it.createElement(et,{dimColor:!0},"Repository:".padEnd(14)),it.createElement(yL,{url:t.repository.url,text:t.repository.text,color:LR.CYAN}),t.pullRequest?it.createElement(it.Fragment,null,it.createElement(et,{dimColor:!0}," · "),it.createElement(yL,{url:t.pullRequest.url,text:t.pullRequest.text,color:t.pullRequest.open?LR.CYAN:LR.GRAY}),it.createElement(et,{dimColor:!0}," ","(",t.pullRequest.stateLabel,")")):null):t.pullRequest?it.createElement(Ze,null,it.createElement(et,{dimColor:!0},"Pull Request:".padEnd(14)),it.createElement(yL,{url:t.pullRequest.url,text:t.pullRequest.text,color:t.pullRequest.open?LR.CYAN:LR.GRAY}),it.createElement(et,{dimColor:!0}," (",t.pullRequest.stateLabel,")")):null,it.createElement($_,{label:"Taste",value:t.taste.value,dimValue:t.taste.dim}),it.createElement($_,{label:"Directory",value:t.directory.value}),it.createElement($_,{label:"Skills",value:t.skills.value,dimValue:t.skills.dim}),it.createElement($_,{label:"Agents",value:t.agents.value,dimValue:t.agents.dim}),it.createElement($_,{label:"System",value:t.system.value}),t.proxy?it.createElement($_,{label:"Proxy",value:t.proxy.value}):null)}function StatusBody({state:e}){return"ready"===e.phase?it.createElement(StatusMessage,{statusData:e.data}):"error"===e.phase?it.createElement(et,{dimColor:!0},"Could not load status: ",e.message):it.createElement(et,{dimColor:!0},"Gathering status…")}function StatusConfigView({staticKey:e,sessionId:t,onClose:n,setInput:r}){const[o,s]=ct({phase:"loading"});return ut(()=>{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]),ot((e,t)=>{t.escape&&(r(""),n())}),it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(StatusBody,{state:o}),it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Press ",it.createElement(CO,null,"Esc")," to return to conversation"))))}__name(StatusMessage,"StatusMessage"),__name(StatusBody,"StatusBody"),__name(StatusConfigView,"StatusConfigView"),Vt(),PR(),PR(),Vt(),PR();var{addDirectory:N_,formatDirectoryForDisplay:__,getAdditionalDirectories:F_,removeAdditionalDirectory:U_}=Vy,j_=__name(({onClose:e})=>{const[t,n]=ct(""),[r,o]=ct(null),[s,a]=ct([]),[i,l]=ct(()=>F_()),[c,d]=ct(()=>({zone:"input",suggestionIndex:0,activeDirIndex:0})),[u,m]=ct(0);ut(()=>{a(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),m(0)},[t]),ut(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const p=__name(e=>{const t=N_(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(F_()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),g=__name(e=>{if(!U_(e))return o({tone:"error",text:`${__(e)} is no longer in workspace scope`}),void l(F_());o({tone:"success",text:`Removed ${__(e)} from directory scope`}),l(F_()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");ot((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}))}}}),ut(()=>{"suggestions"===c.zone&&m(e=>getAdjustedSuggestionOffset({selectedIndex:c.suggestionIndex,currentOffset:e,maxVisible:hR,totalSuggestions:s.length}))},[c,s.length]),ut(()=>{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+hR),f=getAddDirFooterText({focusZone:c.zone});return it.createElement(RO,{title:"Add directory to workspace",subtitle:it.createElement(et,{color:LR.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),footer:it.createElement(et,{italic:!0,color:LR.DIM},it.createElement(BracketedText,{text:f,color:LR.DIM})),gapAfterHeader:!1},it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(et,{color:LR.GRAY},"Added directories"),0===i.length?it.createElement(et,{color:LR.GRAY}," None yet"):i.map((e,t)=>{const n="active-dir"===c.zone&&c.activeDirIndex===t;return it.createElement(Ze,{key:e},it.createElement(et,null," "),it.createElement(s_,{isSelected:n}),it.createElement(a_,{isSelected:n,isActive:!0}," ",__(e)))})),it.createElement(Ze,{marginTop:1},it.createElement(et,{bold:!0,color:LR.WHITE},"Path")),it.createElement(Ze,null,it.createElement(TextInput,{value:t,focus:"input"===c.zone,prefix:`${"input"===c.zone?ft.pointer:" "} `,prefixColor:"input"===c.zone?MO:LR.GRAY,onChange:e=>{n(e),o(null)},onSubmit:p})),!t&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:{error:LR.RED,warning:LR.YELLOW,success:LR.GREEN}[r.tone]},r.text)),s.length>0&&it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.GRAY},"Suggestions"),h.map((e,t)=>{const n=u+t,r="suggestions"===c.zone&&c.suggestionIndex===n;return it.createElement(Ze,{key:e},it.createElement(et,null," "),it.createElement(s_,{isSelected:r}),it.createElement(a_,{isSelected:r,idleColor:LR.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")}}Vt(),Vt(),PR(),Vt(),PR(),Vt(),PR(),Vt(),Vt(),PR(),Vt(),PR(),__name(createBillingTransport,"createBillingTransport");var B_=null;function getBilling(){return B_||(B_=createBilling({transport:createBillingTransport()})),B_}function getCachedBillingContext(){return B_?.getCached()??null}function getBillingContext(){return getBilling().get()}function prefetchBillingContext(){getBilling().prefetch()}function invalidateBillingContext(){B_=null}function buildLaneModelPickerGroups(){const e=filterModelGroupsByRegisteredModules(_D).filter(e=>e.providerId!==fo.COMMAND);return[...buildModelPickerGroups({normalModeGroups:FD}),...e,...buildCustomModelPickerGroups()]}function buildCatalogModelPickerGroups(){return[...buildModelPickerGroups({normalModeGroups:FD}),...buildCustomModelPickerGroups()]}function laneServesModel(e){if(e.activeLane===fo.COMMAND)return!0;const t=ns[e.activeLane]?.supportedModelProviders;if(!t)return!0;const n=Object.values(fD).find(t=>t.id===e.modelId);return!n||laneSupportsModel(t,n)}function laneModelCount(e){return e.laneId===fo.COMMAND?FD.reduce((e,t)=>e+t.models.length,0):_D.find(t=>t.providerId===e.laneId)?.models.length??0}function defaultModelForLane(e){const t=filterModelGroupsByRegisteredModules(_D),n=t.filter(t=>t.providerId===e.activeLane),r=n.length>0?n:t.filter(e=>e.providerId===fo.COMMAND);return r[0]?.models[0]?.id}async function resolveProviderAuth(e){const t=await Promise.all([...new Set(e)].map(async e=>{const t=getProviderConfig(e);if(!t?.requiresAuth)return null;if(!t.checkAuth)return{providerId:e,authed:!0};try{return{providerId:e,authed:await t.checkAuth()}}catch{return{providerId:e,authed:!1}}})),n=new Set,r=new Set;for(const e of t)e&&(n.add(e.providerId),e.authed||r.add(e.providerId));return{authResolvedProviders:n,unauthedProviders:r}}function useCustomModelsReady(e){const[t,n]=ct(!1);return ut(()=>{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"),Vt(),PR(),__name(buildLaneModelPickerGroups,"buildLaneModelPickerGroups"),__name(buildCatalogModelPickerGroups,"buildCatalogModelPickerGroups"),__name(laneServesModel,"laneServesModel"),__name(laneModelCount,"laneModelCount"),__name(defaultModelForLane,"defaultModelForLane"),Vt(),__name(resolveProviderAuth,"resolveProviderAuth"),Vt(),__name(useCustomModelsReady,"useCustomModelsReady"),Vt(),PR();var W_=__name((e,t)=>{const n=t&&e.id===OD?" (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,W_(n,t)+2),32)}__name(getModelLabelColumnWidth,"getModelLabelColumnWidth");var H_=__name(({model:e,providerId:t,isHighlighted:n,isCurrent:r,showProviderLabel:o,showDefaultBadge:s=!0,labelColumnWidth:a=32})=>{const i=ns[t],l=o??i?.showProviderLabelInSelector??!1,c=e.vendorLabel??DD[e.provider],d=s&&e.id===OD,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?tL:void 0,f=e.description?`${l?`${c} · `:""}${e.description}`:"",y=useTerminalWidth()>=a+38&&f;return it.createElement(Ze,null,it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:h,color:r?LR.GREEN:LR.WHITE,bold:r},m),u&&it.createElement(et,{backgroundColor:h,color:LR.GREEN,bold:!0},p),y&&it.createElement(et,{backgroundColor:h},g)),y&&it.createElement(Ze,{flexShrink:1},it.createElement(et,{backgroundColor:h,color:LR.DIM,wrap:"truncate-end"},f)),it.createElement(et,{backgroundColor:h,color:LR.GREEN},r?` ${ft.tick} `:" "))},"ModelRow");Vt(),PR();var G_=__name((e,t)=>`${e+1}. ${t}`,"labelText"),V_=__name(({modelLabel:e,supportedEfforts:t,currentEffort:n,onSelect:r,onCancel:o})=>{const s=mt(()=>buildEffortPickerRows(t),[t]),a=mt(()=>{if(void 0===n)return 0;const e=s.findIndex(e=>e.value===n);return e>=0?e:0},[s,n]),i=mt(()=>Math.max(...s.map((e,t)=>G_(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 it.createElement(RO,{title:`Select reasoning effort for ${e}`,hint:"↑/↓ navigate · enter to select · esc to go back"},it.createElement(Ze,{flexDirection:"column"},s.map((e,t)=>{const r=t===l,o=e.value===n;return it.createElement(Ze,{key:e.label},it.createElement(et,{color:r||!o?LR.WHITE:LR.GREEN,backgroundColor:r?tL:void 0,bold:r||o},G_(t,e.label).padEnd(i)),it.createElement(et,{color:r?LR.WHITE:LR.DIM,backgroundColor:r?tL:void 0},e.description," "),o&&it.createElement(et,{color:LR.GREEN}," ",ft.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}]:[]})}Vt(),PR(),__name(windowModelGroups,"windowModelGroups");var z_=__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]=ct(""),[p,g]=ct(null),[h,f]=ct(()=>new Set),[y,S]=ct(()=>new Set),w=r??p??fo.COMMAND,v=useCustomModelsReady(d),k=mt(()=>buildLaneModelPickerGroups(),[v]),C=mt(()=>filterModelPickerGroupsByAuth({groups:k,authResolvedProviders:y,unauthedProviders:h}),[k,y,h]),b=mt(()=>filterModelPickerGroups(C,u),[C,u]),E=mt(()=>{const e=new Set(C.map(e=>`${e.providerId}:${e.label}`));return k.filter(t=>!e.has(`${t.providerId}:${t.label}`))},[k,C]),T=mt(()=>filterModelPickerGroups(E,u),[E,u]),P=mt(()=>flattenModelPickerGroups(b),[b]),M=mt(()=>{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=mt(()=>getModelLabelColumnWidth(k.flatMap(e=>e.models)),[k]),[I,A]=ct(0),R=useTerminalHeight()-1,L=Math.max(4,R-16-2*b.length),O=void 0!==o,D=mt(()=>O?null:getCachedBillingContext(),[O]),[$,N]=ct(D),[_,F]=ct(!O&&!D);ut(()=>{if(O)return;if($)return;let e=!0;return getBillingContext().then(t=>{e&&(N(t),F(!1))}),()=>{e=!1}},[O,$]);const U=!O&&!0===$?.fetchFailed,j=O?o:$?.planId??null,B=O?s:$?.purchasedCredits??0,W=O?a:$?.freeCredits??0,H=n?Math.max(0,P.findIndex(e=>e.model.id===n)):0,[G,V]=ct("model"),[z,K]=ct(null),{cursor:q,error:Y,setError:Q}=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")});ut(()=>{A(e=>clampScrollOffset({cursor:q,total:P.length,maxVisible:L,currentOffset:e}))},[q,P.length,L]);const J=dt(!1),X=__name(t=>{if(!z||J.current)return;J.current=!0;const{model:r,providerId:o}=z,s=getReasoningEffort(r.id),a=t!==s,l=r.id===n;(async()=>{try{if(a&&(await setReasoningEffort({modelId:r.id,effort:t}),l)){const e=await tellSandboxEffort({effort:t});e.ok||dlog(`[Model] ${e.message}`),i?.()}}catch(e){dlog(`[Model] Failed to persist reasoning effort: ${e}`)}finally{e(r.id,o)}})()},"handleEffortSelect"),Z=__name(()=>{J.current||(K(null),V("model"))},"handleEffortCancel");if(ut(()=>{if(_)return;if(Y!==QP)return;const e=P[q];Q(e&&!U?getModelPickerAccessError({model:e.model,providerId:e.providerId,billing:{planId:j,purchasedCredits:B,freeCredits:W}}):null)},[_,U,Y,Q,P,q,j,B,W]),ut(()=>{(async()=>{const e=await getConfiguredProvider();e&&e!==fo.COMMAND&&g(e)})()},[]),ut(()=>{let e=!0;return(async()=>{const t=await resolveProviderAuth(k.map(e=>e.providerId));e&&(S(t.authResolvedProviders),f(t.unauthedProviders))})(),()=>{e=!1}},[k]),"effort"===G&&z){const e=z.model.reasoningEfforts??getSupportedEfforts(z.model.id)??[];return it.createElement(V_,{modelLabel:z.model.label,supportedEfforts:e,currentEffort:getReasoningEffort(z.model.id),onSelect:X,onCancel:Z})}const ee=I,te=I+L,ne=windowModelGroups({groups:b,firstSectionBase:0,windowStart:ee,windowEnd:te}),re=P.length>L;return it.createElement(RO,{title:"Select model",subtitle:l??"Switch between the available models. Sets the default for new sessions; other open sessions are unaffected.",footer:it.createElement(et,{italic:!0,color:LR.DIM},"type to search · ↑/↓ navigate · shift+↑/↓ jump provider · enter to select",u?" · esc to clear":" · esc to cancel")},it.createElement(Ze,{marginBottom:2,flexDirection:"column",width:"100%"},it.createElement(kL,{query:u,resultCount:u?P.length:void 0,placeholder:"Type to search models..."})),0===P.length?it.createElement(Ze,{marginY:1},it.createElement(et,{color:LR.GRAY},T.length>0?"Provider login required. Run /connect to authenticate.":`No models match "${u}"`)):it.createElement(Ze,{flexDirection:"column"},ne.map(({group:e,groupWindow:t},r)=>it.createElement(Ze,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:r>0?1:0},it.createElement(et,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>it.createElement(H_,{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&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",ee+1,"–",Math.min(te,P.length)," of ",P.length,ee>0?" · ↑ more":"",te<P.length?" · ↓ more":"")),Y&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.GRAY},Y)))},"ModelSelector"),K_=__name(e=>{if(!e)return"Inherit from session";for(const t of FD)for(const n of t.models)if(n.id===e)return n.label;return e},"agentModelLabel"),q_=[{value:"inherit",label:"1. Inherit from session (default)"},{value:"pick",label:"2. Pick a specific model"}],Y_=__name(({selectedModel:e,onSelect:t})=>{const[n,r]=ct("choice"),[o,s]=ct(e?1:0);return ot((e,n)=>{if(n.upArrow)s(e=>Math.max(0,e-1));else if(n.downArrow)s(e=>Math.min(q_.length-1,e+1));else if("1"!==e)if("2"!==e){if(n.return){const e=q_[o];if(!e)return;"inherit"===e.value?t(null):r("picker")}}else r("picker");else t(null)},{isActive:"choice"===n}),"picker"===n?it.createElement(z_,{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}):it.createElement(Ze,{flexDirection:"column"},q_.map((e,t)=>{const n=t===o;return it.createElement(Ze,{key:e.value},it.createElement(et,{color:n?LR.WHITE:LR.GRAY,backgroundColor:n?tL:void 0,bold:n},n?">":" "," ",e.label))}),e&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.GRAY},"Currently pinned: ",K_(e))),it.createElement(bO,{hints:["↑↓ navigate","Enter to select","Inherit follows /model; pinned agents keep their own model and prompt cache"]}))},"AgentModelSelector"),Q_=__name(({config:e,onSaveComplete:t,viewOnly:n=!1})=>{const[r,o]=ct("idle"),[s,a]=ct(""),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:LS,model:e.model,reasoningEffort:e.reasoningEffort}),t(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");ot((e,t)=>{n||!t.return||"idle"!==r&&"error"!==r||i()});const l=formatAgentToolAccessForDisplay({access:[...e.selectedTools],allToolNames:LS,displayNameByToolName:$S,displayNameToToolName:NS}),c=e.location&&e.agentType?getAgentDisplayPath({location:e.location,name:e.agentType}):"";return it.createElement(Ze,{flexDirection:"column",gap:1},it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"Name:"),it.createElement(et,{color:LR.GRAY},e.agentType)),it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"Location:"),it.createElement(et,{color:LR.GRAY},c)),it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"Tools:"),it.createElement(et,{color:LR.GRAY},l)),it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"Model:"),it.createElement(et,{color:LR.GRAY},K_(e.model))),it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"Reasoning effort:"),it.createElement(et,{color:LR.GRAY},e.reasoningEffort??"model default"))),it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"Description"),it.createElement(et,{color:LR.GRAY},"(Tells ","Command Code"," when to use this agent):")),it.createElement(et,{color:LR.GRAY},e.ccToolDefinition),it.createElement(Ze,{gap:1},it.createElement(et,{color:LR.WHITE,bold:!0},"System Prompt:")),it.createElement(et,{color:LR.GRAY},e.sysPrompt),!n&&it.createElement(Ze,{marginTop:1},"idle"===r&&it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to save ·"," ",it.createElement(CO,null,"Esc")," to cancel"),"saving"===r&&it.createElement(et,{color:LR.YELLOW},"Saving agent…"),"saved"===r&&it.createElement(j$,null,s),"error"===r&&it.createElement(Ze,{flexDirection:"column"},it.createElement(U$,null,"Error: ",s),it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to retry"))))},"AgentSummary"),J_=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],X_=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=ct("menu"),a=new Set(resolveAgentToolSelection({access:e.tools,allToolNames:LS,displayNameToToolName:NS})),i={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:a,model:e.model??null,reasoningEffort:e.reasoningEffort??null},l=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],c=__name(e=>{"back"!==e.value?"view"!==e.value?"edit"!==e.value?"delete"===e.value&&s("delete"):s("edit"):s("view"):t()},"handleMenuSelect"),d=__name(async r=>{if("confirm-delete"===r.value)try{await deleteAgentDefinition({runtime:createNodeRuntime(),filePath:e.filePath}),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return ot((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=J_[r];e&&d(e)}}),"view"===o?it.createElement(RO,{title:e.name,gapAfterHeader:!1,footer:it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to go back")},it.createElement(Q_,{config:i,onSaveComplete:()=>s("menu"),viewOnly:!0})):"edit"===o?it.createElement(RO,{title:e.name,gapAfterHeader:!1},it.createElement(et,{color:LR.YELLOW},"Edit functionality coming soon..."),it.createElement(kO,null,"Press ",it.createElement(CO,null,"Esc")," to go back")):"delete"===o?it.createElement(RO,{title:"Delete agent",subtitle:`Are you sure you want to delete the agent ${e.name}?`},it.createElement(Ze,null,it.createElement(SelectInput,{items:J_,onSelect:d,indicatorComponent:m_,itemComponent:u_}))):it.createElement(RO,{title:e.name,footer:it.createElement(kO,null,"Press ",it.createElement(CO,null,"↑↓")," to navigate ·"," ",it.createElement(CO,null,"Enter")," to select · ",it.createElement(CO,null,"Esc")," ","to go back")},it.createElement(SelectInput,{items:l,onSelect:c,indicatorComponent:m_,itemComponent:u_}))},"AgentDetails");Vt();var Z_="https://commandcode.ai/docs/core-concepts/custom-agents",eF=__name(({onDone:e})=>(ot((t,n)=>{n.return&&e()}),it.createElement(RO,{title:"Create agents with Command Code",gapAfterHeader:!1,boxProps:{gap:1}},it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.GRAY},"Ask Command Code to create or update subagents for you, e.g."),it.createElement(et,{color:LR.GRAY}," ",ft.pointerSmall," “create a code-reviewer subagent that reviews diffs for bugs”"),it.createElement(et,{color:LR.GRAY}," ",ft.pointerSmall," “make a changelog agent that uses a fast model”")),it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.GRAY},"Or edit the files directly:"),it.createElement(et,{color:LR.GRAY}," • .commandcode/agents/ (this project)"),it.createElement(et,{color:LR.GRAY}," • ~/.commandcode/agents/ (all projects)")),it.createElement(et,{color:LR.GRAY},"Docs: ",Z_),it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to go back and just ask"))),"AskCommandCodeGuide"),tF=__name(({handleSelect:e,createdAgentName:t})=>{const[n,r]=ct([]),[o,s]=ct([]),[a,i]=ct([]),[l,c]=ct(!0),[d,u]=ct(!1),[m,p]=ct(null),[g,h]=ct(!1),[f,y]=ct(0),[S,w]=ct(0),v=useTerminalHeight();ut(()=>{__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(ot((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}),ut(()=>{y(e=>Math.min(e,Math.max(0,k.length-1)))},[k.length]),ut(()=>{w(e=>clampScrollOffset({cursor:f,total:k.length,maxVisible:P,currentOffset:e}))},[f,k.length,P]),l)return it.createElement(F$,{label:"Loading agents"});if(g&&m){const e=isBuiltinAgentPath(m.filePath);return it.createElement(X_,{agent:m,onBack:()=>{h(!1),p(null)},setRevalidateAgent:u,isReadOnly:e})}const x=S,I=S+P,A=k.slice(x,I),R=k.length>P;let L=null;return it.createElement(RO,{title:"Agents",titleSuffix:C>0?` (${C} agent${C>1?"s":""})`:" (No custom agents)"},t&&it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{color:LR.GREEN,dimColor:!0},"Created agent: ",t)),it.createElement(Ze,{flexDirection:"column"},A.map((e,t)=>{const n=x+t,r=E(n),o="action"!==r&&r!==L;L=r;const s=n===f,a="user"===r?"User agents":"project"===r?"Project agents":"Default agents (read-only)";return it.createElement(it.Fragment,{key:e.value},o&&it.createElement(Ze,{marginTop:0===t?0:1},it.createElement(et,{color:HR,bold:!0},a)),it.createElement(Ze,null,it.createElement(et,{color:s?LR.WHITE:LR.GRAY,backgroundColor:s?tL:void 0,bold:s},s?"> ":" ",e.label," ")))})),R&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",x+1,"–",Math.min(I,k.length)," of ",k.length,x>0?" · ↑ more":"",I<k.length?" · ↓ more":"")),it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(bO,{hints:["↑↓ navigate","Enter to select","Esc to close"],marginTop:0}),it.createElement(et,{color:LR.DIM},"Agents live in .commandcode/agents/ (project) and ~/.commandcode/agents/ (all projects) — edit the files directly anytime."),it.createElement(et,{color:LR.DIM},"Docs: ",Z_)))},"ManageAgents");Vt(),PR(),Vt(),Vt(),PR();var nF=__name(({model:e,selectedEffort:t,onSelect:n,onBack:r})=>{const o=(e?getSupportedEfforts(e):null)??[];return it.createElement(V_,{modelLabel:K_(e),supportedEfforts:o,currentEffort:t??void 0,onSelect:e=>n(e??null),onCancel:r})},"AgentEffortSelector");Vt();var rF=[{label:"1. Project (.commandcode/agents/)",value:"project"},{label:"2. Personal (~/.commandcode/agents/)",value:"personal"}],oF=__name(({onSelect:e})=>it.createElement(SelectInput,{items:rF,onSelect:t=>{"project"!==t.value&&"personal"!==t.value||e(t.value)},indicatorComponent:s_,itemComponent:i_}),"LocationSelector");Vt(),PR();var sF=__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:$S}):null,u=usePasteAwareChange({onChange:s}),m=usePasteAwareChange({onChange:a});return"agentType"===e?it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.WHITE},"Enter a unique identifier for your agent:"),"tool_conflict"===d?.issue&&it.createElement(et,{color:LR.RED},ft.warning," This name conflicts with an existing tool name. Please choose a different name."),"reserved"===d?.issue&&it.createElement(et,{color:LR.RED},ft.warning," This name is reserved. Reserved names: ",Yw.join(", "))),it.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?it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.WHITE},"Enter the system prompt for your agent:"),it.createElement(et,{color:LR.GRAY},"Be comprehensive for best results.")),it.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?it.createElement(it.Fragment,null,it.createElement(et,{color:LR.WHITE},"When should ","Command Code"," use this agent?"),it.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");Vt(),PR();var aF=__name((e,t)=>e?"[x]":"[ ]","categoryCheckbox"),iF=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=ct(!1),[a,i]=ct(0),[l,c]=ct(0),d=useTerminalHeight(),u=mt(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),WS.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:"}),LS.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=WS.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t)),s=r?.tools.some(t=>e.has(t));return{label:`${aF(Boolean(o),Boolean(s))} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${$S[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;ut(()=>{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 ot((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()}}),it.createElement(Ze,{flexDirection:"column"},S.map(e=>{const t=p.findIndex(t=>t.value===e.value),n=-1!==t&&t===a;if("divider"===e.type)return it.createElement(Ze,{key:`divider-${e.value}`},it.createElement(et,{color:LR.GRAY}," ",e.label));if("spacer"===e.type)return it.createElement(Ze,{key:`spacer-${e.value}`,height:1});if("label"===e.type)return it.createElement(Ze,{key:`label-${e.value}`},it.createElement(et,{color:LR.GRAY}," ",e.label));const r="continue"===e.type;return it.createElement(Ze,{key:`item-${e.value}`},it.createElement(et,{color:n?LR.WHITE:LR.GRAY,bold:r&&n},n?">":" "," ",e.label))}),w&&it.createElement(Ze,null,it.createElement(et,{color:LR.GRAY}," ","Showing ",f+1,"–",Math.min(y,m.length)," of"," ",m.length,f>0?" · ↑ more":"",y<m.length?" · ↓ more":"")),it.createElement(Ze,{marginTop:1},e.size===LS.length&&it.createElement(et,{color:LR.GRAY},"All tools selected"),e.size>0&&e.size<LS.length&&it.createElement(et,{color:LR.GRAY},e.size," tools selected"),0===e.size&&it.createElement(et,{color:LR.GRAY},"No tools selected")))},"ToolsSelector"),lF=__name(({onComplete:e})=>{const[t,n]=ct(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":"effort"===r?"Select reasoning effort":"summary"===r?"Confirm and save":""},"getSubText"),c=__name(e=>{a({type:"select_location",location:e}),a({type:"select_method",method:"manual"})},"handleLocationSelect");return it.createElement(RO,{title:"Create new agent",subtitle:l()},it.createElement(Ze,null,"location"===r&&it.createElement(oF,{onSelect:c}),"configuration"===r&&it.createElement(Ze,{flexDirection:"column",gap:1},it.createElement(sF,{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&&it.createElement(iF,{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&&it.createElement(Y_,{selectedModel:s.model,onSelect:e=>a({type:"select_model",model:e})}),"effort"===r&&it.createElement(nF,{model:s.model,selectedEffort:s.reasoningEffort??null,onSelect:e=>a({type:"select_effort",effort:e}),onBack:()=>a({type:"back"})}),"summary"===r&&it.createElement(Q_,{config:s,onSaveComplete:i})))},"AgentNew"),cF=__name(({onCancel:e})=>{const[t,n]=ct(null),[r,o]=ct(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return ot((t,n)=>{n.escape&&e()}),it.createElement(Ze,{width:"100%",flexDirection:"column"},null===t&&it.createElement(tF,{handleSelect:s,createdAgentName:r}),"ask_command_code"===t&&it.createElement(eF,{onDone:e}),"create_new_agent"===t&&it.createElement(lF,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");function isToggleShortcut(e,t){return""===e||!0===t.ctrl&&"b"===e}Vt(),PR(),__name(isToggleShortcut,"isToggleShortcut");var dF=new Set;function requestBackgroundTasksExpand(){for(const e of dF)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]=ct(()=>listShellTasks({includeStopped:!0}));return ut(()=>{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 uF=getShellTaskLabel,mF=getShellTaskStatusText,pF=getVisibleShellTasks,gF=latestShellTaskOutputLines,hF={running:LR.CYAN,completed:LR.GREEN,failed:LR.RED,"auto-stopped":LR.YELLOW,stopped:LR.GRAY};function getStatusColor(e){return hF[getShellTaskStatusTone(e)]}function TaskRow({task:e,selected:t}){const n=truncateString2({text:uF(e),maxChars:56}),r=t?tL:void 0;return it.createElement(Ze,null,it.createElement(s_,{isSelected:t,backgroundColor:r}),it.createElement(et,{color:t?MO:void 0,backgroundColor:r}," ",n),it.createElement(et,{color:LR.DIM,backgroundColor:r}," ","(",mF(e),")"))}function TaskGroup({title:e,tasks:t,selectedTaskId:n}){return 0===t.length?null:it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.DIM,bold:!0},e," (",t.length,")"),t.map(e=>it.createElement(TaskRow,{key:e.id,task:e,selected:e.id===n})))}function TaskDetailsBody({task:e,output:t}){const n=gF(t,10),r=formatTaskRuntime(e);return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,{bold:!0},"Status: "),it.createElement(et,{color:getStatusColor(e)},mF(e))),void 0!==r&&it.createElement(Ze,null,it.createElement(et,{bold:!0},"Runtime: "),it.createElement(et,null,r)),it.createElement(Ze,null,it.createElement(et,{bold:!0},"Script: "),it.createElement(et,{wrap:"wrap"},e.command)),it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{bold:!0},"Output:"),it.createElement(Ze,{flexDirection:"column",borderStyle:"single",borderColor:LR.DIM,paddingX:1},n.length>0?n.map((t,n)=>it.createElement(et,{key:`${e.id}-${n}`},truncateString2({text:t,maxChars:100}))):it.createElement(et,{color:LR.DIM},"No output yet.")),it.createElement(et,{italic:!0,color:LR.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]=ct(!1),[s,a]=ct("list"),[i,l]=ct(0),[c,d]=ct(""),u=mt(()=>pF(t),[t]),m=u[i]??u[0];ut(()=>{e?.(r)},[r,e]),ut(()=>{const e=__name(()=>{a("list"),o(!0)},"listener");return dF.add(e),()=>{dF.delete(e)}},[]),ut(()=>{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]),ut(()=>{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(ot((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 it.createElement(RO,{title:"monitor"===m.kind?"Monitor details":"Shell details",titleColor:LR.CYAN,ruleColor:LR.CYAN,subtitle:truncateString2({text:uF(m),maxChars:80}),hint:"← to go back · Esc/Enter/Space to close · x to stop",boxProps:{marginTop:1,marginBottom:1}},it.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 it.createElement(RO,{title:"Background",titleColor:LR.CYAN,ruleColor:LR.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?it.createElement(it.Fragment,null,it.createElement(TaskGroup,{title:"Monitors",tasks:g,selectedTaskId:m?.id}),it.createElement(TaskGroup,{title:"Shells",tasks:h,selectedTaskId:m?.id})):it.createElement(Ze,{flexDirection:"column",marginTop:1},u.map(e=>it.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"),Vt(),PR();var fF=[{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."}],yF=__name(({onSelect:e,onCancel:t})=>{const[n,r]=ct(null);ut(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(ot((e,n)=>{n.escape&&t()}),null===n)return null;const s=fF.findIndex(e=>e.value===n);return it.createElement(RO,{title:"Select a compact mode to compact sessions",subtitle:"Choose how Command Code handles automatic context compaction.",footer:it.createElement(et,{italic:!0,color:LR.DIM},"Press ",it.createElement(et,{bold:!0},"Esc")," to cancel")},it.createElement(SelectInput,{items:fF,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:m_,itemComponent:({isSelected:e,label:t})=>{const r=fF.find(e=>e.label===t),o=r?.value===n,s=fF.findIndex(e=>e.label===t);return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(d_,{isSelected:e,idleColor:o?LR.GREEN:LR.WHITE,bold:e||o},` ${s+1}. ${r?.label??t} `),o&&it.createElement(l_,null)),it.createElement(d_,{isSelected:e,idleColor:LR.DIM,bold:!1},` ${r?.description??""} `))}}))},"CompactModeSelector");Vt(),Vt(),Vt();var SF=[],wF=new Set;function publish(e){SF=e;for(const e of wF)e()}function stepKey(e){return e.split(" · ")[0]??e}function showConnectStep(e){const t=SF.at(-1);!t||t.done||stepKey(t.label)!==stepKey(e)?publish([...SF.map(e=>e.done?e:{...e,done:!0,label:stepKey(e.label)}),{label:e,done:!1,since:Date.now()}]):publish([...SF.slice(0,-1),{...t,label:e}])}function clearConnectSteps(){publish([])}function getConnectSteps(){return SF}function useConnectSteps(){return ht(e=>(wF.add(e),()=>wF.delete(e)),getConnectSteps)}__name(publish,"publish"),__name(stepKey,"stepKey"),__name(showConnectStep,"showConnectStep"),__name(clearConnectSteps,"clearConnectSteps"),__name(getConnectSteps,"getConnectSteps"),__name(useConnectSteps,"useConnectSteps");var vF=[["Checking out","Checked out"],["Creating","Created"],["Restarting","Restarted"],["Starting","Started"],["Connecting","Connected"],["Cloning","Cloned"],["Updating","Updated"],["Preparing","Prepared"],["Loading","Loaded"],["Using","Used"]];function doneLabel(e){for(const[t,n]of vF)if(e.startsWith(`${t} `))return`${n}${e.slice(t.length)}`;return e}__name(doneLabel,"doneLabel"),Vt(),Vt(),PR();var kF=["·","○","◇","☆","✧","☆","◇","○","⌘"],CF=[12,5,4,4,4,4,4,5,16],bF=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<CF.length;e++)if(n+=CF[e],t<n)return kF[e];const r=t-58;n=0;for(let e=0;e<bF.length;e++)if(n+=bF[e],r<n)return kF[7-e];return kF[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=mt(()=>e.split(""),[e]),o=__name(e=>{const n=e-(t-5);return n>=0&&n<JR.length?JR[n]:XR},"getCharColor");return it.createElement(et,null,r.map((e,t)=>it.createElement(et,{key:`${t}:${e}`,color:o(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return it.createElement(et,{color:t??OR,bold:!0},`${getWaveSymbol(e)} `)}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var EF=formatStatusTokenCount,TF=formatElapsedMs,PF=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=ct(0),[s,a]=ct(n),i=dt(n);i.current=n;const l=getTerminalWidth(),[c,d]=ct(()=>l>=72?"all":l>=42?"medium":"none");ut(()=>{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]),ut(()=>{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 FL.statusRender({width:l,layoutMode:c,status:e,frame:r}),it.createElement(Ze,{width:l,height:1,paddingLeft:0,marginLeft:0},it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:UR.BG,color:UR.FG}," "),it.createElement(et,{backgroundColor:UR.BG},it.createElement(CMDIcon,{frame:4*r,color:UR.FG})),it.createElement(ShimmerText,{text:e,offset:u,bg:UR.BG}),it.createElement(et,{backgroundColor:UR.BG,color:UR.FG}," ")),m&&it.createElement(Ze,{columnGap:1,marginLeft:1},it.createElement(et,{bold:!0,color:LR.GRAY},"esc"),it.createElement(et,{color:LR.DIM},"to interrupt"),it.createElement(et,{color:LR.DIM},"•"),it.createElement(et,{color:LR.DIM},TF(t)),it.createElement(et,{color:LR.DIM},"•"),it.createElement(et,{color:LR.GRAY},ft.arrowDown),it.createElement(et,{color:LR.DIM},EF(Math.round(s)))),p&&it.createElement(Ze,{marginLeft:1},it.createElement(et,{color:LR.DIM},EF(Math.round(s)))))},"Status");function ShimmerLine({text:e,indent:t=1}){const[n,r]=ct(0);return ut(()=>{const e=setInterval(()=>r(e=>e+1),80);return()=>clearInterval(e)},[]),it.createElement(Ze,{marginLeft:t},it.createElement(ShimmerText,{text:e,offset:n%(e.length+10)}))}function activeText(e){return e.includes(" · ")?e:`${e}…`}function ConnectSteps(){const e=useConnectSteps(),[t,n]=ct(()=>Date.now());ut(()=>{const e=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(e)},[]);const r=e.at(-1);if(!r||r.done)return it.createElement(ShimmerLine,{text:"Connecting to the sandbox…"});const o=r.label.startsWith("Cloning ")&&t-r.since>15e3;return it.createElement(Ze,{flexDirection:"column"},e.filter(e=>e.done).map((e,t)=>it.createElement(Ze,{key:`${t}:${e.label}`,marginLeft:1},it.createElement(et,{color:LR.GREEN},"✓ "),it.createElement(et,{color:LR.DIM},doneLabel(e.label)))),it.createElement(ShimmerLine,{text:activeText(r.label),indent:3}),o&&it.createElement(Ze,{marginLeft:3},it.createElement(et,{color:LR.DIM},"Large repo: it is cloned once per sandbox, and reopening is fast.")))}function useExternalEditor({input:e,setInput:t,setInputKey:n,detectedContent:r,setDetectedContent:o,onEditorClose:s}){const[a,i]=ct(!1),[l,c]=ct(null),d=pt(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 ry)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=pt(()=>{c(null)},[]);return{isEditorOpen:a,editorError:l,handleOpenInEditor:d,clearEditorError:u}}__name(ShimmerLine,"ShimmerLine"),__name(activeText,"activeText"),__name(ConnectSteps,"ConnectSteps"),Vt(),PR(),Vt(),PR(),__name(useExternalEditor,"useExternalEditor"),Vt(),PR();var MF=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=ct(null),[s,a]=ct(!1),[i,l]=ct({visible:!1,type:"connected"}),c=dt(null);null===c.current&&(c.current=RE({onConnectedChange:a,onContext:o,onIndicatorChange:l}));const d=c.current;ut(()=>{d.setPaused(n)},[d,n]),ut(()=>{if(t)return d.start(),()=>{d.stop()}},[t,d]);const u=mE(),m=u?NE[u]??"IDE":"IDE",p={visible:i.visible,message:"connected"===i.type?`${m} ${ft.tick}`:"run /ide",type:i.type};return{context:r,connected:s,refresh:d.refresh,connectionIndicator:p}},"useVSCodeContext");Vt(),PR();var xF=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=ct(null),o=dt(!1);return ut(()=>{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=dt([]),s=dt(""),a=dt(!1),i=dt(null),l=dt(!1),c=dt("");return ut(()=>{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})}Vt(),__name(pushEntry,"pushEntry"),__name(commitBurst,"commitBurst"),__name(useUndoStack,"useUndoStack"),Vt(),PR(),__name(getCommandHintLayout,"getCommandHintLayout"),__name(getModelHintText,"getModelHintText"),Vt(),PR();var IF=createNodeRuntime(),AF=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=ct(()=>process.cwd()),[a,i]=ct([]),[l,c]=ct(0),[d,u]=ct(0),m=n.trim()?15:10;ut(()=>{invalidateFileIndex()},[]),ut(()=>{let e=!1;return __name(async()=>{if(n.trim()){const t=await searchFiles({runtime:IF,searchTerm:n,basePath:process.cwd()});if(e)return;return i(t),c(0),void u(0)}try{const t=await browseDirectory({runtime:IF,dirPath:r,basePath:process.cwd()});if(e)return;i(t),c(0),u(0)}catch{}},"run")(),()=>{e=!0}},[r,n]),ot((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 it.createElement(Ze,{flexDirection:"column",paddingLeft:1},it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},n.trim()?`Searching for: "${n}"`:`Files: ${r}`)),0===p.length?it.createElement(W$,{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 it.createElement(et,{key:e.path,color:o?MO:LR.DIM,bold:o&&isLightTheme()},e.isDirectory?`${r}/`:r)}),it.createElement(bO,{hints:["↑↓ navigate",!n.trim()&&"→ to open folder","Enter to select","Esc to close"]}))},"FileList");Vt(),PR();var RF=__name(()=>it.createElement(Ze,{paddingRight:3},it.createElement(et,{color:LR.DIM,wrap:"truncate"},ft.pointerSmall," ","stashed")),"StashBadge"),LF=__name(({hint:e})=>it.createElement(Ze,{paddingRight:1},it.createElement(et,{color:LR.DIM,wrap:"truncate"},e)),"PasteKeyHint"),OF=__name(({tasteLearningOn:e,byokSession:t,showSeparator:n=!0})=>{if(null==e)return null;const r=e&&t;return it.createElement(it.Fragment,null,n&&it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:e&&!r?DR.TEXT:LR.DIM},r?"taste off (byok)":"taste "+(e?"on":"off")))},"TasteStateBadge");function useBackgroundTasksSummary(){const[e,t]=ct(()=>formatShellTaskCounts(listShellTasks({includeStopped:!1})));return ut(()=>{const e=setInterval(__name(()=>t(formatShellTaskCounts(listShellTasks({includeStopped:!1}))),"refresh"),1e3);return()=>clearInterval(e)},[]),e}__name(useBackgroundTasksSummary,"useBackgroundTasksSummary");var DF=__name(({showSeparator:e=!0,armed:t=!1})=>{const n=useBackgroundTasksSummary();return n?it.createElement(it.Fragment,null,e&&it.createElement(et,{color:LR.DIM}," · "),t?it.createElement(it.Fragment,null,it.createElement(et,{color:LR.CYAN,inverse:!0},` ${n} `),it.createElement(et,{color:LR.DIM}," · Enter to open")):it.createElement(it.Fragment,null,it.createElement(et,{color:LR.CYAN},n),it.createElement(et,{color:LR.DIM}," · ↓ to manage"))):null},"BackgroundTasksBadge"),$F=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?it.createElement(it.Fragment,null,t&&it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:"connected"===e.type?LR.GREEN:LR.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),NF=__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,pasteKeyHint:C})=>{const b=e>=60,E=C&&e>=90?C:null;return it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r&&"bypass"!==r&&"dont-ask"!==r||i?it.createElement(Ze,{flexDirection:"row",justifyContent:"space-between",width:e-1},it.createElement(Ze,{flexDirection:"row",columnGap:0},n&&!i?it.createElement(et,{color:WR},t):it.createElement(fL,{mode:r,pendingExitKey:i}),!i&&it.createElement(SL,{prInfo:o}),!i&&it.createElement($F,{indicator:a}),!i&&b&&it.createElement(OF,{tasteLearningOn:w,byokSession:v}),!i&&it.createElement(DF,{armed:k})),(b||S||E)&&it.createElement(Ze,{flexDirection:"column",alignItems:"flex-end"},!S&&E&&it.createElement(LF,{hint:E}),S?it.createElement(RF,null):null,!S&&b&&s&&it.createElement(aL,{usage:s}))):it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"row",justifyContent:"space-between",width:e-1},it.createElement(fL,{mode:r}),S&&it.createElement(RF,null),!S&&E&&it.createElement(LF,{hint:E})),it.createElement(Ze,{flexDirection:"row",justifyContent:"space-between",width:e-1},it.createElement(Ze,{flexDirection:"row",columnGap:0},it.createElement(et,{color:n?WR:LR.DIM},t),it.createElement(SL,{prInfo:o}),it.createElement($F,{indicator:a}),b&&it.createElement(OF,{tasteLearningOn:w,byokSession:v}),it.createElement(DF,{armed:k})),it.createElement(Ze,{flexDirection:"row",columnGap:2},b&&s&&it.createElement(aL,{usage:s})))),(l||c||u&&d)&&it.createElement(Ze,{flexDirection:"row",columnGap:1},l&&it.createElement(et,null,ft.tick," ","Command Code"," updated:"," ",it.createElement(et,{color:LR.DIM},"v",l.updatedFrom),it.createElement(et,{color:LR.DIM}," ",ft.arrowRight," "),it.createElement(et,null,"v",l.updatedTo)),!l&&c&&it.createElement(et,{color:LR.YELLOW,dimColor:!0},ft.info," Update available:"," ",c.currentVersion," ",ft.arrowRight," ",c.latestVersion),u&&d&&it.createElement(et,{color:LR.GREEN,dimColor:!0},ft.bullet," Provider:"," ",getProviderDisplayName(d)))),m&&it.createElement(Ze,{paddingLeft:2},it.createElement(et,{color:LR.GREEN},"! for bash mode")),g&&p&&it.createElement(Ze,{paddingLeft:2},it.createElement(et,{color:OR},"SHARED: ",p.url," (copied to clipboard)")),h&&it.createElement(Ze,{paddingLeft:2},it.createElement(et,{color:h.includes("NOT SHARED")?LR.RED:OR},h)),f&&it.createElement(Ze,{paddingLeft:2},it.createElement(et,{color:OR},f)),y&&it.createElement(Ze,{paddingLeft:2},it.createElement(et,{color:LR.YELLOW},ft.warning," ",y)))},"BottomIndicator");Vt();var _F=[["rc","token"],["rc","user"]];function carriesSecretArgument(e){const[t,n,...r]=e.trim().replace(/^\//,"").split(/\s+/).filter(Boolean);return void 0!==t&&void 0!==n&&0!==r.length&&_F.some(([e,r])=>e===t.toLowerCase()&&r===n.toLowerCase())}function useClipboardPasteKey(e){const{latestInputRef:t,cursorPositionRef:n,detectedImagesRef:r,setDetectedImages:o,setInput:s,incrementInputKey:a,setInitialCursor:i,handlePaste:l,onTextPasted:c,showClipboardNotice:d,clearClipboardNotice:u,showPasteKeyHint:m}=e,p=pt(e=>{const l=nextImagePasteNumber(r.current),{text:c,cursor:d}=insertTextAt(t.current,n.current,imagePasteToken(l)),u=[...r.current,{imageNumber:l,image:e}];r.current=u,o(u),s(c),t.current=c,n.current=d,i(d),a()},[n,r,a,t,o,i,s]),g=pt(async e=>{const r=stripEmbeddedPasteEndMarker(e),o=t.current,s=n.current,a=o.slice(0,s),i=o.slice(s);await l(`${a}[200~${r}[201~${i}`)&&c()},[n,l,t,c]);return pt(async()=>{const e=setTimeout(()=>{d("Reading clipboard…",{sticky:!0})},150);try{const t=await probeClipboardImage();if(t.image)return p(t.image),clearTimeout(e),void u();const n=t.text??await detectClipboardText();if(clearTimeout(e),n)return u(),void await g(n);d(describeClipboardImageMiss({environment:t.environment,attempted:t.attempted})),m()}catch{clearTimeout(e),u()}},[u,p,g,d,m])}__name(carriesSecretArgument,"carriesSecretArgument"),Vt(),PR(),__name(useClipboardPasteKey,"useClipboardPasteKey");var FF=["","","[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 UF=__name(({pasteKeyAdvice:e})=>it.createElement(Ze,{flexDirection:"column",paddingLeft:1},it.createElement(et,{color:LR.DIM,bold:!0},"Available Shortcuts:"),it.createElement(Ze,{columnGap:4},it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.DIM},"! for bash mode"),it.createElement(et,{color:LR.DIM},"/ for commands"),it.createElement(et,{color:LR.DIM},"@ for file paths"),it.createElement(et,{color:LR.DIM},getModeToggleShortcutHint()," to toggle accept edits")),it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.DIM},"double tap esc to clear input"),it.createElement(et,{color:LR.DIM},getNewlineShortcutHint()," for newline"),it.createElement(et,{color:LR.DIM},"ctrl + g to open in editor"),it.createElement(et,{color:LR.DIM},"ctrl + z to undo"),it.createElement(et,{color:LR.DIM},"ctrl + s to stash prompt"),it.createElement(et,{color:LR.DIM},spacedKey(e.key)," to paste image"),e.textOnlyKey&&it.createElement(et,{color:LR.DIM},spacedKey(e.textOnlyKey)," pastes text only in ",e.terminal)))),"ShortcutMenu");function spacedKey(e){return e.split("+").join(" + ")}function currentPasteKeyAdvice(){return pasteImageKeyAdvice({terminal:detectTerminal({env:process.env}),environment:currentClipboardEnvironment()})}__name(spacedKey,"spacedKey"),__name(currentPasteKeyAdvice,"currentPasteKeyAdvice");var jF=__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:L=!1,ideContextEnabled:O=!0,footer:D})=>{const[$,N]=ct(0),[_,F]=ct(!1),[U,j]=ct(!1),[B,W]=ct(!1),[H,G]=ct(""),[V,z]=ct(null),K=dt(0),q=dt(0),[Y,Q]=ct([]),[J,X]=ct([]),[Z,ee]=ct(null),[te,ne]=ct(null),re=dt(null),oe=pt(()=>{re.current&&(clearTimeout(re.current),re.current=null),ne(null)},[]),se=pt((e,t)=>{re.current&&(clearTimeout(re.current),re.current=null),ne(e),t?.sticky||(re.current=setTimeout(()=>{re.current=null,ne(null)},5e3))},[]);ut(()=>()=>{re.current&&clearTimeout(re.current)},[]);const ae=mt(currentPasteKeyAdvice,[]),ie=mt(()=>formatPasteImageKeyHint(ae),[ae]),[le,ce]=ct(()=>ie?Date.now():null);ut(()=>{if(null===le)return;const e=setTimeout(()=>{ce(null)},2e4);return()=>clearTimeout(e)},[le]);const de=pt(()=>{ie&&ce(Date.now())},[ie]),ue=dt(!1),me=dt(!1),[pe,ge]=ct(!1),he=dt(!1),fe=pt(e=>{he.current=e,ge(e)},[]),ye=dt(!1),Se=dt(void 0),[we,ve]=ct(-1),[ke,Ce]=ct(""),be=dt(0),Ee=dt(e);Ee.current=e;const Te=dt(J);Te.current=J;const{commitUndo:Pe}=useUndoStack({input:e,setInput:n,initialCursorRef:Se,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey")}),{isEditorOpen:Me,editorError:xe,handleOpenInEditor:Ie,clearEditorError:Ae}=useExternalEditor({input:e,setInput:n,setInputKey:N,detectedContent:Y,setDetectedContent:Q,onEditorClose:__name(()=>{ue.current=!1},"onEditorClose")}),Re=mt(()=>shouldCollapsePastedText(),[]),{handlePaste:Le,resetPasteState:Oe,isPasting:De}=useBracketedPaste({input:e,setInput:n,setDetectedImages:X,setDetectedContent:Q,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{Se.current=e},"setInitialCursor"),collapsePastedText:Re,nextImageNumber:nextImagePasteNumber(J),onPasteMiss:__name(e=>{se(describeClipboardImageMiss({environment:e.environment,attempted:e.attempted})),de()},"onPasteMiss")}),$e=useClipboardPasteKey({latestInputRef:Ee,cursorPositionRef:be,detectedImagesRef:Te,setDetectedImages:X,setInput:n,incrementInputKey:__name(()=>N(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{Se.current=e},"setInitialCursor"),handlePaste:Le,onTextPasted:__name(()=>{ye.current=!0},"onTextPasted"),showClipboardNotice:se,clearClipboardNotice:oe,showPasteKeyHint:de}),Ne=dt(()=>{});Ne.current=t=>{Me||(async()=>{const n=be.current,r=e.slice(0,n),o=e.slice(n),s=stripEmbeddedPasteEndMarker(t);await Le(`${r}[200~${s}[201~${o}`)&&(ye.current=!0)})()},ut(()=>registerPasteConsumer(e=>Ne.current(e)),[]);const _e=dt(new Map),Fe=mt(()=>{const e=_e.current,t=new Map,n=new Map;for(const r of J){const o=e.has(r)?e.get(r)??null:saveTempImage(r.image,r.imageNumber);t.set(r,o),n.set(r.imageNumber,o)}return _e.current=t,n},[J]),{skills:Ue,customMenuItems:je}=useSlashMenuData(),Be=mt(()=>{const e=resolveSlashMenuItems({searchQuery:"",customMenuItems:je,skills:Ue,showProviderCommand:!0,showTerminalSetupCommand:isVSCodeTerminal2()});return new Set([...e.map(e=>e.command),...Ue.map(e=>buildSkillNamespacedCommand(e.name))])},[Ue,je]),We=pt(e=>Be.has(e),[Be]),{context:He,connected:Ge,refresh:Ve,connectionIndicator:ze}=MF({enabled:O,paused:L}),{stdout:Ke}=nt(),qe=Ke?.columns??80,{pr:Ye}=xF();ut(()=>{const e=s||B;I?.(e)},[s,B,I]),ut(()=>{if(!ye.current)return;ye.current=!1;const t=Iy(e);!B&&t.showCommandMenu||(W(t.showCommandMenu),G(t.showCommandMenu?t.commandSearchQuery:""))},[e,B]);const Qe=pt(()=>{X([])},[]),Je=pt(()=>{W(!1),z(null)},[]),Xe=pt(()=>{Je(),G(""),i(!1),c(""),ve(-1),Ce(""),Se.current=void 0,N(e=>e+1)},[Je,c,i]),tt=pt(t=>!(null===Z||!t?.replaceCurrentInput&&e.trim().length>0||(ue.current=!0,n(Z),ee(null),Xe(),setTimeout(()=>{ue.current=!1},0),0)),[e,Xe,n,Z]),rt=pt(()=>{n(""),j(!1),Je(),G(""),Q([]),Qe(),Oe(),ve(-1),Ce(""),N(e=>e+1)},[n,Oe,Qe,Je]),st=pt(e=>{ue.current=!0,n(e.text),Se.current=e.cursor,N(e=>e+1),setTimeout(()=>{ue.current=!1},0)},[n]),at=pt(()=>{st(insertTextAt(e,be.current,"\n"))},[e,st]);ot(async(t,r)=>{if(he.current&&!r.downArrow&&!r.return&&"\r"!==t&&(fe(!1),r.upArrow))return;if(r.upArrow){if(s||B)return;const t=e.indexOf("\n"),r=-1===t||be.current<=t;if(0!==e.length&&-1===we&&!r)return;const o=M?.count()??0;if(0===o)return;-1===we&&Ce(e);const a=Math.min(we+1,o-1);return void(a!==we&&(ve(a),n(M?.getAt(a)||""),N(e=>e+1)))}if(r.downArrow){if(s||B)return;if(-1===we){const t=e.lastIndexOf("\n"),n=-1===t||be.current>t;return void((0===e.length||n)&&listShellTasks().some(e=>"running"===e.status)&&fe(!0))}const t=e.lastIndexOf("\n");if(!(-1===t||be.current>t))return;const r=we-1;return ve(r),n(-1===r?ke:M?.getAt(r)||""),void N(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void Qe();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return ue.current=!0,void Ie();if(isCtrlKey({inputChar:t,key:r,letter:"s",ctrlCode:19})){const t=e.trim().length>0;if(!t&&null===Z)return;if(!t&&tt())return;ue.current=!0;const r=Z??"";return ee(t?e:null),n(r),Xe(),void setTimeout(()=>{ue.current=!1},0)}if(getIsExpandToolShortcut(r,t))return ue.current=!0,n(e),N(e=>e+1),void setTimeout(()=>{ue.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:De()}))return me.current=!0,at(),void setTimeout(()=>{me.current=!1},0);if(r.meta&&"w"===t)return ue.current=!0,void rt();const o=r.ctrl&&"v"===t.toLowerCase()||FF.includes(t),a=r.meta&&"v"===t.toLowerCase();if(o||a){if(Me)return;return ue.current=!0,setTimeout(()=>{ue.current=!1},0),void await $e()}if(!r.ctrl&&!r.meta||"u"!==t)if(r.ctrl&&"z"===t?.toLowerCase())Pe();else{if(r.escape){if(B)return;const t=Date.now();return t-K.current<500?(e.length>0?rt():A?.(),K.current=0,q.current=0,F(!1),void j(!1)):(K.current=t,_||U||(q.current=t),F(!1),void j(!1))}if(_&&(r.backspace||r.delete)&&0===e.length)F(!1);else if(r.return&&!r.shift&&!r.ctrl&&!r.meta){if(he.current&&(fe(!1),listShellTasks().some(e=>"running"===e.status)))return void requestBackgroundTasksExpand();if(me.current)return void(me.current=!1);if(Date.now()-q.current<100)return q.current=0,void at();if(s)return;if(B)return;if(Me)return;const e=applyBackslashNewline(Ee.current,be.current);return e?void st(e):void await gt(Ee.current)}}});const lt=pt(async t=>{if(Me)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||De())&&await Le(t))return void(ye.current=!0);if(ue.current)return void(ue.current=!1);-1!==we&&ve(-1),X(e=>{if(0===e.length)return e;const n=prunePastedImages({input:t,images:e});return n===e?e:[...n]});const u=1===t.length,m=t.slice(-1);if(u){if("?"===m&&!_)return F(!0),n(""),void N(e=>e+1);if("!"===m&&!U)return F(!1),j(!0),n(""),void N(e=>e+1)}const p=Iy(t),g=t.length<e.length&&!e.startsWith(t),h=!g&&t.length<e.length,f=t.length===e.length+1||h,y=Ay({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),xe&&Ae(),0===t.length&&(j(!1),Je(),G(""),Q([]),c(""),Oe()),n(t)},[_,e,n,s,i,l,c,B,H,U,we,Le,Oe,De,R,xe,Ae,Me,Je]),gt=pt(async(r=e)=>{if(Ve(),q.current=0,_)return void F(!1);const o=r.trim(),s=!U&&o.startsWith("/");let a=o;!U&&Y.length>0&&(a=resolvePastedTextTokens({input:a,detectedContent:Y}));const i=U?[]:resolvePastedImageTokens({input:o,images:J}),l={};if(!U)for(const e of J){if(!o.includes(imagePasteToken(e.imageNumber)))continue;const t=Fe.get(e.imageNumber);t&&(l[e.imageNumber]=t)}const c=Object.keys(l).length>0,u=He?EE(He):void 0;if(s&&d&&(n(""),"handled"===(await d(a,i,u)).status))return carriesSecretArgument(a)||M?.add(a),j(!1),Je(),G(""),Qe(),Q([]),ve(-1),Ce(""),void tt({replaceCurrentInput:!0});ve(-1),Ce(""),a.length>0&&!carriesSecretArgument(a)&&M?.add(a);const m=buildIdeContextHint({ideContext:He});t({input:a,role:U?"bash":"user",images:i,ideContext:u,ideHint:m,imageTokenPaths:c?l:void 0}),j(!1),Je(),G(""),Qe(),Q([]),tt({replaceCurrentInput:!0})},[t,d,_,e,U,J,Fe,Y,M,Ve,He,Qe,Je,tt,n]),ht=pt(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(""),N(e=>e+1)},[n,i,e,s,l,c]),yt=pt(()=>{i(!1),c("")},[i,c]),St=pt(e=>{const t=Ey.has(e),r="/design"===e.trimEnd();if(t||r){const t=e.trimEnd();return n(t+" "),G(t.substring(1)+" "),void N(e=>e+1)}Je(),G(""),n(e+" "),N(e=>e+1)},[n,Je]),wt=pt(t=>{if("/design help"===t)return Je(),G(""),n(""),N(e=>e+1),M?.add(t),void d?.("/design help");if(by.has(t))return Je(),G(""),M?.add(t),ve(-1),Ce(""),n(""),N(e=>e+1),void d?.(t);const r=Ey.has(t),o=Ba.has(t),s=Wa.has(t);if(r)St(t);else{if(Je(),G(""),!o&&!s&&e!==t)return n(t+" "),void N(e=>e+1);M?.add(t),ve(-1),Ce(""),n(""),N(e=>e+1),d?.(t)}},[d,n,e,M,St,Je]),vt=pt(()=>{Je(),G(""),ve(-1),Ce(""),N(e=>e+1)},[Je]),kt=pt(e=>{be.current=e,Se.current=void 0},[]),Ct=mt(()=>formatSlashCommandInputHint({value:e,selectedCommand:B?V:null}),[e,B,V]),bt=Boolean(Ct)&&!x,Et=mt(()=>{const t=Ye&&("OPEN"===Ye.state||"MERGED"===Ye.state);return"auto-accept"===E||"plan"===E||"bypass"===E||"dont-ask"===E||Ge||t?!_:!_&&0===e.length&&!U},[_,e,U,E,Ge,Ye]),Tt=null!==Z,Pt=__name(()=>_||s||B?0:bt||Et||x||U?3:4,"getBottomMargin");return it.createElement(Ze,{width:"100%",flexDirection:"column",marginBottom:Pt()},it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(et,{color:U?LR.GREEN:LR.GRAY},ft.line.repeat(qe)),(()=>{const t=__name(t=>it.createElement(TextInput,{key:$,value:e,placeholder:Me?"Save and close the editor to continue...":o,onChange:lt,showCursor:!Me&&r,onCursorChange:kt,initialCursor:Se.current,prefix:`${U?"!":ft.pointer} `,prefixColor:U?LR.GREEN:LR.WHITE,singleLine:t?.singleLine,maxWidth:t?.maxWidth,imageTokenLinks:Fe,isRecognizedSlashCommand:We,disablePasteRouting:!0}),"renderTextInput"),n=B?"/model"===V&&C?getModelHintText(C):Ct:null,s=n?getCommandHintLayout({text:n,terminalWidth:qe}):null;return s?it.createElement(Ze,{flexDirection:"row",width:"100%"},it.createElement(Ze,{width:25},t({singleLine:!0,maxWidth:25})),it.createElement(Ze,{width:s.descriptionWidth},it.createElement(et,{color:LR.DIM,wrap:"truncate"},s.text))):t()})(),it.createElement(et,{color:U?LR.GREEN:LR.GRAY},ft.line.repeat(qe))),_&&it.createElement(UF,{pasteKeyAdvice:ae}),s&&it.createElement(AF,{onSelectFile:ht,onClose:yt,searchQuery:l}),B&&it.createElement(oL,{onSelectCommand:wt,onInsertCommand:St,onSubmitSearch:gt,onClose:vt,searchQuery:H,onSelectedCommandChange:z}),!B&&!s&&bt&&it.createElement(Ze,null,it.createElement(et,{color:LR.DIM,wrap:"truncate"},Ct)),!B&&!s&&!bt&&(Et||x||Tt)&&it.createElement(NF,{termWidth:qe,indicatorText:getIdeInputIndicatorText(Ge,He,qe),isIDEIndicator:hasIdeInputIndicatorContext(Ge,He),permissionMode:E,prInfo:Ye,contextUsage:u,tasteLearningOn:m,byokSession:isByok({model:C??""}),connectionIndicator:ze,pendingExitKey:x,updateStatus:w,updateFailedInfo:v,currentProvider:k,showProviderInfo:b,isBashMode:U,shareInfo:g,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,creditWarning:S,hasStashedPrompt:Tt,backgroundTasksArmed:pe,pasteKeyHint:null!==le&&0===J.length?ie:null}),xe&&it.createElement(Ze,{paddingLeft:1,flexDirection:"column"},it.createElement(et,{color:LR.YELLOW},xe)),!xe&&te&&it.createElement(Ze,{paddingLeft:1},it.createElement(et,{color:LR.DIM,wrap:"truncate"},te)),D)},"InputBox");Vt(),PR();var BF=__name(()=>{const[e,t]=ct([]);return ut(()=>subscribeModStatus(t),[]),0===e.length?null:it.createElement(Ze,{paddingLeft:2},it.createElement(et,{wrap:"truncate"},e.map(e=>e.text).join(" ")))},"ModStatusLine");Vt(),PR();var WF=__name(({messages:e})=>{const t=countVisibleQueuedMessages(e);if(0===t)return null;const n=getQueuedDisplayRows(e);return it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(Ze,{marginBottom:0},it.createElement(et,{color:NR,inverse:!0},` Queued (${t}) `)),n.map(e=>it.createElement(Ze,{key:e.text},it.createElement(et,{color:LR.DIM},ft.pointerSmall," "),it.createElement(et,{color:LR.DIM},truncateString2({text:e.count>1?`${e.text} (${e.count})`:e.text,maxChars:80})))))},"QueuedMessages");function useWorkedDuration(e,t){const n=dt(null),[r,o]=ct(null);return ut(()=>{n.current=null,o(null)},[t]),ut(()=>{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:it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},`✻ Worked for ${formatElapsedMs(e)}`))}Vt(),PR(),__name(useWorkedDuration,"useWorkedDuration"),__name(WorkedDurationNote,"WorkedDurationNote");var HF=it.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:L,onDoubleEscapeEmpty:O,retryAttempt:D,onAltP:$,inputActive:N=!0,inactiveHint:_,sessionId:F})=>{const[U,j]=ct(()=>null===n?0:Date.now()-n),B=dt(s),W=t||r.isExecuting,H=t&&isSandboxMode()&&isSandboxConnecting(),G=useWorkedDuration(W&&!H,F);return ut(()=>{R&&s!==B.current&&s.length>0&&L?.(),B.current=s},[s,R,L]),ut(()=>{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]),it.createElement(Ze,{flexDirection:"column"},it.createElement(WF,{messages:e}),it.createElement(Ze,{flexDirection:"row",justifyContent:"space-between"},it.createElement(Ze,{flexDirection:"column"},H&&it.createElement(ConnectSteps,null),W&&!H&&null===D&&it.createElement(PF,{tokens:p,timeElapsed:U,status:r.isExecuting?`Executing: ${r.currentCommand}`:o}),!W&&it.createElement(WorkedDurationNote,{durationMs:G}),W&&!H&&null===D&&I&&it.createElement(Ze,{marginLeft:1},it.createElement(et,{color:LR.DIM}," ","⎿"," ","Tip: ",I)))),N?it.createElement(jF,{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:O,onAltP:$,isProcessing:t,footer:it.createElement(BF,null)}):it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{marginLeft:1},it.createElement(kO,null,_??"Background focused · ↑/↓ to select · Enter to view · x to stop · ←/Esc to go back to feed")),it.createElement(BF,null)))});Vt();var GF=__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 ot((e,t)=>{t.ctrl&&"c"===e&&l()}),it.createElement(OO,{authState:n,statusMessage:r,browserUrl:o,apiKeyInput:s,setApiKeyInput:a,handleApiKeySubmit:i})},"LoginOverlay");function getStatusTextColor(e){return"connected"===e?LR.GREEN:"connecting"===e||"authenticated"===e?LR.CYAN:"requires_auth"===e?LR.YELLOW:LR.GRAY}Vt(),PR(),__name(getStatusTextColor,"getStatusTextColor");var VF=__name((e,t)=>{const n=__name((e,n)=>it.createElement(et,{color:e,backgroundColor:t},n),"icon");return"connected"===e?n(LR.GREEN,ft.tick):"connecting"===e?n(LR.CYAN,ft.circle):"authenticated"===e?n(LR.CYAN,ft.tick):"requires_auth"===e?n(LR.YELLOW,ft.warning):"error"===e?n(LR.RED,ft.cross):n(LR.GRAY,ft.circle)},"getStatusIcon"),zF=__name(({onClose:e,mcp:t})=>{const[n,r]=ct([]),[o,s]=ct(!0),[a,i]=ct(0),[l,c]=ct("list"),[d,u]=ct(null),[m,p]=ct(0),g=useTerminalHeight(),h=pt(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]);ut(()=>{h()},[h]),ut(()=>{if(t)return t.onChange(()=>{h()})},[t,h]);const f=mt(()=>[...orderMcpManagerServers(n)],[n]),y=f[a]??null,S=g-1,w=mt(()=>new Set(f.map(e=>e.scope)).size,[f]),v=Math.max(4,S-8-2*w);ut(()=>{p(e=>clampScrollOffset({cursor:a,total:f.length,maxVisible:v,currentOffset:e}))},[a,f.length,v]),ot((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:LR.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:y.name,enabled:!0,scope:y.scope}))return void u({text:`${ft.cross} Failed to enable ${y.name}, server may no longer exist in ${y.scope} scope`,color:LR.YELLOW});await h(),u({text:`${ft.tick} Enabled ${y.name}`,color:LR.GREEN})}catch(e){u({text:`${ft.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:LR.RED})}}else{u({text:`Disabling ${y.name}...`,color:LR.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:y.name,enabled:!1,scope:y.scope}))return void u({text:`${ft.cross} Failed to disable ${y.name}, server may no longer exist in ${y.scope} scope`,color:LR.YELLOW});await disconnectMcpServer({name:y.name,registry:t}),await h(),u({text:`${ft.tick} Disabled ${y.name}`,color:LR.GREEN})}catch(e){u({text:`${ft.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:LR.RED})}}else c("confirm-remove");else{u({text:`Authenticating ${y.name}...`,color:LR.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:LR.YELLOW});"success"===e.kind?(u({text:`${ft.tick} Authenticated with ${y.name}`,color:LR.GREEN}),await h()):u({text:`${ft.cross} Auth failed: ${e.message}`,color:LR.RED})}catch(e){u({text:`${ft.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:LR.RED})}}else{u({text:`Connecting ${y.name}...`,color:LR.CYAN,loading:!0});try{await connectMcpServer({name:y.name,registry:t}),u({text:`${ft.tick} Connected to ${y.name}`,color:LR.GREEN}),await h()}catch(e){u({text:`${ft.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:LR.RED})}}else u({text:"Already authenticated",color:LR.GREEN});else u({text:"Already connected",color:LR.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:`${ft.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:LR.RED}),c("actions")}else c("actions")},"handleRemoveConfirm");if(o)return it.createElement(RO,{title:"Manage MCP servers"},it.createElement(et,{color:LR.DIM},"Loading..."));if("confirm-remove"===l&&y)return it.createElement(RO,{title:`Remove ${y.name}?`,titleColor:LR.RED,hint:"↑↓ navigate · Enter to select · Esc to cancel"},it.createElement(et,{color:LR.DIM},"This will remove the server from ",y.scope," ","config."),it.createElement(Ze,{marginTop:1},it.createElement(SelectInput,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:C,indicatorComponent:m_,itemComponent:u_})));if("actions"===l&&y){const e=buildMcpManagerActionItems(y);return it.createElement(RO,{title:y.name,hint:"↑↓ navigate · Enter to select · Esc to go back"},it.createElement(Ze,null,VF(y.status),it.createElement(et,{color:LR.DIM}," ",getMcpManagerStatusText(y))),it.createElement(Ze,{marginTop:1},it.createElement(SelectInput,{items:[...e],onSelect:k,indicatorComponent:m_,itemComponent:u_})),d&&it.createElement(Ze,{marginTop:1},d.loading&&it.createElement(et,{color:d.color},it.createElement(bt,{type:"dots"})," "),it.createElement(et,{color:d.color},d.text)))}let b=null;const E=m,T=m+v,P=f.slice(E,T),M=f.length>v;return it.createElement(RO,{title:"Manage MCP servers",hint:0===n.length?"Esc to close":"↑↓ navigate · Enter to select · Esc to close"},it.createElement(et,{color:LR.DIM},n.length," ",1===n.length?"server":"servers"),0===n.length?it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(et,{color:LR.DIM},"No MCP servers configured."),it.createElement(et,{color:LR.DIM},'Use "',getBinaryCommand(),' mcp add" to add a server.'),it.createElement(yL,{url:"https://commandcode.ai/docs/mcp",text:"View MCP Docs ↗",color:LR.CYAN,dimColor:!0})):it.createElement(Ze,{marginTop:1,flexDirection:"column"},P.map((e,t)=>{const n=E+t,r=e.scope!==b;b=e.scope;const o=n===a;return it.createElement(it.Fragment,{key:e.name},r&&it.createElement(Ze,{marginTop:0===t?0:1},it.createElement(et,{bold:!0},getMcpManagerScopeLabel(e.scope)),it.createElement(et,{color:LR.DIM}," ","(",getMcpManagerScopePath(e.scope),")")),it.createElement(Ze,null,it.createElement(et,{color:o?LR.WHITE:void 0,backgroundColor:o?tL:void 0,bold:o},e.name),it.createElement(et,{color:LR.DIM,backgroundColor:o?tL:void 0}," · "),VF(e.status,o?tL:void 0),it.createElement(et,{color:getStatusTextColor(e.status),backgroundColor:o?tL:void 0}," ",getMcpManagerStatusText(e)," ")))})),M&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",E+1,"–",Math.min(T,f.length)," of"," ",f.length,E>0?" · ↑ more":"",T<f.length?" · ↓ more":"")),d&&it.createElement(Ze,{marginTop:1},d.loading&&it.createElement(et,{color:d.color},it.createElement(bt,{type:"dots"})," "),it.createElement(et,{color:d.color},d.text)))},"McpManager");Vt(),PR();var KF=__name(({onClose:e})=>{const[t,n]=ct([]),[r,o]=ct(0),[s,a]=ct(!0),[i,l]=ct(null);ut(()=>{__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(ot((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 it.createElement(RO,{title:"Select memory to edit:"},it.createElement(et,{color:LR.DIM},"Loading memory files..."));if(i)return it.createElement(RO,{title:"Select memory to edit:"},it.createElement(et,{color:LR.RED},ft.cross," ",i));const u=projectMemorySelectorOptions(d);return it.createElement(RO,{title:"Select memory to edit:",hint:"↑/↓ to navigate · enter to edit · esc to cancel"},it.createElement(Ze,{columnGap:4},it.createElement(Ze,{flexDirection:"column"},u.map((e,t)=>it.createElement(Ze,{key:e.label},it.createElement(s_,{isSelected:r===t}),it.createElement(a_,{isSelected:r===t,idleColor:IO}," ",e.label)))),it.createElement(Ze,{flexDirection:"column"},u.map((e,t)=>it.createElement(a_,{key:e.label,isSelected:r===t,idleColor:IO},e.description)))))},"MemorySelector");function linkImageTokens(e,t){if(!t)return e;const n=new RegExp(EM.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)?LR.DIM:LR.RED,s=r?getSpecialUserMessageContent({content:e,billingUrl:cs}):linkImageTokens(e,n);return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{backgroundColor:r?void 0:GR.BG,paddingRight:1},it.createElement(et,{color:r?o:GR.POINTER,bold:!r},ft.pointer),it.createElement(Ze,{marginLeft:1},it.createElement(et,{color:r?o:GR.FG,wrap:"wrap"},s))),t&&!r&&it.createElement(Ze,{marginLeft:2},it.createElement(et,{color:eL},TL),it.createElement(et,{color:LR.DIM}," ","Selected ",t.lines," ",1===t.lines?"line":"lines"," from"," ",t.file," in ",t.ide)))}Vt(),PR(),Vt(),PR(),__name(linkImageTokens,"linkImageTokens"),__name(UserMessage,"UserMessage");var qF=ft.squareSmallFilled;function goalStatusGlyph(e){return"completed"===e?ft.tick:"paused"===e?"⏸":"idle"===e?ft.circle:qF}function goalStatusHeadColor(e){return"completed"===e?LR.GREEN:"paused"===e?LR.YELLOW:LR.DIM}function goalNoticeGlyph(e){return"cleared"===e?ft.tick:"none"===e?ft.circle:"paused"===e?"⏸":qF}function AutoCompactMessage({content:e}){return it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},qF," ",e))}function ZdrPausedMessage(){return it.createElement(Ze,{marginTop:1,marginBottom:1},it.createElement(et,null,it.createElement(et,{color:LR.DIM},qF," "),it.createElement(et,{color:LR.DIM},"Per-task model overrides reverted to ZDR safe defaults. Run"," "),it.createElement(et,{color:QR.CODE},"/config"),it.createElement(et,{color:LR.DIM}," to review · esc to dismiss")))}function ModelNoticeMessage({text:e}){return it.createElement(Ze,{marginTop:1,marginBottom:1},it.createElement(et,null,it.createElement(et,{color:LR.DIM},qF," "),it.createElement(et,{color:LR.DIM},e),it.createElement(et,{color:LR.DIM}," · esc to dismiss")))}function TasteSkipMessage(){return it.createElement(Ze,{marginTop:1,marginBottom:1},it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:DR.BADGE_BG,color:DR.BADGE_FG,bold:!0},xL)),it.createElement(et,{color:LR.DIM}," Skipped. Run "),it.createElement(et,{color:QR.CODE},"/learn-taste"),it.createElement(et,{color:LR.DIM}," or "),it.createElement(et,{color:QR.CODE},"cmd learn-taste"),it.createElement(et,{color:LR.DIM}," anytime."))}function TasteNoticeMessage({notice:e}){const t=e.path?`${tasteDirForRoot({projectRoot:process.cwd()})}/${e.path}`:null;return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:DR.BADGE_BG,color:DR.BADGE_FG,bold:!0},xL)),it.createElement(et,{color:DR.TEXT}," ",e.label)),it.createElement(Ze,{columnGap:1,marginLeft:1},it.createElement(et,{color:eL},TL),it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{wrap:"wrap"},e.text,e.confidence&&it.createElement(et,{color:LR.DIM},` [Confidence ${e.confidence}]`)))),e.path&&t&&it.createElement(Ze,{marginLeft:3},it.createElement(yL,{url:fileUrl(t),text:e.path,color:LR.DIM})))}function SkillLoadedMessage({name:e}){return it.createElement(Ze,null,it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:FR.BG,color:FR.FG,bold:!0},`${ML}SKILL${ML}`)),it.createElement(et,null," ",e),it.createElement(et,{color:LR.DIM}," loaded"))}function HookWarningMessage({content:e}){return it.createElement(Ze,null,it.createElement(et,{color:LR.YELLOW},ft.warning),it.createElement(Ze,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.YELLOW},e)))}function HookLineMessage({content:e}){return it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},` ${e}`))}function HookLineContinuationMessage({content:e}){return it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},` ${e}`))}function HookFrameMessage({lines:e,header:t}){return it.createElement(Ze,{flexDirection:"column"},void 0!==t&&it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},` ${t}`)),e.map((e,t)=>it.createElement(Ze,{key:t,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},e.primary?` └ ${e.text}`:` ${e.text}`))))}function GoalLineMessage({content:e,subline:t}){return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:eL},TL),it.createElement(et,{color:LR.DIM,wrap:"wrap"}," ",e)),t?it.createElement(Ze,{marginLeft:4,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM,wrap:"wrap"},t)):null)}function GoalAcceptMessage({command:e,acceptLine:t,hint:n}){return it.createElement(Ze,{flexDirection:"column"},it.createElement(UserMessage,{content:e}),it.createElement(GoalLineMessage,{content:t,subline:n}))}function GoalCompleteMessage({elapsed:e,turns:t,goal:n}){const r=`${t} ${1===t?"turn":"turns"}`;return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,null,it.createElement(et,{color:LR.GREEN},ft.tick," Goal achieved"),it.createElement(et,{color:LR.DIM},` (${e} · ${r})`))),it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.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 it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:a},s," ",t)),it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM,wrap:"wrap"},n)),r?it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM,wrap:"wrap"},r)):null,o?it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},o)):null)}function BranchResultMessage({title:e}){return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},e?it.createElement(et,null,it.createElement(et,{color:LR.GREEN},"⑂ Forked."),it.createElement(et,null," You're now in "),it.createElement(et,{bold:!0},'"',e,'"')):it.createElement(et,null,it.createElement(et,{color:LR.GREEN},"⑂ Forked."),it.createElement(et,null," You're now in the new session"))),it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},"Original session saved · /resume to switch back")))}function SessionFileMessage({sessionId:e,fileLine:t}){return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},qF," Session ID: "),it.createElement(et,null,e)),it.createElement(Ze,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:eL},TL," "),it.createElement(et,{color:LR.DIM,wrap:"wrap"},t)))}function InfoMessage({content:e,metadata:t}){if(t?.isTasteSkip)return it.createElement(TasteSkipMessage,null);if(t?.tasteNotice)return it.createElement(TasteNoticeMessage,{notice:t.tasteNotice});if(t?.skillLoaded)return it.createElement(SkillLoadedMessage,{name:t.skillLoaded.name});if(t?.isAutoCompact)return it.createElement(AutoCompactMessage,{content:e});if(t?.hookFrame&&t.hookFrame.length>0)return it.createElement(HookFrameMessage,{lines:t.hookFrame,header:t.hookFrameHeader});if(t?.isHookLine)return it.createElement(HookLineMessage,{content:e});if(t?.isHookLineContinuation)return it.createElement(HookLineContinuationMessage,{content:e});if(t?.isHookWarning)return it.createElement(HookWarningMessage,{content:e});if(t?.isSuccess)return it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.GREEN},ft.tick," ",e));if(t?.isGoalAccept)return it.createElement(GoalAcceptMessage,{command:e,acceptLine:t.goalAcceptLine??"",hint:t.goalSubline});if(t?.isGoalComplete)return it.createElement(GoalCompleteMessage,{elapsed:t.goalElapsed??"",turns:t.goalTurns??1,goal:t.goalText??""});if(t?.isGoalStatus)return it.createElement(GoalStatusMessage,{state:t.goalState??"running",headline:t.goalHeadline??"",goal:t.goalText??"",detail:t.goalDetail,hint:t.goalSubline});if(t?.isBranchResult)return it.createElement(BranchResultMessage,{title:t.branchTitle});if(t?.isSessionFile)return it.createElement(SessionFileMessage,{sessionId:t.sessionFileId??"",fileLine:t.sessionFileLine??""});if(t?.isGoalNotice){const n=goalNoticeGlyph(t.goalNoticeKind);return it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},n," ",e))}return t?.isGoalLine?it.createElement(GoalLineMessage,{content:e,subline:t.goalSubline}):it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM},qF," ",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"),Vt(),PR(),Vt(),Vt(),Vt(),Vt();var YF=/\[\^[^\]]+\]/;function splitMarkdownBlocks(e){return e?YF.test(e)?[e]:wt.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"),Vt();var QF=String.fromCharCode(8203),JF=new Set(["_","~","*","`"]),XF=/!?\[[^\]]*\]\([^)]*$/,ZF=/!?\[[^\]]*$/;function isSpace(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function isOnlyMarkersOrSpace(e){for(const t of e)if(!isSpace(t)&&!JF.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(XF);if(void 0!==t?.index)return e.slice(0,t.index).trimEnd();const n=e.match(ZF);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}${QF}`: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 eU=Tt()?"⠶":"#";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 it.createElement(Ze,null,n?it.createElement(Ze,{width:2,flexShrink:0}):it.createElement(et,{color:VR},eU),it.createElement(Ze,{marginLeft:n?0:1,flexGrow:1,flexShrink:1,minWidth:0,flexDirection:"column"},it.createElement(Markdown,{maxPhysicalRows:t?streamingMaxRows(r):void 0},o)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o=LR.GREEN,s=ft.tick,a="default",i=t||"(No output)";n&&(o=LR.YELLOW,s=ft.arrowRight,a=LR.YELLOW,i="Executing…"),r&&(o=LR.RED,s=ft.cross,a=LR.RED);const l=mt(()=>buildTreeConnectors(i),[i]);return it.createElement(Ze,null,it.createElement(et,{color:o},s),it.createElement(Ze,{flexDirection:"column",marginLeft:1},it.createElement(Ze,null,it.createElement(et,{color:LR.GRAY},"$ "),it.createElement(et,{color:o,bold:!0},e)),it.createElement(Ze,{columnGap:1,marginLeft:1},it.createElement(et,{color:eL},l),it.createElement(et,{color:a,wrap:"wrap"},i))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?LR.YELLOW:void 0,o=mt(()=>buildTreeConnectors(e),[e]);return it.createElement(Ze,{flexDirection:"column",marginBottom:0,marginTop:-1},it.createElement(Ze,{columnGap:1},it.createElement(et,{color:eL},o),it.createElement(Ze,{flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:r},e))),t&&it.createElement(Ze,{marginLeft:3},it.createElement(et,{color:LR.DIM},"See ",t)))}function ErrorMessage({content:e}){return isInterruptedByUserMessage(e)?it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},ft.pointer),it.createElement(Ze,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(et,{color:LR.DIM,wrap:"wrap"},sS))):it.createElement(Ze,null,it.createElement(et,{color:LR.RED},ft.warning),it.createElement(Ze,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},it.createElement(Markdown,{color:LR.RED},e)))}__name(streamingMaxRows,"streamingMaxRows"),__name(AssistantMessage,"AssistantMessage"),Vt(),__name(BashMessage,"BashMessage"),Vt(),__name(CommandResultMessage,"CommandResultMessage"),Vt(),PR(),__name(ErrorMessage,"ErrorMessage"),Vt(),PR();var tU={connected:{char:ft.tick,color:LR.GREEN},installed:{char:ft.tick,color:LR.GREEN},up_to_date:{char:ft.tick,color:LR.GREEN},needs_reload:{char:ft.circle,color:LR.YELLOW},failed:{char:ft.cross,color:LR.RED},not_in_ide:{char:ft.circle,color:LR.YELLOW}};function IDEStatusMessage({status:e,ide:t,details:n}){const{prefix:r,ide:o,suffix:s}=getIDESetupStatusHeadline(e,t),a=tU[e];return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,null,it.createElement(et,{color:a.color},a.char),it.createElement(et,null," ",r),o&&it.createElement(et,{color:LR.CYAN},o),s&&it.createElement(et,null,s))),n?.map(e=>it.createElement(et,{key:e,color:LR.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:Fe});return it.createElement(Ze,{flexDirection:"column",width:"90%"},it.createElement(Ze,null,it.createElement(et,{color:$R},"✻"," "),it.createElement(et,{color:$R},o.showExpandHint?`${o.headerLabel} `:o.headerLabel),o.showExpandHint&&it.createElement(BracketWrap,{color:LR.DIM},o.expandHint)),o.showBody&&o.hiddenAboveLabel&&it.createElement(Ze,{marginLeft:2},it.createElement(et,{color:LR.DIM},o.hiddenAboveLabel)),o.showBody&&it.createElement(Ze,{marginLeft:2,flexDirection:"column"},it.createElement(et,{color:$R,wrap:"wrap",italic:!0},o.bodyText)))}__name(IDEStatusMessage,"IDEStatusMessage"),Vt(),PR(),__name(reasoningBodyColumns,"reasoningBodyColumns"),__name(ReasoningMessage,"ReasoningMessage"),Vt(),PR(),Vt(),PR();function HelpMessage(){const e=getInvokedCommandName(),t=mt(()=>getVisibleSlashCommands(),[]);return it.createElement(Ze,{flexDirection:"column",paddingY:1},it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(Ze,null,it.createElement(et,{bold:!0},"Command Code"),it.createElement(et,{color:LR.GRAY}," v","1.72.3")),it.createElement(et,{color:LR.GRAY},va)),it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{bold:!0},"Usage"),it.createElement(Ze,{paddingLeft:2},it.createElement(et,null,e," <command> [options]"))),it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{bold:!0},"Options"),it.createElement(Ze,{flexDirection:"column",paddingLeft:2},Pa.map(t=>it.createElement(Ze,{key:t.key},it.createElement(et,null,t.key.replace(/^cmd/,e).padEnd(ka)),it.createElement(et,{color:LR.GRAY},t.description))))),it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{bold:!0},"Commands"),it.createElement(Ze,{flexDirection:"column",paddingLeft:2},xa.map(t=>it.createElement(Ze,{key:t.key},it.createElement(et,null,t.key.replace(/^cmd/,e).padEnd(ka)),it.createElement(et,{color:LR.GRAY},t.description))))),it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{bold:!0},"Slash Commands"),it.createElement(Ze,{flexDirection:"column",paddingLeft:2},t.map(e=>it.createElement(Ze,{key:e.key},it.createElement(et,null,e.key.padEnd(ka)),it.createElement(et,{color:LR.GRAY},e.description))))),it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{bold:!0},"Keyboard Shortcuts"),it.createElement(Ze,{flexDirection:"column",paddingLeft:2},Ta.map(e=>it.createElement(Ze,{key:e.key},it.createElement(et,null,e.key.padEnd(ka)),it.createElement(et,{color:LR.GRAY},e.description))))),it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(et,{bold:!0},"Examples"),it.createElement(Ze,{flexDirection:"column",paddingLeft:2},Aa.map(t=>it.createElement(Ze,{key:t.key},it.createElement(et,null,t.key.replace(/^cmd/,e).padEnd(ka)),it.createElement(et,{color:LR.GRAY},t.description))))),it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.CYAN},ft.pointer),it.createElement(et,{color:LR.GRAY}," ",Ca.replace(/cmd/,e))),it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{bold:!0},"Links"),it.createElement(Ze,{flexDirection:"column",paddingLeft:2},Ia.map(e=>it.createElement(Ze,{key:e.key},it.createElement(et,null,e.key.padEnd(ka)),it.createElement(et,{color:LR.CYAN},e.description))))))}function SystemMessage({content:e}){return isHelpSystemEntryContent(e)?it.createElement(HelpMessage,null):it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{wrap:"wrap"},it.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 it.createElement(UserMessage,{content:e.input,ideHint:t,imageTokenPaths:n})}return"assistant"===e.role?it.createElement(AssistantMessage,{content:e.input,isStreaming:"running"===e.metadata?.status,continuation:!0===e.metadata?.continuation}):"reasoning"===e.role?it.createElement(ReasoningMessage,{content:e.input,expandedOutput:t,expandKey:"ctrl",isStreaming:"running"===e.metadata?.status}):"tool"===e.role?it.createElement(ToolMessage,{name:Dh(e.name||""),input:e.input,output:e.output||"",isPending:Ah(e),hasError:Ih(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?it.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:Ah(e),hasError:Ih(e)}):"system"===e.role?it.createElement(SystemMessage,{content:e.input}):"info"===e.role?it.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?it.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?it.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?it.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 nU=__name(e=>getModelShortName({modelId:e,findModelById:findModelById}),"getModelShortName");function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages [${BE?"ctrl+y":"ctrl+e"} to expand more] `,r=Math.max(0,Math.floor((t-n.length)/2)),o="─".repeat(r);return it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:HR},o),it.createElement(BracketedText,{text:n,color:HR}),it.createElement(et,{color:HR},o))}__name(TranscriptDivider,"TranscriptDivider");var rU=it.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=mt(()=>cO(d),[d]),m=mt(()=>gO(d),[d]),p=mt(()=>getPackageJson(import.meta.url).version||"0.0.0",[]),g=mt(()=>getGitHeaderInfo(),[]),h=__name(e=>isSandboxMode()?`(base: ${e})`:`(branch: ${e})`,"branchLabel"),f=mt(()=>{if(isSandboxMode())return"cloud sandbox";const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),y=o?nU(o):"sonnet-4.6",S=Boolean(o&&byokProviderId({model:o}))||isSandboxMode()?"":" · taste-1",w=isSandboxMode()?"model":"models",v=mt(()=>{if(!o)return"";if(!modelSupportsReasoningEffort(o))return"";const e=null===s?getReasoningEffort(o):s;return e?` with ${e} effort`:""},[s,o,n]),k=mt(()=>{const e=o?byokProviderId({model:o}):void 0;return e?` · ${e} (byok)`:a&&a!==fo.COMMAND?` · ${getProviderShortName(a)} (byok)`:""},[o,a,n]);return it.createElement(tt,{items:c,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return it.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:d});if("header"===e)return"compact"===m?it.createElement(Ze,{key:"header",marginBottom:1,flexDirection:"row"},it.createElement(Ze,{width:mO,flexShrink:0},it.createElement(nL,null,uO)),it.createElement(Ze,{flexDirection:"column",marginLeft:2},it.createElement(Ze,null,it.createElement(et,{bold:!0},"Command Code"),it.createElement(et,{color:HR}," ","v",p)),it.createElement(et,{color:HR},w,": ",y,v,S,k),it.createElement(et,{color:HR},f,g&&g.isLocal&&g.branch&&` (${g.branch})`))):it.createElement(Ze,{key:"header",marginBottom:1,flexDirection:"column"},it.createElement(nL,null,u.trimEnd()),it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(Ze,null,it.createElement(et,{color:HR},"# "),it.createElement(et,{bold:!0},"Command Code"),it.createElement(et,{color:HR}," v",p)),it.createElement(et,{color:HR},"# ",w,": ",y,v,S,k),it.createElement(Ze,null,it.createElement(et,{color:HR},"# ",f,g&&g.isLocal&&g.branch&&it.createElement(et,{color:HR}," ",h(g.branch))))));const t=e,n=renderFeedEntry(t,r);return it.createElement(Ze,{key:t.id,paddingBottom:1,width:"90%"},n)})});Vt(),PR();var oU=lt(__name(function LiveAgentStatusInner2({entry:e}){const t=Dh(e.name||"Agent"),n=summarizeAgentTaskInput(e.input||""),r=e.metadata?.tokensUsed||0,o=e.metadata?.elapsedSeconds||0,s=e.metadata?.recentTools||[],[a,i]=ct(".");return ut(()=>{const e=setInterval(()=>{i(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),it.createElement(Ze,{flexDirection:"column",marginBottom:1,width:"90%"},it.createElement(Ze,null,it.createElement(et,{backgroundColor:jR.BG,color:jR.FG,bold:!0},` ${t} `),n&&it.createElement(et,null," (",n,")")),it.createElement(Ze,{columnGap:1,marginLeft:1},it.createElement(et,null,"⎿"," "),it.createElement(et,{color:LR.GRAY},"Running (",formatTime3(o)," |"," ",formatTokens(r),")",a)),s.length>0&&it.createElement(Ze,{flexDirection:"column",marginLeft:1},s.map((e,t)=>{const n=Dh(e.name);return it.createElement(Ze,{key:t,columnGap:1},it.createElement(et,{color:LR.GRAY},"⎿"),it.createElement(et,{color:LR.GRAY}," ",n),e.input&&it.createElement(et,{color:LR.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),sU=lt(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:it.createElement(oU,{entry:e})},"LiveAgentStatus"));Vt(),Vt(),PR();var aU=[],iU=aU,lU=!1,cU=null,dU="",uU=new Set,mU=new Set,pU=new Set;function shapeOf(e){return e.map(e=>e.content.replace(/\d+/g,"#")).join("\0")}function emit2(){for(const e of pU)e()}function cancelPeek(){cU&&clearTimeout(cU),cU=null,lU=!1}function armPeek(){cU&&clearTimeout(cU),lU=!0,cU=setTimeout(()=>{cU=null,lU=!1,emit2()},5e3),cU.unref?.()}function projectUserEdits(e){return e.filter(e=>!uU.has(e.content)).map(e=>"completed"!==e.status&&mU.has(e.content)?{...e,status:"completed"}:e)}function setSessionTodos(e){const t=projectUserEdits(e);if(t.length>0&&mU.size>0&&t.every(e=>"completed"===e.status))return void clearSessionTodos();const n=shapeOf(t),r=n!==dU;(r||JSON.stringify(t)!==JSON.stringify(iU))&&(iU=t.length>0?t:aU,dU=n,iU.length>0&&r&&armPeek(),emit2())}function adoptSettled(e){iU=e.length>0?[...e]:aU,dU=shapeOf(iU),cancelPeek(),emit2()}function seedSessionTodos(e){uU.clear(),mU.clear(),adoptSettled(e)}function removeSessionTodoAt(e){const t=iU[e];return t&&uU.add(t.content),adoptSettled(iU.filter((t,n)=>n!==e)),iU}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?jh(r):null;if(o){if(o.every(e=>"completed"===e.status))break;return seedSessionTodos(o),iU}}return clearSessionTodos(),aU}function clearSessionTodos(){(iU!==aU||lU||0!==uU.size||0!==mU.size)&&(iU=aU,dU="",uU.clear(),mU.clear(),cancelPeek(),emit2())}function getSessionTodos(){return iU}function isTodoPanelCollapsed(){return!lU}function completeSessionTodoAt(e){const t=iU[e];return t&&mU.add(t.content),adoptSettled(iU.map((t,n)=>n===e?{...t,status:"completed"}:t)),iU}function completeAllSessionTodos(){const e=iU.map(e=>e.content);for(const t of e)mU.add(t);return adoptSettled(aU),e}function subscribe(e){return pU.add(e),()=>pU.delete(e)}function useSessionTodos(){return ht(subscribe,getSessionTodos)}function useTodoPanelCollapsed(){return ht(subscribe,isTodoPanelCollapsed)}function usePausedLabel(e){const[t,n]=ct(!e);return ut(()=>{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 it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(Ze,null,it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:FR.BG,color:FR.FG,bold:!0},`${ML}TODOS${ML}`)),it.createElement(Ze,{flexShrink:0},it.createElement(et,null," ",it.createElement(BracketWrap,null,s))),a&&it.createElement(Ze,{flexShrink:1,minWidth:0},it.createElement(et,{color:r?LR.DIM:BR.IN_PROGRESS,bold:!r,wrap:"truncate-end"},` ${a}${r?" (paused)":""}`)),it.createElement(Ze,{flexShrink:0},it.createElement(et,null," ",it.createElement(BracketWrap,{color:LR.DIM},n?"ctrl+x to expand":"ctrl+x to manage")))),!n&&it.createElement(CappedChecklist,{todos:t}))}function CappedChecklist({todos:e}){const{foldedDone:t,visible:n,hiddenTail:r}=projectVisibleTodos(e);return it.createElement(Ze,{flexDirection:"column"},t>0&&it.createElement(Ze,{flexDirection:"row"},it.createElement(Ze,{width:2},it.createElement(et,{color:BR.SUCCESS},ft.checkboxOn)),it.createElement(et,{color:BR.SUCCESS,strikethrough:!0},t," completed")),it.createElement(TodoChecklist,{todos:n}),r>0&&it.createElement(et,{color:LR.DIM},` … +${r} more`))}function projectTasteFeedVisibility(e){return e.showTasteLearningInFeed?[...e.feed]:e.feed.filter(e=>void 0===e.metadata?.tasteNotice)}__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"),Vt(),__name(projectTasteFeedVisibility,"projectTasteFeedVisibility"),Vt();var gU=new Set,hU=!1;function isTodosManagerOpen(){return hU}function requestTodosManagerOpen(){for(const e of gU)e()}function statusColor(e){return"completed"===e?LR.GREEN:"in_progress"===e?LR.CYAN:LR.WHITE}function TodoRow({todo:e,selected:t}){const n="completed"===e.status?ft.checkboxOn:ft.checkboxOff,r=t?tL:void 0;return it.createElement(Ze,null,it.createElement(s_,{isSelected:t,backgroundColor:r}),it.createElement(et,{color:statusColor(e.status),backgroundColor:r}," ",n),it.createElement(et,{color:t?MO:statusColor(e.status),strikethrough:"completed"===e.status,backgroundColor:r,wrap:"truncate-end"}," ",e.content),"in_progress"===e.status&&it.createElement(et,{color:LR.DIM,backgroundColor:r}," ","(in progress)"))}function TodosManagerPanel({sessionId:e,onExpandedChange:t}){const n=useSessionTodos(),[r,o]=ct(!1),[s,a]=ct(0);ut(()=>(hU=r,t?.(r),()=>{hU=!1,t?.(!1)}),[r,t]),ut(()=>{const e=__name(()=>{a(0),o(!0)},"listener");return gU.add(e),()=>{gU.delete(e)}},[]),ut(()=>{if(0===n.length)return o(!1),void a(0);a(e=>Math.min(e,n.length-1))},[n.length]);const i=__name(t=>{I$(e)?.applyTodoUserEdit(t)},"syncHarness");if(ot((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 it.createElement(RO,{title:"Todos",subtitle:l>0?`${n.length} items · ${l} done`:`${n.length} items`,gapAfterHeader:!1,boxProps:{marginTop:1,marginBottom:1}},it.createElement(Ze,{flexDirection:"column",marginTop:1},n.map((e,t)=>it.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"),Vt(),PR(),PR();var fU=__name(({currentModel:e,onClose:t,refreshBanner:n,sessionId:r})=>{const o=customReasoningEfforts(e)??getSupportedEfforts(e)??[],s=findModelById(e)?.label??getModelDisplayName(e),a=dt(!1),i=__name(o=>{if(a.current)return;a.current=!0;const s=o!==getReasoningEffort(e);(async()=>{try{if(s){const t=await tellSandboxEffort({effort:o});if(!t.ok)return void dlog(`[Effort] ${t.message}`);await setReasoningEffort({modelId:e,effort:o}),n(),void 0!==o&&r&&I$(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 it.createElement(V_,{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})}Vt(),PR(),Vt(),PR(),__name(store,"store"),__name(getCustomProviderKeyState,"getCustomProviderKeyState"),__name(getConfiguredKeyReference,"getConfiguredKeyReference"),__name(storeCustomProviderKey,"storeCustomProviderKey"),__name(getStoredKeyPreview,"getStoredKeyPreview"),__name(getStoredKeyToken,"getStoredKeyToken"),__name(clearCustomProviderKey,"clearCustomProviderKey"),Vt(),PR(),Vt();var yU={"@ai-sdk/openai":"openai-responses","@ai-sdk/anthropic":"anthropic-messages","@ai-sdk/openai-compatible":"openai-completions"};function modelOverrides(e){if(!isPlainObject8(e))return{};const t=e.provider;if(!isPlainObject8(t))return{};if("string"!=typeof t.npm)return{};const n=yU[t.npm];if(void 0===n)return;const r="string"==typeof t.api&&t.api.startsWith("https://")&&!t.api.includes("${")?t.api.replace(/\/+$/,""):void 0;return{api:n,...void 0!==r?{baseURL:r}:{}}}function cachePath(){return n(H(),".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 ae(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 ee(r(t),{recursive:!0}),await q(t,JSON.stringify({fetchedAt:Date.now(),data:e}))}catch{}}async function fetchCatalog(e){const t=new AbortController,n=setTimeout(()=>t.abort(),6e3);try{const n=await e("https://models.dev/api.json",{headers:{accept:"application/json"},signal:t.signal});if(!n.ok)return null;const r=await n.json();return isPlainObject8(r)?r:null}catch{return null}finally{clearTimeout(n)}}async function loadCatalog(e){const t=await readCache();if(t?.fresh)return t.data;const n=await fetchCatalog(e);return n?(await writeCache(n),n):t?.data??null}function asPositive(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}function urlParts(e){try{const t=new URL(e);return{host:t.hostname.toLowerCase(),path:t.pathname.replace(/\/+$/,"")||"/"}}catch{return}}function recordContains(e,t){if(e===t)return!0;const n="/"===e?"/":`${e}/`;return t.startsWith(n)}function curateModels(e){return isPlainObject8(e)?Object.entries(e).filter(e=>isPlainObject8(e[1])).filter(([,e])=>"deprecated"!==e.status).filter(([,e])=>{const t=isPlainObject8(e.modalities)?e.modalities.output:void 0;return!Array.isArray(t)||t.includes("text")}).sort(([,e],[,t])=>String(t.release_date??"").localeCompare(String(e.release_date??""))).flatMap(([e,t])=>{const n=modelOverrides(t);if(void 0===n)return[];const r=isPlainObject8(t.limit)?t.limit:void 0;return{id:e,...n,..."string"==typeof t.name&&t.name?{name:t.name}:{},...void 0!==asPositive(r?.context)?{contextWindow:asPositive(r?.context)}:{},...void 0!==asPositive(r?.output)?{maxOutput:asPositive(r?.output)}:{}}}):[]}__name(modelOverrides,"modelOverrides"),__name(cachePath,"cachePath"),__name(isPlainObject8,"isPlainObject"),__name(readCache,"readCache"),__name(writeCache,"writeCache"),__name(fetchCatalog,"fetchCatalog"),__name(loadCatalog,"loadCatalog"),__name(asPositive,"asPositive"),__name(urlParts,"urlParts"),__name(recordContains,"recordContains"),__name(curateModels,"curateModels");var SU=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(SU.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"),Vt();var wU=[{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}],vU=[{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"}],kU=/^[a-z0-9._-]+$/;function hostOf2(e){try{return new URL(e).hostname.toLowerCase()}catch{return}}function fallbackProviderSuggestions(){return[...vU,...wU]}async function loadProviderSuggestions(e){let t=[];try{t=await listModelsDevProviders(e?.fetchImpl?{fetchImpl:e.fetchImpl}:void 0)}catch{}const n=t.filter(e=>kU.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"),Vt();var CU=["/chat/completions","/completions","/responses","/messages","/models"];function normalizeEndpointInput(e){let t=e.trim().replace(/\/+$/,"");for(const e of CU)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=LR.DIM}){const t=`${H()}/.commandcode/providers.json`;return it.createElement(yL,{url:`file://${t}`,text:"~/.commandcode/providers.json",color:e})}function toNewProviderModels(e){return e.map(e=>({id:e.id,...e.name?{name:e.name}:{},...void 0!==e.contextWindow?{contextWindow:e.contextWindow}:{},...void 0!==e.maxOutput?{maxOutput:e.maxOutput}:{},...e.api?{api:e.api}:{},...e.baseURL?{baseURL:e.baseURL}:{}}))}function cardKeyLine(e){return"stored"===e.keyState?it.createElement(et,null,"key ",it.createElement(et,{color:LR.GREEN},e.keyPreview)," ",it.createElement(et,{color:LR.GREEN},"✓")," stored in auth.json",e.configuredReference?` · overrides ${e.configuredReference}`:""):"configured"===e.keyState?it.createElement(et,null,"key ",e.configuredReference??"set"):"keyless"===e.keyState?it.createElement(et,null,"no key — the endpoint asks for none"):it.createElement(et,{color:LR.YELLOW},"no key yet, requests fail until one is added")}function cardHints(e){const t=[it.createElement(it.Fragment,null,it.createElement(CO,null,"u")," update models"),it.createElement(it.Fragment,null,it.createElement(CO,null,"d")," delete"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," close")];return"stored"===e?[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," save"),it.createElement(it.Fragment,null,it.createElement(CO,null,"r")," replace key"),it.createElement(it.Fragment,null,it.createElement(CO,null,"c")," clear"),...t]:"missing"===e?[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," add key"),...t]:[it.createElement(it.Fragment,null,it.createElement(CO,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]=ct(""),[m,p]=ct("card"),[g,h]=ct(void 0),[f,y]=ct(!1),[S,w]=ct(void 0),[v,k]=ct(void 0);it.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");ot((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?it.createElement(it.Fragment,null,S.baseURL," · ",S.modelCount," ",1===S.modelCount?"model":"models"," · config:"," ",it.createElement(yL,{url:`file://${H()}/.commandcode/providers.json`,text:"providers.json",color:LR.DIM})):void 0;if("card"===m){const e=cardKeyLine({keyState:n,keyPreview:r,configuredReference:o}),s=cardHints(n);return it.createElement(RO,{title:t,titleSuffix:it.createElement(et,{color:LR.DIM}," (byok)"),subtitle:T,footer:it.createElement(bO,{hints:s,marginTop:0})},it.createElement(Ze,null,e))}return"confirm-remove"===m?it.createElement(RO,{title:`Remove ${t}?`,subtitle:"Its entry, models, and stored key go with it",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"y")," remove"),"any other key keeps it"]})},it.createElement(et,null,"Deletes the entry from ",it.createElement(ProvidersJsonLink,null)," and clears its stored key.")):"removing"===m||"updating-models"===m?it.createElement(RO,{title:t,rule:!1},it.createElement(et,null,"removing"===m?`Removing '${e}'…`:`Refetching models for '${e}'…`)):"removed"===m?it.createElement(RO,{title:`${t} removed`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," close")]})},it.createElement(et,{color:LR.DIM},"Provider deleted from ",it.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?it.createElement(RO,{title:t,subtitle:T,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," back"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," close")]})},it.createElement(et,{color:LR.GREEN},"Models updated — ",v?.count??0," declared from"," ",v?.source??"the refetch",".")):"saved"===m?it.createElement(RO,{title:`Key saved for ${t}`,subtitle:"Stored in ~/.commandcode/auth.json",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," pick a model"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," close")]})}):"cleared"===m?it.createElement(RO,{title:`Stored key cleared for ${t}`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," close")]})},it.createElement(et,{color:LR.DIM},"Its models stay listed",o?" — the providers.json key applies again":"; requests will need a key again")):"error"===m?it.createElement(RO,{title:`Could not update ${t}`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," close")]})},it.createElement(et,{color:LR.DIM},g??'Check that ~/.commandcode is writable, or set "apiKey" to a "$ENV_VAR" reference in providers.json')):it.createElement(RO,{title:`API key for ${t}`,subtitle:`Saved to ~/.commandcode/auth.json under '${e}'. requests go straight to this provider with your key`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," save"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," back")]})},it.createElement(Ze,{borderStyle:"single",borderColor:LR.YELLOW,paddingX:1,width:"100%"},it.createElement(et,{color:LR.DIM},"key: "),it.createElement(Ze,{flexGrow:1},it.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 it.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 it.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 bU=[{value:"openai-completions",label:"OpenAI-compatible",detail:"/chat/completions · Ollama, vLLM, LM Studio, most hosted APIs"},{value:"openai-responses",label:"OpenAI Responses",detail:"/responses · endpoints speaking the OpenAI Responses API"},{value:"anthropic-messages",label:"Anthropic wire",detail:"/v1/messages · endpoints speaking the Claude Messages API"}];function cycleWire(e){const t=bU.findIndex(t=>t.value===e.current),n=bU.length,r=((e.forward?t+1:t-1)+n)%n;return bU[r]?.value??e.current}__name(cycleWire,"cycleWire");var EU=[["{",""],[' "provider": {',""],[' "openrouter": {',"the id you typed"],[' "baseURL": "https://openrouter.ai/api/v1",',"API root, no route"],[' "apiKey": "$OPENROUTER_API_KEY",',"reference — never a raw key"],[' "models": { "openai/gpt-5.6": {} }',"edit anytime, reloads live"],[" }",""],[" }",""],["}",""]];function endpointSubtitle(e){return e.prefilledName?`Prefilled for ${e.prefilledName} — edit it or press enter to accept`:"anthropic-messages"===e.wire?"The Messages API root · /v1 is added on the wire when missing":"openai-responses"===e.wire?"The API root requests go to · /responses is added on the wire":"The API root requests go to · most end in /v1"}function endpointPlaceholder(e){return"anthropic-messages"===e?"https://api.example.com/anthropic":"openai-responses"===e?"https://api.example.com/v1":"http://localhost:11434/v1"}function idStepMatches(e){return"id"!==e.phase?[]:e.query.trim()?matchKnownProviders({query:e.query,providers:e.providers,limit:e.providers.length}):e.providers}function AddCustomProviderEntry({onClose:e,onOpenModels:t,sessionId:n}){const[r,o]=ct(""),[s,a]=ct("openai-completions"),[i,l]=ct(""),[c,d]=ct(""),[u,m]=ct(""),[p,g]=ct("id"),[h,f]=ct(()=>fallbackProviderSuggestions());it.useEffect(()=>{let e=!0;return loadProviderSuggestions().then(t=>{e&&t.length>0&&f(t)}),()=>{e=!1}},[]);const[y,S]=ct(void 0),[w,v]=ct(null),[k,C]=ct(void 0),[b,E]=ct(void 0),T=it.useRef(null),P=it.useRef("api"),M=it.useRef([]),[x,I]=ct(void 0),[A,R]=ct(0),[L,O]=ct(void 0),D=""===c.trim(),$=idStepMatches({phase:p,query:r,providers:h}),N=__name(e=>{M.current.push(p),g(e)},"goTo"),_=__name((e,t)=>{M.current.push(e),g(t)},"arriveFrom"),F=__name(()=>{const t=M.current.pop();C(void 0),E(void 0),t?g(t):e()},"goBack");ot((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=>cycleWire({current:e,forward:!0===o.downArrow})),void(o.return&&N("endpoint"))):"done"===p&&o.return?(e(),void t?.()):void("error"===p&&o.return&&e());(o.upArrow||o.downArrow)&&$.length>0&&v(e=>{const t=$.length-1;if(null===e)return o.downArrow?0:t;const n=e+(o.downArrow?1:-1);return n<0?t:n>t?0:n})}}else g(P.current)});const U=__name(()=>{const e=null===w?void 0:$[w];if(e)return getCustomProviderModelsSync().some(t=>t.id===e.id)?void C(`'${e.id}' already exists — select it in /connect to manage it.`):(C(void 0),o(e.id),S(e),a(e.wire),l(e.baseURL),v(null),void N("api"));const t=r.trim().toLowerCase();if(!t)return;if(!isValidProviderId(t))return void C("Lowercase letters, digits, dots, dashes and underscores only.");if(isReservedProviderId(t))return void C(`'${t}' is a built-in subscription lane — try '${t}-api'.`);if(getCustomProviderModelsSync().some(e=>e.id===t))return void C(`'${t}' already exists — select it in /connect to manage it.`);C(void 0),o(t);const n=findKnownProvider({id:t,providers:h});S(n),n&&(a(n.wire),l(n.baseURL)),N("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),N("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 O("The key could not be stored — check that ~/.commandcode is writable."),void g("error")}g("probing");const t=await T.current??null;t&&t.models.length>0?await G(t.models):await B()},"submitKey"),H=__name(()=>{const e=u.split(",").map(e=>e.trim()).filter(Boolean);0!==e.length&&G(e.map(e=>({id:e})))},"submitManualIds"),G=__name(async e=>{g("saving");try{await addUserProviderEntry({runtime:createNodeRuntime(),id:r,baseURL:i,api:s,keyless:D,models:toNewProviderModels(e)}),R(e.length),await refreshCustomProviderModels(n?{sessionId:n}:void 0),g("done")}catch(e){O(e instanceof Error?e.message:String(e)),g("error")}},"writeEntry"),V=k?it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.RED},k)):null,z=r.trim()?`Add a provider · ${r.trim().toLowerCase()}`:"Add a provider";if("saving"===p||"probing"===p)return it.createElement(RO,{title:z,rule:!1},it.createElement(et,null,"probing"===p?`Asking ${i} which models it serves…`:`Writing '${r}' to ~/.commandcode/providers.json…`));if("done"===p)return it.createElement(RO,{title:`'${r}' is set up`,subtitle:`${A} ${1===A?"model":"models"} declared${D?" · keyless endpoint":" · key stored in auth.json"}`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," pick a model"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," close")]})},it.createElement(et,{color:LR.DIM},"Provider added to ",it.createElement(ProvidersJsonLink,null),". Edit it anytime, it reloads live."));if("error"===p)return it.createElement(RO,{title:`Adding '${r}' didn't finish`,footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," close")]})},it.createElement(et,{color:LR.DIM},L));if("help"===p)return it.createElement(RO,{title:"Adding a provider: the short version",footer:it.createElement(Ze,{flexDirection:"column"},it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,"docs:"," ",it.createElement(yL,{url:"https://commandcode.ai/docs/byok",text:"commandcode.ai/docs/byok",color:LR.DIM})),"any key to go back"]}))},it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:LR.DIM},"• provider id names the entry in ",it.createElement(ProvidersJsonLink,null)," · models select as id/model"),it.createElement(et,{color:LR.DIM},"• endpoint is the base URL requests go to · most end in /v1"),it.createElement(et,{color:LR.DIM},"• pasted keys go to auth.json · providers.json only ever holds $ENV_VAR or !command references"),it.createElement(et,{color:LR.DIM},"• no key needed? press enter on the empty key field (local servers)"),it.createElement(et,{color:LR.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"),it.createElement(et,{color:LR.DIM},"• the ",it.createElement(ProvidersJsonLink,null)," file is yours · edit it anytime, it reloads live · manage it from /connect"),it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.DIM},"what it writes:"),EU.map(([e,t])=>it.createElement(et,{key:e},it.createElement(et,{color:LR.CYAN}," ",e),t?it.createElement(et,{color:LR.DIM}," ","// ",t):null)))));if("manual-models"===p)return it.createElement(RO,{title:z,subtitle:x?`Couldn't list models automatically — ${x}`:`Which models does ${r} serve?`,footer:it.createElement(bO,{marginTop:0,hints:["comma-separated, exact ids",it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," save"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," back")]})},it.createElement(Ze,{borderStyle:"single",borderColor:LR.YELLOW,paddingX:1,width:"100%"},it.createElement(et,{color:LR.DIM},"models: "),it.createElement(Ze,{flexGrow:1},it.createElement(TextInput,{value:u,onChange:m,onSubmit:H,placeholder:"llama3.3:70b, qwen2.5-coder:32b",showCursor:!0}))));if("key"===p)return it.createElement(RO,{title:z,subtitle:"Keys live in ~/.commandcode/auth.json, never in providers.json",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," save"),"empty enter = keyless (local servers)",it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," back")]})},it.createElement(Ze,{borderStyle:"single",borderColor:LR.YELLOW,paddingX:1,width:"100%"},it.createElement(et,{color:LR.DIM},"key: "),it.createElement(Ze,{flexGrow:1},it.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 it.createElement(RO,{title:z,subtitle:"What does the endpoint speak?",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"↑/↓")," switch"),it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," continue"),it.createElement(it.Fragment,null,it.createElement(CO,null,"h")," help"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," back")]})},it.createElement(Ze,{flexDirection:"column"},bU.map(e=>it.createElement(et,{key:e.value},s===e.value?"❯ ":" ",it.createElement(et,{bold:s===e.value},e.label),it.createElement(et,{color:LR.DIM}," · ",e.detail)))));if("endpoint"===p){const e=y&&i===y.baseURL;return it.createElement(RO,{title:z,subtitle:endpointSubtitle({prefilledName:e?y.name:void 0,wire:s}),footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," continue"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," back")]})},it.createElement(Ze,{borderStyle:"single",borderColor:LR.YELLOW,paddingX:1,width:"100%"},it.createElement(et,{color:LR.DIM},"base URL: "),it.createElement(Ze,{flexGrow:1},it.createElement(TextInput,{value:i,onChange:e=>{l(e),C(void 0),E(void 0)},onSubmit:j,placeholder:endpointPlaceholder(s),showCursor:!0}))),b&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.YELLOW},b)),V)}const K=null===w?0:Math.min(Math.max(0,w-6+1),Math.max(0,$.length-6)),q=$.slice(K,K+6),Y=$.length-(K+q.length);return it.createElement(RO,{title:"Add a provider",subtitle:"Pick a known provider below, or type your own id.",footer:it.createElement(bO,{marginTop:0,hints:[it.createElement(it.Fragment,null,it.createElement(CO,null,"↑/↓")," pick from the list"),it.createElement(it.Fragment,null,it.createElement(CO,null,"enter")," continue"),it.createElement(it.Fragment,null,it.createElement(CO,null,"esc")," close")]})},it.createElement(Ze,{borderStyle:"single",borderColor:LR.YELLOW,paddingX:1,width:"100%"},it.createElement(et,{color:LR.DIM},"provider id: "),it.createElement(Ze,{flexGrow:1},it.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&&it.createElement(Ze,{flexDirection:"column",marginTop:1},q.map((e,t)=>{const n=null!==w&&K+t===w;return it.createElement(Ze,{key:e.id},it.createElement(s_,{isSelected:n}),it.createElement(a_,{isSelected:n,idleColor:LR.DIM},` ${e.id}`),it.createElement(et,{color:LR.DIM}," ","· ",e.baseURL))}),(K>0||Y>0)&&it.createElement(et,{color:LR.DIM}," ",K>0?`↑ ${K} more · `:"",Y>0?`↓ ${Y} more`:"")))}__name(endpointSubtitle,"endpointSubtitle"),__name(endpointPlaceholder,"endpointPlaceholder"),__name(idStepMatches,"idStepMatches"),__name(AddCustomProviderEntry,"AddCustomProviderEntry"),Vt(),PR();var TU="__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},qM)}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===TU)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 PU=__name(({onSelect:e,onCancel:t,sessionId:n})=>{const[r,o]=it.useState(()=>getCustomProviderModelsSync()),[s,a]=it.useState(()=>getCustomProviderWarningsSync()),[i,l]=it.useState({});it.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]=it.useState({});it.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:TU,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 ot((e,n)=>{n.escape&&t()}),it.createElement(RO,{title:"Connect",subtitle:"Connect to AI providers and see currently connected providers",hint:"↑/↓ navigate · enter select · esc close"},it.createElement(SelectInput,{items:p.map(e=>({label:e.label,value:e.value})),onSelect:f,initialIndex:0,indicatorComponent:s_,itemComponent:({isSelected:e,label:t})=>{const n=h.get(t??"");return it.createElement(Ze,null,it.createElement(a_,{isSelected:e,...n?.notLive?{idleColor:LR.DIM}:{}},` ${(t??"").padEnd(g)}`,n?.status.startsWith("✓")?it.createElement(it.Fragment,null,it.createElement(et,{color:LR.GREEN},"✓"),n.status.slice(1)):n?.status??""))}}),s.length>0&&it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.YELLOW},it.createElement(ProvidersJsonLink,{color:LR.YELLOW})," needs attention —"," ",1===s.length?"one entry":"some entries"," ","did not load as written:"),s.slice(0,3).map(e=>it.createElement(et,{key:e,color:LR.DIM}," ",e)),s.length>3&&it.createElement(et,{color:LR.DIM}," ","… and"," ",s.length-3," more")))},"ProviderSelector");Vt(),PR();var MU=__name(e=>0===e?"No code changes":`${e} file${e>1?"s":""} changed`,"formatFileCountLabel"),xU=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=mt(()=>[...e].sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),[e]),[o,s]=ct(()=>Math.max(0,r.length-1)),[a,i]=ct(()=>Math.max(0,r.length-8)),[l,c]=ct("checkpoint"),[d,u]=ct(null),[m,p]=ct(0),g=mt(()=>hasCodeChangesToRestore({sortedCheckpoints:r,selectedCheckpoint:d}),[d,r]),h=mt(()=>g?Fx:Fx.filter(e=>"conversation"===e.mode),[g]);if(ut(()=>{if(r.length>0){const e=r.length-1;s(e),i(Math.max(0,r.length-8))}},[r.length,8]),ot((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 it.createElement(RO,{title:"Rewind",subtitle:"No checkpoints available. Start a conversation to create checkpoints.",gapAfterHeader:!1,footer:it.createElement(kO,null,"Press ",it.createElement(CO,null,"Esc")," to close")});if("mode"===l&&d)return it.createElement(RO,{title:"Rewind",subtitle:it.createElement(it.Fragment,null,"Restore to:"," ",it.createElement(et,{color:LR.WHITE},truncateString2({text:d.prompt||"checkpoint",maxChars:50}))),footer:it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to confirm ·"," ",it.createElement(CO,null,"Esc")," to go back")},it.createElement(Ze,{flexDirection:"column"},h.map((e,t)=>{const n=m===t,r=t===h.length-1;return it.createElement(Ze,{key:e.mode,flexDirection:"column"},it.createElement(Ze,{flexDirection:"row"},it.createElement(et,{color:n?OR:void 0},n?`${EL} `:" "),it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{color:n?OR:LR.WHITE},e.label),it.createElement(et,{color:LR.DIM},e.description))),!r&&it.createElement(et,null," "))})));const f=r.slice(a,a+8);return it.createElement(RO,{title:"Rewind",subtitle:"Select a checkpoint to restore your session",gapAfterHeader:!1,footer:it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to select ·"," ",it.createElement(CO,null,"Esc")," to cancel")},r.length>8&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",a+1,"-",Math.min(a+8,r.length)," ","of ",r.length)),it.createElement(Ze,{marginTop:1}),it.createElement(Ze,{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 it.createElement(Ze,{key:e.messageId,flexDirection:"column"},it.createElement(Ze,{flexDirection:"row"},it.createElement(et,{color:s?OR:void 0},s?`${EL} `:" "),it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,{color:s?OR:LR.WHITE},truncateString2({text:e.prompt||"(no prompt)",maxChars:60})),it.createElement(et,{color:LR.DIM}," • "),it.createElement(et,{color:LR.DIM},getRelativeTimeString({timestamp:e.createdAt}),c&&" (latest)")),it.createElement(et,{color:LR.DIM},MU(i)))),!l&&it.createElement(et,null," "))})))},"RewindSelector");Vt(),PR();var IU=["default","no-tools","user-only","labeled-only","all"],AU={default:"","no-tools":"[no-tools]","user-only":"[user]","labeled-only":"[labeled]",all:"[all]"};function nextFilterMode(e){const t=IU.indexOf(e);return IU[(t+1)%IU.length]}function previousFilterMode(e){const t=IU.indexOf(e);return IU[(t-1+IU.length)%IU.length]}function buildToolCallMap(e){const t=new Map,n=__name(e=>{for(const r of e){const{entry:e}=r;if("message"===e.type&&"assistant"===e.message.role)for(const n of e.message.content)"tool_use"===n.type&&t.set(n.id,{name:n.name,input:n.input});n(r.children)}},"visit");return n(e),t}function pathArgOf(e){const t=e.file_path??e.path;return"string"==typeof t?toRelativePath(t):"?"}function formatToolBracket(e){const{name:t,input:n}=e;if("read_file"===t){const e=pathArgOf(n),t=n.offset,r=n.limit;return"number"==typeof t&&"number"==typeof r?`[read: ${e}:${t}-${t+r}]`:`[read: ${e}]`}return"write_file"===t?`[write: ${pathArgOf(n)}]`:"edit_file"===t?`[edit: ${pathArgOf(n)}]`:"shell_command"===t?`[bash: ${truncateString2({text:"string"==typeof n.command?n.command:"",maxChars:50})}]`:"grep"===t?`[grep: /${"string"==typeof n.pattern?n.pattern:""}/ in ${"string"==typeof n.directory?toRelativePath(n.directory):"."}]`:"glob"===t?`[glob: ${"string"==typeof n.pattern?n.pattern:""}]`:"read_directory"===t?`[ls: ${pathArgOf(n)}]`:`[${t}: ${truncateString2({text:JSON.stringify(n),maxChars:40})}]`}function messageText5(e){return extractTextFromMessageContent({content:e.content})}function isToolResultOnlyUserMessage2(e){return"user"===e.role&&e.content.length>0&&e.content.every(e=>"tool_result"===e.type)}__name(nextFilterMode,"nextFilterMode"),__name(previousFilterMode,"previousFilterMode"),__name(buildToolCallMap,"buildToolCallMap"),__name(pathArgOf,"pathArgOf"),__name(formatToolBracket,"formatToolBracket"),__name(messageText5,"messageText"),__name(isToolResultOnlyUserMessage2,"isToolResultOnlyUserMessage");var RU=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:!RU.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:LR.DIM}}return{text:`user: ${normalizeRowText(messageText5(n))}`,color:LR.CYAN}}const r=messageText5(n).trim();return r?{text:`assistant: ${normalizeRowText(r)}`,color:LR.GREEN}:{text:"assistant: (no content)",color:LR.DIM}}return"compaction"===e.type?{text:`[compaction: ${Math.round(e.tokensBefore/1e3)}k tokens]`,color:LR.CYAN}:"branch_summary"===e.type?{text:`[branch summary]: ${normalizeRowText(e.summary)}`,color:LR.YELLOW}:"custom_message"===e.type?{text:`[${e.customType}]: ${normalizeRowText(extractTextFromMessageContent({content:e.content}))}`,color:LR.MAGENTA}:"custom"===e.type?{text:`[custom: ${e.customType}]`,color:LR.DIM}:"model_change"===e.type?{text:`[model: ${e.model}]`,color:LR.DIM}:"effort_change"===e.type?{text:`[effort: ${e.effort}]`,color:LR.DIM}:"label"===e.type?{text:`[label: ${e.label??"(cleared)"}]`,color:LR.DIM}:{text:e.name?`[title: ${e.name}]`:"[title: (empty)]",color:LR.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 LU={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=LU[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 OU=[{value:"none",label:"No summary"},{value:"summarize",label:"Summarize"},{value:"custom",label:"Summarize with custom prompt"}],DU=__name(({tree:e,currentLeafId:t,initialSelectedId:n,initialFilterMode:r,branchSummarySkipPrompt:o,onSelect:s,onAbortSummary:a,onCancel:i,onLabelChange:l})=>{const[c,d]=ct(r),[u,m]=ct(""),[p,g]=ct(()=>new Set),h=__name(e=>{d(e),g(new Set)},"applyFilterMode"),f=__name(e=>{h(t=>t===e?"default":e)},"toggleFilterMode"),[y,S]=ct(!1),[w,v]=ct("browse"),[k,C]=ct(""),[b,E]=ct(""),[T,P]=ct(0),[M,x]=ct(null),[I,A]=ct(0),[R,L]=ct(0),[O,D]=ct(n??t??void 0),$=useTerminalHeight(),N=mt(()=>{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]),_=mt(()=>buildToolCallMap(e),[e]),F=mt(()=>{const e=new Set;let n=t;for(;null!==n;){e.add(n);const t=N.get(n);n=t?t.parentId:null}return e},[N,t]),U=mt(()=>reorderActiveFirst(buildVisibleNodes({nodes:e,mode:c,currentLeafId:t}),t),[e,c,t]),{rows:j,visibleChildrenIds:B}=mt(()=>flattenVisibleTree({roots:U,activePathIds:F,foldedNodes:p}),[U,F,p]),W=mt(()=>new Map(j.map(e=>[e.id,e])),[j]),H=mt(()=>u?j.filter(e=>matchesSearch(searchableText({entry:e.entry,label:e.label,toolCallMap:_}),u)):j,[j,u,_]);ut(()=>{if(0===H.length)return void A(0);let e=O;for(;e;){const t=H.findIndex(t=>t.id===e);if(t>=0)return void A(t);e=N.get(e)?.parentId}A(H.length-1)},[H,c,u,N]);const G=H[I]?.id,V=dt(!1);ut(()=>{V.current?G&&D(G):V.current=!0},[G]);const z=$-1,K=Math.max(6,z-10);ut(()=>{L(e=>clampScrollOffset({cursor:I,total:H.length,maxVisible:K,currentOffset:e}))},[I,H.length,K]);const q=H[I],Y=__name(e=>{D(e.entryId),e.summarize?(v("summarizing"),s(e).then(e=>{e.aborted&&v("browse")})):s(e)},"commitSelection"),Q=__name(()=>{if(!q)return;D(q.id);const{targetId:e}=resolveTargetLocally({byId:N,entryId:q.id});isOnPathLocally({byId:N,ancestorId:t,targetId:e})||o?Y({entryId:q.id,summarize:!1}):(x(q.id),P(0),v("confirm-summary"))},"handleEnterInBrowse");ot((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(OU.length-1,e+1));if(t.return&&M){const e=OU[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)Q();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 J=__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 it.createElement(RO,{title:"/tree",gapAfterHeader:!1},it.createElement(et,{color:LR.CYAN},"Summarizing abandoned branch… (Esc to cancel)"));if("confirm-summary"===w)return it.createElement(RO,{title:"/tree",subtitle:"You're leaving work behind on this branch. Summarize it before jumping?",hint:"enter confirm · esc back"},it.createElement(Ze,{flexDirection:"column"},OU.map((e,t)=>it.createElement(et,{key:e.value,color:t===T?OR:LR.WHITE,bold:t===T},t===T?`${EL} `:" ",e.label))));if("custom-prompt"===w)return it.createElement(RO,{title:"/tree",subtitle:"Focus instructions for the summary:",gapAfterHeader:!1,hint:"enter confirm · esc back"},it.createElement(TextInput,{value:b,focus:!0,prefix:`${EL} `,prefixColor:"cyan",onChange:E,onSubmit:X}));if("label"===w&&q)return it.createElement(RO,{title:"/tree",subtitle:"Label:",gapAfterHeader:!1,hint:"enter save (empty clears) · esc cancel"},it.createElement(TextInput,{value:k,focus:!0,prefix:`${EL} `,prefixColor:"cyan",onChange:C,onSubmit:J}));const Z=H.slice(R,R+K),ee=new Date,te=AU[c];return it.createElement(Ze,{flexDirection:"column",paddingLeft:1,width:"100%"},it.createElement(et,{color:OR,bold:!0},"/tree"),it.createElement(Ze,{marginBottom:1,width:"100%"},it.createElement(kL,{query:u,resultCount:u?H.length:void 0,placeholder:"Type to search…"})),0===H.length?it.createElement(Ze,{marginBottom:1},it.createElement(W$,{message:"No entries found"})):it.createElement(Ze,{flexDirection:"column"},Z.map((e,t)=>{const n=R+t===I,{text:r,color:o}=describeRow(e.entry,_);return it.createElement(et,{key:e.id,backgroundColor:n?tL:void 0,bold:n,wrap:"truncate-end"},n?`${EL} `:" ",it.createElement(et,{color:eL},e.prefix),e.isActivePath?it.createElement(et,{color:OR},"• "):null,void 0!==e.label?it.createElement(et,{color:LR.YELLOW},"[",e.label,"]"," "):null,y&&e.labelTimestamp?it.createElement(et,{color:LR.DIM},formatLabelTimestamp(e.labelTimestamp,ee)," "):null,it.createElement(et,{color:o},r))})),it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"(",0===H.length?0:I+1,"/",H.length,")",te?` ${te}`:"",y?" [+label time]":"")),it.createElement(Ze,{flexDirection:"column"},it.createElement(kO,null,"↑/↓ move · ←/→ page · tab / alt+←/→ branch · shift+L label · shift+T label time"),it.createElement(kO,null,"filters ctrl+d/t/u/l/a · cycle ctrl+o · type to search · rebind via ~/.commandcode/keybindings.json")))},"TreeSelector");Vt(),PR();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."}],NU=['/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"'],_U=__name(({onCancel:e})=>(ot((t,n)=>{n.escape&&e()}),it.createElement(Ze,{flexDirection:"column",paddingLeft:2,paddingRight:2},it.createElement(Ze,{marginBottom:1,flexDirection:"column"},it.createElement(et,{bold:!0,color:OR},"Use"),it.createElement(Ze,{paddingLeft:2,flexDirection:"column"},it.createElement(et,{color:LR.DIM},'/design <mode> "target or request"'),it.createElement(et,{color:LR.DIM},'/design "freeform request" also works. The closest mode is inferred.'))),it.createElement(Ze,{marginBottom:1,flexDirection:"column"},it.createElement(et,{bold:!0,color:OR},"Modes"),it.createElement(Ze,{paddingLeft:2,flexDirection:"column"},yy.map(e=>it.createElement(Ze,{key:e.name,columnGap:2},it.createElement(Ze,{width:18,flexShrink:0},it.createElement(et,{color:LR.CYAN},"/design ",e.name)),it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},e.description)))))),it.createElement(Ze,{marginBottom:1,marginTop:1,flexDirection:"column"},it.createElement(et,{bold:!0,color:OR},"Working rules"),it.createElement(Ze,{paddingLeft:2,flexDirection:"column"},$U.map(e=>it.createElement(Ze,{key:e.label,columnGap:2},it.createElement(Ze,{width:16,flexShrink:0},it.createElement(et,{color:LR.CYAN},e.label)),it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},e.desc)))))),it.createElement(Ze,{marginBottom:1,marginTop:1,flexDirection:"column"},it.createElement(et,{bold:!0,color:OR},"Quick examples:"),it.createElement(Ze,{paddingLeft:2,flexDirection:"column"},NU.map(e=>it.createElement(et,{key:e,color:LR.DIM},e)))),it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Press Esc to close. Type /design help anytime to return.")))),"DesignGuide");Vt(),PR(),Vt(),Vt();var FU=__name(({error:e,traceId:t})=>it.createElement(Ze,{padding:1},it.createElement(B$,{title:"Error initializing onboarding:"},e,t&&it.createElement(et,{color:LR.DIM},"\n\n","Trace ID: ",t),"\n\n","Continuing without onboarding...")),"OnboardingError");Vt(),Vt();var UU=__name(()=>it.createElement(et,null,"Skip"),"SkipOptionText"),jU=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[o,s]=ct(1);return ot((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())}),it.createElement(Ze,{flexDirection:"column",borderStyle:"single",borderColor:DR.TEXT,paddingX:1,paddingY:0},it.createElement(et,{color:DR.TEXT,bold:!0},"Build Your Coding Taste"),it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(et,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),it.createElement(Ze,{marginTop:1},it.createElement(et,null,"Analyze"," ",1===e?"that session":"those sessions"," ","to build your coding taste package?"))),it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,{color:1===o?DR.TEXT:LR.GRAY},1===o?ft.pointer:" "," 1. Yes, learn (recommended)")),it.createElement(Ze,null,it.createElement(et,{color:2===o?DR.TEXT:LR.GRAY},2===o?ft.pointer:" "," 2."," ",it.createElement(UU,null)))),it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"↑↓ · "),it.createElement(et,{color:QR.CODE},"enter"),it.createElement(et,{color:LR.DIM}," ok · "),it.createElement(et,{color:QR.CODE},"esc"),it.createElement(et,{color:LR.DIM}," skip · "),it.createElement(et,{color:QR.CODE},"n"),it.createElement(et,{color:LR.DIM}," never")))},"ImportChoice"),BU=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onSkip:a})=>"asking"===e?t&&"has_sessions"===t.reason?it.createElement(jU,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:a}):null:"learning"===e?it.createElement(cN,{onComplete:r,onCancel:a,onError:o,onErrorDismiss:s}):null,"OnboardingStepRenderer"),WU=__name(({onComplete:e,autoLearn:t=!1})=>{ut(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,traceId:o,isLoading:s}=Y$({autoLearn:t,onShouldSkip:e}),{step:a,setStep:i}=Q$({conditions:n,autoLearn:t}),{handleImportStart:l,handleImportComplete:c,handleImportError:d,handleErrorDismiss:u,handleSkip:m}=J$({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?it.createElement(FU,{error:r,traceId:o}):"done"===a||"asking"!==a&&"learning"!==a?null:it.createElement(BU,{step:a,conditions:n,onImportStart:l,onImportComplete:c,onImportError:d,onErrorDismiss:u,onSkip:m})},"TasteOnboarding");Vt(),PR();var HU=[{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 GU=__name(({onSelect:e,onCancel:t})=>{const[n]=ct(()=>getCliTheme()),[r]=ct(()=>resolveCliTheme("auto")),o=mt(()=>HU.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");ot((e,n)=>{n.escape&&t()});const a=o.findIndex(e=>e.value===n),i=o.find(e=>e.value===n)?.label??`${n} theme`;return it.createElement(RO,{title:"Select a theme",subtitle:`Choose the color palette for this terminal · currently ${i}`,footer:it.createElement(et,{italic:!0,color:LR.DIM},"Press ",it.createElement(et,{bold:!0},"Esc")," to cancel")},it.createElement(SelectInput,{items:o,onSelect:s,initialIndex:a>=0?a:0,indicatorComponent:s_,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 it.createElement(Ze,{flexDirection:"column",marginBottom:i?0:1},it.createElement(Ze,null,it.createElement(a_,{isSelected:e,isActive:a,idleColor:LR.DIM},` ${r+1}. ${s?.label??t}`),a&&it.createElement(l_,null)),it.createElement(c_,null,s?.description??""))}}))},"ThemeSelector");function remoteLockPath(){return n(H(),".commandcode","remote-host.json")}Vt(),Vt(),__name(remoteLockPath,"remoteLockPath");var VU=__name(e=>"object"==typeof e&&null!==e,"isRecord"),zU=__name(e=>"string"==typeof e&&""!==e?e:void 0,"asString"),KU=__name(e=>VU(e)&&"EEXIST"===e.code,"isAlreadyExists");function parseLock(e){let t;try{t=JSON.parse(e)}catch{return}if(!VU(t))return;const n=t.pid,r=zU(t.cwd),o=zU(t.sessionId);return"number"==typeof n&&Number.isInteger(n)&&!(n<=0)&&r&&o?{pid:n,cwd:r,sessionId:o,startedAt:zU(t.startedAt)??"unknown",label:zU(t.label)}:void 0}__name(parseLock,"parseLock");var qU=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive");async function readLock(e){try{return parseLock(await ae(e,"utf8"))}catch{return}}async function readRemoteLock(e=remoteLockPath()){const t=await readLock(e);if(t&&qU(t.pid))return t}async function acquireRemoteLock(e,t=remoteLockPath()){await ee(r(t),{recursive:!0});const n=JSON.stringify(e,null,2);for(let r=0;r<3;r+=1){try{return await q(t,n,{flag:"wx",mode:384}),{ok:!0}}catch(e){if(!KU(e))throw e}const r=await readLock(t);if(r&&r.pid!==e.pid&&qU(r.pid))return{ok:!1,holder:r};await Z(t,{force:!0}).catch(()=>{})}return{ok:!1,holder:await readLock(t)}}async function takeoverRemoteLock(e,t=remoteLockPath()){await ee(r(t),{recursive:!0}),await q(t,JSON.stringify(e,null,2),{mode:384})}function watchRemoteLock(e){const t=e.path??remoteLockPath(),n=c(t);let o,s,a=!1;const i=__name(()=>{a=!0,o?.close(),s&&clearInterval(s)},"finish"),l=__name(()=>{if(a)return;let n;try{n=parseLock(R(t,"utf8"))}catch{n=void 0}n?.pid!==e.pid&&(i(),e.onLost())},"check");try{o=U(r(t),(e,t)=>{null!==t&&t!==n||l()})}catch{}return s=setInterval(l,e.pollMs??2e3),s.unref?.(),i}async function releaseRemoteLock(e=process.pid,t=remoteLockPath()){const n=await readLock(t);n&&n.pid!==e||await Z(t,{force:!0}).catch(()=>{})}function releaseRemoteLockSync(e=process.pid,t=remoteLockPath()){try{const n=parseLock(R(t,"utf8"));if(n&&n.pid!==e)return;_(t)}catch{}}__name(readLock,"readLock"),__name(readRemoteLock,"readRemoteLock"),__name(acquireRemoteLock,"acquireRemoteLock"),__name(takeoverRemoteLock,"takeoverRemoteLock"),__name(watchRemoteLock,"watchRemoteLock"),__name(releaseRemoteLock,"releaseRemoteLock"),__name(releaseRemoteLockSync,"releaseRemoteLockSync"),Vt();var YU=["telegram","discord"],QU={telegram:{token:"CMD_TELEGRAM_BOT_TOKEN",user:"CMD_TELEGRAM_USER",channel:"CMD_TELEGRAM_CHANNEL"},discord:{token:"CMD_DISCORD_BOT_TOKEN",user:"CMD_DISCORD_USER",channel:"CMD_DISCORD_CHANNEL"}};function remoteConfigPath(){return n(H(),".commandcode","auth.json")}__name(remoteConfigPath,"remoteConfigPath");var JU=__name(e=>"object"==typeof e&&null!==e,"isRecord"),XU=__name(e=>"string"==typeof e&&""!==e?e:void 0,"asString");async function readAuthDocument(e){let t;try{t=await ae(e,"utf8")}catch{return{ok:!0,data:{}}}try{const e=JSON.parse(t);return JU(e)?{ok:!0,data:e}:{ok:!1}}catch{return{ok:!1}}}__name(readAuthDocument,"readAuthDocument");var ZU="remoteControl",ej=["rc"],tj=__name((e,t)=>{const n=[ZU,...ej].map(t=>JU(e[t])?e[t]:void 0).map(e=>JU(e?.[t])?e[t]:void 0).find(e=>void 0!==e),r=JU(e[t])?e[t]:void 0,o=n??r??{};return{token:XU(o.token),allowedUserId:XU(o.allowedUserId),channelId:XU(o.channelId)}},"providerOf"),nj=__name(e=>[...ej,...YU].filter(t=>t in e),"staleKeys"),rj=__name(e=>Boolean(e.token)||Boolean(e.allowedUserId)||Boolean(e.channelId),"isConfigured");async function loadRemoteConfig(e=remoteConfigPath()){const t=await readAuthDocument(e);if(!t.ok)return{};const n={};for(const e of YU){const r=tj(t.data,e);rj(r)&&(n[e]=r)}return n}async function updateRemoteProviderConfig(e,t,n=remoteConfigPath()){const r=await readAuthDocument(n);if(!r.ok)throw new Error(`${n} is not valid JSON, so it will not be overwritten. Fix or remove the file, then try again.`);const o=await loadRemoteConfig(n),s=o[e];await writeAuthDocument(n,r.data,{...o,[e]:{token:t.token??s?.token,allowedUserId:t.allowedUserId??s?.allowedUserId,channelId:t.channelId??s?.channelId}})}async function migrateRemoteConfig(e=remoteConfigPath()){const t=await readAuthDocument(e);return!(!t.ok||0===nj(t.data).length||(await writeAuthDocument(e,t.data,await loadRemoteConfig(e)),0))}async function writeAuthDocument(e,t,n){const o=n??{},s=JU(t[ZU])?t[ZU]:{},a={...t,[ZU]:{...s,...o}};for(const e of nj(a))delete a[e];const i=JSON.stringify(a,null,2);await ee(r(e),{recursive:!0});const l=`${e}.tmp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;await q(l,i,{mode:384});try{await re(l,e)}catch(e){throw await Z(l).catch(()=>{}),e}}function resolveRemoteSettings(e,t=process.env,n="telegram"){const r=QU[n],o=e[n];return{token:XU(t[r.token])??o?.token,allowedUserId:XU(t[r.user])??o?.allowedUserId,channelId:XU(t[r.channel])??o?.channelId}}function resolveDefaultProvider(e){if(e.active)return e.active;const t=e.env??process.env,n=YU.filter(n=>void 0!==resolveRemoteSettings(e.config,t,n).token);return 1===n.length?n[0]??"telegram":"telegram"}__name(loadRemoteConfig,"loadRemoteConfig"),__name(updateRemoteProviderConfig,"updateRemoteProviderConfig"),__name(migrateRemoteConfig,"migrateRemoteConfig"),__name(writeAuthDocument,"writeAuthDocument"),__name(resolveRemoteSettings,"resolveRemoteSettings"),__name(resolveDefaultProvider,"resolveDefaultProvider"),Vt();var oj={setTimeout(e,t){const n=setTimeout(e,t);return n.unref?.(),n},clearTimeout(e){clearTimeout(e)},now:__name(()=>Date.now(),"now"),random:__name(()=>Math.random(),"random")};Vt();var sj=__name(e=>e.split("@",1)[0]??e,"stripBotSuffix");function parseRemoteCommand(e){const t=e.trim();if(!t.startsWith("/"))return;const[n="",...r]=t.split(/\s+/),o=sj(n.slice(1)).toLowerCase(),s=r.join(" ").trim();return""!==o?"stop"===o?{kind:"stop"}:"help"===o||"start"===o?{kind:"help"}:"status"===o?{kind:"status"}:{kind:"slash",name:o,argument:s}:void 0}__name(parseRemoteCommand,"parseRemoteCommand");function encodePermissionCallback(e){return`p:${e.id}:${e.allow?"a":"d"}`}function parsePermissionCallback(e){if(!e.startsWith("p:"))return;const[t,n]=e.slice(2).split(":"),r=Number(t);return!Number.isInteger(r)||r<0||"a"!==n&&"d"!==n?void 0:{id:r,allow:"a"===n}}__name(encodePermissionCallback,"encodePermissionCallback"),__name(parsePermissionCallback,"parsePermissionCallback");function encodeQuestionCallback(e){return`q:${e.id}:${e.questionIndex}:${e.optionIndex}`}function parseQuestionCallback(e){if(!e.startsWith("q:"))return;const t=e.slice(2).split(":");if(3!==t.length)return;const[n,r,o]=t.map(Number),s=__name(e=>void 0!==e&&Number.isInteger(e)&&e>=0,"valid");return s(n)&&s(r)&&s(o)?{id:n,questionIndex:r,optionIndex:o}:void 0}__name(encodeQuestionCallback,"encodeQuestionCallback"),__name(parseQuestionCallback,"parseQuestionCallback");function encodeValueCallback(e){return`v:${e.command}:${e.value}`}function parseValueCallback(e){if(!e.startsWith("v:"))return;const t=e.slice(2),n=t.indexOf(":");if(n<=0)return;const r=t.slice(0,n),o=t.slice(n+1).trim();return""===o?void 0:{command:r,value:o}}__name(encodeValueCallback,"encodeValueCallback"),__name(parseValueCallback,"parseValueCallback"),Vt();var aj,ij=new Set,lj=new Set,cj=new Set,dj=new Set;function subscribeRemoteMessage(e){return ij.add(e),()=>{ij.delete(e)}}function subscribeRemoteChoice(e){return lj.add(e),()=>{lj.delete(e)}}function emitRemoteChoice(e){for(const t of lj)t(e)}function emitRemoteMessage(e){for(const t of ij)t(e)}function subscribeLocalPrompt(e){return cj.add(e),()=>{cj.delete(e)}}function emitLocalPrompt(e){for(const t of cj)t(e)}function subscribeRemoteStopped(e){return dj.add(e),()=>{dj.delete(e)}}function emitRemoteStopped(){for(const e of dj)e()}function getActiveRemote(){return aj}function setActiveRemote(e){aj&&(aj.bridge.stop(),emitRemoteStopped()),aj=e}function clearActiveRemote(){aj?.bridge.stop(),aj=void 0,emitRemoteStopped()}__name(subscribeRemoteMessage,"subscribeRemoteMessage"),__name(subscribeRemoteChoice,"subscribeRemoteChoice"),__name(emitRemoteChoice,"emitRemoteChoice"),__name(emitRemoteMessage,"emitRemoteMessage"),__name(subscribeLocalPrompt,"subscribeLocalPrompt"),__name(emitLocalPrompt,"emitLocalPrompt"),__name(subscribeRemoteStopped,"subscribeRemoteStopped"),__name(emitRemoteStopped,"emitRemoteStopped"),__name(getActiveRemote,"getActiveRemote"),__name(setActiveRemote,"setActiveRemote"),__name(clearActiveRemote,"clearActiveRemote");var uj=__name(e=>new Promise(t=>{const n=setTimeout(t,e);n.unref?.()}),"graceElapsed");async function shutdownActiveRemote(){const e=aj;e&&(aj=void 0,e.bridge.stop(),emitRemoteStopped(),await Promise.race([e.bridge.announce(e.farewell),uj(1500)]))}__name(shutdownActiveRemote,"shutdownActiveRemote"),Vt();var mj=__name(e=>e instanceof Error?e.message:String(e),"errorMessage");Vt();var pj="```";function openingFence(e,t){if(e.startsWith(pj))return t?void 0:e.trimEnd()}function splitLongLine(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function splitForChat(e,t){if(e.length<=t)return[e];const n=[];let r,o,s=[],a=0;const i=__name(()=>{if(0===s.length)return;const e=r?[pj]:[];n.push([...s,...e].join("\n")),o=r,s=[],a=0},"flush"),l=__name(()=>{void 0!==o&&(s=[o],a=o.length+1,o=void 0)},"startChunk");for(const n of e.split("\n")){const e=t-(r?4:0);for(const t of n.length>e?splitLongLine(n,e):[n]){s.length>0&&a+t.length+1>e&&(i(),l()),s.push(t),a+=t.length+1;const n=openingFence(t,void 0!==r);n?r=n:t.startsWith(pj)&&(r=void 0)}}return i(),n.filter(e=>""!==e)}__name(openingFence,"openingFence"),__name(splitLongLine,"splitLongLine"),__name(splitForChat,"splitForChat"),Vt();var gj=__name(e=>"object"==typeof e&&null!==e,"isRecord"),hj=__name(e=>"string"==typeof e?e:void 0,"asString"),fj="Thinking";function renderBlock(e){const t=e.suffix?`${e.header} · ${e.suffix}`:e.header,n=e.lines??[];if(0===n.length)return t;const r=n.slice(0,3),o=n.length-r.length,s=r.map(e=>`│ ${e}`);if(o>0)return[t,...s,`└ +${o} more lines`].join("\n");const a=s.pop();return[t,...s,`└${a?.slice(1)??""}`].join("\n")}function createReplyStream(e,t={}){let n=e;const r=t.clock??oj;let o="",s=!0,a=!1,i=fj;const l=r.now();let c,d=0;const u=[],m=new Map;function renderStatus(e){const n=Math.floor((r.now()-l)/1e3),o=n<60?`${n}s`:`${Math.floor(n/60)}m ${n%60}s`,s=[n>=1?`${e}… ${o}`:`${e}…`,...d>0?[`↓ ${d}`]:[]].join(" · ");return t.formatStatus?.(s)??`✻ ${s}`}function scheduleTick(){void 0!==c&&r.clearTimeout(c),c=r.setTimeout(()=>{s&&void 0!==i&&(n.update(compose(o)),scheduleTick())},1e4)}function stopTick(){void 0!==c&&(r.clearTimeout(c),c=void 0)}function toolLog(){if(0===u.length)return"";const e=Math.max(0,u.length-40);return`\`\`\`\n${[...e>0?[`… ${e} earlier call(s)`]:[],...e>0?u.slice(-40):u].join("\n")}\n\`\`\`\n\n`}function compose(e){const t=void 0===i?[]:[renderStatus(i)];return[toolLog().trimEnd(),e,...t].filter(e=>""!==e).join("\n\n")}function setStatus(e){i=e,void 0===e?stopTick():scheduleTick(),n.update(compose(o))}function pushBlock(e){u.push(renderBlock(e)),n.update(compose(o))}function abandon(){s=!1,i=void 0,stopTick(),n.cancel()}function retarget(e){s&&(n=e,n.update(compose(o)),void 0!==i&&scheduleTick())}function close(e){s=!1,i=void 0,stopTick(),n.finish(compose(e))}function onEvent(e){if(s)if(a=!0,"run_start"!==e.type){if("model_request_end"===e.type){const t=gj(e.usage)?e.usage:void 0,n=t?.outputTokens;return void("number"==typeof n&&(d+=n))}if("thinking_start"!==e.type)if("message_start"!==e.type){if("text_delta"===e.type)return o+=hj(e.delta)??"",i=void 0,void n.update(compose(o));if("tool_queued"===e.type){const n=hj(e.toolName),r=hj(e.toolCallId);if(!n||!r||!t.summarizeCall)return;return void m.set(r,t.summarizeCall({toolName:n,input:gj(e.input)?e.input:{}}))}if("tool_running"===e.type){const n=hj(e.toolName);return void setStatus(hj(e.description)??(n?t.describeTool?.(n)??n:void 0)??"Working")}if("tool_completed"!==e.type&&"tool_errored"!==e.type||(i=""===o?fj:void 0),"tool_completed"===e.type){const n=hj(e.toolCallId),r=hj(e.toolName),o=n?m.get(n):void 0;if(n&&m.delete(n),!o||!r)return;const s=t.summarizeResult?.({toolName:r,result:e.result});return void pushBlock({header:o.header,suffix:s?.suffix??o.suffix,lines:s?.lines})}if("tool_errored"===e.type){const t=hj(e.toolCallId),n=t?m.get(t):void 0;if(t&&m.delete(t),!n)return;return void pushBlock({header:n.header,lines:[hj(e.error)??"failed"]})}if("run_end"===e.type){const t=gj(e.result)?e.result:{};return void close(hj(t.finalText)||o)}if("interrupted"!==e.type){if("run_error"===e.type){const t=gj(e.error)?e.error:{};close(`Run failed: ${hj(t.message)??"unknown error"}`)}}else close(`${o}\n\n⏹ Interrupted.`.trim())}else o="";else setStatus(fj)}else setStatus(fj)}return __name(renderStatus,"renderStatus"),__name(scheduleTick,"scheduleTick"),__name(stopTick,"stopTick"),__name(toolLog,"toolLog"),__name(compose,"compose"),__name(setStatus,"setStatus"),__name(pushBlock,"pushBlock"),__name(abandon,"abandon"),__name(retarget,"retarget"),__name(close,"close"),__name(onEvent,"onEvent"),n.update(compose(o)),scheduleTick(),{onEvent:onEvent,isOpen:__name(()=>s,"isOpen"),hasEvents:__name(()=>a,"hasEvents"),abandon:abandon,retarget:retarget}}function fenceFor2(e){const t=[...e.matchAll(/`+/g)].reduce((e,t)=>Math.max(e,t[0].length),0);return"`".repeat(Math.max(3,t+1))}function getRemoteMessageLabel(e){const[t=""]=e.text.split("\n",1);return t.length>60?`${t.slice(0,59)}…`:t}__name(renderBlock,"renderBlock"),__name(createReplyStream,"createReplyStream"),Vt(),__name(fenceFor2,"fenceFor"),__name(getRemoteMessageLabel,"getRemoteMessageLabel");var yj=__name(e=>e.userName??`user ${e.userId}`,"senderOf"),Sj=__name((e,t)=>`Remote message from ${e} (${t}). Carry out the request below.`,"instructionsFor");function buildRemoteSubmission(e){const t=e.platform??"Telegram",n=yj(e),r=fenceFor2(e.text);return{role:"user",input:[Sj(t,n),"",r,e.text,r].join("\n"),displayMessage:`${t} (${n}): ${getRemoteMessageLabel(e)}`,isAutomated:!0,isMeta:!0,isRelayed:!0}}__name(buildRemoteSubmission,"buildRemoteSubmission"),Vt(),Vt();var wj="input",vj=__name(e=>"string"==typeof e?e:void 0,"asString"),kj=__name(e=>"object"==typeof e&&null!==e,"isRecord"),Cj=__name(e=>"string"==typeof e?e:"number"==typeof e?String(e):void 0,"asId");function toApiError2(e,t,n){const r=kj(n)&&"string"==typeof n.message?n.message:`HTTP ${t}`,o=kj(n)&&"number"==typeof n.retry_after?Math.ceil(1e3*n.retry_after):void 0;return Object.assign(new Error(`Discord ${e} failed: ${r}`),{retryable:429===t||t>=500,retryAfterMs:o})}__name(toApiError2,"toApiError");var bj=__name(e=>e.length<=5&&e.every(e=>e.length<=5),"fitsButtonGrid"),Ej=__name(e=>({type:1,components:e.map(e=>({type:2,style:2,label:e.text.slice(0,80),custom_id:e.data.slice(0,100)}))}),"buttonRow");function selectRows(e){const t=[];for(let n=0;n<e.length&&t.length<5;n+=25){const r=e.slice(n,n+25),o=e.length>25;t.push({type:1,components:[{type:3,custom_id:`select-${String(t.length)}`,placeholder:o?`Choose one (${String(n+1)}–${String(n+r.length)})`:"Choose one",options:r.map(e=>({label:e.text.slice(0,100),value:e.data.slice(0,100)}))}]})}return t}__name(selectRows,"selectRows");var Tj=__name(e=>e&&0!==e.length?{components:bj(e)?e.map(Ej):selectRows(e.flat())}:{},"componentsBody");function createDiscordClient(e){const t=e.fetchFn??fetch,n=e.sleep??(e=>new Promise(t=>setTimeout(t,e)));async function call(r,o,s){let a;for(let i=0;i<3;i+=1){const l=await t(`https://discord.com/api/v10${o}`,{method:r,headers:{authorization:`Bot ${e.token}`,"content-type":"application/json"},...void 0===s?{}:{body:JSON.stringify(s)}});if(204===l.status)return;const c=await l.json().catch(()=>({}));if(l.ok)return c;const d=toApiError2(o,l.status,c);if(!d.retryable)throw d;a=d,await n(d.retryAfterMs??500*2**i)}throw a}__name(call,"call");const r=__name((e,t)=>{const n=kj(e)?Cj(e.id):void 0;if(!n)throw new Error(`Discord ${t}: malformed response`);return n},"messageIdOf");return{async createThread({channelId:e,name:t}){const n=await call("POST",`/channels/${e}/threads`,{name:t.slice(0,100),type:11,auto_archive_duration:1440});return r(n,"createThread")},async renameThread({channelId:e,name:t}){await call("PATCH",`/channels/${e}`,{name:t.slice(0,100)})},async sendMessage({channelId:e,text:t,buttons:n}){const o=await call("POST",`/channels/${e}/messages`,{content:t,...Tj(n)});return r(o,"sendMessage")},async editMessage({channelId:e,messageId:t,text:n}){await call("PATCH",`/channels/${e}/messages/${t}`,{content:n})},async deleteMessage({channelId:e,messageId:t}){await call("DELETE",`/channels/${e}/messages/${t}`)},async replyToInteraction({interactionId:e,token:t,text:n}){await call("POST",`/interactions/${e}/${t}/callback`,{type:4,data:{content:n,flags:64}})},async guildOfChannel(e){const t=await call("GET",`/channels/${e}`),n=kj(t)?Cj(t.guild_id):void 0;if(!n)throw new Error("Discord guildOfChannel: not a server channel");return n},async publishCommands({applicationId:e,guildId:t,commands:n}){await call("PUT",`/applications/${e}/guilds/${t}/commands`,n.map(e=>({type:1,name:e.name,description:e.description.slice(0,100),...e.argument?{options:[{type:3,name:wj,description:e.argument.slice(0,100),required:!1}]}:{}})))},async ackInteraction({interactionId:e,token:t}){await call("POST",`/interactions/${e}/${t}/callback`,{type:6})}}}function parseDiscordMessage(e){if(!kj(e))return;const t=kj(e.author)?e.author:void 0,n=Cj(e.id),r=Cj(e.channel_id),o=Cj(t?.id);return n&&r&&o?{messageId:n,channelId:r,userId:o,userName:"string"==typeof t?.username?t.username:void 0,text:"string"==typeof e.content?e.content:"",fromBot:!0===t?.bot}:void 0}function parseDiscordInteraction(e){if(!kj(e)||3!==e.type)return;const t=kj(e.data)?e.data:void 0,n=kj(e.message)?e.message:void 0,r=Cj(e.id),o=interactionChannelId(e),s=interactionUserId(e),a=Array.isArray(t?.values)?vj(t.values[0]):void 0;if(!r||!o||!s)return;if("string"!=typeof e.token)return;const i=a??vj(t?.custom_id);return void 0!==i?{interactionId:r,token:e.token,channelId:o,messageId:Cj(n?.id),userId:s,data:i}:void 0}function interactionChannelId(e){const t=kj(e.channel)?e.channel:void 0;return Cj(e.channel_id)??Cj(t?.id)}function interactionUserId(e){const t=kj(e.member)?e.member:void 0,n=kj(e.user)?e.user:kj(t?.user)?t.user:void 0;return Cj(n?.id)}function parseDiscordCommand(e){if(!kj(e)||2!==e.type)return;const t=kj(e.data)?e.data:void 0,n=Cj(e.id),r=interactionChannelId(e),o=interactionUserId(e);if(!n||!r||!o)return;if("string"!=typeof e.token)return;if("string"!=typeof t?.name)return;const s=(Array.isArray(t.options)?t.options:[]).find(e=>kj(e)&&e.name===wj);return{interactionId:n,token:e.token,channelId:r,userId:o,name:t.name,value:"string"==typeof s?.value?s.value:""}}function createDiscordReply(e){const{client:t,channelId:n}=e,r=e.prefix??"",o=e.clock??oj,s=e.onLog??(()=>{}),a=[],i=[];let l,c="",d="",u=Number.NEGATIVE_INFINITY,m=!1,p=Promise.resolve();const g=__name(e=>""===r?e:`${r}\n\n${e}`,"label");async function deliver(r){const o=splitForChat(g(r),2e3);for(const[r,s]of o.entries()){if(i[r]===s)continue;const o=a[r];if(void 0===o){const o=await t.sendMessage({channelId:n,text:s});a[r]=o,e.onSent?.(o)}else await t.editMessage({channelId:n,messageId:o,text:s});i[r]=s}}function enqueueSend(e){const t=d;d=e,u=o.now(),p=p.then(()=>deliver(e)).catch(e=>{d=t,s(`reply failed: ${mj(e)}`)})}function flushLater(){if(void 0!==l)return;const e=Math.max(0,1e3-(o.now()-u));l=o.setTimeout(()=>{l=void 0,c!==d&&enqueueSend(c)},e)}return __name(deliver,"deliver"),__name(enqueueSend,"enqueueSend"),__name(flushLater,"flushLater"),{cancel(){m=!0,void 0!==l&&(o.clearTimeout(l),l=void 0)},update(e){m||(c=e,e!==d&&(o.now()-u>=1e3?enqueueSend(e):flushLater()))},async finish(e){m||(c=""===e?"(no text reply)":e,void 0!==l&&(o.clearTimeout(l),l=void 0),await p,c!==d&&enqueueSend(c),await p)}}}__name(createDiscordClient,"createDiscordClient"),__name(parseDiscordMessage,"parseDiscordMessage"),__name(parseDiscordInteraction,"parseDiscordInteraction"),__name(interactionChannelId,"interactionChannelId"),__name(interactionUserId,"interactionUserId"),__name(parseDiscordCommand,"parseDiscordCommand"),Vt(),__name(createDiscordReply,"createDiscordReply");var Pj=__name(e=>e.length<=2e3?e:`${e.slice(0,1999)}…`,"clipToDiscordLimit");function createDiscordBridge(e){const{client:t,allowedUserId:n,onMessage:r}=e,o=e.clock??oj,s=e.onLog??(()=>{});let a,i,l=e.threadName;const c=[];function threadId(){return i??=t.createThread({channelId:e.channelId,name:e.threadName??"Command Code"}).then(e=>(a=e,e)),i}__name(threadId,"threadId");const d=__name(e=>e===a,"isOurs");async function deliver(e){try{const n=await t.sendMessage({channelId:e.channelId,text:Pj(e.text),buttons:e.buttons});c.push({channelId:e.channelId,messageId:n})}catch(e){const t=mj(e);s(t.includes("403")?`note failed: ${t}. The bot needs "Send Messages in Threads" in that channel`:`note failed: ${t}`)}}function handleMessage(e){const t=parseDiscordMessage(e);t&&(""!==t.text?t.fromBot||d(t.channelId)&&(t.userId===n?r({chatId:t.channelId,userId:t.userId,userName:t.userName,text:t.text,platform:"Discord"}):s(`refused message from unauthorized user ${t.userId}`)):d(t.channelId)&&!t.fromBot&&s("message arrived with no content. Is MESSAGE CONTENT INTENT on in the developer portal?"))}function acknowledge(e){return t.ackInteraction({interactionId:e.interactionId,token:e.token}).catch(e=>{s(`interaction ack failed: ${mj(e)}`)})}function handleCommand2(e){const t=parseDiscordCommand(e);if(!t)return!1;if(!d(t.channelId))return!0;const o=`/${t.name}${t.value?` ${t.value}`:""}`;return t.userId!==n?(s(`refused command from unauthorized user ${t.userId}`),reply(t,"Not authorized for this session."),!0):(reply(t,`Running ${o}`),r({chatId:t.channelId,userId:t.userId,userName:void 0,text:o,platform:"Discord"}),!0)}function reply(e,n){return t.replyToInteraction({interactionId:e.interactionId,token:e.token,text:n}).catch(e=>{s(`command reply failed: ${mj(e)}`)})}async function publishCommands(n){const r=e.commands??[];if(0!==r.length)try{const o=await t.guildOfChannel(e.channelId);await t.publishCommands({applicationId:n,guildId:o,commands:r}),s(`registered ${r.length} slash command(s)`)}catch(e){const t=mj(e);s(t.includes("Missing Access")||t.includes("403")?`slash commands not registered: ${t}. Re-invite the bot with the applications.commands scope`:`slash commands not registered: ${t}`)}}function handleInteraction(r){const o=parseDiscordInteraction(r);o&&d(o.channelId)&&(acknowledge(o),o.userId===n?e.onChoice?.({chatId:o.channelId,userId:o.userId,data:o.data,acknowledge:__name(async()=>{},"acknowledge"),dismiss:__name(async()=>{if(o.messageId)try{await t.deleteMessage({channelId:o.channelId,messageId:o.messageId})}catch(e){s(`message delete failed: ${mj(e)}`)}},"dismiss")}):s(`refused interaction from unauthorized ${o.userId}`))}__name(deliver,"deliver"),__name(handleMessage,"handleMessage"),__name(acknowledge,"acknowledge"),__name(handleCommand2,"handleCommand"),__name(reply,"reply"),__name(publishCommands,"publishCommands"),__name(handleInteraction,"handleInteraction");const u=e.connect({onDispatch:__name(({type:e,data:t})=>{if("MESSAGE_CREATE"===e)return handleMessage(t);"INTERACTION_CREATE"===e&&(handleCommand2(t)||handleInteraction(t))},"onDispatch"),onReady:__name(({applicationId:t})=>{threadId().then(()=>e.onReady?.({skippedUpdates:0}),t=>e.onFatal?.(`could not open a thread in that channel. Check the id, and that the bot can Create Public Threads there (${mj(t)})`)),t?publishCommands(t):s("no application id in READY, so slash commands are not registered")},"onReady"),onFatal:__name(t=>e.onFatal?.(t),"onFatal")});return{start:__name(()=>u.start(),"start"),stop:__name(()=>u.stop(),"stop"),isRunning:__name(()=>u.isRunning(),"isRunning"),openReply:__name(n=>{const r="function"==typeof e.label?e.label():e.label;return void 0!==r&&r!==l&&(l=r,threadId().then(e=>t.renameThread({channelId:e,name:r})).catch(e=>{s(`thread rename failed: ${mj(e)}`)})),createDiscordReply({client:t,channelId:n,prefix:r,onSent:__name(e=>c.push({channelId:n,messageId:e}),"onSent"),onLog:s,clock:o})},"openReply"),sendNote:__name((e,t)=>{deliver({channelId:e,text:t})},"sendNote"),sendChoices:__name(e=>{deliver({channelId:e.chatId,text:e.text,buttons:e.buttons})},"sendChoices"),announce:__name(async e=>{const t=await threadId().catch(()=>{});t&&await deliver({channelId:t,text:e})},"announce"),get ownerChatId(){return a},clearSentMessages:__name(async()=>{const e=[...c].reverse();c.length=0;let n=0;for(const r of e)try{await t.deleteMessage(r),n+=1}catch{}return n},"clearSentMessages")}}__name(createDiscordBridge,"createDiscordBridge"),Vt();var Mj=__name(e=>`\`${e.replaceAll("`","")}\``,"code"),xj=__name(e=>`⌘ Command Code · ${e.repo}`,"title");function discordConnectBanner(e){const{info:t,note:n}=e,r=[Mj(`v${t.version}`),Mj(t.model),...t.branch?[Mj(t.branch)]:[]].join(" · ");return[`## ${xj(t)}`,r,"-# Slash commands work in this thread. /help lists them.",...n?[`-# ${n}`]:[]].join("\n")}__name(discordConnectBanner,"discordConnectBanner");var Ij=__name(e=>[`## ⚪ ${xj(e)} · ended`,"-# Messages sent from now on are skipped when a session reconnects."].join("\n"),"discordFarewell"),Aj=__name(e=>`-# ✻ ${e}`,"discordStatusLine"),Rj=__name(e=>`-# ⌘ ${e.repo}${e.branch?` · ${e.branch}`:""} · ${e.model}`,"discordReplyLabel"),Lj=__name(e=>[`## ${xj(e.info)}${e.info.branch?` · ${e.info.branch}`:""}`,`${Mj(`v${e.info.version}`)} · ${Mj(e.info.model)}`,`-# ${e.mode}`].join("\n"),"discordStatus");Vt();var Oj={4004:"that bot token is not valid",4010:"invalid shard",4011:"this bot is in too many servers to run unsharded",4012:"invalid API version",4013:"invalid intents",4014:"the MESSAGE CONTENT intent is off. Turn it on in the Discord developer portal, under Bot → Privileged Gateway Intents"},Dj=__name(e=>"object"==typeof e&&null!==e,"isRecord");function createDiscordGateway(e){const t=e.clock??oj,n=e.onLog??(()=>{}),r=e.createSocket??(e=>new WebSocket(e));let o,s,a,i,l,c,d=!1,u=0,m=0,p=!1;const g=__name(()=>{void 0!==s&&t.clearTimeout(s),void 0!==a&&t.clearTimeout(a),s=void 0,a=void 0},"clearTimers"),h=__name(e=>{try{o?.send(JSON.stringify(e))}catch(e){n(`gateway send failed: ${String(e)}`)}},"send");function backoffMs2(){const e=Math.min(m-1,5);return Math.min(1e3*2**e,3e4)+Math.floor(500*t.random())}function scheduleHeartbeat(e,r){s=t.setTimeout(()=>{if(d&&r===u){if(p)return n("gateway heartbeat not acknowledged, reconnecting"),void o?.close(4e3);p=!0,h({op:1,d:c??null}),scheduleHeartbeat(e,r)}},e)}function identify(){h(i&&void 0!==c?{op:6,d:{token:e.token,session_id:i,seq:c}}:{op:2,d:{token:e.token,intents:33280,properties:{os:process.platform,browser:"commandcode",device:"commandcode"}}})}function handleDispatch(t,r){if("READY"===t&&Dj(r)){m=0,i="string"==typeof r.session_id?r.session_id:void 0,l="string"==typeof r.resume_gateway_url?`${r.resume_gateway_url}/?v=10&encoding=json`:void 0,n("gateway ready");const t=Dj(r.application)?r.application:void 0,o=Dj(r.user)?r.user:void 0;return void e.onReady?.({applicationId:"string"==typeof t?.id?t.id:"string"==typeof o?.id?o.id:void 0})}if("RESUMED"===t)return m=0,void n("gateway resumed");e.onDispatch({type:t,data:r})}function handleFrame(e,r){if(!d||r!==u)return;let a;try{a=JSON.parse("string"==typeof e?e:String(e))}catch{return}if(Dj(a)){if("number"==typeof a.s&&(c=a.s),10===a.op&&Dj(a.d)){const e="number"==typeof a.d.heartbeat_interval?a.d.heartbeat_interval:41250;return p=!1,s=t.setTimeout(()=>{d&&r===u&&(p=!0,h({op:1,d:c??null}),scheduleHeartbeat(e,r))},Math.floor(e*t.random())),void identify()}if(11!==a.op)return 7===a.op?(n("gateway asked us to reconnect"),void o?.close(4e3)):9===a.op?(!0!==a.d&&(i=void 0,c=void 0,l=void 0),n("gateway invalidated the session"),void o?.close(4e3)):void(0===a.op&&"string"==typeof a.t&&handleDispatch(a.t,a.d));p=!1}}function connect(t){if(!d||t!==u)return;g();const s=i&&l?l:"wss://gateway.discord.gg/?v=10&encoding=json";let a;try{a=r(s)}catch(e){return n(`gateway connect failed: ${String(e)}`),void scheduleReconnect(t)}o=a,a.onopen=()=>n("gateway socket open"),a.onmessage=e=>handleFrame(e.data,t),a.onerror=()=>n("gateway socket error"),a.onclose=r=>{if(!d||t!==u)return;const o=Oj[r.code];if(o)return d=!1,g(),n(`gateway closed fatally (${r.code}): ${o}`),void e.onFatal?.(o);4007!==r.code&&4009!==r.code||(i=void 0,c=void 0,l=void 0),n(`gateway closed (${r.code})`),scheduleReconnect(t)}}function scheduleReconnect(e){d&&e===u&&(g(),m+=1,a=t.setTimeout(()=>connect(e),backoffMs2()))}return __name(backoffMs2,"backoffMs"),__name(scheduleHeartbeat,"scheduleHeartbeat"),__name(identify,"identify"),__name(handleDispatch,"handleDispatch"),__name(handleFrame,"handleFrame"),__name(connect,"connect"),__name(scheduleReconnect,"scheduleReconnect"),{start(){d||(d=!0,u+=1,m=0,connect(u))},stop(){d=!1,u+=1,g();try{o?.close(1e3)}catch{}o=void 0,i=void 0,c=void 0,l=void 0},isRunning:__name(()=>d,"isRunning")}}__name(createDiscordGateway,"createDiscordGateway"),Vt(),Vt();var $j={"content-type":"application/json"},Nj=__name(e=>e instanceof Error&&"retryable"in e,"isTelegramApiError");function toApiError3(e,t,n){const r=Hj(n)?n:{},o=Hj(r.parameters)?r.parameters:{},s="string"==typeof r.description?r.description:`Telegram API error (HTTP ${t})`;return Object.assign(new Error(`${e}: ${s}`),{retryable:429===t||t>=500,retryAfterMs:"number"==typeof o.retry_after?1e3*o.retry_after:void 0})}__name(toApiError3,"toApiError");var _j=__name(e=>!Nj(e)||e.retryable,"isRetryableFailure"),Fj=__name((e,t)=>Nj(e)&&void 0!==e.retryAfterMs?e.retryAfterMs:500*2**t,"retryDelayMs"),Uj=__name(e=>e instanceof Error&&e.message.includes("message is not modified"),"isNotModifiedError"),jj=__name(e=>e instanceof Error&&/can'?t parse entities/i.test(e.message),"isParseEntitiesError"),Bj=__name(e=>e instanceof Error&&/chat not found/i.test(e.message),"isChatMissingError"),Wj=__name(e=>e instanceof Error&&/message to edit not found|message can'?t be edited/i.test(e.message),"isMessageGoneError"),Hj=__name(e=>"object"==typeof e&&null!==e,"isRecord"),Gj=__name(e=>"string"==typeof e?e:"number"==typeof e?String(e):void 0,"asId");function parseMessage2(e){if(!Hj(e))return;const t=Hj(e.chat)?e.chat:void 0,n=Hj(e.from)?e.from:void 0,r=e.message_id,o=Gj(t?.id),s=Gj(n?.id);return"number"==typeof r&&o&&s?{messageId:r,chatId:o,userId:s,userName:"string"==typeof n?.username?n.username:void 0,text:"string"==typeof e.text?e.text:""}:void 0}function parseCallback(e){if(!Hj(e))return;const t=Hj(e.from)?e.from:void 0,n=Hj(e.message)?e.message:void 0,r=Hj(n?.chat)?n.chat:void 0,o=Gj(e.id),s=Gj(r?.id),a=Gj(t?.id);return o&&s&&a&&"string"==typeof e.data&&"number"==typeof n?.message_id?{callbackId:o,chatId:s,userId:a,userName:"string"==typeof t?.username?t.username:void 0,data:e.data,messageId:n.message_id}:void 0}function parseUpdates(e){if(!Array.isArray(e))return[];const t=[];for(const n of e)Hj(n)&&"number"==typeof n.update_id&&t.push({updateId:n.update_id,message:parseMessage2(n.message),callback:parseCallback(n.callback_query)});return t}__name(parseMessage2,"parseMessage"),__name(parseCallback,"parseCallback"),__name(parseUpdates,"parseUpdates");var Vj=__name(e=>e?{parse_mode:e}:{},"parseModeBody"),zj=__name(e=>e&&e.length>0?{reply_markup:{inline_keyboard:e.map(e=>e.map(e=>({text:e.text,callback_data:e.data})))}}:{},"replyMarkupBody");function defaultSleep3(e){return new Promise(t=>{const n=setTimeout(t,e);n.unref?.()})}function createTelegramClient(e){const t=e.fetchFn??fetch,n=e.sleep??defaultSleep3,r=`https://api.telegram.org/bot${e.token}`;async function call(e){const{method:n,body:o,signal:s=null}=e,a=await t(`${r}/${n}`,o instanceof FormData?{method:"POST",body:o,signal:s}:{method:"POST",body:JSON.stringify(o),headers:$j,signal:s}),i=await a.json().catch(()=>{});if(Hj(i)&&!0===i.ok)return i.result;throw toApiError3(n,a.status,i)}async function callWithRetry(e){for(let t=0;;t+=1)try{return await call(e)}catch(e){const r=t>=2;if(!_j(e)||r)throw e;await n(Fj(e,t))}}return __name(call,"call"),__name(callWithRetry,"callWithRetry"),{getUpdates:async({offset:e,timeoutSeconds:t,signal:n})=>parseUpdates(await call({method:"getUpdates",body:{offset:e,timeout:t,allowed_updates:["message","callback_query"]},signal:n})),async sendMessage({chatId:e,text:t,parseMode:n,buttons:r}){const o=parseMessage2(await callWithRetry({method:"sendMessage",body:{chat_id:e,text:t,...Vj(n),...zj(r)}}));if(!o)throw new Error("sendMessage: malformed Telegram response");return o.messageId},async answerCallback({callbackId:e,text:t}){await callWithRetry({method:"answerCallbackQuery",body:{callback_query_id:e,...void 0===t?{}:{text:t}}})},async deleteMessage({chatId:e,messageId:t}){await callWithRetry({method:"deleteMessage",body:{chat_id:e,message_id:t}})},async editMessageText({chatId:e,messageId:t,text:n,parseMode:r}){try{await callWithRetry({method:"editMessageText",body:{chat_id:e,message_id:t,text:n,...Vj(r)}})}catch(e){if(Uj(e))return;throw e}}}}__name(defaultSleep3,"defaultSleep"),__name(createTelegramClient,"createTelegramClient"),Vt();var Kj=/```[\w+-]*\n?[\s\S]*?```|`[^`\n]+`/g,qj=/^```[\w+-]*\n?([\s\S]*?)```$/,Yj=/^`([^`\n]+)`$/,Qj=/^#{1,6}[ \t]+(.+)$/gm,Jj=/\*\*([^\n]+?)\*\*/g,Xj=/~~([^\n]+?)~~/g,Zj=/\[([^\]\n]+)\]\(([^)\s]+)\)/g,eB=__name(e=>/^https?:\/\//i.test(e),"isWebUrl"),tB=__name(e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),"escapeHtml");function splitCodeRuns(e){const t=[];let n=0;for(const r of e.matchAll(Kj)){const o=r.index;void 0!==o&&(o>n&&t.push({isCode:!1,value:e.slice(n,o)}),t.push({isCode:!0,value:r[0]}),n=o+r[0].length)}return n<e.length&&t.push({isCode:!1,value:e.slice(n)}),t}function codeBody(e){const t=qj.exec(e);return t?(t[1]??"").replace(/\n$/,""):Yj.exec(e)?.[1]}__name(splitCodeRuns,"splitCodeRuns"),__name(codeBody,"codeBody");var nB=__name(e=>{const t=codeBody(e);return void 0===t?tB(e):e.startsWith("```")?`<pre><code>${tB(t)}</code></pre>`:`<code>${tB(t)}</code>`},"codeToHtml"),rB=__name(e=>tB(e).replace(Qj,"<b>$1</b>").replace(Jj,"<b>$1</b>").replace(Xj,"<s>$1</s>").replace(Zj,(e,t,n)=>eB(n)?`<a href="${n}">${t}</a>`:e),"proseToHtml");function toTelegramHtml(e){return splitCodeRuns(e).map(e=>e.isCode?nB(e.value):rB(e.value)).join("")}__name(toTelegramHtml,"toTelegramHtml");var oB=__name(e=>e.replace(Qj,"$1").replace(Jj,"$1").replace(Xj,"$1").replace(Zj,(e,t,n)=>eB(n)?`${t} (${n})`:e),"proseToPlain");function stripMarkdown(e){return splitCodeRuns(e).map(e=>e.isCode?codeBody(e.value)??e.value:oB(e.value)).join("")}__name(stripMarkdown,"stripMarkdown");var sB=__name(e=>`\`${e.replaceAll("`","")}\``,"code"),aB=__name(e=>`⌘ Command Code · ${e.repo}`,"title");function telegramConnectBanner(e){const{info:t,note:n}=e,r=[sB(`v${t.version}`),sB(t.model),...t.branch?[sB(t.branch)]:[]].join(" · ");return[`# ${aB(t)}`,r,...n?["",n]:[]].join("\n")}__name(telegramConnectBanner,"telegramConnectBanner");var iB=__name(e=>[`# ⚪ ${aB(e)} · ended`,"Messages sent from now on are skipped when a session reconnects."].join("\n"),"telegramFarewell"),lB=__name(e=>`⌘ ${e.repo}${e.branch?` · ${e.branch}`:""} · ${e.model}`,"telegramReplyLabel"),cB=__name(e=>[`# ${aB(e.info)}${e.info.branch?` · ${e.info.branch}`:""}`,`${sB(`v${e.info.version}`)} · ${sB(e.info.model)}`,e.mode].join("\n"),"telegramStatus");Vt();var dB=__name(e=>e.length<=4096?e:`${e.slice(0,4095)}…`,"clipToMessageLimit");function createRemoteReply(e){const{client:t,chatId:n}=e,r=e.prefix??"",o=e.clock??oj,s=e.onLog??(()=>{}),a=e.onSendFailure??(e=>{s(`reply send failed: ${mj(e)}`)}),i=[],l=[];let c,d="",u="",m=Number.NEGATIVE_INFINITY,p=!1,g=Promise.resolve();const h=__name(e=>""===r?e:`${r}\n\n${e}`,"label");async function sendChunk(e){try{return await t.sendMessage({chatId:n,text:toTelegramHtml(e),parseMode:"HTML"})}catch(r){if(!jj(r))throw r;return s(`html rejected, sending plain: ${mj(r)}`),t.sendMessage({chatId:n,text:stripMarkdown(e)})}}async function editChunk(e,r){try{return await t.editMessageText({chatId:n,messageId:e,text:toTelegramHtml(r),parseMode:"HTML"}),!0}catch(o){if(Wj(o))return!1;if(!jj(o))throw o;return s(`html rejected, editing plain: ${mj(o)}`),await t.editMessageText({chatId:n,messageId:e,text:stripMarkdown(r)}),!0}}async function post(t,n){const r=await sendChunk(n);i[t]=r,e.onSent?.(r)}async function send(e){const t=splitForChat(e,4096);for(const[e,n]of t.entries()){if(l[e]===n)continue;const t=i[e];void 0===t?await post(e,n):await editChunk(t,n)||await post(e,n),l[e]=n}}function enqueueSend(e){const t=u;u=e,m=o.now(),g=g.then(()=>send(e)).catch(n=>{u===e&&(u=t),a(n)})}function flush(){if(c=void 0,""===d)return;const e=h(d);e!==u&&enqueueSend(e)}function update(e){if(p)return;if(d=e,void 0!==c)return;const t=Math.max(0,m+1e3-o.now());c=o.setTimeout(flush,t)}function cancel5(){p=!0,void 0!==c&&o.clearTimeout(c),c=void 0}async function finish(e){if(p)return;void 0!==c&&o.clearTimeout(c),c=void 0;const t=h(""===e?"(no text reply)":e);await g,t!==u&&enqueueSend(t),await g}return __name(sendChunk,"sendChunk"),__name(editChunk,"editChunk"),__name(post,"post"),__name(send,"send"),__name(enqueueSend,"enqueueSend"),__name(flush,"flush"),__name(update,"update"),__name(cancel5,"cancel"),__name(finish,"finish"),{update:update,finish:finish,cancel:cancel5}}function createSendFailureReporter(e){let t=!1;function report(n){Bj(n)?t||(t=!0,e("waiting on Telegram: message your bot once. a bot cannot text you first, and everything held posts when you do")):e(`send failed: ${mj(n)}`)}return __name(report,"report"),{report:report,reset:__name(()=>{t=!1},"reset")}}function createRemoteBridge(e){const{client:t,allowedUserId:n,onMessage:r}=e,o=e.clock??oj,s=e.onLog??(()=>{}),a=createSendFailureReporter(s);let i,l,c=!1,d=0,u=0,m=0,p=!1;function backoffMs2(){const e=Math.min(m-1,5);return Math.min(1e3*2**e,3e4)+Math.floor(250*o.random())}__name(backoffMs2,"backoffMs");const g=[],h=__name(e=>{g.push(e)},"track");async function clearSentMessages(){const e=[...g].reverse();g.length=0;let r=0;for(const o of e)try{await t.deleteMessage({chatId:n,messageId:o}),r+=1}catch{}return r}async function deliverMarkdown(e){try{return h(await t.sendMessage({chatId:e.chatId,text:dB(toTelegramHtml(e.text)),parseMode:"HTML",buttons:e.buttons})),!0}catch(e){if(!jj(e))return a.report(e),!1;s("note HTML rejected, retrying as plain text")}try{return h(await t.sendMessage({chatId:e.chatId,text:dB(stripMarkdown(e.text)),buttons:e.buttons})),!0}catch(e){return a.report(e),!1}}__name(clearSentMessages,"clearSentMessages"),__name(deliverMarkdown,"deliverMarkdown");const f=__name((e,t)=>deliverMarkdown({chatId:e,text:t}),"deliverNote");function sendNote(e,t){f(e,t)}function sendChoices(e){deliverMarkdown(e)}async function acknowledge(e,n){try{await t.answerCallback({callbackId:e,text:n})}catch(e){s(`callback answer failed: ${mj(e)}`)}}async function dismiss(e,n){try{await t.deleteMessage({chatId:e,messageId:n})}catch(e){s(`message delete failed: ${mj(e)}`)}}let y;function flushAnnouncement(e){const t=y;void 0!==t&&(y=void 0,f(e,t))}function deliver(e){""!==e.text&&(e.userId===n?(a.reset(),flushAnnouncement(e.chatId),r({chatId:e.chatId,userId:e.userId,userName:e.userName,text:e.text})):s(`refused message from unauthorized user ${e.userId}`))}function deliverChoice(t){if(t.userId!==n)return s(`refused callback from unauthorized user ${t.userId}`),void acknowledge(t.callbackId,"Not authorized.");e.onChoice?.({chatId:t.chatId,userId:t.userId,data:t.data,acknowledge:__name(e=>acknowledge(t.callbackId,e),"acknowledge"),dismiss:__name(()=>dismiss(t.chatId,t.messageId),"dismiss")})}function schedule(e,t){c&&e===d&&(i=o.setTimeout(()=>{tick(e)},t))}async function tick(e){if(c&&e===d){l=new AbortController;try{const n=await t.getUpdates({offset:u,timeoutSeconds:30,signal:l.signal});if(!c||e!==d)return;m=0,p&&(p=!1,s("Telegram reconnected"));for(const e of n)e.updateId>=u&&(u=e.updateId+1),e.message&&deliver(e.message),e.callback&&deliverChoice(e.callback);schedule(e,0)}catch(t){if(!c||e!==d)return;m+=1,p||(p=!0,s(`Telegram unreachable: ${mj(t)}. retrying`)),schedule(e,backoffMs2())}}}async function drainBacklog(e){let n=0;for(let r=0;r<20;r+=1){if(!c||e!==d)return n;l=new AbortController;try{const e=await t.getUpdates({offset:u,timeoutSeconds:0,signal:l.signal});if(0===e.length)return n;for(const t of e)t.updateId>=u&&(u=t.updateId+1);n+=e.length}catch(e){return s(`backlog drain failed: ${mj(e)}`),n}}return n}function start(){if(c)return;c=!0,d+=1,m=0,p=!1,s("remote bridge started");const t=d;drainBacklog(t).then(n=>{c&&t===d&&(n>0&&s(`skipped ${n} queued update(s)`),e.onReady?.({skippedUpdates:n}),schedule(t,0))})}function stop(){c&&(c=!1,d+=1,void 0!==i&&o.clearTimeout(i),i=void 0,l?.abort(),l=void 0,s("remote bridge stopped"))}return __name(sendNote,"sendNote"),__name(sendChoices,"sendChoices"),__name(acknowledge,"acknowledge"),__name(dismiss,"dismiss"),__name(flushAnnouncement,"flushAnnouncement"),__name(deliver,"deliver"),__name(deliverChoice,"deliverChoice"),__name(schedule,"schedule"),__name(tick,"tick"),__name(drainBacklog,"drainBacklog"),__name(start,"start"),__name(stop,"stop"),{start:start,stop:stop,isRunning:__name(()=>c,"isRunning"),openReply:__name(n=>createRemoteReply({client:t,chatId:n,prefix:"function"==typeof e.label?e.label():e.label,onSent:h,onLog:s,onSendFailure:a.report,clock:o}),"openReply"),sendNote:sendNote,sendChoices:sendChoices,clearSentMessages:clearSentMessages,announce:__name(async e=>{await f(n,e)||(y=e)},"announce"),ownerChatId:n}}async function greetTelegramChat(e){const t=e.client??createTelegramClient({token:e.token});try{return await t.sendMessage({chatId:e.chatId,text:"Setup done. This is where Command Code answers."}),{kind:"greeted"}}catch(e){return Bj(e)?{kind:"not-started"}:{kind:"failed",reason:mj(e)}}}__name(createRemoteReply,"createRemoteReply"),Vt(),__name(createSendFailureReporter,"createSendFailureReporter"),__name(createRemoteBridge,"createRemoteBridge"),Vt(),__name(greetTelegramChat,"greetTelegramChat"),Vt(),PR(),Vt(),PR(),Vt();var uB=new Map,mB=new Set;function subscribeAgentSlashCommands(e){return mB.add(e),()=>{mB.delete(e)}}function enqueueAgentSlashCommand(e){const t={command:e.command,source:e.source??"agent"},n=uB.get(e.sessionId);n?n.push(t):uB.set(e.sessionId,[t]);for(const e of[...mB])e()}function drainAgentSlashCommands(e){const t=uB.get(e.sessionId);return t&&0!==t.length?(uB.delete(e.sessionId),t):[]}function hasAgentSlashCommands(e){return(uB.get(e.sessionId)?.length??0)>0}__name(subscribeAgentSlashCommands,"subscribeAgentSlashCommands"),__name(enqueueAgentSlashCommand,"enqueueAgentSlashCommand"),__name(drainAgentSlashCommands,"drainAgentSlashCommands"),__name(hasAgentSlashCommands,"hasAgentSlashCommands");var pB=__name(e=>"remote"===e?"remote":"agent","originOf"),gB="Only you can run /rc — connecting the bot or changing who may use it is yours to decide, not mine. /rc status and /rc disconnect still work.";function refuseAgentSlashCommand(e){const[t,n]=e.trim().replace(/^\//,"").split(/\s+/);if("rc"===t&&"status"!==n&&"off"!==n&&"disconnect"!==n)return gB}__name(refuseAgentSlashCommand,"refuseAgentSlashCommand"),Vt(),PR(),Vt(),PR();var hB=__name(e=>Buffer.byteLength(e,"utf8")<=64,"fits"),fB=__name((e,t)=>e===t?"✓ ":"","mark");function chunk(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([...e.slice(n,n+2)]);return t}function buildRemoteModelMenu(e){const t=[];for(const n of e.groups)for(const r of n.models){const n=encodeValueCallback({command:"model",value:r.id});hB(n)&&t.push({text:`${fB(r.id,e.currentModel)}${r.name}`,data:n})}return 0===e.groups.length?{text:"Provider login required. Run /connect to authenticate.",buttons:[]}:{text:["Select model","Pick one, or send /model <id>"].join("\n").trimEnd(),buttons:chunk(t)}}async function resolveRemoteModelMenu(e){const t=buildLaneModelPickerGroups(),[n,r]=await Promise.all([getBillingContext(),resolveProviderAuth(t.map(e=>e.providerId))]);return buildRemoteModelMenu({currentModel:e,groups:filterModelPickerGroupsByPlan({groups:filterModelPickerGroupsByAuth({groups:t,...r}),billing:n})})}__name(chunk,"chunk"),__name(buildRemoteModelMenu,"buildRemoteModelMenu"),__name(resolveRemoteModelMenu,"resolveRemoteModelMenu");var yB=__name((e,t)=>e===t?"✓ ":"","mark");async function effortMenu(){const e=getConfiguredModel(),t=getSupportedEfforts(e);if(!t||0===t.length)return{text:"This model has no reasoning effort to set.",buttons:[]};const n=getReasoningEffort(e);return{text:`Reasoning effort\nTap one, or send /effort <level>\n\n${t.join(", ")}`,buttons:[t.map(e=>({text:`${yB(e,n)}${e}`,data:encodeValueCallback({command:"effort",value:e})}))]}}__name(effortMenu,"effortMenu");var SB=__name(e=>{const t=getSupportedEfforts(getConfiguredModel());return t&&0!==t.length?t.includes(e.toLowerCase())?void 0:`"${e}" is not a level. Try: ${t.join(", ")}.`:"This model has no reasoning effort to set."},"rejectEffort");function cliSummary(e){const t=ja.find(t=>t.command===`/${e}`);return t?.description??e}__name(cliSummary,"cliSummary");var wB=[{name:"model",summary:cliSummary("model"),argument:"a model id, or leave empty for the list",menu:__name(()=>resolveRemoteModelMenu(getConfiguredModel()),"menu")},{name:"effort",summary:cliSummary("effort"),argument:"a level, or leave empty for the list",menu:effortMenu,reject:SB},{name:"compact",summary:cliSummary("compact"),menu:__name(async()=>({text:"Compacting…",buttons:[]}),"menu")},{name:"clear",summary:cliSummary("clear"),menu:__name(async()=>({text:"Cleared.",buttons:[]}),"menu")}],vB=[{name:"status",summary:"this session, its model, and whether it asks first"},{name:"stop",summary:"interrupt whatever it is doing"},{name:"help",summary:"what you can send"}],kB=new Map(wB.map(e=>[e.name,e])),CB=__name(e=>kB.get(e.toLowerCase()),"findRemoteCommand"),bB=new Set(["model","effort"]),EB=__name(e=>bB.has(e),"needsMenu"),TB=__name(()=>[...wB.map(({name:e,summary:t,argument:n})=>({name:e,summary:t,argument:n})),...vB],"listRemoteCommands");function buildRemoteHelp(){return["What you can send","",...TB().map(e=>`/${e.name}: ${e.summary}`),"","Anything else is a prompt for the agent."].join("\n")}__name(buildRemoteHelp,"buildRemoteHelp");var PB="Not set up yet. Run /rc and it walks you through it.",MB=gB,xB=__name(e=>void 0!==e.origin&&"user"!==e.origin,"isUntrustedDispatch"),IB=__name(e=>"remote"===e.origin?"/rc only works at the terminal. The bot cannot reconfigure itself from the chat. /status and /stop work from here.":MB,"untrustedRefusal");function info(e,t){e.setFeed(e=>[...e,hh(t)])}__name(info,"info");var AB=__name(()=>getModelShortName({modelId:getConfiguredModel(),findModelById:findModelById}),"shortModelName");function shortPath(e){const t=e.split("/").filter(Boolean);return t.length<=2?e:`…/${t.slice(-2).join("/")}`}function sessionLabel(){const e=process.cwd(),t=getCurrentBranch({cwd:e}),n=getPackageJson(import.meta.url).version||"0.0.0",r=`${c(e)}${t?` (${t})`:""}`;return[`Command Code v${n}`,AB(),r].join(" · ")}function sessionInfo(){const e=process.cwd();return{version:getPackageJson(import.meta.url).version||"0.0.0",model:AB(),repo:c(e),branch:getCurrentBranch({cwd:e})||void 0}}__name(shortPath,"shortPath"),__name(sessionLabel,"sessionLabel"),__name(sessionInfo,"sessionInfo");var RB=__name(e=>"discord"===e?"Discord":"Telegram","platformName"),LB={on:"default",default:"default","auto-accept":"auto-accept",bypass:"bypass",yolo:"bypass"};function modeBehaviour(e){return"bypass"===e?"it never asks before editing files or running commands":"auto-accept"===e?"it edits files on its own, and asks in the chat before running commands":"it asks you in the chat before each new tool"}__name(modeBehaviour,"modeBehaviour");var OB=/failed|rejected|unauthorized|not acknowledged|no content|waiting on|reconnected/i,DB=__name(e=>t=>{OB.test(t)&&info(e,`Remote: ${t}`)},"bridgeLogger"),$B=__name(e=>{const t=Date.parse(e);if(Number.isNaN(t))return"unknown";const n=Math.max(0,Math.round((Date.now()-t)/6e4));return n<1?"just now":n<60?`${n}m ago`:`${Math.round(n/60)}h ago`},"sinceLabel");function describeLockHolder(e){return[e.label??"Command Code",` ${shortPath(e.cwd)}`,` started ${$B(e.startedAt)} · pid ${e.pid}`].join("\n")}function applyPermissionMode(e,t){const n=e.permissionModeRef.current;return e.permissionModeRef.current=t,e.setPermissionMode(t),I$(e.sessionId)?.setPermissionMode({mode:t}),n}__name(describeLockHolder,"describeLockHolder"),__name(applyPermissionMode,"applyPermissionMode");var NB,_B,FB=__name(()=>new Promise(e=>{const t=setTimeout(e,400);t.unref?.()}),"handoverPause");function takeRcSelectorStep(){const e=NB;return NB=void 0,e}__name(takeRcSelectorStep,"takeRcSelectorStep");var UB=!1;function registerExitRelease(){UB||(UB=!0,process.once("exit",()=>{releaseRemoteLockSync()}))}async function buildRcStatusMessage(e){const t=getActiveRemote(),n=await HB(),r=resolveRemoteSettings(await loadRemoteConfig(),process.env,n),o=await readRemoteLock(),s=!t&&o&&o.pid!==process.pid?["","Another session has the bot:",describeLockHolder(o),"Run /rc to take it over."]:[];return["Remote control: "+(t?`on via ${t.platform} in ${modeLabel(t.mode)} mode, ${modeBehaviour(t.mode)}`:"off"),...t&&e?[` ${sessionLabel()}`]:[],` ${RB(n)} token: ${r.token?"configured":"not set"} · allowed user: ${r.allowedUserId??"not set"}`,` credentials: ${remoteConfigPath()}`,...s].join("\n")}__name(registerExitRelease,"registerExitRelease"),__name(buildRcStatusMessage,"buildRcStatusMessage");var jB=__name(e=>"discord"===e?Ij(sessionInfo()):iB(sessionInfo()),"farewellFor");function stopRemote(e,t={}){const n=getActiveRemote();if(!n)return void info(e,"Remote control is not running.");if(n.restoreMode&&applyPermissionMode(e,n.restoreMode),_B?.(),_B=void 0,!t.clearChat)return shutdownActiveRemote(),releaseRemoteLock(),void info(e,"Remote control stopped.");const{bridge:r}=n;clearActiveRemote(),(async()=>{const t=await r.clearSentMessages();getActiveRemote()||await releaseRemoteLock(),info(e,0===t?"Remote control stopped. Nothing of mine left in the chat.":`Remote control stopped, and ${t} message(s) cleared from the chat. Your own messages stay, because a bot can only delete its own, and only for 48 hours.`)})()}__name(stopRemote,"stopRemote");var BB=__name(e=>({pid:process.pid,cwd:process.cwd(),sessionId:e,startedAt:(new Date).toISOString(),label:sessionLabel()}),"lockInfoFor");function surrenderRemote(e){const t=getActiveRemote();t&&(t.restoreMode&&applyPermissionMode(e,t.restoreMode),shutdownActiveRemote(),info(e,"Remote control moved to another session, which took over the bot. Run /rc here to take it back."))}function buildBridge(e){const t={allowedUserId:e.allowedUserId,onMessage:emitRemoteMessage,onChoice:emitRemoteChoice,onLog:e.onLog,label:__name(()=>"discord"===e.provider?Rj(sessionInfo()):lB(sessionInfo()),"label")},n=__name(e=>e>0?`Skipped ${e} message(s) queued while no session was connected.`:void 0,"skippedNote"),r=__name((t,r)=>{const o="discord"===e.provider?discordConnectBanner:telegramConnectBanner;t.announce(o({info:sessionInfo(),note:n(r)}))},"announceReady");if("discord"===e.provider){const n=createDiscordClient({token:e.token}),o=createDiscordBridge({...t,client:n,channelId:e.channelId??"",threadName:sessionLabel(),commands:TB().map(e=>({name:e.name,description:e.summary,argument:e.argument})),connect:__name(t=>createDiscordGateway({token:e.token,onDispatch:t.onDispatch,onReady:t.onReady,onFatal:t.onFatal,onLog:e.onLog}),"connect"),onFatal:e.onFatal,onReady:__name(({skippedUpdates:e})=>r(o,e),"onReady")});return o}const o=createRemoteBridge({...t,client:createTelegramClient({token:e.token}),onReady:__name(({skippedUpdates:e})=>r(o,e),"onReady")});return o}__name(surrenderRemote,"surrenderRemote"),__name(buildBridge,"buildBridge");var WB=__name(e=>"telegram"===e,"needsExclusiveBot");async function claimBot(e,t){const n=BB(e.sessionId);if(_B?.(),_B=void 0,t)await takeoverRemoteLock(n),await FB();else{const t=await acquireRemoteLock(n);if(!t.ok)return info(e,t.holder?`The bot is attached to another session:\n${describeLockHolder(t.holder)}\n\nRun /rc and pick "Take it over" to move it here.`:"The bot is attached to another session. Run /rc to take it over."),!1}return registerExitRelease(),_B=watchRemoteLock({pid:process.pid,onLost:__name(()=>surrenderRemote(e),"onLost")}),!0}__name(claimBot,"claimBot");var HB=__name(async()=>resolveDefaultProvider({config:await loadRemoteConfig(),active:getActiveRemote()?.provider}),"defaultProvider");async function startRemote(e,t,n={}){const r=n.provider??await HB(),o=resolveRemoteSettings(await loadRemoteConfig(),process.env,r);if(!o.token||!o.allowedUserId)return info(e,PB),!1;if("discord"===r&&!o.channelId)return info(e,PB),!1;if(WB(r)&&!await claimBot(e,!0===n.takeover))return!1;const s=buildBridge({provider:r,token:o.token,allowedUserId:o.allowedUserId,channelId:o.channelId,onLog:DB(e),onFatal:__name(t=>{info(e,`Discord disconnected: ${t}`),stopRemote(e)},"onFatal")}),a=getActiveRemote()?.restoreMode??e.permissionModeRef.current;return applyPermissionMode(e,t),setActiveRemote({bridge:s,mode:t,provider:r,platform:RB(r),farewell:jB(r),restoreMode:a}),s.start(),info(e,`Remote control is on. Send a message here or on ${RB(r)} to continue, or /rc to disconnect.`),!0}async function restartActiveRemote(e){const t=getActiveRemote();t&&(info(e,"Restarting remote control with the new settings…"),await startRemote(e,t.mode,{provider:t.provider}))}function disconnect(e,t){const n=getActiveRemote();n?t.provider&&t.provider!==n.provider?info(e,`${RB(t.provider)} is not connected, ${n.platform} is. Run /rc ${n.provider} off to stop that one.`):t.clear||xB(e)?stopRemote(e,{clearChat:t.clear}):(NB="stopping",e.setShowRcSelector(!0)):info(e,"Remote control is not running.")}async function handleRcCommand(e,t){await migrateRemoteConfig().catch(()=>{});const[n,r,o]=t.trim().split(/\s+/).filter(Boolean);if(!n)return xB(e)?void info(e,IB(e)):void e.setShowRcSelector(!0);if("status"===n)return void info(e,await buildRcStatusMessage(e.sessionId));if("off"===n||"disconnect"===n)return void disconnect(e,{clear:"clear"===r});const s=YU.find(e=>e===n);if(s)return"off"===r||"disconnect"===r?void disconnect(e,{provider:s,clear:"clear"===o}):void info(e,`Try /rc ${s} off, or /rc to connect.`);if(xB(e))return void info(e,IB(e));const a=LB[n];if(a)await startRemote(e,a);else{if("token"===n){if(!r)return void info(e,"Provide the bot token: /rc token <bot-token>");const t=await HB();return await updateRemoteProviderConfig(t,{token:r}),info(e,`${RB(t)} bot token saved to ${remoteConfigPath()}.`),void await restartActiveRemote(e)}if("user"===n){const t=await HB();return r&&/^\d+$/.test(r)?(await updateRemoteProviderConfig(t,{allowedUserId:r}),info(e,`Allowed ${RB(t)} user set to ${r}.`),void await restartActiveRemote(e)):void info(e,"discord"===t?"Provide your numeric Discord id: /rc user <id>. In Discord, turn on Settings → Developer → Developer Mode, then right-click your name → Copy User ID.":"Provide your numeric Telegram id: /rc user <id>. Message @userinfobot on Telegram and it replies with the number.")}info(e,`Unknown /rc argument "${n}". Try: /rc · /rc status · /rc default · /rc auto-accept · /rc yolo · /rc off · /rc telegram off · /rc discord off · /rc token <bot-token> · /rc user <id>`)}}__name(startRemote,"startRemote"),__name(restartActiveRemote,"restartActiveRemote"),__name(disconnect,"disconnect"),__name(handleRcCommand,"handleRcCommand"),Vt();var GB=/("[^"]+"|(?:[\w-]+\.)+(?:com|org|net|io|dev|me|app)(?:\/[\w\-./]*)?|(?<![\w./])\/[\w-]+|@[\w-]+)/g,VB=__name(e=>/^[\w-]+\./.test(e),"isAddress");function urlFor(e,t){return VB(e)?`https://${e}`:e.startsWith("@")&&"telegram"===t?`https://t.me/${e.slice(1)}`:""}function splitStepTokens(e,t="telegram"){return e.split(GB).map((e,n)=>{const r=n%2==1,o=r?urlFor(e,t):"";return{text:e,isToken:r,...""===o?{}:{url:o}}}).filter(e=>""!==e.text)}__name(urlFor,"urlFor"),__name(splitStepTokens,"splitStepTokens");var zB={telegram:"Telegram",discord:"Discord"},KB=[{label:"Telegram",value:"telegram",description:"Drive this session from a Telegram bot."},{label:"Discord",value:"discord",description:"A thread per session, so several can run at once."}],qB=[{label:modeLabel("default"),value:"default",description:"Asks before each new tool. Approve or Deny in the chat."},{label:modeLabel("auto-accept"),value:"auto-accept",description:"Reads and writes files. Asks before running commands."},{label:modeLabel("bypass"),value:"bypass",description:"Dangerously bypasses every permission. Never asks."}],YB={label:"Disconnect",value:"off",description:"Stop the bot. The session keeps running here."},QB=[{label:"Take it over",value:"takeover",description:"That session disconnects, this one takes the bot."},{label:"Leave it alone",value:"cancel",description:"That session keeps the bot."}],JB=[{label:"Disconnect",value:"stop",description:"Keep the chat history."},{label:"Disconnect and clear all chat history",value:"stop-clear",description:"Delete the bot's messages. Yours stay."}],XB=__name(e=>t=>/^\d+$/.test(t)?void 0:`${e} is digits only.`,"digitsOnly"),ZB={telegram:[{key:"token",title:"create the bot",steps:["1. Open Telegram and search for @BotFather","2. Send it /newbot","3. It asks for a name, then a username. Any name will do;",' the username has to end in "bot" (e.g. yourname_cmd_bot)',"4. It replies with a token. Copy it and paste it here"],reject:__name(e=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(e)?void 0:"That does not look like a bot token. It is a number, a colon, then a long string.","reject")},{key:"allowedUserId",title:"say who may use it",steps:["1. In Telegram, search for @userinfobot","2. Send it /start","3. It replies with your user ID. Paste that number here"],reject:XB("Your Telegram id")}],discord:[{key:"token",title:"create the bot",steps:["1. Open discord.com/developers/applications and log in",'2. Top right: click "New Application". Give it any name,',' tick the terms box, click "Create"','3. In the left sidebar, click "Bot"','4. Click "Reset Token", confirm, then "Copy". Discord shows'," a token once. If you lose it, reset it again",'5. Still on that page, scroll to "Privileged Gateway Intents"',' and turn ON "Message Content Intent". Click "Save Changes"',"6. Paste the token here"],reject:__name(e=>/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{20,}$/.test(e)?void 0:rW,"reject")},{key:"allowedUserId",title:"say who may use it",steps:["1. In the Discord app (not the portal): click the gear by",' your name → "Developer" → turn ON "Developer Mode"','2. Right-click your own name in any chat → "Copy User ID"',"3. Paste that number here"],reject:XB("Your Discord id")},{key:"channelId",title:"invite the bot, then pick its channel",steps:['1. Back in the portal, left sidebar: "OAuth2"','2. Under "OAuth2 URL Generator", tick TWO scopes:',' "bot" and "applications.commands"','3. A "Bot Permissions" box opens underneath. Tick four:',' "View Channels", "Send Messages",',' "Create Public Threads", "Send Messages in Threads"','4. At the bottom, copy the "Generated URL". Open it in a',' browser, choose your server, click "Authorize"',"5. Back in Discord, right-click the channel the bot should",' post in → "Copy Channel ID"',"6. Paste that number here","","Every /rc opens its own thread in that channel, so several","sessions can run on one bot at the same time."],reject:XB("A channel id")}]},eW=["1. Open Telegram and find the bot you just made","2. Send it /start","","A bot cannot text you first, so this is what creates the chat."],tW=[{label:"Done, check it",value:"greet-check",description:"Sends a message back, so you see it works."},{label:"Skip",value:"greet-skip",description:"Nothing reaches Telegram until you do it."}],nW=__name(e=>ZB[e].length+("telegram"===e?1:0),"stepCount"),rW="That does not look like a bot token. It has three parts separated by dots, so make sure you copied the Bot token, not the Application ID.",oW=__name(({line:e,provider:t})=>it.createElement(et,{color:LR.GRAY},splitStepTokens(e,t).map((e,t)=>{const n=`${e.text}:${String(t)}`;return e.url?it.createElement(yL,{key:n,url:e.url,text:e.text,color:OR}):it.createElement(et,{key:n,color:e.isToken?OR:void 0,bold:e.isToken},e.text)})),"StepLine"),sW=__name(({lines:e,provider:t})=>it.createElement(Ze,{flexDirection:"column",marginBottom:1},e.map((e,n)=>""===e?it.createElement(Ze,{key:`gap-${String(n)}`,height:1}):it.createElement(oW,{key:e,line:e,provider:t}))),"Steps"),aW=__name(({options:e,onSelect:t})=>it.createElement(SelectInput,{items:e.map(e=>({label:e.label,value:e.value})),onSelect:t,indicatorComponent:s_,itemComponent:({isSelected:t,label:n})=>{const r=e.findIndex(e=>e.label===n),o=e[r],s=r===e.length-1;return it.createElement(Ze,{flexDirection:"column",marginBottom:s?0:1},it.createElement(a_,{isSelected:t},` ${r+1}. ${o?.label??n}`),it.createElement(c_,null,o?.description??""))}}),"OptionList"),iW=__name(({remoteActive:e,onSelect:t,onCancel:n})=>{const[r,o]=ct(()=>takeRcSelectorStep()??"platform"),[s,a]=ct(""),[i,l]=ct(null),[c,d]=ct(null),[u,m]=ct(void 0),[p,g]=ct("telegram"),[h,f]=ct(0),[y,S]=ct(void 0);ut(()=>{let e=!0;return loadRemoteConfig().then(t=>{e&&S(t)}),readRemoteLock().then(t=>{e&&m(t?.pid===process.pid?void 0:t)}),()=>{e=!1}},[]);const w=__name(e=>{if(!y)return;const t=resolveRemoteSettings(y,process.env,e);return ZB[e].every(e=>Boolean(t[e.key]))},"isConfigured"),v=__name(e=>{if(!y)return 0;const t=resolveRemoteSettings(y,process.env,e),n=ZB[e].findIndex(e=>!t[e.key]);return-1===n?0:n},"firstMissingField");ot((e,t)=>{t.escape&&("platform"!==r?(o("platform"),l(null),a("")):n())});const k=__name(t=>e?[...t,YB]:t,"withStop"),C=__name(e=>"held"===e?QB:"stopping"===e?JB:"greet"===e?tW:k("platform"===e?KB:qB),"optionsFor")(r),b=__name(e=>!0===w(e)?"mode":(f(v(e)),"field"),"afterSetup"),E=__name(r=>{if("telegram"===r.value||"discord"===r.value){const t=r.value;return g(t),d(null),void o("telegram"!==t||void 0===u||e?b(t):"held")}if("cancel"!==r.value)if("takeover"!==r.value)if("off"!==r.value){if("greet-check"!==r.value)return"greet-skip"===r.value?(d(null),void o("mode")):void("stop"!==r.value&&"stop-clear"!==r.value?t({kind:"start",provider:p,mode:r.value,takeover:void 0!==u}):t({kind:"stop",clearChat:"stop-clear"===r.value}));x()}else o("stopping");else o(b(p));else n()},"handleSelect"),T=__name((e,t)=>{updateRemoteProviderConfig(p,e).then(()=>{l(null),a(""),o(t)},e=>{l(`Could not save: ${String(e)}`)})},"save"),P=__name(e=>{l(e),a("")},"reject"),M=__name(e=>{const t=ZB[p],n=t[h];if(!n)return;const r=e.trim(),o=n.reject(r);if(o)return void P(o);const s=h===t.length-1,a="telegram"===p?"greet":"mode";T({[n.key]:r},s?a:"field"),s||f(h+1)},"submitField"),x=__name(()=>{d("Sending a message to your bot…"),loadRemoteConfig().then(e=>{const t=resolveRemoteSettings(e,process.env,"telegram"),{token:n,allowedUserId:r}=t;return n&&r?greetTelegramChat({token:n,chatId:r}):{kind:"failed",reason:"the credentials are not saved"}}).then(e=>{if("greeted"===e.kind)return d(null),void o("mode");d("not-started"===e.kind?"Telegram has no chat yet. Send your bot /start, then try again.":`Telegram refused: ${e.reason}`)})},"checkGreeting");if("greet"===r)return it.createElement(RO,{title:"Remote control",subtitle:`${zB.telegram} · step ${nW("telegram")} of ${nW("telegram")} · open the chat`,footer:it.createElement(et,{italic:!0,color:LR.DIM},"Press ",it.createElement(et,{bold:!0},"Esc")," to go back"),gapAfterHeader:!1},it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(sW,{lines:eW,provider:"telegram"}),it.createElement(aW,{options:tW,onSelect:E}),c&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.YELLOW},c))));if("field"===r){const e=ZB[p][h];return e?it.createElement(RO,{title:"Remote control",subtitle:`${zB[p]} · step ${h+1} of ${nW(p)} · ${e.title}`,footer:it.createElement(et,{italic:!0,color:LR.DIM},"Press ",it.createElement(et,{bold:!0},"Esc")," to go back"),gapAfterHeader:!1},it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(sW,{lines:e.steps,provider:p}),it.createElement(Ze,null,it.createElement(TextInput,{value:s,focus:!0,prefix:`${ft.pointer} `,prefixColor:MO,onChange:e=>{a(e),l(null)},onSubmit:M})),i&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.RED},i)))):it.createElement(Ze,null)}const I=__name(t=>"held"===t?"Another session has the bot":"stopping"===t?"Clear the chat on the way out?":"mode"===t?"Which permission mode?":"Run this session from a chat app · currently "+(e?"on":"off"),"subtitleFor");return it.createElement(RO,{title:"Remote control",subtitle:I(r),footer:it.createElement(et,{italic:!0,color:LR.DIM},"Press ",it.createElement(et,{bold:!0},"Esc")," to"," ","platform"===r?"cancel":"go back")},"held"===r&&u&&it.createElement(Ze,{flexDirection:"column",marginBottom:1},describeLockHolder(u).split("\n").map(e=>it.createElement(et,{key:e,color:LR.GRAY},e)),it.createElement(et,{color:LR.GRAY},"Telegram allows one session per bot, so only one can have it.")),it.createElement(aW,{options:C,onSelect:E}),c&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.YELLOW},c)))},"RcSelector"),lW=lt(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:o,setStaticKey:s,transcriptMode:a,tasteOnboardingEntryId:i,autoLearnTaste:l,showTasteSkipBanner:c,showTasteLearningInFeed:d,showZdrNotice:u,modelNotice:m,retryAttempt:p,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,showFileList:S,setShowFileList:w,showProviderSelector:v,showModelSelector:k,showEffortSelector:C,showMemorySelector:b,showMcpManager:E,showAgentsConfig:T,showRewindSelector:P,showTreeSelector:M,treeFilterMode:x,treeBranchSummarySkipPrompt:I,showLoginOverlay:A,showUsageOverlay:R,showAddDirModal:L,showCompactModeSelector:O,showThemeSelector:D,showRcSelector:$,authComponentInfo:N,status:_,currentProvider:F,currentModel:U,showProviderNotification:j,shareInfo:B,showShareNotification:W,unshareNotificationMessage:H,updateStatus:G,updateFailedInfo:V,creditWarning:z,permissionMode:K,hintMessage:q,pendingExitKey:Y,interactionTokens:Q,contextUsage:J,tasteLearningOn:X,historyManagerRef:Z,executionState:ee,sessionId:te,onSubmit:ne,onCommand:re,onToggleAutoAccept:oe,onResetPendingExitKey:se,onDoubleEscapeEmpty:ae,onTasteOnboardingComplete:ie,permissionPanel:le,questionPanel:ce,designSuggestionPanel:de,onRewindSelect:ue,onRewindCancel:me,onTreeSelect:pe,onTreeCancel:ge,onTreeLabel:he,onTreeAbortSummary:fe,onLoginComplete:ye,onLoginCancel:Se,setShowProviderSelector:we,setShowModelSelector:ve,setShowEffortSelector:ke,setShowMemorySelector:Ce,setShowMcpManager:be,setShowAgentsConfig:Ee,setShowAddDirModal:Te,setShowUsageOverlay:Pe,handleProviderSelect:Me,handleProviderCancel:xe,handleModelSelect:Ie,handleModelCancel:Ae,handleCompactModeSelect:Re,handleCompactModeCancel:Le,handleThemeSelect:Oe,handleThemeCancel:De,handleRcSelect:$e,handleRcCancel:Ne,handleAuthSuccess:_e,handleAuthCancel:Fe,showDesignGuide:Ue,setShowDesignGuide:je}){const Be=mt(()=>projectTasteFeedVisibility({feed:e.filter(e=>"taste-onboarding"!==e.role),showTasteLearningInFeed:d}),[e,d]),We=pt(()=>je(!1),[je]),He=useTerminalWidth(),[Ge,Ve]=ct(!1),[ze,Ke]=ct(!1),qe=dt(null);qe.current=r?qe.current??Date.now():null;const Ye=mt(()=>"off"===a?Be:projectTranscriptWindow({feed:Be,mode:a}),[Be,a]),Qe=mt(()=>"off"===a?0:Math.max(0,Be.length-Ye.length),[Be.length,Ye.length,a]),Je=mt(()=>0===Qe?Ye:Ye.filter(e=>"user"!==e.role),[Ye,Qe]),Xe=pt(()=>Ee(!1),[Ee]),tt=pt(()=>Ce(!1),[Ce]),nt=pt(()=>be(!1),[be]),rt=pt(()=>Te(!1),[Te]),ot=pt(()=>ve(!0),[ve]),st=pt(()=>ke(!1),[ke]),at=pt(()=>{hardResetForResize(),s(e=>e+1)},[s]),lt=!("off"!==a||le||ce||de||v||k||C||N||b||E||T||P||M||A||R||L||O||D||$||Ue||i),ut=I$(te),gt=ut?ut.getEffort():null;return it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(rU,{staticKey:o,feed:Je,showHeader:!0,expandedToolOutput:"off"!==a,currentModel:U,currentEffort:gt,currentProvider:F,hiddenCount:Qe}),i&&it.createElement(WU,{onComplete:ie,autoLearn:l}),c&&it.createElement(TasteSkipMessage,null),u&&it.createElement(ZdrPausedMessage,null),m&&it.createElement(ModelNoticeMessage,{text:m}),t.map(e=>e.metadata?.isAgent?it.createElement(sU,{key:e.id,entry:e}):it.createElement(Ze,{key:e.id,marginBottom:1,width:"90%"},it.createElement(FeedEntryView,{entry:e,expandedToolOutput:"off"!==a}))),it.createElement(RetryMessage,{attempt:p}),"off"===a&&!i&&!ze&&it.createElement(TodoPanel,{active:r}),de,ce,le,"off"!==a&&it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},"─".repeat(He))),it.createElement(Ze,{paddingRight:1},it.createElement(et,{backgroundColor:FR.BG,color:FR.FG,bold:!0},`${ML}DETAILED TRANSCRIPT${ML}`),it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{bold:!0},"ctrl+o"),it.createElement(et,{color:LR.DIM}," to toggle"),it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{bold:!0},BE?"ctrl+y":"ctrl+e"),it.createElement(et,{color:LR.DIM}," ","to"," ","limited"===a?"show all":"collapse"),it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{bold:!0},"esc"),it.createElement(et,{color:LR.DIM}," to exit"))),lt&&it.createElement(it.Fragment,null,it.createElement(BackgroundTasksPanel,{onExpandedChange:Ve}),it.createElement(TodosManagerPanel,{sessionId:te,onExpandedChange:Ke}),it.createElement(HF,{queuedMessages:n,sessionId:te,isProcessing:r,processingStartedAt:qe.current,executionState:ee,status:_,input:g,setInput:h,onSubmit:ne,showFileList:S,setShowFileList:w,fileSearchQuery:f,setFileSearchQuery:y,onCommand:re,outputTokens:Q,contextUsage:J,tasteLearningOn:X,shareInfo:B,showShareNotification:W,unshareNotificationMessage:H,updateStatus:G,updateFailedInfo:V,creditWarning:z,currentProvider:F,currentModel:U,showProviderInfo:j,permissionMode:K,onToggleAutoAccept:oe,hintMessage:q,historyManager:Z.current,pendingExitKey:Y,onResetPendingExitKey:se,onDoubleEscapeEmpty:ae,retryAttempt:p,onAltP:ot,renderKey:o,inputActive:!Ge&&!ze,inactiveHint:ze?"Todos focused · ↑/↓ to select · c to complete · x to remove · a all done · Esc to go back to feed":void 0})),v&&it.createElement(Ze,{marginY:1},it.createElement(PU,{onSelect:Me,onCancel:xe,sessionId:te})),k&&it.createElement(Ze,{marginY:1},it.createElement(z_,{onSelect:Ie,onCancel:Ae,currentModel:U,currentProvider:F,refreshBanner:at,sessionId:te})),C&&it.createElement(Ze,{marginY:1},it.createElement(fU,{currentModel:U,sessionId:te,onClose:st,refreshBanner:at})),Ue&&it.createElement(Ze,{marginY:1},it.createElement(_U,{onCancel:We})),O&&it.createElement(Ze,{marginY:1},it.createElement(yF,{onSelect:Re,onCancel:Le})),D&&it.createElement(Ze,{marginY:1},it.createElement(GU,{onSelect:Oe,onCancel:De})),$&&it.createElement(Ze,{marginY:1},it.createElement(iW,{remoteActive:void 0!==getActiveRemote(),onSelect:$e,onCancel:Ne})),T&&it.createElement(Ze,{marginY:1},it.createElement(cF,{onCancel:Xe})),b&&it.createElement(Ze,{marginY:1},it.createElement(KF,{onClose:tt})),E&&it.createElement(Ze,{marginY:1},it.createElement(zF,{onClose:nt,mcp:I$(te)?.mcp})),P&&I$(te)&&it.createElement(Ze,{marginY:1},it.createElement(xU,{checkpoints:[...I$(te).listCheckpoints()],onSelect:ue,onCancel:me})),M&&I$(te)&&it.createElement(Ze,{marginY:1},it.createElement(DU,{tree:I$(te).getSessionTree(),currentLeafId:I$(te).getSessionLeafId(),initialFilterMode:x,branchSummarySkipPrompt:I,onSelect:pe,onAbortSummary:fe,onCancel:ge,onLabelChange:he})),N&&it.createElement(Ze,{marginY:1},it.createElement(N.Component,{onSuccess:_e,onCancel:Fe})),A&&it.createElement(Ze,{marginY:1},it.createElement(GF,{onComplete:ye,onCancel:Se})),L&&it.createElement(Ze,{marginY:1},it.createElement(j_,{onClose:rt})))},"MainView"));function useFeatureModelCatalog(){const[e,t]=ct(()=>getCachedBillingContext());ut(()=>{if(e)return;let n=!0;return getBillingContext().then(e=>{n&&t(e)}),()=>{n=!1}},[e]);const n=useCustomModelsReady(),r=mt(()=>buildCatalogModelPickerGroups(),[n]),o=mt(()=>filterModelPickerGroupsByPlan({groups:r,billing:e}),[r,e]),s=mt(()=>flattenModelPickerGroups(o).map(e=>({id:e.model.id,label:getModelDisplayName(e.model.id)})),[o]);return{groups:o,catalog:s,resolved:null!==e}}Vt(),Vt(),PR(),Vt(),PR(),__name(useFeatureModelCatalog,"useFeatureModelCatalog"),Vt(),PR();var cW=["Listing only models with a zero-data-retention upstream."];function wrappedRowCount(e){const t=Math.max(1,e.width),n=e.text.split(/\s+/).filter(Boolean);if(0===n.length)return 1;let r=1,o=0;for(const e of n){if(e.length>t){o>0&&(r+=1),r+=Math.ceil(e.length/t)-1,o=e.length%t||t;continue}const n=0===o?e.length:e.length+1;o+n<=t?o+=n:(r+=1,o=e.length)}return r}function zdrBannerRowCount(e){return cW.reduce((t,n)=>t+wrappedRowCount({text:n,width:e}),0)+1}function narrowGroups(e){return e.groups.map(t=>({...t,models:t.models.filter(e.accepts)})).filter(e=>e.models.length>0)}__name(wrappedRowCount,"wrappedRowCount"),__name(zdrBannerRowCount,"zdrBannerRowCount"),__name(narrowGroups,"narrowGroups");var dW=__name(({featureLabel:e,defaultLabel:t,currentModelId:n,modelFilter:r,onPick:o,onBack:s})=>{const[a,i]=ct(""),{groups:l,resolved:c}=useFeatureModelCatalog(),d=isCmdZdrEnabled(),u=mt(()=>r||d?narrowGroups({groups:l,accepts:__name(e=>!(r&&!r(e)||d&&!modelSupportsZdr(e.id)),"accepts")}):l,[l,r,d]),m=mt(()=>filterModelPickerGroups(u,a),[u,a]),p=mt(()=>getModelLabelColumnWidth(u.flatMap(e=>e.models),{showDefaultBadge:!1}),[u]),g=mt(()=>[{kind:"reset"},...flattenModelPickerGroups(m).map(e=>({kind:"model",providerId:e.providerId,model:e.model}))],[m]),h=mt(()=>{if(!n)return 0;const e=g.findIndex(e=>"model"===e.kind&&e.model.id===n);return e>=0?e:0},[g,n]),{cursor:f}=useListNavigation({items:g,initialIndex:h,searchCursorIndex:1,searchQuery:a,onSearchChange:i,onSelect:__name(e=>{c&&o("reset"===e.kind?void 0:e.model.id)},"onSelect"),onCancel:s}),[y,S]=ct(0),w=useTerminalHeight(),v=useTerminalWidth(),k=w-1,C=d?zdrBannerRowCount(v):0,b=Math.max(4,k-13-C-2*m.length);ut(()=>{S(e=>clampScrollOffset({cursor:f,total:g.length,maxVisible:b,currentOffset:e}))},[f,g.length,b]);const E=y,T=y+b,P=0===E,M=windowModelGroups({groups:m,firstSectionBase:1,windowStart:E,windowEnd:T}),x=g.length>b;return it.createElement(RO,{title:`${e} › select model`,subtitle:it.createElement(it.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:it.createElement(et,{italic:!0,color:LR.DIM},"type to search · ↑/↓ navigate · enter select",a?" · esc to clear":" · esc back")},d&&it.createElement(Ze,{marginBottom:1,flexDirection:"column"},cW.map(e=>it.createElement(et,{key:e,color:LR.YELLOW},e))),it.createElement(Ze,{marginBottom:2,flexDirection:"column",width:"100%"},it.createElement(kL,{query:a,resultCount:a?g.length-1:void 0,placeholder:"Type to search models..."})),c?it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"column"},P&&it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{bold:!0,dimColor:!0},"Default"),it.createElement(Ze,null,it.createElement(et,{backgroundColor:0===f?tL:void 0,color:n?LR.WHITE:LR.GREEN},t," "),!n&&it.createElement(et,{color:LR.GREEN},ft.tick))),M.map(({group:e,groupWindow:t},r)=>it.createElement(Ze,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:0!==r||P?1:0},it.createElement(et,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>it.createElement(H_,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===f,isCurrent:r.id===n,showProviderLabel:!1,showDefaultBadge:!1,labelColumnWidth:p}))))),x&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",E+1,"–",Math.min(T,g.length)," of"," ",g.length,E>0?" · ↑ more":"",T<g.length?" · ↓ more":""))):it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},"Loading available models…")))},"FeatureModelPicker"),uW="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===Tp}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 mW=__name(({onClose:e,staticKey:t,loadTasteStatus:n,onShowTasteLearningInFeedChange:r})=>{const[o,s]=ct([]),a=isByok({model:getConfiguredModel()}),[i,l]=ct(!0),[c,d]=ct(""),[u,m]=ct(null),{catalog:p}=useFeatureModelCatalog(),g=pt(()=>listConfigSettings({modelCatalog:p,isByok:isByok}).then(e=>s(e)),[p]);ut(()=>{let e=!0;return listConfigSettings({modelCatalog:p,isByok:isByok}).then(t=>{e&&s(t)}).finally(()=>{e&&l(!1)}),()=>{e=!1}},[p]);const h=mt(()=>filterConfigSettings({settings:o,query:c}),[o,c]),f=mt(()=>o.reduce((e,t)=>Math.max(e,t.label.length),0)+2,[o]),y=__name((e,t)=>{"theme"!==e.id||"string"!=typeof t?"taste-learning"!==e.id&&e.id!==Tp?e.id===bp&&"boolean"==typeof t&&r(t):n():applyTuiTheme(resolveCliTheme(t))},"applyLiveSideEffect"),S=__name(async e=>{if(e.featureModelKey)return void m(e);const t=nextSettingValue(e),n=o;s(n=>n.map(n=>n.id===e.id?{...n,currentValue:t}:n));try{await updateConfigSetting({id:e.id,value:t}),y(e,t)}catch{s(n)}},"selectSetting"),w=__name(async(e,t)=>{try{await updateConfigSetting({id:e.id,value:t??Lp}),await g()}catch{}m(null)},"pickFeatureModel"),{cursor:v,error:k,setError:C}=useListNavigation({items:[...h],onSelect:__name(e=>{S(e)},"onSelect"),onReset:__name(e=>{b(e)},"onReset"),onCancel:e,searchQuery:c,onSearchChange:d,isActive:!i&&null===u,validate:__name(e=>a&&isTasteRow(e)?uW:e.locked?`${e.label} is locked by settings.local.json — edit that file to change it.`:null,"validate")}),b=__name(async e=>{if(a&&isTasteRow(e))return void C(uW);if(e.locked)return void C(`${e.label} is locked by settings.local.json — edit that file to change it.`);if(e.currentValue===e.defaultValue)return void C(`${e.label} is already at its default.`);if(e.featureModelKey){try{await updateConfigSetting({id:e.id,value:e.defaultValue}),await g()}catch{}return}const t=o;s(t=>t.map(t=>t.id===e.id?{...t,currentValue:e.defaultValue}:t));try{await updateConfigSetting({id:e.id,value:e.defaultValue}),y(e,e.defaultValue)}catch{s(t)}},"resetSetting"),E=useTerminalWidth(),T=h[v],P=mt(()=>T?clampDescriptionLines({text:T.description,width:Math.max(20,E-2),maxLines:2}):[],[T,E]);if(u?.featureModelKey){const e=mp.find(e=>e.key===u.featureModelKey),t="string"==typeof u.currentValue&&u.currentValue!==Lp?u.currentValue:void 0;return it.createElement(dW,{featureLabel:u.label,defaultLabel:e?getFeatureDefaultLabel({meta:e,getModelDisplayName:getModelDisplayName,zdrEnabled:isCmdZdrEnabled()}):"",currentModelId:t,modelFilter:"vision"===u.featureModelKey?e=>modelSupportsVision(e.id):void 0,onBack:()=>m(null),onPick:e=>{w(u,e)}})}return i?it.createElement(RO,{key:t,title:"Settings",gapAfterHeader:!1},it.createElement(F$,{label:"Loading settings"})):it.createElement(RO,{title:"Settings",footer:it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(Ze,{flexDirection:"column",height:2,width:"100%"},P.map((e,t)=>it.createElement(et,{key:t,color:LR.DIM,wrap:"truncate-end"},e))),it.createElement(bO,{marginTop:0,hints:["type to filter","↑↓ navigate","enter to change","tab to reset",c?"esc to clear":"esc to close"]}))},it.createElement(Ze,{marginBottom:1,flexDirection:"column",width:"100%"},it.createElement(kL,{query:c,resultCount:c?h.length:void 0,placeholder:"Search settings..."})),0===h.length?it.createElement(Ze,{marginY:1},it.createElement(et,{color:LR.GRAY},'No settings match "',c,'"')):it.createElement(Ze,{flexDirection:"column"},h.map((e,t)=>{const n=t===v?tL:void 0,r=!c&&startsNewGroup(h,t);return it.createElement(it.Fragment,{key:e.id},r&&it.createElement(Ze,{marginTop:0===t?0:1},it.createElement(et,{color:LR.DIM,bold:!0},e.group)),it.createElement(Ze,null,it.createElement(et,{color:e.locked||a&&isTasteRow(e)?LR.DIM:LR.WHITE,backgroundColor:n},e.label.padEnd(f)),it.createElement(et,{color:e.locked||a&&isTasteRow(e)?LR.DIM:LR.GREEN,backgroundColor:n},formatSettingValue(e)),(e.locked||a&&isTasteRow(e))&&it.createElement(et,{color:LR.DIM,backgroundColor:n},a&&isTasteRow(e)?" (unavailable on BYOK)":" (locked by settings.local.json)")))})),k&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.GRAY},k)))},"SettingsConfig");function SettingsConfigView({staticKey:e,onClose:t,loadTasteStatus:n,onShowTasteLearningInFeedChange:r}){return it.useEffect(()=>{hardResetForResize()},[]),it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(mW,{onClose:t,staticKey:e,loadTasteStatus:n,onShowTasteLearningInFeedChange:r})))}function categoryColor(e){return isFatalWarningCategory(e)?LR.RED:LR.YELLOW}__name(SettingsConfigView,"SettingsConfigView"),Vt(),Vt(),PR(),Vt(),Vt(),PR(),__name(categoryColor,"categoryColor");var pW=formatSkillWarningsAsMarkdown;async function copyAllWarnings(e,t){try{const{writeClipboardText:n}=await Promise.resolve().then(()=>(PR(),TR));if(!await n(pW(e)))throw new Error("clipboard unavailable");const r=e.length;t({text:`Copied ${r} issue${1===r?"":"s"} to clipboard`,color:LR.GREEN})}catch{t({text:"Clipboard write failed",color:LR.YELLOW})}}__name(copyAllWarnings,"copyAllWarnings");var gW=__name(({warnings:e,onClose:t,isActive:n=!0})=>{const r=groupWarnings(e),o=e.length>0,[s,a]=ct(null),i=dt(null),l=dt(!0);ut(()=>()=>{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 ot((n,r)=>r.escape||" "===n&&o?(UL(),void t()):void("c"===n&&o&&copyAllWarnings(e,c)),{isActive:n}),it.createElement(Ze,{flexDirection:"column",paddingX:0,width:"100%"},it.createElement(Ze,null,it.createElement(et,{color:OR,bold:!0},"Skills"," "),it.createElement(et,{color:LR.DIM},"› "),it.createElement(et,{color:OR,bold:!0},"Skipped"," "),it.createElement(et,{color:LR.WHITE},e.length)),o&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},"Press c to copy all issues")),o?it.createElement(Ze,{flexDirection:"column"},r.map(e=>it.createElement(Ze,{key:e.category,flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,{color:categoryColor(e.category)},e.category)),e.items.map(e=>it.createElement(Ze,{key:e.path,flexDirection:"column",marginBottom:1},it.createElement(Ze,{paddingLeft:2},it.createElement(yL,{url:g(e.path).href,text:skillIdentifier(e.path),color:LR.WHITE})),it.createElement(Ze,{paddingLeft:4},it.createElement(et,{color:LR.WHITE},e.reason))))))):it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"No issues — every skill loaded.")),s&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:s.color},s.text)),it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(et,{color:LR.DIM},o?"c copy all issues · esc back to skills":"esc back to skills")))},"SkillsConfigIssues"),hW=[],fW=__name(({warnings:e=hW,onClose:t})=>{const[n,r]=ct("list");return ot((o,s)=>{"list"===n&&(s.escape&&t?t():" "===o&&!s.ctrl&&!s.meta&&e.length>0&&r("issues"))},{isActive:"list"===n}),"issues"===n?it.createElement(gW,{warnings:e,onClose:()=>r("list"),isActive:!0}):it.createElement(Ze,{flexDirection:"column",paddingX:0,width:"100%"},it.createElement(Ze,null,it.createElement(et,{color:OR,bold:!0},"Skills"),e.length>0&&it.createElement(it.Fragment,null,it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:LR.YELLOW},e.length," skipped"))),it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.DIM},"No skills found")),it.createElement(et,{color:LR.DIM},"Create skills in:"),it.createElement(et,{color:LR.DIM}," ","~/",".commandcode","/","skills","/ (user)"),it.createElement(et,{color:LR.DIM}," ","~/.agents/","skills","/ (user, .agents)"),it.createElement(et,{color:LR.DIM}," ",".commandcode","/","skills","/ (project)"),it.createElement(et,{color:LR.DIM}," ",".agents/","skills","/ (project, .agents)"),it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},e.length>0&&"space to view issues · ","Press ",it.createElement(et,{bold:!0},"Esc")," to close")))},"SkillsConfigEmpty");Vt();var yW=__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");Vt();var SW=__name(({title:e,subtitle:t,skills:n,baseIndex:r,cursor:o,disabled:s})=>it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(Ze,null,it.createElement(et,{color:HR,bold:!0},e," "),it.createElement(et,{color:HR},t)),n.map((e,t)=>{const n=r+t===o,a=s.has(e.label),i=n?tL:void 0;return it.createElement(Ze,{key:e.filePath},it.createElement(et,{color:a?LR.DIM:LR.GREEN,backgroundColor:i},a?"[off] ":"[on] "),it.createElement(et,{color:a?LR.DIM:LR.WHITE,backgroundColor:i},e.label),e.fromAgents&&it.createElement(et,{color:LR.DIM,backgroundColor:i}," [.agents]"),it.createElement(et,{color:LR.DIM,backgroundColor:i}," · ~",e.estimatedTokens," tokens "))})),"SkillSection"),wW=__name(({onClose:e})=>{const[t,n]=ct([]),[r,o]=ct([]),[s,a]=ct(!0),[i,l]=ct(null),[c,d]=ct(""),[u,m]=ct(new Set),[p,g]=ct(new Map),[h,f]=ct(!1),[y,S]=ct(null),[w,v]=ct("list"),[k,C]=ct(0),b=useTerminalHeight(),E=dt(!1);ut(()=>{__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=mt(()=>filterSkillPickerRowsForQuery({rows:t,searchQuery:c}),[t,c]),P=T.sections.project,M=T.sections.user,x=T.sections.bundled,I=T.rows,A=b-1,R=(P.length>0?1:0)+(M.length>0?1:0)+(x.length>0?1:0),L=Math.max(4,A-14-2*R),O=__name(async e=>{if(E.current)return;const t=getSkillTogglePolicy({skillName:e.label,disabled:u,disabledScopes:p,noProjectRoot:h});if(!t.allowed)return void S(t.notice);E.current=!0;const n=new Set(u);t.enabling&&n.delete(e.label),t.enabling||n.add(e.label),m(n),S(null);try{const n=await setCommandSkillEnabled(e.label,t.enabling),r=new Map(p);t.enabling&&r.delete(e.label),t.enabling||r.set(e.label,n),g(r),S(getSkillPickerNoProjectWriteNotice(n))}catch(e){m(u),S(`Failed to save: ${e instanceof Error?e.message:String(e)}`)}finally{E.current=!1}},"toggleSkill");ut(()=>{"issues"===w&&d("")},[w]);const D="list"===w&&t.length>0,{cursor:$}=useListNavigation({items:I,onSelect:O,onCancel:e,searchQuery:c,onSearchChange:d,initialIndex:0,isActive:D});if(ut(()=>{C(e=>clampScrollOffset({cursor:$,total:I.length,maxVisible:L,currentOffset:e}))},[$,I.length,L]),ot((t,n)=>{if(!n.tab)return;const r=I[$];r&&(async()=>{try{await Rt([{file:r.filePath,line:1}]),e()}catch(e){if(e instanceof Error&&e.message.includes("$EDITOR environment variable"))return void l(yW());l(e instanceof Error?e.message:"Failed to open skill in editor")}})()},{isActive:D}),ot((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 it.createElement(RO,{title:"Skills",gapAfterHeader:!1},it.createElement(et,{color:LR.DIM},"Loading skills..."));if(i)return it.createElement(RO,{title:"Skills",titleColor:LR.RED,gapAfterHeader:!1,footer:it.createElement(et,{italic:!0,color:LR.DIM},"Press ",it.createElement(et,{bold:!0},"Esc")," to close")},it.createElement(et,{color:LR.DIM},i));if(0===t.length)return it.createElement(fW,{warnings:r,onClose:e});if("issues"===w)return it.createElement(gW,{warnings:r,onClose:()=>v("list"),isActive:!0});const N=t.filter(e=>u.has(e.label)).length,_=k,F=k+L,U=sliceSectionForWindow({section:P,sectionBase:0,windowStart:_,windowEnd:F}),j=sliceSectionForWindow({section:M,sectionBase:P.length,windowStart:_,windowEnd:F}),B=sliceSectionForWindow({section:x,sectionBase:P.length+M.length,windowStart:_,windowEnd:F}),W=I.length>L;return it.createElement(RO,{title:"Skills",titleSuffix:it.createElement(it.Fragment,null," ",t.length," skill",1===t.length?"":"s",N>0&&it.createElement(it.Fragment,null,it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:LR.YELLOW},N," off")),r.length>0&&it.createElement(it.Fragment,null,it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:LR.YELLOW},r.length," skipped"))),subtitle:getSkillPickerNoProjectNotice(h),footer:it.createElement(Ze,{flexDirection:"column"},it.createElement(et,{italic:!0,color:LR.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"),it.createElement(et,{color:LR.DIM},"add skills:"," ",it.createElement(et,{color:LR.CYAN},getBinaryCommand()," skills add ","<owner/repo>")))},it.createElement(Ze,{marginBottom:1,flexDirection:"column",width:"100%"},it.createElement(kL,{query:c,resultCount:c?I.length:void 0,placeholder:"Type to search skills..."})),0===I.length?it.createElement(Ze,{marginY:1},it.createElement(et,{color:LR.GRAY},'No skills match "',c,'"')):it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"column"},U.rows.length>0&&it.createElement(SW,{title:"Project skills",subtitle:"(.commandcode/skills or .agents/skills)",skills:U.rows,baseIndex:U.baseIndex,cursor:$,disabled:u}),j.rows.length>0&&it.createElement(SW,{title:"User skills",subtitle:"(~/.commandcode/skills or ~/.agents/skills)",skills:j.rows,baseIndex:j.baseIndex,cursor:$,disabled:u}),B.rows.length>0&&it.createElement(SW,{title:"Bundled skills",subtitle:"(ships with Command Code)",skills:B.rows,baseIndex:B.baseIndex,cursor:$,disabled:u})),W&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",_+1,"–",Math.min(F,I.length)," of"," ",I.length,_>0?" · ↑ more":"",F<I.length?" · ↓ more":""))),y&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.YELLOW},y)))},"SkillsConfig");function SkillsConfigView({staticKey:e,onClose:t}){return it.useEffect(()=>{hardResetForResize()},[]),it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(wW,{onClose:t,staticKey:e})))}__name(SkillsConfigView,"SkillsConfigView"),Vt(),Vt(),PR();var vW=[{kind:"scope",scope:"project",label:"This project"},{kind:"scope",scope:"global",label:"User"},{kind:"feed",label:"Show in feed"}],kW=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=ct(!0),[s,a]=ct(void 0),[i,l]=ct(void 0),[c,d]=ct(!0),[u,m]=ct(!0),p=isProjectTasteToggleLocked(i),g=pt(async()=>{try{const[e,t]=await Promise.all([getTasteLearningSettings(),getShowTasteLearningInFeed()]);o(e.global),a(e.project),l(e.projectSource),d(t)}catch{}},[]);ut(()=>{g().finally(()=>m(!1))},[g]);const h=__name(async(e,n,r)=>{e();try{await r(),t?.(),await g()}catch(e){n()}},"persist"),f=isByok({model:getConfiguredModel()}),y=__name(e=>{if(f)return;const t=resolveTasteScopeToggle({scope:e.scope,globalEnabled:r,projectOverride:s,projectSource:i});if("locked"===t.kind)return;if("global"===t.scope)return h(()=>o(t.value),()=>o(!t.value),()=>setTasteLearning({tasteLearning:t.value,scope:"global"}));const n=s;return h(()=>a(t.value),()=>a(n),()=>setTasteLearning({tasteLearning:t.value,scope:"project"}))},"toggleRow"),S=__name(e=>{if(f)return;const t=resolveTasteScopeReset({scope:e.scope,globalEnabled:r,projectOverride:s,projectSource:i});if("noop"===t.kind)return;if("save-global"===t.kind)return h(()=>o(!0),()=>o(!1),()=>setTasteLearning({tasteLearning:!0,scope:"global"}));const n=s;return h(()=>a(void 0),()=>a(n),()=>clearProjectTasteLearning())},"resetRow"),w=__name(()=>{if(f)return;const e=!c;return h(()=>d(e),()=>d(!e),()=>setShowTasteLearningInFeed({show:e}))},"toggleFeed"),v=__name(()=>{if(!f&&!c)return h(()=>d(!0),()=>d(!1),()=>setShowTasteLearningInFeed({show:!0}))},"resetFeed"),k=__name(e=>"feed"===e.kind?w():y(e),"handleToggle"),C=__name(e=>"feed"===e.kind?v():S(e),"handleReset"),{cursor:b}=useListNavigation({items:vW,onSelect:__name(e=>{k(e)},"onSelect"),onReset:__name(e=>{C(e)},"onReset"),onCancel:e,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,isActive:!u});if(u)return it.createElement(RO,{key:n,title:"Taste Learning",gapAfterHeader:!1},it.createElement(F$,{label:"Loading configuration"}));const E=__name(e=>!f&&("feed"===e.kind?c:"project"===e.scope?s??r:r),"valueFor");return it.createElement(RO,{key:n,title:"Taste Learning",subtitle:f?gg:"Learn from your interactions.",hint:f?"esc to close":"↑/↓ navigate · enter to toggle · r reset to default · esc to close"},vW.map((e,t)=>{const n=t===b,r=E(e),o=f||"scope"===e.kind&&"project"===e.scope&&p;return it.createElement(Ze,{key:"feed"===e.kind?"feed":e.scope,marginTop:"feed"===e.kind?1:0},it.createElement(et,{color:n?LR.CYAN:LR.GRAY},n?`${ft.pointer} `:" "),it.createElement(et,{color:n?LR.CYAN:LR.WHITE},e.label.padEnd(16)),it.createElement(et,{color:r?LR.GREEN:LR.DIM},r?"enabled":"disabled"),o?it.createElement(et,{color:LR.DIM}," ",f?"(unavailable on BYOK)":"(set in settings.local.json)"):null)}),it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(et,{color:LR.DIM},'"Show in feed" only hides the notices — learning stays on.'),it.createElement(et,{color:LR.DIM},"Taste data stored in .commandcode/taste/taste.md"),p?it.createElement(et,{color:LR.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 it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(kW,{onClose:t,onSettingsChange:n,staticKey:e})))}function OrgLimitMeter({row:e,width:t,marginTop:n}){const r=e.reached?LR.RED:getUsageColor(e.pct),o=buildBlockBar({percentage:e.pct,width:t});return it.createElement(Ze,{flexDirection:"column",marginTop:n},it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},`${e.label} `),it.createElement(et,{color:r},o.filled),it.createElement(et,{color:HR},o.empty),it.createElement(et,{bold:!0,color:r},` ${Math.round(e.pct)}%`)),it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},`${" ".repeat(e.label.length+1)}${e.detail}`)))}function OrgLimitsSection({limits:e,width:t,now:n}){const r=projectOrgSpendLimitRows({limits:e,now:n});return 0===r.length?null:it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.DIM},"Spend limits"),r.map((e,n)=>it.createElement(OrgLimitMeter,{key:e.label,row:e,width:t,marginTop:0===n?0:1})))}function fetchUsageData2(){return fetchUsageData({getAuthKey:getAuthKey2,getApiBaseUrl:getApiBaseUrl,createRequest:__name(({baseUrl:e})=>createApiClient({baseUrl:e}),"createRequest")})}function getAuthKey2(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function WindowLimitMeter({label:e,used:t,cap:n,resetAt:r,width:o,now:s}){const 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 it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},e.padEnd(7)," "),it.createElement(et,{color:i},l.filled),it.createElement(et,{color:HR},l.empty),it.createElement(et,{bold:!0,color:i},` ${Math.round(a)}%`),it.createElement(et,{color:LR.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?LR.RED:"warning"===t?LR.YELLOW:void 0}__name(TasteConfigView,"TasteConfigView"),Vt(),Vt(),PR(),Vt(),PR(),Vt(),__name(OrgLimitMeter,"OrgLimitMeter"),__name(OrgLimitsSection,"OrgLimitsSection"),__name(fetchUsageData2,"fetchUsageData"),__name(getAuthKey2,"getAuthKey"),__name(WindowLimitMeter,"WindowLimitMeter"),__name(getProgressBarWidth,"getProgressBarWidth"),__name(getDaysColor,"getDaysColor");var CW=__name(({plan:e,status:t})=>it.createElement(Ze,{marginBottom:0},it.createElement(Ze,{flexShrink:0},it.createElement(et,{backgroundColor:LR.BLUE,color:"#f4f4f4",bold:!0},`${ML}USAGE${ML}`)),e&&it.createElement(it.Fragment,null,it.createElement(et,null," "),it.createElement(et,{color:LR.GRAY},`${e.name} Plan`)),t&&it.createElement(it.Fragment,null,it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:"active"===t?LR.GREEN:LR.YELLOW},t))),"UsageBadge"),bW=__name(()=>it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.YELLOW},"Running low? Keep going:"),it.createElement(et,null,it.createElement(et,{bold:!0},"/extra "),it.createElement(et,{color:LR.DIM},"pay-as-you-go at API cost, zero markup")),it.createElement(et,null,it.createElement(et,{bold:!0},"/upgrade "),it.createElement(et,{color:LR.DIM},"bigger limits"))),"ExtraUsageCallout"),EW=__name(({showRetry:e})=>it.createElement(Ze,{marginTop:1},it.createElement(kO,null,e&&it.createElement(it.Fragment,null,it.createElement(CO,null,"r")," to retry · "),"Press ",it.createElement(CO,null,"Esc")," to close")),"UsageFooter"),TW=__name(({onClose:e})=>{const[t,n]=ct("loading"),[r,o]=ct(null),[s,a]=ct(!1),i=getProgressBarWidth({terminalWidth:useTerminalWidth()}),l=pt(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=it.useRef(null);ot((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)}}),ut(()=>{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 it.createElement(Ze,{flexDirection:"column",paddingX:0,width:"100%"},it.createElement(CW,{plan:m,status:u?.status??null}),it.createElement(F$,null),it.createElement(EW,null));if("error"===t)return it.createElement(Ze,{flexDirection:"column",paddingX:0,width:"100%"},it.createElement(CW,{plan:m,status:u?.status??null}),it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},s?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),it.createElement(EW,{showRetry:!s}));if(!r)return null;const p=d?.hasBillingData??!1,g=d?.usageUrl??null,h=d?.orgLimits??[],f=d?.now??Date.now();if(!p)return it.createElement(Ze,{flexDirection:"column",paddingX:0,width:"100%"},it.createElement(CW,{plan:m,status:u?.status??null}),it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(W$,{message:"No billing data found."}),g&&it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},"Visit "),it.createElement(yL,{url:g,text:"Studio",color:LR.CYAN}),it.createElement(et,{color:LR.DIM}," for usage details."))),it.createElement(OrgLimitsSection,{limits:h,width:i,now:f}),it.createElement(EW,null));const y=d?.windowLimits??null,S=d?.sandboxMinutes??null,w=!0===d?.sandboxAccess&&null!==S&&(S.limitMinutes>0||S.usedMinutes>0),v=d?.summary??null,k=d?.credits,C=k?.usagePercent??0,b=Boolean(k?.hasCreditsInfo),E=(k?.purchasedRemaining??0)+(k?.freeRemaining??0),T=d?.daysLeft??null,P=getDaysColor(T),M=b&&shouldNudgeExtraUsage({usagePercent:C,windows:[y?.fiveHour,y?.weekly]}),x=getUsageColor(C),I=buildBlockBar({percentage:C,width:i});return it.createElement(Ze,{flexDirection:"column",paddingX:0,width:"100%"},it.createElement(Ze,{marginBottom:1},it.createElement(CW,{plan:m,status:u?.status??null})),b?it.createElement(Ze,null,it.createElement(et,{color:x},I.filled),it.createElement(et,{color:HR},I.empty),it.createElement(et,{bold:!0,color:x},` ${Math.round(C)}% used`)):it.createElement(et,{color:LR.DIM},"Plan details unavailable"),b&&it.createElement(Ze,null,v&&it.createElement(it.Fragment,null,it.createElement(et,null,v.totalCount.toLocaleString()),it.createElement(et,{color:LR.DIM},"billing-period"===v.periodBasis?" requests this month":" requests")),null!==T&&it.createElement(it.Fragment,null,v&&it.createElement(et,{color:LR.DIM}," · "),0===T?it.createElement(et,{color:P},"renews today"):it.createElement(it.Fragment,null,it.createElement(et,{color:P},`${T} day${1===T?"":"s"}`),it.createElement(et,{color:LR.DIM}," to renew"))),E>0&&it.createElement(it.Fragment,null,(v||null!==T)&&it.createElement(et,{color:LR.DIM}," · "),it.createElement(et,{color:LR.DIM},"Extra Credits: "),it.createElement(et,null,formatCredits(E)))),y?.limited&&it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.DIM},"Usage limits"),y.fiveHour&&it.createElement(WindowLimitMeter,{label:"5-hour",used:y.fiveHour.used,cap:y.fiveHour.cap,resetAt:y.fiveHour.resetAt,width:i,now:f}),y.weekly&&it.createElement(Ze,{marginTop:y.fiveHour?1:0,flexDirection:"column"},it.createElement(WindowLimitMeter,{label:"Weekly",used:y.weekly.used,cap:y.weekly.cap,resetAt:y.weekly.resetAt,width:i,now:f}))),M&&it.createElement(bW,null),w&&it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(et,{color:LR.DIM},"Sandbox minutes"),S.limitMinutes>0?it.createElement(WindowLimitMeter,{label:"Month",used:S.usedMinutes,cap:S.limitMinutes,resetAt:S.resetAt,width:i,now:f}):it.createElement(et,null,`${S.usedMinutes} min used this month, billed per minute`)),it.createElement(OrgLimitsSection,{limits:h,width:i,now:f}),g&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Full breakdown at "),it.createElement(yL,{url:g,text:d?.usageUrlDisplay??g,color:LR.CYAN})),it.createElement(EW,null))},"UsageOverlay");function UsageView({staticKey:e,onClose:t}){return it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(TW,{onClose:t})))}__name(UsageView,"UsageView"),Vt(),PR(),Vt(),PR(),Vt();var PW="@last";function shortenHomePath(e){const t=H();return e.startsWith(t)?`~${e.slice(t.length)}`:e}__name(shortenHomePath,"shortenHomePath");var MW={approved:{label:`${ft.tick} approved`,color:LR.GREEN},"not-implemented":{label:`${ft.circleDotted} set aside`,color:LR.YELLOW},pending:{label:`${ft.dot} pending`,color:LR.DIM}},xW=createNodeRuntime(),IW={"?":"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:LR.GREEN,bold:!1,italic:!1};const t={color:LR.WHITE,bold:!1,italic:!1};if(!e.style)return t;switch(e.style.role){case"heading":return{color:QR.HEADING,bold:!0,italic:!1};case"code":case"code-fence":return{color:QR.CODE,bold:!1,italic:!1};case"quote":return{color:LR.DIM,bold:!1,italic:!0};case"table":return{color:LR.CYAN,bold:!1,italic:!1};default:return t}}__name(lineStyleProps,"lineStyleProps");var AW=__name(({plan:e,variant:t="browse",fallbackContent:n,onBack:r,onSubmitFeedback:o,onExecute:s,onAutoAccept:a})=>{const[i,l]=ct(null),[c,d]=ct(e.annotations),[u,m]=ct(!1);ut(()=>{u||d(e.annotations)},[e.annotations,u]);const[p,g]=ct({kind:"line",lineNumber:1}),[h,f]=ct(null),y=dt([]),S=mt(()=>shouldCollapsePastedText(),[]),[w,v]=ct(null),[k,C]=ct(null),[b,E]=ct(!1),[T,P]=ct(0),[M,x]=ct(null),I=useTerminalHeight(),A=useTerminalWidth();ut(()=>{__name(async()=>{const t=await readPlanContent({runtime:xW,filePath:e.filePath})??n??null;l(null===t?[]:splitPlanLines(t))},"load")()},[e.filePath,n]);const R=e.version??1;ut(()=>{R<=1||!e.filePath||readPlanVersionSnapshot({runtime:xW,filePath:e.filePath,version:R-1}).then(x).catch(()=>{})},[R,e.filePath]);const L=mt(()=>null!==M&&null!==i?diffPlanChangedLines({previous:M,current:i}):new Set,[M,i]),O=c.length,D=mt(()=>{const e={id:"feedback",label:`Submit review (${O})`,chord:"ctrl+r",color:LR.CYAN,hint:"agent revises the plan, returns it for review"};return"approval"===t?[...O>0?[e]:[],{id:"auto-accept",label:"Approve",chord:"ctrl+a",color:LR.GREEN,hint:O>0?"executes the plan · comments go along as notes":"executes the plan"},{id:"cancel",label:"Cancel",chord:"esc",color:LR.YELLOW,hint:""}]:[...O>0?[e]:[],{id:"execute",label:"Execute plan",chord:"ctrl+e",color:LR.GREEN,hint:"executes the plan as written"},{id:"cancel",label:"Back",chord:"esc",color:LR.YELLOW,hint:""}]},[t,O]),$=mt(()=>h?c.filter(e=>e.line!==h.line):c,[c,h]),N=mt(()=>buildPlanReaderRows({lines:i??[],annotations:$}),[i,$]),_=mt(()=>classifyPlanLines(i??[]),[i]),F=i?.length??0,U=resolvePlanWrapWidth(Math.max(20,A-7-2)),j=mt(()=>buildPlanReaderDisplayRows({rows:N,width:U}),[N,U]),B=getPlanReaderCursorDisplaySpan({displayRows:j,cursor:p}),W=I-1,H=Math.max(4,W-10-7),G=h?1:0,V=-1===B.first?j.length-1:B.first,z=-1===B.last?j.length-1:B.last+G;ut(()=>{P(e=>{const t=clampScrollOffset({cursor:Math.max(0,z),total:j.length+G,maxVisible:H,currentOffset:e});return clampScrollOffset({cursor:Math.max(0,V),total:j.length+G,maxVisible:H,currentOffset:t})})},[V,z,j.length,G,H]),ut(()=>{g(e=>snapPlanReaderCursor({cursor:e,lineCount:F,actions:[]}))},[F]),ut(()=>{g(e=>"action"!==e.kind||D.some(t=>t.id===e.id)?e:{kind:"line",lineNumber:Math.max(1,F)})},[D,F]);const K=__name(t=>{m(!0),d(t),e.filePath&&setPlanAnnotations({runtime:xW,filePath:e.filePath,annotations:t}).catch(()=>C("Failed to save comments to disk"))},"persistAnnotations"),q="line"===p.kind?c.find(e=>e.line===p.lineNumber):void 0,Y=__name(()=>{if(0===c.length||!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:xW,filePath:e.filePath}).catch(()=>{}),K([]),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 K([]),void a?.(t)}K([]),a?.()},"approve"),J=__name(()=>{"approval"===t&&(O>0?v({kind:"approve",choice:"notes"}):Q(!1))},"requestApprove"),X=__name(()=>{O>0&&!e.filePath?v({kind:"cancel"}):r()},"requestCancel"),Z=__name(t=>{"feedback"!==t?"execute"!==t?"auto-accept"!==t?"cancel"===t&&X():J():(s??o)(buildPlanExecutePrompt({title:e.title,filePath:e.filePath||e.fileName})):Y()},"runAction"),ee=__name(()=>{e.filePath?(E(!0),openFileInEditor(e.filePath).then(async()=>{const t=await readPlanContent({runtime:xW,filePath:e.filePath});null!==t&&l(splitPlanLines(t))}).catch(e=>C(e instanceof Error?e.message:"Failed to open the editor")).finally(()=>{E(!1),hardResetForResize()})):C("This plan is not saved to a file yet")},"openExternalEditor"),te=__name(e=>{"line"!==p.kind||p.lineNumber<1||p.lineNumber>F||(y.current=e?[]:q?.pastes??[],f({line:p.lineNumber,value:e||(q?.text??""),hadExisting:void 0!==q}))},"openDraft"),ne=__name(e=>{h&&(K(upsertPlanAnnotation({annotations:c,line:h.line,text:e,createdAt:(new Date).toISOString(),pastes:y.current})),y.current=[],f(null))},"commitDraft"),re=mt(()=>{const e=new Set;for(const t of c)e.add(t.line);for(const t of L)e.add(t);return[...e].sort((e,t)=>e-t)},[c,L]),oe=__name(e=>{if(0===re.length)return;const t="line"===p.kind?p.lineNumber:F+1,n="next"===e?re.find(e=>e>t)??re[0]:[...re].reverse().find(e=>e<t)??re[re.length-1];void 0!==n&&g({kind:"line",lineNumber:n})},"jumpMarked");ot((e,t)=>{t.escape&&f(null)},{isActive:null!==h}),ot((e,t)=>{if(w)if(t.escape)v(null);else if("approve"===w.kind&&(t.leftArrow||t.rightArrow||t.tab))v({kind:"approve",choice:"notes"===w.choice?"original":"notes"});else if(t.return){if("approve"===w.kind)return v(null),void Q("notes"===w.choice);v(null),r()}},{isActive:null!==w}),ot((e,n)=>{if(n.escape)return void X();if(n.upArrow||n.downArrow)return C(null),void g(e=>{if("action"===e.kind){const t=D.findIndex(t=>t.id===e.id);if(n.upArrow){if(t<=0&&F>0)return{kind:"line",lineNumber:F};const n=D[Math.max(0,t-1)];return n?{kind:"action",id:n.id}:e}const r=D[Math.min(D.length-1,t+1)];return r?{kind:"action",id:r.id}:e}if(n.upArrow)return{kind:"line",lineNumber:Math.max(1,e.lineNumber-1)};if(e.lineNumber>=F){const t=D[0];return t?{kind:"action",id:t.id}:e}return{kind:"line",lineNumber:e.lineNumber+1}});if(n.pageUp||n.pageDown)return C(null),void g(e=>"action"===e.kind&&n.pageDown?e:movePlanReaderCursorByPage({displayRows:j,cursor:e,direction:n.pageDown?"down":"up",pageRows:Math.max(1,H-1)}));if(n.home||n.end)return C(null),void(F>0&&g({kind:"line",lineNumber:n.home?1:F}));if(n.leftArrow||n.rightArrow){if("action"!==p.kind)return;const e=D.findIndex(e=>e.id===p.id);if(-1===e)return;const t=n.leftArrow?Math.max(0,e-1):Math.min(D.length-1,e+1),r=D[t];return void(r&&g({kind:"action",id:r.id}))}if(n.ctrl&&"r"===e)return void Y();if(n.ctrl&&"a"===e&&"approval"===t)return void J();if(n.ctrl&&"e"===e&&"browse"===t)return void Z("execute");if(n.ctrl&&"g"===e)return void ee();if(n.ctrl&&"n"===e)return void oe("next");if(n.ctrl&&"p"===e)return void oe("previous");if(n.return)return"action"===p.kind?void Z(p.id):void te("");const r=IW[e];"line"!==p.kind||!r||n.ctrl||n.meta?"line"===p.kind&&e.length>0&&!n.ctrl&&!n.meta&&te(e):K(upsertPlanAnnotation({annotations:c,line:p.lineNumber,text:q?.text===r?"":r,createdAt:(new Date).toISOString()}))},{isActive:null===h&&null===w&&null!==i&&!b});const se=MW[e.status],ae=T,ie=T+H-G,le=j.slice(ae,ie),ce=h?h.hadExisting?"enter to keep · clear + enter removes · esc keep as was":"enter to pin · esc discard":w?"approve"===w.kind?"←/→ choose · enter confirm · esc back":"enter discard · esc back":"action"===p.kind?"↑/↓ choose · enter to run":["type + enter to comment",...re.length>0?["ctrl+n/p jump "+(L.size>0?"changes":"comments")]:[],"quick: ? why x cut ! risky","ctrl+g $EDITOR"].join(" · ");return it.createElement(RO,{title:"approval"===t?`Plan review: ${e.title}`:e.title,titleSuffix:"approval"===t?it.createElement(it.Fragment,null," ","· ",shortenHomePath(e.filePath)||e.fileName," · v",e.version??1):it.createElement(it.Fragment,null," ","· ",shortenHomePath(e.filePath)||e.fileName," · v",e.version??1," ",it.createElement(et,{color:se.color},se.label)),subtitle:"approval"===t?"Review the plan like a PR — type on any line to comment, enter pins it under the line.":void 0,footer:it.createElement(et,{italic:!0,color:LR.DIM},ce)},null===i?it.createElement(et,{color:LR.DIM},"Loading plan..."):0===F?it.createElement(et,{color:LR.DIM},"Plan file is empty or missing on disk."):it.createElement(Ze,{flexDirection:"column"},le.map((e,t)=>{const n=ae+t,{row:r}=e;if("action"===r.kind)return null;if("annotation"===r.kind)return it.createElement(Ze,{key:`annotation-${r.lineNumber}-${n}`},it.createElement(et,{color:LR.DIMMER}," ".repeat(5)),it.createElement(et,{backgroundColor:DR.BADGE_BG,color:DR.BADGE_FG}," ",e.isFirstSegment?"↳ ":" ",e.text," "));const o="line"===p.kind&&p.lineNumber===r.lineNumber,s=lineStyleProps({style:_[r.lineNumber-1],changed:L.has(r.lineNumber)}),a=j[n+1],i=!a||"line"!==a.row.kind||a.row.lineNumber!==r.lineNumber,l=n===ie-1,c=null!==h&&h.line===r.lineNumber&&(i||l);return it.createElement(it.Fragment,{key:`line-${r.lineNumber}-${n}`},it.createElement(Ze,null,it.createElement(et,{color:LR.DIMMER},e.isFirstSegment?String(r.lineNumber).padStart(4," "):" "," "),it.createElement(et,{color:r.hasAnnotation?LR.CYAN:LR.DIMMER},e.isFirstSegment&&r.hasAnnotation?`${ft.bullet} `:" "),it.createElement(et,{color:s.color,bold:s.bold,italic:s.italic,backgroundColor:o?tL:void 0},e.text||" ")),c&&h&&it.createElement(Ze,null,it.createElement(et,{color:LR.CYAN}," ┃ ",ft.bullet," "),it.createElement(TextInput,{value:h.value,onChange:e=>{y.current=prunePlanAnnotationPastes(e,y.current),f(t=>t?{...t,value:e}:t)},onSubmit:ne,placeholder:"Type your comment…",focus:null!==h,stripBracketedPaste:!0,clipboardOnEmptyPaste:!0,collapsePastedText:S,onPasteCollapsed:e=>{y.current=[...y.current,e]}})))})),it.createElement(Ze,{flexDirection:"column",marginTop:1},it.createElement(iL,{dividerColor:LR.DIMMER}),it.createElement(Ze,null,it.createElement(et,{bold:!0,backgroundColor:DR.BADGE_BG,color:LR.WHITE}," REVIEW "),it.createElement(et,{color:LR.DIM},O>0&&` ${O} pending comment${1===O?"":"s"}`,R>1&&` · round ${R}${L.size>0?` · ${L.size} line${1===L.size?"":"s"} changed`:""}`)),w?"approve"===w.kind?it.createElement(Ze,null,it.createElement(et,{bold:!0,color:LR.GREEN},"Approve"," "),it.createElement(et,{color:"notes"===w.choice?LR.WHITE:LR.DIM,backgroundColor:"notes"===w.choice?tL:void 0},"notes"===w.choice?"(•)":"( )"," ","with ",O," comment",1===O?"":"s"," as notes"),it.createElement(et,{color:LR.DIMMER}," "),it.createElement(et,{color:"original"===w.choice?LR.WHITE:LR.DIM,backgroundColor:"original"===w.choice?tL:void 0},"original"===w.choice?"(•)":"( )"," ","original plan · discard comments")):it.createElement(Ze,null,it.createElement(et,{color:LR.YELLOW},"Discard ",O," pending comment",1===O?"":"s"," and exit review?")):D.map(e=>{const t="action"===p.kind&&p.id===e.id;return it.createElement(Ze,{key:e.id},it.createElement(et,{bold:!0,color:e.color,backgroundColor:t?tL:void 0},t?`${ft.pointer} ${e.label} `:e.label),it.createElement(et,{color:LR.DIM}," ",e.chord),e.hint&&it.createElement(et,{color:LR.DIMMER}," ",e.hint))}),k&&it.createElement(et,{color:LR.YELLOW},k)))},"PlanReader"),RW=createNodeRuntime();function PlanApprovalView({staticKey:e,planContent:t,planFilePath:n,onAutoAccept:r,onCancel:o,onSendFeedback:s}){ut(()=>{hardResetForResize()},[]);const[a,i]=ct(null);ut(()=>{n&&listPlans({runtime:RW}).then(e=>i(e.find(e=>e.filePath===n)??null)).catch(()=>{})},[n]);const l=mt(()=>{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 it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(AW,{plan:l,variant:"approval",fallbackContent:t,onBack:o,onSubmitFeedback:s,onAutoAccept:r})))}__name(PlanApprovalView,"PlanApprovalView"),Vt(),Vt(),PR();var LW=Date.now(),OW=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 DW=__name(({sessionId:e,target:t,onClose:n,onSubmitFeedback:r,onExecute:o})=>{const[s,a]=ct([]),[i,l]=ct([]),[c,d]=ct(!0),[u,m]=ct(null),[p,g]=ct("session"),[h,f]=ct(null),[y,S]=ct(""),[w,v]=ct(0),[k,C]=ct(0),b=useTerminalHeight(),E=dt(!1);ut(()=>{__name(async()=>{try{const[n,r]=await Promise.all([listPlans({runtime:OW,sessionId:e,sessionStartMs:LW}),listPlans({runtime:OW})]);if(a([...n]),l([...r]),t&&!E.current)if(E.current=!0,t===PW){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=mt(()=>{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(ut(()=>{v(e=>clampScrollOffset({cursor:A,total:P.length,maxVisible:x,currentOffset:e}))},[A,P.length,x]),ot((e,t)=>{(t.leftArrow||t.rightArrow)&&(g(e=>"session"===e?"all":"session"),v(0))},{isActive:I}),h)return it.createElement(AW,{plan:h,onBack:()=>{f(null),C(e=>e+1)},onSubmitFeedback:r,onExecute:o});if(c)return it.createElement(RO,{title:"Plans",gapAfterHeader:!1},it.createElement(et,{color:LR.DIM},"Loading plans..."));if(u)return it.createElement(RO,{title:"Plans",titleColor:LR.RED,gapAfterHeader:!1,hint:"Esc to close"},it.createElement(et,{color:LR.DIM},u));const R=w,L=w+x,O=P.slice(R,L),D=P.length>x;return it.createElement(RO,{title:"Plans",titleSuffix:it.createElement(it.Fragment,null," ",P.length," plan",1===P.length?"":"s"),subtitle:it.createElement(it.Fragment,null,it.createElement(et,{bold:"session"===p,color:"session"===p?EO:LR.DIM},"This session"),it.createElement(et,{color:LR.DIMMER},` ${ft.triangleLeftSmall} ${ft.triangleRightSmall} `),it.createElement(et,{bold:"all"===p,color:"all"===p?EO:LR.DIM},"All plans")),footer:it.createElement(et,{italic:!0,color:LR.DIM},"type to search · ↑/↓ navigate · ←/→ switch tab · enter to open",y?" · esc to clear":" · esc to close")},it.createElement(Ze,{marginBottom:1,flexDirection:"column",width:"100%"},it.createElement(kL,{query:y,resultCount:y?P.length:void 0,placeholder:"Type to search plans..."})),0===P.length?it.createElement(Ze,{marginY:1},it.createElement(et,{color:LR.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.")):it.createElement(it.Fragment,null,it.createElement(Ze,{flexDirection:"column"},O.map((e,t)=>{const n=R+t===A,r=MW[e.status];return it.createElement(Ze,{key:e.fileName},it.createElement(et,{color:n?MO:LR.GRAY},n?`${ft.pointer} `:" "),it.createElement(et,{bold:n,color:n?MO:LR.WHITE},e.title),it.createElement(et,{color:r.color}," ",r.label),(e.version??1)>1&&it.createElement(et,{color:LR.DIM}," ","v",e.version),e.annotations.length>0&&it.createElement(et,{color:LR.CYAN}," ",e.annotations.length," comment",1===e.annotations.length?"":"s"),it.createElement(et,{color:LR.DIM}," ",formatRelativeTimeShort({timestamp:e.updatedAt})))})),D&&it.createElement(Ze,{marginTop:1},it.createElement(et,{color:LR.DIM},"Showing ",R+1,"–",Math.min(L,P.length)," of"," ",P.length,R>0?" · ↑ more":"",L<P.length?" · ↓ more":""))))},"PlansScreen");function PlansView({staticKey:e,sessionId:t,target:n,onClose:r,onSubmitFeedback:o,onExecute:s}){return it.useEffect(()=>{hardResetForResize()},[]),it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(Ze,{flexDirection:"column",width:"100%"},it.createElement(DW,{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:LR.DIM,o=e.userRenamed&&e.title?e.title:null;return o?it.createElement(et,{color:n},`${o} `,it.createElement(et,{color:r},`· ${e.forkProvenance}`)):it.createElement(et,{color:r},e.forkProvenance)}__name(PlansView,"PlansView"),Vt(),Vt(),PR(),Vt(),__name(ForkSummary,"ForkSummary");var $W=__name((e,t)=>e.padEnd(t),"padCell"),NW=__name(e=>e instanceof Error&&e.message?e.message:"Unknown error","getActionErrorMessage");function resolveRowColor(e){return e.isDeletePending?LR.RED:e.isCurrentSession?OR:e.isSelected?LR.WHITE:LR.GRAY}function renderRowSummary(e){const{session:t,isSelected:n,nameColor:r}=e;if(t.forkProvenance)return it.createElement(ForkSummary,{session:t,isSelected:n,nameColor:r});const o=getSessionSummary({session:t});return t.userRenamed&&t.title?it.createElement(et,{color:r},o):o}__name(resolveRowColor,"resolveRowColor"),__name(renderRowSummary,"renderRowSummary");var _W=["recent","created","messages"],FW={recent:"Recent",created:"Created",messages:"Messages"};function nextSortMode(e){const t=_W.indexOf(e);return _W[(t+1)%_W.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 UW=__name(({onSelectSession:e,onClose:t,currentSessionId:n})=>{const[r,o]=ct([]),[s,a]=ct(0),[i,l]=ct(0),[c,d]=ct(!0),[u,m]=ct(!1),[p,g]=ct(!1),[h,f]=ct(null),[y,S]=ct(null),[w,v]=ct(""),[k,C]=ct(!1),[b,E]=ct("recent"),[T,P]=ct(!1),[M,x]=ct("list"),[I,A]=ct(null),[R,L]=ct(""),[O,D]=ct(null),[$]=ct(()=>getCurrentGitBranch()),[N]=ct(()=>resolveProjectBaseDir()),_=useTerminalHeight(),F=Math.max(6,_-19),U=pt(async()=>{d(!0);const e=await listCommandSessions();o(e),d(!1)},[]);ut(()=>{U()},[U]),ut(()=>{if(!y)return;const e=setTimeout(()=>S(null),3e3);return()=>clearTimeout(e)},[y]);const j=pt(async e=>{try{const t=getCommandSessionRuntime(),{method:n}=await deleteSessionV3({runtime:t,baseDir:N,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: ${NW(e)}`)}},[U,N]),B=pt(async e=>{const t=I;if(t)try{const n=getCommandSessionRuntime();await renameSessionFile({runtime:n,cwd:n.cwd(),baseDir:N,id:t,name:e}),x("list"),A(null),D(null),await U()}catch(e){D(`Failed to rename session: ${NW(e)}`)}else x("list")},[I,U,N]),W=filterSessionsByBranch({sessions:r,branchFilter:u,currentBranch:$}),H=T?W.filter(e=>e.userRenamed):W,G=sortSessions(w?H.filter(e=>matchesSearch2(e,w)):H,b);if(ut(()=>{a(e=>Math.min(e,Math.max(0,G.length-1)))},[G.length]),ot((r,o)=>{if("rename"===M)return o.escape?(x("list"),void A(null)):void 0;if(p){if(!o.return)return void g(!1);if(G.length>0&&s<G.length){const e=G[s];j(e.id)}}else{if(o.delete||isCtrlKey({inputChar:r,key:o,letter:"d",ctrlCode:4})){if(0===G.length)return;return G[s]?.id===n?void f("Cannot delete the current session"):(f(null),void g(!0))}if(isCtrlKey({inputChar:r,key:o,letter:"r",ctrlCode:18})){if(c)return;const e=G[s];if(!e)return;return D(null),L(e.title??""),A(e.id),void x("rename")}if(isCtrlKey({inputChar:r,key:o,letter:"p",ctrlCode:16}))C(e=>!e);else{if(!isCtrlKey({inputChar:r,key:o,letter:"s",ctrlCode:19}))return isCtrlKey({inputChar:r,key:o,letter:"n",ctrlCode:14})?(P(e=>!e),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 it.createElement(Ze,{flexDirection:"column",paddingLeft:2},it.createElement(F$,{label:"Loading sessions"}));if(0===r.length)return it.createElement(Ze,{flexDirection:"column",paddingLeft:2},it.createElement(W$,{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:$});return it.createElement(RO,{title:"Resume Session",subtitle:`Sort: ${FW[b]} · Name: ${T?"Named":"All"} · Branch: ${u?$??"unknown":"All"}`},it.createElement(Ze,{marginBottom:1,width:"100%"},it.createElement(kL,{query:w,resultCount:w?G.length:void 0,placeholder:"Type to search sessions..."})),it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:HR,bold:!0},$W("#",6),$W("Modified",12),$W("Git Branch",22),$W("Messages",12),"Summary",k?" · Path":"")),0===G.length?it.createElement(Ze,{marginBottom:1},it.createElement(W$,{message:q.text,hint:q.hint})):it.createElement(Ze,{flexDirection:"column"},V.map((e,t)=>{const r=i+t,o=s===r,a=p&&o,l=a?void 0:LR.YELLOW,c=resolveRowColor({isDeletePending:a,isCurrentSession:e.id===n,isSelected:o}),d=truncateString2({text:e.gitBranch||"-",maxChars:20}),u=k?toRelativePath(`${N}/${e.id}.jsonl`):null;return it.createElement(et,{key:e.id,color:c,backgroundColor:o?tL:void 0,bold:o,wrap:"truncate-end"},$W(`${r+1}.`,6),$W(formatRelativeTimeShort({timestamp:e.lastModified}),12),$W(d,22),$W(String(e.messageCount),12),renderRowSummary({session:e,isSelected:o,nameColor:l}),u?it.createElement(et,{color:LR.DIM},` ${u}`):null," ")})),it.createElement(Ze,{marginTop:1}),"rename"===M&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.CYAN},"Rename: "),it.createElement(TextInput,{value:R,onChange:L,onSubmit:B,singleLine:!0,stripBracketedPaste:!0})),O&&it.createElement(Ze,{marginBottom:1},it.createElement(U$,{glyph:!1},O)),K&&it.createElement(Ze,{marginBottom:1},it.createElement(et,{color:LR.RED},K)),h&&it.createElement(Ze,{marginBottom:1},it.createElement(U$,{glyph:!1},h)),y&&it.createElement(Ze,{marginBottom:1},it.createElement(j$,{glyph:!1},y)),G.length>F&&it.createElement(et,{color:LR.DIM},"Showing ",i+1,"–",Math.min(i+F,G.length)," ","of ",G.length,i>0?" · ↑ more":"",i+F<G.length?" · ↓ more":""),it.createElement(bO,{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"),jW=lt(__name(function SessionView2({onSelectSession:e,onClose:t,currentSessionId:n}){return it.createElement(UW,{onSelectSession:e,onClose:t,currentSessionId:n})},"SessionView"));Vt(),Vt();var BW=__name(({onTrust:e,onExit:t})=>{const{exit:n}=st(),[r,o]=ct(1),s=process.cwd(),a=H(),i=a&&s.startsWith(a)?`~${s.slice(a.length)}`:s;return ot((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()}}),it.createElement(RO,{title:"Do you trust the files in this folder?",subtitle:i,hint:"↑/↓ to navigate · enter to select · esc to exit"},it.createElement(Ze,{flexDirection:"column"},it.createElement(et,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),it.createElement(Ze,{marginTop:1},it.createElement(et,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),it.createElement(Ze,{marginTop:1,flexDirection:"column"},it.createElement(Ze,null,it.createElement(s_,{isSelected:1===r}),it.createElement(a_,{isSelected:1===r,idleColor:IO}," ","1. Yes, proceed")),it.createElement(Ze,null,it.createElement(s_,{isSelected:2===r}),it.createElement(a_,{isSelected:2===r,idleColor:IO}," ","2. No, exit"))))},"TrustPrompt"),WW=lt(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return it.createElement(it.Fragment,null,it.createElement(tO,{staticKey:e}),it.createElement(BW,{onTrust:t,onExit:n}))},"TrustView"));function useAgentSlashCommandQueue({sessionId:e,isCmdCodeBusy:t,onCommand:n}){const r=dt(!1),o=dt(()=>{});o.current=()=>{if(t||r.current)return;const s=drainAgentSlashCommands({sessionId:e});0!==s.length&&(r.current=!0,(async()=>{try{for(const e of s)await n(e.command,void 0,void 0,pB(e.source))}finally{r.current=!1}hasAgentSlashCommands({sessionId:e})&&o.current()})())},ut(()=>{o.current()},[t,e,n]),ut(()=>subscribeAgentSlashCommands(()=>{o.current()}),[])}function useAuth(){const[e,t]=ct(()=>getConfiguredProviderSync()),[n,r]=ct(()=>getConfiguredModel()),[o,s]=ct(null),[a,i]=ct(!1),[l,c]=ct(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,authComponentInfo:o,setAuthComponentInfo:s,showProviderNotification:a,setShowProviderNotification:i,premiumCreditsExhausted:l,setPremiumCreditsExhausted:c,providerNotificationTimer:dt(null),modelNotificationTimer:dt(null)}}Vt(),__name(useAgentSlashCommandQueue,"useAgentSlashCommandQueue"),Vt(),PR(),__name(useAuth,"useAuth"),Vt(),PR();var HW=__name(()=>{const[e,t]=ct({isExecuting:!1,currentCommand:null});return{executeBash:pt(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");Vt(),Vt(),PR(),Vt(),PR();var GW={detectIDE:mE,isIdeIpcConnected:__name(async e=>{const t=CE(),n=await t.connect(e);return t.disconnect(),n},"isIdeIpcConnected"),log:dlog,platform:__name(()=>process.platform,"platform")};Vt();var VW=null,zW={};function requestReload(e){VW=e}function discardPendingReload(){VW=null}function consumePendingReload(){const e=VW;return VW=null,e}function setOriginalInvocation(e){zW=e}function getOriginalInvocation(){return zW}function resolveProviderOrReport(e){return resolveCommandProviderId(e.provider)||(e.setFeed(t=>[...t,kh(`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,kh("Provider login is not available here.")]):void t(t=>[...t,hh(`${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,hh(s.message)])}function handleLoginComplete({success:e,message:t,setShowLoginOverlay:n,setFeed:r,setStatus:o}){if(n(!1),!e)return r(e=>[...e,kh(t)]),void o("Ready...");r(e=>[...e,hh(t)]),invalidateBillingContext(),o("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,hh("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,hh(`${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,hh(n?`Logged out of ${r}`:`No saved ${r} credential found`)])}catch(n){const r=n instanceof Error?n.message:"Unknown error";t(t=>[...t,kh(`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?kh(s.notice.message):hh(s.notice.message)])}function parseChangelogVersions(e){return e.split(/^(?=## )/m).map(e=>e.trim()).filter(e=>e.startsWith("## "))}function findChangelogPath(e){let t=r(p(e));for(let e=0;e<6;e++){const e=n(t,"CHANGELOG.md");if(A(e))return e;const o=r(t);if(o===t)return null;t=o}return null}function handleChangelog({setFeed:e,rawArguments:t="",moduleUrl:n}){const r=findChangelogPath(n??import.meta.url);if(!r)return void e(e=>[...e,hh("No changelog available in this build.")]);const o=parseChangelogVersions(R(r,"utf8"));if(0===o.length)return void e(e=>[...e,hh("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,vh(`**What's new**\n\n${a}${l}`)])}async function releaseHarness(e){if(e){try{await(I$(e)?.flush())}catch{}A$(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([kh(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);I$(e)?.applyTodoUserEdit({todos:h}),g.bannerModelChanged||isWrappedChild()?hardResetForResize():UL(),l(e=>e+1)}__name(requestReload,"requestReload"),__name(discardPendingReload,"discardPendingReload"),__name(consumePendingReload,"consumePendingReload"),__name(setOriginalInvocation,"setOriginalInvocation"),__name(getOriginalInvocation,"getOriginalInvocation"),Vt(),PR(),__name(resolveProviderOrReport,"resolveProviderOrReport"),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Vt(),PR(),__name(parseChangelogVersions,"parseChangelogVersions"),__name(findChangelogPath,"findChangelogPath"),__name(handleChangelog,"handleChangelog"),Vt(),PR(),Vt(),PR(),__name(releaseHarness,"releaseHarness"),__name(handleSelectSession,"handleSelectSession");var KW="Nothing to clone yet.";async function handleCloneCommand(e){const t=I$(e.sessionId);if(t)try{const n=await t.cloneSession();if(!n)return void e.setFeed(e=>[...e,hh(KW)]);e.setFeed(e=>[...e,hh(`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,kh("Couldn't clone the session (storage error). Staying on the current session.")])}else e.setFeed(e=>[...e,hh(KW)])}async function handleCompactCommand({sessionId:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:o,setStaticKey:s}){try{r(!0),n("Compacting conversation...");const a=await x$({sessionId:e,baseUrl:getApiBaseUrl()}),i=await a.compact();UL(),s(e=>e+1);const l=buildCompactCommandNotice(i);t(e=>[...e,hh(l.message)]),r(!1),n("Ready..."),o(buildPostCompactContextUsage())}catch(e){t(t=>[...t,kh(buildCompactErrorNotice(e).message)]),r(!1),n("Ready...")}}__name(handleCloneCommand,"handleCloneCommand"),Vt(),PR(),__name(handleCompactCommand,"handleCompactCommand"),Vt(),PR();var qW=__name(e=>{const t=e.metadata?.blockOf;return"string"==typeof t?t:e.id},"groupIdOf"),YW=__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=qW(n),o=[];for(let n=t;n>=0;n--){const t=e[n];if(!t||"assistant"!==t.role||qW(t)!==r)break;const s=YW(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,hh("Nothing to copy yet — no reply in this session.")]);const r=await writeClipboardText(n),o=n.length.toLocaleString("en-US");t(e=>[...e,hh(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?jh(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")}function rehydrate(e){if("run_error"!==e.type)return e;const t=e.error??{};return{type:"run_error",error:"number"==typeof t.status?hn.generate(t.status,{error:{message:t.message,code:t.code}},t.message??"Run failed",void 0):Object.assign(new Error(t.message??"Run failed"),{name:t.name??"Error"})}}function createSandboxRunQuery(e){return async({input:t,onEvent:n,additionalContent:r,maxTurns:o})=>{const s=new Map,a=new Map;let i=null,l=null,c=-1,d=!1;const u=e.onAgentEvent(e=>{"run_error"===e.type&&(d=!0),n?.(rehydrate(e))}),m=e.onNotification(e=>{if("turn/completed"!==e.method)return;const t=e.params;s.set(t.turnId,t),a.get(t.turnId)?.(t)}),p=e.onEnded(t=>{l=t,c=e.streamNumber(),i?.(t)}),g=e.onGap(()=>{e.request({method:"session/state"}).then(e=>{const t=e.result?.busy;if(!1===t)for(const[e,t]of a)t({turnId:e,stopReason:"end_turn",finalText:"",turnCount:0}),a.delete(e)}).catch(()=>{})}),h=__name(t=>{const n=s.get(t);if(n)return Promise.resolve(n);const r=__name(e=>new Error(`The turn did not finish: ${e}.`),"unfinished");return l&&c===e.streamNumber()?Promise.reject(r(l)):new Promise((e,n)=>{a.set(t,e),i=__name(e=>n(r(e)),"ended")})},"awaitTurn"),f=__name(async(t,n)=>{takeInterruptWanted();const r=await e.request({method:"turn/start",params:{input:t,...n?.length?{additionalContent:n}:{},...void 0===o?{}:{maxTurns:o}}}),s=r.error;if(s)throw new Error(s.message??"The sandbox refused the turn");return takeInterruptWanted()&&e.request({method:"turn/interrupt"}).catch(()=>{}),h(r.result.turnId)},"start"),y=__name(async t=>{const n=await e.request({method:"session/state"}).catch(()=>null),r=n?.result;return void 0===r||!0===r.busy&&r.turnId===t.turnId||s.has(t.turnId)?h(t.turnId):(await t.reload().catch(()=>{}),{turnId:t.turnId,stopReason:"end_turn",finalText:"",turnCount:0})},"watchAdopted"),S=t===ON?takeAdoptedTurn():null;try{let e=S?await y(S):await f(t,r);for(;e.leftover?.length&&"interrupted"!==e.stopReason;)e=await f(joinLeftover(e.leftover));return e.error&&!d&&n?.(rehydrate({type:"run_error",error:e.error})),await(S?.afterward().catch(()=>{})),{finalText:e.finalText,stopReason:e.stopReason,turnCount:e.turnCount}}finally{u(),m(),p(),g()}}}function joinLeftover(e){const t=[];for(const n of e)"string"==typeof n?t.push({type:"text",text:n}):t.push(...n);return t.every(e=>"text"===e.type)?t.map(e=>e.text).join("\n\n"):t}async function steerSandbox(e){const t=(e.images??[]).map(e=>({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})),n=t.length>0?[...t,{type:"text",text:e.input}]:e.input;return void 0===(await e.connection.request({method:"turn/steer",params:{input:n}})).error}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,source:d,isRelayed:u,hiddenMessages:m,isGoalContinuation:p,isGoalBootstrap:g,suppressUserEcho:h,feed:f,setFeed:y,setLiveEntries:S,isCmdCodeBusy:w,setIsCmdCodeBusy:v,setQueuedMessages:k,setStatus:C,setInteractionTokens:b,updateStatus:E,setUpdateStatus:T,billingLink:P,setBillingLink:M,currentModel:x,currentProvider:I,premiumCreditsExhausted:A,setPremiumCreditsExhausted:R,setCurrentModel:L,sessionId:O,isSubmittingRef:D,setInput:$,setStaticKey:N,executeBash:_}=e,F=resolveSubmitStartPlan({role:t,input:n,isCmdCodeBusy:w,isSubmitting:D.current,displayMessage:i,isAutomated:l,isMeta:c,source:d,isRelayed:u,hiddenMessages:m,images:r,ideContext:s,ideHint:a});if("skip"===F.kind&&!n.length)return F.outcome;if(E&&T(null),b(0),"skip"===F.kind)return F.outcome;if("bash"===F.kind){const e=sandboxBashMessage();if(e)return y([...f,hh(e)]),$(""),"completed";D.current=!0;const t=wh(n);return y([...f,t]),$(""),await _(n,e=>{y(e)},()=>{UL(),N(e=>e+1)}),D.current=!1,"completed"}if("queue"===F.kind){const e=getSandboxConnection();return e&&!c&&await steerSandbox({connection:e,input:n,...r?{images:r}:{}}).catch(()=>!1)?(y(e=>[...e,gh(n)]),l||$(""),F.outcome):(k(e=>[...e,F.queuedMessage]),l||$(""),F.outcome)}D.current=!0;const U=await runModInputInterception(e);if("handled"===U.action){D.current=!1;const e=U.message;return e&&y(t=>[...t,hh(e)]),"skipped"}const j="transform"===U.action?U.text:n;await loadCustomProviderModels();const B=isSandboxMode()?null:await checkOAuthSetupRequired({currentProvider:I??null,isByokModel:isByok({model:x??""}),providerAuthHeaders:providerAuthHeaders});if(B)return D.current=!1,C(B),y(e=>[...e,kh(B)]),"skipped";v(!0),C(Lh()),l||$("");let W=!1,H=null,G=null,V=null,z=0;const K=createSubmitGoalSupervisor(e);let q=null;const Y=resolvePremiumCreditsPreflight({premiumCreditsExhausted:A,currentModel:x});if(Y.blocked)return W=!0,C(Y.status),y(e=>[...e,hh(Y.message)]),v(!1),D.current=!1,Y.outcome;try{q=await K.getGoalTurnBudget();const e=getSandboxConnection();if(isSandboxMode()&&!e)return y(e=>[...e,hh('The sandbox is not connected yet. Wait for the "Connected to sandbox" line (or its error), then send again.')]),D.current=!1,"completed";const t=e?null:await x$({sessionId:O,baseUrl:getApiBaseUrl()});if(g&&!isCommandGoalLoopArmed(O))return"skipped";const n=clipboardImagesToUserContent(r),l=s?`${s}\n\n${j}`:j,c=n.length>0?[...n,{type:"text",text:l}]:s?[{type:"text",text:l}]:void 0,d={...r&&r.length>0?{images:r,...o?{imageTokenPaths:o}:{}}:{},...a?{ideHint:a}:{}};trackFirstMessage();const u=await runHarnessTurnIntoFeed({harness:t,input:j,turnUserInput:c,runQuery:e?createSandboxRunQuery(e):e=>runHarnessQuery({...e,harness:e.harness}),setFeed:y,setLiveEntries:S,displayMessage:i,suppressUserEcho:h,additionalContent:hiddenMessagesToUserContent(m),inputMeta:F.inputMeta,maxTurns:q?.remainingTurns,onRoundTrip:__name(e=>{z=e},"onRoundTrip"),echoMetadata:Object.keys(d).length>0?d:void 0,setStatus:C,onInteractionTokens:b,onRunError:__name(e=>{G=e},"onRunError"),routeEntry:createBlockCommittingRouter({setFeed:y,setLiveEntries:S}),scrubGoalCompleteMarker:isCommandGoalLoopArmed(O)});if(G){const e=x?byokProviderId({model:x}):void 0;throw formatRunError(G,e?{byokProvider:e}:void 0)}return V=u.finalText,z=u.turnCount,"completed"}catch(e){const t=resolveSubmitErrorAction({error:e,sessionId:O});if("interrupted"===t.kind)return W=!0,t.outcome;if(trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"submit_error"}),context:{component:qo.SUBMIT,heading:"Prompt submission failed",code:t.kind}}),W=!0,H=t.goalErrorKind,"insufficient-credits"===t.kind){C(t.status);const e=await getBillingLink({billingLink:P,setBillingLink:M});return y(t=>[...t,kh(buildInsufficientCreditsSubmitActionMessage({billingUrl:e}))]),t.outcome}if("premium-credits-exhausted"===t.kind)return R?.(!0),L?.(t.fallbackModelId),UL(),N(e=>e+1),C(t.status),y(e=>[...e,hh(t.message)]),t.outcome;C(t.status);const n="info"===t.renderKind?hh(t.message):kh(t.message);return y(e=>[...e,n]),t.outcome}finally{v(!1),W||C("Ready..."),D.current=!1,await K.afterTurn({assistantText:W?null:V,errorKind:W?H:null,isGoalContinuation:p,turnsUsed:z,goalStartedAt:q?.startedAt})}return"skipped"}function emitGoalNotice(e,t){e(e=>[...e,hh(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=>(I$(t)??await x$({sessionId:t,baseUrl:getApiBaseUrl()})).verifyGoal(e),"verifyCompletion"),getEvidence:__name(()=>{const e=I$(t);return e?harnessRecentToolEvidence(e):""},"getEvidence"),emitCompletion:__name(e=>{n(t=>[...t,hh("",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,kh(qC)]);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,kh(buildDesignSkillLoadErrorMessage(t))])}}__name(findLastAssistantText,"findLastAssistantText"),__name(handleCopy,"handleCopy"),Vt(),PR(),Vt(),PR(),Vt(),PR(),__name(getAuthKey3,"getAuthKey"),__name(trackFirstMessage,"trackFirstMessage"),Vt(),PR(),__name(isWhitespaceOnly3,"isWhitespaceOnly"),__name(routeTodoWriteEntry,"routeTodoWriteEntry"),__name(createBlockCommittingRouter,"createBlockCommittingRouter"),Vt(),PR(),__name(rehydrate,"rehydrate"),__name(createSandboxRunQuery,"createSandboxRunQuery"),__name(joinLeftover,"joinLeftover"),__name(steerSandbox,"steerSandbox"),__name(getBillingLink,"getBillingLink"),__name(runModInputInterception,"runModInputInterception"),__name(handleSubmit,"handleSubmit"),__name(emitGoalNotice,"emitGoalNotice"),__name(createSubmitGoalSupervisor,"createSubmitGoalSupervisor"),__name(handleDesignCommand,"handleDesignCommand"),Vt(),PR();var QW="Nothing to export yet — the transcript is created on the first message.",JW=new Set(["html","jsonl","md"]);function matchFormatKeyword(e){const t=e.toLowerCase();return JW.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(A(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=Lt.isSupported?createOSC8Link(fileUrl(e.path),t,!1):t;return`Exported ${e.formatLabel} session to ${n}`}async function buildSessionHtmlExport(e){const{messages:t}=await loadCommandSessionMessages({sessionId:e.sessionId});if(0===t.length)return null;const n=await loadCommandUserRenamedTitle({sessionId:e.sessionId})??e.sessionId;return renderSessionHtml({messages:fromV2(t.map(e=>e.message)),title:n,sessionId:e.sessionId,exportedAt:(new Date).toISOString(),...e.currentModel?{model:e.currentModel}:{}})}async function buildSessionMarkdownExport(e){const{messages:t}=await loadCommandSessionMessages({sessionId:e.sessionId});if(0===t.length)return null;const n=await loadCommandUserRenamedTitle({sessionId:e.sessionId})??e.sessionId;return renderSessionMarkdown({messages:fromV2(t.map(e=>e.message)),title:n,sessionId:e.sessionId,exportedAt:(new Date).toISOString(),...e.currentModel?{model:e.currentModel}:{}})}async function exportJsonl(e){const t=n(getProjectSessionDir({env:process.env,cwd:e.cwd}),`${e.sessionId}.jsonl`);if(A(t)){try{j(t,e.target)}catch(t){const n=t instanceof Error?t.message:String(t);return void e.setFeed(e=>[...e,hh(`Export failed: ${n}`)])}e.setFeed(t=>[...t,hh(exportedMessage({path:e.target,formatLabel:"JSONL"}))])}else e.setFeed(e=>[...e,hh(QW)])}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,hh(`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,hh(`Export failed: ${n}`)])}e.setFeed(t=>[...t,hh(exportedMessage({path:e.target,formatLabel:"HTML"}))])}else e.setFeed(e=>[...e,hh(QW)])}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,hh(`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,hh(`Export failed: ${n}`)])}e.setFeed(t=>[...t,hh(exportedMessage({path:e.target,formatLabel:"Markdown"}))])}else e.setFeed(e=>[...e,hh(QW)])}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,hh(`Unknown export extension "${r.extension}". Supported export formats: .html, .jsonl, .md`)])}async function handleForkCommand(e,t){const n=I$(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,fh({name:r.title})])}catch{e.setFeed(e=>[...e,kh(Uf)])}else e.setFeed(e=>[...e,"error"===r.notice.kind?kh(r.notice.message):hh(r.notice.message)])}function setMode(e,t){e.permissionModeRef.current=t,e.setPermissionMode(t),I$(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,hh(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"),Vt(),PR(),__name(handleForkCommand,"handleForkCommand"),Vt(),PR(),__name(setMode,"setMode"),__name(handlePlanCommand,"handlePlanCommand"),Vt(),PR();var XW=[{title:"Composing",rows:[{keys:"Enter",action:"Send the prompt"},{keys:"Shift+Enter / Alt+Enter",action:"Insert a newline"},{keys:"Ctrl+G",action:"Edit the prompt in $EDITOR"},{keys:"Ctrl+S",action:"Stash / restore the current prompt"},{keys:"↑ / ↓",action:"Browse prompt history"},{keys:"@",action:"Mention a file (fuzzy search)"},{keys:"/",action:"Open the command menu"},{keys:"!",action:"Bash mode — run a shell command"}]},{title:"While it works",rows:[{keys:"Esc",action:"Interrupt the current turn"},{keys:"Type + Enter",action:"Queue a steering message"},{keys:"Ctrl+X",action:"Open the todo manager (/todos) for the current plan"}]},{title:"Transcript",rows:[{keys:"Ctrl+O",action:"Toggle expanded tool output"},{keys:"Ctrl+E / Ctrl+Y",action:"Toggle the full transcript"}]},{title:"Session & modes",rows:[{keys:"Shift+Tab",action:"Cycle mode: standard → accept edits → plan → yolo"},{keys:"Alt+P",action:"Quick model switch"},{keys:"Esc Esc",action:"Rewind to a checkpoint"},{keys:"Ctrl+C Ctrl+C",action:"Exit"}]}];function buildHotkeysMarkdown(){const e=["**Keyboard shortcuts**"];for(const t of XW){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,vh(buildHotkeysMarkdown())])}async function handleImportCommand({setFeed:e},t=""){const n=resolveAgentImportSourceArg(t);if(!n.ok)return void e(e=>[...e,kh(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,hh("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,hh(formatAgentImportSummary(o))])}catch(t){e(e=>[...e,kh(`Import failed: ${t instanceof Error?t.message:"unknown error"}`)])}}function setMode2(e,t){e.permissionModeRef.current=t,e.setPermissionMode(t),I$(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,hh(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?kh(t.notice.message):hh(t.notice.message)]),"renamed"===t.kind){e.setRenamedTerminalTitle(t.name);try{(e.harness??await x$({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 x$({sessionId:e,baseUrl:getApiBaseUrl()}),o=await r.regenerateTitle();if(!o)return void t(e=>[...e,hh("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,hh("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=I$(e.sessionId)?.getSessionStats().name,n=t?null:await loadCommandSessionMeta({sessionId:e.sessionId}).catch(()=>null),r=t??n?.title;e.setFeed(e=>[...e,hh(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=I$(e),o=resolveRewindCommand({hasActiveConversation:Boolean(r),checkpointCount:r?.listCheckpoints().length??0});"notice"!==o.kind?n(!0):t(e=>[...e,"error"===o.notice.kind?kh(o.notice.message):hh(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=I$(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)}),UL(),a(e=>e+1),c.promptToRestore&&i(c.promptToRestore),r(e=>[...e,hh(c.notice.message)]),void o(c.statusMessage);r(e=>[...e,"error"===c.notice.kind?kh(c.notice.message):hh(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,hh("No active session.")]);const r=n(getProjectSessionDir({env:process.env,cwd:getCurrentWorkingDirectory()}),`${e}.jsonl`),o=formatSessionFileLine({absolutePath:r,exists:A(r),linksSupported:Lt.isSupported});t(t=>[...t,hh(`Session ID: ${e}\nCurrent session file: ${r}`,{isSessionFile:!0,sessionFileId:e,sessionFileLine:o})])}__name(buildHotkeysMarkdown,"buildHotkeysMarkdown"),__name(handleHotkeys,"handleHotkeys"),Vt(),PR(),__name(handleImportCommand,"handleImportCommand"),Vt(),PR(),__name(setMode2,"setMode"),__name(handleModeCommand,"handleModeCommand"),Vt(),PR(),__name(applyRenameResult,"applyRenameResult"),__name(autoRenameSession,"autoRenameSession"),__name(handleRenameCommand,"handleRenameCommand"),__name(handleNameCommand,"handleNameCommand"),Vt(),PR(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),Vt(),PR(),__name(compactTranscriptPath,"compactTranscriptPath"),__name(formatSessionFileLine,"formatSessionFileLine"),__name(handleSessionFile,"handleSessionFile"),Vt(),PR();var ZW=xe(f),eH=/https:\/\/gist\.github\.com\/\S+/;function parseGistUrl(e){const t=eH.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 ZW("gh",["gist","create",e,"--desc","Command Code session"],{encoding:"utf8"});return{stdout:String(t)}}async function resolveShareGistFormat(e){const t=(e??"").trim();return t?matchFormatKeyword(t):resolveConfiguredExportFormat((await loadUserConfig()).defaultShareGistFormat)}async function writeGistPayload(e){const t=n(e.tempDir,`command-code-session-${e.sessionId.slice(0,8)}.${e.format}`);if("jsonl"===e.format){const r=n(getProjectSessionDir({env:process.env,cwd:getCurrentWorkingDirectory()}),`${e.sessionId}.jsonl`);return A(r)?(j(r,t),t):null}if("md"===e.format){const n=await e.buildMarkdownExport({sessionId:e.sessionId,currentModel:e.currentModel});return n?(await q(t,n,"utf8"),t):null}const r=await e.buildHtmlExport({sessionId:e.sessionId,currentModel:e.currentModel});return r?(await q(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,hh(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 le(n(G(),"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: ${Lt.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 Z(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?I$(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?I$(e):void 0});if("no-session"!==a.status){if("not-shared"===a.status)return o(a.message),void setTimeout(()=>o(""),fC);if("error"===a.status)return r(a.message),void setTimeout(()=>r(""),fC);o(a.message),r(""),n(null),setTimeout(()=>{o("")},fC)}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,hh(`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,hh(`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,hh(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=I$(e),a=resolveTreeCommand({hasActiveConversation:Boolean(s),treeEntryCount:s?.getSessionTree().length??0});if("notice"===a.kind)return void t(e=>[...e,"error"===a.notice.kind?kh(a.notice.message):hh(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=I$(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,hh("Already at this point")]),{aborted:!1}):(s(!1),o(reconstructFeedFromMessages(harnessSessionMessages(l))),UL(),a(e=>e+1),r.editorText&&i(r.editorText),o(e=>[...e,hh("Navigated to selected point")]),{aborted:!1})}catch(e){return o(t=>[...t,kh(`Failed to navigate: ${actionErrorMessage(e)}`)]),{aborted:!1}}}function handleTreeCancel({setShowTreeSelector:e}){e(!1)}function handleTreeAbortSummary({sessionId:e}){I$(e)?.abortBranchSummary()}function handleTreeLabel({entryId:e,label:t,sessionId:n,setFeed:r}){const o=I$(n);if(o)try{o.setTreeLabel({targetId:e,label:t})}catch(e){r(t=>[...t,kh(`Failed to set label: ${actionErrorMessage(e)}`)])}}function announceCompletedUpdate({fromVersion:e,toVersion:t}){console.log(Pt.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:qo.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"),Vt(),PR(),__name(loadPersistedTraceIds,"loadPersistedTraceIds"),__name(handleTrace,"handleTrace"),Vt(),PR(),__name(actionErrorMessage,"actionErrorMessage"),__name(handleTreeCommand,"handleTreeCommand"),__name(handleTreeSelect,"handleTreeSelect"),__name(handleTreeCancel,"handleTreeCancel"),__name(handleTreeAbortSummary,"handleTreeAbortSummary"),__name(handleTreeLabel,"handleTreeLabel"),Vt(),PR(),Vt(),PR(),__name(announceCompletedUpdate,"announceCompletedUpdate"),__name(trackUpdateFailure,"trackUpdateFailure");var tH={createLifecycleEventClient:__name(()=>createApiClient({baseUrl:getApiBaseUrl()}),"createLifecycleEventClient"),isTelemetryEnabled:isTelemetryEnabled,log:dlog,onCompletedUpdate:announceCompletedUpdate,trackUpdateFailure:trackUpdateFailure},nH={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:nH,host:tH,copy:{binCommand:`${getBinaryCommand()}`,updateCommand:"npm i -g command-code"},emit:s});trackTuiUpdateCommandTelemetry(a),"error"!==a.level?e(e=>[...e,hh(a.message,a.metadata)]):e(e=>[...e,kh(a.message)])}function tildeHome(e){const t=W.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function formatWorktreePathLine(e){return` ${yt.dim(ft.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?yt.dim(` (branch ${a.target.branch}${a.usedRemote?", from origin":""})`):"",n=a.created&&a.copiedFiles>0?yt.dim(` · copied ${a.copiedFiles} file(s)`):"",r=a.created&&a.copyFailedFiles.length>0?yt.dim(` · ${a.copyFailedFiles.length} include copy failure(s)`):"";process.stdout.write(`${yt.cyan(ft.squareSmallFilled)} ${e} worktree ${yt.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"),Vt(),PR(),Vt(),PR(),__name(tildeHome,"tildeHome"),__name(formatWorktreePathLine,"formatWorktreePathLine"),__name(enterWorktreeFromFlag,"enterWorktreeFromFlag");var rH=__name((e,t)=>e.setFeed(e=>[...e,hh(t)]),"info"),oH=__name((e,t)=>e.setFeed(e=>[...e,kh(t)]),"error");function renderList(e,n){const r=listWorktrees(e);return 0===r.length?"No worktrees found.":["Worktrees:",...r.map(r=>{const o=samePath2(r.path,e)?"●":"○",s=t.relative(n,r.path),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 oH(e,"/worktree requires a git repository.");const r=getMainWorktreeRoot(n)??n,o=t[0]?.toLowerCase();if(!o||"list"===o||"ls"===o)return void rH(e,renderList(n,r));if("remove"===o||"rm"===o){const o=t[1];return o?void await handleRemove(e,o,n,r):void oH(e,"Usage: /worktree remove <name>")}const s="new"===o||"create"===o||"add"===o?t[1]:t[0];await handleSwitch(e,s,n)}async function handleRemove(e,n,r,o){const s=resolveTarget(n,o);if(samePath2(s.worktreePath,r))return void oH(e,"Can't remove the worktree you're in. Switch away first, then remove it.");if(!listWorktrees(r).some(e=>samePath2(e.path,s.worktreePath)))return void oH(e,`No worktree named "${n}".`);const a=removeWorktree({worktreePath:s.worktreePath,cwd:r,deleteBranch:isManagedWorktreePath(s.worktreePath,o)?s.branch:void 0});a.ok?rH(e,`Removed worktree "${n}".`):oH(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 oH(e,`Couldn't create worktree: ${r.error}`);if(samePath2(r.target.worktreePath,n))return void rH(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))`:"";rH(e,`${o} worktree "${r.target.name}"${s}${a}. Switching… (a fresh session starts in the worktree; this one stays resumable).`),await(I$(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,vh(Wh)])}async function handleTerminalSetupCommand({setFeed:e}){const t=gh("/terminal-setup"),n=setupVSCodeTerminal(),r=bh(n.message,!n.success,n.details),o=bh("Terminal tab titles need no setup — titles are set automatically via standard escape sequences (VS Code 1.117+ honors them out of the box).",!1),s=isKittyKeyboardActive()?[bh("Shift+Enter already works natively in this terminal (kitty keyboard protocol) — the VS Code keybindings only apply inside a VS Code-family terminal.",!1)]:[];e(e=>[...e,t,r,o,...s])}async function handleIDESetupCommand({setFeed:e}){const t=await runIdeSetup({host:GW,moduleUrl:import.meta.url}),n=Eh(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(),UL(),r(null),o(!1),s(""),await deleteCommandSessionShareInfo({sessionId:c}).catch(()=>{});const m=I$(c);m?.stopBackgroundLearning(),await(m?.flush().catch(()=>{})),A$(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,hh(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,hh(s.notice.message,s.notice.metadata)]),o&&"notice"===s.status&&"cleared"===s.notice.metadata?.goalNoticeKind&&I$(e.sessionId)?.requestStopAfterTurn(),"start"===s.status&&await runGoalTurn(e,s.goalText,n,r)}async function openExternalSlashCommandTarget({setFeed:e,target:t}){e(e=>[...e,hh(`Opening ${createOSC8Link(t.url,t.noticeLabel,!1)} in your browser…`)]);try{await xt(t.url,{wait:!1,background:!0})}catch{const{fallback:n}=t;if("info"===n.kind)return void e(e=>[...e,hh(n.message)]);e(e=>[...e,kh("Failed to open browser"),vh(createOSC8Link(t.url,n.label,!1))])}}function handleLearnCommand({setAutoLearnTaste:e,setShowTasteOnboarding:t,setTasteOnboardingEntryId:n,setFeed:r}){e(!0),t(!0);const o=Ch();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}),s=sandboxGateMessage(e.trim().split(/\s+/)[0]?.split(":")[0]?.replace(/^\//,"")??"");if(s)return t.setFeed(e=>[...e,hh(s)]),{status:"handled"};if("blocked"===o.kind)return t.setFeed(e=>[...e,hh(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,hh("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,kh(`No skill named "${o.skillName}". Run /skills to see what is installed.`)]),{status:"handled"})}if("unknown"===o.kind)return{status:"unknown"};const{commandName:a,rawArguments:i,positionalArgs:l}=o;if("/exit"===a||"/quit"===a)return discardPendingReload(),t.setShouldExit(!0),{status:"handled"};if("/reload"===a)return await(I$(t.sessionId)?.flush().catch(()=>{})),requestReload(buildReloadCarryoverState({sessionId:t.sessionId,permissionMode:t.permissionModeRef.current})),t.setShouldExit(!0),{status:"handled"};if("/clear"===a)return await handleClearCommand(t),{status:"handled"};if("/help"===a)return await handleHelpCommand(t),{status:"handled"};if("/share"===a){const e=i.trim();return"gist"===e||e.startsWith("gist ")?(await handleShareGistCommand({sessionId:t.sessionId,currentModel:t.currentModel,rawFormatArg:e.slice(4).trim(),setFeed:t.setFeed}),{status:"handled"}):(await handleShareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setShowShareNotification:t.setShowShareNotification}),{status:"handled"})}if("/unshare"===a)return await handleUnshareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setUnshareNotificationMessage:t.setUnshareNotificationMessage}),{status:"handled"};if("/taste"===a)return t.setShowTasteConfig(!0),{status:"handled"};if("/learn-taste"===a)return handleLearnCommand(t),{status:"handled"};if("/design"===a)return await handleDesignCommand({ctx:t,rawArguments:i,positionalArgs:l,command:e}),{status:"handled"};if("/skills"===a)return t.setShowSkillsConfig(!0),{status:"handled"};if("/plans"===a)return t.setPlansTarget(i.trim()||null),t.setShowPlansView(!0),{status:"handled"};if("/plan-review"===a)return t.setPlansTarget(PW),t.setShowPlansView(!0),{status:"handled"};if("/config"===a)return t.setShowSettingsConfig(!0),{status:"handled"};if("/connect"===a)return t.setShowProviderSelector(!0),{status:"handled"};if("/model"===a)return await handleModelCommand(t,i),{status:"handled"};if("/effort"===a)return await handleEffortCommand(t,i),{status:"handled"};if("/memory"===a)return t.setShowMemorySelector(!0),{status:"handled"};if("/resume"===a||"/sessions"===a)return t.setShowSessionSelector(!0),{status:"handled"};if("/fork"===a)return await handleForkCommand(t,i.trim()||void 0),{status:"handled"};if("/worktree"===a)return await handleWorktreeCommand(t,l),{status:"handled"};if("/clone"===a)return await handleCloneCommand(t),{status:"handled"};if("/init"===a)return await handleInitCommand(t),{status:"handled"};if("/import"===a)return await handleImportCommand(t,i),{status:"handled"};if("/goal"===a)return await handleGoalCommand(t,i,n,r),{status:"handled"};if("/agents"===a)return t.setShowAgentsConfig(!0),{status:"handled"};if("/mcp"===a)return t.setShowMcpManager(!0),{status:"handled"};if("/compact"===a)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"===a)return t.setShowCompactModeSelector(!0),{status:"handled"};if("/update"===a)return t.setInput(""),await handleUpdateCommand({setFeed:t.setFeed,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setUpdateStatus:t.setUpdateStatus,pinnedStatusRef:t.pinnedStatusRef}),{status:"handled"};if("/context"===a)return t.setShowContextView(!0),{status:"handled"};if("/rewind"===a)return handleRewindCommand({sessionId:t.sessionId,setFeed:t.setFeed,setShowRewindSelector:t.setShowRewindSelector}),{status:"handled"};if("/tree"===a)return await handleTreeCommand({sessionId:t.sessionId,setFeed:t.setFeed,setShowTreeSelector:t.setShowTreeSelector,setTreeFilterMode:t.setTreeFilterMode,setTreeBranchSummarySkipPrompt:t.setTreeBranchSummarySkipPrompt}),{status:"handled"};if("/login"===a)return await handleLoginCommand({provider:i,setFeed:t.setFeed,setShowLoginOverlay:t.setShowLoginOverlay,setAuthComponentInfo:t.setAuthComponentInfo}),t.setInput(""),{status:"handled"};if("/logout"===a)return await handleLogoutCommand({provider:i,setFeed:t.setFeed,setRetryAttempt:t.setRetryAttempt,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),t.setInput(""),{status:"handled"};if("/learn"===a){const e=resolveExternalSlashCommandTarget({commandName:a});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),{status:"handled"}}if("/feedback"===a){const e=resolveExternalSlashCommandTarget({commandName:a,rawArguments:i});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),t.setInput(""),{status:"handled"}}if("/trace"===a)return await handleTrace({setFeed:t.setFeed,sessionId:t.sessionId}),t.setInput(""),{status:"handled"};if("/copy"===a)return await handleCopy({feed:t.feed,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/export"===a)return await handleExport({sessionId:t.sessionId,rawPath:i,currentModel:t.currentModel,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/changelog"===a)return handleChangelog({setFeed:t.setFeed,rawArguments:i}),t.setInput(""),{status:"handled"};if("/hotkeys"===a)return handleHotkeys({setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/todos"===a)return 0===getSessionTodos().length?t.setFeed(e=>[...e,hh("No todos in this session yet.")]):requestTodosManagerOpen(),t.setInput(""),{status:"handled"};if("/session-file"===a)return handleSessionFile({sessionId:t.sessionId,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/terminal-setup"===a)return await handleTerminalSetupCommand(t),{status:"handled"};if("/ide"===a)return await handleIDESetupCommand(t),{status:"handled"};if("/add-dir"===a)return t.setShowAddDirModal(!0),{status:"handled"};if("/rename"===a)return await handleRenameCommand({name:i.trim(),sessionId:t.sessionId,setFeed:t.setFeed,setRenamedTerminalTitle:t.setRenamedTerminalTitle,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),t.setInput(""),{status:"handled"};if("/name"===a)return await handleNameCommand({name:i.trim(),sessionId:t.sessionId,setFeed:t.setFeed,setRenamedTerminalTitle:t.setRenamedTerminalTitle}),t.setInput(""),{status:"handled"};if("/usage"===a)return t.setShowUsageOverlay(!0),{status:"handled"};if("/theme"===a)return await handleThemeCommand(t,i),{status:"handled"};if("/rc"===a)return await handleRcCommand(t,i),{status:"handled"};if("/plan"===a)return await handlePlanCommand({rawArguments:i,ctx:t}),{status:"handled"};if("/mode"===a||a.startsWith("/mode:")){const e=a.startsWith("/mode:")?a.slice(6):i;return await handleModeCommand({rawArguments:e,ctx:t}),{status:"handled"}}if("/review"===a){const e=await resolveReviewSlashCommand({rawArguments:i});return"missing-gh"===e.status?(t.setFeed(t=>[...t,hh(e.message,e.metadata)]),t.setInput(""),{status:"handled"}):(await submitAutomatedSlashTurn({turn:e.turn,ctx:t}),{status:"handled"})}if("/pr-comments"===a){await submitAutomatedSlashTurn({turn:buildPrCommentsSlashTurn(),ctx:t});const e=I$(t.sessionId),n=resolvePrCommentsFollowUpInput(e?harnessSessionMessages(e):[]);return n&&t.setInput(n),{status:"handled"}}if("/status"===a)return t.setShowStatusView(!0),{status:"handled"};if("/upgrade"===a){const e=resolveExternalSlashCommandTarget({commandName:a,billingUrl:await getBillingLink({billingLink:t.billingLink,setBillingLink:t.setBillingLink})});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),{status:"handled"}}if("/extra"===a){const e=resolveExternalSlashCommandTarget({commandName:a,billingUrl:await getBillingLink({billingLink:t.billingLink,setBillingLink:t.setBillingLink})});return e&&await openExternalSlashCommandTarget({setFeed:t.setFeed,target:e}),{status:"handled"}}const c=getActiveModHost(),d=a.slice(1);if(c?.commands().some(e=>e.name===d)){try{const e=await c.runCommand({name:d,args:i}),n=e?.message;n&&t.setFeed(e=>[...e,hh(n)]),e?.prompt&&await submitAutomatedSlashTurn({turn:buildAutomatedSlashTurn({commandName:d,rawArguments:i,fullPrompt:e.prompt}),ctx:t})}catch(e){t.setFeed(t=>[...t,kh(`Mod command /${d} failed: ${e instanceof Error?e.message:String(e)}`)])}return{status:"handled"}}const u=await resolveCustomSlashTurn({runtime:createNodeRuntime(),commandName:a,rawArguments:i,positionalArgs:l});if(u)return await submitAutomatedSlashTurn({turn:u,ctx:t}),{status:"handled"};return await handleSkillCommand({commandName:a,command:e,rawArguments:i,positionalArgs:l,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,hh(s.message)]),{status:"handled"}):"load-error"===s.status?(o.setFeed(e=>[...e,kh(s.message)]),{status:"handled"}):(await submitAutomatedSlashTurn({turn:s.turn,ctx:o}),{status:"handled"})}__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"),Vt();var sH=new Set(["info","error"]),aH=__name(e=>{if(!sH.has(e.role))return;const t="string"==typeof e.input?e.input.trim():"";return""===t?void 0:t},"spokenText");function echoFeedToChat(e){if("remote"!==e.origin)return e.setFeed;const t=getActiveRemote(),n=t?.bridge.ownerChatId;if(!t||void 0===n)return e.setFeed;const r=new Set;return o=>{e.setFeed(e=>{const s="function"==typeof o?o(e):o;for(const o of s.slice(e.length)){const e=aH(o);void 0===e||r.has(o.id)||(r.add(o.id),t.bridge.sendNote(n,e))}return s})}}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=mt(()=>({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,setShowRcSelector:o.setShowRcSelector,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=dt(m);return p.current=m,{commandCtx:m,onCommand:pt((e,t,n,r)=>handleCommand(e,{...p.current,...r?{origin:r}:{},setFeed:echoFeedToChat({setFeed:p.current.setFeed,origin:r})},t,n),[])}}__name(echoFeedToChat,"echoFeedToChat"),__name(useCommandCtx,"useCommandCtx"),Vt(),PR();var iH=ms,lH=ps;function useCreditWarning({interactionTokens:e,currentModel:t}){const[n,r]=ct(null),o=dt(null),s=dt(null),a=dt(null),i=pt(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},iH)}catch{}},[]);return ut(()=>{if(0!==e&&!isLocalOnly()&&!isByok({model:t}))return s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{i(),s.current=null},lH),()=>{s.current&&clearTimeout(s.current)}},[e,t,i]),ut(()=>()=>{a.current&&clearTimeout(a.current),s.current&&clearTimeout(s.current)},[]),{creditWarning:n}}__name(useCreditWarning,"useCreditWarning"),Vt(),PR();var cH=createNodeRuntime();function useCronWakeup({sessionId:e,onSubmit:t}){const n=dt(t),r=dt(e),o=dt(Promise.resolve());ut(()=>{n.current=t},[t]),ut(()=>{r.current=e},[e]),ut(()=>{const e=subscribeCronFire(e=>{o.current=o.current.catch(()=>{}).then(async()=>{const t="loop"===e.kind||!0===e.loopOwned,o=I$(r.current);if(t&&o&&!o.hasScheduledTask({id:e.taskId}))return;const s=await buildScheduledTaskWakeupSubmission({event:e,runtime:cH});await n.current(s)}),o.current.catch(()=>{})});return()=>{e()}},[])}function useExit(){const[e,t]=ct(!1),[n,r]=ct(null),o=dt(null),s=dt(0),a=dt(null),i=pt(()=>{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(useCronWakeup,"useCronWakeup"),Vt(),__name(useExit,"useExit"),Vt(),PR(),Vt(),PR();var dH="1"===process.env.CMD_TEST_INJECT_LIVE_ENTRY;function makeInjectedShellEntry(e,t,n,r={}){return{...Sh("shell_command",t,{status:n}),id:e,...r}}function buildInjectedLiveEntry(){return dH?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 uH="1"===process.env.CMD_TEST_INJECT_STREAM,mH="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?Th(t,{id:mH,status:"running"}):"tool"===e?{...Sh("shell_command",t,{status:"running"}),id:mH}:"agent"===e?{...Ph({name:"Task",input:t}),id:mH}:{...yh(t),id:mH,metadata:{status:"running"}}}function makeStreamFinalEntry(e,t){return"reasoning"===e?Th(t,{id:mH}):"tool"===e||"agent"===e?{...Sh("shell_command",t,{}),id:mH,output:"done"}:{...yh(t),id:mH}}function maybeStartInjectedStream(e){if(!uH)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 pH="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 gH=(()=>{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(!pH)return;const t=createBlockCommittingRouter({setFeed:e.setFeed,setLiveEntries:e.setLiveEntries});let n=0;const r=setInterval(()=>{const e=gH[n];e?(t({...Sh("todo_write",_h("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 hH=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(hH)||hH<=0)return;const{setFeed:t}=e;let n=0;const r=setInterval(()=>{const e=n===hH-1,o=makeInjectedTurnEntry(n,e);t(e=>[...e,o]),n+=1,e&&clearInterval(r)},testTurnTickMs());return()=>clearInterval(r)}function useFeed(){const[e,t]=ct(()=>buildInjectedFeed()),n=pt(e=>{t(t=>applyFeedRetention("function"==typeof e?e(t):e))},[]);ut(()=>{trimStaticBuffer()},[e]);const[r,o]=ct(()=>{const e=buildInjectedLiveEntry();return e?[e]:[]}),[s,a]=ct([]),[i,l]=ct(dH),c=dt([]),d=pt(e=>{const t="function"==typeof e?e(c.current):e;c.current=t,a(t)},[]);return ut(()=>maybeStartInjectedTurns({setFeed:n}),[n]),ut(()=>maybeStartInjectedStream({setFeed:n,setLiveEntries:o,setIsCmdCodeBusy:l}),[]),ut(()=>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:L,setRetryAttempt:O,setStatus:D,pendingExitKey:$,setPendingExitKey:N,pendingExitKeyRef:_,lastExitKeyTimeRef:F,exitConfirmationTimeoutRef:U,resetPendingExitKey:j,pendingPermission:B,setPendingPermission:W,pendingQuestion:H,setPendingQuestion:G,setShouldExit:V,sessionId:z,handleToggleAutoAccept:K,handleDoubleEscapeEmpty:q,respondToPrompt:Y,createErrorEntry:Q}){const J=__name(()=>{I$(z)?.cancelLoops().then(e=>{if(0===e)return;const t=1===e?"task":"tasks";A(n=>[...n,hh(`Loop stopped · ${e} scheduled ${t} cancelled`,{isGoalNotice:!0,goalNoticeKind:"cleared"})])})},"cancelLoopsAndNotify"),X=__name(()=>{const e=getSandboxConnection();e?interruptSandboxTurn(e):interruptActiveTurn(),clearCommandGoalIfActive(z),J();const t=P.length>0;if(L(!1),O(null),R([]),D(sS),!t){const e=Q(oS);A(t=>[...t,e])}if(M.current.length>0){const e=M.current.filter(e=>!0!==e.isRelayed),t=M.current.filter(e=>!0===e.isRelayed);if(e.length>0){const t=formatQueuedMessagesForRequeue(e);x(e=>mergeRequeuedInput({queuedText:t,currentInput:e}))}I(t),M.current=t}},"handleInterrupt");ot((P,M)=>{const I=getKeybindings();if(keybindingMatches(I,"app.permission.cycle",P,M)||""===P||M.meta&&"m"===P)return void K();if(y&&M.escape)return void S(!1);if(w&&M.escape)return void v(!1);if(k&&M.escape)return void C(null);if(isTodosManagerOpen())return void($&&j());if(e||t||n||r||o||s||a||i||g||l||c||d||u||m||p)return void($&&j());const A=""===P||M.ctrl&&"c"===P,R=isSandboxMode()&&isSandboxConnecting();if(A){if(T&&!R)return void X();const e=Date.now(),t=e-F.current;return F.current=e,"ctrl-c"===_.current&&t<2e3?(U.current&&(clearTimeout(U.current),U.current=null),void V(!0)):(x(()=>""),_.current="ctrl-c",N("ctrl-c"),U.current&&clearTimeout(U.current),void(U.current=setTimeout(()=>{_.current=null,N(null),U.current=null},2e3)))}if(keybindingMatches(I,"app.tools.expand",P,M)){if(H?.params.planContent)return;return UL(),E("off"===b?"limited":"off"),void f(e=>e+1)}const L=isCtrlKey({inputChar:P,key:M,letter:"e",ctrlCode:5})||isCtrlKey({inputChar:P,key:M,letter:"y",ctrlCode:25}),O=null!==B&&"function"==typeof B.params?.explain;if("off"!==b&&L&&!O)return UL(),E("limited"===b?"full":"limited"),void f(e=>e+1);if("off"===b&&getSessionTodos().length>0&&keybindingMatches(I,"app.todos.toggle",P,M))return void requestTodosManagerOpen();if(keybindingMatches(I,"app.model.select",P,M)||isAltP(P))return void h(!0);if(!M.escape)return;if("off"!==b)return UL(),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");if(T&&!R)return void X();const z=R?getSandboxConnection():null;z?interruptSandboxTurn(z):J()})}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=pt(()=>{isSandboxMode()?t.setFeed(e=>[...e,hh("Permissions are bypassed in a sandbox session; the mode cannot be changed here yet.")]):a.setPermissionMode(e=>{const t=cyclePermissionMode({current:e,disableBypass:I$(c)?.isBypassDisabled()??!0}),n=resolvePendingPromptOnModeChange(t,{pendingIsRisky:void 0!==s.pendingPermission?.params?.risk});return n&&s.pendingPermission&&("approve"===n&&a.respondToPrompt(gM),s.pendingPermission.resolve("approve"===n),s.setPendingPermission(null)),I$(c)?.setPermissionMode({mode:t}),t})},[a.setPermissionMode,a.respondToPrompt,s.pendingPermission,s.setPendingPermission,c]),g=pt(()=>{a.setPermissionMode(e=>{const t="bypass"===e?e:"auto-accept";return I$(c)?.setPermissionMode({mode:t}),t})},[a.setPermissionMode,c]),h=pt(()=>{const e=!t.isCmdCodeBusy&&!s.pendingPermission&&!s.pendingQuestion,n=(I$(c)?.listCheckpoints().length??0)>0;e&&n&&r.setShowRewindSelector(!0)},[t.isCmdCodeBusy,s.pendingPermission,s.pendingQuestion,r.setShowRewindSelector,c]),f=pt(t=>{n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),t?.skipped&&r.setShowTasteSkipBanner(!0),e&&r.setShowSessionSelector(!0)},[e,n,r]),y=pt(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=pt(()=>{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:kh}),{handleToggleAutoAccept:p,handleEnableAutoAccept:g,handleDoubleEscapeEmpty:h,handleTasteOnboardingComplete:f,handleTrust:y,handleNoTrust:S}}function runGit2(e){return S(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}function warnAboutPromptTruncation(e){const t=e.trim().length;t<=Ox||console.error(Pt.yellow(`Warning: prompt is ${t} characters; only the first ${Ox} are sent.`))}function warnAboutLocalOnlyWork(e){e||console.error(Pt.yellow("Warning: local changes are not included (the sandbox works from the repo on GitHub)."))}function runSandboxStartPreflight(e){if(e.baseBranch&&!isValidSandboxBranchName(e.baseBranch))throw new Error("Invalid --base branch name.");warnAboutPromptTruncation(e.prompt);const t=validateSandboxGitRepo({run:__name(({command:e})=>runGit2(e),"run")});return warnAboutLocalOnlyWork(t.isClean),{repoUrl:t.repoUrl}}function createSandboxTransport(){const e=createApiClient({baseUrl:getApiBaseUrl(),timeout:3e5});return{post:__name(t=>e.post({endpoint:t.route,body:t.body}),"post"),get:__name(t=>e.get({endpoint:t.route}),"get")}}function deadlineFor(e){return"session/set_model"===e||"session/set_effort"===e?6e5:3e4}__name(testTurnChars,"testTurnChars"),__name(testTurnTickMs,"testTurnTickMs"),__name(makeInjectedTurnEntry,"makeInjectedTurnEntry"),__name(maybeStartInjectedTurns,"maybeStartInjectedTurns"),__name(useFeed,"useFeed"),Vt(),PR(),PR(),Vt(),PR(),__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Vt(),PR(),Vt(),PR(),Vt(),PR(),__name(runGit2,"runGit"),__name(warnAboutPromptTruncation,"warnAboutPromptTruncation"),__name(warnAboutLocalOnlyWork,"warnAboutLocalOnlyWork"),__name(runSandboxStartPreflight,"runSandboxStartPreflight"),Vt(),PR(),__name(createSandboxTransport,"createSandboxTransport"),__name(deadlineFor,"deadlineFor");var fH="deadline";function withDeadline(e){return new Promise((t,n)=>{const r=setTimeout(()=>n(new Error(fH)),e.ms);e.promise.then(e=>{clearTimeout(r),t(e)},e=>{clearTimeout(r),n(e)})})}function isDeadline(e){return e instanceof Error&&e.message===fH}async function authHeaders(){const e=await getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env});if(!e)throw new Error("Not authenticated.");return{authorization:`Bearer ${e}`}}function isNotRunning(e){const t=e?.status;return 409===t}__name(withDeadline,"withDeadline"),__name(isDeadline,"isDeadline"),__name(authHeaders,"authHeaders"),__name(isNotRunning,"isNotRunning");var yH=__name(e=>new Promise(t=>setTimeout(t,e)),"sleep");async function openSandboxConnection(e){const t=createSandboxClient({transport:createSandboxTransport()});e.sessionId||e.onPhase?.("Creating a sandbox");const n=(e.sessionId?{sessionId:e.sessionId}:await startSession2({client:t,model:e.model,effort:e.effort,...e.baseBranch?{baseBranch:e.baseBranch}:{}})).sessionId,r=!e.sessionId,o={model:e.model,effort:e.effort};let s=await t.status({sessionId:n});"rpc"!==s.mode||isTerminalSandboxTaskStatus(s.status)&&!1===s.boxUp?(e.onPhase?.("Starting the sandbox"),await reopen({client:t,sessionId:n,...o})):e.sessionId&&e.onPhase?.("Connecting to the sandbox");const a=new Set,i=new Set,l=new Set,c=new Set,d=new Map,u=__name(()=>{const e=Date.now()-5e3;for(const[t,n]of d)n.sentAt>e||(n.reject(new Error("No answer from the sandbox: events were lost.")),d.delete(t))},"failStalePending");let m=0;const p=`${process.pid}-${Date.now().toString(36)}`;let g=!1,h=0;const f=new Set,y=__name(()=>{h=Date.now(),R=Date.now();for(const e of[...f])e()},"markProcessUp"),S=__name(e=>new Promise(t=>{if(h>=e)return void t();const n=__name(()=>{clearTimeout(r),f.delete(n),t()},"wake"),r=setTimeout(n,2e3);f.add(n)}),"untilProcessUp"),w=__name(e=>{"hello"===e.method&&y();const t=e.id;if("string"==typeof t&&d.has(t))return d.get(t)?.resolve(e),void d.delete(t);if("string"==typeof e.method)for(const t of i)t(e)},"onRpcFrame"),v=__name(e=>{for(const[t,n]of d)n.reject(new Error(`No answer from the sandbox: ${e}.`)),d.delete(t);for(const t of l)t(e)},"failWaiters"),k=__name(e=>{g||(C=null),v(e?`the sandbox reported ${e}`:"the stream ended")},"settleEnd");let C=null,b=0,E=0,T=0;function attach(){T++;const t=streamSandboxTask({sessionId:n,isReattach:!0,...b>0?{lastEventId:b}:{},getBaseUrl:getApiBaseUrl,getAuthHeaders:authHeaders,maxReconnects:8,callbacks:{onAgentEvent:__name(({event:e})=>{for(const t of a)t(e)},"onAgentEvent"),onRpcFrame:__name(({frame:e})=>w(e),"onRpcFrame"),onGap:__name(()=>{u();for(const e of c)e();e.onGap?.()},"onGap"),onStatus:__name(({action:t})=>{R=Date.now(),"running"===t.type&&y(),"failed"===t.type&&(A=t.message,v(t.message)),e.onStatus?.(t)},"onStatus"),onErrorEvent:__name(({message:e})=>{A=e,v(e),y()},"onErrorEvent"),onDisconnected:__name(()=>e.onDisconnected?.(),"onDisconnected")}});return t.done.then(e=>{if(C!==t)return;const n=t.getLastEventId()>b;if(b=t.getLastEventId(),E=n?0:E+1,null===e&&!g&&E<=2)return C=null,void setTimeout(()=>{P()},1e3);k(e)},()=>{C===t&&(b=t.getLastEventId(),k(null))}),t}__name(attach,"attach");const P=__name(async()=>{if(g)return;const e=await t.status({sessionId:n}).catch(()=>null);e&&!1!==e.boxUp?await x().catch(()=>{}):k(null)},"reattachIfUp");let M=null;const x=__name(()=>C?Promise.resolve():(M||(M=(async()=>{s=await t.status({sessionId:n}),isTerminalSandboxTaskStatus(s.status)&&!1===s.boxUp&&(e.onPhase?.("Starting the sandbox"),A=null,await reopen({client:t,sessionId:n,...o}),b=0),C=attach(),await L()})().finally(()=>{M=null})),M),"ensureUp"),I=__name((e,t)=>{"session/set_model"===e&&"string"==typeof t.model&&(o.model=t.model,o.effort=void 0),"session/set_effort"===e&&"string"==typeof t.effort&&(o.effort=t.effort)},"remember");let A=null,R=Date.now();const L=__name(async()=>{const a=Date.now()+9e5;R=Date.now();let i=!1;for(;Date.now()-R<12e4&&Date.now()<a;){if(A)throw new Error(A);const a=`${p}:probe-${++m}`,l=Date.now(),c=new Promise((e,t)=>d.set(a,{resolve:e,reject:t,sentAt:Date.now()}));c.catch(()=>{});try{return await t.input({sessionId:n,frame:probeFrame(a)}),void await withDeadline({promise:c,ms:2e4})}catch(c){if(d.delete(a),!isNotRunning(c)&&!isDeadline(c))throw c;if(await S(l),A)throw new Error(A);if(s=await t.status({sessionId:n}),!1!==s.boxUp){!i&&!r&&Date.now()-R>45e3&&isTerminalSandboxTaskStatus(s.status)&&(i=!0,e.onPhase?.("Restarting the sandbox"),A=null,R=Date.now(),await t.continueTask({sessionId:n,prompt:"",mode:"rpc",restart:!0,...o.model?{model:o.model}:{},...o.effort?{effort:o.effort}:{}}),b=0,C?.detach(),C=attach());continue}if(A||i)throw new Error(A??"The sandbox stopped before its process was ready.");i=!0,e.onPhase?.("Starting the sandbox"),await reopen({client:t,sessionId:n,...o}),R=Date.now(),b=0,C?.detach(),C=attach()}}throw new Error("The sandbox stopped reporting progress while starting. Try again, or reopen it later.")},"waitReady"),O=__name(async({method:e,params:r})=>{await x();const o=`${p}:${++m}`,s={jsonrpc:"2.0",id:o,method:e,params:r??{}},a=new Promise((e,t)=>d.set(o,{resolve:e,reject:t,sentAt:Date.now()}));a.catch(()=>{});try{await t.input({sessionId:n,frame:s})}catch(e){if(!isNotRunning(e))throw d.delete(o),e;C&&(b=C.getLastEventId()),C?.detach(),C=null;try{await x(),await t.input({sessionId:n,frame:s})}catch(e){throw d.delete(o),e}}const i=setTimeout(()=>{const e=d.get(o);e&&(d.delete(o),e.reject(new Error("No answer from the sandbox: its agent process is not responding.")))},deadlineFor(e)),l=await a.finally(()=>clearTimeout(i));return void 0===l.error&&I(e,r??{}),l},"request");return C=attach(),await L(),{sessionId:n,summary:__name(()=>s,"summary"),request:O,onAgentEvent:__name(e=>(a.add(e),()=>a.delete(e)),"onAgentEvent"),onNotification:__name(e=>(i.add(e),()=>i.delete(e)),"onNotification"),onEnded:__name(e=>(l.add(e),()=>l.delete(e)),"onEnded"),onGap:__name(e=>(c.add(e),()=>c.delete(e)),"onGap"),streamNumber:__name(()=>T,"streamNumber"),close:__name(()=>{g=!0,C?.detach()},"close")}}function probeFrame(e){return{jsonrpc:"2.0",id:e,method:"session/state",params:{}}}async function startSession2(e){const t=runSandboxStartPreflight({prompt:"",...e.baseBranch?{baseBranch:e.baseBranch}:{}});return{sessionId:(await e.client.start({repoUrl:t.repoUrl,prompt:"",mode:"rpc",...e.baseBranch?{baseBranch:e.baseBranch}:{},...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{}})).sessionId}}async function reopen(e){const t=__name(()=>e.client.continueTask({sessionId:e.sessionId,prompt:"",mode:"rpc",...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{}}),"attempt");try{await t()}catch(e){if(!isNotRunning(e))throw e;await yH(3e3),await t()}}async function adoptRunningTurn(e){const{connection:t}=e,n=__name(n=>alignModel({connection:t,...n?{state:n}:{},...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{}}),"align"),r=await readState(t);return!0===r?.busy&&r.turnId?(setAdoptedTurn({turnId:r.turnId,afterward:__name(async()=>n((await readState(t))?.session),"afterward"),reload:e.reload}),!0):(await n(r?.session),!1)}async function readState(e){const t=await e.request({method:"session/state"}).catch(()=>null);return t?.result}async function alignModel(e){const{connection:t,state:n,model:r,effort:o}=e;if(n?.model&&r){if(n.model!==r){const e=await t.request({method:"session/set_model",params:{model:r}}).catch(()=>null);if(!e||e.error)return}o&&n.effort!==o&&await t.request({method:"session/set_effort",params:{effort:o}}).catch(()=>null)}}async function loadSandboxFeed(e){const t=createSandboxClient({transport:createSandboxTransport()}),{lines:n}=await t.transcript({sessionId:e.sessionId});return reconstructFeedFromMessages(displayMessagesFromV3Lines(n))}async function rebuildFeedAfterGap(e){let t=null;e.setFeed(e=>(t=e,e));const n=e.load??loadSandboxFeed,r=await n({sessionId:e.sessionId});e.setFeed(e=>e===t?r: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(openSandboxConnection,"openSandboxConnection"),__name(probeFrame,"probeFrame"),__name(startSession2,"startSession"),__name(reopen,"reopen"),Vt(),__name(adoptRunningTurn,"adoptRunningTurn"),__name(readState,"readState"),__name(alignModel,"alignModel"),Vt(),PR(),__name(loadSandboxFeed,"loadSandboxFeed"),__name(rebuildFeedAfterGap,"rebuildFeedAfterGap"),Vt(),__name(resolveExternalModelChange,"resolveExternalModelChange"),Vt(),__name(raceAnswerAgainstAbort,"raceAnswerAgainstAbort"),Vt();var SH={},wH={};function setStartupSessionOptions(e){SH=void 0===e.persist?{}:{persist:e.persist},wH={...e.sessionFilePath?{sessionFilePath:e.sessionFilePath}:{},...e.name?{name:e.name}:{}}}function getStickyStartupSessionOptions(){return SH}function consumeStartupSessionOverrides(){const e=wH;return wH={},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,setConnecting:v,onFatal:k}){const C=dt(f);C.current=f;const b=dt(null),E=dt(!1),T=dt(w);T.current=w;const P=pt(()=>{hardResetForResize(),S?.(e=>e+1)},[S]),M=pt(e=>{C.current=e,y?.(e),P()},[P,y]);ut(()=>{if(w)return;const e=b.current,t=E.current;b.current=null,E.current=!1,(null!==e||t)&&(null===e||e===C.current?t&&P():M(e))},[w,M,P]);const[x,I]=ct(!1),[A,R]=ct(0),L=dt(null),O=__name(()=>{L.current?.(),L.current=null},"releaseRebuildBarrier");ut(()=>onHarnessSessionRebuild(t=>{if(t===e)return new Promise(e=>{L.current?.(),L.current=e,R(e=>e+1)})}),[e]);const D=dt(a.current),$=dt(null);return ut(()=>{if(isSandboxMode()){O();let e=!1;return(async()=>{u?.("Connecting to the sandbox"),setSandboxConnecting(!0),v?.(!0);const t=getRequestedSandboxSessionId();let n=t,r=!1;const o=await openSandboxConnectionOnce(()=>openSandboxConnection({sessionId:t,...getRequestedSandboxBase()?{baseBranch:getRequestedSandboxBase()??""}:{},...sandboxModelFor(f)?{model:sandboxModelFor(f)}:{},...sandboxEffortFor(f)?{effort:sandboxEffortFor(f)}:{},onPhase:__name(e=>{isSandboxConnecting()&&(r="Connecting to the sandbox"===e,showConnectStep(e))},"onPhase"),onStatus:__name(e=>{"setup_step"!==e.type&&"replayed_setup"!==e.type||(u?.(e.message??"Starting the sandbox"),e.message&&isSandboxConnecting()&&showConnectStep(e.message)),"running"===e.type&&(u?.(Lh()),r&&isSandboxConnecting()&&(clearConnectSteps(),showConnectStep("Connecting to the sandbox")))},"onStatus"),onGap:__name(()=>{const e=getSandboxConnection()?.sessionId??n;e&&m&&rebuildFeedAfterGap({sessionId:e,setFeed:m}).catch(()=>{})},"onGap")}));if(!e){if(n=o.sessionId,setSandboxConnection(o),f&&!sandboxModelFor(f)&&m?.(e=>[...e,hh(`${f} is a custom model this machine serves; the sandbox runs its default model instead.`)]),t){showConnectStep("Loading the conversation");const t=await loadSandboxFeed({sessionId:o.sessionId}).catch(()=>null);t&&!e&&m?.(()=>t)}await adoptRunningTurn({connection:o,...sandboxModelFor(f)?{model:sandboxModelFor(f)}:{},...sandboxEffortFor(f)?{effort:sandboxEffortFor(f)}:{},reload:__name(()=>loadSandboxFeed({sessionId:o.sessionId}).then(e=>m?.(()=>e)).catch(()=>{}),"reload")}),u?.(""),clearConnectSteps(),m?.(e=>[...e,hh(`Connected to sandbox ${o.sessionId.slice(0,8)} (${o.summary().repoUrl.replace("https://github.com/","")}, branch ${o.summary().branch??"?"})`)]),setSandboxConnecting(!1),v?.(!1),I(!0)}})().catch(t=>{e||(setSandboxConnecting(!1),u?.(""),clearConnectSteps(),v?.(!1),m?.(e=>[...e,kh(`Sandbox: ${t instanceof Error?t.message:String(t)}`)]),setTimeout(()=>k?.(),400))}),()=>{e=!0}}if(!o||n)return void O();const t=__name(()=>Boolean(l)||a.current!==D.current,"userChoseMode");let y,S,w=!1;return(async()=>{const n=consumeStartupSessionOverrides(),{persist:o}=getStickyStartupSessionOptions(),l=await loadResumeAgentState({sessionId:e,...n.sessionFilePath?{baseDir:r(n.sessionFilePath)}:{}});if(w)return;const f=__name(()=>{const e=p?.current??[];if(0===e.length)return[];const t=e.filter(e=>!0!==e.isRelayed),n=e.filter(e=>!0===e.isRelayed);return 0===t.length?[]:(p&&(p.current=n),g?.(()=>n),m?.(e=>[...e,...t.flatMap(e=>{if(e.isMeta)return[];const t=gh(e.displayMessage??e.input);return e.ideHint&&(t.metadata={ideHint:e.ideHint}),[t]})]),t.map(e=>{const t=e.ideContext?`${e.ideContext}\n\n${e.input}`:e.input;return e.images&&0!==e.images.length?{input:[...clipboardImagesToUserContent(e.images),{type:"text",text:t}],...e.source?{source:e.source}:{}}:{input:t,...e.source?{source:e.source}:{}}}))},"drainQueuedMessages"),v=await loadCommandModHost(),k=await x$({sessionId:e,baseUrl:getApiBaseUrl(),...t()?{permissionMode:a.current}:{},dangerouslySkipPermissions:c,drainQueuedMessages:f,peekQueuedMessageCount:__name(()=>(p?.current??[]).filter(e=>!0!==e.isRelayed).length,"peekQueuedMessageCount"),interaction:buildInteraction({permissionsService:s,permissionModeRef:a,setPendingQuestion:d,setStatus:u}),requestSlashCommand:__name(({command:t})=>{const n=refuseAgentSlashCommand(t);return n?{status:"unavailable",message:n}:(enqueueAgentSlashCommand({sessionId:e,command:t}),{status:"accepted"})},"requestSlashCommand"),resumeState:l,modHost:v,...void 0!==o?{persist:o}:{},...n.sessionFilePath?{sessionFilePath:n.sessionFilePath}:{},ideBridge:createLocalIdeBridge()}).catch(()=>{});if(O(),w||!k)return;n.name&&k.setSessionName(n.name),k.getPermissionMode()!==a.current&&(t()?k.setPermissionMode({mode:a.current}):(a.current=k.getPermissionMode(),i?.(k.getPermissionMode())));const x=k.getModel(),A=x!==C.current;A&&M(x),A||k.getEffort()===getReasoningEffort(x)||P(),v&&m&&(v.setEntrySink(e=>{m(t=>[...t,hh(e.join("\n"))])}),S=__name(()=>v.setEntrySink(void 0),"clearModEntrySink")),y=k.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(T.current?E.current=!0:P());const t=resolveExternalModelChange({setting:e.setting,value:e.value,currentModel:C.current});return void(t&&(T.current?b.current=t.modelId:M(t.modelId)))}if("subagent_stop"===e.type){if(!m)return;return void m(t=>settleBackgroundAgentRow({entries:t,toolCallId:e.toolCallId,tokensUsed:e.tokensUsed,...e.status?{status:e.status}:{}}))}if("notice"!==e.type||!m)return;const t=tasteNoticeToFeedEntry(e);t&&m(e=>[...e,t])}),I(!0),$.current!==e&&($.current=e,k.fireSessionStartHooks({source:consumeNextSessionStartSource()}).then(e=>{if(w||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,hh(n.join("\n"))])}).catch(()=>{}))})(),()=>{w=!0,y?.(),S?.()}},[e,t,n,o,s,a,i,l,c,d,u,y,M,A,P]),{ready:x}}function useLifecycle({exit:e,feedState:t,exitState:n,statusState:r,authState:o,onboarding:s,uiOverlays:a,skipOnboarding:i,sessionId:l,sessionTitleHolder:c}){ut(()=>{n.shouldExit&&(isSandboxMode()&&getSandboxConnection()?.close(),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),releaseRemoteLockSync(),c&&(c.loadTitle=()=>loadCommandUserRenamedTitle({sessionId:l}),c.sessionId=l),(async()=>{try{await Promise.allSettled([shutdownActiveRemote(),disconnectAllMcpServers(),R$()])}catch{}try{e()}catch{process.exit(0)}})())},[n.shouldExit,e]),ut(()=>()=>{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)},[]),ut(()=>{(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]),ut(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(Lh())},Bh);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),ut(()=>{i||isSandboxMode()||triggerTasteOnboarding({projectTrusted:s.projectTrusted,onboardingComplete:s.onboardingComplete,isOnboardingMode:s.showTasteOnboarding,tasteOnboardingCheckedRef:s.tasteOnboardingCheckedRef,setIsOnboardingMode:s.setShowTasteOnboarding})},[s.projectTrusted,s.onboardingComplete,s.showTasteOnboarding,i]),ut(()=>{if(s.showTasteOnboarding&&!s.tasteOnboardingEntryId){const e=Ch();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(Oo),t(!1)}}function handleCompactModeCancel({setShowCompactModeSelector:e}){e(!1)}__name(setStartupSessionOptions,"setStartupSessionOptions"),__name(getStickyStartupSessionOptions,"getStickyStartupSessionOptions"),__name(consumeStartupSessionOverrides,"consumeStartupSessionOverrides"),__name(buildInteraction,"buildInteraction"),__name(useHarness,"useHarness"),Vt(),PR(),__name(useLifecycle,"useLifecycle"),Vt(),PR(),Vt(),PR(),__name(handleCompactModeSelect,"handleCompactModeSelect"),__name(handleCompactModeCancel,"handleCompactModeCancel");var vH=__name(e=>{},"noopBool");function useMainActionCallbacks({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,permissionState:s,setInput:a}){const i=dt({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,permissionState:s,setInput:a});i.current={feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,permissionState:s,setInput:a};const l=pt(e=>{const{feedState:t,sessionState:n,statusState:r,uiOverlays:o,authState:s}=i.current;handleSelectSession({selectedSessionId:e,previousSessionId:n.sessionId,sessionLoadIdRef:n.sessionLoadIdRef,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:n.setSessionId,setShowSessionSelector:o.setShowSessionSelector,setSessionLoaded:n.setSessionLoaded,setStaticKey:o.setStaticKey,setShareInfo:r.setShareInfo,setCurrentModel:s.setCurrentModel,inTuiResume:!0})},[]),c=pt(({messageId:e,mode:t})=>{const{feedState:n,sessionState:r,statusState:o,uiOverlays:s,setInput:a}=i.current;handleRewindSelect({messageId:e,mode:t,sessionId:r.sessionId,setFeed:n.setFeed,setStatus:o.setStatus,setShowRewindSelector:s.setShowRewindSelector,setStaticKey:s.setStaticKey,setInput:a})},[]),d=pt(()=>{handleRewindCancel({setShowRewindSelector:i.current.uiOverlays.setShowRewindSelector})},[]),u=pt(e=>{const{feedState:t,sessionState:n,uiOverlays:r,setInput:o}=i.current;return handleTreeSelect({...e,sessionId:n.sessionId,setFeed:t.setFeed,setShowTreeSelector:r.setShowTreeSelector,setStaticKey:r.setStaticKey,setInput:o})},[]),m=pt(()=>{handleTreeCancel({setShowTreeSelector:i.current.uiOverlays.setShowTreeSelector})},[]),p=pt(e=>{const{feedState:t,sessionState:n}=i.current;handleTreeLabel({...e,sessionId:n.sessionId,setFeed:t.setFeed})},[]),g=pt(()=>{handleTreeAbortSummary({sessionId:i.current.sessionState.sessionId})},[]),h=pt((e,t)=>{const{feedState:n,statusState:r,uiOverlays:o}=i.current;handleLoginComplete({success:e,message:t,setShowLoginOverlay:o.setShowLoginOverlay,setFeed:n.setFeed,setStatus:r.setStatus})},[]),f=pt(()=>{const{feedState:e,statusState:t,uiOverlays:n}=i.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),y=__name(e=>{const t=i.current.authState.currentModel;if(dlog("[LaneSwitch] autoSwitchModelForLane",{provider:e,model:t}),laneServesModel({activeLane:e,modelId:t}))return;const n=defaultModelForLane({activeLane:e});dlog("[LaneSwitch] fallback",{fallback:n}),n&&k(n,e)},"autoSwitchModelForLane"),S=pt(e=>{const{authState:t,sessionState:n,statusState:r,uiOverlays:o}=i.current;handleProviderSelect({provider:e,setCurrentProvider:t.setCurrentProvider,setShowProviderSelector:o.setShowProviderSelector,setAuthComponentInfo:t.setAuthComponentInfo,setStatus:r.setStatus,setShowProviderNotification:t.setShowProviderNotification,providerNotificationTimer:t.providerNotificationTimer,setShowModelSelector:o.setShowModelSelector,sessionId:n.sessionId,onActiveModelOrphaned:__name(async()=>{{const e=await w();dlog("[LaneSwitch] orphaned → lane default",{fallback:e}),clearModelOverride(),setSessionModel(e),await persistDefaultModel({model:e});const t=i.current.sessionState.sessionId;t&&await saveCommandSessionMeta({sessionId:t,meta:{model:e}}),i.current.authState.setCurrentModel(e),i.current.uiOverlays.setStaticKey(e=>e+1)}},"onActiveModelOrphaned"),onDiskDefaultOrphaned:__name(async()=>{await persistDefaultModel({model:await w()})},"onDiskDefaultOrphaned")}).then(({switched:t})=>{t&&y(e)})},[]),w=__name(async()=>{const e=i.current.authState.currentProvider??await getConfiguredProvider()??fo.COMMAND;return e===fo.COMMAND?gr:defaultModelForLane({activeLane:e})??gr},"resolveOrphanFallback"),v=pt(()=>{handleProviderCancel({setShowProviderSelector:i.current.uiOverlays.setShowProviderSelector})},[]),k=pt((e,t)=>{const{authState:n,sessionState:r,statusState:o,uiOverlays:s,feedState:a}=i.current;handleModelSelect({modelId:e,provider:t,setCurrentModel:n.setCurrentModel,setShowModelSelector:s.setShowModelSelector,setStatus:o.setStatus,modelNotificationTimer:n.modelNotificationTimer,setShowModelNotification:vH,setCurrentProvider:n.setCurrentProvider,setStaticKey:s.setStaticKey,sessionId:r.sessionId,setFeed:a.setFeed,setContextUsage:o.setContextUsage,setModelNotice:s.setModelNotice})},[]),C=pt(()=>{handleModelCancel({setShowModelSelector:i.current.uiOverlays.setShowModelSelector})},[]),b=pt(e=>{const{statusState:t,uiOverlays:n}=i.current;handleCompactModeSelect({mode:e,setShowCompactModeSelector:n.setShowCompactModeSelector,setStatus:t.setStatus})},[]),E=pt(()=>{handleCompactModeCancel({setShowCompactModeSelector:i.current.uiOverlays.setShowCompactModeSelector})},[]),T=pt(e=>{const{statusState:t,uiOverlays:n}=i.current;handleThemeSelect({theme:e,setShowThemeSelector:n.setShowThemeSelector,setStatus:t.setStatus,setStaticKey:n.setStaticKey})},[]),P=pt(()=>{handleThemeCancel({setShowThemeSelector:i.current.uiOverlays.setShowThemeSelector})},[]),M=pt(e=>{const{feedState:t,uiOverlays:n,sessionState:r,permissionState:o}=i.current;n.setShowRcSelector(!1);const s={setFeed:t.setFeed,setShowRcSelector:n.setShowRcSelector,sessionId:r.sessionId,permissionModeRef:o.permissionModeRef,setPermissionMode:o.setPermissionMode};"stop"!==e.kind?startRemote(s,e.mode,{provider:e.provider,takeover:e.takeover}):stopRemote(s,{clearChat:e.clearChat})},[]),x=pt(()=>{i.current.uiOverlays.setShowRcSelector(!1)},[]),I=pt(()=>{const{authState:e,sessionState:t,statusState:n,uiOverlays:r}=i.current;handleAuthSuccess({authComponentInfo:e.authComponentInfo,setAuthComponentInfo:e.setAuthComponentInfo,setShowProviderSelector:r.setShowProviderSelector,setCurrentProvider:e.setCurrentProvider,setStatus:n.setStatus,setShowProviderNotification:e.setShowProviderNotification,providerNotificationTimer:e.providerNotificationTimer,sessionId:t.sessionId}).then(({switchedProvider:e})=>{e&&y(e)})},[]),A=pt(()=>{handleAuthCancel({setAuthComponentInfo:i.current.authState.setAuthComponentInfo})},[]);return{onSelectSession:l,onRewindSelect:c,onRewindCancel:d,onTreeSelect:u,onTreeCancel:m,onTreeLabel:p,onTreeAbortSummary:g,onLoginComplete:h,onLoginCancel:f,handleProviderSelect:S,handleProviderCancel:v,handleModelSelect:k,handleModelCancel:C,handleCompactModeSelect:b,handleCompactModeCancel:E,handleThemeSelect:T,handleThemeCancel:P,handleRcSelect:M,handleRcCancel:x,handleAuthSuccess:I,handleAuthCancel:A}}function useMonitorOutputWakeup({onSubmit:e}){const t=dt(e);ut(()=>{t.current=e},[e]),ut(()=>{const e=subscribeMonitorCheck(e=>{t.current(buildMonitorWakeupSubmission(e))});return()=>{e()}},[])}function useOnboarding(){const[e,t]=ct(!1),[n,r]=ct(!1),[o,s]=ct(!0),[a,i]=ct(!1),[l,c]=ct(!1),[d,u]=ct(null),[m,p]=ct(!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:dt(!1)}}function usePendingOps(){const[e,t]=ct(null),[n,r]=ct(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"),Vt(),PR(),__name(useMonitorOutputWakeup,"useMonitorOutputWakeup"),Vt(),__name(useOnboarding,"useOnboarding"),Vt(),__name(usePendingOps,"usePendingOps"),Vt(),PR(),Vt(),PR(),__name(resolvePermissionSettingsPath,"resolvePermissionSettingsPath");var kH=__name((e={})=>{const{projectRoot:t,local:n=!1,onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:a}=e,i=t||process.cwd(),l=dt({onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:a}),[c,d]=ct(null),u=dt(null),[m,p]=ct(null),[g,h]=ct(!1);return ut(()=>{l.current={onGenericPermissionRequest:r,onPermissionRequest:o,onPermissionResponse:s,onShellPermissionRequest:a}},[r,o,s,a]),ut(()=>{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:pt(async e=>{if(!c)return{allowed:!0};const t=await c.requestPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),requestShellPermission:pt(async e=>{if(!c)return{allowed:!0};const t=await c.requestShellPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),requestGenericPermission:pt(async e=>{if(!c)return{allowed:!0};const t=await c.requestGenericPermission(e);return l.current.onPermissionResponse?.(t),t},[c]),respondToPrompt:pt(e=>{u.current?.respond(e)&&(p(null),h(!1))},[]),clearSessionPermissions:pt(()=>{c?.clearSessionPermissions()},[c]),clearProjectPermissions:pt(()=>{c?.clearProjectPermissions()},[c]),setAutoApprove:pt((e,t)=>{c?.setAutoApprove(e,t)},[c]),setEnabled:pt(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]=ct(()=>e||(n?"bypass":"default")),i=dt(s);ut(()=>{i.current=s},[s]);const{requestShellPermission:l,service:c,respondToPrompt:d,clearSessionPermissions:u,setEnabled:m}=kH({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 ut(()=>{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=dt(s);ut(()=>{a.current=s},[s]);const i=t.length>0;ut(()=>{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.source?{source:e.source}:{},...void 0!==e.isRelayed?{isRelayed:e.isRelayed}:{},...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])}__name(usePermissionMode,"usePermissionMode"),Vt(),__name(useQueuedMessageFlush,"useQueuedMessageFlush"),Vt(),PR(),Vt(),PR();var CH={shell_command:"Run a command",kill_shell:"Kill a running process",edit_file:"Edit a file",write_file:"Write a file",read_file:"Read a file",read_directory:"List a directory",web_fetch:"Fetch a URL",web_search:"Search the web"};function actionLabel(e){return CH[e]??$S[e]??e}__name(actionLabel,"actionLabel");var bH=__name(e=>e.length>500?`${e.slice(0,500)}…`:e,"clip"),EH=__name(e=>"string"==typeof e&&""!==e.trim()?e:void 0,"asText");function isRedundantDescription(e,t){return!!e.startsWith("Execute shell command:")||void 0!==t&&(e===t||e.includes(t))}__name(isRedundantDescription,"isRedundantDescription");var TH=__name(e=>"object"==typeof e&&null!==e?e:{},"fieldsOf"),PH=__name(e=>{const t=TH(e).risk;if(void 0===t)return{flagged:!1};const n=EH(TH(t).detail);return void 0===n?{flagged:!0}:{flagged:!0,detail:n}},"riskOf");function describePrompt(e){const t=TH(e.params),n=EH(t.command)??EH(t.filePath),r=EH(t.description),o=r&&isRedundantDescription(r,n)?void 0:r,s=PH(e.params);return["⏸ **Approve?**","",actionLabel(e.toolName),...n?["",`\`\`\`\n${bH(n)}\n\`\`\``]:[],...o?[o]:[],...s.flagged?["",`⚠️ ${s.detail??"flagged as risky"}`]:[]].join("\n")}__name(describePrompt,"describePrompt"),Vt();var MH=__name((e,t)=>e.length>t?`${e.slice(0,t-1)}…`:e,"clip");function buildQuestionMessage(e){const{question:t}=e,n=[e.position?`❓ **${t.header??"Question"}** (${e.position.index} of ${e.position.total})`:`❓ **${t.header??"Question"}**`,"",t.question,""],r=[];return t.options.forEach((t,o)=>{const s=o+1;n.push(t.description?`${s}. ${t.label}: ${MH(t.description,120)}`:`${s}. ${t.label}`),r.push({text:`${s}. ${MH(t.label,40)}`,data:encodeQuestionCallback({id:e.id,questionIndex:e.questionIndex,optionIndex:o})})}),t.multiSelect&&n.push("","Pick one here, or answer at the terminal for several."),{text:n.join("\n"),buttons:r.map(e=>[e])}}function planStreamTarget(e){return e?.isOpen()&&e.hasEvents()?"follow":"replace"}function planRemoteMessage(e){const t=planStreamTarget(e);return"follow"===t?{target:t,note:"⏳ Queued. It goes in after the answer above."}:{target:t}}__name(buildQuestionMessage,"buildQuestionMessage"),Vt(),__name(planStreamTarget,"planStreamTarget"),__name(planRemoteMessage,"planRemoteMessage"),Vt(),PR();var xH=__name((e,t)=>e.length>t?`${e.slice(0,t-1)}…`:e,"clip");function summarizeToolCall(e){const t=Dh(e.toolName);let n="";try{n=_h(e.toolName,e.input)}catch{n=""}return{header:n?`${t} [${xH(n.replace(/\s+/g," ").trim(),90)}]`:t}}__name(summarizeToolCall,"summarizeToolCall");var IH=__name(e=>"object"==typeof e&&null!==e,"isRecord");function textOfType(e,t){if(!Array.isArray(e))return[];const n=[];for(const r of e)IH(r)&&r.type===t&&"string"==typeof r.value&&n.push(r.value);return n}__name(textOfType,"textOfType");var AH=__name(e=>textOfType(e,"text").join("\n"),"resultText"),RH=__name(e=>textOfType(e,"error-text").join("\n").split("\n").map(e=>e.trimEnd()).filter(e=>""!==e),"errorText"),LH=__name(e=>`${e} line${1===e?"":"s"}`,"countLabel");function summarizeToolResult(e){const t=RH(e.result);if(t.length>0)return{header:"",lines:t.map(e=>xH(e,100))};const n=AH(e.result).split("\n").map(e=>e.trimEnd()).filter(e=>""!==e);return 0===n.length?{header:""}:{header:"",suffix:LH(n.length)}}__name(summarizeToolResult,"summarizeToolResult");var OH=__name(e=>({describeTool:actionLabel,summarizeCall:summarizeToolCall,summarizeResult:summarizeToolResult,..."Discord"===e?{formatStatus:Aj}:{}}),"replyStreamOptions"),DH=__name(e=>e.length>300?`${e.slice(0,300)}…`:e,"clipEcho"),$H={label:"No",value:"no",description:"Deny this action",scope:void 0};async function requestModelSwitch(e){const t=getModelDisplayName(e.modelId),n=await getBillingContext(),r=checkModelAccess({model:{id:e.modelId,name:t},planId:n.planId,purchasedCredits:n.purchasedCredits,freeCredits:n.freeCredits});return r.allowed?(enqueueAgentSlashCommand({sessionId:e.sessionId,command:`/model ${e.modelId}`,source:"remote"}),{switched:!0,message:`Switching to ${t}.`}):{switched:!1,message:r.errorMessage??`${t} is not on your plan.`}}function describeSession(){const e=getActiveRemote(),t=e?`${modeLabel(e.mode)} — ${modeBehaviour(e.mode)}`:"not connected";return("Discord"===e?.platform?Lj:cB)({info:sessionInfo(),mode:t})}async function applyRemoteValue(e){if("model"===e.name){const t=resolveKnownModelId2(e.value);return t?(await requestModelSwitch({sessionId:e.sessionId,modelId:t})).message:`Unknown model "${e.value}". Send /model for the list.`}const t=CB(e.name),n=t?.reject?.(e.value);return n||(enqueueAgentSlashCommand({sessionId:e.sessionId,command:`/${e.name} ${e.value}`.trim(),source:"remote"}),`Set ${e.name} to ${e.value}.`)}async function runRemoteCommand({command:e,chatId:t,sessionId:n,bridge:r}){if("stop"===e.kind)return interruptActiveTurn(),void r.sendNote(t,"Interrupted.");if("help"===e.kind)return void r.sendNote(t,buildRemoteHelp());if("status"===e.kind)return void r.sendNote(t,describeSession());const o=CB(e.name);if(o){if(""===e.argument){const e=await o.menu();return EB(o.name)||enqueueAgentSlashCommand({sessionId:n,command:`/${o.name}`,source:"remote"}),void r.sendChoices({chatId:t,text:e.text,buttons:e.buttons})}r.sendNote(t,await applyRemoteValue({sessionId:n,name:o.name,value:e.argument}))}else r.sendNote(t,`/${e.name} doesn't work from the chat. Send /help for what does, or send it without the slash to make it a prompt.`)}function answerPermission(e,t,n){const r=e.prompts.get(n.id);if(!r||r!==e.livePermission)return e.prompts.delete(n.id),t.acknowledge("That prompt is no longer waiting."),void t.dismiss();e.prompts.delete(n.id),e.respondToPrompt(n.allow?gM:$H),r.resolve(n.allow),e.clearPendingPermission(),t.acknowledge(n.allow?"Approved":"Denied"),t.dismiss()}function answerQuestion(e,t,n){const r=e.questions.get(n.id),o=r?.pending.params.questions[n.questionIndex],s=o?.options[n.optionIndex];if(!r||!s||r.pending!==e.liveQuestion)return e.questions.delete(n.id),t.acknowledge("That question is already answered."),void t.dismiss();r.answers.set(n.questionIndex,s.label),t.acknowledge(s.label),t.dismiss();const a=r.pending.params.questions.length-r.answers.size;a>0?e.bridge.sendNote(t.chatId,`Noted: ${s.label}. ${a} left.`):(e.questions.delete(n.id),e.resolveQuestionBatch(r),e.bridge.sendNote(t.chatId,`Answered: ${s.label}`))}async function answerValue(e,t,n){const r=await applyRemoteValue({sessionId:e.sessionId,name:n.command,value:n.value}).catch(e=>`That failed: ${mj(e)}`);await t.acknowledge(r),t.dismiss(),e.bridge.sendNote(t.chatId,r)}function handleChoice(e,t){const n=parsePermissionCallback(t.data);if(n)return void answerPermission(e,t,n);const r=parseQuestionCallback(t.data);if(r)return void answerQuestion(e,t,r);const o=parseValueCallback(t.data);if(!o||!CB(o.command))return t.acknowledge("That menu is out of date."),void t.dismiss();answerValue(e,t,o)}function useRemoteBridge({sessionId:e,harnessReady:t,onSubmit:n,pendingPermission:r,setPendingPermission:o,respondToPrompt:s,pendingQuestion:a,setPendingQuestion:i,setPermissionMode:l,dangerouslySkipPermissions:c}){const d=dt(n),u=dt(s),m=dt(o),p=dt(i),g=dt(l),h=dt(null),f=dt(null),y=dt([]),S=dt(null),w=dt(null),v=dt(null),k=dt(new Map),C=dt(0),b=dt(null),E=dt(new Map),T=dt(0);d.current=n,u.current=s,m.current=o,p.current=i,g.current=l,S.current=r,w.current=a;const P=dt(()=>{});P.current=e=>{const{params:t}=e.pending,n=t.questions.map((t,n)=>({questionIndex:n,selectedOptions:[e.answers.get(n)??""]})),r=resolvePlanModeAnswerTransition({answer:n[0]?.selectedOptions[0]??"",exitPlanMode:t.exitPlanMode,enterPlanMode:t.enterPlanMode,dangerouslySkipPermissions:c});r&&g.current(r),e.pending.resolve({answers:n}),p.current(null)};const M=__name((e,t)=>{const n=getActiveRemote();if(!n)return;const r=h.current;if("follow"===planStreamTarget(r))return t?(f.current=e,void r?.retarget(n.bridge.openReply(e))):void y.current.push(e);f.current=e,r?.abandon(),h.current=createReplyStream(n.bridge.openReply(e),OH(n.platform))},"openStream");ut(()=>{const t=[subscribeRemoteMessage(t=>{const n=getActiveRemote();if(!n)return;const r=parseRemoteCommand(t.text);if(r)return void runRemoteCommand({command:r,chatId:t.chatId,sessionId:e,bridge:n.bridge}).catch(e=>{n.bridge.sendNote(t.chatId,`That command failed: ${mj(e)}`)});const o=planRemoteMessage(h.current);o.note&&n.bridge.sendNote(t.chatId,o.note),M(t.chatId,!1),d.current(buildRemoteSubmission(t))}),subscribeRemoteChoice(t=>{const n=getActiveRemote();n&&handleChoice({sessionId:e,bridge:n.bridge,prompts:k.current,questions:E.current,livePermission:S.current,liveQuestion:w.current,respondToPrompt:u.current,clearPendingPermission:__name(()=>m.current(null),"clearPendingPermission"),resolveQuestionBatch:P.current},t)}),subscribeRemoteStopped(()=>{h.current?.abandon(),h.current=null,f.current=null,y.current=[],k.current.clear(),E.current.clear(),v.current=null,b.current=null}),subscribeLocalPrompt(({text:e})=>{const t=getActiveRemote();if(!t)return;const n=t.bridge.ownerChatId;void 0!==n&&(t.bridge.sendNote(n,`💻 ${DH(e)}`),M(n,!0))})];return()=>{for(const e of t)e()}},[e]),ut(()=>{const t=I$(e);if(t)return t.events.subscribe(e=>{if("run_start"===e.type&&null===h.current){const e=y.current.shift();void 0!==e&&M(e,!1)}const t=h.current;t&&(t.onEvent(e),t.isOpen()||(h.current=null,f.current=null))})},[e,t]),ut(()=>{if(r||(v.current=null,k.current.clear()),a||(b.current=null,E.current.clear()),!r&&!a)return;const e=getActiveRemote(),t=f.current;if(e&&null!==t&&h.current?.isOpen()){if(r&&v.current!==r){v.current=r;const n=C.current;C.current+=1,k.current.set(n,r),e.bridge.sendChoices({chatId:t,text:describePrompt(r),buttons:[[{text:"✅ Approve",data:encodePermissionCallback({id:n,allow:!0})},{text:"⛔️ Deny",data:encodePermissionCallback({id:n,allow:!1})}]]})}if(a&&b.current!==a){b.current=a;const n=T.current;T.current+=1,E.current.set(n,{pending:a,answers:new Map});const r=a.params.questions.length;a.params.questions.forEach((o,s)=>{const a=buildQuestionMessage({id:n,questionIndex:s,question:o,...r>1?{position:{index:s+1,total:r}}:{}});e.bridge.sendChoices({chatId:t,text:a.text,buttons:a.buttons})})}}},[r,a])}function useSession(){const[e,t]=ct(()=>crypto.randomUUID()),[n,r]=ct(!1);return{sessionId:e,setSessionId:t,sessionLoaded:n,setSessionLoaded:r,sessionLoadIdRef:dt(null)}}__name(requestModelSwitch,"requestModelSwitch"),__name(describeSession,"describeSession"),__name(applyRemoteValue,"applyRemoteValue"),__name(runRemoteCommand,"runRemoteCommand"),__name(answerPermission,"answerPermission"),__name(answerQuestion,"answerQuestion"),__name(answerValue,"answerValue"),__name(handleChoice,"handleChoice"),__name(useRemoteBridge,"useRemoteBridge"),Vt(),__name(useSession,"useSession"),Vt(),PR(),Vt(),PR();var NH=createOSC8Link("https://commandcode.ai/docs/hooks","Docs ↗",!1),_H=createOSC8Link("https://commandcode.ai/docs/core-concepts/custom-agents","Docs ↗",!1);function buildStartupWarningEntries(e){const t=[];for(const n of e.fileLevelMessages)t.push({message:n,isFileLevel:!0});if(e.summaryLine&&t.push({message:e.summaryLine,isFileLevel:!1}),0===t.length)return[];const n=t[t.length-1];return n.message=`${n.message} ${e.docsLink}`,t.map(t=>t.isFileLevel?hh(t.message,e.fileLevelMetadata):hh(t.message))}function buildHookStartupEntries(e){const t=buildHookStartupMessages(e),n=t.find(e=>!e.isHookWarning);return buildStartupWarningEntries({fileLevelMessages:t.filter(e=>e.isHookWarning).map(e=>e.message),summaryLine:n?.message??null,docsLink:NH,fileLevelMetadata:{isHookWarning:!0}})}function buildAgentStartupEntries(e){return buildStartupWarningEntries({fileLevelMessages:[],summaryLine:summarizeAgentConfigWarnings(e),docsLink:_H})}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=pt(async()=>{try{const e=!isSandboxMode()&&await isTasteLearningEnabled();l.setTasteLearningOn(e),e&&await initTasteDir({runtime:createNodeRuntime()})}catch{}},[l.setTasteLearningOn]),k=pt(async()=>{const e=await getConfiguredProvider();c.setCurrentProvider(e)},[c.setCurrentProvider]),C=pt(()=>{},[]),b=pt(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=pt(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]);ut(()=>{(async()=>{if(isSandboxMode())return d.setProjectTrusted(!0),d.setCheckingProject(!1),v(),k(),void loadCustomProviderModels();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=dt(!1);ut(()=>{T.current||d.projectTrusted&&0!==getCommandZdrPausedFeatures().length&&(T.current=!0,u.setShowZdrNotice(!0))},[d.projectTrusted,u.setShowZdrNotice]);const P=dt(null);ut(()=>{d.projectTrusted&&c.currentModel!==P.current&&(P.current=c.currentModel,u.setModelNotice(getModelNotice(c.currentModel)??null))},[d.projectTrusted,c.currentModel,u.setModelNotice]);const M=dt(null);ut(()=>{if(!p||!d.projectTrusted)return;const e=i.sessionId;if(M.current===e)return;const t=I$(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]);const x=dt(null);ut(()=>{if(!p||!d.projectTrusted)return;const e=i.sessionId;if(x.current===e)return;const t=I$(e);if(!t)return;x.current=e;const n=buildAgentStartupEntries(t.agentConfigWarnings);0!==n.length&&a.setFeed(e=>[...e,...n])},[p,d.projectTrusted,i.sessionId,a.setFeed]),ut(()=>{if(!d.projectTrusted)return;const e=createCommandHistoryManager();return f.current=e,e.init(),()=>{e.cleanup()}},[d.projectTrusted,f]),ut(()=>{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]);const[I,A]=ct(!1);ut(()=>{!o||hasAdoptedTurn()||I||!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,I]);const R=dt(null);R.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 L=dt(!1);ut(()=>{p&&!L.current&&hasAdoptedTurn()&&(L.current=!0,A(!0),handleSubmit({...R.current,role:"user",input:ON,suppressUserEcho:!0,isAutomated:!0}).finally(()=>{takeAdoptedTurn(),A(!1)}))},[p]);const O=pt(async({role:e,input:t,images:n,imageTokenPaths:r,ideContext:o,ideHint:s,displayMessage:a,isAutomated:i,isMeta:l,source:c,isRelayed:d,hiddenMessages:m})=>{u.setShowTasteSkipBanner(!1),u.setShowZdrNotice(!1),u.setModelNotice(null),i||"bash"===e||emitLocalPrompt({text:a??t}),await handleSubmit({...R.current,role:e,input:t,images:n,imageTokenPaths:r,ideContext:o,ideHint:s,displayMessage:a,isAutomated:i,isMeta:l,source:c,isRelayed:d,hiddenMessages:m})},[u.setShowTasteSkipBanner,u.setShowZdrNotice,u.setModelNotice]);return{loadTasteStatus:v,loadCurrentProvider:k,initializeMcpInBackground:C,onSubmit:O}}function useStatus(e){const[t,n]=ct("Ready..."),r=dt(!1),[o,s]=ct(""),a=dt(null),[i,l]=ct(null),c=dt(i),[d,u]=ct(null),[m,p]=ct(!1),[g,h]=ct(""),[f,y]=ct(null),[S,w]=ct(0),[v,k]=ct(null),[C,b]=ct(null),[E,T]=ct(e??null);ut(()=>{c.current=i},[i]),ut(()=>{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,modelLabel:n=null}){const r=dt(process.cwd()),o=dt(e),s=dt(null),a=dt(n);a.current=n;const i=pt(e=>{s.current=e,setTerminalTitle(formatSessionTabTitle({sessionTitle:e,projectDir:r.current,modelLabel:a.current}))},[]),l=pt(e=>{(async()=>{const t=await loadCommandSessionMeta({sessionId:e});o.current===e&&t?.title&&t.title!==s.current&&i(t.title)})()},[i]);ut(()=>{o.current=e,i(null),l(e)},[e,i,l]);const c=dt(!0);ut(()=>{c.current?c.current=!1:i(s.current)},[n,i]);const d=dt(t);ut(()=>{const n=d.current;d.current=t,t!==n&&reassertTerminalTitle(),!t&&n&&(s.current||l(e))},[t,e,l]),ut(()=>{if(!process.stderr.isTTY)return;const e=setInterval(reassertTerminalTitle,5e3);return()=>{clearInterval(e)}},[]);const u=pt(e=>{i(e)},[i]);return{setRenamedTerminalTitle:u,applyGeneratedTitle:u}}function useUiOverlays(){const[e,t]=ct(!1),[n,r]=ct(!1),[o,s]=ct(!1),[a,i]=ct(!1),[l,c]=ct(!1),[d,u]=ct(!1),[m,p]=ct(!1),[g,h]=ct(!1),[f,y]=ct(!1),[S,w]=ct(!1),[v,k]=ct(!1),[C,b]=ct(!1),[E,T]=ct(!1),[P,M]=ct(!1),[x,I]=ct("default"),[A,R]=ct(!1),[L,O]=ct(!1),[D,$]=ct(!1),[N,_]=ct(!1),[F,U]=ct(!1),[j,B]=ct(!1),[W,H]=ct(null),[G,V]=ct(!1),[z,K]=ct(!1),[q,Y]=ct(!1),[Q,J]=ct(!1),[X,Z]=ct(!1),[ee,te]=ct(null),[ne,re]=ct(0),[oe,se]=ct(!1),[ae,ie]=ct(!1),[le,ce]=ct(null),[de,ue]=ct("off"),me="off"!==de,pe=pt(e=>{hardResetForResize(),re(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:L,setShowLoginOverlay:O,showCompactModeSelector:D,setShowCompactModeSelector:$,showContextView:N,setShowContextView:_,showStatusView:F,setShowStatusView:U,showPlansView:j,setShowPlansView:B,plansTarget:W,setPlansTarget:H,planBreadcrumbPending:G,setPlanBreadcrumbPending:V,showUsageOverlay:z,setShowUsageOverlay:K,showThemeSelector:q,setShowThemeSelector:Y,showRcSelector:Q,setShowRcSelector:J,staticKey:ne,setStaticKey:re,closeFullScreenOverlay:pe,showTasteSkipBanner:oe,setShowTasteSkipBanner:se,showZdrNotice:ae,setShowZdrNotice:ie,modelNotice:le,setModelNotice:ce,transcriptMode:de,setTranscriptMode:ue,expandedToolOutput:me,showDesignGuide:X,setShowDesignGuide:Z,pendingDesignSuggestion:ee,setPendingDesignSuggestion:te}}__name(buildStartupWarningEntries,"buildStartupWarningEntries"),__name(buildHookStartupEntries,"buildHookStartupEntries"),__name(buildAgentStartupEntries,"buildAgentStartupEntries"),__name(submitInitialPrompt,"submitInitialPrompt"),__name(useStartup,"useStartup"),Vt(),__name(useStatus,"useStatus"),Vt(),PR(),__name(useTerminalTitle,"useTerminalTitle"),Vt(),__name(useUiOverlays,"useUiOverlays");var FH=__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}=st(),{stdout:p}=nt();usePasteRouter(),ut(()=>{isLocalOnly()||prefetchBillingContext()},[]);const[g,h]=ct(""),[f,y]=ct(""),[S,w]=ct(!1),v=dt(!1),k=dt(!1),C=dt(null);ut(()=>{let e=!0;return loadUserConfig().then(t=>{e&&w(!1!==t.showTasteLearningInFeed)}).catch(()=>{e&&w(!0)}),()=>{e=!1}},[]);const b=useUiOverlays(),E=useFeed(),T=useSession(),P=useStatus(s),M=useAuth(),x=usePendingOps(),I=useOnboarding(),A=useExit(),{executeBash:R,executionState:L}=HW(),O=usePermissionMode({initialPermissionMode:c,local:d,dangerouslySkipPermissions:o,setPendingPermission:x.setPendingPermission,setStatus:P.setStatus}),D=mt(()=>getModelShortName({modelId:M.currentModel,findModelById:findModelById}),[M.currentModel]),$=useTerminalTitle({sessionId:T.sessionId,isCmdCodeBusy:E.isCmdCodeBusy,modelLabel:D}),{ready:N}=useHarness({sessionId:T.sessionId,sessionLoaded:T.sessionLoaded,showSessionSelector:b.showSessionSelector,projectTrusted:I.projectTrusted,setConnecting:E.setIsCmdCodeBusy,onFatal:__name(()=>{process.exitCode=1,A.setShouldExit(!0)},"onFatal"),permissionsService:O.permissionsService,permissionModeRef:O.permissionModeRef,setPermissionMode:O.setPermissionMode,permissionModeExplicit:Boolean(c)||o,dangerouslySkipPermissions:O.dangerouslySkipPermissions,setPendingQuestion:x.setPendingQuestion,setStatus:P.setStatus,setFeed:E.setFeed,queuedMessagesRef:E.queuedMessagesRef,setQueuedMessages:E.setQueuedMessages,onSessionTitled:$.applyGeneratedTitle,currentModel:M.currentModel,setCurrentModel:M.setCurrentModel,setStaticKey:b.setStaticKey,isCmdCodeBusy:E.isCmdCodeBusy}),{onCommand:_}=useCommandCtx({feedState:E,sessionState:T,statusState:P,authState:M,uiOverlays:b,onboarding:I,exitState:A,permissionState:O,terminalTitleState:$,isSubmittingRef:v,executeBash:R,setInput:h});useAgentSlashCommandQueue({sessionId:T.sessionId,isCmdCodeBusy:E.isCmdCodeBusy,onCommand:_}),ut(()=>{b.planBreadcrumbPending&&!E.isCmdCodeBusy&&(b.setPlanBreadcrumbPending(!1),E.setFeed(e=>[...e,vh("Plan saved — run /plans to review, annotate, or execute it anytime.")]))},[b.planBreadcrumbPending,b.setPlanBreadcrumbPending,E.isCmdCodeBusy,E.setFeed]);const{loadTasteStatus:F,loadCurrentProvider:U,onSubmit:j}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:i,stdout:p,feedState:E,sessionState:T,statusState:P,authState:M,onboarding:I,uiOverlays:b,permissionState:O,harnessReady:N,isSubmittingRef:v,initialPromptSubmittedRef:k,historyManagerRef:C,executeBash:R,setInput:h,onCommand:_});useMonitorOutputWakeup({onSubmit:j}),useCronWakeup({sessionId:T.sessionId,onSubmit:j}),useRemoteBridge({sessionId:T.sessionId,harnessReady:N,onSubmit:j,pendingPermission:x.pendingPermission,setPendingPermission:x.setPendingPermission,respondToPrompt:O.respondToPrompt,pendingQuestion:x.pendingQuestion,setPendingQuestion:x.setPendingQuestion,setPermissionMode:O.setPermissionMode,dangerouslySkipPermissions:O.dangerouslySkipPermissions}),useQueuedMessageFlush({isCmdCodeBusy:E.isCmdCodeBusy,queuedMessages:E.queuedMessages,queuedMessagesRef:E.queuedMessagesRef,setQueuedMessages:E.setQueuedMessages,isSubmittingRef:v,onSubmit:j}),useLifecycle({exit:m,feedState:E,exitState:A,statusState:P,authState:M,onboarding:I,uiOverlays:b,skipOnboarding:l,sessionId:T.sessionId,sessionTitleHolder:u});const{handleToggleAutoAccept:B,handleEnableAutoAccept:W,handleDoubleEscapeEmpty:H,handleTasteOnboardingComplete:G,handleTrust:V,handleNoTrust:z}=useHandlers({resume:e,feedState:E,onboarding:I,uiOverlays:b,exitState:A,pendingOps:x,permissionState:O,statusState:P,authState:M,sessionId:T.sessionId,loadTasteStatus:F,loadCurrentProvider:U,setInput:__name(e=>h(e),"setInput")}),K=useMainActionCallbacks({feedState:E,sessionState:T,statusState:P,authState:M,uiOverlays:b,permissionState:O,setInput:h}),{creditWarning:q}=useCreditWarning({interactionTokens:P.interactionTokens,currentModel:M.currentModel});return renderView({feedState:E,sessionState:T,statusState:P,authState:M,uiOverlays:b,onboarding:I,exitState:A,pendingOps:x,permissionState:O,historyManagerRef:C,executionState:L,actionCallbacks:K,onSubmit:j,onCommand:_,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,updateFailedInfo:a,creditWarning:q,handleTrust:V,handleNoTrust:z,handleToggleAutoAccept:B,handleEnableAutoAccept:W,handleDoubleEscapeEmpty:H,handleTasteOnboardingComplete:G,loadTasteStatus:F,showTasteLearningInFeed:S,setShowTasteLearningInFeed:w})},"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,showTasteLearningInFeed:M,setShowTasteLearningInFeed:x}){if(a.shouldExit)return null;if(s.checkingProject)return null;if(s.showTrustPrompt)return it.createElement(WW,{staticKey:o.staticKey,onTrust:v,onExit:k});if(o.showSessionSelector)return it.createElement(jW,{onSelectSession:u.onSelectSession,onClose:()=>o.closeFullScreenOverlay(o.setShowSessionSelector),currentSessionId:t.sessionId});if(!s.projectTrusted)return null;const I=o.pendingDesignSuggestion?it.createElement(O_,{suggestion:o.pendingDesignSuggestion,onSelect:e=>{p(`/design ${e}`)},onClose:()=>o.setPendingDesignSuggestion(null)}):null,A=i.pendingQuestion?.params.exitPlanMode?i.pendingQuestion:null,R=i.pendingQuestion&&!A?it.createElement(QuestionView,{pendingQuestion:i.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,dangerouslySkipPermissions:l.dangerouslySkipPermissions,setPendingQuestion:i.setPendingQuestion,setStatus:n.setStatus,setStaticKey:o.setStaticKey}):null,L=i.pendingPermission?it.createElement(b_,{pendingPermission:i.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:i.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleEnableAutoAccept:b}):null,{closeFullScreenOverlay:O}=o;if(A){const e=__name(e=>{const t=resolvePlanModeAnswerTransition({answer:e,exitPlanMode:!0,dangerouslySkipPermissions:l.dangerouslySkipPermissions});t&&l.setPermissionMode(t),A.resolve({answers:[{questionIndex:0,selectedOptions:[e]}]}),i.setPendingQuestion(null),hardResetForResize(),o.setStaticKey(e=>e+1)},"resolveApproval");return it.createElement(PlanApprovalView,{staticKey:o.staticKey,planContent:A.params.planContent,planFilePath:A.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 it.createElement(TasteConfigView,{staticKey:o.staticKey,onClose:()=>O(o.setShowTasteConfig),loadTasteStatus:P});if(o.showSkillsConfig)return it.createElement(SkillsConfigView,{staticKey:o.staticKey,onClose:()=>O(o.setShowSkillsConfig)});if(o.showSettingsConfig)return it.createElement(SettingsConfigView,{staticKey:o.staticKey,onClose:()=>O(o.setShowSettingsConfig),loadTasteStatus:P,onShowTasteLearningInFeedChange:x});if(o.showUsageOverlay)return it.createElement(UsageView,{staticKey:o.staticKey,onClose:()=>O(o.setShowUsageOverlay)});if(o.showContextView)return it.createElement(ContextConfigView,{staticKey:o.staticKey,sessionId:t.sessionId,onClose:()=>O(o.setShowContextView),setInput:h});if(o.showStatusView)return it.createElement(StatusConfigView,{staticKey:o.staticKey,sessionId:t.sessionId,onClose:()=>O(o.setShowStatusView),setInput:h});if(o.showPlansView){const e=__name(e=>{o.setPlansTarget(null),O(o.setShowPlansView),m({role:"user",input:e})},"submitFromPlans");return it.createElement(PlansView,{staticKey:o.staticKey,sessionId:t.sessionId,target:o.plansTarget,onClose:()=>{o.setPlansTarget(null),O(o.setShowPlansView)},onSubmitFeedback:e,onExecute:n=>{"plan"===l.permissionModeRef.current&&(l.permissionModeRef.current="auto-accept",l.setPermissionMode("auto-accept"),I$(t.sessionId)?.setPermissionMode({mode:"auto-accept"})),e(n)}})}return it.createElement(lW,{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,showTasteLearningInFeed:M,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,showRcSelector:o.showRcSelector,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:L,questionPanel:R,designSuggestionPanel:I,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,handleRcSelect:u.handleRcSelect,handleRcCancel:u.handleRcCancel,handleAuthSuccess:u.handleAuthSuccess,handleAuthCancel:u.handleAuthCancel,showDesignGuide:o.showDesignGuide,setShowDesignGuide:o.setShowDesignGuide})}__name(renderView,"renderView"),Vt();var UH=__name(()=>{const e=getInvokedCommandName();return"win32"===process.platform&&"cmd"===e?"cmdc":e},"getResumeCommandName");PR(),Vt();var jH=__name(({worktreePath:e,warning:t,onChoice:n})=>{const[r,o]=ct(1);return ot((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)}),it.createElement(RO,{title:"Exiting worktree session",subtitle:t,hint:"Enter to confirm · Esc to cancel"},it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,null,it.createElement(et,{color:1===r?LR.CYAN:LR.GRAY},1===r?ft.pointer:" "," 1. Keep worktree"," ",it.createElement(et,{color:LR.GRAY},"Stays at ",tildeHome(e)))),it.createElement(Ze,null,it.createElement(et,{color:2===r?LR.CYAN:LR.GRAY},2===r?ft.pointer:" "," 2. Remove worktree"," ",it.createElement(et,{color:LR.GRAY},"All changes and commits will be lost.")))))},"WorktreeExitPrompt");function promptWorktreeExit(e){return new Promise(t=>{const{unmount:n}=rt(it.createElement(jH,{worktreePath:e.worktreePath,warning:e.warning,onChoice:e=>{n(),t(e)}}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})})}function clearedHandoffEnv(e=process.env,t=process.pid){return{...releasedPaneOwnerEnv(e,t)}}function canRespawn(){if(process.versions.bun)return!1;const e=process.argv[1];return"string"==typeof e&&e.length>0}function resetTerminalForRespawn(){process.stdout.isTTY&&UL()}async function writeReloadHandoff(e){const t=process.env[ex];if(t)try{await K.writeFile(t,serializeReloadCarryover(e))}catch{}}async function consumeReloadHandoff(e){try{return parseReloadCarryover(await K.readFile(e,"utf-8"))}catch{return null}finally{await K.unlink(e).catch(()=>{})}}function restoreTerminal({signal:e=null}={}){try{process.stdin.isTTY&&process.stdin.setRawMode(!1)}catch{}try{process.stdout.write("[?25h")}catch{}if(e)try{popKittyKeyboardProtocol()}catch{}}__name(promptWorktreeExit,"promptWorktreeExit"),Vt(),PR(),__name(clearedHandoffEnv,"clearedHandoffEnv"),__name(canRespawn,"canRespawn"),__name(resetTerminalForRespawn,"resetTerminalForRespawn"),__name(writeReloadHandoff,"writeReloadHandoff"),__name(consumeReloadHandoff,"consumeReloadHandoff"),__name(restoreTerminal,"restoreTerminal");var BH=yt.hex(LR.DIM);function printReloadFallbackHint(){process.stdout.write(BH("Couldn't restart automatically in this build — exiting instead.\n"))}async function shutdownWrapperRuntime(){try{await Promise.allSettled([disconnectAllMcpServers(),R$(),disposeCommandModHost()])}catch{}try{await shutdownTelemetry()}catch{}process.removeAllListeners("SIGINT"),process.removeAllListeners("SIGTERM"),process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{}),process.stdin.pause()}async function runRelaunchLoop(e){await shutdownWrapperRuntime();const n=await K.mkdtemp(t.join(W.tmpdir(),"cmd-reload-")),r=t.join(n,"handoff.json");let o=e;for(;;){const e=await commandSessionTranscriptExists(o.sessionId),t=buildRelaunchArgs({invocation:getOriginalInvocation(),request:o,resumable:e,argv:process.argv.slice(2)});clearTerminalTitle(),resetTerminalForRespawn();const s=w(process.execPath,[process.argv[1],...t],{stdio:"inherit",env:{...process.env,[ex]:r,[tx]:String(process.pid),...clearedHandoffEnv()}});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(BH(`\nCouldn't relaunch Command Code: ${e.message}\n`)),await K.rm(n,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}if(a!==ZM){if(restoreTerminal({signal:i}),await K.rm(n,{recursive:!0,force:!0}).catch(()=>{}),i){const e=W.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),await disposeCommandModHost(),process.exit(ZM)),await runRelaunchLoop(e)):printReloadFallbackHint()}__name(printReloadFallbackHint,"printReloadFallbackHint"),__name(shutdownWrapperRuntime,"shutdownWrapperRuntime"),__name(runRelaunchLoop,"runRelaunchLoop"),__name(handlePendingReload,"handlePendingReload"),Vt(),PR();var WH=["disambiguateEscapeCodes"];async function resolveKittyKeyboard(e={}){const t=e.env??process.env,n=e.probe??queryKittyKeyboardSupport,r=!isVSCodeTerminal2({env:t})&&await n();return setKittyKeyboardActive(r),{mode:r?"enabled":"disabled",flags:WH}}__name(resolveKittyKeyboard,"resolveKittyKeyboard");var HH=yt.hex(LR.DIM),GH=__name((e,t)=>{const n=UH(),r=be([e]),o=t?`cd ${be([t])} && ${n} --resume ${r}`:`${n} --resume ${r}`;return`${HH("Resume this session with:")}\n${HH(o)}\n`},"formatResumeHint"),VH=__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"),zH=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),KH=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),qH=__name(e=>e.permissionMode?e.permissionMode:e.plan?"plan":void 0,"resolveInitialPermissionMode"),YH=__name(({options:e,resumeSessionId:t,sessionTitleHolder:n})=>{const r=qH(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"),QH=__name(e=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1,kittyKeyboard:e}),"getInkRenderOptions"),JH=!1,XH=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode(),!JH&&isKittyKeyboardActive()&&popKittyKeyboardProtocol()})},"setupBracketedPasteMode"),ZH=__name(()=>{XH()},"initializeTerminal"),eG=__name(()=>{process.on("SIGINT",()=>{})},"swallowSigintDuringShutdown"),tG=__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"),nG=__name(async(e={})=>{const t=VH(process.stdin.isTTY);let n,o;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),ZH(),"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=>A(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(zH(e)&&!n){const e=await isCommandProjectSessionInitialized(),t=e?await listCommandSessions():[],n=KH({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}if(e.forkSession){const t=await tG({resumeSessionId:n,useContinue:Boolean(e.continue)});t&&(n=t,e.continue=!1)}await applyStartupTheme();const a=await resolveKittyKeyboard();startEarlyInputCapture(),setStartupSessionOptions({...!1===e.session?{persist:!1}:{},...o?{sessionFilePath:o}:{},...e.name?{name:e.name}:{}});const i={},l=YH({options:e,resumeSessionId:n,sessionTitleHolder:i}),d=QH(a),u=rt(it.createElement(FH,{...l}),d);registerInkControl({clear:u.clear,stdout:process.stdout,instance:await resolveInkInstance(process.stdout)}),await u.waitUntilExit(),JH=!0,clearTerminalTitle(),eG();const m=consumePendingReload();m&&await handlePendingReload(m);const p=await(i.loadTitle?.())??null,g=Boolean(p);let h;const f=getAutoCreatedWorktree();if(f){const e=worktreeHasWork(f.worktreePath,f.baseSha);let t="auto";if(e||g){const n=worktreeChangeCount(f.worktreePath),r=e?n>0?`You have ${n} uncommitted file${1===n?"":"s"}. These will be lost if you remove the worktree.`:"This worktree has commits that are not on your main branch. They will be lost if you remove it.":null;t=await promptWorktreeExit({worktreePath:f.worktreePath,warning:r})}const n=finalizeAutoCreatedWorktree(t);if(n.worktreePath){const e=HH(createOSC8Link(fileUrl(n.worktreePath),tildeHome(n.worktreePath),!1));if(n.removed){const n="auto"===t?"Removed empty worktree":"Removed worktree";process.stdout.write(`${HH(n)}\n${e}\n\n`)}else if(n.kept){h=n.worktreePath;const t=n.reason&&"kept"!==n.reason?` (${n.reason})`:"";process.stdout.write(`${HH(`Kept worktree${t}`)}\n${e}\n\n`)}}}if(isSandboxMode()){const e=getSandboxConnection()?.sessionId??getRequestedSandboxSessionId();return void(e&&process.stdout.write(`${HH("Reopen this sandbox with:")}\n${HH(`${UH()} --experimental --sandbox ${e}`)}\n`))}const y=i.sessionId;if(y&&await commandSessionExists(y)){const e=p?sanitizeTitleForOutput(p):"";process.stdout.write(GH(e||y,h))}},"interactiveMode");function modelAndEffort(e){const t=sandboxModelFor(e??getConfiguredModel()),n=sandboxEffortFor(t);return{...t?{model:t}:{},...n?{effort:n}:{}}}function openCommand2(e){return`${UH()} --experimental --sandbox ${e}`}async function startWithTask(e){const t=runSandboxStartPreflight({prompt:e.task,...e.baseBranch?{baseBranch:e.baseBranch}:{}});return(await e.client.start({repoUrl:t.repoUrl,prompt:e.task,mode:"rpc",...e.baseBranch?{baseBranch:e.baseBranch}:{},...modelAndEffort(e.model)})).sessionId}function refusal(e){const t=e.error;return t?t.message??"refused":null}async function sendToLiveBox(e){const t=await openSandboxConnection({sessionId:e.sessionId,...modelAndEffort(e.model)});try{const n=void 0!==e.model||!0===e.effortGiven?modelAndEffort(e.model):{};if(e.model&&n.model){const e=refusal(await t.request({method:"session/set_model",params:{model:n.model}}));if(e)throw new Error(`The sandbox kept its model: ${e}.`)}if(n.effort){const e=refusal(await t.request({method:"session/set_effort",params:{effort:n.effort}}));if(e)throw new Error(`The sandbox kept its effort: ${e}.`)}const r=refusal(await t.request({method:"turn/start",params:{input:e.task,headless:!0}}));if(r)throw new Error(`The sandbox did not take the task: ${r}.`)}finally{t.close()}}async function sendFollowUp(e){const{client:t,sessionId:n,task:r}=e,o=await t.status({sessionId:n});if("running"===o.status)throw new Error(`A task is already running in ${n.slice(0,8)}\nConnect: ${openCommand2(n)}`);!1===o.boxUp||"rpc"!==o.mode?await t.continueTask({sessionId:n,prompt:r,mode:"rpc",...modelAndEffort(e.model)}):await sendToLiveBox({sessionId:n,task:r,...e.model?{model:e.model}:{},...e.effortGiven?{effortGiven:!0}:{}})}async function runSandboxPrint(e){warnAboutPromptTruncation(e.task);const t=truncateSandboxPrompt(e.task);if(!t)throw new Error('Give the task: cmd -p --sandbox "task", or cmd -p --sandbox <id> "task" for a follow-up.');if(e.sessionId&&e.baseBranch)throw new Error("--base applies to a new session only; a follow-up stays on its branch.");const n=createSandboxClient({transport:createSandboxTransport()}),r=e.sessionId?(await sendFollowUp({client:n,sessionId:e.sessionId,task:t,...e.model?{model:e.model}:{},...e.effortGiven?{effortGiven:!0}:{}}),e.sessionId):await startWithTask({client:n,task:t,...e.baseBranch?{baseBranch:e.baseBranch}:{},...e.model?{model:e.model}:{}});process.stdout.write(`${r}\n`),process.stderr.write(Pt.dim(`${e.sessionId?"Sent to sandbox":"Sandbox started"}\nConnect: ${openCommand2(r)}\n`))}Vt(),PR(),__name(modelAndEffort,"modelAndEffort"),__name(openCommand2,"openCommand"),__name(startWithTask,"startWithTask"),__name(refusal,"refusal"),__name(sendToLiveBox,"sendToLiveBox"),__name(sendFollowUp,"sendFollowUp"),__name(runSandboxPrint,"runSandboxPrint"),Vt(),PR(),Vt();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 rG=__name(e=>({turnNumber:e,apiDurationMs:0,toolCalls:[],toolDurationMs:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}),"newTurn");function createBenchmarkCollector(e){const t=e.now??Date.now,n=e.writeFile??((e,t)=>{x.writeFileSync(e,t)}),r=t(),o=[],s=[],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=rG(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(rG(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 oG=null,sG=!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(sG)return;sG=!0;const e=__name(e=>{oG?.abort(),process.stderr.write(`\n${e}\n`),exitAfterModHostTeardown(lT.INTERRUPTED)},"handleTermination");process.on("SIGINT",()=>e("Interrupted.")),process.on("SIGTERM",()=>e("Terminated."))}async function printMode(e={}){trackCommand({command:"print"}),setupSignalHandlers(),oG=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)]),exitAfterModHostTeardown(o.exitCode)}function resolveLaunchPermissionMode2(e){return e.permissionMode?e.permissionMode:e.plan?"plan":e.dangerouslySkipPermissions?"bypass":void 0}async function isAuthenticated(){return null!==await getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}async function rpcMode(e={}){let t;trackCommand({command:"rpc"}),await isAuthenticated()||(process.stderr.write(CT),process.exit(lT.AUTH_ERROR)),e.model&&setModelOverride(e.model);try{t=await resolvePrintSession(e)}catch(e){const t=e instanceof Error?e.message:String(e);process.stderr.write(`Error: ${t}\n`),process.exit(lT.ERROR)}t.warning&&process.stderr.write(`${t.warning}\n`);const n=await resolvePrintResumeState({sessionId:t.sessionId,priorMessages:t.priorMessages,...t.sessionFilePath?{sessionFilePath:t.sessionFilePath}:{}}),r=await getConfiguredProvider(),o=null!=r&&"command-code"!==r;await runRpcMode({sessionId:t.sessionId,...o?{modelSwitchRefusal:`this session runs on the ${r} provider; start a new one with --model to use another model`}:{},stdin:process.stdin,writeLine:__name(e=>{process.stdout.write(`${e}\n`)},"writeLine"),dangerouslySkipPermissions:e.dangerouslySkipPermissions,createHarness:__name(async({sessionId:r,mods:o,drainQueuedMessages:s,peekQueuedMessageCount:a})=>{const i=await createHarnessSession({sessionId:r,baseUrl:getApiBaseUrl(),entrypoint:resolvePrintHarnessEntrypoint(t.entrypoint),headless:!0,mods:o,drainQueuedMessages:s,peekQueuedMessageCount:a,dangerouslySkipPermissions:e.dangerouslySkipPermissions,permissionMode:resolveLaunchPermissionMode2(e),modHost:await loadCommandModHost({projectMods:Boolean(e.dangerouslySkipPermissions)}),resumeState:n,persist:e.persist,...t.sessionFilePath?{sessionFilePath:t.sessionFilePath}:{},ideBridge:createLocalIdeBridge()});return e.name&&i.setSessionName(e.name),i},"createHarness")}),await new Promise(e=>{process.stdout.write("",()=>e())}),exitAfterModHostTeardown(lT.SUCCESS)}__name(resolveLaunchPermissionMode,"resolveLaunchPermissionMode"),__name(getAuthKey4,"getAuthKey"),__name(readStdin,"readStdin"),__name(writeOutput,"writeOutput"),__name(setupSignalHandlers,"setupSignalHandlers"),__name(printMode,"printMode"),Vt(),PR(),__name(resolveLaunchPermissionMode2,"resolveLaunchPermissionMode"),__name(isAuthenticated,"isAuthenticated"),__name(rpcMode,"rpcMode"),Vt(),PR();var aG=getPackageJson(import.meta.url),iG="string"==typeof aG.version&&aG.version.trim()?aG.version:"unknown";function createSystemOneTransport(){const e=b();return createNodeTransport({baseUrl:getApiBaseUrl(),headers:__name(()=>resolveCommandAuthHeaders({sessionId:e,cliVersion:iG}),"headers")})}function readStdinText(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("timeout reading from stdin"))},3e4);r.unref?.(),process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n)}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}function systemOneUsageHint(e){return`Run it headlessly: cmd -p '{"state": "...", "questions": {"<name>": {"type": "noul", "instructions": "..."}}}' -m ${e}`}async function runSystemOnePrint(e){const t=e.now??Date.now,n=t(),r="json"===e.outputFormat,o=__name((o,s,a=`Error: ${o}\n`)=>r?{exitCode:s,stderrText:a,stdoutText:`${safeJsonStringify({type:"result",subtype:"error",model:e.model,durationMs:t()-n,error:o})}\n`}:{exitCode:s,stderrText:a},"fail");let s=e.query;if(void 0===s||""===s.trim()){if(e.stdinIsTTY)return o(`no request given. ${systemOneUsageHint(e.model)}, or pipe the JSON on stdin`,lT.ERROR);try{s=await e.readStdin()}catch(e){return o(`could not read stdin: ${e instanceof Error?e.message:String(e)}`,lT.ERROR)}}const a=parseSystemOneQuery(s);if(!a.ok)return o(a.error,lT.ERROR);const i=await runSystemOne({transport:e.transport,model:e.model,request:a.request,...e.signal?{signal:e.signal}:{}});if(!i.ok&&"bad-response"===i.kind)return o(i.error,lT.SERVER_ERROR);if(!i.ok){const e=classifyPrintModeError(i.error);return o(e.stderrText.replace(/^\s*Error: /,"").trim(),e.exitCode,e.stderrText)}const{response:l}=i;if(!r){const t={model:l.model??e.model,answers:l.answers,usage:l.usage??{}};return{exitCode:lT.SUCCESS,stdoutText:`${JSON.stringify(t,null,2)}\n`}}const c=safeJsonStringify({type:"result",subtype:"success",model:l.model??e.model,answers:l.answers,usage:l.usage??{},durationMs:t()-n});return{exitCode:lT.SUCCESS,stdoutText:`${c}\n`}}async function ensureAuthenticated(){return ensureCommandAuthenticated({runLogin:__name(async()=>{await runLogin()},"runLogin"),getAuthKey:__name(()=>getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env}),"getAuthKey"),onAuthFailed:__name(()=>{console.error(`${ft.cross} Authentication failed. Please try again with: ${getBinaryCommand()} login`)},"onAuthFailed"),onLoginError:__name(e=>{console.error(`${ft.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:gr,groups:[...getModelGroupsInOrder(),...customModelListGroups()]})}function formatSystemOneModelNote(){const e=["Decision models (headless only)"],t=isJevFree()?"free through September 24, 2026":"$0.042 per 1M input tokens, everything else free";for(const n of XP)e.push(`${n} typed questions in, probabilities out, ${t} — ${systemOneUsageHint(n)}`);return e.join("\n")}async function printModelList(){await loadCustomProviderModels();const e=Boolean(process.stdout.isTTY)&&void 0===process.env.NO_COLOR;process.stdout.write(`${formatModelList({color:e})}\n`),process.stdout.write(`\n${formatSystemOneModelNote()}\n`);const t=getCustomProviderWarningsSync();t.length>0&&process.stderr.write(`\nproviders.json needs attention — ${1===t.length?"one entry":"some entries"} did not load as written:\n${t.map(e=>` ${e}`).join("\n")}\n`)}async function resolveModelFlagOrExit({model:e}){const t=await resolveSelectableModel(e);if(t){if(t.warning&&process.stderr.write(`Note: ${t.warning}\n`),!t.providerId){const e=customProvidersDeclaring(t.modelId);e.length>0&&process.stderr.write(`Note: "${t.modelId}" routes via Command Code; your providers.json also declares it — use ${e.map(e=>`"${e}/${t.modelId}"`).join(" or ")} to route there instead.\n`)}return{modelId:t.modelId,...void 0!==t.providerId?{providerId:t.providerId}:{}}}const n=suggestModel(e),r=n?` Did you mean "${n}"?`:"";process.stderr.write(`Error: unknown model "${e}".${r}\nRun "${getBinaryCommand()} --list-models" to see all available models\n`),process.exit(1)}__name(createSystemOneTransport,"createSystemOneTransport"),__name(readStdinText,"readStdinText"),__name(systemOneUsageHint,"systemOneUsageHint"),__name(runSystemOnePrint,"runSystemOnePrint"),Vt(),PR(),__name(ensureAuthenticated,"ensureAuthenticated"),Vt(),PR(),__name(suggestModel,"suggestModel"),__name(formatModelList,"formatModelList"),__name(formatSystemOneModelNote,"formatSystemOneModelNote"),__name(printModelList,"printModelList"),__name(resolveModelFlagOrExit,"resolveModelFlagOrExit"),Vt(),PR();var lG=!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:B.platform(),arch:B.arch()})}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync(),releaseRemoteLockSync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}async function disconnectMcpServers(){try{await Promise.allSettled([disconnectAllMcpServers(),R$()])}catch{}}function handleShutdownSignal(){lG||(lG=!0,abandonPendingCommandSpan(),Promise.allSettled([shutdownActiveRemote(),disconnectMcpServers(),disposeCommandModHost(),shutdownTelemetry()]).finally(()=>{process.exit(0)}))}async function shutdownAndExit(e=0){lG=!0,abandonPendingCommandSpan();try{await Promise.allSettled([shutdownActiveRemote(),disconnectMcpServers(),disposeCommandModHost(),shutdownTelemetry(jn)])}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=B.platform(),r=B.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 cG=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth");function sandboxRequested(e){return void 0!==e.sandbox&&!1!==e.sandbox}function sandboxValue(e){return"string"==typeof e.sandbox?e.sandbox.trim():""}async function requireSandboxBypassAllowed(){isBypassPermissionsDisabled(await loadCommandCodeConfig({runtime:getCommandConfigRuntime()}))&&(process.stderr.write("Sandbox sessions run without permission prompts, which your settings disable (permissions.disableBypass).\n"),process.exit(1))}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)Vy.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||!0===t.rpc;e||Boolean(t.trust||t.dangerouslySkipPermissions)||await isCommandProjectSessionInitialized()||(console.error(`Worktree error: this directory isn't trusted yet. Run \`${getInvokedCommandName()}\` here once to trust it, then retry with --worktree.`),process.exit(1));const n=enterWorktreeFromFlag(t.worktree,{quiet:e,track:!e});n.ok||(console.error(`Worktree error: ${n.error}`),process.exit(1)),await initializeCommandProjectSessions()}const o=t.model?resolveSystemOneModel(t.model):void 0;if(o){void 0===t.print&&(process.stderr.write(`Error: ${o} is a decision model (TypeSafe System One): it answers typed questions with probabilities, not chat, so it has no interactive mode. ${systemOneUsageHint(o)}\n`),process.exit(1)),await cG(),trackCommand({command:"print"});const n=await runSystemOnePrint({model:o,query:extractPrintModeQuery({print:t.print,prompt:e}),outputFormat:t.outputFormat,stdinIsTTY:Boolean(process.stdin.isTTY),readStdin:readStdinText,transport:createSystemOneTransport()});n.stderrText&&process.stderr.write(n.stderrText),n.stdoutText&&process.stdout.write(n.stdoutText),await shutdownAndExit(n.exitCode)}const a=t.model?await resolveModelFlagOrExit({model:t.model}):void 0,i=a?.modelId,l=t,c=__name(e=>{process.stderr.write(`${e.message}\n`),e.ok||process.exit(1)},"applySettingResult");for(const e of HN){const t=l[e.key];"string"==typeof t&&c(await e.apply(t,{model:i}))}const d=l.config;if(Array.isArray(d))for(const e of d)"string"==typeof e&&c(await applyConfigSetting(e));if((t.dangerouslySkipPermissions||"bypass"===t.permissionMode)&&isBypassPermissionsDisabled(await loadCommandCodeConfig({runtime:getCommandConfigRuntime()}))&&(process.stderr.write("Bypass permissions are disabled by settings (permissions.disableBypass); continuing with normal permission prompts.\n"),t.dangerouslySkipPermissions=!1,"bypass"===t.permissionMode&&(t.permissionMode=void 0)),t.rpc)return void await rpcMode({dangerouslySkipPermissions:t.dangerouslySkipPermissions,plan:t.plan,permissionMode:t.permissionMode,model:i,resume:t.resume,continue:t.continue,..."string"==typeof t.session?{session:t.session}:{},forkSession:t.forkSession,name:t.name,persist:!1!==t.session&&void 0});if(void 0!==t.print&&sandboxRequested(t)){await requireSandboxBypassAllowed(),await cG();const n=sandboxValue(t),r=mD.test(n)?n:null,o=extractPrintModeQuery({print:t.print,prompt:e});return void await runSandboxPrint({sessionId:r,task:r?o:n||o,...t.base?{baseBranch:t.base}:{},...i?{model:i}:{},..."string"==typeof l.effort?{effortGiven:!0}:{}}).catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)})}if(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:i,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})}i&&setModelOverride(i,a?.providerId),setGoalMaxTurnsOverride(t.maxTurns);const u=parseInteractivePromptArgument((sandboxRequested(t)&&!mD.test(sandboxValue(t))?sandboxValue(t):"")||e);await cG();const m=buildInteractiveRuntimeOptions(t),p=resolveInteractiveLaunchConfig({options:t,runtimeOptions:m,initialPrompt:u});if(setOriginalInvocation({trust:m.trust,dangerouslySkipPermissions:m.dangerouslySkipPermissions,skipOnboarding:m.skipOnboarding,maxTurns:t.maxTurns,skillPaths:n,skillDiscovery:r}),await installKeybindingsFromConfig({runtime:getCommandConfigRuntime()}),sandboxRequested(t)){const e=sandboxValue(t),n=mD.test(e)?e:null;return n&&t.base&&(process.stderr.write("--base applies to a new session only; a reopened one stays on its branch.\n"),process.exit(1)),await requireSandboxBypassAllowed(),enableSandboxMode({sessionId:n,...t.base?{baseBranch:t.base}:{}}),await nG({...p,dangerouslySkipPermissions:!0}),void await shutdownAndExit(Number(process.exitCode??0))}await nG(p),await shutdownAndExit(0)}__name(sandboxRequested,"sandboxRequested"),__name(sandboxValue,"sandboxValue"),__name(requireSandboxBypassAllowed,"requireSandboxBypassAllowed"),__name(interactiveModeAction,"interactiveModeAction"),Vt(),PR(),Vt(),PR();var dG={connected:yt.green("✔"),installed:yt.green("✔"),up_to_date:yt.green("✔"),needs_reload:yt.yellow("◌"),failed:yt.red("✖"),not_in_ide:yt.yellow("◌")};function formatSetupResult(e){const{prefix:t,ide:n,suffix:r}=getIDESetupStatusHeadline(e.status,e.ide),o=`${t}${n??""}${r}`;return["",`${dG[e.status]} ${o}`,...(e.details??[]).map(e=>yt.dim(` ${e}`)),""]}__name(formatSetupResult,"formatSetupResult"),globalThis.COMMAND_CODE_CWD=process.cwd();var uG=__name(()=>process.cwd(),"getCwd"),mG=__name(()=>process.argv.slice(2),"getArgs"),pG=__name(()=>{const e=uG(),t=mG(),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(){pG();const e=resolveCliStartupPlan({args:mG()});if(e.shouldRunIdeSetup){const e=await runIdeSetup({host:GW,moduleUrl:import.meta.url});formatSetupResult(e).forEach(e=>console.log(e)),process.exit("failed"===e.status?1:0)}e.shouldRunAutoUpdate&&runCliStartupPendingUpdates({plan:e,host:tH}),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:tH}),scheduleCliStartupIdeAutoInstall({host:GW,moduleUrl:import.meta.url})}__name(getAuthKey6,"getAuthKey"),__name(preRun,"preRun"),Vt(),PR();var gG=Object.fromEntries(Object.entries(Ak).map(([e,t])=>[t,e])),hG=new Set(UD.map(e=>e.id));function formatProviderModule(e){return hG.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=gG[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 UD){if(s.has(e.id))continue;if(!1===e.discoverable)continue;const n=gG[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=[Pt.bold("Providers available for login/logout"),""];for(const r of e){const e=r.authenticated?Pt.green("logged in"):Pt.dim("not logged in"),o=r.installed?"":Pt.dim(" (not installed, installs on first login)");n.push(Pt.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: ${Pt.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(Pt.yellow("Provider load errors"));for(const e of t.errors)console.log(`${Pt.yellow(e.id)}: ${e.error}`)}}__name(formatProviderModule,"formatProviderModule"),__name(buildProviderLoginRows,"buildProviderLoginRows"),__name(formatProviderLoginRows,"formatProviderLoginRows"),__name(providersAction,"providersAction");var fG=new He("providers").description("List providers available for login/logout").option("--json","Output providers as JSON for automation").action(providersAction);function assertSessionId(e){mD.test(e)||(console.error(Pt.red(`Invalid session id: ${e}`)),console.error(Pt.dim(`Find it with: ${getBinaryCommand()} --experimental sandbox list`)),process.exit(1))}function client(){return createSandboxClient({transport:createSandboxTransport()})}function printTaskSummary(e){console.error(`${Pt.dim("Status:")} ${e.status}`),e.prUrl&&console.error(`PR: ${Pt.cyan(e.prUrl)}`),e.error&&console.error(Pt.red(e.error)),console.error(Pt.dim(`Open it with: ${getBinaryCommand()} --experimental --sandbox ${e.sessionId}`))}async function statusSandboxTask(e){assertSessionId(e),printTaskSummary(await client().status({sessionId:e}))}async function stopSandboxTask(e){assertSessionId(e);const{status:t}=await client().cancel({sessionId:e});"cancelled"===t?console.error(Pt.yellow("Session stopped.")):console.error(Pt.yellow(`Session already ${t.replace("_"," ")}.`))}async function listSandboxTasks(){const{sessions:e}=await client().list();if(0!==e.length){console.log(Pt.dim(`${"SESSION".padEnd(38)}${"STATUS".padEnd(12)}${"AGE".padEnd(12)}REPO`));for(const t of e){const e=t.repoUrl.replace(/^https:\/\/github\.com\//,""),n=formatRelativeTimeShort({timestamp:t.createdAt});console.log(`${t.sessionId.padEnd(38)}${t.status.padEnd(12)}${n.padEnd(12)}${Pt.dim(e)}`)}}else console.error("No sandbox sessions yet.")}function run3(e){e().catch(e=>{const t=e instanceof Error?e.message:"Unknown error";console.error(Pt.red(t)),process.exit(1)})}function createSandboxCommand(){const e=new He("sandbox").description("Manage your cloud sandbox sessions").action(()=>{console.log(["Work in a sandbox:"," cmd --experimental --sandbox open a new session (the TUI)"," cmd --experimental --sandbox <id> reopen a session",' cmd --experimental --sandbox "message" open a new session with a first message',' cmd --experimental -p --sandbox "task" run one task, print the session id',' cmd --experimental -p --sandbox <id> "task" send a follow-up task',"Manage sessions:"," cmd --experimental sandbox list | status <id> | stop <id>"].join("\n"))});return e.command("list").description("List your sandbox sessions").action(()=>run3(listSandboxTasks)),e.command("status").description("Show a session summary").argument("<sessionId>").action(e=>run3(()=>statusSandboxTask(e))),e.command("stop").description("Stop a running session").argument("<sessionId>").action(e=>run3(()=>stopSandboxTask(e))),e}Vt(),Vt(),PR(),__name(assertSessionId,"assertSessionId"),__name(client,"client"),__name(printTaskSummary,"printTaskSummary"),__name(statusSandboxTask,"statusSandboxTask"),__name(stopSandboxTask,"stopSandboxTask"),__name(listSandboxTasks,"listSandboxTasks"),__name(run3,"run"),__name(createSandboxCommand,"createSandboxCommand"),Vt(),Vt(),PR();var yG=[`${Pt.dim("Usage:")}`,` ${Pt.cyan(`${getBinaryCommand()} skills add`)} ${Pt.white("<owner/repo>")}`,"",`${Pt.dim("Examples:")}`,` ${Pt.cyan(`${getBinaryCommand()} skills add`)} ${Pt.white("acme/my-skills")} ${Pt.dim("# single-skill repo")}`,` ${Pt.cyan(`${getBinaryCommand()} skills add`)} ${Pt.white("acme/skills/path/to/skill")} ${Pt.dim("# specific path in repo")}`,` ${Pt.cyan(`${getBinaryCommand()} skills add`)} ${Pt.white("acme/multi-skills -s my-skill")} ${Pt.dim("# pick one from multi-skill repo")}`,` ${Pt.cyan(`${getBinaryCommand()} skills add`)} ${Pt.white("acme/repo@branch")} ${Pt.dim("# specific branch")}`,` ${Pt.cyan(`${getBinaryCommand()} skills add`)} ${Pt.white("acme/repo --global")} ${Pt.dim("# install to ~/.commandcode/skills/")}`],SG=__name((e,t)=>`${Pt.green(ft.tick)} Installed ${Pt.cyan(e)} ${Pt.dim(`${ft.arrowRight} ${t}/`)}`,"formatInstalled"),wG=__name(e=>`${Pt.red(ft.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(wG(t.message)),console.log(""),t.message.startsWith("Invalid repository")&&(console.log(`Expected format: ${Pt.cyan("owner/repo")} or ${Pt.cyan("owner/repo/path")}`),console.log("")),yG.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=It({text:`Fetching ${Pt.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(wG(`No skills found in ${Pt.cyan(e)}`)),console.log(Pt.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(o,1)),"missing-requested-skill"===d.kind)return console.error(wG(`Skill "${d.requestedSkillName}" not found in ${Pt.cyan(d.repoInput)}`)),console.log(""),console.log(Pt.dim("Available skills:")),d.availableSkillNames.forEach(e=>console.log(` ${Pt.cyan(e)}`)),void await cleanupAndExit(o,1);if("prompt"===d.kind){const t=await Ye({message:`Select skills to install from ${e}`,options:[...d.options],required:!0});"symbol"==typeof t&&(console.log(Pt.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=It({text:`Installing ${Pt.cyan(e.name)}...`,color:"cyan"}),u.start()},"onSkillStart"),onSkillInstalled:__name(e=>{u?.stop(),console.log(SG(e.name,r))},"onSkillInstalled"),onSkillFailed:__name(({skillName:e,message:t})=>{u?.stop(),console.error(wG(`Failed to install "${e}"`)),console.log(Pt.dim(` ${t}`))},"onSkillFailed")});await cleanupAndExit(o,m.exitCode)}catch(e){s.stop();const t=e instanceof Error?e.message:String(e);console.error(wG(t)),await cleanupAndExit(o,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction2,"addAction");var vG=new He("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${yG.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(wG("No repository specified.")),console.log(""),yG.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction2);Vt(),PR();var kG=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${Pt.cyan(e)} ${Pt.dim(`· ${n}`)}`},"formatSkillLine"),CG=__name((e,t)=>`${Pt.bold(Pt.white(e))} ${Pt.dim(`(${t})`)}`,"formatSectionHeader"),bG=__name(e=>{if(0!==e.warningCount){console.log(""),console.log(`${Pt.bold(Pt.yellow("Skipped"))} ${Pt.dim(`(${e.warningCount})`)}`);for(const t of e.warningGroups){console.log(""),console.log(` ${Pt.bold(t.category)} ${Pt.dim(`(${t.items.length})`)}`);for(const e of t.items)console.log(` ${Pt.bold(skillIdentifier(e.path))}`),console.log(` ${Pt.dim(e.reason)}`)}}},"printWarnings"),EG=__name(e=>{const t=["",Pt.dim("No skills installed."),"",Pt.dim("Looking in:")];for(const n of e.lookupPaths)t.push(Pt.dim(` ${n.path} ${Pt.white(`(${n.label})`)}`));return t.push("",`Install a skill: ${Pt.cyan(e.installCommand)} ${Pt.dim(e.installPlaceholder)}`,""),t},"formatEmptyHint"),TG=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),PG=__name(e=>{e&&(console.log(""),console.log(Pt.dim(e.replace("--debug",Pt.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()}`});TG(EG(t));for(const e of s.sections)console.log(CG(e.title,e.skills.length)),e.skills.forEach(e=>{console.log(kG(e.name,e.description))}),console.log("");e&&(bG({warningCount:s.warningCount,warningGroups:s.warningGroups}),s.warningCount>0&&console.log("")),e||(PG(s.debugHint),console.log("")),process.exit(0)}console.log(""),console.log(heading({text:"Skills",sub:Pt.dim(`${s.userInstalledTotal} installed`)}));for(const e of s.sections)console.log(""),console.log(CG(e.title,e.skills.length)),e.skills.forEach(e=>{console.log(kG(e.name,e.description))});e&&bG({warningCount:s.warningCount,warningGroups:s.warningGroups}),e||PG(s.debugHint),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${Pt.red(ft.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction2,"listAction");var MG=new He("list").description("List all installed skills. Run with -d/--debug to also see why any skills were skipped.").action(listAction2);Vt(),PR();var xG=__name((e,t)=>`${Pt.green(ft.tick)} Removed ${Pt.cyan(e)} from ${t} skills`,"formatRemoved"),IG=__name(e=>`${Pt.red(ft.cross)} ${e}`,"formatError"),AG=__name((e,t)=>{let n=e;for(const e of t)n=n.replace(e,Pt.cyan(e));return Pt.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(IG(o)),console.log(AG(getSkillListCommandHint({binCommand:`${getBinaryCommand()}`}),[`${getBinaryCommand()} skills list`])),process.exit(1)),!t.yes&&n){const t=await Qe({message:`Remove ${Pt.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(Pt.dim("Cancelled")),process.exit(0))}await removeCommandSkill({skillName:e,global:t.global}),console.log(xG(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(IG(o.message)),"not-found"===o.kind)for(const t of o.hints)console.log(AG(t,[`${getBinaryCommand()} skills remove ${e} --global`,`${getBinaryCommand()} skills list`]));process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction2,"removeAction");var RG=new He("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),LG=new He("skills").description("Manage skills from GitHub repositories").addCommand(vG).addCommand(RG).addCommand(MG);Vt(),PR(),Vt(),PR(),Vt(),Vt(),PR();var OG=[ft.bullet,ft.squareSmallFilled,ft.lozenge,ft.star,ft.triangleRight,ft.triangleUp];Vt(),PR(),Vt();var DG=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return DG.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"),Vt(),PR(),Vt(),Vt();var $G=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),o=e.learningCount>0;return it.createElement(Ze,{flexDirection:"column",marginLeft:3},it.createElement(Ze,{marginBottom:1,flexDirection:"row"},it.createElement(et,{color:LR.DIM},TL),it.createElement(Ze,{marginLeft:2},it.createElement(et,{color:DR.TEXT},o?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),it.createElement(Ze,{flexDirection:"column",marginLeft:1},it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},ft.pointerSmall," Taste stored in"," "),it.createElement(yL,{url:fileUrl(e.storage),text:r||".commandcode/taste/taste.md",color:LR.CYAN})),it.createElement(Ze,null,it.createElement(et,{color:LR.DIM},ft.pointerSmall," Share your coding taste:"," ",it.createElement(et,{color:LR.CYAN},"npx taste push --all")))),it.createElement(Ze,{marginTop:1,marginLeft:1},it.createElement(et,{color:LR.DIM},o?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Vt();var NG=__name(({message:e})=>it.createElement(B$,null,e),"RepoLearnErrorPanel");Vt();var _G=__name(({done:e,error:t})=>t?it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Press ",it.createElement(CO,null,"Esc")," to exit")):e?it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Press ",it.createElement(CO,null,"Enter")," to continue")):it.createElement(Ze,{marginTop:1},it.createElement(kO,null,"Esc to cancel")),"RepoLearnFooter");Vt(),PR();var FG=__name(({insights:e,insightCount:t})=>0===e.length?null:it.createElement(Ze,{flexDirection:"column",marginTop:1,marginLeft:4},it.createElement(et,{color:LR.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>it.createElement(et,{key:`${t}-${e}`,color:LR.DIM},OG[t%OG.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Vt(),PR();var UG=__name(({status:e})=>"active"===e?it.createElement(Ze,null,it.createElement(et,{color:LR.YELLOW},it.createElement(bt,{type:"dots"})),it.createElement(et,null," ")):"complete"===e?it.createElement(et,{color:FR.BG},ft.square," "):it.createElement(et,{color:LR.DIM},ft.circle," "),"StepStatusIndicator");function getStepLabelColor(e,t){return"complete"===e?LR.WHITE:t?LR.YELLOW:LR.DIM}__name(getStepLabelColor,"getStepLabelColor");var jG=__name(({steps:e,currentMessage:t})=>it.createElement(Ze,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return it.createElement(Ze,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},it.createElement(Ze,null,it.createElement(Ze,{marginRight:1},it.createElement(UG,{status:e.status})),it.createElement(et,{bold:n,color:getStepLabelColor(e.status,n)},e.label)),n&&t?it.createElement(Ze,{marginLeft:3},it.createElement(et,{color:LR.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Vt();var BG=__name(({isComplete:e,hasError:t})=>t?it.createElement(et,{color:LR.DIM},"learning interrupted"):e?it.createElement(et,{color:DR.TEXT},"learned your coding taste"):it.createElement(vL,null),"TastePillStatus"),WG=__name(({isComplete:e,hasError:t})=>it.createElement(Ze,{flexDirection:"column",marginTop:1,marginBottom:0},it.createElement(IL,null),it.createElement(Ze,{marginTop:0},it.createElement(et,{color:LR.DIM},TL),it.createElement(Ze,{marginLeft:2},it.createElement(BG,{isComplete:e,hasError:t})))),"RepoLearnTastePill");Vt();var HG=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=mt(()=>cO(n),[n]);return it.createElement(Ze,{flexDirection:"column"},it.createElement(Ze,{flexDirection:"column",marginBottom:1},it.createElement(nL,null,r.trimEnd())),e?it.createElement(et,{color:LR.WHITE},e):it.createElement(it.Fragment,null,it.createElement(et,{color:LR.WHITE},"Learning your coding taste from"," ",it.createElement(et,{bold:!0,color:LR.CYAN},t??"repository")),it.createElement(et,{color:LR.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function useRepoLearnState(e){const t=e??OI,[n,r]=ct(()=>createRepoLearnProjection({stepOrder:t})),o=dt(null),[s,a]=ct(null),i=pt(()=>{o.current=Date.now()},[]),l=pt(e=>{r(t=>({...t,showLogin:e}))},[]);return ut(()=>{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 up.on("reset",e),up.on("new-event",n),up.on("learning-complete",s),()=>{up.off("reset",e),up.off("new-event",n),up.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?it.createElement(NG,{message:e}):t?it.createElement($G,{summary:n,elapsedSeconds:r}):it.createElement(FG,{insights:o,insightCount:s})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:o}){const s=useRepoLearnState(n),a=dt(!1);return ut(()=>{a.current||(a.current=!0,s.markStarted(),e().catch(()=>{}))},[e,s.markStarted]),ot((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?it.createElement(Ze,{flexDirection:"column"},it.createElement(HG,{text:r,repoName:o}),it.createElement(GF,{onComplete:(e,t)=>{s.setShowLogin(!1),e?up.resolveAuth():up.rejectAuth(t)},onCancel:()=>{s.setShowLogin(!1),up.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):it.createElement(Ze,{flexDirection:"column"},it.createElement(HG,{text:r,repoName:o}),it.createElement(WG,{isComplete:s.done&&!s.error,hasError:Boolean(s.error)}),it.createElement(jG,{steps:s.steps,currentMessage:s.currentMessage}),it.createElement(StatusPanel,{error:s.error,done:s.done,summary:s.summary,elapsedSeconds:s.elapsedSeconds,insights:s.insights,insightCount:s.insightCount}),it.createElement(_G,{done:s.done,error:s.error}))}async function runRepoLearnProgress(e){return await applyStartupTheme(),withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{up.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,up.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),up.markLearningComplete())}},"handleRunTask"),c=__name(({published:e,cancelled:l})=>{i||(i=!0,a=e,r.abort(),d.unmount(),up.reset(),s?n(s):t({result:o,published:a,cancelled:l}))},"handleExit"),d=rt(it.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:c}));d.waitUntilExit().catch(e=>{up.reset(),n(e)})})}function getAuthKey7(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}function logLearnSummary(e){const{summary:t}=e;console.log(yt.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("")}Vt(),PR(),__name(useRepoLearnState,"useRepoLearnState"),__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),__name(getAuthKey7,"getAuthKey"),__name(logLearnSummary,"logLearnSummary");var GG=__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 He("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",GG("--max-commits"),200).addOption(new Ge("--max-signals <number>","Maximum diff signals to extract").default(50).argParser(GG("--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:up,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:[...DI];({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),UL(),await nG({skipOnboarding:!0}),await shutdownAndExit(0)}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Vt(),PR(),Vt(),PR();var VG=yt.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(`${yt.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?`${yt.dim(t[1])}${yt.green(t[2])}${yt.white(t[3]??"")}${t[4]?yt.dim(t[4]):""}`:yt.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${yt.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 zG=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){const n=buildPackageUrl({owner:e,packageName:t});return Lt(`commandcode.ai/${e}/${t}`,n,{fallback:zG})}function getProfileLink(e){const t=buildProfileUrl2(e);return Lt(`commandcode.ai/${e}`,t,{fallback:zG})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return Ot(e,n,{trim:!1})}function logMergeReviewTip(){console.log(yt.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}function handleResultErrors(e){for(const t of e){const e=normalizeTasteResultError(t);console.error(`${yt.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(yt.red(`Error: ${t}`)),await flushAndExit(1)}}}function formatSingleIssue(e,t){const n=[`${e.line?yt.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(yt.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`${yt.green(e)} ${yt.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?yt.red(t.summary):yt.yellow(t.summary),"",...formatIssueGroup(r,yt.red,yt.bold(yt.red("Errors:"))),...formatIssueGroup(o,yt.yellow,yt.bold(yt.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"),Vt(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var KG=createTasteLintService({runtime:createNodeRuntime(),formatValidationIssues:formatValidationIssues});function createLintCommand(){return new He("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 ${yt.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(`${yt.green(ft.tick)} All ${yt.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(yt.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(yt.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 KG.lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(yt.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Vt(),PR();var qG={};__export(qG,{downloadPackage:()=>downloadPackage,downloadRemotePackage:()=>downloadRemotePackage,getAllPackages:()=>getAllPackages,getPackage:()=>getPackage,listPackages:()=>listPackages,writePackage:()=>writePackage,writePackages:()=>writePackages}),Vt(),PR();var YG=createNodeRuntime();function getAuthKey8(){return getCommandAuthKey({runtime:getCommandConfigRuntime(),path:getAuthFile(),env:process.env})}async function requireAuthKey(){const e=await getAuthKey8();if(!e)throw new Error(`No API key found. Please authenticate with: ${getBinaryCommand()} login`);return e}function storage(){return createTasteRemoteStorage({transport:createNodeTransport({baseUrl:getApiBaseUrl()}),requireAuthKey:requireAuthKey,getAuthKey:getAuthKey8,getAuthenticatedEntity:__name(()=>getAuthenticatedEntity({client:createApiClient({baseUrl:getApiBaseUrl()})}),"getAuthenticatedEntity"),trackError:__name(({error:e,label:t,heading:n,context:r})=>trackError({error:sanitizeErrorForTelemetry({error:e,label:t}),context:{component:qo.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:YG,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 QG=createNodeRuntime(),JG=createTasteLocalStorage({runtime:QG,target:"local-project"}),XG=createTasteLocalStorage({runtime:QG,target:"local-global"});function list(e){return createTasteListService({runtime:QG,localProject:JG,localGlobal:XG,remote:qG}).list(e)}function getUserName(){return getCommandAuthUserName({runtime:getCommandConfigRuntime(),path:getAuthFile()})}function createListCommand(){return new He("list").alias("ls").option("-g, --global","List global packages").addOption(new Ge("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Ge("--staging","Use staging environment").hideHelp()).description(`List available packages ${yt.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}function formatPackageLine(e){return` ${yt.white(e.name)}${e.publicBadge?yt.green(e.publicBadge):""}${e.starsBadge?yt.yellow(e.starsBadge):""}${e.downloadsBadge?yt.gray(e.downloadsBadge):""}${e.padding}${yt.dim.gray(e.statsLabel)}`}function validateListOptions(e){exitWithTasteCliValidation(validateTasteListCliOptions(e))}async function fetchPackages({options:e}){const t=resolveTasteListStorage(e),n=e.remote?It(`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${VG} Packages`),console.log(`${yt.gray("⎿")} ${yt.dim(t)}\n`);const n=projectTasteListView({packages:e,symbols:{star:ft.star,arrowDown:ft.arrowDown}});for(const e of n.rows)console.log(formatPackageLine(e));console.log(yt.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(yt.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"),Vt(),PR(),Vt(),PR();var ZG=createNodeRuntime(),eV=createTasteLocalStorage({runtime:ZG,target:"local-project"}),tV=createTasteLocalStorage({runtime:ZG,target:"local-global"});async function open7(e){try{const t=await createTasteOpenService({runtime:ZG,localProject:eV,localGlobal:tV,remote:qG}).resolveOpen(e);return t.success?(await Rt([{file:t.filePath,line:t.lineNumber}]),t):t}catch(e){return classifyTasteOpenError({error:e,platform:Pe.platform})}}function createOpenCommand(){return new He("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 ${yt.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 xt(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${yt.green(ft.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(`${yt.green(ft.tick)} Opened ${yt.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"),Vt(),PR(),Vt(),PR(),Vt();var nV=null,rV=!1;function setActiveSpinner(e){nV=e}function stopActiveSpinner(e){nV&&(nV.stop(e),nV=null)}function setPrompted(e){rV=e}function wasPrompted(){return rV}function logResult(e){if(wasPrompted())return ze.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{summary:t,sourceName:n}=e,r=wasPrompted()?"":`${ft.tick} `,o=t.detailPath?yt.dim(`\n ${shortenPath(t.detailPath)}`):"";return"single-replaced"===t.variant?`${yt.green(r)}Replaced ${yt.green(`'${t.packageName}'`)} taste package in project`+o:"single-merged"===t.variant?`${yt.green(r)}Pulled ${yt.green(`'${t.packageName}'`)} taste package from ${n} ${yt.gray(`(${t.mergeParts.join(", ")})`)}`+o:`${yt.green(r)}Pulled ${yt.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(`${yt.green("Pulled")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`,wasPrompted()?4:0)),t.overwritten.length>0&&r.push(wrapLine(`${yt.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`,wasPrompted()?4:0)),t.skipped.length>0&&r.push(wrapLine(`${yt.dim("Skipped")} (${t.skipped.length}) ${yt.dim(t.skipped.join(", "))}`,wasPrompted()?4:0)),wasPrompted())return r.length>0&&ze.log.message(r.join("\n")),ze.outro(`${t.totalLabel} from ${n}`),void setPrompted(!1);console.log(`${yt.green(ft.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(yt.yellow(o.message))}function beginPrompt(e,t){stopActiveSpinner(),ze.intro(yt.dim(e)),t&&ze.log.message(yt.dim(t)),setPrompted(!0)}function handleCancel(e){ze.isCancel(e)&&(ze.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=ze.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=ze.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),ze.log.warn(e.nonInteractive.warning),e.nonInteractive.strategy;if(beginPrompt(`${e.title.prefix}${yt.green(e.title.emphasis)}${e.title.suffix}`,e.existsMessage),ze.log.message(`${e.context.firstLine}\n${e.context.secondLine}${e.context.secondLineNote?` ${yt.dim(e.context.secondLineNote)}`:""}`),e.reviewLink){const t=Lt(e.reviewLink.text,e.reviewLink.url,{fallback:__name((e,t)=>t,"fallback")});ze.log.info(`${e.reviewLink.prefix}${yt.cyan(t)} ${yt.dim(e.reviewLink.note)}`)}const t=await ze.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"),Vt(),PR(),Vt(),PR(),__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 oV=createNodeRuntime(),sV=createTasteLocalStorage({runtime:oV,target:"local-project"}),aV=createTasteLocalStorage({runtime:oV,target:"local-global"});function service(){return createTastePullService({localProject:sV,localGlobal:aV,remote:qG,getDestinationPath:__name(e=>resolveTastePackageDestinationPathForRuntime({runtime:oV,...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 He("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 Ge("--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 Ge("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${yt.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(It("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(It("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 ze.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?yt.dim(`\n ${shortenPath(e)}`):""}function renderPushSummary(e){const t=wasPrompted()?"":`${ft.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?` ${yt.gray(`(${e.replacedLabel})`)}`:"";return void logResult2(`${yt.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?` ${yt.gray(`(${e.mergeParts.join(", ")})`)}`:"";return void logResult2(`${yt.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(`${yt.green(t)}Pushed ${yt.green(e.count)} taste packages ${yt.green(`(${e.packages.join(", ")})`)} to ${e.targetName}`)):logResult2(`${yt.green(t)}Pushed ${yt.green(`'${e.packageName}'`)} taste package to ${e.locationLabel}`+formatDetailPath(e.detailPath)):logResult2(`${yt.green(t)}Pushed ${yt.green(`'${e.packageName}'`)} taste package to ${e.locationLabel} ${yt.gray(`(${e.mergeParts.join(", ")})`)}`+formatDetailPath(e.detailPath)):logResult2(`${yt.green(t)}Replaced ${yt.green(`'${e.packageName}'`)} taste package in ${e.locationLabel}`+formatDetailPath(e.detailPath))}else logResult2(`${yt.green(t)}Pushed ${e.packageCountLabel} to ${formatAllLocation(e.location)}`)}else logResult2(`${yt.green(t)}Pushed ${e.packageCountLabel} to remote`);else logResult2(`${yt.green(t)}Skipped ${e.packageCountLabel}`)}function logPushUrls(e){for(const t of collectTastePushRemoteLinks(e))console.log(yt.gray(` ${getPackageLink(t)}`))}function logConflictSummary(e){const t=projectTastePushOutcome(e.result),n=[];t.succeeded.length>0&&n.push(wrapLine(`${yt.green("Merged")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`,4)),t.overwritten.length>0&&n.push(wrapLine(`${yt.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`,4)),t.skipped.length>0&&n.push(wrapLine(`${yt.dim("Skipped")} (${t.skipped.length}) ${yt.dim(t.skipped.join(", "))}`,4)),n.length>0&&ze.log.message(n.join("\n")),ze.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(`${yt.green("Pushed")} (${t.succeeded.length}) ${t.succeeded.join(", ")}`)),t.overwritten.length>0&&n.push(wrapLine(`${yt.yellow("Overwritten")} (${t.overwritten.length}) ${t.overwritten.join(", ")}`)),t.skipped.length>0&&n.push(wrapLine(`${yt.dim("Skipped")} (${t.skipped.length}) ${yt.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"),Vt(),PR(),Vt(),PR(),__name(logResult2,"logResult"),__name(formatAllLocation,"formatAllLocation"),__name(formatDetailPath,"formatDetailPath"),__name(renderPushSummary,"renderPushSummary"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Vt(),PR();var iV=createNodeRuntime(),lV=createTasteLocalStorage({runtime:iV,target:"local-project"}),cV=createTasteLocalStorage({runtime:iV,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:lV,localGlobal:cV,remote:qG,getUserOwner:getUserOwner,getProjectName:__name(()=>e.basename(process.cwd()),"getProjectName"),getDestinationPath:__name(e=>resolveTastePackageDestinationPathForRuntime({runtime:iV,...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 ze.select({message:"Owner",options:[...r],initialValue:o});return ze.isCancel(s)&&(ze.cancel("Operation cancelled"),process.exit(0)),s}__name(getUserOwner,"getUserOwner"),__name(service2,"service"),__name(push,"push"),__name(pushRemote,"pushRemote"),Vt(),PR(),__name(promptOwnerSelection,"promptOwnerSelection");var dV=createNodeRuntime(),uV=createTasteLocalStorage({runtime:dV,target:"local-project"});function loadUserNamespaces(){return fetchUserNamespaces({client:createApiClient({baseUrl:getApiBaseUrl()})})}function createPushCommand(){return new He("push").description(`Push taste packages to remote ${yt.dim("(commandcode.ai)")} or global ${yt.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 Ge("--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 Ge("--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 uV.getAllPackages()).some(t=>t.category===e),"hasLocalPackage"),loadNamespaces:loadUserNamespaces,prompt:{onPromptStart:__name(({packageName:e})=>{ze.intro(yt.dim(`pushing ${e}`)),setPrompted(!0),t=ze.spinner(),t.start("Resolving")},"onPromptStart"),onPackageMissing:__name(({packageName:e})=>{t?.error("Failed"),ze.outro(yt.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 uV.getAllPackages()).length),r=e.basename(process.cwd()),o=resolveTasteStrategyLabel({strategy:t.route.strategy,isRemote:!0});console.log(yt.dim(` Pushing ${n} to ${r} (remote)${o}`)),console.log(""),setActiveSpinner(It("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=ze.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(It("Pushing taste package").start())}async function pushGlobal(e){const t=await uV.getAllPackages(),n=formatTastePackageCount(e.route.packages.length>0?e.route.packages.length:t.length),r=shortenPath(getTastePathForRuntime({runtime:dV,target:"local-global"})),o=resolveTasteStrategyLabel({strategy:e.route.strategy});console.log(yt.dim(` Pushing ${n} to ${r}${o}`)),console.log(""),setActiveSpinner(It("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(`${yt.green(ft.tick)} Taste learning is on${whereFor(e)}. New preferences are saved and reused across sessions.`)}function reportDisabled(e){const t=getBinaryCommand();console.log(`${yt.green(ft.tick)} Taste learning is off${whereFor(e)}. Turn it back on with ${yt.cyan(`${t} taste enable`)}.`)}function createEnableCommand(){return new He("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 He("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 He("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"),Vt(),PR(),__name(scopeOf,"scopeOf"),__name(whereFor,"whereFor"),__name(applyTasteLearning,"applyTasteLearning"),__name(reportEnabled,"reportEnabled"),__name(reportDisabled,"reportDisabled"),__name(createEnableCommand,"createEnableCommand"),__name(createDisableCommand,"createDisableCommand"),__name(createTasteCommand,"createTasteCommand"),Vt(),PR();var mV=`${getBinaryCommand()}`;function formatVersion(e,t,n=!1){const r=n?Pt.bold(Pt.green(t)):Pt.white(t);return`${Pt.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(`${mV} update`,Pt.bold(Pt.green(`${mV} update`))))}function showUpdateSuccessHint(e){for(const t of e.detailLines)console.log(Pt.dim(t.replace(mV,Pt.cyan(mV))))}function showManualUpdateHint(e){const[t,n]=e.manualUpdateLines;t&&console.log(Pt.dim(t)),n&&console.log(Pt.cyan(n))}function showCheckFailure(e){for(const t of e.detailLines)console.log(Pt.dim(t))}function renderUpdateEvent(e,t){if("type"in e)"updating"===e.type&&(t.text=e.text.replace("→",ft.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(`${Pt.green(ft.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=It("Checking for updates...").start(),n=await runCliUpdateCommand({checkOnly:e.checkOnly,host:tH,copy:{binCommand:mV,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:qo.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 pV=new He("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})}Vt(),PR(),__name(getAuthKey9,"getAuthKey");var gV=__name((e,t)=>`${ft.info} ${e}: ${Pt.cyan(t)}`,"formatInfoLine"),hV=__name(e=>Pt.bold(`${e}:`),"formatSectionHeader"),fV=__name(e=>Pt.red(e),"formatError"),yV=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),SV=__name((e,t)=>["",hV(e),...t.map(e=>gV(e.label,e.value))],"buildSection"),wV=__name(e=>SV("User Information",projectWhoamiUserRows(e)),"buildUserOutput"),vV=__name(e=>SV("Organization",projectWhoamiOrgRows(e)),"buildOrgOutput"),kV=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),CV=__name((e,t)=>{kV(wV(e)),t&&kV(vV(t)),console.log("")},"displayUserInfo");async function whoamiAction(){const e=It("Fetching user information...").start();try{hasCommandApiKey(await getAuthKey9())||(e.fail(fV(Yt)),process.exit(1));const t=await getAuthenticatedEntity({client:createApiClient({baseUrl:getApiBaseUrl()})});isAuthenticatedEntityLoaded(t)||(e.fail(fV(Qt)),process.exit(1)),e.succeed("User information loaded"),CV(t.user,t.org)}catch(t){e.fail(fV(`Error: ${yV(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var bV=new He("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 EV=createProgram();EV.action(interactiveModeAction),EV.addCommand(i$),EV.addCommand(y$),EV.addCommand(bV),EV.addCommand(pV),EV.addCommand(a$),EV.addCommand(s$),EV.addCommand(createTasteCommand()),EV.addCommand(createMcpCommand()),EV.addCommand(dN),EV.addCommand(e$),EV.addCommand(KD),EV.addCommand(ZD),EV.addCommand(fG),EV.addCommand(LG),EV.addCommand(AN),isExperimentalEnabled()&&EV.addCommand(createSandboxCommand()),addExperimentalRootOptions(EV),setupCommanderHooks(EV),EV.parse();