eve 0.9.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/bin/eve.js +1 -0
  3. package/dist/src/cli/agent-detection.d.ts +8 -0
  4. package/dist/src/cli/agent-detection.js +1 -0
  5. package/dist/src/cli/commands/agent-instructions.d.ts +7 -0
  6. package/dist/src/cli/commands/agent-instructions.js +1 -0
  7. package/dist/src/cli/commands/init-agent-handoff.md +12 -0
  8. package/dist/src/cli/commands/init-agent-instructions.md +16 -0
  9. package/dist/src/cli/commands/init-git.js +1 -1
  10. package/dist/src/cli/commands/init.d.ts +8 -1
  11. package/dist/src/cli/commands/init.js +1 -1
  12. package/dist/src/cli/dev/environment.js +1 -1
  13. package/dist/src/cli/dev/tui/blocks.d.ts +8 -0
  14. package/dist/src/cli/dev/tui/blocks.js +2 -2
  15. package/dist/src/cli/dev/tui/command-typeahead.js +1 -1
  16. package/dist/src/cli/dev/tui/prompt-commands.d.ts +1 -1
  17. package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
  18. package/dist/src/cli/dev/tui/runner.d.ts +5 -0
  19. package/dist/src/cli/dev/tui/runner.js +1 -1
  20. package/dist/src/cli/dev/tui/setup-commands.d.ts +4 -0
  21. package/dist/src/cli/dev/tui/setup-commands.js +2 -2
  22. package/dist/src/cli/dev/tui/setup-issues.d.ts +15 -0
  23. package/dist/src/cli/dev/tui/setup-issues.js +1 -1
  24. package/dist/src/cli/dev/tui/terminal-renderer.d.ts +7 -2
  25. package/dist/src/cli/dev/tui/terminal-renderer.js +9 -9
  26. package/dist/src/cli/run.js +1 -1
  27. package/dist/src/compiled/.vendor-stamp.json +2 -1
  28. package/dist/src/compiled/@vercel/detect-agent/LICENSE +202 -0
  29. package/dist/src/compiled/@vercel/detect-agent/index.d.ts +20 -0
  30. package/dist/src/compiled/@vercel/detect-agent/index.js +1 -0
  31. package/dist/src/execution/sandbox/bindings/docker-templates.js +1 -1
  32. package/dist/src/execution/sandbox/bindings/just-bash.js +1 -1
  33. package/dist/src/execution/sandbox/bindings/microsandbox-templates.js +1 -1
  34. package/dist/src/internal/application/compiled-artifacts.js +1 -1
  35. package/dist/src/internal/application/optional-package-install.js +1 -1
  36. package/dist/src/internal/application/package.js +1 -1
  37. package/dist/src/internal/application/paths.js +1 -1
  38. package/dist/src/internal/application/tsconfig-dependencies.js +1 -1
  39. package/dist/src/internal/authored-module-loader.js +2 -2
  40. package/dist/src/internal/bundler/nitro-rolldown.d.ts +3 -0
  41. package/dist/src/internal/bundler/nitro-rolldown.js +1 -1
  42. package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
  43. package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
  44. package/dist/src/internal/nitro/dev-runtime-source-snapshot.js +1 -1
  45. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  46. package/dist/src/internal/nitro/host/start-development-server.d.ts +1 -2
  47. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  48. package/dist/src/internal/nitro/host/start-production-server.js +2 -2
  49. package/dist/src/internal/process/pnpm.js +1 -1
  50. package/dist/src/internal/workflow-bundle/builder-support.js +2 -2
  51. package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +1 -1
  52. package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
  53. package/dist/src/internal/workflow-bundle/workflow-transformer.js +3 -3
  54. package/dist/src/public/next/server.js +1 -1
  55. package/dist/src/setup/boxes/add-channels.js +1 -1
  56. package/dist/src/setup/boxes/apply-ai-gateway-credential.js +1 -1
  57. package/dist/src/setup/boxes/link-project.js +1 -1
  58. package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
  59. package/dist/src/setup/flows/channels.d.ts +2 -0
  60. package/dist/src/setup/flows/channels.js +1 -1
  61. package/dist/src/setup/flows/deploy.js +1 -1
  62. package/dist/src/setup/flows/install-vercel-cli.d.ts +42 -0
  63. package/dist/src/setup/flows/install-vercel-cli.js +1 -0
  64. package/dist/src/setup/flows/link.js +1 -1
  65. package/dist/src/setup/flows/login.d.ts +49 -0
  66. package/dist/src/setup/flows/login.js +1 -0
  67. package/dist/src/setup/flows/model.js +1 -1
  68. package/dist/src/setup/flows/vercel.d.ts +2 -0
  69. package/dist/src/setup/flows/vercel.js +1 -1
  70. package/dist/src/setup/primitives/coding-agent-env.d.ts +17 -0
  71. package/dist/src/setup/primitives/coding-agent-env.js +1 -0
  72. package/dist/src/setup/primitives/pm/pnpm.js +2 -2
  73. package/dist/src/setup/primitives/pm/run.d.ts +6 -0
  74. package/dist/src/setup/primitives/pm/run.js +1 -1
  75. package/dist/src/setup/primitives/run-vercel.d.ts +1 -1
  76. package/dist/src/setup/primitives/run-vercel.js +1 -1
  77. package/dist/src/setup/scaffold/create/project.js +1 -1
  78. package/dist/src/setup/scaffold/version-tokens.js +1 -1
  79. package/dist/src/setup/slack-connect-create.d.ts +41 -0
  80. package/dist/src/setup/slack-connect-create.js +1 -0
  81. package/dist/src/setup/slack-connect-lifecycle.d.ts +40 -11
  82. package/dist/src/setup/slack-connect-lifecycle.js +1 -1
  83. package/dist/src/setup/slack-connect.d.ts +25 -14
  84. package/dist/src/setup/slack-connect.js +1 -1
  85. package/dist/src/setup/slackbot.d.ts +12 -16
  86. package/dist/src/setup/slackbot.js +1 -1
  87. package/dist/src/setup/vercel-project.d.ts +25 -0
  88. package/dist/src/setup/vercel-project.js +1 -1
  89. package/dist/src/source-change/apply-model-name.d.ts +2 -2
  90. package/dist/src/source-change/apply-model-name.js +1 -1
  91. package/dist/src/source-change/static-source-change.js +1 -1
  92. package/docs/getting-started.mdx +5 -5
  93. package/docs/guides/dev-tui.md +3 -1
  94. package/package.json +4 -4
