eve 0.8.0 → 0.8.2
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 +12 -0
- package/dist/src/cli/dev/tui/runner.d.ts +5 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +1 -0
- package/dist/src/cli/dev/tui/terminal-renderer.js +1 -1
- package/dist/src/execution/sandbox/development-prewarm.d.ts +4 -0
- package/dist/src/execution/sandbox/development-prewarm.js +1 -1
- package/dist/src/execution/sandbox/ensure.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/start-development-server.js +1 -1
- package/dist/src/setup/flows/link.d.ts +6 -0
- package/dist/src/setup/flows/link.js +1 -1
- package/dist/src/setup/flows/vercel.d.ts +3 -2
- package/dist/src/setup/flows/vercel.js +1 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/update/channels.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.8.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- f453509: The dev TUI `/model` flow's "Connect via a project" option can now create a new Vercel project, not only link an existing one. A fresh agent with no project no longer dead-ends on an empty "Project to link" list. `eve link` stays existing-only.
|
|
8
|
+
|
|
9
|
+
## 0.8.1
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 0e6a518: Route `eve dev` startup sandbox prewarm logs into the TUI sandbox section instead of printing them above the interface. Fast prewarms are retained for the TUI startup replay, so the sandbox progress is still visible without corrupting the terminal frame.
|
|
14
|
+
|
|
3
15
|
## 0.8.0
|
|
4
16
|
|
|
5
17
|
### Minor Changes
|
|
@@ -131,6 +131,11 @@ export type AgentTUIRenderer = {
|
|
|
131
131
|
* recovery and slash-command results. Optional.
|
|
132
132
|
*/
|
|
133
133
|
renderNotice?(text: string): void;
|
|
134
|
+
/**
|
|
135
|
+
* Commits one development sandbox lifecycle line to the transcript.
|
|
136
|
+
* Optional so non-terminal renderers can ignore local prewarm progress.
|
|
137
|
+
*/
|
|
138
|
+
renderSandboxLog?(text: string): void;
|
|
134
139
|
renderSetupWarning?(text: string): void;
|
|
135
140
|
renderCommandResult?(text: string): void;
|
|
136
141
|
readonly setupFlow?: SetupFlowRenderer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{pickAgentHeaderTip}from"./agent-header.js";import{formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{failureKey,formatFailureDetail,formatFailureMessage,formatGatewayAuthFailureNotice,isAbortLikeError,isGatewayAuthFailure,isInterruptedError}from"./errors.js";import{BOOT_DETECTIONS,detectSetupIssues,formatSetupIssuesLine}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import{toErrorMessage}from"#shared/errors.js";import{isCurrentTurnBoundaryEvent}from"#client/index.js";import{createDevelopmentRuntimeArtifactSessionRefresher}from"#services/dev-client.js";var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v=pickAgentHeaderTip();#y;#b=new Map;#x=new Map;#S=new Map;#C=new Map;#w=new Set;#T=!1;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.#_=createVercelStatusTracker(t)}e.promptCommandHandler!==void 0&&(this.#h=e.promptCommandHandler),this.#g=e.bootDetections??BOOT_DETECTIONS,e.serverUrl!==void 0&&(this.#f=e.serverUrl,this.#d=createDevelopmentRuntimeArtifactSessionRefresher({serverUrl:e.serverUrl}))}async#E(){let e=this.#f;if(e===void 0){await this.#j(void 0);return}let t;try{t=await this.#t?.info()}catch{t=void 0}this.#y=t;let n={name:this.#r,serverUrl:e};t!==void 0&&(n.info=t),this.#p!==void 0&&(n.tip=this.#v),this.#n.renderAgentHeader?.(n),await this.#j(t)}async run(){try{await this.#D()}finally{this.#n.shutdown?.(),this.#_?.dispose()}}async#D(){let e=this.#r,r,i,a=!1,o=!1,s=this.#m;for(await this.#E(),this.#_?.refreshIdentity();;){if(!o){if(r==null){if(!this.#n.readPrompt){if(a)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let t={title:e};s!==void 0&&(t.initialDraft=s,s=void 0);try{r=await this.#k(t)}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let c=parsePromptCommand(r);if(c?.type===`exit`)return;if(c?.type===`new`){this.#O(),i=void 0,o=!1,r=void 0,this.#n.reset?.();continue}if(c?.type===`help`){this.#M(formatPromptCommandHelp()),i=void 0,o=!1,r=void 0;continue}if(c?.type===`loglevel`){this.#M(this.#N(c.argument)),i=void 0,o=!1,r=void 0;continue}if(c?.type===`extension`){try{let t=this.#h===void 0?{message:`/${c.name} is not available in this session.`}:await this.#h.handle(c,{renderer:this.#n,title:e});t?.message!==void 0&&this.#M(t.message),t?.vercelEffect!==void 0&&this.#_?.applyEffect(t.vercelEffect)}catch(e){if(isInterruptedError(e))return;throw e}i=void 0,r=void 0,o=!1;continue}a=!0}let c=await this.#A({prompt:o?void 0:r,inputResponses:i});try{await this.#n.renderStream(c,{title:e,submittedPrompt:r,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let t=c.turnState?.pendingApprovals??[],n=c.turnState?.pendingQuestions??[];if(t.length>0||n.length>0){let a=[];if(t.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let n of t){let t=await this.#n.readToolApproval(n,{title:e});a.push({requestId:n.approvalId,optionId:t.approved?`approve`:`deny`}),this.#b.delete(n.approvalId)}}if(n.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let t of n){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let i={requestId:t.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),a.push(i),this.#b.delete(t.requestId)}}o=!0,i=a,r=void 0;continue}c.turnState&&c.turnState.boundaryEvent===void 0&&(this.#T=!0)}catch(e){if(isInterruptedError(e))return;throw e}o=!1,i=void 0,r=void 0,this.#T&&(this.#T=!1,this.#O(),this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`))}}#O(){for(let e of this.#S.values())e.abort();this.#S.clear(),this.#x.clear(),this.#b.clear(),this.#C.clear(),this.#w.clear(),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}async#k(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.#P(),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#A(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.#P(),session:this.#e})),r=await this.#e.send(n)}catch(e){if(isInterruptedError(e))throw e;return this.#T=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}let i=createTurnState();return{abort:()=>t.abort(),events:eveEventsToTUIStream({events:r,pendingInputRequests:this.#b,subagentRuns:this.#x,turnState:i,onSubagentCalled:e=>this.#R(e),onSubagentCompleted:e=>this.#B(e),onConnectionAuthRequired:e=>this.#F(e),onConnectionAuthCompleted:e=>this.#I(e),onTerminalFailure:()=>{this.#T=!0},failureOverride:this.#p===void 0?void 0:e=>isGatewayAuthFailure(e)?formatGatewayAuthFailureNotice(e):void 0}),turnState:i}}async#j(e){if(this.#p===void 0||this.#n.renderSetupWarning===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e);let n=await detectSetupIssues(t,this.#g);n.length!==0&&this.#n.renderSetupWarning(formatSetupIssuesLine(n))}#M(e){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}#N(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|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, 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`all`:return`Showing all logs.`}}async#P(){let e=this.#y,t;try{t=await this.#t?.info()}catch{t=void 0}if(t!==void 0&&(this.#y=t,this.#f!==void 0)){let e={info:t,name:this.#r,serverUrl:this.#f};this.#p!==void 0&&(e.tip=this.#v),this.#n.renderAgentHeader?.(e)}(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#F(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.#C.set(e.data.name,t),this.#L(t)}#I(e){let t=this.#C.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.#C.set(e.data.name,t),this.#w.delete(e.data.name),this.#L(t),this.#n.setConnectionAuthPendingCount?.(this.#w.size)}#L(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)}#R(e){let t=e.data.callId;if(this.#S.has(t))return;let n=this.#t;if(!n)return;let r=new AbortController;this.#S.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.#V(t,e),isCurrentTurnBoundaryEvent(e)))break}catch(e){if(!isAbortLikeError(e)){let n=toErrorMessage(e),r=this.#x.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.#S.delete(t)}})()}#z(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})}#B(e){let t=this.#x.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}}#V(e,t){let n=this.#x.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.#z(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.#z(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,input:e.userInput,output:e.screen})}function parseLogDisplayMode(e){return e===`all`||e===`stderr`||e===`none`?e:void 0}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,_=new Set,v=!1,y=!1,b;for await(let e of t)if(!(y&&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;b=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,n=t.actions.filter(e=>e.kind===`tool-call`);if(n.length===0)break;let r=toolBatchKey(`actions.requested`,t.turnId,t.stepIndex,n);if(g.has(r)){for(let e of n)m.has(e.callId)||h.add(e.callId);break}g.add(r);for(let e of n)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,r=t.requests.filter(e=>e.action.kind===`tool-call`);if(r.length===0)break;let a=inputRequestBatchKey(t.turnId,t.stepIndex,r);if(g.has(a)){for(let e of r)m.has(e.action.callId)||h.add(e.action.callId);break}g.add(a);for(let e of r){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}),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(h.has(n)||!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,_,u);t&&(yield t);break}case`session.failed`:{i.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,_,u);t&&(yield t),i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b},v=!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:b},v=!0;return;case`turn.completed`:y=!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}v||(yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b})}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 toolBatchKey(e,t,n,r){return`${e}:${t}:${String(n)}:${stableStringify(r.map(e=>({input:e.input,toolName:e.toolName})))}`}function inputRequestBatchKey(e,t,n){return toolBatchKey(`input.requested`,e,t,n.map(e=>({input:e.action.input,toolName:e.action.toolName})))}function stableStringify(e){return JSON.stringify(toStableJson(e))??`undefined`}function toStableJson(e,t=new WeakSet){if(typeof e!=`object`||!e)return e;if(t.has(e))return`[Circular]`;if(t.add(e),Array.isArray(e))return e.map(e=>toStableJson(e,t));let n=e,r={};for(let e of Object.keys(n).sort())r[e]=toStableJson(n[e],t);return r}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 o=failureKey(e);if(t.has(o))return;t.add(o);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{formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{failureKey,formatFailureDetail,formatFailureMessage,formatGatewayAuthFailureNotice,isAbortLikeError,isGatewayAuthFailure,isInterruptedError}from"./errors.js";import{BOOT_DETECTIONS,detectSetupIssues,formatSetupIssuesLine}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import{toErrorMessage}from"#shared/errors.js";import{isCurrentTurnBoundaryEvent}from"#client/index.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createDevelopmentRuntimeArtifactSessionRefresher}from"#services/dev-client.js";var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v=pickAgentHeaderTip();#y;#b=new Map;#x=new Map;#S=new Map;#C=new Map;#w=new Set;#T=!1;#E;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.#_=createVercelStatusTracker(t)}e.promptCommandHandler!==void 0&&(this.#h=e.promptCommandHandler),this.#g=e.bootDetections??BOOT_DETECTIONS,e.serverUrl!==void 0&&(this.#f=e.serverUrl,this.#d=createDevelopmentRuntimeArtifactSessionRefresher({serverUrl:e.serverUrl}))}async#D(){let e=this.#f;if(e===void 0){await this.#M(void 0);return}let t;try{t=await this.#t?.info()}catch{t=void 0}this.#y=t;let n={name:this.#r,serverUrl:e};t!==void 0&&(n.info=t),this.#p!==void 0&&(n.tip=this.#v),this.#n.renderAgentHeader?.(n),await this.#M(t)}async run(){try{await this.#O()}finally{this.#E?.(),this.#E=void 0,this.#n.shutdown?.(),this.#_?.dispose()}}async#O(){let e=this.#r,r,i,a=!1,o=!1,s=this.#m;for(await this.#D(),this.#N(),this.#_?.refreshIdentity();;){if(!o){if(r==null){if(!this.#n.readPrompt){if(a)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let t={title:e};s!==void 0&&(t.initialDraft=s,s=void 0);try{r=await this.#A(t)}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let c=parsePromptCommand(r);if(c?.type===`exit`)return;if(c?.type===`new`){this.#k(),i=void 0,o=!1,r=void 0,this.#n.reset?.();continue}if(c?.type===`help`){this.#P(formatPromptCommandHelp()),i=void 0,o=!1,r=void 0;continue}if(c?.type===`loglevel`){this.#P(this.#F(c.argument)),i=void 0,o=!1,r=void 0;continue}if(c?.type===`extension`){try{let t=this.#h===void 0?{message:`/${c.name} is not available in this session.`}:await this.#h.handle(c,{renderer:this.#n,title:e});t?.message!==void 0&&this.#P(t.message),t?.vercelEffect!==void 0&&this.#_?.applyEffect(t.vercelEffect)}catch(e){if(isInterruptedError(e))return;throw e}i=void 0,r=void 0,o=!1;continue}a=!0}let c=await this.#j({prompt:o?void 0:r,inputResponses:i});try{await this.#n.renderStream(c,{title:e,submittedPrompt:r,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let t=c.turnState?.pendingApprovals??[],n=c.turnState?.pendingQuestions??[];if(t.length>0||n.length>0){let a=[];if(t.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let n of t){let t=await this.#n.readToolApproval(n,{title:e});a.push({requestId:n.approvalId,optionId:t.approved?`approve`:`deny`}),this.#b.delete(n.approvalId)}}if(n.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let t of n){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let i={requestId:t.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),a.push(i),this.#b.delete(t.requestId)}}o=!0,i=a,r=void 0;continue}c.turnState&&c.turnState.boundaryEvent===void 0&&(this.#T=!0)}catch(e){if(isInterruptedError(e))return;throw e}o=!1,i=void 0,r=void 0,this.#T&&(this.#T=!1,this.#k(),this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`))}}#k(){for(let e of this.#S.values())e.abort();this.#S.clear(),this.#x.clear(),this.#b.clear(),this.#C.clear(),this.#w.clear(),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}async#A(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.#I(),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#j(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.#I(),session:this.#e})),r=await this.#e.send(n)}catch(e){if(isInterruptedError(e))throw e;return this.#T=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}let i=createTurnState();return{abort:()=>t.abort(),events:eveEventsToTUIStream({events:r,pendingInputRequests:this.#b,subagentRuns:this.#x,turnState:i,onSubagentCalled:e=>this.#B(e),onSubagentCompleted:e=>this.#H(e),onConnectionAuthRequired:e=>this.#L(e),onConnectionAuthCompleted:e=>this.#R(e),onTerminalFailure:()=>{this.#T=!0},failureOverride:this.#p===void 0?void 0:e=>isGatewayAuthFailure(e)?formatGatewayAuthFailureNotice(e):void 0}),turnState:i}}async#M(e){if(this.#p===void 0||this.#n.renderSetupWarning===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e);let n=await detectSetupIssues(t,this.#g);n.length!==0&&this.#n.renderSetupWarning(formatSetupIssuesLine(n))}#N(){this.#p===void 0||this.#n.renderSandboxLog===void 0||this.#E===void 0&&(this.#E=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#P(e){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}#F(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|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, 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`all`:return`Showing all logs.`}}async#I(){let e=this.#y,t;try{t=await this.#t?.info()}catch{t=void 0}if(t!==void 0&&(this.#y=t,this.#f!==void 0)){let e={info:t,name:this.#r,serverUrl:this.#f};this.#p!==void 0&&(e.tip=this.#v),this.#n.renderAgentHeader?.(e)}(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#L(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.#C.set(e.data.name,t),this.#z(t)}#R(e){let t=this.#C.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.#C.set(e.data.name,t),this.#w.delete(e.data.name),this.#z(t),this.#n.setConnectionAuthPendingCount?.(this.#w.size)}#z(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)}#B(e){let t=e.data.callId;if(this.#S.has(t))return;let n=this.#t;if(!n)return;let r=new AbortController;this.#S.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.#U(t,e),isCurrentTurnBoundaryEvent(e)))break}catch(e){if(!isAbortLikeError(e)){let n=toErrorMessage(e),r=this.#x.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.#S.delete(t)}})()}#V(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})}#H(e){let t=this.#x.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}}#U(e,t){let n=this.#x.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.#V(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.#V(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,input:e.userInput,output:e.screen})}function parseLogDisplayMode(e){return e===`all`||e===`stderr`||e===`none`?e:void 0}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,_=new Set,v=!1,y=!1,b;for await(let e of t)if(!(y&&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;b=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,n=t.actions.filter(e=>e.kind===`tool-call`);if(n.length===0)break;let r=toolBatchKey(`actions.requested`,t.turnId,t.stepIndex,n);if(g.has(r)){for(let e of n)m.has(e.callId)||h.add(e.callId);break}g.add(r);for(let e of n)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,r=t.requests.filter(e=>e.action.kind===`tool-call`);if(r.length===0)break;let a=inputRequestBatchKey(t.turnId,t.stepIndex,r);if(g.has(a)){for(let e of r)m.has(e.action.callId)||h.add(e.action.callId);break}g.add(a);for(let e of r){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}),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(h.has(n)||!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,_,u);t&&(yield t);break}case`session.failed`:{i.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,_,u);t&&(yield t),i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b},v=!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:b},v=!0;return;case`turn.completed`:y=!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}v||(yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b})}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 toolBatchKey(e,t,n,r){return`${e}:${t}:${String(n)}:${stableStringify(r.map(e=>({input:e.input,toolName:e.toolName})))}`}function inputRequestBatchKey(e,t,n){return toolBatchKey(`input.requested`,e,t,n.map(e=>({input:e.action.input,toolName:e.action.toolName})))}function stableStringify(e){return JSON.stringify(toStableJson(e))??`undefined`}function toStableJson(e,t=new WeakSet){if(typeof e!=`object`||!e)return e;if(t.has(e))return`[Circular]`;if(t.add(e),Array.isArray(e))return e.map(e=>toStableJson(e,t));let n=e,r={};for(let e of Object.keys(n).sort())r[e]=toStableJson(n[e],t);return r}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 o=failureKey(e);if(t.has(o))return;t.add(o);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};
|
|
@@ -70,6 +70,7 @@ export declare class TerminalRenderer implements AgentTUIRenderer {
|
|
|
70
70
|
* text is blank.
|
|
71
71
|
*/
|
|
72
72
|
renderNotice(text: string): void;
|
|
73
|
+
renderSandboxLog(text: string): void;
|
|
73
74
|
/**
|
|
74
75
|
* Commits the boot-time setup attention line (yellow `⚠`, commands blue),
|
|
75
76
|
* shown once after the agent header when boot detection finds issues.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{sliceVisible,stripAnsi,stripTerminalControls,visibleLength}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{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,lineOf,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.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,nextKey,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{toErrorMessage}from"#shared/errors.js";import{initialSelectState,reduceSelect,selectValueAtCursor}from"#setup/cli/select-state.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.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=new Map;#m=new Set;#h=[];#g=new Set;#_=new Map;#v=new Set;#y;#b=!1;#x;#S=[];#C;#w=0;#T;#E=``;#D=0;#O;#k=new PromptHistory;#A=!1;#j;#M=!1;#N=STATUS.processing;#P=`Eve`;#F=!1;#I=!1;#L=!0;#R=0;#z;#B;#V;#H=``;#U;#W;#G;#K=!1;#q=!1;#J;#Y;#X;#Z;#Q;#$;#ee;#te=``;#ne=``;#re;#ie=0;#ae;#oe;#se;#ce;setupFlow={begin:e=>this.#de(e),end:e=>this.#fe(e?.preserveDiagnostics??!0),readSelect:e=>this.#pe(e),readEditableSelect:e=>this.#he(e),readText:e=>this.#ge(e),readAcknowledge:e=>this.#_e(e),readChoice:e=>this.#me(e),setStatus:e=>this.#Te(e),renderLine:(e,t)=>this.#Ee(e,t),renderOutput:e=>this.#De(e),waitForInterrupt:()=>this.#Se()};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.#X=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#d=e?.logs??`none`}renderAgentHeader(e){this.#P=e.name,this.#y=e,this.#Oe();let t=this.#ot().join(`
|
|
2
|
-
`);if(this.#b){t!==this.#x&&(this.#x=t,this.#Ve({kind:`agent-header`,body:t,live:!1})),this.#nt();return}this.#b=!0,this.#x=t,this.#n.flush(this.#ot(),[])}async readPrompt(e){this.#Oe(e),this.#A=!0,this.#M=!1,this.#N=``,this.#O=`Type to chat ${this.#r.glyph.dot} / for commands`;let t=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#k.begin(t.text),this.#le(t),this.#j=typeaheadFor(PROMPT_COMMANDS,t.text),this.#Ie(),this.#nt(),await new Promise((e,r)=>{let apply=e=>{t=e,this.#Re(),this.#le(t),this.#j=typeaheadFor(PROMPT_COMMANDS,e.text,this.#j),this.#nt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#j=void 0,this.#Le(),this.#ke(),r(interruptedError())},suggestions=()=>this.#j!==void 0&&isTypeaheadOpen(this.#j)?this.#j:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#V=r=>{let i=applyLineEditorKey(t,r);if(i!==void 0){apply(i);return}switch(r.type){case`up`:{let e=suggestions();e===void 0?recall(this.#k.previous(t.text)):(this.#j=moveTypeaheadSelection(e,-1),this.#nt());break}case`down`:{let e=suggestions();e===void 0?recall(this.#k.next()):(this.#j=moveTypeaheadSelection(e,1),this.#nt());break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#j=dismissTypeahead(e),this.#nt());break}case`enter`:{let r=highlighted(),i=r!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(r).trimEnd():t.text;this.#j=void 0,this.#k.add(i),this.#A=!1,this.#Le(),this.#N=STATUS.processing,isPromptControlCommand(i)?this.#Ve({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#He(i),this.#ae=i),this.#le(EMPTY_LINE),this.#nt(),this.#je(),e(i);break}case`ctrl-d`:t.text.length===0?interrupt():apply(deleteForward(t));break;case`ctrl-l`:case`ctrl-r`:this.#nt();break;case`ctrl-c`:interrupt();break;default:break}},this.#Ae()})}#le(e){this.#E=e.text,this.#D=e.cursor}async renderStream(e,t){this.#Oe(t),this.#m.clear(),this.#A=!1,this.#M=!0,this.#N=STATUS.processing,this.#Ue(t?.submittedPrompt),this.#I=!1,this.#J=void 0,this.#Y=void 0,this.#Z=void 0,this.#Q=void 0,this.#$=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#ze(),this.#nt();let r=new Promise(e=>{this.#G=e});this.#V=e=>this.#Fe(e),this.#Ae();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.#I)break;this.#Ye(t,n,i)}}catch(e){this.#We(`Error`,toErrorMessage(e))}finally{this.#G=void 0,this.#I&&e.abort?.(),this.#je(),this.#Be(),this.#M=!1,this.#N=completedTurnStatus(this.#I,t?.continueSession===!0),this.#Je(),this.#nt(),(this.#I||!t?.continueSession)&&this.#ke()}if(this.#I)throw interruptedError()}async readToolApproval(e,t){return this.#Oe(t),this.#A=!1,this.#M=!1,this.#N=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#I=!1,this.#nt(),await new Promise((t,n)=>{this.#V=r=>{switch(r.type){case`character`:{let n=r.value.toLowerCase();n===`y`?(this.#N=STATUS.processing,this.#je(),this.#nt(),t({approved:!0})):n===`n`&&(this.#N=STATUS.processing,this.#ue(e.toolCallId),this.#je(),this.#nt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#nt();break;case`ctrl-c`:this.#I=!0,this.#ke(),n(interruptedError());break;default:break}},this.#Ae()})}async readInputQuestion(e,t){this.#Oe(t),this.#A=!1,this.#M=!1,this.#I=!1,this.#O=void 0;let r=e.options??[],i=r.length>0,a=(e.allowFreeform===!0||!i)&&i,o=r.length+ +!!a,s=questionSectionId(e.requestId),c=i?`select`:`text`,l=0,u=``,isOnFreeformRow=()=>a&&l===r.length,renderSection=()=>{this.#Ke({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.#N=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#A=!1}else this.#A=!0,this.#le(lineOf(u)),this.#N=``;this.#nt()};renderSection(),c===`text`&&this.#Ie(),repaintStatus();let finalize=t=>{this.#Ke({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.#A=!1,this.#N=STATUS.processing,this.#Le(),this.#je(),this.#nt();let r={};return t.optionId!==void 0&&(r.optionId=t.optionId),t.text!==void 0&&(r.text=t.text),r};return await new Promise((t,n)=>{this.#V=a=>{if(a.type===`ctrl-c`){this.#I=!0,this.#Le(),this.#ke(),n(interruptedError());return}if(a.type===`ctrl-r`){this.#nt();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=``,this.#Ie(),repaintStatus();break}let e=r[l];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}switch(a.type){case`character`:u+=a.value,this.#Re(),repaintStatus();break;case`backspace`:u=u.slice(0,-1),this.#Re(),repaintStatus();break;case`enter`:{let n=resolveQuestionText(u,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(i){if(u.length>0){u=``,this.#Re(),repaintStatus();break}c=`select`,u=``,this.#A=!1,this.#Le(),repaintStatus();break}u=``,this.#Re(),repaintStatus();break;default:break}},this.#Ae()})}upsertSubagentStep(e){if(this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),r=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&r.length===0)){if(this.#Ge(e.callId,e.subagentName),this.#o===`collapsed`){this.#nt();return}this.#Ke({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:r,live:!e.finalized}),this.#nt()}}upsertSubagentTool(e){if(this.#o===`hidden`)return;if(this.#Ge(e.callId,e.subagentName),this.#o===`collapsed`){this.#nt();return}let t=subagentToolStatus(e.status),r={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&&(r.result=stripTerminalControls(e.errorText)):(r.result=summarizeToolResult(e.output),r.toolOutput=e.output),this.#Ke(r),this.#nt()}markChildToolCallId(e){this.#g.add(e);let t=this.#_.get(e);t!==void 0&&(this.#qe(t),this.#_.delete(e),this.#nt())}#ue(e){let t=this.#p.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.#Ke({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e),preformatted:!0,live:!t}),this.#nt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#w)return;let n=this.#w>0;this.#w=t,t>0?(this.#N=STATUS.connectionAuth,this.#nt()):n&&(this.#N=STATUS.processing,this.#nt())}setVercelStatus(e){this.#T=e,this.#nt()}reset(){this.#f=[],this.#p.clear(),this.#m.clear(),this.#C=void 0,this.#S.length=0,this.#h.length=0,this.#b=!1,this.#x=void 0,this.#g.clear(),this.#_.clear(),this.#v.clear(),this.#ae=void 0,this.#re=void 0,this.#w=0,this.#J=void 0,this.#Y=void 0,this.#Z=void 0,this.#Q=void 0,this.#$=void 0,this.#F&&(this.#n.clearAll(),this.#nt())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Oe(),this.#Ve({kind:`notice`,body:t,live:!1}),this.#nt())}renderSetupWarning(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Oe(),this.#Ve({kind:`warning`,body:t,live:!1}),this.#nt())}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Oe(),this.#Ve({kind:`result`,body:t,live:!1}),this.#nt())}#de(e){this.#Oe(),this.#A=!1,this.#M=!1,this.#N=``,this.#oe={title:stripTerminalControls(e),lines:[],outputBuffer:[]},this.#ze(),this.#nt()}#fe(e){this.#se=void 0,this.#we();let t=this.#oe;if(t!==void 0){if(this.#oe=void 0,this.#Be(),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.#Ve({kind:`flow`,title:`info`,body:e.join(`
|
|
2
|
+
`);if(this.#b){t!==this.#x&&(this.#x=t,this.#Ve({kind:`agent-header`,body:t,live:!1})),this.#nt();return}this.#b=!0,this.#x=t,this.#n.flush(this.#ot(),[])}async readPrompt(e){this.#Oe(e),this.#A=!0,this.#M=!1,this.#N=``,this.#O=`Type to chat ${this.#r.glyph.dot} / for commands`;let t=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#k.begin(t.text),this.#le(t),this.#j=typeaheadFor(PROMPT_COMMANDS,t.text),this.#Ie(),this.#nt(),await new Promise((e,r)=>{let apply=e=>{t=e,this.#Re(),this.#le(t),this.#j=typeaheadFor(PROMPT_COMMANDS,e.text,this.#j),this.#nt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#j=void 0,this.#Le(),this.#ke(),r(interruptedError())},suggestions=()=>this.#j!==void 0&&isTypeaheadOpen(this.#j)?this.#j:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#V=r=>{let i=applyLineEditorKey(t,r);if(i!==void 0){apply(i);return}switch(r.type){case`up`:{let e=suggestions();e===void 0?recall(this.#k.previous(t.text)):(this.#j=moveTypeaheadSelection(e,-1),this.#nt());break}case`down`:{let e=suggestions();e===void 0?recall(this.#k.next()):(this.#j=moveTypeaheadSelection(e,1),this.#nt());break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#j=dismissTypeahead(e),this.#nt());break}case`enter`:{let r=highlighted(),i=r!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(r).trimEnd():t.text;this.#j=void 0,this.#k.add(i),this.#A=!1,this.#Le(),this.#N=STATUS.processing,isPromptControlCommand(i)?this.#Ve({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#He(i),this.#ae=i),this.#le(EMPTY_LINE),this.#nt(),this.#je(),e(i);break}case`ctrl-d`:t.text.length===0?interrupt():apply(deleteForward(t));break;case`ctrl-l`:case`ctrl-r`:this.#nt();break;case`ctrl-c`:interrupt();break;default:break}},this.#Ae()})}#le(e){this.#E=e.text,this.#D=e.cursor}async renderStream(e,t){this.#Oe(t),this.#m.clear(),this.#A=!1,this.#M=!0,this.#N=STATUS.processing,this.#Ue(t?.submittedPrompt),this.#I=!1,this.#J=void 0,this.#Y=void 0,this.#Z=void 0,this.#Q=void 0,this.#$=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#ze(),this.#nt();let r=new Promise(e=>{this.#G=e});this.#V=e=>this.#Fe(e),this.#Ae();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.#I)break;this.#Ye(t,n,i)}}catch(e){this.#We(`Error`,toErrorMessage(e))}finally{this.#G=void 0,this.#I&&e.abort?.(),this.#je(),this.#Be(),this.#M=!1,this.#N=completedTurnStatus(this.#I,t?.continueSession===!0),this.#Je(),this.#nt(),(this.#I||!t?.continueSession)&&this.#ke()}if(this.#I)throw interruptedError()}async readToolApproval(e,t){return this.#Oe(t),this.#A=!1,this.#M=!1,this.#N=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#I=!1,this.#nt(),await new Promise((t,n)=>{this.#V=r=>{switch(r.type){case`character`:{let n=r.value.toLowerCase();n===`y`?(this.#N=STATUS.processing,this.#je(),this.#nt(),t({approved:!0})):n===`n`&&(this.#N=STATUS.processing,this.#ue(e.toolCallId),this.#je(),this.#nt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#nt();break;case`ctrl-c`:this.#I=!0,this.#ke(),n(interruptedError());break;default:break}},this.#Ae()})}async readInputQuestion(e,t){this.#Oe(t),this.#A=!1,this.#M=!1,this.#I=!1,this.#O=void 0;let r=e.options??[],i=r.length>0,a=(e.allowFreeform===!0||!i)&&i,o=r.length+ +!!a,s=questionSectionId(e.requestId),c=i?`select`:`text`,l=0,u=``,isOnFreeformRow=()=>a&&l===r.length,renderSection=()=>{this.#Ke({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.#N=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#A=!1}else this.#A=!0,this.#le(lineOf(u)),this.#N=``;this.#nt()};renderSection(),c===`text`&&this.#Ie(),repaintStatus();let finalize=t=>{this.#Ke({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.#A=!1,this.#N=STATUS.processing,this.#Le(),this.#je(),this.#nt();let r={};return t.optionId!==void 0&&(r.optionId=t.optionId),t.text!==void 0&&(r.text=t.text),r};return await new Promise((t,n)=>{this.#V=a=>{if(a.type===`ctrl-c`){this.#I=!0,this.#Le(),this.#ke(),n(interruptedError());return}if(a.type===`ctrl-r`){this.#nt();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=``,this.#Ie(),repaintStatus();break}let e=r[l];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}switch(a.type){case`character`:u+=a.value,this.#Re(),repaintStatus();break;case`backspace`:u=u.slice(0,-1),this.#Re(),repaintStatus();break;case`enter`:{let n=resolveQuestionText(u,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(i){if(u.length>0){u=``,this.#Re(),repaintStatus();break}c=`select`,u=``,this.#A=!1,this.#Le(),repaintStatus();break}u=``,this.#Re(),repaintStatus();break;default:break}},this.#Ae()})}upsertSubagentStep(e){if(this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),r=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&r.length===0)){if(this.#Ge(e.callId,e.subagentName),this.#o===`collapsed`){this.#nt();return}this.#Ke({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:r,live:!e.finalized}),this.#nt()}}upsertSubagentTool(e){if(this.#o===`hidden`)return;if(this.#Ge(e.callId,e.subagentName),this.#o===`collapsed`){this.#nt();return}let t=subagentToolStatus(e.status),r={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&&(r.result=stripTerminalControls(e.errorText)):(r.result=summarizeToolResult(e.output),r.toolOutput=e.output),this.#Ke(r),this.#nt()}markChildToolCallId(e){this.#g.add(e);let t=this.#_.get(e);t!==void 0&&(this.#qe(t),this.#_.delete(e),this.#nt())}#ue(e){let t=this.#p.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.#Ke({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e),preformatted:!0,live:!t}),this.#nt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#w)return;let n=this.#w>0;this.#w=t,t>0?(this.#N=STATUS.connectionAuth,this.#nt()):n&&(this.#N=STATUS.processing,this.#nt())}setVercelStatus(e){this.#T=e,this.#nt()}reset(){this.#f=[],this.#p.clear(),this.#m.clear(),this.#C=void 0,this.#S.length=0,this.#h.length=0,this.#b=!1,this.#x=void 0,this.#g.clear(),this.#_.clear(),this.#v.clear(),this.#ae=void 0,this.#re=void 0,this.#w=0,this.#J=void 0,this.#Y=void 0,this.#Z=void 0,this.#Q=void 0,this.#$=void 0,this.#F&&(this.#n.clearAll(),this.#nt())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Oe(),this.#Ve({kind:`notice`,body:t,live:!1}),this.#nt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#Oe(),this.#Ve({kind:`sandbox`,body:t,live:!1}),this.#nt())}renderSetupWarning(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Oe(),this.#Ve({kind:`warning`,body:t,live:!1}),this.#nt())}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Oe(),this.#Ve({kind:`result`,body:t,live:!1}),this.#nt())}#de(e){this.#Oe(),this.#A=!1,this.#M=!1,this.#N=``,this.#oe={title:stripTerminalControls(e),lines:[],outputBuffer:[]},this.#ze(),this.#nt()}#fe(e){this.#se=void 0,this.#we();let t=this.#oe;if(t!==void 0){if(this.#oe=void 0,this.#Be(),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.#Ve({kind:`flow`,title:`info`,body:e.join(`
|
|
3
3
|
`),live:!1}),this.#Ve({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#nt()}}async#pe(e){let t=this.#ve(),n=isMultiSelectRequest(e),r={options:e.options,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(r.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(r.initialValues=e.initialValues);let i=initialSelectState(r),a,o=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}));o=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,select:i};return o!==void 0&&o.length>0&&(t.notices=o),a!==void 0&&(t.error=a),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#nt(),await this.#xe((t,r)=>{let o={key:t,options:e.options,select:i},s=reduceSetupSelectInput(n?{...o,kind:e.kind,required:e.required}:{...o,kind:e.kind});switch(s.kind){case`cancel`:r(void 0);return;case`repaint`:this.#nt();return;case`update`:i=s.select,a=void 0,this.#nt();return;case`submit`:r(s.values);return;case`error`:a=s.message,this.#nt();return;case`ignore`:return}}).promise}#me(e){this.#Oe();let t=this.#ye();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#nt();let r=this.#xe((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.#nt();return;case`repaint`:this.#nt();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#he(e){let t=this.#ve(),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:`editable`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint,caretVisible:this.#L}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?(i.text.length===0&&(i=lineOf(e.editable.defaultValue)),this.#Ie()):(i=lineOf(``),this.#Le())};return syncEditableRow(),this.#nt(),await this.#xe((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Re(),this.#nt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#nt()},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.#nt();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.#nt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Le()).promise}async#ge(e){let t=this.#ve(),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.#L)},this.#Ie(),this.#nt(),await this.#xe((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Re(),this.#nt()},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.#nt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#nt();return}i(t);return}default:return}},()=>this.#Le()).promise}async#_e(e){let t=this.#ve();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#nt(),await this.#xe((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#nt();return;default:return}}).promise}#ve(){return this.#Oe(),this.#A=!1,this.#M=!1,this.#N=``,this.#ye()}#ye(){return this.#oe===void 0&&(this.#oe={title:``,lines:[],outputBuffer:[]}),this.#oe}#be(){this.#oe!==void 0&&(this.#oe.question=void 0,this.#oe.hideLinesWhileQuestion=!1),this.#V=void 0,this.#je(),this.#Ce(),this.#nt()}#xe(e,t){let n=!1,r,i=new Promise(e=>{r=e}),settle=e=>{n||(n=!0,t?.(),this.#be(),r(e))};return this.#V=t=>e(t,settle),this.#Ae(),{promise:i,settle}}#Se(){let e,t=new Promise(t=>{e=t});return this.#se=e,this.#Ce(),{promise:t,dispose:()=>{this.#se===e&&(this.#se=void 0,this.#we())}}}#Ce(){if(this.#se===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#se;this.#se=void 0,this.#we(),e?.();return}e.type===`ctrl-r`&&this.#nt()};this.#ce=consumer,this.#V=consumer,this.#Ae()}#we(){this.#ce!==void 0&&(this.#V===this.#ce&&this.#je(),this.#ce=void 0)}#Te(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#oe!==void 0){this.#oe.status=t,t===void 0&&(this.#oe.preview=void 0),this.#nt();return}if(t===void 0){this.#M=!1,this.#N=``,this.#Be(),this.#nt();return}this.#Oe(),this.#M=!0,this.#N=t,this.#ze(),this.#nt()}#Ee(e,t){let r=stripTerminalControls(e);if(r.trim().length===0)return;let i=this.#oe;if(i!==void 0){if(i.preview=void 0,t===`warning`||t===`error`)for(let e of i.outputBuffer)i.lines.push({text:e,tone:`info`,evidence:!0});i.outputBuffer=[],i.lines.push({text:r,tone:t}),this.#nt();return}this.#Oe(),this.#Ve({kind:`flow`,title:t,body:r,live:!1}),this.#nt()}#De(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let r=this.#oe;if(r===void 0){this.#Ee(t,`info`);return}r.preview=t,r.outputBuffer.push(t),r.outputBuffer.length>40&&r.outputBuffer.shift(),this.#nt()}shutdown(){this.#ke()}#Oe(e){this.#P=e?.title??this.#P,this.#X=e?.contextSize??this.#l,!this.#F&&(this.#F=!0,this.#n.reset(),this.#n.hideCursor(),this.#mt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume()),this.#W=()=>this.#nt(),this.#t.on(`resize`,this.#W))}#ke(){this.#je(),this.#Le(),this.#Be(),this.#F&&=(this.#bt(),this.#nt(),this.#n.clear(),this.#n.showCursor(),this.#ht(),this.#n.newline(),this.#e.isTTY&&(this.#e.setRawMode?.(!1),this.#e.pause()),this.#W&&=(this.#t.off(`resize`,this.#W),void 0),!1)}#Ae(){this.#e.off(`data`,this.#Me),this.#e.on(`data`,this.#Me)}#je(){this.#e.off(`data`,this.#Me),this.#Pe(),this.#H=``,this.#V=void 0}#Me=e=>{this.#Pe(),this.#H+=e.toString(`utf8`),this.#Ne(),this.#H===`\x1B`&&(this.#U=setTimeout(()=>{this.#H===`\x1B`&&(this.#H=``,this.#V?.({type:`escape`}))},30),this.#U.unref?.())};#Ne(){for(;this.#H.length>0;){let e=nextKey(this.#H);if(e.incomplete)return;this.#H=this.#H.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#V?.(e.key)}}#Pe(){this.#U&&=(clearTimeout(this.#U),void 0)}#Fe(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#nt();break;case`ctrl-c`:this.#I=!0,this.#G?.();break;default:break}}#Ie(){this.#Le(),this.#Re(),this.#z=setInterval(()=>{this.#L=!this.#L,this.#nt()},500),this.#z.unref?.()}#Le(){this.#z&&=(clearInterval(this.#z),void 0),this.#L=!0}#Re(){this.#L=!0}#ze(){this.#Be(),this.#B=setInterval(()=>{this.#R+=1,this.#nt()},90),this.#B.unref?.()}#Be(){this.#B&&=(clearInterval(this.#B),void 0)}#Ve(e){e.id!==this.#re?.id&&this.#bt(),this.#f.push(e),e.id&&this.#p.set(e.id,e)}#He(e){this.#Ve({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#nt()}#Ue(e){if(e!=null){if(this.#ae===e){this.#ae=void 0;return}this.#Ve({kind:`user`,body:stripTerminalControls(e),live:!1})}}#We(e,t,r){let i={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};r!==void 0&&(i.detail=stripTerminalControls(r)),this.#Ve(i),this.#nt()}#Ge(e,t){this.#v.has(e)||(this.#v.add(e),this.#Ve({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#Ke(e){if(e.id&&this.#m.has(e.id))return;let t=e.id?this.#p.get(e.id):void 0;if(t){Object.assign(t,e);return}this.#Ve(e)}#qe(e){this.#f=this.#f.filter(t=>t.id!==e),this.#p.delete(e)}#Je(){for(let e of this.#f)e.status===`approval`||e.status===`running`||(e.live=!1)}#Ye(e,t,r){switch(e.type){case`step-start`:this.#Xe(r.hasPendingToolResults?STATUS.toolResults:STATUS.processing),r.hasPendingToolResults=!1;break;case`step-finish`:this.#tt(e.usage),this.#nt();break;case`assistant-delta`:{this.#Xe(STATUS.streaming);let t=(r.text.get(e.id)??``)+stripTerminalControls(e.delta);r.text.set(e.id,t),this.#Ze(e.id,t,!0);break}case`assistant-complete`:{let t=r.text.get(e.id)??``,i=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;r.text.set(e.id,i),this.#Ze(e.id,i,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;this.#Xe(STATUS.streaming);let i=(r.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);r.reasoning.set(e.id,i),this.#Qe(e.id,i,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let n=r.reasoning.get(e.id)??``;this.#Qe(e.id,n,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#Xe(STATUS.executingTools),this.#$e({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,r);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let n=r.tools.get(e.toolCallId);if(n===void 0)break;this.#$e({...n,status:`approval`},t,r);break}case`tool-result`:{if(t.tools===`hidden`)break;let n=this.#et(e.toolCallId,r);if(n===void 0)break;r.hasPendingToolResults=!0,this.#Xe(STATUS.toolResults),this.#$e({...n,output:e.output,status:`done`},t,r);break}case`tool-error`:{if(t.tools===`hidden`)break;let n=this.#et(e.toolCallId,r);if(n===void 0)break;r.hasPendingToolResults=!0,this.#Xe(STATUS.toolResults),this.#$e({...n,errorText:e.errorText,status:`error`},t,r);break}case`error`:this.#We(`Error`,e.errorText,e.detail);break;case`finish`:this.#tt(e.usage),this.#nt();break}}#Xe(e){let t=this.#w>0?STATUS.connectionAuth:e;this.#N!==t&&(this.#N=t,this.#nt())}#Ze(e,t,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Ke({id:e,kind:`assistant`,body:i,live:r}),this.#nt())}#Qe(e,t,r,i){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#Ke({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(i.reasoning,r),live:r}),this.#nt())}#$e(e,t,n){if(n.tools.set(e.toolCallId,e),this.#g.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#_.set(e.toolCallId,r),this.#Ke(renderNativeToolBlock(e,r,t.tools===`full`)),this.#nt()}#et(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#_.get(e)??toolSectionId(e),i=this.#p.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`}}#tt(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#J=(t??0)+(n??0)),this.#Y=t??this.#Y,this.#Z=n??this.#Z,this.#Z!=null&&this.#$!==void 0){let e=(Date.now()-this.#$)/1e3;e>0&&(this.#Q=this.#Z/e)}}#nt(){if(this.#F){if(this.#K){this.#q=!0;return}this.#K=!0;try{do this.#q=!1,this.#rt();while(this.#q)}finally{this.#K=!1}}}#rt(){if(!this.#F)return;let e=this.#ft(),t=this.#lt(e),n=Math.max(1,this.#pt()-t.length),r=[],i=this.#C;for(;this.#f.length>0&&this.#f[0].live===!1;){let t=this.#f.shift();if(this.#h.push(t),t.id&&(this.#m.add(t.id),this.#p.delete(t.id)),this.#St(t))continue;let n=this.#st(t,e,i);i=previousBlockOf(t),this.#C=i,r.push(...n),this.#S.push(...n)}let a=[];for(let t of this.#f){if(this.#St(t))continue;let n=this.#st(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)}#it(){if(!this.#F)return;let e=this.#ft(),t=this.#lt(e),n=Math.max(1,this.#pt()-t.length),r=this.#C,i=[];for(let t of this.#f){if(this.#St(t))continue;let n=this.#st(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.#ot(),...this.#S],a)}logDisplayMode(){return this.#d}setLogDisplayMode(e){e!==this.#d&&(this.#d=e,this.#at(),this.#F&&this.#it())}#at(){let e=this.#ft();this.#S.length=0;let t;for(let n of this.#h){if(this.#St(n))continue;let r=this.#st(n,e,t);t=previousBlockOf(n),this.#S.push(...r)}this.#C=t}#ot(){let e=this.#y;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#ft()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#st(e,t,n){let r={spinner:this.#ct()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#ct(){return this.#r.spinner[this.#R%this.#r.spinner.length]??``}#lt(e){let t=this.#r.colors,n=[``],r=this.#oe;if(r!==void 0){let t=this.#ct(),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,frame:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,frame:t}:{kind:`preview`,text:r.preview,frame:t}:(i={kind:`status`,status:{text:r.status,frame:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,frame: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)),n}if(this.#A){let r=this.#j===void 0?void 0:inlineCommandHint(this.#j);r===void 0&&this.#j!==void 0&&isTypeaheadOpen(this.#j)&&n.push(...renderCommandSuggestions(this.#j,this.#r,e));let i=Math.max(4,e-3),{before:a,after:o}=visibleLine({text:this.#E,cursor:this.#D},i,this.#r.glyph.ellipsis),s=isPromptControlCommand(this.#E),style=e=>s&&e.length>0?t.blue(e):e,l=this.#L?t.cyan(this.#r.glyph.caret):` `,u=r?t.dim(` ${r}`):``,d=this.#E.length===0&&this.#O!==void 0?`${l}${t.dim(this.#O)}`:`${style(a)}${l}${style(o)}${u}`;return n.push(...promptInputRows(d,e,this.#r,!0)),this.#ut(n,e),n}let i=this.#M?t.yellow(this.#ct()):t.dim(this.#r.glyph.dot),a=this.#N.length>0?this.#N:`Ready`,o=this.#M?t.dim(a):a,s=this.#dt(),l=s?`${i} ${o} ${t.dim(this.#r.glyph.dot)} ${s}`:`${i} ${o}`;return n.push(clip(l,e)),this.#ut(n,e),n}#ut(e,t){let n={theme:this.#r,width:t},r=this.#y?.info?.agent.model.id;r!==void 0&&(n.model=r);let i=this.#y?.info?.agent.model.endpoint;i!==void 0&&(n.endpoint=i);let a=this.#Y??0,o=this.#Z??0;if(a>0||o>0){let e={inputTokens:a,outputTokens:o};this.#X!==void 0&&(e.contextSize=this.#X),n.tokens=formatTokenFlow(e,this.#r.glyph)}this.#T!==void 0&&(n.vercel=this.#T);let s=buildStatusLine(n);s!==void 0&&e.push(s)}#dt(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#J,outputTokens:this.#Z,tokensPerSecond:this.#Q},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#ft(){return Math.max(20,this.#t.columns||80)}#pt(){return Math.max(8,this.#t.rows||24)}#mt(){if(this.#ee!==void 0||!this.#u)return;this.#te=``,this.#ne=``;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.#gt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ee=()=>{e(),t()}}#ht(){let e=this.#ee;e!==void 0&&(this.#ee=void 0,e(),this.#te.length>0&&(this.#xt(`stdout`)&&process.stdout.write(`${this.#te}\n`),this.#te=``),this.#ne.length>0&&(this.#xt(`stderr`)&&process.stderr.write(`${this.#ne}\n`),this.#ne=``))}#gt(e,n){let r=(e===`stdout`?this.#te:this.#ne)+n,i=r.lastIndexOf(`
|
|
4
4
|
`),a=i===-1?r:r.slice(i+1);if(e===`stdout`?this.#te=a:this.#ne=a,i===-1)return;let o=stripAnsi(r.slice(0,i)).replace(/\s+$/u,``);o.trim().length!==0&&(e===`stdout`?this.#_t(o):this.#Ve({kind:`log`,title:e,body:o,live:!1}),this.#nt())}#_t(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
|
|
5
5
|
`);t=[],e.trim().length!==0&&this.#Ve({kind:`log`,title:`stdout`,body:e,live:!1})};for(let n of e.split(`
|
|
@@ -4,6 +4,10 @@ export declare function startDevelopmentSandboxPrewarmInBackground(input: {
|
|
|
4
4
|
readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
|
|
5
5
|
readonly log?: (message: string) => void;
|
|
6
6
|
}): void;
|
|
7
|
+
export declare function subscribeDevelopmentSandboxPrewarmLogs(input: {
|
|
8
|
+
readonly appRoot: string;
|
|
9
|
+
readonly log: (message: string) => void;
|
|
10
|
+
}): () => void;
|
|
7
11
|
export declare function waitForDevelopmentSandboxPrewarm(input: {
|
|
8
12
|
readonly appRoot: string;
|
|
9
13
|
readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{prewarmAppSandboxes}from"./prewarm.js";import{toErrorMessage}from"#shared/errors.js";import{getRuntimeCompiledArtifactsAppRoot,getRuntimeCompiledArtifactsSandboxAppRoot}from"#runtime/compiled-artifacts-source.js";const pendingDevelopmentPrewarms=new Map;function startDevelopmentSandboxPrewarmInBackground(n){let r=resolvePrewarmKeys(n),
|
|
1
|
+
import{prewarmAppSandboxes}from"./prewarm.js";import{toErrorMessage}from"#shared/errors.js";import{getRuntimeCompiledArtifactsAppRoot,getRuntimeCompiledArtifactsSandboxAppRoot}from"#runtime/compiled-artifacts-source.js";const pendingDevelopmentPrewarms=new Map,retainedDevelopmentPrewarmLogs=new Map;function startDevelopmentSandboxPrewarmInBackground(n){let r=resolvePrewarmKeys(n),o=findPendingPrewarm(r);if(o!==void 0){registerPrewarmAliases(r,o);return}let s={logs:[],promise:Promise.resolve(),subscribers:new Set};for(let e of r)retainedDevelopmentPrewarmLogs.delete(e);recordPrewarmLog(s,`Eve: initializing sandbox templates in the background...`,n.log);let c=prewarmAppSandboxes({appRoot:n.appRoot,compiledArtifactsSource:n.compiledArtifactsSource,log:e=>recordPrewarmLog(s,e,n.log)});s.promise=c,registerPrewarmAliases(r,s),c.catch(e=>{recordPrewarmLog(s,`Eve: failed to initialize sandbox templates in the background: ${toErrorMessage(e)}`,n.log)}).finally(()=>{for(let e of r)pendingDevelopmentPrewarms.get(e)===s&&pendingDevelopmentPrewarms.delete(e),s.subscribers.size===0&&retainedDevelopmentPrewarmLogs.set(e,[...s.logs])})}function subscribeDevelopmentSandboxPrewarmLogs(e){let t=findPendingPrewarm([e.appRoot]);if(t!==void 0){for(let n of t.logs)e.log(n);return t.subscribers.add(e.log),()=>t.subscribers.delete(e.log)}let n=retainedDevelopmentPrewarmLogs.get(e.appRoot);if(n===void 0)return()=>{};retainedDevelopmentPrewarmLogs.delete(e.appRoot);for(let t of n)e.log(t);return()=>{}}async function waitForDevelopmentSandboxPrewarm(e){let t=findPendingPrewarm(resolvePrewarmKeys(e));if(t===void 0)return;let unsubscribe;if(e.log!==void 0){for(let n of t.logs)e.log(n);let subscriber=t=>e.log?.(t);t.subscribers.add(subscriber),unsubscribe=()=>t.subscribers.delete(subscriber)}try{await withProgressHeartbeat(`waiting for background sandbox template prewarm`,e.log,()=>t.promise)}finally{unsubscribe?.()}}function resolvePrewarmKeys(e){let t=new Set([e.appRoot]),i=getRuntimeCompiledArtifactsAppRoot(e.compiledArtifactsSource);i!==void 0&&t.add(i);let a=getRuntimeCompiledArtifactsSandboxAppRoot(e.compiledArtifactsSource);return a!==void 0&&t.add(a),[...t]}function findPendingPrewarm(e){for(let t of e){let e=pendingDevelopmentPrewarms.get(t);if(e!==void 0)return e}}function registerPrewarmAliases(e,t){for(let n of e)pendingDevelopmentPrewarms.set(n,t)}function recordPrewarmLog(e,t,n){e.logs.push(t),e.logs.length>50&&e.logs.splice(0,e.logs.length-50),n?.(t);for(let n of e.subscribers)n(t)}async function withProgressHeartbeat(e,t,n){if(t?.(e),t===void 0)return await n();let r=Date.now(),i=setInterval(()=>{t(`${e} (${Math.round((Date.now()-r)/1e3)}s elapsed)`)},1e4);i.unref?.();try{return await n()}finally{clearInterval(i)}}export{startDevelopmentSandboxPrewarmInBackground,subscribeDevelopmentSandboxPrewarmLogs,waitForDevelopmentSandboxPrewarm};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildCallbackContext}from"#context/build-callback-context.js";import{isEveDevEnvironment}from"#internal/application/optional-package-install.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{getRuntimeCompiledArtifactsSandboxAppRoot}from"#runtime/compiled-artifacts-source.js";import{createRuntimeSandboxKeys}from"#runtime/sandbox/keys.js";import{createRuntimeSandboxTemplatePlan}from"#runtime/sandbox/template-plan.js";import{
|
|
1
|
+
import{waitForDevelopmentSandboxPrewarm}from"#execution/sandbox/development-prewarm.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{isEveDevEnvironment}from"#internal/application/optional-package-install.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{getRuntimeCompiledArtifactsSandboxAppRoot}from"#runtime/compiled-artifacts-source.js";import{createRuntimeSandboxKeys}from"#runtime/sandbox/keys.js";import{createRuntimeSandboxTemplatePlan}from"#runtime/sandbox/template-plan.js";import{prewarmAppSandboxes}from"#execution/sandbox/prewarm.js";import{waitForSandboxTemplatePrewarmLock}from"#execution/sandbox/template-prewarm-lock.js";async function ensureSandboxAccess(n){let r=n.state?.initialized??!1,o=n.state?.session??null,s=getRuntimeCompiledArtifactsSandboxAppRoot(n.compiledArtifactsSource)??process.cwd(),c=n.registry.sandbox,l;function getHandle(){return l===void 0&&(l=createHandle().catch(e=>{throw l=void 0,e})),l}async function createHandle(){if(c===null)return null;let i=c.definition,l=i.backend,u=createRuntimeSandboxTemplatePlan({definition:i,workspaceResourceRoot:c.workspaceResourceRoot}),d=await createRuntimeSandboxKeys({backendName:l.name,compiledArtifactsSource:n.compiledArtifactsSource,nodeId:n.nodeId,sessionId:n.sessionId,sourceId:i.sourceId,templatePlan:u});d.templateKey!==null&&(logDevelopmentSandbox(`Eve: ensuring sandbox template "${formatNodeLabel(n.nodeId)}" before running tool...`),await waitForDevelopmentSandboxPrewarm({appRoot:s,compiledArtifactsSource:n.compiledArtifactsSource,log:e=>logDevelopmentSandbox(`Eve: sandbox template "${formatNodeLabel(n.nodeId)}" (${l.name}): ${e}`)}),await waitForSandboxTemplatePrewarmLock({appRoot:s,backendName:l.name,log:e=>logDevelopmentSandbox(`Eve: sandbox template "${formatNodeLabel(n.nodeId)}" (${l.name}): ${e}`),templateKey:d.templateKey}));let f={existingMetadata:o?.backendName===l.name&&o.sessionKey===d.sessionKey?o.metadata:void 0,runtimeContext:{appRoot:s},sessionKey:d.sessionKey,tags:n.tags,templateKey:d.templateKey},p=await withDevelopmentSandboxProgress(`Eve: opening sandbox session "${formatNodeLabel(n.nodeId)}" on backend "${l.name}"...`,`Eve: opening sandbox session "${formatNodeLabel(n.nodeId)}" on backend "${l.name}"`,async()=>await createBackendHandleWithPrewarmRetry({appRoot:s,backend:l,compiledArtifactsSource:n.compiledArtifactsSource,createInput:f}));return r||=(await runOnSession(async()=>{await i.onSession?.({ctx:buildCallbackContext(),use:p.useSessionFn})}),!0),p}async function runOnSession(e){if(n.runOnSession!==void 0){await n.runOnSession(e);return}await e()}return{async captureState(){if(l!==void 0){let e=await l;e!==null&&(o=await e.captureState())}return{initialized:r,session:o}},async dispose(){l!==void 0&&await(await l)?.dispose()},async get(){return(await getHandle())?.session??null}}}async function createBackendHandleWithPrewarmRetry(e){try{return await e.backend.create(e.createInput)}catch(t){if(e.createInput.templateKey===null||e.compiledArtifactsSource.kind!==`disk`||!SandboxTemplateNotProvisionedError.is(t))throw t;return await prewarmAppSandboxes({appRoot:e.appRoot,compiledArtifactsSource:e.compiledArtifactsSource,log:e=>logDevelopmentSandbox(e)}),await waitForSandboxTemplatePrewarmLock({appRoot:e.appRoot,backendName:e.backend.name,log:e=>logDevelopmentSandbox(`Eve: ${e}`),templateKey:e.createInput.templateKey}),logDevelopmentSandbox(`Eve: sandbox template is ready; retrying sandbox creation...`),await e.backend.create(e.createInput)}}function logDevelopmentSandbox(e){isEveDevEnvironment()&&console.log(e)}async function withDevelopmentSandboxProgress(e,t,r){if(logDevelopmentSandbox(e),!isEveDevEnvironment())return await r();let i=Date.now(),a=setInterval(()=>{logDevelopmentSandbox(`${t} (${Math.round((Date.now()-i)/1e3)}s elapsed)...`)},5e3);a.unref?.();try{return await r()}finally{clearInterval(a)}}function formatNodeLabel(e){return e===`__root__`?`root`:e}export{ensureSandboxAccess};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.8.
|
|
1
|
+
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.8.2`,WORKFLOW_MODULE_ALIASES={"workflow/api":`src/compiled/@workflow/core/runtime.js`,"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`,"workflow/runtime":`src/compiled/@workflow/core/runtime.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 t=e;for(;;){if(existsSync(join(t,`package.json`))&&!isBuildOutputPackageRoot(t))return t;let r=dirname(t);if(r===t)throw Error(`Failed to resolve package root from "${e}".`);t=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 n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}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 resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.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{resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,createDevelopmentSandboxRunId}from"#execution/sandbox/development-run.js";import{
|
|
1
|
+
import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,createDevelopmentSandboxRunId}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{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`,WILDCARD_LISTEN_HOSTNAMES=new Set([`[::]`,`::`,`0.0.0.0`]);function normalizeDevelopmentServerClientUrl(e){let t=new URL(e);return WILDCARD_LISTEN_HOSTNAMES.has(t.hostname)?(t.hostname=`127.0.0.1`,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}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 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 startDevelopmentServer(o,s={}){process.env[EVE_DEV_ENV_FLAG]??=`1`,loadDevelopmentEnvironmentFiles(o);let c=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],l=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=l;let u,d,f,p;try{let t=await prepareApplicationHost(o,{dev:!0});pruneDevelopmentRuntimeArtifactsSnapshotsInBackground(t.appRoot);let n=resolveNitroCompiledArtifactsSource(createNitroArtifactsConfig({appRoot:t.appRoot,dev:!0}));startDevelopmentSandboxPrewarmInBackground({appRoot:t.appRoot,compiledArtifactsSource:n}),pruneLocalSandboxTemplatesInBackground(t.appRoot),u=await createApplicationNitro(t,!0),d=createDevServer(u),guardDevelopmentServerWebSocketUpgrades(u,d);let r=s.host??u.options.devServer.hostname,i=s.port??readEnvironmentPort(),m=i??u.options.devServer.port,h=await listenForDevelopmentServer({devServer:d,host:r,port:m,retryOnAddressInUse:i===void 0});if(!h.url)throw Error(`Nitro dev server did not expose a URL.`);f=installWorkflowLocalQueueEnvironment(h.url),await prepare(u),await build(u);let{startAuthoredSourceWatcher:g}=await import(`#internal/nitro/host/dev-authored-source-watcher.js`);p=await g({nitro:u,preparedHost:t});let _=f;if(_===void 0)throw Error(`Workflow local queue environment was not initialized.`);let v=p,y=d,b=u;return{async close(){try{await v.close(),await y.close(),await b.close(),await stopDevelopmentSandboxResources({devRunId:l,log:e=>console.warn(`[eve:dev] ${e}`)})}finally{_(),restoreDevelopmentSandboxRunId(c)}},url:normalizeDevelopmentServerClientUrl(h.url)}}catch(e){throw await p?.close().catch(()=>{}),f?.(),await d?.close().catch(()=>{}),await u?.close().catch(()=>{}),await stopDevelopmentSandboxResources({devRunId:l,log:e=>console.warn(`[eve:dev] ${e}`)}).catch(()=>{}),restoreDevelopmentSandboxRunId(c),e}}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{normalizeDevelopmentServerClientUrl,startDevelopmentServer};
|
|
@@ -40,5 +40,11 @@ export declare function runLinkFlow(input: {
|
|
|
40
40
|
appRoot: string;
|
|
41
41
|
prompter: Prompter;
|
|
42
42
|
signal?: AbortSignal;
|
|
43
|
+
/**
|
|
44
|
+
* Whether the caller may only link an existing project (`eve link`, the
|
|
45
|
+
* default) or may also create one (the `/model` "Connect via a project"
|
|
46
|
+
* branch, where a fresh agent has no project yet).
|
|
47
|
+
*/
|
|
48
|
+
projectSelection?: "create-or-link" | "existing-only";
|
|
43
49
|
deps?: Partial<LinkFlowDeps>;
|
|
44
50
|
}): Promise<LinkFlowResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__toESM}from"../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{interactiveAsker,withAnswers}from"../ask.js";import{detectProjectIdentity}from"../project-resolution.js";import{snapshotSetupState}from"../state.js";import{WizardCancelledError}from"../step.js";import{detectAiGateway,findEnvFileWithKey}from"../boxes/detect-ai-gateway.js";import{applyAiGatewayCredential}from"../boxes/apply-ai-gateway-credential.js";import{linkVercelProject}from"../boxes/link-project.js";import{resolveProvisioning}from"../boxes/resolve-provisioning.js";import{runInteractive}from"../runner.js";import{inProjectSetupState,prompterSink}from"./in-project.js";var import_picocolors=__toESM(require_picocolors(),1);async function runLinkFlow(e){let{appRoot:t,prompter:i,signal:a}=e,
|
|
1
|
+
import{__toESM}from"../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{interactiveAsker,withAnswers}from"../ask.js";import{detectProjectIdentity}from"../project-resolution.js";import{snapshotSetupState}from"../state.js";import{WizardCancelledError}from"../step.js";import{detectAiGateway,findEnvFileWithKey}from"../boxes/detect-ai-gateway.js";import{applyAiGatewayCredential}from"../boxes/apply-ai-gateway-credential.js";import{linkVercelProject}from"../boxes/link-project.js";import{resolveProvisioning}from"../boxes/resolve-provisioning.js";import{runInteractive}from"../runner.js";import{inProjectSetupState,prompterSink}from"./in-project.js";var import_picocolors=__toESM(require_picocolors(),1);async function runLinkFlow(e){let{appRoot:t,prompter:i,signal:a,projectSelection:o=`existing-only`}=e,s={detectProjectIdentity,findEnvFileWithKey,...e.deps},c=i.log.spinner?.(`Checking the current Vercel link...`),l;try{l=a===void 0?await s.detectProjectIdentity(t):await s.detectProjectIdentity(t,{signal:a}),a?.throwIfAborted()}finally{c?.stop()}if(l===void 0){let[e,n]=await Promise.all([s.findEnvFileWithKey(t,`AI_GATEWAY_API_KEY`),s.findEnvFileWithKey(t,`VERCEL_OIDC_TOKEN`)]),r=e??n;r!==void 0&&i.log.message(`This directory is not linked to a Vercel project yet — the model currently runs on credentials from ${r}.`)}else{let e=l.teamName===void 0?import_picocolors.default.bold(l.projectName):`${import_picocolors.default.bold(l.projectName)} in ${import_picocolors.default.bold(l.teamName)}`;try{if(await i.select({message:`This directory is already linked to\n${e}`,options:[{value:`relink`,label:`Link to another project`},{value:`dismiss`,label:`Dismiss`}]})===`dismiss`)return{kind:`cancelled`}}catch(e){if(e instanceof WizardCancelledError)return{kind:`cancelled`};throw e}}let u=inProjectSetupState(t,{kind:`unresolved`});if((await runInteractive([resolveProvisioning({asker:withAnswers({deploy:`vercel`})(interactiveAsker(i)),prompter:i,targetDirectory:t,mode:{headless:!1},adoptExistingLink:!1,projectSelection:o,deps:s.resolveProvisioning}),linkVercelProject({prompter:i,deps:s.linkProject}),detectAiGateway(),applyAiGatewayCredential({prompter:i,deps:s.applyAiGatewayCredential})],u,prompterSink(i),{snapshot:snapshotSetupState,signal:a})).kind===`cancelled`)return{kind:`cancelled`};let[d,f]=await Promise.all([s.findEnvFileWithKey(t,`VERCEL_OIDC_TOKEN`),s.findEnvFileWithKey(t,`AI_GATEWAY_API_KEY`)]);a?.throwIfAborted(),d===void 0&&f===void 0&&i.log.warning("Linked, but no model credential landed in an env file (VERCEL_OIDC_TOKEN or AI_GATEWAY_API_KEY). Run `vercel env pull` once the project has AI Gateway access.");let p={kind:`done`};return d===void 0?f!==void 0&&(p.credential=`AI_GATEWAY_API_KEY`):p.credential=`VERCEL_OIDC_TOKEN`,p}export{runLinkFlow};
|
|
@@ -23,8 +23,9 @@ export type VercelFlowResult = LinkFlowResult | {
|
|
|
23
23
|
* the provider choice explicit before any link machinery runs: a provider
|
|
24
24
|
* gate (AI Gateway, or instructions for everything else) and a connection
|
|
25
25
|
* gate (link a project, or paste an `AI_GATEWAY_API_KEY` that lands in
|
|
26
|
-
* `.env.local`). The "Connect via a project" branch
|
|
27
|
-
*
|
|
26
|
+
* `.env.local`). The "Connect via a project" branch runs the link flow in
|
|
27
|
+
* create-or-link mode (link detection and all), so a project-less agent can
|
|
28
|
+
* create its first project rather than dead-end on an empty list.
|
|
28
29
|
*/
|
|
29
30
|
export declare function runVercelFlow(input: {
|
|
30
31
|
appRoot: string;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{__toESM}from"../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{appendEnv}from"../append-env.js";import{WizardCancelledError}from"../step.js";import{runLinkFlow}from"./link.js";import{validateGatewayApiKey}from"../validate-gateway-key.js";import{join}from"node:path";var import_picocolors=__toESM(require_picocolors(),1);const AI_GATEWAY_ENV_KEY=`AI_GATEWAY_API_KEY`,ENV_FILE_NAME=`.env.local`,PROVIDER_QUESTION=`Which model provider do you want to use?`,CONNECTION_QUESTION=`How do you want to connect to AI Gateway?`,EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE=`Using another model provider`,EXTERNAL_PROVIDER_INSTRUCTIONS=[`Set your provider's API key in ${ENV_FILE_NAME} — e.g. ANTHROPIC_API_KEY or OPENAI_API_KEY.`,'In agent/agent.ts, set `model` to a provider-authored model — e.g. `anthropic("claude-opus-4.8")` from `@ai-sdk/anthropic`.',`See https://beta.eve.dev/docs/agent-config for details.`,"A running `eve dev` reloads env files automatically — no restart needed."];async function runVercelFlow(e){let{appRoot:t,prompter:a,signal:o}=e,s={runLinkFlow,appendEnv,validateGatewayApiKey,...e.deps},c,l;try{c=await a.select({message:PROVIDER_QUESTION,options:[{value:`gateway`,label:`Vercel AI Gateway`,hint:`one key, every model`},{value:`other`,label:`Something else`,hint:`use your own provider credentials`}],hintLayout:`stacked`}),c===`gateway`&&(l=await a.select({message:CONNECTION_QUESTION,options:[{value:`project`,label:`Connect via a project`,hint:`vercel link + env pull`},{value:`own-key`,label:`Use my own key`,hint:`paste an ${AI_GATEWAY_ENV_KEY}`}],hintLayout:`stacked`}))}catch(e){if(e instanceof WizardCancelledError)return{kind:`cancelled`};throw e}if(c===`other`)return a.acknowledge?await a.acknowledge({message:EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE,lines:EXTERNAL_PROVIDER_INSTRUCTIONS}):a.note(EXTERNAL_PROVIDER_INSTRUCTIONS.join(`
|
|
2
|
-
`),EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE),{kind:`done`,outcome:`external-provider`};if(l===`own-key`)for(;;){let e;try{e=await a.password({message:`Enter your ${AI_GATEWAY_ENV_KEY}`,validate:e=>e.trim().length===0?`API key cannot be empty.`:void 0})}catch(e){if(e instanceof WizardCancelledError)return{kind:`cancelled`};throw e}o?.throwIfAborted();let n=e.trim(),r=a.log.spinner?.(`Validating…`),i;try{i=await s.validateGatewayApiKey(n,o)}finally{r?.stop()}if(o?.throwIfAborted(),i.kind===`invalid`){a.log.error(`${i.message} Check the key and try again, or Esc to cancel.`);continue}return i.kind===`inconclusive`?a.log.warning(`Couldn't reach the gateway to validate (${i.message}). Saving the key anyway.`):a.log.success(`${import_picocolors.default.green(`✓`)} ${import_picocolors.default.bold(`Valid key`)}`),await s.appendEnv(join(t,ENV_FILE_NAME),{[AI_GATEWAY_ENV_KEY]:n},{force:!0}),o?.throwIfAborted(),a.log.success(`Saved ${AI_GATEWAY_ENV_KEY} to ${ENV_FILE_NAME}.`),{kind:`done`,credential:AI_GATEWAY_ENV_KEY}}else return await s.runLinkFlow({appRoot:t,prompter:a,signal:o})}export{CONNECTION_QUESTION,EXTERNAL_PROVIDER_INSTRUCTIONS,EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE,PROVIDER_QUESTION,runVercelFlow};
|
|
2
|
+
`),EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE),{kind:`done`,outcome:`external-provider`};if(l===`own-key`)for(;;){let e;try{e=await a.password({message:`Enter your ${AI_GATEWAY_ENV_KEY}`,validate:e=>e.trim().length===0?`API key cannot be empty.`:void 0})}catch(e){if(e instanceof WizardCancelledError)return{kind:`cancelled`};throw e}o?.throwIfAborted();let n=e.trim(),r=a.log.spinner?.(`Validating…`),i;try{i=await s.validateGatewayApiKey(n,o)}finally{r?.stop()}if(o?.throwIfAborted(),i.kind===`invalid`){a.log.error(`${i.message} Check the key and try again, or Esc to cancel.`);continue}return i.kind===`inconclusive`?a.log.warning(`Couldn't reach the gateway to validate (${i.message}). Saving the key anyway.`):a.log.success(`${import_picocolors.default.green(`✓`)} ${import_picocolors.default.bold(`Valid key`)}`),await s.appendEnv(join(t,ENV_FILE_NAME),{[AI_GATEWAY_ENV_KEY]:n},{force:!0}),o?.throwIfAborted(),a.log.success(`Saved ${AI_GATEWAY_ENV_KEY} to ${ENV_FILE_NAME}.`),{kind:`done`,credential:AI_GATEWAY_ENV_KEY}}else return await s.runLinkFlow({appRoot:t,prompter:a,signal:o,projectSelection:`create-or-link`})}export{CONNECTION_QUESTION,EXTERNAL_PROVIDER_INSTRUCTIONS,EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE,PROVIDER_QUESTION,runVercelFlow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getPackageManagerStrategy}from"../../primitives/pm/index.js";import{pathExists,writeTextFile}from"../files.js";import{patchPackageJson}from"../update/package-json.js";import{resolveVersionToken}from"../version-tokens.js";import{agentTemplateFiles,formatEveDependencySpecifier}from"./project.js";import{join}from"node:path";import{readFile}from"node:fs/promises";const DEPENDENCY_FIELDS=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`];function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hasDeclaredDependency(e,t){if(!isJsonObject(e))return!1;for(let n of DEPENDENCY_FIELDS){let r=e[n];if(isJsonObject(r)&&typeof r[t]==`string`)return!0}return!1}async function addAgentToProject(i){let a=join(i.projectRoot,`package.json`);if(!await pathExists(a))throw Error(`Cannot add an Eve agent to "${i.projectRoot}" because it has no package.json. Run \`eve init <name>\` to create a new project instead.`);let o=agentTemplateFiles(i.model),s=[];for(let e of Object.keys(o))await pathExists(join(i.projectRoot,e))&&s.push(e);if(s.length===0&&await pathExists(join(i.projectRoot,`agent`))&&s.push(`agent/`),s.length>0)throw Error(`Cannot add an Eve agent to "${i.projectRoot}" because it already has: ${s.join(`, `)}. Move them aside first.`);let c=resolveVersionToken(`evePackageVersion`,i.evePackageVersion??`0.8.
|
|
1
|
+
import{getPackageManagerStrategy}from"../../primitives/pm/index.js";import{pathExists,writeTextFile}from"../files.js";import{patchPackageJson}from"../update/package-json.js";import{resolveVersionToken}from"../version-tokens.js";import{agentTemplateFiles,formatEveDependencySpecifier}from"./project.js";import{join}from"node:path";import{readFile}from"node:fs/promises";const DEPENDENCY_FIELDS=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`];function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hasDeclaredDependency(e,t){if(!isJsonObject(e))return!1;for(let n of DEPENDENCY_FIELDS){let r=e[n];if(isJsonObject(r)&&typeof r[t]==`string`)return!0}return!1}async function addAgentToProject(i){let a=join(i.projectRoot,`package.json`);if(!await pathExists(a))throw Error(`Cannot add an Eve agent to "${i.projectRoot}" because it has no package.json. Run \`eve init <name>\` to create a new project instead.`);let o=agentTemplateFiles(i.model),s=[];for(let e of Object.keys(o))await pathExists(join(i.projectRoot,e))&&s.push(e);if(s.length===0&&await pathExists(join(i.projectRoot,`agent`))&&s.push(`agent/`),s.length>0)throw Error(`Cannot add an Eve agent to "${i.projectRoot}" because it already has: ${s.join(`, `)}. Move them aside first.`);let c=resolveVersionToken(`evePackageVersion`,i.evePackageVersion??`0.8.2`),l=resolveVersionToken(`aiPackageVersion`,i.aiPackageVersion??`7.0.0-canary.171`),u=resolveVersionToken(`connectPackageVersion`,i.connectPackageVersion??`0.2.2`),d=resolveVersionToken(`zodPackageVersion`,i.zodPackageVersion??`4.4.3`),f=[];for(let[e,t]of Object.entries(o)){let r=join(i.projectRoot,e);await writeTextFile(r,t),f.push(r)}let p=JSON.parse(await readFile(a,`utf8`)),m={"@vercel/connect":u,ai:l,eve:formatEveDependencySpecifier(c),zod:d},h={};for(let[e,t]of Object.entries(m))hasDeclaredDependency(p,e)||(h[e]=t);return Object.keys(h).length>0&&await patchPackageJson(a,{dependencies:h}),await getPackageManagerStrategy(i.packageManager??`pnpm`).applyProjectConfiguration(i.projectRoot),{filesWritten:f,dependenciesAdded:Object.keys(h).sort()}}export{addAgentToProject};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{getPackageManagerStrategy}from"../../primitives/pm/index.js";import{pathExists,writeTextFile}from"../files.js";import{resolveVersionToken}from"../version-tokens.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_EVE_PACKAGE_VERSION=`0.8.
|
|
1
|
+
import{getPackageManagerStrategy}from"../../primitives/pm/index.js";import{pathExists,writeTextFile}from"../files.js";import{resolveVersionToken}from"../version-tokens.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_EVE_PACKAGE_VERSION=`0.8.2`,DEFAULT_AI_PACKAGE_VERSION=`7.0.0-canary.171`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.2.2`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`;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.evePackageVersion)).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_TSGO_VERSION__`,t.tsgoPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.typesNodePackageVersion)}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__",
|
|
@@ -80,4 +80,4 @@ export default defineAgent({
|
|
|
80
80
|
},
|
|
81
81
|
},
|
|
82
82
|
});
|
|
83
|
-
`:BASE_AGENT_TEMPLATE,...SHARED_TEMPLATE_FILES,"package.json":packageJsonTemplate(t),...getPackageManagerStrategy(n).scaffoldFiles}}async function assertCanCreateInPlace(e,n){if(!await pathExists(e))return;let r=(await readdir(e)).filter(e=>!ALLOWED_CREATE_IN_PLACE_ENTRIES.has(e));if(r.length>0&&!n){let e=r.slice(0,5).join(`, `),t=r.length>5?`, and ${r.length-5} more`:``;throw Error(`Cannot create project in current directory because it is not empty. Found: ${e}${t}. Use an empty directory.`)}}async function scaffoldBaseProject(e){let i=resolve(e.targetDirectory??process.cwd(),e.projectName),a=e.projectName===`.`,s=e.overwriteExisting??!1,u=e.byokProvider??!1,d=e.packageManager??`pnpm`;if(a)await assertCanCreateInPlace(i,s);else if(await pathExists(i))throw Error(`Cannot create project because "${i}" already exists.`);let f=e.typesNodePackageVersion??`25.9.1`,p={appName:basename(i),model:e.model,evePackageVersion:resolveVersionToken(`evePackageVersion`,e.evePackageVersion??`0.8.
|
|
83
|
+
`:BASE_AGENT_TEMPLATE,...SHARED_TEMPLATE_FILES,"package.json":packageJsonTemplate(t),...getPackageManagerStrategy(n).scaffoldFiles}}async function assertCanCreateInPlace(e,n){if(!await pathExists(e))return;let r=(await readdir(e)).filter(e=>!ALLOWED_CREATE_IN_PLACE_ENTRIES.has(e));if(r.length>0&&!n){let e=r.slice(0,5).join(`, `),t=r.length>5?`, and ${r.length-5} more`:``;throw Error(`Cannot create project in current directory because it is not empty. Found: ${e}${t}. Use an empty directory.`)}}async function scaffoldBaseProject(e){let i=resolve(e.targetDirectory??process.cwd(),e.projectName),a=e.projectName===`.`,s=e.overwriteExisting??!1,u=e.byokProvider??!1,d=e.packageManager??`pnpm`;if(a)await assertCanCreateInPlace(i,s);else if(await pathExists(i))throw Error(`Cannot create project because "${i}" already exists.`);let f=e.typesNodePackageVersion??`25.9.1`,p={appName:basename(i),model:e.model,evePackageVersion:resolveVersionToken(`evePackageVersion`,e.evePackageVersion??`0.8.2`),aiPackageVersion:resolveVersionToken(`aiPackageVersion`,e.aiPackageVersion??`7.0.0-canary.171`),connectPackageVersion:resolveVersionToken(`connectPackageVersion`,e.connectPackageVersion??`0.2.2`),zodPackageVersion:resolveVersionToken(`zodPackageVersion`,e.zodPackageVersion??`4.4.3`),tsgoPackageVersion:resolveVersionToken(`tsgoPackageVersion`,e.tsgoPackageVersion??`7.0.0-dev.20260523.1`),typesNodePackageVersion:u?resolveVersionToken(`typesNodePackageVersion`,f):f};await mkdir(i,{recursive:!0});for(let[r,o]of Object.entries(templateFiles(u,d))){let c=`${i}/${r}`,l=await pathExists(c);await writeTextFile(c,renderTemplate(o,p),{force:a&&s}),l&&await e.onOverwriteFile?.(c)}return i}async function isEveProject(e){for(let t of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)try{return await stat(join(e,`agent`,`agent${t}`)),!0}catch{}return!1}export{CURRENT_DIRECTORY_PROJECT_NAME,DEFAULT_AI_PACKAGE_VERSION,DEFAULT_CONNECT_PACKAGE_VERSION,DEFAULT_EVE_PACKAGE_VERSION,DEFAULT_ZOD_PACKAGE_VERSION,agentTemplateFiles,byokProviderEnvVar,formatEveDependencySpecifier,isEveProject,modelProviderSlug,scaffoldBaseProject};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{getPackageManagerStrategy}from"../../primitives/pm/index.js";import{pathExists,writeTextFile}from"../files.js";import{patchPackageJson}from"./package-json.js";import{resolveVersionToken}from"../version-tokens.js";import{getSupportedModuleBaseName,matchesSupportedModuleBaseName}from"./module-files.js";import{WEB_APP_TEMPLATE_FILES,WEB_APP_TEMPLATE_PACKAGE_JSON}from"../create/web-template.js";import"../create/project.js";import{basename,join,resolve}from"node:path";import{readFile,readdir,writeFile}from"node:fs/promises";const SLACK_CHANNEL_DEFAULT_ROUTE=`/eve/v1/slack`,DEFAULT_SLACK_CONNECTOR_SLUG=`my-agent`,PACKAGE_DEPENDENCY_FIELDS=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`],WEB_NEXT_CONFIG_PATH=`next.config.ts`,WEB_VERCEL_JSON_PATH=`vercel.json`,WEB_VERCEL_JSON_SCHEMA=`https://openapi.vercel.sh/vercel.json`,WEB_COMPETING_NEXT_CONFIG_PATHS=[`next.config.js`,`next.config.mjs`,WEB_NEXT_CONFIG_PATH,`next.config.mts`].filter(e=>e!==WEB_NEXT_CONFIG_PATH),WEB_DEFAULT_VERCEL_SERVICES={web:{entrypoint:`.`,framework:`nextjs`,routePrefix:`/`},eve:{buildCommand:`eve build`,entrypoint:`.`,framework:`eve`,routePrefix:`/_eve_internal/eve`}};function toSlackConnectorSlug(e){return e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function readDependencyVersion(e,t){let n=JSON.parse(await readFile(e,`utf8`));if(!isJsonObject(n)||!isJsonObject(n.dependencies))return;let r=n.dependencies[t];return typeof r==`string`?r:void 0}function packageJsonHasDependency(e,t){for(let n of PACKAGE_DEPENDENCY_FIELDS){let r=e[n];if(isJsonObject(r)&&typeof r[t]==`string`)return!0}return!1}async function hasPackageDependency(e,n){if(!await pathExists(e))return!1;let r=JSON.parse(await readFile(e,`utf8`));return isJsonObject(r)&&packageJsonHasDependency(r,n)}async function isNextJsProject(e){return hasPackageDependency(join(e,`package.json`),`next`)}async function ensurePackageDependency(e,n,i){return!await pathExists(e)||await readDependencyVersion(e,n)===i?[]:(await patchPackageJson(e,{dependencies:{[n]:i}}),[{path:e,dependencies:[n],devDependencies:[],scripts:[]}])}function resolveWebPackageVersions(e){return{evePackageVersion:e?.evePackageVersion??`0.8.
|
|
1
|
+
import{getPackageManagerStrategy}from"../../primitives/pm/index.js";import{pathExists,writeTextFile}from"../files.js";import{patchPackageJson}from"./package-json.js";import{resolveVersionToken}from"../version-tokens.js";import{getSupportedModuleBaseName,matchesSupportedModuleBaseName}from"./module-files.js";import{WEB_APP_TEMPLATE_FILES,WEB_APP_TEMPLATE_PACKAGE_JSON}from"../create/web-template.js";import"../create/project.js";import{basename,join,resolve}from"node:path";import{readFile,readdir,writeFile}from"node:fs/promises";const SLACK_CHANNEL_DEFAULT_ROUTE=`/eve/v1/slack`,DEFAULT_SLACK_CONNECTOR_SLUG=`my-agent`,PACKAGE_DEPENDENCY_FIELDS=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`],WEB_NEXT_CONFIG_PATH=`next.config.ts`,WEB_VERCEL_JSON_PATH=`vercel.json`,WEB_VERCEL_JSON_SCHEMA=`https://openapi.vercel.sh/vercel.json`,WEB_COMPETING_NEXT_CONFIG_PATHS=[`next.config.js`,`next.config.mjs`,WEB_NEXT_CONFIG_PATH,`next.config.mts`].filter(e=>e!==WEB_NEXT_CONFIG_PATH),WEB_DEFAULT_VERCEL_SERVICES={web:{entrypoint:`.`,framework:`nextjs`,routePrefix:`/`},eve:{buildCommand:`eve build`,entrypoint:`.`,framework:`eve`,routePrefix:`/_eve_internal/eve`}};function toSlackConnectorSlug(e){return e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function readDependencyVersion(e,t){let n=JSON.parse(await readFile(e,`utf8`));if(!isJsonObject(n)||!isJsonObject(n.dependencies))return;let r=n.dependencies[t];return typeof r==`string`?r:void 0}function packageJsonHasDependency(e,t){for(let n of PACKAGE_DEPENDENCY_FIELDS){let r=e[n];if(isJsonObject(r)&&typeof r[t]==`string`)return!0}return!1}async function hasPackageDependency(e,n){if(!await pathExists(e))return!1;let r=JSON.parse(await readFile(e,`utf8`));return isJsonObject(r)&&packageJsonHasDependency(r,n)}async function isNextJsProject(e){return hasPackageDependency(join(e,`package.json`),`next`)}async function ensurePackageDependency(e,n,i){return!await pathExists(e)||await readDependencyVersion(e,n)===i?[]:(await patchPackageJson(e,{dependencies:{[n]:i}}),[{path:e,dependencies:[n],devDependencies:[],scripts:[]}])}function resolveWebPackageVersions(e){return{evePackageVersion:e?.evePackageVersion??`0.8.2`,aiPackageVersion:e?.aiPackageVersion??`7.0.0-canary.171`,nextPackageVersion:e?.nextPackageVersion??`16.2.6`,reactPackageVersion:e?.reactPackageVersion??`19.2.6`,reactDomPackageVersion:e?.reactDomPackageVersion??`19.2.6`,streamdownPackageVersion:e?.streamdownPackageVersion??`2.5.0`,zodPackageVersion:e?.zodPackageVersion??`4.4.3`,tsgoPackageVersion:e?.tsgoPackageVersion??`7.0.0-dev.20260523.1`,typesNodePackageVersion:e?.typesNodePackageVersion??`25.9.1`,typesReactPackageVersion:e?.typesReactPackageVersion??`19.2.15`,typesReactDomPackageVersion:e?.typesReactDomPackageVersion??`19.2.3`}}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}async function patchWebPackageJson(e,n){if(!await pathExists(e))return[];let a={...WEB_APP_TEMPLATE_PACKAGE_JSON.dependencies,ai:resolveVersionToken(`aiPackageVersion`,n.aiPackageVersion),eve:formatEveDependencySpecifier(resolveVersionToken(`evePackageVersion`,n.evePackageVersion)),next:resolveVersionToken(`nextPackageVersion`,n.nextPackageVersion),react:resolveVersionToken(`reactPackageVersion`,n.reactPackageVersion),"react-dom":resolveVersionToken(`reactDomPackageVersion`,n.reactDomPackageVersion),streamdown:resolveVersionToken(`streamdownPackageVersion`,n.streamdownPackageVersion),zod:resolveVersionToken(`zodPackageVersion`,n.zodPackageVersion)},o={...WEB_APP_TEMPLATE_PACKAGE_JSON.devDependencies,"@types/node":resolveVersionToken(`typesNodePackageVersion`,n.typesNodePackageVersion),"@types/react":resolveVersionToken(`typesReactPackageVersion`,n.typesReactPackageVersion),"@types/react-dom":resolveVersionToken(`typesReactDomPackageVersion`,n.typesReactDomPackageVersion),"@typescript/native-preview":resolveVersionToken(`tsgoPackageVersion`,n.tsgoPackageVersion)},s=WEB_APP_TEMPLATE_PACKAGE_JSON.scripts;return await patchPackageJson(e,{dependencies:a,devDependencies:o,scripts:s}),[{path:e,dependencies:Object.keys(a),devDependencies:Object.keys(o),scripts:Object.keys(s)}]}function normalizeSlackConnectorSlug(e){return toSlackConnectorSlug((e.trim().replace(/^@/,``).split(`/`).at(-1)??``).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^[^a-z0-9]+/,``).replace(/[^a-z0-9]+$/,``).slice(0,100).replace(/[^a-z0-9]+$/,``)||`my-agent`)}async function deriveSlackConnectorSlug(e,t){if(t!==void 0&&t.length>0&&t!==`.`)return normalizeSlackConnectorSlug(t);try{let t=await readFile(join(e,`package.json`),`utf8`),n=JSON.parse(t);if(typeof n.name==`string`&&n.name.length>0)return normalizeSlackConnectorSlug(n.name)}catch{}return normalizeSlackConnectorSlug(basename(resolve(e))||`my-agent`)}function buildSlackTemplate(e){if(!e.startsWith(`slack/`)||e.length===6)throw Error(`Invalid Slack connector UID "${e}".`);return`import { connectSlackCredentials } from "@vercel/connect/eve";
|
|
2
2
|
import { slackChannel } from "eve/channels/slack";
|
|
3
3
|
|
|
4
4
|
export default slackChannel({
|