eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
11 lines • 53.2 kB
JavaScript
import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{interruptedError}from"./errors.js";import{FileContentCache}from"./file-content-cache.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{initialModelEditorState,transitionModelEditor}from"./model-editor.js";import{promptPlaceholder}from"./prompt-placeholder.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{enterBadge,renderAcknowledgeQuestion,renderFlowPanel,renderModelEditorQuestion,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{TurnClock}from"./turn-clock.js";import{allTodoItemsSettled,readTodoToolItems,renderFinishedTodoRows,renderTodoPanelRows}from"./todo-panel.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{inspectError}from"#internal/logging.js";import{eveVersionTag}from"#cli/banner.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{LiveRegion}from"#cli/ui/live-region.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";import{readGatewayServiceTier}from"#shared/gateway-service-tier.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e,t){return e?`Interrupted`:t?`Ready`:`Done`}const STATUS={processing:`Working…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=[];#m=new Map;#h=new Set;#g=[];#_=new Set;#v=new Map;#y=0;#b=new Map;#x=new FileContentCache;#S=new Set;#C;#w=!1;#T;#E=[];#D;#O=0;#k;#A;#j=``;#M=0;#N=new PromptHistory;#P=!1;#F;#I=!1;#L=Date.now();#R=!1;#z=new TurnClock;#B=EMPTY_LINE;#V=!1;#H={kind:`idle`};#U;#W=STATUS.processing;#G;#K=`eve`;#q=!1;#J=!1;#Y=!1;#X=!1;#Z=!0;#Q=0;#$=Date.now();#ee;#te;#ne;#re=!1;#ie;#ae=``;#oe=new StringDecoder(`utf8`);#se;#ce;#le;#ue=!1;#de=!1;#fe;#pe;#me;#he;#ge;#_e;#ve;#ye=``;#be=``;#xe;#Se;#Ce=0;#we;#Te;#Ee;#De;#Oe;#ke;#Ae;#je;setupFlow={begin:(e,t)=>this.#Le(e,t),end:e=>this.#Re(e?.preserveDiagnostics??!0),readSelect:e=>this.#ze(e),readEditableSelect:e=>this.#Ve(e),readProviderPicker:e=>this.#He(e),readModelEditor:e=>this.#Ue(e),readText:e=>this.#We(e),readAcknowledge:e=>this.#Ge(e),readChoice:e=>this.#Be(e),setStatus:e=>this.#$e(e),renderLine:(e,t)=>this.#et(e,t),renderOutput:e=>this.#tt(e),waitForInterrupt:()=>this.#Xe()};constructor(t){this.#e=t?.input??process.stdin,this.#t=t?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:t?.color??!0,unicode:t?.unicode??detectUnicode()}),this.#i=t?.tools??`auto-collapsed`,this.#a=t?.reasoning??`auto-collapsed`,this.#o=t?.subagents??`auto-collapsed`,this.#s=t?.connectionAuth??`full`,this.#c=t?.assistantResponseStats??`tokensPerSecond`,this.#me=t?.contextSize,this.#l=t?.captureForeignOutput??this.#t===process.stdout,this.#u=t?.diagnostics,this.#f=t?.logs??`none`,this.#d=t?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#K=e.name,this.#C=e,this.#nt();let t=this.#Ut().join(`
`);if(this.#w){t!==this.#T&&(this.#T=t,this.#_t({kind:`agent-header`,body:t,live:!1})),this.#Rt();return}this.#w=!0,this.#T=t,this.#n.flush(this.#Ut(),[])}async readPrompt(e){this.#nt(e),this.#gt(),this.#yt(),this.#P=!0,this.#I=!0,this.#H={kind:`idle`},this.#W=``;let r=lineOf(stripPromptControlCharacters(e?.initialDraft??this.#B.text));return this.#B=EMPTY_LINE,this.#N.begin(r.text),this.#Me(r),this.#F=typeaheadFor(this.#d,r.text),this.#dt(),this.#Rt(),await new Promise((e,i)=>{this.#U=i;let apply=e=>{r=e,this.#pt(),this.#Me(r),this.#F=typeaheadFor(this.#d,e.text,this.#F),this.#Rt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#F=void 0,this.#ft(),this.#rt(),i(interruptedError())},suggestions=()=>this.#F!==void 0&&isTypeaheadOpen(this.#F)?this.#F:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ie=i=>{let a=applyLineEditorKey(r,i,{multiline:!0});if(a!==void 0){apply(a);return}switch(i.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#F=moveTypeaheadSelection(e,-1),this.#Rt();break}let t=movePromptLine(r,`up`);t===void 0?recall(this.#N.previous(r.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#F=moveTypeaheadSelection(e,1),this.#Rt();break}let t=movePromptLine(r,`down`);t===void 0?recall(this.#N.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#F=dismissTypeahead(e),this.#Rt());break}case`enter`:{let i=highlighted(),a=i!==void 0&&parsePromptCommand(r.text)===null?typeaheadCompletion(i).trimEnd():r.text;if(a.trim().length===0)break;this.#F=void 0,this.#N.add(a),this.#P=!1,this.#ft(),this.#W=STATUS.processing,isPromptControlCommand(a)?this.#_t({kind:`command`,body:stripTerminalControls(a.trim()),live:!1}):(this.#ht(),this.#vt(a),this.#we=a,this.#z.arm()),this.#Me(EMPTY_LINE),this.#Rt(),this.#at(),e(a);break}case`ctrl-d`:r.text.length===0?interrupt():apply(deleteForward(r));break;case`ctrl-l`:this.#Vt();break;case`ctrl-r`:this.#Rt();break;case`ctrl-c`:r.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#it()})}#Me(e){this.#j=e.text,this.#M=e.cursor}async renderStream(e,t){this.#nt(t),this.#h.clear(),this.#P=!1,this.#H.kind!==`waiting`&&(this.#H={kind:`waiting`,startedAtMs:Date.now()}),this.#W=this.#O>0?STATUS.connectionAuth:STATUS.processing,this.#bt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#u?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#z.armed&&this.#z.arm(),this.#X=!1,this.#fe=void 0,this.#pe=void 0,this.#he=void 0,this.#ge=void 0,this.#_e=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#mt(),this.#V=!0,this.#Rt();let r=new Promise(e=>{this.#le=e});this.#ie=e=>this.#ut(e),this.#it();let i={text:new Map,reasoning:new Map,tools:new Map};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#X)break;this.#Et(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#xt(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#xt(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#le=void 0,this.#X&&e.abort?.(),this.#at(),this.#gt(),this.#V=!1,this.#H.kind===`waiting`&&(this.#H={kind:`idle`}),this.#W=completedTurnStatus(this.#X,t?.continueSession===!0),this.#Nt(i),this.#X&&this.#Mt(),this.#Tt(),this.#u?.reportStats(),this.#Rt(),t?.continueSession||this.#rt()}}async readToolApproval(e,t){return this.#nt(t),this.#gt(),this.#P=!1,this.#H={kind:`idle`},this.#W=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#X=!1,this.#Rt(),await new Promise((t,n)=>{this.#U=n,this.#ie=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#ht(),this.#W=STATUS.processing,this.#at(),this.#Rt(),t({approved:!0})):n===`n`&&(this.#ht(),this.#W=STATUS.processing,this.#Pe(e.toolCallId),this.#at(),this.#Rt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#Rt();break;case`ctrl-c`:this.#X=!0,this.#rt(),n(interruptedError());break;default:break}},this.#it()})}async readInputQuestion(e,t){this.#nt(t),this.#gt(),this.#P=!1,this.#I=!1,this.#H={kind:`idle`},this.#X=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`overlay`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,overlayPanel=t=>renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#Z},this.#r,t),renderTextSection=()=>{this.#Ct({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#r),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#dt():(this.#ft(),this.#pt())};s===`overlay`?(s=`overlay`,this.#P=!1,this.#wt(o),this.#Te=overlayPanel,this.#W=``,syncFreeformCaret(),this.#Rt()):(s=`text`,this.#Te=void 0,renderTextSection(),this.#P=!0,this.#Me(l),this.#W=``,this.#dt(),this.#Rt());let finalize=t=>{this.#Te=void 0,this.#Ct({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#r.colors.dim(this.#r.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#P=!1,this.#ht(),this.#W=STATUS.processing,this.#ft(),this.#at(),this.#Rt();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Te=void 0,this.#Ct({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#r.colors.dim(this.#r.glyph.elbow)} ${this.#r.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#P=!1,this.#W=``,this.#ft(),this.#at(),this.#Rt(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#Rt())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#U=r,u=t,this.#ie=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#pt(),s===`text`&&this.#Me(l),this.#Rt();return}this.#X=!0,this.#Te=void 0,this.#ft(),this.#rt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#Rt();return}if(s===`overlay`){switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#pt(),this.#Rt();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#pt(),this.#Rt());break}if(t.type===`text`&&/^[1-9]$/u.test(t.value)){let e=Number(t.value)-1;e<n.length?selectOptionAt(e):e===n.length&&i&&(c=e,syncFreeformCaret(),this.#Rt())}break}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#pt(),this.#Me(l),this.#Rt();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#pt(),this.#Me(l),this.#Rt());break}case`enter`:{let t=resolveQuestionText(l.text,e);if(t===void 0)break;u(finalize(t));break}case`escape`:if(l.text.length>0){l=EMPTY_LINE,this.#pt(),this.#Me(l),this.#Rt();break}dismiss();break;default:break}},this.#it()})}upsertSubagentStep(e){if(this.#u?.recordSubagentDispatch(e.callId),this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#St(e.callId,e.subagentName),this.#o===`collapsed`){this.#Rt();return}this.#Ct({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#o!==`full`,live:!e.finalized}),this.#Rt()}}upsertSubagentTool(e){if(this.#u?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#u?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#o===`hidden`)return;if(this.#St(e.callId,e.subagentName),this.#o===`collapsed`){this.#Rt();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#At({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#Ct(r),this.#Ne(e.callId),this.#Rt()}#Ne(e){applyCohortLiveness(this.#p.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#wt(subagentToolSectionId(e.callId,e.childCallId)),this.#Rt()}subagents={begin:e=>this.beginSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#o===`hidden`)return;this.#St(e.callId,e.name);let t=this.#m.get(subagentHeaderId(e.callId));t?.status===`done`&&delete t.status,this.#Rt()}completeSubagent(e){let t=this.#m.get(subagentHeaderId(e.callId));t!==void 0&&(t.status=`done`,this.#Rt())}markChildToolCallId(e){this.#_.add(e);let t=this.#v.get(e);t!==void 0&&(this.#wt(t),this.#v.delete(e),this.#Rt())}#Pe(e){let t=this.#m.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#Ct({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#Rt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#O)return;let n=this.#O>0;this.#O=t,t>0?(this.#W=STATUS.connectionAuth,this.#Rt()):n&&(this.#W=STATUS.processing,this.#Rt())}setVercelStatus(e){this.#k=e,this.#Rt()}setRemoteConnectionStatus(e){this.#A=e,this.#Rt()}reset(){this.#p=[],this.#m.clear(),this.#h.clear(),this.#D=void 0,this.#E.length=0,this.#g.length=0,this.#w=!1,this.#T=void 0,this.#Fe(),this.#R=!1,this.#we=void 0,this.#Se=void 0,this.#O=0,this.#fe=void 0,this.#pe=void 0,this.#he=void 0,this.#ge=void 0,this.#_e=void 0,this.#q&&(this.#n.clearAll(),this.#Rt())}renderSessionBoundary(){this.#yt(),this.#Fe();let e=this.#r.colors,t=this.#r.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#_t({kind:`session-boundary`,body:n,live:!1}),this.#Rt()}#Fe(){this.#_.clear(),this.#v.clear(),this.#S.clear(),this.#b.clear(),this.#Oe=void 0,this.#ke=void 0,this.#x.clear(),this.#z.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#nt(),this.#_t({kind:`notice`,body:t,live:!1}),this.#Rt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#u?.append({source:`sandbox`,detail:t}),this.#nt(),this.#_t({kind:`sandbox`,body:t,live:!1}),this.#Rt())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#Ie();return}this.#nt(),this.#De=t,this.#Rt()}clearSetupWarning(){this.#Ie()}#Ie(){this.#De!==void 0&&(this.#De=void 0,this.#Rt())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#nt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#_t(r),this.#Rt()}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#nt(),this.#_t({kind:`result`,body:t,live:!1}),this.#Rt())}#Le(e,t=`spinner`){this.#nt(),this.#P=!1,this.#H={kind:`idle`},this.#W=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ee={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#mt(),this.#Rt()}#Re(e){this.#Ae=void 0,this.#Qe();let t=this.#Ee;if(t!==void 0){if(this.#Ee=void 0,this.#gt(),e){let e=[];for(let n of t.lines){if(n.evidence===!0){e.push(n.text);continue}(n.tone===`warning`||n.tone===`error`)&&(e.length>0&&this.#_t({kind:`flow`,title:`info`,body:e.join(`
`),live:!1}),this.#_t({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#Rt()}}async#ze(e){let t=this.#Ke(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a={options:i,searchAction:r,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(a.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(a.initialValues=e.initialValues);let o=initialSelectState(a),s,c=!1,l=0,isCurrentSearch=e=>e===l,clearSearch=()=>{l+=1,c=!1,o=reduceSelect(o,{type:`clear`},{options:i,searchAction:r,submitRow:n}),this.#Rt()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#Rt();try{let s=await t(e);if(!isCurrentSearch(a))return;let c=o.filter;i=s,o={...initialSelectState({options:s,searchAction:r,submitRow:n}),filter:c}}catch(e){isCurrentSearch(a)&&(s=toErrorMessage(e))}finally{isCurrentSearch(a)&&(c=!1,this.#Rt())}},u=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#Gt()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#Rt(),await this.#Ye((t,a)=>{let close=e=>{l+=1,a(e)};if(c){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#Rt();return}let u={key:t,options:i,searchAction:r,select:o},d=reduceSetupSelectInput(n?{...u,kind:e.kind,required:e.required}:{...u,kind:e.kind});switch(d.kind){case`cancel`:close(void 0);return;case`repaint`:this.#Rt();return;case`update`:o=d.select,s=void 0,this.#Rt();return;case`submit`:{let e=searchActionQuery(d.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(d.values);return}loadSearch(e,t);return}case`error`:s=d.message,this.#Rt();return;case`ignore`:return}}).promise}#Be(e){this.#nt();let t=this.#qe();t.status={kind:`progress`,text:stripTerminalControls(e.status)};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#Rt();let r=this.#Ye((t,r)=>{let i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#Rt();return;case`repaint`:this.#Rt();return;case`submit`:n!==void 0&&r(e.actions[n].value);return;case void 0:return}},()=>{t.status=void 0});return{choice:r.promise,close:()=>r.settle(void 0)}}async#Ve(e){let t=this.#Ke(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#Z,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#dt():(i=lineOf(``),this.#ft())};return syncEditableRow(),this.#Rt(),await this.#Ye((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#pt(),this.#Rt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#Rt()},submit=()=>{let t=selectValueAtCursor([...e.options],r.cursor);if(t===void 0)return;if(t!==e.editable.value){n({kind:`selected`,value:t});return}let o=(i.text||e.editable.defaultValue).trim(),s=e.editable.validate?.(o);if(s!==void 0){a=s,this.#Rt();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#Rt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#ft()).promise}async#He(e){let t=this.#Ke(),n=initialProviderPickerState(e.options,e.initialValue),r,cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor),r=e.options.find(e=>e.value===t);if(r!==void 0)return enterBadge(this.#r,r.checked===!0?`change`:void 0)};t.question=t=>{let r=cursorBadge(),i={kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#Z,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#r,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#dt():this.#ft()};return syncCaret(),this.#Rt(),await this.#Ye((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#Rt();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#Rt();return;case`validate`:{n=o.state,syncCaret(),this.#Rt();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#Rt();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#pt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#ft()}).promise}async#Ue(e){let t=this.#Ke(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#r,t),this.#Rt(),await this.#Ye((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#Rt();return;case`cancel`:r(void 0);return;case`settle`:r(i.result);return}},i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:i.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#Rt();return;case void 0:break}if(t.type===`left`||t.type===`right`){dispatch({type:`adjust`,direction:t.type});return}if(t.type===`tab`){dispatch({type:`adjust`,direction:`right`});return}if(t.type===`backspace`){dispatch({type:`backspace`});return}if(t.type===`text`)for(let e of t.value.replaceAll(`
`,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#We(e){let t=this.#Ke(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder!==void 0&&(i.placeholder=e.placeholder),e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#r,t,this.#Z)},this.#dt(),this.#Rt(),await this.#Ye((t,i)=>{let apply=e=>{n=e,r=void 0,this.#pt(),this.#Rt()},a=applyLineEditorKey(n,t);if(a!==void 0){apply(a);return}switch(t.type){case`ctrl-c`:case`escape`:i(void 0);return;case`ctrl-r`:this.#Rt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#Rt();return}i(t);return}default:return}},()=>this.#ft()).promise}async#Ge(e){let t=this.#Ke();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#Rt(),await this.#Ye((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#Rt();return;default:return}}).promise}#Ke(){return this.#nt(),this.#P=!1,this.#H={kind:`idle`},this.#W=``,this.#qe()}#qe(){return this.#Ee===void 0&&(this.#Ee={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Ee}#Je(){this.#Ee?.implicit===!0?this.#Ee=void 0:this.#Ee!==void 0&&(this.#Ee.question=void 0,this.#Ee.hideLinesWhileQuestion=!1),this.#ie=void 0,this.#at(),this.#Ee!==void 0&&this.#Ze(),this.#Rt()}#Ye(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Je(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Je(),i(e))};return this.#lt(),this.#ie=t=>e(t,settle,reject),this.#it(),{promise:a,settle}}#Xe(){let e,t=new Promise(t=>{e=t});return this.#Ae=e,this.#Ze(),{promise:t,dispose:()=>{this.#Ae===e&&(this.#Ae=void 0,this.#Qe())}}}#Ze(){if(this.#Ae===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#Ae;this.#Ae=void 0,this.#Qe(),e?.();return}e.type===`ctrl-r`&&this.#Rt()};this.#je=consumer,this.#lt(),this.#ie=consumer,this.#it()}#Qe(){this.#je!==void 0&&(this.#ie===this.#je&&this.#at(),this.#je=void 0)}#$e(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e)}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis)};if(this.#Ee!==void 0){this.#Ee.status=t,t===void 0&&(this.#Ee.preview=void 0),this.#Rt();return}if(!(this.#P||this.#V)){if(t===void 0){this.#H={kind:`idle`},this.#G=void 0,this.#gt(),this.#Rt();return}this.#nt(),this.#ht(),this.#G=t.text,this.#Rt()}}#et(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Ee;if(r!==void 0){if(r.preview=void 0,t===`warning`||t===`error`)for(let e of r.outputBuffer)r.lines.push({text:e,tone:`info`,evidence:!0});r.outputBuffer=[],r.lines.push({text:n,tone:t}),this.#Rt();return}this.#nt(),this.#_t({kind:`flow`,title:t,body:n,live:!1}),this.#Rt()}#tt(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Ee;if(n===void 0){this.#et(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#Rt()}shutdown(){this.#rt(),this.#J&&!this.#Y&&(this.#Y=!0,this.#t.write(`${this.#r.colors.dim(eveVersionTag())}\n`))}#nt(e){this.#K=e?.title??this.#K,e?.contextSize!==void 0&&(this.#me=e.contextSize),!this.#q&&(this.#q=!0,this.#J=!0,this.#n.reset(),this.#n.hideCursor(),this.#an(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#ce=()=>this.#Rt(),this.#t.on(`resize`,this.#ce))}#rt(){let e=this.#U;if(this.#U=void 0,e?.(interruptedError()),this.#at(),this.#ft(),this.#gt(),this.#ne!==void 0&&(clearTimeout(this.#ne),this.#ne=void 0),this.#re=!1,this.#q){this.#mn();for(let e of this.#p)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#Rt(),this.#n.clear(),this.#n.showCursor(),this.#on(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#ce&&=(this.#t.off(`resize`,this.#ce),void 0),this.#q=!1}}#it(){this.#e.off(`data`,this.#ot),this.#e.on(`data`,this.#ot),this.#ae.length>0&&queueMicrotask(()=>{this.#ie!==void 0&&this.#ae.length>0&&(this.#ct(),this.#st())})}#at(){this.#e.off(`data`,this.#ot),this.#lt(),this.#ie=void 0}#ot=e=>{this.#lt(),this.#ae+=this.#oe.write(e),this.#ct(),this.#st()};#st(){if(this.#ae===`\x1B`){this.#se=setTimeout(()=>{this.#ae===`\x1B`&&(this.#ae=``,this.#ie?.({type:`escape`}))},30),this.#se.unref?.();return}if(isIncompletePaste(this.#ae)){let e=this.#ae;this.#se=setTimeout(()=>{if(this.#ae!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#ae=``,t.length>0&&this.#ie?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#se.unref?.()}}#ct(){for(;this.#ae.length>0;){let e=nextKey(this.#ae);if(e.incomplete)return;this.#ae=this.#ae.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#ie?.(e.key)}}#lt(){this.#se&&=(clearTimeout(this.#se),void 0)}#ut(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#Rt();break;case`ctrl-c`:this.#X||(this.#X=!0,this.#H={kind:`idle`},this.#W=`Interrupted`,this.#le?.(),this.#Rt());break;case`enter`:break;default:{let t=applyLineEditorKey(this.#B,e,{multiline:!0});t!==void 0&&(this.#B=t,this.#Rt());break}}}#dt(){this.#ft(),this.#pt(),this.#ee=setInterval(()=>{this.#Z=!this.#Z,this.#Rt()},500),this.#ee.unref?.()}#ft(){this.#ee&&=(clearInterval(this.#ee),void 0),this.#Z=!0}#pt(){this.#Z=!0}#mt(){this.#gt(),this.#te=setInterval(()=>{this.#Q+=1,this.#Rt()},90),this.#te.unref?.()}#ht(){let e=Date.now();this.#$=e,this.#H={kind:`waiting`,startedAtMs:e},this.#mt()}#gt(){this.#te&&=(clearInterval(this.#te),void 0)}#_t(e){e.id!==this.#Se?.id&&this.#mn(),e.updateSeq=++this.#y,this.#p.push(e),e.id&&this.#m.set(e.id,e)}#vt(e){this.#R=!0,this.#_t({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#Rt()}#yt(){let e=this.#z.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#Xt(e.elapsedMs)}`,n=this.#pe??0;if(this.#me!==void 0&&this.#me>0&&n>0){let e=Math.round(n/this.#me*100);t+=` ${this.#r.glyph.dot} ${e}% context`}this.#_t({kind:`turn-stats`,body:t,live:!1})}#bt(e){if(e!=null){if(this.#we===e){this.#we=void 0;return}this.#_t({kind:`user`,body:stripTerminalControls(e),live:!1})}}#xt(e,t,n={}){let r=stripTerminalControls(e),i=stripTerminalControls(t),a=n.detail===void 0?void 0:stripTerminalControls(n.detail),o=n.hint===void 0?void 0:stripTerminalControls(n.hint),s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#u?.append(o===void 0?s:{...s,hint:o});let c={kind:`error`,title:r,body:i,live:!1};o!==void 0&&(c.hint=o),a!==void 0&&(c.detail=this.#u===void 0?a:`details: ${this.#u.displayPath}`),this.#_t(c),this.#Rt()}#St(e,t){if(this.#S.has(e))return;this.#S.add(e);let n=stripTerminalControls(t),r=this.#b.get(n)??[];if(r.push(e),this.#b.set(n,r),r.length===2){let e=this.#m.get(subagentHeaderId(r[0]));e!==void 0&&(e.subtitle=`#1`)}let i={id:subagentHeaderId(e),kind:`subagent`,subagentCallId:e,title:n,live:!0};r.length>1&&(i.subtitle=`#${r.length}`),this.#_t(i)}#Ct(e){if(e.id&&this.#h.has(e.id))return;let t=e.id?this.#m.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#y;return}this.#_t(e)}#wt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#Tt(){for(let e of this.#p)e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#Et(e,t,n){switch(e.type){case`step-finish`:this.#u?.recordStepUsage(e.usage),e.usage!==void 0&&this.#z.addUsage(e.usage),this.#Nt(n),this.#Lt(e.usage),this.#Rt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#Dt(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;n.text.set(e.id,r),this.#Dt(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);if(n.reasoning.set(e.id,r),t.reasoning===`full`){this.#Ot(e.id,r,!0,t);break}break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;if(t.reasoning===`full`){this.#Ot(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#kt({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#u?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#kt({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;this.#kt({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#It(e.toolCallId,n);if(r===void 0)break;this.#kt({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#It(e.toolCallId,n);if(this.#u?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#kt({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#It(e.toolCallId,n);if(r===void 0)break;this.#kt({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#xt(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`finish`:this.#Lt(e.usage),this.#Rt();break}}#Dt(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#Ct({id:e,kind:`assistant`,body:r,live:n}),this.#Rt())}#Ot(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Ct({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#Rt())}#kt(e,t,n){if(n.tools.set(e.toolCallId,e),this.#_.has(e.toolCallId)||this.#Pt(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#v.set(e.toolCallId,r);let i=this.#At(e);this.#Ct(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#Ft(n),this.#Rt()}#At(e){e.output!==void 0&&this.#x.observeRead(e.output);let t={};this.#jt(e.toolName)&&(t.isSubagent=!0);let n=readWriteFileInput(e.toolName,e.input);if(n===void 0)return t.isSubagent===!0?t:void 0;let r=this.#x.observeWrite({path:n.path,content:n.content,callId:e.toolCallId});r!==void 0&&(t.previousContent=r);let i=writeExistedFlag(e.output);return i!==void 0&&(t.existed=i),t}#jt(e){let t=this.#C?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#Mt(){for(let e of this.#p)e.kind!==`tool`&&e.kind!==`subagent-tool`||e.status===`running`&&(e.status=`error`,e.result=`interrupted`,e.live=!1)}#Nt(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#v.get(t)??toolSectionId(t);this.#wt(r),this.#v.delete(t)}}#Pt(e){let t=readTodoToolItems(e.toolName,e.input);if(t===void 0)return!1;if(t.length>0&&allTodoItemsSettled(t)){let e=JSON.stringify(t);this.#ke!==e&&(this.#ke=e,this.#_t({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#rn(),this.#r).join(`
`),live:!1})),this.#Oe=void 0}else this.#Oe=t.length>0?t:void 0,this.#ke=void 0;return this.#Rt(),!0}#Ft(e){let t=[];for(let n of e.tools.values()){if(this.#_.has(n.toolCallId))continue;let e=this.#v.get(n.toolCallId)??toolSectionId(n.toolCallId),r=this.#m.get(e);r?.kind===`tool`&&t.push({block:r,active:isActiveToolStatus(n.status)})}applyCohortLiveness(t)}#It(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#v.get(e)??toolSectionId(e),i=this.#m.get(r);if(!(i===void 0||i.kind!==`tool`))return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.toolName??i.title??`tool`}}#Lt(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#fe=(t??0)+(n??0)),this.#pe=t??this.#pe,this.#he=n??this.#he,this.#he!=null&&this.#_e!==void 0){let e=(Date.now()-this.#_e)/1e3;e>0&&(this.#ge=this.#he/e)}}#Rt(){if(this.#q){if(this.#ue){this.#de=!0;return}this.#ue=!0;try{do this.#de=!1,this.#zt();while(this.#de)}finally{this.#ue=!1}}}#zt(){if(!this.#q)return;let e=this.#rn(),t=this.#Jt(e),n=Math.max(1,this.#in()-t.length),r=[],i=this.#D,a=groupToolBlocksForDisplay(this.#p),o=0;for(;o<a.length&&a[o].display.live===!1;)o+=1;if(o>0){let e=new Set(a.slice(0,o).flatMap(e=>e.members));for(let t=this.#p.length-1;t>=0;--t)e.has(this.#p[t])&&this.#p.splice(t,1)}for(let t of a.slice(0,o)){for(let e of t.members)this.#g.push(e),e.id&&(this.#h.add(e.id),this.#m.delete(e.id));if(this.#gn(t.display))continue;let n=this.#Wt(t.display,e,i);i=previousBlockOf(t.display),this.#D=i,r.push(...n),this.#E.push(...n)}let s=[];for(let{display:t}of a.slice(o)){if(this.#gn(t))continue;let n=this.#Wt(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)s.push({block:t,row:n[e]})}let c=[...clipLiveRows(s.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,c):this.#n.update(c)}#Bt(){if(!this.#q)return;let e=this.#rn(),t=this.#Jt(e),n=Math.max(1,this.#in()-t.length),r=this.#D,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#p)){if(this.#gn(t))continue;let n=this.#Wt(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#r),...t];this.#n.clearAll(),this.#n.flush([...this.#Ut(),...this.#E],a)}logDisplayMode(){return this.#f}setLogDisplayMode(e){e!==this.#f&&(this.#f=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#Ht(),this.#q&&this.#Bt())}flushDelayedDevBuildErrors(){let e=this.#xe;e!==void 0&&(this.#xe=void 0,this.#_t({kind:`log`,title:`stderr`,body:e,live:!0}),this.#Rt())}#Vt(){this.#re=!0,this.#ne!==void 0&&clearTimeout(this.#ne),this.#ne=setTimeout(()=>{this.#re=!1,this.#ne=void 0,this.#Rt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#f)),this.#Rt()}#Ht(){let e=this.#rn();this.#E.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#g,{logCoalescing:`runs`})){if(this.#gn(n))continue;let r=this.#Wt(n,e,t);t=previousBlockOf(n),this.#E.push(...r)}this.#D=t}#Ut(){let e=this.#C;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#rn()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#Wt(e,t,n){let r={activityPulse:this.#Kt(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#Gt(){return this.#r.spinner[this.#Q%this.#r.spinner.length]??``}#Kt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#qt(e,t){return e.indicator.kind===`spinner`?{glyph:this.#Gt(),color:`yellow`}:{glyph:this.#Kt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#Jt(e){let n=this.#r.colors,r=[``];if(this.#Te!==void 0)return r.push(...this.#Te(e),``),this.#en(r,e),r;let a=this.#Ee;if(a!==void 0){let t=this.#qt(a,a.status),n=a.status===void 0?void 0:{...a.status,indicator:t},i;if(a.question!==void 0){let t=a.question(e);i={kind:`question`,rows:t},n!==void 0&&(i={kind:`question`,rows:t,status:n})}else n===void 0?i=a.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:a.preview,indicator:t}:(i={kind:`status`,status:n},a.preview!==void 0&&(i={kind:`status`,status:n,preview:a.preview}));let o={title:a.title,lines:a.hideLinesWhileQuestion===!0?[]:a.lines,content:i};return r.push(...renderFlowPanel(o,this.#r,e)),this.#tn(r,e),r}if(this.#Oe!==void 0&&r.push(...renderTodoPanelRows({items:this.#Oe,width:e,theme:this.#r,working:this.#V||this.#H.kind===`waiting`,pulse:this.#Kt(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}),``),this.#De!==void 0&&r.push(...renderAttentionRows(this.#De,e,this.#r),``),this.#P){let i=this.#F===void 0?void 0:inlineCommandHint(this.#F);i===void 0&&this.#F!==void 0&&isTypeaheadOpen(this.#F)&&r.push(...renderCommandSuggestions(this.#F,this.#r,e));let a=isPromptControlCommand(this.#j),o=i?n.dim(` ${i}`):``,l=[];this.#en(l,e);let d=Math.max(1,this.#in()-1-r.length-1-l.length),f={text:this.#j,cursor:this.#M,width:e,theme:this.#r,caretVisible:this.#Z,isCommand:a,ghost:o,maxRows:d};return this.#I&&this.#j.length===0&&(f.placeholder=this.#R?``:promptPlaceholder(Date.now()-this.#L)),r.push(...promptInputRows(f)),r.push(...l),r}let o=this.#H.kind===`waiting`&&this.#G===void 0;if(this.#V||o){r.push(this.#Yt(e)),this.#Qt(r,e);let t=[];return this.#en(t,e),!this.#V&&t.length>0&&r.push(``),r.push(...t),r}if(this.#B.text.length>0)return this.#$t(r,e,{inert:!1}),this.#en(r,e),r;let l=this.#G??(this.#W.length>0?this.#W:`Ready`),d=this.#nn(),f=n.dim(this.#r.glyph.dot),p=d?`${f} ${l} ${n.dim(this.#r.glyph.dot)} ${d}`:`${f} ${l}`;return r.push(clip(p,e)),this.#en(r,e),r}#Yt(e){let t=this.#r.colors,n=this.#Kt(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),r=this.#H,i=this.#z.startedAtMs??this.#_e??(r.kind===`waiting`?r.startedAtMs:Date.now()),a=Date.now()-i,o=`${typewriterText(`Working for`,a,80)} ${this.#Xt(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#Xt(e){return`${formatTurnDuration(e)}${this.#Zt()}`}#Zt(){let{inputTokens:e,outputTokens:t}=this.#z.usage;return e===0&&t===0?``:` ${this.#r.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#r.glyph)}`}#Qt(e,t){this.#V&&this.#$t(e,t,{inert:!0})}#$t(e,t,n){e.push(``);let r={text:this.#B.text,cursor:this.#B.cursor,width:t,theme:this.#r,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#B.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#en(e,t){let n=this.#A===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#r,width:r};this.#re&&(i.logLevel=this.#f);let a=this.#C?.serverUrl;if(a!==void 0&&this.#A===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#C?.info?.agent.model;o?.id!==void 0&&(i.model=o.id),o?.reasoning!==void 0&&o.reasoning!==`provider-default`&&(i.reasoning=o.reasoning),readGatewayServiceTier(o?.providerOptions).kind===`priority`&&(i.fastMode=!0);let s=o?.endpoint;s!==void 0&&(i.endpoint=s),this.#k!==void 0&&(i.vercel=this.#k),this.#A!==void 0&&(i.remote=this.#A);let c=buildStatusLine(i);c!==void 0&&e.push(clip(`${n}${c}`,t))}#tn(e,t){if(this.#A===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#A,theme:this.#r,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#nn(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#fe,outputTokens:this.#he,tokensPerSecond:this.#ge},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#rn(){return Math.max(20,this.#t.columns||80)}#in(){return Math.max(8,this.#t.rows||24)}#an(){if(this.#ve!==void 0||!this.#l)return;this.#ye=``,this.#be=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#cn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#u?.subscribeLogRecords(e=>this.#sn(e)),this.#ve=()=>{this.#u?.unsubscribeLogRecords(),e(),t()}}#on(){let e=this.#ve;e!==void 0&&(this.#ve=void 0,e(),this.#ye.length>0&&(this.#u?.append({source:`stdout`,detail:this.#ye}),this.#hn(`stdout`)&&process.stdout.write(`${this.#ye}\n`),this.#ye=``),this.#be.length>0&&(this.#u?.append({source:`stderr`,detail:this.#be}),this.#hn(`stderr`)&&process.stderr.write(`${this.#be}\n`),this.#be=``))}#sn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#un(`[eve:${e.namespace}] ${e.message}${t}`),this.#Rt()}#cn(e,t){let n=(e===`stdout`?this.#ye:this.#be)+t,r=n.lastIndexOf(`
`),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#ye=i:this.#be=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#u?.append({source:e,detail:a}),e===`stdout`?this.#ln(a):this.#un(a),this.#Rt())}#ln(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
`);t=[],e.trim().length!==0&&this.#_t({kind:`log`,title:`stdout`,body:e,live:!0})};for(let n of e.split(`
`)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#_t({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#fn(r,n.trimEnd())}flushPending()}#un(e){let t=e.split(`
`),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#u===void 0){this.#_t({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#u.displayPath);if(t.kind===`inline`){this.#_t({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#_t({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#_t({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
`);r.trim().length>0&&this.#_t({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
`);this.#dn(i)}#dn(e){if(this.#f===`all`){if(e.trim().length===0)return;this.#_t({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#xe=e}#fn(e,t){let n=this.#pn();if(e.kind===`failed`){this.#dn(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#Ce}`;this.#Ce+=1,this.#Se={id:r,summary:t},this.#_t({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}if(n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#xe=void 0);return}e.kind===`rebuilt`&&(this.#xe=void 0),this.#_t({kind:`log`,title:`stdout`,body:t,live:!0})}#pn(){let e=this.#Se;if(e===void 0)return;let t=this.#m.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#mn(){let e=this.#Se;if(e===void 0)return;this.#Se=void 0;let t=this.#m.get(e.id);t!==void 0&&(t.live=!1)}#hn(e){switch(this.#f){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#gn(e){return e.kind===`sandbox`?!this.#hn(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#f!==`stderr`:e.logVisibility===`all-only`?this.#f!==`all`:!this.#hn(e.title===`stderr`?`stderr`:`stdout`):!1}};function chunkToString(e,t){return typeof e==`string`?e:Buffer.from(e).toString(t)}async function*iterateTUIStream(e){if(e instanceof ReadableStream){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}return}yield*e}function clip(e,t){return clipVisible(e,t)}function promptInputRows({text:e,cursor:t,width:n,theme:r,caretVisible:i,isCommand:a,ghost:o,maxRows:s,placeholder:c,inert:l}){let u=r.colors;if(e.length===0&&c!==void 0){let e=renderInputWithBlockCursor({...visibleLine({text:c,cursor:0},Math.max(1,n-3),r.glyph.ellipsis),visible:i,inverse:u.inverse,render:e=>u.dim(renderInputText(e))});return[clip(`${u.dim(r.glyph.promptIdle)} ${e}`,n),``]}let style=e=>{let t=renderInputText(e);return a&&t.length>0?u.blue(t):t},d=layoutPromptInput({text:e,cursor:t}),f=Math.min(Math.max(1,s),d.rows.length),p=Math.max(0,Math.min(d.caretRow-f+1,d.rows.length-f)),m=l===!0?u.dim(r.glyph.prompt):u.cyan(r.glyph.prompt),h=u.dim(r.glyph.ellipsis),g=Math.max(1,n-3),_=[];for(let e=p;e<p+f;e+=1){let t=d.rows[e],a=e===0?m:` `;(e===p&&p>0||e===p+f-1&&p+f<d.rows.length)&&(a=h);let s;if(e===d.caretRow){let{before:e,under:n,after:a}=visibleLine({text:t.text,cursor:d.caretOffset},g,r.glyph.ellipsis);s=renderInputWithBlockCursor({before:e,under:n,after:a,visible:i,inverse:u.inverse,render:style}),o.length>0&&d.rows.length===1&&(s+=o)}else s=style(t.text);_.push(clip(`${a} ${s}`,n))}return _.push(``),_}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function isActiveToolStatus(e){return e===`running`||e===`approval`}function applyCohortLiveness(e){let t=e.some(e=>e.active);for(let n of e)n.block.live=t||n.active}function leadsWithGap(e,t){if(e.kind===`tool`&&(t?.kind===`user`||t?.kind===`assistant`||t?.kind===`question`))return!0;if(e.kind===`sandbox`&&t?.kind===`sandbox`)return!1;if(t?.kind===`sandbox`&&e.kind!==`sandbox`||t?.kind===`log`)return!0;switch(e.kind){case`user`:case`assistant`:case`reasoning`:case`subagent`:case`error`:case`notice`:case`question`:case`connection-auth`:case`sandbox`:case`log`:case`command`:case`warning`:case`flow`:case`turn-stats`:case`session-boundary`:case`todo-list`:case`agent-header`:return!0;default:return!1}}function parseSandboxLogLine(e){let t=e.trim();if(!t.startsWith(`eve: `))return;let n=t.slice(5);return/\bsandbox\b/i.test(n)&&!isLowValueSandboxLogLine(n)?n:void 0}function isLowValueSandboxLogLine(e){return/^initializing (?:\d+ )?sandbox templates?\b/i.test(e)||/^initialized \d+ sandbox\b/i.test(e)||/^reused cached sandbox template\b/i.test(e)||/^sandbox template "[^"]+" \([^)]+\): (checking|reusing|loading microsandbox runtime|microsandbox runtime ready)\b/i.test(e)}function clipLiveRows(e,t,n,r){if(e.length<=t)return[...e];if(t<=1)return[clip(hiddenRowsMarker(e.length,r),n)];let i=t-1;return[clip(hiddenRowsMarker(e.length-i,r),n),...e.slice(e.length-i)]}function hiddenRowsMarker(e,t){let n=e.toLocaleString(),r=e===1?`row`:`rows`;return t.colors.dim(`${t.glyph.dot} ${t.glyph.ellipsis} ${n} earlier ${r} hidden while streaming`)}function collapseReasoning(e,t){switch(e){case`collapsed`:return!0;case`auto-collapsed`:return!t;default:return!1}}function renderNativeToolBlock(e,t,n,r){let i=e.preparing===!0?presentPreparingTool(e.toolName,r):presentTool(e.toolName,e.input,r),a={id:t,kind:`tool`,title:stripTerminalControls(i.title),subtitle