@@ -1,11 +1,11 @@
1
- import{sliceVisible,stripAnsi,stripTerminalControls,visibleLength}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,lineOf,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,nextKey,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{toErrorMessage}from"#shared/errors.js";import{initialSelectState,reduceSelect,selectValueAtCursor}from"#setup/cli/select-state.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e,t){return e?`Interrupted`:t?`Ready`:`Done`}const STATUS={processing:`Working…`,toolResults:`Reading results…`,streaming:`Responding…`,executingTools:`Running tools…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=[];#p=new Map;#m=new Set;#h=[];#g=new Set;#_=new Map;#v=new Set;#y;#b=!1;#x;#S=[];#C;#w=0;#T;#E=``;#D=0;#O=new PromptHistory;#k=!1;#A;#j=!1;#M=STATUS.processing;#N=`Eve`;#P=!1;#F=!1;#I=!0;#L=0;#R;#z;#B;#V=!1;#H;#U=``;#W;#G;#K;#q=!1;#J=!1;#Y;#X;#Z;#Q;#$;#ee;#te;#ne=``;#re=``;#ie;#ae;#oe=0;#se;#ce;#le;#ue;setupFlow={begin:e=>this.#pe(e),end:e=>this.#me(e?.preserveDiagnostics??!0),readSelect:e=>this.#he(e),readEditableSelect:e=>this.#_e(e),readText:e=>this.#ve(e),readAcknowledge:e=>this.#ye(e),readChoice:e=>this.#ge(e),setStatus:e=>this.#De(e),renderLine:(e,t)=>this.#Oe(e,t),renderOutput:e=>this.#ke(e),waitForInterrupt:()=>this.#we()};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#i=e?.tools??`auto-collapsed`,this.#a=e?.reasoning??`full`,this.#o=e?.subagents??`auto-collapsed`,this.#s=e?.connectionAuth??`full`,this.#c=e?.assistantResponseStats??`tokensPerSecond`,this.#l=e?.contextSize,this.#Z=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#d=e?.logs??`none`}renderAgentHeader(e){this.#N=e.name,this.#y=e,this.#Ae();let t=this.#lt().join(`
2
- `);if(this.#b){t!==this.#x&&(this.#x=t,this.#Ue({kind:`agent-header`,body:t,live:!1})),this.#it();return}this.#b=!0,this.#x=t,this.#n.flush(this.#lt(),[])}async readPrompt(e){this.#Ae(e),this.#k=!0,this.#j=!1,this.#M=``;let t=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#O.begin(t.text),this.#de(t),this.#A=typeaheadFor(PROMPT_COMMANDS,t.text),this.#Re(),this.#it(),await new Promise((e,r)=>{let apply=e=>{t=e,this.#Be(),this.#de(t),this.#A=typeaheadFor(PROMPT_COMMANDS,e.text,this.#A),this.#it()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#A=void 0,this.#ze(),this.#je(),r(interruptedError())},suggestions=()=>this.#A!==void 0&&isTypeaheadOpen(this.#A)?this.#A:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#H=r=>{let i=applyLineEditorKey(t,r);if(i!==void 0){apply(i);return}switch(r.type){case`up`:{let e=suggestions();e===void 0?recall(this.#O.previous(t.text)):(this.#A=moveTypeaheadSelection(e,-1),this.#it());break}case`down`:{let e=suggestions();e===void 0?recall(this.#O.next()):(this.#A=moveTypeaheadSelection(e,1),this.#it());break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#A=dismissTypeahead(e),this.#it());break}case`enter`:{let r=highlighted(),i=r!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(r).trimEnd():t.text;this.#A=void 0,this.#O.add(i),this.#k=!1,this.#ze(),this.#M=STATUS.processing,isPromptControlCommand(i)?this.#Ue({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#We(i),this.#se=i),this.#de(EMPTY_LINE),this.#it(),this.#Ne(),e(i);break}case`ctrl-d`:t.text.length===0?interrupt():apply(deleteForward(t));break;case`ctrl-l`:this.#st();break;case`ctrl-r`:this.#it();break;case`ctrl-c`:interrupt();break;default:break}},this.#Me()})}#de(e){this.#E=e.text,this.#D=e.cursor}async renderStream(e,t){this.#Ae(t),this.#m.clear(),this.#k=!1,this.#j=!0,this.#M=STATUS.processing,this.#Ge(t?.submittedPrompt),this.#F=!1,this.#Y=void 0,this.#X=void 0,this.#Q=void 0,this.#$=void 0,this.#ee=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#Ve(),this.#it();let r=new Promise(e=>{this.#K=e});this.#H=e=>this.#Le(e),this.#Me();let i={text:new Map,reasoning:new Map,tools:new Map,hasPendingToolResults:!1};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#F)break;this.#Ze(t,n,i)}}catch(e){this.#Ke(`Error`,toErrorMessage(e))}finally{this.#K=void 0,this.#F&&e.abort?.(),this.#Ne(),this.#He(),this.#j=!1,this.#M=completedTurnStatus(this.#F,t?.continueSession===!0),this.#Xe(),this.#it(),(this.#F||!t?.continueSession)&&this.#je()}if(this.#F)throw interruptedError()}async readToolApproval(e,t){return this.#Ae(t),this.#k=!1,this.#j=!1,this.#M=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#F=!1,this.#it(),await new Promise((t,n)=>{this.#H=r=>{switch(r.type){case`character`:{let n=r.value.toLowerCase();n===`y`?(this.#M=STATUS.processing,this.#Ne(),this.#it(),t({approved:!0})):n===`n`&&(this.#M=STATUS.processing,this.#fe(e.toolCallId),this.#Ne(),this.#it(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#it();break;case`ctrl-c`:this.#F=!0,this.#je(),n(interruptedError());break;default:break}},this.#Me()})}async readInputQuestion(e,t){this.#Ae(t),this.#k=!1,this.#j=!1,this.#F=!1;let r=e.options??[],i=r.length>0,a=(e.allowFreeform===!0||!i)&&i,o=r.length+ +!!a,s=questionSectionId(e.requestId),c=i?`select`:`text`,l=0,u=``,isOnFreeformRow=()=>a&&l===r.length,renderSection=()=>{this.#Je({id:s,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,l,this.#r),preformatted:!0,live:!0})},repaintStatus=()=>{if(c===`select`){let e=isOnFreeformRow()?`type`:`select`;this.#M=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#k=!1}else this.#k=!0,this.#de(lineOf(u)),this.#M=``;this.#it()};renderSection(),c===`text`&&this.#Re(),repaintStatus();let finalize=t=>{this.#Je({id:s,kind:`question`,title:stripTerminalControls(e.prompt),body:` ${this.#r.colors.green(this.#r.glyph.success)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#k=!1,this.#M=STATUS.processing,this.#ze(),this.#Ne(),this.#it();let r={};return t.optionId!==void 0&&(r.optionId=t.optionId),t.text!==void 0&&(r.text=t.text),r};return await new Promise((t,n)=>{this.#H=a=>{if(a.type===`ctrl-c`){this.#F=!0,this.#ze(),this.#je(),n(interruptedError());return}if(a.type===`ctrl-r`){this.#it();return}if(c===`select`){switch(a.type){case`up`:o>0&&(l=(l-1+o)%o,renderSection(),repaintStatus());break;case`down`:o>0&&(l=(l+1)%o,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){c=`text`,u=``,this.#Re(),repaintStatus();break}let e=r[l];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}switch(a.type){case`character`:u+=a.value,this.#Be(),repaintStatus();break;case`backspace`:u=u.slice(0,-1),this.#Be(),repaintStatus();break;case`enter`:{let n=resolveQuestionText(u,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(i){if(u.length>0){u=``,this.#Be(),repaintStatus();break}c=`select`,u=``,this.#k=!1,this.#ze(),repaintStatus();break}u=``,this.#Be(),repaintStatus();break;default:break}},this.#Me()})}upsertSubagentStep(e){if(this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),r=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&r.length===0)){if(this.#qe(e.callId,e.subagentName),this.#o===`collapsed`){this.#it();return}this.#Je({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:r,live:!e.finalized}),this.#it()}}upsertSubagentTool(e){if(this.#o===`hidden`)return;if(this.#qe(e.callId,e.subagentName),this.#o===`collapsed`){this.#it();return}let t=subagentToolStatus(e.status),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,depth:1,title:stripTerminalControls(e.toolName),subtitle:summarizeToolArgs(e.input),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolInput:e.input};e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=summarizeToolResult(e.output),r.toolOutput=e.output),this.#Je(r),this.#it()}markChildToolCallId(e){this.#g.add(e);let t=this.#_.get(e);t!==void 0&&(this.#Ye(t),this.#_.delete(e),this.#it())}#fe(e){let t=this.#p.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=e.state===`authorized`||e.state===`declined`||e.state===`failed`||e.state===`timed-out`;this.#Je({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e),preformatted:!0,live:!t}),this.#it()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#w)return;let n=this.#w>0;this.#w=t,t>0?(this.#M=STATUS.connectionAuth,this.#it()):n&&(this.#M=STATUS.processing,this.#it())}setVercelStatus(e){this.#T=e,this.#it()}reset(){this.#f=[],this.#p.clear(),this.#m.clear(),this.#C=void 0,this.#S.length=0,this.#h.length=0,this.#b=!1,this.#x=void 0,this.#g.clear(),this.#_.clear(),this.#v.clear(),this.#se=void 0,this.#ae=void 0,this.#w=0,this.#Y=void 0,this.#X=void 0,this.#Q=void 0,this.#$=void 0,this.#ee=void 0,this.#P&&(this.#n.clearAll(),this.#it())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ae(),this.#Ue({kind:`notice`,body:t,live:!1}),this.#it())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#Ae(),this.#Ue({kind:`sandbox`,body:t,live:!1}),this.#it())}renderSetupWarning(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ae(),this.#Ue({kind:`warning`,body:t,live:!1}),this.#it())}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ae(),this.#Ue({kind:`result`,body:t,live:!1}),this.#it())}#pe(e){this.#Ae(),this.#k=!1,this.#j=!1,this.#M=``,this.#ce={title:stripTerminalControls(e),lines:[],outputBuffer:[]},this.#Ve(),this.#it()}#me(e){this.#le=void 0,this.#Ee();let t=this.#ce;if(t!==void 0){if(this.#ce=void 0,this.#He(),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.#Ue({kind:`flow`,title:`info`,body:e.join(`
3
- `),live:!1}),this.#Ue({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#it()}}async#he(e){let t=this.#be(),n=isMultiSelectRequest(e),r={options:e.options,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(r.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(r.initialValues=e.initialValues);let i=initialSelectState(r),a,o=e.notices;if(e.kind===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));o=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,select:i};return o!==void 0&&o.length>0&&(t.notices=o),a!==void 0&&(t.error=a),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#it(),await this.#Ce((t,r)=>{let o={key:t,options:e.options,select:i},s=reduceSetupSelectInput(n?{...o,kind:e.kind,required:e.required}:{...o,kind:e.kind});switch(s.kind){case`cancel`:r(void 0);return;case`repaint`:this.#it();return;case`update`:i=s.select,a=void 0,this.#it();return;case`submit`:r(s.values);return;case`error`:a=s.message,this.#it();return;case`ignore`:return}}).promise}#ge(e){this.#Ae();let t=this.#xe();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#it();let r=this.#Ce((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.#it();return;case`repaint`:this.#it();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#_e(e){let t=this.#be(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`editable`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint,caretVisible:this.#I}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?(i.text.length===0&&(i=lineOf(e.editable.defaultValue)),this.#Re()):(i=lineOf(``),this.#ze())};return syncEditableRow(),this.#it(),await this.#Ce((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Be(),this.#it()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#it()},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.#it();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.#it();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#ze()).promise}async#ve(e){let t=this.#be(),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.#I)},this.#Re(),this.#it(),await this.#Ce((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Be(),this.#it()},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.#it();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#it();return}i(t);return}default:return}},()=>this.#ze()).promise}async#ye(e){let t=this.#be();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#it(),await this.#Ce((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#it();return;default:return}}).promise}#be(){return this.#Ae(),this.#k=!1,this.#j=!1,this.#M=``,this.#xe()}#xe(){return this.#ce===void 0&&(this.#ce={title:``,lines:[],outputBuffer:[]}),this.#ce}#Se(){this.#ce!==void 0&&(this.#ce.question=void 0,this.#ce.hideLinesWhileQuestion=!1),this.#H=void 0,this.#Ne(),this.#Te(),this.#it()}#Ce(e,t){let n=!1,r,i=new Promise(e=>{r=e}),settle=e=>{n||(n=!0,t?.(),this.#Se(),r(e))};return this.#H=t=>e(t,settle),this.#Me(),{promise:i,settle}}#we(){let e,t=new Promise(t=>{e=t});return this.#le=e,this.#Te(),{promise:t,dispose:()=>{this.#le===e&&(this.#le=void 0,this.#Ee())}}}#Te(){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.#Ee(),e?.();return}e.type===`ctrl-r`&&this.#it()};this.#ue=consumer,this.#H=consumer,this.#Me()}#Ee(){this.#ue!==void 0&&(this.#H===this.#ue&&this.#Ne(),this.#ue=void 0)}#De(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#ce!==void 0){this.#ce.status=t,t===void 0&&(this.#ce.preview=void 0),this.#it();return}if(t===void 0){this.#j=!1,this.#M=``,this.#He(),this.#it();return}this.#Ae(),this.#j=!0,this.#M=t,this.#Ve(),this.#it()}#Oe(e,t){let r=stripTerminalControls(e);if(r.trim().length===0)return;let i=this.#ce;if(i!==void 0){if(i.preview=void 0,t===`warning`||t===`error`)for(let e of i.outputBuffer)i.lines.push({text:e,tone:`info`,evidence:!0});i.outputBuffer=[],i.lines.push({text:r,tone:t}),this.#it();return}this.#Ae(),this.#Ue({kind:`flow`,title:t,body:r,live:!1}),this.#it()}#ke(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let r=this.#ce;if(r===void 0){this.#Oe(t,`info`);return}r.preview=t,r.outputBuffer.push(t),r.outputBuffer.length>40&&r.outputBuffer.shift(),this.#it()}shutdown(){this.#je()}#Ae(e){this.#N=e?.title??this.#N,this.#Z=e?.contextSize??this.#l,!this.#P&&(this.#P=!0,this.#n.reset(),this.#n.hideCursor(),this.#_t(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume()),this.#G=()=>this.#it(),this.#t.on(`resize`,this.#G))}#je(){this.#Ne(),this.#ze(),this.#He(),this.#B!==void 0&&(clearTimeout(this.#B),this.#B=void 0),this.#V=!1,this.#P&&=(this.#Tt(),this.#it(),this.#n.clear(),this.#n.showCursor(),this.#vt(),this.#n.newline(),this.#e.isTTY&&(this.#e.setRawMode?.(!1),this.#e.pause()),this.#G&&=(this.#t.off(`resize`,this.#G),void 0),!1)}#Me(){this.#e.off(`data`,this.#Pe),this.#e.on(`data`,this.#Pe)}#Ne(){this.#e.off(`data`,this.#Pe),this.#Ie(),this.#U=``,this.#H=void 0}#Pe=e=>{this.#Ie(),this.#U+=e.toString(`utf8`),this.#Fe(),this.#U===`\x1B`&&(this.#W=setTimeout(()=>{this.#U===`\x1B`&&(this.#U=``,this.#H?.({type:`escape`}))},30),this.#W.unref?.())};#Fe(){for(;this.#U.length>0;){let e=nextKey(this.#U);if(e.incomplete)return;this.#U=this.#U.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#H?.(e.key)}}#Ie(){this.#W&&=(clearTimeout(this.#W),void 0)}#Le(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#it();break;case`ctrl-c`:this.#F=!0,this.#K?.();break;default:break}}#Re(){this.#ze(),this.#Be(),this.#R=setInterval(()=>{this.#I=!this.#I,this.#it()},500),this.#R.unref?.()}#ze(){this.#R&&=(clearInterval(this.#R),void 0),this.#I=!0}#Be(){this.#I=!0}#Ve(){this.#He(),this.#z=setInterval(()=>{this.#L+=1,this.#it()},90),this.#z.unref?.()}#He(){this.#z&&=(clearInterval(this.#z),void 0)}#Ue(e){e.id!==this.#ae?.id&&this.#Tt(),this.#f.push(e),e.id&&this.#p.set(e.id,e)}#We(e){this.#Ue({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#it()}#Ge(e){if(e!=null){if(this.#se===e){this.#se=void 0;return}this.#Ue({kind:`user`,body:stripTerminalControls(e),live:!1})}}#Ke(e,t,r){let i={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};r!==void 0&&(i.detail=stripTerminalControls(r)),this.#Ue(i),this.#it()}#qe(e,t){this.#v.has(e)||(this.#v.add(e),this.#Ue({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#Je(e){if(e.id&&this.#m.has(e.id))return;let t=e.id?this.#p.get(e.id):void 0;if(t){Object.assign(t,e);return}this.#Ue(e)}#Ye(e){this.#f=this.#f.filter(t=>t.id!==e),this.#p.delete(e)}#Xe(){for(let e of this.#f)e.status===`approval`||e.status===`running`||(e.live=!1)}#Ze(e,t,r){switch(e.type){case`step-start`:this.#Qe(r.hasPendingToolResults?STATUS.toolResults:STATUS.processing),r.hasPendingToolResults=!1;break;case`step-finish`:this.#rt(e.usage),this.#it();break;case`assistant-delta`:{this.#Qe(STATUS.streaming);let t=(r.text.get(e.id)??``)+stripTerminalControls(e.delta);r.text.set(e.id,t),this.#$e(e.id,t,!0);break}case`assistant-complete`:{let t=r.text.get(e.id)??``,i=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;r.text.set(e.id,i),this.#$e(e.id,i,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;this.#Qe(STATUS.streaming);let i=(r.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);r.reasoning.set(e.id,i),this.#et(e.id,i,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let n=r.reasoning.get(e.id)??``;this.#et(e.id,n,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#Qe(STATUS.executingTools),this.#tt({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,r);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let n=r.tools.get(e.toolCallId);if(n===void 0)break;this.#tt({...n,status:`approval`},t,r);break}case`tool-result`:{if(t.tools===`hidden`)break;let n=this.#nt(e.toolCallId,r);if(n===void 0)break;r.hasPendingToolResults=!0,this.#Qe(STATUS.toolResults),this.#tt({...n,output:e.output,status:`done`},t,r);break}case`tool-error`:{if(t.tools===`hidden`)break;let n=this.#nt(e.toolCallId,r);if(n===void 0)break;r.hasPendingToolResults=!0,this.#Qe(STATUS.toolResults),this.#tt({...n,errorText:e.errorText,status:`error`},t,r);break}case`error`:this.#Ke(`Error`,e.errorText,e.detail);break;case`finish`:this.#rt(e.usage),this.#it();break}}#Qe(e){let t=this.#w>0?STATUS.connectionAuth:e;this.#M!==t&&(this.#M=t,this.#it())}#$e(e,t,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Je({id:e,kind:`assistant`,body:i,live:r}),this.#it())}#et(e,t,r,i){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#Je({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(i.reasoning,r),live:r}),this.#it())}#tt(e,t,n){if(n.tools.set(e.toolCallId,e),this.#g.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#_.set(e.toolCallId,r),this.#Je(renderNativeToolBlock(e,r,t.tools===`full`)),this.#it()}#nt(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#_.get(e)??toolSectionId(e),i=this.#p.get(r);if(!(i===void 0||i.kind!==`tool`))return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.title??`tool`}}#rt(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#Y=(t??0)+(n??0)),this.#X=t??this.#X,this.#Q=n??this.#Q,this.#Q!=null&&this.#ee!==void 0){let e=(Date.now()-this.#ee)/1e3;e>0&&(this.#$=this.#Q/e)}}#it(){if(this.#P){if(this.#q){this.#J=!0;return}this.#q=!0;try{do this.#J=!1,this.#at();while(this.#J)}finally{this.#q=!1}}}#at(){if(!this.#P)return;let e=this.#ht(),t=this.#ft(e),n=Math.max(1,this.#gt()-t.length),r=[],i=this.#C;for(;this.#f.length>0&&this.#f[0].live===!1;){let t=this.#f.shift();if(this.#h.push(t),t.id&&(this.#m.add(t.id),this.#p.delete(t.id)),this.#Dt(t))continue;let n=this.#ut(t,e,i);i=previousBlockOf(t),this.#C=i,r.push(...n),this.#S.push(...n)}let a=[];for(let t of this.#f){if(this.#Dt(t))continue;let n=this.#ut(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)a.push({block:t,row:n[e]})}let o=[...clipLiveRows(a.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,o):this.#n.update(o)}#ot(){if(!this.#P)return;let e=this.#ht(),t=this.#ft(e),n=Math.max(1,this.#gt()-t.length),r=this.#C,i=[];for(let t of this.#f){if(this.#Dt(t))continue;let n=this.#ut(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.#lt(),...this.#S],a)}logDisplayMode(){return this.#d}setLogDisplayMode(e){e!==this.#d&&(this.#d=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#ct(),this.#P&&this.#ot())}flushDelayedDevBuildErrors(){let e=this.#ie;e!==void 0&&(this.#ie=void 0,this.#Ue({kind:`log`,title:`stderr`,body:e,live:!1}),this.#it())}#st(){this.#V=!0,this.#B!==void 0&&clearTimeout(this.#B),this.#B=setTimeout(()=>{this.#V=!1,this.#B=void 0,this.#it()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#d)),this.#it()}#ct(){let e=this.#ht();this.#S.length=0;let t;for(let n of this.#h){if(this.#Dt(n))continue;let r=this.#ut(n,e,t);t=previousBlockOf(n),this.#S.push(...r)}this.#C=t}#lt(){let e=this.#y;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#ht()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#ut(e,t,n){let r={spinner:this.#dt()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#dt(){return this.#r.spinner[this.#L%this.#r.spinner.length]??``}#ft(e){let t=this.#r.colors,n=[``],r=this.#ce;if(r!==void 0){let t=this.#dt(),i;if(r.question!==void 0){let n=r.question(e);i={kind:`question`,rows:n},r.status!==void 0&&(i={kind:`question`,rows:n,status:{text:r.status,frame:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,frame:t}:{kind:`preview`,text:r.preview,frame:t}:(i={kind:`status`,status:{text:r.status,frame:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,frame:t},preview:r.preview}));let a={title:r.title,lines:r.hideLinesWhileQuestion===!0?[]:r.lines,content:i};return n.push(...renderFlowPanel(a,this.#r,e)),n}if(this.#k){let r=this.#A===void 0?void 0:inlineCommandHint(this.#A);r===void 0&&this.#A!==void 0&&isTypeaheadOpen(this.#A)&&n.push(...renderCommandSuggestions(this.#A,this.#r,e));let i=Math.max(4,e-3),{before:a,after:o}=visibleLine({text:this.#E,cursor:this.#D},i,this.#r.glyph.ellipsis),s=isPromptControlCommand(this.#E),style=e=>s&&e.length>0?t.blue(e):e,l=this.#I?t.cyan(this.#r.glyph.caret):` `,u=r?t.dim(` ${r}`):``,d=`${style(a)}${l}${style(o)}${u}`;return n.push(...promptInputRows(d,e,this.#r,!0)),this.#pt(n,e),n}let i=this.#j?t.yellow(this.#dt()):t.dim(this.#r.glyph.dot),a=this.#M.length>0?this.#M:`Ready`,o=this.#j?t.dim(a):a,s=this.#mt(),l=s?`${i} ${o} ${t.dim(this.#r.glyph.dot)} ${s}`:`${i} ${o}`;return n.push(clip(l,e)),this.#pt(n,e),n}#pt(e,t){let n={theme:this.#r,width:t};this.#V&&(n.logLevel=this.#d);let r=this.#y?.info?.agent.model.id;r!==void 0&&(n.model=r);let i=this.#y?.info?.agent.model.endpoint;i!==void 0&&(n.endpoint=i);let a=this.#X??0,o=this.#Q??0;if(a>0||o>0){let e={inputTokens:a,outputTokens:o};this.#Z!==void 0&&(e.contextSize=this.#Z),n.tokens=formatTokenFlow(e,this.#r.glyph)}this.#T!==void 0&&(n.vercel=this.#T);let s=buildStatusLine(n);s!==void 0&&e.push(s)}#mt(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Y,outputTokens:this.#Q,tokensPerSecond:this.#$},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#ht(){return Math.max(20,this.#t.columns||80)}#gt(){return Math.max(8,this.#t.rows||24)}#_t(){if(this.#te!==void 0||!this.#u)return;this.#ne=``,this.#re=``;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.#yt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#te=()=>{e(),t()}}#vt(){let e=this.#te;e!==void 0&&(this.#te=void 0,e(),this.#ne.length>0&&(this.#Et(`stdout`)&&process.stdout.write(`${this.#ne}\n`),this.#ne=``),this.#re.length>0&&(this.#Et(`stderr`)&&process.stderr.write(`${this.#re}\n`),this.#re=``))}#yt(e,n){let r=(e===`stdout`?this.#ne:this.#re)+n,i=r.lastIndexOf(`
4
- `),a=i===-1?r:r.slice(i+1);if(e===`stdout`?this.#ne=a:this.#re=a,i===-1)return;let o=stripAnsi(r.slice(0,i)).replace(/\s+$/u,``);o.trim().length!==0&&(e===`stdout`?this.#bt(o):this.#xt(o),this.#it())}#bt(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
5
- `);t=[],e.trim().length!==0&&this.#Ue({kind:`log`,title:`stdout`,body:e,live:!1})};for(let n of e.split(`
6
- `)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#Ue({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#Ct(r,n.trimEnd())}flushPending()}#xt(e){let t=e.split(`
7
- `),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){this.#Ue({kind:`log`,title:`stderr`,body:e,live:!1});return}let r=t.slice(0,n).join(`
8
- `);r.trim().length>0&&this.#Ue({kind:`log`,title:`stderr`,body:r,live:!1});let i=t.slice(n).join(`
9
- `);this.#St(i)}#St(e){if(this.#d===`all`){if(e.trim().length===0)return;this.#Ue({kind:`log`,title:`stderr`,body:e,live:!1});return}this.#ie=e}#Ct(e,t){let n=this.#wt();if(e.kind===`failed`){this.#St(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.#oe}`;this.#oe+=1,this.#ae={id:r,summary:t},this.#Ue({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.#ie=void 0);return}e.kind===`rebuilt`&&(this.#ie=void 0),this.#Ue({kind:`log`,title:`stdout`,body:t,live:!1})}#wt(){let e=this.#ae;if(e===void 0)return;let t=this.#p.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#Tt(){let e=this.#ae;if(e===void 0)return;this.#ae=void 0;let t=this.#p.get(e.id);t!==void 0&&(t.live=!1)}#Et(e){switch(this.#d){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#Dt(e){return e.kind===`sandbox`?!this.#Et(`sandbox`):e.kind===`log`?!this.#Et(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(t,n){return visibleLength(t)>n?sliceVisible(t,n):t}function promptInputRows(e,t,n,r){let i=n.colors;return[clip(`${r?i.cyan(n.glyph.prompt):i.dim(n.glyph.prompt)} ${r?e:i.dim(e)}`,t),``]}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function leadsWithGap(e,t){if(e.kind===`sandbox`&&t?.kind===`sandbox`)return!1;if(t?.kind===`sandbox`&&e.kind!==`sandbox`)return!0;if(e.kind===`log`&&t?.kind===`log`)return t.title!==e.title;if(t?.kind===`log`&&e.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`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,r){let o={id:t,kind:`tool`,title:stripTerminalControls(e.toolName),subtitle:summarizeToolArgs(e.input),status:e.status,live:e.status===`running`||e.status===`approval`,expanded:r,toolInput:e.input};return e.output===void 0?e.errorText!==void 0&&(o.result=stripTerminalControls(e.errorText)):(o.result=summarizeToolResult(e.output),o.toolOutput=e.output),o}function subagentToolStatus(e){switch(e){case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`}}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 formatConnectionAuthContent(e){let t=[],r=stripTerminalControls(e.description);r.length>0&&t.push(r);let i=e.challenge;if(i?.url&&t.push(`URL: ${stripTerminalControls(i.url)}`),i?.userCode&&t.push(`Code: ${stripTerminalControls(i.userCode)}`),i?.expiresAt&&t.push(`Expires: ${stripTerminalControls(i.expiresAt)}`),i?.instructions&&t.push(stripTerminalControls(i.instructions)),e.reason!==void 0){let r=stripTerminalControls(e.reason);r.length>0&&t.push(`Reason: ${r}`)}return t.join(`
1
+ import{sliceVisible,stripAnsi,stripTerminalControls,visibleLength}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,lineOf,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,nextKey,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{toErrorMessage}from"#shared/errors.js";import{initialSelectState,reduceSelect,selectValueAtCursor}from"#setup/cli/select-state.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e,t){return e?`Interrupted`:t?`Ready`:`Done`}const STATUS={processing:`Working…`,toolResults:`Reading results…`,streaming:`Responding…`,executingTools:`Running tools…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=[];#p=new Map;#m=new Set;#h=[];#g=new Set;#_=new Map;#v=new Set;#y;#b=!1;#x;#S=[];#C;#w=0;#T;#E=``;#D=0;#O=new PromptHistory;#k=!1;#A;#j=!1;#M=STATUS.processing;#N=`Eve`;#P=!1;#F=!1;#I=!0;#L=0;#R;#z;#B;#V=!1;#H;#U=``;#W;#G;#K;#q=!1;#J=!1;#Y;#X;#Z;#Q;#$;#ee;#te;#ne=``;#re=``;#ie;#ae;#oe=0;#se;#ce;#le;#ue;#de;setupFlow={begin:e=>this.#he(e),end:e=>this.#ge(e?.preserveDiagnostics??!0),readSelect:e=>this.#_e(e),readEditableSelect:e=>this.#ye(e),readText:e=>this.#be(e),readAcknowledge:e=>this.#xe(e),readChoice:e=>this.#ve(e),setStatus:e=>this.#ke(e),renderLine:(e,t)=>this.#Ae(e,t),renderOutput:e=>this.#je(e),waitForInterrupt:()=>this.#Ee()};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#i=e?.tools??`auto-collapsed`,this.#a=e?.reasoning??`full`,this.#o=e?.subagents??`auto-collapsed`,this.#s=e?.connectionAuth??`full`,this.#c=e?.assistantResponseStats??`tokensPerSecond`,this.#l=e?.contextSize,this.#Z=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#d=e?.logs??`none`}renderAgentHeader(e){this.#N=e.name,this.#y=e,this.#Me();let t=this.#dt().join(`
2
+ `);if(this.#b){t!==this.#x&&(this.#x=t,this.#Ge({kind:`agent-header`,body:t,live:!1})),this.#ot();return}this.#b=!0,this.#x=t,this.#n.flush(this.#dt(),[])}async readPrompt(e){this.#Me(e),this.#k=!0,this.#j=!1,this.#M=``;let t=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#O.begin(t.text),this.#fe(t),this.#A=typeaheadFor(PROMPT_COMMANDS,t.text),this.#Be(),this.#ot(),await new Promise((e,r)=>{let apply=e=>{t=e,this.#He(),this.#fe(t),this.#A=typeaheadFor(PROMPT_COMMANDS,e.text,this.#A),this.#ot()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#A=void 0,this.#Ve(),this.#Ne(),r(interruptedError())},suggestions=()=>this.#A!==void 0&&isTypeaheadOpen(this.#A)?this.#A:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#H=r=>{let i=applyLineEditorKey(t,r);if(i!==void 0){apply(i);return}switch(r.type){case`up`:{let e=suggestions();e===void 0?recall(this.#O.previous(t.text)):(this.#A=moveTypeaheadSelection(e,-1),this.#ot());break}case`down`:{let e=suggestions();e===void 0?recall(this.#O.next()):(this.#A=moveTypeaheadSelection(e,1),this.#ot());break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#A=dismissTypeahead(e),this.#ot());break}case`enter`:{let r=highlighted(),i=r!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(r).trimEnd():t.text;this.#A=void 0,this.#O.add(i),this.#k=!1,this.#Ve(),this.#M=STATUS.processing,isPromptControlCommand(i)?this.#Ge({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#Ke(i),this.#se=i),this.#fe(EMPTY_LINE),this.#ot(),this.#Fe(),e(i);break}case`ctrl-d`:t.text.length===0?interrupt():apply(deleteForward(t));break;case`ctrl-l`:this.#lt();break;case`ctrl-r`:this.#ot();break;case`ctrl-c`:interrupt();break;default:break}},this.#Pe()})}#fe(e){this.#E=e.text,this.#D=e.cursor}async renderStream(e,t){this.#Me(t),this.#m.clear(),this.#k=!1,this.#j=!0,this.#M=STATUS.processing,this.#qe(t?.submittedPrompt),this.#F=!1,this.#Y=void 0,this.#X=void 0,this.#Q=void 0,this.#$=void 0,this.#ee=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#Ue(),this.#ot();let r=new Promise(e=>{this.#K=e});this.#H=e=>this.#ze(e),this.#Pe();let i={text:new Map,reasoning:new Map,tools:new Map,hasPendingToolResults:!1};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#F)break;this.#$e(t,n,i)}}catch(e){this.#Je(`Error`,toErrorMessage(e))}finally{this.#K=void 0,this.#F&&e.abort?.(),this.#Fe(),this.#We(),this.#j=!1,this.#M=completedTurnStatus(this.#F,t?.continueSession===!0),this.#Qe(),this.#ot(),(this.#F||!t?.continueSession)&&this.#Ne()}if(this.#F)throw interruptedError()}async readToolApproval(e,t){return this.#Me(t),this.#k=!1,this.#j=!1,this.#M=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#F=!1,this.#ot(),await new Promise((t,n)=>{this.#H=r=>{switch(r.type){case`character`:{let n=r.value.toLowerCase();n===`y`?(this.#M=STATUS.processing,this.#Fe(),this.#ot(),t({approved:!0})):n===`n`&&(this.#M=STATUS.processing,this.#pe(e.toolCallId),this.#Fe(),this.#ot(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#ot();break;case`ctrl-c`:this.#F=!0,this.#Ne(),n(interruptedError());break;default:break}},this.#Pe()})}async readInputQuestion(e,t){this.#Me(t),this.#k=!1,this.#j=!1,this.#F=!1;let r=e.options??[],i=r.length>0,a=(e.allowFreeform===!0||!i)&&i,o=r.length+ +!!a,s=questionSectionId(e.requestId),c=i?`select`:`text`,l=0,u=``,isOnFreeformRow=()=>a&&l===r.length,renderSection=()=>{this.#Xe({id:s,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,l,this.#r),preformatted:!0,live:!0})},repaintStatus=()=>{if(c===`select`){let e=isOnFreeformRow()?`type`:`select`;this.#M=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#k=!1}else this.#k=!0,this.#fe(lineOf(u)),this.#M=``;this.#ot()};renderSection(),c===`text`&&this.#Be(),repaintStatus();let finalize=t=>{this.#Xe({id:s,kind:`question`,title:stripTerminalControls(e.prompt),body:` ${this.#r.colors.green(this.#r.glyph.success)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#k=!1,this.#M=STATUS.processing,this.#Ve(),this.#Fe(),this.#ot();let r={};return t.optionId!==void 0&&(r.optionId=t.optionId),t.text!==void 0&&(r.text=t.text),r};return await new Promise((t,n)=>{this.#H=a=>{if(a.type===`ctrl-c`){this.#F=!0,this.#Ve(),this.#Ne(),n(interruptedError());return}if(a.type===`ctrl-r`){this.#ot();return}if(c===`select`){switch(a.type){case`up`:o>0&&(l=(l-1+o)%o,renderSection(),repaintStatus());break;case`down`:o>0&&(l=(l+1)%o,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){c=`text`,u=``,this.#Be(),repaintStatus();break}let e=r[l];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}switch(a.type){case`character`:u+=a.value,this.#He(),repaintStatus();break;case`backspace`:u=u.slice(0,-1),this.#He(),repaintStatus();break;case`enter`:{let n=resolveQuestionText(u,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(i){if(u.length>0){u=``,this.#He(),repaintStatus();break}c=`select`,u=``,this.#k=!1,this.#Ve(),repaintStatus();break}u=``,this.#He(),repaintStatus();break;default:break}},this.#Pe()})}upsertSubagentStep(e){if(this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),r=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&r.length===0)){if(this.#Ye(e.callId,e.subagentName),this.#o===`collapsed`){this.#ot();return}this.#Xe({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:r,live:!e.finalized}),this.#ot()}}upsertSubagentTool(e){if(this.#o===`hidden`)return;if(this.#Ye(e.callId,e.subagentName),this.#o===`collapsed`){this.#ot();return}let t=subagentToolStatus(e.status),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,depth:1,title:stripTerminalControls(e.toolName),subtitle:summarizeToolArgs(e.input),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolInput:e.input};e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=summarizeToolResult(e.output),r.toolOutput=e.output),this.#Xe(r),this.#ot()}markChildToolCallId(e){this.#g.add(e);let t=this.#_.get(e);t!==void 0&&(this.#Ze(t),this.#_.delete(e),this.#ot())}#pe(e){let t=this.#p.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=e.state===`authorized`||e.state===`declined`||e.state===`failed`||e.state===`timed-out`;this.#Xe({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e),preformatted:!0,live:!t}),this.#ot()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#w)return;let n=this.#w>0;this.#w=t,t>0?(this.#M=STATUS.connectionAuth,this.#ot()):n&&(this.#M=STATUS.processing,this.#ot())}setVercelStatus(e){this.#T=e,this.#ot()}reset(){this.#f=[],this.#p.clear(),this.#m.clear(),this.#C=void 0,this.#S.length=0,this.#h.length=0,this.#b=!1,this.#x=void 0,this.#g.clear(),this.#_.clear(),this.#v.clear(),this.#se=void 0,this.#ae=void 0,this.#w=0,this.#Y=void 0,this.#X=void 0,this.#Q=void 0,this.#$=void 0,this.#ee=void 0,this.#P&&(this.#n.clearAll(),this.#ot())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Me(),this.#Ge({kind:`notice`,body:t,live:!1}),this.#ot())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#Me(),this.#Ge({kind:`sandbox`,body:t,live:!1}),this.#ot())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#me();return}this.#Me(),this.#le=t,this.#ot()}clearSetupWarning(){this.#me()}#me(){this.#le!==void 0&&(this.#le=void 0,this.#ot())}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Me(),this.#Ge({kind:`result`,body:t,live:!1}),this.#ot())}#he(e){this.#Me(),this.#k=!1,this.#j=!1,this.#M=``,this.#ce={title:stripTerminalControls(e),lines:[],outputBuffer:[]},this.#Ue(),this.#ot()}#ge(e){this.#ue=void 0,this.#Oe();let t=this.#ce;if(t!==void 0){if(this.#ce=void 0,this.#We(),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.#Ge({kind:`flow`,title:`info`,body:e.join(`
3
+ `),live:!1}),this.#Ge({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#ot()}}async#_e(e){let t=this.#Se(),n=isMultiSelectRequest(e),r={options:e.options,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(r.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(r.initialValues=e.initialValues);let i=initialSelectState(r),a,o=e.notices;if(e.kind===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));o=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,select:i};return o!==void 0&&o.length>0&&(t.notices=o),a!==void 0&&(t.error=a),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#ot(),await this.#Te((t,r)=>{let o={key:t,options:e.options,select:i},s=reduceSetupSelectInput(n?{...o,kind:e.kind,required:e.required}:{...o,kind:e.kind});switch(s.kind){case`cancel`:r(void 0);return;case`repaint`:this.#ot();return;case`update`:i=s.select,a=void 0,this.#ot();return;case`submit`:r(s.values);return;case`error`:a=s.message,this.#ot();return;case`ignore`:return}}).promise}#ve(e){this.#Me();let t=this.#Ce();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#ot();let r=this.#Te((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.#ot();return;case`repaint`:this.#ot();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#ye(e){let t=this.#Se(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`editable`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint,caretVisible:this.#I}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?(i.text.length===0&&(i=lineOf(e.editable.defaultValue)),this.#Be()):(i=lineOf(``),this.#Ve())};return syncEditableRow(),this.#ot(),await this.#Te((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#He(),this.#ot()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#ot()},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.#ot();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.#ot();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ve()).promise}async#be(e){let t=this.#Se(),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.#I)},this.#Be(),this.#ot(),await this.#Te((t,i)=>{let apply=e=>{n=e,r=void 0,this.#He(),this.#ot()},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.#ot();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#ot();return}i(t);return}default:return}},()=>this.#Ve()).promise}async#xe(e){let t=this.#Se();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#ot(),await this.#Te((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#ot();return;default:return}}).promise}#Se(){return this.#Me(),this.#k=!1,this.#j=!1,this.#M=``,this.#Ce()}#Ce(){return this.#ce===void 0&&(this.#ce={title:``,lines:[],outputBuffer:[]}),this.#ce}#we(){this.#ce!==void 0&&(this.#ce.question=void 0,this.#ce.hideLinesWhileQuestion=!1),this.#H=void 0,this.#Fe(),this.#De(),this.#ot()}#Te(e,t){let n=!1,r,i=new Promise(e=>{r=e}),settle=e=>{n||(n=!0,t?.(),this.#we(),r(e))};return this.#H=t=>e(t,settle),this.#Pe(),{promise:i,settle}}#Ee(){let e,t=new Promise(t=>{e=t});return this.#ue=e,this.#De(),{promise:t,dispose:()=>{this.#ue===e&&(this.#ue=void 0,this.#Oe())}}}#De(){if(this.#ue===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#ue;this.#ue=void 0,this.#Oe(),e?.();return}e.type===`ctrl-r`&&this.#ot()};this.#de=consumer,this.#H=consumer,this.#Pe()}#Oe(){this.#de!==void 0&&(this.#H===this.#de&&this.#Fe(),this.#de=void 0)}#ke(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#ce!==void 0){this.#ce.status=t,t===void 0&&(this.#ce.preview=void 0),this.#ot();return}if(t===void 0){this.#j=!1,this.#M=``,this.#We(),this.#ot();return}this.#Me(),this.#j=!0,this.#M=t,this.#Ue(),this.#ot()}#Ae(e,t){let r=stripTerminalControls(e);if(r.trim().length===0)return;let i=this.#ce;if(i!==void 0){if(i.preview=void 0,t===`warning`||t===`error`)for(let e of i.outputBuffer)i.lines.push({text:e,tone:`info`,evidence:!0});i.outputBuffer=[],i.lines.push({text:r,tone:t}),this.#ot();return}this.#Me(),this.#Ge({kind:`flow`,title:t,body:r,live:!1}),this.#ot()}#je(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let r=this.#ce;if(r===void 0){this.#Ae(t,`info`);return}r.preview=t,r.outputBuffer.push(t),r.outputBuffer.length>40&&r.outputBuffer.shift(),this.#ot()}shutdown(){this.#Ne()}#Me(e){this.#N=e?.title??this.#N,this.#Z=e?.contextSize??this.#l,!this.#P&&(this.#P=!0,this.#n.reset(),this.#n.hideCursor(),this.#yt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume()),this.#G=()=>this.#ot(),this.#t.on(`resize`,this.#G))}#Ne(){this.#Fe(),this.#Ve(),this.#We(),this.#B!==void 0&&(clearTimeout(this.#B),this.#B=void 0),this.#V=!1,this.#P&&=(this.#Dt(),this.#ot(),this.#n.clear(),this.#n.showCursor(),this.#bt(),this.#n.newline(),this.#e.isTTY&&(this.#e.setRawMode?.(!1),this.#e.pause()),this.#G&&=(this.#t.off(`resize`,this.#G),void 0),!1)}#Pe(){this.#e.off(`data`,this.#Ie),this.#e.on(`data`,this.#Ie)}#Fe(){this.#e.off(`data`,this.#Ie),this.#Re(),this.#U=``,this.#H=void 0}#Ie=e=>{this.#Re(),this.#U+=e.toString(`utf8`),this.#Le(),this.#U===`\x1B`&&(this.#W=setTimeout(()=>{this.#U===`\x1B`&&(this.#U=``,this.#H?.({type:`escape`}))},30),this.#W.unref?.())};#Le(){for(;this.#U.length>0;){let e=nextKey(this.#U);if(e.incomplete)return;this.#U=this.#U.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#H?.(e.key)}}#Re(){this.#W&&=(clearTimeout(this.#W),void 0)}#ze(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#ot();break;case`ctrl-c`:this.#F=!0,this.#K?.();break;default:break}}#Be(){this.#Ve(),this.#He(),this.#R=setInterval(()=>{this.#I=!this.#I,this.#ot()},500),this.#R.unref?.()}#Ve(){this.#R&&=(clearInterval(this.#R),void 0),this.#I=!0}#He(){this.#I=!0}#Ue(){this.#We(),this.#z=setInterval(()=>{this.#L+=1,this.#ot()},90),this.#z.unref?.()}#We(){this.#z&&=(clearInterval(this.#z),void 0)}#Ge(e){e.id!==this.#ae?.id&&this.#Dt(),this.#f.push(e),e.id&&this.#p.set(e.id,e)}#Ke(e){this.#Ge({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#ot()}#qe(e){if(e!=null){if(this.#se===e){this.#se=void 0;return}this.#Ge({kind:`user`,body:stripTerminalControls(e),live:!1})}}#Je(e,t,r){let i={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};r!==void 0&&(i.detail=stripTerminalControls(r)),this.#Ge(i),this.#ot()}#Ye(e,t){this.#v.has(e)||(this.#v.add(e),this.#Ge({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#Xe(e){if(e.id&&this.#m.has(e.id))return;let t=e.id?this.#p.get(e.id):void 0;if(t){Object.assign(t,e);return}this.#Ge(e)}#Ze(e){this.#f=this.#f.filter(t=>t.id!==e),this.#p.delete(e)}#Qe(){for(let e of this.#f)e.status===`approval`||e.status===`running`||(e.live=!1)}#$e(e,t,r){switch(e.type){case`step-start`:this.#et(r.hasPendingToolResults?STATUS.toolResults:STATUS.processing),r.hasPendingToolResults=!1;break;case`step-finish`:this.#at(e.usage),this.#ot();break;case`assistant-delta`:{this.#et(STATUS.streaming);let t=(r.text.get(e.id)??``)+stripTerminalControls(e.delta);r.text.set(e.id,t),this.#tt(e.id,t,!0);break}case`assistant-complete`:{let t=r.text.get(e.id)??``,i=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;r.text.set(e.id,i),this.#tt(e.id,i,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;this.#et(STATUS.streaming);let i=(r.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);r.reasoning.set(e.id,i),this.#nt(e.id,i,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let n=r.reasoning.get(e.id)??``;this.#nt(e.id,n,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#et(STATUS.executingTools),this.#rt({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,r);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let n=r.tools.get(e.toolCallId);if(n===void 0)break;this.#rt({...n,status:`approval`},t,r);break}case`tool-result`:{if(t.tools===`hidden`)break;let n=this.#it(e.toolCallId,r);if(n===void 0)break;r.hasPendingToolResults=!0,this.#et(STATUS.toolResults),this.#rt({...n,output:e.output,status:`done`},t,r);break}case`tool-error`:{if(t.tools===`hidden`)break;let n=this.#it(e.toolCallId,r);if(n===void 0)break;r.hasPendingToolResults=!0,this.#et(STATUS.toolResults),this.#rt({...n,errorText:e.errorText,status:`error`},t,r);break}case`error`:this.#Je(`Error`,e.errorText,e.detail);break;case`finish`:this.#at(e.usage),this.#ot();break}}#et(e){let t=this.#w>0?STATUS.connectionAuth:e;this.#M!==t&&(this.#M=t,this.#ot())}#tt(e,t,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Xe({id:e,kind:`assistant`,body:i,live:r}),this.#ot())}#nt(e,t,r,i){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#Xe({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(i.reasoning,r),live:r}),this.#ot())}#rt(e,t,n){if(n.tools.set(e.toolCallId,e),this.#g.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#_.set(e.toolCallId,r),this.#Xe(renderNativeToolBlock(e,r,t.tools===`full`)),this.#ot()}#it(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#_.get(e)??toolSectionId(e),i=this.#p.get(r);if(!(i===void 0||i.kind!==`tool`))return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.title??`tool`}}#at(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#Y=(t??0)+(n??0)),this.#X=t??this.#X,this.#Q=n??this.#Q,this.#Q!=null&&this.#ee!==void 0){let e=(Date.now()-this.#ee)/1e3;e>0&&(this.#$=this.#Q/e)}}#ot(){if(this.#P){if(this.#q){this.#J=!0;return}this.#q=!0;try{do this.#J=!1,this.#st();while(this.#J)}finally{this.#q=!1}}}#st(){if(!this.#P)return;let e=this.#_t(),t=this.#mt(e),n=Math.max(1,this.#vt()-t.length),r=[],i=this.#C;for(;this.#f.length>0&&this.#f[0].live===!1;){let t=this.#f.shift();if(this.#h.push(t),t.id&&(this.#m.add(t.id),this.#p.delete(t.id)),this.#kt(t))continue;let n=this.#ft(t,e,i);i=previousBlockOf(t),this.#C=i,r.push(...n),this.#S.push(...n)}let a=[];for(let t of this.#f){if(this.#kt(t))continue;let n=this.#ft(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)a.push({block:t,row:n[e]})}let o=[...clipLiveRows(a.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,o):this.#n.update(o)}#ct(){if(!this.#P)return;let e=this.#_t(),t=this.#mt(e),n=Math.max(1,this.#vt()-t.length),r=this.#C,i=[];for(let t of this.#f){if(this.#kt(t))continue;let n=this.#ft(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.#dt(),...this.#S],a)}logDisplayMode(){return this.#d}setLogDisplayMode(e){e!==this.#d&&(this.#d=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#ut(),this.#P&&this.#ct())}flushDelayedDevBuildErrors(){let e=this.#ie;e!==void 0&&(this.#ie=void 0,this.#Ge({kind:`log`,title:`stderr`,body:e,live:!1}),this.#ot())}#lt(){this.#V=!0,this.#B!==void 0&&clearTimeout(this.#B),this.#B=setTimeout(()=>{this.#V=!1,this.#B=void 0,this.#ot()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#d)),this.#ot()}#ut(){let e=this.#_t();this.#S.length=0;let t;for(let n of this.#h){if(this.#kt(n))continue;let r=this.#ft(n,e,t);t=previousBlockOf(n),this.#S.push(...r)}this.#C=t}#dt(){let e=this.#y;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#_t()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#ft(e,t,n){let r={spinner:this.#pt()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#pt(){return this.#r.spinner[this.#L%this.#r.spinner.length]??``}#mt(e){let t=this.#r.colors,n=[``],r=this.#ce;if(r!==void 0){let t=this.#pt(),i;if(r.question!==void 0){let n=r.question(e);i={kind:`question`,rows:n},r.status!==void 0&&(i={kind:`question`,rows:n,status:{text:r.status,frame:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,frame:t}:{kind:`preview`,text:r.preview,frame:t}:(i={kind:`status`,status:{text:r.status,frame:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,frame:t},preview:r.preview}));let a={title:r.title,lines:r.hideLinesWhileQuestion===!0?[]:r.lines,content:i};return n.push(...renderFlowPanel(a,this.#r,e)),n}if(this.#le!==void 0&&n.push(...renderAttentionRows(this.#le,e,this.#r),``),this.#k){let r=this.#A===void 0?void 0:inlineCommandHint(this.#A);r===void 0&&this.#A!==void 0&&isTypeaheadOpen(this.#A)&&n.push(...renderCommandSuggestions(this.#A,this.#r,e));let i=Math.max(4,e-3),{before:a,after:o}=visibleLine({text:this.#E,cursor:this.#D},i,this.#r.glyph.ellipsis),s=isPromptControlCommand(this.#E),style=e=>s&&e.length>0?t.blue(e):e,l=this.#I?t.cyan(this.#r.glyph.caret):` `,u=r?t.dim(` ${r}`):``,d=`${style(a)}${l}${style(o)}${u}`;return n.push(...promptInputRows(d,e,this.#r,!0)),this.#ht(n,e),n}let i=this.#j?t.yellow(this.#pt()):t.dim(this.#r.glyph.dot),a=this.#M.length>0?this.#M:`Ready`,o=this.#j?t.dim(a):a,s=this.#gt(),l=s?`${i} ${o} ${t.dim(this.#r.glyph.dot)} ${s}`:`${i} ${o}`;return n.push(clip(l,e)),this.#ht(n,e),n}#ht(e,t){let n={theme:this.#r,width:t};this.#V&&(n.logLevel=this.#d);let r=this.#y?.info?.agent.model.id;r!==void 0&&(n.model=r);let i=this.#y?.info?.agent.model.endpoint;i!==void 0&&(n.endpoint=i);let a=this.#X??0,o=this.#Q??0;if(a>0||o>0){let e={inputTokens:a,outputTokens:o};this.#Z!==void 0&&(e.contextSize=this.#Z),n.tokens=formatTokenFlow(e,this.#r.glyph)}this.#T!==void 0&&(n.vercel=this.#T);let s=buildStatusLine(n);s!==void 0&&e.push(s)}#gt(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Y,outputTokens:this.#Q,tokensPerSecond:this.#$},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#_t(){return Math.max(20,this.#t.columns||80)}#vt(){return Math.max(8,this.#t.rows||24)}#yt(){if(this.#te!==void 0||!this.#u)return;this.#ne=``,this.#re=``;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.#xt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#te=()=>{e(),t()}}#bt(){let e=this.#te;e!==void 0&&(this.#te=void 0,e(),this.#ne.length>0&&(this.#Ot(`stdout`)&&process.stdout.write(`${this.#ne}\n`),this.#ne=``),this.#re.length>0&&(this.#Ot(`stderr`)&&process.stderr.write(`${this.#re}\n`),this.#re=``))}#xt(e,n){let r=(e===`stdout`?this.#ne:this.#re)+n,i=r.lastIndexOf(`
4
+ `),a=i===-1?r:r.slice(i+1);if(e===`stdout`?this.#ne=a:this.#re=a,i===-1)return;let o=stripAnsi(r.slice(0,i)).replace(/\s+$/u,``);o.trim().length!==0&&(e===`stdout`?this.#St(o):this.#Ct(o),this.#ot())}#St(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
5
+ `);t=[],e.trim().length!==0&&this.#Ge({kind:`log`,title:`stdout`,body:e,live:!1})};for(let n of e.split(`
6
+ `)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#Ge({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#Tt(r,n.trimEnd())}flushPending()}#Ct(e){let t=e.split(`
7
+ `),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){this.#Ge({kind:`log`,title:`stderr`,body:e,live:!1});return}let r=t.slice(0,n).join(`
8
+ `);r.trim().length>0&&this.#Ge({kind:`log`,title:`stderr`,body:r,live:!1});let i=t.slice(n).join(`
9
+ `);this.#wt(i)}#wt(e){if(this.#d===`all`){if(e.trim().length===0)return;this.#Ge({kind:`log`,title:`stderr`,body:e,live:!1});return}this.#ie=e}#Tt(e,t){let n=this.#Et();if(e.kind===`failed`){this.#wt(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.#oe}`;this.#oe+=1,this.#ae={id:r,summary:t},this.#Ge({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.#ie=void 0);return}e.kind===`rebuilt`&&(this.#ie=void 0),this.#Ge({kind:`log`,title:`stdout`,body:t,live:!1})}#Et(){let e=this.#ae;if(e===void 0)return;let t=this.#p.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#Dt(){let e=this.#ae;if(e===void 0)return;this.#ae=void 0;let t=this.#p.get(e.id);t!==void 0&&(t.live=!1)}#Ot(e){switch(this.#d){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#kt(e){return e.kind===`sandbox`?!this.#Ot(`sandbox`):e.kind===`log`?!this.#Ot(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(t,n){return visibleLength(t)>n?sliceVisible(t,n):t}function promptInputRows(e,t,n,r){let i=n.colors;return[clip(`${r?i.cyan(n.glyph.prompt):i.dim(n.glyph.prompt)} ${r?e:i.dim(e)}`,t),``]}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function leadsWithGap(e,t){if(e.kind===`sandbox`&&t?.kind===`sandbox`)return!1;if(t?.kind===`sandbox`&&e.kind!==`sandbox`)return!0;if(e.kind===`log`&&t?.kind===`log`)return t.title!==e.title;if(t?.kind===`log`&&e.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`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,r){let o={id:t,kind:`tool`,title:stripTerminalControls(e.toolName),subtitle:summarizeToolArgs(e.input),status:e.status,live:e.status===`running`||e.status===`approval`,expanded:r,toolInput:e.input};return e.output===void 0?e.errorText!==void 0&&(o.result=stripTerminalControls(e.errorText)):(o.result=summarizeToolResult(e.output),o.toolOutput=e.output),o}function subagentToolStatus(e){switch(e){case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`}}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 formatConnectionAuthContent(e){let t=[],r=stripTerminalControls(e.description);r.length>0&&t.push(r);let i=e.challenge;if(i?.url&&t.push(`URL: ${stripTerminalControls(i.url)}`),i?.userCode&&t.push(`Code: ${stripTerminalControls(i.userCode)}`),i?.expiresAt&&t.push(`Expires: ${stripTerminalControls(i.expiresAt)}`),i?.instructions&&t.push(stripTerminalControls(i.instructions)),e.reason!==void 0){let r=stripTerminalControls(e.reason);r.length>0&&t.push(`Reason: ${r}`)}return t.join(`
10
10
  `)}function formatQuestionContent(e,t,r){let i=r.colors,a=[],o=e.options??[];if(o.length>0){for(let[e,s]of o.entries()){let o=stripTerminalControls(s.label),c=s.description===void 0?``:stripTerminalControls(s.description),l=c.length>0?` ${i.dim(`— ${c}`)}`:``,u=t===e,d=u?`${i.cyan(r.glyph.pointer)} `:` `,f=u?i.cyan(o):o;a.push(`${d}${f}${l}`)}if(e.allowFreeform===!0){let e=t===o.length,n=e?`${i.cyan(r.glyph.pointer)} `:` `,s=`Type your own answer`;a.push(`${n}${e?i.cyan(s):i.dim(s)}`)}}else a.push(i.dim(` (type your answer)`));return a.join(`
11
11
  `)}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};
@@ -1,3 +1,3 @@
1
- import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{basename}from"node:path";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{eveCliBanner}from"#cli/banner.js";import{Command,CommanderError,InvalidArgumentError}from"#compiled/commander/index.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{registerProjectCommands}from"#cli/commands/register-project-commands.js";import{LOG_DISPLAY_MODES,parseLogDisplayMode}from"#cli/dev/tui/log-display-mode.js";import{parseDevelopmentServerUrl}from"#cli/dev/url.js";async function loadBuildHost(){return(await import(`#internal/nitro/host.js`)).buildApplication}async function loadPrintApplicationInfo(){return(await import(`#cli/commands/info.js`)).printApplicationInfo}async function loadRunDevelopmentTui(){return(await import(`#cli/dev/tui/tui.js`)).runDevelopmentTui}async function loadRunEvalCommand(){return(await import(`#evals/cli/eval.js`)).runEvalCommand}async function loadStartHost(){return(await import(`#internal/nitro/host.js`)).startDevelopmentServer}async function loadStartProductionHost(){return(await import(`#internal/nitro/host.js`)).startProductionServer}function shouldPrintCliBootBanner(e){return e.name()===`info`||e.name()===`dev`||e.name()===`init`}async function waitForShutdownSignal(e){await new Promise((t,n)=>{let r=!1,cleanup=()=>{process.off(`SIGINT`,handleSignal),process.off(`SIGTERM`,handleSignal)},handleSignal=()=>{r||(r=!0,cleanup(),e.close().then(t,n))};process.once(`SIGINT`,handleSignal),process.once(`SIGTERM`,handleSignal)})}async function waitForProductionServer(e){await Promise.race([e.wait(),waitForShutdownSignal({close:()=>e.close()})])}function parsePortOption(e){if(!/^-?\d+$/.test(e))throw new InvalidArgumentError(`Expected a numeric port, received "${e}".`);let t=Number(e);if(t<0||t>65535)throw new InvalidArgumentError(`Expected a port between 0 and 65535, received "${e}".`);return t}const DISPLAY_MODES=new Set([`full`,`collapsed`,`auto-collapsed`,`hidden`]),STATS_MODES=new Set([`tokens`,`tokensPerSecond`]);function parseDisplayMode(e){if(!DISPLAY_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...DISPLAY_MODES].join(`, `)}, received "${e}".`);return e}function parseStatsMode(e){if(!STATS_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...STATS_MODES].join(`, `)}, received "${e}".`);return e}function parseLogsMode(e){let t=parseLogDisplayMode(e);if(t===void 0)throw new InvalidArgumentError(`Expected one of ${LOG_DISPLAY_MODES.join(`, `)}, received "${e}".`);return t}function parseContextSizeOption(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new InvalidArgumentError(`Expected a positive number, received "${e}".`);return t}function resolveDevUiMode(e){return e.options.ui===!1||!e.interactive?`headless`:`tui`}function resolveTuiTitle(e){if(e.name!==void 0&&e.name.length>0)return e.name;if(e.remoteServerUrl!==void 0)try{return new URL(e.remoteServerUrl).host}catch{return}let n=humanizeProjectName(basename(e.appRoot));return n.length>0?n:void 0}function humanizeProjectName(e){return e.replace(/[-_.]+/gu,` `).trim().split(/\s+/u).filter(e=>e.length>0).map(e=>e[0].toUpperCase()+e.slice(1)).join(` `)}function resolveTuiDisplayOptions(e){let t={logs:e.logs??`stderr`,reasoning:e.reasoning??`full`,tools:e.tools??`auto-collapsed`};return e.subagents!==void 0&&(t.subagents=e.subagents),e.connectionAuth!==void 0&&(t.connectionAuth=e.connectionAuth),e.assistantResponseStats!==void 0&&(t.assistantResponseStats=e.assistantResponseStats),e.contextSize!==void 0&&(t.contextSize=e.contextSize),t}function hasInteractiveTerminal(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function rewriteDevelopmentUrlShorthand(e){let t=e[1];return e[0]!==`dev`||e.length!==2||t===void 0||t.startsWith(`-`)?[...e]:[`dev`,`--url`,t]}function resolveRemoteDevelopmentServerUrl(e){if(e.url){if(e.host!==void 0)throw new InvalidArgumentError(`The --host option cannot be used with --url.`);if(e.port!==void 0)throw new InvalidArgumentError(`The --port option cannot be used with --url.`);if(e.ui===!1)throw new InvalidArgumentError(`The --no-ui option cannot be used with --url.`);return e.url}}function createCliProgram(t,o){let u=resolveApplicationRoot(),d=resolveInstalledPackageInfo().version,f=new Command,p=createCliTheme();f.name(`eve`).description(`Build and run an Eve application.`).version(d).showHelpAfterError().exitOverride().hook(`preAction`,(e,n)=>{shouldPrintCliBootBanner(n)&&t.log(eveCliBanner())}).configureOutput({writeErr:e=>{t.error(e.trimEnd())},writeOut:e=>{t.log(e.trimEnd())}});let m=f.command(`channels`).description(`Manage user-authored channels in the current project.`);return m.command(`add [kind]`).description(`Add channels interactively, or scaffold a channel kind (slack | web).`).option(`-f, --force`,`Overwrite existing channel files`).option(`-y, --yes`,`Assume yes for confirmations; requires an explicit channel kind`).action(async(e,n)=>{let{runChannelsAddCommand:r}=await import(`#cli/commands/channels.js`);await r(t,u,{kind:e,options:n})}),m.command(`list`).description(`List user-authored channels in the current project.`).option(`--json`,`Output as JSON`).action(async e=>{let{runChannelsListCommand:n}=await import(`#cli/commands/channels.js`);await n(t,u,e)}),f.command(`init <target>`).description(`Create a new Eve agent, or add one to an existing project directory.`).option(`--channel-web-nextjs`,`Add the Web Chat application (Next.js)`).action(async(e,n)=>{let{runInitCommand:r}=await import(`#cli/commands/init.js`);await r(t,u,e,n)}),registerProjectCommands({program:f,logger:t,appRoot:u}),f.command(`build`).description(`Build the current Eve application.`).action(async()=>{let{loadDevelopmentEnvironmentFiles:e}=await import(`#cli/dev/environment.js`);e(u);let n=await(o.buildHost??await loadBuildHost())(u);t.log(renderCliTaggedLine(p,{message:`built output at ${n}`,tag:`build`,tone:`success`}))}),f.command(`start`).description(`Start a built Eve application.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,parsePortOption).action(async e=>{let{loadDevelopmentEnvironmentFiles:n}=await import(`#cli/dev/environment.js`);n(u);let i=await(o.startProductionHost??await loadStartProductionHost())(u,{host:e.host,port:e.port});t.log(renderCliTaggedLine(p,{message:`server listening at ${i.url}`,tag:`start`,tone:`success`})),await waitForProductionServer(i)}),f.command(`dev`).description(`Start the Eve development server or connect to an existing URL.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,parsePortOption).option(`-u, --url <url>`,`Connect to an existing server URL`,parseDevelopmentServerUrl).option(`--no-ui`,`Start the server without an interactive UI`).option(`--name <name>`,`Title shown in the terminal UI (defaults to the app folder name)`).option(`--input <text>`,`Pre-fill the prompt input after launching the UI`).option(`--tools <mode>`,`How tool calls render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--reasoning <mode>`,`How reasoning renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--subagents <mode>`,`How subagent sections render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--connection-auth <mode>`,`How connection authorization renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--assistant-response-stats <mode>`,`Assistant header statistic: tokens | tokensPerSecond`,parseStatsMode).option(`--context-size <tokens>`,`Model context window size, shown as a usage percentage`,parseContextSizeOption).option(`--logs <mode>`,`Which server/agent logs to show: all | stderr | sandbox | none`,parseLogsMode).addHelpText(`after`,`
1
+ import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{basename}from"node:path";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{eveCliBanner}from"#cli/banner.js";import{Command,CommanderError,InvalidArgumentError}from"#compiled/commander/index.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{registerProjectCommands}from"#cli/commands/register-project-commands.js";import{LOG_DISPLAY_MODES,parseLogDisplayMode}from"#cli/dev/tui/log-display-mode.js";import{parseDevelopmentServerUrl}from"#cli/dev/url.js";async function loadBuildHost(){return(await import(`#internal/nitro/host.js`)).buildApplication}async function loadPrintApplicationInfo(){return(await import(`#cli/commands/info.js`)).printApplicationInfo}async function loadRunDevelopmentTui(){return(await import(`#cli/dev/tui/tui.js`)).runDevelopmentTui}async function loadRunEvalCommand(){return(await import(`#evals/cli/eval.js`)).runEvalCommand}async function loadStartHost(){return(await import(`#internal/nitro/host.js`)).startDevelopmentServer}async function loadStartProductionHost(){return(await import(`#internal/nitro/host.js`)).startProductionServer}function shouldPrintCliBootBanner(e){return e.name()===`info`||e.name()===`dev`||e.name()===`init`}async function waitForShutdownSignal(e){await new Promise((t,n)=>{let r=!1,cleanup=()=>{process.off(`SIGINT`,handleSignal),process.off(`SIGTERM`,handleSignal)},handleSignal=()=>{r||(r=!0,cleanup(),e.close().then(t,n))};process.once(`SIGINT`,handleSignal),process.once(`SIGTERM`,handleSignal)})}async function waitForProductionServer(e){await Promise.race([e.wait(),waitForShutdownSignal({close:()=>e.close()})])}function parsePortOption(e){if(!/^-?\d+$/.test(e))throw new InvalidArgumentError(`Expected a numeric port, received "${e}".`);let t=Number(e);if(t<0||t>65535)throw new InvalidArgumentError(`Expected a port between 0 and 65535, received "${e}".`);return t}const DISPLAY_MODES=new Set([`full`,`collapsed`,`auto-collapsed`,`hidden`]),STATS_MODES=new Set([`tokens`,`tokensPerSecond`]);function parseDisplayMode(e){if(!DISPLAY_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...DISPLAY_MODES].join(`, `)}, received "${e}".`);return e}function parseStatsMode(e){if(!STATS_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...STATS_MODES].join(`, `)}, received "${e}".`);return e}function parseLogsMode(e){let t=parseLogDisplayMode(e);if(t===void 0)throw new InvalidArgumentError(`Expected one of ${LOG_DISPLAY_MODES.join(`, `)}, received "${e}".`);return t}function parseContextSizeOption(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new InvalidArgumentError(`Expected a positive number, received "${e}".`);return t}function resolveDevUiMode(e){return e.options.ui===!1||!e.interactive?`headless`:`tui`}function resolveTuiTitle(e){if(e.name!==void 0&&e.name.length>0)return e.name;if(e.remoteServerUrl!==void 0)try{return new URL(e.remoteServerUrl).host}catch{return}let n=humanizeProjectName(basename(e.appRoot));return n.length>0?n:void 0}function humanizeProjectName(e){return e.replace(/[-_.]+/gu,` `).trim().split(/\s+/u).filter(e=>e.length>0).map(e=>e[0].toUpperCase()+e.slice(1)).join(` `)}function resolveTuiDisplayOptions(e){let t={logs:e.logs??`stderr`,reasoning:e.reasoning??`full`,tools:e.tools??`auto-collapsed`};return e.subagents!==void 0&&(t.subagents=e.subagents),e.connectionAuth!==void 0&&(t.connectionAuth=e.connectionAuth),e.assistantResponseStats!==void 0&&(t.assistantResponseStats=e.assistantResponseStats),e.contextSize!==void 0&&(t.contextSize=e.contextSize),t}function hasInteractiveTerminal(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function rewriteDevelopmentUrlShorthand(e){let t=e[1];return e[0]!==`dev`||e.length!==2||t===void 0||t.startsWith(`-`)?[...e]:[`dev`,`--url`,t]}function resolveRemoteDevelopmentServerUrl(e){if(e.url){if(e.host!==void 0)throw new InvalidArgumentError(`The --host option cannot be used with --url.`);if(e.port!==void 0)throw new InvalidArgumentError(`The --port option cannot be used with --url.`);if(e.ui===!1)throw new InvalidArgumentError(`The --no-ui option cannot be used with --url.`);return e.url}}function createCliProgram(t,o){let u=resolveApplicationRoot(),d=resolveInstalledPackageInfo().version,f=new Command,p=createCliTheme();f.name(`eve`).description(`Build and run an Eve application.`).version(d).showHelpAfterError().exitOverride().hook(`preAction`,(e,n)=>{shouldPrintCliBootBanner(n)&&t.log(eveCliBanner())}).configureOutput({writeErr:e=>{t.error(e.trimEnd())},writeOut:e=>{t.log(e.trimEnd())}});let m=f.command(`channels`).description(`Manage user-authored channels in the current project.`);return m.command(`add [kind]`).description(`Add channels interactively, or scaffold a channel kind (slack | web).`).option(`-f, --force`,`Overwrite existing channel files`).option(`-y, --yes`,`Assume yes for confirmations; requires an explicit channel kind`).action(async(e,n)=>{let{runChannelsAddCommand:r}=await import(`#cli/commands/channels.js`);await r(t,u,{kind:e,options:n})}),m.command(`list`).description(`List user-authored channels in the current project.`).option(`--json`,`Output as JSON`).action(async e=>{let{runChannelsListCommand:n}=await import(`#cli/commands/channels.js`);await n(t,u,e)}),f.command(`init [target]`).description(`Create a new Eve agent, or add one to an existing project directory.`).option(`--channel-web-nextjs`,`Add the Web Chat application (Next.js)`).action(async(e,n)=>{let{runInitCommand:r}=await import(`#cli/commands/init.js`);await r(t,u,e,n)}),registerProjectCommands({program:f,logger:t,appRoot:u}),f.command(`build`).description(`Build the current Eve application.`).action(async()=>{let{loadDevelopmentEnvironmentFiles:e}=await import(`#cli/dev/environment.js`);e(u);let n=await(o.buildHost??await loadBuildHost())(u);t.log(renderCliTaggedLine(p,{message:`built output at ${n}`,tag:`build`,tone:`success`}))}),f.command(`start`).description(`Start a built Eve application.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,parsePortOption).action(async e=>{let{loadDevelopmentEnvironmentFiles:n}=await import(`#cli/dev/environment.js`);n(u);let i=await(o.startProductionHost??await loadStartProductionHost())(u,{host:e.host,port:e.port});t.log(renderCliTaggedLine(p,{message:`server listening at ${i.url}`,tag:`start`,tone:`success`})),await waitForProductionServer(i)}),f.command(`dev`).description(`Start the Eve development server or connect to an existing URL.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,parsePortOption).option(`-u, --url <url>`,`Connect to an existing server URL`,parseDevelopmentServerUrl).option(`--no-ui`,`Start the server without an interactive UI`).option(`--name <name>`,`Title shown in the terminal UI (defaults to the app folder name)`).option(`--input <text>`,`Pre-fill the prompt input after launching the UI`).option(`--tools <mode>`,`How tool calls render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--reasoning <mode>`,`How reasoning renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--subagents <mode>`,`How subagent sections render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--connection-auth <mode>`,`How connection authorization renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--assistant-response-stats <mode>`,`Assistant header statistic: tokens | tokensPerSecond`,parseStatsMode).option(`--context-size <tokens>`,`Model context window size, shown as a usage percentage`,parseContextSizeOption).option(`--logs <mode>`,`Which server/agent logs to show: all | stderr | sandbox | none`,parseLogsMode).addHelpText(`after`,`
2
2
  You can also pass a bare URL as the only argument, for example: eve dev https://example.com
3
3
  `).action(async e=>{let n=resolveRemoteDevelopmentServerUrl(e),i=hasInteractiveTerminal(),a=resolveDevUiMode({options:e,interactive:i});if(e.input!==void 0&&a===`headless`)throw new InvalidArgumentError(`--input requires the interactive UI.`);let{loadDevelopmentEnvironmentFiles:c}=await import(`#cli/dev/environment.js`);c(u);let runInteractiveUi=async r=>{t.log(``);let i=o.runDevelopmentTui??await loadRunDevelopmentTui(),a=resolveTuiDisplayOptions(e),s=resolveTuiTitle({name:e.name,remoteServerUrl:n,appRoot:u});s!==void 0&&(a.name=s);let c={serverUrl:r,...a};n===void 0&&(c.appRoot=u),e.input!==void 0&&(c.initialInput=e.input),await i(c)};if(n){if(t.log(renderCliTaggedLine(p,{message:`connecting to ${n}`,tag:`dev`,tone:`info`})),a===`headless`){t.log(renderCliTaggedLine(p,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`}));return}await runInteractiveUi(n);return}let l=await(o.startHost??await loadStartHost())(u,{host:e.host,port:e.port}),d=!1,closeServer=async()=>{d||(d=!0,await l.close())};try{if(a!==`tui`&&t.log(renderCliTaggedLine(p,{message:`server listening at ${l.url}`,tag:`dev`,tone:`success`})),a===`headless`)return e.ui!==!1&&!i&&t.log(renderCliTaggedLine(p,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`})),await waitForShutdownSignal({close:closeServer});await runInteractiveUi(l.url)}finally{await closeServer()}}),f.command(`info`).description(`Print resolved application information.`).option(`--json`,`Output as JSON`).action(async e=>{await(o.printApplicationInfo??await loadPrintApplicationInfo())(t,u,e)}),f.command(`eval`).description(`Run evals against an Eve agent.`).argument(`[evalIds...]`,`Eval ids (or directory prefixes) to run (all discovered evals when omitted)`).option(`--url <url>`,`Remote agent URL (skip local host startup)`).option(`--tag <tag...>`,`Run only evals carrying a tag`).option(`--strict`,`Fail the exit code when any score falls below its threshold`).option(`--list`,`Print discovered evals without running them`).option(`--timeout <ms>`,`Per-eval timeout in milliseconds`).option(`--max-concurrency <n>`,`Max concurrent eval executions`).option(`--json`,`Output results as JSON`).option(`--junit <path>`,`Write JUnit XML results to a file`).option(`--skip-report`,`Skip eval-defined reporters (e.g. Braintrust)`).option(`--verbose`,`Stream per-eval ctx.log lines to stdout`).action(async(e,n)=>{await(o.runEvalCommand??await loadRunEvalCommand())(e,n,t)}),f}async function runCli(e=process.argv.slice(2),t=console,n={}){let r=createCliProgram(t,n),i=e.length===0?[`dev`]:rewriteDevelopmentUrlShorthand(e);try{await r.parseAsync(i,{from:`user`})}catch(e){if(e instanceof CommanderError){if(e.exitCode===0)return;throw Error(e.message)}throw e}}export{resolveDevUiMode,resolveTuiDisplayOptions,resolveTuiTitle,runCli};
@@ -20,6 +20,7 @@
20
20
  "semver": "7.8.4",
21
21
  "@standard-schema/spec": "1.1.0",
22
22
  "turndown": "7.2.4",
23
+ "@vercel/detect-agent": "1.2.3",
23
24
  "@vercel/oidc": "3.5.0",
24
25
  "@vercel/sandbox": "2.2.1",
25
26
  "@workflow/core": "5.0.0-beta.15",
@@ -28,5 +29,5 @@
28
29
  "zod": "4.4.3",
29
30
  "zod-validation-error": "5.0.0"
30
31
  },
31
- "scriptHash": "8747039183f8d37273f8ede1c4f82e37763b9103421d434baddd3298a4a83c38"
32
+ "scriptHash": "a6001eeee1872ee43456043e6c0b8ca745ad8766a75b148eb3d638e4cccce565"
32
33
  }
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2017 Vercel, Inc.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,20 @@
1
+ // Minimal declaration for the vendored slice of `@vercel/detect-agent`.
2
+ // Eve only asks "was this launch agent-driven?", so the per-agent name
3
+ // union upstream declares is collapsed to `string`; widen this if a
4
+ // future caller branches on specific agents.
5
+
6
+ export type AgentResult =
7
+ | {
8
+ isAgent: true;
9
+ agent: { name: string };
10
+ }
11
+ | {
12
+ isAgent: false;
13
+ agent: undefined;
14
+ };
15
+
16
+ /**
17
+ * Detects whether the current process was launched by a known AI coding
18
+ * agent, from environment markers (and a Devin filesystem probe).
19
+ */
20
+ export declare function determineAgent(): Promise<AgentResult>;
@@ -0,0 +1 @@
1
+ import{createRequire as e}from"node:module";var t=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),n=e(import.meta.url),r=t(((e,t)=>{var r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},c=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(r({},`__esModule`,{value:!0}),e),u={};s(u,{KNOWN_AGENTS:()=>T,determineAgent:()=>E}),t.exports=l(u);var d=n(`node:fs/promises`),f=n(`node:fs`);let p=`cursor`,m=`cursor-cli`,h=`claude`,g=`cowork`,_=`devin`,v=`replit`,y=`gemini`,b=`codex`,x=`antigravity`,S=`augment-cli`,C=`opencode`,w=`github-copilot`,T={CURSOR:p,CURSOR_CLI:m,CLAUDE:h,COWORK:g,DEVIN:_,REPLIT:v,GEMINI:y,CODEX:b,ANTIGRAVITY:x,AUGMENT_CLI:S,OPENCODE:C,GITHUB_COPILOT:w,V0:`v0`};async function E(){if(process.env.AI_AGENT){let e=process.env.AI_AGENT.trim();if(e)return e===w||e===`github-copilot-cli`?{isAgent:!0,agent:{name:w}}:e===`v0`?{isAgent:!0,agent:{name:`v0`}}:{isAgent:!0,agent:{name:e}}}if(process.env.CURSOR_TRACE_ID)return{isAgent:!0,agent:{name:p}};if(process.env.CURSOR_AGENT||process.env.CURSOR_EXTENSION_HOST_ROLE===`agent-exec`)return{isAgent:!0,agent:{name:m}};if(process.env.GEMINI_CLI)return{isAgent:!0,agent:{name:y}};if(process.env.CODEX_SANDBOX||process.env.CODEX_CI||process.env.CODEX_THREAD_ID)return{isAgent:!0,agent:{name:b}};if(process.env.ANTIGRAVITY_AGENT)return{isAgent:!0,agent:{name:x}};if(process.env.AUGMENT_AGENT)return{isAgent:!0,agent:{name:S}};if(process.env.OPENCODE_CLIENT)return{isAgent:!0,agent:{name:C}};if(process.env.CLAUDECODE||process.env.CLAUDE_CODE)return process.env.CLAUDE_CODE_IS_COWORK?{isAgent:!0,agent:{name:g}}:{isAgent:!0,agent:{name:h}};if(process.env.REPL_ID)return{isAgent:!0,agent:{name:v}};if(process.env.COPILOT_MODEL||process.env.COPILOT_ALLOW_ALL||process.env.COPILOT_GITHUB_TOKEN)return{isAgent:!0,agent:{name:w}};try{return await(0,d.access)(`/opt/.devin`,f.constants.F_OK),{isAgent:!0,agent:{name:_}}}catch{}return{isAgent:!1,agent:void 0}}0&&(t.exports={KNOWN_AGENTS:T,determineAgent:E})}))().determineAgent;export{r as determineAgent};
@@ -1 +1 @@
1
- import{dirname,join}from"node:path";import"node:fs";import{mkdir,readdir,rm,stat,utimes,writeFile}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{expectDockerSuccess}from"#execution/sandbox/bindings/docker-utils.js";import{createDockerCli}from"#execution/sandbox/bindings/docker-cli.js";import{LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,selectStaleTemplateEntries}from"#execution/sandbox/bindings/local-template-prune.js";const DOCKER_TEMPLATE_IMAGE_REPOSITORY=`eve-sandbox-template`;async function pruneDockerSandboxTemplates(e){let n=e.dockerCli??createDockerCli(),i=resolveDockerTemplateMarkersDirectory(e.appRoot),a;try{a=await readdir(i,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let o=selectStaleTemplateEntries(await Promise.all(a.filter(e=>e.isFile()).map(async e=>{let n=join(i,e.name);return{imageTag:e.name,mtimeMs:(await stat(n)).mtimeMs,path:n}})),{now:e.now??Date.now(),recentWindowMs:e.recentWindowMs??LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,retainCount:e.retainCount??LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT});for(let e of o){let t=await n.run([`rmi`,dockerTemplateImageReferenceFromTag(e.imageTag)]),r=t.exitCode!==0&&/no such image/i.test(t.stderr);(t.exitCode===0||r)&&await rm(e.path,{force:!0})}}function dockerTemplateImageReference(e){return dockerTemplateImageReferenceFromTag(dockerTemplateImageTag(e))}function dockerTemplateImageReferenceFromTag(e){return`${DOCKER_TEMPLATE_IMAGE_REPOSITORY}:${e}`}function dockerTemplateImageTag(e){return`${e.templateKey.toLowerCase()}-${e.optionsHash}`}function resolveDockerTemplateMarkerPath(e,n){return join(resolveDockerTemplateMarkersDirectory(e),dockerTemplateImageTag(n))}async function touchDockerTemplateMarker(t,r){await mkdir(dirname(t),{recursive:!0});try{let e=new Date;await utimes(t,e,e)}catch{await writeFile(t,`${r}\n`)}}async function dockerImageExists(e,t){return(await e.run([`image`,`inspect`,`--format`,`{{.Id}}`,t])).exitCode===0}async function ensureDockerBaseImage(e,t){if(t.pullPolicy===`always`){expectDockerSuccess(await e.run([`pull`,t.image]),`pull base image "${t.image}"`);return}if(!await dockerImageExists(e,t.image)){if(t.pullPolicy===`never`)throw Error(`The local sandbox base image "${t.image}" is not present locally and pullPolicy is "never". Pull the image manually or relax the pull policy.`);expectDockerSuccess(await e.run([`pull`,t.image]),`pull base image "${t.image}"`)}}function resolveDockerTemplateMarkersDirectory(e){return join(resolveSandboxCacheDirectory(e),`docker`,`templates`)}export{DOCKER_TEMPLATE_IMAGE_REPOSITORY,dockerImageExists,dockerTemplateImageReference,ensureDockerBaseImage,pruneDockerSandboxTemplates,resolveDockerTemplateMarkerPath,touchDockerTemplateMarker};
1
+ import"node:fs";import{dirname,join}from"node:path";import{mkdir,readdir,rm,stat,utimes,writeFile}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{expectDockerSuccess}from"#execution/sandbox/bindings/docker-utils.js";import{createDockerCli}from"#execution/sandbox/bindings/docker-cli.js";import{LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,selectStaleTemplateEntries}from"#execution/sandbox/bindings/local-template-prune.js";const DOCKER_TEMPLATE_IMAGE_REPOSITORY=`eve-sandbox-template`;async function pruneDockerSandboxTemplates(e){let n=e.dockerCli??createDockerCli(),i=resolveDockerTemplateMarkersDirectory(e.appRoot),a;try{a=await readdir(i,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let o=selectStaleTemplateEntries(await Promise.all(a.filter(e=>e.isFile()).map(async e=>{let n=join(i,e.name);return{imageTag:e.name,mtimeMs:(await stat(n)).mtimeMs,path:n}})),{now:e.now??Date.now(),recentWindowMs:e.recentWindowMs??LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,retainCount:e.retainCount??LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT});for(let e of o){let t=await n.run([`rmi`,dockerTemplateImageReferenceFromTag(e.imageTag)]),r=t.exitCode!==0&&/no such image/i.test(t.stderr);(t.exitCode===0||r)&&await rm(e.path,{force:!0})}}function dockerTemplateImageReference(e){return dockerTemplateImageReferenceFromTag(dockerTemplateImageTag(e))}function dockerTemplateImageReferenceFromTag(e){return`${DOCKER_TEMPLATE_IMAGE_REPOSITORY}:${e}`}function dockerTemplateImageTag(e){return`${e.templateKey.toLowerCase()}-${e.optionsHash}`}function resolveDockerTemplateMarkerPath(e,n){return join(resolveDockerTemplateMarkersDirectory(e),dockerTemplateImageTag(n))}async function touchDockerTemplateMarker(t,r){await mkdir(dirname(t),{recursive:!0});try{let e=new Date;await utimes(t,e,e)}catch{await writeFile(t,`${r}\n`)}}async function dockerImageExists(e,t){return(await e.run([`image`,`inspect`,`--format`,`{{.Id}}`,t])).exitCode===0}async function ensureDockerBaseImage(e,t){if(t.pullPolicy===`always`){expectDockerSuccess(await e.run([`pull`,t.image]),`pull base image "${t.image}"`);return}if(!await dockerImageExists(e,t.image)){if(t.pullPolicy===`never`)throw Error(`The local sandbox base image "${t.image}" is not present locally and pullPolicy is "never". Pull the image manually or relax the pull policy.`);expectDockerSuccess(await e.run([`pull`,t.image]),`pull base image "${t.image}"`)}}function resolveDockerTemplateMarkersDirectory(e){return join(resolveSandboxCacheDirectory(e),`docker`,`templates`)}export{DOCKER_TEMPLATE_IMAGE_REPOSITORY,dockerImageExists,dockerTemplateImageReference,ensureDockerBaseImage,pruneDockerSandboxTemplates,resolveDockerTemplateMarkerPath,touchDockerTemplateMarker};
@@ -1 +1 @@
1
- import{dirname,join}from"node:path";import"node:fs";import{mkdir,readdir,rename,rm,stat}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{randomUUID}from"node:crypto";import{copyDirectoryAtomically,createFileBackedInternalSandboxSession,pathExists,resolveLocalBackendSessionRootPath,resolveLocalBackendTemplateRootPath,resolveLocalBackendTemplatesDirectory,touchDirectory,writeSandboxSeedFiles}from"#execution/sandbox/bindings/local-backend-utils.js";import{LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,selectStaleTemplateEntries}from"#execution/sandbox/bindings/local-template-prune.js";import{createLoggingSandboxSession}from"#execution/sandbox/logging-session.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{createBashSandbox,createJustBashHandle,justBashSetNetworkPolicyUnsupported}from"#execution/sandbox/bindings/just-bash-runtime.js";const JUST_BASH_CACHE_DIRECTORY_NAME=`just-bash`,JUST_BASH_BACKEND_NAME=`just-bash`;function createJustBashSandboxBackend(t={}){let r=t.createOptions?.autoInstall??!0;return{name:JUST_BASH_BACKEND_NAME,async prewarm(t){let a=resolveTemplateRootPath(resolveSandboxCacheDirectory(t.runtimeContext.appRoot),t.templateKey);if(await pathExists(a))return await touchDirectory(a),{reused:!0};let s=`${a}.${randomUUID()}.tmp`,u=!1,d=await createBashSandbox({appRoot:t.runtimeContext.appRoot,autoInstall:r,rootPath:s,sessionKey:t.templateKey}),f=buildSandboxSession(createFileBackedInternalSandboxSession({id:d.sessionKey,sandbox:d}),justBashSetNetworkPolicyUnsupported);try{if(t.bootstrap!==void 0&&(t.log?.(`running sandbox bootstrap`),await t.bootstrap({use:async()=>createLoggingSandboxSession({log:t.log,session:f})})),await writeSandboxSeedFiles(f,t.seedFiles),await d.captureState()===null)throw Error(`Failed to capture local sandbox template state for "${t.templateKey}".`);await mkdir(dirname(a),{recursive:!0});try{await rename(s,a),u=!0}catch(e){if(await pathExists(a))return{reused:!0};throw e}}finally{await d.dispose(),u||await rm(s,{force:!0,recursive:!0}).catch(()=>{})}return{reused:!1}},async create(e){let t=resolveSandboxCacheDirectory(e.runtimeContext.appRoot),i=getLocalRootPath(e.existingMetadata)??resolveSessionRootPath(t,e.sessionKey);if(!await pathExists(i))if(e.templateKey===null)await mkdir(i,{recursive:!0});else{let n=resolveTemplateRootPath(t,e.templateKey);if(!await pathExists(n))throw new SandboxTemplateNotProvisionedError({backendName:JUST_BASH_BACKEND_NAME,templateKey:e.templateKey});await copyDirectoryAtomically(n,i)}return createJustBashHandle(await createBashSandbox({appRoot:e.runtimeContext.appRoot,autoInstall:r,rootPath:i,sessionKey:e.sessionKey}),JUST_BASH_BACKEND_NAME)}}}async function pruneJustBashSandboxTemplates(e){let n=resolveLocalBackendTemplatesDirectory(resolveSandboxCacheDirectory(e.appRoot),JUST_BASH_CACHE_DIRECTORY_NAME),i=e.now??Date.now(),o=e.recentWindowMs??LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,s=e.retainCount??LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,c;try{c=await readdir(n,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let l=await Promise.all(c.filter(e=>e.isDirectory()).map(async e=>{let r=join(n,e.name);return{isTemporary:e.name.endsWith(`.tmp`),mtimeMs:(await stat(r)).mtimeMs,path:r}})),u=selectStaleTemplateEntries(l.filter(e=>!e.isTemporary),{now:i,recentWindowMs:o,retainCount:s}),d=selectStaleTemplateEntries(l.filter(e=>e.isTemporary),{now:i,recentWindowMs:o,retainCount:0});await Promise.all([...u,...d].map(async e=>await rm(e.path,{force:!0,recursive:!0})))}function resolveTemplateRootPath(e,t){return resolveLocalBackendTemplateRootPath(e,JUST_BASH_CACHE_DIRECTORY_NAME,t)}function resolveSessionRootPath(e,t){return resolveLocalBackendSessionRootPath(e,JUST_BASH_CACHE_DIRECTORY_NAME,t)}function getLocalRootPath(e){let t=e?.rootPath;return typeof t==`string`?t:void 0}export{JUST_BASH_BACKEND_NAME,createJustBashSandboxBackend,pruneJustBashSandboxTemplates};
1
+ import"node:fs";import{dirname,join}from"node:path";import{mkdir,readdir,rename,rm,stat}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{randomUUID}from"node:crypto";import{copyDirectoryAtomically,createFileBackedInternalSandboxSession,pathExists,resolveLocalBackendSessionRootPath,resolveLocalBackendTemplateRootPath,resolveLocalBackendTemplatesDirectory,touchDirectory,writeSandboxSeedFiles}from"#execution/sandbox/bindings/local-backend-utils.js";import{LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,selectStaleTemplateEntries}from"#execution/sandbox/bindings/local-template-prune.js";import{createLoggingSandboxSession}from"#execution/sandbox/logging-session.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{createBashSandbox,createJustBashHandle,justBashSetNetworkPolicyUnsupported}from"#execution/sandbox/bindings/just-bash-runtime.js";const JUST_BASH_CACHE_DIRECTORY_NAME=`just-bash`,JUST_BASH_BACKEND_NAME=`just-bash`;function createJustBashSandboxBackend(t={}){let r=t.createOptions?.autoInstall??!0;return{name:JUST_BASH_BACKEND_NAME,async prewarm(t){let a=resolveTemplateRootPath(resolveSandboxCacheDirectory(t.runtimeContext.appRoot),t.templateKey);if(await pathExists(a))return await touchDirectory(a),{reused:!0};let s=`${a}.${randomUUID()}.tmp`,u=!1,d=await createBashSandbox({appRoot:t.runtimeContext.appRoot,autoInstall:r,rootPath:s,sessionKey:t.templateKey}),f=buildSandboxSession(createFileBackedInternalSandboxSession({id:d.sessionKey,sandbox:d}),justBashSetNetworkPolicyUnsupported);try{if(t.bootstrap!==void 0&&(t.log?.(`running sandbox bootstrap`),await t.bootstrap({use:async()=>createLoggingSandboxSession({log:t.log,session:f})})),await writeSandboxSeedFiles(f,t.seedFiles),await d.captureState()===null)throw Error(`Failed to capture local sandbox template state for "${t.templateKey}".`);await mkdir(dirname(a),{recursive:!0});try{await rename(s,a),u=!0}catch(e){if(await pathExists(a))return{reused:!0};throw e}}finally{await d.dispose(),u||await rm(s,{force:!0,recursive:!0}).catch(()=>{})}return{reused:!1}},async create(e){let t=resolveSandboxCacheDirectory(e.runtimeContext.appRoot),i=getLocalRootPath(e.existingMetadata)??resolveSessionRootPath(t,e.sessionKey);if(!await pathExists(i))if(e.templateKey===null)await mkdir(i,{recursive:!0});else{let n=resolveTemplateRootPath(t,e.templateKey);if(!await pathExists(n))throw new SandboxTemplateNotProvisionedError({backendName:JUST_BASH_BACKEND_NAME,templateKey:e.templateKey});await copyDirectoryAtomically(n,i)}return createJustBashHandle(await createBashSandbox({appRoot:e.runtimeContext.appRoot,autoInstall:r,rootPath:i,sessionKey:e.sessionKey}),JUST_BASH_BACKEND_NAME)}}}async function pruneJustBashSandboxTemplates(e){let n=resolveLocalBackendTemplatesDirectory(resolveSandboxCacheDirectory(e.appRoot),JUST_BASH_CACHE_DIRECTORY_NAME),i=e.now??Date.now(),o=e.recentWindowMs??LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,s=e.retainCount??LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,c;try{c=await readdir(n,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let l=await Promise.all(c.filter(e=>e.isDirectory()).map(async e=>{let r=join(n,e.name);return{isTemporary:e.name.endsWith(`.tmp`),mtimeMs:(await stat(r)).mtimeMs,path:r}})),u=selectStaleTemplateEntries(l.filter(e=>!e.isTemporary),{now:i,recentWindowMs:o,retainCount:s}),d=selectStaleTemplateEntries(l.filter(e=>e.isTemporary),{now:i,recentWindowMs:o,retainCount:0});await Promise.all([...u,...d].map(async e=>await rm(e.path,{force:!0,recursive:!0})))}function resolveTemplateRootPath(e,t){return resolveLocalBackendTemplateRootPath(e,JUST_BASH_CACHE_DIRECTORY_NAME,t)}function resolveSessionRootPath(e,t){return resolveLocalBackendSessionRootPath(e,JUST_BASH_CACHE_DIRECTORY_NAME,t)}function getLocalRootPath(e){let t=e?.rootPath;return typeof t==`string`?t:void 0}export{JUST_BASH_BACKEND_NAME,createJustBashSandboxBackend,pruneJustBashSandboxTemplates};
@@ -1 +1 @@
1
- import{join}from"node:path";import"node:fs";import{readdir,rm,stat}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{resolveLocalBackendSessionRootPath,resolveLocalBackendTemplateRootPath,resolveLocalBackendTemplatesDirectory}from"#execution/sandbox/bindings/local-backend-utils.js";import{LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT}from"#execution/sandbox/bindings/local-template-prune.js";import{readTemplateMetadata,resolveMicrosandboxMetadataPath}from"#execution/sandbox/bindings/microsandbox-metadata.js";import{loadMicrosandboxWithoutInstall,removeSnapshotIfExists}from"#execution/sandbox/bindings/microsandbox-runtime.js";const MICROSANDBOX_CACHE_DIRECTORY_NAME=`microsandbox`;async function pruneMicrosandboxTemplates(e){let t=resolveMicrosandboxTemplatesDirectory(resolveSandboxCacheDirectory(e.appRoot)),n=e.now??Date.now(),r=e.recentWindowMs??LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,a=e.retainCount??LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,o=await readMicrosandboxTemplateDirectories(t),s=o.filter(e=>!e.isTemporary);await Promise.all([...s.map(async(e,t)=>{t<a||n-e.mtimeMs<=r||await removeTemplateDirectory(e.path,e.metadata)}),...o.filter(e=>e.isTemporary).map(async e=>{n-e.mtimeMs<=r||await removeTemplateDirectory(e.path,e.metadata)})])}function resolveMicrosandboxTemplateRootPath(e,t){return resolveLocalBackendTemplateRootPath(e,MICROSANDBOX_CACHE_DIRECTORY_NAME,t)}function resolveMicrosandboxTemplatesDirectory(e){return resolveLocalBackendTemplatesDirectory(e,MICROSANDBOX_CACHE_DIRECTORY_NAME)}function resolveMicrosandboxSessionRootPath(e,t){return resolveLocalBackendSessionRootPath(e,MICROSANDBOX_CACHE_DIRECTORY_NAME,t)}async function readMicrosandboxTemplateDirectories(n){let i;try{i=await readdir(n,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return[];throw e}return(await Promise.all(i.filter(e=>e.isDirectory()).map(async t=>{let i=join(n,t.name);return{isTemporary:t.name.endsWith(`.tmp`),metadata:await readTemplateMetadata(resolveMicrosandboxMetadataPath(i)),mtimeMs:(await stat(i)).mtimeMs,path:i}}))).sort((e,t)=>t.mtimeMs-e.mtimeMs)}async function removeTemplateDirectory(e,t){if(await rm(e,{force:!0,recursive:!0}),t===null)return;let r=await loadMicrosandboxWithoutInstall();r!==null&&await removeSnapshotIfExists(r,t.snapshotName)}export{pruneMicrosandboxTemplates,resolveMicrosandboxSessionRootPath,resolveMicrosandboxTemplateRootPath,resolveMicrosandboxTemplatesDirectory};
1
+ import"node:fs";import{join}from"node:path";import{readdir,rm,stat}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{resolveLocalBackendSessionRootPath,resolveLocalBackendTemplateRootPath,resolveLocalBackendTemplatesDirectory}from"#execution/sandbox/bindings/local-backend-utils.js";import{LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT}from"#execution/sandbox/bindings/local-template-prune.js";import{readTemplateMetadata,resolveMicrosandboxMetadataPath}from"#execution/sandbox/bindings/microsandbox-metadata.js";import{loadMicrosandboxWithoutInstall,removeSnapshotIfExists}from"#execution/sandbox/bindings/microsandbox-runtime.js";const MICROSANDBOX_CACHE_DIRECTORY_NAME=`microsandbox`;async function pruneMicrosandboxTemplates(e){let t=resolveMicrosandboxTemplatesDirectory(resolveSandboxCacheDirectory(e.appRoot)),n=e.now??Date.now(),r=e.recentWindowMs??LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,a=e.retainCount??LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,o=await readMicrosandboxTemplateDirectories(t),s=o.filter(e=>!e.isTemporary);await Promise.all([...s.map(async(e,t)=>{t<a||n-e.mtimeMs<=r||await removeTemplateDirectory(e.path,e.metadata)}),...o.filter(e=>e.isTemporary).map(async e=>{n-e.mtimeMs<=r||await removeTemplateDirectory(e.path,e.metadata)})])}function resolveMicrosandboxTemplateRootPath(e,t){return resolveLocalBackendTemplateRootPath(e,MICROSANDBOX_CACHE_DIRECTORY_NAME,t)}function resolveMicrosandboxTemplatesDirectory(e){return resolveLocalBackendTemplatesDirectory(e,MICROSANDBOX_CACHE_DIRECTORY_NAME)}function resolveMicrosandboxSessionRootPath(e,t){return resolveLocalBackendSessionRootPath(e,MICROSANDBOX_CACHE_DIRECTORY_NAME,t)}async function readMicrosandboxTemplateDirectories(n){let i;try{i=await readdir(n,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return[];throw e}return(await Promise.all(i.filter(e=>e.isDirectory()).map(async t=>{let i=join(n,t.name);return{isTemporary:t.name.endsWith(`.tmp`),metadata:await readTemplateMetadata(resolveMicrosandboxMetadataPath(i)),mtimeMs:(await stat(i)).mtimeMs,path:i}}))).sort((e,t)=>t.mtimeMs-e.mtimeMs)}async function removeTemplateDirectory(e,t){if(await rm(e,{force:!0,recursive:!0}),t===null)return;let r=await loadMicrosandboxWithoutInstall();r!==null&&await removeSnapshotIfExists(r,t.snapshotName)}export{pruneMicrosandboxTemplates,resolveMicrosandboxSessionRootPath,resolveMicrosandboxTemplateRootPath,resolveMicrosandboxTemplatesDirectory};
@@ -1,4 +1,4 @@
1
- import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{join}from"node:path";import{existsSync}from"node:fs";import{mkdir,writeFile}from"node:fs/promises";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";async function writeCompiledArtifactsFiles(n){let a=join(n.outDir,`compiled-artifacts-bootstrap.mjs`),o=join(n.outDir,`compiled-artifacts-instrumentation.mjs`),s=resolveInstrumentationModule(n.compileResult.manifest.agentRoot);await mkdir(n.outDir,{recursive:!0}),await writeFile(a,await createCompiledArtifactsBootstrapSource({compileResult:n.compileResult,installModulePath:resolvePackageSourceFilePath(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:a,metadata:n.compileResult.metadata})),s!==void 0&&await writeFile(o,createInstrumentationPluginSource({agentName:n.compileResult.manifest.config.name,instrumentationPath:s,registerConfigPath:resolvePackageSourceFilePath(`src/harness/instrumentation-config.ts`)}));let c={bootstrapPath:a};return s!==void 0&&(c.instrumentationPluginPath=o,c.instrumentationSourcePath=s),c}const INSTRUMENTATION_EXTENSIONS=[`.ts`,`.mts`,`.js`,`.mjs`];function resolveInstrumentationModule(e){for(let r of INSTRUMENTATION_EXTENSIONS){let i=join(e,`instrumentation${r}`);if(existsSync(i))return i}}function stripCompiledModuleMapExports(e){return e.replace(/^export const moduleMap = /m,`const moduleMap = `).replace(/\nexport default moduleMap;\n?$/,`
1
+ import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{join}from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";async function writeCompiledArtifactsFiles(t){let i=join(t.outDir,`compiled-artifacts-bootstrap.mjs`),a=join(t.outDir,`compiled-artifacts-instrumentation.mjs`),o=resolveInstrumentationModule(t.compileResult.manifest.agentRoot);await mkdir(t.outDir,{recursive:!0}),await writeFile(i,await createCompiledArtifactsBootstrapSource({compileResult:t.compileResult,installModulePath:resolvePackageSourceFilePath(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:i,metadata:t.compileResult.metadata})),o!==void 0&&await writeFile(a,createInstrumentationPluginSource({agentName:t.compileResult.manifest.config.name,instrumentationPath:o,registerConfigPath:resolvePackageSourceFilePath(`src/harness/instrumentation-config.ts`)}));let s={bootstrapPath:i};return o!==void 0&&(s.instrumentationPluginPath=a,s.instrumentationSourcePath=o),s}const INSTRUMENTATION_EXTENSIONS=[`.ts`,`.mts`,`.js`,`.mjs`];function resolveInstrumentationModule(e){for(let n of INSTRUMENTATION_EXTENSIONS){let r=join(e,`instrumentation${n}`);if(existsSync(r))return r}}function stripCompiledModuleMapExports(e){return e.replace(/^export const moduleMap = /m,`const moduleMap = `).replace(/\nexport default moduleMap;\n?$/,`
2
2
  `)}async function createCompiledArtifactsBootstrapSource(e){let t=stripCompiledModuleMapExports(createCompiledModuleMapSource({importSpecifierStyle:`absolute`,manifest:e.compileResult.manifest,moduleMapPath:e.moduleMapPath})).trim();return[`// Generated by Eve. Do not edit by hand.`,`import { installBundledCompiledArtifacts } from ${stringifyEsmImportSpecifier(e.installModulePath)};`,``,t,``,`const metadata = ${JSON.stringify(e.metadata,null,2)};`,``,`const manifest = ${JSON.stringify(e.compileResult.manifest,null,2)};`,``,`export function installCompiledArtifactsBootstrap() {`,` installBundledCompiledArtifacts({`,` manifest,`,` metadata,`,` moduleMap,`,` });`,`}`,``,`installCompiledArtifactsBootstrap();`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installCompiledArtifactsPlugin() {`,` // Already installed on import above.`,`}`,``,`export async function __eveInstallCompiledArtifactsStep() {`,` "use step";`,` return null;`,`}`,``].join(`
3
3
  `)}function createInstrumentationPluginSource(e){return[`// Generated by Eve. Do not edit by hand.`,`import * as instrumentationModule from ${stringifyEsmImportSpecifier(e.instrumentationPath)};`,`import { registerInstrumentationConfig } from ${stringifyEsmImportSpecifier(e.registerConfigPath)};`,``,`if (instrumentationModule.default != null) {`,` registerInstrumentationConfig(instrumentationModule.default, { agentName: ${JSON.stringify(e.agentName)} });`,`}`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installInstrumentationPlugin() {}`,``].join(`
4
4
  `)}export{writeCompiledArtifactsFiles};
@@ -1 +1 @@
1
- import{dirname,join}from"node:path";import{spawn}from"node:child_process";import{existsSync}from"node:fs";const EVE_DEV_ENV_FLAG=`EVE_DEV`;function isEveDevEnvironment(){return process.env[EVE_DEV_ENV_FLAG]===`1`}function detectProjectPackageManager(n){let i=n;for(;;){if(existsSync(join(i,`pnpm-lock.yaml`))||existsSync(join(i,`pnpm-workspace.yaml`)))return`pnpm`;if(existsSync(join(i,`yarn.lock`)))return`yarn`;if(existsSync(join(i,`bun.lock`))||existsSync(join(i,`bun.lockb`)))return`bun`;if(existsSync(join(i,`package-lock.json`)))return`npm`;let n=dirname(i);if(n===i)return`npm`;i=n}}const INSTALL_ARGUMENTS={bun:[`add`,`--dev`],npm:[`install`,`--save-dev`],pnpm:[`add`,`-D`],yarn:[`add`,`-D`]};async function installPackageIntoProject(e){let t=detectProjectPackageManager(e.appRoot),r=[...INSTALL_ARGUMENTS[t],e.packageName];console.info(`[eve:dev] installing optional dependency "${e.packageName}" via \`${t} ${r.join(` `)}\`...`);let i=spawn(t,r,{cwd:e.appRoot,shell:shouldSpawnPackageManagerWithShell(),stdio:[`ignore`,`pipe`,`pipe`]}),a=[];i.stdout?.on(`data`,e=>a.push(e)),i.stderr?.on(`data`,e=>a.push(e));let o=await new Promise((e,t)=>{i.on(`error`,t),i.on(`close`,t=>e(t??1))});if(o!==0){let n=Buffer.concat(a).toString(`utf8`).trim();throw Error(`Failed to install "${e.packageName}" with ${t} (exit ${o}).`+(n.length>0?`\n${n.slice(-2e3)}`:``))}console.info(`[eve:dev] installed "${e.packageName}".`)}async function loadOptionalEnginePackage(e){try{return await e.importModule()}catch(t){if(!e.autoInstall||!isEveDevEnvironment())throw Error(e.missingMessage,{cause:t});try{await installPackageIntoProject({appRoot:e.appRoot,packageName:e.packageName})}catch(t){throw Error(`${e.missingMessage} Automatic installation failed: ${toMessage(t)}`,{cause:t})}return await e.importModule()}}function shouldSpawnPackageManagerWithShell(e=process.platform){return e===`win32`}function toMessage(e){return e instanceof Error?e.message:String(e)}export{EVE_DEV_ENV_FLAG,detectProjectPackageManager,installPackageIntoProject,isEveDevEnvironment,loadOptionalEnginePackage};
1
+ import{existsSync}from"node:fs";import{dirname,join}from"node:path";import{spawn}from"node:child_process";const EVE_DEV_ENV_FLAG=`EVE_DEV`;function isEveDevEnvironment(){return process.env[EVE_DEV_ENV_FLAG]===`1`}function detectProjectPackageManager(r){let i=r;for(;;){if(existsSync(join(i,`pnpm-lock.yaml`))||existsSync(join(i,`pnpm-workspace.yaml`)))return`pnpm`;if(existsSync(join(i,`yarn.lock`)))return`yarn`;if(existsSync(join(i,`bun.lock`))||existsSync(join(i,`bun.lockb`)))return`bun`;if(existsSync(join(i,`package-lock.json`)))return`npm`;let r=dirname(i);if(r===i)return`npm`;i=r}}const INSTALL_ARGUMENTS={bun:[`add`,`--dev`],npm:[`install`,`--save-dev`],pnpm:[`add`,`-D`],yarn:[`add`,`-D`]};async function installPackageIntoProject(e){let t=detectProjectPackageManager(e.appRoot),n=[...INSTALL_ARGUMENTS[t],e.packageName];console.info(`[eve:dev] installing optional dependency "${e.packageName}" via \`${t} ${n.join(` `)}\`...`);let i=spawn(t,n,{cwd:e.appRoot,shell:shouldSpawnPackageManagerWithShell(),stdio:[`ignore`,`pipe`,`pipe`]}),a=[];i.stdout?.on(`data`,e=>a.push(e)),i.stderr?.on(`data`,e=>a.push(e));let o=await new Promise((e,t)=>{i.on(`error`,t),i.on(`close`,t=>e(t??1))});if(o!==0){let n=Buffer.concat(a).toString(`utf8`).trim();throw Error(`Failed to install "${e.packageName}" with ${t} (exit ${o}).`+(n.length>0?`\n${n.slice(-2e3)}`:``))}console.info(`[eve:dev] installed "${e.packageName}".`)}async function loadOptionalEnginePackage(e){try{return await e.importModule()}catch(t){if(!e.autoInstall||!isEveDevEnvironment())throw Error(e.missingMessage,{cause:t});try{await installPackageIntoProject({appRoot:e.appRoot,packageName:e.packageName})}catch(t){throw Error(`${e.missingMessage} Automatic installation failed: ${toMessage(t)}`,{cause:t})}return await e.importModule()}}function shouldSpawnPackageManagerWithShell(e=process.platform){return e===`win32`}function toMessage(e){return e instanceof Error?e.message:String(e)}export{EVE_DEV_ENV_FLAG,detectProjectPackageManager,installPackageIntoProject,isEveDevEnvironment,loadOptionalEnginePackage};
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.9.1`,WORKFLOW_MODULE_ALIASES={"workflow/api":`src/compiled/@workflow/core/runtime.js`,"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`,"workflow/runtime":`src/compiled/@workflow/core/runtime.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let t=e;for(;;){if(existsSync(join(t,`package.json`))&&!isBuildOutputPackageRoot(t))return t;let r=dirname(t);if(r===t)throw Error(`Failed to resolve package root from "${e}".`);t=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
1
+ 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.9.2`,WORKFLOW_MODULE_ALIASES={"workflow/api":`src/compiled/@workflow/core/runtime.js`,"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`,"workflow/runtime":`src/compiled/@workflow/core/runtime.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let 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 resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
@@ -1 +1 @@
1
- import{resolveInstalledPackageInfo,resolvePackageRoot,resolvePackageSourceDirectoryPath}from"#internal/application/package.js";import{join,resolve}from"node:path";import{existsSync,readFileSync,readdirSync,rmSync}from"node:fs";import{createHash}from"node:crypto";import{workflowEntryReference}from"#execution/workflow-runtime.js";function resolveApplicationRoot(e=process.cwd()){return resolve(e)}function getWorkflowBuildCacheKey(e){return createHash(`sha256`).update(e).digest(`hex`).slice(0,12)}function isVercelBuildEnvironment(){return!!process.env.VERCEL}function resolveNitroBuildDirectory(e,t=`all`){let n=join(e,`.eve`,`nitro`);return t===`all`?n:join(n,t)}function resolveNitroSurfaceOutputDirectory(e,t){return join(e,`.eve`,`nitro-output`,t)}function resolveWorkflowBuildDirectory(e){let n=join(resolvePackageRoot(),`.eve`,`workflow-cache`);return pruneStaleWorkflowCacheSiblings(n),join(n,getWorkflowBuildCacheKey(e))}function pruneStaleWorkflowCacheSiblings(t){if(!existsSync(t))return;let n=resolveInstalledPackageInfo().version,r;try{r=readdirSync(t)}catch{return}for(let e of r){let r=join(t,e),i=join(r,`eve-cache.json`);if(existsSync(i))try{let e=JSON.parse(readFileSync(i,`utf8`));typeof e.eveVersion==`string`&&e.eveVersion!==n&&rmSync(r,{force:!0,recursive:!0})}catch{}}}function resolveSandboxCacheDirectory(e){return join(e,`.eve`,`sandbox-cache`)}function resolveOutputDirectory(e){return isVercelBuildEnvironment()?join(e,`.vercel`,`output`):join(e,`.output`)}function getApplicationInfo(e){return{appRoot:e,outputDir:resolveOutputDirectory(e),workflowId:workflowEntryReference.workflowId,workflowBuildDir:resolveWorkflowBuildDirectory(e),workflowSourceDir:resolvePackageSourceDirectoryPath(`src/execution`)}}export{getApplicationInfo,resolveApplicationRoot,resolveNitroBuildDirectory,resolveNitroSurfaceOutputDirectory,resolveOutputDirectory,resolveSandboxCacheDirectory,resolveWorkflowBuildDirectory};
1
+ import{resolveInstalledPackageInfo,resolvePackageRoot,resolvePackageSourceDirectoryPath}from"#internal/application/package.js";import{existsSync,readFileSync,readdirSync,rmSync}from"node:fs";import{join,resolve}from"node:path";import{createHash}from"node:crypto";import{workflowEntryReference}from"#execution/workflow-runtime.js";function resolveApplicationRoot(e=process.cwd()){return resolve(e)}function getWorkflowBuildCacheKey(e){return createHash(`sha256`).update(e).digest(`hex`).slice(0,12)}function isVercelBuildEnvironment(){return!!process.env.VERCEL}function resolveNitroBuildDirectory(e,t=`all`){let n=join(e,`.eve`,`nitro`);return t===`all`?n:join(n,t)}function resolveNitroSurfaceOutputDirectory(e,t){return join(e,`.eve`,`nitro-output`,t)}function resolveWorkflowBuildDirectory(e){let n=join(resolvePackageRoot(),`.eve`,`workflow-cache`);return pruneStaleWorkflowCacheSiblings(n),join(n,getWorkflowBuildCacheKey(e))}function pruneStaleWorkflowCacheSiblings(t){if(!existsSync(t))return;let n=resolveInstalledPackageInfo().version,i;try{i=readdirSync(t)}catch{return}for(let e of i){let r=join(t,e),i=join(r,`eve-cache.json`);if(existsSync(i))try{let e=JSON.parse(readFileSync(i,`utf8`));typeof e.eveVersion==`string`&&e.eveVersion!==n&&rmSync(r,{force:!0,recursive:!0})}catch{}}}function resolveSandboxCacheDirectory(e){return join(e,`.eve`,`sandbox-cache`)}function resolveOutputDirectory(e){return isVercelBuildEnvironment()?join(e,`.vercel`,`output`):join(e,`.output`)}function getApplicationInfo(e){return{appRoot:e,outputDir:resolveOutputDirectory(e),workflowId:workflowEntryReference.workflowId,workflowBuildDir:resolveWorkflowBuildDirectory(e),workflowSourceDir:resolvePackageSourceDirectoryPath(`src/execution`)}}export{getApplicationInfo,resolveApplicationRoot,resolveNitroBuildDirectory,resolveNitroSurfaceOutputDirectory,resolveOutputDirectory,resolveSandboxCacheDirectory,resolveWorkflowBuildDirectory};