eve 0.12.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/src/chunks/{use-eve-agent-D9ZhQhyV.js → use-eve-agent-DEm_Jg4k.js} +18 -4
- package/dist/src/chunks/{use-eve-agent-DFI0POM9.js → use-eve-agent-DsXOQMFZ.js} +18 -4
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/dev/tui/command-typeahead.d.ts +1 -1
- package/dist/src/cli/dev/tui/command-typeahead.js +1 -1
- package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +6 -2
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.d.ts +6 -2
- package/dist/src/cli/dev/tui/setup-commands.js +2 -2
- package/dist/src/cli/dev/tui/setup-issues.d.ts +16 -2
- package/dist/src/cli/dev/tui/setup-issues.js +1 -1
- package/dist/src/cli/dev/tui/setup-panel.js +2 -2
- package/dist/src/cli/dev/tui/target.d.ts +21 -0
- package/dist/src/cli/dev/tui/target.js +1 -0
- package/dist/src/cli/dev/tui/terminal-renderer.js +3 -3
- package/dist/src/cli/dev/tui/test/fake-setup-flow-renderer.d.ts +2 -0
- package/dist/src/cli/dev/tui/test/fake-setup-flow-renderer.js +1 -0
- package/dist/src/cli/dev/tui/theme.d.ts +3 -1
- package/dist/src/cli/dev/tui/theme.js +1 -1
- package/dist/src/cli/dev/tui/tui.d.ts +4 -14
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/cli/dev/url.js +1 -1
- package/dist/src/cli/run.d.ts +0 -12
- package/dist/src/cli/run.js +2 -2
- package/dist/src/client/client.js +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/open-stream.d.ts +2 -0
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session.d.ts +2 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/types.d.ts +9 -0
- package/dist/src/evals/cli/eval-client.d.ts +12 -16
- package/dist/src/evals/cli/eval-client.js +1 -1
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/harness/compaction.d.ts +2 -3
- package/dist/src/harness/compaction.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
- package/dist/src/internal/nitro/host/start-development-server.js +2 -2
- package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
- package/dist/src/services/dev-client/client-options.d.ts +9 -4
- package/dist/src/services/dev-client/client-options.js +1 -1
- package/dist/src/services/dev-client/credential-gate.d.ts +19 -0
- package/dist/src/services/dev-client/credential-gate.js +1 -0
- package/dist/src/services/dev-client/local-host.d.ts +4 -0
- package/dist/src/services/dev-client/local-host.js +1 -0
- package/dist/src/services/dev-client/request-headers.d.ts +38 -56
- package/dist/src/services/dev-client/request-headers.js +1 -1
- package/dist/src/services/dev-client/runtime-artifacts.js +1 -1
- package/dist/src/services/dev-client/vercel-auth-error.d.ts +2 -0
- package/dist/src/services/dev-client/vercel-auth-error.js +2 -2
- package/dist/src/services/dev-client.js +1 -1
- package/dist/src/setup/cli/option-row.d.ts +11 -5
- package/dist/src/setup/cli/option-row.js +1 -1
- package/dist/src/setup/cli/prompt-ui.d.ts +6 -6
- package/dist/src/setup/cli/prompt-ui.js +2 -2
- package/dist/src/setup/flows/model.d.ts +2 -0
- package/dist/src/setup/flows/model.js +1 -1
- package/dist/src/setup/project-resolution.d.ts +13 -0
- package/dist/src/setup/project-resolution.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/index.d.ts +1 -1
- package/dist/src/setup/scaffold/index.js +1 -1
- package/dist/src/setup/scaffold/update/channels.d.ts +8 -1
- package/dist/src/setup/scaffold/update/channels.js +2 -2
- package/dist/src/setup/vercel-deployment.d.ts +53 -0
- package/dist/src/setup/vercel-deployment.js +1 -0
- package/dist/src/setup/vercel-project.js +1 -1
- package/dist/src/setup/verified-remote-client.d.ts +23 -0
- package/dist/src/setup/verified-remote-client.js +1 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/evals/targets.mdx +7 -5
- package/docs/guides/client/overview.mdx +3 -0
- package/docs/guides/dev-tui.md +5 -5
- package/package.json +1 -1
- package/dist/src/harness/tool-result-pruning.d.ts +0 -8
- package/dist/src/harness/tool-result-pruning.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{clipVisible,renderInputText,stripAnsi,stripTerminalControls}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";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=new StringDecoder(`utf8`);#G;#K;#q;#J=!1;#Y=!1;#X;#Z;#Q;#$;#ee;#te;#ne;#re=``;#ie=``;#ae;#oe;#se=0;#ce;#le;#ue;#de;#fe;setupFlow={begin:e=>this.#ge(e),end:e=>this.#_e(e?.preserveDiagnostics??!0),readSelect:e=>this.#ve(e),readEditableSelect:e=>this.#be(e),readText:e=>this.#xe(e),readAcknowledge:e=>this.#Se(e),readChoice:e=>this.#ye(e),setStatus:e=>this.#Ae(e),renderLine:(e,t)=>this.#je(e,t),renderOutput:e=>this.#Me(e),waitForInterrupt:()=>this.#De()};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.#Q=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.#Ne();let t=this.#pt().join(`
|
|
1
|
+
import{clipVisible,renderInputText,stripAnsi,stripTerminalControls}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";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=new StringDecoder(`utf8`);#G;#K;#q;#J=!1;#Y=!1;#X;#Z;#Q;#$;#ee;#te;#ne;#re=``;#ie=``;#ae;#oe;#se=0;#ce;#le;#ue;#de;#fe;setupFlow={begin:e=>this.#ge(e),end:e=>this.#_e(e?.preserveDiagnostics??!0),readSelect:e=>this.#ve(e),readEditableSelect:e=>this.#be(e),readText:e=>this.#xe(e),readAcknowledge:e=>this.#Se(e),readChoice:e=>this.#ye(e),setStatus:e=>this.#Ae(e),renderLine:(e,t)=>this.#je(e,t),renderOutput:e=>this.#Me(e),waitForInterrupt:()=>this.#De()};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.#Q=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.#Ne();let t=this.#pt().join(`
|
|
2
2
|
`);if(this.#b){t!==this.#x&&(this.#x=t,this.#qe({kind:`agent-header`,body:t,live:!1})),this.#ct();return}this.#b=!0,this.#x=t,this.#n.flush(this.#pt(),[])}async readPrompt(e){this.#Ne(e),this.#k=!0,this.#j=!1,this.#M=``;let t=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#O.begin(t.text),this.#pe(t),this.#A=typeaheadFor(PROMPT_COMMANDS,t.text),this.#He(),this.#ct(),await new Promise((e,n)=>{let apply=e=>{t=e,this.#We(),this.#pe(t),this.#A=typeaheadFor(PROMPT_COMMANDS,e.text,this.#A),this.#ct()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#A=void 0,this.#Ue(),this.#Pe(),n(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=n=>{let i=applyLineEditorKey(t,n,{multiline:!0});if(i!==void 0){apply(i);return}switch(n.type){case`up`:{let e=suggestions();if(e!==void 0){this.#A=moveTypeaheadSelection(e,-1),this.#ct();break}let n=movePromptLine(t,`up`);n===void 0?recall(this.#O.previous(t.text)):apply(n);break}case`down`:{let e=suggestions();if(e!==void 0){this.#A=moveTypeaheadSelection(e,1),this.#ct();break}let n=movePromptLine(t,`down`);n===void 0?recall(this.#O.next()):apply(n);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#A=dismissTypeahead(e),this.#ct());break}case`enter`:{let n=highlighted(),i=n!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(n).trimEnd():t.text;this.#A=void 0,this.#O.add(i),this.#k=!1,this.#Ue(),this.#M=STATUS.processing,isPromptControlCommand(i)?this.#qe({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#Je(i),this.#ce=i),this.#pe(EMPTY_LINE),this.#ct(),this.#Ie(),e(i);break}case`ctrl-d`:t.text.length===0?interrupt():apply(deleteForward(t));break;case`ctrl-l`:this.#dt();break;case`ctrl-r`:this.#ct();break;case`ctrl-c`:t.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#Fe()})}#pe(e){this.#E=e.text,this.#D=e.cursor}async renderStream(e,t){this.#Ne(t),this.#m.clear(),this.#k=!1,this.#j=!0,this.#M=STATUS.processing,this.#Ye(t?.submittedPrompt),this.#F=!1,this.#X=void 0,this.#Z=void 0,this.#$=void 0,this.#ee=void 0,this.#te=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#Ge(),this.#ct();let r=new Promise(e=>{this.#q=e});this.#H=e=>this.#Ve(e),this.#Fe();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.#tt(t,n,i)}}catch(e){this.#Xe(`Error`,toErrorMessage(e))}finally{this.#q=void 0,this.#F&&e.abort?.(),this.#Ie(),this.#Ke(),this.#j=!1,this.#M=completedTurnStatus(this.#F,t?.continueSession===!0),this.#et(),this.#ct(),t?.continueSession||this.#Pe()}}async readToolApproval(e,t){return this.#Ne(t),this.#k=!1,this.#j=!1,this.#M=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#F=!1,this.#ct(),await new Promise((t,n)=>{this.#H=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#M=STATUS.processing,this.#Ie(),this.#ct(),t({approved:!0})):n===`n`&&(this.#M=STATUS.processing,this.#me(e.toolCallId),this.#Ie(),this.#ct(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#ct();break;case`ctrl-c`:this.#F=!0,this.#Pe(),n(interruptedError());break;default:break}},this.#Fe()})}async readInputQuestion(e,t){this.#Ne(t),this.#k=!1,this.#j=!1,this.#F=!1;let n=e.options??[],i=n.length>0,a=(e.allowFreeform===!0||!i)&&i,o=n.length+ +!!a,s=questionSectionId(e.requestId),c=i?`select`:`text`,l=0,u=EMPTY_LINE,isOnFreeformRow=()=>a&&l===n.length,renderSection=()=>{this.#Qe({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.#pe(u),this.#M=``;this.#ct()};renderSection(),c===`text`&&this.#He(),repaintStatus();let finalize=t=>{this.#Qe({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.#Ue(),this.#Ie(),this.#ct();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n};return await new Promise((t,r)=>{this.#H=a=>{if(a.type===`ctrl-c`){if(c===`text`&&u.text.length>0){u=EMPTY_LINE,this.#We(),repaintStatus();return}this.#F=!0,this.#Ue(),this.#Pe(),r(interruptedError());return}if(a.type===`ctrl-r`){this.#ct();return}if(c===`select`){switch(a.type){case`up`:o>0&&(l=(l-1+o)%o,renderSection(),repaintStatus());break;case`down`:o>0&&(l=(l+1)%o,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){c=`text`,u=EMPTY_LINE,this.#He(),repaintStatus();break}let e=n[l];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}let s=applyLineEditorKey(u,a,{multiline:!0});if(s!==void 0){u=s,this.#We(),repaintStatus();return}switch(a.type){case`up`:case`down`:{let e=movePromptLine(u,a.type);e!==void 0&&(u=e,this.#We(),repaintStatus());break}case`enter`:{let n=resolveQuestionText(u.text,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(i){if(u.text.length>0){u=EMPTY_LINE,this.#We(),repaintStatus();break}c=`select`,u=EMPTY_LINE,this.#k=!1,this.#Ue(),repaintStatus();break}u=EMPTY_LINE,this.#We(),repaintStatus();break;default:break}},this.#Fe()})}upsertSubagentStep(e){if(this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#Ze(e.callId,e.subagentName),this.#o===`collapsed`){this.#ct();return}this.#Qe({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:n,live:!e.finalized}),this.#ct()}}upsertSubagentTool(e){if(this.#o===`hidden`)return;if(this.#Ze(e.callId,e.subagentName),this.#o===`collapsed`){this.#ct();return}let t=subagentToolStatus(e.status),n={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,depth:1,title:stripTerminalControls(e.toolName),subtitle:summarizeToolArgs(e.input),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolInput:e.input};e.output===void 0?e.errorText!==void 0&&(n.result=stripTerminalControls(e.errorText)):(n.result=summarizeToolResult(e.output),n.toolOutput=e.output),this.#Qe(n),this.#ct()}markChildToolCallId(e){this.#g.add(e);let t=this.#_.get(e);t!==void 0&&(this.#$e(t),this.#_.delete(e),this.#ct())}#me(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.#Qe({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e),preformatted:!0,live:!t}),this.#ct()}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.#ct()):n&&(this.#M=STATUS.processing,this.#ct())}setVercelStatus(e){this.#T=e,this.#ct()}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.#ce=void 0,this.#oe=void 0,this.#w=0,this.#X=void 0,this.#Z=void 0,this.#$=void 0,this.#ee=void 0,this.#te=void 0,this.#P&&(this.#n.clearAll(),this.#ct())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ne(),this.#qe({kind:`notice`,body:t,live:!1}),this.#ct())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#Ne(),this.#qe({kind:`sandbox`,body:t,live:!1}),this.#ct())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#he();return}this.#Ne(),this.#ue=t,this.#ct()}clearSetupWarning(){this.#he()}#he(){this.#ue!==void 0&&(this.#ue=void 0,this.#ct())}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ne(),this.#qe({kind:`result`,body:t,live:!1}),this.#ct())}#ge(e){this.#Ne(),this.#k=!1,this.#j=!1,this.#M=``,this.#le={title:stripTerminalControls(e),lines:[],outputBuffer:[]},this.#Ge(),this.#ct()}#_e(e){this.#de=void 0,this.#ke();let t=this.#le;if(t!==void 0){if(this.#le=void 0,this.#Ke(),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.#qe({kind:`flow`,title:`info`,body:e.join(`
|
|
3
3
|
`),live:!1}),this.#qe({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#ct()}}async#ve(e){let t=this.#Ce(),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.#ct(),await this.#Ee((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.#ct();return;case`update`:i=s.select,a=void 0,this.#ct();return;case`submit`:r(s.values);return;case`error`:a=s.message,this.#ct();return;case`ignore`:return}}).promise}#ye(e){this.#Ne();let t=this.#we();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#ct();let r=this.#Ee((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.#ct();return;case`repaint`:this.#ct();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#be(e){let t=this.#Ce(),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.#He()):(i=lineOf(``),this.#Ue())};return syncEditableRow(),this.#ct(),await this.#Ee((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#We(),this.#ct()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#ct()},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.#ct();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.#ct();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ue()).promise}async#xe(e){let t=this.#Ce(),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.#He(),this.#ct(),await this.#Ee((t,i)=>{let apply=e=>{n=e,r=void 0,this.#We(),this.#ct()},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.#ct();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#ct();return}i(t);return}default:return}},()=>this.#Ue()).promise}async#Se(e){let t=this.#Ce();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#ct(),await this.#Ee((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#ct();return;default:return}}).promise}#Ce(){return this.#Ne(),this.#k=!1,this.#j=!1,this.#M=``,this.#we()}#we(){return this.#le===void 0&&(this.#le={title:``,lines:[],outputBuffer:[]}),this.#le}#Te(){this.#le!==void 0&&(this.#le.question=void 0,this.#le.hideLinesWhileQuestion=!1),this.#H=void 0,this.#Ie(),this.#Oe(),this.#ct()}#Ee(e,t){let n=!1,r,i=new Promise(e=>{r=e}),settle=e=>{n||(n=!0,t?.(),this.#Te(),r(e))};return this.#H=t=>e(t,settle),this.#Fe(),{promise:i,settle}}#De(){let e,t=new Promise(t=>{e=t});return this.#de=e,this.#Oe(),{promise:t,dispose:()=>{this.#de===e&&(this.#de=void 0,this.#ke())}}}#Oe(){if(this.#de===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#de;this.#de=void 0,this.#ke(),e?.();return}e.type===`ctrl-r`&&this.#ct()};this.#fe=consumer,this.#H=consumer,this.#Fe()}#ke(){this.#fe!==void 0&&(this.#H===this.#fe&&this.#Ie(),this.#fe=void 0)}#Ae(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#le!==void 0){this.#le.status=t,t===void 0&&(this.#le.preview=void 0),this.#ct();return}if(t===void 0){this.#j=!1,this.#M=``,this.#Ke(),this.#ct();return}this.#Ne(),this.#j=!0,this.#M=t,this.#Ge(),this.#ct()}#je(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let i=this.#le;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:n,tone:t}),this.#ct();return}this.#Ne(),this.#qe({kind:`flow`,title:t,body:n,live:!1}),this.#ct()}#Me(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#le;if(n===void 0){this.#je(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#ct()}shutdown(){this.#Pe()}#Ne(e){this.#N=e?.title??this.#N,this.#Q=e?.contextSize??this.#l,!this.#P&&(this.#P=!0,this.#n.reset(),this.#n.hideCursor(),this.#xt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#K=()=>this.#ct(),this.#t.on(`resize`,this.#K))}#Pe(){this.#Ie(),this.#Ue(),this.#Ke(),this.#B!==void 0&&(clearTimeout(this.#B),this.#B=void 0),this.#V=!1,this.#P&&=(this.#kt(),this.#ct(),this.#n.clear(),this.#n.showCursor(),this.#St(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#K&&=(this.#t.off(`resize`,this.#K),void 0),!1)}#Fe(){this.#e.off(`data`,this.#Le),this.#e.on(`data`,this.#Le)}#Ie(){this.#e.off(`data`,this.#Le),this.#Be(),this.#U=``,this.#W=new StringDecoder(`utf8`),this.#H=void 0}#Le=e=>{this.#Be(),this.#U+=this.#W.write(e),this.#ze(),this.#Re()};#Re(){if(this.#U===`\x1B`){this.#G=setTimeout(()=>{this.#U===`\x1B`&&(this.#U=``,this.#H?.({type:`escape`}))},30),this.#G.unref?.();return}if(isIncompletePaste(this.#U)){let e=this.#U;this.#G=setTimeout(()=>{if(this.#U!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#U=``,t.length>0&&this.#H?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#G.unref?.()}}#ze(){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)}}#Be(){this.#G&&=(clearTimeout(this.#G),void 0)}#Ve(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#ct();break;case`ctrl-c`:this.#F||(this.#F=!0,this.#M=`Interrupted`,this.#q?.(),this.#ct());break;default:break}}#He(){this.#Ue(),this.#We(),this.#R=setInterval(()=>{this.#I=!this.#I,this.#ct()},500),this.#R.unref?.()}#Ue(){this.#R&&=(clearInterval(this.#R),void 0),this.#I=!0}#We(){this.#I=!0}#Ge(){this.#Ke(),this.#z=setInterval(()=>{this.#L+=1,this.#ct()},90),this.#z.unref?.()}#Ke(){this.#z&&=(clearInterval(this.#z),void 0)}#qe(e){e.id!==this.#oe?.id&&this.#kt(),this.#f.push(e),e.id&&this.#p.set(e.id,e)}#Je(e){this.#qe({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#ct()}#Ye(e){if(e!=null){if(this.#ce===e){this.#ce=void 0;return}this.#qe({kind:`user`,body:stripTerminalControls(e),live:!1})}}#Xe(e,t,n){let i={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};n!==void 0&&(i.detail=stripTerminalControls(n)),this.#qe(i),this.#ct()}#Ze(e,t){this.#v.has(e)||(this.#v.add(e),this.#qe({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#Qe(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.#qe(e)}#$e(e){this.#f=this.#f.filter(t=>t.id!==e),this.#p.delete(e)}#et(){for(let e of this.#f)e.status===`approval`||e.status===`running`||(e.live=!1)}#tt(e,t,n){switch(e.type){case`step-start`:this.#nt(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#st(e.usage),this.#ct();break;case`assistant-delta`:{this.#nt(STATUS.streaming);let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#rt(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,i=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;n.text.set(e.id,i),this.#rt(e.id,i,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;this.#nt(STATUS.streaming);let i=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);n.reasoning.set(e.id,i),this.#it(e.id,i,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#it(e.id,r,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#nt(STATUS.executingTools),this.#at({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;this.#at({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#ot(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#nt(STATUS.toolResults),this.#at({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{if(t.tools===`hidden`)break;let r=this.#ot(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#nt(STATUS.toolResults),this.#at({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#Xe(`Error`,e.errorText,e.detail);break;case`finish`:this.#st(e.usage),this.#ct();break}}#nt(e){let t=this.#w>0?STATUS.connectionAuth:e;this.#M!==t&&(this.#M=t,this.#ct())}#rt(e,t,n){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Qe({id:e,kind:`assistant`,body:i,live:n}),this.#ct())}#it(e,t,n,i){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#Qe({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(i.reasoning,n),live:n}),this.#ct())}#at(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.#Qe(renderNativeToolBlock(e,r,t.tools===`full`)),this.#ct()}#ot(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`}}#st(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#X=(t??0)+(n??0)),this.#Z=t??this.#Z,this.#$=n??this.#$,this.#$!=null&&this.#te!==void 0){let e=(Date.now()-this.#te)/1e3;e>0&&(this.#ee=this.#$/e)}}#ct(){if(this.#P){if(this.#J){this.#Y=!0;return}this.#J=!0;try{do this.#Y=!1,this.#lt();while(this.#Y)}finally{this.#J=!1}}}#lt(){if(!this.#P)return;let e=this.#yt(),t=this.#gt(e),n=Math.max(1,this.#bt()-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.#jt(t))continue;let n=this.#mt(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.#jt(t))continue;let n=this.#mt(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)}#ut(){if(!this.#P)return;let e=this.#yt(),t=this.#gt(e),n=Math.max(1,this.#bt()-t.length),r=this.#C,i=[];for(let t of this.#f){if(this.#jt(t))continue;let n=this.#mt(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.#pt(),...this.#S],a)}logDisplayMode(){return this.#d}setLogDisplayMode(e){e!==this.#d&&(this.#d=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#ft(),this.#P&&this.#ut())}flushDelayedDevBuildErrors(){let e=this.#ae;e!==void 0&&(this.#ae=void 0,this.#qe({kind:`log`,title:`stderr`,body:e,live:!1}),this.#ct())}#dt(){this.#V=!0,this.#B!==void 0&&clearTimeout(this.#B),this.#B=setTimeout(()=>{this.#V=!1,this.#B=void 0,this.#ct()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#d)),this.#ct()}#ft(){let e=this.#yt();this.#S.length=0;let t;for(let n of this.#h){if(this.#jt(n))continue;let r=this.#mt(n,e,t);t=previousBlockOf(n),this.#S.push(...r)}this.#C=t}#pt(){let e=this.#y;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#yt()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#mt(e,t,n){let r={spinner:this.#ht()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#ht(){return this.#r.spinner[this.#L%this.#r.spinner.length]??``}#gt(e){let t=this.#r.colors,n=[``],r=this.#le;if(r!==void 0){let t=this.#ht(),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.#ue!==void 0&&n.push(...renderAttentionRows(this.#ue,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=isPromptControlCommand(this.#E),a=r?t.dim(` ${r}`):``,o=[];this.#_t(o,e);let s=Math.max(1,this.#bt()-1-n.length-1-o.length);return n.push(...promptInputRows({text:this.#E,cursor:this.#D,width:e,theme:this.#r,caretVisible:this.#I,isCommand:i,ghost:a,maxRows:s})),n.push(...o),n}let i=this.#j?t.yellow(this.#ht()):t.dim(this.#r.glyph.dot),a=this.#M.length>0?this.#M:`Ready`,o=this.#j?t.dim(a):a,s=this.#vt(),l=s?`${i} ${o} ${t.dim(this.#r.glyph.dot)} ${s}`:`${i} ${o}`;return n.push(clip(l,e)),this.#_t(n,e),n}#_t(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.#Z??0,o=this.#$??0;if(a>0||o>0){let e={inputTokens:a,outputTokens:o};this.#Q!==void 0&&(e.contextSize=this.#Q),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)}#vt(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#X,outputTokens:this.#$,tokensPerSecond:this.#ee},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#yt(){return Math.max(20,this.#t.columns||80)}#bt(){return Math.max(8,this.#t.rows||24)}#xt(){if(this.#ne!==void 0||!this.#u)return;this.#re=``,this.#ie=``;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.#Ct(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ne=()=>{e(),t()}}#St(){let e=this.#ne;e!==void 0&&(this.#ne=void 0,e(),this.#re.length>0&&(this.#At(`stdout`)&&process.stdout.write(`${this.#re}\n`),this.#re=``),this.#ie.length>0&&(this.#At(`stderr`)&&process.stderr.write(`${this.#ie}\n`),this.#ie=``))}#Ct(e,t){let r=(e===`stdout`?this.#re:this.#ie)+t,i=r.lastIndexOf(`
|
|
4
4
|
`),a=i===-1?r:r.slice(i+1);if(e===`stdout`?this.#re=a:this.#ie=a,i===-1)return;let o=stripAnsi(r.slice(0,i)).replace(/\s+$/u,``);o.trim().length!==0&&(e===`stdout`?this.#wt(o):this.#Tt(o),this.#ct())}#wt(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
|
|
@@ -6,6 +6,6 @@ import{clipVisible,renderInputText,stripAnsi,stripTerminalControls}from"./termin
|
|
|
6
6
|
`)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#qe({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#Dt(r,n.trimEnd())}flushPending()}#Tt(e){let t=e.split(`
|
|
7
7
|
`),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){this.#qe({kind:`log`,title:`stderr`,body:e,live:!1});return}let r=t.slice(0,n).join(`
|
|
8
8
|
`);r.trim().length>0&&this.#qe({kind:`log`,title:`stderr`,body:r,live:!1});let i=t.slice(n).join(`
|
|
9
|
-
`);this.#Et(i)}#Et(e){if(this.#d===`all`){if(e.trim().length===0)return;this.#qe({kind:`log`,title:`stderr`,body:e,live:!1});return}this.#ae=e}#Dt(e,t){let n=this.#Ot();if(e.kind===`failed`){this.#Et(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.#se}`;this.#se+=1,this.#oe={id:r,summary:t},this.#qe({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.#ae=void 0);return}e.kind===`rebuilt`&&(this.#ae=void 0),this.#qe({kind:`log`,title:`stdout`,body:t,live:!1})}#Ot(){let e=this.#oe;if(e===void 0)return;let t=this.#p.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#kt(){let e=this.#oe;if(e===void 0)return;this.#oe=void 0;let t=this.#p.get(e.id);t!==void 0&&(t.live=!1)}#At(e){switch(this.#d){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#jt(e){return e.kind===`sandbox`?!this.#At(`sandbox`):e.kind===`log`?!this.#At(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 clipVisible(t,n)}function promptInputRows({text:e,cursor:n,width:r,theme:i,caretVisible:a,isCommand:o,ghost:s,maxRows:c}){let l=i.colors,style=e=>{let n=renderInputText(e);return o&&n.length>0?l.blue(n):n},u=layoutPromptInput({text:e,cursor:n}),d=Math.min(Math.max(1,c),u.rows.length),f=Math.max(0,Math.min(u.caretRow-d+1,u.rows.length-d)),p=l.cyan(i.glyph.prompt),m=l.dim(i.glyph.ellipsis),h=Math.max(1,r-
|
|
10
|
-
`)}function formatQuestionContent(e,t,n){let i=n.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}`)}`:``,
|
|
9
|
+
`);this.#Et(i)}#Et(e){if(this.#d===`all`){if(e.trim().length===0)return;this.#qe({kind:`log`,title:`stderr`,body:e,live:!1});return}this.#ae=e}#Dt(e,t){let n=this.#Ot();if(e.kind===`failed`){this.#Et(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.#se}`;this.#se+=1,this.#oe={id:r,summary:t},this.#qe({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.#ae=void 0);return}e.kind===`rebuilt`&&(this.#ae=void 0),this.#qe({kind:`log`,title:`stdout`,body:t,live:!1})}#Ot(){let e=this.#oe;if(e===void 0)return;let t=this.#p.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#kt(){let e=this.#oe;if(e===void 0)return;this.#oe=void 0;let t=this.#p.get(e.id);t!==void 0&&(t.live=!1)}#At(e){switch(this.#d){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#jt(e){return e.kind===`sandbox`?!this.#At(`sandbox`):e.kind===`log`?!this.#At(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 clipVisible(t,n)}function promptInputRows({text:e,cursor:n,width:r,theme:i,caretVisible:a,isCommand:o,ghost:s,maxRows:c}){let l=i.colors,style=e=>{let n=renderInputText(e);return o&&n.length>0?l.blue(n):n},u=layoutPromptInput({text:e,cursor:n}),d=Math.min(Math.max(1,c),u.rows.length),f=Math.max(0,Math.min(u.caretRow-d+1,u.rows.length-d)),p=l.cyan(i.glyph.prompt),m=l.dim(i.glyph.ellipsis),h=Math.max(1,r-4),g=[];for(let e=f;e<f+d;e+=1){let n=u.rows[e],o=e===0?p:` `;(e===f&&f>0||e===f+d-1&&f+d<u.rows.length)&&(o=m);let c;if(e===u.caretRow){let{before:e,under:r,after:o}=visibleLine({text:n.text,cursor:u.caretOffset},h,i.glyph.ellipsis),d=r||` `,f=a?l.inverse(renderInputText(d)):style(d);c=`${style(e)}${f}${style(o)}`,s.length>0&&u.rows.length===1&&(c+=s)}else c=style(n.text);g.push(clip(` ${o} ${c}`,r))}return g.push(``),g}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,n){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:n,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=[],n=stripTerminalControls(e.description);n.length>0&&t.push(n);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 n=stripTerminalControls(e.reason);n.length>0&&t.push(`Reason: ${n}`)}return t.join(`
|
|
10
|
+
`)}function formatQuestionContent(e,t,n){let i=n.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=t===e,u=c.length>0?`${l?` `:` `}${i.dim(`— ${c}`)}`:``,d=renderCursorRow(l?`${n.glyph.selectedPointer} ${o}`:` ${o}`,l,i);a.push(`${d}${u}`)}if(e.allowFreeform===!0){let e=t===o.length,r=`Type your own answer`,s=e?`${n.glyph.selectedPointer} ${r}`:` ${i.dim(r)}`;a.push(renderCursorRow(s,e,i))}}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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function createFakeSetupFlowRenderer(e={}){return{begin:()=>{},end:()=>{},readSelect:async()=>void 0,readEditableSelect:async()=>void 0,readText:async()=>void 0,readAcknowledge:async()=>{},readChoice:()=>({choice:Promise.resolve(void 0),close:()=>{}}),setStatus:()=>{},renderLine:()=>{},renderOutput:()=>{},waitForInterrupt:()=>({promise:new Promise(()=>{}),dispose:()=>{}}),...e}}export{createFakeSetupFlowRenderer};
|
|
@@ -58,8 +58,10 @@ export interface ThemeGlyphs {
|
|
|
58
58
|
connection: string;
|
|
59
59
|
/** `→` — separates a tool call from its summarized result. */
|
|
60
60
|
arrow: string;
|
|
61
|
-
/** `▷` —
|
|
61
|
+
/** `▷` — cursor marker for an inert option. */
|
|
62
62
|
pointer: string;
|
|
63
|
+
/** `▶` — cursor marker for an actionable option. */
|
|
64
|
+
selectedPointer: string;
|
|
63
65
|
/** `◦` — available, unselected option marker. */
|
|
64
66
|
option: string;
|
|
65
67
|
/** `❯` — the input prompt mark. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function ansi(e,t,n){if(!n)return e=>e;let r=`[${e}m`,i=`[${t}m`;return e=>`${r}${e}${i}`}function ansi256(e,t){if(!t)return e=>e;let n=`[38;5;${e}m`;return e=>`${n}${e}[39m`}const UNICODE_GLYPHS={brand:`▲`,user:`▌`,reasoning:`○`,success:`✓`,error:`⨯`,warning:`⚠`,subagent:`◆`,rule:`│`,question:`?`,connection:`●`,arrow:`→`,pointer:`▷`,option:`◦`,prompt:`❯`,elbow:`⎿`,hrule:`▔`,caret:`▏`,dot:`·`,ellipsis:`…`,arrowUp:`↑`,arrowDown:`↓`},ASCII_GLYPHS={brand:`>`,user:`|`,reasoning:`o`,success:`+`,error:`x`,warning:`!`,subagent:`*`,rule:`|`,question:`?`,connection:`*`,arrow:`->`,pointer:`>`,option:`.`,prompt:`>`,elbow:"`-",hrule:`=`,caret:`_`,dot:`-`,ellipsis:`...`,arrowUp:`^`,arrowDown:`v`},UNICODE_SPINNER=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],ASCII_SPINNER=[`-`,`\\`,`|`,`/`];function createTheme(i={}){let a=i.color??!0,o=i.unicode??!0;return{color:a,unicode:o,colors:{reset:ansi(0,0,a),bold:ansi(1,22,a),dim:ansi(2,22,a),inverse:ansi(7,27,a),italic:ansi(3,23,a),white:ansi(97,39,a),gray:ansi(90,39,a),cyan:ansi(36,39,a),green:ansi(32,39,a),red:ansi(31,39,a),yellow:ansi(33,39,a),magenta:ansi(35,39,a),blue:ansi(34,39,a),orange:ansi256(208,a)},glyph:o?UNICODE_GLYPHS:ASCII_GLYPHS,spinner:o?UNICODE_SPINNER:ASCII_SPINNER}}function detectUnicode(e=process.env){let t=e.EVE_TUI_UNICODE;return t===`0`||t===`false`?!1:t===`1`||t===`true`?!0:e.TERM===`dumb`?!1:process.platform===`win32`?!!(e.WT_SESSION||e.TERM_PROGRAM===`vscode`):!0}export{createTheme,detectUnicode};
|
|
1
|
+
function ansi(e,t,n){if(!n)return e=>e;let r=`[${e}m`,i=`[${t}m`;return e=>`${r}${e}${i}`}function ansi256(e,t){if(!t)return e=>e;let n=`[38;5;${e}m`;return e=>`${n}${e}[39m`}const UNICODE_GLYPHS={brand:`▲`,user:`▌`,reasoning:`○`,success:`✓`,error:`⨯`,warning:`⚠`,subagent:`◆`,rule:`│`,question:`?`,connection:`●`,arrow:`→`,pointer:`▷`,selectedPointer:`▶`,option:`◦`,prompt:`❯`,elbow:`⎿`,hrule:`▔`,caret:`▏`,dot:`·`,ellipsis:`…`,arrowUp:`↑`,arrowDown:`↓`},ASCII_GLYPHS={brand:`>`,user:`|`,reasoning:`o`,success:`+`,error:`x`,warning:`!`,subagent:`*`,rule:`|`,question:`?`,connection:`*`,arrow:`->`,pointer:`>`,selectedPointer:`>`,option:`.`,prompt:`>`,elbow:"`-",hrule:`=`,caret:`_`,dot:`-`,ellipsis:`...`,arrowUp:`^`,arrowDown:`v`},UNICODE_SPINNER=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],ASCII_SPINNER=[`-`,`\\`,`|`,`/`];function createTheme(i={}){let a=i.color??!0,o=i.unicode??!0;return{color:a,unicode:o,colors:{reset:ansi(0,0,a),bold:ansi(1,22,a),dim:ansi(2,22,a),inverse:ansi(7,27,a),italic:ansi(3,23,a),white:ansi(97,39,a),gray:ansi(90,39,a),cyan:ansi(36,39,a),green:ansi(32,39,a),red:ansi(31,39,a),yellow:ansi(33,39,a),magenta:ansi(35,39,a),blue:ansi(34,39,a),orange:ansi256(208,a)},glyph:o?UNICODE_GLYPHS:ASCII_GLYPHS,spinner:o?UNICODE_SPINNER:ASCII_SPINNER}}function detectUnicode(e=process.env){let t=e.EVE_TUI_UNICODE;return t===`0`||t===`false`?!1:t===`1`||t===`true`?!0:e.TERM===`dumb`?!1:process.platform===`win32`?!!(e.WT_SESSION||e.TERM_PROGRAM===`vscode`):!0}export{createTheme,detectUnicode};
|
|
@@ -1,20 +1,10 @@
|
|
|
1
1
|
import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";
|
|
2
|
+
import type { DevelopmentTuiTarget } from "./target.js";
|
|
2
3
|
import type { TuiDisplayOptions } from "./types.js";
|
|
3
|
-
|
|
4
|
-
* Options for running the `eve dev` terminal UI against a server URL.
|
|
5
|
-
*/
|
|
4
|
+
export type { DevelopmentTuiTarget } from "./target.js";
|
|
6
5
|
export interface RunDevelopmentTuiInput extends TuiDisplayOptions {
|
|
7
|
-
/**
|
|
8
|
-
|
|
9
|
-
* server started by `eve dev`, or a remote `--url` target.
|
|
10
|
-
*/
|
|
11
|
-
readonly serverUrl: string;
|
|
12
|
-
/**
|
|
13
|
-
* Absolute application root. When present and the server is a local dev
|
|
14
|
-
* server, enables the TUI's `/model` command to edit local agent source.
|
|
15
|
-
* Omitted for remote (`--url`) targets.
|
|
16
|
-
*/
|
|
17
|
-
readonly appRoot?: string;
|
|
6
|
+
/** The local server or remote URL used by this TUI session. */
|
|
7
|
+
readonly target: DevelopmentTuiTarget;
|
|
18
8
|
/**
|
|
19
9
|
* Text to seed the prompt input with after the UI launches. The buffer is
|
|
20
10
|
* editable and is not auto-submitted — the user presses Enter to send it.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createPromptCommandHandler}from"./prompt-command-handler.js";import{EveTUIRunner}from"./runner.js";import{toErrorMessage}from"#shared/errors.js";import{Client}from"#client/index.js";import{resolveDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{formatVercelAuthChallengeMessage,isVercelAuthChallenge}from"#services/dev-client/vercel-auth-error.js";async function runDevelopmentTui(t){let{
|
|
1
|
+
import{createPromptCommandHandler}from"./prompt-command-handler.js";import{EveTUIRunner}from"./runner.js";import{toErrorMessage}from"#shared/errors.js";import{Client}from"#client/index.js";import{resolveDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{resolveVerifiedRemoteDevelopmentClient}from"#setup/verified-remote-client.js";import{formatVercelAuthChallengeMessage,isVercelAuthChallenge}from"#services/dev-client/vercel-auth-error.js";async function resolveClientOptions(e){return e.kind===`local`?{options:resolveDevelopmentClientOptions(e.serverUrl),lastOidcTokenFailure:()=>void 0}:await resolveVerifiedRemoteDevelopmentClient({serverUrl:e.serverUrl,workspaceRoot:e.workspaceRoot})}async function runDevelopmentTui(t){let{target:n,initialInput:r,onBootProgress:i,...a}=t,{serverUrl:o}=n,{options:s,lastOidcTokenFailure:c}=await resolveClientOptions(n),l=new Client(s),u={...a,session:l.session(),client:l,serverUrl:o,promptCommandHandler:createPromptCommandHandler(n.kind===`local`?{appRoot:n.workspaceRoot}:{}),formatTransportError:e=>isVercelAuthChallenge(e)?formatVercelAuthChallengeMessage({serverUrl:o,oidcTokenFailure:c()}):toErrorMessage(e)};n.kind===`local`&&(u.appRoot=n.workspaceRoot),r!==void 0&&(u.initialInput=r),i!==void 0&&(u.onBootProgress=i),await new EveTUIRunner(u).run()}export{runDevelopmentTui};
|
package/dist/src/cli/dev/url.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{InvalidArgumentError}from"#compiled/commander/index.js";const DEVELOPMENT_SERVER_PROTOCOLS=new Set([`http:`,`https:`]);function assertDevelopmentServerProtocol(
|
|
1
|
+
import{InvalidArgumentError}from"#compiled/commander/index.js";import{isLocalEveServerUrl}from"#services/dev-client/local-host.js";const DEVELOPMENT_SERVER_PROTOCOLS=new Set([`http:`,`https:`]);function assertDevelopmentServerProtocol(t,r){if(!DEVELOPMENT_SERVER_PROTOCOLS.has(t.protocol))throw new InvalidArgumentError(`Expected an absolute http(s) URL, received "${r}".`)}function assertSecureRemoteProtocol(n,r){if(n.protocol===`http:`&&!isLocalEveServerUrl(n))throw new InvalidArgumentError(`Remote servers must use https://; received "${r}". Only local hosts may use http://.`)}function parseDevelopmentServerUrl(t){let n=t.trim();try{let e=new URL(n);return assertDevelopmentServerProtocol(e,t),assertSecureRemoteProtocol(e,t),e.hash=``,e.search=``,e.toString()}catch(n){throw n instanceof InvalidArgumentError?n:new InvalidArgumentError(`Expected an absolute http(s) URL, received "${t}".`)}}export{parseDevelopmentServerUrl};
|
package/dist/src/cli/run.d.ts
CHANGED
|
@@ -65,18 +65,6 @@ export declare function resolveDevUiMode(input: {
|
|
|
65
65
|
options: Pick<DevelopmentCliOptions, "ui">;
|
|
66
66
|
interactive: boolean;
|
|
67
67
|
}): DevUiMode;
|
|
68
|
-
/**
|
|
69
|
-
* Resolves the terminal UI's header title: an explicit `--name`, else the
|
|
70
|
-
* remote server's host (for `--url`), else the humanized app-folder name
|
|
71
|
-
* (e.g. `apps/fixtures/weather-agent` → "Weather Agent"). Returns `undefined` when
|
|
72
|
-
* nothing meaningful can be derived, so the runner falls back to its own
|
|
73
|
-
* default.
|
|
74
|
-
*/
|
|
75
|
-
export declare function resolveTuiTitle(input: {
|
|
76
|
-
name: string | undefined;
|
|
77
|
-
remoteServerUrl: string | undefined;
|
|
78
|
-
appRoot: string;
|
|
79
|
-
}): string | undefined;
|
|
80
68
|
/**
|
|
81
69
|
* Builds the terminal-UI display options for `eve dev`. Tools default to
|
|
82
70
|
* `auto-collapsed`, reasoning to `full`, and stderr logs are visible so
|
package/dist/src/cli/run.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{eveCliBanner}from"#cli/banner.js";import{startCliLiveRow}from"#cli/ui/live-row.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{Command,CommanderError,InvalidArgumentError}from"#compiled/commander/index.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{registerProjectCommands}from"#cli/commands/register-project-commands.js";import{LOG_DISPLAY_MODES,parseLogDisplayMode}from"#cli/dev/tui/log-display-mode.js";import{resolveTuiTitle}from"#cli/dev/tui/target.js";import{parseDevelopmentServerUrl}from"#cli/dev/url.js";const devBootLog=createLogger(`dev.boot`);function createDevBootProgressReporter(e){return t=>{switch(t.type){case`phase-started`:e?.update(`Building your agent`,t.phase),devBootLog.debug(t.phase);return;case`phase-finished`:devBootLog.debug(`${t.phase} finished`,{ms:t.elapsedMs});return;case`before-first-paint`:e?.stop();return;default:return t}}}async function loadBuildHost(){return(await import(`#internal/nitro/host.js`)).buildApplication}async function loadPrintApplicationInfo(){return(await import(`#cli/commands/info.js`)).printApplicationInfo}async function loadRunDevelopmentTui(){return(await import(`#cli/dev/tui/tui.js`)).runDevelopmentTui}async function loadRunEvalCommand(){return(await import(`#evals/cli/eval.js`)).runEvalCommand}async function loadStartHost(){return(await import(`#internal/nitro/host.js`)).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 resolveTuiDisplayOptions(e){let t={logs:e.logs??`stderr`,reasoning:e.reasoning??`full`,tools:e.tools??`auto-collapsed`};return e.subagents!==void 0&&(t.subagents=e.subagents),e.connectionAuth!==void 0&&(t.connectionAuth=e.connectionAuth),e.assistantResponseStats!==void 0&&(t.assistantResponseStats=e.assistantResponseStats),e.contextSize!==void 0&&(t.contextSize=e.contextSize),t}function hasInteractiveTerminal(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function rewriteDevelopmentUrlShorthand(e){let t=e[1];return e[0]!==`dev`||e.length!==2||t===void 0||t.startsWith(`-`)?[...e]:[`dev`,`--url`,t]}function resolveRemoteDevelopmentServerUrl(e){if(e.url){if(e.host!==void 0)throw new InvalidArgumentError(`The --host option cannot be used with --url.`);if(e.port!==void 0)throw new InvalidArgumentError(`The --port option cannot be used with --url.`);if(e.ui===!1)throw new InvalidArgumentError(`The --no-ui option cannot be used with --url.`);return e.url}}function createCliProgram(e,s){let d=resolveApplicationRoot(),f=resolveInstalledPackageInfo().version,m=new Command,h=createCliTheme();m.name(`eve`).description(`Build and run an eve application.`).version(f).showHelpAfterError().exitOverride().hook(`preAction`,(t,n)=>{shouldPrintCliBootBanner(n)&&e.log(eveCliBanner())}).configureOutput({writeErr:t=>{e.error(t.trimEnd())},writeOut:t=>{e.log(t.trimEnd())}});let g=m.command(`channels`).description(`Manage user-authored channels in the current project.`);return g.command(`add [kind]`).description(`Add channels interactively, or scaffold a channel kind (slack | web).`).option(`-f, --force`,`Overwrite existing channel files`).option(`-y, --yes`,`Assume yes for confirmations; requires an explicit channel kind`).action(async(t,n)=>{let{runChannelsAddCommand:r}=await import(`#cli/commands/channels.js`);await r(e,d,{kind:t,options:n})}),g.command(`list`).description(`List user-authored channels in the current project.`).option(`--json`,`Output as JSON`).action(async t=>{let{runChannelsListCommand:n}=await import(`#cli/commands/channels.js`);await n(e,d,t)}),m.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(t,n)=>{let{runInitCommand:r}=await import(`#cli/commands/init.js`);await r(e,d,t,n)}),registerProjectCommands({program:m,logger:e,appRoot:d}),m.command(`build`).description(`Build the current eve application.`).action(async()=>{let{loadDevelopmentEnvironmentFiles:t}=await import(`#cli/dev/environment.js`);t(d);let n=await(s.buildHost??await loadBuildHost())(d);e.log(renderCliTaggedLine(h,{message:`built output at ${n}`,tag:`build`,tone:`success`}))}),m.command(`start`).description(`Start a built eve application.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,parsePortOption).action(async t=>{let{loadDevelopmentEnvironmentFiles:n}=await import(`#cli/dev/environment.js`);n(d);let i=await(s.startProductionHost??await loadStartProductionHost())(d,{host:t.host,port:t.port});e.log(renderCliTaggedLine(h,{message:`server listening at ${i.url}`,tag:`start`,tone:`success`})),await waitForProductionServer(i)}),m.command(`dev`).description(`Start the eve development server or connect to an existing URL.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 2000)`,parsePortOption).option(`-u, --url <url>`,`Connect to an existing server URL`,parseDevelopmentServerUrl).option(`--no-ui`,`Start the server without an interactive UI`).option(`--name <name>`,`Title shown in the terminal UI (defaults to the app folder name)`).option(`--input <text>`,`Pre-fill the prompt input after launching the UI`).option(`--tools <mode>`,`How tool calls render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--reasoning <mode>`,`How reasoning renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--subagents <mode>`,`How subagent sections render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--connection-auth <mode>`,`How connection authorization renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--assistant-response-stats <mode>`,`Assistant header statistic: tokens | tokensPerSecond`,parseStatsMode).option(`--context-size <tokens>`,`Model context window size, shown as a usage percentage`,parseContextSizeOption).option(`--logs <mode>`,`Which server/agent logs to show: all | stderr | sandbox | none`,parseLogsMode).addHelpText(`after`,`
|
|
2
2
|
You can also pass a bare URL as the only argument, for example: eve dev https://example.com
|
|
3
|
-
`).action(async t=>{let
|
|
3
|
+
`).action(async t=>{let n=resolveRemoteDevelopmentServerUrl(t),i=hasInteractiveTerminal(),o=resolveDevUiMode({options:t,interactive:i});if(t.input!==void 0&&o===`headless`)throw new InvalidArgumentError(`--input requires the interactive UI.`);let{loadDevelopmentEnvironmentFiles:l}=await import(`#cli/dev/environment.js`);l(d);let runInteractiveUi=async(e,r)=>{let i=await devBootPhase(`loading interactive UI`,async()=>s.runDevelopmentTui??await loadRunDevelopmentTui(),r),a=resolveTuiDisplayOptions(t),o=n===void 0?{kind:`local`,serverUrl:e,workspaceRoot:d}:{kind:`remote`,serverUrl:e,workspaceRoot:d},c=resolveTuiTitle({name:t.name,target:o});c!==void 0&&(a.name=c),await i({target:o,initialInput:t.input,onBootProgress:r,...a})};if(n){if(e.log(renderCliTaggedLine(h,{message:`connecting to ${n}`,tag:`dev`,tone:`info`})),o===`headless`){e.log(renderCliTaggedLine(h,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`}));return}e.log(``),await runInteractiveUi(n);return}o===`tui`&&e.log(``);let u=o===`tui`?startCliLiveRow(e):void 0,f=createDevBootProgressReporter(u);u?.update(`Building your agent`);let p=!1,m,closeServer=async()=>{p||m===void 0||(p=!0,await m.close())};try{if(m=await(s.startHost??await loadStartHost())(d,{host:t.host,onBootProgress:f,port:t.port}),o!==`tui`&&e.log(renderCliTaggedLine(h,{message:`server listening at ${m.url}`,tag:`dev`,tone:`success`})),o===`headless`)return t.ui!==!1&&!i&&e.log(renderCliTaggedLine(h,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`})),await waitForShutdownSignal({close:closeServer});await runInteractiveUi(m.url,f)}finally{u?.stop(),await closeServer()}}),m.command(`info`).description(`Print resolved application information.`).option(`--json`,`Output as JSON`).action(async t=>{await(s.printApplicationInfo??await loadPrintApplicationInfo())(e,d,t)}),m.command(`eval`).description(`Run evals against an eve agent.`).argument(`[evalIds...]`,`Eval ids (or directory prefixes) to run (all discovered evals when omitted)`).option(`--url <url>`,`Remote agent URL (skip local host startup)`,parseDevelopmentServerUrl).option(`--tag <tag...>`,`Run only evals carrying a tag`).option(`--strict`,`Fail the exit code when any score falls below its threshold`).option(`--list`,`Print discovered evals without running them`).option(`--timeout <ms>`,`Per-eval timeout in milliseconds`).option(`--max-concurrency <n>`,`Max concurrent eval executions`).option(`--json`,`Output results as JSON`).option(`--junit <path>`,`Write JUnit XML results to a file`).option(`--skip-report`,`Skip eval-defined reporters (e.g. Braintrust)`).option(`--verbose`,`Stream per-eval t.log lines to stdout`).action(async(t,n)=>{await(s.runEvalCommand??await loadRunEvalCommand())(t,n,e)}),m}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,runCli};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";import{ClientSession}from"#client/session.js";import{createInitialSessionState}from"#client/session-utils.js";import{createClientUrl}from"#client/url.js";var Client=class{#e;#t;#n;#r;#i;constructor(e){this.#n=e.host,this.#e=e.auth,this.#t=e.headers,this.#r=e.maxReconnectAttempts??3,this.#i=e.preserveCompletedSessions??!1}async health(){let t=createClientUrl(this.#n,EVE_HEALTH_ROUTE_PATH),r=await this.#
|
|
1
|
+
import{EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";import{ClientSession}from"#client/session.js";import{createInitialSessionState}from"#client/session-utils.js";import{createClientUrl}from"#client/url.js";var Client=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#n=e.host,this.#e=e.auth,this.#t=e.headers,this.#r=e.maxReconnectAttempts??3,this.#i=e.preserveCompletedSessions??!1,this.#a=e.redirect}async health(){let t=createClientUrl(this.#n,EVE_HEALTH_ROUTE_PATH),r=await this.#o(),i=await fetch(t,withRedirectPolicy({headers:r},this.#a));if(!i.ok){let e=await i.text();throw new ClientError(i.status,e)}return await i.json()}async info(){let e=createClientUrl(this.#n,EVE_INFO_ROUTE_PATH),r=await this.#o(),i=await fetch(e,withRedirectPolicy({headers:r},this.#a));if(!i.ok){let e=await i.text();throw new ClientError(i.status,e)}return await i.json()}async fetch(e,t={}){let n=createClientUrl(this.#n,e),r=await this.#o(headersInitToRecord(t.headers));return await fetch(n,withRedirectPolicy({...t,headers:r},this.#a))}session(e){let t;return t=typeof e==`string`?{continuationToken:e,streamIndex:0}:e||createInitialSessionState(),new ClientSession({host:this.#n,maxReconnectAttempts:this.#r,preserveCompletedSessions:this.#i,redirect:this.#a,resolveHeaders:e=>this.#o(e)},t)}async#o(e){let t=new Headers,n=await resolveHeadersValue(this.#t);for(let[e,r]of Object.entries(n))t.set(e,r);if(e)for(let[n,r]of Object.entries(e))t.set(n,r);let r=await this.#s();return r&&t.set(`authorization`,r),t}async#s(){let e=this.#e;if(e){if(`bearer`in e){let t=(await resolveTokenValue(e.bearer)).trim();return t.length===0?void 0:`Bearer ${t}`}if(`basic`in e){let t=await resolveTokenValue(e.basic.password);return`Basic ${encodeBasicCredentials(e.basic.username,t)}`}}}};async function resolveTokenValue(e){return typeof e==`function`?e():e}async function resolveHeadersValue(e){return e===void 0?{}:typeof e==`function`?await e():e}function headersInitToRecord(e){return e===void 0?{}:Object.fromEntries(new Headers(e).entries())}function withRedirectPolicy(e,t){return t===void 0?e:{...e,redirect:t}}function encodeBasicCredentials(e,t){let n=new TextEncoder().encode(`${e}:${t}`),r=Array.from(n,e=>String.fromCodePoint(e)).join(``);return btoa(r)}export{Client};
|
|
@@ -6,7 +6,7 @@ export { createDataUrlFilePart, createTextWithFileContent } from "#client/file-p
|
|
|
6
6
|
export { MessageResponse } from "#client/message-response.js";
|
|
7
7
|
export { ClientSession } from "#client/session.js";
|
|
8
8
|
export type { EveAgentStoreCallbacks, EveAgentStoreInit, EveAgentStoreSnapshot, EveAgentStoreStatus, PrepareSend, } from "#client/eve-agent-store.js";
|
|
9
|
-
export type { AgentInfoEntry, AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoFrameworkChannelEntry, AgentInfoFrameworkToolEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, ClientAuth, ClientOptions, HeadersValue, HealthResult, MessageResult, SendTurnInput, SendTurnPayload, SessionState, StreamOptions, TokenValue, } from "#client/types.js";
|
|
9
|
+
export type { AgentInfoEntry, AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoFrameworkChannelEntry, AgentInfoFrameworkToolEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, ClientAuth, ClientOptions, ClientRedirectPolicy, HeadersValue, HealthResult, MessageResult, SendTurnInput, SendTurnPayload, SessionState, StreamOptions, TokenValue, } from "#client/types.js";
|
|
10
10
|
export type { EveAgentReducer, EveAgentReducerEvent, ClientInputRespondedEvent, ClientMessageFailedEvent, ClientMessageSubmittedEvent, } from "#client/reducer.js";
|
|
11
11
|
export type { EveMessageData, EveDynamicToolPart, EveMessageInputRequest, EveMessage, EveMessageMetadata, EveMessagePart, EveMessageToolMetadata, } from "#client/message-reducer.js";
|
|
12
12
|
export type { ActionResultStreamEvent, ActionsRequestedStreamEvent, AssistantStepFinishReason, CompactionCompletedStreamEvent, CompactionRequestedStreamEvent, AuthorizationCompletedStreamEvent, ConnectionAuthorizationOutcome, AuthorizationRequiredStreamEvent, HandleMessageStreamEvent, InputRequestedStreamEvent, MessageAppendedStreamEvent, MessageCompletedStreamEvent, MessageReceivedStreamEvent, ReasoningAppendedStreamEvent, ReasoningCompletedStreamEvent, ResultCompletedStreamEvent, SessionCompletedStreamEvent, SessionFailedStreamEvent, SessionStartedStreamEvent, SessionWaitingStreamEvent, StepCompletedStreamEvent, StepFailedStreamEvent, StepStartedStreamEvent, SubagentCalledStreamEvent, SubagentChildEventStreamEvent, SubagentCompletedStreamEvent, SubagentStartedStreamEvent, TurnCompletedStreamEvent, TurnFailedStreamEvent, TurnStartedStreamEvent, TurnFailureStreamEvent, } from "#protocol/message.js";
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { HandleMessageStreamEvent } from "#protocol/message.js";
|
|
2
|
+
import type { ClientRedirectPolicy } from "#client/types.js";
|
|
2
3
|
/**
|
|
3
4
|
* Internal configuration for opening a durable event stream.
|
|
4
5
|
*/
|
|
@@ -6,6 +7,7 @@ interface OpenStreamInput {
|
|
|
6
7
|
readonly host: string;
|
|
7
8
|
readonly maxReconnectAttempts: number;
|
|
8
9
|
readonly resolveHeaders: () => Promise<Headers>;
|
|
10
|
+
readonly redirect?: ClientRedirectPolicy;
|
|
9
11
|
readonly sessionId: string;
|
|
10
12
|
readonly signal?: AbortSignal;
|
|
11
13
|
readonly startIndex: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveMessageStreamRoutePath}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";const STREAM_OPEN_RETRYABLE_STATUS=new Set([404,409,425,500,502,503,504]);async function*openStreamIterable(e){let t=e.startIndex,n=e.maxReconnectAttempts;for(;;){let a=await openStreamBody({...e,startIndex:t}),o=!1;try{for await(let e of readNdjsonStream(a))t+=1,yield e}catch(e){if(!isStreamDisconnectError(e))throw e;o=!0}if(!o||e.signal?.aborted||n<=0)return;--n}}async function openStreamBody(r){let i,o;for(let s=0;s<12;s+=1){let c=createClientUrl(r.host,createEveMessageStreamRoutePath(r.sessionId),r.startIndex>0?{startIndex:String(r.startIndex)}:void 0),l=await r.resolveHeaders(),u=await fetch(c,{headers:l,signal:r.signal??null});if(u.ok){if(!u.body)throw new ClientError(u.status,`Response body is null.`);return u.body}if(i=u.status,o=await u.text(),!STREAM_OPEN_RETRYABLE_STATUS.has(u.status))throw new ClientError(u.status,o);s<11&&await sleep(250)}throw new ClientError(i??0,o??`Failed to open message stream.`)}async function sleep(e){await new Promise(t=>setTimeout(t,e))}export{openStreamBody,openStreamIterable};
|
|
1
|
+
import{createEveMessageStreamRoutePath}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";const STREAM_OPEN_RETRYABLE_STATUS=new Set([404,409,425,500,502,503,504]);async function*openStreamIterable(e){let t=e.startIndex,n=e.maxReconnectAttempts;for(;;){let a=await openStreamBody({...e,startIndex:t}),o=!1;try{for await(let e of readNdjsonStream(a))t+=1,yield e}catch(e){if(!isStreamDisconnectError(e))throw e;o=!0}if(!o||e.signal?.aborted||n<=0)return;--n}}async function openStreamBody(r){let i,o;for(let s=0;s<12;s+=1){let c=createClientUrl(r.host,createEveMessageStreamRoutePath(r.sessionId),r.startIndex>0?{startIndex:String(r.startIndex)}:void 0),l=await r.resolveHeaders(),u=await fetch(c,{headers:l,redirect:r.redirect,signal:r.signal??null});if(u.ok){if(!u.body)throw new ClientError(u.status,`Response body is null.`);return u.body}if(i=u.status,o=await u.text(),!STREAM_OPEN_RETRYABLE_STATUS.has(u.status))throw new ClientError(u.status,o);s<11&&await sleep(250)}throw new ClientError(i??0,o??`Failed to open message stream.`)}async function sleep(e){await new Promise(t=>setTimeout(t,e))}export{openStreamBody,openStreamIterable};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { HandleMessageStreamEvent } from "#protocol/message.js";
|
|
2
2
|
import { MessageResponse } from "#client/message-response.js";
|
|
3
|
-
import type { SendTurnInput, SessionState, StreamOptions } from "#client/types.js";
|
|
3
|
+
import type { ClientRedirectPolicy, SendTurnInput, SessionState, StreamOptions } from "#client/types.js";
|
|
4
4
|
/**
|
|
5
5
|
* Internal interface that a {@link ClientSession} uses to access client-level
|
|
6
6
|
* configuration without depending on the full {@link Client} class.
|
|
@@ -9,6 +9,7 @@ interface SessionContext {
|
|
|
9
9
|
readonly host: string;
|
|
10
10
|
readonly maxReconnectAttempts: number;
|
|
11
11
|
readonly preserveCompletedSessions: boolean;
|
|
12
|
+
readonly redirect?: ClientRedirectPolicy;
|
|
12
13
|
resolveHeaders(perRequest?: Readonly<Record<string, string>>): Promise<Headers>;
|
|
13
14
|
}
|
|
14
15
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_CREATE_SESSION_ROUTE_PATH,createEveContinueSessionRoutePath}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";import{advanceSession}from"#client/session-utils.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{normalizeOutputSchemaForRequest}from"#client/output-schema.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";import{openStreamBody,openStreamIterable}from"#client/open-stream.js";var ClientSession=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get state(){return this.#t}async send(e){let t=normalizeSendTurnInput(e),n=this.#t,{continuationToken:r,sessionId:i}=await this.#n(t,n);return new MessageResponse({continuationToken:r,createStream:()=>this.#r(i,r,n,t),sessionId:i})}stream(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);return this.#a(t,e)}async#n(n,r){let a=r.sessionId?createEveContinueSessionRoutePath(r.sessionId):EVE_CREATE_SESSION_ROUTE_PATH,s=createClientUrl(this.#e.host,a),c=await this.#e.resolveHeaders(n.headers);c.set(`content-type`,`application/json`);let l=createHandleMessageBody({input:n,outputSchema:normalizeOutputSchemaForRequest(n.outputSchema),session:r});if(l===null)throw Error(`Session.send requires a non-empty message, inputResponses, or both.`);let u=await postTurnWithRetry({body:JSON.stringify(l),headers:c,mustDeliver:(n.inputResponses?.length??0)>0,signal:n.signal,url:s}),d=await u.json(),f=(typeof d.sessionId==`string`?d.sessionId:void 0)??u.headers.get(EVE_SESSION_ID_HEADER)?.trim()??r.sessionId;if(!f)throw Error(`Message route did not return a session id.`);return{continuationToken:typeof d.continuationToken==`string`?d.continuationToken:void 0,sessionId:f}}async*#r(e,t,n,i){let a=[];try{let t=n.sessionId===e?n.streamIndex:0,r=this.#e.maxReconnectAttempts;for(;;){let n=await this.#i(e,t,i.signal,i.headers),o=!1;try{for await(let e of readNdjsonStream(n))if(a.push(e),t+=1,yield e,isCurrentTurnBoundaryEvent(e)){o=!0;break}}catch(e){if(!isStreamDisconnectError(e))throw e}if(o||i.signal?.aborted||r<=0)break;--r}}finally{this.#t=advanceSession({continuationToken:t,events:a,preserveCompletedSessions:this.#e.preserveCompletedSessions,sessionId:e,session:n})}}async#i(e,t,n,r){return await openStreamBody({host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(r),sessionId:e,signal:n,startIndex:t})}async*#a(e,t){let n=this.#t,i=t?.startIndex??n.streamIndex,a=[];try{for await(let n of openStreamIterable({host:this.#e.host,maxReconnectAttempts:this.#e.maxReconnectAttempts,resolveHeaders:()=>this.#e.resolveHeaders(),sessionId:e,signal:t?.signal,startIndex:i}))a.push(n),yield n}finally{this.#t=advanceSession({continuationToken:n.continuationToken,events:a,preserveCompletedSessions:this.#e.preserveCompletedSessions,session:{...n,sessionId:e,streamIndex:i},sessionId:e})}}};async function postTurnWithRetry(e){let t=e.mustDeliver?10:1,r,i;for(let a=0;a<t;a+=1){let o=await fetch(e.url,{body:e.body,headers:e.headers,method:`POST`,signal:e.signal??null});if(o.ok)return o;if(r=o.status,i=await o.text(),!isRetryableDeliveryFailure(o.status,i))throw new ClientError(o.status,i);a<t-1&&await sleep(200)}throw new ClientError(r??0,i??`Failed to deliver session turn.`)}function isRetryableDeliveryFailure(e,t){return e===500&&/target session was not found/i.test(t)}async function sleep(e){await new Promise(t=>setTimeout(t,e))}function normalizeSendTurnInput(e){return typeof e==`string`?{message:e}:e}function createHandleMessageBody(e){let t={};return e.input.message!==void 0&&(t.message=e.input.message),e.input.inputResponses!==void 0&&e.input.inputResponses.length>0&&(t.inputResponses=e.input.inputResponses),e.input.clientContext!==void 0&&(t.clientContext=e.input.clientContext),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.session.continuationToken!==void 0&&(t.continuationToken=e.session.continuationToken),Object.keys(t).length===0||e.session.continuationToken===void 0&&t.message===void 0||e.session.continuationToken!==void 0&&t.message===void 0&&t.inputResponses===void 0?null:t}export{ClientSession};
|
|
1
|
+
import{EVE_CREATE_SESSION_ROUTE_PATH,createEveContinueSessionRoutePath}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";import{advanceSession}from"#client/session-utils.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{normalizeOutputSchemaForRequest}from"#client/output-schema.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";import{openStreamBody,openStreamIterable}from"#client/open-stream.js";var ClientSession=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get state(){return this.#t}async send(e){let t=normalizeSendTurnInput(e),n=this.#t,{continuationToken:r,sessionId:i}=await this.#n(t,n);return new MessageResponse({continuationToken:r,createStream:()=>this.#r(i,r,n,t),sessionId:i})}stream(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);return this.#a(t,e)}async#n(n,r){let a=r.sessionId?createEveContinueSessionRoutePath(r.sessionId):EVE_CREATE_SESSION_ROUTE_PATH,s=createClientUrl(this.#e.host,a),c=await this.#e.resolveHeaders(n.headers);c.set(`content-type`,`application/json`);let l=createHandleMessageBody({input:n,outputSchema:normalizeOutputSchemaForRequest(n.outputSchema),session:r});if(l===null)throw Error(`Session.send requires a non-empty message, inputResponses, or both.`);let u=await postTurnWithRetry({body:JSON.stringify(l),headers:c,mustDeliver:(n.inputResponses?.length??0)>0,redirect:this.#e.redirect,signal:n.signal,url:s}),d=await u.json(),f=(typeof d.sessionId==`string`?d.sessionId:void 0)??u.headers.get(EVE_SESSION_ID_HEADER)?.trim()??r.sessionId;if(!f)throw Error(`Message route did not return a session id.`);return{continuationToken:typeof d.continuationToken==`string`?d.continuationToken:void 0,sessionId:f}}async*#r(e,t,n,i){let a=[];try{let t=n.sessionId===e?n.streamIndex:0,r=this.#e.maxReconnectAttempts;for(;;){let n=await this.#i(e,t,i.signal,i.headers),o=!1;try{for await(let e of readNdjsonStream(n))if(a.push(e),t+=1,yield e,isCurrentTurnBoundaryEvent(e)){o=!0;break}}catch(e){if(!isStreamDisconnectError(e))throw e}if(o||i.signal?.aborted||r<=0)break;--r}}finally{this.#t=advanceSession({continuationToken:t,events:a,preserveCompletedSessions:this.#e.preserveCompletedSessions,sessionId:e,session:n})}}async#i(e,t,n,r){return await openStreamBody({host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(r),redirect:this.#e.redirect,sessionId:e,signal:n,startIndex:t})}async*#a(e,t){let n=this.#t,i=t?.startIndex??n.streamIndex,a=[];try{for await(let n of openStreamIterable({host:this.#e.host,maxReconnectAttempts:this.#e.maxReconnectAttempts,resolveHeaders:()=>this.#e.resolveHeaders(),redirect:this.#e.redirect,sessionId:e,signal:t?.signal,startIndex:i}))a.push(n),yield n}finally{this.#t=advanceSession({continuationToken:n.continuationToken,events:a,preserveCompletedSessions:this.#e.preserveCompletedSessions,session:{...n,sessionId:e,streamIndex:i},sessionId:e})}}};async function postTurnWithRetry(e){let t=e.mustDeliver?10:1,r,i;for(let a=0;a<t;a+=1){let o=await fetch(e.url,{body:e.body,headers:e.headers,method:`POST`,redirect:e.redirect,signal:e.signal??null});if(o.ok)return o;if(r=o.status,i=await o.text(),!isRetryableDeliveryFailure(o.status,i))throw new ClientError(o.status,i);a<t-1&&await sleep(200)}throw new ClientError(r??0,i??`Failed to deliver session turn.`)}function isRetryableDeliveryFailure(e,t){return e===500&&/target session was not found/i.test(t)}async function sleep(e){await new Promise(t=>setTimeout(t,e))}function normalizeSendTurnInput(e){return typeof e==`string`?{message:e}:e}function createHandleMessageBody(e){let t={};return e.input.message!==void 0&&(t.message=e.input.message),e.input.inputResponses!==void 0&&e.input.inputResponses.length>0&&(t.inputResponses=e.input.inputResponses),e.input.clientContext!==void 0&&(t.clientContext=e.input.clientContext),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.session.continuationToken!==void 0&&(t.continuationToken=e.session.continuationToken),Object.keys(t).length===0||e.session.continuationToken===void 0&&t.message===void 0||e.session.continuationToken!==void 0&&t.message===void 0&&t.inputResponses===void 0?null:t}export{ClientSession};
|
|
@@ -28,6 +28,8 @@ export type ClientAuth = {
|
|
|
28
28
|
} | {
|
|
29
29
|
readonly bearer: TokenValue;
|
|
30
30
|
};
|
|
31
|
+
/** Redirect modes supported by the configured fetch implementation. */
|
|
32
|
+
export type ClientRedirectPolicy = NonNullable<RequestInit["redirect"]>;
|
|
31
33
|
/**
|
|
32
34
|
* Configuration for creating a new {@link Client}.
|
|
33
35
|
*/
|
|
@@ -47,6 +49,13 @@ export interface ClientOptions {
|
|
|
47
49
|
* that need to be refreshed alongside the bearer credential).
|
|
48
50
|
*/
|
|
49
51
|
readonly headers?: HeadersValue;
|
|
52
|
+
/**
|
|
53
|
+
* Redirect policy for every request, including streams. Overrides a
|
|
54
|
+
* per-request `RequestInit.redirect`. Credential-bearing clients should use
|
|
55
|
+
* `"manual"` or `"error"` so custom auth headers can't follow a cross-origin
|
|
56
|
+
* redirect.
|
|
57
|
+
*/
|
|
58
|
+
readonly redirect?: ClientRedirectPolicy;
|
|
50
59
|
/**
|
|
51
60
|
* Maximum number of stream reconnection attempts per message turn.
|
|
52
61
|
*
|
|
@@ -1,22 +1,18 @@
|
|
|
1
1
|
import { Client } from "#client/client.js";
|
|
2
2
|
import type { ClientOptions } from "#client/types.js";
|
|
3
|
+
import { type VerifiedRemoteDevelopmentClientDeps } from "#setup/verified-remote-client.js";
|
|
3
4
|
import type { EveEvalTargetHandle } from "#evals/types.js";
|
|
4
5
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* as every other development client (`resolveDevelopmentClientOptions`):
|
|
9
|
-
* per-request headers carrying the Vercel OIDC trusted-IDP token (which
|
|
10
|
-
* bypasses Deployment Protection without a per-project secret) plus
|
|
11
|
-
* `x-vercel-protection-bypass` when `VERCEL_AUTOMATION_BYPASS_SECRET` is
|
|
12
|
-
* set, and a bearer resolved from the same OIDC cascade.
|
|
13
|
-
*
|
|
14
|
-
* `EVE_EVAL_AUTH_TOKEN` overrides the bearer with a static token for
|
|
15
|
-
* targets whose auth is not OIDC-based.
|
|
6
|
+
* Synchronous {@link ClientOptions} for an eval target: local needs no auth,
|
|
7
|
+
* remote stays anonymous unless `EVE_EVAL_AUTH_TOKEN` sets a static bearer.
|
|
8
|
+
* Ambient Vercel credentials need the async {@link createEvalClient}.
|
|
16
9
|
*/
|
|
17
10
|
export declare function resolveEvalClientOptions(target: Pick<EveEvalTargetHandle, "kind" | "url">): ClientOptions;
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
*/
|
|
22
|
-
|
|
11
|
+
export interface CreateEvalClientOptions {
|
|
12
|
+
/** Working directory for Vercel lookup and the fallback on-disk project link. */
|
|
13
|
+
readonly workspaceRoot?: string;
|
|
14
|
+
/** Test seams for the two authority-resolution boundaries. */
|
|
15
|
+
readonly deps?: Partial<VerifiedRemoteDevelopmentClientDeps>;
|
|
16
|
+
}
|
|
17
|
+
/** Creates one eval client, authorizing ambient Vercel credentials only after origin proof. */
|
|
18
|
+
export declare function createEvalClient(target: Pick<EveEvalTargetHandle, "kind" | "url">, options?: CreateEvalClientOptions): Promise<Client>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{Client}from"#client/client.js";function resolveEvalClientOptions(t){if(t.kind===`local`)return{host:t.url};let n={...resolveDevelopmentClientOptions(t.url),preserveCompletedSessions:!1},r=process.env.EVE_EVAL_AUTH_TOKEN?.trim();return r?{...n,auth:{bearer:r}}:n}function createEvalClient(e){return new Client(
|
|
1
|
+
import{resolveDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{resolveVerifiedRemoteDevelopmentClient}from"#setup/verified-remote-client.js";import{Client}from"#client/client.js";function resolveEvalClientOptions(t){if(t.kind===`local`)return{host:t.url};let n={...resolveDevelopmentClientOptions(t.url),preserveCompletedSessions:!1},r=process.env.EVE_EVAL_AUTH_TOKEN?.trim();return r?{...n,auth:{bearer:r},redirect:`manual`}:n}async function createEvalClient(e,r={}){let i=resolveEvalClientOptions(e);if(e.kind===`local`||i.auth!==void 0||r.workspaceRoot===void 0)return new Client(i);let{options:a}=await resolveVerifiedRemoteDevelopmentClient({serverUrl:e.url,workspaceRoot:r.workspaceRoot,deps:r.deps});return new Client({...i,...a})}export{createEvalClient,resolveEvalClientOptions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{basename,join}from"node:path";import{readFile}from"node:fs/promises";import{
|
|
1
|
+
import{basename,join}from"node:path";import{readFile}from"node:fs/promises";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{startDevelopmentServer}from"#internal/nitro/host.js";import{createEvalClient}from"#evals/cli/eval-client.js";import{discoverAndImportEvals,discoverEvalConfig}from"#evals/runner/discover.js";import{runEvals}from"#evals/runner/run-evals.js";import{ConsoleReporter}from"#evals/runner/reporters/console.js";import{JUnit}from"#evals/runner/reporters/junit.js";import{resolveEvalTargetHandle}from"#evals/target.js";async function runEvalCommand(e,t,n){let o=resolveApplicationRoot();loadDevelopmentEnvironmentFiles(o);let s=e.length>0?e:void 0,c=await discoverAndImportEvals(o,s);if(c.length===0){s?n.error(`No evals found matching: ${s.join(`, `)}`):n.error(`No evals found. Create files under evals/ with the *.eval.ts extension.`),process.exitCode=2;return}let l=filterEvalsByTag(c,t.tag??[]);if(l.length===0){n.error(`No evals matched the provided tags (${(t.tag??[]).join(`, `)}).`),process.exitCode=2;return}let u,d;try{u=parsePositiveInteger(t.maxConcurrency,`--max-concurrency`),d=parseNonNegativeInteger(t.timeout,`--timeout`)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}if(t.list===!0){printEvalList(l,t.json===!0,n);return}let f;try{f=await discoverEvalConfig(o)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let p,m,h;try{t.url?(h=await createEvalClient({kind:`remote`,url:t.url},{workspaceRoot:o}),m=await resolveEvalTargetHandle({client:h,expectedAgentName:await readExpectedAgentName(o),kind:`remote`,url:t.url})):(p=await startDevelopmentServer(o,{host:`127.0.0.1`,port:0}),h=await createEvalClient({kind:`local`,url:p.url}),m=await resolveEvalTargetHandle({client:h,expectedAgentName:await readExpectedAgentName(o),kind:`local`,url:p.url}));let e=t.json===!0?[]:[new ConsoleReporter];t.junit!==void 0&&e.push(JUnit({filePath:t.junit}));let r=await runEvals({evaluations:l,config:f,target:m,client:h,appRoot:o,reporters:e,includeEvalReporters:t.skipReport!==!0,maxConcurrency:u,timeoutMs:d,onEvalLog:t.verbose===!0?(e,t)=>n.log(`[${e}] ${t}`):void 0});t.json&&n.log(JSON.stringify(r,null,2));let i=r.failed>0,a=t.strict===!0&&r.scored>0;(i||a)&&(process.exitCode=1)}finally{p&&await p.close()}let g=typeof process.exitCode==`number`?process.exitCode:0;process.exit(g)}function parsePositiveInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<1)throw Error(`${t} must be a positive integer; got "${e}".`);return n}function parseNonNegativeInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw Error(`${t} must be a non-negative integer; got "${e}".`);return n}function filterEvalsByTag(e,t){return t.length===0?[...e]:e.filter(e=>e.tags?.some(e=>t.includes(e))??!1)}function printEvalList(e,t,n){if(t){let t=e.map(e=>({id:e.id,description:e.description,tags:e.tags}));n.log(JSON.stringify(t,null,2));return}for(let t of e){let e=t.description===void 0?``:` — ${t.description}`,r=t.tags!==void 0&&t.tags.length>0?` [${t.tags.join(`, `)}]`:``;n.log(`${t.id}${r}${e}`)}}async function readExpectedAgentName(r){try{let i=JSON.parse(await readFile(join(r,`package.json`),`utf8`));return typeof i.name==`string`&&i.name.length>0?i.name:basename(r)}catch{return basename(r)}}export{runEvalCommand};
|
|
@@ -6,9 +6,8 @@ import type { CompactionConfig, ToolLoopHarnessConfig } from "#harness/types.js"
|
|
|
6
6
|
* deciding whether compaction is needed; the real token count comes back
|
|
7
7
|
* from the model each step via {@link CompactionConfig.lastKnownInputTokens}.
|
|
8
8
|
*
|
|
9
|
-
* Accepts any JSON-serializable value so
|
|
10
|
-
*
|
|
11
|
-
* every layer of context management on one consistent token ruler.
|
|
9
|
+
* Accepts any JSON-serializable value so callers can apply the same heuristic
|
|
10
|
+
* to whole message arrays or individual content parts on one consistent ruler.
|
|
12
11
|
*/
|
|
13
12
|
export declare function estimateTokens(value: unknown): number;
|
|
14
13
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{generateText}from"ai";const COMPACTION_SYSTEM_PROMPT=[`You are a conversation summarizer.`,`Write a concise but useful summary for continuing the work.`,`Preserve the goal, important instructions, technical decisions, discoveries, open work, and relevant tool results.`,`Use the same language as the conversation.`,`Prefer short labeled sections such as Goal, Instructions, Discoveries, Accomplished, and Next steps when helpful.`,`Do not answer questions or invent facts.`].join(` `);function estimateTokens(e){return JSON.stringify(e).length/4}function getInputTokenCount(e,t){let n=t.lastKnownInputTokens,r=t.lastKnownPromptMessageCount;return n===void 0||r===void 0||!Number.isInteger(r)||r<0||r>e.length?estimateTokens(e):n+estimateTokens(e.slice(r))}function shouldCompact(e,t){return getInputTokenCount(e,t)>t.threshold}async function resolveCompactionModel(e){let t=e.compactionModelReference??e.modelReference;return{model:t===e.modelReference?e.model:await e.resolveModel(t),providerOptions:t.providerOptions}}async function compactMessages(n,r,i,a,o,s){let c=selectRecentWindowSize(n,i);for(;;){let{older:l,recent:u}=splitMessagesForCompaction(n,c);if(l.length===0)return u;let d=await generateText({headers:s,model:r,prompt:formatCompactionPrompt(l.map(e=>({content:summarizeCompactionMessageContent(e),role:e.role}))),providerOptions:a,system:COMPACTION_SYSTEM_PROMPT,telemetry:o?{...o,functionId:`eve.compaction`}:void 0,temperature:0}),f=u.
|
|
1
|
+
import{generateText}from"ai";const COMPACTION_SYSTEM_PROMPT=[`You are a conversation summarizer.`,`Write a concise but useful summary for continuing the work.`,`Preserve the goal, important instructions, technical decisions, discoveries, open work, and relevant tool results.`,`Use the same language as the conversation.`,`Prefer short labeled sections such as Goal, Instructions, Discoveries, Accomplished, and Next steps when helpful.`,`Do not answer questions or invent facts.`].join(` `);function estimateTokens(e){return JSON.stringify(e).length/4}function getInputTokenCount(e,t){let n=t.lastKnownInputTokens,r=t.lastKnownPromptMessageCount;return n===void 0||r===void 0||!Number.isInteger(r)||r<0||r>e.length?estimateTokens(e):n+estimateTokens(e.slice(r))}function shouldCompact(e,t){return getInputTokenCount(e,t)>t.threshold}async function resolveCompactionModel(e){let t=e.compactionModelReference??e.modelReference;return{model:t===e.modelReference?e.model:await e.resolveModel(t),providerOptions:t.providerOptions}}async function compactMessages(n,r,i,a,o,s){let c=selectRecentWindowSize(n,i);for(;;){let{older:l,recent:u}=splitMessagesForCompaction(n,c);if(l.length===0)return keepNonToolResultMessages(u);let d=await generateText({headers:s,model:r,prompt:formatCompactionPrompt(l.map(e=>({content:summarizeCompactionMessageContent(e),role:e.role}))),providerOptions:a,system:COMPACTION_SYSTEM_PROMPT,telemetry:o?{...o,functionId:`eve.compaction`}:void 0,temperature:0}),f=keepNonToolResultMessages(u),p=f.at(-1)?.role,m=p===void 0||p===`assistant`?[{role:`user`,content:`Continue.`}]:[],h=[{content:`Summary of our conversation so far:`,role:`user`},{content:d.text,role:`assistant`},...f,...m];if(estimateTokens(h)<=i.threshold||c===0)return h;--c}}function keepNonToolResultMessages(e){let t=[];for(let n of e)if(n.role!==`tool`){if(n.role===`assistant`){let e=assistantMessageText(n);e.length>0&&t.push({content:e,role:`assistant`});continue}t.push(n)}return t}function assistantMessageText(e){return typeof e.content==`string`?e.content.trim():e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``).trim()}function selectRecentWindowSize(e,t){let n=Math.min(t.recentWindowSize,Math.max(e.length-1,0)),r=resolveCompactionSummaryReserve(t),i=0,a=0;for(let o=e.length-1;o>=0&&i<n;--o){let n=e[o];if(n===void 0)continue;let s=estimateTokens([n]);if(a+s+r>t.threshold)break;a+=s,i+=1}return i}function resolveCompactionSummaryReserve(e){return Math.min(2048,Math.max(64,Math.floor(e.threshold/4)))}function splitMessagesForCompaction(e,t){return t<=0?{older:[...e],recent:[]}:{older:e.slice(0,-t),recent:e.slice(-t)}}function formatCompactionPrompt(e){let t=e.filter(e=>e.content.trim().length>0).map(e=>`### ${e.role}\n${e.content.trim()}`);return t.length===0?`Summarize the conversation so far.`:[`Conversation transcript:`,...t].join(`
|
|
2
2
|
|
|
3
3
|
`)}function summarizeCompactionMessageContent(e){return typeof e.content==`string`?summarizeText(e.content):e.content.map(e=>summarizeCompactionContentPart(e)).filter(e=>e.length>0).join(`
|
|
4
4
|
`).trim()}function summarizeCompactionContentPart(e){switch(e.type){case`text`:return summarizeText(e.text);case`reasoning`:return``;case`file`:return e.filename?`Attached file ${e.filename} (${e.mediaType})`:`Attached file attachment (${e.mediaType})`;case`tool-call`:return summarizeToolCallPart(e);case`tool-result`:return summarizeToolResultPart(e);default:return``}}function summarizeToolCallPart(e){let t=e.input===void 0?``:summarizeCompactValue(e.input);return t?`Called ${e.toolName} with ${t}`:`Called ${e.toolName}`}function summarizeToolResultPart(e){let t=e.output===void 0?``:summarizeCompactValue(e.output),n=e.isError?`errored`:`returned`;return t?`Tool ${e.toolName} ${n} ${t}`:`Tool ${e.toolName} ${n}`}function summarizeCompactValue(e,t=0){if(e===null)return`null`;if(e===void 0)return``;if(typeof e==`string`)return summarizeText(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(Array.isArray(e)){if(e.length===0)return`array(0)`;if(t>=2)return`array(${e.length})`;let n=e.slice(0,3).map(e=>summarizeCompactValue(e,t+1)),r=e.length>3?`, …`:``;return`array(${e.length}: ${n.join(`, `)}${r})`}if(typeof e==`object`){let n=Object.entries(e);if(n.length===0)return`object(0)`;if(t>=2)return`object(${n.length} keys)`;let r=n.slice(0,3).map(([e,n])=>`${e}=${summarizeCompactValue(n,t+1)}`),i=n.length>3?`, …`:``;return`object(${r.join(`, `)}${i})`}return``}function summarizeText(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=280?t:`${t.slice(0,280).trimEnd()}…`}export{compactMessages,estimateTokens,getInputTokenCount,resolveCompactionModel,shouldCompact};
|