eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
15 lines • 62.4 kB
JavaScript
import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{copyTextToClipboard}from"./clipboard.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{MessageQueue,renderMessageQueueRows}from"./message-queue.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{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompleteOsc,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{TraceViewerSession}from"./traces/trace-viewer-session.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{BACKGROUND_COLOR_QUERY,parseBackgroundColorReply}from"./terminal-background.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,orderedSelection,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{AltScreen}from"#cli/ui/alt-screen.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){return e.interrupted?`Interrupted`:e.cancelled?`Cancelled`:e.continueSession?`Ready`:`Done`}const incompletePasteFlushMs=1e3,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=[];#h=new Map;#g=new Set;#_=[];#v=new Set;#y=new Map;#b=0;#x=new Map;#S=new Set;#C=new Set;#w=new FileContentCache;#T=new Set;#E;#D;#O=!1;#k;#A=[];#j;#M=0;#N;#P;#F=``;#I=0;#L=new PromptHistory;#R=!1;#z;#B=!1;#V=Date.now();#H=!1;#U=new TurnClock;#W=EMPTY_LINE;#G=!1;#K={kind:`idle`};#q;#J=STATUS.processing;#Y;#X=`eve`;#Z=!1;#Q=!1;#$=!1;#ee=!1;#te=!1;#ne=!1;#re=!1;#ie;#ae=!0;#oe=0;#se=Date.now();#ce;#le;#ue;#de=!1;#fe;#pe=``;#me=new StringDecoder(`utf8`);#he;#ge;#_e;#ve=!1;#ye=!1;#be;#xe;#Se;#Ce;#we;#Te;#Ee;#De=``;#Oe=``;#ke;#Ae;#je;#Me=!1;#Ne;#Pe=0;#Fe;#Ie;#Le;#Re;#ze;#Be;#Ve=new MessageQueue;#He;#Ue=!1;#We;#Ge;#Ke=!1;#qe;#Je;#Ye;#Xe;#Ze;setupFlow={begin:(e,t)=>this.#rt(e,t),setNavigation:e=>this.#it(e),end:e=>this.#at(e?.preserveDiagnostics??!0),readSelect:e=>this.#ot(e),readEditableSelect:e=>this.#ct(e),readProviderPicker:e=>this.#lt(e),readModelEditor:e=>this.#ut(e),readText:e=>this.#dt(e),readAcknowledge:e=>this.#ft(e),readChoice:e=>this.#st(e),setStatus:e=>this.#bt(e),renderLine:(e,t)=>this.#xt(e,t),replaceContent:e=>this.#St(e),renderOutput:e=>this.#Ct(e),withInheritedStdio:e=>this.#wt(e),withExclusiveTerminal:e=>this.#wt(e),waitForInterrupt:e=>this.#_t(e)};traceViewer={open:e=>this.#Et(e)};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=new AltScreen(this.#t),this.#i=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#a=e?.tools??`auto-collapsed`,this.#o=e?.reasoning??`auto-collapsed`,this.#s=e?.subagents??`auto-collapsed`,this.#c=e?.connectionAuth??`full`,this.#l=e?.assistantResponseStats??`tokensPerSecond`,this.#Se=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#d=e?.diagnostics,this.#ie=e?.onExitRequest,this.#p=e?.logs??`none`,this.#f=e?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#X=e.name,this.#E=e,this.#kt();let t=this.#yn().join(`
`);if(this.#O){t!==this.#k&&(this.#k=t,this.#Kt({kind:`agent-header`,body:t,live:!1})),this.#mn();return}this.#O=!0,this.#k=t,this.#n.flush(this.#yn(),[])}beginStartupDraft(e){this.#kt({title:e.title}),this.#R=!0,this.#B=!0,this.#D={name:e.title,tip:e.tip};let t=lineOf(stripPromptControlCharacters(e.initialDraft??``));this.#Qe(t),this.#Bt(),this.#mn();let apply=e=>{t=e,this.#Ht(),this.#Qe(t),this.#mn()};this.#fe=e=>{let n=applyLineEditorKey(t,e,{multiline:!0});if(n!==void 0){apply(n);return}e.type===`ctrl-c`&&this.#ie?.()},this.#Mt()}finishStartupDraft(){let e=this.#F;return this.#Nt(),this.#Vt(),this.#R=!1,this.#D=void 0,this.#B=!1,e}async readPrompt(e){this.#kt(e),this.#Gt(),this.#Jt(),this.#R=!0,this.#B=!0,this.#K={kind:`idle`},this.#J=``,this.#ne=this.#re,this.#re=!1;let t=this.#Ve.restoreDraft()?.split(`
`).map(stripPromptControlCharacters).join(`
`),n=stripPromptControlCharacters(e?.initialDraft??this.#W.text),r=t===void 0?n:n.length===0?t:`${t}\n\n${n}`,i=lineOf(r);return this.#W=EMPTY_LINE,this.#L.begin(i.text),this.#Qe(i),this.#z=typeaheadFor(this.#f,i.text),this.#Bt(),this.#mn(),await new Promise((e,t)=>{this.#q=t;let apply=e=>{i=e,this.#Ht(),this.#Qe(i),this.#z=typeaheadFor(this.#f,e.text,this.#z),this.#mn()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#z=void 0,this.#Vt(),this.#jt(),t(interruptedError())},suggestions=()=>this.#z!==void 0&&isTypeaheadOpen(this.#z)?this.#z:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#fe=t=>{t.type!==`ctrl-c`&&this.#ne&&(this.#ne=!1,this.#mn());let n=applyLineEditorKey(i,t,{multiline:!0});if(n!==void 0){apply(n);return}switch(t.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#z=moveTypeaheadSelection(e,-1),this.#mn();break}let t=movePromptLine(i,`up`);t===void 0?recall(this.#L.previous(i.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#z=moveTypeaheadSelection(e,1),this.#mn();break}let t=movePromptLine(i,`down`);t===void 0?recall(this.#L.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.#z=dismissTypeahead(e),this.#mn());break}case`enter`:{let t=highlighted(),n=t!==void 0&&parsePromptCommand(i.text)===null?typeaheadCompletion(t).trimEnd():i.text;if(n.trim().length===0)break;this.#z=void 0,this.#L.add(n),this.#R=!1,this.#Vt(),this.#J=STATUS.processing,isPromptControlCommand(n)?this.#Kt({kind:`command`,body:stripTerminalControls(n.trim()),live:!1}):(this.#Wt(),this.#qt(n),this.#Fe=n,this.#U.arm()),this.#Qe(EMPTY_LINE),this.#mn(),this.#Nt(),e(n);break}case`ctrl-d`:i.text.length===0?(this.#Tt(),interrupt()):apply(deleteForward(i));break;case`ctrl-l`:this.#_n();break;case`ctrl-r`:this.#mn();break;case`ctrl-c`:if(this.#ne){this.#Tt(),interrupt();break}this.#ne=!0,apply(EMPTY_LINE)}},this.#Mt()})}#Qe(e){this.#F=e.text,this.#I=e.cursor}takeQueuedPrompt(){let e=this.#Ve.view().steering,t=this.#Ve.takePrompt();return t!==void 0&&(this.#Ge=e?`steer`:`queue`),t}async renderStream(e,t){this.#kt(t),this.#g.clear(),this.#R=!1,this.#K.kind!==`waiting`&&(this.#K={kind:`waiting`,startedAtMs:Date.now()}),this.#J=this.#M>0?STATUS.connectionAuth:STATUS.processing,this.#Yt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#d?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#U.armed&&this.#U.arm(),this.#ee=!1,this.#Ue=!1,this.#Ke=!1,this.#qe=t?.submittedPrompt,this.#Ve.beginTurn(),this.#He=e.cancel,this.#be=void 0,this.#xe=void 0,this.#Ce=void 0,this.#we=void 0,this.#Te=Date.now();let n={tools:t?.tools??this.#a,reasoning:t?.reasoning??this.#o,assistantResponseStats:t?.assistantResponseStats??this.#l};this.#Ut(),this.#G=!0,this.#mn();let r=new Promise(e=>{this.#_e=e});this.#fe=e=>this.#zt(e),this.#Mt();let i={text:new Map,reasoning:new Map,tools:new Map,cancelled:!1,restoreCancelledPrompt:!0};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#ee)break;this.#nn(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.#_e=void 0,this.#ee&&e.abort?.(),this.#He=void 0,this.#Nt(),this.#Gt(),this.#G=!1,this.#K.kind===`waiting`&&(this.#K={kind:`idle`}),this.#J=completedTurnStatus({interrupted:this.#ee,cancelled:this.#Ue,continueSession:t?.continueSession===!0}),this.#ln(i),(this.#ee||i.cancelled)&&this.#cn(i),this.#tn(),this.#d?.reportStats(),this.#mn(),t?.continueSession||this.#jt()}}async renderIdleStream(e,t){let n={tools:t?.tools??this.#a,reasoning:t?.reasoning??this.#o,assistantResponseStats:t?.assistantResponseStats??this.#l},r={text:new Map,reasoning:new Map,tools:new Map,cancelled:!1,restoreCancelledPrompt:!1};try{for await(let t of iterateTUIStream(e.events))this.#nn(t,n,r)}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.#ln(r),r.cancelled&&this.#cn(r),this.#tn(),this.#d?.reportStats(),this.#mn()}}async readToolApproval(e,t){return this.#kt(t),this.#Gt(),this.#R=!1,this.#K={kind:`idle`},this.#J=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#ee=!1,this.#mn(),await new Promise((t,n)=>{this.#q=n,this.#fe=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Wt(),this.#J=STATUS.processing,this.#Nt(),this.#mn(),t({approved:!0})):n===`n`&&(this.#Wt(),this.#J=STATUS.processing,this.#et(e.toolCallId),this.#Nt(),this.#mn(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#mn();break;case`ctrl-c`:this.#ee=!0,this.#jt(),n(interruptedError())}},this.#Mt()})}async readInputQuestion(e,t){this.#kt(t),this.#Gt(),this.#R=!1,this.#B=!1,this.#K={kind:`idle`},this.#ee=!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.#ae},this.#i,t),renderTextSection=()=>{this.#Qt({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#Bt():(this.#Vt(),this.#Ht())};s===`overlay`?(s=`overlay`,this.#R=!1,this.#en(o),this.#Ie=overlayPanel,this.#J=``,syncFreeformCaret(),this.#mn()):(s=`text`,this.#Ie=void 0,renderTextSection(),this.#R=!0,this.#Qe(l),this.#J=``,this.#Bt(),this.#mn());let finalize=t=>{this.#Ie=void 0,this.#Qt({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#R=!1,this.#Wt(),this.#J=STATUS.processing,this.#Vt(),this.#Nt(),this.#mn();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Ie=void 0,this.#Qt({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#R=!1,this.#J=``,this.#Vt(),this.#Nt(),this.#mn(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#mn())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#q=r,u=t,this.#fe=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#Ht(),s===`text`&&this.#Qe(l),this.#mn();return}this.#ee=!0,this.#Ie=void 0,this.#Vt(),this.#jt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#mn();return}if(s===`overlay`){let r=setupSelectionIntent(t,{textNavigation:!isOnFreeformRow()});if(r?.kind===`move`){moveCursor(r.direction===`up`?-1:1);return}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.#Ht(),this.#mn();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#Ht(),this.#mn());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.#mn())}}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#Ht(),this.#Qe(l),this.#mn();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Ht(),this.#Qe(l),this.#mn());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.#Ht(),this.#Qe(l),this.#mn();break}dismiss()}},this.#Mt()})}upsertSubagentStep(e){if(this.#d?.recordSubagentDispatch(e.callId),this.#s===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(t.length!==0||n.length!==0){if(this.#Zt(e.callId,e.subagentName),this.#s===`collapsed`){this.#mn();return}this.#$t({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#s!==`full`,live:!e.finalized}),this.#mn()}}upsertSubagentTool(e){if(this.#d?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#d?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#s===`hidden`)return;if(this.#Zt(e.callId,e.subagentName),this.#s===`collapsed`){this.#mn();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#on({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.#s===`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.#$t(r),this.#$e(e.callId),this.#mn()}#$e(e){applyCohortLiveness(this.#m.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#en(subagentToolSectionId(e.callId,e.childCallId)),this.#mn()}subagents={begin:e=>this.beginSubagent(e),background:e=>this.backgroundSubagent(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.#s===`hidden`)return;this.#Zt(e.callId,e.name);let t=this.#h.get(subagentHeaderId(e.callId));t!==void 0&&(t.status===`done`&&delete t.status,t.live=!0),this.#C.delete(e.callId),this.#mn()}backgroundSubagent(e){let t=this.#h.get(subagentHeaderId(e.callId));t===void 0||this.#g.has(subagentHeaderId(e.callId))||(t.status=`running`,t.live=!0,t.updateSeq=++this.#b,this.#S.add(e.callId),this.#mn())}completeSubagent(e){let t=this.#h.get(subagentHeaderId(e.callId));if(t!==void 0){if(t.status=`done`,e.authoritative){this.#S.delete(e.callId),this.#C.delete(e.callId);for(let t of this.#m)t.subagentCallId===e.callId&&(t.live=!1)}else{this.#C.add(e.callId);for(let t of this.#m)t.subagentCallId===e.callId&&(t.live=!0)}this.#mn()}}markChildToolCallId(e){this.#v.add(e);let t=this.#y.get(e);t!==void 0&&(this.#en(t),this.#y.delete(e),this.#mn())}#et(e){let t=this.#h.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#c===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#Qt({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.#mn()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#M)return;let n=this.#M>0;this.#M=t,t>0?(this.#J=STATUS.connectionAuth,this.#mn()):n&&(this.#J=STATUS.processing,this.#mn())}setVercelStatus(e){this.#N=e,this.#mn()}setRemoteConnectionStatus(e){this.#P=e,this.#mn()}reset(){this.#m=[],this.#h.clear(),this.#g.clear(),this.#j=void 0,this.#A.length=0,this.#_.length=0,this.#O=!1,this.#k=void 0,this.#tt(),this.#H=!1,this.#Fe=void 0,this.#Ae=void 0,this.#M=0,this.#be=void 0,this.#xe=void 0,this.#Ce=void 0,this.#we=void 0,this.#Te=void 0,this.#Z&&(this.#n.clearAll(),this.#mn())}renderSessionBoundary(){this.#Jt(),this.#tt();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#Kt({kind:`session-boundary`,body:n,live:!1}),this.#mn()}#tt(){this.#v.clear(),this.#y.clear(),this.#T.clear(),this.#S.clear(),this.#C.clear(),this.#x.clear(),this.#ze=void 0,this.#Be=void 0,this.#Ve.reset(),this.#Ge=void 0,this.#w.clear(),this.#U.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#kt(),this.#Kt({kind:`notice`,body:t,live:!1}),this.#mn())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#d?.append({source:`sandbox`,detail:t}),this.#kt(),this.#Kt({kind:`sandbox`,body:t,live:!1}),this.#mn())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#nt();return}this.#kt(),this.#Re=t,this.#mn()}clearSetupWarning(){this.#nt()}#nt(){this.#Re!==void 0&&(this.#Re=void 0,this.#mn())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#kt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Kt(r),this.#mn()}renderCommandResult(e,t){let n=stripAnsi(e);n.trim().length!==0&&(this.#kt(),this.#Kt({kind:`result`,body:n,live:!1,status:t===`success`?`done`:void 0}),this.#mn())}#rt(e,t=`spinner`){this.#kt(),this.#R=!1,this.#K={kind:`idle`},this.#J=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Le={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Ut(),this.#mn()}#it(e){this.#Le!==void 0&&(this.#Le.navigation=e,this.#mn())}#at(e){this.#Je=void 0,this.#yt();let t=this.#Le;if(t!==void 0){if(this.#Le=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.#Kt({kind:`flow`,title:`info`,body:e.join(`
`),live:!1}),this.#Kt({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#mn()}}async#ot(e){let t=this.#pt(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a=e.navigation?.kind===`planner`,o={options:i,searchAction:r,submitRow:n&&!a};`initialValue`in e&&e.initialValue!==void 0&&(o.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(o.initialValues=e.initialValues);let s=initialSelectState(o),c,l=!1,u=0,isCurrentSearch=e=>e===u,clearSearch=()=>{u+=1,l=!1,s=reduceSelect(s,{type:`clear`},{options:i,searchAction:r,submitRow:n&&!a}),this.#mn()},loadSearch=async(e,t)=>{l=!0,c=void 0;let o=++u;this.#mn();try{let c=await t(e);if(!isCurrentSearch(o))return;let l=s.filter;i=c,s={...initialSelectState({options:c,searchAction:r,submitRow:n&&!a}),filter:l}}catch(e){isCurrentSearch(o)&&(c=toErrorMessage(e))}finally{isCurrentSearch(o)&&(l=!1,this.#mn())}},d=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}));d=e.notices??r,t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:s};return d!==void 0&&d.length>0&&(t.notices=d),c!==void 0&&(t.error=c),l&&(t.loadingFrame=this.#xn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#mn(),await this.#gt((t,o)=>{let close=e=>{u+=1,o(e)};if(l){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#mn();return}let d=e.navigation?.kind===`planner`?e.navigation:void 0,f=t.type===`left`&&(d?.activeStep??0)>(d?.firstNavigableStep??0)?`back`:t.type===`right`&&d!==void 0&&d.activeStep>=(d.firstNavigableStep??0)&&d.activeStep<d.steps.length-1?`forward`:void 0;if(f!==void 0){close({kind:`navigate`,direction:f,values:n?orderedSelection(i,s.selected):[]});return}let p={key:t,options:i,searchAction:r,select:s},m=reduceSetupSelectInput(n?{...p,kind:e.kind,required:e.required,plannerNavigation:a||void 0}:{...p,kind:e.kind});switch(m.kind){case`cancel`:close(void 0);return;case`repaint`:this.#mn();return;case`update`:s=m.select,c=void 0,this.#mn();return;case`submit`:{let e=searchActionQuery(m.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(m.values);return}loadSearch(e,t);return}case`error`:c=m.message,this.#mn();return;case`ignore`:return}}).promise}#st(e){this.#kt();let t=this.#mt();t.status={kind:`progress`,text:stripTerminalControls(e.status),startedAtMs:Date.now()};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#i,t),this.#mn();let r=this.#gt((t,r)=>{let i=setupSelectionIntent(t,{textNavigation:!0});switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#mn();return;case`repaint`:this.#mn();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#ct(e){let t=this.#pt(),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.#ae,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#i,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#Bt():(i=lineOf(``),this.#Vt())};return syncEditableRow(),this.#mn(),await this.#gt((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Ht(),this.#mn()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#mn()},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.#mn();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t,{textNavigation:!onEditableRow()});switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#mn();return;case void 0:}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Vt()).promise}async#lt(e){let t=this.#pt(),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.#i,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:`ai-gateway-key`,caretVisible:this.#ae,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#i,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#Bt():this.#Vt()};return syncCaret(),this.#mn(),await this.#gt((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.#mn();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#mn();return;case`validate`:{n=o.state,syncCaret(),this.#mn();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,{textNavigation:n.phase.kind===`inactive`});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.#mn();return;case void 0:}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#Ht(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Vt()}).promise}async#ut(e){let t=this.#pt(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#i,t),this.#mn(),await this.#gt((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#mn();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.#mn();return;case void 0:}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#dt(e){let t=this.#pt(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder===void 0?e.defaultValue!==void 0&&(i.placeholder=e.defaultValue):i.placeholder=e.placeholder,e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#i,t,this.#ae)},this.#Bt(),this.#mn(),await this.#gt((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Ht(),this.#mn()},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.#mn();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#mn();return}i(t);return}default:return}},()=>this.#Vt()).promise}async#ft(e){let t=this.#pt();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#i,t),this.#mn(),await this.#gt((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#mn();return;default:return}}).promise}#pt(){this.#kt(),this.#R=!1,this.#K={kind:`idle`},this.#J=``;let e=this.#mt();return e.status!==void 0&&(e.status=void 0,e.summary=void 0,e.preview=void 0),e}#mt(){return this.#Le===void 0&&(this.#Le={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Le}#ht(){this.#Le?.implicit===!0?this.#Le=void 0:this.#Le!==void 0&&(this.#Le.question=void 0,this.#Le.hideLinesWhileQuestion=!1),this.#fe=void 0,this.#Nt(),this.#Le!==void 0&&this.#vt(),this.#mn()}#gt(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#ht(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#ht(),i(e))};return this.#Rt(),this.#fe=t=>{t.type===`ctrl-c`&&this.#Tt(),e(t,settle,reject)},this.#Mt(),{promise:a,settle}}#_t(e){let t,n=new Promise(e=>{t=e});return this.#Je=t,this.#vt(e?.interruptible??!0),{promise:n,dispose:()=>{this.#Je===t&&(this.#Je=void 0,this.#yt())}}}#vt(e=!0){if(this.#Je===void 0)return;let consumer=t=>{if(e&&(t.type===`ctrl-c`||t.type===`escape`)){t.type===`ctrl-c`&&this.#Tt();let e=this.#Je;this.#Je=void 0,this.#yt(),e?.(t.type===`ctrl-c`?`ctrl-c`:`escape`);return}t.type===`ctrl-r`&&this.#mn()};this.#Ye=consumer,this.#Rt(),this.#fe=consumer,this.#Mt()}#yt(){this.#Ye!==void 0&&(this.#fe===this.#Ye&&this.#Nt(),this.#Ye=void 0)}#bt(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e),startedAtMs:Date.now()}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis),startedAtMs:Date.now()};if(this.#Le!==void 0){this.#Le.status=t,t===void 0&&(this.#Le.preview=void 0),this.#mn();return}if(!(this.#R||this.#G)){if(t===void 0){this.#K={kind:`idle`},this.#Y=void 0,this.#Gt(),this.#mn();return}this.#kt(),this.#Wt(),this.#Y=t.text,this.#mn()}}#xt(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Le;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.#mn();return}this.#kt(),this.#Kt({kind:`flow`,title:t,body:n,live:!1}),this.#mn()}#St(e){let t=this.#Le;t!==void 0&&(t.lines=[],t.outputBuffer=[],t.preview=void 0,t.status=void 0,t.summary=e===void 0?void 0:{headline:stripTerminalControls(e.headline),facts:e.facts.map(e=>({label:stripTerminalControls(e.label),value:stripTerminalControls(e.value)}))},this.#mn())}#Ct(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Le;if(n===void 0){this.#xt(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#mn()}async#wt(e){this.#pe=``,this.#Rt(),this.#Je=void 0,this.#yt(),this.#Nt(),this.#Gt(),this.#n.clear(),this.#In(),this.#r.enter({cursor:`visible`,mouse:!1}),this.#e.isTTY&&this.#e.setRawMode?.(!1),this.#e.pause();try{return await e()}finally{this.#r.exit(),this.#e.isTTY&&this.#e.setRawMode?.(!0),this.#e.resume(),this.#pe=``,this.#Rt(),this.#n.hideCursor(),this.#Fn(),this.#Le!==void 0&&(this.#Ut(),this.#vt()),this.#n.reset(),this.#mn()}}setSessionId(e){this.#We=e}shutdown(){if(this.#jt(),this.#Q&&!this.#$){this.#$=!0;let e=this.#We===void 0?``:` ${this.#i.glyph.dot} session ${this.#We}`;this.#t.write(`${this.#i.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}suspendPromptForInput(){this.#W={cursor:this.#I,text:this.#F},this.#jt()}requestInterrupt(){this.#ee=!0,this.#Le!==void 0&&this.#fe?.({type:`ctrl-c`}),this.#_e?.(),this.#jt()}exitRequested(){return this.#te}#Tt(){this.#te=!0,this.#ie?.()}async#Et(e){if(this.#Xe!==void 0||!this.#Z)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#Nn(),height:this.#Pn()}),paint:e=>this.#r.paint(e,this.#Pn()),tracingDisabled:process.env.EVE_TRACES===`off`,copyText:e=>copyTextToClipboard(e,e=>this.#r.writeRaw(e)),terminalBackground:this.#Ze});this.#Xe=t,this.#r.enter(),this.#i.color&&this.#r.writeRaw(BACKGROUND_COLOR_QUERY),await new Promise(e=>{this.#Ot=e,this.#fe=e=>{t.handleKey(e)===`close`&&this.#Dt()},this.#Mt(),t.start()})}#Dt(){let e=this.#Xe;if(e===void 0)return;this.#Xe=void 0,e.dispose(),this.#Nt(),this.#r.exit(),this.#n.hideCursor(),this.#mn(),this.#n.showCursor();let t=this.#Ot;this.#Ot=void 0,t?.()}#Ot;#kt(e){this.#X=e?.title??this.#X,e?.contextSize!==void 0&&(this.#Se=e.contextSize),!this.#Z&&(this.#Z=!0,this.#Q=!0,this.#n.reset(),this.#n.hideCursor(),this.#Fn(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#ge=()=>this.#mn(),this.#t.on(`resize`,this.#ge),process.on(`exit`,this.#At))}#At=()=>{this.#Z&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#jt(){this.#Dt();let e=this.#q;if(this.#q=void 0,e?.(interruptedError()),this.#Nt(),this.#Vt(),this.#Gt(),this.#ue!==void 0&&(clearTimeout(this.#ue),this.#ue=void 0),this.#de=!1,this.#Wn(),this.#Z){this.#Kn();for(let e of this.#m)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#mn(),this.#n.clear(),this.#n.showCursor(),this.#In(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#ge&&=(this.#t.off(`resize`,this.#ge),void 0),process.off(`exit`,this.#At),this.#Z=!1}}#Mt(){this.#e.off(`data`,this.#Pt),this.#e.on(`data`,this.#Pt),this.#pe.length>0&&queueMicrotask(()=>{this.#fe!==void 0&&this.#pe.length>0&&(this.#It(),this.#Ft())})}#Nt(){this.#e.off(`data`,this.#Pt),this.#Rt(),this.#fe=void 0}#Pt=e=>{this.#Rt(),this.#pe+=this.#me.write(e),this.#It(),this.#Ft()};#Ft(){if(this.#pe===`\x1B`){this.#he=setTimeout(()=>{this.#pe===`\x1B`&&(this.#pe=``,this.#fe?.({type:`escape`}))},30),this.#he.unref?.();return}if(isIncompletePaste(this.#pe)){let e=this.#pe;this.#he=setTimeout(()=>{if(this.#pe!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#pe=``,t.length>0&&this.#fe?.({type:`text`,value:t,framing:`bracketed-paste`})},incompletePasteFlushMs),this.#he.unref?.();return}if(isIncompleteOsc(this.#pe)){let e=this.#pe;this.#he=setTimeout(()=>{this.#pe===e&&(this.#pe=``)},incompletePasteFlushMs),this.#he.unref?.()}}#It(){for(;this.#pe.length>0;){let e=nextKey(this.#pe);if(e.incomplete)return;if(this.#pe=this.#pe.slice(e.consumed),e.key!==void 0&&e.key.type!==`ignore`){if(e.key.type===`osc`){this.#Lt(e.key.value);continue}this.#fe?.(e.key)}}}#Lt(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#Ze=t,this.#Xe?.setTerminalBackground(t))}#Rt(){this.#he&&=(clearTimeout(this.#he),void 0)}#zt(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#mn();break;case`enter`:{let e=this.#W.text;if(e.trim().length===0)break;if(parsePromptCommand(e)?.type===`cancel`&&this.#He!==void 0){this.#W=EMPTY_LINE,this.#Ve.requestCancellation(),this.#Ke=!0,this.renderCommandInvocation(e.trim()),this.renderCommandResult(`Turn cancellation requested.`),this.#He(),this.#mn();break}this.#Ve.enqueue(e)&&(this.#W=EMPTY_LINE),this.#mn();break}case`ctrl-c`:case`escape`:if(e.type===`ctrl-c`&&this.#Ve.view().cancelling){this.#ee=!0,this.#re=!0,this.#K={kind:`idle`},this.#J=`Interrupted`,this.#_e?.(),this.#mn();break}if(this.#Ve.idle&&this.#He===void 0)break;this.#Ve.handleEscape(),this.#Ke=!0,this.#He?.(),this.#mn();break;default:{let t=applyLineEditorKey(this.#W,e,{multiline:!0});t!==void 0&&(this.#W=t,this.#mn());break}}}#Bt(){this.#Vt(),this.#Ht(),this.#ce=setInterval(()=>{this.#ae=!this.#ae,this.#mn()},500),this.#ce.unref?.()}#Vt(){this.#ce&&=(clearInterval(this.#ce),void 0),this.#ae=!0}#Ht(){this.#ae=!0}#Ut(){this.#Gt(),this.#le=setInterval(()=>{this.#oe+=1,this.#mn()},90),this.#le.unref?.()}#Wt(){let e=Date.now();this.#se=e,this.#K={kind:`waiting`,startedAtMs:e},this.#Ut()}#Gt(){this.#le&&=(clearInterval(this.#le),void 0)}#Kt(e){e.id!==this.#Ae?.id&&this.#Kn(),e.updateSeq=++this.#b;let t=e.subagentCallId!==void 0&&this.#S.has(e.subagentCallId)?-1:this.#m.findIndex(e=>e.subagentCallId!==void 0&&this.#S.has(e.subagentCallId));t<0?this.#m.push(e):this.#m.splice(t,0,e),e.id&&this.#h.set(e.id,e)}#qt(e){this.#H=!0,this.#Kt({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#mn()}#Jt(){let e=this.#U.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#En(e.elapsedMs)}`,n=this.#xe??0;if(this.#Se!==void 0&&this.#Se>0&&n>0){let e=Math.round(n/this.#Se*100);t+=` ${this.#i.glyph.dot} ${e}% context`}this.#Kt({kind:`turn-stats`,body:t,live:!1})}#Yt(e){if(e==null)return;let t=this.#Ge;if(this.#Ge=void 0,this.#Fe===e){this.#Fe=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#Kt(n)}#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.#d?.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.#d===void 0?a:`details: ${this.#d.displayPath}`),this.#Kt(c),this.#mn()}#Zt(e,t){if(this.#T.has(e))return;this.#T.add(e);let n=stripTerminalControls(t),r=this.#x.get(n)??[];if(r.push(e),this.#x.set(n,r),r.length===2){let e=this.#h.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.#Kt(i)}#Qt(e){if(e.id&&this.#g.has(e.id))return;let t=e.id?this.#h.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#b;return}this.#Kt(e)}#$t(e){if(e.id&&this.#g.has(e.id))return;let t=e.id?this.#h.get(e.id):void 0;if(t!==void 0){Object.assign(t,e),t.updateSeq=++this.#b;return}let n=e.subagentCallId;if(n===void 0){this.#Kt(e);return}e.id!==this.#Ae?.id&&this.#Kn(),e.updateSeq=++this.#b;let r=-1;for(let e=0;e<this.#m.length;e+=1)this.#m[e]?.subagentCallId===n&&(r=e);this.#m.splice(r<0?this.#m.length:r+1,0,e),e.id!==void 0&&this.#h.set(e.id,e)}#en(e){this.#m=this.#m.filter(t=>t.id!==e),this.#h.delete(e)}#tn(){for(let e of this.#m)e.subagentCallId!==void 0&&this.#C.has(e.subagentCallId)||e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#nn(e,t,n){switch(e.type){case`step-finish`:this.#d?.recordStepUsage(e.usage),e.usage!==void 0&&this.#U.addUsage(e.usage),this.#ln(n),this.#pn(e.usage),this.#mn();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#rn(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=typeof e.text==`string`?stripTerminalControls(e.text):t;n.text.set(e.id,r),this.#rn(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.#in(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.#in(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#an({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#d?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#an({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.#an({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#fn(e.toolCallId,n);if(r===void 0)break;this.#an({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#fn(e.toolCallId,n);if(this.#d?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#an({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#fn(e.toolCallId,n);if(r===void 0)break;this.#an({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#Xt(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:if(n.cancelled=!0,!n.restoreCancelledPrompt)break;this.#Ue=!0,!this.#Ke&&this.#qe!==void 0&&this.#W.text.length===0&&(this.#W=lineOf(this.#qe),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#pn(e.usage),this.#mn()}}#rn(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#Qt({id:e,kind:`assistant`,body:r,live:n}),this.#mn())}#in(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Qt({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#mn())}#an(e,t,n){if(n.tools.set(e.toolCallId,e),this.#v.has(e.toolCallId)||this.#un(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#y.set(e.toolCallId,r);let i=this.#on(e);this.#Qt(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#dn(n),this.#mn()}#on(e){e.output!==void 0&&this.#w.observeRead(e.output);let t={};this.#sn(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.#w.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}#sn(e){let t=this.#E?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#cn(e){for(let t of e.tools.keys()){if(this.#v.has(t))continue;let e=this.#y.get(t)??toolSectionId(t),n=this.#h.get(e);n?.kind===`tool`&&n.status===`running`&&(n.status=`error`,n.result=`interrupted`,n.live=!1)}}#ln(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#y.get(t)??toolSectionId(t);this.#en(r),this.#y.delete(t)}}#un(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.#Be!==e&&(this.#Be=e,this.#Kt({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#Nn(),this.#i).join(`
`),live:!1})),this.#ze=void 0}else this.#ze=t.length>0?t:void 0,this.#Be=void 0;return this.#mn(),!0}#dn(e){let t=[];for(let n of e.tools.values()){if(this.#v.has(n.toolCallId))continue;let e=this.#y.get(n.toolCallId)??toolSectionId(n.toolCallId),r=this.#h.get(e);r?.kind===`tool`&&t.push({block:r,active:isActiveToolStatus(n.status)})}applyCohortLiveness(t)}#fn(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#y.get(e)??toolSectionId(e),i=this.#h.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`}}#pn(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#be=(t??0)+(n??0)),this.#xe=t??this.#xe,this.#Ce=n??this.#Ce,this.#Ce!=null&&this.#Te!==void 0){let e=(Date.now()-this.#Te)/1e3;e>0&&(this.#we=this.#Ce/e)}}#mn(){if(this.#Z){if(this.#ve){this.#ye=!0;return}this.#ve=!0;try{do this.#ye=!1,this.#hn();while(this.#ye)}finally{this.#ve=!1}}}#hn(){if(!this.#Z)return;if(this.#Xe!==void 0){this.#Xe.repaint();return}let e=this.#Nn(),t=this.#wn(e),n=this.#D===void 0?[]:this.#yn(),r=Math.max(1,this.#Pn()-n.length-t.length),i=[],a=this.#j,o=groupToolBlocksForDisplay(this.#m),s=0;for(;s<o.length&&o[s].display.live===!1;)s+=1;if(s>0){let e=new Set(o.slice(0,s).flatMap(e=>e.members));for(let t=this.#m.length-1;t>=0;--t)e.has(this.#m[t])&&this.#m.splice(t,1)}for(let t of o.slice(0,s)){for(let e of t.members)this.#_.push(e),e.id&&(this.#g.add(e.id),this.#h.delete(e.id));if(this.#Jn(t.display))continue;let n=this.#bn(t.display,e,a);a=previousBlockOf(t.display),this.#j=a,i.push(...n),this.#A.push(...n)}let c=[];for(let{display:t}of o.slice(s)){if(this.#Jn(t))continue;let n=this.#bn(t,e,a);a=previousBlockOf(t);for(let e=0;e<n.length;e+=1)c.push({block:t,row:n[e]})}let l=[...n,...clipLiveRows(c.map(e=>e.row),r,e,this.#i),...t];i.length>0?this.#n.flush(i,l):this.#n.update(l)}#gn(){if(!this.#Z)return;let e=this.#Nn(),t=this.#wn(e),n=Math.max(1,this.#Pn()-t.length),r=this.#j,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#m)){if(this.#Jn(t))continue;let n=this.#bn(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#i),...t];this.#n.clearAll(),this.#n.flush([...this.#yn(),...this.#A],a)}logDisplayMode(){return this.#p}setLogDisplayMode(e){e!==this.#p&&(this.#p=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#vn(),this.#Z&&this.#gn())}flushDelayedDevBuildErrors(){let e=this.#ke;e!==void 0&&(this.#ke=void 0,this.#Kt({kind:`log`,title:`stderr`,body:e,live:!0}),this.#mn())}#_n(){this.#de=!0,this.#ue!==void 0&&clearTimeout(this.#ue),this.#ue=setTimeout(()=>{this.#de=!1,this.#ue=void 0,this.#mn()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#p)),this.#mn()}#vn(){let e=this.#Nn();this.#A.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#_,{logCoalescing:`runs`})){if(this.#Jn(n))continue;let r=this.#bn(n,e,t);t=previousBlockOf(n),this.#A.push(...r)}this.#j=t}#yn(){let e=this.#E,t=this.#D;if(e===void 0&&t===void 0)return[];let n={name:e?.name??t?.name,theme:this.#i,width:this.#Nn()};e?.info!==void 0&&(n.info=e.info);let r=e?.tip??t?.tip;return r!==void 0&&(n.tip=r),buildAgentHeader(n)}#bn(e,t,n){let r={activityPulse:this.#Sn(this.#se,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#i,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#xn(){return this.#i.spinner[this.#oe%this.#i.spinner.length]??``}#Sn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#Cn(e,t){return e.indicator.kind===`spinner`?{glyph:this.#xn(),color:`yellow`}:{glyph:this.#Sn(e.indicator.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#wn(e){let t=this.#i.colors,n=[``];if(this.#Ie!==void 0)return n.push(...this.#Ie(e),``),this.#An(n,e),n;let r=this.#Le;if(r!==void 0){let t=this.#Cn(r,r.status),i;if(r.status!==void 0){let{startedAtMs:e,...n}=r.status,a=Date.now()-e,o=a>=5e3?` ${formatTurnDuration(a)}`:``;i={...n,text:`${n.text}${o}`,indicator:t}}let a;if(r.question!==void 0){let t=r.question(e);a={kind:`question`,rows:t},i!==void 0&&(a={kind:`question`,rows:t,status:i})}else i===void 0?a=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(a={kind:`status`,status:i},r.preview!==void 0&&(a={kind:`status`,status:i,preview:r.preview}));let o={title:r.title,navigation:r.navigation,lines:r.summary===void 0?r.hideLinesWhileQuestion===!0?[]:r.lines:[{text:r.summary.headline,tone:`success`},...r.summary.facts.map(e=>({text:`${e.label}: ${e.value}`,tone:`info`}))],content:a};return n.push(...renderFlowPanel(o,this.#i,e)),this.#jn(n,e),n}this.#Re!==void 0&&n.push(...renderAttentionRows(this.#Re,e,this.#i),``),this.#ze!==void 0&&n.push(...renderTodoPanelRows({items:this.#ze,width:e,theme:this.#i,working:this.#G||this.#K.kind===`waiting`,pulse:this.#Sn(this.#se,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}),``);let i=renderMessageQueueRows({view:this.#Ve.view(),width:e,theme:this.#i,working:this.#G});if(i.length>0&&n.push(...i,``),this.#R){let r=this.#z===void 0?void 0:inlineCommandHint(this.#z);r===void 0&&this.#z!==void 0&&isTypeaheadOpen(this.#z)&&n.push(...renderCommandSuggestions(this.#z,this.#i,e)),this.#ne&&n.push(clip(t.dim(`Press Ctrl+C again to exit`),e),``);let i=isPromptControlCommand(this.#F),a=r?t.dim(` ${r}`):``,o=[];this.#D!==void 0&&o.push(clip(t.dim(`${this.#i.glyph.dot} Building your agent…`),e)),this.#An(o,e);let s=Math.max(1,this.#Pn()-1-n.length-1-o.length),c={text:this.#F,cursor:this.#I,width:e,theme:this.#i,caretVisible:this.#ae,isCommand:i,ghost:a,maxRows:s};return this.#B&&this.#F.length===0&&(c.placeholder=this.#H?``:promptPlaceholder(Date.now()-this.#V)),n.push(...promptInputRows(c)),n.push(...o),n}let a=this.#K.kind===`waiting`&&this.#Y===void 0;if(this.#G||a){n.push(this.#Tn(e)),this.#On(n,e);let t=[];return this.#An(t,e),!this.#G&&t.length>0&&n.push(``),n.push(...t),n}if(this.#W.text.length>0)return this.#kn(n,e,{inert:!1}),this.#An(n,e),n;let o=this.#Y??(this.#J.length>0?this.#J:`Ready`),s=this.#Mn(),c=t.dim(this.#i.glyph.dot),l=s?`${c} ${o} ${t.dim(this.#i.glyph.dot)} ${s}`:`${c} ${o}`;return n.push(clip(l,e)),this.#An(n,e),n}#Tn(e){let t=this.#i.colors,n=this.#Sn(this.#se,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),r=this.#K,i=this.#U.startedAtMs??this.#Te??(r.kind===`waiting`?r.startedAtMs:Date.now()),a=Date.now()-i,o=`${typewriterText(`Working for`,a,80)} ${this.#En(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#En(e){return`${formatTurnDuration(e)}${this.#Dn()}`}#Dn(){let{inputTokens:e,outputTokens:t}=this.#U.usage;return e===0&&t===0?``:` ${this.#i.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#i.glyph)}`}#On(e,t){this.#G&&this.#kn(e,t,{inert:!0})}#kn(e,t,n){e.push(``);let r={text:this.#W.text,cursor:this.#W.cursor,width:t,theme:this.#i,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#W.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#An(e,t){let n=this.#P===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#i,width:r};this.#Me&&this.#je!==void 0&&(i.devBuild=this.#je),this.#de&&(i.logLevel=this.#p);let a=this.#E?.serverUrl;if(a!==void 0&&this.#P===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#E?.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.#N!==void 0&&(i.vercel=this.#N),this.#P!==void 0&&(i.remote=this.#P);let c=buildStatusLine(i);c!==void 0&&e.push(clip(`${n}${c}`,t))}#jn(e,t){if(this.#P===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#P,theme:this.#i,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Mn(){let e=this.#i.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#be,outputTokens:this.#Ce,tokensPerSecond:this.#we},this.#l);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#i.glyph.dot} `)):``}#Nn(){return Math.max(20,this.#t.columns||80)}#Pn(){return Math.max(8,this.#t.rows||24)}#Fn(){if(this.#Ee!==void 0||!this.#u)return;this.#De=``,this.#Oe=``;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.#Rn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#d?.subscribeLogRecords(e=>this.#Ln(e)),this.#Ee=()=>{this.#d?.unsubscribeLogRecords(),e(),t()}}#In(){let e=this.#Ee;e!==void 0&&(this.#Ee=void 0,e(),this.#De.length>0&&(this.#d?.append({source:`stdout`,detail:this.#De}),this.#qn(`stdout`)&&process.stdout.write(`${this.#De}\n`),this.#De=``),this.#Oe.length>0&&(this.#d?.append({source:`stderr`,detail:this.#Oe}),this.#qn(`stderr`)&&process.stderr.write(`${this.#Oe}\n`),this.#Oe=``))}#Ln(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#Bn(`[eve:${e.namespace}] ${e.message}${t}`),this.#mn()}#Rn(e,t){let n=(e===`stdout`?this.#De:this.#Oe)+t;if(e===`stdout`&&parseDevRebuildLogLine(n.trimEnd())!==void 0){this.#De=``,this.#d?.append({source:e,detail:n.trimEnd()}),this.#zn(n.trimEnd()),this.#mn();return}let r=n.lastIndexOf(`
`),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#De=i:this.#Oe=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#d?.append({source:e,detail:a}),e===`stdout`?this.#zn(a):this.#Bn(a),this.#mn())}#zn(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
`);t=[],e.trim().length!==0&&this.#Kt({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.#Kt({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#Hn(r,n.trimEnd())}flushPending()}#Bn(e){let t=e.split(`
`),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#d===void 0){this.#Kt({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#d.displayPath);if(t.kind===`inline`){this.#Kt({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#Kt({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#Kt({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
`);r.trim().length>0&&this.#Kt({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
`);this.#Vn(i)}#Vn(e){if(this.#Wn(),this.#p===`all`){if(e.trim().length===0)return;this.#Kt({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#ke=e}#Hn(e,t){let n=this.#Gn();if(e.kind===`failed`){this.#Vn(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(this.#Un({phase:`building`,summary:t}),n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#Pe}`;this.#Pe+=1,this.#Ae={id:r,summary:t},this.#Kt({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}let r=n?.state.summary??this.#je?.summary;if(r!==void 0&&this.#Un({phase:`complete`,summary:r}),n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#ke=void 0);return}e.kind===`rebuilt`&&(this.#ke=void 0),this.#Kt({kind:`log`,title:`stdout`,body:t,live:!0})}#Un(e){this.#Ne!==void 0&&clearTimeout(this.#Ne),this.#je=e,this.#Me=e.phase===`complete`,this.#Ne=setTimeout(()=>{e.phase===`building`?(this.#Me=!0,this.#Ne=void 0):this.#Wn(),this.#mn()},e.phase===`building`?250:4e3)}#Wn(){this.#Ne!==void 0&&clearTimeout(this.#Ne),this.#je=void 0,this.#Me=!1,this.#Ne=void 0}#Gn(){let e=this.#Ae;if(e===void 0)return;let t=this.#h.get(e.id);if(t!==void 0&&t.live===!0)return{state:e,block:t}}#Kn(){let e=this.#Ae;if(e===void 0)return;this.#Ae=void 0;let t=this.#h.get(e.id);t!==void 0&&(t.live=!1)}#qn(e){switch(this.#p){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#Jn(e){return e.kind===`sandbox`?!this.#qn(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#p!==`stderr`:e.logVisibility===`all-only`?this.#p!==`all`:!this.#qn(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:stripTerminalControls(i.subtitle),status:e.status,live:e.status===`running`||e.status===`approval`,expanded:n,toolInput:e.input,toolName:e.toolName,toolGroup:i.group};return i.doneTitle!==void 0&&(a.doneTitle=stripTerminalControls(i.doneTitle)),i.detail!==void 0&&(a.detailLines=i.detail,a.keepDetailWhenDone=i.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(a.result=stripTerminalControls(e.errorText)):(a.result=i.summarizeResult(e.output),a.toolOutput=e.output),a}function writeExistedFlag(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.existed;return typeof t==`boolean`?t:void 0}function subagentToolStatus(e){switch(e){case`preparing`:return`running`;case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`;case`rejected`:return`denied`}}function formatToolApprovalTitle(e){return stripTerminalControls(e.title??e.toolName)}function toolSectionId(e){return`tool:${e}`}function questionSectionId(e){return`question:${e}`}function subagentHeaderId(e){return`subagent:${e}:header`}function subagentStepSectionId(e,t){return`subagent:${e}:step:${t}`}function subagentToolSectionId(e,t){return`subagent:${e}:tool:${t}`}function connectionAuthSectionId(e){return`connection-auth:${e}`}function connectionAuthTerminalMessage(e){switch(e){case`authorized`:return`Authorization complete`;case`declined`:return`Authorization declined`;case`failed`:return`Authorization failed`;case`timed-out`:return`Authorization timed out`;case`required`:case`pending`:return}}function formatConnectionAuthContent(e,t){let n=[];if(t!==void 0)n.push(t);else{let t=stripTerminalControls(e.description);t.length>0&&n.push(t);let r=e.challenge;r?.url&&n.push(`URL: ${stripTerminalControls(r.url)}`),r?.userCode&&n.push(`Code: ${stripTerminalControls(r.userCode)}`),r?.expiresAt&&n.push(`Expires: ${stripTerminalControls(r.expiresAt)}`),r?.instructions&&n.push(stripTerminalControls(r.instructions))}if(e.reason!==void 0){let t=stripTerminalControls(e.reason);t.length>0&&n.push(`Reason: ${t}`)}return n.join(`
`)}function formatQuestionContent(e,t,n){let r=n.colors,i=[],a=e.options??[];if(a.length>0){for(let[e,o]of a.entries()){let a=stripTerminalControls(o.label),s=o.description===void 0?``:stripTerminalControls(o.description),c=t===e,l=s.length>0?`${c?` `:` `}${r.dim(`— ${s}`)}`:``,u=c?`${n.glyph.selectedPointer} ${a}`:` ${a}`,d=renderCursorRow(u,c,r);i.push(`${d}${l}`)}if(e.allowFreeform===!0){let e=t===a.length,o=`Type your own answer`,s=e?`${n.glyph.selectedPointer} ${o}`:` ${r.dim(o)}`;i.push(renderCursorRow(s,e,r))}}else i.push(r.dim(` (type your answer)`));return i.join(`
`)}function resolveQuestionText(e,t){let n=e.trim();if(n.length===0)return;let r=n.toLowerCase(),i=t.options??[];if(i.length>0){let e=matchQuestionOption(r,i);if(e!==void 0)return{optionId:e.id,label:e.label}}if(t.allowFreeform===!0||i.length===0)return{text:n,label:n}}function matchQuestionOption(e,t){let n=t.find(t=>t.id.toLowerCase()===e);if(n!==void 0)return n;let r=t.find(t=>t.label.toLowerCase()===e);if(r!==void 0)return r;let i=Number(e);if(Number.isInteger(i)&&i>0&&i<=t.length)return t[i-1]}export{TerminalRenderer};