eve 0.27.2 → 0.27.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/dist/src/channel/reset-session.d.ts +8 -0
- package/dist/src/channel/reset-session.js +1 -0
- package/dist/src/channel/routes.d.ts +24 -1
- package/dist/src/channel/send.js +1 -1
- package/dist/src/channel/session-callback.js +1 -1
- package/dist/src/channel/types.d.ts +14 -0
- package/dist/src/chunks/{use-eve-agent-CbF0l_Fp.js → use-eve-agent-BtkhbY2I.js} +53 -4
- package/dist/src/chunks/{use-eve-agent-CgxB9WQv.js → use-eve-agent-NUjD28Iu.js} +53 -4
- package/dist/src/cli/commands/build.js +1 -1
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/dev/tui/blocks.d.ts +7 -0
- package/dist/src/cli/dev/tui/blocks.js +3 -3
- package/dist/src/cli/dev/tui/message-queue.d.ts +88 -0
- package/dist/src/cli/dev/tui/message-queue.js +1 -0
- package/dist/src/cli/dev/tui/runner.d.ts +33 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.js +1 -1
- package/dist/src/cli/dev/tui/subagent-pump.d.ts +9 -0
- package/dist/src/cli/dev/tui/subagent-pump.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +9 -0
- package/dist/src/cli/dev/tui/terminal-renderer.js +13 -11
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/session.d.ts +13 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/types.d.ts +10 -0
- package/dist/src/context/dynamic-tool-lifecycle.d.ts +13 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/context/keys.d.ts +5 -0
- package/dist/src/context/keys.js +1 -1
- package/dist/src/execution/node-step.d.ts +6 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/sandbox/bindings/docker.js +1 -1
- package/dist/src/execution/sandbox/bindings/just-bash.js +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-lifecycle.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/terminal-session-failure-step.js +1 -1
- package/dist/src/execution/workflow-callback-url.d.ts +12 -2
- package/dist/src/execution/workflow-callback-url.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-module-loader.js +3 -3
- package/dist/src/internal/authored-package-tsconfig-paths.js +1 -1
- package/dist/src/internal/authored-relative-extension-resolver.d.ts +6 -0
- package/dist/src/internal/authored-relative-extension-resolver.js +1 -0
- package/dist/src/internal/nitro/dev-runtime-source-snapshot.js +1 -1
- package/dist/src/internal/nitro/host/build-application.js +1 -1
- package/dist/src/internal/nitro/host/types.d.ts +9 -0
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/node-esm-compat-banner.js +1 -1
- package/dist/src/internal/workflow-bundle/builder-support.d.ts +5 -0
- package/dist/src/internal/workflow-bundle/builder.js +2 -2
- package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.d.ts +39 -0
- package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.js +1 -0
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +4 -4
- package/dist/src/internal/workflow-bundle/vercel-workflow-output.d.ts +10 -1
- package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -1
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/protocol/reset-session.d.ts +14 -0
- package/dist/src/protocol/reset-session.js +1 -0
- package/dist/src/protocol/routes.d.ts +5 -0
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/channels/eve.d.ts +2 -2
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/public/channels/index.d.ts +1 -1
- package/dist/src/public/channels/linear/inbound-images.d.ts +18 -0
- package/dist/src/public/channels/linear/inbound-images.js +1 -0
- package/dist/src/public/channels/linear/linearChannel.js +1 -1
- package/dist/src/public/channels/slack/limits.js +1 -1
- package/dist/src/public/definitions/channel.d.ts +1 -1
- package/dist/src/public/next/vercel-output-config.js +1 -1
- package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
- package/dist/src/setup/flows/install-vercel-cli.d.ts +8 -2
- package/dist/src/setup/flows/install-vercel-cli.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/vercel-project-api.d.ts +1 -1
- package/dist/src/setup/vercel-project-api.js +1 -1
- package/dist/src/shared/public-route-prefix.d.ts +23 -0
- package/dist/src/shared/public-route-prefix.js +1 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/custom.mdx +38 -1
- package/docs/channels/linear.mdx +1 -1
- package/docs/extensions.md +100 -20
- package/docs/guides/dev-tui.md +9 -2
- package/docs/guides/frontend/nextjs.mdx +2 -0
- package/docs/reference/cli.md +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{pickAgentHeaderTip}from"./agent-header.js";import{probeAgentInfo}from"./agent-info-probe.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{createRemoteConnectionController}from"./remote-connection.js";import{SubagentPump}from"./subagent-pump.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import"#client/index.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createDevelopmentRuntimeArtifactRefresher}from"#services/dev-client.js";import{devBootPhase}from"#internal/dev-boot-progress.js";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;#y;#b;#x=!1;#S=new AbortController;#C=!1;#w=[];#T;#E;#D;#O=pickAgentHeaderTip();#k;#A=new Map;#j;#M=new Map;#N=new Set;#P=!1;#F;constructor(t){this.#e=t.session,t.client!==void 0&&(this.#t=t.client),this.#n=createRenderer(t);let n={formatActionResultError};if(this.#t!==void 0&&(n.client=this.#t),this.#n.subagents!==void 0&&(n.view=this.#n.subagents),this.#j=new SubagentPump(n),this.#r=t.name??`eve`,this.#i=t.tools??`full`,this.#a=t.reasoning??`full`,this.#o=t.subagents??`full`,this.#s=t.connectionAuth??`full`,this.#c=t.assistantResponseStats??`tokensPerSecond`,this.#l=t.contextSize,this.#u=t.formatTransportError??toErrorMessage,t.initialInput!==void 0&&(this.#m=t.initialInput),t.appRoot!==void 0){this.#p=t.appRoot;let e={appRoot:t.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};t.detectProjectIdentity!==void 0&&(e.detectIdentity=t.detectProjectIdentity),this.#E=createVercelStatusTracker(e),t.probeMcpConnection!==void 0&&(this.#D=createMcpConnectionStatusTracker({onChange:()=>{},probe:t.probeMcpConnection}))}if(t.promptCommandHandler!==void 0&&(this.#h=t.promptCommandHandler),this.#g=t.availablePromptCommands??PROMPT_COMMANDS,t.remote!==void 0){if(this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#_=createRemoteConnectionController({client:this.#t,credentials:t.remote.credentials,target:t.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:t.remote.resolveOidcToken,resolveDeployment:t.remote.resolveDeployment})}this.#v=t.bootDetections??BOOT_DETECTIONS,this.#y=t.getVercelAuthStatus??getVercelAuthStatus,t.onBootProgress!==void 0&&(this.#b=t.onBootProgress),t.serverUrl!==void 0&&(this.#f=t.serverUrl),t.serverUrl!==void 0&&t.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactRefresher({serverUrl:t.serverUrl}))}async#I(){if(this.#f===void 0){this.#R(),await this.#G(void 0);return}let e;if(this.#_!==void 0){let t=await this.#_.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}),this.#b);n.kind===`ready`&&(e=n.info)}catch{e=void 0}}this.#R();let t=this.#L(e);await this.#G(t)}#L(e){let t=this.#p===void 0?e:resolveModelProviderState(e,process.env);this.#k=t;let n=this.#f;if(n===void 0)return t;let r={name:this.#r,serverUrl:n};return t!==void 0&&(r.info=t),this.#p!==void 0&&(r.tip=this.#O),this.#n.renderAgentHeader?.(r),t}#R(){let e=this.#b;this.#b=void 0,e?.({type:`before-first-paint`})}async run(){try{await this.#z()}finally{this.#x=!0,this.#S.abort(),this.#j.abortAll(),this.#F?.(),this.#F=void 0,this.#n.shutdown?.(),this.#E?.dispose(),this.#D?.dispose(),this.#_?.dispose()}}async#z(){let e=this.#r,r,i,a=!1,o=!1,s=this.#m;await this.#I(),this.#_?.current().connection.state===`auth-required`&&await this.#te({type:`extension`,name:`vc:login`,argument:``},e,{trigger:`startup`}),this.#Y(),this.#E?.refreshIdentity(),this.#D?.refresh();let c=this.#m===void 0?void 0:parsePromptCommand(this.#m);for(c?.type===`extension`&&c.name===`model`&&c.argument===``&&this.#p!==void 0&&this.#h!==void 0&&this.#n.setupFlow!==void 0&&(s=void 0,await this.#ne(e));;){if(!o){if(r==null){if(!this.#n.readPrompt){if(a)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let t={title:e};s!==void 0&&(t.initialDraft=s,s=void 0);try{r=await this.#V(t)}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let c=parsePromptCommand(r);if(c?.type===`exit`)return;if(c?.type===`new`){this.#B(),i=void 0,o=!1,r=void 0,this.#n.reset?.();continue}if(c?.type===`help`){this.#X(formatPromptCommandHelp(this.#g)),i=void 0,o=!1,r=void 0;continue}if(c?.type===`loglevel`){this.#X(this.#ie(c.argument)),i=void 0,o=!1,r=void 0;continue}if(c?.type===`extension`){try{await this.#te(c,e,{trigger:`command`})}catch(e){if(isInterruptedError(e))return;throw e}i=void 0,r=void 0,o=!1;continue}a=!0}let c=await this.#H({prompt:o?void 0:r,inputResponses:i}),u=r,d=!1;try{for(;;){await this.#n.renderStream(c,{title:e,submittedPrompt:u,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let t=c.turnState?.pendingApprovals??[],n=c.turnState?.pendingQuestions??[];if(t.length>0||n.length>0){let a=[];if(t.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let n of t){let t=await this.#n.readToolApproval(n,{title:e});a.push({requestId:n.approvalId,optionId:t.approved?`approve`:`deny`}),this.#A.delete(n.approvalId)}}if(n.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 n){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),a.push(i),this.#A.delete(t.requestId)}}if(a.length===0)break;o=!0,i=a,r=void 0,d=!0;break}if(this.#le(c)){c=this.#U(),u=void 0;continue}if(c.turnState&&c.turnState.boundaryEvent===void 0)if(c.turnState.aborted)this.#P=!0;else{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}d||(o=!1,i=void 0,r=void 0,this.#P&&(this.#P=!1,this.#B(),c.turnState?.aborted?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()))}}#B(){this.#j.abortAll(),this.#A.clear(),this.#M.clear(),this.#N.clear(),this.#n.setConnectionAuthPendingCount?.(0),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}async#V(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,refresh=async()=>{if(!(r||i)){i=!0;try{await n.refreshIdle({onRuntimeArtifactsChanged:()=>this.#se()})}finally{i=!1}}},startRefresh=()=>{if(r||i)return;let e=refresh().finally(()=>{a===e&&(a=void 0)});a=e};startRefresh();let o=setInterval(()=>{startRefresh()},500);o.unref?.();try{return await t}finally{r=!0,clearInterval(o),await a}}async#H(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;try{this.#d!==void 0&&await this.#d.refresh({inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#se()}),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),r=await this.#e.send(n)}catch(e){if(isInterruptedError(e))throw e;return this.#_?.reportFailure(e),this.#P=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}return this.#W(r,()=>t.abort())}#U(){let e=new AbortController;return this.#W(this.#e.stream({signal:e.signal}),()=>e.abort())}#W(e,t){let n=createTurnState();return{abort:()=>{n.aborted=!0,t()},events:eveEventsToTUIStream({events:e,pendingInputRequests:this.#A,turnState:n,onSubagentCalled:e=>this.#j.begin(e),onSubagentCompleted:e=>this.#j.settle(e),onConnectionAuthRequired:e=>this.#ce(e),onConnectionAuthCompleted:e=>this.#ue(e),onTerminalFailure:()=>{this.#P=!0},failureHintOverride:this.#p===void 0?void 0:localFailureHint}),turnState:n}}async#G(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#w=await detectSetupIssues(t,this.#v),this.#n.renderSetupWarning!==void 0&&(this.#K(),this.#q())}#K(){let e=orderedSetupIssues(this.#w,this.#T);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#q(){let e=this.#p;if(e===void 0)return;let t;try{t=await this.#y(e,{signal:this.#S.signal})}catch{return}this.#x||this.#C||(this.#T=authIssueForStatus(t),this.#K())}async#J(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n={appRoot:t,env:process.env};e!==void 0&&(n.info=e);try{this.#w=await detectSetupIssues(n,this.#v);let e=await this.#y(t,{signal:this.#S.signal});this.#T=authIssueForStatus(e)}catch{return}this.#x||this.#K()}#Y(){this.#p===void 0||this.#n.renderSandboxLog===void 0||this.#F===void 0&&(this.#F=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#X(e){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}}async#Z(e,t){let n=this.#h;if(n===void 0)return{message:`/${e.name} is not available in this session.`};let r={renderer:this.#n,title:t.title,initialModelStep:t.initialModelStep,remoteConnection:this.#_},i=this.#D?.current(),a=i!==void 0&&Object.keys(i).length>0?{...r,disabledConnectionReasons:i}:r;return t.keepSetupFlowOpen===!0?await n.handle(e,{...a,keepSetupFlowOpen:!0}):await n.handle(e,a)}#Q(e,t){if(t!==`startup`)return;let n=this.#_?.current().connection.state,r=n===`auth-failed`||n===`unavailable`?`failed`:void 0,i=e.argument.length===0?``:` ${e.argument}`;this.#n.renderCommandInvocation?.(`/${e.name}${i}`,r)}async#$(e){if(e?.kind===`connection-added`){this.#E?.applyEffect({kind:`refresh-identity`}),this.#C=!0,await this.#ee(),await this.#ae();return}if(e?.kind===`model-access-changed`){this.#E?.applyEffect({kind:`refresh-identity`}),this.#C=!0,await this.#ae();return}e!==void 0&&(this.#E?.applyEffect(e),this.#C=!0,this.#J(this.#k))}async#ee(){let e=this.#d;e!==void 0&&await e.refreshAfterSourceChange({onRuntimeArtifactsChanged:()=>this.#se()})}async#te(e,t,n){let r=await this.#Z(e,{initialModelStep:n.initialModelStep,keepSetupFlowOpen:n.keepSetupFlowOpen,title:t});this.#Q(e,n.trigger),this.#X(r?.message),await this.#$(r?.effect),this.#re()}async#ne(e){let t=this.#p;if(t===void 0)return;let authStatus=async()=>{try{return await this.#y(t,{signal:this.#S.signal})}catch{return}},n=await authStatus();if(n===`cli-missing`&&(await this.#te({type:`extension`,name:`vc:install`,argument:``},e,{trigger:`startup`,keepSetupFlowOpen:!0}),n=await authStatus(),n===`cli-missing`)){this.#n.setupFlow?.end();return}if(n===`logged-out`&&(await this.#te({type:`extension`,name:`vc:login`,argument:``},e,{trigger:`startup`,keepSetupFlowOpen:!0}),n=await authStatus(),n===`cli-missing`||n===`logged-out`)){this.#n.setupFlow?.end();return}await this.#te({type:`extension`,name:`model`,argument:``},e,{trigger:`startup`,initialModelStep:`provider`})}#re(){let e=this.#_?.current().connection;e?.state!==`ready`||e.info===this.#k||(this.#k=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}#ie(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#ae(){let e=this.#p;if(e===void 0)return;loadDevelopmentEnvironmentFiles(e);let t=this.#L(await this.#oe());this.#J(t)}async#oe(){let e=this.#t;if(e===void 0)return;let t=await probeAgentInfo({client:e});return t.kind===`ready`?t.info:void 0}async#se(){let e=this.#k,t=await this.#oe();t!==void 0&&this.#L(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#ce(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.#M.set(e.data.name,t),this.#de(t)}#le(e){if(e.turnState?.boundaryEvent!==`session.waiting`)return!1;let t=!1;for(let e of this.#M.values())e.state!==`required`||e.webhookUrl===void 0||(e.state=`pending`,this.#N.add(e.name),this.#de(e),t=!0);return t&&this.#n.setConnectionAuthPendingCount?.(this.#N.size),this.#N.size>0}#ue(e){let t=this.#M.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.#M.set(e.data.name,t),this.#N.delete(e.data.name),this.#de(t),this.#n.setConnectionAuthPendingCount?.(this.#N.size)}#de(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})}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.`}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,turnState:r,onSubagentCalled:i,onSubagentCompleted:a,onConnectionAuthRequired:o,onConnectionAuthCompleted:s,onTerminalFailure:c,failureHintOverride:l}=e,u=new Map,d=new Map,f=0,p=new Set,m=new Set,h=new Set,g=!1,_=!1,v;for await(let e of t)if(!(_&&isPostTurnVisibleEvent(e)))switch(e.type){case`session.started`:case`turn.started`:case`message.received`:break;case`step.started`:f+=1,yield{type:`step-start`};break;case`step.completed`:{let t=e;v=t.data.usage,yield*closeOpenParts(u,`assistant-complete`,f),yield*closeOpenParts(d,`reasoning-complete`,f),yield{type:`step-finish`,usage:t.data.usage};break}case`message.appended`:{let t=e,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(u,n),i=t.data.messageSoFar;if(r.completed){if(r.text.startsWith(i)||f<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`message.completed`:{let t=textPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(u,t),r=e.data.message;if(n.completed){if(r===null||r===n.text||f<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=f,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=f,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let e=r.slice(n.text.length);e.length>0&&(yield{type:`assistant-delta`,id:i,delta:e}),n.text=r,n.completed=!0,n.completedEpoch=f,yield{type:`assistant-complete`,id:i}}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=f,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let t=e,n=reasoningPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(d,n),i=t.data.reasoningSoFar;if(r.completed){if(r.text.startsWith(i)||f<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`reasoning-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`reasoning.completed`:{let t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(d,t),r=e.data.reasoning;if(n.completed){if(r.length===0||r===n.text||n.text.startsWith(r)||f<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=f;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}let i=partGenerationId(t,n.generation);if(n.text.length===0&&r.length>0)n.text=r,yield{type:`reasoning-delta`,id:i,delta:r};else if(r.length>0&&!r.startsWith(n.text))break;n.completed=!0,n.completedEpoch=f,yield{type:`reasoning-complete`,id:i};break}case`actions.requested`:{let t=e.data.actions.filter(e=>e.kind===`tool-call`);if(t.length===0)break;for(let e of t)p.has(e.callId)||(p.add(e.callId),yield{type:`tool-call`,toolCallId:e.callId,toolName:e.toolName,input:e.input});break}case`input.requested`:{let t=e.data.requests.filter(e=>e.action.kind===`tool-call`);if(t.length===0)break;for(let e of t){let t=e.action.callId;if(p.has(t)||(p.add(t),yield{type:`tool-call`,toolCallId:t,toolName:e.action.toolName,input:e.action.input}),!m.has(e.requestId)){if(m.add(e.requestId),n.set(e.requestId,e),isQuestionRequest(e)){upsertPendingQuestion(r,e);continue}upsertPendingApproval(r,e),yield{type:`tool-approval-request`,approvalId:e.requestId,toolCallId:t}}}break}case`action.result`:{let t=e;if(t.data.result.kind!==`tool-result`)break;let n=t.data.result.callId;if(!p.has(n))break;switch(t.data.status){case`completed`:yield{type:`tool-result`,toolCallId:n,output:t.data.result.output};break;case`failed`:yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)};break;case`rejected`:yield{type:`tool-rejected`,toolCallId:n,reason:formatActionResultError(t)};break}break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,h,l);t&&(yield t);break}case`session.failed`:{r.sawSessionFailure=!0,c?.(e);let t=toFailureEvent(e,h,l);t&&(yield t),r.boundaryEvent=e.type,yield*closeOpenParts(u,`assistant-complete`,f),yield*closeOpenParts(d,`reasoning-complete`,f),yield{type:`finish`,usage:v},g=!0;return}case`session.waiting`:case`session.completed`:r.boundaryEvent=e.type,yield*closeOpenParts(u,`assistant-complete`,f),yield*closeOpenParts(d,`reasoning-complete`,f),yield{type:`finish`,usage:v},g=!0;return;case`turn.completed`:_=!0,yield*closeOpenParts(u,`assistant-complete`,f),yield*closeOpenParts(d,`reasoning-complete`,f);break;case`subagent.called`:i?.(e);break;case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:a?.(e.data.callId);break;case`authorization.required`:o?.(e);break;case`authorization.completed`:s?.(e);break;default:break}g||(yield*closeOpenParts(u,`assistant-complete`,f),yield*closeOpenParts(d,`reasoning-complete`,f),yield{type:`finish`,usage:v})}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)},l=n?.(e)??formatFailureHint(e);l!==void 0&&(i.hint=l);let u=formatFailureDetail(e);return u!==void 0&&(i.detail=u),i}function isQuestionRequest(e){return e.display===`select`||e.display===`text`?!0:e.display===`confirmation`?!1:e.options!==void 0&&e.options.length>0}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};
|
|
1
|
+
import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{pickAgentHeaderTip}from"./agent-header.js";import{probeAgentInfo}from"./agent-info-probe.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{createRemoteConnectionController}from"./remote-connection.js";import{SubagentPump}from"./subagent-pump.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import"#client/index.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createDevelopmentRuntimeArtifactRefresher}from"#services/dev-client.js";import{devBootPhase}from"#internal/dev-boot-progress.js";async function delayMs(e){await new Promise(t=>{setTimeout(t,e).unref?.()})}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;#y;#b;#x=!1;#S=new AbortController;#C=!1;#w=[];#T;#E;#D;#O=pickAgentHeaderTip();#k;#A=new Map;#j;#M=new Map;#N=new Set;#P=!1;#F;constructor(t){this.#e=t.session,t.client!==void 0&&(this.#t=t.client),this.#n=createRenderer(t);let n={formatActionResultError};if(this.#t!==void 0&&(n.client=this.#t),this.#n.subagents!==void 0&&(n.view=this.#n.subagents),this.#j=new SubagentPump(n),this.#r=t.name??`eve`,this.#i=t.tools??`full`,this.#a=t.reasoning??`full`,this.#o=t.subagents??`full`,this.#s=t.connectionAuth??`full`,this.#c=t.assistantResponseStats??`tokensPerSecond`,this.#l=t.contextSize,this.#u=t.formatTransportError??toErrorMessage,t.initialInput!==void 0&&(this.#m=t.initialInput),t.appRoot!==void 0){this.#p=t.appRoot;let e={appRoot:t.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};t.detectProjectIdentity!==void 0&&(e.detectIdentity=t.detectProjectIdentity),this.#E=createVercelStatusTracker(e),t.probeMcpConnection!==void 0&&(this.#D=createMcpConnectionStatusTracker({onChange:()=>{},probe:t.probeMcpConnection}))}if(t.promptCommandHandler!==void 0&&(this.#h=t.promptCommandHandler),this.#g=t.availablePromptCommands??PROMPT_COMMANDS,t.remote!==void 0){if(this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#_=createRemoteConnectionController({client:this.#t,credentials:t.remote.credentials,target:t.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:t.remote.resolveOidcToken,resolveDeployment:t.remote.resolveDeployment})}this.#v=t.bootDetections??BOOT_DETECTIONS,this.#y=t.getVercelAuthStatus??getVercelAuthStatus,t.onBootProgress!==void 0&&(this.#b=t.onBootProgress),t.serverUrl!==void 0&&(this.#f=t.serverUrl),t.serverUrl!==void 0&&t.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactRefresher({serverUrl:t.serverUrl}))}async#I(){if(this.#f===void 0){this.#R(),await this.#q(void 0);return}let e;if(this.#_!==void 0){let t=await this.#_.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}),this.#b);n.kind===`ready`&&(e=n.info)}catch{e=void 0}}this.#R();let t=this.#L(e);await this.#q(t)}#L(e){let t=this.#p===void 0?e:resolveModelProviderState(e,process.env);this.#k=t;let n=this.#f;if(n===void 0)return t;let r={name:this.#r,serverUrl:n};return t!==void 0&&(r.info=t),this.#p!==void 0&&(r.tip=this.#O),this.#n.renderAgentHeader?.(r),t}#R(){let e=this.#b;this.#b=void 0,e?.({type:`before-first-paint`})}async run(){try{await this.#z()}finally{this.#x=!0,this.#S.abort(),this.#j.abortAll(),this.#F?.(),this.#F=void 0,this.#n.shutdown?.(),this.#E?.dispose(),this.#D?.dispose(),this.#_?.dispose()}}async#z(){let e=this.#r,r,i,a=!1,o=!1,s=this.#m;await this.#I(),this.#_?.current().connection.state===`auth-required`&&await this.#re({type:`extension`,name:`vc:login`,argument:``},e,{trigger:`startup`}),this.#Z(),this.#E?.refreshIdentity(),this.#D?.refresh();let c=this.#m===void 0?void 0:parsePromptCommand(this.#m);for(c?.type===`extension`&&c.name===`model`&&c.argument===``&&this.#p!==void 0&&this.#h!==void 0&&this.#n.setupFlow!==void 0&&(s=void 0,await this.#ie(e));;){if(!o){if(r==null){if(!this.#n.readPrompt){if(a)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let t={title:e};s!==void 0&&(t.initialDraft=s,s=void 0);try{r=await this.#H(t)}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let c=parsePromptCommand(r);if(c?.type===`exit`)return;if(c?.type===`new`){if(!await this.#V()){i=void 0,o=!1,r=void 0;continue}i=void 0,o=!1,r=void 0;continue}if(c?.type===`help`){this.#Q(formatPromptCommandHelp(this.#g)),i=void 0,o=!1,r=void 0;continue}if(c?.type===`loglevel`){this.#Q(this.#oe(c.argument)),i=void 0,o=!1,r=void 0;continue}if(c?.type===`extension`){try{await this.#re(c,e,{trigger:`command`})}catch(e){if(isInterruptedError(e))return;throw e}i=void 0,r=void 0,o=!1;continue}a=!0}let c=await this.#U({prompt:o?void 0:r,inputResponses:i}),u=this.#e.state.sessionId;u!==void 0&&this.#n.setSessionId?.(u);let d=r,f=!1;try{for(;;){await this.#n.renderStream(c,{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 t=c.turnState?.pendingApprovals??[],n=c.turnState?.pendingQuestions??[];if(t.length>0||n.length>0){let a=[];if(t.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let n of t){let t=await this.#n.readToolApproval(n,{title:e});a.push({requestId:n.approvalId,optionId:t.approved?`approve`:`deny`}),this.#A.delete(n.approvalId)}}if(n.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 n){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),a.push(i),this.#A.delete(t.requestId)}}if(a.length===0)break;o=!0,i=a,r=void 0,f=!0;break}if(this.#de(c)){c=this.#G(),d=void 0;continue}if(c.turnState&&c.turnState.boundaryEvent===void 0)if(c.turnState.aborted)this.#P=!0;else{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;o=!1,i=void 0,r=void 0;let p=c.turnState?.boundaryEvent;!this.#P&&(p===`session.waiting`||p===`session.completed`)&&(r=this.#n.takeQueuedPrompt?.()),this.#P&&(this.#P=!1,this.#B(),c.turnState?.aborted?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())}}#B(){this.#j.abortAll(),this.#A.clear(),this.#M.clear(),this.#N.clear(),this.#n.setConnectionAuthPendingCount?.(0),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}async#V(){try{await this.#e.reset()}catch(e){return this.#n.renderNotice?.(`Couldn't reset the session: ${toErrorMessage(e)}`),!1}return this.#B(),this.#n.reset?.(),!0}async#H(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,refresh=async()=>{if(!(r||i)){i=!0;try{await n.refreshIdle({onRuntimeArtifactsChanged:()=>this.#le()})}finally{i=!1}}},startRefresh=()=>{if(r||i)return;let e=refresh().finally(()=>{a===e&&(a=void 0)});a=e};startRefresh();let o=setInterval(()=>{startRefresh()},500);o.unref?.();try{return await t}finally{r=!0,clearInterval(o),await a}}async#U(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;try{this.#d!==void 0&&await this.#d.refresh({inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#le()}),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),r=await this.#e.send(n)}catch(e){if(isInterruptedError(e))throw e;return this.#_?.reportFailure(e),this.#P=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}return this.#K(r,()=>t.abort())}async#W(e){if(e.cancelInFlight!==!0){e.cancelInFlight=!0;try{for(let t=0;t<8;t+=1){if(e.boundaryEvent!==void 0||e.aborted===!0)return;let t=e.turnId;try{if((await this.#e.cancel(t===void 0?void 0:{turnId:t})).status===`accepted`)return}catch{}await delayMs(250)}}finally{e.cancelInFlight=!1}}}#G(){let e=new AbortController;return this.#K(this.#e.stream({signal:e.signal}),()=>e.abort())}#K(e,t){let n=createTurnState();return{abort:()=>{n.aborted=!0,t()},cancel:()=>{this.#W(n)},events:eveEventsToTUIStream({events:e,pendingInputRequests:this.#A,turnState:n,onSubagentCalled:e=>this.#j.begin(e),onSubagentCompleted:e=>this.#j.settle(e),onTurnCancelled:()=>this.#j.settleAll(),onConnectionAuthRequired:e=>this.#ue(e),onConnectionAuthCompleted:e=>this.#fe(e),onTerminalFailure:()=>{this.#P=!0},failureHintOverride:this.#p===void 0?void 0:localFailureHint}),turnState:n}}async#q(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#w=await detectSetupIssues(t,this.#v),this.#n.renderSetupWarning!==void 0&&(this.#J(),this.#Y())}#J(){let e=orderedSetupIssues(this.#w,this.#T);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#Y(){let e=this.#p;if(e===void 0)return;let t;try{t=await this.#y(e,{signal:this.#S.signal})}catch{return}this.#x||this.#C||(this.#T=authIssueForStatus(t),this.#J())}async#X(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n={appRoot:t,env:process.env};e!==void 0&&(n.info=e);try{this.#w=await detectSetupIssues(n,this.#v);let e=await this.#y(t,{signal:this.#S.signal});this.#T=authIssueForStatus(e)}catch{return}this.#x||this.#J()}#Z(){this.#p===void 0||this.#n.renderSandboxLog===void 0||this.#F===void 0&&(this.#F=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#Q(e){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}}async#$(e,t){let n=this.#h;if(n===void 0)return{message:`/${e.name} is not available in this session.`};let r={renderer:this.#n,title:t.title,initialModelStep:t.initialModelStep,remoteConnection:this.#_},i=this.#D?.current(),a=i!==void 0&&Object.keys(i).length>0?{...r,disabledConnectionReasons:i}:r;return t.keepSetupFlowOpen===!0?await n.handle(e,{...a,keepSetupFlowOpen:!0}):await n.handle(e,a)}#ee(e,t){if(t!==`startup`)return;let n=this.#_?.current().connection.state,r=n===`auth-failed`||n===`unavailable`?`failed`:void 0,i=e.argument.length===0?``:` ${e.argument}`;this.#n.renderCommandInvocation?.(`/${e.name}${i}`,r)}async#te(e){if(e?.kind===`connection-added`){this.#E?.applyEffect({kind:`refresh-identity`}),this.#C=!0,await this.#ne(),await this.#se();return}if(e?.kind===`model-access-changed`){this.#E?.applyEffect({kind:`refresh-identity`}),this.#C=!0,await this.#se();return}e!==void 0&&(this.#E?.applyEffect(e),this.#C=!0,this.#X(this.#k))}async#ne(){let e=this.#d;e!==void 0&&await e.refreshAfterSourceChange({onRuntimeArtifactsChanged:()=>this.#le()})}async#re(e,t,n){let r=await this.#$(e,{initialModelStep:n.initialModelStep,keepSetupFlowOpen:n.keepSetupFlowOpen,title:t});this.#ee(e,n.trigger),this.#Q(r?.message),await this.#te(r?.effect),this.#ae()}async#ie(e){let t=this.#p;if(t===void 0)return;let authStatus=async()=>{try{return await this.#y(t,{signal:this.#S.signal})}catch{return}},n=await authStatus();if(n===`cli-missing`&&(await this.#re({type:`extension`,name:`vc:install`,argument:``},e,{trigger:`startup`,keepSetupFlowOpen:!0}),n=await authStatus(),n===`cli-missing`)){this.#n.setupFlow?.end();return}if(n===`logged-out`&&(await this.#re({type:`extension`,name:`vc:login`,argument:``},e,{trigger:`startup`,keepSetupFlowOpen:!0}),n=await authStatus(),n===`cli-missing`||n===`logged-out`)){this.#n.setupFlow?.end();return}await this.#re({type:`extension`,name:`model`,argument:``},e,{trigger:`startup`,initialModelStep:`provider`})}#ae(){let e=this.#_?.current().connection;e?.state!==`ready`||e.info===this.#k||(this.#k=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}#oe(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#se(){let e=this.#p;if(e===void 0)return;loadDevelopmentEnvironmentFiles(e);let t=this.#L(await this.#ce());this.#X(t)}async#ce(){let e=this.#t;if(e===void 0)return;let t=await probeAgentInfo({client:e});return t.kind===`ready`?t.info:void 0}async#le(){let e=this.#k,t=await this.#ce();t!==void 0&&this.#L(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#ue(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.#M.set(e.data.name,t),this.#pe(t)}#de(e){if(e.turnState?.boundaryEvent!==`session.waiting`)return!1;let t=!1;for(let e of this.#M.values())e.state!==`required`||e.webhookUrl===void 0||(e.state=`pending`,this.#N.add(e.name),this.#pe(e),t=!0);return t&&this.#n.setConnectionAuthPendingCount?.(this.#N.size),this.#N.size>0}#fe(e){let t=this.#M.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.#M.set(e.data.name,t),this.#N.delete(e.data.name),this.#pe(t),this.#n.setConnectionAuthPendingCount?.(this.#N.size)}#pe(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})}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.`}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,turnState:r,onSubagentCalled:i,onSubagentCompleted:a,onTurnCancelled:o,onConnectionAuthRequired:s,onConnectionAuthCompleted:c,onTerminalFailure:l,failureHintOverride:u}=e,d=new Map,f=new Map,p=0,m=new Set,h=new Set,g=new Set,_=!1,v=!1,y;for await(let e of t)if(!(v&&isPostTurnVisibleEvent(e)))switch(e.type){case`session.started`:case`message.received`:break;case`turn.started`:r.turnId=e.data.turnId;break;case`step.started`:p+=1,yield{type:`step-start`};break;case`step.completed`:{let t=e;y=t.data.usage,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`step-finish`,usage:t.data.usage};break}case`message.appended`:{let t=e,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(d,n),i=t.data.messageSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`message.completed`:{let t=textPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(d,t),r=e.data.message;if(n.completed){if(r===null||r===n.text||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p,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=p,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let e=r.slice(n.text.length);e.length>0&&(yield{type:`assistant-delta`,id:i,delta:e}),n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i}}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let t=e,n=reasoningPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(f,n),i=t.data.reasoningSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`reasoning-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`reasoning.completed`:{let t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(f,t),r=e.data.reasoning;if(n.completed){if(r.length===0||r===n.text||n.text.startsWith(r)||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}let i=partGenerationId(t,n.generation);if(n.text.length===0&&r.length>0)n.text=r,yield{type:`reasoning-delta`,id:i,delta:r};else if(r.length>0&&!r.startsWith(n.text))break;n.completed=!0,n.completedEpoch=p,yield{type:`reasoning-complete`,id:i};break}case`actions.requested`:{let t=e.data.actions.filter(e=>e.kind===`tool-call`);if(t.length===0)break;for(let e of t)m.has(e.callId)||(m.add(e.callId),yield{type:`tool-call`,toolCallId:e.callId,toolName:e.toolName,input:e.input});break}case`input.requested`:{let t=e.data.requests.filter(e=>e.action.kind===`tool-call`);if(t.length===0)break;for(let e of t){let t=e.action.callId;if(m.has(t)||(m.add(t),yield{type:`tool-call`,toolCallId:t,toolName:e.action.toolName,input:e.action.input}),!h.has(e.requestId)){if(h.add(e.requestId),n.set(e.requestId,e),isQuestionRequest(e)){upsertPendingQuestion(r,e);continue}upsertPendingApproval(r,e),yield{type:`tool-approval-request`,approvalId:e.requestId,toolCallId:t}}}break}case`action.result`:{let t=e;if(t.data.result.kind!==`tool-result`)break;let n=t.data.result.callId;if(!m.has(n))break;switch(t.data.status){case`completed`:yield{type:`tool-result`,toolCallId:n,output:t.data.result.output};break;case`failed`:yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)};break;case`rejected`:yield{type:`tool-rejected`,toolCallId:n,reason:formatActionResultError(t)};break}break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,g,u);t&&(yield t);break}case`session.failed`:{r.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,g,u);t&&(yield t),r.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:y},_=!0;return}case`session.waiting`:case`session.completed`:r.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:y},_=!0;return;case`turn.completed`:v=!0,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p);break;case`turn.cancelled`:o?.(),yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`turn-cancelled`};break;case`subagent.called`:i?.(e);break;case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:a?.(e.data.callId);break;case`authorization.required`:s?.(e);break;case`authorization.completed`:c?.(e);break;default:break}_||(yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:y})}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)},l=n?.(e)??formatFailureHint(e);l!==void 0&&(i.hint=l);let u=formatFailureDetail(e);return u!==void 0&&(i.detail=u),i}function isQuestionRequest(e){return e.display===`select`||e.display===`text`?!0:e.display===`confirmation`?!1:e.options!==void 0&&e.options.length>0}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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createTuiPrompter}from"./tui-prompter.js";import{runDeployFlow}from"#setup/flows/deploy.js";import{WizardCancelledError}from"#setup/step.js";import{runLoginFlow}from"#setup/flows/login.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{runChannelsFlow}from"#setup/flows/channels.js";import{runConnectionsFlow}from"#setup/flows/connections.js";import{runInstallVercelCliFlow}from"#setup/flows/install-vercel-cli.js";import{runModelFlow}from"#setup/flows/model.js";import{runProviderFlow}from"#setup/flows/provider.js";import{openUrl}from"#setup/primitives/open-url.js";import{slackMessageDeepLink}from"#setup/slack-connect.js";const SETUP_FLOW_CONFIG={"vc:install":{title:`Install the Vercel CLI`,indicator:`pulse`},"vc:login":{title:`Log in to Vercel`,indicator:`pulse`},model:{title:`Configure the agent model`,indicator:`pulse`},channels:{title:`Agent channels`,indicator:`pulse`},connect:{title:`Agent connections`,indicator:`pulse`},deploy:{title:`Deploy to Vercel`,indicator:`spinner`}};function muteableRenderer(e,t){return{readSelect:n=>t()?Promise.resolve(void 0):e.readSelect(n),readEditableSelect:n=>t()?Promise.resolve(void 0):e.readEditableSelect(n),readProviderPicker:n=>t()?Promise.resolve(void 0):e.readProviderPicker(n),readModelEditor:n=>t()?Promise.resolve(void 0):e.readModelEditor(n),readText:n=>t()?Promise.resolve(void 0):e.readText(n),readAcknowledge:n=>t()?Promise.resolve():e.readAcknowledge(n),readChoice:n=>t()?{choice:Promise.resolve(void 0),close:()=>{}}:e.readChoice(n),setStatus:n=>{t()||e.setStatus(n)},renderLine:(n,r)=>{(!t()||r===`warning`||r===`error`)&&e.renderLine(n,r)},renderOutput:n=>{t()||e.renderOutput(n)}}}async function runTuiSetupCommand(t){let{command:r}=t,i=!1,a=new AbortController,o=muteableRenderer(t.renderer,()=>i),s=(t.createPrompter??createTuiPrompter)(o),c=t.renderer.waitForInterrupt(),l=Symbol(`interrupted`),u=executeSetupCommand(t,s,o,a.signal);try{let e=await Promise.race([u,c.promise.then(()=>l)]);return e===l?(i=!0,a.abort(new WizardCancelledError),{...await u,message:`/${r} interrupted.`,preserveFlowDiagnostics:!0}):e}finally{c.dispose(),t.renderer.setStatus(void 0)}}async function executeSetupCommand(e,i,u,d){let{command:f,appRoot:p}=e,m={runInstallVercelCliFlow,runLoginFlow,runModelFlow,runChannelsFlow,runConnectionsFlow,runDeployFlow,...e.flows};try{switch(f){case`vc:install`:return installVercelCliResultMessage(await m.runInstallVercelCliFlow({appRoot:p,prompter:i,signal:d}));case`vc:login`:return loginResultMessage(await m.runLoginFlow({appRoot:p,prompter:i,signal:d}));case`model`:{let pickProvider=e=>u.readProviderPicker(e),t={appRoot:p,prompter:i,signal:d,deps:{pickModelSettings:e=>u.readModelEditor(e),runProviderFlow:e=>runProviderFlow({...e,picker:pickProvider})}};e.initialModelStep!==void 0&&(t.initialStep=e.initialModelStep);let n=await m.runModelFlow(t);if(n.kind===`cancelled`)return{message:n.discardedDraft===!0?`/model dismissed. Drafted changes were discarded; Done commits them.`:`/model dismissed.`,preserveFlowDiagnostics:!1};let r=[];n.modelMessage!==void 0&&r.push(n.modelMessage),n.providerOutcome!==void 0&&r.push(providerOutcomeMessage(n.providerOutcome));let a={message:r.join(`
|
|
2
|
-
`),preserveFlowDiagnostics:!1};return n.providerOutcome!==void 0&&(a.effect={kind:`model-access-changed`}),a}case`channels`:{let e=await m.runChannelsFlow({appRoot:p,prompter:i,signal:d});switch(e.kind){case`failed`:return pendingChannelsResult(`Channel files changed, but /channels failed: ${e.message}`);case`cancelled`:return{message:`/channels dismissed.`,preserveFlowDiagnostics:!0};case`deploy-and-chat`:return await runDeployAndChat(m,{appRoot:p,prompter:i,signal:d},e.chat);case`done`:return e.addedChannels.length===0?{message:`No channels added.`,preserveFlowDiagnostics:!0}:{message:`Channels added: ${e.addedChannels.join(`, `)} — run /deploy to ship them.`,preserveFlowDiagnostics:!0,effect:{kind:`channels-added`}}}}case`connect`:{let t=await m.runConnectionsFlow({appRoot:p,prompter:i,signal:d,disabledConnectionReasons:e.disabledConnectionReasons});switch(t.kind){case`cancelled`:return{message:`/connect dismissed.`,preserveFlowDiagnostics:!0,effect:{kind:`model-access-changed`}};case`failed`:return{message:t.addedConnections.length===0?`/connect failed: ${t.message}`:`Connection files changed, but /connect failed: ${t.message}`,preserveFlowDiagnostics:!0,effect:t.addedConnections.length===0?{kind:`model-access-changed`}:{kind:`connection-added`}};case`done`:return{message:t.addedConnections.length===0?`No connections added.`:`Connections added: ${t.addedConnections.join(`, `)}.`,preserveFlowDiagnostics:!0,effect:t.addedConnections.length===0?{kind:`model-access-changed`}:{kind:`connection-added`}}}}case`deploy`:{let e=await m.runDeployFlow({appRoot:p,prompter:i,interactive:!0,signal:d});return e.kind===`cancelled`?{message:`/deploy dismissed.`,preserveFlowDiagnostics:!0}:e.kind===`needs-link`?{message:`Not linked to a Vercel project — run /model to connect one first.`,preserveFlowDiagnostics:!0}:{message:e.productionUrl===void 0?`Deployed.`:`Deployed: ${e.productionUrl}`,preserveFlowDiagnostics:!0,effect:{kind:`deployed`}}}}}catch(e){if(e instanceof WizardCancelledError)return{message:`/${f} dismissed.`,preserveFlowDiagnostics:f!==`model`};let t=vercelActionOutcome(e,f);return
|
|
2
|
+
`),preserveFlowDiagnostics:!1};return n.providerOutcome!==void 0&&(a.effect={kind:`model-access-changed`}),a}case`channels`:{let e=await m.runChannelsFlow({appRoot:p,prompter:i,signal:d});switch(e.kind){case`failed`:return pendingChannelsResult(`Channel files changed, but /channels failed: ${e.message}`);case`cancelled`:return{message:`/channels dismissed.`,preserveFlowDiagnostics:!0};case`deploy-and-chat`:return await runDeployAndChat(m,{appRoot:p,prompter:i,signal:d},e.chat);case`done`:return e.addedChannels.length===0?{message:`No channels added.`,preserveFlowDiagnostics:!0}:{message:`Channels added: ${e.addedChannels.join(`, `)} — run /deploy to ship them.`,preserveFlowDiagnostics:!0,effect:{kind:`channels-added`}}}}case`connect`:{let t=await m.runConnectionsFlow({appRoot:p,prompter:i,signal:d,disabledConnectionReasons:e.disabledConnectionReasons});switch(t.kind){case`cancelled`:return{message:`/connect dismissed.`,preserveFlowDiagnostics:!0,effect:{kind:`model-access-changed`}};case`failed`:return{message:t.addedConnections.length===0?`/connect failed: ${t.message}`:`Connection files changed, but /connect failed: ${t.message}`,preserveFlowDiagnostics:!0,effect:t.addedConnections.length===0?{kind:`model-access-changed`}:{kind:`connection-added`}};case`done`:return{message:t.addedConnections.length===0?`No connections added.`:`Connections added: ${t.addedConnections.join(`, `)}.`,preserveFlowDiagnostics:!0,effect:t.addedConnections.length===0?{kind:`model-access-changed`}:{kind:`connection-added`}}}}case`deploy`:{let e=await m.runDeployFlow({appRoot:p,prompter:i,interactive:!0,signal:d});return e.kind===`cancelled`?{message:`/deploy dismissed.`,preserveFlowDiagnostics:!0}:e.kind===`needs-link`?{message:`Not linked to a Vercel project — run /model to connect one first.`,preserveFlowDiagnostics:!0}:{message:e.productionUrl===void 0?`Deployed.`:`Deployed: ${e.productionUrl}`,preserveFlowDiagnostics:!0,effect:{kind:`deployed`}}}}}catch(e){if(e instanceof WizardCancelledError)return{message:`/${f} dismissed.`,preserveFlowDiagnostics:f!==`model`};let t=await vercelCliUpgradeOutcome(e,f,m,{appRoot:p,prompter:i,signal:d});if(t!==void 0)return t;let r=vercelActionOutcome(e,f);return r===void 0?{message:`/${f} failed: ${e instanceof Error?e.message:String(e)}`,preserveFlowDiagnostics:!0}:r}}async function vercelCliUpgradeOutcome(e,t,n,r){if(!(e instanceof HumanActionRequiredError)||e.action.kind!==`vercel-cli-upgrade`)return;let a;try{a=await r.prompter.select({message:`Your Vercel CLI needs an update to list your teams. Upgrade now?`,options:[{value:`upgrade`,label:`Upgrade Vercel CLI`,description:`Run the Vercel CLI's native upgrader`},{value:`later`,label:`Not now`}],initialValue:`upgrade`})}catch{a=`later`}if(a===`later`)return{message:`The Vercel CLI needs an update — run \`vercel upgrade\`, then retry /${t}.`,preserveFlowDiagnostics:!0};let o;try{o=await n.runInstallVercelCliFlow({appRoot:r.appRoot,prompter:r.prompter,signal:r.signal,upgrade:!0})}catch(e){return{message:vercelCliUpgradeFailureMessage(t,errorMessage(e)),preserveFlowDiagnostics:!0}}switch(o.kind){case`installed`:return{message:`Upgraded the Vercel CLI. Retry /${t}.`,preserveFlowDiagnostics:!1};case`failed`:return{message:vercelCliUpgradeFailureMessage(t,o.reason),preserveFlowDiagnostics:!0};case`cancelled`:return{message:`Vercel CLI upgrade cancelled — run \`vercel upgrade\`, then retry /${t}.`,preserveFlowDiagnostics:!0};case`already`:return{message:`The Vercel CLI is already up to date. Retry /${t}.`,preserveFlowDiagnostics:!1}}}function errorMessage(e){let t=(e instanceof Error?e.message:String(e)).replace(/\s+/gu,` `).trim();return t.length<=240?t:`${t.slice(0,239)}…`}function vercelCliUpgradeFailureMessage(e,t){return`Couldn't upgrade the Vercel CLI${t===void 0||t===``?``:` (${t})`} — run \`vercel upgrade\`, then retry /${e}.`}function vercelActionOutcome(e,t){if(!(e instanceof HumanActionRequiredError))return;let n=vercelActionMessage(e.action.kind,t);return n===void 0?void 0:{message:n,preserveFlowDiagnostics:!0}}function vercelActionMessage(e,t){switch(e){case`vercel-login`:return`You're not logged in to Vercel — run /vc:login, then retry /${t}.`;case`vercel-forbidden`:return`Vercel denied access to that team — run /vc:login to re-authenticate (for example to complete SSO), or pick a team you can access, then retry /${t}.`;case`vercel-cli-missing`:return`The Vercel CLI isn't installed — run /vc:install to install it, then retry /${t}.`;case`vercel-cli-upgrade`:return`The Vercel CLI needs an update — run \`vercel upgrade\`, then retry /${t}.`;default:return}}async function runDeployAndChat(e,t,r){let i;try{i=await e.runDeployFlow({...t,interactive:!0})}catch(e){if(e instanceof WizardCancelledError)return pendingChannelsResult(`Channels added, but /deploy was dismissed. Run /deploy to ship them.`);let t=vercelActionOutcome(e,`deploy`);return pendingChannelsResult(t===void 0?`Channels added, but /deploy failed: ${e instanceof Error?e.message:String(e)}`:`Channels added. ${t.message}`)}if(i.kind===`cancelled`)return pendingChannelsResult(`Channels added, but /deploy was dismissed. Run /deploy to ship them.`);if(i.kind===`needs-link`)return pendingChannelsResult(`Channels added, but this directory is not linked to Vercel. Run /model, then /deploy.`);let a=i.productionUrl===void 0?`Deployed.`:`Deployed: ${i.productionUrl}`,o;if(r.chatUrl===void 0)o=`Message your agent in Slack to see it live.`;else{let e=slackMessageDeepLink(r.chatUrl);openUrl(e),o=`Chat with your agent in Slack: ${e}`}return{message:`${a}\n${o}`,preserveFlowDiagnostics:!0,effect:{kind:`deployed`}}}function installVercelCliResultMessage(e){switch(e.kind){case`cancelled`:return{message:`/vc:install dismissed.`,preserveFlowDiagnostics:!1};case`already`:return{message:`The Vercel CLI is already installed.`,preserveFlowDiagnostics:!1};case`failed`:return{message:"Couldn't install the Vercel CLI — install it manually with `npm i -g vercel@latest`.",preserveFlowDiagnostics:!0};case`installed`:return{message:`Installed the Vercel CLI. Run /vc:login next.`,preserveFlowDiagnostics:!1,effect:{kind:`refresh-identity`}}}}function loginResultMessage(e){switch(e.kind){case`cancelled`:return{message:`/vc:login dismissed.`,preserveFlowDiagnostics:!1};case`already`:return{message:`You're already logged in to Vercel.`,preserveFlowDiagnostics:!1};case`cli-missing`:return{message:`The Vercel CLI isn't installed — run /vc:install to install it, then retry /vc:login.`,preserveFlowDiagnostics:!0};case`failed`:return{message:`Vercel login didn't complete — run /vc:login to try again.`,preserveFlowDiagnostics:!0};case`logged-in`:return{message:`Logged in to Vercel.`,preserveFlowDiagnostics:!1,effect:{kind:`refresh-identity`}};case`unavailable`:return{message:`Couldn't reach Vercel — check your connection, then retry /vc:login.`,preserveFlowDiagnostics:!0}}}function pendingChannelsResult(e){return{message:e,preserveFlowDiagnostics:!0,effect:{kind:`channels-added`}}}function providerOutcomeMessage(e){let{resolution:t,status:n}=e;if(n.kind===`gateway-project`)return t===void 0?`Project linked. No model credential found; set AI_GATEWAY_API_KEY in .env.local.`:t.credential===`oidc`?`Project linked. Connected to AI Gateway via VERCEL_OIDC_TOKEN.`:t.shadowedOidc===void 0?`Project linked. Connected to AI Gateway via AI_GATEWAY_API_KEY.`:`Project linked. AI_GATEWAY_API_KEY (${t.source.kind===`shell`?`shell`:t.source.path}) outranks the project's VERCEL_OIDC_TOKEN and stays the active credential — ${t.source.kind===`shell`?`unset it in your shell`:`remove it from ${t.source.path}`} to run on the project.`;if(n.kind===`gateway-key`){let e=n.source.kind===`shell`?`your shell`:n.source.path;return`Connected to AI Gateway via ${n.envKey} in ${e}.`}return`Provider updated — no gateway credential detected; set AI_GATEWAY_API_KEY in .env.local.`}export{SETUP_FLOW_CONFIG,runTuiSetupCommand};
|
|
@@ -123,5 +123,14 @@ export declare class SubagentPump {
|
|
|
123
123
|
*/
|
|
124
124
|
settle(callId: string): void;
|
|
125
125
|
abortAll(): void;
|
|
126
|
+
/**
|
|
127
|
+
* Settles every live run and stops its child stream. Called when the
|
|
128
|
+
* parent turn is cancelled (an Esc steer or Esc Esc): the server cancels
|
|
129
|
+
* the pending descendants, so their sections must close now — a child
|
|
130
|
+
* still flushing reasoning would otherwise keep painting stale sections
|
|
131
|
+
* into the next (steered) turn's transcript. Runs stay registered so a
|
|
132
|
+
* late parent `subagent.completed` settles as a no-op.
|
|
133
|
+
*/
|
|
134
|
+
settleAll(): void;
|
|
126
135
|
}
|
|
127
136
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isAbortLikeError}from"./errors.js";import{toErrorMessage}from"#shared/errors.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";var SubagentPump=class{#e;#t;#n;#r=new Map;#i=new Map;constructor(e){this.#e=e.client,this.#t=e.view,this.#n=e.formatActionResultError}begin(e){let t=e.data.callId,n=this.#r.get(t);n===void 0?this.#r.set(t,{name:e.data.name,status:`running`,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map}):n.name=e.data.name,this.#t?.markChildToolCallId(t),this.#t?.begin({callId:t,name:e.data.name}),this.#a(e)}settle(e){this.#s(e)}abortAll(){for(let e of this.#i.values())e.abort();this.#i.clear(),this.#r.clear()}#a(r){let i=r.data.callId;if(this.#i.has(i))return;let a=this.#e;if(!a)return;let o=new AbortController;this.#i.set(i,o),(async()=>{let s=!1;try{let e=a.session({sessionId:r.data.childSessionId,streamIndex:0}).stream({signal:o.signal});for await(let t of e){if(o.signal.aborted)break;if(this.#l(i,t),isCurrentTurnBoundaryEvent(t)){s=!0;break}}}catch(n){if(!isAbortLikeError(n)){let e=toErrorMessage(n),r=this.#r.get(i);if(r){let{key:t,step:n}=openCurrentSubagentSection(r);n.message=n.message?`${n.message}\n\nstream error: ${e}`:`stream error: ${e}`,n.finalized=!0,r.currentSectionKey=null,this.#t?.upsertStep({callId:i,subagentName:r.name,sectionKey:t,reasoning:n.reasoning,message:n.message,finalized:!0})}}}finally{this.#i.delete(i)}s&&this.#s(i)})()}#o(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={preparing:0,"approval-requested":1,executing:2,done:3,failed:3,rejected:3};e[n.status]>e[r.status]&&(r.status=n.status),n.input!==void 0&&(r.input=n.input)}else t.tools.set(n.childCallId,i);this.#t?.markChildToolCallId(n.childCallId),this.#t?.upsertTool({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#s(e){let t=this.#r.get(e);if(!(!t||t.status===`settled`)){t.status=`settled`;for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#t?.upsertStep({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null,this.#c(e,t),this.#t?.complete({callId:e})}}#c(e,t){for(let[n,r]of t.tools)r.status===`preparing`&&(t.tools.delete(n),this.#t?.removeTool({callId:e,childCallId:n}))}#l(e,t){let n=this.#r.get(e);if(!n)return;n.status===`settled`&&(n.status=`running`,this.#t?.begin({callId:e,name:n.name}));let r=this.#t,emit=(t,i)=>{r?.upsertStep({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent(),this.#c(e,n);break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#o(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#o(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;switch(t.data.status){case`completed`:a.status=`done`,a.output=i.output;break;case`failed`:a.status=`failed`,a.errorText=this.#n(t);break;case`rejected`:a.status=`rejected`,a.errorText=this.#n(t);break}let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r?.upsertTool(o);break}default:break}}};function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{SubagentPump};
|
|
1
|
+
import{isAbortLikeError}from"./errors.js";import{toErrorMessage}from"#shared/errors.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";var SubagentPump=class{#e;#t;#n;#r=new Map;#i=new Map;constructor(e){this.#e=e.client,this.#t=e.view,this.#n=e.formatActionResultError}begin(e){let t=e.data.callId,n=this.#r.get(t);n===void 0?this.#r.set(t,{name:e.data.name,status:`running`,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map}):n.name=e.data.name,this.#t?.markChildToolCallId(t),this.#t?.begin({callId:t,name:e.data.name}),this.#a(e)}settle(e){this.#s(e)}abortAll(){for(let e of this.#i.values())e.abort();this.#i.clear(),this.#r.clear()}settleAll(){for(let e of this.#r.keys())this.#s(e);for(let e of this.#i.values())e.abort();this.#i.clear()}#a(r){let i=r.data.callId;if(this.#i.has(i))return;let a=this.#e;if(!a)return;let o=new AbortController;this.#i.set(i,o),(async()=>{let s=!1;try{let e=a.session({sessionId:r.data.childSessionId,streamIndex:0}).stream({signal:o.signal});for await(let t of e){if(o.signal.aborted)break;if(this.#l(i,t),isCurrentTurnBoundaryEvent(t)){s=!0;break}}}catch(n){if(!isAbortLikeError(n)){let e=toErrorMessage(n),r=this.#r.get(i);if(r){let{key:t,step:n}=openCurrentSubagentSection(r);n.message=n.message?`${n.message}\n\nstream error: ${e}`:`stream error: ${e}`,n.finalized=!0,r.currentSectionKey=null,this.#t?.upsertStep({callId:i,subagentName:r.name,sectionKey:t,reasoning:n.reasoning,message:n.message,finalized:!0})}}}finally{this.#i.delete(i)}s&&this.#s(i)})()}#o(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={preparing:0,"approval-requested":1,executing:2,done:3,failed:3,rejected:3};e[n.status]>e[r.status]&&(r.status=n.status),n.input!==void 0&&(r.input=n.input)}else t.tools.set(n.childCallId,i);this.#t?.markChildToolCallId(n.childCallId),this.#t?.upsertTool({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#s(e){let t=this.#r.get(e);if(!(!t||t.status===`settled`)){t.status=`settled`;for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#t?.upsertStep({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null,this.#c(e,t),this.#t?.complete({callId:e})}}#c(e,t){for(let[n,r]of t.tools)r.status===`preparing`&&(t.tools.delete(n),this.#t?.removeTool({callId:e,childCallId:n}))}#l(e,t){let n=this.#r.get(e);if(!n)return;n.status===`settled`&&(n.status=`running`,this.#t?.begin({callId:e,name:n.name}));let r=this.#t,emit=(t,i)=>{r?.upsertStep({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent(),this.#c(e,n);break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#o(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#o(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;switch(t.data.status){case`completed`:a.status=`done`,a.output=i.output;break;case`failed`:a.status=`failed`,a.errorText=this.#n(t);break;case`rejected`:a.status=`rejected`,a.errorText=this.#n(t);break}let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r?.upsertTool(o);break}default:break}}};function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{SubagentPump};
|
|
@@ -61,6 +61,13 @@ export declare class TerminalRenderer implements AgentTUIRenderer {
|
|
|
61
61
|
*/
|
|
62
62
|
renderAgentHeader(options: AgentHeaderOptions): void;
|
|
63
63
|
readPrompt(options?: AgentTUISessionOptions): Promise<string>;
|
|
64
|
+
/**
|
|
65
|
+
* Consumes the next prompt produced by mid-turn input — the staged Esc
|
|
66
|
+
* steer message, or the whole queue coalesced into one. The runner calls
|
|
67
|
+
* this at a clean turn boundary and submits the result directly; the
|
|
68
|
+
* remembered origin marks the echoed user block with its gutter arrow.
|
|
69
|
+
*/
|
|
70
|
+
takeQueuedPrompt(): string | undefined;
|
|
64
71
|
renderStream(result: AgentTUIStreamResult, options?: AgentTUISessionOptions): Promise<void>;
|
|
65
72
|
readToolApproval(request: AgentTUIToolApprovalRequest, options?: AgentTUISessionOptions): Promise<AgentTUIToolApprovalResponse>;
|
|
66
73
|
readInputQuestion(question: AgentTUIInputQuestion, options?: AgentTUISessionOptions): Promise<AgentTUIInputQuestionResponse | undefined>;
|
|
@@ -129,6 +136,8 @@ export declare class TerminalRenderer implements AgentTUIRenderer {
|
|
|
129
136
|
* connector (` ⎿ /model cancelled.`), Claude Code's sub-result grammar.
|
|
130
137
|
*/
|
|
131
138
|
renderCommandResult(text: string): void;
|
|
139
|
+
/** Last server session id the runner reported; named in the parting line. */
|
|
140
|
+
setSessionId(sessionId: string): void;
|
|
132
141
|
shutdown(): void;
|
|
133
142
|
/** The log sources the transcript currently renders. */
|
|
134
143
|
logDisplayMode(): LogDisplayMode;
|
|
@@ -1,13 +1,15 @@
|
|
|
1
|
-
import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{interruptedError}from"./errors.js";import{FileContentCache}from"./file-content-cache.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{initialModelEditorState,transitionModelEditor}from"./model-editor.js";import{promptPlaceholder}from"./prompt-placeholder.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{enterBadge,renderAcknowledgeQuestion,renderFlowPanel,renderModelEditorQuestion,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{TurnClock}from"./turn-clock.js";import{allTodoItemsSettled,readTodoToolItems,renderFinishedTodoRows,renderTodoPanelRows}from"./todo-panel.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{inspectError}from"#internal/logging.js";import{eveVersionTag}from"#cli/banner.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{LiveRegion}from"#cli/ui/live-region.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";import{readGatewayServiceTier}from"#shared/gateway-service-tier.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e
|
|
2
|
-
`);if(this.#w){t!==this.#T&&(this.#T=t,this.#_t({kind:`agent-header`,body:t,live:!1})),this.#Rt();return}this.#w=!0,this.#T=t,this.#n.flush(this.#Ut(),[])}async readPrompt(e){this.#nt(e),this.#gt(),this.#yt(),this.#P=!0,this.#I=!0,this.#H={kind:`idle`},this.#W=``;let r=lineOf(stripPromptControlCharacters(e?.initialDraft??this.#B.text));return this.#B=EMPTY_LINE,this.#N.begin(r.text),this.#Me(r),this.#F=typeaheadFor(this.#d,r.text),this.#dt(),this.#Rt(),await new Promise((e,i)=>{this.#U=i;let apply=e=>{r=e,this.#pt(),this.#Me(r),this.#F=typeaheadFor(this.#d,e.text,this.#F),this.#Rt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#F=void 0,this.#ft(),this.#rt(),i(interruptedError())},suggestions=()=>this.#F!==void 0&&isTypeaheadOpen(this.#F)?this.#F:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ie=i=>{let a=applyLineEditorKey(r,i,{multiline:!0});if(a!==void 0){apply(a);return}switch(i.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#F=moveTypeaheadSelection(e,-1),this.#Rt();break}let t=movePromptLine(r,`up`);t===void 0?recall(this.#N.previous(r.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#F=moveTypeaheadSelection(e,1),this.#Rt();break}let t=movePromptLine(r,`down`);t===void 0?recall(this.#N.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#F=dismissTypeahead(e),this.#Rt());break}case`enter`:{let i=highlighted(),a=i!==void 0&&parsePromptCommand(r.text)===null?typeaheadCompletion(i).trimEnd():r.text;if(a.trim().length===0)break;this.#F=void 0,this.#N.add(a),this.#P=!1,this.#ft(),this.#W=STATUS.processing,isPromptControlCommand(a)?this.#_t({kind:`command`,body:stripTerminalControls(a.trim()),live:!1}):(this.#ht(),this.#vt(a),this.#we=a,this.#z.arm()),this.#Me(EMPTY_LINE),this.#Rt(),this.#at(),e(a);break}case`ctrl-d`:r.text.length===0?interrupt():apply(deleteForward(r));break;case`ctrl-l`:this.#Vt();break;case`ctrl-r`:this.#Rt();break;case`ctrl-c`:r.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#it()})}#Me(e){this.#j=e.text,this.#M=e.cursor}async renderStream(e,t){this.#nt(t),this.#h.clear(),this.#P=!1,this.#H.kind!==`waiting`&&(this.#H={kind:`waiting`,startedAtMs:Date.now()}),this.#W=this.#O>0?STATUS.connectionAuth:STATUS.processing,this.#bt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#u?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#z.armed&&this.#z.arm(),this.#X=!1,this.#fe=void 0,this.#pe=void 0,this.#he=void 0,this.#ge=void 0,this.#_e=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#mt(),this.#V=!0,this.#Rt();let r=new Promise(e=>{this.#le=e});this.#ie=e=>this.#ut(e),this.#it();let i={text:new Map,reasoning:new Map,tools:new Map};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#X)break;this.#Et(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#xt(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#xt(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#le=void 0,this.#X&&e.abort?.(),this.#at(),this.#gt(),this.#V=!1,this.#H.kind===`waiting`&&(this.#H={kind:`idle`}),this.#W=completedTurnStatus(this.#X,t?.continueSession===!0),this.#Nt(i),this.#X&&this.#Mt(),this.#Tt(),this.#u?.reportStats(),this.#Rt(),t?.continueSession||this.#rt()}}async readToolApproval(e,t){return this.#nt(t),this.#gt(),this.#P=!1,this.#H={kind:`idle`},this.#W=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#X=!1,this.#Rt(),await new Promise((t,n)=>{this.#U=n,this.#ie=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#ht(),this.#W=STATUS.processing,this.#at(),this.#Rt(),t({approved:!0})):n===`n`&&(this.#ht(),this.#W=STATUS.processing,this.#Pe(e.toolCallId),this.#at(),this.#Rt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#Rt();break;case`ctrl-c`:this.#X=!0,this.#rt(),n(interruptedError());break;default:break}},this.#it()})}async readInputQuestion(e,t){this.#nt(t),this.#gt(),this.#P=!1,this.#I=!1,this.#H={kind:`idle`},this.#X=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`overlay`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,overlayPanel=t=>renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#Z},this.#r,t),renderTextSection=()=>{this.#Ct({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#r),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#dt():(this.#ft(),this.#pt())};s===`overlay`?(s=`overlay`,this.#P=!1,this.#wt(o),this.#Te=overlayPanel,this.#W=``,syncFreeformCaret(),this.#Rt()):(s=`text`,this.#Te=void 0,renderTextSection(),this.#P=!0,this.#Me(l),this.#W=``,this.#dt(),this.#Rt());let finalize=t=>{this.#Te=void 0,this.#Ct({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#r.colors.dim(this.#r.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#P=!1,this.#ht(),this.#W=STATUS.processing,this.#ft(),this.#at(),this.#Rt();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Te=void 0,this.#Ct({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#r.colors.dim(this.#r.glyph.elbow)} ${this.#r.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#P=!1,this.#W=``,this.#ft(),this.#at(),this.#Rt(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#Rt())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#U=r,u=t,this.#ie=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#pt(),s===`text`&&this.#Me(l),this.#Rt();return}this.#X=!0,this.#Te=void 0,this.#ft(),this.#rt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#Rt();return}if(s===`overlay`){switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#pt(),this.#Rt();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#pt(),this.#Rt());break}if(t.type===`text`&&/^[1-9]$/u.test(t.value)){let e=Number(t.value)-1;e<n.length?selectOptionAt(e):e===n.length&&i&&(c=e,syncFreeformCaret(),this.#Rt())}break}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#pt(),this.#Me(l),this.#Rt();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#pt(),this.#Me(l),this.#Rt());break}case`enter`:{let t=resolveQuestionText(l.text,e);if(t===void 0)break;u(finalize(t));break}case`escape`:if(l.text.length>0){l=EMPTY_LINE,this.#pt(),this.#Me(l),this.#Rt();break}dismiss();break;default:break}},this.#it()})}upsertSubagentStep(e){if(this.#u?.recordSubagentDispatch(e.callId),this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#St(e.callId,e.subagentName),this.#o===`collapsed`){this.#Rt();return}this.#Ct({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#o!==`full`,live:!e.finalized}),this.#Rt()}}upsertSubagentTool(e){if(this.#u?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#u?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#o===`hidden`)return;if(this.#St(e.callId,e.subagentName),this.#o===`collapsed`){this.#Rt();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#At({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#Ct(r),this.#Ne(e.callId),this.#Rt()}#Ne(e){applyCohortLiveness(this.#p.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#wt(subagentToolSectionId(e.callId,e.childCallId)),this.#Rt()}subagents={begin:e=>this.beginSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#o===`hidden`)return;this.#St(e.callId,e.name);let t=this.#m.get(subagentHeaderId(e.callId));t?.status===`done`&&delete t.status,this.#Rt()}completeSubagent(e){let t=this.#m.get(subagentHeaderId(e.callId));t!==void 0&&(t.status=`done`,this.#Rt())}markChildToolCallId(e){this.#_.add(e);let t=this.#v.get(e);t!==void 0&&(this.#wt(t),this.#v.delete(e),this.#Rt())}#Pe(e){let t=this.#m.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#Ct({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#Rt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#O)return;let n=this.#O>0;this.#O=t,t>0?(this.#W=STATUS.connectionAuth,this.#Rt()):n&&(this.#W=STATUS.processing,this.#Rt())}setVercelStatus(e){this.#k=e,this.#Rt()}setRemoteConnectionStatus(e){this.#A=e,this.#Rt()}reset(){this.#p=[],this.#m.clear(),this.#h.clear(),this.#D=void 0,this.#E.length=0,this.#g.length=0,this.#w=!1,this.#T=void 0,this.#Fe(),this.#R=!1,this.#we=void 0,this.#Se=void 0,this.#O=0,this.#fe=void 0,this.#pe=void 0,this.#he=void 0,this.#ge=void 0,this.#_e=void 0,this.#q&&(this.#n.clearAll(),this.#Rt())}renderSessionBoundary(){this.#yt(),this.#Fe();let e=this.#r.colors,t=this.#r.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#_t({kind:`session-boundary`,body:n,live:!1}),this.#Rt()}#Fe(){this.#_.clear(),this.#v.clear(),this.#S.clear(),this.#b.clear(),this.#Oe=void 0,this.#ke=void 0,this.#x.clear(),this.#z.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#nt(),this.#_t({kind:`notice`,body:t,live:!1}),this.#Rt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#u?.append({source:`sandbox`,detail:t}),this.#nt(),this.#_t({kind:`sandbox`,body:t,live:!1}),this.#Rt())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#Ie();return}this.#nt(),this.#De=t,this.#Rt()}clearSetupWarning(){this.#Ie()}#Ie(){this.#De!==void 0&&(this.#De=void 0,this.#Rt())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#nt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#_t(r),this.#Rt()}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#nt(),this.#_t({kind:`result`,body:t,live:!1}),this.#Rt())}#Le(e,t=`spinner`){this.#nt(),this.#P=!1,this.#H={kind:`idle`},this.#W=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ee={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#mt(),this.#Rt()}#Re(e){this.#Ae=void 0,this.#Qe();let t=this.#Ee;if(t!==void 0){if(this.#Ee=void 0,this.#gt(),e){let e=[];for(let n of t.lines){if(n.evidence===!0){e.push(n.text);continue}(n.tone===`warning`||n.tone===`error`)&&(e.length>0&&this.#_t({kind:`flow`,title:`info`,body:e.join(`
|
|
3
|
-
`)
|
|
4
|
-
`,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#We(e){let t=this.#Ke(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder!==void 0&&(i.placeholder=e.placeholder),e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#r,t,this.#Z)},this.#dt(),this.#Rt(),await this.#Ye((t,i)=>{let apply=e=>{n=e,r=void 0,this.#pt(),this.#Rt()},a=applyLineEditorKey(n,t);if(a!==void 0){apply(a);return}switch(t.type){case`ctrl-c`:case`escape`:i(void 0);return;case`ctrl-r`:this.#Rt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#Rt();return}i(t);return}default:return}},()=>this.#ft()).promise}async#Ge(e){let t=this.#Ke();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#Rt(),await this.#Ye((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#Rt();return;default:return}}).promise}#Ke(){return this.#nt(),this.#P=!1,this.#H={kind:`idle`},this.#W=``,this.#qe()}#qe(){return this.#Ee===void 0&&(this.#Ee={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Ee}#Je(){this.#Ee?.implicit===!0?this.#Ee=void 0:this.#Ee!==void 0&&(this.#Ee.question=void 0,this.#Ee.hideLinesWhileQuestion=!1),this.#ie=void 0,this.#at(),this.#Ee!==void 0&&this.#Ze(),this.#Rt()}#Ye(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Je(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Je(),i(e))};return this.#lt(),this.#ie=t=>e(t,settle,reject),this.#it(),{promise:a,settle}}#Xe(){let e,t=new Promise(t=>{e=t});return this.#Ae=e,this.#Ze(),{promise:t,dispose:()=>{this.#Ae===e&&(this.#Ae=void 0,this.#Qe())}}}#Ze(){if(this.#Ae===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#Ae;this.#Ae=void 0,this.#Qe(),e?.();return}e.type===`ctrl-r`&&this.#Rt()};this.#je=consumer,this.#lt(),this.#ie=consumer,this.#it()}#Qe(){this.#je!==void 0&&(this.#ie===this.#je&&this.#at(),this.#je=void 0)}#$e(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e)}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis)};if(this.#Ee!==void 0){this.#Ee.status=t,t===void 0&&(this.#Ee.preview=void 0),this.#Rt();return}if(!(this.#P||this.#V)){if(t===void 0){this.#H={kind:`idle`},this.#G=void 0,this.#gt(),this.#Rt();return}this.#nt(),this.#ht(),this.#G=t.text,this.#Rt()}}#et(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Ee;if(r!==void 0){if(r.preview=void 0,t===`warning`||t===`error`)for(let e of r.outputBuffer)r.lines.push({text:e,tone:`info`,evidence:!0});r.outputBuffer=[],r.lines.push({text:n,tone:t}),this.#Rt();return}this.#nt(),this.#_t({kind:`flow`,title:t,body:n,live:!1}),this.#Rt()}#tt(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Ee;if(n===void 0){this.#et(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#Rt()}shutdown(){this.#rt(),this.#J&&!this.#Y&&(this.#Y=!0,this.#t.write(`${this.#r.colors.dim(eveVersionTag())}\n`))}#nt(e){this.#K=e?.title??this.#K,e?.contextSize!==void 0&&(this.#me=e.contextSize),!this.#q&&(this.#q=!0,this.#J=!0,this.#n.reset(),this.#n.hideCursor(),this.#an(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#ce=()=>this.#Rt(),this.#t.on(`resize`,this.#ce))}#rt(){let e=this.#U;if(this.#U=void 0,e?.(interruptedError()),this.#at(),this.#ft(),this.#gt(),this.#ne!==void 0&&(clearTimeout(this.#ne),this.#ne=void 0),this.#re=!1,this.#q){this.#mn();for(let e of this.#p)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#Rt(),this.#n.clear(),this.#n.showCursor(),this.#on(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#ce&&=(this.#t.off(`resize`,this.#ce),void 0),this.#q=!1}}#it(){this.#e.off(`data`,this.#ot),this.#e.on(`data`,this.#ot),this.#ae.length>0&&queueMicrotask(()=>{this.#ie!==void 0&&this.#ae.length>0&&(this.#ct(),this.#st())})}#at(){this.#e.off(`data`,this.#ot),this.#lt(),this.#ie=void 0}#ot=e=>{this.#lt(),this.#ae+=this.#oe.write(e),this.#ct(),this.#st()};#st(){if(this.#ae===`\x1B`){this.#se=setTimeout(()=>{this.#ae===`\x1B`&&(this.#ae=``,this.#ie?.({type:`escape`}))},30),this.#se.unref?.();return}if(isIncompletePaste(this.#ae)){let e=this.#ae;this.#se=setTimeout(()=>{if(this.#ae!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#ae=``,t.length>0&&this.#ie?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#se.unref?.()}}#ct(){for(;this.#ae.length>0;){let e=nextKey(this.#ae);if(e.incomplete)return;this.#ae=this.#ae.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#ie?.(e.key)}}#lt(){this.#se&&=(clearTimeout(this.#se),void 0)}#ut(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#Rt();break;case`ctrl-c`:this.#X||(this.#X=!0,this.#H={kind:`idle`},this.#W=`Interrupted`,this.#le?.(),this.#Rt());break;case`enter`:break;default:{let t=applyLineEditorKey(this.#B,e,{multiline:!0});t!==void 0&&(this.#B=t,this.#Rt());break}}}#dt(){this.#ft(),this.#pt(),this.#ee=setInterval(()=>{this.#Z=!this.#Z,this.#Rt()},500),this.#ee.unref?.()}#ft(){this.#ee&&=(clearInterval(this.#ee),void 0),this.#Z=!0}#pt(){this.#Z=!0}#mt(){this.#gt(),this.#te=setInterval(()=>{this.#Q+=1,this.#Rt()},90),this.#te.unref?.()}#ht(){let e=Date.now();this.#$=e,this.#H={kind:`waiting`,startedAtMs:e},this.#mt()}#gt(){this.#te&&=(clearInterval(this.#te),void 0)}#_t(e){e.id!==this.#Se?.id&&this.#mn(),e.updateSeq=++this.#y,this.#p.push(e),e.id&&this.#m.set(e.id,e)}#vt(e){this.#R=!0,this.#_t({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#Rt()}#yt(){let e=this.#z.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#Xt(e.elapsedMs)}`,n=this.#pe??0;if(this.#me!==void 0&&this.#me>0&&n>0){let e=Math.round(n/this.#me*100);t+=` ${this.#r.glyph.dot} ${e}% context`}this.#_t({kind:`turn-stats`,body:t,live:!1})}#bt(e){if(e!=null){if(this.#we===e){this.#we=void 0;return}this.#_t({kind:`user`,body:stripTerminalControls(e),live:!1})}}#xt(e,t,n={}){let r=stripTerminalControls(e),i=stripTerminalControls(t),a=n.detail===void 0?void 0:stripTerminalControls(n.detail),o=n.hint===void 0?void 0:stripTerminalControls(n.hint),s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#u?.append(o===void 0?s:{...s,hint:o});let c={kind:`error`,title:r,body:i,live:!1};o!==void 0&&(c.hint=o),a!==void 0&&(c.detail=this.#u===void 0?a:`details: ${this.#u.displayPath}`),this.#_t(c),this.#Rt()}#St(e,t){if(this.#S.has(e))return;this.#S.add(e);let n=stripTerminalControls(t),r=this.#b.get(n)??[];if(r.push(e),this.#b.set(n,r),r.length===2){let e=this.#m.get(subagentHeaderId(r[0]));e!==void 0&&(e.subtitle=`#1`)}let i={id:subagentHeaderId(e),kind:`subagent`,subagentCallId:e,title:n,live:!0};r.length>1&&(i.subtitle=`#${r.length}`),this.#_t(i)}#Ct(e){if(e.id&&this.#h.has(e.id))return;let t=e.id?this.#m.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#y;return}this.#_t(e)}#wt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#Tt(){for(let e of this.#p)e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#Et(e,t,n){switch(e.type){case`step-finish`:this.#u?.recordStepUsage(e.usage),e.usage!==void 0&&this.#z.addUsage(e.usage),this.#Nt(n),this.#Lt(e.usage),this.#Rt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#Dt(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;n.text.set(e.id,r),this.#Dt(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);if(n.reasoning.set(e.id,r),t.reasoning===`full`){this.#Ot(e.id,r,!0,t);break}break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;if(t.reasoning===`full`){this.#Ot(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#kt({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#u?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#kt({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;this.#kt({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#It(e.toolCallId,n);if(r===void 0)break;this.#kt({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#It(e.toolCallId,n);if(this.#u?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#kt({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#It(e.toolCallId,n);if(r===void 0)break;this.#kt({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#xt(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`finish`:this.#Lt(e.usage),this.#Rt();break}}#Dt(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#Ct({id:e,kind:`assistant`,body:r,live:n}),this.#Rt())}#Ot(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Ct({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#Rt())}#kt(e,t,n){if(n.tools.set(e.toolCallId,e),this.#_.has(e.toolCallId)||this.#Pt(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#v.set(e.toolCallId,r);let i=this.#At(e);this.#Ct(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#Ft(n),this.#Rt()}#At(e){e.output!==void 0&&this.#x.observeRead(e.output);let t={};this.#jt(e.toolName)&&(t.isSubagent=!0);let n=readWriteFileInput(e.toolName,e.input);if(n===void 0)return t.isSubagent===!0?t:void 0;let r=this.#x.observeWrite({path:n.path,content:n.content,callId:e.toolCallId});r!==void 0&&(t.previousContent=r);let i=writeExistedFlag(e.output);return i!==void 0&&(t.existed=i),t}#jt(e){let t=this.#C?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#Mt(){for(let e of this.#p)e.kind!==`tool`&&e.kind!==`subagent-tool`||e.status===`running`&&(e.status=`error`,e.result=`interrupted`,e.live=!1)}#Nt(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#v.get(t)??toolSectionId(t);this.#wt(r),this.#v.delete(t)}}#Pt(e){let t=readTodoToolItems(e.toolName,e.input);if(t===void 0)return!1;if(t.length>0&&allTodoItemsSettled(t)){let e=JSON.stringify(t);this.#ke!==e&&(this.#ke=e,this.#_t({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#rn(),this.#r).join(`
|
|
5
|
-
`),live:!1})
|
|
6
|
-
`),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#ye=i:this.#be=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#u?.append({source:e,detail:a}),e===`stdout`?this.#ln(a):this.#un(a),this.#Rt())}#ln(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
|
|
7
|
-
`);t=[],e.
|
|
8
|
-
`)
|
|
9
|
-
`)
|
|
10
|
-
`)
|
|
11
|
-
`)
|
|
1
|
+
import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{interruptedError}from"./errors.js";import{FileContentCache}from"./file-content-cache.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{MessageQueue,renderMessageQueueRows}from"./message-queue.js";import{initialModelEditorState,transitionModelEditor}from"./model-editor.js";import{promptPlaceholder}from"./prompt-placeholder.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{enterBadge,renderAcknowledgeQuestion,renderFlowPanel,renderModelEditorQuestion,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{TurnClock}from"./turn-clock.js";import{allTodoItemsSettled,readTodoToolItems,renderFinishedTodoRows,renderTodoPanelRows}from"./todo-panel.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{inspectError}from"#internal/logging.js";import{eveVersionTag}from"#cli/banner.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{LiveRegion}from"#cli/ui/live-region.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";import{readGatewayServiceTier}from"#shared/gateway-service-tier.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e){return e.interrupted?`Interrupted`:e.cancelled?`Cancelled`:e.continueSession?`Ready`:`Done`}const STATUS={processing:`Working…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=[];#m=new Map;#h=new Set;#g=[];#_=new Set;#v=new Map;#y=0;#b=new Map;#x=new FileContentCache;#S=new Set;#C;#w=!1;#T;#E=[];#D;#O=0;#k;#A;#j=``;#M=0;#N=new PromptHistory;#P=!1;#F;#I=!1;#L=Date.now();#R=!1;#z=new TurnClock;#B=EMPTY_LINE;#V=!1;#H={kind:`idle`};#U;#W=STATUS.processing;#G;#K=`eve`;#q=!1;#J=!1;#Y=!1;#X=!1;#Z=!0;#Q=0;#$=Date.now();#ee;#te;#ne;#re=!1;#ie;#ae=``;#oe=new StringDecoder(`utf8`);#se;#ce;#le;#ue=!1;#de=!1;#fe;#pe;#me;#he;#ge;#_e;#ve;#ye=``;#be=``;#xe;#Se;#Ce=0;#we;#Te;#Ee;#De;#Oe;#ke;#Ae=new MessageQueue;#je;#Me=!1;#Ne;#Pe;#Fe=!1;#Ie;#Le;#Re;setupFlow={begin:(e,t)=>this.#We(e,t),end:e=>this.#Ge(e?.preserveDiagnostics??!0),readSelect:e=>this.#Ke(e),readEditableSelect:e=>this.#Je(e),readProviderPicker:e=>this.#Ye(e),readModelEditor:e=>this.#Xe(e),readText:e=>this.#Ze(e),readAcknowledge:e=>this.#Qe(e),readChoice:e=>this.#qe(e),setStatus:e=>this.#ot(e),renderLine:(e,t)=>this.#st(e,t),renderOutput:e=>this.#ct(e),waitForInterrupt:()=>this.#rt()};constructor(t){this.#e=t?.input??process.stdin,this.#t=t?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:t?.color??!0,unicode:t?.unicode??detectUnicode()}),this.#i=t?.tools??`auto-collapsed`,this.#a=t?.reasoning??`auto-collapsed`,this.#o=t?.subagents??`auto-collapsed`,this.#s=t?.connectionAuth??`full`,this.#c=t?.assistantResponseStats??`tokensPerSecond`,this.#me=t?.contextSize,this.#l=t?.captureForeignOutput??this.#t===process.stdout,this.#u=t?.diagnostics,this.#f=t?.logs??`none`,this.#d=t?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#K=e.name,this.#C=e,this.#lt();let t=this.#Xt().join(`
|
|
2
|
+
`);if(this.#w){t!==this.#T&&(this.#T=t,this.#wt({kind:`agent-header`,body:t,live:!1})),this.#Gt();return}this.#w=!0,this.#T=t,this.#n.flush(this.#Xt(),[])}async readPrompt(e){this.#lt(e),this.#Ct(),this.#Et(),this.#P=!0,this.#I=!0,this.#H={kind:`idle`},this.#W=``;let r=this.#Ae.restoreDraft()?.split(`
|
|
3
|
+
`).map(stripPromptControlCharacters).join(`
|
|
4
|
+
`),i=stripPromptControlCharacters(e?.initialDraft??this.#B.text),a=lineOf(r===void 0?i:i.length===0?r:`${r}\n\n${i}`);return this.#B=EMPTY_LINE,this.#N.begin(a.text),this.#ze(a),this.#F=typeaheadFor(this.#d,a.text),this.#vt(),this.#Gt(),await new Promise((e,r)=>{this.#U=r;let apply=e=>{a=e,this.#bt(),this.#ze(a),this.#F=typeaheadFor(this.#d,e.text,this.#F),this.#Gt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#F=void 0,this.#yt(),this.#ut(),r(interruptedError())},suggestions=()=>this.#F!==void 0&&isTypeaheadOpen(this.#F)?this.#F:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ie=r=>{let i=applyLineEditorKey(a,r,{multiline:!0});if(i!==void 0){apply(i);return}switch(r.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#F=moveTypeaheadSelection(e,-1),this.#Gt();break}let t=movePromptLine(a,`up`);t===void 0?recall(this.#N.previous(a.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#F=moveTypeaheadSelection(e,1),this.#Gt();break}let t=movePromptLine(a,`down`);t===void 0?recall(this.#N.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#F=dismissTypeahead(e),this.#Gt());break}case`enter`:{let r=highlighted(),i=r!==void 0&&parsePromptCommand(a.text)===null?typeaheadCompletion(r).trimEnd():a.text;if(i.trim().length===0)break;this.#F=void 0,this.#N.add(i),this.#P=!1,this.#yt(),this.#W=STATUS.processing,isPromptControlCommand(i)?this.#wt({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#St(),this.#Tt(i),this.#we=i,this.#z.arm()),this.#ze(EMPTY_LINE),this.#Gt(),this.#ft(),e(i);break}case`ctrl-d`:a.text.length===0?interrupt():apply(deleteForward(a));break;case`ctrl-l`:this.#Jt();break;case`ctrl-r`:this.#Gt();break;case`ctrl-c`:a.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#dt()})}#ze(e){this.#j=e.text,this.#M=e.cursor}takeQueuedPrompt(){let e=this.#Ae.view().steering,t=this.#Ae.takePrompt();return t!==void 0&&(this.#Pe=e?`steer`:`queue`),t}async renderStream(e,t){this.#lt(t),this.#h.clear(),this.#P=!1,this.#H.kind!==`waiting`&&(this.#H={kind:`waiting`,startedAtMs:Date.now()}),this.#W=this.#O>0?STATUS.connectionAuth:STATUS.processing,this.#Dt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#u?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#z.armed&&this.#z.arm(),this.#X=!1,this.#Me=!1,this.#Fe=!1,this.#Ie=t?.submittedPrompt,this.#Ae.beginTurn(),this.#je=e.cancel,this.#fe=void 0,this.#pe=void 0,this.#he=void 0,this.#ge=void 0,this.#_e=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#xt(),this.#V=!0,this.#Gt();let r=new Promise(e=>{this.#le=e});this.#ie=e=>this.#_t(e),this.#dt();let i={text:new Map,reasoning:new Map,tools:new Map};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#X)break;this.#Nt(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#Ot(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#Ot(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#le=void 0,this.#X&&e.abort?.(),this.#je=void 0,this.#ft(),this.#Ct(),this.#V=!1,this.#H.kind===`waiting`&&(this.#H={kind:`idle`}),this.#W=completedTurnStatus({interrupted:this.#X,cancelled:this.#Me,continueSession:t?.continueSession===!0}),this.#Bt(i),(this.#X||this.#Me)&&this.#zt(),this.#Mt(),this.#u?.reportStats(),this.#Gt(),t?.continueSession||this.#ut()}}async readToolApproval(e,t){return this.#lt(t),this.#Ct(),this.#P=!1,this.#H={kind:`idle`},this.#W=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#X=!1,this.#Gt(),await new Promise((t,n)=>{this.#U=n,this.#ie=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#St(),this.#W=STATUS.processing,this.#ft(),this.#Gt(),t({approved:!0})):n===`n`&&(this.#St(),this.#W=STATUS.processing,this.#Ve(e.toolCallId),this.#ft(),this.#Gt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#Gt();break;case`ctrl-c`:this.#X=!0,this.#ut(),n(interruptedError());break;default:break}},this.#dt()})}async readInputQuestion(e,t){this.#lt(t),this.#Ct(),this.#P=!1,this.#I=!1,this.#H={kind:`idle`},this.#X=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`overlay`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,overlayPanel=t=>renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#Z},this.#r,t),renderTextSection=()=>{this.#At({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#r),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#vt():(this.#yt(),this.#bt())};s===`overlay`?(s=`overlay`,this.#P=!1,this.#jt(o),this.#Te=overlayPanel,this.#W=``,syncFreeformCaret(),this.#Gt()):(s=`text`,this.#Te=void 0,renderTextSection(),this.#P=!0,this.#ze(l),this.#W=``,this.#vt(),this.#Gt());let finalize=t=>{this.#Te=void 0,this.#At({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#r.colors.dim(this.#r.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#P=!1,this.#St(),this.#W=STATUS.processing,this.#yt(),this.#ft(),this.#Gt();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Te=void 0,this.#At({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#r.colors.dim(this.#r.glyph.elbow)} ${this.#r.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#P=!1,this.#W=``,this.#yt(),this.#ft(),this.#Gt(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#Gt())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#U=r,u=t,this.#ie=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#bt(),s===`text`&&this.#ze(l),this.#Gt();return}this.#X=!0,this.#Te=void 0,this.#yt(),this.#ut(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#Gt();return}if(s===`overlay`){switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#bt(),this.#Gt();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#bt(),this.#Gt());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.#Gt())}break}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#bt(),this.#ze(l),this.#Gt();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#bt(),this.#ze(l),this.#Gt());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.#bt(),this.#ze(l),this.#Gt();break}dismiss();break;default:break}},this.#dt()})}upsertSubagentStep(e){if(this.#u?.recordSubagentDispatch(e.callId),this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#kt(e.callId,e.subagentName),this.#o===`collapsed`){this.#Gt();return}this.#At({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#o!==`full`,live:!e.finalized}),this.#Gt()}}upsertSubagentTool(e){if(this.#u?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#u?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#o===`hidden`)return;if(this.#kt(e.callId,e.subagentName),this.#o===`collapsed`){this.#Gt();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#Lt({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#At(r),this.#Be(e.callId),this.#Gt()}#Be(e){applyCohortLiveness(this.#p.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#jt(subagentToolSectionId(e.callId,e.childCallId)),this.#Gt()}subagents={begin:e=>this.beginSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#o===`hidden`)return;this.#kt(e.callId,e.name);let t=this.#m.get(subagentHeaderId(e.callId));t?.status===`done`&&delete t.status,this.#Gt()}completeSubagent(e){let t=this.#m.get(subagentHeaderId(e.callId));t!==void 0&&(t.status=`done`,this.#Gt())}markChildToolCallId(e){this.#_.add(e);let t=this.#v.get(e);t!==void 0&&(this.#jt(t),this.#v.delete(e),this.#Gt())}#Ve(e){let t=this.#m.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#At({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.#Gt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#O)return;let n=this.#O>0;this.#O=t,t>0?(this.#W=STATUS.connectionAuth,this.#Gt()):n&&(this.#W=STATUS.processing,this.#Gt())}setVercelStatus(e){this.#k=e,this.#Gt()}setRemoteConnectionStatus(e){this.#A=e,this.#Gt()}reset(){this.#p=[],this.#m.clear(),this.#h.clear(),this.#D=void 0,this.#E.length=0,this.#g.length=0,this.#w=!1,this.#T=void 0,this.#He(),this.#R=!1,this.#we=void 0,this.#Se=void 0,this.#O=0,this.#fe=void 0,this.#pe=void 0,this.#he=void 0,this.#ge=void 0,this.#_e=void 0,this.#q&&(this.#n.clearAll(),this.#Gt())}renderSessionBoundary(){this.#Et(),this.#He();let e=this.#r.colors,t=this.#r.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#wt({kind:`session-boundary`,body:n,live:!1}),this.#Gt()}#He(){this.#_.clear(),this.#v.clear(),this.#S.clear(),this.#b.clear(),this.#Oe=void 0,this.#ke=void 0,this.#Ae.reset(),this.#Pe=void 0,this.#x.clear(),this.#z.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#lt(),this.#wt({kind:`notice`,body:t,live:!1}),this.#Gt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#u?.append({source:`sandbox`,detail:t}),this.#lt(),this.#wt({kind:`sandbox`,body:t,live:!1}),this.#Gt())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#Ue();return}this.#lt(),this.#De=t,this.#Gt()}clearSetupWarning(){this.#Ue()}#Ue(){this.#De!==void 0&&(this.#De=void 0,this.#Gt())}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.#wt(r),this.#Gt()}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#lt(),this.#wt({kind:`result`,body:t,live:!1}),this.#Gt())}#We(e,t=`spinner`){this.#lt(),this.#P=!1,this.#H={kind:`idle`},this.#W=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ee={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#xt(),this.#Gt()}#Ge(e){this.#Le=void 0,this.#at();let t=this.#Ee;if(t!==void 0){if(this.#Ee=void 0,this.#Ct(),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.#wt({kind:`flow`,title:`info`,body:e.join(`
|
|
5
|
+
`),live:!1}),this.#wt({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#Gt()}}async#Ke(e){let t=this.#$e(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a={options:i,searchAction:r,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(a.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(a.initialValues=e.initialValues);let o=initialSelectState(a),s,c=!1,l=0,isCurrentSearch=e=>e===l,clearSearch=()=>{l+=1,c=!1,o=reduceSelect(o,{type:`clear`},{options:i,searchAction:r,submitRow:n}),this.#Gt()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#Gt();try{let s=await t(e);if(!isCurrentSearch(a))return;let c=o.filter;i=s,o={...initialSelectState({options:s,searchAction:r,submitRow:n}),filter:c}}catch(e){isCurrentSearch(a)&&(s=toErrorMessage(e))}finally{isCurrentSearch(a)&&(c=!1,this.#Gt())}},u=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#Qt()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#Gt(),await this.#nt((t,a)=>{let close=e=>{l+=1,a(e)};if(c){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#Gt();return}let u={key:t,options:i,searchAction:r,select:o},d=reduceSetupSelectInput(n?{...u,kind:e.kind,required:e.required}:{...u,kind:e.kind});switch(d.kind){case`cancel`:close(void 0);return;case`repaint`:this.#Gt();return;case`update`:o=d.select,s=void 0,this.#Gt();return;case`submit`:{let e=searchActionQuery(d.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(d.values);return}loadSearch(e,t);return}case`error`:s=d.message,this.#Gt();return;case`ignore`:return}}).promise}#qe(e){this.#lt();let t=this.#et();t.status={kind:`progress`,text:stripTerminalControls(e.status)};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#Gt();let r=this.#nt((t,r)=>{let i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#Gt();return;case`repaint`:this.#Gt();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#Je(e){let t=this.#$e(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#Z,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#vt():(i=lineOf(``),this.#yt())};return syncEditableRow(),this.#Gt(),await this.#nt((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#bt(),this.#Gt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#Gt()},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.#Gt();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#Gt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#yt()).promise}async#Ye(e){let t=this.#$e(),n=initialProviderPickerState(e.options,e.initialValue),r,cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor),r=e.options.find(e=>e.value===t);if(r!==void 0)return enterBadge(this.#r,r.checked===!0?`change`:void 0)};t.question=t=>{let r=cursorBadge(),i={kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#Z,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#r,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#vt():this.#yt()};return syncCaret(),this.#Gt(),await this.#nt((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.#Gt();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#Gt();return;case`validate`:{n=o.state,syncCaret(),this.#Gt();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#Gt();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#bt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#yt()}).promise}async#Xe(e){let t=this.#$e(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#r,t),this.#Gt(),await this.#nt((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#Gt();return;case`cancel`:r(void 0);return;case`settle`:r(i.result);return}},i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:i.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#Gt();return;case void 0:break}if(t.type===`left`||t.type===`right`){dispatch({type:`adjust`,direction:t.type});return}if(t.type===`tab`){dispatch({type:`adjust`,direction:`right`});return}if(t.type===`backspace`){dispatch({type:`backspace`});return}if(t.type===`text`)for(let e of t.value.replaceAll(`
|
|
6
|
+
`,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#Ze(e){let t=this.#$e(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder!==void 0&&(i.placeholder=e.placeholder),e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#r,t,this.#Z)},this.#vt(),this.#Gt(),await this.#nt((t,i)=>{let apply=e=>{n=e,r=void 0,this.#bt(),this.#Gt()},a=applyLineEditorKey(n,t);if(a!==void 0){apply(a);return}switch(t.type){case`ctrl-c`:case`escape`:i(void 0);return;case`ctrl-r`:this.#Gt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#Gt();return}i(t);return}default:return}},()=>this.#yt()).promise}async#Qe(e){let t=this.#$e();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#Gt(),await this.#nt((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#Gt();return;default:return}}).promise}#$e(){return this.#lt(),this.#P=!1,this.#H={kind:`idle`},this.#W=``,this.#et()}#et(){return this.#Ee===void 0&&(this.#Ee={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Ee}#tt(){this.#Ee?.implicit===!0?this.#Ee=void 0:this.#Ee!==void 0&&(this.#Ee.question=void 0,this.#Ee.hideLinesWhileQuestion=!1),this.#ie=void 0,this.#ft(),this.#Ee!==void 0&&this.#it(),this.#Gt()}#nt(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#tt(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#tt(),i(e))};return this.#gt(),this.#ie=t=>e(t,settle,reject),this.#dt(),{promise:a,settle}}#rt(){let e,t=new Promise(t=>{e=t});return this.#Le=e,this.#it(),{promise:t,dispose:()=>{this.#Le===e&&(this.#Le=void 0,this.#at())}}}#it(){if(this.#Le===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#Le;this.#Le=void 0,this.#at(),e?.();return}e.type===`ctrl-r`&&this.#Gt()};this.#Re=consumer,this.#gt(),this.#ie=consumer,this.#dt()}#at(){this.#Re!==void 0&&(this.#ie===this.#Re&&this.#ft(),this.#Re=void 0)}#ot(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e)}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis)};if(this.#Ee!==void 0){this.#Ee.status=t,t===void 0&&(this.#Ee.preview=void 0),this.#Gt();return}if(!(this.#P||this.#V)){if(t===void 0){this.#H={kind:`idle`},this.#G=void 0,this.#Ct(),this.#Gt();return}this.#lt(),this.#St(),this.#G=t.text,this.#Gt()}}#st(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Ee;if(r!==void 0){if(r.preview=void 0,t===`warning`||t===`error`)for(let e of r.outputBuffer)r.lines.push({text:e,tone:`info`,evidence:!0});r.outputBuffer=[],r.lines.push({text:n,tone:t}),this.#Gt();return}this.#lt(),this.#wt({kind:`flow`,title:t,body:n,live:!1}),this.#Gt()}#ct(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Ee;if(n===void 0){this.#st(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#Gt()}setSessionId(e){this.#Ne=e}shutdown(){if(this.#ut(),this.#J&&!this.#Y){this.#Y=!0;let e=this.#Ne===void 0?``:` ${this.#r.glyph.dot} session ${this.#Ne}`;this.#t.write(`${this.#r.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}#lt(e){this.#K=e?.title??this.#K,e?.contextSize!==void 0&&(this.#me=e.contextSize),!this.#q&&(this.#q=!0,this.#J=!0,this.#n.reset(),this.#n.hideCursor(),this.#fn(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#ce=()=>this.#Gt(),this.#t.on(`resize`,this.#ce))}#ut(){let e=this.#U;if(this.#U=void 0,e?.(interruptedError()),this.#ft(),this.#yt(),this.#Ct(),this.#ne!==void 0&&(clearTimeout(this.#ne),this.#ne=void 0),this.#re=!1,this.#q){this.#xn();for(let e of this.#p)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#Gt(),this.#n.clear(),this.#n.showCursor(),this.#pn(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#ce&&=(this.#t.off(`resize`,this.#ce),void 0),this.#q=!1}}#dt(){this.#e.off(`data`,this.#pt),this.#e.on(`data`,this.#pt),this.#ae.length>0&&queueMicrotask(()=>{this.#ie!==void 0&&this.#ae.length>0&&(this.#ht(),this.#mt())})}#ft(){this.#e.off(`data`,this.#pt),this.#gt(),this.#ie=void 0}#pt=e=>{this.#gt(),this.#ae+=this.#oe.write(e),this.#ht(),this.#mt()};#mt(){if(this.#ae===`\x1B`){this.#se=setTimeout(()=>{this.#ae===`\x1B`&&(this.#ae=``,this.#ie?.({type:`escape`}))},30),this.#se.unref?.();return}if(isIncompletePaste(this.#ae)){let e=this.#ae;this.#se=setTimeout(()=>{if(this.#ae!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#ae=``,t.length>0&&this.#ie?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#se.unref?.()}}#ht(){for(;this.#ae.length>0;){let e=nextKey(this.#ae);if(e.incomplete)return;this.#ae=this.#ae.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#ie?.(e.key)}}#gt(){this.#se&&=(clearTimeout(this.#se),void 0)}#_t(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#Gt();break;case`ctrl-c`:this.#X||(this.#X=!0,this.#H={kind:`idle`},this.#W=`Interrupted`,this.#le?.(),this.#Gt());break;case`enter`:{let e=this.#B.text;if(e.trim().length===0)break;this.#Ae.enqueue(e)&&(this.#B=EMPTY_LINE),this.#Gt();break}case`escape`:{if(this.#Ae.idle&&this.#je===void 0)break;let e=this.#Ae.handleEscape();(e===`steer`||e===`cancel`)&&(this.#Fe=!0,this.#je?.()),this.#Gt();break}default:{this.#Ae.disarm();let t=applyLineEditorKey(this.#B,e,{multiline:!0});t!==void 0&&(this.#B=t,this.#Gt());break}}}#vt(){this.#yt(),this.#bt(),this.#ee=setInterval(()=>{this.#Z=!this.#Z,this.#Gt()},500),this.#ee.unref?.()}#yt(){this.#ee&&=(clearInterval(this.#ee),void 0),this.#Z=!0}#bt(){this.#Z=!0}#xt(){this.#Ct(),this.#te=setInterval(()=>{this.#Q+=1,this.#Gt()},90),this.#te.unref?.()}#St(){let e=Date.now();this.#$=e,this.#H={kind:`waiting`,startedAtMs:e},this.#xt()}#Ct(){this.#te&&=(clearInterval(this.#te),void 0)}#wt(e){e.id!==this.#Se?.id&&this.#xn(),e.updateSeq=++this.#y,this.#p.push(e),e.id&&this.#m.set(e.id,e)}#Tt(e){this.#R=!0,this.#wt({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#Gt()}#Et(){let e=this.#z.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#rn(e.elapsedMs)}`,n=this.#pe??0;if(this.#me!==void 0&&this.#me>0&&n>0){let e=Math.round(n/this.#me*100);t+=` ${this.#r.glyph.dot} ${e}% context`}this.#wt({kind:`turn-stats`,body:t,live:!1})}#Dt(e){if(e==null)return;let t=this.#Pe;if(this.#Pe=void 0,this.#we===e){this.#we=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#wt(n)}#Ot(e,t,n={}){let r=stripTerminalControls(e),i=stripTerminalControls(t),a=n.detail===void 0?void 0:stripTerminalControls(n.detail),o=n.hint===void 0?void 0:stripTerminalControls(n.hint),s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#u?.append(o===void 0?s:{...s,hint:o});let c={kind:`error`,title:r,body:i,live:!1};o!==void 0&&(c.hint=o),a!==void 0&&(c.detail=this.#u===void 0?a:`details: ${this.#u.displayPath}`),this.#wt(c),this.#Gt()}#kt(e,t){if(this.#S.has(e))return;this.#S.add(e);let n=stripTerminalControls(t),r=this.#b.get(n)??[];if(r.push(e),this.#b.set(n,r),r.length===2){let e=this.#m.get(subagentHeaderId(r[0]));e!==void 0&&(e.subtitle=`#1`)}let i={id:subagentHeaderId(e),kind:`subagent`,subagentCallId:e,title:n,live:!0};r.length>1&&(i.subtitle=`#${r.length}`),this.#wt(i)}#At(e){if(e.id&&this.#h.has(e.id))return;let t=e.id?this.#m.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#y;return}this.#wt(e)}#jt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#Mt(){for(let e of this.#p)e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#Nt(e,t,n){switch(e.type){case`step-finish`:this.#u?.recordStepUsage(e.usage),e.usage!==void 0&&this.#z.addUsage(e.usage),this.#Bt(n),this.#Wt(e.usage),this.#Gt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#Pt(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;n.text.set(e.id,r),this.#Pt(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.#Ft(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.#Ft(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#It({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#u?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#It({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.#It({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#Ut(e.toolCallId,n);if(r===void 0)break;this.#It({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#Ut(e.toolCallId,n);if(this.#u?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#It({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#Ut(e.toolCallId,n);if(r===void 0)break;this.#It({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#Ot(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:this.#Me=!0,!this.#Fe&&this.#Ie!==void 0&&this.#B.text.length===0&&(this.#B=lineOf(this.#Ie),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#Wt(e.usage),this.#Gt();break}}#Pt(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#At({id:e,kind:`assistant`,body:r,live:n}),this.#Gt())}#Ft(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#At({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#Gt())}#It(e,t,n){if(n.tools.set(e.toolCallId,e),this.#_.has(e.toolCallId)||this.#Vt(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#v.set(e.toolCallId,r);let i=this.#Lt(e);this.#At(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#Ht(n),this.#Gt()}#Lt(e){e.output!==void 0&&this.#x.observeRead(e.output);let t={};this.#Rt(e.toolName)&&(t.isSubagent=!0);let n=readWriteFileInput(e.toolName,e.input);if(n===void 0)return t.isSubagent===!0?t:void 0;let r=this.#x.observeWrite({path:n.path,content:n.content,callId:e.toolCallId});r!==void 0&&(t.previousContent=r);let i=writeExistedFlag(e.output);return i!==void 0&&(t.existed=i),t}#Rt(e){let t=this.#C?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#zt(){for(let e of this.#p)e.kind!==`tool`&&e.kind!==`subagent-tool`||e.status===`running`&&(e.status=`error`,e.result=`interrupted`,e.live=!1)}#Bt(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#v.get(t)??toolSectionId(t);this.#jt(r),this.#v.delete(t)}}#Vt(e){let t=readTodoToolItems(e.toolName,e.input);if(t===void 0)return!1;if(t.length>0&&allTodoItemsSettled(t)){let e=JSON.stringify(t);this.#ke!==e&&(this.#ke=e,this.#wt({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#un(),this.#r).join(`
|
|
7
|
+
`),live:!1})),this.#Oe=void 0}else this.#Oe=t.length>0?t:void 0,this.#ke=void 0;return this.#Gt(),!0}#Ht(e){let t=[];for(let n of e.tools.values()){if(this.#_.has(n.toolCallId))continue;let e=this.#v.get(n.toolCallId)??toolSectionId(n.toolCallId),r=this.#m.get(e);r?.kind===`tool`&&t.push({block:r,active:isActiveToolStatus(n.status)})}applyCohortLiveness(t)}#Ut(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#v.get(e)??toolSectionId(e),i=this.#m.get(r);if(!(i===void 0||i.kind!==`tool`))return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.toolName??i.title??`tool`}}#Wt(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#fe=(t??0)+(n??0)),this.#pe=t??this.#pe,this.#he=n??this.#he,this.#he!=null&&this.#_e!==void 0){let e=(Date.now()-this.#_e)/1e3;e>0&&(this.#ge=this.#he/e)}}#Gt(){if(this.#q){if(this.#ue){this.#de=!0;return}this.#ue=!0;try{do this.#de=!1,this.#Kt();while(this.#de)}finally{this.#ue=!1}}}#Kt(){if(!this.#q)return;let e=this.#un(),t=this.#tn(e),n=Math.max(1,this.#dn()-t.length),r=[],i=this.#D,a=groupToolBlocksForDisplay(this.#p),o=0;for(;o<a.length&&a[o].display.live===!1;)o+=1;if(o>0){let e=new Set(a.slice(0,o).flatMap(e=>e.members));for(let t=this.#p.length-1;t>=0;--t)e.has(this.#p[t])&&this.#p.splice(t,1)}for(let t of a.slice(0,o)){for(let e of t.members)this.#g.push(e),e.id&&(this.#h.add(e.id),this.#m.delete(e.id));if(this.#Cn(t.display))continue;let n=this.#Zt(t.display,e,i);i=previousBlockOf(t.display),this.#D=i,r.push(...n),this.#E.push(...n)}let s=[];for(let{display:t}of a.slice(o)){if(this.#Cn(t))continue;let n=this.#Zt(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)s.push({block:t,row:n[e]})}let c=[...clipLiveRows(s.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,c):this.#n.update(c)}#qt(){if(!this.#q)return;let e=this.#un(),t=this.#tn(e),n=Math.max(1,this.#dn()-t.length),r=this.#D,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#p)){if(this.#Cn(t))continue;let n=this.#Zt(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#r),...t];this.#n.clearAll(),this.#n.flush([...this.#Xt(),...this.#E],a)}logDisplayMode(){return this.#f}setLogDisplayMode(e){e!==this.#f&&(this.#f=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#Yt(),this.#q&&this.#qt())}flushDelayedDevBuildErrors(){let e=this.#xe;e!==void 0&&(this.#xe=void 0,this.#wt({kind:`log`,title:`stderr`,body:e,live:!0}),this.#Gt())}#Jt(){this.#re=!0,this.#ne!==void 0&&clearTimeout(this.#ne),this.#ne=setTimeout(()=>{this.#re=!1,this.#ne=void 0,this.#Gt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#f)),this.#Gt()}#Yt(){let e=this.#un();this.#E.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#g,{logCoalescing:`runs`})){if(this.#Cn(n))continue;let r=this.#Zt(n,e,t);t=previousBlockOf(n),this.#E.push(...r)}this.#D=t}#Xt(){let e=this.#C;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#un()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#Zt(e,t,n){let r={activityPulse:this.#$t(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#Qt(){return this.#r.spinner[this.#Q%this.#r.spinner.length]??``}#$t(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#en(e,t){return e.indicator.kind===`spinner`?{glyph:this.#Qt(),color:`yellow`}:{glyph:this.#$t(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#tn(e){let n=this.#r.colors,r=[``];if(this.#Te!==void 0)return r.push(...this.#Te(e),``),this.#sn(r,e),r;let a=this.#Ee;if(a!==void 0){let t=this.#en(a,a.status),n=a.status===void 0?void 0:{...a.status,indicator:t},i;if(a.question!==void 0){let t=a.question(e);i={kind:`question`,rows:t},n!==void 0&&(i={kind:`question`,rows:t,status:n})}else n===void 0?i=a.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:a.preview,indicator:t}:(i={kind:`status`,status:n},a.preview!==void 0&&(i={kind:`status`,status:n,preview:a.preview}));let o={title:a.title,lines:a.hideLinesWhileQuestion===!0?[]:a.lines,content:i};return r.push(...renderFlowPanel(o,this.#r,e)),this.#cn(r,e),r}this.#De!==void 0&&r.push(...renderAttentionRows(this.#De,e,this.#r),``),this.#Oe!==void 0&&r.push(...renderTodoPanelRows({items:this.#Oe,width:e,theme:this.#r,working:this.#V||this.#H.kind===`waiting`,pulse:this.#$t(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}),``);let o=renderMessageQueueRows({view:this.#Ae.view(),width:e,theme:this.#r,working:this.#V});if(o.length>0&&r.push(...o,``),this.#P){let i=this.#F===void 0?void 0:inlineCommandHint(this.#F);i===void 0&&this.#F!==void 0&&isTypeaheadOpen(this.#F)&&r.push(...renderCommandSuggestions(this.#F,this.#r,e));let a=isPromptControlCommand(this.#j),o=i?n.dim(` ${i}`):``,l=[];this.#sn(l,e);let d=Math.max(1,this.#dn()-1-r.length-1-l.length),f={text:this.#j,cursor:this.#M,width:e,theme:this.#r,caretVisible:this.#Z,isCommand:a,ghost:o,maxRows:d};return this.#I&&this.#j.length===0&&(f.placeholder=this.#R?``:promptPlaceholder(Date.now()-this.#L)),r.push(...promptInputRows(f)),r.push(...l),r}let l=this.#H.kind===`waiting`&&this.#G===void 0;if(this.#V||l){r.push(this.#nn(e)),this.#an(r,e);let t=[];return this.#sn(t,e),!this.#V&&t.length>0&&r.push(``),r.push(...t),r}if(this.#B.text.length>0)return this.#on(r,e,{inert:!1}),this.#sn(r,e),r;let d=this.#G??(this.#W.length>0?this.#W:`Ready`),f=this.#ln(),p=n.dim(this.#r.glyph.dot),m=f?`${p} ${d} ${n.dim(this.#r.glyph.dot)} ${f}`:`${p} ${d}`;return r.push(clip(m,e)),this.#sn(r,e),r}#nn(e){let t=this.#r.colors,n=this.#$t(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),r=this.#H,i=this.#z.startedAtMs??this.#_e??(r.kind===`waiting`?r.startedAtMs:Date.now()),a=Date.now()-i,o=`${typewriterText(`Working for`,a,80)} ${this.#rn(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#rn(e){return`${formatTurnDuration(e)}${this.#in()}`}#in(){let{inputTokens:e,outputTokens:t}=this.#z.usage;return e===0&&t===0?``:` ${this.#r.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#r.glyph)}`}#an(e,t){this.#V&&this.#on(e,t,{inert:!0})}#on(e,t,n){e.push(``);let r={text:this.#B.text,cursor:this.#B.cursor,width:t,theme:this.#r,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#B.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#sn(e,t){let n=this.#A===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#r,width:r};this.#re&&(i.logLevel=this.#f);let a=this.#C?.serverUrl;if(a!==void 0&&this.#A===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#C?.info?.agent.model;o?.id!==void 0&&(i.model=o.id),o?.reasoning!==void 0&&o.reasoning!==`provider-default`&&(i.reasoning=o.reasoning),readGatewayServiceTier(o?.providerOptions).kind===`priority`&&(i.fastMode=!0);let s=o?.endpoint;s!==void 0&&(i.endpoint=s),this.#k!==void 0&&(i.vercel=this.#k),this.#A!==void 0&&(i.remote=this.#A);let c=buildStatusLine(i);c!==void 0&&e.push(clip(`${n}${c}`,t))}#cn(e,t){if(this.#A===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#A,theme:this.#r,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#ln(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#fe,outputTokens:this.#he,tokensPerSecond:this.#ge},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#un(){return Math.max(20,this.#t.columns||80)}#dn(){return Math.max(8,this.#t.rows||24)}#fn(){if(this.#ve!==void 0||!this.#l)return;this.#ye=``,this.#be=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#hn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#u?.subscribeLogRecords(e=>this.#mn(e)),this.#ve=()=>{this.#u?.unsubscribeLogRecords(),e(),t()}}#pn(){let e=this.#ve;e!==void 0&&(this.#ve=void 0,e(),this.#ye.length>0&&(this.#u?.append({source:`stdout`,detail:this.#ye}),this.#Sn(`stdout`)&&process.stdout.write(`${this.#ye}\n`),this.#ye=``),this.#be.length>0&&(this.#u?.append({source:`stderr`,detail:this.#be}),this.#Sn(`stderr`)&&process.stderr.write(`${this.#be}\n`),this.#be=``))}#mn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#_n(`[eve:${e.namespace}] ${e.message}${t}`),this.#Gt()}#hn(e,t){let n=(e===`stdout`?this.#ye:this.#be)+t,r=n.lastIndexOf(`
|
|
8
|
+
`),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#ye=i:this.#be=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#u?.append({source:e,detail:a}),e===`stdout`?this.#gn(a):this.#_n(a),this.#Gt())}#gn(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
|
|
9
|
+
`);t=[],e.trim().length!==0&&this.#wt({kind:`log`,title:`stdout`,body:e,live:!0})};for(let n of e.split(`
|
|
10
|
+
`)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#wt({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#yn(r,n.trimEnd())}flushPending()}#_n(e){let t=e.split(`
|
|
11
|
+
`),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#u===void 0){this.#wt({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#u.displayPath);if(t.kind===`inline`){this.#wt({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#wt({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#wt({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
|
|
12
|
+
`);r.trim().length>0&&this.#wt({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
|
|
13
|
+
`);this.#vn(i)}#vn(e){if(this.#f===`all`){if(e.trim().length===0)return;this.#wt({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#xe=e}#yn(e,t){let n=this.#bn();if(e.kind===`failed`){this.#vn(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#Ce}`;this.#Ce+=1,this.#Se={id:r,summary:t},this.#wt({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}if(n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#xe=void 0);return}e.kind===`rebuilt`&&(this.#xe=void 0),this.#wt({kind:`log`,title:`stdout`,body:t,live:!0})}#bn(){let e=this.#Se;if(e===void 0)return;let t=this.#m.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#xn(){let e=this.#Se;if(e===void 0)return;this.#Se=void 0;let t=this.#m.get(e.id);t!==void 0&&(t.live=!1)}#Sn(e){switch(this.#f){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#Cn(e){return e.kind===`sandbox`?!this.#Sn(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#f!==`stderr`:e.logVisibility===`all-only`?this.#f!==`all`:!this.#Sn(e.title===`stderr`?`stderr`:`stdout`):!1}};function chunkToString(e,t){return typeof e==`string`?e:Buffer.from(e).toString(t)}async function*iterateTUIStream(e){if(e instanceof ReadableStream){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}return}yield*e}function clip(e,t){return clipVisible(e,t)}function promptInputRows({text:e,cursor:t,width:n,theme:r,caretVisible:i,isCommand:a,ghost:o,maxRows:s,placeholder:c,inert:l}){let u=r.colors;if(e.length===0&&c!==void 0){let e=renderInputWithBlockCursor({...visibleLine({text:c,cursor:0},Math.max(1,n-3),r.glyph.ellipsis),visible:i,inverse:u.inverse,render:e=>u.dim(renderInputText(e))});return[clip(`${u.dim(r.glyph.promptIdle)} ${e}`,n),``]}let style=e=>{let t=renderInputText(e);return a&&t.length>0?u.blue(t):t},d=layoutPromptInput({text:e,cursor:t}),f=Math.min(Math.max(1,s),d.rows.length),p=Math.max(0,Math.min(d.caretRow-f+1,d.rows.length-f)),m=l===!0?u.dim(r.glyph.prompt):u.cyan(r.glyph.prompt),h=u.dim(r.glyph.ellipsis),g=Math.max(1,n-3),_=[];for(let e=p;e<p+f;e+=1){let t=d.rows[e],a=e===0?m:` `;(e===p&&p>0||e===p+f-1&&p+f<d.rows.length)&&(a=h);let s;if(e===d.caretRow){let{before:e,under:n,after:a}=visibleLine({text:t.text,cursor:d.caretOffset},g,r.glyph.ellipsis);s=renderInputWithBlockCursor({before:e,under:n,after:a,visible:i,inverse:u.inverse,render:style}),o.length>0&&d.rows.length===1&&(s+=o)}else s=style(t.text);_.push(clip(`${a} ${s}`,n))}return _.push(``),_}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function isActiveToolStatus(e){return e===`running`||e===`approval`}function applyCohortLiveness(e){let t=e.some(e=>e.active);for(let n of e)n.block.live=t||n.active}function leadsWithGap(e,t){if(e.kind===`tool`&&(t?.kind===`user`||t?.kind===`assistant`||t?.kind===`question`))return!0;if(e.kind===`sandbox`&&t?.kind===`sandbox`)return!1;if(t?.kind===`sandbox`&&e.kind!==`sandbox`||t?.kind===`log`)return!0;switch(e.kind){case`user`:case`assistant`:case`reasoning`:case`subagent`:case`error`:case`notice`:case`question`:case`connection-auth`:case`sandbox`:case`log`:case`command`:case`warning`:case`flow`:case`turn-stats`:case`session-boundary`:case`todo-list`:case`agent-header`:return!0;default:return!1}}function parseSandboxLogLine(e){let t=e.trim();if(!t.startsWith(`eve: `))return;let n=t.slice(5);return/\bsandbox\b/i.test(n)&&!isLowValueSandboxLogLine(n)?n:void 0}function isLowValueSandboxLogLine(e){return/^initializing (?:\d+ )?sandbox templates?\b/i.test(e)||/^initialized \d+ sandbox\b/i.test(e)||/^reused cached sandbox template\b/i.test(e)||/^sandbox template "[^"]+" \([^)]+\): (checking|reusing|loading microsandbox runtime|microsandbox runtime ready)\b/i.test(e)}function clipLiveRows(e,t,n,r){if(e.length<=t)return[...e];if(t<=1)return[clip(hiddenRowsMarker(e.length,r),n)];let i=t-1;return[clip(hiddenRowsMarker(e.length-i,r),n),...e.slice(e.length-i)]}function hiddenRowsMarker(e,t){let n=e.toLocaleString(),r=e===1?`row`:`rows`;return t.colors.dim(`${t.glyph.dot} ${t.glyph.ellipsis} ${n} earlier ${r} hidden while streaming`)}function collapseReasoning(e,t){switch(e){case`collapsed`:return!0;case`auto-collapsed`:return!t;default:return!1}}function renderNativeToolBlock(e,t,n,r){let i=e.preparing===!0?presentPreparingTool(e.toolName,r):presentTool(e.toolName,e.input,r),a={id:t,kind:`tool`,title:stripTerminalControls(i.title),subtitle:stripTerminalControls(i.subtitle),status:e.status,live:e.status===`running`||e.status===`approval`,expanded:n,toolInput:e.input,toolName:e.toolName,toolGroup:i.group};return i.doneTitle!==void 0&&(a.doneTitle=stripTerminalControls(i.doneTitle)),i.detail!==void 0&&(a.detailLines=i.detail,a.keepDetailWhenDone=i.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(a.result=stripTerminalControls(e.errorText)):(a.result=i.summarizeResult(e.output),a.toolOutput=e.output),a}function writeExistedFlag(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.existed;return typeof t==`boolean`?t:void 0}function subagentToolStatus(e){switch(e){case`preparing`:return`running`;case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`;case`rejected`:return`denied`}}function formatToolApprovalTitle(e){return stripTerminalControls(e.title??e.toolName)}function toolSectionId(e){return`tool:${e}`}function questionSectionId(e){return`question:${e}`}function subagentHeaderId(e){return`subagent:${e}:header`}function subagentStepSectionId(e,t){return`subagent:${e}:step:${t}`}function subagentToolSectionId(e,t){return`subagent:${e}:tool:${t}`}function connectionAuthSectionId(e){return`connection-auth:${e}`}function connectionAuthTerminalMessage(e){switch(e){case`authorized`:return`Authorization complete`;case`declined`:return`Authorization declined`;case`failed`:return`Authorization failed`;case`timed-out`:return`Authorization timed out`;case`required`:case`pending`:return}}function formatConnectionAuthContent(e,t){let n=[];if(t!==void 0)n.push(t);else{let t=stripTerminalControls(e.description);t.length>0&&n.push(t);let r=e.challenge;r?.url&&n.push(`URL: ${stripTerminalControls(r.url)}`),r?.userCode&&n.push(`Code: ${stripTerminalControls(r.userCode)}`),r?.expiresAt&&n.push(`Expires: ${stripTerminalControls(r.expiresAt)}`),r?.instructions&&n.push(stripTerminalControls(r.instructions))}if(e.reason!==void 0){let t=stripTerminalControls(e.reason);t.length>0&&n.push(`Reason: ${t}`)}return n.join(`
|
|
12
14
|
`)}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=renderCursorRow(c?`${n.glyph.selectedPointer} ${a}`:` ${a}`,c,r);i.push(`${u}${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(`
|
|
13
15
|
`)}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};
|
|
@@ -7,7 +7,7 @@ export { createDataUrlFilePart, createTextWithFileContent } from "#client/file-p
|
|
|
7
7
|
export { MessageResponse } from "#client/message-response.js";
|
|
8
8
|
export { ClientSession } from "#client/session.js";
|
|
9
9
|
export type { EveAgentStoreCallbacks, EveAgentStoreInit, EveAgentStoreSnapshot, EveAgentStoreStatus, PrepareSend, } from "#client/eve-agent-store.js";
|
|
10
|
-
export type { AgentInfoEntry, AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoFrameworkChannelEntry, AgentInfoFrameworkToolEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, CancelSessionResult, ClientAuth, ClientOptions, ClientRedirectPolicy, HeadersValue, HealthResult, MessageResult, ResolvedStreamReconnectPolicy, SendTurnInput, SendTurnPayload, SessionState, StreamOptions, StreamReconnectPolicy, StreamReconnectRetryPolicy, TokenValue, } from "#client/types.js";
|
|
10
|
+
export type { AgentInfoEntry, AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoFrameworkChannelEntry, AgentInfoFrameworkToolEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, CancelSessionResult, ClientAuth, ClientOptions, ClientRedirectPolicy, HeadersValue, HealthResult, MessageResult, ResetResult, ResolvedStreamReconnectPolicy, SendTurnInput, SendTurnPayload, SessionState, StreamOptions, StreamReconnectPolicy, StreamReconnectRetryPolicy, TokenValue, } from "#client/types.js";
|
|
11
11
|
export type { EveAgentReducer, EveAgentReducerEvent, ClientInputRespondedEvent, ClientMessageFailedEvent, ClientMessageSubmittedEvent, } from "#client/reducer.js";
|
|
12
12
|
export type { EveAuthorizationChallenge, EveAuthorizationOutcome, EveAuthorizationPart, EveMessageData, EveDynamicToolPart, EveMessageInputRequest, EveMessage, EveMessageMetadata, EveMessagePart, EveMessageToolMetadata, } from "#client/message-reducer.js";
|
|
13
13
|
export type { ActionResultStreamEvent, ActionsRequestedStreamEvent, AssistantStepFinishReason, AuthorizationOutcome, CompactionCompletedStreamEvent, CompactionRequestedStreamEvent, AuthorizationCompletedStreamEvent, ConnectionAuthorizationOutcome, AuthorizationRequiredStreamEvent, HandleMessageStreamEvent, InputRequestedStreamEvent, MessageAppendedStreamEvent, MessageCompletedStreamEvent, MessageReceivedPart, MessageReceivedStreamEvent, ReasoningAppendedStreamEvent, ReasoningCompletedStreamEvent, ResultCompletedStreamEvent, SessionCompletedStreamEvent, SessionFailedStreamEvent, SessionStartedStreamEvent, SessionWaitingStreamEvent, StepCompletedStreamEvent, StepFailedStreamEvent, StepStartedStreamEvent, SubagentCalledStreamEvent, SubagentChildEventStreamEvent, SubagentCompletedStreamEvent, SubagentStartedStreamEvent, TurnCancelledStreamEvent, TurnCompletedStreamEvent, TurnFailedStreamEvent, TurnStartedStreamEvent, TurnFailureStreamEvent, } from "#protocol/message.js";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { HandleMessageStreamEvent } from "#protocol/message.js";
|
|
2
2
|
import { MessageResponse } from "#client/message-response.js";
|
|
3
|
-
import type { CancelSessionResult, ClientRedirectPolicy, SendTurnInput, SessionState, StreamOptions } from "#client/types.js";
|
|
3
|
+
import type { CancelSessionResult, ClientRedirectPolicy, ResetResult, SendTurnInput, SessionState, StreamOptions } from "#client/types.js";
|
|
4
4
|
/**
|
|
5
5
|
* Internal interface that a {@link ClientSession} uses to access client-level
|
|
6
6
|
* configuration without depending on the full {@link Client} class.
|
|
@@ -51,6 +51,18 @@ export declare class ClientSession {
|
|
|
51
51
|
cancel(options?: {
|
|
52
52
|
turnId?: string;
|
|
53
53
|
}): Promise<CancelSessionResult>;
|
|
54
|
+
/**
|
|
55
|
+
* Terminally retires the session that owns this handle's continuation token.
|
|
56
|
+
*
|
|
57
|
+
* Unlike {@link cancel}, reset does not merely stop an active turn: it
|
|
58
|
+
* releases the durable workflow owner so the next {@link send} creates a
|
|
59
|
+
* fresh conversation and initializes a new session-scoped sandbox on first
|
|
60
|
+
* sandbox use. Resetting a never-started handle is a successful no-op. After
|
|
61
|
+
* a successful reset, this handle has no session state.
|
|
62
|
+
*
|
|
63
|
+
* @throws {ClientError} If the reset route returns a non-successful status.
|
|
64
|
+
*/
|
|
65
|
+
reset(): Promise<ResetResult>;
|
|
54
66
|
/**
|
|
55
67
|
* Opens this session's event stream for the current session ID.
|
|
56
68
|
*
|