@github/copilot 0.0.340-6 → 0.0.340-7

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.
Files changed (2) hide show
  1. package/index.js +1 -1
  2. package/package.json +2 -2
package/index.js CHANGED
@@ -2326,7 +2326,7 @@ ${z.stack}`):u.debug(`Command threw error: ${z}`)),z}}catch(x){let U=x&&typeof x
2326
2326
  `+U+`
2327
2327
  `),await r.forceSave(),hs.exit(0)}catch(R){a.error(`Error executing prompt: ${R}`),await r.forceSave(),hs.exit(1)}finally{if(y)try{await y.stopServers()}catch(R){a.error(`Error stopping MCP servers: ${R}`)}}}var s3n=({featureFlags:t=Hde,authManager:e,sessionManager:l,needsSessionPicker:n,allowAllTools:I,rules:r,showBanner:a,showHeader:s,trajectoryOutputFile:o,logger:d,additionalDirs:u,disabledMcpServers:G,errorService:p,cliModel:h,showLlmTiming:W})=>{let{theme:y,setThemePreference:R,themeInitialized:w}=Mn(),{stdout:C}=HN(),L=UJ(),x=p2(),[U,D]=(0,Ft.useState)(0),[M,q]=(0,Ft.useState)(n??!1),T=(0,Ft.useCallback)(()=>{hs.stdout.write(Lb.cursorTo(0,0)+Lb.eraseScreen),D(Dt=>Dt+1)},[D,C]),z=Vrl(),se=d??new OA,Ae=W?new L8:void 0;(0,Ft.useEffect)(()=>{let Dt=null,vl=z.columns,RI=z.rows,ui=(Hs,pd)=>{let Tc=Hs,yp=pd;if(Tc===vl&&yp!==RI){RI=yp;return}Tc!==vl&&(vl=Tc,RI=yp,Dt&&clearTimeout(Dt),Dt=setTimeout(()=>{T()},50))};return z.setOnResize(ui),()=>{z.setOnResize(null),Dt&&clearTimeout(Dt)}},[T,C]),(0,Ft.useEffect)(()=>{p?.addErrorHandler(Dt=>{ps(l,{type:"error",text:String(Dt)})})},[p]);let[Ee,ne]=(0,Ft.useState)([]),[P,Ge]=(0,Ft.useState)({}),[ie,Ye]=(0,Ft.useState)(0),[pe,ke]=(0,Ft.useState)(!1),[Ve,ye]=(0,Ft.useState)({totalTokens:0,postTruncationTokens:0,tokenLimit:0,truncationStrategy:"truncation",messagesRemoved:0,tokensRemoved:0}),[oe,_e]=(0,Ft.useState)(null),Se=()=>{if(pe){ke(!1),_e(null),T();return}ke(!0),T()},Gt=()=>{if(pe||oe!==null){ke(!1),_e(null),T();return}let ui=Ee.filter(Hs=>Hs.type==="tool_call_completed"||Hs.type==="tool_call_requested").slice(-10).at(0)?.timestamp||new Date;_e(ui),T()},Il=Dt=>Dt.type!=="tool_call_completed"&&Dt.type!=="tool_call_requested"?!1:pe?!0:oe!==null&&Dt.timestamp&&Dt.timestamp.getTime()>=oe.getTime(),[gt,_t]=(0,Ft.useState)(!1),[st,xt]=(0,Ft.useState)({status:"Unknown"}),[al,Cn]=(0,Ft.useState)(0),[ul,ve]=(0,Ft.useState)(!1),[Ct,Vl]=(0,Ft.useState)(!1),[jt,dn]=(0,Ft.useState)(!1),[On,tn]=(0,Ft.useState)(!1),[ql,nr]=(0,Ft.useState)(!1),[ea,sr]=(0,Ft.useState)(!1),[As,Vo]=(0,Ft.useState)(!1),[ja,_o]=(0,Ft.useState)(!1),[ln,An]=(0,Ft.useState)("list"),[Kn,AI]=(0,Ft.useState)(void 0),[PI,de]=(0,Ft.useState)(!1),[et,dl]=(0,Ft.useState)(0),[Al,un]=(0,Ft.useState)(hs.cwd()),[eI]=(0,Ft.useState)(()=>new Gue(hs.cwd(),u||[])),[Yn,dI]=(0,Ft.useState)([]),[tI,md]=(0,Ft.useState)(null),[Xr,pc]=(0,Ft.useState)([]),[Od,nm]=(0,Ft.useState)(null),[Gd,ci]=(0,Ft.useState)(s===!1),[fh,Hh]=(0,Ft.useState)(s??!0),[La,Td]=(0,Ft.useState)({}),[di,gu]=(0,Ft.useState)(null),[sn,EG]=(0,Ft.useState)(null),[lo,Im]=Erl(1),[rm,mZ]=(0,Ft.useState)(!1),[GZ,RG]=(0,Ft.useState)(!1),Ln=hs.env.GITHUB_COPILOT_INTEGRATION_ID||"copilot-developer-cli",{models:Je}=yrl(se,l.getCurrentSessionId(),st.authInfo,Ln),{customAgents:ml,selectCustomAgent:Gn}=Arl(t.CUSTOM_AGENTS,se,Ln,st.authInfo||null,YNe(),Al),Na=(0,Ft.useCallback)(Dt=>{let vl=l.getFormattedUsageOutput();gu(Dt?{type:"error",reason:Dt,usage:vl}:{type:"routine",usage:vl}),setTimeout(()=>{hs.exit(0)},300)},[l]);(0,Ft.useEffect)(()=>{(async()=>{let vl={};try{vl=await xr.load()||{}}catch(RI){se.error(`Failed to load configuration: ${RI}`)}vl.banner=vl?.banner??"once",vl.render_markdown=vl?.render_markdown??!0,Td(vl),L&&vl.screen_reader===void 0&&Vl(!0)})()},[L]),(0,Ft.useEffect)(()=>{if(tI===null&&Yn.length>0){La.beep!==!1&&hs.stdout.write(Lb.beep);let Dt=Yn[0];md(Dt),dI(vl=>vl.slice(1))}},[tI,Yn]),(0,Ft.useEffect)(()=>{if(Od===null&&Xr.length>0){La.beep!==!1&&hs.stdout.write(Lb.beep);let Dt=Xr[0];nm(Dt),pc(vl=>vl.slice(1))}},[Od,Xr]);let no=(0,Ft.useRef)(!0),vs=(0,Ft.useRef)(q5e({requestToolPermissionFromUser:Dt=>new Promise(vl=>{dI(RI=>[{request:Dt,resolve:Hs=>{if(Hs.kind==="approve-for-session"&&Hs.approval.kind!==Dt.kind)throw new Error(`Mismatched approval kind: expected ${Dt.kind}, got ${Hs.approval.kind}`);vl(Hs)}},...RI])}),requestPathPermissionFromUser:Dt=>new Promise(vl=>{pc(RI=>[...RI,{paths:Dt.paths,resolve:vl}])}),approveAllToolPermissionRequests:I,rules:r,pathManager:eI})),{displayCwd:zs,gitBranchInfo:mo,selectedModel:wi,setSelectedModel:Do,updateGitStatus:ZI}=Nrl({cliModel:h,sessionManager:l,currentWorkingDirectory:Al,customAgentName:ml.selected?.displayName,stdoutColumns:C.columns,models:Je});(0,Ft.useEffect)(()=>{(async()=>{if(!Je||Je.type!=="success"||!wi)return;let vl=Je.list.find(RI=>RI.id===wi);if(vl?.capabilities?.limits){let RI=vl.capabilities.limits.max_prompt_tokens||vl.capabilities.limits.max_context_window_tokens||2e5;ye(ui=>({...ui,tokenLimit:RI}))}})()},[wi,Je]),(0,Ft.useEffect)(()=>{(async()=>{if(!wi||!Je)return;let vl=l.getChatContextMessages(),RI=l.getSystemContextMessages();if(vl.length>0||RI.length>0){let ui=H$(vl,wi),Hs=H$(RI,wi),pd=ui+Hs;ye(Tc=>({...Tc,totalTokens:pd,postTruncationTokens:pd}))}})()},[wi,Je,l]);let[zo,bd]=(0,Ft.useState)(void 0),Ka=async()=>{try{let Dt=await V2.load()||{mcpServers:{}},vl=new iR(se),RI=new RK(se,JSON.stringify(Dt),vl,G||[]);await RI.startServers(),bd(RI)}catch(Dt){ps(l,{type:"error",text:`Failed to start MCP Servers: ${Dt instanceof Error?Dt.message:String(Dt)}`}),bd(void 0)}};(0,Ft.useEffect)(()=>{let Dt=zo?Object.keys(zo.getConfig().mcpServers):[];if(Dt.length>0){let vl=`Configured MCP servers: ${Dt.join(", ")}`;ps(l,{type:"info",text:vl})}return()=>{zo&&zo.stopServers().catch(vl=>{se.error(`Error shutting down MCP host on cleanup: ${vl instanceof Error?vl.message:String(vl)}`)})}},[zo]),(0,Ft.useEffect)(()=>{Ka()},[]),(0,Ft.useEffect)(()=>{if(!zo||!(zo instanceof RK))return;let Dt=async(RI,ui)=>{try{RI&&ui?await zo.configureGitHubAuth(RI,ui)&&ps(l,{type:"info",text:"Connected to GitHub MCP Server"}):await zo.removeGitHubAuth()&&ps(l,{type:"info",text:"Disconnected from GitHub MCP Server"})}catch(Hs){se.error(`Error configuring GitHub MCP Server: ${Hs}`)}};return e.onAuthChange(Dt),(async()=>{try{let RI=await e.getCurrentAuthInfo();if(RI){let ui=await Rk(RI);await Dt(RI,ui)}}catch(RI){se.error(`Error applying existing auth to MCP host: ${RI}`)}})(),()=>{e.removeAuthCallback(Dt)}},[zo]);let aa=wrl(Dt=>{Y2.updateCurrentCommand(Dt)}),[Yb,am]=Wrl(),ue=(0,Ft.useMemo)(()=>new uue({cacheTimeout:5*6e4,includeDirsInIndex:!1,indexFileStats:!1,maxStatConcurrency:64,onIndexingStart:()=>am.startIndexing(),onIndexingComplete:(Dt,vl)=>am.completeIndexing(Dt,vl),logger:se}),[am]),[ce,xe]=_Il(aa,ue,eI);(0,Ft.useEffect)(()=>{let Dt=!1,vl=null,RI=async()=>{await ZI(),Dt||(vl=setTimeout(()=>void RI(),15e3))};return RI(),()=>{Dt=!0,vl&&clearTimeout(vl)}},[ZI]);let Ke=(0,Ft.useCallback)(Dt=>{l.updateToolCallTimelineEntryResult(Dt);let vl=setTimeout(()=>{ZI()},500);return()=>clearTimeout(vl)},[ZI]);(0,Ft.useEffect)(()=>{Y2.initialize()},[]),(0,Ft.useEffect)(()=>{(async()=>{try{let vl=await e.getCurrentAuthInfo();vl?(xt({status:"LoggedIn",authInfo:vl}),ps(l,{type:"info",text:bYe(vl)})):xt({status:"NotLoggedIn"})}catch{xt({status:"NotLoggedIn"})}})()},[]),(0,Ft.useEffect)(()=>{(async()=>{try{hs.env.COPILOT_ALLOW_ALL==="true"||await Xde.isFolderTrusted(Al)?Cn(1):(Cn(2),ve(!0))}catch{hs.env.COPILOT_ALLOW_ALL==="true"?Cn(1):(Cn(2),ve(!0))}})()},[Al]),(0,Ft.useEffect)(()=>{wnl().then(Dt=>{EG(Dt)}).catch(Dt=>{se.error(`Error checking for updates: ${Dt}`)})},[]),(0,Ft.useEffect)(()=>()=>{no.current=!1},[]),Frl(l,ne,no);let ut=(0,Ft.useMemo)(()=>EYe(t.CUSTOM_AGENTS),[t.CUSTOM_AGENTS]),{slashCommands:St,handleSlashCommand:Gl,matchingSlashCommands:tl}=Rrl({builtInSlashCommands:ut,logger:se,currentWorkingDirectory:Al,setCurrentWorkingDirectory:un,fileSearch:ue,authManager:e,mcpHost:zo,loginStatus:st,setLoginStatus:xt,addEntryToSession:l.addTimelineEntry.bind(l),clearSessionHistory:l.clearHistory.bind(l),getSessionUsageOutput:l.getFormattedUsageOutput.bind(l),pathManager:eI,resetSessionToolApprovals:vs.current.resetSessionToolApprovals,clearTimeline:()=>ne([]),clearHeader:()=>Hh(!1),clearContextWindowMetrics:()=>ye(Dt=>({totalTokens:0,postTruncationTokens:0,tokenLimit:Dt.tokenLimit,truncationStrategy:Dt.truncationStrategy,messagesRemoved:0,tokensRemoved:0})),setThemePreference:R,refreshStatic:T,hasAvailableCustomAgents:ml.available.length>0,slashCommandResultActions:{exit:Na,showCustomAgentPickerDialog:()=>dn(!0),showFeedbackDialog:()=>de(!0),showLoginDialog:()=>tn(!0),showMCPDialog:(Dt,vl)=>{nr(!0),Dt&&An(Dt),vl&&AI(vl)},showModelPickerDialog:()=>sr(!0),showSessionDialog:()=>Vo(!0),showUserSwitcherDialog:()=>_o(!0)}}),{handleTabCompletion:Ql,tabCyclingState:Yl}=Yrl(St,aa,{setSlashCommandPickerIndex:dl}),fl=(0,Ft.useMemo)(()=>{let Dt=tl(aa.text);return Yl||dl(0),Dt},[tl,aa.text,Yl]),Jn=(0,Ft.useMemo)(()=>{let Dt=aa.text,vl=fl[et];if(!vl)return{suggestion:void 0,isHint:!1};let RI=Dt.trimEnd();return RI===vl.name&&vl.args?{suggestion:Dt!==RI?vl.args:` ${vl.args}`,isHint:!0}:{suggestion:(vl.name+(vl.args?" ":"")).substring(Dt.length),isHint:!1}},[aa.text,et,fl]),ur=(0,Ft.useCallback)(Dt=>{gt||EQ||(async()=>{if(l.enableAutoSave(),await Y2.addCommand(Dt),Dt.startsWith("!")){let TI=Dt.substring(1),Om=`$ ${TI}`,Fi=Date.now().toString();ps(l,{type:"tool_call_requested",callId:Fi,name:Q8e,toolTitle:Om,intentionSummary:null,arguments:{command:TI,description:`Execute shell command: ${TI}`},isAlwaysExpanded:!0,showNoContent:!1}),wh=new AbortController;let sN="";try{EQ=!0,RG(!0);let Tm=l3n(TI,{shell:!0,cwd:Al,env:hs.env,stdio:"pipe",signal:wh.signal}),MW=[],pZ=!1,Ep=kh=>{pZ||(pZ=kh.includes(13)),MW.push(kh);let Lh=Buffer.concat(MW).toString("utf-8");sN=pZ?Rel(Lh):Lh,l.updateToolCallTimelineEntryPartialOutput(Fi,sN)};Tm.stderr.on("data",Ep),Tm.stdout.on("data",Ep),Tm.stdin.end();let hZ=await new Promise((kh,Lh)=>{Tm.on("error",Lh),Tm.on("exit",(Rp,AZ)=>{AZ?Lh(new Error(`Process was killed with signal: ${AZ}`)):kh(Rp)})});l.updateToolCallTimelineEntryResult({callId:Fi,resultType:hZ===0?"success":"failure",log:sN,markdown:!1})}catch(Tm){l.updateToolCallTimelineEntryResult({callId:Fi,resultType:"failure",log:`${sN?`${sN}
2328
2328
 
2329
- `:""}Error executing shell command: ${Tm instanceof Error?Tm.message:String(Tm)}`,markdown:!1})}finally{EQ=!1,WO=!1,wh=null,RG(!1)}return}if((await Gl(Dt)).handled)return;let RI=null,ui="You must be logged in to send messages. Please run /login";if(st.status==="Unknown")try{if(RI=await e.getCurrentAuthInfo(),!RI){ps(l,{type:"error",text:ui});return}}catch{ps(l,{type:"error",text:ui});return}else if(st.status!=="LoggedIn"){ps(l,{type:"error",text:ui});return}else RI=st.authInfo;if(al!==1){ps(l,{type:"error",text:"This folder is not trusted. Please confirm folder trust to continue."});return}let Hs=Je?.type==="success"?Je.list:void 0,pd=await f9(h,l,Hs);if(!pd){ps(l,{type:"error",text:"No model available. Check policy enablement under GitHub Settings > Copilot"});return}let{expandedText:Tc,syntheticToolCalls:yp,imageAttachments:YG}=await frl(Dt,ce.storedMentions,Al,se),OI=YG.length>0?{text:Tc,images:YG}:Tc;ps(l,{type:"user",text:Dt}),_t(!0);try{await Lrl(t,OI,yp,vs.current,RI,Ke,Ge,ye,Ye,l,se,eI,Al,pd,o,zo,W,Ae,!1,ml.selected?.prompt)}catch(TI){let Om=TI instanceof Error?TI.message:String(TI);ps(l,{type:"error",text:`Execution failed: ${Om}`})}finally{no.current&&(_t(!1),La.beep!==!1&&hs.stdout.write(Lb.beep),setTimeout(()=>void ZI(),1e3))}})()},[gt,Ke,zo,st,al,ce.storedMentions,ml.selected?.prompt]),Zs=(0,Ft.useCallback)(()=>{ja||(ce.isActive?xe.navigateUp():!Y2.isNavigating()&&fl.length?dl(Math.max(0,et-1)):Y2.navigateUp(aa))},[ja,ce.isActive,xe,fl.length,et,aa]),Tr=(0,Ft.useCallback)(()=>{ja||(ce.isActive?xe.navigateDown():!Y2.isNavigating()&&fl.length?dl(Math.min(fl.length-1,et+1)):Y2.navigateDown(aa))},[ja,ce.isActive,xe,fl.length,et,aa]);dd((Dt,vl)=>{if(vl.ctrl&&Dt==="d"){Na();return}if(vl.ctrl&&Dt==="c"){if((gt||EQ)&&wh&&!wh.signal.aborted){WO=!0,wh.abort(),l.handleAbortedOperation(),Im();return}if(aa.text.length>0){aa.clear(),Y2.resetNavigation(),Im();return}if(!lo){Im();return}Na()}if(vl.escape){(gt||EQ)&&wh&&!wh.signal.aborted&&(WO=!0,wh.abort(),l.handleAbortedOperation());return}if(vl.ctrl&&Dt==="r"){Gt();return}if(vl.ctrl&&Dt==="o"){Se();return}if(!(gt||EQ||ja)){if(vl.tab||vl.return){if(ce.isActive){xe.complete();return}return}!vl.leftArrow&&!vl.rightArrow&&!vl.upArrow&&!vl.downArrow&&Y2.setNavigating(!1)}}),(0,Ft.useEffect)(()=>{mZ(aa.text.startsWith("!"))},[aa.text]);let Mi=hp(()=>{if(Ct)return Gd?Ft.default.createElement($7t,{onConfirm:OI=>{(async()=>{try{OI==="yes"?(await xr.writeKey("screen_reader",!0),ps(l,{type:"info",text:"Enabled screen reader mode for future sessions."})):OI==="never"&&(await xr.writeKey("screen_reader",!1),ps(l,{type:"info",text:"Disabled screen reader mode for future sessions."})),Vl(!1)}catch(TI){ps(l,{type:"error",text:`Failed to update screen reader configuration: ${TI instanceof Error?TI.message:String(TI)}`})}})()}}):Ft.default.createElement(Ft.default.Fragment,null);if(ul)return Gd?Ft.default.createElement(M8t,{folderPath:Al,onConfirm:OI=>{let TI=()=>{Cn(1),ve(!1)};OI==="yes"?TI():OI==="remember"?Xde.addTrustedFolder(Al).then(()=>{TI(),ps(l,{type:"info",text:`Folder ${Al} has been added to trusted folders.`})}).catch(Om=>{ps(l,{type:"error",text:`Failed to add folder to trusted list: ${Om instanceof Error?Om.message:String(Om)}`})}):hs.exit(0)}}):Ft.default.createElement(Ft.default.Fragment,null);if(jt)return Ft.default.createElement(T8t,{customAgents:ml,onSubmission:OI=>{(async()=>{if(OI.kind!=="cancelled"){let TI=await Gn(OI.id);if(TI.kind==="error"){ps(l,{type:"error",text:`Failed to select custom agent: ${TI.message}`});return}ps(l,{type:"info",text:`Selected custom agent: ${OI.id}`})}dn(!1)})()}});if(As)return Ft.default.createElement(e$t,{sessionId:l.getCurrentSessionId(),onClose:()=>{Vo(!1)}});if(On)return Ft.default.createElement(C7t,{onLoginSuccess:(OI,TI)=>{hp(async()=>{await e.loginUser(OI,TI),tn(!1),ps(l,{type:"info",text:`Signed in successfully as ${yce({host:OI,login:TI})}! You can now use Copilot.`}),xt({status:"LoggedIn",authInfo:{type:"user",host:OI,login:TI}})})},onLoginClose:()=>{tn(!1)}});if(ql)return Ft.default.createElement(X7t,{initialMode:ln,initialServerName:Kn,onClose:()=>{nr(!1),An("list"),AI(void 0)},onConfigSaved:()=>{Ka().then(()=>{ps(l,{type:"info",text:"MCP configuration saved successfully! Changes will take effect immediately."})}).catch(OI=>{ps(l,{type:"error",text:`Failed to reload MCP config. Error: ${OI instanceof Error?OI.message:String(OI)}`})})}});if(ea)return Ft.default.createElement(L7t,{models:Je,cliModel:h,sessionManager:l,onClose:()=>{sr(!1)},onModelSelected:OI=>{lhe(),l.setSelectedModel(OI),(async()=>{try{let Om={...await xr.load()||{},model:OI};await xr.write(Om)}catch{}})(),ps(l,{type:"info",text:`Model changed to: ${OI}. The new model will be used for the next conversation.`}),Do(OI)}});if(ja)return Ft.default.createElement(u$t,{authManager:e,initialAuth:st.status==="LoggedIn"?st.authInfo:null,onSelect:OI=>{xt({status:"LoggedIn",authInfo:OI.authInfo}),_o(!1),ps(l,{type:"info",text:`Switched to ${Ece(OI.authInfo)}`}),e.switchToAuth(OI)},onCancel:()=>_o(!1),onError:OI=>{ps(l,{type:"error",text:`Failed to switch user. Error: ${OI}`})}});if(tI){let OI=Yn.length;return Ft.default.createElement(qe,{flexDirection:"column"},OI>0&&Ft.default.createElement(qe,{marginBottom:1},Ft.default.createElement(Fe,{color:y.FG},"Permission request (",OI," remaining)")),Ft.default.createElement(q7t,{request:tI.request,onConfirm:TI=>{tI.resolve(TI),md(null)}}))}if(Od){let OI=Xr.length;return Ft.default.createElement(qe,{flexDirection:"column"},OI>0&&Ft.default.createElement(qe,{marginBottom:1},Ft.default.createElement(Fe,{color:y.FG},"Path confirmation (",OI," remaining)")),Ft.default.createElement(J7t,{paths:Od.paths,onConfirm:TI=>{Od.resolve(TI),nm(null)}}))}let Dt=gt||EQ,vl="Enter @ to mention files or / for commands",RI=Jn.suggestion,ui=Jn.isHint,Hs=Dt||WO,pd=!Y2.isNavigating()&&fl.length>0,Tc=ce.isActive,yp=!Tc&&!pd,YG=hp(()=>WO?"cancelling":GZ?"executing":"thinking");return Ft.default.createElement(Ft.default.Fragment,null,st.status==="NotLoggedIn"&&Ft.default.createElement(Fe,{bold:!0,color:y.COPILOT},"Please use /login to sign in to use Copilot"),Hs&&Ft.default.createElement(qe,{paddingBottom:1},Ft.default.createElement(o$t,{mode:YG,streamingResponseSize:ie})),Ft.default.createElement(qe,{flexDirection:"row",columnGap:1},Ft.default.createElement(qe,{flexGrow:1},Ft.default.createElement(Fe,null,zs),mo&&Ft.default.createElement(Fe,{color:y.MUTED},mo)),Ft.default.createElement(Fe,{color:y.MUTED},wi),ml.selected&&Ft.default.createElement(Fe,{color:y.SELECTED,bold:!0},ml.selected?.displayName),Ft.default.createElement(C8t,{metrics:Ve})),Ft.default.createElement(K8t,{terminalWidth:z.columns-Hrl*2,onSubmit:ur,textCursorLocation:aa,placeholder:vl,inlineSuggestion:RI,inlineSuggestionIsHint:ui,onTabCompletion:Ql,disableEnterSubmit:Dt||WO||ce.isActive,onUpArrow:Zs,onDownArrow:Tr}),pd&&Ft.default.createElement(qe,{paddingBottom:1},Ft.default.createElement(s$t,{options:fl,selectedIndex:et,maxRows:10,showScrollHints:!0})),Tc&&Ft.default.createElement(qe,{paddingBottom:1},Ft.default.createElement(Q8t,{files:ce.suggestions.map(OI=>OI.relativePath),selectedIndex:ce.selectedIndex,maxRows:10,showScrollHints:!0,query:ce.query})),Ft.default.createElement(D8t,{indexingIndicator:Yb}),yp&&Ft.default.createElement(tqt,{quotaSnapshots:P,isRecentTimelineExpanded:oe!==null,isAllTimelineExpanded:pe,showControlCMessage:lo,inShellExecMode:rm}))}),_i=Ft.default.createElement(qe,{key:"header",flexDirection:"column"},Ft.default.createElement(qe,{flexDirection:"column"},Ft.default.createElement(w8t,{animationComplete:()=>ci(!0),completed:Gd,bannerConfig:a?"always":La.banner,loggerOverride:se,version:x.version}),Ft.default.createElement(qe,{flexDirection:"row",paddingX:1},Ft.default.createElement(Fe,{color:y.MUTED},"Version ",x.version),x.buildMetadata&&Ft.default.createElement(Ft.default.Fragment,null,Ft.default.createElement(Fe,{color:y.MUTED}," \xB7 "),Ft.default.createElement(Fe,{color:y.MUTED},"Commit ",x.buildMetadata.gitCommit)))),Ft.default.createElement(qe,{flexDirection:"column",padding:1,gap:1},Ft.default.createElement(Fe,{color:y.MUTED,wrap:"wrap"},"Copilot can write, test and debug code right from your terminal. Describe a task to get started or enter ? for help. Copilot uses AI, check for mistakes."))),Nu=Ee.filter(Dt=>!("isHidden"in Dt&&Dt.isHidden)),Oc=Nu.findIndex(Dt=>Dt.type==="tool_call_requested"||Dt.type==="copilot"&&"isStreaming"in Dt&&Dt.isStreaming);Oc===-1&&(Oc=Nu.length);let rN=Nu.slice(0,Oc),aN=Nu.slice(Oc),Xh=rN.map(Dt=>Ft.default.createElement(YVe,{key:Dt.id,entry:Dt,expand:Il(Dt),renderAsMarkdown:La.render_markdown})),bZ=aN.map(Dt=>Ft.default.createElement(YVe,{key:Dt.id,entry:Dt,expand:Il(Dt),renderAsMarkdown:La.render_markdown})),Wp=Gd&&w;return Ft.default.createElement(LKe,{mode:"interactive"},M?Ft.default.createElement(qe,{flexDirection:"column",paddingX:1},Ft.default.createElement(a$t,{onSessionSelected:Dt=>{(async()=>{try{await l.resumeSpecificSession(Dt),q(!1),ci(!0),Hh(!1)}catch(vl){l.addTimelineEntry({type:"error",text:`Failed to resume session: ${vl instanceof Error?vl.message:String(vl)}`})}})()},onCancel:()=>{(async()=>{try{hs.exit(0)}catch(Dt){l.addTimelineEntry({type:"error",text:`Failed to restart with new session: ${Dt instanceof Error?Dt.message:String(Dt)}`})}})()}})):Ft.default.createElement(qe,{flexDirection:"column"},Wp&&Ft.default.createElement(Ft.default.Fragment,null,Ft.default.createElement(qGe,{key:U,items:[...fh?[_i]:[],...Xh]},Dt=>Dt),bZ),!Wp&&fh&&_i,!di&&Ft.default.createElement(qe,{flexDirection:"column",paddingX:Hrl,paddingTop:fh?0:1},PI?Ft.default.createElement(U8t,{onCancel:()=>de(!1)}):Mi),di&&Ft.default.createElement(qe,{flexDirection:"column",paddingX:1,rowGap:1},di.usage&&Ft.default.createElement(Fe,{dimColor:!0},di.usage),Ft.default.createElement(d$t,{packageName:x.name,checkUpdateResponse:sn}),di.type==="routine"?Ft.default.createElement(Fe,{color:y.ACCENT,bold:!0},"Shutting down..."):Ft.default.createElement(Fe,{color:y.ERROR,bold:!0},`Shutting down: ${di.reason}`)),Ft.default.createElement(Fe,null,U%2?"\u200C":"\u200D")))};function Brl(t,e=!1){let l=Ft.default.createElement(T1e,{logger:new OA,children:Ft.default.createElement(LKe,{mode:"non-interactive",children:Ft.default.createElement(YVe,{entry:t,expand:e})})}),{lastFrame:n}=Zbt(l),I=n();return I?I.trim():""}var xrl=s3n;c();function o3n(t){return`session_${t.sessionId}_${t.startTime.getTime()}`}function Srl(t){let e=/^session_(.+)_(\d+)\.json$/,l=t.match(e);if(!l)return null;let[,n,I]=l;return{sessionId:n,startTime:new Date(parseInt(I,10))}}var RQ=class t{currentSession;onTimelineEntriesChangeCallback=null;debounceSave=null;logger;autoSaveEnabled=!1;usageMetrics={totalPremiumRequests:0,totalApiDurationMs:0,sessionStartTime:Date.now(),codeChanges:{linesAdded:0,linesRemoved:0,filesModified:new Set},modelMetrics:new Map};static async create(e){let l=new t;switch(e.kind){case"new":break;case"resume-last":await l.resumeLastSession();break;case"resume":await l.resumeSpecificSession(e.sessionId);break;case"resume-with-picker":break;default:{let n=e;throw new Error(`unexpected session kind: ${JSON.stringify(n)}`)}}return l}static async hasMultipleSessions(){try{return(await bQ.directoryFiles()).length>1}catch{return!1}}constructor(){this.currentSession=this.generateSession(),this.logger=new OA}setLogger(e){this.logger=e}getLogger(){return this.logger}setOnTimelineEntriesChangeCallback(e){this.onTimelineEntriesChangeCallback=e,this.notifyTimelineEntriesChange()}notifyTimelineEntriesChange(){this.onTimelineEntriesChangeCallback?.([...this.currentSession.timeline])}enableAutoSave(){this.autoSaveEnabled=!0}async forceSave(){await this.saveHistorySession(this.currentSession)}scheduleSave(){this.debounceSave&&clearTimeout(this.debounceSave);let e=this.currentSession;this.debounceSave=setTimeout(()=>{this.autoSaveEnabled&&this.saveHistorySession(e)},100)}getTimelineEntries(){return[...this.currentSession.timeline]}async loadHistorySession(e){try{let l=await bQ.load(e);if(!l)return;let n={...l,startTime:new Date(l.startTime)};this.currentSession=n;for(let I of this.currentSession.timeline)I.timestamp=new Date(I.timestamp);this.currentSession.chatMessages=this.completeOrphanedToolCalls(this.currentSession.chatMessages),this.completeOrphanedStreamingEntries(),this.enableAutoSave(),this.notifyTimelineEntriesChange()}catch(l){throw this.logger.error(`Error loading history session: ${l}`),l}}async saveHistorySession(e){let l=o3n(e);await bQ.write(e,l)}getCurrentSessionId(){return this.currentSession?.sessionId}getCurrentSessionStartTime(){return this.currentSession?.startTime}getSelectedModel(){return this.currentSession?.selectedModel}getCurrentModel(e){return e||this.currentSession?.selectedModel||this.usageMetrics.currentModel||""}setSelectedModel(e){this.currentSession.selectedModel=e,this.scheduleSave()}addTimelineEntry(e){try{let l=Hy();return this.currentSession.timeline.push({id:l,timestamp:new Date,...e}),this.scheduleSave(),this.notifyTimelineEntriesChange(),l}catch(l){return this.logger.error(`Error adding timeline entry: ${l}`),null}}clearHistory(){this.currentSession.chatMessages=[],this.currentSession.timeline=[],this.scheduleSave(),this.notifyTimelineEntriesChange()}addChatMessage(e){this.currentSession.chatMessages.push(e),this.scheduleSave()}getChatContextMessages(){return this.currentSession.chatMessages.filter(e=>e.role!=="system")}getSystemContextMessages(){return this.currentSession.chatMessages.filter(e=>e.role==="system")}handleAbortedOperation(){this.currentSession.chatMessages=this.completeOrphanedToolCalls(this.currentSession.chatMessages),this.completeOrphanedStreamingEntries(),this.scheduleSave()}completeOrphanedToolCalls(e){if(e.length===0)return e;let l=[];for(let r=e.length-1;r>=0;r--){let a=e[r];if(a.role==="assistant"&&"tool_calls"in a&&a.tool_calls&&a.tool_calls.length>0)for(let s of a.tool_calls)l.push(s.id);else break}if(l.length===0)return e;let n="The execution of this tool, or a previous tool was interrupted.";this.logger.info(`Completing ${l.length} orphaned tool calls.`);let I=l.map(r=>({role:"tool",tool_call_id:r,content:n}));for(let r of l)this.updateToolCallTimelineEntryResult({callId:r,resultType:"rejected",log:n});return[...e,...I]}completeOrphanedStreamingEntries(){for(let e of this.currentSession.timeline)e.type==="copilot"&&e.isStreaming&&(e.isStreaming=void 0)}updateToolCallTimelineEntryResult(e){let l=this.currentSession.timeline.findLastIndex(r=>r.type==="tool_call_requested"&&r.callId===e.callId);if(l===-1){this.logger.error(`Pending tool call with ID ${e.callId} not found`);return}let n=this.currentSession.timeline[l];if(n.type==="tool_call_requested"&&n.name==="str_replace_editor"&&e.log){let s=n.arguments?.path;this.updateCodeChangeMetrics(e.log,s)}let I=this.currentSession.timeline[l];this.currentSession.timeline[l]={type:"tool_call_completed",id:I.id,timestamp:I.timestamp,callId:I.callId,name:I.name,toolTitle:I.toolTitle,intentionSummary:I.intentionSummary,arguments:I.arguments,result:{type:e.resultType,log:e.log,markdown:e.markdown},isAlwaysExpanded:I.isAlwaysExpanded,showNoContent:I.showNoContent},this.scheduleSave(),this.notifyTimelineEntriesChange()}updateToolCallTimelineEntryPartialOutput(e,l){let n=this.currentSession.timeline.findLastIndex(r=>r.type==="tool_call_requested"&&r.callId===e);if(n===-1){this.logger.error(`Pending tool call with ID ${e} not found`);return}let I=this.currentSession.timeline[n];this.currentSession.timeline[n]={type:"tool_call_requested",id:I.id,timestamp:I.timestamp,callId:I.callId,name:I.name,toolTitle:I.toolTitle,intentionSummary:I.intentionSummary,arguments:I.arguments,partialOutput:l,isAlwaysExpanded:I.isAlwaysExpanded,showNoContent:I.showNoContent},this.notifyTimelineEntriesChange()}updateCopilotTimelineEntry(e,l,n){let I=this.currentSession.timeline.findLastIndex(a=>a.type==="copilot"&&a.id===e);if(I===-1){this.logger.error(`Copilot entry with ID ${e} not found`);return}let r=this.currentSession.timeline[I];if(r.type!=="copilot"){this.logger.error(`Timeline entry with ID ${e} is not a copilot entry`);return}r.text=l,r.isStreaming=n,this.notifyTimelineEntriesChange()}async resumeSpecificSession(e){let l=await bQ.directoryFiles();if(l.length===0)throw new Error(`Session not found: ${e}`);let n=null,I=[];for(let r of l){let a=Srl(r);if(a&&a.sessionId===e){n=r;break}}if(!n){for(let r of l){let a=Srl(r);a&&a.sessionId.startsWith(e)&&I.push({file:r,parsed:a})}I.length>0&&(I.sort((r,a)=>a.parsed.startTime.getTime()-r.parsed.startTime.getTime()),n=I[0].file)}if(!n)throw new Error(`Session not found: ${e}`);try{await this.loadHistorySession(n)}catch(r){throw new Error(`Failed to load session ${e}: ${r}`)}}async resumeLastSession(){let e=await bQ.directoryFiles();if(e.length===0)throw new Error("No sessions found");let l=e[0];try{await this.loadHistorySession(l)}catch(n){throw new Error(`Failed to resume last session: ${n}`)}}generateSession(){return this.resetUsageMetrics(),{sessionId:this.generateSessionId(),startTime:new Date,chatMessages:[],timeline:[]}}generateSessionId(){return Hy()}getUsageMetrics(){return this.usageMetrics}resetUsageMetrics(){this.usageMetrics={totalPremiumRequests:0,totalApiDurationMs:0,sessionStartTime:Date.now(),codeChanges:{linesAdded:0,linesRemoved:0,filesModified:new Set},modelMetrics:new Map}}getModelRequestMultiplier(e){return{"claude-sonnet-4":1,"gpt-5":1,"claude-sonnet-4.5":1}[e]??1}trackUserMessage(e){let l=e||"",I=1*this.getModelRequestMultiplier(l);this.usageMetrics.totalPremiumRequests+=I,this.usageMetrics.modelMetrics.has(l)||this.usageMetrics.modelMetrics.set(l,{requests:{count:0,cost:0},usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0}});let r=this.usageMetrics.modelMetrics.get(l);r.requests.count+=1,r.requests.cost+=I,this.usageMetrics.currentModel=l}updateModelUsageMetrics(e,l,n){let I=e||"";if(this.usageMetrics.totalApiDurationMs+=l,n){this.usageMetrics.modelMetrics.has(I)||this.usageMetrics.modelMetrics.set(I,{requests:{count:0,cost:0},usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0}});let r=this.usageMetrics.modelMetrics.get(I);if(r.usage.inputTokens+=n.prompt_tokens||0,r.usage.outputTokens+=n.completion_tokens||0,n.prompt_tokens_details?.cached_tokens){r.usage.cacheReadTokens+=n.prompt_tokens_details.cached_tokens;let a=(n.prompt_tokens||0)-n.prompt_tokens_details.cached_tokens;r.usage.cacheWriteTokens+=Math.max(0,a)}}}updateCodeChangeMetrics(e,l){if(!e||!e.includes("diff --git"))return;let n=e.split(`
2329
+ `:""}Error executing shell command: ${Tm instanceof Error?Tm.message:String(Tm)}`,markdown:!1})}finally{EQ=!1,WO=!1,wh=null,RG(!1)}return}if((await Gl(Dt)).handled)return;let RI=null,ui="You must be logged in to send messages. Please run /login";if(st.status==="Unknown")try{if(RI=await e.getCurrentAuthInfo(),!RI){ps(l,{type:"error",text:ui});return}}catch{ps(l,{type:"error",text:ui});return}else if(st.status!=="LoggedIn"){ps(l,{type:"error",text:ui});return}else RI=st.authInfo;if(al!==1){ps(l,{type:"error",text:"This folder is not trusted. Please confirm folder trust to continue."});return}let Hs=Je?.type==="success"?Je.list:void 0,pd=await f9(h,l,Hs);if(!pd){ps(l,{type:"error",text:"No model available. Check policy enablement under GitHub Settings > Copilot"});return}let{expandedText:Tc,syntheticToolCalls:yp,imageAttachments:YG}=await frl(Dt,ce.storedMentions,Al,se),OI=YG.length>0?{text:Tc,images:YG}:Tc;ps(l,{type:"user",text:Dt}),_t(!0);try{await Lrl(t,OI,yp,vs.current,RI,Ke,Ge,ye,Ye,l,se,eI,Al,pd,o,zo,W,Ae,!1,ml.selected?.prompt)}catch(TI){let Om=TI instanceof Error?TI.message:String(TI);ps(l,{type:"error",text:`Execution failed: ${Om}`})}finally{no.current&&(_t(!1),La.beep!==!1&&hs.stdout.write(Lb.beep),setTimeout(()=>void ZI(),1e3))}})()},[gt,Ke,zo,st,al,ce.storedMentions,ml.selected?.prompt]),Zs=(0,Ft.useCallback)(()=>{ja||(ce.isActive?xe.navigateUp():!Y2.isNavigating()&&fl.length?dl(Math.max(0,et-1)):Y2.navigateUp(aa))},[ja,ce.isActive,xe,fl.length,et,aa]),Tr=(0,Ft.useCallback)(()=>{ja||(ce.isActive?xe.navigateDown():!Y2.isNavigating()&&fl.length?dl(Math.min(fl.length-1,et+1)):Y2.navigateDown(aa))},[ja,ce.isActive,xe,fl.length,et,aa]);dd((Dt,vl)=>{if(vl.ctrl&&Dt==="d"){Na();return}if(vl.ctrl&&Dt==="c"){if((gt||EQ)&&wh&&!wh.signal.aborted){WO=!0,wh.abort(),l.handleAbortedOperation(),Im();return}if(aa.text.length>0){aa.clear(),Y2.resetNavigation(),Im();return}if(!lo){Im();return}Na()}if(vl.escape){(gt||EQ)&&wh&&!wh.signal.aborted&&(WO=!0,wh.abort(),l.handleAbortedOperation());return}if(vl.ctrl&&Dt==="r"){Gt();return}if(vl.ctrl&&Dt==="o"){Se();return}if(!(gt||EQ||ja)){if(vl.tab||vl.return){if(ce.isActive){xe.complete();return}return}!vl.leftArrow&&!vl.rightArrow&&!vl.upArrow&&!vl.downArrow&&Y2.setNavigating(!1)}}),(0,Ft.useEffect)(()=>{mZ(aa.text.startsWith("!"))},[aa.text]);let Mi=hp(()=>{if(Ct)return Gd?Ft.default.createElement($7t,{onConfirm:OI=>{(async()=>{try{OI==="yes"?(await xr.writeKey("screen_reader",!0),ps(l,{type:"info",text:"Enabled screen reader mode for future sessions."})):OI==="never"&&(await xr.writeKey("screen_reader",!1),ps(l,{type:"info",text:"Disabled screen reader mode for future sessions."})),Vl(!1)}catch(TI){ps(l,{type:"error",text:`Failed to update screen reader configuration: ${TI instanceof Error?TI.message:String(TI)}`})}})()}}):Ft.default.createElement(Ft.default.Fragment,null);if(ul)return Gd?Ft.default.createElement(M8t,{folderPath:Al,onConfirm:OI=>{let TI=()=>{Cn(1),ve(!1)};OI==="yes"?TI():OI==="remember"?Xde.addTrustedFolder(Al).then(()=>{TI(),ps(l,{type:"info",text:`Folder ${Al} has been added to trusted folders.`})}).catch(Om=>{ps(l,{type:"error",text:`Failed to add folder to trusted list: ${Om instanceof Error?Om.message:String(Om)}`})}):hs.exit(0)}}):Ft.default.createElement(Ft.default.Fragment,null);if(jt)return Ft.default.createElement(T8t,{customAgents:ml,onSubmission:OI=>{(async()=>{if(OI.kind!=="cancelled"){let TI=await Gn(OI.id);if(TI.kind==="error"){ps(l,{type:"error",text:`Failed to select custom agent: ${TI.message}`});return}ps(l,{type:"info",text:`Selected custom agent: ${OI.id}`})}dn(!1)})()}});if(As)return Ft.default.createElement(e$t,{sessionId:l.getCurrentSessionId(),onClose:()=>{Vo(!1)}});if(On)return Ft.default.createElement(C7t,{onLoginSuccess:(OI,TI)=>{hp(async()=>{await e.loginUser(OI,TI),tn(!1),ps(l,{type:"info",text:`Signed in successfully as ${yce({host:OI,login:TI})}! You can now use Copilot.`}),xt({status:"LoggedIn",authInfo:{type:"user",host:OI,login:TI}})})},onLoginClose:()=>{tn(!1)}});if(ql)return Ft.default.createElement(X7t,{initialMode:ln,initialServerName:Kn,onClose:()=>{nr(!1),An("list"),AI(void 0)},onConfigSaved:()=>{Ka().then(()=>{ps(l,{type:"info",text:"MCP configuration saved successfully! Changes will take effect immediately."})}).catch(OI=>{ps(l,{type:"error",text:`Failed to reload MCP config. Error: ${OI instanceof Error?OI.message:String(OI)}`})})}});if(ea)return Ft.default.createElement(L7t,{models:Je,cliModel:h,sessionManager:l,onClose:()=>{sr(!1)},onModelSelected:OI=>{lhe(),l.setSelectedModel(OI),(async()=>{try{let Om={...await xr.load()||{},model:OI};await xr.write(Om)}catch{}})(),ps(l,{type:"info",text:`Model changed to: ${OI}. The new model will be used for the next conversation.`}),Do(OI)}});if(ja)return Ft.default.createElement(u$t,{authManager:e,initialAuth:st.status==="LoggedIn"?st.authInfo:null,onSelect:OI=>{xt({status:"LoggedIn",authInfo:OI.authInfo}),_o(!1),ps(l,{type:"info",text:`Switched to ${Ece(OI.authInfo)}`}),e.switchToAuth(OI)},onCancel:()=>_o(!1),onError:OI=>{ps(l,{type:"error",text:`Failed to switch user. Error: ${OI}`})}});if(tI){let OI=Yn.length;return Ft.default.createElement(qe,{flexDirection:"column"},OI>0&&Ft.default.createElement(qe,{marginBottom:1},Ft.default.createElement(Fe,{color:y.FG},"Permission request (",OI," remaining)")),Ft.default.createElement(q7t,{request:tI.request,onConfirm:TI=>{tI.resolve(TI),md(null)}}))}if(Od){let OI=Xr.length;return Ft.default.createElement(qe,{flexDirection:"column"},OI>0&&Ft.default.createElement(qe,{marginBottom:1},Ft.default.createElement(Fe,{color:y.FG},"Path confirmation (",OI," remaining)")),Ft.default.createElement(J7t,{paths:Od.paths,onConfirm:TI=>{Od.resolve(TI),nm(null)}}))}let Dt=gt||EQ,vl="Enter @ to mention files or / for commands",RI=Jn.suggestion,ui=Jn.isHint,Hs=Dt||WO,pd=!Y2.isNavigating()&&fl.length>0,Tc=ce.isActive,yp=!Tc&&!pd,YG=hp(()=>WO?"cancelling":GZ?"executing":"thinking");return Ft.default.createElement(Ft.default.Fragment,null,st.status==="NotLoggedIn"&&Ft.default.createElement(Fe,{bold:!0,color:y.COPILOT},"Please use /login to sign in to use Copilot"),Hs&&Ft.default.createElement(qe,{paddingBottom:1},Ft.default.createElement(o$t,{mode:YG,streamingResponseSize:ie})),Ft.default.createElement(qe,{flexDirection:"row",columnGap:1},Ft.default.createElement(qe,{flexGrow:1},Ft.default.createElement(Fe,null,zs),mo&&Ft.default.createElement(Fe,{color:y.MUTED},mo)),Ft.default.createElement(Fe,{color:y.MUTED},wi),ml.selected&&Ft.default.createElement(Fe,{color:y.SELECTED,bold:!0},ml.selected?.displayName),Ft.default.createElement(C8t,{metrics:Ve})),Ft.default.createElement(K8t,{terminalWidth:z.columns-Hrl*2,onSubmit:ur,textCursorLocation:aa,placeholder:vl,inlineSuggestion:RI,inlineSuggestionIsHint:ui,onTabCompletion:Ql,disableEnterSubmit:Dt||WO||ce.isActive,onUpArrow:Zs,onDownArrow:Tr}),pd&&Ft.default.createElement(qe,{paddingBottom:1},Ft.default.createElement(s$t,{options:fl,selectedIndex:et,maxRows:10,showScrollHints:!0})),Tc&&Ft.default.createElement(qe,{paddingBottom:1},Ft.default.createElement(Q8t,{files:ce.suggestions.map(OI=>OI.relativePath),selectedIndex:ce.selectedIndex,maxRows:10,showScrollHints:!0,query:ce.query})),Ft.default.createElement(D8t,{indexingIndicator:Yb}),yp&&Ft.default.createElement(tqt,{quotaSnapshots:P,isRecentTimelineExpanded:oe!==null,isAllTimelineExpanded:pe,showControlCMessage:lo,inShellExecMode:rm}))}),_i=Ft.default.createElement(qe,{key:"header",flexDirection:"column"},Ft.default.createElement(qe,{flexDirection:"column"},Ft.default.createElement(w8t,{animationComplete:()=>ci(!0),completed:Gd,bannerConfig:a?"always":La.banner,loggerOverride:se,version:x.version}),Ft.default.createElement(qe,{flexDirection:"row",paddingX:1},Ft.default.createElement(Fe,{color:y.MUTED},"Version ",x.version),x.buildMetadata&&Ft.default.createElement(Ft.default.Fragment,null,Ft.default.createElement(Fe,{color:y.MUTED}," \xB7 "),Ft.default.createElement(Fe,{color:y.MUTED},"Commit ",x.buildMetadata.gitCommit)))),Ft.default.createElement(qe,{flexDirection:"column",padding:1,gap:1},Ft.default.createElement(Fe,{color:y.MUTED,wrap:"wrap"},"Copilot can write, test and debug code right from your terminal. Describe a task to get started or enter ? for help. Copilot uses AI, check for mistakes."))),Nu=Ee.filter(Dt=>!("isHidden"in Dt&&Dt.isHidden)),Oc=Nu.findIndex(Dt=>Dt.type==="tool_call_requested"||Dt.type==="copilot"&&"isStreaming"in Dt&&Dt.isStreaming);Oc===-1&&(Oc=Nu.length);let rN=Nu.slice(0,Oc),aN=Nu.slice(Oc),Xh=rN.map(Dt=>Ft.default.createElement(YVe,{key:Dt.id,entry:Dt,expand:Il(Dt),renderAsMarkdown:La.render_markdown})),bZ=aN.map(Dt=>Ft.default.createElement(YVe,{key:Dt.id,entry:Dt,expand:Il(Dt),renderAsMarkdown:La.render_markdown})),Wp=Gd&&w;return Ft.default.createElement(LKe,{mode:"interactive"},M?Ft.default.createElement(qe,{flexDirection:"column",paddingX:1},Ft.default.createElement(a$t,{onSessionSelected:Dt=>{(async()=>{try{await l.resumeSpecificSession(Dt),q(!1),ci(!0),Hh(!1)}catch(vl){l.addTimelineEntry({type:"error",text:`Failed to resume session: ${vl instanceof Error?vl.message:String(vl)}`})}})()},onCancel:()=>{(async()=>{try{hs.exit(0)}catch(Dt){l.addTimelineEntry({type:"error",text:`Failed to restart with new session: ${Dt instanceof Error?Dt.message:String(Dt)}`})}})()}})):Ft.default.createElement(qe,{flexDirection:"column"},Wp&&Ft.default.createElement(Ft.default.Fragment,null,Ft.default.createElement(qGe,{key:U,items:[...fh?[_i]:[],...Xh]},Dt=>Dt),bZ),!Wp&&fh&&_i,!di&&Ft.default.createElement(qe,{flexDirection:"column",paddingX:Hrl,paddingTop:fh?0:1},PI?Ft.default.createElement(U8t,{onCancel:()=>de(!1)}):Mi),di&&Ft.default.createElement(qe,{flexDirection:"column",paddingX:1,rowGap:1},di.usage&&Ft.default.createElement(Fe,{dimColor:!0},di.usage),Ft.default.createElement(d$t,{packageName:x.name,checkUpdateResponse:sn}),di.type==="routine"?Ft.default.createElement(Fe,{color:y.ACCENT,bold:!0},"Shutting down..."):Ft.default.createElement(Fe,{color:y.ERROR,bold:!0},`Shutting down: ${di.reason}`)),Ft.default.createElement(Fe,null,U%2?"\u200C":"\u200D")))};function Brl(t,e=!1){let l=Ft.default.createElement(T1e,{logger:new OA,children:Ft.default.createElement(LKe,{mode:"non-interactive",children:Ft.default.createElement(YVe,{entry:t,expand:e})})}),{lastFrame:n}=Zbt(l),I=n();return I?I.trim():""}var xrl=s3n;c();function o3n(t){return`session_${t.sessionId}_${t.startTime.getTime()}`}function Srl(t){let e=/^session_(.+)_(\d+)\.json$/,l=t.match(e);if(!l)return null;let[,n,I]=l;return{sessionId:n,startTime:new Date(parseInt(I,10))}}var RQ=class t{currentSession;onTimelineEntriesChangeCallback=null;debounceSave=null;logger;autoSaveEnabled=!1;usageMetrics={totalPremiumRequests:0,totalApiDurationMs:0,sessionStartTime:Date.now(),codeChanges:{linesAdded:0,linesRemoved:0,filesModified:new Set},modelMetrics:new Map};static async create(e){let l=new t;switch(e.kind){case"new":break;case"resume-last":await l.resumeLastSession();break;case"resume":await l.resumeSpecificSession(e.sessionId);break;case"resume-with-picker":break;default:{let n=e;throw new Error(`unexpected session kind: ${JSON.stringify(n)}`)}}return l}static async hasMultipleSessions(){try{return(await bQ.directoryFiles()).length>1}catch{return!1}}constructor(){this.currentSession=this.generateSession(),this.logger=new OA}setLogger(e){this.logger=e}getLogger(){return this.logger}setOnTimelineEntriesChangeCallback(e){this.onTimelineEntriesChangeCallback=e,this.notifyTimelineEntriesChange()}notifyTimelineEntriesChange(){this.onTimelineEntriesChangeCallback?.([...this.currentSession.timeline])}enableAutoSave(){this.autoSaveEnabled=!0}async forceSave(){await this.saveHistorySession(this.currentSession)}scheduleSave(){this.debounceSave&&clearTimeout(this.debounceSave);let e=this.currentSession;this.debounceSave=setTimeout(()=>{this.autoSaveEnabled&&this.saveHistorySession(e)},100)}getTimelineEntries(){return[...this.currentSession.timeline]}async loadHistorySession(e){try{let l=await bQ.load(e);if(!l)return;let n={...l,startTime:new Date(l.startTime)};this.currentSession=n;for(let I of this.currentSession.timeline)I.timestamp=new Date(I.timestamp);this.currentSession.chatMessages=this.completeOrphanedToolCalls(this.currentSession.chatMessages),this.completeOrphanedStreamingEntries(),this.enableAutoSave(),this.notifyTimelineEntriesChange()}catch(l){throw this.logger.error(`Error loading history session: ${l}`),l}}async saveHistorySession(e){let l=o3n(e);await bQ.write(e,l)}getCurrentSessionId(){return this.currentSession?.sessionId}getCurrentSessionStartTime(){return this.currentSession?.startTime}getSelectedModel(){return this.currentSession?.selectedModel}getCurrentModel(e){return e||this.currentSession?.selectedModel||this.usageMetrics.currentModel||""}setSelectedModel(e){this.currentSession.selectedModel=e,this.scheduleSave()}addTimelineEntry(e){try{let l=Hy();return this.currentSession.timeline.push({id:l,timestamp:new Date,...e}),this.scheduleSave(),this.notifyTimelineEntriesChange(),l}catch(l){return this.logger.error(`Error adding timeline entry: ${l}`),null}}clearHistory(){this.currentSession.chatMessages=[],this.currentSession.timeline=[],this.scheduleSave(),this.notifyTimelineEntriesChange()}addChatMessage(e){this.currentSession.chatMessages.push(e),this.scheduleSave()}getChatContextMessages(){return this.currentSession.chatMessages.filter(e=>e.role!=="system")}getSystemContextMessages(){return this.currentSession.chatMessages.filter(e=>e.role==="system")}handleAbortedOperation(){this.currentSession.chatMessages=this.completeOrphanedToolCalls(this.currentSession.chatMessages),this.completeOrphanedStreamingEntries(),this.scheduleSave()}completeOrphanedToolCalls(e){if(e.length===0)return e;let l=[],n=new Set,I=!1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(o.role==="assistant"&&(I=!0),o.role==="assistant"&&"tool_calls"in o&&o.tool_calls&&o.tool_calls.length>0)for(let d of o.tool_calls)n.has(d.id)||l.push(d.id);else{if(I)break;o.role==="tool"&&o.tool_call_id&&n.add(o.tool_call_id)}}if(l.length===0)return e;let r="The execution of this tool, or a previous tool was interrupted.";this.logger.info(`Completing ${l.length} orphaned tool calls.`);let a=l.map(s=>({role:"tool",tool_call_id:s,content:r}));for(let s of l)this.updateToolCallTimelineEntryResult({callId:s,resultType:"rejected",log:r});return[...e,...a]}completeOrphanedStreamingEntries(){for(let e of this.currentSession.timeline)e.type==="copilot"&&e.isStreaming&&(e.isStreaming=void 0)}updateToolCallTimelineEntryResult(e){let l=this.currentSession.timeline.findLastIndex(r=>r.type==="tool_call_requested"&&r.callId===e.callId);if(l===-1){this.logger.error(`Pending tool call with ID ${e.callId} not found`);return}let n=this.currentSession.timeline[l];if(n.type==="tool_call_requested"&&n.name==="str_replace_editor"&&e.log){let s=n.arguments?.path;this.updateCodeChangeMetrics(e.log,s)}let I=this.currentSession.timeline[l];this.currentSession.timeline[l]={type:"tool_call_completed",id:I.id,timestamp:I.timestamp,callId:I.callId,name:I.name,toolTitle:I.toolTitle,intentionSummary:I.intentionSummary,arguments:I.arguments,result:{type:e.resultType,log:e.log,markdown:e.markdown},isAlwaysExpanded:I.isAlwaysExpanded,showNoContent:I.showNoContent},this.scheduleSave(),this.notifyTimelineEntriesChange()}updateToolCallTimelineEntryPartialOutput(e,l){let n=this.currentSession.timeline.findLastIndex(r=>r.type==="tool_call_requested"&&r.callId===e);if(n===-1){this.logger.error(`Pending tool call with ID ${e} not found`);return}let I=this.currentSession.timeline[n];this.currentSession.timeline[n]={type:"tool_call_requested",id:I.id,timestamp:I.timestamp,callId:I.callId,name:I.name,toolTitle:I.toolTitle,intentionSummary:I.intentionSummary,arguments:I.arguments,partialOutput:l,isAlwaysExpanded:I.isAlwaysExpanded,showNoContent:I.showNoContent},this.notifyTimelineEntriesChange()}updateCopilotTimelineEntry(e,l,n){let I=this.currentSession.timeline.findLastIndex(a=>a.type==="copilot"&&a.id===e);if(I===-1){this.logger.error(`Copilot entry with ID ${e} not found`);return}let r=this.currentSession.timeline[I];if(r.type!=="copilot"){this.logger.error(`Timeline entry with ID ${e} is not a copilot entry`);return}r.text=l,r.isStreaming=n,this.notifyTimelineEntriesChange()}async resumeSpecificSession(e){let l=await bQ.directoryFiles();if(l.length===0)throw new Error(`Session not found: ${e}`);let n=null,I=[];for(let r of l){let a=Srl(r);if(a&&a.sessionId===e){n=r;break}}if(!n){for(let r of l){let a=Srl(r);a&&a.sessionId.startsWith(e)&&I.push({file:r,parsed:a})}I.length>0&&(I.sort((r,a)=>a.parsed.startTime.getTime()-r.parsed.startTime.getTime()),n=I[0].file)}if(!n)throw new Error(`Session not found: ${e}`);try{await this.loadHistorySession(n)}catch(r){throw new Error(`Failed to load session ${e}: ${r}`)}}async resumeLastSession(){let e=await bQ.directoryFiles();if(e.length===0)throw new Error("No sessions found");let l=e[0];try{await this.loadHistorySession(l)}catch(n){throw new Error(`Failed to resume last session: ${n}`)}}generateSession(){return this.resetUsageMetrics(),{sessionId:this.generateSessionId(),startTime:new Date,chatMessages:[],timeline:[]}}generateSessionId(){return Hy()}getUsageMetrics(){return this.usageMetrics}resetUsageMetrics(){this.usageMetrics={totalPremiumRequests:0,totalApiDurationMs:0,sessionStartTime:Date.now(),codeChanges:{linesAdded:0,linesRemoved:0,filesModified:new Set},modelMetrics:new Map}}getModelRequestMultiplier(e){return{"claude-sonnet-4":1,"gpt-5":1,"claude-sonnet-4.5":1}[e]??1}trackUserMessage(e){let l=e||"",I=1*this.getModelRequestMultiplier(l);this.usageMetrics.totalPremiumRequests+=I,this.usageMetrics.modelMetrics.has(l)||this.usageMetrics.modelMetrics.set(l,{requests:{count:0,cost:0},usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0}});let r=this.usageMetrics.modelMetrics.get(l);r.requests.count+=1,r.requests.cost+=I,this.usageMetrics.currentModel=l}updateModelUsageMetrics(e,l,n){let I=e||"";if(this.usageMetrics.totalApiDurationMs+=l,n){this.usageMetrics.modelMetrics.has(I)||this.usageMetrics.modelMetrics.set(I,{requests:{count:0,cost:0},usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0}});let r=this.usageMetrics.modelMetrics.get(I);if(r.usage.inputTokens+=n.prompt_tokens||0,r.usage.outputTokens+=n.completion_tokens||0,n.prompt_tokens_details?.cached_tokens){r.usage.cacheReadTokens+=n.prompt_tokens_details.cached_tokens;let a=(n.prompt_tokens||0)-n.prompt_tokens_details.cached_tokens;r.usage.cacheWriteTokens+=Math.max(0,a)}}}updateCodeChangeMetrics(e,l){if(!e||!e.includes("diff --git"))return;let n=e.split(`
2330
2330
  `),I=0,r=0;for(let a of n)a.startsWith("+")&&!a.startsWith("+++")?I++:a.startsWith("-")&&!a.startsWith("---")&&r++;this.usageMetrics.codeChanges.linesAdded+=I,this.usageMetrics.codeChanges.linesRemoved+=r,l&&this.usageMetrics.codeChanges.filesModified.add(l)}formatTokenCount(e){return e===0?"0":e<1e3?e.toString():e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}m`}formatDuration(e){let l=Math.floor(e/1e3),n=Math.floor(l/60),I=Math.floor(n/60);if(I>0){let r=n%60,a=e%6e4/1e3;return`${I}h ${r}m ${a.toFixed(1)}s`}else if(n>0){let r=e%6e4/1e3;return`${n}m ${r.toFixed(1)}s`}else return`${(e/1e3).toFixed(1)}s`}getFormattedUsageOutput(){let e=this.usageMetrics,l=this.formatDuration(Date.now()-e.sessionStartTime),n=this.formatDuration(e.totalApiDurationMs),I=Math.round(e.totalPremiumRequests),a=[`Total usage est: ${I} ${I===1?"Premium request":"Premium requests"}`,`Total duration (API): ${n}`,`Total duration (wall): ${l}`,`Total code changes: ${e.codeChanges.linesAdded} lines added, ${e.codeChanges.linesRemoved} lines removed`];if(e.modelMetrics.size>0){a.push("Usage by model:");for(let[s,o]of e.modelMetrics){let{requests:d,usage:u}=o,G=this.formatTokenCount(u.inputTokens),p=this.formatTokenCount(u.outputTokens),h=this.formatTokenCount(u.cacheReadTokens),W=this.formatTokenCount(u.cacheWriteTokens),y=Math.round(d.cost),R=y===1?"Premium request":"Premium requests",C=(s||"(unknown)").padEnd(20);a.push(` ${C} ${G} input, ${p} output, ${h} cache read, ${W} cache write (Est. ${y} ${R})`)}}return a.join(`
2331
2331
  `)}};c();var Yq=ot(VGl(),1);function QGl(){(0,Yq.install)(),(0,Yq.setGlobalDispatcher)(new Yq.EnvHttpProxyAgent({allowH2:!0}))}c();var OFe=class{constructor(e){this.logger=e;this.listenToErrors()}errorHandlers=[];formatError(e,l){if(l instanceof Error)return`${e}: ${l.message}
2332
2332
  ${l.stack}`;if(typeof l=="object"&&l!==null)try{return`${e}: ${JSON.stringify(l)}`}catch{return`${e}: [object with circular reference]`}else return`${e}: ${String(l)}`}addErrorHandler(e){this.errorHandlers.push(e)}listenToErrors(){process.on("uncaughtException",e=>{this.handleError("Uncaught Exception",e)}),process.on("unhandledRejection",e=>{this.handleError("Unhandled Rejection",e)})}handleError(e,l){this.logger.error(this.formatError(e,l)),this.errorHandlers.length===0&&(process.stderr.write(this.formatError(e,l)+`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@github/copilot",
3
3
  "description": "GitHub Copilot CLI brings the power of Copilot coding agent directly to your terminal.",
4
- "version": "0.0.340-6",
4
+ "version": "0.0.340-7",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -33,7 +33,7 @@
33
33
  "sdk/**/*"
34
34
  ],
35
35
  "buildMetadata": {
36
- "gitCommit": "0a831f1"
36
+ "gitCommit": "5afde61"
37
37
  },
38
38
  "dependencies": {
39
39
  "node-pty": "npm:@devm33/node-pty@^1.0.8",