eve 0.27.3 → 0.27.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/src/channel/reset-session.d.ts +8 -0
  3. package/dist/src/channel/reset-session.js +1 -0
  4. package/dist/src/channel/routes.d.ts +24 -1
  5. package/dist/src/channel/send.js +1 -1
  6. package/dist/src/channel/types.d.ts +14 -0
  7. package/dist/src/chunks/{use-eve-agent-CbF0l_Fp.js → use-eve-agent-BtkhbY2I.js} +53 -4
  8. package/dist/src/chunks/{use-eve-agent-CgxB9WQv.js → use-eve-agent-NUjD28Iu.js} +53 -4
  9. package/dist/src/cli/dev/tui/blocks.d.ts +7 -0
  10. package/dist/src/cli/dev/tui/blocks.js +3 -3
  11. package/dist/src/cli/dev/tui/message-queue.d.ts +88 -0
  12. package/dist/src/cli/dev/tui/message-queue.js +1 -0
  13. package/dist/src/cli/dev/tui/runner.d.ts +33 -0
  14. package/dist/src/cli/dev/tui/runner.js +1 -1
  15. package/dist/src/cli/dev/tui/subagent-pump.d.ts +9 -0
  16. package/dist/src/cli/dev/tui/subagent-pump.js +1 -1
  17. package/dist/src/cli/dev/tui/terminal-renderer.d.ts +9 -0
  18. package/dist/src/cli/dev/tui/terminal-renderer.js +13 -11
  19. package/dist/src/client/index.d.ts +1 -1
  20. package/dist/src/client/session.d.ts +13 -1
  21. package/dist/src/client/session.js +1 -1
  22. package/dist/src/client/types.d.ts +10 -0
  23. package/dist/src/execution/workflow-runtime.js +1 -1
  24. package/dist/src/internal/application/package.js +1 -1
  25. package/dist/src/internal/nitro/dev-runtime-source-snapshot.js +1 -1
  26. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  27. package/dist/src/protocol/reset-session.d.ts +14 -0
  28. package/dist/src/protocol/reset-session.js +1 -0
  29. package/dist/src/protocol/routes.d.ts +5 -0
  30. package/dist/src/protocol/routes.js +1 -1
  31. package/dist/src/public/channels/eve.d.ts +2 -2
  32. package/dist/src/public/channels/eve.js +1 -1
  33. package/dist/src/public/channels/index.d.ts +1 -1
  34. package/dist/src/public/definitions/channel.d.ts +1 -1
  35. package/dist/src/setup/scaffold/create/project.js +1 -1
  36. package/dist/src/setup/vercel-project-api.d.ts +1 -1
  37. package/dist/src/setup/vercel-project-api.js +1 -1
  38. package/dist/src/svelte/index.js +1 -1
  39. package/dist/src/svelte/use-eve-agent.js +1 -1
  40. package/dist/src/vue/index.js +1 -1
  41. package/dist/src/vue/use-eve-agent.js +1 -1
  42. package/docs/channels/custom.mdx +38 -1
  43. package/docs/extensions.md +98 -18
  44. package/docs/guides/dev-tui.md +9 -2
  45. package/docs/reference/cli.md +1 -1
  46. package/package.json +1 -1
