eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
3 lines (2 loc) • 32.3 kB
JavaScript
import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{failureKey,formatFailureDetail,formatFailureHint,formatFailureMessage,isInterruptedError,localFailureHint}from"./errors.js";import{parseLogDisplayMode}from"./log-display-mode.js";import{createMcpConnectionStatusTracker}from"./mcp-connection-status.js";import{describeRemoteAuthCompletedMutations}from"./remote-auth-result.js";import{createRemoteConnectionController}from"./remote-connection.js";import{prepareRemoteTuiAccess}from"./remote-startup.js";import{SubagentPump}from"./subagent-pump.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,detectSetupIssues,formatSetupIssuesLine,normalizeLocalModelEndpoint,orderedSetupIssues}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import"#client/index.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{inspectApplication}from"#services/inspect-application.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{probeAgentInfo}from"#services/dev-client/agent-info-probe.js";import{isJsonObjectValue}from"#shared/json.js";import{SteeringStream}from"#cli/dev/tui/steering-stream.js";import{renderApplicationInfo}from"#cli/commands/info.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{createDevelopmentRuntimeArtifactRefresher}from"#services/dev-client.js";async function delayMs(e){await new Promise(t=>{setTimeout(t,e).unref?.()})}async function abortableDelay(e,t){t.aborted||await new Promise(n=>{let r=setTimeout(done,e);r.unref?.(),t.addEventListener(`abort`,done,{once:!0});function done(){clearTimeout(r),t.removeEventListener(`abort`,done),n()}})}function authIssueForStatus(e){if(e===`logged-out`)return LOGIN_SETUP_ISSUE;if(e===`cli-missing`)return CLI_MISSING_SETUP_ISSUE}var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v=!1;#y;#b;#x=!0;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j=!1;#M=new AbortController;#N=!1;#P=0;#F=0;#I=[];#L;#R;#z;#B;#V=new Map;#H;#U=[];#W;#G=!1;#K;#q=new Map;#J=new Set;#Y;#X;constructor(e){this.#e=e.session,e.client!==void 0&&(this.#t=e.client),e.lifecycle!==void 0&&(this.#X=e.lifecycle),this.#n=createRenderer(e);let t={formatActionResultError};if(this.#t!==void 0&&(t.client=this.#t),this.#n.subagents!==void 0&&(t.view=this.#n.subagents),e.appRoot!==void 0&&(t.onToolCompleted=async(e,t,n)=>{let r=registryHandoffAddress(e,t,n);r!==void 0&&this.#fe(r)}),this.#K=new SubagentPump(t),this.#r=e.name??`eve`,this.#w=e.withExclusiveTerminal,this.#i=e.tools??`full`,this.#a=e.reasoning??`full`,this.#o=e.subagents??`full`,this.#s=e.connectionAuth??`full`,this.#c=e.assistantResponseStats??`tokensPerSecond`,this.#l=e.contextSize,this.#u=e.formatTransportError??toErrorMessage,e.initialInput!==void 0&&(this.#m=e.initialInput),e.startup!==void 0&&(this.#h=e.startup),this.#_=e.onboard===!0,this.#y=e.onOnboardingStep,this.#b=e.onOnboardingTerminal,e.appRoot!==void 0){this.#p=e.appRoot;let t={appRoot:e.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};e.detectProjectIdentity!==void 0&&(t.detectIdentity=e.detectProjectIdentity),this.#R=createVercelStatusTracker(t),e.probeMcpConnection!==void 0&&(this.#z=createMcpConnectionStatusTracker({onChange:()=>{},probe:e.probeMcpConnection}))}if(e.promptCommandHandler!==void 0&&(this.#S=e.promptCommandHandler),this.#C=e.availablePromptCommands??PROMPT_COMMANDS,e.remote!==void 0){if(this.#E=e.remote.runAuthFlow,this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#T=createRemoteConnectionController({client:this.#t,credentials:e.remote.credentials,target:e.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:e.remote.resolveOidcToken,resolveDeployment:e.remote.resolveDeployment})}this.#D=e.bootDetections??BOOT_DETECTIONS,this.#O=e.getVercelAuthStatus??getVercelAuthStatus,this.#k=e.inspectApplication??inspectApplication,e.onBootProgress!==void 0&&(this.#A=e.onBootProgress),e.serverUrl!==void 0&&(this.#f=e.serverUrl),e.serverUrl!==void 0&&e.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactRefresher({serverUrl:e.serverUrl}))}async#Z(){if(this.#f===void 0){this.#ee(),this.#_||await this.#me(void 0);return}let e;if(this.#T!==void 0){let t=await this.#T.check();t.state===`ready`&&(e=t.info)}else{let t=this.#t;if(t!==void 0)try{let n=await devBootPhase(`connecting to agent`,()=>probeAgentInfo({client:t,timeoutMs:2e3}),this.#A);n.kind===`ready`&&(e=n.info)}catch{e=void 0}}this.#ee();let t=this.#$(e);this.#_||await this.#me(t)}#Q(){let e=this.#h?.finish();return this.#g=e?.queuedPrompt,e?.draft??this.#m}#$(e){let t=this.#p===void 0?e:normalizeLocalModelEndpoint(e,process.env);this.#B=t;let n=this.#f;if(n===void 0||this.#x)return t;let r={name:this.#r,serverUrl:n};return t!==void 0&&(r.info=t),this.#n.renderAgentHeader?.(r),t}#ee(){let e=this.#A;this.#A=void 0,e?.({type:`before-first-paint`})}async run(){let onStop=()=>this.#n.requestInterrupt?.();this.#X?.signal.aborted===!0?onStop():this.#X?.signal.addEventListener(`abort`,onStop,{once:!0});try{await this.#te()}finally{this.#X?.signal.removeEventListener(`abort`,onStop),this.#j=!0,this.#M.abort(),this.#K.abortAll(),this.#n.shutdown?.(),this.#R?.dispose(),this.#z?.dispose(),this.#T?.dispose()}}async#te(){let e=this.#r,t,n,r=!1,i=!1,a=!1;this.#n.setStartupPhase?.(`starting`),await this.#Z(),this.#R?.refreshIdentity(),this.#z?.refresh();let o=(this.#_||this.#B?.agent.model.endpoint?.kind===`gateway`&&!this.#B.agent.model.endpoint.connected)&&this.#p!==void 0&&this.#S!==void 0&&this.#n.setupFlow!==void 0,s;if(this.#T!==void 0&&this.#n.setupFlow!==void 0){let e=await prepareRemoteTuiAccess({connection:this.#T,renderer:this.#n.setupFlow,signal:this.#X?.signal,runAuthFlow:this.#E});if(e?.kind===`authenticated`){let e=this.#T.current().connection;e.state===`ready`&&this.#$(e.info)}else e?.kind===`failed`||e?.kind===`unavailable`?s={tone:`error`,message:e.kind===`failed`?e.message:e.failure.message}:e?.kind===`cancelled`&&(s={cancelled:!0},e.completedMutations.length>0&&(s.message=`Completed before cancellation: ${describeRemoteAuthCompletedMutations(e.completedMutations).join(`, `)}.`))}o&&(this.#n.setStartupPhase?.(`connecting`),s=await this.#Ce(e));let c=this.#Q();for(s?.cancelled||s?.tone===`error`?c=[this.#g,c].filter(Boolean).join(`
`)||void 0:t=this.#g,this.#x=!1,this.#$(this.#B),this.#he(),this.#n.setStartupPhase?.(void 0),(!o||s?.cancelled||s?.tone===`error`)&&this.#ve(s?.message,s?.tone);;){if(this.#X?.signal.aborted===!0||this.#n.exitRequested?.()===!0)return;let o=this.#U[0];if(o!==void 0&&n===void 0&&this.#H===void 0){this.#U.shift(),this.#W=o;try{await this.#pe(o)}finally{this.#W=void 0}i=!1,a=!1,t=void 0;continue}if(!a){if(t==null){if(!this.#n.readPrompt){if(r)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let n={title:e};c!==void 0&&(n.initialDraft=c,c=void 0);try{this.#G=!0,t=await this.#oe(n)}catch(e){if(isInterruptedError(e)){if(this.#H===void 0&&this.#U.length===0)return;a=!0,t=``}else throw e}finally{this.#G=!1}if(this.#U.length>0&&this.#H===void 0){t=void 0;continue}if(t==null&&this.#H===void 0)return}let o=this.#H===void 0?parsePromptCommand(t):null;if(o?.type===`exit`){this.#X?.requestStop();return}if(o?.type===`cancel`){if(this.#e===void 0){this.#ve(`No active turn to cancel.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.cancel();if(this.#ve(e.status===`accepted`?`Turn cancellation requested.`:`No active turn to cancel.`),e.status===`no_active_turn`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#ve(`Couldn't cancel the turn: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(o?.type===`reset`){if(!await this.#ie()){n=void 0,a=!1,t=void 0;continue}n=void 0,a=!1,t=void 0;continue}if(o?.type===`compact`){if(this.#e===void 0){this.#ve(`No active session to compact.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.compact();if(this.#ve(e.status===`accepted`?`Compaction requested.`:`No active session to compact.`),e.status===`no_active_session`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#ve(`Couldn't compact the session: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(o?.type===`clear`){if(this.#e===void 0){this.#ve(`No active session to clear.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.clear();if(this.#ve(e.status===`accepted`?`Context clear requested.`:`No active session to clear.`),e.status===`no_active_session`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#ve(`Couldn't clear the session: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(o?.type===`help`){this.#ve(formatPromptCommandHelp(this.#C)),n=void 0,a=!1,t=void 0;continue}if(o?.type===`info`){await this.#Ee(),n=void 0,a=!1,t=void 0;continue}if(o?.type===`loglevel`){this.#ve(this.#De(o.argument)),n=void 0,a=!1,t=void 0;continue}if(o?.type===`traces`){await this.#Te(o.argument),n=void 0,a=!1,t=void 0;continue}if(o?.type===`extension`){try{await this.#Se(o,e,{trigger:`command`})}catch(e){if(isInterruptedError(e))return;throw e}n=void 0,t=void 0,a=!1;continue}r=!0}let s=this.#H;this.#H=void 0;let l=s??(i?this.#ue():await(async()=>(this.#re(),await this.#ce({prompt:a?void 0:t,inputResponses:n})))()),u=this.#e?.state.sessionId;u!==void 0&&this.#n.setSessionId?.(u);let d=t,f=!1;try{for(;;){await this.#n.renderStream(l,{title:e,submittedPrompt:d,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let r=l.turnState?.pendingApprovals??[],i=l.turnState?.pendingQuestions??[];if(r.length>0||i.length>0){let o=[];if(r.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let t of r){let n=await this.#n.readToolApproval(t,{title:e});o.push({requestId:t.approvalId,optionId:n.approved?`approve`:`cancel`}),this.#V.delete(t.approvalId)}}if(i.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let t of i){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let i={requestId:t.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),o.push(i),this.#V.delete(t.requestId)}}if(o.length===0)break;a=!0,n=o,t=void 0,f=!0;break}if(this.#Ne(l)){l=this.#ue(),d=void 0;continue}if(l.turnState&&l.turnState.boundaryEvent===void 0&&!l.turnState.aborted){let e=this.#e?.state.sessionId;this.#n.renderNotice?.(e?`Lost the event stream — the turn may still be running on the server (session ${e}). Your next message resumes this session; use /cancel to stop the turn.`:`Lost the connection to the running turn.`)}break}}catch(e){if(isInterruptedError(e))return;throw e}if(f)continue;i=!1,a=!1,n=void 0,t=void 0;let p=l.turnState?.boundaryEvent;this.#Y!==this.#e&&(p===`session.waiting`||p===`session.completed`)&&(t=this.#n.takeQueuedPrompt?.()),this.#re(l.turnState?.aborted===!0)}}#ne(){this.#K.abortAll(),this.#V.clear(),this.#q.clear(),this.#J.clear(),this.#n.setConnectionAuthPendingCount?.(0),this.#e=void 0,this.#d?.clear()}#re(e=!1){let t=this.#Y;t!==void 0&&(this.#Y=void 0,this.#e===t&&(this.#ne(),e?this.#n.renderNotice?.(`Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server.`):this.#n.renderSessionBoundary===void 0?this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`):this.#n.renderSessionBoundary()))}async#ie(){if(this.#e===void 0)return this.#ne(),this.#n.reset?.(),!0;try{await this.#e.reset()}catch(e){return this.#n.renderNotice?.(`Couldn't reset the session: ${toErrorMessage(e)}`),!1}return this.#ne(),this.#n.reset?.(),!0}async#ae(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#d;if(n===void 0)return await t;let r=!1,i=!1,a,o=!1,s=0,refresh=async()=>{if(!(r||i)){i=!0;try{await n.refreshIdle({onRuntimeArtifactsChanged:()=>this.#je()}),this.#p!==void 0&&this.#B===void 0&&!o&&(o=!0,this.#ke().finally(()=>{o=!1}));let e=this.#B?.agent.model.endpoint,t=e?.kind===`chatgpt`&&(e.state===`signed-out`||e.state===`reauth-required`),r=Date.now();t&&r-s>=5e3&&(s=r,this.#ke())}finally{i=!1}}},startRefresh=()=>{if(r||i)return;let e=refresh().finally(()=>{a===e&&(a=void 0)});a=e};startRefresh();let c=setInterval(()=>{startRefresh()},500);c.unref?.();try{return await t}finally{r=!0,clearInterval(c),await a}}async#oe(e){let t=this.#ae(e);if(this.#n.renderIdleStream===void 0||this.#e?.state.sessionId===void 0)return await t;let n=new AbortController,r=this.#se(n.signal,e).catch(e=>{n.signal.aborted||this.#n.renderNotice?.(`Stopped following session updates: ${toErrorMessage(e)}`)});try{return await t}finally{n.abort(),await r}}async#se(e,t){let n=this.#e;if(n===void 0)return;let r=100;for(;!e.aborted;){let i=n.stream({signal:e})[Symbol.asyncIterator](),a=!1;try{for(;!e.aborted;){let r=!1,o={async*[Symbol.asyncIterator](){for(;!e.aborted;){let e=await i.next();if(e.done===!0||(r=!0,a=!0,yield e.value,isCurrentTurnBoundaryEvent(e.value)))return}}},s=this.#de(o,()=>{},n);if(await this.#n.renderIdleStream(s,{...t,continueSession:!0}),this.#Ne(s),(s.turnState?.pendingApprovals.length??0)>0||(s.turnState?.pendingQuestions.length??0)>0){this.#H={events:(async function*(){})(),turnState:s.turnState},this.#n.suspendPromptForInput?.();return}if(s.turnState?.boundaryEvent===`session.completed`||s.turnState?.boundaryEvent===`session.failed`)return;if(!r)break}}finally{await i.return?.()}r=a?100:Math.min(r*2,2e3),e.aborted||await abortableDelay(r,e)}}async#ce(e){let t=new AbortController,n={signal:t.signal};e.prompt!==void 0&&(n.message=e.prompt),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses);let r,i=this.#e;try{if(this.#d!==void 0&&await this.#d.refresh({inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#je()}),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),this.#e===void 0){if(this.#t===void 0)throw Error(`Cannot create a session without an eve client.`);if(n.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let e=await this.#t.sessions.create({...n,message:n.message});this.#e=e.session,r=e.response}else r=n.inputResponses===void 0?await this.#e.send(n.message,{signal:n.signal,turnPolicy:`queue`}):await this.#e.respond(n.inputResponses,{signal:n.signal})}catch(e){if(isInterruptedError(e))throw e;return this.#T?.reportFailure(e),this.#Y=i,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}return this.#de(r,()=>t.abort(),this.#e)}async#le(e,t){if(e.cancelInFlight!==!0){e.cancelInFlight=!0;try{for(let n=0;n<8;n+=1){if(e.boundaryEvent!==void 0||e.aborted===!0)return;let n=e.turnId;try{if((await t?.cancel(n===void 0?void 0:{turnId:n}))?.status===`accepted`)return}catch{}await delayMs(250)}}finally{e.cancelInFlight=!1}}}#ue(){if(this.#e===void 0)throw Error(`Cannot stream a session before its first turn is accepted.`);let e=new AbortController,t=this.#e;return this.#de(t.stream({signal:e.signal}),()=>e.abort(),t)}#de(e,t,n){let r=createTurnState(),i=n===void 0?void 0:new SteeringStream(e,n);return{steer:i===void 0?void 0:e=>i.send(e),abort:()=>{r.aborted=!0,this.#Y=n,i?.abort(),t()},cancel:()=>{this.#le(r,n)},events:eveEventsToTUIStream({onAssistantResponse:()=>{this.#_&&!this.#v&&(this.#v=!0,this.#y?.({flow:`onboarding`,step:`first_response`}))},events:i??e,pendingInputRequests:this.#V,turnState:r,onSubagentCalled:e=>this.#K.begin(e),onSubagentBackgrounded:e=>this.#K.background(e),onSubagentCompleted:e=>this.#K.settle(e),onTurnCancelled:e=>this.#K.settleCancelledTurn(e),onConnectionAuthRequired:e=>this.#Me(e),onConnectionAuthCompleted:e=>this.#Pe(e),onRegistryHandoff:this.#p===void 0?void 0:async e=>this.#fe(e),onTerminalFailure:()=>{this.#Y=n},failureHintOverride:this.#p===void 0?void 0:localFailureHint}),turnState:r}}#fe(e){this.#W===e||this.#U.includes(e)||(this.#U.push(e),this.#G&&this.#n.suspendPromptForInput?.())}async#pe(e){await this.#Se({type:`extension`,name:`add`,argument:e},`Add to your agent`,{trigger:`command`})}async#me(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#I=await detectSetupIssues(t,this.#D),this.#n.renderSetupWarning!==void 0&&(this.#he(),this.#ge())}#he(){if(this.#x)return;let e=orderedSetupIssues(this.#I,this.#L);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#ge(){let e=this.#p;if(e===void 0||process.env.EVE_MODEL_CONNECTION!==`ai-gateway-project`)return;let t;try{t=await this.#O(e,{signal:this.#M.signal})}catch{return}this.#j||this.#N||(this.#L=authIssueForStatus(t),this.#he())}async#_e(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n=++this.#P,r={appRoot:t,env:process.env};e!==void 0&&(r.info=e);try{let[e,i]=await Promise.all([detectSetupIssues(r,this.#D),process.env.EVE_MODEL_CONNECTION===`ai-gateway-project`?this.#O(t,{signal:this.#M.signal}):void 0]);if(this.#j||n!==this.#P)return;this.#I=e,this.#L=i===void 0?void 0:authIssueForStatus(i),this.#he()}catch{return}}#ve(e,t){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e,t);return}this.#n.renderNotice?.(e)}}async#ye(e,t){let n=this.#S;if(n===void 0)return{message:`/${e.name} is not available in this session.`};let r=this.#B?.agent.model.endpoint,i={...t,renderer:this.#n,settleOutcome:e=>this.#xe(e),chatGptAccountLabel:r?.kind===`chatgpt`&&r.state===`ready`?r.accountLabel:void 0,withExclusiveTerminal:this.#w},a=this.#z?.current(),o=a!==void 0&&Object.keys(a).length>0?{...i,disabledConnectionReasons:a}:i;return await n.handle(e,o)}async#be(e){if(e?.kind===`model-access-changed`){this.#R?.applyEffect({kind:`refresh-identity`}),this.#N=!0,await this.#Oe(e);return}e!==void 0&&(this.#R?.applyEffect(e),this.#N=!0,this.#_e(this.#B))}async#xe(e){if(e.effect===void 0)return e;let t=e.effect.kind===`model-access-changed`&&e.effect.reload?setTimeout(()=>{this.#x&&this.#n.setStartupPhase?.(`updating`),this.#n.setupFlow?.setStatus(`Loading selected model…`)},150):void 0;try{await this.#be(e.effect);let{effect:t,...n}=e;return n}catch{return{tone:`error`,message:`Settings were saved, but the agent could not reload. Retry the command or restart eve dev.`}}finally{clearTimeout(t)}}async#Se(e,t,n){let r=await this.#ye(e,{...n,title:t}),i=r===void 0?void 0:await this.#xe(r);return!(n.suppressSuccessfulTranscript===!0&&i?.tone!==`error`||n.suppressCancelledTranscript===!0&&i?.cancelled===!0)&&n.trigger!==`startup`&&this.#ve(i?.message,i?.tone),this.#we(),i}async#Ce(e){this.#y?.({flow:`onboarding`,step:`model_provider`});let t=await this.#Se({type:`extension`,name:`login`,argument:``},e,{trigger:`startup`,initialModelStep:`provider`});return!t?.cancelled&&t?.tone!==`error`&&this.#y?.({flow:`onboarding`,step:`connection_ready`}),this.#b?.({flow:`onboarding`,step:`model_provider`,result:t?.cancelled?`cancelled`:t?.tone===`error`?`error`:`completed`}),t}#we(){if(this.#x)return;let e=this.#T?.current().connection;e?.state===`ready`&&e.info!==this.#B&&(this.#B=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}async#Te(e){if(this.#p===void 0||this.#n.traceViewer===void 0){this.#ve(`/traces is only available in local dev sessions.`);return}try{await this.#n.traceViewer.open({appRoot:this.#p,sessionId:this.#e?.state.sessionId,reference:e===``?void 0:e})}catch(e){if(isInterruptedError(e))return;throw e}}async#Ee(){let e=this.#p;if(e===void 0){this.#ve(`/info is only available in local dev sessions.`);return}try{this.#ve(renderApplicationInfo(await this.#k(e)))}catch(e){this.#ve(`Couldn't inspect the application: ${toErrorMessage(e)}`,`error`)}}#De(e){let t=this.#n;if(t.logDisplayMode===void 0||t.setLogDisplayMode===void 0)return`/loglevel is not available in this session.`;if(e===``)return`Logs: ${t.logDisplayMode()}. Use /loglevel all|stderr|sandbox|none — logs stay buffered, so switching also hides or restores past lines.`;let n=parseLogDisplayMode(e);if(n===void 0)return`Unknown log level "${e}". Use all, stderr, sandbox, or none.`;if(n===t.logDisplayMode())return`Logs already set to ${n}.`;switch(t.setLogDisplayMode(n),n){case`none`:return`Logs hidden. Output stays buffered — /loglevel all restores it.`;case`stderr`:return`Showing stderr logs only.`;case`sandbox`:return`Showing sandbox logs only.`;case`all`:return`Showing all logs.`}}async#Oe(e){let t=this.#p;t!==void 0&&(++this.#F,++this.#P,await loadDevelopmentEnvironmentFiles(t),e.reload&&await this.#d?.refreshAfterSourceChange({}),e.model&&this.#B?this.#$({...this.#B,agent:{...this.#B.agent,model:{...this.#B.agent.model,...e.model}}}):this.#$(this.#B),this.#I=[],this.#L=void 0,this.#he(),this.#ke())}async#ke(e=!1){let t=this.#B,n=++this.#F,r=await this.#Ae();this.#j||n!==this.#F||r===void 0||(this.#$(r),e&&!this.#n.renderAgentHeader&&this.#n.renderNotice?.(formatAgentUpdateNotice(t,r)),this.#_e(this.#B))}async#Ae(){let e=this.#t;if(e===void 0)return;let t=await probeAgentInfo({client:e});return t.kind===`ready`?t.info:void 0}#je(){this.#ke(!0)}#Me(e){let t={name:e.data.name,description:e.data.description,state:`required`};e.data.authorization!==void 0&&(t.challenge=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),this.#q.set(e.data.name,t),this.#Fe(t)}#Ne(e){if(e.turnState?.boundaryEvent!==`session.waiting`)return!1;let t=!1;for(let e of this.#q.values())e.state===`required`&&e.webhookUrl!==void 0&&(e.state=`pending`,this.#J.add(e.name),this.#Fe(e),t=!0);return t&&this.#n.setConnectionAuthPendingCount?.(this.#J.size),this.#J.size>0}#Pe(e){let t=this.#q.get(e.data.name)??{name:e.data.name,description:``,state:e.data.outcome};t.state=e.data.outcome,e.data.reason!==void 0&&(t.reason=e.data.reason),this.#q.set(e.data.name,t),this.#J.delete(e.data.name),this.#Fe(t),this.#n.setConnectionAuthPendingCount?.(this.#J.size)}#Fe(e){let t={name:e.name,description:e.description,state:e.state};e.challenge!==void 0&&(t.challenge=e.challenge),e.reason!==void 0&&(t.reason=e.reason),this.#n.upsertConnectionAuth?.(t)}};function createRenderer(e){return e.renderer?e.renderer:new TerminalRenderer({tools:e.tools,reasoning:e.reasoning,subagents:e.subagents,connectionAuth:e.connectionAuth,assistantResponseStats:e.assistantResponseStats,contextSize:e.contextSize,logs:e.logs,availablePromptCommands:e.availablePromptCommands,input:e.userInput,output:e.screen,diagnostics:e.diagnostics,onExitRequest:e.lifecycle?.requestStop})}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id,r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}function registryHandoffAddress(e,t,n){if((e!==`self-modification__agent`||t!==`registry_add`)&&(e!==void 0||t!==`selfmod__registry_add`)||typeof n!=`object`||!n)return;let r=n;return r.status===`needs-terminal`&&typeof r.address==`string`?r.address:void 0}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,turnState:r,onSubagentCalled:i,onSubagentBackgrounded:a,onSubagentCompleted:o,onTurnCancelled:s,onConnectionAuthRequired:c,onConnectionAuthCompleted:l,onRegistryHandoff:u,onTerminalFailure:d,failureHintOverride:f}=e,p=new Map,m=new Map,h=new Map,g=createEventDeduper(),_=0,v=new Set,y=new Set,b=new Set,x=!1,S=!1,C;for await(let w of t)if(g.admit(w)&&!(S&&isPostTurnVisibleEvent(w)))switch(w.type){case`session.started`:case`message.received`:break;case`turn.started`:w.data.turnId!==r.turnId&&(S=!1),r.turnId=w.data.turnId,yield{type:`turn-start`,turnId:w.data.turnId};break;case`step.started`:_+=1,yield{type:`step-start`,modelId:w.data.modelId};break;case`step.completed`:{let e=w;C=e.data.usage,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`step-finish`,usage:e.data.usage};break}case`message.appended`:{let t=w,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(p,n);if(r.completed){if(_<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}let i=t.data.messageDelta;if(i.length===0)break;r.text+=i,i&&e.onAssistantResponse?.(),yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:i};break}case`message.completed`:{let t=textPartId(w.data.turnId,w.data.stepIndex),n=partStateFor(p,t),r=w.data.message;if(n.completed){if(r===null||_<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=_,yield{type:`assistant-complete`,id:partGenerationId(t,n.generation),text:r};break}let i=partGenerationId(t,n.generation);if(r!==null){if(n.text.length===0)n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let t=r.slice(n.text.length);t.length>0&&(t&&e.onAssistantResponse?.(),yield{type:`assistant-delta`,id:i,delta:t}),n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i}}else n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i,text:r}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let e=w,t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(m,t);if(n.completed){if(_<=n.completedEpoch)break;n.generation+=1,n.text=``,n.completed=!1}let r=e.data.reasoningDelta;if(r.length===0)break;n.text+=r,yield{type:`reasoning-delta`,id:partGenerationId(t,n.generation),delta:r};break}case`reasoning.completed`:{let e=reasoningPartId(w.data.turnId,w.data.stepIndex),t=partStateFor(m,e),n=w.data.reasoning;if(t.completed){if(n.length===0||_<=t.completedEpoch)break;t.generation+=1,t.text=n,t.completedEpoch=_;let r=partGenerationId(e,t.generation);yield{type:`reasoning-delta`,id:r,delta:n},yield{type:`reasoning-complete`,id:r};break}let r=partGenerationId(e,t.generation);if(t.text.length===0&&n.length>0)t.text=n,yield{type:`reasoning-delta`,id:r,delta:n};else if(n.length>0&&!n.startsWith(t.text)){yield{type:`reasoning-complete`,id:r},t.generation+=1,t.text=n,t.completed=!0,t.completedEpoch=_;let i=partGenerationId(e,t.generation);yield{type:`reasoning-delta`,id:i,delta:n},yield{type:`reasoning-complete`,id:i};break}t.completed=!0,t.completedEpoch=_,yield{type:`reasoning-complete`,id:r};break}case`actions.requested`:{let e=w.data.actions.filter(e=>e.kind===`tool-call`);if(e.length===0)break;for(let t of e)h.set(t.callId,t.toolName),!v.has(t.callId)&&(v.add(t.callId),yield{type:`tool-call`,toolCallId:t.callId,toolName:t.toolName,input:t.input});break}case`input.requested`:{let e=w.data.requests.filter(e=>e.action.kind===`tool-call`);if(e.length===0)break;for(let t of e){let e=t.action.callId;if(h.set(e,t.action.toolName),t.kind!==`session-limit`&&!v.has(e)&&(v.add(e),yield{type:`tool-call`,toolCallId:e,toolName:t.action.toolName,input:t.action.input}),!y.has(t.requestId)){if(y.add(t.requestId),n.set(t.requestId,t),t.kind!==`tool-approval`){upsertPendingQuestion(r,t);continue}upsertPendingApproval(r,t),yield{type:`tool-approval-request`,approvalId:t.requestId,toolCallId:e}}}break}case`action.result`:{let e=w,t=e.data.result,n=`output`in t?t.output:void 0;if(e.data.status===`completed`&&isJsonObjectValue(n)&&n.status===`working`&&typeof n.taskId==`string`&&typeof n.agentId==`string`&&a?.(t.callId),e.data.result.kind!==`tool-result`)break;let r=e.data.result.callId;if(!v.has(r))break;switch(e.data.status){case`completed`:{let t=e.data.result.output;yield{type:`tool-result`,toolCallId:r,output:t};let n=registryHandoffAddress(void 0,h.get(r),t);n!==void 0&&await u?.(n);break}case`failed`:yield{type:`tool-error`,toolCallId:r,errorText:formatActionResultError(e)};break;case`rejected`:yield{type:`tool-rejected`,toolCallId:r,reason:formatActionResultError(e)}}break}case`step.failed`:case`turn.failed`:{let e=toFailureEvent(w,b,f);e&&(yield e);break}case`session.failed`:{r.sawSessionFailure=!0,d?.(w);let e=toFailureEvent(w,b,f);e&&(yield e),r.boundaryEvent=w.type,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C},x=!0;return}case`session.waiting`:case`session.completed`:r.boundaryEvent=w.type,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C},x=!0;return;case`turn.completed`:S=!0,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_);break;case`turn.cancelled`:s?.(w.data.turnId),yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`turn-cancelled`};break;case`subagent.called`:i?.(w);break;case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:{let e=w;e.data.backgroundTask===void 0?o?.(e.data.callId):a?.(e.data.callId);break}case`authorization.required`:c?.(w);break;case`authorization.completed`:l?.(w)}x||(yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{aborted:!1,pendingApprovals:[],pendingQuestions:[],sawSessionFailure:!1}}function upsertPendingApproval(e,t){let n=toAgentTUIToolApprovalRequest(t),r=e.pendingApprovals.findIndex(e=>e.approvalId===n.approvalId);r===-1?e.pendingApprovals.push(n):e.pendingApprovals[r]=n}function toAgentTUIToolApprovalRequest(e){return{approvalId:e.requestId,toolCallId:e.action.callId,toolName:e.action.toolName,input:e.action.input}}function upsertPendingQuestion(e,t){let n=e.pendingQuestions.findIndex(e=>e.requestId===t.requestId);n===-1?e.pendingQuestions.push(t):e.pendingQuestions[n]=t}function textPartId(e,t){return`text:${e}:${t}`}function reasoningPartId(e,t){return`reasoning:${e}:${t}`}function partStateFor(e,t){let n=e.get(t);return n===void 0&&(n={generation:0,text:``,completed:!1,completedEpoch:0},e.set(t,n)),n}function partGenerationId(e,t){return t===0?e:`${e}#${t}`}function*closeOpenParts(e,t,n){for(let[r,i]of e)i.completed||i.text.length===0||(i.completed=!0,i.completedEpoch=n,yield{type:t,id:partGenerationId(r,i.generation)})}function isPostTurnVisibleEvent(e){switch(e.type){case`actions.requested`:case`authorization.completed`:case`authorization.required`:case`input.requested`:case`message.appended`:case`message.completed`:case`reasoning.appended`:case`reasoning.completed`:case`result.completed`:case`step.completed`:case`step.failed`:case`step.started`:case`subagent.called`:case`subagent.completed`:case`subagent.event`:case`subagent.started`:case`turn.completed`:case`turn.failed`:return!0;default:return!1}}function formatActionResultError(e){if(e.data.error?.message)return e.data.error.message;let t=e.data.result.output;if(typeof t==`string`)return t;try{return JSON.stringify(t)}catch{return`Tool execution failed.`}}function toFailureEvent(e,t,n){let r=failureKey(e);if(t.has(r))return;t.add(r);let i={type:`error`,errorText:formatFailureMessage(e)},a=n?.(e)??formatFailureHint(e);a!==void 0&&(i.hint=a);let o=formatFailureDetail(e);return o!==void 0&&(i.detail=o),i}function toAgentTUIInputQuestion(e){let t=e.display===`text`?`text`:e.display===`select`||e.options!==void 0&&e.options.length>0?`select`:`text`,n={requestId:e.requestId,prompt:e.prompt,display:t};return e.options!==void 0&&(n.options=e.options.map(e=>{let t={id:e.id,label:e.label};return e.description!==void 0&&(t.description=e.description),e.style!==void 0&&(t.style=e.style),t})),e.allowFreeform!==void 0&&(n.allowFreeform=e.allowFreeform),n}export{EveTUIRunner,parsePromptCommand,registryHandoffAddress};