eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
14 lines • 65.1 kB
JavaScript
import{buildAgentHeader}from"./agent-header.js";import{detectMarkdownRendering}from"./markdown.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.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,KillRing,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{enterBadge,flowMessageRows,renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{initialModelPickerState,modelPickerTitle,renderModelPicker,transitionModelPicker}from"./model-picker.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompleteOsc,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil}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{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`}function turnActivityLabel(e){return e===void 0?`Thinking`:e.runningTools.size>0?`Running`:e.modelActivity}function updateTurnActivity(e,t){switch(t.type){case`turn-start`:case`step-start`:case`reasoning-delta`:e.modelActivity=`Thinking`;break;case`assistant-delta`:case`tool-call-preparing`:e.modelActivity=`Generating`;break;case`assistant-complete`:t.text?.trim()&&(e.modelActivity=`Generating`);break;case`tool-call`:e.runningTools.add(t.toolCallId),e.modelActivity=`Thinking`;break;case`tool-result`:case`tool-error`:case`tool-rejected`:e.runningTools.delete(t.toolCallId)}}const incompletePasteFlushMs=1e3,STATUS={processing:`Thinking`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h=[];#g=new Map;#_=new Set;#v=[];#y=new Set;#b=new Map;#x=0;#S=new Map;#C=new Set;#w=new Set;#T=new FileContentCache;#E=new Set;#D;#O;#k;#A;#j=0;#M;#N=!1;#P;#F=[];#I;#L=0;#R;#z;#B=``;#V=0;#H=new PromptHistory;#U=new KillRing;#W=!1;#G;#K=!1;#q=!1;#J=new TurnClock;#Y;#X=EMPTY_LINE;#Z=!1;#Q={kind:`idle`};#$;#ee=STATUS.processing;#te;#ne=`eve`;#re=!1;#ie=!1;#ae=!1;#oe=!1;#se=!1;#ce=!1;#le=!1;#ue;#de=!0;#fe=0;#pe=Date.now();#me;#he;#ge;#_e=!1;#ve;#ye=``;#be=new StringDecoder(`utf8`);#xe;#Se;#Ce;#we=!1;#Te=!1;#Ee;#De;#Oe;#ke;#Ae;#je;#Me;#Ne=``;#Pe=``;#Fe;#Ie;#Le;#Re=!1;#ze;#Be=0;#Ve;#He;#Ue;#We;#Ge;#Ke;#qe=new MessageQueue;#Je;#Ye;#Xe=!1;#Ze;#Qe;#$e=!1;#et;#tt;#nt;#rt;#it;setupFlow={begin:(e,t)=>this.#dt(e,t),setNavigation:e=>this.#ft(e),end:e=>this.#pt(e?.preserveDiagnostics??!0),readSelect:e=>this.#mt(e),readEditableSelect:e=>this.#gt(e),readProviderPicker:e=>this.#_t(e),readModelPicker:e=>this.#vt(e),readText:e=>this.#yt(e),readAcknowledge:e=>this.#bt(e),readChoice:e=>this.#ht(e),setStatus:e=>this.#Ot(e),renderLine:(e,t)=>this.#kt(e,t),replaceContent:e=>this.#At(e),renderOutput:e=>this.#jt(e),withInheritedStdio:e=>this.#Mt(e),withExclusiveTerminal:e=>this.#Mt(e),waitForInterrupt:e=>this.#Tt(e)};traceViewer={open:e=>this.#Pt(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?.renderMarkdown??detectMarkdownRendering(),this.#o=e?.tools??`auto-collapsed`,this.#s=e?.reasoning??`auto-collapsed`,this.#c=e?.subagents??`auto-collapsed`,this.#l=e?.connectionAuth??`full`,this.#u=e?.assistantResponseStats??`tokensPerSecond`,this.#Oe=e?.contextSize,this.#d=e?.captureForeignOutput??this.#t===process.stdout,this.#f=e?.diagnostics,this.#ue=e?.onExitRequest,this.#m=e?.logs??`none`,this.#p=e?.availablePromptCommands??PROMPT_COMMANDS}setStartupPhase(e){this.#O=e,e===void 0?this.#tn():this.#$t(),this.#Dn()}renderAgentHeader(e){this.#M=void 0,this.#ne=e.name,(this.#D?.info?.agent.model.routing.kind!==`dynamic`||e.info?.agent.model.routing.kind!==`dynamic`)&&(this.#Ge=void 0),this.#D=e,this.#Lt();let t=this.#Mn().join(`
`);if(this.#N){t!==this.#P&&(this.#P=t,this.#an({kind:`agent-header`,body:t,live:!1})),this.#Dn();return}this.#N=!0,this.#P=t,this.#n.flush(this.#Mn(),this.#Ln(this.#Kn()))}beginStartupDraft(e){this.#Lt({title:e.title}),this.#W=!0,this.#K=!0,this.#O=`starting`,this.#M={name:e.title},this.#j=Date.now();let t=lineOf(stripPromptControlCharacters(e.initialDraft??``));this.#k=t,this.#ot(t),this.#Xt(),this.#$t(),this.#Dn();let apply=e=>{t=e,this.#k=e,this.#Qt(),this.#ot(t),this.#Dn()};this.#A=e=>{if(e.type===`escape`&&this.#tt!==void 0){this.#tt(`escape`);return}if(e.type===`ctrl-c`&&this.#tt!==void 0){this.#Nt(),this.#tt(`ctrl-c`);return}let n=this.#U.apply(t,e,{multiline:!0});if(n!==void 0){apply(n);return}if(e.type===`enter`&&t.text.trim().length>0){this.#qe.enqueue(t.text)&&apply(EMPTY_LINE);return}e.type===`ctrl-c`&&this.#ue?.()},this.#at()}#at(){this.#k!==void 0&&this.#A!==void 0&&(this.#qt(),this.#ot(this.#k),this.#W=!0,this.#ve=this.#A,this.#Bt())}finishStartupDraft(){let e={draft:this.#k?.text??this.#B,queuedPrompt:this.#qe.takePrompt()};return this.#k=void 0,this.#A=void 0,this.#Vt(),this.#Zt(),this.#W=!1,this.#K=!1,e}async readPrompt(e){this.#Lt(e),this.#in(),this.#sn(),this.#W=!0,this.#K=!0,this.#Q={kind:`idle`},this.#ee=``,this.#ce=this.#le,this.#le=!1;let t=this.#qe.restoreDraft()?.split(`
`).map(stripPromptControlCharacters).join(`
`),n=stripPromptControlCharacters(e?.initialDraft??this.#X.text),r=t===void 0?n:n.length===0?t:`${t}\n\n${n}`,i=lineOf(r);return this.#X=EMPTY_LINE,this.#H.begin(i.text),this.#ot(i),this.#G=typeaheadFor(this.#p,i.text),this.#Xt(),this.#Dn(),await new Promise((e,t)=>{this.#$=t;let apply=e=>{i=e,this.#Qt(),this.#ot(i),this.#G=typeaheadFor(this.#p,e.text,this.#G),this.#Dn()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#G=void 0,this.#Zt(),this.#zt(),t(interruptedError())},suggestions=()=>this.#G!==void 0&&isTypeaheadOpen(this.#G)?this.#G:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ve=t=>{t.type!==`ctrl-c`&&this.#ce&&(this.#ce=!1,this.#Dn());let n=this.#U.apply(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.#G=moveTypeaheadSelection(e,-1),this.#Dn();break}let t=movePromptLine(i,`up`);t===void 0?recall(this.#H.previous(i.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#G=moveTypeaheadSelection(e,1),this.#Dn();break}let t=movePromptLine(i,`down`);t===void 0?recall(this.#H.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.#G=dismissTypeahead(e),this.#Dn());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.#G=void 0,this.#H.add(n),this.#W=!1,this.#Zt(),this.#ee=STATUS.processing,isPromptControlCommand(n)?this.#an({kind:`command`,body:stripTerminalControls(n.trim()),live:!1}):(this.#en(),this.#on(n),this.#Ve=n,this.#J.arm()),this.#ot(EMPTY_LINE),this.#Dn(),this.#Vt(),e(n);break}case`ctrl-d`:i.text.length===0?(this.#Nt(),interrupt()):apply(deleteForward(i));break;case`ctrl-l`:this.#An();break;case`ctrl-r`:this.#Dn();break;case`ctrl-c`:if(this.#ce){this.#Nt(),interrupt();break}this.#ce=!0,apply(EMPTY_LINE)}},this.#Bt()})}#ot(e){this.#B=e.text,this.#V=e.cursor}takeQueuedPrompt(){let e=this.#qe.view().steering,t=this.#qe.takePrompt();return t!==void 0&&(this.#Qe=e?`steer`:`queue`),t}async renderStream(e,t){this.#Lt(t),this.#_.clear(),this.#W=!1,this.#Q.kind!==`waiting`&&(this.#Q={kind:`waiting`,startedAtMs:Date.now()}),this.#ee=this.#L>0?STATUS.connectionAuth:STATUS.processing,this.#cn(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#f?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#J.armed&&this.#J.arm(),this.#oe=!1,this.#Xe=!1,this.#$e=!1,this.#et=t?.submittedPrompt,this.#qe.beginTurn(),this.#Je=e.cancel,this.#Ye=e.steer,this.#Ee=void 0,this.#De=void 0,this.#ke=void 0,this.#Ae=void 0,this.#je=Date.now();let n={text:new Map,reasoning:new Map,tools:new Map,modelActivity:`Thinking`,runningTools:new Set,cancelled:!1,restoreCancelledPrompt:!0};this.#Y=n;let r={tools:t?.tools??this.#o,reasoning:t?.reasoning??this.#s,assistantResponseStats:t?.assistantResponseStats??this.#u};this.#$t(),this.#Z=!0,this.#Dn();let i=new Promise(e=>{this.#Ce=e});this.#ve=e=>this.#Jt(e),this.#Bt();try{for await(let t of takeUntil(iterateTUIStream(e.events),i)){if(this.#oe)break;this.#gn(t,r,n)}}catch(e){let t=summarizeKnownError(e);t===null?this.#ln(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#ln(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#Ce=void 0,this.#oe&&e.abort?.(),this.#Je=void 0,this.#Ye=void 0,this.#Vt(),this.#Z=!1,this.#Y=void 0,this.#Q.kind===`waiting`&&(this.#Q={kind:`idle`}),this.#in(),this.#ee=completedTurnStatus({interrupted:this.#oe,cancelled:this.#Xe,continueSession:t?.continueSession===!0}),this.#Cn(n),(this.#oe||n.cancelled)&&this.#Sn(n),this.#hn(),this.#in(),this.#f?.reportStats(),this.#Dn(),t?.continueSession||this.#zt()}}async renderIdleStream(e,t){let n={tools:t?.tools??this.#o,reasoning:t?.reasoning??this.#s,assistantResponseStats:t?.assistantResponseStats??this.#u},r={text:new Map,reasoning:new Map,tools:new Map,modelActivity:`Thinking`,runningTools:new Set,cancelled:!1,restoreCancelledPrompt:!1};try{for await(let t of iterateTUIStream(e.events))this.#gn(t,n,r)}catch(e){let t=summarizeKnownError(e);t===null?this.#ln(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#ln(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#Cn(r),r.cancelled&&this.#Sn(r),this.#hn(),this.#in(),this.#f?.reportStats(),this.#Dn()}}async readToolApproval(e,t){return this.#Lt(t),this.#tn(),this.#W=!1,this.#Q={kind:`idle`},this.#ee=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#oe=!1,this.#Dn(),await new Promise((t,n)=>{this.#$=n,this.#ve=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#en(),this.#ee=STATUS.processing,this.#Vt(),this.#Dn(),t({approved:!0})):n===`n`&&(this.#en(),this.#ee=STATUS.processing,this.#ct(e.toolCallId),this.#Vt(),this.#Dn(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#Dn();break;case`ctrl-c`:this.#oe=!0,this.#zt(),n(interruptedError())}},this.#Bt()})}async readInputQuestion(e,t){this.#Lt(t),this.#tn(),this.#W=!1,this.#K=!1,this.#Q={kind:`idle`},this.#oe=!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.#de},this.#i,t),renderTextSection=()=>{this.#dn({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#Xt():(this.#Zt(),this.#Qt())};s===`overlay`?(s=`overlay`,this.#W=!1,this.#pn(o),this.#He=overlayPanel,this.#ee=``,syncFreeformCaret(),this.#Dn()):(s=`text`,this.#He=void 0,renderTextSection(),this.#W=!0,this.#ot(l),this.#ee=``,this.#Xt(),this.#Dn());let finalize=t=>{this.#He=void 0,this.#dn({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.#W=!1,this.#en(),this.#ee=STATUS.processing,this.#Zt(),this.#Vt(),this.#Dn();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#He=void 0,this.#dn({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Skipped. The question stays open.`)}`,preformatted:!0,live:!1}),this.#W=!1,this.#ee=``,this.#Zt(),this.#Vt(),this.#Dn(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#Dn())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#$=r,u=t,this.#ve=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#Qt(),s===`text`&&this.#ot(l),this.#Dn();return}this.#oe=!0,this.#He=void 0,this.#Zt(),this.#zt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#Dn();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.#Qt(),this.#Dn();break}dismiss();break;default:if(isOnFreeformRow()){let e=this.#U.apply(l,t);e!==void 0&&(l=e,this.#Qt(),this.#Dn());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.#Dn())}}return}let a=this.#U.apply(l,t,{multiline:!0});if(a!==void 0){l=a,this.#Qt(),this.#ot(l),this.#Dn();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Qt(),this.#ot(l),this.#Dn());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.#Qt(),this.#ot(l),this.#Dn();break}dismiss()}},this.#Bt()})}upsertSubagentStep(e){if(this.#f?.recordSubagentDispatch(e.callId),this.#c===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(t.length!==0||n.length!==0){if(this.#un(e.callId,e.subagentName),this.#c===`collapsed`){this.#Dn();return}this.#fn({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#c!==`full`,live:!e.finalized}),this.#Dn()}}upsertSubagentTool(e){if(this.#f?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#f?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#c===`hidden`)return;if(this.#un(e.callId,e.subagentName),this.#c===`collapsed`){this.#Dn();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#bn({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.#c===`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.#fn(r),this.#st(e.callId),this.#Dn()}#st(e){applyCohortLiveness(this.#h.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#pn(subagentToolSectionId(e.callId,e.childCallId)),this.#Dn()}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.#c===`hidden`)return;this.#un(e.callId,e.name);let t=this.#g.get(subagentHeaderId(e.callId));t!==void 0&&(t.status===`done`&&delete t.status,t.live=!0),this.#w.delete(e.callId),this.#Dn()}backgroundSubagent(e){let t=this.#g.get(subagentHeaderId(e.callId));if(t===void 0||this.#_.has(subagentHeaderId(e.callId)))return;t.status=`running`,t.live=!0,t.updateSeq=++this.#x;let n=this.#C.has(e.callId);this.#C.add(e.callId),n||this.#mn(e.callId),this.#in(),this.#Dn()}completeSubagent(e){let t=this.#g.get(subagentHeaderId(e.callId));if(t!==void 0){if(t.status=`done`,e.authoritative){this.#C.delete(e.callId),this.#w.delete(e.callId);for(let t of this.#h)t.subagentCallId===e.callId&&(t.live=!1)}else{this.#w.add(e.callId);for(let t of this.#h)t.subagentCallId===e.callId&&(t.live=!0)}this.#in(),this.#Dn()}}markChildToolCallId(e){this.#y.add(e);let t=this.#b.get(e);t!==void 0&&(this.#pn(t),this.#b.delete(e),this.#Dn())}#ct(e){let t=this.#g.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#l===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#dn({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.#Dn()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#L)return;let n=this.#L>0;this.#L=t,t>0?(this.#ee=STATUS.connectionAuth,this.#Dn()):n&&(this.#ee=STATUS.processing,this.#Dn())}setVercelStatus(e){this.#R=e,this.#Dn()}setRemoteConnectionStatus(e){this.#z=e,this.#Dn()}reset(){this.#h=[],this.#g.clear(),this.#_.clear(),this.#I=void 0,this.#F.length=0,this.#v.length=0,this.#N=!1,this.#P=void 0,this.#lt(),this.#q=!1,this.#Ve=void 0,this.#Ie=void 0,this.#L=0,this.#Ee=void 0,this.#De=void 0,this.#ke=void 0,this.#Ae=void 0,this.#je=void 0,this.#re&&(this.#n.clearAll(),this.#Dn())}renderSessionBoundary(){this.#sn(),this.#lt();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#an({kind:`session-boundary`,body:n,live:!1}),this.#Dn()}#lt(){this.#Ge=void 0,this.#Ke=void 0,this.#y.clear(),this.#b.clear(),this.#E.clear(),this.#C.clear(),this.#w.clear(),this.#S.clear(),this.#qe.reset(),this.#Qe=void 0,this.#T.clear(),this.#J.reset(),this.#in()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Lt(),this.#an({kind:`notice`,body:t,live:!1}),this.#Dn())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#ut();return}this.#Lt(),this.#We=t,this.#Dn()}clearSetupWarning(){this.#ut()}#ut(){this.#We!==void 0&&(this.#We=void 0,this.#Dn())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#Lt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#an(r),this.#Dn()}renderCommandResult(e,t){let n=stripAnsi(e);n.trim().length!==0&&(this.#Lt(),this.#an({kind:`result`,body:n,live:!1,status:t===`success`?`done`:void 0}),this.#Dn())}#dt(e,t=`spinner`){this.#Lt(),this.#k===void 0&&(this.#W=!1),this.#Q={kind:`idle`},this.#ee=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ue={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#$t(),this.#Dn()}#ft(e){this.#Ue!==void 0&&(this.#Ue.navigation=e,this.#Dn())}#pt(e){this.#tt=void 0,this.#Dt();let t=this.#Ue;if(t!==void 0){if(this.#Ue=void 0,this.#k===void 0?this.#tn():this.#at(),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.#an({kind:`flow`,title:`info`,body:e.join(`
`),live:!1}),this.#an({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#Dn()}}async#mt(e){let t=this.#xt(e.message),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.#Dn()},loadSearch=async(e,t)=>{l=!0,c=void 0;let o=++u;this.#Dn();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.#Dn())}},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,message:``,options:i,select:s};return d!==void 0&&d.length>0&&(t.notices=d),c!==void 0&&(t.error=c),l&&(t.loadingFrame=this.#Pn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#Dn(),await this.#wt((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.#Dn();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.#Dn();return;case`update`:s=m.select,c=void 0,this.#Dn();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.#Dn();return;case`ignore`:return}}).promise}#ht(e){this.#Lt();let t=this.#St();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.#Dn();let r=this.#wt((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.#Dn();return;case`repaint`:this.#Dn();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#gt(e){let t=this.#xt(e.message),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:``,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#de,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.#Xt():(i=lineOf(``),this.#Zt())};return syncEditableRow(),this.#Dn(),await this.#wt((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Qt(),this.#Dn()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#Dn()},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.#Dn();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.#Dn();return;case void 0:}if(!onEditableRow())return;let s=this.#U.apply(i,t);s!==void 0&&applyEditor(s)},()=>this.#Zt()).promise}async#_t(e){this.#U.clear();let t=this.#xt(e.message),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:``,options:e.options,select:n.select,edit:{optionValue:`ai-gateway-key`,caretVisible:this.#de,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.#Xt():this.#Zt()};return syncCaret(),this.#Dn(),await this.#wt((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.#Dn();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#Dn();return;case`validate`:{n=o.state,syncCaret(),this.#Dn();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.#Dn();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.#Qt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Zt()}).promise}async#vt(e){let t=initialModelPickerState(e),n=this.#xt(modelPickerTitle(t));return n.question=n=>renderModelPicker(e,t,this.#i,n),this.#Dn(),await this.#wt((r,i)=>{let dispatch=r=>{let a=transitionModelPicker(t,r,e);switch(a.kind){case`render`:if(t===a.state)return;t=a.state,n.questionTitle=modelPickerTitle(t),this.#Dn();return;case`cancel`:i(void 0);return;case`settle`:i(a.result);return}};if(r.type===`ctrl-c`){dispatch({type:`cancel`});return}if(r.type===`escape`||r.type===`left`){dispatch({type:`back`});return}let a=setupSelectionIntent(r);switch(a?.kind){case`move`:dispatch({type:a.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#Dn();return}if(r.type===`backspace`){dispatch({type:`backspace`});return}if(r.type===`alt-backspace`){dispatch({type:`delete-word-backward`});return}if(r.type===`text`)for(let e of r.value.replaceAll(`
`,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#yt(e){e.mask===!0&&this.#U.clear();let t=this.#xt(e.message),n=lineOf(``),r;return t.question=t=>{let i={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.#de)},this.#Xt(),this.#Dn(),await this.#wt((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Qt(),this.#Dn()},a=e.mask?applyLineEditorKey(n,t):this.#U.apply(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.#Dn();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#Dn();return}i(t);return}default:return}},()=>this.#Zt()).promise}async#bt(e){let t=this.#xt(e.message);return t.question=t=>renderAcknowledgeQuestion({message:``,lines:e.lines},this.#i,t),this.#Dn(),await this.#wt((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#Dn();return;default:return}}).promise}#xt(e){this.#Lt(),this.#W=!1,this.#Q={kind:`idle`},this.#ee=``;let t=this.#St();return t.questionTitle=stripTerminalControls(e),t.status!==void 0&&(t.status=void 0,t.summary=void 0,t.preview=void 0),t}#St(){return this.#Ue===void 0&&(this.#Ue={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Ue}#Ct(){this.#Ue?.implicit===!0?this.#Ue=void 0:this.#Ue!==void 0&&(this.#Ue.question=void 0,this.#Ue.questionTitle=void 0,this.#Ue.hideLinesWhileQuestion=!1),this.#ve=void 0,this.#Vt(),this.#k===void 0?this.#Ue!==void 0&&this.#Et():this.#at(),this.#Ue===void 0&&this.#Dn()}#wt(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Ct(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Ct(),i(e))};return this.#qt(),this.#ve=t=>{t.type===`ctrl-c`&&this.#Nt(),e(t,settle,reject)},this.#Bt(),{promise:a,settle}}#Tt(e){let t,n=new Promise(e=>{t=e});return this.#tt=t,this.#Et(e?.interruptible??!0),{promise:n,dispose:()=>{this.#tt===t&&(this.#tt=void 0,this.#Dt())}}}#Et(e=!0){if(this.#k!==void 0){this.#at();return}if(this.#tt===void 0)return;let consumer=t=>{if(e&&(t.type===`ctrl-c`||t.type===`escape`)){t.type===`ctrl-c`&&this.#Nt();let e=this.#tt;this.#tt=void 0,this.#Dt(),e?.(t.type===`ctrl-c`?`ctrl-c`:`escape`);return}t.type===`ctrl-r`&&this.#Dn()};this.#nt=consumer,this.#qt(),this.#ve=consumer,this.#Bt()}#Dt(){this.#nt!==void 0&&(this.#ve===this.#nt&&this.#Vt(),this.#nt=void 0)}#Ot(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.#Ue!==void 0){this.#Ue.status=t,t===void 0&&(this.#Ue.preview=void 0),this.#Dn();return}if(!(this.#W||this.#Z)){if(t===void 0){this.#Q={kind:`idle`},this.#te=void 0,this.#tn(),this.#Dn();return}this.#Lt(),this.#en(),this.#te=t.text,this.#Dn()}}#kt(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Ue;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.#Dn();return}this.#Lt(),this.#an({kind:`flow`,title:t,body:n,live:!1}),this.#Dn()}#At(e){let t=this.#Ue;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.#Dn())}#jt(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Ue;if(n===void 0){this.#kt(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#Dn()}async#Mt(e){this.#ye=``,this.#qt(),this.#tt=void 0,this.#Dt(),this.#Vt(),this.#nn(),this.#n.clear(),this.#Yn(),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.#ye=``,this.#qt(),this.#n.hideCursor(),this.#Jn(),this.#Ue===void 0?this.#in():(this.#$t(),this.#Et()),this.#n.reset(),this.#Dn()}}setSessionId(e){this.#Ze=e}shutdown(){if(this.#zt(),this.#ie&&!this.#ae){this.#ae=!0;let e=this.#Ze===void 0?``:` ${this.#i.glyph.dot} session ${this.#Ze}`;this.#t.write(`${this.#i.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}suspendPromptForInput(){this.#X={cursor:this.#V,text:this.#B},this.#zt()}requestInterrupt(){this.#oe=!0,this.#Ue!==void 0&&this.#ve?.({type:`ctrl-c`}),this.#Ce?.(),this.#zt()}exitRequested(){return this.#se}#Nt(){this.#se=!0,this.#ue?.()}async#Pt(e){if(this.#rt!==void 0||!this.#re)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#Kn(),height:this.#qn()}),paint:e=>this.#r.paint(e,this.#qn()),tracingDisabled:process.env.EVE_TRACES===`off`,copyText:e=>copyTextToClipboard(e,e=>this.#r.writeRaw(e)),terminalBackground:this.#it});this.#rt=t,this.#r.enter(),this.#i.color&&this.#r.writeRaw(BACKGROUND_COLOR_QUERY),await new Promise(e=>{this.#It=e,this.#ve=e=>{t.handleKey(e)===`close`&&this.#Ft()},this.#Bt(),t.start()})}#Ft(){let e=this.#rt;if(e===void 0)return;this.#rt=void 0,e.dispose(),this.#Vt(),this.#r.exit(),this.#n.hideCursor(),this.#Dn(),this.#n.showCursor();let t=this.#It;this.#It=void 0,t?.()}#It;#Lt(e){this.#ne=e?.title??this.#ne,e?.contextSize!==void 0&&(this.#Oe=e.contextSize),!this.#re&&(this.#re=!0,this.#ie=!0,this.#n.reset(),this.#n.hideCursor(),this.#Jn(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#Se=()=>this.#Dn(),this.#t.on(`resize`,this.#Se),process.on(`exit`,this.#Rt))}#Rt=()=>{this.#re&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#zt(){this.#Ft();let e=this.#$;if(this.#$=void 0,e?.(interruptedError()),this.#Vt(),this.#Zt(),this.#nn(),this.#ge!==void 0&&(clearTimeout(this.#ge),this.#ge=void 0),this.#_e=!1,this.#rr(),this.#re){this.#ar();for(let e of this.#h)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#Dn(),this.#n.clear(),this.#n.showCursor(),this.#Yn(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#Se&&=(this.#t.off(`resize`,this.#Se),void 0),process.off(`exit`,this.#Rt),this.#re=!1}}#Bt(){this.#e.off(`data`,this.#Ht),this.#e.on(`data`,this.#Ht),this.#ye.length>0&&queueMicrotask(()=>{this.#ve!==void 0&&this.#ye.length>0&&(this.#Gt(),this.#Ut())})}#Vt(){this.#e.off(`data`,this.#Ht),this.#qt(),this.#ve=void 0}#Ht=e=>{this.#qt(),this.#ye+=this.#be.write(e),this.#Gt(),this.#Ut()};#Ut(){if(this.#ye===`\x1B`){this.#xe=setTimeout(()=>{this.#ye===`\x1B`&&(this.#ye=``,this.#Wt({type:`escape`}))},30),this.#xe.unref?.();return}if(isIncompletePaste(this.#ye)){let e=this.#ye;this.#xe=setTimeout(()=>{if(this.#ye!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#ye=``,t.length>0&&this.#Wt({type:`text`,value:t,framing:`bracketed-paste`})},incompletePasteFlushMs),this.#xe.unref?.();return}if(isIncompleteOsc(this.#ye)){let e=this.#ye;this.#xe=setTimeout(()=>{this.#ye===e&&(this.#ye=``)},incompletePasteFlushMs),this.#xe.unref?.()}}#Wt(e){this.#U.interruptYank(e),this.#ve?.(e)}#Gt(){for(;this.#ye.length>0;){let e=nextKey(this.#ye);if(e.incomplete)return;if(this.#ye=this.#ye.slice(e.consumed),e.key!==void 0&&e.key.type!==`ignore`){if(e.key.type===`osc`){this.#Kt(e.key.value);continue}this.#Wt(e.key)}}}#Kt(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#it=t,this.#rt?.setTerminalBackground(t))}#qt(){this.#xe&&=(clearTimeout(this.#xe),void 0)}#Jt(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#Dn();break;case`enter`:{let e=this.#X.text;if(e.trim().length===0)break;if(parsePromptCommand(e)?.type===`cancel`&&this.#Je!==void 0){this.#X=EMPTY_LINE,this.#qe.requestCancellation(),this.#$e=!0,this.renderCommandInvocation(e.trim()),this.renderCommandResult(`Turn cancellation requested.`),this.#Je(),this.#Dn();break}let t=this.#Ye;t!==void 0&&parsePromptCommand(e)===null?(this.#X=EMPTY_LINE,this.#Yt(e,t)):this.#qe.enqueue(e)&&(this.#X=EMPTY_LINE),this.#Dn();break}case`ctrl-c`:case`escape`:if(e.type===`ctrl-c`&&this.#qe.view().cancelling){this.#oe=!0,this.#le=!0,this.#Q={kind:`idle`},this.#ee=`Interrupted`,this.#Ce?.(),this.#Dn();break}if(this.#qe.idle&&this.#Je===void 0)break;if(this.#qe.handleEscape()===`steer`){let e=this.#Ye;if(e!==void 0){let t=this.#qe.takeSteering();this.#Yt(t,e)}}else this.#$e=!0,this.#Je?.();this.#Dn();break;default:{let t=this.#U.apply(this.#X,e,{multiline:!0});t!==void 0&&(this.#X=t,this.#Dn());break}}}#Yt(e,t){this.#Qe=`steer`,this.#cn(e),t(e).catch(t=>{this.#qe.restoreSteering(e),this.#ln(`Steering failed`,toErrorMessage(t)),this.#Dn()})}#Xt(){this.#Zt(),this.#Qt(),this.#me=setInterval(()=>{this.#de=!this.#de,this.#Dn()},500),this.#me.unref?.()}#Zt(){this.#me&&=(clearInterval(this.#me),void 0),this.#de=!0}#Qt(){this.#de=!0}#$t(){this.#nn(),this.#he=setInterval(()=>{this.#fe+=1,this.#Dn()},90),this.#he.unref?.()}#en(){let e=Date.now();this.#pe=e,this.#Q={kind:`waiting`,startedAtMs:e},this.#$t()}#tn(){this.#rn()||this.#nn()}#nn(){this.#he&&=(clearInterval(this.#he),void 0)}#rn(){return this.#h.some(e=>e.live&&e.subagentCallId!==void 0&&(this.#C.has(e.subagentCallId)||this.#w.has(e.subagentCallId)))}#in(){this.#rn()?this.#$t():!this.#Z&&this.#Q.kind===`idle`&&this.#nn()}#an(e){e.id!==this.#Ie?.id&&this.#ar(),e.updateSeq=++this.#x;let t=e.subagentCallId!==void 0&&this.#C.has(e.subagentCallId)?-1:this.#h.findIndex(e=>e.subagentCallId!==void 0&&this.#C.has(e.subagentCallId));t<0?this.#h.push(e):this.#h.splice(t,0,e),e.id&&this.#g.set(e.id,e)}#on(e){this.#q=!0,this.#an({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#Dn()}#sn(){let e=this.#J.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#zn(e.elapsedMs)}`,n=this.#De??0;if(this.#Oe!==void 0&&this.#Oe>0&&n>0){let e=Math.round(n/this.#Oe*100);t+=` ${this.#i.glyph.dot} ${e}% context`}this.#an({kind:`turn-stats`,body:t,live:!1})}#cn(e){if(e==null)return;let t=this.#Qe;if(this.#Qe=void 0,this.#Ve===e){this.#Ve=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#an(n)}#ln(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.#f?.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.#f===void 0?a:`details: ${this.#f.displayPath}`),this.#an(c),this.#Dn()}#un(e,t){if(this.#E.has(e))return;this.#E.add(e);let n=stripTerminalControls(t),r=this.#S.get(n)??[];if(r.push(e),this.#S.set(n,r),r.length===2){let e=this.#g.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.#an(i)}#dn(e){if(e.id&&this.#_.has(e.id))return;let t=e.id?this.#g.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#x;return}this.#an(e)}#fn(e){if(e.id&&this.#_.has(e.id))return;let t=e.id?this.#g.get(e.id):void 0;if(t!==void 0){Object.assign(t,e),t.updateSeq=++this.#x;return}let n=e.subagentCallId;if(n===void 0){this.#an(e);return}e.id!==this.#Ie?.id&&this.#ar(),e.updateSeq=++this.#x;let r=-1;for(let e=0;e<this.#h.length;e+=1)this.#h[e]?.subagentCallId===n&&(r=e);this.#h.splice(r<0?this.#h.length:r+1,0,e),e.id!==void 0&&this.#g.set(e.id,e)}#pn(e){this.#h=this.#h.filter(t=>t.id!==e),this.#g.delete(e)}#mn(e){let t=this.#h.filter(t=>t.subagentCallId===e);t.length!==0&&(this.#h=this.#h.filter(t=>t.subagentCallId!==e),this.#h.push(...t))}#hn(){for(let e of this.#h)e.subagentCallId!==void 0&&this.#w.has(e.subagentCallId)||e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#gn(e,t,n){let r=turnActivityLabel(n);switch(updateTurnActivity(n,e),e.type){case`turn-start`:e.turnId!==this.#Ke&&(this.#Ke=e.turnId,this.#Ge=void 0,this.#Dn());break;case`step-start`:this.#Ge=typeof e.modelId==`string`&&stripTerminalControls(e.modelId.slice(0,256)).replace(/\s+/gu,` `).trim()||void 0,this.#Dn();break;case`step-finish`:this.#f?.recordStepUsage(e.usage),e.usage!==void 0&&this.#J.addUsage(e.usage),this.#Cn(n),this.#En(e.usage),this.#Dn();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#_n(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.#_n(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.#vn(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.#vn(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#yn({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#f?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#yn({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.#yn({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#Tn(e.toolCallId,n);if(r===void 0)break;this.#yn({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#Tn(e.toolCallId,n);if(this.#f?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#yn({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#Tn(e.toolCallId,n);if(r===void 0)break;this.#yn({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#ln(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:if(n.cancelled=!0,!n.restoreCancelledPrompt)break;this.#Xe=!0,!this.#$e&&this.#et!==void 0&&this.#X.text.length===0&&(this.#X=lineOf(this.#et),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#En(e.usage),this.#Dn()}n===this.#Y&&turnActivityLabel(n)!==r&&this.#Dn()}#_n(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#dn({id:e,kind:`assistant`,body:r,live:n}),this.#Dn())}#vn(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#dn({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#Dn())}#yn(e,t,n){if(n.tools.set(e.toolCallId,e),this.#y.has(e.toolCallId)||isPanelRoutedTool(e.toolName))return;let r=toolSectionId(e.toolCallId);this.#b.set(e.toolCallId,r);let i=this.#bn(e);this.#dn(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#wn(n),this.#Dn()}#bn(e){e.output!==void 0&&this.#T.observeRead(e.output);let t={};this.#xn(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.#T.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}#xn(e){let t=this.#D?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#Sn(e){for(let t of e.tools.keys()){if(this.#y.has(t))continue;let e=this.#b.get(t)??toolSectionId(t),n=this.#g.get(e);n?.kind===`tool`&&n.status===`running`&&(n.status=`error`,n.result=`interrupted`,n.live=!1)}}#Cn(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#b.get(t)??toolSectionId(t);this.#pn(r),this.#b.delete(t)}}#wn(e){let t=[];for(let n of e.tools.values()){if(this.#y.has(n.toolCallId))continue;let e=this.#b.get(n.toolCallId)??toolSectionId(n.toolCallId),r=this.#g.get(e);r?.kind===`tool`&&t.push({block:r,active:isActiveToolStatus(n.status)})}applyCohortLiveness(t)}#Tn(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#b.get(e)??toolSectionId(e),i=this.#g.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`}}#En(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#Ee=(t??0)+(n??0)),this.#De=t??this.#De,this.#ke=n??this.#ke,this.#ke!=null&&this.#je!==void 0){let e=(Date.now()-this.#je)/1e3;e>0&&(this.#Ae=this.#ke/e)}}#Dn(){if(this.#re){if(this.#we){this.#Te=!0;return}this.#we=!0;try{do this.#Te=!1,this.#On();while(this.#Te)}finally{this.#we=!1}}}#On(){if(!this.#re)return;if(this.#rt!==void 0){this.#rt.repaint();return}let e=this.#Kn(),t=this.#Ln(e),n=this.#M===void 0?[]:this.#Mn(),r=Math.max(1,this.#qn()-n.length-t.length),i=[],a=this.#I,o=groupToolBlocksForDisplay(this.#h),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.#h.length-1;t>=0;--t)e.has(this.#h[t])&&this.#h.splice(t,1)}for(let t of o.slice(0,s)){for(let e of t.members)this.#v.push(e),e.id&&(this.#_.add(e.id),this.#g.delete(e.id));if(this.#sr(t.display))continue;let n=this.#Nn(t.display,e,a);a=previousBlockOf(t.display),this.#I=a,i.push(...n),this.#F.push(...n)}let c=[];for(let{display:t}of o.slice(s)){if(this.#sr(t))continue;let n=this.#Nn(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)}#kn(){if(!this.#re)return;let e=this.#Kn(),t=this.#Ln(e),n=Math.max(1,this.#qn()-t.length),r=this.#I,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#h)){if(this.#sr(t))continue;let n=this.#Nn(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.#Mn(),...this.#F],a)}logDisplayMode(){return this.#m}setLogDisplayMode(e){e!==this.#m&&(this.#m=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#jn(),this.#re&&this.#kn())}flushDelayedDevBuildErrors(){let e=this.#Fe;e!==void 0&&(this.#Fe=void 0,this.#an({kind:`log`,title:`stderr`,body:e,live:!0}),this.#Dn())}#An(){this.#_e=!0,this.#ge!==void 0&&clearTimeout(this.#ge),this.#ge=setTimeout(()=>{this.#_e=!1,this.#ge=void 0,this.#Dn()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#m)),this.#Dn()}#jn(){let e=this.#Kn();this.#F.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#v,{logCoalescing:`runs`})){if(this.#sr(n))continue;let r=this.#Nn(n,e,t);t=previousBlockOf(n),this.#F.push(...r)}this.#I=t}#Mn(){let e=this.#D,t=this.#M;if(e===void 0&&t===void 0)return[];let n={name:e?.name??t?.name,theme:this.#i,width:this.#Kn()};return e?.info!==void 0&&(n.info=e.info),buildAgentHeader(n)}#Nn(e,t,n){let r={renderMarkdown:this.#a,activityPulse:this.#Fn(this.#pe,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}#Pn(){return this.#i.spinner[this.#fe%this.#i.spinner.length]??``}#Fn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#In(e,t){return e.indicator.kind===`spinner`?{glyph:this.#Pn(),color:`yellow`}:{glyph:this.#Fn(e.indicator.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#Ln(e){let t=this.#i.colors,n=[``];if(this.#He!==void 0)return n.push(...this.#He(e),``),this.#Un(n,e),n;let r=this.#Ue;if(r!==void 0&&(this.#k===void 0||r.question!==void 0)){let t=this.#In(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`,title:r.questionTitle,rows:t},i!==void 0&&(a={kind:`question`,title:r.questionTitle,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.#Wn(n,e),n}r!==void 0&&n.push(...flowMessageRows(r.lines,this.#i).map(t=>t.length===0?``:clip(` ${t}`,e))),this.#O===void 0&&this.#We!==void 0&&n.push(...renderAttentionRows(this.#We,e,this.#i),``);let i=renderMessageQueueRows({view:this.#qe.view(),width:e,theme:this.#i,working:this.#Z});if(i.length>0&&n.push(...i,``),this.#W){let r=this.#G===void 0?void 0:inlineCommandHint(this.#G);r===void 0&&this.#G!==void 0&&isTypeaheadOpen(this.#G)&&n.push(...renderCommandSuggestions(this.#G,this.#i,e)),this.#ce&&n.push(clip(t.dim(`Press Ctrl+C again to exit`),e),``);let i=isPromptControlCommand(this.#B),a=r?t.dim(` ${r}`):``,o=[];this.#Un(o,e);let s=Math.max(1,this.#qn()-1-n.length-1-o.length),c={text:this.#B,cursor:this.#V,width:e,theme:this.#i,caretVisible:this.#de,isCommand:i,ghost:a,maxRows:s};return this.#K&&this.#B.length===0&&(c.placeholder=this.#k===void 0?this.#q?``:`Send a message…`:`Message · Enter to queue`),n.push(...promptInputRows(c)),n.push(...o),n}let a=this.#Q.kind===`waiting`&&this.#te===void 0;if(this.#Z||a){n.push(this.#Rn(e)),this.#Vn(n,e);let t=[];return this.#Un(t,e),!this.#Z&&t.length>0&&n.push(``),n.push(...t),n}if(this.#X.text.length>0)return this.#Hn(n,e,{inert:!1}),this.#Un(n,e),n;let o=this.#te??(this.#ee.length>0?this.#ee:`Ready`),s=this.#Gn(),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.#Un(n,e),n}#Rn(e){let t=this.#i.colors,n=this.#Q,r=this.#J.startedAtMs??this.#je??(n.kind===`waiting`?n.startedAtMs:Date.now()),i=Math.max(0,Date.now()-r),a=i%1e3<500?this.#i.unicode?`•`:`*`:` `,o=i<1e3?`0s`:formatTurnDuration(Math.floor(i/1e3)*1e3),s=`${turnActivityLabel(this.#Y)} (${o})`,{inputTokens:c,outputTokens:l}=this.#J.usage;return clip(`${a} ${s}${c>0||l>0?t.dim(` (${formatTokenFlow({inputTokens:c,outputTokens:l},this.#i.glyph)})`):``}`,e)}#zn(e){return`${formatTurnDuration(e)}${this.#Bn()}`}#Bn(){let{inputTokens:e,outputTokens:t}=this.#J.usage;return e===0&&t===0?``:` ${this.#i.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#i.glyph)}`}#Vn(e,t){this.#Z&&this.#Hn(e,t,{inert:!0})}#Hn(e,t,n){e.push(``);let r={text:this.#X.text,cursor:this.#X.cursor,width:t,theme:this.#i,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#X.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#Un(e,t){if(this.#O!==void 0){let n=this.#Ue?.status?.text??{starting:`Starting agent…`,connecting:`Reading saved connection…`,updating:`Loading selected model…`}[this.#O],r=this.#Fn(this.#j,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH);e.push(clip(this.#i.colors.dim(`${r} ${n}`),t));return}let n=this.#z===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#i,width:r};this.#Re&&this.#Le!==void 0&&(i.devBuild=this.#Le),this.#_e&&(i.logLevel=this.#m);let a=this.#D?.info?.agent.model;a?.routing.kind===`dynamic`?i.model=this.#Ge===void 0?`dynamic model`:`dynamic model · ${this.#Ge}`:a?.id!==void 0&&(i.model=a.id),a?.reasoning!==void 0&&a.reasoning!==`provider-default`&&(i.reasoning=a.reasoning),readGatewayServiceTier(a?.providerOptions).kind===`priority`&&(i.fastMode=!0);let o=a?.endpoint;o!==void 0&&(i.endpoint=o),this.#R!==void 0&&(i.vercel=this.#R),this.#z!==void 0&&(i.remote=this.#z);let s=buildStatusLine(i);s!==void 0&&e.push(clip(`${n}${s}`,t))}#Wn(e,t){if(this.#z===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#z,theme:this.#i,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Gn(){let e=this.#i.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Ee,outputTokens:this.#ke,tokensPerSecond:this.#Ae},this.#u);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#i.glyph.dot} `)):``}#Kn(){return Math.max(20,this.#t.columns||80)}#qn(){return Math.max(8,this.#t.rows||24)}#Jn(){if(this.#Me!==void 0||!this.#d)return;this.#Ne=``,this.#Pe=``;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.#Zn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#f?.subscribeLogRecords(e=>this.#Xn(e)),this.#Me=()=>{this.#f?.unsubscribeLogRecords(),e(),t()}}#Yn(){let e=this.#Me;e!==void 0&&(this.#Me=void 0,e(),this.#Ne.length>0&&(this.#f?.append({source:`stdout`,detail:this.#Ne}),this.#or(`stdout`)&&process.stdout.write(`${this.#Ne}\n`),this.#Ne=``),this.#Pe.length>0&&(this.#f?.append({source:`stderr`,detail:this.#Pe}),this.#or(`stderr`)&&process.stderr.write(`${this.#Pe}\n`),this.#Pe=``))}#Xn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#$n(`[eve:${e.namespace}] ${e.message}${t}`),this.#Dn()}#Zn(e,t){let n=(e===`stdout`?this.#Ne:this.#Pe)+t;if(e===`stdout`&&parseDevRebuildLogLine(n.trimEnd())!==void 0){this.#Ne=``,this.#f?.append({source:e,detail:n.trimEnd()}),this.#Qn(n.trimEnd()),this.#Dn();return}let r=n.lastIndexOf(`
`),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#Ne=i:this.#Pe=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#f?.append({source:e,detail:a}),e===`stdout`?this.#Qn(a):this.#$n(a),this.#Dn())}#Qn(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
`);t=[],e.trim().length!==0&&this.#an({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.#an({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#tr(r,n.trimEnd())}flushPending()}#$n(e){let t=e.split(`
`),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#f===void 0){this.#an({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#f.displayPath);if(t.kind===`inline`){this.#an({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#an({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#an({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
`);r.trim().length>0&&this.#an({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
`);this.#er(i)}#er(e){if(this.#rr(),this.#m===`all`){if(e.trim().length===0)return;this.#an({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#Fe=e}#tr(e,t){let n=this.#ir();if(e.kind===`failed`){this.#er(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(this.#nr({phase:`building`,summary:t}),n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#Be}`;this.#Be+=1,this.#Ie={id:r,summary:t},this.#an({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}let r=n?.state.summary??this.#Le?.summary;if(r!==void 0&&this.#nr({phase:`complete`,summary:r}),n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#Fe=void 0);return}e.kind===`rebuilt`&&(this.#Fe=void 0),this.#an({kind:`log`,title:`stdout`,body:t,live:!0})}#nr(e){this.#ze!==void 0&&clearTimeout(this.#ze),this.#Le=e,this.#Re=e.phase===`complete`,this.#ze=setTimeout(()=>{e.phase===`building`?(this.#Re=!0,this.#ze=void 0):this.#rr(),this.#Dn()},e.phase===`building`?250:4e3)}#rr(){this.#ze!==void 0&&clearTimeout(this.#ze),this.#Le=void 0,this.#Re=!1,this.#ze=void 0}#ir(){let e=this.#Ie;if(e===void 0)return;let t=this.#g.get(e.id);if(t!==void 0&&t.live===!0)return{state:e,block:t}}#ar(){let e=this.#Ie;if(e===void 0)return;this.#Ie=void 0;let t=this.#g.get(e.id);t!==void 0&&(t.live=!1)}#or(e){switch(this.#m){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#sr(e){return e.kind===`sandbox`?!this.#or(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#m!==`stderr`:e.logVisibility===`all-only`?this.#m!==`all`:!this.#or(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(`${r.glyph.prompt} ${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`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};