@@ -1 +1 @@
1
- import{isAbortLikeError}from"./errors.js";import{toErrorMessage}from"#shared/errors.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";var SubagentPump=class{#e;#t;#n;#r=new Map;#i=new Map;constructor(e){this.#e=e.client,this.#t=e.view,this.#n=e.formatActionResultError}begin(e){let t=e.data.callId,n=this.#r.get(t);n===void 0?this.#r.set(t,{name:e.data.name,status:`running`,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map}):n.name=e.data.name,this.#t?.markChildToolCallId(t),this.#t?.begin({callId:t,name:e.data.name}),this.#a(e)}settle(e){this.#s(e)}abortAll(){for(let e of this.#i.values())e.abort();this.#i.clear(),this.#r.clear()}#a(r){let i=r.data.callId;if(this.#i.has(i))return;let a=this.#e;if(!a)return;let o=new AbortController;this.#i.set(i,o),(async()=>{let s=!1;try{let e=a.session({sessionId:r.data.childSessionId,streamIndex:0}).stream({signal:o.signal});for await(let t of e){if(o.signal.aborted)break;if(this.#l(i,t),isCurrentTurnBoundaryEvent(t)){s=!0;break}}}catch(n){if(!isAbortLikeError(n)){let e=toErrorMessage(n),r=this.#r.get(i);if(r){let{key:t,step:n}=openCurrentSubagentSection(r);n.message=n.message?`${n.message}\n\nstream error: ${e}`:`stream error: ${e}`,n.finalized=!0,r.currentSectionKey=null,this.#t?.upsertStep({callId:i,subagentName:r.name,sectionKey:t,reasoning:n.reasoning,message:n.message,finalized:!0})}}}finally{this.#i.delete(i)}s&&this.#s(i)})()}#o(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={preparing:0,"approval-requested":1,executing:2,done:3,failed:3,rejected:3};e[n.status]>e[r.status]&&(r.status=n.status),n.input!==void 0&&(r.input=n.input)}else t.tools.set(n.childCallId,i);this.#t?.markChildToolCallId(n.childCallId),this.#t?.upsertTool({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#s(e){let t=this.#r.get(e);if(!(!t||t.status===`settled`)){t.status=`settled`;for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#t?.upsertStep({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null,this.#c(e,t),this.#t?.complete({callId:e})}}#c(e,t){for(let[n,r]of t.tools)r.status===`preparing`&&(t.tools.delete(n),this.#t?.removeTool({callId:e,childCallId:n}))}#l(e,t){let n=this.#r.get(e);if(!n)return;n.status===`settled`&&(n.status=`running`,this.#t?.begin({callId:e,name:n.name}));let r=this.#t,emit=(t,i)=>{r?.upsertStep({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent(),this.#c(e,n);break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#o(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#o(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;switch(t.data.status){case`completed`:a.status=`done`,a.output=i.output;break;case`failed`:a.status=`failed`,a.errorText=this.#n(t);break;case`rejected`:a.status=`rejected`,a.errorText=this.#n(t);break}let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r?.upsertTool(o);break}default:break}}};function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{SubagentPump};
1
+ import{isAbortLikeError}from"./errors.js";import{toErrorMessage}from"#shared/errors.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";var SubagentPump=class{#e;#t;#n;#r=new Map;#i=new Map;constructor(e){this.#e=e.client,this.#t=e.view,this.#n=e.formatActionResultError}begin(e){let t=e.data.callId,n=this.#r.get(t);n===void 0?this.#r.set(t,{name:e.data.name,status:`running`,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map}):n.name=e.data.name,this.#t?.markChildToolCallId(t),this.#t?.begin({callId:t,name:e.data.name}),this.#a(e)}settle(e){this.#s(e)}abortAll(){for(let e of this.#i.values())e.abort();this.#i.clear(),this.#r.clear()}settleAll(){for(let e of this.#r.keys())this.#s(e);for(let e of this.#i.values())e.abort();this.#i.clear()}#a(r){let i=r.data.callId;if(this.#i.has(i))return;let a=this.#e;if(!a)return;let o=new AbortController;this.#i.set(i,o),(async()=>{let s=!1;try{let e=a.session({sessionId:r.data.childSessionId,streamIndex:0}).stream({signal:o.signal});for await(let t of e){if(o.signal.aborted)break;if(this.#l(i,t),isCurrentTurnBoundaryEvent(t)){s=!0;break}}}catch(n){if(!isAbortLikeError(n)){let e=toErrorMessage(n),r=this.#r.get(i);if(r){let{key:t,step:n}=openCurrentSubagentSection(r);n.message=n.message?`${n.message}\n\nstream error: ${e}`:`stream error: ${e}`,n.finalized=!0,r.currentSectionKey=null,this.#t?.upsertStep({callId:i,subagentName:r.name,sectionKey:t,reasoning:n.reasoning,message:n.message,finalized:!0})}}}finally{this.#i.delete(i)}s&&this.#s(i)})()}#o(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={preparing:0,"approval-requested":1,executing:2,done:3,failed:3,rejected:3};e[n.status]>e[r.status]&&(r.status=n.status),n.input!==void 0&&(r.input=n.input)}else t.tools.set(n.childCallId,i);this.#t?.markChildToolCallId(n.childCallId),this.#t?.upsertTool({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#s(e){let t=this.#r.get(e);if(!(!t||t.status===`settled`)){t.status=`settled`;for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#t?.upsertStep({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null,this.#c(e,t),this.#t?.complete({callId:e})}}#c(e,t){for(let[n,r]of t.tools)r.status===`preparing`&&(t.tools.delete(n),this.#t?.removeTool({callId:e,childCallId:n}))}#l(e,t){let n=this.#r.get(e);if(!n)return;n.status===`settled`&&(n.status=`running`,this.#t?.begin({callId:e,name:n.name}));let r=this.#t,emit=(t,i)=>{r?.upsertStep({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent(),this.#c(e,n);break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#o(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#o(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;switch(t.data.status){case`completed`:a.status=`done`,a.output=i.output;break;case`failed`:a.status=`failed`,a.errorText=this.#n(t);break;case`rejected`:a.status=`rejected`,a.errorText=this.#n(t);break}let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r?.upsertTool(o);break}default:break}}};function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{SubagentPump};
@@ -61,6 +61,13 @@ export declare class TerminalRenderer implements AgentTUIRenderer {
61
61
  */
62
62
  renderAgentHeader(options: AgentHeaderOptions): void;
63
63
  readPrompt(options?: AgentTUISessionOptions): Promise<string>;
64
+ /**
65
+ * Consumes the next prompt produced by mid-turn input — the staged Esc
66
+ * steer message, or the whole queue coalesced into one. The runner calls
67
+ * this at a clean turn boundary and submits the result directly; the
68
+ * remembered origin marks the echoed user block with its gutter arrow.
69
+ */
70
+ takeQueuedPrompt(): string | undefined;
64
71
  renderStream(result: AgentTUIStreamResult, options?: AgentTUISessionOptions): Promise<void>;
65
72
  readToolApproval(request: AgentTUIToolApprovalRequest, options?: AgentTUISessionOptions): Promise<AgentTUIToolApprovalResponse>;
66
73
  readInputQuestion(question: AgentTUIInputQuestion, options?: AgentTUISessionOptions): Promise<AgentTUIInputQuestionResponse | undefined>;
@@ -129,6 +136,8 @@ export declare class TerminalRenderer implements AgentTUIRenderer {
129
136
  * connector (` ⎿ /model cancelled.`), Claude Code's sub-result grammar.
130
137
  */
131
138
  renderCommandResult(text: string): void;
139
+ /** Last server session id the runner reported; named in the parting line. */
140
+ setSessionId(sessionId: string): void;
132
141
  shutdown(): void;
133
142
  /** The log sources the transcript currently renders. */
134
143
  logDisplayMode(): LogDisplayMode;
@@ -1,13 +1,15 @@
1
- import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{interruptedError}from"./errors.js";import{FileContentCache}from"./file-content-cache.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{initialModelEditorState,transitionModelEditor}from"./model-editor.js";import{promptPlaceholder}from"./prompt-placeholder.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{enterBadge,renderAcknowledgeQuestion,renderFlowPanel,renderModelEditorQuestion,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{TurnClock}from"./turn-clock.js";import{allTodoItemsSettled,readTodoToolItems,renderFinishedTodoRows,renderTodoPanelRows}from"./todo-panel.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{inspectError}from"#internal/logging.js";import{eveVersionTag}from"#cli/banner.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{LiveRegion}from"#cli/ui/live-region.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";import{readGatewayServiceTier}from"#shared/gateway-service-tier.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e,t){return e?`Interrupted`:t?`Ready`:`Done`}const STATUS={processing:`Working…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=[];#m=new Map;#h=new Set;#g=[];#_=new Set;#v=new Map;#y=0;#b=new Map;#x=new FileContentCache;#S=new Set;#C;#w=!1;#T;#E=[];#D;#O=0;#k;#A;#j=``;#M=0;#N=new PromptHistory;#P=!1;#F;#I=!1;#L=Date.now();#R=!1;#z=new TurnClock;#B=EMPTY_LINE;#V=!1;#H={kind:`idle`};#U;#W=STATUS.processing;#G;#K=`eve`;#q=!1;#J=!1;#Y=!1;#X=!1;#Z=!0;#Q=0;#$=Date.now();#ee;#te;#ne;#re=!1;#ie;#ae=``;#oe=new StringDecoder(`utf8`);#se;#ce;#le;#ue=!1;#de=!1;#fe;#pe;#me;#he;#ge;#_e;#ve;#ye=``;#be=``;#xe;#Se;#Ce=0;#we;#Te;#Ee;#De;#Oe;#ke;#Ae;#je;setupFlow={begin:(e,t)=>this.#Le(e,t),end:e=>this.#Re(e?.preserveDiagnostics??!0),readSelect:e=>this.#ze(e),readEditableSelect:e=>this.#Ve(e),readProviderPicker:e=>this.#He(e),readModelEditor:e=>this.#Ue(e),readText:e=>this.#We(e),readAcknowledge:e=>this.#Ge(e),readChoice:e=>this.#Be(e),setStatus:e=>this.#$e(e),renderLine:(e,t)=>this.#et(e,t),renderOutput:e=>this.#tt(e),waitForInterrupt:()=>this.#Xe()};constructor(t){this.#e=t?.input??process.stdin,this.#t=t?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:t?.color??!0,unicode:t?.unicode??detectUnicode()}),this.#i=t?.tools??`auto-collapsed`,this.#a=t?.reasoning??`auto-collapsed`,this.#o=t?.subagents??`auto-collapsed`,this.#s=t?.connectionAuth??`full`,this.#c=t?.assistantResponseStats??`tokensPerSecond`,this.#me=t?.contextSize,this.#l=t?.captureForeignOutput??this.#t===process.stdout,this.#u=t?.diagnostics,this.#f=t?.logs??`none`,this.#d=t?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#K=e.name,this.#C=e,this.#nt();let t=this.#Ut().join(`
2
- `);if(this.#w){t!==this.#T&&(this.#T=t,this.#_t({kind:`agent-header`,body:t,live:!1})),this.#Rt();return}this.#w=!0,this.#T=t,this.#n.flush(this.#Ut(),[])}async readPrompt(e){this.#nt(e),this.#gt(),this.#yt(),this.#P=!0,this.#I=!0,this.#H={kind:`idle`},this.#W=``;let r=lineOf(stripPromptControlCharacters(e?.initialDraft??this.#B.text));return this.#B=EMPTY_LINE,this.#N.begin(r.text),this.#Me(r),this.#F=typeaheadFor(this.#d,r.text),this.#dt(),this.#Rt(),await new Promise((e,i)=>{this.#U=i;let apply=e=>{r=e,this.#pt(),this.#Me(r),this.#F=typeaheadFor(this.#d,e.text,this.#F),this.#Rt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#F=void 0,this.#ft(),this.#rt(),i(interruptedError())},suggestions=()=>this.#F!==void 0&&isTypeaheadOpen(this.#F)?this.#F:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ie=i=>{let a=applyLineEditorKey(r,i,{multiline:!0});if(a!==void 0){apply(a);return}switch(i.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#F=moveTypeaheadSelection(e,-1),this.#Rt();break}let t=movePromptLine(r,`up`);t===void 0?recall(this.#N.previous(r.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#F=moveTypeaheadSelection(e,1),this.#Rt();break}let t=movePromptLine(r,`down`);t===void 0?recall(this.#N.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#F=dismissTypeahead(e),this.#Rt());break}case`enter`:{let i=highlighted(),a=i!==void 0&&parsePromptCommand(r.text)===null?typeaheadCompletion(i).trimEnd():r.text;if(a.trim().length===0)break;this.#F=void 0,this.#N.add(a),this.#P=!1,this.#ft(),this.#W=STATUS.processing,isPromptControlCommand(a)?this.#_t({kind:`command`,body:stripTerminalControls(a.trim()),live:!1}):(this.#ht(),this.#vt(a),this.#we=a,this.#z.arm()),this.#Me(EMPTY_LINE),this.#Rt(),this.#at(),e(a);break}case`ctrl-d`:r.text.length===0?interrupt():apply(deleteForward(r));break;case`ctrl-l`:this.#Vt();break;case`ctrl-r`:this.#Rt();break;case`ctrl-c`:r.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#it()})}#Me(e){this.#j=e.text,this.#M=e.cursor}async renderStream(e,t){this.#nt(t),this.#h.clear(),this.#P=!1,this.#H.kind!==`waiting`&&(this.#H={kind:`waiting`,startedAtMs:Date.now()}),this.#W=this.#O>0?STATUS.connectionAuth:STATUS.processing,this.#bt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#u?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#z.armed&&this.#z.arm(),this.#X=!1,this.#fe=void 0,this.#pe=void 0,this.#he=void 0,this.#ge=void 0,this.#_e=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#mt(),this.#V=!0,this.#Rt();let r=new Promise(e=>{this.#le=e});this.#ie=e=>this.#ut(e),this.#it();let i={text:new Map,reasoning:new Map,tools:new Map};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#X)break;this.#Et(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#xt(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#xt(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#le=void 0,this.#X&&e.abort?.(),this.#at(),this.#gt(),this.#V=!1,this.#H.kind===`waiting`&&(this.#H={kind:`idle`}),this.#W=completedTurnStatus(this.#X,t?.continueSession===!0),this.#Nt(i),this.#X&&this.#Mt(),this.#Tt(),this.#u?.reportStats(),this.#Rt(),t?.continueSession||this.#rt()}}async readToolApproval(e,t){return this.#nt(t),this.#gt(),this.#P=!1,this.#H={kind:`idle`},this.#W=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#X=!1,this.#Rt(),await new Promise((t,n)=>{this.#U=n,this.#ie=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#ht(),this.#W=STATUS.processing,this.#at(),this.#Rt(),t({approved:!0})):n===`n`&&(this.#ht(),this.#W=STATUS.processing,this.#Pe(e.toolCallId),this.#at(),this.#Rt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#Rt();break;case`ctrl-c`:this.#X=!0,this.#rt(),n(interruptedError());break;default:break}},this.#it()})}async readInputQuestion(e,t){this.#nt(t),this.#gt(),this.#P=!1,this.#I=!1,this.#H={kind:`idle`},this.#X=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`overlay`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,overlayPanel=t=>renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#Z},this.#r,t),renderTextSection=()=>{this.#Ct({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#r),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#dt():(this.#ft(),this.#pt())};s===`overlay`?(s=`overlay`,this.#P=!1,this.#wt(o),this.#Te=overlayPanel,this.#W=``,syncFreeformCaret(),this.#Rt()):(s=`text`,this.#Te=void 0,renderTextSection(),this.#P=!0,this.#Me(l),this.#W=``,this.#dt(),this.#Rt());let finalize=t=>{this.#Te=void 0,this.#Ct({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#r.colors.dim(this.#r.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#P=!1,this.#ht(),this.#W=STATUS.processing,this.#ft(),this.#at(),this.#Rt();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Te=void 0,this.#Ct({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#r.colors.dim(this.#r.glyph.elbow)} ${this.#r.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#P=!1,this.#W=``,this.#ft(),this.#at(),this.#Rt(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#Rt())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#U=r,u=t,this.#ie=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#pt(),s===`text`&&this.#Me(l),this.#Rt();return}this.#X=!0,this.#Te=void 0,this.#ft(),this.#rt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#Rt();return}if(s===`overlay`){switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#pt(),this.#Rt();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#pt(),this.#Rt());break}if(t.type===`text`&&/^[1-9]$/u.test(t.value)){let e=Number(t.value)-1;e<n.length?selectOptionAt(e):e===n.length&&i&&(c=e,syncFreeformCaret(),this.#Rt())}break}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#pt(),this.#Me(l),this.#Rt();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#pt(),this.#Me(l),this.#Rt());break}case`enter`:{let t=resolveQuestionText(l.text,e);if(t===void 0)break;u(finalize(t));break}case`escape`:if(l.text.length>0){l=EMPTY_LINE,this.#pt(),this.#Me(l),this.#Rt();break}dismiss();break;default:break}},this.#it()})}upsertSubagentStep(e){if(this.#u?.recordSubagentDispatch(e.callId),this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#St(e.callId,e.subagentName),this.#o===`collapsed`){this.#Rt();return}this.#Ct({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#o!==`full`,live:!e.finalized}),this.#Rt()}}upsertSubagentTool(e){if(this.#u?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#u?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#o===`hidden`)return;if(this.#St(e.callId,e.subagentName),this.#o===`collapsed`){this.#Rt();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#At({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#Ct(r),this.#Ne(e.callId),this.#Rt()}#Ne(e){applyCohortLiveness(this.#p.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#wt(subagentToolSectionId(e.callId,e.childCallId)),this.#Rt()}subagents={begin:e=>this.beginSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#o===`hidden`)return;this.#St(e.callId,e.name);let t=this.#m.get(subagentHeaderId(e.callId));t?.status===`done`&&delete t.status,this.#Rt()}completeSubagent(e){let t=this.#m.get(subagentHeaderId(e.callId));t!==void 0&&(t.status=`done`,this.#Rt())}markChildToolCallId(e){this.#_.add(e);let t=this.#v.get(e);t!==void 0&&(this.#wt(t),this.#v.delete(e),this.#Rt())}#Pe(e){let t=this.#m.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#Ct({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#Rt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#O)return;let n=this.#O>0;this.#O=t,t>0?(this.#W=STATUS.connectionAuth,this.#Rt()):n&&(this.#W=STATUS.processing,this.#Rt())}setVercelStatus(e){this.#k=e,this.#Rt()}setRemoteConnectionStatus(e){this.#A=e,this.#Rt()}reset(){this.#p=[],this.#m.clear(),this.#h.clear(),this.#D=void 0,this.#E.length=0,this.#g.length=0,this.#w=!1,this.#T=void 0,this.#Fe(),this.#R=!1,this.#we=void 0,this.#Se=void 0,this.#O=0,this.#fe=void 0,this.#pe=void 0,this.#he=void 0,this.#ge=void 0,this.#_e=void 0,this.#q&&(this.#n.clearAll(),this.#Rt())}renderSessionBoundary(){this.#yt(),this.#Fe();let e=this.#r.colors,t=this.#r.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#_t({kind:`session-boundary`,body:n,live:!1}),this.#Rt()}#Fe(){this.#_.clear(),this.#v.clear(),this.#S.clear(),this.#b.clear(),this.#Oe=void 0,this.#ke=void 0,this.#x.clear(),this.#z.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#nt(),this.#_t({kind:`notice`,body:t,live:!1}),this.#Rt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#u?.append({source:`sandbox`,detail:t}),this.#nt(),this.#_t({kind:`sandbox`,body:t,live:!1}),this.#Rt())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#Ie();return}this.#nt(),this.#De=t,this.#Rt()}clearSetupWarning(){this.#Ie()}#Ie(){this.#De!==void 0&&(this.#De=void 0,this.#Rt())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#nt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#_t(r),this.#Rt()}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#nt(),this.#_t({kind:`result`,body:t,live:!1}),this.#Rt())}#Le(e,t=`spinner`){this.#nt(),this.#P=!1,this.#H={kind:`idle`},this.#W=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ee={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#mt(),this.#Rt()}#Re(e){this.#Ae=void 0,this.#Qe();let t=this.#Ee;if(t!==void 0){if(this.#Ee=void 0,this.#gt(),e){let e=[];for(let n of t.lines){if(n.evidence===!0){e.push(n.text);continue}(n.tone===`warning`||n.tone===`error`)&&(e.length>0&&this.#_t({kind:`flow`,title:`info`,body:e.join(`
3
- `),live:!1}),this.#_t({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#Rt()}}async#ze(e){let t=this.#Ke(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a={options:i,searchAction:r,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(a.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(a.initialValues=e.initialValues);let o=initialSelectState(a),s,c=!1,l=0,isCurrentSearch=e=>e===l,clearSearch=()=>{l+=1,c=!1,o=reduceSelect(o,{type:`clear`},{options:i,searchAction:r,submitRow:n}),this.#Rt()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#Rt();try{let s=await t(e);if(!isCurrentSearch(a))return;let c=o.filter;i=s,o={...initialSelectState({options:s,searchAction:r,submitRow:n}),filter:c}}catch(e){isCurrentSearch(a)&&(s=toErrorMessage(e))}finally{isCurrentSearch(a)&&(c=!1,this.#Rt())}},u=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#Gt()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#Rt(),await this.#Ye((t,a)=>{let close=e=>{l+=1,a(e)};if(c){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#Rt();return}let u={key:t,options:i,searchAction:r,select:o},d=reduceSetupSelectInput(n?{...u,kind:e.kind,required:e.required}:{...u,kind:e.kind});switch(d.kind){case`cancel`:close(void 0);return;case`repaint`:this.#Rt();return;case`update`:o=d.select,s=void 0,this.#Rt();return;case`submit`:{let e=searchActionQuery(d.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(d.values);return}loadSearch(e,t);return}case`error`:s=d.message,this.#Rt();return;case`ignore`:return}}).promise}#Be(e){this.#nt();let t=this.#qe();t.status={kind:`progress`,text:stripTerminalControls(e.status)};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#Rt();let r=this.#Ye((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.#Rt();return;case`repaint`:this.#Rt();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#Ve(e){let t=this.#Ke(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#Z,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#dt():(i=lineOf(``),this.#ft())};return syncEditableRow(),this.#Rt(),await this.#Ye((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#pt(),this.#Rt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#Rt()},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.#Rt();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.#Rt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#ft()).promise}async#He(e){let t=this.#Ke(),n=initialProviderPickerState(e.options,e.initialValue),r,cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor),r=e.options.find(e=>e.value===t);if(r!==void 0)return enterBadge(this.#r,r.checked===!0?`change`:void 0)};t.question=t=>{let r=cursorBadge(),i={kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#Z,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#r,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#dt():this.#ft()};return syncCaret(),this.#Rt(),await this.#Ye((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#Rt();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#Rt();return;case`validate`:{n=o.state,syncCaret(),this.#Rt();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#Rt();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#pt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#ft()}).promise}async#Ue(e){let t=this.#Ke(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#r,t),this.#Rt(),await this.#Ye((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#Rt();return;case`cancel`:r(void 0);return;case`settle`:r(i.result);return}},i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:i.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#Rt();return;case void 0:break}if(t.type===`left`||t.type===`right`){dispatch({type:`adjust`,direction:t.type});return}if(t.type===`tab`){dispatch({type:`adjust`,direction:`right`});return}if(t.type===`backspace`){dispatch({type:`backspace`});return}if(t.type===`text`)for(let e of t.value.replaceAll(`
4
- `,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#We(e){let t=this.#Ke(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder!==void 0&&(i.placeholder=e.placeholder),e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#r,t,this.#Z)},this.#dt(),this.#Rt(),await this.#Ye((t,i)=>{let apply=e=>{n=e,r=void 0,this.#pt(),this.#Rt()},a=applyLineEditorKey(n,t);if(a!==void 0){apply(a);return}switch(t.type){case`ctrl-c`:case`escape`:i(void 0);return;case`ctrl-r`:this.#Rt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#Rt();return}i(t);return}default:return}},()=>this.#ft()).promise}async#Ge(e){let t=this.#Ke();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#Rt(),await this.#Ye((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#Rt();return;default:return}}).promise}#Ke(){return this.#nt(),this.#P=!1,this.#H={kind:`idle`},this.#W=``,this.#qe()}#qe(){return this.#Ee===void 0&&(this.#Ee={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Ee}#Je(){this.#Ee?.implicit===!0?this.#Ee=void 0:this.#Ee!==void 0&&(this.#Ee.question=void 0,this.#Ee.hideLinesWhileQuestion=!1),this.#ie=void 0,this.#at(),this.#Ee!==void 0&&this.#Ze(),this.#Rt()}#Ye(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Je(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Je(),i(e))};return this.#lt(),this.#ie=t=>e(t,settle,reject),this.#it(),{promise:a,settle}}#Xe(){let e,t=new Promise(t=>{e=t});return this.#Ae=e,this.#Ze(),{promise:t,dispose:()=>{this.#Ae===e&&(this.#Ae=void 0,this.#Qe())}}}#Ze(){if(this.#Ae===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#Ae;this.#Ae=void 0,this.#Qe(),e?.();return}e.type===`ctrl-r`&&this.#Rt()};this.#je=consumer,this.#lt(),this.#ie=consumer,this.#it()}#Qe(){this.#je!==void 0&&(this.#ie===this.#je&&this.#at(),this.#je=void 0)}#$e(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e)}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis)};if(this.#Ee!==void 0){this.#Ee.status=t,t===void 0&&(this.#Ee.preview=void 0),this.#Rt();return}if(!(this.#P||this.#V)){if(t===void 0){this.#H={kind:`idle`},this.#G=void 0,this.#gt(),this.#Rt();return}this.#nt(),this.#ht(),this.#G=t.text,this.#Rt()}}#et(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Ee;if(r!==void 0){if(r.preview=void 0,t===`warning`||t===`error`)for(let e of r.outputBuffer)r.lines.push({text:e,tone:`info`,evidence:!0});r.outputBuffer=[],r.lines.push({text:n,tone:t}),this.#Rt();return}this.#nt(),this.#_t({kind:`flow`,title:t,body:n,live:!1}),this.#Rt()}#tt(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Ee;if(n===void 0){this.#et(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#Rt()}shutdown(){this.#rt(),this.#J&&!this.#Y&&(this.#Y=!0,this.#t.write(`${this.#r.colors.dim(eveVersionTag())}\n`))}#nt(e){this.#K=e?.title??this.#K,e?.contextSize!==void 0&&(this.#me=e.contextSize),!this.#q&&(this.#q=!0,this.#J=!0,this.#n.reset(),this.#n.hideCursor(),this.#an(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#ce=()=>this.#Rt(),this.#t.on(`resize`,this.#ce))}#rt(){let e=this.#U;if(this.#U=void 0,e?.(interruptedError()),this.#at(),this.#ft(),this.#gt(),this.#ne!==void 0&&(clearTimeout(this.#ne),this.#ne=void 0),this.#re=!1,this.#q){this.#mn();for(let e of this.#p)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#Rt(),this.#n.clear(),this.#n.showCursor(),this.#on(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#ce&&=(this.#t.off(`resize`,this.#ce),void 0),this.#q=!1}}#it(){this.#e.off(`data`,this.#ot),this.#e.on(`data`,this.#ot),this.#ae.length>0&&queueMicrotask(()=>{this.#ie!==void 0&&this.#ae.length>0&&(this.#ct(),this.#st())})}#at(){this.#e.off(`data`,this.#ot),this.#lt(),this.#ie=void 0}#ot=e=>{this.#lt(),this.#ae+=this.#oe.write(e),this.#ct(),this.#st()};#st(){if(this.#ae===`\x1B`){this.#se=setTimeout(()=>{this.#ae===`\x1B`&&(this.#ae=``,this.#ie?.({type:`escape`}))},30),this.#se.unref?.();return}if(isIncompletePaste(this.#ae)){let e=this.#ae;this.#se=setTimeout(()=>{if(this.#ae!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#ae=``,t.length>0&&this.#ie?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#se.unref?.()}}#ct(){for(;this.#ae.length>0;){let e=nextKey(this.#ae);if(e.incomplete)return;this.#ae=this.#ae.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#ie?.(e.key)}}#lt(){this.#se&&=(clearTimeout(this.#se),void 0)}#ut(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#Rt();break;case`ctrl-c`:this.#X||(this.#X=!0,this.#H={kind:`idle`},this.#W=`Interrupted`,this.#le?.(),this.#Rt());break;case`enter`:break;default:{let t=applyLineEditorKey(this.#B,e,{multiline:!0});t!==void 0&&(this.#B=t,this.#Rt());break}}}#dt(){this.#ft(),this.#pt(),this.#ee=setInterval(()=>{this.#Z=!this.#Z,this.#Rt()},500),this.#ee.unref?.()}#ft(){this.#ee&&=(clearInterval(this.#ee),void 0),this.#Z=!0}#pt(){this.#Z=!0}#mt(){this.#gt(),this.#te=setInterval(()=>{this.#Q+=1,this.#Rt()},90),this.#te.unref?.()}#ht(){let e=Date.now();this.#$=e,this.#H={kind:`waiting`,startedAtMs:e},this.#mt()}#gt(){this.#te&&=(clearInterval(this.#te),void 0)}#_t(e){e.id!==this.#Se?.id&&this.#mn(),e.updateSeq=++this.#y,this.#p.push(e),e.id&&this.#m.set(e.id,e)}#vt(e){this.#R=!0,this.#_t({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#Rt()}#yt(){let e=this.#z.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#Xt(e.elapsedMs)}`,n=this.#pe??0;if(this.#me!==void 0&&this.#me>0&&n>0){let e=Math.round(n/this.#me*100);t+=` ${this.#r.glyph.dot} ${e}% context`}this.#_t({kind:`turn-stats`,body:t,live:!1})}#bt(e){if(e!=null){if(this.#we===e){this.#we=void 0;return}this.#_t({kind:`user`,body:stripTerminalControls(e),live:!1})}}#xt(e,t,n={}){let r=stripTerminalControls(e),i=stripTerminalControls(t),a=n.detail===void 0?void 0:stripTerminalControls(n.detail),o=n.hint===void 0?void 0:stripTerminalControls(n.hint),s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#u?.append(o===void 0?s:{...s,hint:o});let c={kind:`error`,title:r,body:i,live:!1};o!==void 0&&(c.hint=o),a!==void 0&&(c.detail=this.#u===void 0?a:`details: ${this.#u.displayPath}`),this.#_t(c),this.#Rt()}#St(e,t){if(this.#S.has(e))return;this.#S.add(e);let n=stripTerminalControls(t),r=this.#b.get(n)??[];if(r.push(e),this.#b.set(n,r),r.length===2){let e=this.#m.get(subagentHeaderId(r[0]));e!==void 0&&(e.subtitle=`#1`)}let i={id:subagentHeaderId(e),kind:`subagent`,subagentCallId:e,title:n,live:!0};r.length>1&&(i.subtitle=`#${r.length}`),this.#_t(i)}#Ct(e){if(e.id&&this.#h.has(e.id))return;let t=e.id?this.#m.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#y;return}this.#_t(e)}#wt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#Tt(){for(let e of this.#p)e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#Et(e,t,n){switch(e.type){case`step-finish`:this.#u?.recordStepUsage(e.usage),e.usage!==void 0&&this.#z.addUsage(e.usage),this.#Nt(n),this.#Lt(e.usage),this.#Rt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#Dt(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;n.text.set(e.id,r),this.#Dt(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);if(n.reasoning.set(e.id,r),t.reasoning===`full`){this.#Ot(e.id,r,!0,t);break}break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;if(t.reasoning===`full`){this.#Ot(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#kt({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#u?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#kt({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;this.#kt({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#It(e.toolCallId,n);if(r===void 0)break;this.#kt({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#It(e.toolCallId,n);if(this.#u?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#kt({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#It(e.toolCallId,n);if(r===void 0)break;this.#kt({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#xt(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`finish`:this.#Lt(e.usage),this.#Rt();break}}#Dt(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#Ct({id:e,kind:`assistant`,body:r,live:n}),this.#Rt())}#Ot(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Ct({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#Rt())}#kt(e,t,n){if(n.tools.set(e.toolCallId,e),this.#_.has(e.toolCallId)||this.#Pt(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#v.set(e.toolCallId,r);let i=this.#At(e);this.#Ct(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#Ft(n),this.#Rt()}#At(e){e.output!==void 0&&this.#x.observeRead(e.output);let t={};this.#jt(e.toolName)&&(t.isSubagent=!0);let n=readWriteFileInput(e.toolName,e.input);if(n===void 0)return t.isSubagent===!0?t:void 0;let r=this.#x.observeWrite({path:n.path,content:n.content,callId:e.toolCallId});r!==void 0&&(t.previousContent=r);let i=writeExistedFlag(e.output);return i!==void 0&&(t.existed=i),t}#jt(e){let t=this.#C?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#Mt(){for(let e of this.#p)e.kind!==`tool`&&e.kind!==`subagent-tool`||e.status===`running`&&(e.status=`error`,e.result=`interrupted`,e.live=!1)}#Nt(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#v.get(t)??toolSectionId(t);this.#wt(r),this.#v.delete(t)}}#Pt(e){let t=readTodoToolItems(e.toolName,e.input);if(t===void 0)return!1;if(t.length>0&&allTodoItemsSettled(t)){let e=JSON.stringify(t);this.#ke!==e&&(this.#ke=e,this.#_t({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#rn(),this.#r).join(`
5
- `),live:!1})),this.#Oe=void 0}else this.#Oe=t.length>0?t:void 0,this.#ke=void 0;return this.#Rt(),!0}#Ft(e){let t=[];for(let n of e.tools.values()){if(this.#_.has(n.toolCallId))continue;let e=this.#v.get(n.toolCallId)??toolSectionId(n.toolCallId),r=this.#m.get(e);r?.kind===`tool`&&t.push({block:r,active:isActiveToolStatus(n.status)})}applyCohortLiveness(t)}#It(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#v.get(e)??toolSectionId(e),i=this.#m.get(r);if(!(i===void 0||i.kind!==`tool`))return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.toolName??i.title??`tool`}}#Lt(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#fe=(t??0)+(n??0)),this.#pe=t??this.#pe,this.#he=n??this.#he,this.#he!=null&&this.#_e!==void 0){let e=(Date.now()-this.#_e)/1e3;e>0&&(this.#ge=this.#he/e)}}#Rt(){if(this.#q){if(this.#ue){this.#de=!0;return}this.#ue=!0;try{do this.#de=!1,this.#zt();while(this.#de)}finally{this.#ue=!1}}}#zt(){if(!this.#q)return;let e=this.#rn(),t=this.#Jt(e),n=Math.max(1,this.#in()-t.length),r=[],i=this.#D,a=groupToolBlocksForDisplay(this.#p),o=0;for(;o<a.length&&a[o].display.live===!1;)o+=1;if(o>0){let e=new Set(a.slice(0,o).flatMap(e=>e.members));for(let t=this.#p.length-1;t>=0;--t)e.has(this.#p[t])&&this.#p.splice(t,1)}for(let t of a.slice(0,o)){for(let e of t.members)this.#g.push(e),e.id&&(this.#h.add(e.id),this.#m.delete(e.id));if(this.#gn(t.display))continue;let n=this.#Wt(t.display,e,i);i=previousBlockOf(t.display),this.#D=i,r.push(...n),this.#E.push(...n)}let s=[];for(let{display:t}of a.slice(o)){if(this.#gn(t))continue;let n=this.#Wt(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)s.push({block:t,row:n[e]})}let c=[...clipLiveRows(s.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,c):this.#n.update(c)}#Bt(){if(!this.#q)return;let e=this.#rn(),t=this.#Jt(e),n=Math.max(1,this.#in()-t.length),r=this.#D,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#p)){if(this.#gn(t))continue;let n=this.#Wt(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.#Ut(),...this.#E],a)}logDisplayMode(){return this.#f}setLogDisplayMode(e){e!==this.#f&&(this.#f=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#Ht(),this.#q&&this.#Bt())}flushDelayedDevBuildErrors(){let e=this.#xe;e!==void 0&&(this.#xe=void 0,this.#_t({kind:`log`,title:`stderr`,body:e,live:!0}),this.#Rt())}#Vt(){this.#re=!0,this.#ne!==void 0&&clearTimeout(this.#ne),this.#ne=setTimeout(()=>{this.#re=!1,this.#ne=void 0,this.#Rt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#f)),this.#Rt()}#Ht(){let e=this.#rn();this.#E.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#g,{logCoalescing:`runs`})){if(this.#gn(n))continue;let r=this.#Wt(n,e,t);t=previousBlockOf(n),this.#E.push(...r)}this.#D=t}#Ut(){let e=this.#C;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#rn()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#Wt(e,t,n){let r={activityPulse:this.#Kt(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#Gt(){return this.#r.spinner[this.#Q%this.#r.spinner.length]??``}#Kt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#qt(e,t){return e.indicator.kind===`spinner`?{glyph:this.#Gt(),color:`yellow`}:{glyph:this.#Kt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#Jt(e){let n=this.#r.colors,r=[``];if(this.#Te!==void 0)return r.push(...this.#Te(e),``),this.#en(r,e),r;let a=this.#Ee;if(a!==void 0){let t=this.#qt(a,a.status),n=a.status===void 0?void 0:{...a.status,indicator:t},i;if(a.question!==void 0){let t=a.question(e);i={kind:`question`,rows:t},n!==void 0&&(i={kind:`question`,rows:t,status:n})}else n===void 0?i=a.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:a.preview,indicator:t}:(i={kind:`status`,status:n},a.preview!==void 0&&(i={kind:`status`,status:n,preview:a.preview}));let o={title:a.title,lines:a.hideLinesWhileQuestion===!0?[]:a.lines,content:i};return r.push(...renderFlowPanel(o,this.#r,e)),this.#tn(r,e),r}if(this.#Oe!==void 0&&r.push(...renderTodoPanelRows({items:this.#Oe,width:e,theme:this.#r,working:this.#V||this.#H.kind===`waiting`,pulse:this.#Kt(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}),``),this.#De!==void 0&&r.push(...renderAttentionRows(this.#De,e,this.#r),``),this.#P){let i=this.#F===void 0?void 0:inlineCommandHint(this.#F);i===void 0&&this.#F!==void 0&&isTypeaheadOpen(this.#F)&&r.push(...renderCommandSuggestions(this.#F,this.#r,e));let a=isPromptControlCommand(this.#j),o=i?n.dim(` ${i}`):``,l=[];this.#en(l,e);let d=Math.max(1,this.#in()-1-r.length-1-l.length),f={text:this.#j,cursor:this.#M,width:e,theme:this.#r,caretVisible:this.#Z,isCommand:a,ghost:o,maxRows:d};return this.#I&&this.#j.length===0&&(f.placeholder=this.#R?``:promptPlaceholder(Date.now()-this.#L)),r.push(...promptInputRows(f)),r.push(...l),r}let o=this.#H.kind===`waiting`&&this.#G===void 0;if(this.#V||o){r.push(this.#Yt(e)),this.#Qt(r,e);let t=[];return this.#en(t,e),!this.#V&&t.length>0&&r.push(``),r.push(...t),r}if(this.#B.text.length>0)return this.#$t(r,e,{inert:!1}),this.#en(r,e),r;let l=this.#G??(this.#W.length>0?this.#W:`Ready`),d=this.#nn(),f=n.dim(this.#r.glyph.dot),p=d?`${f} ${l} ${n.dim(this.#r.glyph.dot)} ${d}`:`${f} ${l}`;return r.push(clip(p,e)),this.#en(r,e),r}#Yt(e){let t=this.#r.colors,n=this.#Kt(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),r=this.#H,i=this.#z.startedAtMs??this.#_e??(r.kind===`waiting`?r.startedAtMs:Date.now()),a=Date.now()-i,o=`${typewriterText(`Working for`,a,80)} ${this.#Xt(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#Xt(e){return`${formatTurnDuration(e)}${this.#Zt()}`}#Zt(){let{inputTokens:e,outputTokens:t}=this.#z.usage;return e===0&&t===0?``:` ${this.#r.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#r.glyph)}`}#Qt(e,t){this.#V&&this.#$t(e,t,{inert:!0})}#$t(e,t,n){e.push(``);let r={text:this.#B.text,cursor:this.#B.cursor,width:t,theme:this.#r,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#B.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#en(e,t){let n=this.#A===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#r,width:r};this.#re&&(i.logLevel=this.#f);let a=this.#C?.serverUrl;if(a!==void 0&&this.#A===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#C?.info?.agent.model;o?.id!==void 0&&(i.model=o.id),o?.reasoning!==void 0&&o.reasoning!==`provider-default`&&(i.reasoning=o.reasoning),readGatewayServiceTier(o?.providerOptions).kind===`priority`&&(i.fastMode=!0);let s=o?.endpoint;s!==void 0&&(i.endpoint=s),this.#k!==void 0&&(i.vercel=this.#k),this.#A!==void 0&&(i.remote=this.#A);let c=buildStatusLine(i);c!==void 0&&e.push(clip(`${n}${c}`,t))}#tn(e,t){if(this.#A===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#A,theme:this.#r,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#nn(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#fe,outputTokens:this.#he,tokensPerSecond:this.#ge},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#rn(){return Math.max(20,this.#t.columns||80)}#in(){return Math.max(8,this.#t.rows||24)}#an(){if(this.#ve!==void 0||!this.#l)return;this.#ye=``,this.#be=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#cn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#u?.subscribeLogRecords(e=>this.#sn(e)),this.#ve=()=>{this.#u?.unsubscribeLogRecords(),e(),t()}}#on(){let e=this.#ve;e!==void 0&&(this.#ve=void 0,e(),this.#ye.length>0&&(this.#u?.append({source:`stdout`,detail:this.#ye}),this.#hn(`stdout`)&&process.stdout.write(`${this.#ye}\n`),this.#ye=``),this.#be.length>0&&(this.#u?.append({source:`stderr`,detail:this.#be}),this.#hn(`stderr`)&&process.stderr.write(`${this.#be}\n`),this.#be=``))}#sn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#un(`[eve:${e.namespace}] ${e.message}${t}`),this.#Rt()}#cn(e,t){let n=(e===`stdout`?this.#ye:this.#be)+t,r=n.lastIndexOf(`
6
- `),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#ye=i:this.#be=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#u?.append({source:e,detail:a}),e===`stdout`?this.#ln(a):this.#un(a),this.#Rt())}#ln(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
7
- `);t=[],e.trim().length!==0&&this.#_t({kind:`log`,title:`stdout`,body:e,live:!0})};for(let n of e.split(`
8
- `)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#_t({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#fn(r,n.trimEnd())}flushPending()}#un(e){let t=e.split(`
9
- `),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#u===void 0){this.#_t({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#u.displayPath);if(t.kind===`inline`){this.#_t({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#_t({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#_t({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
10
- `);r.trim().length>0&&this.#_t({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
11
- `);this.#dn(i)}#dn(e){if(this.#f===`all`){if(e.trim().length===0)return;this.#_t({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#xe=e}#fn(e,t){let n=this.#pn();if(e.kind===`failed`){this.#dn(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#Ce}`;this.#Ce+=1,this.#Se={id:r,summary:t},this.#_t({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}if(n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#xe=void 0);return}e.kind===`rebuilt`&&(this.#xe=void 0),this.#_t({kind:`log`,title:`stdout`,body:t,live:!0})}#pn(){let e=this.#Se;if(e===void 0)return;let t=this.#m.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#mn(){let e=this.#Se;if(e===void 0)return;this.#Se=void 0;let t=this.#m.get(e.id);t!==void 0&&(t.live=!1)}#hn(e){switch(this.#f){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#gn(e){return e.kind===`sandbox`?!this.#hn(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#f!==`stderr`:e.logVisibility===`all-only`?this.#f!==`all`:!this.#hn(e.title===`stderr`?`stderr`:`stdout`):!1}};function chunkToString(e,t){return typeof e==`string`?e:Buffer.from(e).toString(t)}async function*iterateTUIStream(e){if(e instanceof ReadableStream){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}return}yield*e}function clip(e,t){return clipVisible(e,t)}function promptInputRows({text:e,cursor:t,width:n,theme:r,caretVisible:i,isCommand:a,ghost:o,maxRows:s,placeholder:c,inert:l}){let u=r.colors;if(e.length===0&&c!==void 0){let e=renderInputWithBlockCursor({...visibleLine({text:c,cursor:0},Math.max(1,n-3),r.glyph.ellipsis),visible:i,inverse:u.inverse,render:e=>u.dim(renderInputText(e))});return[clip(`${u.dim(r.glyph.promptIdle)} ${e}`,n),``]}let style=e=>{let t=renderInputText(e);return a&&t.length>0?u.blue(t):t},d=layoutPromptInput({text:e,cursor:t}),f=Math.min(Math.max(1,s),d.rows.length),p=Math.max(0,Math.min(d.caretRow-f+1,d.rows.length-f)),m=l===!0?u.dim(r.glyph.prompt):u.cyan(r.glyph.prompt),h=u.dim(r.glyph.ellipsis),g=Math.max(1,n-3),_=[];for(let e=p;e<p+f;e+=1){let t=d.rows[e],a=e===0?m:` `;(e===p&&p>0||e===p+f-1&&p+f<d.rows.length)&&(a=h);let s;if(e===d.caretRow){let{before:e,under:n,after:a}=visibleLine({text:t.text,cursor:d.caretOffset},g,r.glyph.ellipsis);s=renderInputWithBlockCursor({before:e,under:n,after:a,visible:i,inverse:u.inverse,render:style}),o.length>0&&d.rows.length===1&&(s+=o)}else s=style(t.text);_.push(clip(`${a} ${s}`,n))}return _.push(``),_}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function isActiveToolStatus(e){return e===`running`||e===`approval`}function applyCohortLiveness(e){let t=e.some(e=>e.active);for(let n of e)n.block.live=t||n.active}function leadsWithGap(e,t){if(e.kind===`tool`&&(t?.kind===`user`||t?.kind===`assistant`||t?.kind===`question`))return!0;if(e.kind===`sandbox`&&t?.kind===`sandbox`)return!1;if(t?.kind===`sandbox`&&e.kind!==`sandbox`||t?.kind===`log`)return!0;switch(e.kind){case`user`:case`assistant`:case`reasoning`:case`subagent`:case`error`:case`notice`:case`question`:case`connection-auth`:case`sandbox`:case`log`:case`command`:case`warning`:case`flow`:case`turn-stats`:case`session-boundary`:case`todo-list`:case`agent-header`:return!0;default:return!1}}function parseSandboxLogLine(e){let t=e.trim();if(!t.startsWith(`eve: `))return;let n=t.slice(5);return/\bsandbox\b/i.test(n)&&!isLowValueSandboxLogLine(n)?n:void 0}function isLowValueSandboxLogLine(e){return/^initializing (?:\d+ )?sandbox templates?\b/i.test(e)||/^initialized \d+ sandbox\b/i.test(e)||/^reused cached sandbox template\b/i.test(e)||/^sandbox template "[^"]+" \([^)]+\): (checking|reusing|loading microsandbox runtime|microsandbox runtime ready)\b/i.test(e)}function clipLiveRows(e,t,n,r){if(e.length<=t)return[...e];if(t<=1)return[clip(hiddenRowsMarker(e.length,r),n)];let i=t-1;return[clip(hiddenRowsMarker(e.length-i,r),n),...e.slice(e.length-i)]}function hiddenRowsMarker(e,t){let n=e.toLocaleString(),r=e===1?`row`:`rows`;return t.colors.dim(`${t.glyph.dot} ${t.glyph.ellipsis} ${n} earlier ${r} hidden while streaming`)}function collapseReasoning(e,t){switch(e){case`collapsed`:return!0;case`auto-collapsed`:return!t;default:return!1}}function renderNativeToolBlock(e,t,n,r){let i=e.preparing===!0?presentPreparingTool(e.toolName,r):presentTool(e.toolName,e.input,r),a={id:t,kind:`tool`,title:stripTerminalControls(i.title),subtitle:stripTerminalControls(i.subtitle),status:e.status,live:e.status===`running`||e.status===`approval`,expanded:n,toolInput:e.input,toolName:e.toolName,toolGroup:i.group};return i.doneTitle!==void 0&&(a.doneTitle=stripTerminalControls(i.doneTitle)),i.detail!==void 0&&(a.detailLines=i.detail,a.keepDetailWhenDone=i.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(a.result=stripTerminalControls(e.errorText)):(a.result=i.summarizeResult(e.output),a.toolOutput=e.output),a}function writeExistedFlag(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.existed;return typeof t==`boolean`?t:void 0}function subagentToolStatus(e){switch(e){case`preparing`:return`running`;case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`;case`rejected`:return`denied`}}function formatToolApprovalTitle(e){return stripTerminalControls(e.title??e.toolName)}function toolSectionId(e){return`tool:${e}`}function questionSectionId(e){return`question:${e}`}function subagentHeaderId(e){return`subagent:${e}:header`}function subagentStepSectionId(e,t){return`subagent:${e}:step:${t}`}function subagentToolSectionId(e,t){return`subagent:${e}:tool:${t}`}function connectionAuthSectionId(e){return`connection-auth:${e}`}function connectionAuthTerminalMessage(e){switch(e){case`authorized`:return`Authorization complete`;case`declined`:return`Authorization declined`;case`failed`:return`Authorization failed`;case`timed-out`:return`Authorization timed out`;case`required`:case`pending`:return}}function formatConnectionAuthContent(e,t){let n=[];if(t!==void 0)n.push(t);else{let t=stripTerminalControls(e.description);t.length>0&&n.push(t);let r=e.challenge;r?.url&&n.push(`URL: ${stripTerminalControls(r.url)}`),r?.userCode&&n.push(`Code: ${stripTerminalControls(r.userCode)}`),r?.expiresAt&&n.push(`Expires: ${stripTerminalControls(r.expiresAt)}`),r?.instructions&&n.push(stripTerminalControls(r.instructions))}if(e.reason!==void 0){let t=stripTerminalControls(e.reason);t.length>0&&n.push(`Reason: ${t}`)}return n.join(`
1
+ import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{interruptedError}from"./errors.js";import{FileContentCache}from"./file-content-cache.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{MessageQueue,renderMessageQueueRows}from"./message-queue.js";import{initialModelEditorState,transitionModelEditor}from"./model-editor.js";import{promptPlaceholder}from"./prompt-placeholder.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{enterBadge,renderAcknowledgeQuestion,renderFlowPanel,renderModelEditorQuestion,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{TurnClock}from"./turn-clock.js";import{allTodoItemsSettled,readTodoToolItems,renderFinishedTodoRows,renderTodoPanelRows}from"./todo-panel.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{inspectError}from"#internal/logging.js";import{eveVersionTag}from"#cli/banner.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{LiveRegion}from"#cli/ui/live-region.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";import{readGatewayServiceTier}from"#shared/gateway-service-tier.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e){return e.interrupted?`Interrupted`:e.cancelled?`Cancelled`:e.continueSession?`Ready`:`Done`}const STATUS={processing:`Working…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=[];#m=new Map;#h=new Set;#g=[];#_=new Set;#v=new Map;#y=0;#b=new Map;#x=new FileContentCache;#S=new Set;#C;#w=!1;#T;#E=[];#D;#O=0;#k;#A;#j=``;#M=0;#N=new PromptHistory;#P=!1;#F;#I=!1;#L=Date.now();#R=!1;#z=new TurnClock;#B=EMPTY_LINE;#V=!1;#H={kind:`idle`};#U;#W=STATUS.processing;#G;#K=`eve`;#q=!1;#J=!1;#Y=!1;#X=!1;#Z=!0;#Q=0;#$=Date.now();#ee;#te;#ne;#re=!1;#ie;#ae=``;#oe=new StringDecoder(`utf8`);#se;#ce;#le;#ue=!1;#de=!1;#fe;#pe;#me;#he;#ge;#_e;#ve;#ye=``;#be=``;#xe;#Se;#Ce=0;#we;#Te;#Ee;#De;#Oe;#ke;#Ae=new MessageQueue;#je;#Me=!1;#Ne;#Pe;#Fe=!1;#Ie;#Le;#Re;setupFlow={begin:(e,t)=>this.#We(e,t),end:e=>this.#Ge(e?.preserveDiagnostics??!0),readSelect:e=>this.#Ke(e),readEditableSelect:e=>this.#Je(e),readProviderPicker:e=>this.#Ye(e),readModelEditor:e=>this.#Xe(e),readText:e=>this.#Ze(e),readAcknowledge:e=>this.#Qe(e),readChoice:e=>this.#qe(e),setStatus:e=>this.#ot(e),renderLine:(e,t)=>this.#st(e,t),renderOutput:e=>this.#ct(e),waitForInterrupt:()=>this.#rt()};constructor(t){this.#e=t?.input??process.stdin,this.#t=t?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:t?.color??!0,unicode:t?.unicode??detectUnicode()}),this.#i=t?.tools??`auto-collapsed`,this.#a=t?.reasoning??`auto-collapsed`,this.#o=t?.subagents??`auto-collapsed`,this.#s=t?.connectionAuth??`full`,this.#c=t?.assistantResponseStats??`tokensPerSecond`,this.#me=t?.contextSize,this.#l=t?.captureForeignOutput??this.#t===process.stdout,this.#u=t?.diagnostics,this.#f=t?.logs??`none`,this.#d=t?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#K=e.name,this.#C=e,this.#lt();let t=this.#Xt().join(`
2
+ `);if(this.#w){t!==this.#T&&(this.#T=t,this.#wt({kind:`agent-header`,body:t,live:!1})),this.#Gt();return}this.#w=!0,this.#T=t,this.#n.flush(this.#Xt(),[])}async readPrompt(e){this.#lt(e),this.#Ct(),this.#Et(),this.#P=!0,this.#I=!0,this.#H={kind:`idle`},this.#W=``;let r=this.#Ae.restoreDraft()?.split(`
3
+ `).map(stripPromptControlCharacters).join(`
4
+ `),i=stripPromptControlCharacters(e?.initialDraft??this.#B.text),a=lineOf(r===void 0?i:i.length===0?r:`${r}\n\n${i}`);return this.#B=EMPTY_LINE,this.#N.begin(a.text),this.#ze(a),this.#F=typeaheadFor(this.#d,a.text),this.#vt(),this.#Gt(),await new Promise((e,r)=>{this.#U=r;let apply=e=>{a=e,this.#bt(),this.#ze(a),this.#F=typeaheadFor(this.#d,e.text,this.#F),this.#Gt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#F=void 0,this.#yt(),this.#ut(),r(interruptedError())},suggestions=()=>this.#F!==void 0&&isTypeaheadOpen(this.#F)?this.#F:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ie=r=>{let i=applyLineEditorKey(a,r,{multiline:!0});if(i!==void 0){apply(i);return}switch(r.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#F=moveTypeaheadSelection(e,-1),this.#Gt();break}let t=movePromptLine(a,`up`);t===void 0?recall(this.#N.previous(a.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#F=moveTypeaheadSelection(e,1),this.#Gt();break}let t=movePromptLine(a,`down`);t===void 0?recall(this.#N.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#F=dismissTypeahead(e),this.#Gt());break}case`enter`:{let r=highlighted(),i=r!==void 0&&parsePromptCommand(a.text)===null?typeaheadCompletion(r).trimEnd():a.text;if(i.trim().length===0)break;this.#F=void 0,this.#N.add(i),this.#P=!1,this.#yt(),this.#W=STATUS.processing,isPromptControlCommand(i)?this.#wt({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#St(),this.#Tt(i),this.#we=i,this.#z.arm()),this.#ze(EMPTY_LINE),this.#Gt(),this.#ft(),e(i);break}case`ctrl-d`:a.text.length===0?interrupt():apply(deleteForward(a));break;case`ctrl-l`:this.#Jt();break;case`ctrl-r`:this.#Gt();break;case`ctrl-c`:a.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#dt()})}#ze(e){this.#j=e.text,this.#M=e.cursor}takeQueuedPrompt(){let e=this.#Ae.view().steering,t=this.#Ae.takePrompt();return t!==void 0&&(this.#Pe=e?`steer`:`queue`),t}async renderStream(e,t){this.#lt(t),this.#h.clear(),this.#P=!1,this.#H.kind!==`waiting`&&(this.#H={kind:`waiting`,startedAtMs:Date.now()}),this.#W=this.#O>0?STATUS.connectionAuth:STATUS.processing,this.#Dt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#u?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#z.armed&&this.#z.arm(),this.#X=!1,this.#Me=!1,this.#Fe=!1,this.#Ie=t?.submittedPrompt,this.#Ae.beginTurn(),this.#je=e.cancel,this.#fe=void 0,this.#pe=void 0,this.#he=void 0,this.#ge=void 0,this.#_e=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#xt(),this.#V=!0,this.#Gt();let r=new Promise(e=>{this.#le=e});this.#ie=e=>this.#_t(e),this.#dt();let i={text:new Map,reasoning:new Map,tools:new Map};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#X)break;this.#Nt(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#Ot(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#Ot(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#le=void 0,this.#X&&e.abort?.(),this.#je=void 0,this.#ft(),this.#Ct(),this.#V=!1,this.#H.kind===`waiting`&&(this.#H={kind:`idle`}),this.#W=completedTurnStatus({interrupted:this.#X,cancelled:this.#Me,continueSession:t?.continueSession===!0}),this.#Bt(i),(this.#X||this.#Me)&&this.#zt(),this.#Mt(),this.#u?.reportStats(),this.#Gt(),t?.continueSession||this.#ut()}}async readToolApproval(e,t){return this.#lt(t),this.#Ct(),this.#P=!1,this.#H={kind:`idle`},this.#W=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#X=!1,this.#Gt(),await new Promise((t,n)=>{this.#U=n,this.#ie=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#St(),this.#W=STATUS.processing,this.#ft(),this.#Gt(),t({approved:!0})):n===`n`&&(this.#St(),this.#W=STATUS.processing,this.#Ve(e.toolCallId),this.#ft(),this.#Gt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#Gt();break;case`ctrl-c`:this.#X=!0,this.#ut(),n(interruptedError());break;default:break}},this.#dt()})}async readInputQuestion(e,t){this.#lt(t),this.#Ct(),this.#P=!1,this.#I=!1,this.#H={kind:`idle`},this.#X=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`overlay`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,overlayPanel=t=>renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#Z},this.#r,t),renderTextSection=()=>{this.#At({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#r),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#vt():(this.#yt(),this.#bt())};s===`overlay`?(s=`overlay`,this.#P=!1,this.#jt(o),this.#Te=overlayPanel,this.#W=``,syncFreeformCaret(),this.#Gt()):(s=`text`,this.#Te=void 0,renderTextSection(),this.#P=!0,this.#ze(l),this.#W=``,this.#vt(),this.#Gt());let finalize=t=>{this.#Te=void 0,this.#At({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#r.colors.dim(this.#r.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#P=!1,this.#St(),this.#W=STATUS.processing,this.#yt(),this.#ft(),this.#Gt();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Te=void 0,this.#At({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#r.colors.dim(this.#r.glyph.elbow)} ${this.#r.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#P=!1,this.#W=``,this.#yt(),this.#ft(),this.#Gt(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#Gt())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#U=r,u=t,this.#ie=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#bt(),s===`text`&&this.#ze(l),this.#Gt();return}this.#X=!0,this.#Te=void 0,this.#yt(),this.#ut(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#Gt();return}if(s===`overlay`){switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#bt(),this.#Gt();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#bt(),this.#Gt());break}if(t.type===`text`&&/^[1-9]$/u.test(t.value)){let e=Number(t.value)-1;e<n.length?selectOptionAt(e):e===n.length&&i&&(c=e,syncFreeformCaret(),this.#Gt())}break}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#bt(),this.#ze(l),this.#Gt();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#bt(),this.#ze(l),this.#Gt());break}case`enter`:{let t=resolveQuestionText(l.text,e);if(t===void 0)break;u(finalize(t));break}case`escape`:if(l.text.length>0){l=EMPTY_LINE,this.#bt(),this.#ze(l),this.#Gt();break}dismiss();break;default:break}},this.#dt()})}upsertSubagentStep(e){if(this.#u?.recordSubagentDispatch(e.callId),this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#kt(e.callId,e.subagentName),this.#o===`collapsed`){this.#Gt();return}this.#At({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#o!==`full`,live:!e.finalized}),this.#Gt()}}upsertSubagentTool(e){if(this.#u?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#u?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#o===`hidden`)return;if(this.#kt(e.callId,e.subagentName),this.#o===`collapsed`){this.#Gt();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#Lt({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#At(r),this.#Be(e.callId),this.#Gt()}#Be(e){applyCohortLiveness(this.#p.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#jt(subagentToolSectionId(e.callId,e.childCallId)),this.#Gt()}subagents={begin:e=>this.beginSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#o===`hidden`)return;this.#kt(e.callId,e.name);let t=this.#m.get(subagentHeaderId(e.callId));t?.status===`done`&&delete t.status,this.#Gt()}completeSubagent(e){let t=this.#m.get(subagentHeaderId(e.callId));t!==void 0&&(t.status=`done`,this.#Gt())}markChildToolCallId(e){this.#_.add(e);let t=this.#v.get(e);t!==void 0&&(this.#jt(t),this.#v.delete(e),this.#Gt())}#Ve(e){let t=this.#m.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#At({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#Gt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#O)return;let n=this.#O>0;this.#O=t,t>0?(this.#W=STATUS.connectionAuth,this.#Gt()):n&&(this.#W=STATUS.processing,this.#Gt())}setVercelStatus(e){this.#k=e,this.#Gt()}setRemoteConnectionStatus(e){this.#A=e,this.#Gt()}reset(){this.#p=[],this.#m.clear(),this.#h.clear(),this.#D=void 0,this.#E.length=0,this.#g.length=0,this.#w=!1,this.#T=void 0,this.#He(),this.#R=!1,this.#we=void 0,this.#Se=void 0,this.#O=0,this.#fe=void 0,this.#pe=void 0,this.#he=void 0,this.#ge=void 0,this.#_e=void 0,this.#q&&(this.#n.clearAll(),this.#Gt())}renderSessionBoundary(){this.#Et(),this.#He();let e=this.#r.colors,t=this.#r.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#wt({kind:`session-boundary`,body:n,live:!1}),this.#Gt()}#He(){this.#_.clear(),this.#v.clear(),this.#S.clear(),this.#b.clear(),this.#Oe=void 0,this.#ke=void 0,this.#Ae.reset(),this.#Pe=void 0,this.#x.clear(),this.#z.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#lt(),this.#wt({kind:`notice`,body:t,live:!1}),this.#Gt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#u?.append({source:`sandbox`,detail:t}),this.#lt(),this.#wt({kind:`sandbox`,body:t,live:!1}),this.#Gt())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#Ue();return}this.#lt(),this.#De=t,this.#Gt()}clearSetupWarning(){this.#Ue()}#Ue(){this.#De!==void 0&&(this.#De=void 0,this.#Gt())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#lt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#wt(r),this.#Gt()}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#lt(),this.#wt({kind:`result`,body:t,live:!1}),this.#Gt())}#We(e,t=`spinner`){this.#lt(),this.#P=!1,this.#H={kind:`idle`},this.#W=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ee={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#xt(),this.#Gt()}#Ge(e){this.#Le=void 0,this.#at();let t=this.#Ee;if(t!==void 0){if(this.#Ee=void 0,this.#Ct(),e){let e=[];for(let n of t.lines){if(n.evidence===!0){e.push(n.text);continue}(n.tone===`warning`||n.tone===`error`)&&(e.length>0&&this.#wt({kind:`flow`,title:`info`,body:e.join(`
5
+ `),live:!1}),this.#wt({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#Gt()}}async#Ke(e){let t=this.#$e(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a={options:i,searchAction:r,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(a.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(a.initialValues=e.initialValues);let o=initialSelectState(a),s,c=!1,l=0,isCurrentSearch=e=>e===l,clearSearch=()=>{l+=1,c=!1,o=reduceSelect(o,{type:`clear`},{options:i,searchAction:r,submitRow:n}),this.#Gt()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#Gt();try{let s=await t(e);if(!isCurrentSearch(a))return;let c=o.filter;i=s,o={...initialSelectState({options:s,searchAction:r,submitRow:n}),filter:c}}catch(e){isCurrentSearch(a)&&(s=toErrorMessage(e))}finally{isCurrentSearch(a)&&(c=!1,this.#Gt())}},u=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#Qt()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#Gt(),await this.#nt((t,a)=>{let close=e=>{l+=1,a(e)};if(c){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#Gt();return}let u={key:t,options:i,searchAction:r,select:o},d=reduceSetupSelectInput(n?{...u,kind:e.kind,required:e.required}:{...u,kind:e.kind});switch(d.kind){case`cancel`:close(void 0);return;case`repaint`:this.#Gt();return;case`update`:o=d.select,s=void 0,this.#Gt();return;case`submit`:{let e=searchActionQuery(d.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(d.values);return}loadSearch(e,t);return}case`error`:s=d.message,this.#Gt();return;case`ignore`:return}}).promise}#qe(e){this.#lt();let t=this.#et();t.status={kind:`progress`,text:stripTerminalControls(e.status)};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#Gt();let r=this.#nt((t,r)=>{let i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#Gt();return;case`repaint`:this.#Gt();return;case`submit`:n!==void 0&&r(e.actions[n].value);return;case void 0:return}},()=>{t.status=void 0});return{choice:r.promise,close:()=>r.settle(void 0)}}async#Je(e){let t=this.#$e(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#Z,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#vt():(i=lineOf(``),this.#yt())};return syncEditableRow(),this.#Gt(),await this.#nt((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#bt(),this.#Gt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#Gt()},submit=()=>{let t=selectValueAtCursor([...e.options],r.cursor);if(t===void 0)return;if(t!==e.editable.value){n({kind:`selected`,value:t});return}let o=(i.text||e.editable.defaultValue).trim(),s=e.editable.validate?.(o);if(s!==void 0){a=s,this.#Gt();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#Gt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#yt()).promise}async#Ye(e){let t=this.#$e(),n=initialProviderPickerState(e.options,e.initialValue),r,cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor),r=e.options.find(e=>e.value===t);if(r!==void 0)return enterBadge(this.#r,r.checked===!0?`change`:void 0)};t.question=t=>{let r=cursorBadge(),i={kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#Z,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#r,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#vt():this.#yt()};return syncCaret(),this.#Gt(),await this.#nt((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#Gt();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#Gt();return;case`validate`:{n=o.state,syncCaret(),this.#Gt();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#Gt();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#bt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#yt()}).promise}async#Xe(e){let t=this.#$e(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#r,t),this.#Gt(),await this.#nt((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#Gt();return;case`cancel`:r(void 0);return;case`settle`:r(i.result);return}},i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:i.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#Gt();return;case void 0:break}if(t.type===`left`||t.type===`right`){dispatch({type:`adjust`,direction:t.type});return}if(t.type===`tab`){dispatch({type:`adjust`,direction:`right`});return}if(t.type===`backspace`){dispatch({type:`backspace`});return}if(t.type===`text`)for(let e of t.value.replaceAll(`
6
+ `,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#Ze(e){let t=this.#$e(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder!==void 0&&(i.placeholder=e.placeholder),e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#r,t,this.#Z)},this.#vt(),this.#Gt(),await this.#nt((t,i)=>{let apply=e=>{n=e,r=void 0,this.#bt(),this.#Gt()},a=applyLineEditorKey(n,t);if(a!==void 0){apply(a);return}switch(t.type){case`ctrl-c`:case`escape`:i(void 0);return;case`ctrl-r`:this.#Gt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#Gt();return}i(t);return}default:return}},()=>this.#yt()).promise}async#Qe(e){let t=this.#$e();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#Gt(),await this.#nt((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#Gt();return;default:return}}).promise}#$e(){return this.#lt(),this.#P=!1,this.#H={kind:`idle`},this.#W=``,this.#et()}#et(){return this.#Ee===void 0&&(this.#Ee={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Ee}#tt(){this.#Ee?.implicit===!0?this.#Ee=void 0:this.#Ee!==void 0&&(this.#Ee.question=void 0,this.#Ee.hideLinesWhileQuestion=!1),this.#ie=void 0,this.#ft(),this.#Ee!==void 0&&this.#it(),this.#Gt()}#nt(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#tt(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#tt(),i(e))};return this.#gt(),this.#ie=t=>e(t,settle,reject),this.#dt(),{promise:a,settle}}#rt(){let e,t=new Promise(t=>{e=t});return this.#Le=e,this.#it(),{promise:t,dispose:()=>{this.#Le===e&&(this.#Le=void 0,this.#at())}}}#it(){if(this.#Le===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#Le;this.#Le=void 0,this.#at(),e?.();return}e.type===`ctrl-r`&&this.#Gt()};this.#Re=consumer,this.#gt(),this.#ie=consumer,this.#dt()}#at(){this.#Re!==void 0&&(this.#ie===this.#Re&&this.#ft(),this.#Re=void 0)}#ot(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e)}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis)};if(this.#Ee!==void 0){this.#Ee.status=t,t===void 0&&(this.#Ee.preview=void 0),this.#Gt();return}if(!(this.#P||this.#V)){if(t===void 0){this.#H={kind:`idle`},this.#G=void 0,this.#Ct(),this.#Gt();return}this.#lt(),this.#St(),this.#G=t.text,this.#Gt()}}#st(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Ee;if(r!==void 0){if(r.preview=void 0,t===`warning`||t===`error`)for(let e of r.outputBuffer)r.lines.push({text:e,tone:`info`,evidence:!0});r.outputBuffer=[],r.lines.push({text:n,tone:t}),this.#Gt();return}this.#lt(),this.#wt({kind:`flow`,title:t,body:n,live:!1}),this.#Gt()}#ct(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Ee;if(n===void 0){this.#st(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#Gt()}setSessionId(e){this.#Ne=e}shutdown(){if(this.#ut(),this.#J&&!this.#Y){this.#Y=!0;let e=this.#Ne===void 0?``:` ${this.#r.glyph.dot} session ${this.#Ne}`;this.#t.write(`${this.#r.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}#lt(e){this.#K=e?.title??this.#K,e?.contextSize!==void 0&&(this.#me=e.contextSize),!this.#q&&(this.#q=!0,this.#J=!0,this.#n.reset(),this.#n.hideCursor(),this.#fn(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#ce=()=>this.#Gt(),this.#t.on(`resize`,this.#ce))}#ut(){let e=this.#U;if(this.#U=void 0,e?.(interruptedError()),this.#ft(),this.#yt(),this.#Ct(),this.#ne!==void 0&&(clearTimeout(this.#ne),this.#ne=void 0),this.#re=!1,this.#q){this.#xn();for(let e of this.#p)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#Gt(),this.#n.clear(),this.#n.showCursor(),this.#pn(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#ce&&=(this.#t.off(`resize`,this.#ce),void 0),this.#q=!1}}#dt(){this.#e.off(`data`,this.#pt),this.#e.on(`data`,this.#pt),this.#ae.length>0&&queueMicrotask(()=>{this.#ie!==void 0&&this.#ae.length>0&&(this.#ht(),this.#mt())})}#ft(){this.#e.off(`data`,this.#pt),this.#gt(),this.#ie=void 0}#pt=e=>{this.#gt(),this.#ae+=this.#oe.write(e),this.#ht(),this.#mt()};#mt(){if(this.#ae===`\x1B`){this.#se=setTimeout(()=>{this.#ae===`\x1B`&&(this.#ae=``,this.#ie?.({type:`escape`}))},30),this.#se.unref?.();return}if(isIncompletePaste(this.#ae)){let e=this.#ae;this.#se=setTimeout(()=>{if(this.#ae!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#ae=``,t.length>0&&this.#ie?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#se.unref?.()}}#ht(){for(;this.#ae.length>0;){let e=nextKey(this.#ae);if(e.incomplete)return;this.#ae=this.#ae.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#ie?.(e.key)}}#gt(){this.#se&&=(clearTimeout(this.#se),void 0)}#_t(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#Gt();break;case`ctrl-c`:this.#X||(this.#X=!0,this.#H={kind:`idle`},this.#W=`Interrupted`,this.#le?.(),this.#Gt());break;case`enter`:{let e=this.#B.text;if(e.trim().length===0)break;this.#Ae.enqueue(e)&&(this.#B=EMPTY_LINE),this.#Gt();break}case`escape`:{if(this.#Ae.idle&&this.#je===void 0)break;let e=this.#Ae.handleEscape();(e===`steer`||e===`cancel`)&&(this.#Fe=!0,this.#je?.()),this.#Gt();break}default:{this.#Ae.disarm();let t=applyLineEditorKey(this.#B,e,{multiline:!0});t!==void 0&&(this.#B=t,this.#Gt());break}}}#vt(){this.#yt(),this.#bt(),this.#ee=setInterval(()=>{this.#Z=!this.#Z,this.#Gt()},500),this.#ee.unref?.()}#yt(){this.#ee&&=(clearInterval(this.#ee),void 0),this.#Z=!0}#bt(){this.#Z=!0}#xt(){this.#Ct(),this.#te=setInterval(()=>{this.#Q+=1,this.#Gt()},90),this.#te.unref?.()}#St(){let e=Date.now();this.#$=e,this.#H={kind:`waiting`,startedAtMs:e},this.#xt()}#Ct(){this.#te&&=(clearInterval(this.#te),void 0)}#wt(e){e.id!==this.#Se?.id&&this.#xn(),e.updateSeq=++this.#y,this.#p.push(e),e.id&&this.#m.set(e.id,e)}#Tt(e){this.#R=!0,this.#wt({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#Gt()}#Et(){let e=this.#z.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#rn(e.elapsedMs)}`,n=this.#pe??0;if(this.#me!==void 0&&this.#me>0&&n>0){let e=Math.round(n/this.#me*100);t+=` ${this.#r.glyph.dot} ${e}% context`}this.#wt({kind:`turn-stats`,body:t,live:!1})}#Dt(e){if(e==null)return;let t=this.#Pe;if(this.#Pe=void 0,this.#we===e){this.#we=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#wt(n)}#Ot(e,t,n={}){let r=stripTerminalControls(e),i=stripTerminalControls(t),a=n.detail===void 0?void 0:stripTerminalControls(n.detail),o=n.hint===void 0?void 0:stripTerminalControls(n.hint),s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#u?.append(o===void 0?s:{...s,hint:o});let c={kind:`error`,title:r,body:i,live:!1};o!==void 0&&(c.hint=o),a!==void 0&&(c.detail=this.#u===void 0?a:`details: ${this.#u.displayPath}`),this.#wt(c),this.#Gt()}#kt(e,t){if(this.#S.has(e))return;this.#S.add(e);let n=stripTerminalControls(t),r=this.#b.get(n)??[];if(r.push(e),this.#b.set(n,r),r.length===2){let e=this.#m.get(subagentHeaderId(r[0]));e!==void 0&&(e.subtitle=`#1`)}let i={id:subagentHeaderId(e),kind:`subagent`,subagentCallId:e,title:n,live:!0};r.length>1&&(i.subtitle=`#${r.length}`),this.#wt(i)}#At(e){if(e.id&&this.#h.has(e.id))return;let t=e.id?this.#m.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#y;return}this.#wt(e)}#jt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#Mt(){for(let e of this.#p)e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#Nt(e,t,n){switch(e.type){case`step-finish`:this.#u?.recordStepUsage(e.usage),e.usage!==void 0&&this.#z.addUsage(e.usage),this.#Bt(n),this.#Wt(e.usage),this.#Gt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#Pt(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;n.text.set(e.id,r),this.#Pt(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);if(n.reasoning.set(e.id,r),t.reasoning===`full`){this.#Ft(e.id,r,!0,t);break}break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;if(t.reasoning===`full`){this.#Ft(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#It({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#u?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#It({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;this.#It({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#Ut(e.toolCallId,n);if(r===void 0)break;this.#It({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#Ut(e.toolCallId,n);if(this.#u?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#It({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#Ut(e.toolCallId,n);if(r===void 0)break;this.#It({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#Ot(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:this.#Me=!0,!this.#Fe&&this.#Ie!==void 0&&this.#B.text.length===0&&(this.#B=lineOf(this.#Ie),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#Wt(e.usage),this.#Gt();break}}#Pt(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#At({id:e,kind:`assistant`,body:r,live:n}),this.#Gt())}#Ft(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#At({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#Gt())}#It(e,t,n){if(n.tools.set(e.toolCallId,e),this.#_.has(e.toolCallId)||this.#Vt(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#v.set(e.toolCallId,r);let i=this.#Lt(e);this.#At(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#Ht(n),this.#Gt()}#Lt(e){e.output!==void 0&&this.#x.observeRead(e.output);let t={};this.#Rt(e.toolName)&&(t.isSubagent=!0);let n=readWriteFileInput(e.toolName,e.input);if(n===void 0)return t.isSubagent===!0?t:void 0;let r=this.#x.observeWrite({path:n.path,content:n.content,callId:e.toolCallId});r!==void 0&&(t.previousContent=r);let i=writeExistedFlag(e.output);return i!==void 0&&(t.existed=i),t}#Rt(e){let t=this.#C?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#zt(){for(let e of this.#p)e.kind!==`tool`&&e.kind!==`subagent-tool`||e.status===`running`&&(e.status=`error`,e.result=`interrupted`,e.live=!1)}#Bt(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#v.get(t)??toolSectionId(t);this.#jt(r),this.#v.delete(t)}}#Vt(e){let t=readTodoToolItems(e.toolName,e.input);if(t===void 0)return!1;if(t.length>0&&allTodoItemsSettled(t)){let e=JSON.stringify(t);this.#ke!==e&&(this.#ke=e,this.#wt({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#un(),this.#r).join(`
7
+ `),live:!1})),this.#Oe=void 0}else this.#Oe=t.length>0?t:void 0,this.#ke=void 0;return this.#Gt(),!0}#Ht(e){let t=[];for(let n of e.tools.values()){if(this.#_.has(n.toolCallId))continue;let e=this.#v.get(n.toolCallId)??toolSectionId(n.toolCallId),r=this.#m.get(e);r?.kind===`tool`&&t.push({block:r,active:isActiveToolStatus(n.status)})}applyCohortLiveness(t)}#Ut(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#v.get(e)??toolSectionId(e),i=this.#m.get(r);if(!(i===void 0||i.kind!==`tool`))return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.toolName??i.title??`tool`}}#Wt(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#fe=(t??0)+(n??0)),this.#pe=t??this.#pe,this.#he=n??this.#he,this.#he!=null&&this.#_e!==void 0){let e=(Date.now()-this.#_e)/1e3;e>0&&(this.#ge=this.#he/e)}}#Gt(){if(this.#q){if(this.#ue){this.#de=!0;return}this.#ue=!0;try{do this.#de=!1,this.#Kt();while(this.#de)}finally{this.#ue=!1}}}#Kt(){if(!this.#q)return;let e=this.#un(),t=this.#tn(e),n=Math.max(1,this.#dn()-t.length),r=[],i=this.#D,a=groupToolBlocksForDisplay(this.#p),o=0;for(;o<a.length&&a[o].display.live===!1;)o+=1;if(o>0){let e=new Set(a.slice(0,o).flatMap(e=>e.members));for(let t=this.#p.length-1;t>=0;--t)e.has(this.#p[t])&&this.#p.splice(t,1)}for(let t of a.slice(0,o)){for(let e of t.members)this.#g.push(e),e.id&&(this.#h.add(e.id),this.#m.delete(e.id));if(this.#Cn(t.display))continue;let n=this.#Zt(t.display,e,i);i=previousBlockOf(t.display),this.#D=i,r.push(...n),this.#E.push(...n)}let s=[];for(let{display:t}of a.slice(o)){if(this.#Cn(t))continue;let n=this.#Zt(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)s.push({block:t,row:n[e]})}let c=[...clipLiveRows(s.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,c):this.#n.update(c)}#qt(){if(!this.#q)return;let e=this.#un(),t=this.#tn(e),n=Math.max(1,this.#dn()-t.length),r=this.#D,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#p)){if(this.#Cn(t))continue;let n=this.#Zt(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#r),...t];this.#n.clearAll(),this.#n.flush([...this.#Xt(),...this.#E],a)}logDisplayMode(){return this.#f}setLogDisplayMode(e){e!==this.#f&&(this.#f=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#Yt(),this.#q&&this.#qt())}flushDelayedDevBuildErrors(){let e=this.#xe;e!==void 0&&(this.#xe=void 0,this.#wt({kind:`log`,title:`stderr`,body:e,live:!0}),this.#Gt())}#Jt(){this.#re=!0,this.#ne!==void 0&&clearTimeout(this.#ne),this.#ne=setTimeout(()=>{this.#re=!1,this.#ne=void 0,this.#Gt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#f)),this.#Gt()}#Yt(){let e=this.#un();this.#E.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#g,{logCoalescing:`runs`})){if(this.#Cn(n))continue;let r=this.#Zt(n,e,t);t=previousBlockOf(n),this.#E.push(...r)}this.#D=t}#Xt(){let e=this.#C;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#un()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#Zt(e,t,n){let r={activityPulse:this.#$t(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#Qt(){return this.#r.spinner[this.#Q%this.#r.spinner.length]??``}#$t(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#en(e,t){return e.indicator.kind===`spinner`?{glyph:this.#Qt(),color:`yellow`}:{glyph:this.#$t(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#tn(e){let n=this.#r.colors,r=[``];if(this.#Te!==void 0)return r.push(...this.#Te(e),``),this.#sn(r,e),r;let a=this.#Ee;if(a!==void 0){let t=this.#en(a,a.status),n=a.status===void 0?void 0:{...a.status,indicator:t},i;if(a.question!==void 0){let t=a.question(e);i={kind:`question`,rows:t},n!==void 0&&(i={kind:`question`,rows:t,status:n})}else n===void 0?i=a.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:a.preview,indicator:t}:(i={kind:`status`,status:n},a.preview!==void 0&&(i={kind:`status`,status:n,preview:a.preview}));let o={title:a.title,lines:a.hideLinesWhileQuestion===!0?[]:a.lines,content:i};return r.push(...renderFlowPanel(o,this.#r,e)),this.#cn(r,e),r}this.#De!==void 0&&r.push(...renderAttentionRows(this.#De,e,this.#r),``),this.#Oe!==void 0&&r.push(...renderTodoPanelRows({items:this.#Oe,width:e,theme:this.#r,working:this.#V||this.#H.kind===`waiting`,pulse:this.#$t(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}),``);let o=renderMessageQueueRows({view:this.#Ae.view(),width:e,theme:this.#r,working:this.#V});if(o.length>0&&r.push(...o,``),this.#P){let i=this.#F===void 0?void 0:inlineCommandHint(this.#F);i===void 0&&this.#F!==void 0&&isTypeaheadOpen(this.#F)&&r.push(...renderCommandSuggestions(this.#F,this.#r,e));let a=isPromptControlCommand(this.#j),o=i?n.dim(` ${i}`):``,l=[];this.#sn(l,e);let d=Math.max(1,this.#dn()-1-r.length-1-l.length),f={text:this.#j,cursor:this.#M,width:e,theme:this.#r,caretVisible:this.#Z,isCommand:a,ghost:o,maxRows:d};return this.#I&&this.#j.length===0&&(f.placeholder=this.#R?``:promptPlaceholder(Date.now()-this.#L)),r.push(...promptInputRows(f)),r.push(...l),r}let l=this.#H.kind===`waiting`&&this.#G===void 0;if(this.#V||l){r.push(this.#nn(e)),this.#an(r,e);let t=[];return this.#sn(t,e),!this.#V&&t.length>0&&r.push(``),r.push(...t),r}if(this.#B.text.length>0)return this.#on(r,e,{inert:!1}),this.#sn(r,e),r;let d=this.#G??(this.#W.length>0?this.#W:`Ready`),f=this.#ln(),p=n.dim(this.#r.glyph.dot),m=f?`${p} ${d} ${n.dim(this.#r.glyph.dot)} ${f}`:`${p} ${d}`;return r.push(clip(m,e)),this.#sn(r,e),r}#nn(e){let t=this.#r.colors,n=this.#$t(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),r=this.#H,i=this.#z.startedAtMs??this.#_e??(r.kind===`waiting`?r.startedAtMs:Date.now()),a=Date.now()-i,o=`${typewriterText(`Working for`,a,80)} ${this.#rn(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#rn(e){return`${formatTurnDuration(e)}${this.#in()}`}#in(){let{inputTokens:e,outputTokens:t}=this.#z.usage;return e===0&&t===0?``:` ${this.#r.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#r.glyph)}`}#an(e,t){this.#V&&this.#on(e,t,{inert:!0})}#on(e,t,n){e.push(``);let r={text:this.#B.text,cursor:this.#B.cursor,width:t,theme:this.#r,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#B.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#sn(e,t){let n=this.#A===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#r,width:r};this.#re&&(i.logLevel=this.#f);let a=this.#C?.serverUrl;if(a!==void 0&&this.#A===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#C?.info?.agent.model;o?.id!==void 0&&(i.model=o.id),o?.reasoning!==void 0&&o.reasoning!==`provider-default`&&(i.reasoning=o.reasoning),readGatewayServiceTier(o?.providerOptions).kind===`priority`&&(i.fastMode=!0);let s=o?.endpoint;s!==void 0&&(i.endpoint=s),this.#k!==void 0&&(i.vercel=this.#k),this.#A!==void 0&&(i.remote=this.#A);let c=buildStatusLine(i);c!==void 0&&e.push(clip(`${n}${c}`,t))}#cn(e,t){if(this.#A===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#A,theme:this.#r,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#ln(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#fe,outputTokens:this.#he,tokensPerSecond:this.#ge},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#un(){return Math.max(20,this.#t.columns||80)}#dn(){return Math.max(8,this.#t.rows||24)}#fn(){if(this.#ve!==void 0||!this.#l)return;this.#ye=``,this.#be=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#hn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#u?.subscribeLogRecords(e=>this.#mn(e)),this.#ve=()=>{this.#u?.unsubscribeLogRecords(),e(),t()}}#pn(){let e=this.#ve;e!==void 0&&(this.#ve=void 0,e(),this.#ye.length>0&&(this.#u?.append({source:`stdout`,detail:this.#ye}),this.#Sn(`stdout`)&&process.stdout.write(`${this.#ye}\n`),this.#ye=``),this.#be.length>0&&(this.#u?.append({source:`stderr`,detail:this.#be}),this.#Sn(`stderr`)&&process.stderr.write(`${this.#be}\n`),this.#be=``))}#mn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#_n(`[eve:${e.namespace}] ${e.message}${t}`),this.#Gt()}#hn(e,t){let n=(e===`stdout`?this.#ye:this.#be)+t,r=n.lastIndexOf(`
8
+ `),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#ye=i:this.#be=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#u?.append({source:e,detail:a}),e===`stdout`?this.#gn(a):this.#_n(a),this.#Gt())}#gn(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
9
+ `);t=[],e.trim().length!==0&&this.#wt({kind:`log`,title:`stdout`,body:e,live:!0})};for(let n of e.split(`
10
+ `)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#wt({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#yn(r,n.trimEnd())}flushPending()}#_n(e){let t=e.split(`
11
+ `),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#u===void 0){this.#wt({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#u.displayPath);if(t.kind===`inline`){this.#wt({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#wt({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#wt({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
12
+ `);r.trim().length>0&&this.#wt({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
13
+ `);this.#vn(i)}#vn(e){if(this.#f===`all`){if(e.trim().length===0)return;this.#wt({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#xe=e}#yn(e,t){let n=this.#bn();if(e.kind===`failed`){this.#vn(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#Ce}`;this.#Ce+=1,this.#Se={id:r,summary:t},this.#wt({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}if(n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#xe=void 0);return}e.kind===`rebuilt`&&(this.#xe=void 0),this.#wt({kind:`log`,title:`stdout`,body:t,live:!0})}#bn(){let e=this.#Se;if(e===void 0)return;let t=this.#m.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#xn(){let e=this.#Se;if(e===void 0)return;this.#Se=void 0;let t=this.#m.get(e.id);t!==void 0&&(t.live=!1)}#Sn(e){switch(this.#f){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#Cn(e){return e.kind===`sandbox`?!this.#Sn(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#f!==`stderr`:e.logVisibility===`all-only`?this.#f!==`all`:!this.#Sn(e.title===`stderr`?`stderr`:`stdout`):!1}};function chunkToString(e,t){return typeof e==`string`?e:Buffer.from(e).toString(t)}async function*iterateTUIStream(e){if(e instanceof ReadableStream){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}return}yield*e}function clip(e,t){return clipVisible(e,t)}function promptInputRows({text:e,cursor:t,width:n,theme:r,caretVisible:i,isCommand:a,ghost:o,maxRows:s,placeholder:c,inert:l}){let u=r.colors;if(e.length===0&&c!==void 0){let e=renderInputWithBlockCursor({...visibleLine({text:c,cursor:0},Math.max(1,n-3),r.glyph.ellipsis),visible:i,inverse:u.inverse,render:e=>u.dim(renderInputText(e))});return[clip(`${u.dim(r.glyph.promptIdle)} ${e}`,n),``]}let style=e=>{let t=renderInputText(e);return a&&t.length>0?u.blue(t):t},d=layoutPromptInput({text:e,cursor:t}),f=Math.min(Math.max(1,s),d.rows.length),p=Math.max(0,Math.min(d.caretRow-f+1,d.rows.length-f)),m=l===!0?u.dim(r.glyph.prompt):u.cyan(r.glyph.prompt),h=u.dim(r.glyph.ellipsis),g=Math.max(1,n-3),_=[];for(let e=p;e<p+f;e+=1){let t=d.rows[e],a=e===0?m:` `;(e===p&&p>0||e===p+f-1&&p+f<d.rows.length)&&(a=h);let s;if(e===d.caretRow){let{before:e,under:n,after:a}=visibleLine({text:t.text,cursor:d.caretOffset},g,r.glyph.ellipsis);s=renderInputWithBlockCursor({before:e,under:n,after:a,visible:i,inverse:u.inverse,render:style}),o.length>0&&d.rows.length===1&&(s+=o)}else s=style(t.text);_.push(clip(`${a} ${s}`,n))}return _.push(``),_}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function isActiveToolStatus(e){return e===`running`||e===`approval`}function applyCohortLiveness(e){let t=e.some(e=>e.active);for(let n of e)n.block.live=t||n.active}function leadsWithGap(e,t){if(e.kind===`tool`&&(t?.kind===`user`||t?.kind===`assistant`||t?.kind===`question`))return!0;if(e.kind===`sandbox`&&t?.kind===`sandbox`)return!1;if(t?.kind===`sandbox`&&e.kind!==`sandbox`||t?.kind===`log`)return!0;switch(e.kind){case`user`:case`assistant`:case`reasoning`:case`subagent`:case`error`:case`notice`:case`question`:case`connection-auth`:case`sandbox`:case`log`:case`command`:case`warning`:case`flow`:case`turn-stats`:case`session-boundary`:case`todo-list`:case`agent-header`:return!0;default:return!1}}function parseSandboxLogLine(e){let t=e.trim();if(!t.startsWith(`eve: `))return;let n=t.slice(5);return/\bsandbox\b/i.test(n)&&!isLowValueSandboxLogLine(n)?n:void 0}function isLowValueSandboxLogLine(e){return/^initializing (?:\d+ )?sandbox templates?\b/i.test(e)||/^initialized \d+ sandbox\b/i.test(e)||/^reused cached sandbox template\b/i.test(e)||/^sandbox template "[^"]+" \([^)]+\): (checking|reusing|loading microsandbox runtime|microsandbox runtime ready)\b/i.test(e)}function clipLiveRows(e,t,n,r){if(e.length<=t)return[...e];if(t<=1)return[clip(hiddenRowsMarker(e.length,r),n)];let i=t-1;return[clip(hiddenRowsMarker(e.length-i,r),n),...e.slice(e.length-i)]}function hiddenRowsMarker(e,t){let n=e.toLocaleString(),r=e===1?`row`:`rows`;return t.colors.dim(`${t.glyph.dot} ${t.glyph.ellipsis} ${n} earlier ${r} hidden while streaming`)}function collapseReasoning(e,t){switch(e){case`collapsed`:return!0;case`auto-collapsed`:return!t;default:return!1}}function renderNativeToolBlock(e,t,n,r){let i=e.preparing===!0?presentPreparingTool(e.toolName,r):presentTool(e.toolName,e.input,r),a={id:t,kind:`tool`,title:stripTerminalControls(i.title),subtitle:stripTerminalControls(i.subtitle),status:e.status,live:e.status===`running`||e.status===`approval`,expanded:n,toolInput:e.input,toolName:e.toolName,toolGroup:i.group};return i.doneTitle!==void 0&&(a.doneTitle=stripTerminalControls(i.doneTitle)),i.detail!==void 0&&(a.detailLines=i.detail,a.keepDetailWhenDone=i.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(a.result=stripTerminalControls(e.errorText)):(a.result=i.summarizeResult(e.output),a.toolOutput=e.output),a}function writeExistedFlag(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.existed;return typeof t==`boolean`?t:void 0}function subagentToolStatus(e){switch(e){case`preparing`:return`running`;case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`;case`rejected`:return`denied`}}function formatToolApprovalTitle(e){return stripTerminalControls(e.title??e.toolName)}function toolSectionId(e){return`tool:${e}`}function questionSectionId(e){return`question:${e}`}function subagentHeaderId(e){return`subagent:${e}:header`}function subagentStepSectionId(e,t){return`subagent:${e}:step:${t}`}function subagentToolSectionId(e,t){return`subagent:${e}:tool:${t}`}function connectionAuthSectionId(e){return`connection-auth:${e}`}function connectionAuthTerminalMessage(e){switch(e){case`authorized`:return`Authorization complete`;case`declined`:return`Authorization declined`;case`failed`:return`Authorization failed`;case`timed-out`:return`Authorization timed out`;case`required`:case`pending`:return}}function formatConnectionAuthContent(e,t){let n=[];if(t!==void 0)n.push(t);else{let t=stripTerminalControls(e.description);t.length>0&&n.push(t);let r=e.challenge;r?.url&&n.push(`URL: ${stripTerminalControls(r.url)}`),r?.userCode&&n.push(`Code: ${stripTerminalControls(r.userCode)}`),r?.expiresAt&&n.push(`Expires: ${stripTerminalControls(r.expiresAt)}`),r?.instructions&&n.push(stripTerminalControls(r.instructions))}if(e.reason!==void 0){let t=stripTerminalControls(e.reason);t.length>0&&n.push(`Reason: ${t}`)}return n.join(`
12
14
  `)}function formatQuestionContent(e,t,n){let r=n.colors,i=[],a=e.options??[];if(a.length>0){for(let[e,o]of a.entries()){let a=stripTerminalControls(o.label),s=o.description===void 0?``:stripTerminalControls(o.description),c=t===e,l=s.length>0?`${c?` `:` `}${r.dim(`— ${s}`)}`:``,u=renderCursorRow(c?`${n.glyph.selectedPointer} ${a}`:` ${a}`,c,r);i.push(`${u}${l}`)}if(e.allowFreeform===!0){let e=t===a.length,o=`Type your own answer`,s=e?`${n.glyph.selectedPointer} ${o}`:` ${r.dim(o)}`;i.push(renderCursorRow(s,e,r))}}else i.push(r.dim(` (type your answer)`));return i.join(`
13
15
  `)}function resolveQuestionText(e,t){let n=e.trim();if(n.length===0)return;let r=n.toLowerCase(),i=t.options??[];if(i.length>0){let e=matchQuestionOption(r,i);if(e!==void 0)return{optionId:e.id,label:e.label}}if(t.allowFreeform===!0||i.length===0)return{text:n,label:n}}function matchQuestionOption(e,t){let n=t.find(t=>t.id.toLowerCase()===e);if(n!==void 0)return n;let r=t.find(t=>t.label.toLowerCase()===e);if(r!==void 0)return r;let i=Number(e);if(Number.isInteger(i)&&i>0&&i<=t.length)return t[i-1]}export{TerminalRenderer};
@@ -7,7 +7,7 @@ export { createDataUrlFilePart, createTextWithFileContent } from "#client/file-p
7
7
  export { MessageResponse } from "#client/message-response.js";
8
8
  export { ClientSession } from "#client/session.js";
9
9
  export type { EveAgentStoreCallbacks, EveAgentStoreInit, EveAgentStoreSnapshot, EveAgentStoreStatus, PrepareSend, } from "#client/eve-agent-store.js";
10
- export type { AgentInfoEntry, AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoFrameworkChannelEntry, AgentInfoFrameworkToolEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, CancelSessionResult, ClientAuth, ClientOptions, ClientRedirectPolicy, HeadersValue, HealthResult, MessageResult, ResolvedStreamReconnectPolicy, SendTurnInput, SendTurnPayload, SessionState, StreamOptions, StreamReconnectPolicy, StreamReconnectRetryPolicy, TokenValue, } from "#client/types.js";
10
+ export type { AgentInfoEntry, AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoFrameworkChannelEntry, AgentInfoFrameworkToolEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, CancelSessionResult, ClientAuth, ClientOptions, ClientRedirectPolicy, HeadersValue, HealthResult, MessageResult, ResetResult, ResolvedStreamReconnectPolicy, SendTurnInput, SendTurnPayload, SessionState, StreamOptions, StreamReconnectPolicy, StreamReconnectRetryPolicy, TokenValue, } from "#client/types.js";
11
11
  export type { EveAgentReducer, EveAgentReducerEvent, ClientInputRespondedEvent, ClientMessageFailedEvent, ClientMessageSubmittedEvent, } from "#client/reducer.js";
12
12
  export type { EveAuthorizationChallenge, EveAuthorizationOutcome, EveAuthorizationPart, EveMessageData, EveDynamicToolPart, EveMessageInputRequest, EveMessage, EveMessageMetadata, EveMessagePart, EveMessageToolMetadata, } from "#client/message-reducer.js";
13
13
  export type { ActionResultStreamEvent, ActionsRequestedStreamEvent, AssistantStepFinishReason, AuthorizationOutcome, CompactionCompletedStreamEvent, CompactionRequestedStreamEvent, AuthorizationCompletedStreamEvent, ConnectionAuthorizationOutcome, AuthorizationRequiredStreamEvent, HandleMessageStreamEvent, InputRequestedStreamEvent, MessageAppendedStreamEvent, MessageCompletedStreamEvent, MessageReceivedPart, MessageReceivedStreamEvent, ReasoningAppendedStreamEvent, ReasoningCompletedStreamEvent, ResultCompletedStreamEvent, SessionCompletedStreamEvent, SessionFailedStreamEvent, SessionStartedStreamEvent, SessionWaitingStreamEvent, StepCompletedStreamEvent, StepFailedStreamEvent, StepStartedStreamEvent, SubagentCalledStreamEvent, SubagentChildEventStreamEvent, SubagentCompletedStreamEvent, SubagentStartedStreamEvent, TurnCancelledStreamEvent, TurnCompletedStreamEvent, TurnFailedStreamEvent, TurnStartedStreamEvent, TurnFailureStreamEvent, } from "#protocol/message.js";
@@ -1,6 +1,6 @@
1
1
  import type { HandleMessageStreamEvent } from "#protocol/message.js";
2
2
  import { MessageResponse } from "#client/message-response.js";
3
- import type { CancelSessionResult, ClientRedirectPolicy, SendTurnInput, SessionState, StreamOptions } from "#client/types.js";
3
+ import type { CancelSessionResult, ClientRedirectPolicy, ResetResult, SendTurnInput, SessionState, StreamOptions } from "#client/types.js";
4
4
  /**
5
5
  * Internal interface that a {@link ClientSession} uses to access client-level
6
6
  * configuration without depending on the full {@link Client} class.
@@ -51,6 +51,18 @@ export declare class ClientSession {
51
51
  cancel(options?: {
52
52
  turnId?: string;
53
53
  }): Promise<CancelSessionResult>;
54
+ /**
55
+ * Terminally retires the session that owns this handle's continuation token.
56
+ *
57
+ * Unlike {@link cancel}, reset does not merely stop an active turn: it
58
+ * releases the durable workflow owner so the next {@link send} creates a
59
+ * fresh conversation and initializes a new session-scoped sandbox on first
60
+ * sandbox use. Resetting a never-started handle is a successful no-op. After
61
+ * a successful reset, this handle has no session state.
62
+ *
63
+ * @throws {ClientError} If the reset route returns a non-successful status.
64
+ */
65
+ reset(): Promise<ResetResult>;
54
66
  /**
55
67
  * Opens this session's event stream for the current session ID.
56
68
  *
@@ -1 +1 @@
1
- import{EVE_CREATE_SESSION_ROUTE_PATH,createEveCancelTurnRoutePath,createEveContinueSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{advanceSession}from"#client/session-utils.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{followStreamIterable}from"#client/open-stream.js";import{serializeOutputSchema}from"#shared/tool-schema.js";var ClientSession=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get state(){return this.#t}async send(e){let t=normalizeSendTurnInput(e),n=this.#t,{continuationToken:r,sessionId:i}=await this.#n(t,n);return this.#t===n&&(this.#t={...n,sessionId:i}),new MessageResponse({continuationToken:r,createStream:()=>this.#r(i,r,n,t),sessionId:i})}async cancel(e){let n=this.#t.sessionId;if(!n)throw Error(`Session has no session ID. Send a message first.`);let r=createClientUrl(this.#e.host,createEveCancelTurnRoutePath(n)),i=await this.#e.resolveHeaders();i.set(`content-type`,`application/json`);let o=await fetch(r,withRedirectPolicy({headers:i,method:`POST`,body:e?JSON.stringify(e):void 0},this.#e.redirect)),c=await o.text();if(!o.ok)throw new ClientError(o.status,c,o.headers);let u;try{u=JSON.parse(c)}catch{throw Error(`Cancel route returned invalid JSON (${o.status}).`)}let d=CancelTurnResponseSchema.safeParse(u);if(!d.success||d.data.sessionId!==n)throw Error(`Cancel route returned an invalid response (${o.status}).`);return{sessionId:d.data.sessionId,status:d.data.status}}stream(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);return this.#i(t,e)}async#n(t,i){let a=i.sessionId?createEveContinueSessionRoutePath(i.sessionId):EVE_CREATE_SESSION_ROUTE_PATH,o=createClientUrl(this.#e.host,a),c=await this.#e.resolveHeaders(t.headers);c.set(`content-type`,`application/json`);let l=createHandleMessageBody({input:t,outputSchema:serializeOutputSchema(t.outputSchema),session:i});if(l===null)throw Error(`Session.send requires a non-empty message, inputResponses, or both.`);let u=await postTurnWithRetry({body:JSON.stringify(l),headers:c,mustDeliver:(t.inputResponses?.length??0)>0,redirect:this.#e.redirect,signal:t.signal,url:o}),f=await u.json(),p=(typeof f.sessionId==`string`?f.sessionId:void 0)??u.headers.get(EVE_SESSION_ID_HEADER)?.trim()??i.sessionId;if(!p)throw Error(`Message route did not return a session id.`);return{continuationToken:typeof f.continuationToken==`string`?f.continuationToken:void 0,sessionId:p}}async*#r(e,t,n,r){let a=[];try{for await(let t of followStreamIterable({host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(r.headers),redirect:this.#e.redirect,streamReconnectPolicy:r.streamReconnectPolicy,sessionId:e,signal:r.signal,startIndex:n.sessionId===e?n.streamIndex:0}))if(a.push(t),yield t,isCurrentTurnBoundaryEvent(t))break}finally{this.#t=advanceSession({continuationToken:t,events:a,preserveCompletedSessions:this.#e.preserveCompletedSessions,sessionId:e,session:n})}}async*#i(e,t){let n=this.#t,r=t?.startIndex??n.streamIndex,i=[];try{for await(let n of followStreamIterable({host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(),redirect:this.#e.redirect,streamReconnectPolicy:t?.streamReconnectPolicy,sessionId:e,signal:t?.signal,startIndex:r}))i.push(n),yield n}finally{r>=0&&(this.#t=advanceSession({continuationToken:n.continuationToken,events:i,preserveCompletedSessions:this.#e.preserveCompletedSessions,session:{...n,sessionId:e,streamIndex:r},sessionId:e}))}}};async function postTurnWithRetry(e){let t=e.mustDeliver?10:1,n,r,i;for(let o=0;o<t;o+=1){let s=await fetch(e.url,{body:e.body,headers:e.headers,method:`POST`,redirect:e.redirect,signal:e.signal??null});if(s.ok)return s;if(n=s.status,r=await s.text(),i=s.headers,!isRetryableDeliveryFailure(s.status,r))throw new ClientError(s.status,r,s.headers);o<t-1&&await sleep(200)}throw new ClientError(n??0,r??`Failed to deliver session turn.`,i)}function isRetryableDeliveryFailure(e,t){return e===500&&/target session was not found/i.test(t)}async function sleep(e){await new Promise(t=>setTimeout(t,e))}function normalizeSendTurnInput(e){return typeof e==`string`?{message:e}:e}function createHandleMessageBody(e){let t={};return e.input.message!==void 0&&(t.message=e.input.message),e.input.inputResponses!==void 0&&e.input.inputResponses.length>0&&(t.inputResponses=e.input.inputResponses),e.input.clientContext!==void 0&&(t.clientContext=e.input.clientContext),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.session.continuationToken!==void 0&&(t.continuationToken=e.session.continuationToken),Object.keys(t).length===0||e.session.continuationToken===void 0&&t.message===void 0||e.session.continuationToken!==void 0&&t.message===void 0&&t.inputResponses===void 0?null:t}function withRedirectPolicy(e,t){return t===void 0?e:{...e,redirect:t}}export{ClientSession};
1
+ import{EVE_CREATE_SESSION_ROUTE_PATH,EVE_RESET_SESSION_ROUTE_PATH,createEveCancelTurnRoutePath,createEveContinueSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{advanceSession,createInitialSessionState}from"#client/session-utils.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{ResetResponseSchema}from"#protocol/reset-session.js";import{followStreamIterable}from"#client/open-stream.js";import{serializeOutputSchema}from"#shared/tool-schema.js";var ClientSession=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get state(){return this.#t}async send(e){let t=normalizeSendTurnInput(e),n=this.#t,{continuationToken:r,sessionId:i}=await this.#n(t,n);if(this.#t===n){let e={...n,sessionId:i};r!==void 0&&(e.continuationToken=r),this.#t=e}return new MessageResponse({continuationToken:r,createStream:()=>this.#r(i,r,n,t),sessionId:i})}async cancel(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);let r=createClientUrl(this.#e.host,createEveCancelTurnRoutePath(t)),i=await this.#e.resolveHeaders();i.set(`content-type`,`application/json`);let a=await fetch(r,withRedirectPolicy({headers:i,method:`POST`,body:e?JSON.stringify(e):void 0},this.#e.redirect)),s=await a.text();if(!a.ok)throw new ClientError(a.status,s,a.headers);let c;try{c=JSON.parse(s)}catch{throw Error(`Cancel route returned invalid JSON (${a.status}).`)}let l=CancelTurnResponseSchema.safeParse(c);if(!l.success||l.data.sessionId!==t)throw Error(`Cancel route returned an invalid response (${a.status}).`);return{sessionId:l.data.sessionId,status:l.data.status}}async reset(){let e=this.#t,n=e.continuationToken;if(n===void 0){if(e.sessionId!==void 0)throw Error(`Session has no continuation token. Consume its event stream before resetting.`);return this.#t=createInitialSessionState(),{status:`no_active_session`}}let r=createClientUrl(this.#e.host,EVE_RESET_SESSION_ROUTE_PATH),i=await this.#e.resolveHeaders();i.set(`content-type`,`application/json`);let a=await fetch(r,withRedirectPolicy({body:JSON.stringify({continuationToken:n}),headers:i,method:`POST`},this.#e.redirect)),s=await a.text();if(!a.ok)throw new ClientError(a.status,s,a.headers);let l;try{l=JSON.parse(s)}catch{throw Error(`Reset route returned invalid JSON (${a.status}).`)}let u=ResetResponseSchema.safeParse(l);if(!u.success||u.data.status===`reset`&&e.sessionId!==void 0&&u.data.previousSessionId!==e.sessionId)throw Error(`Reset route returned an invalid response (${a.status}).`);return this.#t===e&&(this.#t=createInitialSessionState()),u.data.status===`reset`?{previousSessionId:u.data.previousSessionId,status:`reset`}:{status:`no_active_session`}}stream(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);return this.#i(t,e)}async#n(t,n){let a=n.sessionId?createEveContinueSessionRoutePath(n.sessionId):EVE_CREATE_SESSION_ROUTE_PATH,o=createClientUrl(this.#e.host,a),s=await this.#e.resolveHeaders(t.headers);s.set(`content-type`,`application/json`);let c=createHandleMessageBody({input:t,outputSchema:serializeOutputSchema(t.outputSchema),session:n});if(c===null)throw Error(`Session.send requires a non-empty message, inputResponses, or both.`);let l=await postTurnWithRetry({body:JSON.stringify(c),headers:s,mustDeliver:(t.inputResponses?.length??0)>0,redirect:this.#e.redirect,signal:t.signal,url:o}),u=await l.json(),d=(typeof u.sessionId==`string`?u.sessionId:void 0)??l.headers.get(EVE_SESSION_ID_HEADER)?.trim()??n.sessionId;if(!d)throw Error(`Message route did not return a session id.`);return{continuationToken:typeof u.continuationToken==`string`?u.continuationToken:void 0,sessionId:d}}async*#r(e,t,n,r){let i=[];try{for await(let t of followStreamIterable({host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(r.headers),redirect:this.#e.redirect,streamReconnectPolicy:r.streamReconnectPolicy,sessionId:e,signal:r.signal,startIndex:n.sessionId===e?n.streamIndex:0}))if(i.push(t),yield t,isCurrentTurnBoundaryEvent(t))break}finally{this.#t=advanceSession({continuationToken:t,events:i,preserveCompletedSessions:this.#e.preserveCompletedSessions,sessionId:e,session:n})}}async*#i(e,t){let n=this.#t,r=t?.startIndex??n.streamIndex,i=[];try{for await(let n of followStreamIterable({host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(),redirect:this.#e.redirect,streamReconnectPolicy:t?.streamReconnectPolicy,sessionId:e,signal:t?.signal,startIndex:r}))i.push(n),yield n}finally{r>=0&&(this.#t=advanceSession({continuationToken:n.continuationToken,events:i,preserveCompletedSessions:this.#e.preserveCompletedSessions,session:{...n,sessionId:e,streamIndex:r},sessionId:e}))}}};async function postTurnWithRetry(e){let t=e.mustDeliver?10:1,n,r,i;for(let a=0;a<t;a+=1){let s=await fetch(e.url,{body:e.body,headers:e.headers,method:`POST`,redirect:e.redirect,signal:e.signal??null});if(s.ok)return s;if(n=s.status,r=await s.text(),i=s.headers,!isRetryableDeliveryFailure(s.status,r))throw new ClientError(s.status,r,s.headers);a<t-1&&await sleep(200)}throw new ClientError(n??0,r??`Failed to deliver session turn.`,i)}function isRetryableDeliveryFailure(e,t){return e===500&&/target session was not found/i.test(t)}async function sleep(e){await new Promise(t=>setTimeout(t,e))}function normalizeSendTurnInput(e){return typeof e==`string`?{message:e}:e}function createHandleMessageBody(e){let t={};return e.input.message!==void 0&&(t.message=e.input.message),e.input.inputResponses!==void 0&&e.input.inputResponses.length>0&&(t.inputResponses=e.input.inputResponses),e.input.clientContext!==void 0&&(t.clientContext=e.input.clientContext),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.session.continuationToken!==void 0&&(t.continuationToken=e.session.continuationToken),Object.keys(t).length===0||e.session.continuationToken===void 0&&t.message===void 0||e.session.continuationToken!==void 0&&t.message===void 0&&t.inputResponses===void 0?null:t}function withRedirectPolicy(e,t){return t===void 0?e:{...e,redirect:t}}export{ClientSession};
@@ -2,6 +2,7 @@ import type { UserContent } from "ai";
2
2
  import type { StandardJSONSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
3
3
  import type { HandleMessageStreamEvent } from "#protocol/message.js";
4
4
  import type { CancelTurnStatus } from "#protocol/cancel-turn.js";
5
+ import type { ResetStatus } from "#protocol/reset-session.js";
5
6
  import type { InputRequest, InputResponse } from "#runtime/input/types.js";
6
7
  import type { JsonObject } from "#shared/json.js";
7
8
  export type { AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoEntry, AgentInfoFrameworkChannelEntry, AgentInfoFrameworkToolEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, } from "./agent-info-schema.js";
@@ -181,6 +182,15 @@ export interface CancelSessionResult {
181
182
  /** Both outcomes are successful; `no_active_turn` means there was nothing left to cancel. */
182
183
  readonly status: CancelTurnStatus;
183
184
  }
185
+ /** Result of terminally resetting a client session. */
186
+ export type ResetResult = {
187
+ /** The prior session was retired and its continuation token released. */
188
+ readonly previousSessionId: string;
189
+ readonly status: Extract<ResetStatus, "reset">;
190
+ } | {
191
+ /** The client had no continuation token or the token was already free. */
192
+ readonly status: Extract<ResetStatus, "no_active_session">;
193
+ };
184
194
  /**
185
195
  * Aggregated result of one message turn, returned by
186
196
  * {@link MessageResponse.result}.
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{RuntimeNoActiveSessionError}from"#execution/runtime-errors.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{getHookByToken,getRun,resumeHook,start}from"#internal/workflow/runtime.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{sessionCancelHookToken}from"#execution/turn-cancellation-token.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async run(n){let r=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),i=serializeContext(buildRunContext({bundle:r,run:n})),a=readParentLineage(i),o=a.sessionId===void 0?buildSessionAttributes({inputMessage:n.title??n.input.message,serializedContext:i}):buildSubagentRootAttributes({identity:{nodeId:r.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:a.callId,parentSessionId:a.sessionId,parentTurnId:a.turnId,rootSessionId:a.rootSessionId??a.sessionId,serializedContext:i}),s;try{s=await startWorkflowPreferLatest(workflowEntryReference,[{input:n.input,limits:n.limits,serializedContext:i}],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(o)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:n.continuationToken}),e}let c,getEvents=()=>(c??=parseNdjsonStream(()=>getRun(s.runId).getReadable()),c);return{continuationToken:n.continuationToken??s.runId,get events(){return getEvents()},sessionId:s.runId}},async cancelTurn(e){return await requestWorkflowTurnCancellation(e)},async deliver(e){let r={auth:e.auth,kind:`deliver`,payloads:[e.payload],requestId:e.requestId};try{return{sessionId:normalizeWorkflowHook(await resumeHook(e.continuationToken,r)).runId}}catch(r){throw HookNotFoundError.is(r)?new RuntimeNoActiveSessionError(e.continuationToken):(logError(log,`failed to deliver to active session`,r,{continuationToken:e.continuationToken}),r)}},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))},async resolveSession(e){try{return{sessionId:(await getHookByToken(e)).runId}}catch(n){if(HookNotFoundError.is(n))return;throw logError(log,`failed to resolve session by continuation token`,n,{continuationToken:e}),n}}}}async function requestWorkflowTurnCancellation(e){let t=e.turnId===void 0?{}:{turnId:e.turnId};try{return await resumeHook(sessionCancelHookToken(e.sessionId),t),{status:`accepted`}}catch(e){if(isInactiveCancelTarget(e))return{status:`no_active_turn`};throw e}}function isInactiveCancelTarget(e){return HookNotFoundError.is(e)||WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e)||EntityConflictError.is(e)}async function startWorkflowPreferLatest(e,t,n){if(!shouldRouteToLatestDeployment())return n===void 0?await start(e,t):await start(e,t,n);try{return await start(e,t,{...n,deploymentId:`latest`})}catch(r){if(!isLatestDeploymentUnsupportedError(r))throw r;return n===void 0?await start(e,t):await start(e,t,n)}}function shouldRouteToLatestDeployment(){return process.env.VERCEL_ENV===`production`||isEveDevEnvironment()}function isLatestDeploymentUnsupportedError(e){return e instanceof Error&&e.message.includes(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}export{LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,STABLE_WORKFLOW_NAMES,createWorkflowRuntime,requestWorkflowTurnCancellation,startWorkflowPreferLatest,turnWorkflowReference,workflowEntryReference};
1
+ import{createLogger,logError}from"#internal/logging.js";import{RuntimeNoActiveSessionError}from"#execution/runtime-errors.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{cancelRun,getHookByToken,getRun,getWorld,resumeHook,start}from"#internal/workflow/runtime.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{sessionCancelHookToken}from"#execution/turn-cancellation-token.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async run(n){let r=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),i=serializeContext(buildRunContext({bundle:r,run:n})),a=readParentLineage(i),o=a.sessionId===void 0?buildSessionAttributes({inputMessage:n.title??n.input.message,serializedContext:i}):buildSubagentRootAttributes({identity:{nodeId:r.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:a.callId,parentSessionId:a.sessionId,parentTurnId:a.turnId,rootSessionId:a.rootSessionId??a.sessionId,serializedContext:i}),s;try{s=await startWorkflowPreferLatest(workflowEntryReference,[{input:n.input,limits:n.limits,serializedContext:i}],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(o)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:n.continuationToken}),e}let c,getEvents=()=>(c??=parseNdjsonStream(()=>getRun(s.runId).getReadable()),c);return{continuationToken:n.continuationToken??s.runId,get events(){return getEvents()},sessionId:s.runId}},async cancelTurn(e){return await requestWorkflowTurnCancellation(e)},async terminateSession(e){try{return await cancelRun(await getWorld(),e.sessionId,{cancelReason:e.reason??`Session reset by channel`}),{status:`terminated`}}catch(e){if(isAlreadyTerminalSessionError(e))return{status:`already_terminal`};throw e}},async deliver(e){let r={auth:e.auth,kind:`deliver`,payloads:[e.payload],requestId:e.requestId};try{return{sessionId:normalizeWorkflowHook(await resumeHook(e.continuationToken,r)).runId}}catch(r){throw HookNotFoundError.is(r)?new RuntimeNoActiveSessionError(e.continuationToken):(logError(log,`failed to deliver to active session`,r,{continuationToken:e.continuationToken}),r)}},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))},async resolveSession(e){try{return{sessionId:(await getHookByToken(e)).runId}}catch(n){if(HookNotFoundError.is(n))return;throw logError(log,`failed to resolve session by continuation token`,n,{continuationToken:e}),n}}}}async function requestWorkflowTurnCancellation(e){let t=e.turnId===void 0?{}:{turnId:e.turnId};try{return await resumeHook(sessionCancelHookToken(e.sessionId),t),{status:`accepted`}}catch(e){if(isInactiveCancelTarget(e))return{status:`no_active_turn`};throw e}}function isInactiveCancelTarget(e){return HookNotFoundError.is(e)||WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e)||EntityConflictError.is(e)}function isAlreadyTerminalSessionError(e){for(let t of walkCauseChain(e))if(WorkflowRunNotFoundError.is(t)||RunExpiredError.is(t)||EntityConflictError.is(t))return!0;return!1}async function startWorkflowPreferLatest(e,t,n){if(!shouldRouteToLatestDeployment())return n===void 0?await start(e,t):await start(e,t,n);try{return await start(e,t,{...n,deploymentId:`latest`})}catch(r){if(!isLatestDeploymentUnsupportedError(r))throw r;return n===void 0?await start(e,t):await start(e,t,n)}}function shouldRouteToLatestDeployment(){return process.env.VERCEL_ENV===`production`||isEveDevEnvironment()}function isLatestDeploymentUnsupportedError(e){return e instanceof Error&&e.message.includes(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}export{LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,STABLE_WORKFLOW_NAMES,createWorkflowRuntime,requestWorkflowTurnCancellation,startWorkflowPreferLatest,turnWorkflowReference,workflowEntryReference};
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.27.3`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
1
+ import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.27.4`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{lstat,readlink,realpath}from"node:fs/promises";import{parseTsConfigObject,readTextFileIfExists,resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";const DEV_RUNTIME_SOURCE_DIRECTORY=`source`,SOURCE_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WORKSPACE_METADATA_FILE_NAMES=[`package.json`,`pnpm-workspace.yaml`,`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`,`.npmrc`],PACKAGE_DEPENDENCY_FIELDS=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`];var DevelopmentRuntimeSourceSnapshotError=class extends Error{constructor(e){super(e),this.name=`DevelopmentRuntimeSourceSnapshotError`}};async function createDevelopmentSourceSnapshotPlan(e){let t=resolve(e.appRoot),r=resolve(e.snapshotRoot),a=resolveDevelopmentSourceRoot(t),o=join(r,DEV_RUNTIME_SOURCE_DIRECTORY),s={appRoot:t,copyFiles:new Set,copyRoots:new Set,dependencyMountsByPath:new Map,localRootsToProcess:[t],processedLocalRoots:new Set,snapshotRoot:r,snapshotSourceRoot:o,sourceRoot:a,tsconfigPaths:new Set};for(addWorkspaceMetadataFiles(s);s.localRootsToProcess.length>0;){let e=s.localRootsToProcess.shift();if(e===void 0)continue;let t=resolve(e);s.processedLocalRoots.has(t)||!isAuthoredSourcePath(t,a)||(s.processedLocalRoots.add(t),s.copyRoots.add(t),await addTsConfigDependenciesForRoot(s,t),await addDependencyMountsForRoot(s,t))}let c=normalizeCopyRoots([...s.copyRoots]),l=[...s.copyFiles].filter(e=>isPathInsideOrEqual(e,a)).sort((e,t)=>e.localeCompare(t)),u=[...s.tsconfigPaths].filter(e=>isPathInsideOrEqual(e,a)).sort((e,t)=>e.localeCompare(t)),d=[...s.dependencyMountsByPath.values()].sort((e,t)=>e.mountPath.localeCompare(t.mountPath)),f=createWatchPaths({appRoot:t,copyFiles:l,copyRoots:c,dependencyMounts:d,sourceRoot:a,tsconfigPaths:u});return{appRoot:t,copyFiles:l,copyRoots:c,dependencyMounts:d,runtimeAppRoot:toSnapshotPath({sourcePath:t,sourceRoot:a,snapshotSourceRoot:o}),snapshotRoot:r,snapshotSourceRoot:o,sourceRoot:a,tsconfigPaths:u,watchPaths:f}}async function resolveDevelopmentSourceSnapshotWatchPaths(e){return[...(await createDevelopmentSourceSnapshotPlan({appRoot:e,snapshotRoot:join(resolve(e),`.eve`,`dev-runtime`,`__watch-plan__`)})).watchPaths]}function toDevelopmentSourceSnapshotPath(e){return toSnapshotPath(e)}function resolveDevelopmentSourceRoot(r){let a=resolve(r);for(;;){if(SOURCE_ROOT_MARKER_NAMES.some(t=>existsSync(join(a,t))))return a;let o=dirname(a);if(o===a)return resolve(r);a=o}}function addWorkspaceMetadataFiles(t){for(let r of WORKSPACE_METADATA_FILE_NAMES){let i=join(t.sourceRoot,r);existsSync(i)&&t.copyFiles.add(i)}}async function addTsConfigDependenciesForRoot(e,t){let n=await resolveTsConfigDependencyPaths(t);for(let t of n)if(isPathInsideOrEqual(t,e.sourceRoot)){e.tsconfigPaths.add(t),e.copyFiles.add(t);for(let n of await resolveLocalTsConfigPathTargetRoots({configPath:t,sourceRoot:e.sourceRoot}))enqueueLocalRoot(e,n)}}async function addDependencyMountsForRoot(e,t){let n=await readPackageDependencyNames(t);for(let r of n)for(let n of[t,e.sourceRoot])await addDependencyMount(e,joinNodeModulesPackagePath(n,r))}async function addDependencyMount(t,n){let r;try{r=await lstat(n)}catch{return}if(!r.isDirectory()&&!r.isSymbolicLink())return;let a=await resolveDependencySourcePathCandidates(n),s=a.find(e=>isAuthoredSourcePath(e,t.sourceRoot));if(s!==void 0){await addWorkspaceDependencyMount({mountPath:n,state:t,sourcePath:s});return}let c=a.find(t=>existsSync(t));c!==void 0&&t.dependencyMountsByPath.set(resolve(n),{mountPath:resolve(n),sourceKind:`installed`,sourcePath:c})}async function addWorkspaceDependencyMount(e){let t=await resolveNearestPackageRoot(e.sourcePath,e.state.sourceRoot);if(t===void 0||!isAuthoredSourcePath(t,e.state.sourceRoot))return;let{state:n}=e;enqueueLocalRoot(n,t),n.dependencyMountsByPath.set(resolve(e.mountPath),{mountPath:resolve(e.mountPath),sourceKind:`workspace`,sourcePath:t})}async function resolveDependencySourcePathCandidates(e){let n=new Set;try{let r=await readlink(e);n.add(resolve(dirname(e),r))}catch{}try{n.add(await realpath(e))}catch{}return[...n]}function enqueueLocalRoot(e,t){let n=resolve(t);e.processedLocalRoots.has(n)||e.localRootsToProcess.includes(n)||!isAuthoredSourcePath(n,e.sourceRoot)||e.localRootsToProcess.push(n)}async function readPackageDependencyNames(e){let t=await readTextFileIfExists(join(e,`package.json`));if(t===void 0)return[];let r;try{r=JSON.parse(t)}catch{return[]}if(!isObjectRecord(r))return[];let i=new Set;for(let e of PACKAGE_DEPENDENCY_FIELDS){let t=r[e];if(isObjectRecord(t))for(let e of Object.keys(t))i.add(e)}return[...i].sort((e,t)=>e.localeCompare(t))}async function resolveLocalTsConfigPathTargetRoots(e){let n=await readTextFileIfExists(e.configPath);if(n===void 0)return[];let r=parseTsConfigObject(n),a=isObjectRecord(r?.compilerOptions)?r.compilerOptions:void 0,o=isObjectRecord(a?.paths)?a.paths:void 0;if(a===void 0||o===void 0)return[];let s=typeof a.baseUrl==`string`?resolve(dirname(e.configPath),a.baseUrl):dirname(e.configPath),c=new Set;for(let t of Object.values(o))if(Array.isArray(t))for(let n of t){if(typeof n!=`string`||n.length===0)continue;let t=await resolveLocalTsConfigPathTargetRoot({baseDirectory:s,sourceRoot:e.sourceRoot,target:n});t!==void 0&&c.add(t)}return[...c].sort((e,t)=>e.localeCompare(t))}async function resolveLocalTsConfigPathTargetRoot(e){let t=e.target.includes(`*`),n=t?e.target.slice(0,e.target.indexOf(`*`)):e.target;if(n.length===0||n===`.`||n===`./`)return;let r=resolve(e.baseDirectory,n);if(!isAuthoredSourcePath(r,e.sourceRoot))return;let a=await resolveExistingPathOrAncestor({path:r,stopDirectory:e.sourceRoot});if(a===void 0)return;let o=await resolveNearestPackageRoot(a,e.sourceRoot);if(o!==void 0&&o!==e.sourceRoot)return o;if(!t)return a===e.sourceRoot?void 0:a}async function resolveExistingPathOrAncestor(n){let r=resolve(n.path);for(;isAuthoredSourcePath(r,n.stopDirectory);){if(existsSync(r))return r;let n=dirname(r);if(n===r)return;r=n}}async function resolveNearestPackageRoot(r,a){let s=resolve(r);try{(await lstat(s)).isDirectory()||(s=dirname(s))}catch{s=dirname(s)}for(;isAuthoredSourcePath(s,a);){if(existsSync(join(s,`package.json`)))return s;let r=dirname(s);if(r===s)return;s=r}}function normalizeCopyRoots(e){let t=[...new Set(e.map(e=>resolve(e)))].sort((e,t)=>{let n=e.length-t.length;return n===0?e.localeCompare(t):n}),n=[];for(let e of t)n.some(t=>isPathInsideOrEqual(e,t))||n.push(e);return n.sort((e,t)=>e.localeCompare(t))}function createWatchPaths(t){let r=new Set([join(t.appRoot,`package.json`),...t.copyFiles,...t.tsconfigPaths]);for(let e of t.copyRoots)e!==t.appRoot&&r.add(e);for(let e of t.dependencyMounts)e.sourceKind===`workspace`&&e.sourcePath!==t.appRoot&&r.add(e.sourcePath);if(t.sourceRoot!==t.appRoot)for(let i of WORKSPACE_METADATA_FILE_NAMES){let a=join(t.sourceRoot,i);existsSync(a)&&r.add(a)}return[...r].sort((e,t)=>e.localeCompare(t))}function joinNodeModulesPackagePath(e,t){return join(e,`node_modules`,...t.split(`/`))}function toSnapshotPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.sourceRoot))throw new DevelopmentRuntimeSourceSnapshotError(`Cannot map source path "${e.sourcePath}" into a development runtime snapshot because it is outside source root "${e.sourceRoot}".`);return join(e.snapshotSourceRoot,relative(e.sourceRoot,e.sourcePath))}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAuthoredSourcePath(e,t){return isPathInsideOrEqual(e,t)?!relative(t,e).split(/[\\/]/).includes(`node_modules`):!1}function isObjectRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{DEV_RUNTIME_SOURCE_DIRECTORY,DevelopmentRuntimeSourceSnapshotError,createDevelopmentSourceSnapshotPlan,isAuthoredSourcePath,resolveDevelopmentSourceRoot,resolveDevelopmentSourceSnapshotWatchPaths,toDevelopmentSourceSnapshotPath};
1
+ import{existsSync,readFileSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{lstat,readlink,realpath}from"node:fs/promises";import{parseTsConfigObject,readTextFileIfExists,resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";const DEV_RUNTIME_SOURCE_DIRECTORY=`source`,SOURCE_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WORKSPACE_METADATA_FILE_NAMES=[`package.json`,`pnpm-workspace.yaml`,`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`,`.npmrc`],PACKAGE_DEPENDENCY_FIELDS=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`];var DevelopmentRuntimeSourceSnapshotError=class extends Error{constructor(e){super(e),this.name=`DevelopmentRuntimeSourceSnapshotError`}};async function createDevelopmentSourceSnapshotPlan(e){let t=resolve(e.appRoot),n=resolve(e.snapshotRoot),i=resolveDevelopmentSourceRoot(t),o=join(n,DEV_RUNTIME_SOURCE_DIRECTORY),s={appRoot:t,copyFiles:new Set,copyRoots:new Set,dependencyMountsByPath:new Map,localRootsToProcess:[t],processedLocalRoots:new Set,snapshotRoot:n,snapshotSourceRoot:o,sourceRoot:i,tsconfigPaths:new Set};for(addWorkspaceMetadataFiles(s);s.localRootsToProcess.length>0;){let e=s.localRootsToProcess.shift();if(e===void 0)continue;let t=resolve(e);s.processedLocalRoots.has(t)||!isAuthoredSourcePath(t,i)||(s.processedLocalRoots.add(t),s.copyRoots.add(t),await addTsConfigDependenciesForRoot(s,t),await addDependencyMountsForRoot(s,t))}let c=normalizeCopyRoots([...s.copyRoots]),l=[...s.copyFiles].filter(e=>isPathInsideOrEqual(e,i)).sort((e,t)=>e.localeCompare(t)),u=[...s.tsconfigPaths].filter(e=>isPathInsideOrEqual(e,i)).sort((e,t)=>e.localeCompare(t)),d=[...s.dependencyMountsByPath.values()].sort((e,t)=>e.mountPath.localeCompare(t.mountPath)),f=createWatchPaths({appRoot:t,copyFiles:l,copyRoots:c,dependencyMounts:d,sourceRoot:i,tsconfigPaths:u});return{appRoot:t,copyFiles:l,copyRoots:c,dependencyMounts:d,runtimeAppRoot:toSnapshotPath({sourcePath:t,sourceRoot:i,snapshotSourceRoot:o}),snapshotRoot:n,snapshotSourceRoot:o,sourceRoot:i,tsconfigPaths:u,watchPaths:f}}async function resolveDevelopmentSourceSnapshotWatchPaths(e){return[...(await createDevelopmentSourceSnapshotPlan({appRoot:e,snapshotRoot:join(resolve(e),`.eve`,`dev-runtime`,`__watch-plan__`)})).watchPaths]}function toDevelopmentSourceSnapshotPath(e){return toSnapshotPath(e)}function resolveDevelopmentSourceRoot(t){let i=resolve(t);for(;;){if(SOURCE_ROOT_MARKER_NAMES.some(t=>existsSync(join(i,t)))||isWorkspaceManifestRoot(i))return i;let o=dirname(i);if(o===i)return resolve(t);i=o}}function addWorkspaceMetadataFiles(t){for(let n of WORKSPACE_METADATA_FILE_NAMES){let i=join(t.sourceRoot,n);existsSync(i)&&t.copyFiles.add(i)}}async function addTsConfigDependenciesForRoot(e,t){let n=await resolveTsConfigDependencyPaths(t);for(let t of n)if(isPathInsideOrEqual(t,e.sourceRoot)){e.tsconfigPaths.add(t),e.copyFiles.add(t);for(let n of await resolveLocalTsConfigPathTargetRoots({configPath:t,sourceRoot:e.sourceRoot}))enqueueLocalRoot(e,n)}}async function addDependencyMountsForRoot(e,t){let n=await readPackageDependencyNames(resolveDependencyDeclarationRoot(t,e.sourceRoot));for(let r of n)for(let n of listAncestorNodeModulesRoots(t,e.sourceRoot))await addDependencyMount(e,joinNodeModulesPackagePath(n,r))}function resolveDependencyDeclarationRoot(t,i){let o=resolve(t),s=resolve(i);for(;isPathInsideOrEqual(o,s);){if(existsSync(join(o,`package.json`)))return o;let t=dirname(o);if(t===o)break;o=t}return t}function listAncestorNodeModulesRoots(e,t){let r=resolve(t),i=new Set,o=resolve(e);for(;isPathInsideOrEqual(o,r);){i.add(o);let e=dirname(o);if(e===o)break;o=e}return i.add(resolve(e)),i.add(r),[...i]}function isWorkspaceManifestRoot(n){let i=join(n,`package.json`);if(!existsSync(i))return!1;try{let e=JSON.parse(readFileSync(i,`utf8`));return isObjectRecord(e)&&e.workspaces!==void 0}catch{return!1}}async function addDependencyMount(t,n){let r;try{r=await lstat(n)}catch{return}if(!r.isDirectory()&&!r.isSymbolicLink())return;let i=await resolveDependencySourcePathCandidates(n),o=i.find(e=>isAuthoredSourcePath(e,t.sourceRoot));if(o!==void 0){await addWorkspaceDependencyMount({mountPath:n,state:t,sourcePath:o});return}let c=i.find(t=>existsSync(t));c!==void 0&&t.dependencyMountsByPath.set(resolve(n),{mountPath:resolve(n),sourceKind:`installed`,sourcePath:c})}async function addWorkspaceDependencyMount(e){let t=await resolveNearestPackageRoot(e.sourcePath,e.state.sourceRoot);if(t===void 0||!isAuthoredSourcePath(t,e.state.sourceRoot))return;let{state:n}=e;enqueueLocalRoot(n,t),n.dependencyMountsByPath.set(resolve(e.mountPath),{mountPath:resolve(e.mountPath),sourceKind:`workspace`,sourcePath:t})}async function resolveDependencySourcePathCandidates(e){let t=new Set;try{let r=await readlink(e);t.add(resolve(dirname(e),r))}catch{}try{t.add(await realpath(e))}catch{}return[...t]}function enqueueLocalRoot(e,t){let n=resolve(t);e.processedLocalRoots.has(n)||e.localRootsToProcess.includes(n)||!isAuthoredSourcePath(n,e.sourceRoot)||e.localRootsToProcess.push(n)}async function readPackageDependencyNames(e){let t=await readTextFileIfExists(join(e,`package.json`));if(t===void 0)return[];let n;try{n=JSON.parse(t)}catch{return[]}if(!isObjectRecord(n))return[];let i=new Set;for(let e of PACKAGE_DEPENDENCY_FIELDS){let t=n[e];if(isObjectRecord(t))for(let e of Object.keys(t))i.add(e)}return[...i].sort((e,t)=>e.localeCompare(t))}async function resolveLocalTsConfigPathTargetRoots(e){let t=await readTextFileIfExists(e.configPath);if(t===void 0)return[];let r=parseTsConfigObject(t),i=isObjectRecord(r?.compilerOptions)?r.compilerOptions:void 0,o=isObjectRecord(i?.paths)?i.paths:void 0;if(i===void 0||o===void 0)return[];let s=typeof i.baseUrl==`string`?resolve(dirname(e.configPath),i.baseUrl):dirname(e.configPath),c=new Set;for(let t of Object.values(o))if(Array.isArray(t))for(let n of t){if(typeof n!=`string`||n.length===0)continue;let t=await resolveLocalTsConfigPathTargetRoot({baseDirectory:s,sourceRoot:e.sourceRoot,target:n});t!==void 0&&c.add(t)}return[...c].sort((e,t)=>e.localeCompare(t))}async function resolveLocalTsConfigPathTargetRoot(e){let t=e.target.includes(`*`),n=t?e.target.slice(0,e.target.indexOf(`*`)):e.target;if(n.length===0||n===`.`||n===`./`)return;let r=resolve(e.baseDirectory,n);if(!isAuthoredSourcePath(r,e.sourceRoot))return;let i=await resolveExistingPathOrAncestor({path:r,stopDirectory:e.sourceRoot});if(i===void 0)return;let o=await resolveNearestPackageRoot(i,e.sourceRoot);if(o!==void 0&&o!==e.sourceRoot)return o;if(!t)return i===e.sourceRoot?void 0:i}async function resolveExistingPathOrAncestor(t){let r=resolve(t.path);for(;isAuthoredSourcePath(r,t.stopDirectory);){if(existsSync(r))return r;let t=dirname(r);if(t===r)return;r=t}}async function resolveNearestPackageRoot(t,i){let o=resolve(t);try{(await lstat(o)).isDirectory()||(o=dirname(o))}catch{o=dirname(o)}for(;isAuthoredSourcePath(o,i);){if(existsSync(join(o,`package.json`)))return o;let t=dirname(o);if(t===o)return;o=t}}function normalizeCopyRoots(e){let t=[...new Set(e.map(e=>resolve(e)))].sort((e,t)=>{let n=e.length-t.length;return n===0?e.localeCompare(t):n}),n=[];for(let e of t)n.some(t=>isPathInsideOrEqual(e,t))||n.push(e);return n.sort((e,t)=>e.localeCompare(t))}function createWatchPaths(t){let n=new Set([join(t.appRoot,`package.json`),...t.copyFiles,...t.tsconfigPaths]);for(let e of t.copyRoots)e!==t.appRoot&&n.add(e);for(let e of t.dependencyMounts)e.sourceKind===`workspace`&&e.sourcePath!==t.appRoot&&n.add(e.sourcePath);if(t.sourceRoot!==t.appRoot)for(let i of WORKSPACE_METADATA_FILE_NAMES){let a=join(t.sourceRoot,i);existsSync(a)&&n.add(a)}return[...n].sort((e,t)=>e.localeCompare(t))}function joinNodeModulesPackagePath(e,t){return join(e,`node_modules`,...t.split(`/`))}function toSnapshotPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.sourceRoot))throw new DevelopmentRuntimeSourceSnapshotError(`Cannot map source path "${e.sourcePath}" into a development runtime snapshot because it is outside source root "${e.sourceRoot}".`);return join(e.snapshotSourceRoot,relative(e.sourceRoot,e.sourcePath))}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAuthoredSourcePath(e,t){return isPathInsideOrEqual(e,t)?!relative(t,e).split(/[\\/]/).includes(`node_modules`):!1}function isObjectRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{DEV_RUNTIME_SOURCE_DIRECTORY,DevelopmentRuntimeSourceSnapshotError,createDevelopmentSourceSnapshotPlan,isAuthoredSourcePath,resolveDevelopmentSourceRoot,resolveDevelopmentSourceSnapshotWatchPaths,toDevelopmentSourceSnapshotPath};
@@ -1 +1 @@
1
- import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";import{readTrustedDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";import{createCancelFn}from"#channel/cancel.js";import{createResolveActiveSessionFn}from"#channel/resolve-active-session.js";import{attachAgentInfoRouteResponse,attachRouteAgent}from"#internal/nitro/routes/channel-route-context.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#runtime/governance/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let o=buildRouteArgs(e,i,a.name,r),s;try{s=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(a.handler)return await a.handler(e.req,o.args);let t={agent:o.agent,waitUntil:o.args.waitUntil,params:o.args.params,requestIp:o.args.requestIp};return await a.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),s}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let o=a.websocket,s=buildRouteArgs(e,i,a.name,r);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await o(e.req,s.args));return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n):await n()}function buildRouteArgs(t,n,o,s){let c=readVercelRequestId(t.req.headers),l=extractRequestIp(t,s),u=[],d=t.context.params??{},f={};for(let[e,t]of Object.entries(d))f[e]=decodeURIComponent(t);let waitUntil=e=>{u.push(e)},p=n.channels.find(e=>e.name===o)?.adapter??{kind:`channel`},m=createRouteAgent(n.runtime,c);return{agent:m,args:attachRouteAgent(attachAgentInfoRouteResponse({send:createSendFn(n.runtime,p,o,{requestId:c}),resolveActiveSession:createResolveActiveSessionFn(n.runtime,o),cancel:createCancelFn(n.runtime,o),getSession:createGetSessionFn(n.runtime),receive:createCrossChannelReceiveFn(n.runtime,toCrossChannelTargets(n.channels)),params:f,waitUntil,requestIp:l},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(s)}),m),backgroundTasks:u}}function createRouteAgent(e,t){return{async cancelTurn(t){return await e.cancelTurn(t)},async deliver(n){let r={...n,requestId:t};return await e.deliver(r)},async getEventStream(t,n){return await e.getEventStream(t,n)},async run(n){let r={...n,requestId:t};return await e.run(r)}}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractRequestIp(e,t){if(t.kind===`development`){let t=readTrustedDevelopmentClientAddress(e.req.headers,process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]);if(t!==void 0)return t}return extractSocketIp(e)}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
1
+ import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";import{readTrustedDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";import{createCancelFn}from"#channel/cancel.js";import{createResetFn}from"#channel/reset-session.js";import{createResolveActiveSessionFn}from"#channel/resolve-active-session.js";import{attachAgentInfoRouteResponse,attachRouteAgent}from"#internal/nitro/routes/channel-route-context.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#runtime/governance/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let o=buildRouteArgs(e,i,a.name,r),s;try{s=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(a.handler)return await a.handler(e.req,o.args);let t={agent:o.agent,waitUntil:o.args.waitUntil,params:o.args.params,requestIp:o.args.requestIp};return await a.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),s}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let o=a.websocket,s=buildRouteArgs(e,i,a.name,r);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await o(e.req,s.args));return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n):await n()}function buildRouteArgs(t,n,o,s){let c=readVercelRequestId(t.req.headers),l=extractRequestIp(t,s),u=[],d=t.context.params??{},f={};for(let[e,t]of Object.entries(d))f[e]=decodeURIComponent(t);let waitUntil=e=>{u.push(e)},p=n.channels.find(e=>e.name===o)?.adapter??{kind:`channel`},m=createRouteAgent(n.runtime,c);return{agent:m,args:attachRouteAgent(attachAgentInfoRouteResponse({send:createSendFn(n.runtime,p,o,{requestId:c}),resolveActiveSession:createResolveActiveSessionFn(n.runtime,o),cancel:createCancelFn(n.runtime,o),reset:createResetFn(n.runtime,o),getSession:createGetSessionFn(n.runtime),receive:createCrossChannelReceiveFn(n.runtime,toCrossChannelTargets(n.channels)),params:f,waitUntil,requestIp:l},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(s)}),m),backgroundTasks:u}}function createRouteAgent(e,t){return{async cancelTurn(t){return await e.cancelTurn(t)},async deliver(n){let r={...n,requestId:t};return await e.deliver(r)},async getEventStream(t,n){return await e.getEventStream(t,n)},async run(n){let r={...n,requestId:t};return await e.run(r)}}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractRequestIp(e,t){if(t.kind===`development`){let t=readTrustedDevelopmentClientAddress(e.req.headers,process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]);if(t!==void 0)return t}return extractSocketIp(e)}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};