eve 0.15.0 → 0.15.1
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 +9 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/status-line.d.ts +6 -3
- package/dist/src/cli/dev/tui/status-line.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +1 -1
- package/dist/src/cli/dev/tui/vercel-status.d.ts +2 -2
- package/dist/src/cli/dev/tui/vercel-status.js +1 -1
- package/dist/src/cli/run.d.ts +2 -2
- package/dist/src/cli/run.js +2 -2
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/execution/workflow-callback-url.d.ts +8 -0
- package/dist/src/execution/workflow-callback-url.js +1 -1
- package/dist/src/execution/workflow-entry.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/nitro/host/dev-server-state.d.ts +20 -0
- package/dist/src/internal/nitro/host/dev-server-state.js +1 -0
- package/dist/src/internal/nitro/host/start-development-server.d.ts +12 -5
- package/dist/src/internal/nitro/host/start-development-server.js +2 -2
- package/dist/src/internal/nitro/host/types.d.ts +25 -3
- package/dist/src/internal/nitro/host.d.ts +2 -2
- package/dist/src/internal/nitro/host.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/eve-server-health.d.ts +5 -0
- package/dist/src/shared/eve-server-health.js +1 -0
- package/dist/src/shared/network-address.d.ts +12 -0
- package/dist/src/shared/network-address.js +1 -1
- package/dist/src/shared/result.d.ts +12 -0
- package/dist/src/shared/result.js +1 -0
- package/docs/guides/dev-tui.md +1 -1
- package/docs/reference/cli.md +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.15.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- b049756: Use the active eve development server URL for connection authorization callbacks. Local Vercel Connect flows now return to eve's actual port instead of Workflow's port 3000 fallback.
|
|
8
|
+
- 2933ab2: The local `eve dev` status bar now shows a gray `:port` badge and retains it as terminal width narrows. Status segments now use tighter spacing.
|
|
9
|
+
- 2e4e15d: `eve init` now accepts `--yes` as a no-op compatibility flag and warns before continuing.
|
|
10
|
+
- 2933ab2: Running `eve dev` interactively now reconnects to the healthy loopback dev server recorded for the same app root, with a fresh session for each attached terminal UI. Eve replaces stale or malformed state when it starts a new server. `--host`, `--port`, or `PORT` skips reconnection and reports a healthy recorded server instead.
|
|
11
|
+
|
|
3
12
|
## 0.15.0
|
|
4
13
|
|
|
5
14
|
### Minor Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{pickAgentHeaderTip}from"./agent-header.js";import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{failureKey,formatFailureDetail,formatFailureMessage,formatGatewayAuthFailureNotice,isAbortLikeError,isGatewayAuthFailure,isInterruptedError}from"./errors.js";import{parseLogDisplayMode}from"./log-display-mode.js";import{createRemoteConnectionController}from"./remote-connection.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,automaticSetupCommand,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{isCurrentTurnBoundaryEvent}from"#client/index.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createDevelopmentRuntimeArtifactSessionRefresher}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=pickAgentHeaderTip();#O;#k=new Map;#A=new Map;#j=new Map;#M=new Map;#N=new Set;#P=!1;#F;constructor(e){if(this.#e=e.session,e.client!==void 0&&(this.#t=e.client),this.#n=createRenderer(e),this.#r=e.name??`eve`,this.#i=e.tools??`full`,this.#a=e.reasoning??`full`,this.#o=e.subagents??`full`,this.#s=e.connectionAuth??`full`,this.#c=e.assistantResponseStats??`tokensPerSecond`,this.#l=e.contextSize,this.#u=e.formatTransportError??toErrorMessage,e.initialInput!==void 0&&(this.#m=e.initialInput),e.appRoot!==void 0){this.#p=e.appRoot;let t={appRoot:e.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};e.detectProjectIdentity!==void 0&&(t.detectIdentity=e.detectProjectIdentity),this.#E=createVercelStatusTracker(t)}if(e.promptCommandHandler!==void 0&&(this.#h=e.promptCommandHandler),this.#g=e.availablePromptCommands??PROMPT_COMMANDS,e.remote!==void 0){if(this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#_=createRemoteConnectionController({client:this.#t,credentials:e.remote.credentials,target:e.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:e.remote.resolveOidcToken,resolveDeployment:e.remote.resolveDeployment})}this.#v=e.bootDetections??BOOT_DETECTIONS,this.#y=e.getVercelAuthStatus??getVercelAuthStatus,e.onBootProgress!==void 0&&(this.#b=e.onBootProgress),e.serverUrl!==void 0&&(this.#f=e.serverUrl),e.serverUrl!==void 0&&e.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactSessionRefresher({serverUrl:e.serverUrl}))}async#I(){if(this.#f===void 0){this.#R(),await this.#U(void 0);return}let e;if(this.#_!==void 0){let t=await this.#_.check();t.state===`ready`&&(e=t.info)}else try{e=await devBootPhase(`connecting to agent`,()=>this.#t?this.#t.info():Promise.resolve(void 0),this.#b)}catch{e=void 0}this.#R();let t=this.#L(e);await this.#U(t)}#L(e){let t=this.#p===void 0?e:resolveModelProviderState(e,process.env);this.#O=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.#D),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.#F?.(),this.#F=void 0,this.#n.shutdown?.(),this.#E?.dispose(),this.#_?.dispose()}}async#z(){let e=this.#r,t,i,a,o=!1,s=!1,c=this.#m;for(await this.#I(),this.#_?.current().connection.state===`auth-required`&&await this.#Q({type:`extension`,name:`vc:login`,argument:``},e,`startup`),this.#q(),this.#E?.refreshIdentity(),this.#h!==void 0&&this.#n.setupFlow!==void 0&&(i=automaticSetupCommand(this.#w),t=i?.prompt);;){if(!s){if(t==null){if(!this.#n.readPrompt){if(o)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let n={title:e};c!==void 0&&(n.initialDraft=c,c=void 0);try{t=await this.#V(n)}catch(e){if(isInterruptedError(e))return;throw e}if(t==null)return}let l=parsePromptCommand(t);if(l?.type===`exit`)return;if(l?.type===`new`){this.#B(),a=void 0,s=!1,t=void 0,this.#n.reset?.();continue}if(l?.type===`help`){this.#J(formatPromptCommandHelp(this.#g)),a=void 0,s=!1,t=void 0;continue}if(l?.type===`loglevel`){this.#J(this.#ee(l.argument)),a=void 0,s=!1,t=void 0;continue}if(l?.type===`extension`){try{let t=l.name===`model`?i?.initialModelStep:void 0;i=void 0,await this.#Q(l,e,`command`,t)}catch(e){if(isInterruptedError(e))return;throw e}a=void 0,t=void 0,s=!1;continue}o=!0}let l=await this.#H({prompt:s?void 0:t,inputResponses:a});try{await this.#n.renderStream(l,{title:e,submittedPrompt:t,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let n=l.turnState?.pendingApprovals??[],r=l.turnState?.pendingQuestions??[];if(n.length>0||r.length>0){let i=[];if(n.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let t of n){let n=await this.#n.readToolApproval(t,{title:e});i.push({requestId:t.approvalId,optionId:n.approved?`approve`:`deny`}),this.#k.delete(t.approvalId)}}if(r.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 r){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let a={requestId:t.requestId};r.optionId!==void 0&&(a.optionId=r.optionId),r.text!==void 0&&(a.text=r.text),i.push(a),this.#k.delete(t.requestId)}}s=!0,a=i,t=void 0;continue}l.turnState&&l.turnState.boundaryEvent===void 0&&(this.#P=!0)}catch(e){if(isInterruptedError(e))return;throw e}s=!1,a=void 0,t=void 0,this.#P&&(this.#P=!1,this.#B(),this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`))}}#B(){for(let e of this.#j.values())e.abort();this.#j.clear(),this.#A.clear(),this.#k.clear(),this.#M.clear(),this.#N.clear(),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.#t,r=this.#d;if(n===void 0||r===void 0)return await t;let i=!1,a=!1,o,refresh=async()=>{if(!(i||a)){a=!0;try{this.#e=await r.refreshIdle({createSession:()=>n.session(),onRuntimeArtifactsChanged:()=>this.#re(),session:this.#e})}finally{a=!1}}},startRefresh=()=>{if(i||a)return;let e=refresh().finally(()=>{o===e&&(o=void 0)});o=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await t}finally{i=!0,clearInterval(s),await o}}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{let e=this.#t;e!==void 0&&this.#d!==void 0&&(this.#e=await this.#d.refresh({createSession:()=>e.session(),inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#re(),session:this.#e})),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()}}let i=createTurnState();return{abort:()=>t.abort(),events:eveEventsToTUIStream({events:r,pendingInputRequests:this.#k,subagentRuns:this.#A,turnState:i,onSubagentCalled:e=>this.#se(e),onSubagentCompleted:e=>this.#le(e),onConnectionAuthRequired:e=>this.#ie(e),onConnectionAuthCompleted:e=>this.#ae(e),onTerminalFailure:()=>{this.#P=!0},failureOverride:this.#p===void 0?void 0:e=>isGatewayAuthFailure(e)?formatGatewayAuthFailureNotice(e):void 0}),turnState:i}}async#U(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.#W(),this.#G())}#W(){let e=orderedSetupIssues(this.#w,this.#T);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#G(){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.#W())}async#K(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.#W()}#q(){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)}))}#J(e){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}}async#Y(e,t){let n=this.#h;return n===void 0?{message:`/${e.name} is not available in this session.`}:await n.handle(e,{renderer:this.#n,title:t.title,initialModelStep:t.initialModelStep,remoteConnection:this.#_})}#X(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#Z(e){if(e?.kind===`model-access-changed`){this.#E?.applyEffect({kind:`refresh-identity`}),this.#C=!0,await this.#te();return}e!==void 0&&(this.#E?.applyEffect(e),this.#C=!0,this.#K(this.#O))}async#Q(e,t,n,r){let i=await this.#Y(e,{initialModelStep:r,title:t});this.#X(e,n),this.#J(i?.message),await this.#Z(i?.effect),this.#$()}#$(){let e=this.#_?.current().connection;e?.state!==`ready`||e.info===this.#O||(this.#O=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}#ee(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#te(){let e=this.#p;if(e===void 0)return;loadDevelopmentEnvironmentFiles(e);let t=this.#L(await this.#ne());this.#K(t)}async#ne(){try{return await this.#t?.info()}catch{return}}async#re(){let e=this.#O,t=await this.#ne();t!==void 0&&this.#L(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#ie(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.#oe(t)}#ae(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.#oe(t),this.#n.setConnectionAuthPendingCount?.(this.#N.size)}#oe(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)}#se(e){let t=e.data.callId;if(this.#j.has(t))return;let n=this.#t;if(!n)return;let r=new AbortController;this.#j.set(t,r),(async()=>{try{let i=n.session({sessionId:e.data.childSessionId,streamIndex:0}).stream({signal:r.signal});for await(let e of i)if(r.signal.aborted||(this.#ue(t,e),isCurrentTurnBoundaryEvent(e)))break}catch(e){if(!isAbortLikeError(e)){let n=toErrorMessage(e),r=this.#A.get(t);if(r){let{key:e,step:i}=openCurrentSubagentSection(r);i.message=i.message?`${i.message}\n\nstream error: ${n}`:`stream error: ${n}`,i.finalized=!0,r.currentSectionKey=null,this.#n.upsertSubagentStep?.({callId:t,subagentName:r.name,sectionKey:e,reasoning:i.reasoning,message:i.message,finalized:!0})}}}finally{this.#j.delete(t)}})()}#ce(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={"approval-requested":0,executing:1,done:2,failed:2};e[n.status]>e[r.status]&&(r.status=n.status),r.input=n.input}else t.tools.set(n.childCallId,i);this.#n.markChildToolCallId?.(n.childCallId),this.#n.upsertSubagentTool?.({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#le(e){let t=this.#A.get(e);if(t){for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#n.upsertSubagentStep?.({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null}}#ue(e,t){let n=this.#A.get(e);if(!n)return;let r=this.#n,emit=(t,i)=>{r.upsertSubagentStep?.({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();break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#ce(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.#ce(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;t.data.status===`failed`?(a.status=`failed`,a.errorText=formatActionResultError(t)):(a.status=`done`,a.output=i.output);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.upsertSubagentTool?.(o);break}default:break}}};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})}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,subagentRuns:r,turnState:i,onSubagentCalled:a,onSubagentCompleted:o,onConnectionAuthRequired:s,onConnectionAuthCompleted:c,onTerminalFailure:l,failureOverride: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`turn.started`:case`message.received`: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(i,e);continue}upsertPendingApproval(i,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;t.data.status===`failed`?yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)}:yield{type:`tool-result`,toolCallId:n,output:t.data.result.output};break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,g,u);t&&(yield t);break}case`session.failed`:{i.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,g,u);t&&(yield t),i.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`:i.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`subagent.called`:{let t=e;if(!r.has(t.data.callId))r.set(t.data.callId,{name:t.data.name,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map});else{let e=r.get(t.data.callId);e&&(e.name=t.data.name)}a?.(t);break}case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:o?.(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{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 s=n?.(e),c={type:`error`,errorText:s??formatFailureMessage(e)};if(s!==void 0)return c;let l=formatFailureDetail(e);return l!==void 0&&(c.detail=l),c}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}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{EveTUIRunner,parsePromptCommand};
|
|
1
|
+
import{pickAgentHeaderTip}from"./agent-header.js";import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{failureKey,formatFailureDetail,formatFailureMessage,formatGatewayAuthFailureNotice,isAbortLikeError,isGatewayAuthFailure,isInterruptedError}from"./errors.js";import{parseLogDisplayMode}from"./log-display-mode.js";import{createRemoteConnectionController}from"./remote-connection.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,automaticSetupCommand,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{isCurrentTurnBoundaryEvent}from"#client/index.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createDevelopmentRuntimeArtifactSessionRefresher}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=pickAgentHeaderTip();#O;#k=new Map;#A=new Map;#j=new Map;#M=new Map;#N=new Set;#P=!1;#F;constructor(e){if(this.#e=e.session,e.client!==void 0&&(this.#t=e.client),this.#n=createRenderer(e),this.#r=e.name??`eve`,this.#i=e.tools??`full`,this.#a=e.reasoning??`full`,this.#o=e.subagents??`full`,this.#s=e.connectionAuth??`full`,this.#c=e.assistantResponseStats??`tokensPerSecond`,this.#l=e.contextSize,this.#u=e.formatTransportError??toErrorMessage,e.initialInput!==void 0&&(this.#m=e.initialInput),e.appRoot!==void 0){this.#p=e.appRoot;let t={appRoot:e.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};e.detectProjectIdentity!==void 0&&(t.detectIdentity=e.detectProjectIdentity),this.#E=createVercelStatusTracker(t)}if(e.promptCommandHandler!==void 0&&(this.#h=e.promptCommandHandler),this.#g=e.availablePromptCommands??PROMPT_COMMANDS,e.remote!==void 0){if(this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#_=createRemoteConnectionController({client:this.#t,credentials:e.remote.credentials,target:e.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:e.remote.resolveOidcToken,resolveDeployment:e.remote.resolveDeployment})}this.#v=e.bootDetections??BOOT_DETECTIONS,this.#y=e.getVercelAuthStatus??getVercelAuthStatus,e.onBootProgress!==void 0&&(this.#b=e.onBootProgress),e.serverUrl!==void 0&&(this.#f=e.serverUrl),e.serverUrl!==void 0&&e.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactSessionRefresher({serverUrl:e.serverUrl}))}async#I(){if(this.#f===void 0){this.#R(),await this.#W(void 0);return}let e;if(this.#_!==void 0){let t=await this.#_.check();t.state===`ready`&&(e=t.info)}else try{e=await devBootPhase(`connecting to agent`,()=>this.#t?this.#t.info():Promise.resolve(void 0),this.#b)}catch{e=void 0}this.#R();let t=this.#L(e);await this.#W(t)}#L(e){let t=this.#p===void 0?e:resolveModelProviderState(e,process.env);this.#O=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.#D),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.#V(),this.#F?.(),this.#F=void 0,this.#n.shutdown?.(),this.#E?.dispose(),this.#_?.dispose()}}async#z(){let e=this.#r,t,i,a,o=!1,s=!1,c=this.#m;for(await this.#I(),this.#_?.current().connection.state===`auth-required`&&await this.#$({type:`extension`,name:`vc:login`,argument:``},e,`startup`),this.#J(),this.#E?.refreshIdentity(),this.#h!==void 0&&this.#n.setupFlow!==void 0&&(i=automaticSetupCommand(this.#w),t=i?.prompt);;){if(!s){if(t==null){if(!this.#n.readPrompt){if(o)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let n={title:e};c!==void 0&&(n.initialDraft=c,c=void 0);try{t=await this.#H(n)}catch(e){if(isInterruptedError(e))return;throw e}if(t==null)return}let l=parsePromptCommand(t);if(l?.type===`exit`)return;if(l?.type===`new`){this.#B(),a=void 0,s=!1,t=void 0,this.#n.reset?.();continue}if(l?.type===`help`){this.#Y(formatPromptCommandHelp(this.#g)),a=void 0,s=!1,t=void 0;continue}if(l?.type===`loglevel`){this.#Y(this.#te(l.argument)),a=void 0,s=!1,t=void 0;continue}if(l?.type===`extension`){try{let t=l.name===`model`?i?.initialModelStep:void 0;i=void 0,await this.#$(l,e,`command`,t)}catch(e){if(isInterruptedError(e))return;throw e}a=void 0,t=void 0,s=!1;continue}o=!0}let l=await this.#U({prompt:s?void 0:t,inputResponses:a});try{await this.#n.renderStream(l,{title:e,submittedPrompt:t,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let n=l.turnState?.pendingApprovals??[],r=l.turnState?.pendingQuestions??[];if(n.length>0||r.length>0){let i=[];if(n.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let t of n){let n=await this.#n.readToolApproval(t,{title:e});i.push({requestId:t.approvalId,optionId:n.approved?`approve`:`deny`}),this.#k.delete(t.approvalId)}}if(r.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 r){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let a={requestId:t.requestId};r.optionId!==void 0&&(a.optionId=r.optionId),r.text!==void 0&&(a.text=r.text),i.push(a),this.#k.delete(t.requestId)}}s=!0,a=i,t=void 0;continue}l.turnState&&l.turnState.boundaryEvent===void 0&&(this.#P=!0)}catch(e){if(isInterruptedError(e))return;throw e}s=!1,a=void 0,t=void 0,this.#P&&(this.#P=!1,this.#B(),this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`))}}#B(){this.#V(),this.#A.clear(),this.#k.clear(),this.#M.clear(),this.#N.clear(),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}#V(){for(let e of this.#j.values())e.abort();this.#j.clear()}async#H(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#t,r=this.#d;if(n===void 0||r===void 0)return await t;let i=!1,a=!1,o,refresh=async()=>{if(!(i||a)){a=!0;try{this.#e=await r.refreshIdle({createSession:()=>n.session(),onRuntimeArtifactsChanged:()=>this.#ie(),session:this.#e})}finally{a=!1}}},startRefresh=()=>{if(i||a)return;let e=refresh().finally(()=>{o===e&&(o=void 0)});o=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await t}finally{i=!0,clearInterval(s),await o}}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{let e=this.#t;e!==void 0&&this.#d!==void 0&&(this.#e=await this.#d.refresh({createSession:()=>e.session(),inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#ie(),session:this.#e})),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()}}let i=createTurnState();return{abort:()=>t.abort(),events:eveEventsToTUIStream({events:r,pendingInputRequests:this.#k,subagentRuns:this.#A,turnState:i,onSubagentCalled:e=>this.#ce(e),onSubagentCompleted:e=>this.#ue(e),onConnectionAuthRequired:e=>this.#ae(e),onConnectionAuthCompleted:e=>this.#oe(e),onTerminalFailure:()=>{this.#P=!0},failureOverride:this.#p===void 0?void 0:e=>isGatewayAuthFailure(e)?formatGatewayAuthFailureNotice(e):void 0}),turnState:i}}async#W(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.#G(),this.#K())}#G(){let e=orderedSetupIssues(this.#w,this.#T);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#K(){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.#G())}async#q(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.#G()}#J(){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)}))}#Y(e){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}}async#X(e,t){let n=this.#h;return n===void 0?{message:`/${e.name} is not available in this session.`}:await n.handle(e,{renderer:this.#n,title:t.title,initialModelStep:t.initialModelStep,remoteConnection:this.#_})}#Z(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#Q(e){if(e?.kind===`model-access-changed`){this.#E?.applyEffect({kind:`refresh-identity`}),this.#C=!0,await this.#ne();return}e!==void 0&&(this.#E?.applyEffect(e),this.#C=!0,this.#q(this.#O))}async#$(e,t,n,r){let i=await this.#X(e,{initialModelStep:r,title:t});this.#Z(e,n),this.#Y(i?.message),await this.#Q(i?.effect),this.#ee()}#ee(){let e=this.#_?.current().connection;e?.state!==`ready`||e.info===this.#O||(this.#O=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}#te(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#ne(){let e=this.#p;if(e===void 0)return;loadDevelopmentEnvironmentFiles(e);let t=this.#L(await this.#re());this.#q(t)}async#re(){try{return await this.#t?.info()}catch{return}}async#ie(){let e=this.#O,t=await this.#re();t!==void 0&&this.#L(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#ae(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.#se(t)}#oe(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.#se(t),this.#n.setConnectionAuthPendingCount?.(this.#N.size)}#se(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)}#ce(e){let t=e.data.callId;if(this.#j.has(t))return;let n=this.#t;if(!n)return;let r=new AbortController;this.#j.set(t,r),(async()=>{try{let i=n.session({sessionId:e.data.childSessionId,streamIndex:0}).stream({signal:r.signal});for await(let e of i)if(r.signal.aborted||(this.#de(t,e),isCurrentTurnBoundaryEvent(e)))break}catch(e){if(!isAbortLikeError(e)){let n=toErrorMessage(e),r=this.#A.get(t);if(r){let{key:e,step:i}=openCurrentSubagentSection(r);i.message=i.message?`${i.message}\n\nstream error: ${n}`:`stream error: ${n}`,i.finalized=!0,r.currentSectionKey=null,this.#n.upsertSubagentStep?.({callId:t,subagentName:r.name,sectionKey:e,reasoning:i.reasoning,message:i.message,finalized:!0})}}}finally{this.#j.delete(t)}})()}#le(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={"approval-requested":0,executing:1,done:2,failed:2};e[n.status]>e[r.status]&&(r.status=n.status),r.input=n.input}else t.tools.set(n.childCallId,i);this.#n.markChildToolCallId?.(n.childCallId),this.#n.upsertSubagentTool?.({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#ue(e){let t=this.#A.get(e);if(t){for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#n.upsertSubagentStep?.({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null}}#de(e,t){let n=this.#A.get(e);if(!n)return;let r=this.#n,emit=(t,i)=>{r.upsertSubagentStep?.({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();break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#le(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.#le(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;t.data.status===`failed`?(a.status=`failed`,a.errorText=formatActionResultError(t)):(a.status=`done`,a.output=i.output);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.upsertSubagentTool?.(o);break}default:break}}};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})}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,subagentRuns:r,turnState:i,onSubagentCalled:a,onSubagentCompleted:o,onConnectionAuthRequired:s,onConnectionAuthCompleted:c,onTerminalFailure:l,failureOverride: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`turn.started`:case`message.received`: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(i,e);continue}upsertPendingApproval(i,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;t.data.status===`failed`?yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)}:yield{type:`tool-result`,toolCallId:n,output:t.data.result.output};break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,g,u);t&&(yield t);break}case`session.failed`:{i.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,g,u);t&&(yield t),i.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`:i.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`subagent.called`:{let t=e;if(!r.has(t.data.callId))r.set(t.data.callId,{name:t.data.name,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map});else{let e=r.get(t.data.callId);e&&(e.name=t.data.name)}a?.(t);break}case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:o?.(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{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 s=n?.(e),c={type:`error`,errorText:s??formatFailureMessage(e)};if(s!==void 0)return c;let l=formatFailureDetail(e);return l!==void 0&&(c.detail=l),c}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}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{EveTUIRunner,parsePromptCommand};
|
|
@@ -4,6 +4,8 @@ import type { RemoteConnectionSnapshot } from "./remote-connection.js";
|
|
|
4
4
|
import type { VercelStatusSnapshot } from "./vercel-status.js";
|
|
5
5
|
import type { ModelEndpointStatus } from "#shared/model-endpoint-status.js";
|
|
6
6
|
export interface StatusLineInput {
|
|
7
|
+
/** Port of the connected local development server; omitted for remote sessions. */
|
|
8
|
+
serverPort?: string;
|
|
7
9
|
/** Resolved model slug, e.g. "anthropic/claude-sonnet-4-6"; absent when `/eve/v1/info` failed. */
|
|
8
10
|
model?: string;
|
|
9
11
|
/** Preformatted token-flow segment (formatTokenFlow output), e.g. `↑ 394.4K ↓ 4.3K`. */
|
|
@@ -25,8 +27,9 @@ export interface StatusLineInput {
|
|
|
25
27
|
width: number;
|
|
26
28
|
}
|
|
27
29
|
/**
|
|
28
|
-
* Builds
|
|
29
|
-
*
|
|
30
|
-
*
|
|
30
|
+
* Builds a leading local `:port` or remote badge followed by model, token, and
|
|
31
|
+
* deploy status segments. Both badges are the final narrow-width fallback.
|
|
32
|
+
* Remote sessions omit endpoint state. Returns undefined when every segment is
|
|
33
|
+
* empty.
|
|
31
34
|
*/
|
|
32
35
|
export declare function buildStatusLine(input: StatusLineInput): string | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{clipVisible,stripAnsi,visibleLength}from"./terminal-text.js";import{remoteHost}from"./target.js";function renderModel(e){if(e.model===void 0)return;let n=e.remote===void 0?e.model:stripAnsi(e.model).replace(/\s+/gu,` `).trim();return e.theme.colors.dim(n)}function renderEndpoint(e){if(e.remote!==void 0||e.endpoint===void 0)return;let t=e.theme.colors;if(e.endpoint.kind===`external`)return t.dim(`External endpoint`);if(!e.endpoint.connected)return t.yellow(`${e.theme.glyph.warning} AI Gateway`);let n=e.vercel?.identity?.projectName;return t.dim(n===void 0?`AI Gateway`:`AI Gateway (${n})`)}function buildStatusLine(t){let{theme:r,width:i}=t,a=r.colors,o=t.logLevel===void 0?void 0:a.cyan(`logs: ${t.logLevel}`),s=
|
|
1
|
+
import{clipVisible,stripAnsi,visibleLength}from"./terminal-text.js";import{remoteHost}from"./target.js";function renderModel(e){if(e.model===void 0)return;let n=e.remote===void 0?e.model:stripAnsi(e.model).replace(/\s+/gu,` `).trim();return e.theme.colors.dim(n)}function renderServerPort(e){if(e.remote!==void 0||e.serverPort===void 0)return;let t=e.theme.colors;return t.inverse(t.gray(` :${e.serverPort} `))}function renderEndpoint(e){if(e.remote!==void 0||e.endpoint===void 0)return;let t=e.theme.colors;if(e.endpoint.kind===`external`)return t.dim(`External endpoint`);if(!e.endpoint.connected)return t.yellow(`${e.theme.glyph.warning} AI Gateway`);let n=e.vercel?.identity?.projectName;return t.dim(n===void 0?`AI Gateway`:`AI Gateway (${n})`)}function buildStatusLine(t){let{theme:r,width:i}=t,a=r.colors,o=t.logLevel===void 0?void 0:a.cyan(`logs: ${t.logLevel}`),s=renderServerPort(t),c=renderModel(t),l=t.tokens===void 0?void 0:a.dim(t.tokens),u=t.vercel?.pendingDeploy?a.yellow(`/deploy pending`):void 0,d=t.remote===void 0?void 0:formatRemoteStatus(t.remote,r),f=renderEndpoint(t),p=d?.full??s,m=d?.badge??s,h=` ${a.dim(r.glyph.dot)} `,compose=(e,t)=>{let n=t.filter(e=>e!==void 0).join(h);return e===void 0||n.length===0?e??n:`${e} ${n}`},g=[compose(p,[o,c,l,f,u]),compose(p,[o,c,l,u]),compose(p,[o,l,u]),compose(p,[o]),compose(m,[o]),compose(m,[])];if(g[0].length!==0){for(let e of g)if(e.length>0&&visibleLength(e)<=i)return e;return clipVisible(g.findLast(e=>e.length>0),i)}}function formatRemoteStatus(e,t){let n=t.colors,i=e.deployment===void 0?remoteHost(e.target):`${e.deployment.projectName} (${e.deployment.environment})`,a=formatRemoteBadge(` ${t.unicode?`↗`:`->`} ${i} `,e.connection.state,t),o=`${n.dim(t.glyph.dot)} `,s;switch(e.connection.state){case`checking`:s=n.dim(`Checking access…`);break;case`ready`:break;case`auth-required`:s=n.yellow(`Authenticate via OIDC`);break;case`authenticating`:s=n.dim(`Authenticating via OIDC…`);break;case`auth-failed`:s=n.yellow(`Authentication failed`);break;case`unavailable`:s=n.yellow(`Remote unavailable`);break}return{badge:a,full:s===void 0?a:`${a}${o}${s}`}}function formatRemoteBadge(e,t,n){let r=n.colors;switch(t){case`checking`:return r.inverse(r.gray(e));case`ready`:return r.inverse(r.blue(e));case`unavailable`:case`auth-required`:case`authenticating`:case`auth-failed`:return r.inverse(r.yellow(e))}}export{buildStatusLine};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.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{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{toErrorMessage}from"#shared/errors.js";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{StringDecoder}from"node:string_decoder";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e,t){return e?`Interrupted`:t?`Ready`:`Done`}const STATUS={processing:`Working…`,toolResults:`Reading results…`,streaming:`Responding…`,executingTools:`Running tools…`,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=new Set;#b;#x=!1;#S;#C=[];#w;#T=0;#E;#D;#O=``;#k=0;#A=new PromptHistory;#j=!1;#M;#N={kind:`idle`};#P=STATUS.processing;#F=`eve`;#I=!1;#L=!1;#R=!0;#z=0;#B;#V;#H;#U=!1;#W;#G=``;#K=new StringDecoder(`utf8`);#q;#J;#Y;#X=!1;#Z=!1;#Q;#$;#ee;#te;#ne;#re;#ie;#ae=``;#oe=``;#se;#ce;#le=0;#ue;#de;#fe;#pe;#me;setupFlow={begin:(e,t)=>this.#ve(e,t),end:e=>this.#ye(e?.preserveDiagnostics??!0),readSelect:e=>this.#be(e),readEditableSelect:e=>this.#Se(e),readProviderPicker:e=>this.#Ce(e),readText:e=>this.#we(e),readAcknowledge:e=>this.#Te(e),readChoice:e=>this.#xe(e),setStatus:e=>this.#Ne(e),renderLine:(e,t)=>this.#Pe(e,t),renderOutput:e=>this.#Fe(e),waitForInterrupt:()=>this.#Ae()};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#i=e?.tools??`auto-collapsed`,this.#a=e?.reasoning??`full`,this.#o=e?.subagents??`auto-collapsed`,this.#s=e?.connectionAuth??`full`,this.#c=e?.assistantResponseStats??`tokensPerSecond`,this.#l=e?.contextSize,this.#ee=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#f=e?.logs??`none`,this.#d=e?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#F=e.name,this.#b=e,this.#Ie();let t=this.#vt().join(`
|
|
2
2
|
`);if(this.#x){t!==this.#S&&(this.#S=t,this.#Ze({kind:`agent-header`,body:t,live:!1})),this.#pt();return}this.#x=!0,this.#S=t,this.#n.flush(this.#vt(),[])}async readPrompt(e){this.#Ie(e),this.#Xe(),this.#j=!0,this.#N={kind:`idle`},this.#P=``;let t=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#A.begin(t.text),this.#he(t),this.#M=typeaheadFor(this.#d,t.text),this.#Ge(),this.#pt(),await new Promise((e,n)=>{let apply=e=>{t=e,this.#qe(),this.#he(t),this.#M=typeaheadFor(this.#d,e.text,this.#M),this.#pt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#M=void 0,this.#Ke(),this.#Le(),n(interruptedError())},suggestions=()=>this.#M!==void 0&&isTypeaheadOpen(this.#M)?this.#M:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#W=n=>{let r=applyLineEditorKey(t,n,{multiline:!0});if(r!==void 0){apply(r);return}switch(n.type){case`up`:{let e=suggestions();if(e!==void 0){this.#M=moveTypeaheadSelection(e,-1),this.#pt();break}let n=movePromptLine(t,`up`);n===void 0?recall(this.#A.previous(t.text)):apply(n);break}case`down`:{let e=suggestions();if(e!==void 0){this.#M=moveTypeaheadSelection(e,1),this.#pt();break}let n=movePromptLine(t,`down`);n===void 0?recall(this.#A.next()):apply(n);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#M=dismissTypeahead(e),this.#pt());break}case`enter`:{let n=highlighted(),r=n!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(n).trimEnd():t.text;this.#M=void 0,this.#A.add(r),this.#j=!1,this.#Ke(),this.#Ye(),this.#P=STATUS.processing,isPromptControlCommand(r)?this.#Ze({kind:`command`,body:stripTerminalControls(r.trim()),live:!1}):(this.#Qe(r),this.#ue=r),this.#he(EMPTY_LINE),this.#pt(),this.#ze(),e(r);break}case`ctrl-d`:t.text.length===0?interrupt():apply(deleteForward(t));break;case`ctrl-l`:this.#gt();break;case`ctrl-r`:this.#pt();break;case`ctrl-c`:t.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#Re()})}#he(e){this.#O=e.text,this.#k=e.cursor}async renderStream(e,t){this.#Ie(t),this.#h.clear(),this.#j=!1,this.#N.kind!==`waiting`&&(this.#N={kind:`waiting`,startedAtMs:Date.now()}),this.#P=STATUS.processing,this.#$e(t?.submittedPrompt),this.#L=!1,this.#Q=void 0,this.#$=void 0,this.#te=void 0,this.#ne=void 0,this.#re=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#Je(),this.#pt();let r=new Promise(e=>{this.#Y=e});this.#W=e=>this.#We(e),this.#Re();let i={text:new Map,reasoning:new Map,tools:new Map,hasPendingToolResults:!1};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#L)break;this.#at(t,n,i)}}catch(e){this.#et(`Error`,toErrorMessage(e))}finally{this.#Y=void 0,this.#L&&e.abort?.(),this.#ze(),this.#Xe(),this.#N.kind===`waiting`&&(this.#N={kind:`idle`}),this.#P=completedTurnStatus(this.#L,t?.continueSession===!0),this.#it(),this.#pt(),t?.continueSession||this.#Le()}}async readToolApproval(e,t){return this.#Ie(t),this.#Xe(),this.#j=!1,this.#N={kind:`idle`},this.#P=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#L=!1,this.#pt(),await new Promise((t,n)=>{this.#W=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Ye(),this.#P=STATUS.processing,this.#ze(),this.#pt(),t({approved:!0})):n===`n`&&(this.#Ye(),this.#P=STATUS.processing,this.#ge(e.toolCallId),this.#ze(),this.#pt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#pt();break;case`ctrl-c`:this.#L=!0,this.#Le(),n(interruptedError());break;default:break}},this.#Re()})}async readInputQuestion(e,t){this.#Ie(t),this.#Xe(),this.#j=!1,this.#N={kind:`idle`},this.#L=!1;let n=e.options??[],r=n.length>0,a=(e.allowFreeform===!0||!r)&&r,o=n.length+ +!!a,s=questionSectionId(e.requestId),c=r?`select`:`text`,l=0,u=EMPTY_LINE,isOnFreeformRow=()=>a&&l===n.length,renderSection=()=>{this.#nt({id:s,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,l,this.#r),preformatted:!0,live:!0})},repaintStatus=()=>{if(c===`select`){let e=isOnFreeformRow()?`type`:`select`;this.#P=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#j=!1}else this.#j=!0,this.#he(u),this.#P=``;this.#pt()};renderSection(),c===`text`&&this.#Ge(),repaintStatus();let finalize=t=>{this.#nt({id:s,kind:`question`,title:stripTerminalControls(e.prompt),body:` ${this.#r.colors.green(this.#r.glyph.success)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#j=!1,this.#Ye(),this.#P=STATUS.processing,this.#Ke(),this.#ze(),this.#pt();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n};return await new Promise((t,i)=>{this.#W=a=>{if(a.type===`ctrl-c`){if(c===`text`&&u.text.length>0){u=EMPTY_LINE,this.#qe(),repaintStatus();return}this.#L=!0,this.#Ke(),this.#Le(),i(interruptedError());return}if(a.type===`ctrl-r`){this.#pt();return}if(c===`select`){switch(a.type){case`up`:o>0&&(l=(l-1+o)%o,renderSection(),repaintStatus());break;case`down`:o>0&&(l=(l+1)%o,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){c=`text`,u=EMPTY_LINE,this.#Ge(),repaintStatus();break}let e=n[l];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}let s=applyLineEditorKey(u,a,{multiline:!0});if(s!==void 0){u=s,this.#qe(),repaintStatus();return}switch(a.type){case`up`:case`down`:{let e=movePromptLine(u,a.type);e!==void 0&&(u=e,this.#qe(),repaintStatus());break}case`enter`:{let n=resolveQuestionText(u.text,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(r){if(u.text.length>0){u=EMPTY_LINE,this.#qe(),repaintStatus();break}c=`select`,u=EMPTY_LINE,this.#j=!1,this.#Ke(),repaintStatus();break}u=EMPTY_LINE,this.#qe(),repaintStatus();break;default:break}},this.#Re()})}upsertSubagentStep(e){if(this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#tt(e.callId,e.subagentName),this.#o===`collapsed`){this.#pt();return}this.#nt({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:n,live:!e.finalized}),this.#pt()}}upsertSubagentTool(e){if(this.#o===`hidden`)return;if(this.#tt(e.callId,e.subagentName),this.#o===`collapsed`){this.#pt();return}let t=subagentToolStatus(e.status),n={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,depth:1,title:stripTerminalControls(e.toolName),subtitle:summarizeToolArgs(e.input),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolInput:e.input};e.output===void 0?e.errorText!==void 0&&(n.result=stripTerminalControls(e.errorText)):(n.result=summarizeToolResult(e.output),n.toolOutput=e.output),this.#nt(n),this.#pt()}markChildToolCallId(e){this.#_.add(e);let t=this.#v.get(e);t!==void 0&&(this.#rt(t),this.#v.delete(e),this.#pt())}#ge(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=e.state===`authorized`||e.state===`declined`||e.state===`failed`||e.state===`timed-out`;this.#nt({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e),preformatted:!0,live:!t}),this.#pt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#T)return;let n=this.#T>0;this.#T=t,t>0?(this.#P=STATUS.connectionAuth,this.#pt()):n&&(this.#P=STATUS.processing,this.#pt())}setVercelStatus(e){this.#E=e,this.#pt()}setRemoteConnectionStatus(e){this.#D=e,this.#pt()}reset(){this.#p=[],this.#m.clear(),this.#h.clear(),this.#w=void 0,this.#C.length=0,this.#g.length=0,this.#x=!1,this.#S=void 0,this.#_.clear(),this.#v.clear(),this.#y.clear(),this.#ue=void 0,this.#ce=void 0,this.#T=0,this.#Q=void 0,this.#$=void 0,this.#te=void 0,this.#ne=void 0,this.#re=void 0,this.#I&&(this.#n.clearAll(),this.#pt())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ie(),this.#Ze({kind:`notice`,body:t,live:!1}),this.#pt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#Ie(),this.#Ze({kind:`sandbox`,body:t,live:!1}),this.#pt())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#_e();return}this.#Ie(),this.#fe=t,this.#pt()}clearSetupWarning(){this.#_e()}#_e(){this.#fe!==void 0&&(this.#fe=void 0,this.#pt())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#Ie();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Ze(r),this.#pt()}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ie(),this.#Ze({kind:`result`,body:t,live:!1}),this.#pt())}#ve(e,t=`spinner`){this.#Ie(),this.#j=!1,this.#N={kind:`idle`},this.#P=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#de={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Je(),this.#pt()}#ye(e){this.#pe=void 0,this.#Me();let t=this.#de;if(t!==void 0){if(this.#de=void 0,this.#Xe(),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.#Ze({kind:`flow`,title:`info`,body:e.join(`
|
|
3
|
-
`),live:!1}),this.#Ze({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#pt()}}async#be(e){let t=this.#Ee(),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.#pt()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#pt();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.#pt())}},u=e.notices;if(e.kind===`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.#bt()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#pt(),await this.#ke((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.#pt();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.#pt();return;case`update`:o=d.select,s=void 0,this.#pt();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.#pt();return;case`ignore`:return}}).promise}#xe(e){this.#Ie();let t=this.#De();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#pt();let r=this.#ke((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.#pt();return;case`repaint`:this.#pt();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#Se(e){let t=this.#Ee(),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.#R,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.#Ge():(i=lineOf(``),this.#Ke())};return syncEditableRow(),this.#pt(),await this.#ke((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#qe(),this.#pt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#pt()},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.#pt();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.#pt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ke()).promise}async#Ce(e){let t=this.#Ee(),n=initialProviderPickerState(e.options,e.initialValue),r;t.question=t=>renderSelectQuestion({kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#R,editor:{kind:`key`,phase:n.phase}}},this.#r,t);let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#Ge():this.#Ke()};return syncCaret(),this.#pt(),await this.#ke((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.#pt();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#pt();return;case`validate`:{n=o.state,syncCaret(),this.#pt();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.#pt();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.#qe(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Ke()}).promise}async#we(e){let t=this.#Ee(),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.#R)},this.#Ge(),this.#pt(),await this.#ke((t,i)=>{let apply=e=>{n=e,r=void 0,this.#qe(),this.#pt()},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.#pt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#pt();return}i(t);return}default:return}},()=>this.#Ke()).promise}async#Te(e){let t=this.#Ee();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#pt(),await this.#ke((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#pt();return;default:return}}).promise}#Ee(){return this.#Ie(),this.#j=!1,this.#N={kind:`idle`},this.#P=``,this.#De()}#De(){return this.#de===void 0&&(this.#de={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[]}),this.#de}#Oe(){this.#de!==void 0&&(this.#de.question=void 0,this.#de.hideLinesWhileQuestion=!1),this.#W=void 0,this.#ze(),this.#je(),this.#pt()}#ke(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Oe(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Oe(),i(e))};return this.#W=t=>e(t,settle,reject),this.#Re(),{promise:a,settle}}#Ae(){let e,t=new Promise(t=>{e=t});return this.#pe=e,this.#je(),{promise:t,dispose:()=>{this.#pe===e&&(this.#pe=void 0,this.#Me())}}}#je(){if(this.#pe===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#pe;this.#pe=void 0,this.#Me(),e?.();return}e.type===`ctrl-r`&&this.#pt()};this.#me=consumer,this.#W=consumer,this.#Re()}#Me(){this.#me!==void 0&&(this.#W===this.#me&&this.#ze(),this.#me=void 0)}#Ne(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#de!==void 0){this.#de.status=t,t===void 0&&(this.#de.preview=void 0),this.#pt();return}if(t===void 0){this.#N={kind:`idle`},this.#P=``,this.#Xe(),this.#pt();return}this.#Ie(),this.#Ye(),this.#P=t,this.#pt()}#Pe(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#de;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.#pt();return}this.#Ie(),this.#Ze({kind:`flow`,title:t,body:n,live:!1}),this.#pt()}#Fe(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#de;if(n===void 0){this.#Pe(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#pt()}shutdown(){this.#Le()}#Ie(e){this.#F=e?.title??this.#F,this.#ee=e?.contextSize??this.#l,!this.#I&&(this.#I=!0,this.#n.reset(),this.#n.hideCursor(),this.#kt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#J=()=>this.#pt(),this.#t.on(`resize`,this.#J))}#Le(){this.#ze(),this.#Ke(),this.#Xe(),this.#H!==void 0&&(clearTimeout(this.#H),this.#H=void 0),this.#U=!1,this.#I&&=(this.#Lt(),this.#pt(),this.#n.clear(),this.#n.showCursor(),this.#At(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#J&&=(this.#t.off(`resize`,this.#J),void 0),!1)}#Re(){this.#e.off(`data`,this.#Be),this.#e.on(`data`,this.#Be)}#ze(){this.#e.off(`data`,this.#Be),this.#Ue(),this.#G=``,this.#K=new StringDecoder(`utf8`),this.#W=void 0}#Be=e=>{this.#Ue(),this.#G+=this.#K.write(e),this.#He(),this.#Ve()};#Ve(){if(this.#G===`\x1B`){this.#q=setTimeout(()=>{this.#G===`\x1B`&&(this.#G=``,this.#W?.({type:`escape`}))},30),this.#q.unref?.();return}if(isIncompletePaste(this.#G)){let e=this.#G;this.#q=setTimeout(()=>{if(this.#G!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#G=``,t.length>0&&this.#W?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#q.unref?.()}}#He(){for(;this.#G.length>0;){let e=nextKey(this.#G);if(e.incomplete)return;this.#G=this.#G.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#W?.(e.key)}}#Ue(){this.#q&&=(clearTimeout(this.#q),void 0)}#We(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#pt();break;case`ctrl-c`:this.#L||(this.#L=!0,this.#N={kind:`idle`},this.#P=`Interrupted`,this.#Y?.(),this.#pt());break;default:break}}#Ge(){this.#Ke(),this.#qe(),this.#B=setInterval(()=>{this.#R=!this.#R,this.#pt()},500),this.#B.unref?.()}#Ke(){this.#B&&=(clearInterval(this.#B),void 0),this.#R=!0}#qe(){this.#R=!0}#Je(){this.#Xe(),this.#V=setInterval(()=>{this.#z+=1,this.#pt()},90),this.#V.unref?.()}#Ye(){this.#N={kind:`waiting`,startedAtMs:Date.now()},this.#Je()}#Xe(){this.#V&&=(clearInterval(this.#V),void 0)}#Ze(e){e.id!==this.#ce?.id&&this.#Lt(),this.#p.push(e),e.id&&this.#m.set(e.id,e)}#Qe(e){this.#Ze({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#pt()}#$e(e){if(e!=null){if(this.#ue===e){this.#ue=void 0;return}this.#Ze({kind:`user`,body:stripTerminalControls(e),live:!1})}}#et(e,t,n){let r={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};n!==void 0&&(r.detail=stripTerminalControls(n)),this.#Ze(r),this.#pt()}#tt(e,t){this.#y.has(e)||(this.#y.add(e),this.#Ze({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#nt(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);return}this.#Ze(e)}#rt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#it(){for(let e of this.#p)e.status===`approval`||e.status===`running`||(e.live=!1)}#at(e,t,n){switch(e.type){case`step-start`:this.#ot(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#ft(e.usage),this.#pt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);this.#st(t),this.#ot(STATUS.streaming),n.text.set(e.id,t),this.#ct(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;this.#st(r),n.text.set(e.id,r),this.#ct(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);this.#st(r),this.#ot(STATUS.streaming),n.reasoning.set(e.id,r),this.#lt(e.id,r,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#st(r),this.#lt(e.id,r,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#ot(STATUS.executingTools),this.#ut({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.#ut({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#dt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#ot(STATUS.toolResults),this.#ut({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{if(t.tools===`hidden`)break;let r=this.#dt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#ot(STATUS.toolResults),this.#ut({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#et(`Error`,e.errorText,e.detail);break;case`finish`:this.#ft(e.usage),this.#pt();break}}#ot(e){let t=this.#T>0?STATUS.connectionAuth:e;this.#P!==t&&(this.#P=t,this.#pt())}#st(e){e.trim().length>0&&(this.#N={kind:`answering`})}#ct(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#nt({id:e,kind:`assistant`,body:r,live:n}),this.#pt())}#lt(e,t,n,r){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#nt({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#pt())}#ut(e,t,n){if(n.tools.set(e.toolCallId,e),this.#_.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#v.set(e.toolCallId,r),this.#nt(renderNativeToolBlock(e,r,t.tools===`full`)),this.#pt()}#dt(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.title??`tool`}}#ft(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#Q=(t??0)+(n??0)),this.#$=t??this.#$,this.#te=n??this.#te,this.#te!=null&&this.#re!==void 0){let e=(Date.now()-this.#re)/1e3;e>0&&(this.#ne=this.#te/e)}}#pt(){if(this.#I){if(this.#X){this.#Z=!0;return}this.#X=!0;try{do this.#Z=!1,this.#mt();while(this.#Z)}finally{this.#X=!1}}}#mt(){if(!this.#I)return;let e=this.#Dt(),t=this.#Ct(e),n=Math.max(1,this.#Ot()-t.length),r=[],i=this.#w;for(;this.#p.length>0&&this.#p[0].live===!1;){let t=this.#p.shift();if(this.#g.push(t),t.id&&(this.#h.add(t.id),this.#m.delete(t.id)),this.#zt(t))continue;let n=this.#yt(t,e,i);i=previousBlockOf(t),this.#w=i,r.push(...n),this.#C.push(...n)}let a=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#yt(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)a.push({block:t,row:n[e]})}let o=[...clipLiveRows(a.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,o):this.#n.update(o)}#ht(){if(!this.#I)return;let e=this.#Dt(),t=this.#Ct(e),n=Math.max(1,this.#Ot()-t.length),r=this.#w,i=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#yt(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.#vt(),...this.#C],a)}logDisplayMode(){return this.#f}setLogDisplayMode(e){e!==this.#f&&(this.#f=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#_t(),this.#I&&this.#ht())}flushDelayedDevBuildErrors(){let e=this.#se;e!==void 0&&(this.#se=void 0,this.#Ze({kind:`log`,title:`stderr`,body:e,live:!1}),this.#pt())}#gt(){this.#U=!0,this.#H!==void 0&&clearTimeout(this.#H),this.#H=setTimeout(()=>{this.#U=!1,this.#H=void 0,this.#pt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#f)),this.#pt()}#_t(){let e=this.#Dt();this.#C.length=0;let t;for(let n of this.#g){if(this.#zt(n))continue;let r=this.#yt(n,e,t);t=previousBlockOf(n),this.#C.push(...r)}this.#w=t}#vt(){let e=this.#b;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#Dt()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#yt(e,t,n){let r={spinner:this.#bt()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#bt(){return this.#r.spinner[this.#z%this.#r.spinner.length]??``}#xt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#St(e){return e.indicator.kind===`spinner`?{glyph:this.#bt(),color:`yellow`}:{glyph:this.#xt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:`green`}}#Ct(e){let t=this.#r.colors,n=[``],r=this.#de;if(r!==void 0){let t=this.#St(r),i;if(r.question!==void 0){let n=r.question(e);i={kind:`question`,rows:n},r.status!==void 0&&(i={kind:`question`,rows:n,status:{text:r.status,indicator:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(i={kind:`status`,status:{text:r.status,indicator:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,indicator:t},preview:r.preview}));let a={title:r.title,lines:r.hideLinesWhileQuestion===!0?[]:r.lines,content:i};return n.push(...renderFlowPanel(a,this.#r,e)),this.#Tt(n,e),n}if(this.#fe!==void 0&&n.push(...renderAttentionRows(this.#fe,e,this.#r),``),this.#j){let r=this.#M===void 0?void 0:inlineCommandHint(this.#M);r===void 0&&this.#M!==void 0&&isTypeaheadOpen(this.#M)&&n.push(...renderCommandSuggestions(this.#M,this.#r,e));let i=isPromptControlCommand(this.#O),a=r?t.dim(` ${r}`):``,o=[];this.#wt(o,e);let s=Math.max(1,this.#Ot()-1-n.length-1-o.length);return n.push(...promptInputRows({text:this.#O,cursor:this.#k,width:e,theme:this.#r,caretVisible:this.#R,isCommand:i,ghost:a,maxRows:s})),n.push(...o),n}let i=this.#N;if(i.kind===`answering`)return this.#wt(n,e),n;let a=i.kind===`waiting`,o=a?t.green(this.#xt(i.startedAtMs,this.#r.unicode?`⊙`:`o`)):t.dim(this.#r.glyph.dot),s=this.#P.length>0?this.#P:`Ready`,c=a?t.dim(s):s,u=this.#Et(),f=a?` `:``,p=u?`${f}${o} ${c} ${t.dim(this.#r.glyph.dot)} ${u}`:`${f}${o} ${c}`;n.push(clip(p,e));let g=[];return this.#wt(g,e),a&&g.length>0&&n.push(``),n.push(...g),n}#wt(e,t){let n=this.#D===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#r,width:r};this.#U&&(i.logLevel=this.#f);let a=this.#b?.info?.agent.model.id;a!==void 0&&(i.model=a);let o=this.#b?.info?.agent.model.endpoint;o!==void 0&&(i.endpoint=o);let s=this.#$??0,c=this.#te??0;if(s>0||c>0){let e={inputTokens:s,outputTokens:c};this.#ee!==void 0&&(e.contextSize=this.#ee),i.tokens=formatTokenFlow(e,this.#r.glyph)}this.#E!==void 0&&(i.vercel=this.#E),this.#D!==void 0&&(i.remote=this.#D);let l=buildStatusLine(i);l!==void 0&&e.push(clip(`${n}${l}`,t))}#Tt(e,t){if(this.#D===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#D,theme:this.#r,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Et(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Q,outputTokens:this.#te,tokensPerSecond:this.#ne},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#Dt(){return Math.max(20,this.#t.columns||80)}#Ot(){return Math.max(8,this.#t.rows||24)}#kt(){if(this.#ie!==void 0||!this.#u)return;this.#ae=``,this.#oe=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#jt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ie=()=>{e(),t()}}#At(){let e=this.#ie;e!==void 0&&(this.#ie=void 0,e(),this.#ae.length>0&&(this.#Rt(`stdout`)&&process.stdout.write(`${this.#ae}\n`),this.#ae=``),this.#oe.length>0&&(this.#Rt(`stderr`)&&process.stderr.write(`${this.#oe}\n`),this.#oe=``))}#jt(e,t){let n=(e===`stdout`?this.#ae:this.#oe)+t,i=n.lastIndexOf(`
|
|
3
|
+
`),live:!1}),this.#Ze({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#pt()}}async#be(e){let t=this.#Ee(),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.#pt()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#pt();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.#pt())}},u=e.notices;if(e.kind===`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.#bt()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#pt(),await this.#ke((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.#pt();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.#pt();return;case`update`:o=d.select,s=void 0,this.#pt();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.#pt();return;case`ignore`:return}}).promise}#xe(e){this.#Ie();let t=this.#De();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#pt();let r=this.#ke((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.#pt();return;case`repaint`:this.#pt();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#Se(e){let t=this.#Ee(),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.#R,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.#Ge():(i=lineOf(``),this.#Ke())};return syncEditableRow(),this.#pt(),await this.#ke((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#qe(),this.#pt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#pt()},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.#pt();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.#pt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ke()).promise}async#Ce(e){let t=this.#Ee(),n=initialProviderPickerState(e.options,e.initialValue),r;t.question=t=>renderSelectQuestion({kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#R,editor:{kind:`key`,phase:n.phase}}},this.#r,t);let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#Ge():this.#Ke()};return syncCaret(),this.#pt(),await this.#ke((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.#pt();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#pt();return;case`validate`:{n=o.state,syncCaret(),this.#pt();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.#pt();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.#qe(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Ke()}).promise}async#we(e){let t=this.#Ee(),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.#R)},this.#Ge(),this.#pt(),await this.#ke((t,i)=>{let apply=e=>{n=e,r=void 0,this.#qe(),this.#pt()},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.#pt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#pt();return}i(t);return}default:return}},()=>this.#Ke()).promise}async#Te(e){let t=this.#Ee();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#pt(),await this.#ke((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#pt();return;default:return}}).promise}#Ee(){return this.#Ie(),this.#j=!1,this.#N={kind:`idle`},this.#P=``,this.#De()}#De(){return this.#de===void 0&&(this.#de={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[]}),this.#de}#Oe(){this.#de!==void 0&&(this.#de.question=void 0,this.#de.hideLinesWhileQuestion=!1),this.#W=void 0,this.#ze(),this.#je(),this.#pt()}#ke(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Oe(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Oe(),i(e))};return this.#W=t=>e(t,settle,reject),this.#Re(),{promise:a,settle}}#Ae(){let e,t=new Promise(t=>{e=t});return this.#pe=e,this.#je(),{promise:t,dispose:()=>{this.#pe===e&&(this.#pe=void 0,this.#Me())}}}#je(){if(this.#pe===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#pe;this.#pe=void 0,this.#Me(),e?.();return}e.type===`ctrl-r`&&this.#pt()};this.#me=consumer,this.#W=consumer,this.#Re()}#Me(){this.#me!==void 0&&(this.#W===this.#me&&this.#ze(),this.#me=void 0)}#Ne(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#de!==void 0){this.#de.status=t,t===void 0&&(this.#de.preview=void 0),this.#pt();return}if(t===void 0){this.#N={kind:`idle`},this.#P=``,this.#Xe(),this.#pt();return}this.#Ie(),this.#Ye(),this.#P=t,this.#pt()}#Pe(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#de;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.#pt();return}this.#Ie(),this.#Ze({kind:`flow`,title:t,body:n,live:!1}),this.#pt()}#Fe(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#de;if(n===void 0){this.#Pe(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#pt()}shutdown(){this.#Le()}#Ie(e){this.#F=e?.title??this.#F,this.#ee=e?.contextSize??this.#l,!this.#I&&(this.#I=!0,this.#n.reset(),this.#n.hideCursor(),this.#kt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#J=()=>this.#pt(),this.#t.on(`resize`,this.#J))}#Le(){this.#ze(),this.#Ke(),this.#Xe(),this.#H!==void 0&&(clearTimeout(this.#H),this.#H=void 0),this.#U=!1,this.#I&&=(this.#Lt(),this.#pt(),this.#n.clear(),this.#n.showCursor(),this.#At(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#J&&=(this.#t.off(`resize`,this.#J),void 0),!1)}#Re(){this.#e.off(`data`,this.#Be),this.#e.on(`data`,this.#Be)}#ze(){this.#e.off(`data`,this.#Be),this.#Ue(),this.#G=``,this.#K=new StringDecoder(`utf8`),this.#W=void 0}#Be=e=>{this.#Ue(),this.#G+=this.#K.write(e),this.#He(),this.#Ve()};#Ve(){if(this.#G===`\x1B`){this.#q=setTimeout(()=>{this.#G===`\x1B`&&(this.#G=``,this.#W?.({type:`escape`}))},30),this.#q.unref?.();return}if(isIncompletePaste(this.#G)){let e=this.#G;this.#q=setTimeout(()=>{if(this.#G!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#G=``,t.length>0&&this.#W?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#q.unref?.()}}#He(){for(;this.#G.length>0;){let e=nextKey(this.#G);if(e.incomplete)return;this.#G=this.#G.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#W?.(e.key)}}#Ue(){this.#q&&=(clearTimeout(this.#q),void 0)}#We(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#pt();break;case`ctrl-c`:this.#L||(this.#L=!0,this.#N={kind:`idle`},this.#P=`Interrupted`,this.#Y?.(),this.#pt());break;default:break}}#Ge(){this.#Ke(),this.#qe(),this.#B=setInterval(()=>{this.#R=!this.#R,this.#pt()},500),this.#B.unref?.()}#Ke(){this.#B&&=(clearInterval(this.#B),void 0),this.#R=!0}#qe(){this.#R=!0}#Je(){this.#Xe(),this.#V=setInterval(()=>{this.#z+=1,this.#pt()},90),this.#V.unref?.()}#Ye(){this.#N={kind:`waiting`,startedAtMs:Date.now()},this.#Je()}#Xe(){this.#V&&=(clearInterval(this.#V),void 0)}#Ze(e){e.id!==this.#ce?.id&&this.#Lt(),this.#p.push(e),e.id&&this.#m.set(e.id,e)}#Qe(e){this.#Ze({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#pt()}#$e(e){if(e!=null){if(this.#ue===e){this.#ue=void 0;return}this.#Ze({kind:`user`,body:stripTerminalControls(e),live:!1})}}#et(e,t,n){let r={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};n!==void 0&&(r.detail=stripTerminalControls(n)),this.#Ze(r),this.#pt()}#tt(e,t){this.#y.has(e)||(this.#y.add(e),this.#Ze({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#nt(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);return}this.#Ze(e)}#rt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#it(){for(let e of this.#p)e.status===`approval`||e.status===`running`||(e.live=!1)}#at(e,t,n){switch(e.type){case`step-start`:this.#ot(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#ft(e.usage),this.#pt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);this.#st(t),this.#ot(STATUS.streaming),n.text.set(e.id,t),this.#ct(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;this.#st(r),n.text.set(e.id,r),this.#ct(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);this.#st(r),this.#ot(STATUS.streaming),n.reasoning.set(e.id,r),this.#lt(e.id,r,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#st(r),this.#lt(e.id,r,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#ot(STATUS.executingTools),this.#ut({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.#ut({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#dt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#ot(STATUS.toolResults),this.#ut({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{if(t.tools===`hidden`)break;let r=this.#dt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#ot(STATUS.toolResults),this.#ut({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#et(`Error`,e.errorText,e.detail);break;case`finish`:this.#ft(e.usage),this.#pt();break}}#ot(e){let t=this.#T>0?STATUS.connectionAuth:e;this.#P!==t&&(this.#P=t,this.#pt())}#st(e){e.trim().length>0&&(this.#N={kind:`answering`})}#ct(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#nt({id:e,kind:`assistant`,body:r,live:n}),this.#pt())}#lt(e,t,n,r){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#nt({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#pt())}#ut(e,t,n){if(n.tools.set(e.toolCallId,e),this.#_.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#v.set(e.toolCallId,r),this.#nt(renderNativeToolBlock(e,r,t.tools===`full`)),this.#pt()}#dt(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.title??`tool`}}#ft(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#Q=(t??0)+(n??0)),this.#$=t??this.#$,this.#te=n??this.#te,this.#te!=null&&this.#re!==void 0){let e=(Date.now()-this.#re)/1e3;e>0&&(this.#ne=this.#te/e)}}#pt(){if(this.#I){if(this.#X){this.#Z=!0;return}this.#X=!0;try{do this.#Z=!1,this.#mt();while(this.#Z)}finally{this.#X=!1}}}#mt(){if(!this.#I)return;let e=this.#Dt(),t=this.#Ct(e),n=Math.max(1,this.#Ot()-t.length),r=[],i=this.#w;for(;this.#p.length>0&&this.#p[0].live===!1;){let t=this.#p.shift();if(this.#g.push(t),t.id&&(this.#h.add(t.id),this.#m.delete(t.id)),this.#zt(t))continue;let n=this.#yt(t,e,i);i=previousBlockOf(t),this.#w=i,r.push(...n),this.#C.push(...n)}let a=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#yt(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)a.push({block:t,row:n[e]})}let o=[...clipLiveRows(a.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,o):this.#n.update(o)}#ht(){if(!this.#I)return;let e=this.#Dt(),t=this.#Ct(e),n=Math.max(1,this.#Ot()-t.length),r=this.#w,i=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#yt(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.#vt(),...this.#C],a)}logDisplayMode(){return this.#f}setLogDisplayMode(e){e!==this.#f&&(this.#f=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#_t(),this.#I&&this.#ht())}flushDelayedDevBuildErrors(){let e=this.#se;e!==void 0&&(this.#se=void 0,this.#Ze({kind:`log`,title:`stderr`,body:e,live:!1}),this.#pt())}#gt(){this.#U=!0,this.#H!==void 0&&clearTimeout(this.#H),this.#H=setTimeout(()=>{this.#U=!1,this.#H=void 0,this.#pt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#f)),this.#pt()}#_t(){let e=this.#Dt();this.#C.length=0;let t;for(let n of this.#g){if(this.#zt(n))continue;let r=this.#yt(n,e,t);t=previousBlockOf(n),this.#C.push(...r)}this.#w=t}#vt(){let e=this.#b;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#Dt()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#yt(e,t,n){let r={spinner:this.#bt()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#bt(){return this.#r.spinner[this.#z%this.#r.spinner.length]??``}#xt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#St(e){return e.indicator.kind===`spinner`?{glyph:this.#bt(),color:`yellow`}:{glyph:this.#xt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:`green`}}#Ct(e){let t=this.#r.colors,n=[``],r=this.#de;if(r!==void 0){let t=this.#St(r),i;if(r.question!==void 0){let n=r.question(e);i={kind:`question`,rows:n},r.status!==void 0&&(i={kind:`question`,rows:n,status:{text:r.status,indicator:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(i={kind:`status`,status:{text:r.status,indicator:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,indicator:t},preview:r.preview}));let a={title:r.title,lines:r.hideLinesWhileQuestion===!0?[]:r.lines,content:i};return n.push(...renderFlowPanel(a,this.#r,e)),this.#Tt(n,e),n}if(this.#fe!==void 0&&n.push(...renderAttentionRows(this.#fe,e,this.#r),``),this.#j){let r=this.#M===void 0?void 0:inlineCommandHint(this.#M);r===void 0&&this.#M!==void 0&&isTypeaheadOpen(this.#M)&&n.push(...renderCommandSuggestions(this.#M,this.#r,e));let i=isPromptControlCommand(this.#O),a=r?t.dim(` ${r}`):``,o=[];this.#wt(o,e);let s=Math.max(1,this.#Ot()-1-n.length-1-o.length);return n.push(...promptInputRows({text:this.#O,cursor:this.#k,width:e,theme:this.#r,caretVisible:this.#R,isCommand:i,ghost:a,maxRows:s})),n.push(...o),n}let i=this.#N;if(i.kind===`answering`)return this.#wt(n,e),n;let a=i.kind===`waiting`,o=a?t.green(this.#xt(i.startedAtMs,this.#r.unicode?`⊙`:`o`)):t.dim(this.#r.glyph.dot),s=this.#P.length>0?this.#P:`Ready`,c=a?t.dim(s):s,u=this.#Et(),f=a?` `:``,p=u?`${f}${o} ${c} ${t.dim(this.#r.glyph.dot)} ${u}`:`${f}${o} ${c}`;n.push(clip(p,e));let g=[];return this.#wt(g,e),a&&g.length>0&&n.push(``),n.push(...g),n}#wt(e,t){let n=this.#D===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#r,width:r};this.#U&&(i.logLevel=this.#f);let a=this.#b?.serverUrl;if(a!==void 0&&this.#D===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#b?.info?.agent.model.id;o!==void 0&&(i.model=o);let s=this.#b?.info?.agent.model.endpoint;s!==void 0&&(i.endpoint=s);let c=this.#$??0,l=this.#te??0;if(c>0||l>0){let e={inputTokens:c,outputTokens:l};this.#ee!==void 0&&(e.contextSize=this.#ee),i.tokens=formatTokenFlow(e,this.#r.glyph)}this.#E!==void 0&&(i.vercel=this.#E),this.#D!==void 0&&(i.remote=this.#D);let u=buildStatusLine(i);u!==void 0&&e.push(clip(`${n}${u}`,t))}#Tt(e,t){if(this.#D===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#D,theme:this.#r,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Et(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Q,outputTokens:this.#te,tokensPerSecond:this.#ne},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#Dt(){return Math.max(20,this.#t.columns||80)}#Ot(){return Math.max(8,this.#t.rows||24)}#kt(){if(this.#ie!==void 0||!this.#u)return;this.#ae=``,this.#oe=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#jt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ie=()=>{e(),t()}}#At(){let e=this.#ie;e!==void 0&&(this.#ie=void 0,e(),this.#ae.length>0&&(this.#Rt(`stdout`)&&process.stdout.write(`${this.#ae}\n`),this.#ae=``),this.#oe.length>0&&(this.#Rt(`stderr`)&&process.stderr.write(`${this.#oe}\n`),this.#oe=``))}#jt(e,t){let n=(e===`stdout`?this.#ae:this.#oe)+t,i=n.lastIndexOf(`
|
|
4
4
|
`),a=i===-1?n:n.slice(i+1);if(e===`stdout`?this.#ae=a:this.#oe=a,i===-1)return;let o=stripAnsi(n.slice(0,i)).replace(/\s+$/u,``);o.trim().length!==0&&(e===`stdout`?this.#Mt(o):this.#Nt(o),this.#pt())}#Mt(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
|
|
5
5
|
`);t=[],e.trim().length!==0&&this.#Ze({kind:`log`,title:`stdout`,body:e,live:!1})};for(let n of e.split(`
|
|
6
6
|
`)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#Ze({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#Ft(r,n.trimEnd())}flushPending()}#Nt(e){let t=e.split(`
|
|
@@ -36,11 +36,11 @@ export interface VercelStatusTrackerOptions {
|
|
|
36
36
|
* which hides the segment.
|
|
37
37
|
*/
|
|
38
38
|
export interface VercelStatusTracker {
|
|
39
|
-
/** Fire-and-forget identity re-probe;
|
|
39
|
+
/** Fire-and-forget identity re-probe; superseded probes are aborted. */
|
|
40
40
|
refreshIdentity(): void;
|
|
41
41
|
applyEffect(effect: VercelStatusEffect): void;
|
|
42
42
|
current(): VercelStatusSnapshot;
|
|
43
|
-
/** Stops future
|
|
43
|
+
/** Stops future changes and aborts the in-flight identity probe. */
|
|
44
44
|
dispose(): void;
|
|
45
45
|
}
|
|
46
46
|
/** Creates the {@link VercelStatusTracker} for one dev TUI session. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{detectProjectIdentity}from"#setup/project-resolution.js";function createVercelStatusTracker(t){let n=t.detectIdentity??detectProjectIdentity,r,i=!1,a=0,o=!1,snapshot=()=>{let e={pendingDeploy:i};return r!==void 0&&(e.identity=r),e},emit=()=>{o||t.onChange(snapshot())},refreshIdentity=()=>{a+=1;let
|
|
1
|
+
import{detectProjectIdentity}from"#setup/project-resolution.js";function createVercelStatusTracker(t){let n=t.detectIdentity??detectProjectIdentity,r,i=!1,a=0,o=!1,s,snapshot=()=>{let e={pendingDeploy:i};return r!==void 0&&(e.identity=r),e},emit=()=>{o||t.onChange(snapshot())},refreshIdentity=()=>{if(o)return;s?.abort();let e=new AbortController;s=e,a+=1;let i=a;(async()=>{let c;try{c=await n(t.appRoot,{signal:e.signal})}catch{return}finally{s===e&&(s=void 0)}o||i!==a||(r=c,emit())})()};return{refreshIdentity,applyEffect(e){if(!o)switch(e.kind){case`channels-added`:i=!0,emit();return;case`deployed`:i=!1,emit(),refreshIdentity();return;case`refresh-identity`:refreshIdentity();return}},current:snapshot,dispose(){o||(o=!0,a+=1,s?.abort(),s=void 0)}}}export{createVercelStatusTracker};
|
package/dist/src/cli/run.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { RunDevelopmentTuiInput } from "#cli/dev/tui/tui.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { DevelopmentServer, DevelopmentServerOptions, ProductionServerHandle } from "#internal/nitro/host/types.js";
|
|
3
3
|
import type { AssistantResponseStatsMode, LogDisplayMode, TerminalPartDisplayMode, TuiDisplayOptions } from "#cli/dev/tui/types.js";
|
|
4
4
|
interface CliLogger {
|
|
5
5
|
error(message: string): void;
|
|
@@ -28,7 +28,7 @@ interface CliRuntimeDependencies {
|
|
|
28
28
|
}): Promise<void>;
|
|
29
29
|
runDevelopmentTui(input: RunDevelopmentTuiInput): Promise<void>;
|
|
30
30
|
runEvalCommand(evalIds: readonly string[], options: EvalCliOptions, logger: CliLogger): Promise<void>;
|
|
31
|
-
startHost(appRoot: string, options?: DevelopmentServerOptions):
|
|
31
|
+
startHost(appRoot: string, options?: DevelopmentServerOptions): DevelopmentServer;
|
|
32
32
|
startProductionHost(appRoot: string, options?: {
|
|
33
33
|
host?: string;
|
|
34
34
|
port?: number;
|
package/dist/src/cli/run.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{isCodingAgentLaunch}from"#cli/agent-detection.js";import{eveCliBanner}from"#cli/banner.js";import{startCliLiveRow}from"#cli/ui/live-row.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{Command,CommanderError,InvalidArgumentError}from"#compiled/commander/index.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{registerProjectCommands}from"#cli/commands/register-project-commands.js";import{LOG_DISPLAY_MODES,parseLogDisplayMode}from"#cli/dev/tui/log-display-mode.js";import{resolveTuiTitle}from"#cli/dev/tui/target.js";import{parseDevelopmentServerUrl}from"#cli/dev/url.js";const devBootLog=createLogger(`dev.boot`);function createDevBootProgressReporter(e){return t=>{switch(t.type){case`phase-started`:e?.update(`Building your agent`,t.phase),devBootLog.debug(t.phase);return;case`phase-finished`:devBootLog.debug(`${t.phase} finished`,{ms:t.elapsedMs});return;case`before-first-paint`:e?.stop();return;default:return t}}}async function loadBuildHost(){return(await import(`#internal/nitro/host.js`)).buildApplication}async function loadPrintApplicationInfo(){return(await import(`#cli/commands/info.js`)).printApplicationInfo}async function loadRunDevelopmentTui(){return(await import(`#cli/dev/tui/tui.js`)).runDevelopmentTui}async function loadRunEvalCommand(){return(await import(`#evals/cli/eval.js`)).runEvalCommand}async function loadStartHost(){return(await import(`#internal/nitro/host.js`)).
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{isCodingAgentLaunch}from"#cli/agent-detection.js";import{eveCliBanner}from"#cli/banner.js";import{startCliLiveRow}from"#cli/ui/live-row.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{Command,CommanderError,InvalidArgumentError}from"#compiled/commander/index.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{registerProjectCommands}from"#cli/commands/register-project-commands.js";import{LOG_DISPLAY_MODES,parseLogDisplayMode}from"#cli/dev/tui/log-display-mode.js";import{resolveTuiTitle}from"#cli/dev/tui/target.js";import{parseDevelopmentServerUrl}from"#cli/dev/url.js";const devBootLog=createLogger(`dev.boot`);function createDevBootProgressReporter(e){return t=>{switch(t.type){case`phase-started`:e?.update(`Building your agent`,t.phase),devBootLog.debug(t.phase);return;case`phase-finished`:devBootLog.debug(`${t.phase} finished`,{ms:t.elapsedMs});return;case`before-first-paint`:e?.stop();return;default:return t}}}async function loadBuildHost(){return(await import(`#internal/nitro/host.js`)).buildApplication}async function loadPrintApplicationInfo(){return(await import(`#cli/commands/info.js`)).printApplicationInfo}async function loadRunDevelopmentTui(){return(await import(`#cli/dev/tui/tui.js`)).runDevelopmentTui}async function loadRunEvalCommand(){return(await import(`#evals/cli/eval.js`)).runEvalCommand}async function loadStartHost(){return(await import(`#internal/nitro/host.js`)).createDevelopmentServer}async function loadStartProductionHost(){return(await import(`#internal/nitro/host.js`)).startProductionServer}function shouldPrintCliBootBanner(e){return e.name()===`info`||e.name()===`dev`||e.name()===`init`}async function waitForShutdownSignal(e){await new Promise((t,n)=>{let r=!1,cleanup=()=>{process.off(`SIGINT`,handleSignal),process.off(`SIGTERM`,handleSignal)},handleSignal=()=>{r||(r=!0,cleanup(),e.close().then(t,n))};process.once(`SIGINT`,handleSignal),process.once(`SIGTERM`,handleSignal)})}async function waitForProductionServer(e){await Promise.race([e.wait(),waitForShutdownSignal({close:()=>e.close()})])}function parsePortOption(e){if(!/^-?\d+$/.test(e))throw new InvalidArgumentError(`Expected a numeric port, received "${e}".`);let t=Number(e);if(t<0||t>65535)throw new InvalidArgumentError(`Expected a port between 0 and 65535, received "${e}".`);return t}const DISPLAY_MODES=new Set([`full`,`collapsed`,`auto-collapsed`,`hidden`]),STATS_MODES=new Set([`tokens`,`tokensPerSecond`]);function parseDisplayMode(e){if(!DISPLAY_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...DISPLAY_MODES].join(`, `)}, received "${e}".`);return e}function parseStatsMode(e){if(!STATS_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...STATS_MODES].join(`, `)}, received "${e}".`);return e}function parseLogsMode(e){let t=parseLogDisplayMode(e);if(t===void 0)throw new InvalidArgumentError(`Expected one of ${LOG_DISPLAY_MODES.join(`, `)}, received "${e}".`);return t}function parseContextSizeOption(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new InvalidArgumentError(`Expected a positive number, received "${e}".`);return t}function resolveDevUiMode(e){return e.options.ui===!1||!e.interactive?`headless`:`tui`}function resolveTuiDisplayOptions(e){let t={logs:e.logs??`stderr`,reasoning:e.reasoning??`full`,tools:e.tools??`auto-collapsed`};return e.subagents!==void 0&&(t.subagents=e.subagents),e.connectionAuth!==void 0&&(t.connectionAuth=e.connectionAuth),e.assistantResponseStats!==void 0&&(t.assistantResponseStats=e.assistantResponseStats),e.contextSize!==void 0&&(t.contextSize=e.contextSize),t}function hasInteractiveTerminal(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function rewriteDevelopmentUrlShorthand(e){let t=e[1];return e[0]!==`dev`||e.length!==2||t===void 0||t.startsWith(`-`)?[...e]:[`dev`,`--url`,t]}function resolveRemoteDevelopmentServerUrl(e){if(e.url){if(e.host!==void 0)throw new InvalidArgumentError(`The --host option cannot be used with --url.`);if(e.port!==void 0)throw new InvalidArgumentError(`The --port option cannot be used with --url.`);if(e.ui===!1)throw new InvalidArgumentError(`The --no-ui option cannot be used with --url.`);return e.url}}function createCliProgram(e,i){let c=resolveApplicationRoot(),f=resolveInstalledPackageInfo().version,p=new Command,m=createCliTheme();p.name(`eve`).description(`Build and run an eve application.`).version(f).showHelpAfterError().exitOverride().hook(`preAction`,(t,n)=>{shouldPrintCliBootBanner(n)&&e.log(eveCliBanner())}).configureOutput({writeErr:t=>{e.error(t.trimEnd())},writeOut:t=>{e.log(t.trimEnd())}});let h=p.command(`channels`).description(`Manage user-authored channels in the current project.`);return h.command(`add [kind]`).description(`Add channels interactively, or scaffold a channel kind (slack | web).`).option(`-f, --force`,`Overwrite existing channel files`).option(`-y, --yes`,`Assume yes for confirmations; requires an explicit channel kind`).action(async(t,n)=>{let{runChannelsAddCommand:r}=await import(`#cli/commands/channels.js`);await r(e,c,{kind:t,options:n})}),h.command(`list`).description(`List user-authored channels in the current project.`).option(`--json`,`Output as JSON`).action(async t=>{let{runChannelsListCommand:n}=await import(`#cli/commands/channels.js`);await n(e,c,t)}),p.command(`init [target]`).description(`Create a new eve agent, or add one to an existing project directory.`).option(`--channel-web-nextjs`,`Add the Web Chat application (Next.js)`).option(`-y, --yes`,`Accepted for compatibility; has no effect`).action(async(t,n)=>{n.yes&&e.error(`warning: --yes has no effect for eve init.`);let{runInitCommand:r}=await import(`#cli/commands/init.js`);await r(e,c,t,{channelWebNextjs:n.channelWebNextjs})}),registerProjectCommands({program:p,logger:e,appRoot:c}),p.command(`build`).description(`Build the current eve application.`).action(async()=>{let{loadDevelopmentEnvironmentFiles:t}=await import(`#cli/dev/environment.js`);t(c);let n=await(i.buildHost??await loadBuildHost())(c);e.log(renderCliTaggedLine(m,{message:`built output at ${n}`,tag:`build`,tone:`success`}))}),p.command(`start`).description(`Start a built eve application.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,parsePortOption).action(async t=>{let{loadDevelopmentEnvironmentFiles:n}=await import(`#cli/dev/environment.js`);n(c);let a=await(i.startProductionHost??await loadStartProductionHost())(c,{host:t.host,port:t.port});e.log(renderCliTaggedLine(m,{message:`server listening at ${a.url}`,tag:`start`,tone:`success`})),await waitForProductionServer(a)}),p.command(`dev`).description(`Start the eve development server or connect to an existing URL.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 2000)`,parsePortOption).option(`-u, --url <url>`,`Connect to an existing server URL`,parseDevelopmentServerUrl).option(`--no-ui`,`Start the server without an interactive UI`).option(`--name <name>`,`Title shown in the terminal UI (defaults to the app folder name)`).option(`--input <text>`,`Pre-fill the prompt input after launching the UI`).option(`--tools <mode>`,`How tool calls render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--reasoning <mode>`,`How reasoning renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--subagents <mode>`,`How subagent sections render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--connection-auth <mode>`,`How connection authorization renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--assistant-response-stats <mode>`,`Assistant header statistic: tokens | tokensPerSecond`,parseStatsMode).option(`--context-size <tokens>`,`Model context window size, shown as a usage percentage`,parseContextSizeOption).option(`--logs <mode>`,`Which server/agent logs to show: all | stderr | sandbox | none`,parseLogsMode).addHelpText(`after`,`
|
|
2
2
|
You can also pass a bare URL as the only argument, for example: eve dev https://example.com
|
|
3
|
-
`).action(async t=>{let n=resolveRemoteDevelopmentServerUrl(t),a=hasInteractiveTerminal(),s=resolveDevUiMode({options:t,interactive:a});if(t.input!==void 0&&s===`headless`)throw new InvalidArgumentError(`--input requires the interactive UI.`);let
|
|
3
|
+
`).action(async t=>{let n=resolveRemoteDevelopmentServerUrl(t),a=hasInteractiveTerminal(),s=resolveDevUiMode({options:t,interactive:a});if(t.input!==void 0&&s===`headless`)throw new InvalidArgumentError(`--input requires the interactive UI.`);let runInteractiveUi=async(e,r)=>{let a=await devBootPhase(`loading interactive UI`,async()=>i.runDevelopmentTui??await loadRunDevelopmentTui(),r),o=resolveTuiDisplayOptions(t),s=n===void 0?{kind:`local`,serverUrl:e.serverUrl,workspaceRoot:e.appRoot??c}:{kind:`remote`,serverUrl:e.serverUrl,workspaceRoot:c},l=resolveTuiTitle({name:t.name,target:s});l!==void 0&&(o.name=l),await a({target:s,initialInput:t.input,onBootProgress:r,...o})};if(n){let{loadDevelopmentEnvironmentFiles:t}=await import(`#cli/dev/environment.js`);if(t(c),e.log(`↗ remote mode targeting ${m.info(new URL(n).host)}`),s===`headless`){e.log(renderCliTaggedLine(m,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`}));return}e.log(``),await runInteractiveUi({serverUrl:n});return}s===`tui`&&e.log(``);let u=s===`tui`?startCliLiveRow(e):void 0,d=createDevBootProgressReporter(u);u?.update(`Building your agent`);let f=!1,p,closeServer=async()=>{f||p===void 0||(f=!0,await p.close())};try{p=(i.startHost??await loadStartHost())(c,{existing:s===`tui`?`attach-if-unconfigured`:`reject`,host:t.host,onBootProgress:d,port:t.port});let n=await p.start();if(s!==`tui`&&e.log(renderCliTaggedLine(m,{message:`server listening at ${n.url}`,tag:`dev`,tone:`success`})),s===`headless`)return t.ui!==!1&&!a&&e.log(renderCliTaggedLine(m,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`})),await waitForShutdownSignal({close:closeServer});await runInteractiveUi({appRoot:n.appRoot,serverUrl:n.url},d)}finally{u?.stop(),await closeServer()}}),p.command(`info`).description(`Print resolved application information.`).option(`--json`,`Output as JSON`).action(async t=>{await(i.printApplicationInfo??await loadPrintApplicationInfo())(e,c,t)}),p.command(`eval`).description(`Run evals against an eve agent.`).argument(`[evalIds...]`,`Eval ids (or directory prefixes) to run (all discovered evals when omitted)`).option(`--url <url>`,`Remote agent URL (skip local host startup)`,parseDevelopmentServerUrl).option(`--tag <tag...>`,`Run only evals carrying a tag`).option(`--strict`,`Fail the exit code when any score falls below its threshold`).option(`--list`,`Print discovered evals without running them`).option(`--timeout <ms>`,`Per-eval timeout in milliseconds`).option(`--max-concurrency <n>`,`Max concurrent eval executions`).option(`--json`,`Output results as JSON`).option(`--junit <path>`,`Write JUnit XML results to a file`).option(`--skip-report`,`Skip eval-defined reporters (e.g. Braintrust)`).option(`--verbose`,`Stream per-eval t.log lines to stdout`).action(async(t,n)=>{await(i.runEvalCommand??await loadRunEvalCommand())(t,n,e)}),p}async function runCli(e=process.argv.slice(2),t=console,n={}){let r=createCliProgram(t,n),a=e.length===0?[`dev`]:rewriteDevelopmentUrlShorthand(e);try{await r.parseAsync(a,{from:`user`})}catch(e){if(e instanceof CommanderError){if(e.exitCode===0)return;let r=await(n.isCodingAgentLaunch??isCodingAgentLaunch)();if(a[0]===`init`&&r){let{initAgentInstructions:e}=await import(`#cli/commands/agent-instructions.js`);t.log(e())}throw Error(e.message)}throw e}}export{resolveDevUiMode,resolveTuiDisplayOptions,runCli};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{basename,join}from"node:path";import{readFile}from"node:fs/promises";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{
|
|
1
|
+
import{basename,join}from"node:path";import{readFile}from"node:fs/promises";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{createDevelopmentServer}from"#internal/nitro/host.js";import{createEvalClient}from"#evals/cli/eval-client.js";import{discoverAndImportEvals,discoverEvalConfig}from"#evals/runner/discover.js";import{runEvals}from"#evals/runner/run-evals.js";import{ConsoleReporter}from"#evals/runner/reporters/console.js";import{JUnit}from"#evals/runner/reporters/junit.js";import{resolveEvalTargetHandle}from"#evals/target.js";async function runEvalCommand(e,t,n){let o=resolveApplicationRoot();loadDevelopmentEnvironmentFiles(o);let s=e.length>0?e:void 0,c=await discoverAndImportEvals(o,s);if(c.length===0){s?n.error(`No evals found matching: ${s.join(`, `)}`):n.error(`No evals found. Create files under evals/ with the *.eval.ts extension.`),process.exitCode=2;return}let l=filterEvalsByTag(c,t.tag??[]);if(l.length===0){n.error(`No evals matched the provided tags (${(t.tag??[]).join(`, `)}).`),process.exitCode=2;return}let u,d;try{u=parsePositiveInteger(t.maxConcurrency,`--max-concurrency`),d=parseNonNegativeInteger(t.timeout,`--timeout`)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}if(t.list===!0){printEvalList(l,t.json===!0,n);return}let f;try{f=await discoverEvalConfig(o)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let p,m,h;try{if(t.url)h=await createEvalClient({kind:`remote`,url:t.url},{workspaceRoot:o}),m=await resolveEvalTargetHandle({client:h,expectedAgentName:await readExpectedAgentName(o),kind:`remote`,url:t.url});else{p=createDevelopmentServer(o,{host:`127.0.0.1`,port:0});let e=await p.start();h=await createEvalClient({kind:`local`,url:e.url}),m=await resolveEvalTargetHandle({client:h,expectedAgentName:await readExpectedAgentName(o),kind:`local`,url:e.url})}let e=t.json===!0?[]:[new ConsoleReporter];t.junit!==void 0&&e.push(JUnit({filePath:t.junit}));let r=await runEvals({evaluations:l,config:f,target:m,client:h,appRoot:o,reporters:e,includeEvalReporters:t.skipReport!==!0,maxConcurrency:u,timeoutMs:d,onEvalLog:t.verbose===!0?(e,t)=>n.log(`[${e}] ${t}`):void 0});t.json&&n.log(JSON.stringify(r,null,2));let i=r.failed>0,a=t.strict===!0&&r.scored>0;(i||a)&&(process.exitCode=1)}finally{p&&await p.close()}let g=typeof process.exitCode==`number`?process.exitCode:0;process.exit(g)}function parsePositiveInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<1)throw Error(`${t} must be a positive integer; got "${e}".`);return n}function parseNonNegativeInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw Error(`${t} must be a non-negative integer; got "${e}".`);return n}function filterEvalsByTag(e,t){return t.length===0?[...e]:e.filter(e=>e.tags?.some(e=>t.includes(e))??!1)}function printEvalList(e,t,n){if(t){let t=e.map(e=>({id:e.id,description:e.description,tags:e.tags}));n.log(JSON.stringify(t,null,2));return}for(let t of e){let e=t.description===void 0?``:` — ${t.description}`,r=t.tags!==void 0&&t.tags.length>0?` [${t.tags.join(`, `)}]`:``;n.log(`${t.id}${r}${e}`)}}async function readExpectedAgentName(r){try{let i=JSON.parse(await readFile(join(r,`package.json`),`utf8`));return typeof i.name==`string`&&i.name.length>0?i.name:basename(r)}catch{return basename(r)}}export{runEvalCommand};
|
|
@@ -6,6 +6,14 @@
|
|
|
6
6
|
* agent.
|
|
7
7
|
*/
|
|
8
8
|
export declare function resolveVercelProductionCallbackBaseUrl(): string | null;
|
|
9
|
+
/**
|
|
10
|
+
* Resolves the origin used for framework-owned workflow callbacks.
|
|
11
|
+
*
|
|
12
|
+
* Workflow metadata falls back to port 3000 when its optional local port
|
|
13
|
+
* discovery is unavailable. eve already configures the local world with the
|
|
14
|
+
* active dev-server origin, so prefer that value before the metadata fallback.
|
|
15
|
+
*/
|
|
16
|
+
export declare function resolveWorkflowCallbackBaseUrl(metadataUrl: string): string;
|
|
9
17
|
/**
|
|
10
18
|
* Builds a framework-owned callback URL from a resolved callback origin.
|
|
11
19
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function resolveVercelProductionCallbackBaseUrl(){return process.env.VERCEL_ENV===`production`&&process.env.VERCEL_PROJECT_PRODUCTION_URL?`https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`:null}function createWorkflowCallbackUrl(e,t){let n=new URL(t,e),r=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();return r&&n.searchParams.set(`x-vercel-protection-bypass`,r),n.toString()}export{createWorkflowCallbackUrl,resolveVercelProductionCallbackBaseUrl};
|
|
1
|
+
function resolveVercelProductionCallbackBaseUrl(){return process.env.VERCEL_ENV===`production`&&process.env.VERCEL_PROJECT_PRODUCTION_URL?`https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`:null}function resolveWorkflowCallbackBaseUrl(e){let t=process.env.WORKFLOW_LOCAL_BASE_URL?.trim()||void 0;return(resolveVercelProductionCallbackBaseUrl()??t??e).replace(/\/$/,``)}function createWorkflowCallbackUrl(e,t){let n=new URL(t,e),r=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();return r&&n.searchParams.set(`x-vercel-protection-bypass`,r),n.toString()}export{createWorkflowCallbackUrl,resolveVercelProductionCallbackBaseUrl,resolveWorkflowCallbackBaseUrl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{accumulateRuntimeActionResults}from"#harness/runtime-actions.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{
|
|
1
|
+
import{accumulateRuntimeActionResults}from"#harness/runtime-actions.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{normalizeSerializableError,rebuildSerializableError}from"#execution/workflow-errors.js";import{dispatchTurnStep,emitTerminalSessionFailureStep,routeProxiedDeliverStep,runProxyInputRequestStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{coalesceDeliveries}from"#harness/messages.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{notifyDelegatedParentStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{createSessionStep}from"#execution/create-session-step.js";import{dispatchWorkflowRuntimeActionsStep}from"#execution/dispatch-workflow-runtime-actions-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{claimHookOwnership,closeHookIterator,disposeHook}from"#execution/hook-ownership.js";async function workflowEntry(e){"use workflow";let{workflowRunId:t}=getWorkflowMetadata(),n=e.serializedContext[`eve.continuationToken`]||``,i=e.serializedContext[`eve.mode`],a=e.serializedContext[`eve.capabilities`],s=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=t;let c=getWritable();try{let r=readRootSessionId(e.serializedContext),{state:o}=await createSessionStep({compiledArtifactsSource:s.source,continuationToken:n,nodeId:s.nodeId,outputSchema:e.input.outputSchema,rootSessionId:r,sessionId:t});return await runDriverLoop({capabilities:a,driverWritable:c,initialInput:{kind:`deliver`,payloads:[{message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema}],requestId:readChannelRequestId(e.serializedContext)},mode:i,serializedContext:e.serializedContext,sessionState:o})}catch(t){throw await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:c,serializedContext:e.serializedContext}),await fireSessionCallbackStep({error:normalizeSerializableError(t),serializedContext:e.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(e.serializedContext,t),serializedContext:e.serializedContext}),t}}async function runDriverLoop(e){let r=createHook({token:`${e.sessionState.sessionId}:auth`}),i=r[Symbol.asyncIterator](),a=0,nextTurnCompletionToken=()=>`${e.sessionState.sessionId}:turn-completion:${String(a++)}`,o=``,s,c,l=null,u=[],getNextPromise=()=>{if(c===void 0)throw Error(`Cannot wait for deliveries before a continuation token is available.`);return l??=c.next(),l},consumeNext=()=>{l=null},closeParkHook=async()=>{let e=c,t=s;if(s=void 0,c=void 0,l=null,e!==void 0)try{await closeHookIterator(e)}catch(e){if(t!==void 0)try{await disposeHook(t)}catch{}throw e}t!==void 0&&await disposeHook(t)},rekeyHook=async e=>{if(!e||s!==void 0&&e===o)return;let t=createHook({token:e});await claimHookOwnership(t);try{await closeParkHook()}catch(e){try{await disposeHook(t)}catch{}throw e}o=e,s=t,c=t[Symbol.asyncIterator](),l=null};try{e.sessionState.continuationToken&&await rekeyHook(e.sessionState.continuationToken);let r=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:e.initialInput,mode:e.mode,parentWritable:e.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});if(r.kind===`done`)return await finalizeDone({action:r,driverWritable:e.driverWritable});if(!r.sessionState.continuationToken)throw Error("Cannot park: no continuation token available. The channel must post the first message during the initial turn (anchoring the session) or `send()` must be called with an explicit continuationToken.");for(await rekeyHook(r.sessionState.continuationToken);;)switch(r.kind){case`done`:return await finalizeDone({action:r,driverWritable:e.driverWritable});case`dispatch-workflow-runtime-actions`:case`dispatch-runtime-actions`:{let i=await(r.kind===`dispatch-workflow-runtime-actions`?dispatchWorkflowRuntimeActionsStep:dispatchRuntimeActionsStep)({callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),parentWritable:e.driverWritable,serializedContext:r.serializedContext,sessionState:r.sessionState}),a=await waitForPendingRuntimeActionResults({bufferedDeliveries:u,consumeNext,getNextPromise,initialResults:i.results,parentWritable:e.driverWritable,pendingActionKeys:r.pendingActionKeys,rekeyHook,serializedContext:r.serializedContext,sessionState:i.sessionState});if(a===null)return{output:``};r=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{kind:`runtime-action-result`,results:a.results},mode:e.mode,parentWritable:e.driverWritable,serializedContext:a.serializedContext,sessionState:a.sessionState}),await rekeyHook(r.sessionState.continuationToken);break}case`park`:{if(r.authorizationNames&&r.authorizationNames.length>0){let t=r.authorizationNames.length,n=[];for(;n.length<t;){let e=await i.next();if(e.done)break;e.value.kind===`deliver`&&n.push(...e.value.payloads)}r=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{kind:`deliver`,payloads:n},mode:e.mode,parentWritable:e.driverWritable,serializedContext:r.serializedContext,sessionState:r.sessionState}),await rekeyHook(r.sessionState.continuationToken);break}let t=await waitForNextDeliver({bufferedDeliveries:u,consumeNext,getNextPromise});if(t===null)return{output:``};let n=await routeDeliverForChildren({auth:t.auth,parentWritable:e.driverWritable,payloads:t.payloads,sessionState:r.sessionState});if(n===void 0)continue;r=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{auth:t.auth,kind:`deliver`,payloads:[n],requestId:t.requestId},mode:e.mode,parentWritable:e.driverWritable,serializedContext:r.serializedContext,sessionState:r.sessionState}),await rekeyHook(r.sessionState.continuationToken);break}}}finally{await closeParkHook(),await closeHookIterator(i),await disposeHook(r)}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;return await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n}),{output:t}}async function dispatchAndAwaitTurn(e){let t=createHook({token:e.completionToken}),n=t.token;try{await dispatchTurnStep({capabilities:e.capabilities,completionToken:n,delivery:e.delivery,mode:e.mode,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});let r=await awaitHookPayload(t);if(r.kind===`turn-error`)throw rebuildSerializableError(r.error);return r.action}finally{await disposeHook(t)}}async function awaitHookPayload(e){for await(let t of e)return t;throw Error(`Turn completion hook closed before delivering a result.`)}async function waitForPendingRuntimeActionResults(t){let n=t.sessionState,r=t.serializedContext,i=await accumulateRuntimeActionResults({bufferedDeliveries:t.bufferedDeliveries,async getNext(){for(;;){let e=await t.getNextPromise();if(t.consumeNext(),e.done)return null;let i=e.value;if(i.kind===`deliver`){let e=await routeDeliverForChildren({auth:i.auth,parentWritable:t.parentWritable,payloads:i.payloads,sessionState:n});if(e===void 0)continue;return{kind:`deliver`,value:{...i,payloads:[e]}}}if(i.kind===`runtime-action-result`)return{kind:`runtime-action-result`,results:i.results};let a=await runProxyInputRequestStep({hookPayload:i,parentWritable:t.parentWritable,serializedContext:r,sessionState:n});n=a.sessionState,r=a.serializedContext,await t.rekeyHook(n.continuationToken)}},initialResults:t.initialResults,pendingActionKeys:t.pendingActionKeys});return i===null?null:{results:i,serializedContext:r,sessionState:n}}async function routeDeliverForChildren(e){let t=coalescePayloads(e.payloads);return e.sessionState.hasProxyInputRequests?(await routeProxiedDeliverStep({auth:e.auth,parentWritable:e.parentWritable,payload:t,sessionState:e.sessionState})).remainder:t}async function waitForNextDeliver(e){if(e.bufferedDeliveries.length>0)return coalesceDeliveries(e.bufferedDeliveries.splice(0));for(;;){let t=await e.getNextPromise();if(e.consumeNext(),t.done)return null;if(t.value.kind!==`deliver`)continue;let n=t.value;for(;;){let t=await takeReadyPayload(e.getNextPromise());if(t===NO_READY_MESSAGE||(e.consumeNext(),t.done))break;t.value.kind===`deliver`&&(n=coalesceDeliveries([n,t.value]))}return n}}function coalescePayloads(e){if(e.length===0)return{};if(e.length===1)return e[0]??{};let t={},n=[];for(let r of e){for(let[e,n]of Object.entries(r))e!==`inputResponses`&&n!==void 0&&(t[e]=n);r.inputResponses!==void 0&&n.push(...r.inputResponses)}return n.length>0&&(t.inputResponses=n),t}const NO_READY_MESSAGE=Symbol(`no-ready-message`);async function takeReadyPayload(e){return await Promise.resolve(),await Promise.race([e,Promise.resolve(NO_READY_MESSAGE)])}export{workflowEntry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,formatError}from"#internal/logging.js";import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ContinuationTokenKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{resumeHook}from"#internal/workflow/runtime.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{createWorkflowRuntime,startWorkflowPreferLatest}from"#execution/workflow-runtime.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{runStep,withContextScope}from"#context/run-step.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{emitProxiedInputRequest,routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{turnWorkflow}from"#execution/turn-workflow.js";async function turnStep(e){"use step";let t=e,o=await readDurableSession(t.sessionState),l=await deserializeContext(t.serializedContext),f=l.require(ChannelKey),p=l.require(BundleKey);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&l.set(CallbackBaseUrlKey,t.url.replace(/\/$/,``))}catch{}let m=getPendingAuthorization(o.state),h;if(m&&t.input?.kind===`deliver`){let e=[],n=[],r=[];for(let i of t.input.payloads){let t=i.authorizationCallback;if(t){let r=m.challenges.find(e=>e.name===t.connectionName);r&&(e.push({name:r.name,resume:r.resume,callback:t.callback,hookUrl:r.hookUrl}),n.push({name:r.name,authorization:r.challenge}))}else r.push(i)}e.length>0&&(l.set(PendingAuthorizationResultKey,e),o={...o,state:clearPendingAuthorization(o.state,e.map(e=>e.name))},h=n,t=r.length>0?{...t,input:{...t.input,payloads:r}}:{...t,input:void 0})}t.input?.kind===`deliver`&&t.input.auth!==void 0&&l.set(AuthKey,t.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},durable:o,turnAgent:p.turnAgent}),_=buildAdapterContext(f,l),v;if(t.input?.kind===`deliver`){let e=[];for(let n of t.input.payloads){let t=f.deliver?await f.deliver(n,_):defaultDeliverResult(n);t!=null&&e.push(t)}v=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else t.input?.kind===`runtime-action-result`&&(v={runtimeActionResults:t.input.results});if(t.input?.kind===`deliver`&&setChannelContext(l,{...f,state:{..._.state}}),t.input?.kind===`deliver`&&v===void 0){let e=reconcileSessionContinuationToken(l,g),n=serializeContext(l),r=e===g?t.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:n,sessionState:r}}let y=t.parentWritable.getWriter(),b=p.hookRegistry,x=p.resolvedAgent.dynamicInstructionsResolvers??[],S=p.resolvedAgent.dynamicSkillResolvers??[],C=p.resolvedAgent.dynamicToolResolvers??[],emit=async e=>{let t=await callAdapterEventHandler(f,e,_);return setChannelContext(l,{...f,state:{..._.state}}),await y.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t))),t},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:l,registry:b,event:n}),await dispatchDynamicToolEvent({ctx:l,resolvers:C,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:l,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:l,resolvers:x,event:n,messages:t??[]})},w=l.require(ModeKey),T=await runStep(l,g,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:p.turnAgent.outputSchema,input:v,mode:w,session:e});if(h){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of h)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=l.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},session:e,turnAgent:p.turnAgent});return createExecutionNodeStep({capabilities:n,createRuntime:createWorkflowRuntime,handleEvent,mode:w,modelResolutionScope:{moduleMap:p.moduleMap,nodeId:p.nodeId},node:p.graph.root})(r,t)})(t,v)}),E=reconcileSessionContinuationToken(l,T.session),D=serializeContext(l);T={...T,session:E};let O=createDurableSessionState({session:T.session});if(T.next!==null&&typeof T.next==`object`&&`done`in T.next)return await y.close(),{action:`done`,output:T.next.output,isError:T.next.isError,serializedContext:D,sessionState:O};if(T.next===null){y.releaseLock();let e=getPendingWorkflowInterrupt(T.session.state);return e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),serializedContext:D,sessionState:O}:{action:`park`,...derivePendingState(T.session),serializedContext:D,sessionState:O}}return y.releaseLock(),{action:`continue`,serializedContext:D,sessionState:O}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function reconcileSessionContinuationToken(e,t){let n=e.get(ContinuationTokenKey);return n===void 0||n===t.continuationToken?t:{...t,continuationToken:n}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let r=formatError(e.error),i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i,message:a,detail:typeof r.detail==`string`?r.detail:void 0});let s=createSessionFailedEvent({code:i,details:r,message:a,sessionId:o});try{let t=await deserializeContext(e.serializedContext),r=t.get(ChannelKey);r!==void 0&&await callAdapterEventHandler(r,s,buildAdapterContext(r,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(s)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}}async function runProxyInputRequestStep(e){"use step";let t=await readDurableSession(e.sessionState),r=await deserializeContext(e.serializedContext),i=r.require(ChannelKey),a=buildAdapterContext(i,r),o=r.require(ModeKey),c=r.require(BundleKey),l=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:c.turnAgent}),u=e.parentWritable.getWriter(),d;try{let emit=async e=>{let t=await callAdapterEventHandler(i,e,a);await u.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t)))};d=await withContextScope(r,l,async t=>{let n=await emitProxiedInputRequest({emit,hookPayload:e.hookPayload,mode:o,session:t});return{result:n.entries,session:n.session}})}finally{u.releaseLock()}return setChannelContext(r,{...i,state:{...a.state}}),{serializedContext:serializeContext(r),sessionState:createDurableSessionState({session:reconcileSessionContinuationToken(r,upsertProxyInputRequests({entries:d.result,forChildContinuationToken:e.hookPayload.childContinuationToken,session:d.session}))})}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren)await resumeHook(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflow,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,emitTerminalSessionFailureStep,reconcileSessionContinuationToken,resolveEffectiveOutputSchema,routeProxiedDeliverStep,runProxyInputRequestStep,turnStep};
|
|
1
|
+
import{createLogger,formatError}from"#internal/logging.js";import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ContinuationTokenKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{resumeHook}from"#internal/workflow/runtime.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{createWorkflowRuntime,startWorkflowPreferLatest}from"#execution/workflow-runtime.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{setChannelContext}from"#execution/channel-context.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{runStep,withContextScope}from"#context/run-step.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{emitProxiedInputRequest,routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{turnWorkflow}from"#execution/turn-workflow.js";async function turnStep(e){"use step";let t=e,o=await readDurableSession(t.sessionState),l=await deserializeContext(t.serializedContext),f=l.require(ChannelKey),p=l.require(BundleKey);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&l.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let m=getPendingAuthorization(o.state),h;if(m&&t.input?.kind===`deliver`){let e=[],n=[],r=[];for(let i of t.input.payloads){let t=i.authorizationCallback;if(t){let r=m.challenges.find(e=>e.name===t.connectionName);r&&(e.push({name:r.name,resume:r.resume,callback:t.callback,hookUrl:r.hookUrl}),n.push({name:r.name,authorization:r.challenge}))}else r.push(i)}e.length>0&&(l.set(PendingAuthorizationResultKey,e),o={...o,state:clearPendingAuthorization(o.state,e.map(e=>e.name))},h=n,t=r.length>0?{...t,input:{...t.input,payloads:r}}:{...t,input:void 0})}t.input?.kind===`deliver`&&t.input.auth!==void 0&&l.set(AuthKey,t.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},durable:o,turnAgent:p.turnAgent}),_=buildAdapterContext(f,l),v;if(t.input?.kind===`deliver`){let e=[];for(let n of t.input.payloads){let t=f.deliver?await f.deliver(n,_):defaultDeliverResult(n);t!=null&&e.push(t)}v=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else t.input?.kind===`runtime-action-result`&&(v={runtimeActionResults:t.input.results});if(t.input?.kind===`deliver`&&setChannelContext(l,{...f,state:{..._.state}}),t.input?.kind===`deliver`&&v===void 0){let e=reconcileSessionContinuationToken(l,g),n=serializeContext(l),r=e===g?t.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:n,sessionState:r}}let y=t.parentWritable.getWriter(),b=p.hookRegistry,x=p.resolvedAgent.dynamicInstructionsResolvers??[],S=p.resolvedAgent.dynamicSkillResolvers??[],C=p.resolvedAgent.dynamicToolResolvers??[],emit=async e=>{let t=await callAdapterEventHandler(f,e,_);return setChannelContext(l,{...f,state:{..._.state}}),await y.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t))),t},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:l,registry:b,event:n}),await dispatchDynamicToolEvent({ctx:l,resolvers:C,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:l,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:l,resolvers:x,event:n,messages:t??[]})},w=l.require(ModeKey),T=await runStep(l,g,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:p.turnAgent.outputSchema,input:v,mode:w,session:e});if(h){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of h)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=l.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},session:e,turnAgent:p.turnAgent});return createExecutionNodeStep({capabilities:n,createRuntime:createWorkflowRuntime,handleEvent,mode:w,modelResolutionScope:{moduleMap:p.moduleMap,nodeId:p.nodeId},node:p.graph.root})(r,t)})(t,v)}),E=reconcileSessionContinuationToken(l,T.session),D=serializeContext(l);T={...T,session:E};let O=createDurableSessionState({session:T.session});if(T.next!==null&&typeof T.next==`object`&&`done`in T.next)return await y.close(),{action:`done`,output:T.next.output,isError:T.next.isError,serializedContext:D,sessionState:O};if(T.next===null){y.releaseLock();let e=getPendingWorkflowInterrupt(T.session.state);return e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),serializedContext:D,sessionState:O}:{action:`park`,...derivePendingState(T.session),serializedContext:D,sessionState:O}}return y.releaseLock(),{action:`continue`,serializedContext:D,sessionState:O}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function reconcileSessionContinuationToken(e,t){let n=e.get(ContinuationTokenKey);return n===void 0||n===t.continuationToken?t:{...t,continuationToken:n}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let r=formatError(e.error),i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i,message:a,detail:typeof r.detail==`string`?r.detail:void 0});let s=createSessionFailedEvent({code:i,details:r,message:a,sessionId:o});try{let t=await deserializeContext(e.serializedContext),r=t.get(ChannelKey);r!==void 0&&await callAdapterEventHandler(r,s,buildAdapterContext(r,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(s)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}}async function runProxyInputRequestStep(e){"use step";let t=await readDurableSession(e.sessionState),r=await deserializeContext(e.serializedContext),i=r.require(ChannelKey),a=buildAdapterContext(i,r),o=r.require(ModeKey),c=r.require(BundleKey),l=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:c.turnAgent}),u=e.parentWritable.getWriter(),d;try{let emit=async e=>{let t=await callAdapterEventHandler(i,e,a);await u.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t)))};d=await withContextScope(r,l,async t=>{let n=await emitProxiedInputRequest({emit,hookPayload:e.hookPayload,mode:o,session:t});return{result:n.entries,session:n.session}})}finally{u.releaseLock()}return setChannelContext(r,{...i,state:{...a.state}}),{serializedContext:serializeContext(r),sessionState:createDurableSessionState({session:reconcileSessionContinuationToken(r,upsertProxyInputRequests({entries:d.result,forChildContinuationToken:e.hookPayload.childContinuationToken,session:d.session}))})}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren)await resumeHook(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflow,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,emitTerminalSessionFailureStep,reconcileSessionContinuationToken,resolveEffectiveOutputSchema,routeProxiedDeliverStep,runProxyInputRequestStep,turnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.15.
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.15.1`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The last ready development-server URL for one app root.
|
|
3
|
+
*
|
|
4
|
+
* The record lets a second interactive `eve dev` attach to the same server.
|
|
5
|
+
* It is not a lock: a stale or malformed record simply causes the caller to
|
|
6
|
+
* start a new server and overwrite it once that server is ready.
|
|
7
|
+
*/
|
|
8
|
+
export declare class DevelopmentServerState {
|
|
9
|
+
#private;
|
|
10
|
+
readonly appRoot: string;
|
|
11
|
+
constructor(project: {
|
|
12
|
+
readonly appRoot: string;
|
|
13
|
+
});
|
|
14
|
+
/** Returns the recorded URL, if the record exists and is valid. */
|
|
15
|
+
read(): Promise<string | undefined>;
|
|
16
|
+
/** Records a server after it is ready to accept clients. */
|
|
17
|
+
write(url: string): Promise<void>;
|
|
18
|
+
/** Clears the record after the listening server has stopped. */
|
|
19
|
+
remove(): Promise<void>;
|
|
20
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{httpServerUrlSchema}from"#shared/network-address.js";import{join}from"node:path";import{mkdir,readFile,rm,writeFile}from"node:fs/promises";const developmentServerStateSchema=z.object({url:httpServerUrlSchema}).strict();var DevelopmentServerState=class{appRoot;#e;#t;constructor(e){this.appRoot=e.appRoot,this.#e=join(this.appRoot,`.eve`),this.#t=join(this.#e,`dev-server-state.v1.json`)}async read(){let e;try{e=await readFile(this.#t,`utf8`)}catch(e){if(isErrnoException(e,`ENOENT`))return;throw e}try{let t=developmentServerStateSchema.safeParse(JSON.parse(e));return t.success?t.data.url:void 0}catch{return}}async write(e){let t=developmentServerStateSchema.parse({url:e});await mkdir(this.#e,{recursive:!0}),await writeFile(this.#t,`${JSON.stringify(t)}\n`,`utf8`)}async remove(){await rm(this.#t,{force:!0})}};function isErrnoException(e,t){return e instanceof Error&&`code`in e&&e.code===t}export{DevelopmentServerState};
|
|
@@ -1,16 +1,23 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { DevelopmentServer, DevelopmentServerOptions, StartedDevelopmentServer } from "#internal/nitro/host/types.js";
|
|
2
2
|
/**
|
|
3
3
|
* Rewrites a server URL whose hostname is a wildcard listen address into a
|
|
4
4
|
* loopback URL on the same address family.
|
|
5
5
|
*/
|
|
6
6
|
export declare function normalizeDevelopmentServerClientUrl(serverUrl: string): string;
|
|
7
7
|
/**
|
|
8
|
-
*
|
|
8
|
+
* Creates a development server for an eve application. Call `start()` to boot an
|
|
9
|
+
* owned Nitro server or attach to a running owner, and `close()` to tear down a
|
|
10
|
+
* server this instance started. `close()` waits for an in-progress `start()`,
|
|
11
|
+
* resolves after failed-start cleanup, and is a no-op when it attached to an
|
|
12
|
+
* existing owner or was never started.
|
|
9
13
|
*
|
|
10
|
-
* Authored schedules are never registered with Nitro's cron scheduler in
|
|
11
|
-
*
|
|
14
|
+
* Authored schedules are never registered with Nitro's cron scheduler in dev
|
|
15
|
+
* mode. To fire one authored schedule on demand, `POST` the dev-only
|
|
12
16
|
* `/eve/v1/dev/schedules/:scheduleId` route — the handler returns
|
|
13
17
|
* `{ scheduleId, sessionIds }` so callers can subscribe to the existing
|
|
14
18
|
* per-session stream route.
|
|
15
19
|
*/
|
|
16
|
-
export declare function
|
|
20
|
+
export declare function createDevelopmentServer(rootDir: string, options?: DevelopmentServerOptions & {
|
|
21
|
+
existing?: "reject";
|
|
22
|
+
}): DevelopmentServer<StartedDevelopmentServer>;
|
|
23
|
+
export declare function createDevelopmentServer(rootDir: string, options?: DevelopmentServerOptions): DevelopmentServer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`))}
|
|
1
|
+
import{isLoopbackServerUrl}from"#shared/network-address.js";import{detectPackageManager}from"#setup/package-manager.js";import{eveDevArguments}from"#setup/primitives/index.js";import{toErrorMessage}from"#shared/errors.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{resolveDiscoveryProject}from"#discover/project.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,clearInitializedDevelopmentSandboxBackendNames,createDevelopmentSandboxRunId,getInitializedDevelopmentSandboxBackendNames}from"#execution/sandbox/development-run.js";import{pruneDevelopmentRuntimeArtifactsSnapshotsInBackground}from"#internal/nitro/dev-runtime-artifacts.js";import{build,createDevServer,prepare}from"nitro/builder";import{createApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{DevelopmentServerState}from"#internal/nitro/host/dev-server-state.js";import{isEveServerHealthy}from"#shared/eve-server-health.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{DEFAULT_DEVELOPMENT_SERVER_PORT,MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS}from"#internal/nitro/host/ports.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT=65535,WORKFLOW_LOCAL_BASE_URL_ENV=`WORKFLOW_LOCAL_BASE_URL`,PORT_ENV=`PORT`,DEFAULT_DEVELOPMENT_SERVER_HOST=`127.0.0.1`,IPV6_WILDCARD_LISTEN_HOSTNAMES=new Set([`[::]`,`::`]);function normalizeDevelopmentServerClientUrl(e){let t=new URL(e);return IPV6_WILDCARD_LISTEN_HOSTNAMES.has(t.hostname)?(t.hostname=`[::1]`,t.toString()):t.hostname===`0.0.0.0`?(t.hostname=DEFAULT_DEVELOPMENT_SERVER_HOST,t.toString()):e}function isAddressInUseError(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function resolveDevelopmentServerPort(e){let t=typeof e==`string`?Number(e):e??DEFAULT_DEVELOPMENT_SERVER_PORT;if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}function readEnvironmentPort(){let e=process.env[PORT_ENV];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid ${PORT_ENV} environment variable "${e}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}async function detectDevelopmentCommandPackageManager(e){try{return(await detectPackageManager(e)).kind}catch{return`pnpm`}}async function formatDevelopmentServerConnectCommand(e,t){let r=await detectDevelopmentCommandPackageManager(e);return[r,...eveDevArguments(r),t].join(` `)}async function createDevelopmentServerAlreadyRunningError(e,t){let n=await formatDevelopmentServerConnectCommand(e,t);return Error([`A dev server is already running for this eve agent.`,`To connect to the existing instance, run: ${n}`].join(`
|
|
2
|
+
`))}function resolveDevelopmentServerPorts(e){let t=resolveDevelopmentServerPort(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function installWorkflowLocalQueueEnvironment(e){let t=process.env[WORKFLOW_LOCAL_BASE_URL_ENV],n=process.env[PORT_ENV],r=new URL(normalizeDevelopmentServerClientUrl(e));return process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=r.origin,r.port&&(process.env[PORT_ENV]=r.port),()=>{t===void 0?delete process.env[WORKFLOW_LOCAL_BASE_URL_ENV]:process.env[WORKFLOW_LOCAL_BASE_URL_ENV]=t,n===void 0?delete process.env[PORT_ENV]:process.env[PORT_ENV]=n}}function attachTemporarySocketErrorHandler(e){let onSocketError=()=>{};return e.once(`error`,onSocketError),()=>{e.off(`error`,onSocketError)}}function shouldProxyDevelopmentServerWebSocketUpgrades(e){return e.options.features.websocket===!0||e.options.experimental.websocket===!0}function guardDevelopmentServerWebSocketUpgrades(e,t){let n=t.upgrade.bind(t),r=shouldProxyDevelopmentServerWebSocketUpgrades(e);t.upgrade=async(e,t,i)=>{if(!r){t.destroyed||t.destroy();return}let a=attachTemporarySocketErrorHandler(t);try{await n(e,t,i)}catch{t.destroyed||t.destroy()}finally{a()}}}async function closeDevelopmentServerResources(e){let t=[],attempt=async e=>{try{return await e(),!0}catch(e){return t.push(e),!1}},n=e.authoredSourceWatcher;n!==void 0&&await attempt(()=>n.close());let r=e.devServer,i=r===void 0?!0:await attempt(()=>r.close()),a=e.nitro;return a!==void 0&&await attempt(()=>a.close()),await attempt(()=>stopDevelopmentSandboxResources({backendNames:getInitializedDevelopmentSandboxBackendNames(e.developmentSandboxRunId),devRunId:e.developmentSandboxRunId,log:e=>console.warn(`[eve:dev] ${e}`)})),{errors:t,listenerClosed:i}}function createDevelopmentServerCleanupError(e){if(e.length!==0){if(e.length===1){let t=e[0];return t instanceof Error?t:Error(`Failed to close the development server: ${toErrorMessage(t)}`,{cause:t})}return AggregateError(e,`Multiple development-server resources failed to close.`)}}function createDevelopmentServerStartupCleanupError(e,t){return AggregateError([e,...t],`${toErrorMessage(e)} Cleanup also failed.`,{cause:e})}async function listenForDevelopmentServer(e){let t=resolveDevelopmentServerPorts({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!isAddressInUseError(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function startNitroDevelopmentServer(t,n){process.env[EVE_DEV_ENV_FLAG]??=`1`;let r=await resolveDiscoveryProject(t);loadDevelopmentEnvironmentFiles(r.appRoot);let u=readEnvironmentPort(),p=n.port??u,m=n.host!==void 0||n.port!==void 0||u!==void 0,h=new DevelopmentServerState(r),g=await h.read();if(g!==void 0&&isLoopbackServerUrl(g)&&await isEveServerHealthy(g)){if(n.existing===`attach-if-unconfigured`&&!m)return{handle:{kind:`existing`,appRoot:r.appRoot,url:g},close:void 0};throw await createDevelopmentServerAlreadyRunningError(r.appRoot,g)}let _=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],v=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=v;let y,b,x,S;try{let e=await devBootPhase(`compiling agent`,()=>prepareApplicationHost(r.appRoot,{dev:!0}),n.onBootProgress);pruneDevelopmentRuntimeArtifactsSnapshotsInBackground(e.appRoot);let t=resolveNitroCompiledArtifactsSource(createNitroArtifactsConfig({appRoot:e.appRoot,dev:!0}));startDevelopmentSandboxPrewarmInBackground({appRoot:e.appRoot,compiledArtifactsSource:t}),pruneLocalSandboxTemplatesInBackground(e.appRoot);let i=await devBootPhase(`creating dev server`,()=>createApplicationNitro(e,!0),n.onBootProgress);y=i,b=createDevServer(i);let o=b;guardDevelopmentServerWebSocketUpgrades(i,b);let s=n.host??i.options.devServer.hostname??DEFAULT_DEVELOPMENT_SERVER_HOST,c=p===void 0,l=await devBootPhase(`binding port`,()=>listenForDevelopmentServer({devServer:o,host:s,port:p,retryOnAddressInUse:c}),n.onBootProgress);if(!l.url)throw Error(`Nitro dev server did not expose a URL.`);let u=normalizeDevelopmentServerClientUrl(l.url);x=installWorkflowLocalQueueEnvironment(u),await devBootPhase(`building dev bundle`,async()=>{await prepare(i),await build(i)},n.onBootProgress),S=await devBootPhase(`starting file watcher`,async()=>{let{startAuthoredSourceWatcher:t}=await import(`#internal/nitro/host/dev-authored-source-watcher.js`);return t({nitro:i,preparedHost:e})},n.onBootProgress),await h.write(u);let d=x;if(d===void 0)throw Error(`Workflow local queue environment was not initialized.`);let f=S,m=b,g=i,C;return{handle:{kind:`started`,appRoot:r.appRoot,url:u},close:()=>(C??=(async()=>{let e=await closeDevelopmentServerResources({authoredSourceWatcher:f,devServer:m,developmentSandboxRunId:v,nitro:g});e.listenerClosed&&await h.remove().catch(()=>{});try{let t=createDevelopmentServerCleanupError(e.errors);if(t!==void 0)throw t}finally{clearInitializedDevelopmentSandboxBackendNames(v),d(),restoreDevelopmentSandboxRunId(_)}})(),C)}}catch(e){let t=await closeDevelopmentServerResources({authoredSourceWatcher:S,devServer:b,developmentSandboxRunId:v,nitro:y}),n=[...t.errors];throw x?.(),clearInitializedDevelopmentSandboxBackendNames(v),t.listenerClosed&&await h.remove().catch(()=>{}),restoreDevelopmentSandboxRunId(_),n.length>0?createDevelopmentServerStartupCleanupError(e,n):e}}function createDevelopmentServer(e,t={}){let n,r;return{start(){if(n!==void 0)throw Error(`DevelopmentServer.start() was already called.`);return n=startNitroDevelopmentServer(e,t).then(({handle:e,close:t})=>(r=t,e)),n},async close(){n!==void 0&&(await n.catch(()=>void 0),await r?.())}}}function restoreDevelopmentSandboxRunId(e){if(e===void 0){delete process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];return}process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=e}export{createDevelopmentServer,normalizeDevelopmentServerClientUrl};
|
|
@@ -7,14 +7,36 @@ import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";
|
|
|
7
7
|
* Route surface included in one programmatic Nitro host build.
|
|
8
8
|
*/
|
|
9
9
|
export type NitroBuildSurface = "all" | "app" | "flow";
|
|
10
|
+
/** Outcome of starting a Nitro development server the current process owns. */
|
|
11
|
+
export interface StartedDevelopmentServer {
|
|
12
|
+
readonly kind: "started";
|
|
13
|
+
readonly appRoot: string;
|
|
14
|
+
readonly url: string;
|
|
15
|
+
}
|
|
16
|
+
/** A live development server owned by another process. */
|
|
17
|
+
export interface ExistingDevelopmentServer {
|
|
18
|
+
readonly kind: "existing";
|
|
19
|
+
readonly appRoot: string;
|
|
20
|
+
readonly url: string;
|
|
21
|
+
}
|
|
22
|
+
/** Result of starting a development server for an app root. */
|
|
23
|
+
export type DevelopmentServerHandle = StartedDevelopmentServer | ExistingDevelopmentServer;
|
|
10
24
|
/**
|
|
11
|
-
*
|
|
25
|
+
* Lifecycle for one in-process Nitro development server.
|
|
26
|
+
*
|
|
27
|
+
* `start()` either boots a server this process owns or attaches to a running
|
|
28
|
+
* owner; the {@link DevelopmentServerHandle} result discriminates which.
|
|
29
|
+
* `close()` waits for an in-progress `start()`, then tears down only a server
|
|
30
|
+
* this instance started. It resolves after startup cleanup when `start()`
|
|
31
|
+
* fails, and is a no-op when the instance attached to an existing owner or was
|
|
32
|
+
* never started.
|
|
12
33
|
*/
|
|
13
|
-
export interface DevelopmentServerHandle {
|
|
34
|
+
export interface DevelopmentServer<H extends DevelopmentServerHandle = DevelopmentServerHandle> {
|
|
35
|
+
start(): Promise<H>;
|
|
14
36
|
close(): Promise<void>;
|
|
15
|
-
url: string;
|
|
16
37
|
}
|
|
17
38
|
export interface DevelopmentServerOptions {
|
|
39
|
+
readonly existing?: "attach-if-unconfigured" | "reject";
|
|
18
40
|
readonly host?: string;
|
|
19
41
|
readonly onBootProgress?: DevBootProgressReporter;
|
|
20
42
|
readonly port?: number;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { buildApplication } from "#internal/nitro/host/build-application.js";
|
|
2
|
-
export {
|
|
2
|
+
export { createDevelopmentServer } from "#internal/nitro/host/start-development-server.js";
|
|
3
3
|
export { startProductionServer } from "#internal/nitro/host/start-production-server.js";
|
|
4
|
-
export type { DevelopmentServerHandle, DevelopmentServerOptions, ProductionServerHandle, } from "#internal/nitro/host/types.js";
|
|
4
|
+
export type { DevelopmentServer, DevelopmentServerHandle, DevelopmentServerOptions, ExistingDevelopmentServer, ProductionServerHandle, StartedDevelopmentServer, } from "#internal/nitro/host/types.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildApplication}from"#internal/nitro/host/build-application.js";import{
|
|
1
|
+
import{buildApplication}from"#internal/nitro/host/build-application.js";import{createDevelopmentServer}from"#internal/nitro/host/start-development-server.js";import{startProductionServer}from"#internal/nitro/host/start-production-server.js";export{buildApplication,createDevelopmentServer,startProductionServer};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{pathExists,writeTextFile}from"../files.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{basename,join,resolve}from"node:path";import{mkdir,readdir,stat}from"node:fs/promises";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,ALLOWED_CREATE_IN_PLACE_ENTRIES=new Set([`.DS_Store`,`.git`,`.gitkeep`,`.hg`]),DEFAULT_AI_PACKAGE_VERSION=`^7.0.0`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.2.2`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.15.
|
|
1
|
+
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{pathExists,writeTextFile}from"../files.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{basename,join,resolve}from"node:path";import{mkdir,readdir,stat}from"node:fs/promises";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,ALLOWED_CREATE_IN_PLACE_ENTRIES=new Set([`.DS_Store`,`.git`,`.gitkeep`,`.hg`]),DEFAULT_AI_PACKAGE_VERSION=`^7.0.0`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.2.2`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.15.1`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
|
|
2
2
|
|
|
3
3
|
export default defineAgent({
|
|
4
4
|
model: "__EVE_INIT_MODEL__",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{EVE_HEALTH_ROUTE_PATH}from"#protocol/routes.js";async function isEveServerHealthy(e,t={}){let n=AbortSignal.timeout(t.timeoutMs??1e3),r=t.signal===void 0?n:AbortSignal.any([t.signal,n]);try{let t=new URL(EVE_HEALTH_ROUTE_PATH,e).toString();return(await fetch(t,{redirect:`error`,signal:r})).ok}catch{return!1}}export{isEveServerHealthy};
|
|
@@ -1,3 +1,15 @@
|
|
|
1
|
+
import { z } from "#compiled/zod/index.js";
|
|
2
|
+
/** HTTP(S) URL accepted as a development-server endpoint. */
|
|
3
|
+
export declare const httpServerUrlSchema: z.ZodURL;
|
|
4
|
+
/**
|
|
5
|
+
* Returns whether `hostname` names the current machine's loopback interface.
|
|
6
|
+
* Accepts the full IPv4 loopback block, IPv6 loopback, and the RFC 6761
|
|
7
|
+
* `localhost` namespace. Wildcard bind addresses such as `0.0.0.0` are not
|
|
8
|
+
* loopback connect targets.
|
|
9
|
+
*/
|
|
10
|
+
export declare function isLoopbackHostname(hostname: string): boolean;
|
|
11
|
+
/** Returns whether `urlText` is an HTTP(S) URL with a loopback hostname. */
|
|
12
|
+
export declare function isLoopbackServerUrl(urlText: string): boolean;
|
|
1
13
|
/**
|
|
2
14
|
* Whether `host` is an IP literal in a private, link-local, or otherwise
|
|
3
15
|
* reserved range that an outbound framework request must not target — an SSRF
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BlockList,isIP}from"node:net";const reservedRanges=new BlockList;reservedRanges.addSubnet(`0.0.0.0`,8,`ipv4`),reservedRanges.addSubnet(`10.0.0.0`,8,`ipv4`),reservedRanges.addSubnet(`100.64.0.0`,10,`ipv4`),reservedRanges.addSubnet(`169.254.0.0`,16,`ipv4`),reservedRanges.addSubnet(`172.16.0.0`,12,`ipv4`),reservedRanges.addSubnet(`192.168.0.0`,16,`ipv4`),reservedRanges.addSubnet(`198.18.0.0`,15,`ipv4`),reservedRanges.addAddress(`::`,`ipv6`),reservedRanges.addSubnet(`fc00::`,7,`ipv6`),reservedRanges.addSubnet(`fe80::`,10,`ipv6`);function normalizeAddress(e){let t=e.trim().replace(/^\[(.*)\]$/u,`$1`),n=t.indexOf(`%`),r=n===-1?t:t.slice(0,n);if(r.toLowerCase().startsWith(`::ffff:`)){let e=r.slice(7);if(isIP(e)===4)return e}return r}function
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{BlockList,isIP}from"node:net";const httpServerUrlSchema=z.url({protocol:/^https?$/}),reservedRanges=new BlockList;reservedRanges.addSubnet(`0.0.0.0`,8,`ipv4`),reservedRanges.addSubnet(`10.0.0.0`,8,`ipv4`),reservedRanges.addSubnet(`100.64.0.0`,10,`ipv4`),reservedRanges.addSubnet(`169.254.0.0`,16,`ipv4`),reservedRanges.addSubnet(`172.16.0.0`,12,`ipv4`),reservedRanges.addSubnet(`192.168.0.0`,16,`ipv4`),reservedRanges.addSubnet(`198.18.0.0`,15,`ipv4`),reservedRanges.addAddress(`::`,`ipv6`),reservedRanges.addSubnet(`fc00::`,7,`ipv6`),reservedRanges.addSubnet(`fe80::`,10,`ipv6`);function normalizeAddress(e){let t=e.trim().replace(/^\[(.*)\]$/u,`$1`),n=t.indexOf(`%`),r=n===-1?t:t.slice(0,n);if(r.toLowerCase().startsWith(`::ffff:`)){let e=r.slice(7);if(isIP(e)===4)return e}return r}function isLoopbackHostname(e){let t=normalizeAddress(e).toLowerCase();if(t===`localhost`||t.endsWith(`.localhost`))return!0;let n=isIP(t);return n===4?t.startsWith(`127.`):n===6&&t===`::1`}function isLoopbackServerUrl(e){let t=httpServerUrlSchema.safeParse(e);return t.success&&isLoopbackHostname(new URL(t.data).hostname)}function isReservedIpAddress(e){let t=normalizeAddress(e),n=isIP(t);return n===0?!1:reservedRanges.check(t,n===4?`ipv4`:`ipv6`)}export{httpServerUrlSchema,isLoopbackHostname,isLoopbackServerUrl,isReservedIpAddress};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** A typed success-or-failure value for expected, recoverable outcomes. */
|
|
2
|
+
export type Result<T, E> = {
|
|
3
|
+
readonly ok: true;
|
|
4
|
+
readonly value: T;
|
|
5
|
+
} | {
|
|
6
|
+
readonly ok: false;
|
|
7
|
+
readonly error: E;
|
|
8
|
+
};
|
|
9
|
+
/** Wraps a value as a successful {@link Result}. */
|
|
10
|
+
export declare function ok<T>(value: T): Result<T, never>;
|
|
11
|
+
/** Wraps an error as a failed {@link Result}. */
|
|
12
|
+
export declare function err<E>(error: E): Result<never, E>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function ok(e){return{ok:!0,value:e}}function err(e){return{ok:!1,error:e}}export{err,ok};
|
package/docs/guides/dev-tui.md
CHANGED
|
@@ -24,7 +24,7 @@ The conversation streams straight into your terminal's normal scrollback, so you
|
|
|
24
24
|
|
|
25
25
|
Each turn renders without boxes. A colored gutter glyph marks who is speaking, tool calls collapse to a one-line summary (`✓ get_weather city="SF" → 73°F`), and a subagent's work is indented beneath its `◆` header. When input is ready, the prompt stays bare until you type. A green circle-dot pulses while the agent is waiting to answer and disappears when reasoning or answer content begins.
|
|
26
26
|
|
|
27
|
-
A persistent line beneath the prompt or status shows the model, the session's token flow (`↑ 394.4K ↓ 4.3K`), the linked Vercel project, and a yellow `/deploy pending` marker once a channel added this session still needs `/deploy`. The Vercel segment stays hidden until the directory is linked. Remote sessions lead with a padded `↗ project (environment)` badge, or the host when Vercel cannot resolve the deployment. The badge is gray while checking or unavailable, yellow while authentication is required or failed, and blue when connected. Remote status lines omit AI Gateway endpoint state.
|
|
27
|
+
A persistent line beneath the prompt or status shows the model, the session's token flow (`↑ 394.4K ↓ 4.3K`), the linked Vercel project, and a yellow `/deploy pending` marker once a channel added this session still needs `/deploy`. The Vercel segment stays hidden until the directory is linked. Local sessions lead with a gray `:port` badge. Remote sessions lead with a padded `↗ project (environment)` badge, or the host when Vercel cannot resolve the deployment. The badge is gray while checking or unavailable, yellow while authentication is required or failed, and blue when connected. Other status segments use `·` separators. Remote status lines omit AI Gateway endpoint state.
|
|
28
28
|
|
|
29
29
|
Errors render compactly with docs links highlighted. A code bug escaping your agent's own code shows its stack trace dim beneath the error headline. Dev-server rebuilds condense into one status row that updates in place (`tui/setup-panel.ts changed · rebuilding…`, then `· rebuilt`); only the latest rebuild shows, and paths shrink to their last two components.
|
|
30
30
|
|
package/docs/reference/cli.md
CHANGED
|
@@ -109,7 +109,7 @@ Pass a bare URL as the only argument and the UI connects to that server instead
|
|
|
109
109
|
| `--context-size <tokens>` | number | none | Model context window size, shown as a usage percentage |
|
|
110
110
|
| `--logs <mode>` | enum | `stderr` | Server/agent logs to show: `all` \| `stderr` \| `sandbox` \| `none` |
|
|
111
111
|
|
|
112
|
-
Local dev
|
|
112
|
+
Local dev records the last ready URL per resolved app root in `.eve/dev-server-state.v1.json`. A second interactive `eve dev` reconnects only when that URL is loopback and healthy; each terminal UI creates a fresh client session while sharing the server process. A stale or malformed record is replaced when eve starts a new server. Passing `--host`, `--port`, or a `PORT` environment value skips reconnection and reports a healthy recorded server instead.
|
|
113
113
|
|
|
114
114
|
Local dev keeps immutable runtime source snapshots under `.eve/dev-runtime/snapshots/` so in-flight sessions hold a consistent code revision while new prompts pick up rebuilds. On startup, `eve dev` prunes stale runtime snapshots and old local sandbox templates in the background. For manual cleanup, stop `eve dev` and delete `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/`.
|
|
115
115
|
|