eve 0.8.3 → 0.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/src/chunks/{use-eve-agent-Dlut2Qzt.js → use-eve-agent-CdETo3qQ.js} +1 -0
- package/dist/src/chunks/{use-eve-agent-BSXZSn-R.js → use-eve-agent-ClyM-_UT.js} +1 -0
- package/dist/src/cli/banner.d.ts +2 -2
- package/dist/src/cli/banner.js +1 -1
- package/dist/src/cli/dev/tui/agent-header.d.ts +1 -1
- package/dist/src/cli/dev/tui/agent-header.js +1 -1
- package/dist/src/cli/dev/tui/log-display-mode.d.ts +13 -0
- package/dist/src/cli/dev/tui/log-display-mode.js +1 -0
- package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/status-line.d.ts +13 -4
- package/dist/src/cli/dev/tui/status-line.js +1 -1
- package/dist/src/cli/dev/tui/stream-format.d.ts +1 -2
- package/dist/src/cli/dev/tui/stream-format.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +6 -6
- package/dist/src/cli/dev/tui/theme.d.ts +0 -2
- package/dist/src/cli/dev/tui/theme.js +1 -1
- package/dist/src/cli/dev/tui/types.d.ts +8 -11
- package/dist/src/cli/run.js +2 -2
- package/dist/src/execution/sandbox/bindings/docker-base-setup.d.ts +3 -5
- package/dist/src/execution/sandbox/bindings/docker-base-setup.js +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-platform.d.ts +2 -3
- package/dist/src/execution/sandbox/bindings/microsandbox-platform.js +3 -160
- package/dist/src/execution/sandbox/development-prewarm.js +1 -1
- package/dist/src/execution/sandbox/ensure.js +1 -1
- package/dist/src/execution/sandbox/prewarm.d.ts +4 -0
- package/dist/src/execution/sandbox/prewarm.js +2 -1
- package/dist/src/execution/sandbox/template-prewarm-lock.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.d.ts +1 -0
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
- package/dist/src/internal/nitro/host/dev-rebuild-registry.d.ts +5 -0
- package/dist/src/internal/nitro/host/dev-rebuild-registry.js +1 -0
- package/dist/src/internal/nitro/routes/dev-runtime-artifacts.d.ts +3 -0
- package/dist/src/internal/nitro/routes/dev-runtime-artifacts.js +1 -1
- package/dist/src/protocol/routes.d.ts +5 -0
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/sandbox/docker-sandbox.d.ts +3 -3
- package/dist/src/public/sandbox/microsandbox-sandbox.d.ts +4 -4
- package/dist/src/services/dev-client/runtime-artifacts.d.ts +3 -0
- package/dist/src/services/dev-client/runtime-artifacts.js +1 -1
- package/dist/src/services/dev-client.js +1 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/update/channels.js +1 -1
- package/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/guides/dev-tui.md +4 -4
- package/docs/reference/cli.md +1 -1
- package/docs/sandbox.mdx +2 -2
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.8.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- ed7ee20: In the dev TUI, Ctrl+L now cycles the log filter (`none → all → stderr → sandbox`) and briefly shows the new mode as a `logs: <mode>` entry in the status line that clears after 5 seconds of no further cycling. Ctrl+R remains the redraw shortcut.
|
|
8
|
+
- ed7ee20: The dev TUI `/loglevel` command and `--logs` flag gain a `sandbox` mode and now treat sandbox lifecycle lines as a filterable source alongside stdout and stderr: `all` shows all three, `stderr` shows only stderr, `sandbox` shows only sandbox lines, and `none` hides everything. `eve dev` still starts in `stderr`, so sandbox lines stay hidden until you switch to `sandbox` or `all`.
|
|
9
|
+
- 1b1d55b: Queue most `eve dev` authored-source changes until the next user message while rebuilding root `agent.ts` changes immediately. Sandbox prewarm skips unchanged signatures, suppresses low-value cache/reuse progress in the dev REPL, and sandbox backends now keep framework setup minimal by only preparing `/workspace`, verifying Bash, and creating the microsandbox user where needed.
|
|
10
|
+
- ed7ee20: The dev TUI no longer shows the "Type to chat / for commands" hint on the empty prompt, and the status line's token-flow segment drops its leading glyph (now `↑ 394.4K ↓ 4.3K`). The CLI boot banner and `eve init` messages now spell the product as plain `eve` instead of the styled `𝐞𝐯𝐞` wordmark, and the dev TUI startup header drops its leading `▲` (now `eve <agent name>`).
|
|
11
|
+
|
|
3
12
|
## 0.8.3
|
|
4
13
|
|
|
5
14
|
### Patch Changes
|
|
@@ -9,6 +9,7 @@ const EVE_CONTINUE_SESSION_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/session/:session
|
|
|
9
9
|
const EVE_MESSAGE_STREAM_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/session/:sessionId/stream`;
|
|
10
10
|
const EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/dev/schedules/:scheduleId`;
|
|
11
11
|
const EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/dev/runtime-artifacts`;
|
|
12
|
+
const EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH = `${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/rebuild`;
|
|
12
13
|
const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`;
|
|
13
14
|
const EVE_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/callback/:token`;
|
|
14
15
|
function createEveMessageStreamRoutePath(sessionId) {
|
|
@@ -9,6 +9,7 @@ const EVE_CONTINUE_SESSION_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/session/:session
|
|
|
9
9
|
const EVE_MESSAGE_STREAM_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/session/:sessionId/stream`;
|
|
10
10
|
const EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/dev/schedules/:scheduleId`;
|
|
11
11
|
const EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/dev/runtime-artifacts`;
|
|
12
|
+
const EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH = `${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/rebuild`;
|
|
12
13
|
const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`;
|
|
13
14
|
const EVE_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/callback/:token`;
|
|
14
15
|
function createEveMessageStreamRoutePath(sessionId) {
|
package/dist/src/cli/banner.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export declare const EVE_WORDMARK = "
|
|
1
|
+
export declare const EVE_WORDMARK = "eve";
|
|
2
2
|
/**
|
|
3
3
|
* The one-line boot banner shared by every CLI command that announces itself:
|
|
4
|
-
* the
|
|
4
|
+
* the eve badge plus the installed version, dimmed. Printed only by the CLI
|
|
5
5
|
* program's pre-action hook so commands never compose their own variant.
|
|
6
6
|
*/
|
|
7
7
|
export declare function eveCliBanner(): string;
|
package/dist/src/cli/banner.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__toESM}from"../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";var import_picocolors=__toESM(require_picocolors(),1);const EVE_WORDMARK
|
|
1
|
+
import{__toESM}from"../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";var import_picocolors=__toESM(require_picocolors(),1);const EVE_WORDMARK=`eve`;function eveCliBanner(){let{version:e}=resolveInstalledPackageInfo();return`${import_picocolors.default.bgBlack(import_picocolors.default.white(` eve `))} ${import_picocolors.default.dim(`v${e}`)}`}export{EVE_WORDMARK,eveCliBanner};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Builds the startup header the dev TUI commits to scrollback before the
|
|
3
|
-
* first prompt: one
|
|
3
|
+
* first prompt: one `eve <agent name>` brand line, a discovery-diagnostics
|
|
4
4
|
* line when the compiler reported problems, and a rotating tip for local
|
|
5
5
|
* sessions. The resolved model is not repeated here — it lives on the
|
|
6
6
|
* persistent status line at the bottom.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{truncate}from"./tool-format.js";const AGENT_HEADER_TIPS=[`Use /channels to add more ways to reach your agent.`,`Use /deploy to see your agent go live.`,`Type /help to see every command.`];function pickAgentHeaderTip(e=Math.random){return AGENT_HEADER_TIPS[Math.min(AGENT_HEADER_TIPS.length-1,Math.floor(e()*AGENT_HEADER_TIPS.length))]}function buildAgentHeader(t){let{theme:n,info:r,name:i,width:a}=t,o=n.colors,s=[],c=o.bold(
|
|
1
|
+
import{truncate}from"./tool-format.js";const AGENT_HEADER_TIPS=[`Use /channels to add more ways to reach your agent.`,`Use /deploy to see your agent go live.`,`Type /help to see every command.`];function pickAgentHeaderTip(e=Math.random){return AGENT_HEADER_TIPS[Math.min(AGENT_HEADER_TIPS.length-1,Math.floor(e()*AGENT_HEADER_TIPS.length))]}function buildAgentHeader(t){let{theme:n,info:r,name:i,width:a}=t,o=n.colors,s=[],c=o.bold(`eve`);if(s.push(` ${c} ${o.dim(truncate(i,Math.max(8,a-8)))}`),r&&(r.diagnostics.discoveryErrors>0||r.diagnostics.discoveryWarnings>0)){let e=[];r.diagnostics.discoveryErrors>0&&e.push(o.red(`${r.diagnostics.discoveryErrors} error${plural(r.diagnostics.discoveryErrors)}`)),r.diagnostics.discoveryWarnings>0&&e.push(o.yellow(`${r.diagnostics.discoveryWarnings} warning${plural(r.diagnostics.discoveryWarnings)}`)),s.push(` ${o.dim(n.glyph.warning)} ${e.join(o.dim(` · `))}`)}return t.tip!==void 0&&s.push(` ${o.dim(truncate(t.tip,Math.max(8,a-2)))}`),s}function plural(e){return e===1?``:`s`}export{AGENT_HEADER_TIPS,buildAgentHeader,pickAgentHeaderTip};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Every supported captured-output filter, in CLI help order. */
|
|
2
|
+
export declare const LOG_DISPLAY_MODES: readonly ["all", "stderr", "sandbox", "none"];
|
|
3
|
+
export type LogDisplayMode = (typeof LOG_DISPLAY_MODES)[number];
|
|
4
|
+
/**
|
|
5
|
+
* Order the dev TUI's Ctrl+L shortcut steps through {@link LogDisplayMode}
|
|
6
|
+
* values, starting from `none`: each press reveals the next view and wraps
|
|
7
|
+
* back to `none`.
|
|
8
|
+
*/
|
|
9
|
+
export declare const LOG_DISPLAY_MODE_CYCLE: readonly ["none", "all", "stderr", "sandbox"];
|
|
10
|
+
/** Parses one CLI or `/loglevel` argument into a supported display mode. */
|
|
11
|
+
export declare function parseLogDisplayMode(value: string): LogDisplayMode | undefined;
|
|
12
|
+
/** The mode after `current` in the Ctrl+L cycle, wrapping at the end. */
|
|
13
|
+
export declare function nextLogDisplayMode(current: LogDisplayMode): LogDisplayMode;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const LOG_DISPLAY_MODES=[`all`,`stderr`,`sandbox`,`none`],LOG_DISPLAY_MODE_CYCLE=[`none`,`all`,`stderr`,`sandbox`];function parseLogDisplayMode(t){return LOG_DISPLAY_MODES.find(e=>e===t)}function nextLogDisplayMode(e){return LOG_DISPLAY_MODE_CYCLE[(LOG_DISPLAY_MODE_CYCLE.indexOf(e)+1)%LOG_DISPLAY_MODE_CYCLE.length]??`none`}export{LOG_DISPLAY_MODES,LOG_DISPLAY_MODE_CYCLE,nextLogDisplayMode,parseLogDisplayMode};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const PROMPT_COMMANDS=[{name:`help`,aliases:[],description:`Show available commands`,takesArgument:!1,build:()=>({type:`help`})},{name:`new`,aliases:[],description:`Start a fresh session`,takesArgument:!1,build:()=>({type:`new`})},{name:`model`,aliases:[],description:`Configure the agent's model and provider`,argumentHint:`[provider/model]`,takesArgument:!0,build:e=>({type:`extension`,name:`model`,argument:e})},{name:`loglevel`,aliases:[],description:`Show or hide captured stdout/stderr logs`,argumentHint:`[all|stderr|none]`,takesArgument:!0,build:e=>({type:`loglevel`,argument:e})},{name:`channels`,aliases:[],description:`Add chat channels to the agent`,takesArgument:!1,build:()=>({type:`extension`,name:`channels`,argument:``})},{name:`deploy`,aliases:[],description:`Deploy the agent to Vercel`,takesArgument:!1,build:()=>({type:`extension`,name:`deploy`,argument:``})},{name:`exit`,aliases:[`quit`],description:`Quit the TUI`,takesArgument:!1,build:()=>({type:`exit`})}];function parsePromptCommand(t){let n=t.trim();if(!n.startsWith(`/`))return null;for(let t of PROMPT_COMMANDS)for(let e of[t.name,...t.aliases]){let r=`/${e}`;if(n===r)return t.build(``);if(t.takesArgument&&n.startsWith(`${r} `))return t.build(n.slice(r.length).trim())}return null}function isPromptControlCommand(e){return parsePromptCommand(e)!==null}function formatPromptCommandHelp(){let t=PROMPT_COMMANDS.map(e=>{let t=e.argumentHint===void 0?``:` ${e.argumentHint}`,n=e.aliases.map(e=>` (/${e})`).join(``);return{invocation:`/${e.name}${t}${n}`,description:e.description}}),n=Math.max(...t.map(e=>e.invocation.length))+2;return t.map(e=>e.invocation.padEnd(n)+e.description).join(`
|
|
1
|
+
const PROMPT_COMMANDS=[{name:`help`,aliases:[],description:`Show available commands`,takesArgument:!1,build:()=>({type:`help`})},{name:`new`,aliases:[],description:`Start a fresh session`,takesArgument:!1,build:()=>({type:`new`})},{name:`model`,aliases:[],description:`Configure the agent's model and provider`,argumentHint:`[provider/model]`,takesArgument:!0,build:e=>({type:`extension`,name:`model`,argument:e})},{name:`loglevel`,aliases:[],description:`Show or hide captured stdout/stderr/sandbox logs`,argumentHint:`[all|stderr|sandbox|none]`,takesArgument:!0,build:e=>({type:`loglevel`,argument:e})},{name:`channels`,aliases:[],description:`Add chat channels to the agent`,takesArgument:!1,build:()=>({type:`extension`,name:`channels`,argument:``})},{name:`deploy`,aliases:[],description:`Deploy the agent to Vercel`,takesArgument:!1,build:()=>({type:`extension`,name:`deploy`,argument:``})},{name:`exit`,aliases:[`quit`],description:`Quit the TUI`,takesArgument:!1,build:()=>({type:`exit`})}];function parsePromptCommand(t){let n=t.trim();if(!n.startsWith(`/`))return null;for(let t of PROMPT_COMMANDS)for(let e of[t.name,...t.aliases]){let r=`/${e}`;if(n===r)return t.build(``);if(t.takesArgument&&n.startsWith(`${r} `))return t.build(n.slice(r.length).trim())}return null}function isPromptControlCommand(e){return parsePromptCommand(e)!==null}function formatPromptCommandHelp(){let t=PROMPT_COMMANDS.map(e=>{let t=e.argumentHint===void 0?``:` ${e.argumentHint}`,n=e.aliases.map(e=>` (/${e})`).join(``);return{invocation:`/${e.name}${t}${n}`,description:e.description}}),n=Math.max(...t.map(e=>e.invocation.length))+2;return t.map(e=>e.invocation.padEnd(n)+e.description).join(`
|
|
2
2
|
`)}export{PROMPT_COMMANDS,formatPromptCommandHelp,isPromptControlCommand,parsePromptCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{pickAgentHeaderTip}from"./agent-header.js";import{formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{failureKey,formatFailureDetail,formatFailureMessage,formatGatewayAuthFailureNotice,isAbortLikeError,isGatewayAuthFailure,isInterruptedError}from"./errors.js";import{BOOT_DETECTIONS,detectSetupIssues,formatSetupIssuesLine}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import{toErrorMessage}from"#shared/errors.js";import{isCurrentTurnBoundaryEvent}from"#client/index.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createDevelopmentRuntimeArtifactSessionRefresher}from"#services/dev-client.js";var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v=pickAgentHeaderTip();#y;#b=new Map;#x=new Map;#S=new Map;#C=new Map;#w=new Set;#T=!1;#E;constructor(e){if(this.#e=e.session,e.client!==void 0&&(this.#t=e.client),this.#n=createRenderer(e),this.#r=e.name??`Eve`,this.#i=e.tools??`full`,this.#a=e.reasoning??`full`,this.#o=e.subagents??`full`,this.#s=e.connectionAuth??`full`,this.#c=e.assistantResponseStats??`tokensPerSecond`,this.#l=e.contextSize,this.#u=e.formatTransportError??toErrorMessage,e.initialInput!==void 0&&(this.#m=e.initialInput),e.appRoot!==void 0){this.#p=e.appRoot;let t={appRoot:e.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};e.detectProjectIdentity!==void 0&&(t.detectIdentity=e.detectProjectIdentity),this.#_=createVercelStatusTracker(t)}e.promptCommandHandler!==void 0&&(this.#h=e.promptCommandHandler),this.#g=e.bootDetections??BOOT_DETECTIONS,e.serverUrl!==void 0&&(this.#f=e.serverUrl,this.#d=createDevelopmentRuntimeArtifactSessionRefresher({serverUrl:e.serverUrl}))}async#D(){let e=this.#f;if(e===void 0){await this.#M(void 0);return}let t;try{t=await this.#t?.info()}catch{t=void 0}this.#y=t;let n={name:this.#r,serverUrl:e};t!==void 0&&(n.info=t),this.#p!==void 0&&(n.tip=this.#v),this.#n.renderAgentHeader?.(n),await this.#M(t)}async run(){try{await this.#O()}finally{this.#E?.(),this.#E=void 0,this.#n.shutdown?.(),this.#_?.dispose()}}async#O(){let e=this.#r,r,i,a=!1,o=!1,s=this.#m;for(await this.#D(),this.#N(),this.#_?.refreshIdentity();;){if(!o){if(r==null){if(!this.#n.readPrompt){if(a)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let t={title:e};s!==void 0&&(t.initialDraft=s,s=void 0);try{r=await this.#A(t)}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let c=parsePromptCommand(r);if(c?.type===`exit`)return;if(c?.type===`new`){this.#k(),i=void 0,o=!1,r=void 0,this.#n.reset?.();continue}if(c?.type===`help`){this.#P(formatPromptCommandHelp()),i=void 0,o=!1,r=void 0;continue}if(c?.type===`loglevel`){this.#P(this.#F(c.argument)),i=void 0,o=!1,r=void 0;continue}if(c?.type===`extension`){try{let t=this.#h===void 0?{message:`/${c.name} is not available in this session.`}:await this.#h.handle(c,{renderer:this.#n,title:e});t?.message!==void 0&&this.#P(t.message),t?.vercelEffect!==void 0&&this.#_?.applyEffect(t.vercelEffect)}catch(e){if(isInterruptedError(e))return;throw e}i=void 0,r=void 0,o=!1;continue}a=!0}let c=await this.#j({prompt:o?void 0:r,inputResponses:i});try{await this.#n.renderStream(c,{title:e,submittedPrompt:r,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let t=c.turnState?.pendingApprovals??[],n=c.turnState?.pendingQuestions??[];if(t.length>0||n.length>0){let a=[];if(t.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let n of t){let t=await this.#n.readToolApproval(n,{title:e});a.push({requestId:n.approvalId,optionId:t.approved?`approve`:`deny`}),this.#b.delete(n.approvalId)}}if(n.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let t of n){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let i={requestId:t.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),a.push(i),this.#b.delete(t.requestId)}}o=!0,i=a,r=void 0;continue}c.turnState&&c.turnState.boundaryEvent===void 0&&(this.#T=!0)}catch(e){if(isInterruptedError(e))return;throw e}o=!1,i=void 0,r=void 0,this.#T&&(this.#T=!1,this.#k(),this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`))}}#k(){for(let e of this.#S.values())e.abort();this.#S.clear(),this.#x.clear(),this.#b.clear(),this.#C.clear(),this.#w.clear(),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}async#A(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#t,r=this.#d;if(n===void 0||r===void 0)return await t;let i=!1,a=!1,o,refresh=async()=>{if(!(i||a)){a=!0;try{this.#e=await r.refreshIdle({createSession:()=>n.session(),onRuntimeArtifactsChanged:()=>this.#I(),session:this.#e})}finally{a=!1}}},startRefresh=()=>{if(i||a)return;let e=refresh().finally(()=>{o===e&&(o=void 0)});o=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await t}finally{i=!0,clearInterval(s),await o}}async#j(e){let t=new AbortController,n={signal:t.signal};e.prompt!==void 0&&(n.message=e.prompt),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses);let r;try{let e=this.#t;e!==void 0&&this.#d!==void 0&&(this.#e=await this.#d.refresh({createSession:()=>e.session(),inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#I(),session:this.#e})),r=await this.#e.send(n)}catch(e){if(isInterruptedError(e))throw e;return this.#T=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}let i=createTurnState();return{abort:()=>t.abort(),events:eveEventsToTUIStream({events:r,pendingInputRequests:this.#b,subagentRuns:this.#x,turnState:i,onSubagentCalled:e=>this.#B(e),onSubagentCompleted:e=>this.#H(e),onConnectionAuthRequired:e=>this.#L(e),onConnectionAuthCompleted:e=>this.#R(e),onTerminalFailure:()=>{this.#T=!0},failureOverride:this.#p===void 0?void 0:e=>isGatewayAuthFailure(e)?formatGatewayAuthFailureNotice(e):void 0}),turnState:i}}async#M(e){if(this.#p===void 0||this.#n.renderSetupWarning===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e);let n=await detectSetupIssues(t,this.#g);n.length!==0&&this.#n.renderSetupWarning(formatSetupIssuesLine(n))}#N(){this.#p===void 0||this.#n.renderSandboxLog===void 0||this.#E===void 0&&(this.#E=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#P(e){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}#F(e){let t=this.#n;if(t.logDisplayMode===void 0||t.setLogDisplayMode===void 0)return`/loglevel is not available in this session.`;if(e===``)return`Logs: ${t.logDisplayMode()}. Use /loglevel all|stderr|none — logs stay buffered, so switching also hides or restores past lines.`;let n=parseLogDisplayMode(e);if(n===void 0)return`Unknown log level "${e}". Use all, stderr, or none.`;if(n===t.logDisplayMode())return`Logs already set to ${n}.`;switch(t.setLogDisplayMode(n),n){case`none`:return`Logs hidden. Output stays buffered — /loglevel all restores it.`;case`stderr`:return`Showing stderr logs only.`;case`all`:return`Showing all logs.`}}async#I(){let e=this.#y,t;try{t=await this.#t?.info()}catch{t=void 0}if(t!==void 0&&(this.#y=t,this.#f!==void 0)){let e={info:t,name:this.#r,serverUrl:this.#f};this.#p!==void 0&&(e.tip=this.#v),this.#n.renderAgentHeader?.(e)}(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#L(e){let t={name:e.data.name,description:e.data.description,state:`required`};e.data.authorization!==void 0&&(t.challenge=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),this.#C.set(e.data.name,t),this.#z(t)}#R(e){let t=this.#C.get(e.data.name)??{name:e.data.name,description:``,state:e.data.outcome};t.state=e.data.outcome,e.data.reason!==void 0&&(t.reason=e.data.reason),this.#C.set(e.data.name,t),this.#w.delete(e.data.name),this.#z(t),this.#n.setConnectionAuthPendingCount?.(this.#w.size)}#z(e){let t={name:e.name,description:e.description,state:e.state};e.challenge!==void 0&&(t.challenge=e.challenge),e.reason!==void 0&&(t.reason=e.reason),this.#n.upsertConnectionAuth?.(t)}#B(e){let t=e.data.callId;if(this.#S.has(t))return;let n=this.#t;if(!n)return;let r=new AbortController;this.#S.set(t,r),(async()=>{try{let i=n.session({sessionId:e.data.childSessionId,streamIndex:0}).stream({signal:r.signal});for await(let e of i)if(r.signal.aborted||(this.#U(t,e),isCurrentTurnBoundaryEvent(e)))break}catch(e){if(!isAbortLikeError(e)){let n=toErrorMessage(e),r=this.#x.get(t);if(r){let{key:e,step:i}=openCurrentSubagentSection(r);i.message=i.message?`${i.message}\n\nstream error: ${n}`:`stream error: ${n}`,i.finalized=!0,r.currentSectionKey=null,this.#n.upsertSubagentStep?.({callId:t,subagentName:r.name,sectionKey:e,reasoning:i.reasoning,message:i.message,finalized:!0})}}}finally{this.#S.delete(t)}})()}#V(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={"approval-requested":0,executing:1,done:2,failed:2};e[n.status]>e[r.status]&&(r.status=n.status),r.input=n.input}else t.tools.set(n.childCallId,i);this.#n.markChildToolCallId?.(n.childCallId),this.#n.upsertSubagentTool?.({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#H(e){let t=this.#x.get(e);if(t){for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#n.upsertSubagentStep?.({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null}}#U(e,t){let n=this.#x.get(e);if(!n)return;let r=this.#n,emit=(t,i)=>{r.upsertSubagentStep?.({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent();break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#V(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#V(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;t.data.status===`failed`?(a.status=`failed`,a.errorText=formatActionResultError(t)):(a.status=`done`,a.output=i.output);let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r.upsertSubagentTool?.(o);break}default:break}}};function createRenderer(e){return e.renderer?e.renderer:new TerminalRenderer({tools:e.tools,reasoning:e.reasoning,subagents:e.subagents,connectionAuth:e.connectionAuth,assistantResponseStats:e.assistantResponseStats,contextSize:e.contextSize,logs:e.logs,input:e.userInput,output:e.screen})}function parseLogDisplayMode(e){return e===`all`||e===`stderr`||e===`none`?e:void 0}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id,r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,subagentRuns:r,turnState:i,onSubagentCalled:a,onSubagentCompleted:o,onConnectionAuthRequired:s,onConnectionAuthCompleted:c,onTerminalFailure:l,failureOverride:u}=e,d=new Map,f=new Map,p=0,m=new Set,h=new Set,g=new Set,_=new Set,v=!1,y=!1,b;for await(let e of t)if(!(y&&isPostTurnVisibleEvent(e)))switch(e.type){case`session.started`:case`turn.started`:case`message.received`:break;case`step.started`:p+=1,yield{type:`step-start`};break;case`step.completed`:{let t=e;b=t.data.usage,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`step-finish`,usage:t.data.usage};break}case`message.appended`:{let t=e,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(d,n),i=t.data.messageSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`message.completed`:{let t=textPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(d,t),r=e.data.message;if(n.completed){if(r===null||r===n.text||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p,yield{type:`assistant-complete`,id:partGenerationId(t,n.generation),text:r};break}let i=partGenerationId(t,n.generation);if(r!==null){if(n.text.length===0)n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let e=r.slice(n.text.length);e.length>0&&(yield{type:`assistant-delta`,id:i,delta:e}),n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i}}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let t=e,n=reasoningPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(f,n),i=t.data.reasoningSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`reasoning-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`reasoning.completed`:{let t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(f,t),r=e.data.reasoning;if(n.completed){if(r.length===0||r===n.text||n.text.startsWith(r)||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}let i=partGenerationId(t,n.generation);if(n.text.length===0&&r.length>0)n.text=r,yield{type:`reasoning-delta`,id:i,delta:r};else if(r.length>0&&!r.startsWith(n.text))break;n.completed=!0,n.completedEpoch=p,yield{type:`reasoning-complete`,id:i};break}case`actions.requested`:{let t=e.data,n=t.actions.filter(e=>e.kind===`tool-call`);if(n.length===0)break;let r=toolBatchKey(`actions.requested`,t.turnId,t.stepIndex,n);if(g.has(r)){for(let e of n)m.has(e.callId)||h.add(e.callId);break}g.add(r);for(let e of n)m.has(e.callId)||(m.add(e.callId),yield{type:`tool-call`,toolCallId:e.callId,toolName:e.toolName,input:e.input});break}case`input.requested`:{let t=e.data,r=t.requests.filter(e=>e.action.kind===`tool-call`);if(r.length===0)break;let a=inputRequestBatchKey(t.turnId,t.stepIndex,r);if(g.has(a)){for(let e of r)m.has(e.action.callId)||h.add(e.action.callId);break}g.add(a);for(let e of r){let t=e.action.callId;if(m.has(t)||(m.add(t),yield{type:`tool-call`,toolCallId:t,toolName:e.action.toolName,input:e.action.input}),n.set(e.requestId,e),isQuestionRequest(e)){upsertPendingQuestion(i,e);continue}upsertPendingApproval(i,e),yield{type:`tool-approval-request`,approvalId:e.requestId,toolCallId:t}}break}case`action.result`:{let t=e;if(t.data.result.kind!==`tool-result`)break;let n=t.data.result.callId;if(h.has(n)||!m.has(n))break;t.data.status===`failed`?yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)}:yield{type:`tool-result`,toolCallId:n,output:t.data.result.output};break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,_,u);t&&(yield t);break}case`session.failed`:{i.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,_,u);t&&(yield t),i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b},v=!0;return}case`session.waiting`:case`session.completed`:i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b},v=!0;return;case`turn.completed`:y=!0,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p);break;case`subagent.called`:{let t=e;if(!r.has(t.data.callId))r.set(t.data.callId,{name:t.data.name,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map});else{let e=r.get(t.data.callId);e&&(e.name=t.data.name)}a?.(t);break}case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:o?.(e.data.callId);break;case`authorization.required`:s?.(e);break;case`authorization.completed`:c?.(e);break;default:break}v||(yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{pendingApprovals:[],pendingQuestions:[],sawSessionFailure:!1}}function upsertPendingApproval(e,t){let n=toAgentTUIToolApprovalRequest(t),r=e.pendingApprovals.findIndex(e=>e.approvalId===n.approvalId);r===-1?e.pendingApprovals.push(n):e.pendingApprovals[r]=n}function toAgentTUIToolApprovalRequest(e){return{approvalId:e.requestId,toolCallId:e.action.callId,toolName:e.action.toolName,input:e.action.input}}function upsertPendingQuestion(e,t){let n=e.pendingQuestions.findIndex(e=>e.requestId===t.requestId);n===-1?e.pendingQuestions.push(t):e.pendingQuestions[n]=t}function textPartId(e,t){return`text:${e}:${t}`}function reasoningPartId(e,t){return`reasoning:${e}:${t}`}function partStateFor(e,t){let n=e.get(t);return n===void 0&&(n={generation:0,text:``,completed:!1,completedEpoch:0},e.set(t,n)),n}function partGenerationId(e,t){return t===0?e:`${e}#${t}`}function*closeOpenParts(e,t,n){for(let[r,i]of e)i.completed||i.text.length===0||(i.completed=!0,i.completedEpoch=n,yield{type:t,id:partGenerationId(r,i.generation)})}function isPostTurnVisibleEvent(e){switch(e.type){case`actions.requested`:case`authorization.completed`:case`authorization.required`:case`input.requested`:case`message.appended`:case`message.completed`:case`reasoning.appended`:case`reasoning.completed`:case`result.completed`:case`step.completed`:case`step.failed`:case`step.started`:case`subagent.called`:case`subagent.completed`:case`subagent.event`:case`subagent.started`:case`turn.completed`:case`turn.failed`:return!0;default:return!1}}function toolBatchKey(e,t,n,r){return`${e}:${t}:${String(n)}:${stableStringify(r.map(e=>({input:e.input,toolName:e.toolName})))}`}function inputRequestBatchKey(e,t,n){return toolBatchKey(`input.requested`,e,t,n.map(e=>({input:e.action.input,toolName:e.action.toolName})))}function stableStringify(e){return JSON.stringify(toStableJson(e))??`undefined`}function toStableJson(e,t=new WeakSet){if(typeof e!=`object`||!e)return e;if(t.has(e))return`[Circular]`;if(t.add(e),Array.isArray(e))return e.map(e=>toStableJson(e,t));let n=e,r={};for(let e of Object.keys(n).sort())r[e]=toStableJson(n[e],t);return r}function formatActionResultError(e){if(e.data.error?.message)return e.data.error.message;let t=e.data.result.output;if(typeof t==`string`)return t;try{return JSON.stringify(t)}catch{return`Tool execution failed.`}}function toFailureEvent(e,t,n){let o=failureKey(e);if(t.has(o))return;t.add(o);let s=n?.(e),c={type:`error`,errorText:s??formatFailureMessage(e)};if(s!==void 0)return c;let l=formatFailureDetail(e);return l!==void 0&&(c.detail=l),c}function isQuestionRequest(e){return e.display===`select`||e.display===`text`?!0:e.display===`confirmation`?!1:e.options!==void 0&&e.options.length>0}function toAgentTUIInputQuestion(e){let t=e.display===`text`?`text`:e.display===`select`||e.options!==void 0&&e.options.length>0?`select`:`text`,n={requestId:e.requestId,prompt:e.prompt,display:t};return e.options!==void 0&&(n.options=e.options.map(e=>{let t={id:e.id,label:e.label};return e.description!==void 0&&(t.description=e.description),e.style!==void 0&&(t.style=e.style),t})),e.allowFreeform!==void 0&&(n.allowFreeform=e.allowFreeform),n}function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{EveTUIRunner,parsePromptCommand};
|
|
1
|
+
import{pickAgentHeaderTip}from"./agent-header.js";import{formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{failureKey,formatFailureDetail,formatFailureMessage,formatGatewayAuthFailureNotice,isAbortLikeError,isGatewayAuthFailure,isInterruptedError}from"./errors.js";import{parseLogDisplayMode}from"./log-display-mode.js";import{BOOT_DETECTIONS,detectSetupIssues,formatSetupIssuesLine}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import{toErrorMessage}from"#shared/errors.js";import{isCurrentTurnBoundaryEvent}from"#client/index.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createDevelopmentRuntimeArtifactSessionRefresher}from"#services/dev-client.js";var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v=pickAgentHeaderTip();#y;#b=new Map;#x=new Map;#S=new Map;#C=new Map;#w=new Set;#T=!1;#E;constructor(e){if(this.#e=e.session,e.client!==void 0&&(this.#t=e.client),this.#n=createRenderer(e),this.#r=e.name??`Eve`,this.#i=e.tools??`full`,this.#a=e.reasoning??`full`,this.#o=e.subagents??`full`,this.#s=e.connectionAuth??`full`,this.#c=e.assistantResponseStats??`tokensPerSecond`,this.#l=e.contextSize,this.#u=e.formatTransportError??toErrorMessage,e.initialInput!==void 0&&(this.#m=e.initialInput),e.appRoot!==void 0){this.#p=e.appRoot;let t={appRoot:e.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};e.detectProjectIdentity!==void 0&&(t.detectIdentity=e.detectProjectIdentity),this.#_=createVercelStatusTracker(t)}e.promptCommandHandler!==void 0&&(this.#h=e.promptCommandHandler),this.#g=e.bootDetections??BOOT_DETECTIONS,e.serverUrl!==void 0&&(this.#f=e.serverUrl,this.#d=createDevelopmentRuntimeArtifactSessionRefresher({serverUrl:e.serverUrl}))}async#D(){let e=this.#f;if(e===void 0){await this.#M(void 0);return}let t;try{t=await this.#t?.info()}catch{t=void 0}this.#y=t;let n={name:this.#r,serverUrl:e};t!==void 0&&(n.info=t),this.#p!==void 0&&(n.tip=this.#v),this.#n.renderAgentHeader?.(n),await this.#M(t)}async run(){try{await this.#O()}finally{this.#E?.(),this.#E=void 0,this.#n.shutdown?.(),this.#_?.dispose()}}async#O(){let e=this.#r,r,i,a=!1,o=!1,s=this.#m;for(await this.#D(),this.#N(),this.#_?.refreshIdentity();;){if(!o){if(r==null){if(!this.#n.readPrompt){if(a)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let t={title:e};s!==void 0&&(t.initialDraft=s,s=void 0);try{r=await this.#A(t)}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let c=parsePromptCommand(r);if(c?.type===`exit`)return;if(c?.type===`new`){this.#k(),i=void 0,o=!1,r=void 0,this.#n.reset?.();continue}if(c?.type===`help`){this.#P(formatPromptCommandHelp()),i=void 0,o=!1,r=void 0;continue}if(c?.type===`loglevel`){this.#P(this.#F(c.argument)),i=void 0,o=!1,r=void 0;continue}if(c?.type===`extension`){try{let t=this.#h===void 0?{message:`/${c.name} is not available in this session.`}:await this.#h.handle(c,{renderer:this.#n,title:e});t?.message!==void 0&&this.#P(t.message),t?.vercelEffect!==void 0&&this.#_?.applyEffect(t.vercelEffect)}catch(e){if(isInterruptedError(e))return;throw e}i=void 0,r=void 0,o=!1;continue}a=!0}let c=await this.#j({prompt:o?void 0:r,inputResponses:i});try{await this.#n.renderStream(c,{title:e,submittedPrompt:r,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let t=c.turnState?.pendingApprovals??[],n=c.turnState?.pendingQuestions??[];if(t.length>0||n.length>0){let a=[];if(t.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let n of t){let t=await this.#n.readToolApproval(n,{title:e});a.push({requestId:n.approvalId,optionId:t.approved?`approve`:`deny`}),this.#b.delete(n.approvalId)}}if(n.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let t of n){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let i={requestId:t.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),a.push(i),this.#b.delete(t.requestId)}}o=!0,i=a,r=void 0;continue}c.turnState&&c.turnState.boundaryEvent===void 0&&(this.#T=!0)}catch(e){if(isInterruptedError(e))return;throw e}o=!1,i=void 0,r=void 0,this.#T&&(this.#T=!1,this.#k(),this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`))}}#k(){for(let e of this.#S.values())e.abort();this.#S.clear(),this.#x.clear(),this.#b.clear(),this.#C.clear(),this.#w.clear(),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}async#A(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#t,r=this.#d;if(n===void 0||r===void 0)return await t;let i=!1,a=!1,o,refresh=async()=>{if(!(i||a)){a=!0;try{this.#e=await r.refreshIdle({createSession:()=>n.session(),onRuntimeArtifactsChanged:()=>this.#I(),session:this.#e})}finally{a=!1}}},startRefresh=()=>{if(i||a)return;let e=refresh().finally(()=>{o===e&&(o=void 0)});o=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await t}finally{i=!0,clearInterval(s),await o}}async#j(e){let t=new AbortController,n={signal:t.signal};e.prompt!==void 0&&(n.message=e.prompt),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses);let r;try{let e=this.#t;e!==void 0&&this.#d!==void 0&&(this.#e=await this.#d.refresh({createSession:()=>e.session(),inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#I(),session:this.#e})),r=await this.#e.send(n)}catch(e){if(isInterruptedError(e))throw e;return this.#T=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}let i=createTurnState();return{abort:()=>t.abort(),events:eveEventsToTUIStream({events:r,pendingInputRequests:this.#b,subagentRuns:this.#x,turnState:i,onSubagentCalled:e=>this.#B(e),onSubagentCompleted:e=>this.#H(e),onConnectionAuthRequired:e=>this.#L(e),onConnectionAuthCompleted:e=>this.#R(e),onTerminalFailure:()=>{this.#T=!0},failureOverride:this.#p===void 0?void 0:e=>isGatewayAuthFailure(e)?formatGatewayAuthFailureNotice(e):void 0}),turnState:i}}async#M(e){if(this.#p===void 0||this.#n.renderSetupWarning===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e);let n=await detectSetupIssues(t,this.#g);n.length!==0&&this.#n.renderSetupWarning(formatSetupIssuesLine(n))}#N(){this.#p===void 0||this.#n.renderSandboxLog===void 0||this.#E===void 0&&(this.#E=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#P(e){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}#F(e){let t=this.#n;if(t.logDisplayMode===void 0||t.setLogDisplayMode===void 0)return`/loglevel is not available in this session.`;if(e===``)return`Logs: ${t.logDisplayMode()}. Use /loglevel all|stderr|sandbox|none — logs stay buffered, so switching also hides or restores past lines.`;let n=parseLogDisplayMode(e);if(n===void 0)return`Unknown log level "${e}". Use all, stderr, sandbox, or none.`;if(n===t.logDisplayMode())return`Logs already set to ${n}.`;switch(t.setLogDisplayMode(n),n){case`none`:return`Logs hidden. Output stays buffered — /loglevel all restores it.`;case`stderr`:return`Showing stderr logs only.`;case`sandbox`:return`Showing sandbox logs only.`;case`all`:return`Showing all logs.`}}async#I(){let e=this.#y,t;try{t=await this.#t?.info()}catch{t=void 0}if(t!==void 0&&(this.#y=t,this.#f!==void 0)){let e={info:t,name:this.#r,serverUrl:this.#f};this.#p!==void 0&&(e.tip=this.#v),this.#n.renderAgentHeader?.(e)}(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#L(e){let t={name:e.data.name,description:e.data.description,state:`required`};e.data.authorization!==void 0&&(t.challenge=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),this.#C.set(e.data.name,t),this.#z(t)}#R(e){let t=this.#C.get(e.data.name)??{name:e.data.name,description:``,state:e.data.outcome};t.state=e.data.outcome,e.data.reason!==void 0&&(t.reason=e.data.reason),this.#C.set(e.data.name,t),this.#w.delete(e.data.name),this.#z(t),this.#n.setConnectionAuthPendingCount?.(this.#w.size)}#z(e){let t={name:e.name,description:e.description,state:e.state};e.challenge!==void 0&&(t.challenge=e.challenge),e.reason!==void 0&&(t.reason=e.reason),this.#n.upsertConnectionAuth?.(t)}#B(e){let t=e.data.callId;if(this.#S.has(t))return;let n=this.#t;if(!n)return;let r=new AbortController;this.#S.set(t,r),(async()=>{try{let i=n.session({sessionId:e.data.childSessionId,streamIndex:0}).stream({signal:r.signal});for await(let e of i)if(r.signal.aborted||(this.#U(t,e),isCurrentTurnBoundaryEvent(e)))break}catch(e){if(!isAbortLikeError(e)){let n=toErrorMessage(e),r=this.#x.get(t);if(r){let{key:e,step:i}=openCurrentSubagentSection(r);i.message=i.message?`${i.message}\n\nstream error: ${n}`:`stream error: ${n}`,i.finalized=!0,r.currentSectionKey=null,this.#n.upsertSubagentStep?.({callId:t,subagentName:r.name,sectionKey:e,reasoning:i.reasoning,message:i.message,finalized:!0})}}}finally{this.#S.delete(t)}})()}#V(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={"approval-requested":0,executing:1,done:2,failed:2};e[n.status]>e[r.status]&&(r.status=n.status),r.input=n.input}else t.tools.set(n.childCallId,i);this.#n.markChildToolCallId?.(n.childCallId),this.#n.upsertSubagentTool?.({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#H(e){let t=this.#x.get(e);if(t){for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#n.upsertSubagentStep?.({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null}}#U(e,t){let n=this.#x.get(e);if(!n)return;let r=this.#n,emit=(t,i)=>{r.upsertSubagentStep?.({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent();break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#V(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#V(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;t.data.status===`failed`?(a.status=`failed`,a.errorText=formatActionResultError(t)):(a.status=`done`,a.output=i.output);let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r.upsertSubagentTool?.(o);break}default:break}}};function createRenderer(e){return e.renderer?e.renderer:new TerminalRenderer({tools:e.tools,reasoning:e.reasoning,subagents:e.subagents,connectionAuth:e.connectionAuth,assistantResponseStats:e.assistantResponseStats,contextSize:e.contextSize,logs:e.logs,input:e.userInput,output:e.screen})}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id,r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,subagentRuns:r,turnState:i,onSubagentCalled:a,onSubagentCompleted:o,onConnectionAuthRequired:s,onConnectionAuthCompleted:c,onTerminalFailure:l,failureOverride:u}=e,d=new Map,f=new Map,p=0,m=new Set,h=new Set,g=new Set,_=new Set,v=!1,y=!1,b;for await(let e of t)if(!(y&&isPostTurnVisibleEvent(e)))switch(e.type){case`session.started`:case`turn.started`:case`message.received`:break;case`step.started`:p+=1,yield{type:`step-start`};break;case`step.completed`:{let t=e;b=t.data.usage,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`step-finish`,usage:t.data.usage};break}case`message.appended`:{let t=e,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(d,n),i=t.data.messageSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`message.completed`:{let t=textPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(d,t),r=e.data.message;if(n.completed){if(r===null||r===n.text||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p,yield{type:`assistant-complete`,id:partGenerationId(t,n.generation),text:r};break}let i=partGenerationId(t,n.generation);if(r!==null){if(n.text.length===0)n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let e=r.slice(n.text.length);e.length>0&&(yield{type:`assistant-delta`,id:i,delta:e}),n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i}}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let t=e,n=reasoningPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(f,n),i=t.data.reasoningSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`reasoning-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`reasoning.completed`:{let t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(f,t),r=e.data.reasoning;if(n.completed){if(r.length===0||r===n.text||n.text.startsWith(r)||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}let i=partGenerationId(t,n.generation);if(n.text.length===0&&r.length>0)n.text=r,yield{type:`reasoning-delta`,id:i,delta:r};else if(r.length>0&&!r.startsWith(n.text))break;n.completed=!0,n.completedEpoch=p,yield{type:`reasoning-complete`,id:i};break}case`actions.requested`:{let t=e.data,n=t.actions.filter(e=>e.kind===`tool-call`);if(n.length===0)break;let r=toolBatchKey(`actions.requested`,t.turnId,t.stepIndex,n);if(g.has(r)){for(let e of n)m.has(e.callId)||h.add(e.callId);break}g.add(r);for(let e of n)m.has(e.callId)||(m.add(e.callId),yield{type:`tool-call`,toolCallId:e.callId,toolName:e.toolName,input:e.input});break}case`input.requested`:{let t=e.data,r=t.requests.filter(e=>e.action.kind===`tool-call`);if(r.length===0)break;let a=inputRequestBatchKey(t.turnId,t.stepIndex,r);if(g.has(a)){for(let e of r)m.has(e.action.callId)||h.add(e.action.callId);break}g.add(a);for(let e of r){let t=e.action.callId;if(m.has(t)||(m.add(t),yield{type:`tool-call`,toolCallId:t,toolName:e.action.toolName,input:e.action.input}),n.set(e.requestId,e),isQuestionRequest(e)){upsertPendingQuestion(i,e);continue}upsertPendingApproval(i,e),yield{type:`tool-approval-request`,approvalId:e.requestId,toolCallId:t}}break}case`action.result`:{let t=e;if(t.data.result.kind!==`tool-result`)break;let n=t.data.result.callId;if(h.has(n)||!m.has(n))break;t.data.status===`failed`?yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)}:yield{type:`tool-result`,toolCallId:n,output:t.data.result.output};break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,_,u);t&&(yield t);break}case`session.failed`:{i.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,_,u);t&&(yield t),i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b},v=!0;return}case`session.waiting`:case`session.completed`:i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b},v=!0;return;case`turn.completed`:y=!0,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p);break;case`subagent.called`:{let t=e;if(!r.has(t.data.callId))r.set(t.data.callId,{name:t.data.name,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map});else{let e=r.get(t.data.callId);e&&(e.name=t.data.name)}a?.(t);break}case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:o?.(e.data.callId);break;case`authorization.required`:s?.(e);break;case`authorization.completed`:c?.(e);break;default:break}v||(yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{pendingApprovals:[],pendingQuestions:[],sawSessionFailure:!1}}function upsertPendingApproval(e,t){let n=toAgentTUIToolApprovalRequest(t),r=e.pendingApprovals.findIndex(e=>e.approvalId===n.approvalId);r===-1?e.pendingApprovals.push(n):e.pendingApprovals[r]=n}function toAgentTUIToolApprovalRequest(e){return{approvalId:e.requestId,toolCallId:e.action.callId,toolName:e.action.toolName,input:e.action.input}}function upsertPendingQuestion(e,t){let n=e.pendingQuestions.findIndex(e=>e.requestId===t.requestId);n===-1?e.pendingQuestions.push(t):e.pendingQuestions[n]=t}function textPartId(e,t){return`text:${e}:${t}`}function reasoningPartId(e,t){return`reasoning:${e}:${t}`}function partStateFor(e,t){let n=e.get(t);return n===void 0&&(n={generation:0,text:``,completed:!1,completedEpoch:0},e.set(t,n)),n}function partGenerationId(e,t){return t===0?e:`${e}#${t}`}function*closeOpenParts(e,t,n){for(let[r,i]of e)i.completed||i.text.length===0||(i.completed=!0,i.completedEpoch=n,yield{type:t,id:partGenerationId(r,i.generation)})}function isPostTurnVisibleEvent(e){switch(e.type){case`actions.requested`:case`authorization.completed`:case`authorization.required`:case`input.requested`:case`message.appended`:case`message.completed`:case`reasoning.appended`:case`reasoning.completed`:case`result.completed`:case`step.completed`:case`step.failed`:case`step.started`:case`subagent.called`:case`subagent.completed`:case`subagent.event`:case`subagent.started`:case`turn.completed`:case`turn.failed`:return!0;default:return!1}}function toolBatchKey(e,t,n,r){return`${e}:${t}:${String(n)}:${stableStringify(r.map(e=>({input:e.input,toolName:e.toolName})))}`}function inputRequestBatchKey(e,t,n){return toolBatchKey(`input.requested`,e,t,n.map(e=>({input:e.action.input,toolName:e.action.toolName})))}function stableStringify(e){return JSON.stringify(toStableJson(e))??`undefined`}function toStableJson(e,t=new WeakSet){if(typeof e!=`object`||!e)return e;if(t.has(e))return`[Circular]`;if(t.add(e),Array.isArray(e))return e.map(e=>toStableJson(e,t));let n=e,r={};for(let e of Object.keys(n).sort())r[e]=toStableJson(n[e],t);return r}function formatActionResultError(e){if(e.data.error?.message)return e.data.error.message;let t=e.data.result.output;if(typeof t==`string`)return t;try{return JSON.stringify(t)}catch{return`Tool execution failed.`}}function toFailureEvent(e,t,n){let o=failureKey(e);if(t.has(o))return;t.add(o);let s=n?.(e),c={type:`error`,errorText:s??formatFailureMessage(e)};if(s!==void 0)return c;let l=formatFailureDetail(e);return l!==void 0&&(c.detail=l),c}function isQuestionRequest(e){return e.display===`select`||e.display===`text`?!0:e.display===`confirmation`?!1:e.options!==void 0&&e.options.length>0}function toAgentTUIInputQuestion(e){let t=e.display===`text`?`text`:e.display===`select`||e.options!==void 0&&e.options.length>0?`select`:`text`,n={requestId:e.requestId,prompt:e.prompt,display:t};return e.options!==void 0&&(n.options=e.options.map(e=>{let t={id:e.id,label:e.label};return e.description!==void 0&&(t.description=e.description),e.style!==void 0&&(t.style=e.style),t})),e.allowFreeform!==void 0&&(n.allowFreeform=e.allowFreeform),n}function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{EveTUIRunner,parsePromptCommand};
|
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import type { Theme } from "./theme.js";
|
|
2
|
+
import type { LogDisplayMode } from "./log-display-mode.js";
|
|
2
3
|
import type { VercelStatusSnapshot } from "./vercel-status.js";
|
|
3
4
|
import type { ModelEndpointStatus } from "#shared/model-endpoint-status.js";
|
|
4
5
|
export interface StatusLineInput {
|
|
5
6
|
/** Resolved model slug, e.g. "anthropic/claude-sonnet-4-6"; absent when `/eve/v1/info` failed. */
|
|
6
7
|
model?: string;
|
|
7
|
-
/** Preformatted token-flow segment (formatTokenFlow output), e.g.
|
|
8
|
+
/** Preformatted token-flow segment (formatTokenFlow output), e.g. `↑ 394.4K ↓ 4.3K`. */
|
|
8
9
|
tokens?: string;
|
|
10
|
+
/**
|
|
11
|
+
* Transient dev-TUI log-display mode shown after a Ctrl+L cycle, e.g.
|
|
12
|
+
* `sandbox`. Rendered as a prominent leading `logs: <mode>` segment that
|
|
13
|
+
* survives width degradation and can stand alone; absent once the hint times
|
|
14
|
+
* out.
|
|
15
|
+
*/
|
|
16
|
+
logLevel?: LogDisplayMode;
|
|
9
17
|
/** Model endpoint readiness: external, or AI Gateway connected/not-connected. */
|
|
10
18
|
endpoint?: ModelEndpointStatus;
|
|
11
19
|
/** Workspace-scoped Vercel state; identity absent while unlinked or still resolving. */
|
|
@@ -24,8 +32,9 @@ export interface StatusLineInput {
|
|
|
24
32
|
* credential. Everything else renders dim except the yellow action signals (a
|
|
25
33
|
* pending deploy, the not-connected gateway). On narrow widths segments degrade
|
|
26
34
|
* in order, the endpoint first and then the model, keeping tokens and the
|
|
27
|
-
* pending-deploy marker longest.
|
|
28
|
-
*
|
|
29
|
-
*
|
|
35
|
+
* pending-deploy marker longest. A transient `logs: <mode>` segment from a
|
|
36
|
+
* Ctrl+L cycle leads the row when present and is kept longest of all. Segments
|
|
37
|
+
* stay recoverable from the agent header in scrollback. Returns undefined when
|
|
38
|
+
* no segment has content so callers skip the row.
|
|
30
39
|
*/
|
|
31
40
|
export declare function buildStatusLine(input: StatusLineInput): string | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sliceVisible,visibleLength}from"./terminal-text.js";function buildStatusLine(t){let{theme:n,width:r}=t,i=n.colors,a=t.model===void 0?void 0:i.dim(t.model),
|
|
1
|
+
import{sliceVisible,visibleLength}from"./terminal-text.js";function buildStatusLine(t){let{theme:n,width:r}=t,i=n.colors,a=t.logLevel===void 0?void 0:i.cyan(`logs: ${t.logLevel}`),o=t.model===void 0?void 0:i.dim(t.model),s=t.tokens===void 0?void 0:i.dim(t.tokens),c=t.vercel?.pendingDeploy?i.yellow(`/deploy pending`):void 0,l=t.vercel?.identity?.projectName,u=t.endpoint===void 0?void 0:t.endpoint.kind===`external`?i.dim(`External endpoint`):t.endpoint.connected?i.dim(l===void 0?`AI Gateway`:`AI Gateway (${l})`):i.yellow(`${n.glyph.warning} AI Gateway`),d=` ${i.dim(n.glyph.dot)} `,compose=e=>e.filter(e=>e!==void 0).join(d),f=[compose([a,o,s,u,c]),compose([a,o,s,c]),compose([a,s,c]),compose([a])];if(f[0].length!==0){for(let e of f)if(e.length>0&&visibleLength(e)<=r)return e;return sliceVisible(f.findLast(e=>e.length>0),r)}}export{buildStatusLine};
|
|
@@ -77,7 +77,7 @@ export declare function takeUntil<T>(source: AsyncIterable<T>, stop: Promise<voi
|
|
|
77
77
|
/** `394.4K`-style compact count: plain below 1000, then K/M with one trimmed decimal. */
|
|
78
78
|
export declare function formatCompactTokenCount(count: number): string;
|
|
79
79
|
/**
|
|
80
|
-
* The status line's token-flow segment:
|
|
80
|
+
* The status line's token-flow segment: `↑ 394.4K ↓ 4.3K`, input (prompt)
|
|
81
81
|
* tokens up, output tokens down, both from the latest usage report. A known
|
|
82
82
|
* `--context-size` appends the context-fill percentage of the input side.
|
|
83
83
|
*/
|
|
@@ -86,7 +86,6 @@ export declare function formatTokenFlow(flow: {
|
|
|
86
86
|
outputTokens: number;
|
|
87
87
|
contextSize?: number;
|
|
88
88
|
}, glyph: {
|
|
89
|
-
tokens: string;
|
|
90
89
|
arrowUp: string;
|
|
91
90
|
arrowDown: string;
|
|
92
91
|
}): string;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
const CSI_FINAL=/[\u0040-\u007e]/u;function stripPromptControlCharacters(e){let t=``;for(let n of e)n>=` `&&n!==``&&(t+=n);return t}function nextKey(t){let n=t[0];if(n===void 0)return{consumed:0,incomplete:!0};if(n===`\x1B`){if(t.length===1)return{consumed:0,incomplete:!0};let n=t[1];if(n===`O`)return t.length<3?{consumed:0,incomplete:!0}:{key:parseKey(Buffer.from(t.slice(0,3))),consumed:3};if(n===`[`){for(let n=2;n<t.length;n+=1)if(CSI_FINAL.test(t[n]))return{key:parseKey(Buffer.from(t.slice(0,n+1))),consumed:n+1};return{consumed:0,incomplete:!0}}return{key:{type:`escape`},consumed:1}}if(n<` `||n===``)return{key:parseKey(Buffer.from(n)),consumed:1};let r=1;for(;r<t.length;){let e=t[r];if(e===`\x1B`||e<` `||e===``)break;r+=1}return{key:parseKey(Buffer.from(t.slice(0,r))),consumed:r}}function parseKey(e){let t=e.toString(`utf8`);switch(t){case``:return{type:`ctrl-a`};case``:return{type:`ctrl-e`};case``:return{type:`ctrl-d`};case`\v`:return{type:`ctrl-k`};case`\f`:return{type:`ctrl-l`};case``:return{type:`ctrl-r`};case``:return{type:`ctrl-u`};case``:return{type:`ctrl-w`};case``:return{type:`ctrl-c`};case`\r`:case`
|
|
2
|
-
`:return{type:`enter`};case``:case`\b`:return{type:`backspace`};case`\x1B[A`:case`\x1BOA`:return{type:`up`};case`\x1B[B`:case`\x1BOB`:return{type:`down`};case`\x1B[C`:case`\x1BOC`:return{type:`right`};case`\x1B[D`:case`\x1BOD`:return{type:`left`};case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:return{type:`home`};case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:return{type:`end`};case`\x1B[3~`:return{type:`delete`};case` `:return{type:`tab`};case`\x1B`:return{type:`escape`};default:{let e=stripPromptControlCharacters(t);return e.length>0?{type:`character`,value:e}:{type:`ignore`}}}}async function*takeUntil(e,t){let n=e[Symbol.asyncIterator](),r=t.then(()=>({done:!0,value:void 0}));try{for(;;){let e=n.next();e.catch(()=>{});let t=await Promise.race([e,r]);if(t.done)break;yield t.value}}finally{n.return?.()?.catch(()=>{})}}function formatCompactTokenCount(e){if(e<1e3)return`${e}`;let t=e<1e6?e/1e3:e/1e6,n=e<1e6?`K`:`M`;return`${t.toFixed(1).replace(/\.0$/,``)}${n}`}function formatTokenFlow(e,t){let n=formatCompactTokenCount(e.inputTokens),r=formatCompactTokenCount(e.outputTokens),i=`${t.
|
|
2
|
+
`:return{type:`enter`};case``:case`\b`:return{type:`backspace`};case`\x1B[A`:case`\x1BOA`:return{type:`up`};case`\x1B[B`:case`\x1BOB`:return{type:`down`};case`\x1B[C`:case`\x1BOC`:return{type:`right`};case`\x1B[D`:case`\x1BOD`:return{type:`left`};case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:return{type:`home`};case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:return{type:`end`};case`\x1B[3~`:return{type:`delete`};case` `:return{type:`tab`};case`\x1B`:return{type:`escape`};default:{let e=stripPromptControlCharacters(t);return e.length>0?{type:`character`,value:e}:{type:`ignore`}}}}async function*takeUntil(e,t){let n=e[Symbol.asyncIterator](),r=t.then(()=>({done:!0,value:void 0}));try{for(;;){let e=n.next();e.catch(()=>{});let t=await Promise.race([e,r]);if(t.done)break;yield t.value}}finally{n.return?.()?.catch(()=>{})}}function formatCompactTokenCount(e){if(e<1e3)return`${e}`;let t=e<1e6?e/1e3:e/1e6,n=e<1e6?`K`:`M`;return`${t.toFixed(1).replace(/\.0$/,``)}${n}`}function formatTokenFlow(e,t){let n=formatCompactTokenCount(e.inputTokens),r=formatCompactTokenCount(e.outputTokens),i=`${t.arrowUp} ${n} ${t.arrowDown} ${r}`,a=formatContextPercentage(e.inputTokens,e.contextSize);return a==null?i:`${i} ${a}`}function formatContextPercentage(e,t){if(!(t==null||t<=0||!Number.isFinite(t)))return`${Math.round(e/t*100).toLocaleString()}%`}function formatAssistantResponseStats(e,t){if(t===`tokensPerSecond`)return formatTokensPerSecond(e.tokensPerSecond);if(e.outputTokens!=null)return`${e.outputTokens.toLocaleString()} output tokens`}function formatTokensPerSecond(e){if(e!=null)return`${formatNumber(e)} tok/s`}function formatNumber(e){return Number.isInteger(e)?e.toLocaleString():e.toLocaleString(void 0,{maximumFractionDigits:1})}export{formatAssistantResponseStats,formatCompactTokenCount,formatTokenFlow,nextKey,parseKey,stripPromptControlCharacters,takeUntil};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{sliceVisible,stripAnsi,stripTerminalControls,visibleLength}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,lineOf,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,nextKey,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{toErrorMessage}from"#shared/errors.js";import{initialSelectState,reduceSelect,selectValueAtCursor}from"#setup/cli/select-state.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e,t){return e?`Interrupted`:t?`Ready`:`Done`}const STATUS={processing:`Working…`,toolResults:`Reading results…`,streaming:`Responding…`,executingTools:`Running tools…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=[];#p=new Map;#m=new Set;#h=[];#g=new Set;#_=new Map;#v=new Set;#y;#b=!1;#x;#S=[];#C;#w=0;#T;#E=``;#D=0;#O
|
|
2
|
-
`);if(this.#b){t!==this.#x&&(this.#x=t,this.#
|
|
3
|
-
`),live:!1}),this.#Ve({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#nt()}}async#pe(e){let t=this.#ve(),n=isMultiSelectRequest(e),r={options:e.options,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(r.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(r.initialValues=e.initialValues);let i=initialSelectState(r),a,o=e.notices;if(e.kind===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));o=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,select:i};return o!==void 0&&o.length>0&&(t.notices=o),a!==void 0&&(t.error=a),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#nt(),await this.#xe((t,r)=>{let o={key:t,options:e.options,select:i},s=reduceSetupSelectInput(n?{...o,kind:e.kind,required:e.required}:{...o,kind:e.kind});switch(s.kind){case`cancel`:r(void 0);return;case`repaint`:this.#nt();return;case`update`:i=s.select,a=void 0,this.#nt();return;case`submit`:r(s.values);return;case`error`:a=s.message,this.#nt();return;case`ignore`:return}}).promise}#me(e){this.#Oe();let t=this.#ye();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#nt();let r=this.#xe((t,r)=>{let i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#nt();return;case`repaint`:this.#nt();return;case`submit`:n!==void 0&&r(e.actions[n].value);return;case void 0:return}},()=>{t.status=void 0});return{choice:r.promise,close:()=>r.settle(void 0)}}async#he(e){let t=this.#ve(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`editable`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint,caretVisible:this.#L}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?(i.text.length===0&&(i=lineOf(e.editable.defaultValue)),this.#Ie()):(i=lineOf(``),this.#Le())};return syncEditableRow(),this.#nt(),await this.#xe((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Re(),this.#nt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#nt()},submit=()=>{let t=selectValueAtCursor([...e.options],r.cursor);if(t===void 0)return;if(t!==e.editable.value){n({kind:`selected`,value:t});return}let o=(i.text||e.editable.defaultValue).trim(),s=e.editable.validate?.(o);if(s!==void 0){a=s,this.#nt();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#nt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Le()).promise}async#ge(e){let t=this.#ve(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder!==void 0&&(i.placeholder=e.placeholder),e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#r,t,this.#L)},this.#Ie(),this.#nt(),await this.#xe((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Re(),this.#nt()},a=applyLineEditorKey(n,t);if(a!==void 0){apply(a);return}switch(t.type){case`ctrl-c`:case`escape`:i(void 0);return;case`ctrl-r`:this.#nt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#nt();return}i(t);return}default:return}},()=>this.#Le()).promise}async#_e(e){let t=this.#ve();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#nt(),await this.#xe((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#nt();return;default:return}}).promise}#ve(){return this.#Oe(),this.#A=!1,this.#M=!1,this.#N=``,this.#ye()}#ye(){return this.#oe===void 0&&(this.#oe={title:``,lines:[],outputBuffer:[]}),this.#oe}#be(){this.#oe!==void 0&&(this.#oe.question=void 0,this.#oe.hideLinesWhileQuestion=!1),this.#V=void 0,this.#je(),this.#Ce(),this.#nt()}#xe(e,t){let n=!1,r,i=new Promise(e=>{r=e}),settle=e=>{n||(n=!0,t?.(),this.#be(),r(e))};return this.#V=t=>e(t,settle),this.#Ae(),{promise:i,settle}}#Se(){let e,t=new Promise(t=>{e=t});return this.#se=e,this.#Ce(),{promise:t,dispose:()=>{this.#se===e&&(this.#se=void 0,this.#we())}}}#Ce(){if(this.#se===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#se;this.#se=void 0,this.#we(),e?.();return}e.type===`ctrl-r`&&this.#nt()};this.#ce=consumer,this.#V=consumer,this.#Ae()}#we(){this.#ce!==void 0&&(this.#V===this.#ce&&this.#je(),this.#ce=void 0)}#Te(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#oe!==void 0){this.#oe.status=t,t===void 0&&(this.#oe.preview=void 0),this.#nt();return}if(t===void 0){this.#M=!1,this.#N=``,this.#Be(),this.#nt();return}this.#Oe(),this.#M=!0,this.#N=t,this.#ze(),this.#nt()}#Ee(e,t){let r=stripTerminalControls(e);if(r.trim().length===0)return;let i=this.#oe;if(i!==void 0){if(i.preview=void 0,t===`warning`||t===`error`)for(let e of i.outputBuffer)i.lines.push({text:e,tone:`info`,evidence:!0});i.outputBuffer=[],i.lines.push({text:r,tone:t}),this.#nt();return}this.#Oe(),this.#Ve({kind:`flow`,title:t,body:r,live:!1}),this.#nt()}#De(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let r=this.#oe;if(r===void 0){this.#Ee(t,`info`);return}r.preview=t,r.outputBuffer.push(t),r.outputBuffer.length>40&&r.outputBuffer.shift(),this.#nt()}shutdown(){this.#ke()}#Oe(e){this.#P=e?.title??this.#P,this.#X=e?.contextSize??this.#l,!this.#F&&(this.#F=!0,this.#n.reset(),this.#n.hideCursor(),this.#mt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume()),this.#W=()=>this.#nt(),this.#t.on(`resize`,this.#W))}#ke(){this.#je(),this.#Le(),this.#Be(),this.#F&&=(this.#bt(),this.#nt(),this.#n.clear(),this.#n.showCursor(),this.#ht(),this.#n.newline(),this.#e.isTTY&&(this.#e.setRawMode?.(!1),this.#e.pause()),this.#W&&=(this.#t.off(`resize`,this.#W),void 0),!1)}#Ae(){this.#e.off(`data`,this.#Me),this.#e.on(`data`,this.#Me)}#je(){this.#e.off(`data`,this.#Me),this.#Pe(),this.#H=``,this.#V=void 0}#Me=e=>{this.#Pe(),this.#H+=e.toString(`utf8`),this.#Ne(),this.#H===`\x1B`&&(this.#U=setTimeout(()=>{this.#H===`\x1B`&&(this.#H=``,this.#V?.({type:`escape`}))},30),this.#U.unref?.())};#Ne(){for(;this.#H.length>0;){let e=nextKey(this.#H);if(e.incomplete)return;this.#H=this.#H.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#V?.(e.key)}}#Pe(){this.#U&&=(clearTimeout(this.#U),void 0)}#Fe(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#nt();break;case`ctrl-c`:this.#I=!0,this.#G?.();break;default:break}}#Ie(){this.#Le(),this.#Re(),this.#z=setInterval(()=>{this.#L=!this.#L,this.#nt()},500),this.#z.unref?.()}#Le(){this.#z&&=(clearInterval(this.#z),void 0),this.#L=!0}#Re(){this.#L=!0}#ze(){this.#Be(),this.#B=setInterval(()=>{this.#R+=1,this.#nt()},90),this.#B.unref?.()}#Be(){this.#B&&=(clearInterval(this.#B),void 0)}#Ve(e){e.id!==this.#re?.id&&this.#bt(),this.#f.push(e),e.id&&this.#p.set(e.id,e)}#He(e){this.#Ve({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#nt()}#Ue(e){if(e!=null){if(this.#ae===e){this.#ae=void 0;return}this.#Ve({kind:`user`,body:stripTerminalControls(e),live:!1})}}#We(e,t,r){let i={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};r!==void 0&&(i.detail=stripTerminalControls(r)),this.#Ve(i),this.#nt()}#Ge(e,t){this.#v.has(e)||(this.#v.add(e),this.#Ve({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#Ke(e){if(e.id&&this.#m.has(e.id))return;let t=e.id?this.#p.get(e.id):void 0;if(t){Object.assign(t,e);return}this.#Ve(e)}#qe(e){this.#f=this.#f.filter(t=>t.id!==e),this.#p.delete(e)}#Je(){for(let e of this.#f)e.status===`approval`||e.status===`running`||(e.live=!1)}#Ye(e,t,r){switch(e.type){case`step-start`:this.#Xe(r.hasPendingToolResults?STATUS.toolResults:STATUS.processing),r.hasPendingToolResults=!1;break;case`step-finish`:this.#tt(e.usage),this.#nt();break;case`assistant-delta`:{this.#Xe(STATUS.streaming);let t=(r.text.get(e.id)??``)+stripTerminalControls(e.delta);r.text.set(e.id,t),this.#Ze(e.id,t,!0);break}case`assistant-complete`:{let t=r.text.get(e.id)??``,i=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;r.text.set(e.id,i),this.#Ze(e.id,i,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;this.#Xe(STATUS.streaming);let i=(r.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);r.reasoning.set(e.id,i),this.#Qe(e.id,i,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let n=r.reasoning.get(e.id)??``;this.#Qe(e.id,n,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#Xe(STATUS.executingTools),this.#$e({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,r);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let n=r.tools.get(e.toolCallId);if(n===void 0)break;this.#$e({...n,status:`approval`},t,r);break}case`tool-result`:{if(t.tools===`hidden`)break;let n=this.#et(e.toolCallId,r);if(n===void 0)break;r.hasPendingToolResults=!0,this.#Xe(STATUS.toolResults),this.#$e({...n,output:e.output,status:`done`},t,r);break}case`tool-error`:{if(t.tools===`hidden`)break;let n=this.#et(e.toolCallId,r);if(n===void 0)break;r.hasPendingToolResults=!0,this.#Xe(STATUS.toolResults),this.#$e({...n,errorText:e.errorText,status:`error`},t,r);break}case`error`:this.#We(`Error`,e.errorText,e.detail);break;case`finish`:this.#tt(e.usage),this.#nt();break}}#Xe(e){let t=this.#w>0?STATUS.connectionAuth:e;this.#N!==t&&(this.#N=t,this.#nt())}#Ze(e,t,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Ke({id:e,kind:`assistant`,body:i,live:r}),this.#nt())}#Qe(e,t,r,i){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#Ke({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(i.reasoning,r),live:r}),this.#nt())}#$e(e,t,n){if(n.tools.set(e.toolCallId,e),this.#g.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#_.set(e.toolCallId,r),this.#Ke(renderNativeToolBlock(e,r,t.tools===`full`)),this.#nt()}#et(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#_.get(e)??toolSectionId(e),i=this.#p.get(r);if(!(i===void 0||i.kind!==`tool`))return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.title??`tool`}}#tt(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#J=(t??0)+(n??0)),this.#Y=t??this.#Y,this.#Z=n??this.#Z,this.#Z!=null&&this.#$!==void 0){let e=(Date.now()-this.#$)/1e3;e>0&&(this.#Q=this.#Z/e)}}#nt(){if(this.#F){if(this.#K){this.#q=!0;return}this.#K=!0;try{do this.#q=!1,this.#rt();while(this.#q)}finally{this.#K=!1}}}#rt(){if(!this.#F)return;let e=this.#ft(),t=this.#lt(e),n=Math.max(1,this.#pt()-t.length),r=[],i=this.#C;for(;this.#f.length>0&&this.#f[0].live===!1;){let t=this.#f.shift();if(this.#h.push(t),t.id&&(this.#m.add(t.id),this.#p.delete(t.id)),this.#St(t))continue;let n=this.#st(t,e,i);i=previousBlockOf(t),this.#C=i,r.push(...n),this.#S.push(...n)}let a=[];for(let t of this.#f){if(this.#St(t))continue;let n=this.#st(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)a.push({block:t,row:n[e]})}let o=[...clipLiveRows(a.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,o):this.#n.update(o)}#it(){if(!this.#F)return;let e=this.#ft(),t=this.#lt(e),n=Math.max(1,this.#pt()-t.length),r=this.#C,i=[];for(let t of this.#f){if(this.#St(t))continue;let n=this.#st(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#r),...t];this.#n.clearAll(),this.#n.flush([...this.#ot(),...this.#S],a)}logDisplayMode(){return this.#d}setLogDisplayMode(e){e!==this.#d&&(this.#d=e,this.#at(),this.#F&&this.#it())}#at(){let e=this.#ft();this.#S.length=0;let t;for(let n of this.#h){if(this.#St(n))continue;let r=this.#st(n,e,t);t=previousBlockOf(n),this.#S.push(...r)}this.#C=t}#ot(){let e=this.#y;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#ft()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#st(e,t,n){let r={spinner:this.#ct()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#ct(){return this.#r.spinner[this.#R%this.#r.spinner.length]??``}#lt(e){let t=this.#r.colors,n=[``],r=this.#oe;if(r!==void 0){let t=this.#ct(),i;if(r.question!==void 0){let n=r.question(e);i={kind:`question`,rows:n},r.status!==void 0&&(i={kind:`question`,rows:n,status:{text:r.status,frame:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,frame:t}:{kind:`preview`,text:r.preview,frame:t}:(i={kind:`status`,status:{text:r.status,frame:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,frame:t},preview:r.preview}));let a={title:r.title,lines:r.hideLinesWhileQuestion===!0?[]:r.lines,content:i};return n.push(...renderFlowPanel(a,this.#r,e)),n}if(this.#A){let r=this.#j===void 0?void 0:inlineCommandHint(this.#j);r===void 0&&this.#j!==void 0&&isTypeaheadOpen(this.#j)&&n.push(...renderCommandSuggestions(this.#j,this.#r,e));let i=Math.max(4,e-3),{before:a,after:o}=visibleLine({text:this.#E,cursor:this.#D},i,this.#r.glyph.ellipsis),s=isPromptControlCommand(this.#E),style=e=>s&&e.length>0?t.blue(e):e,l=this.#L?t.cyan(this.#r.glyph.caret):` `,u=r?t.dim(` ${r}`):``,d=this.#E.length===0&&this.#O!==void 0?`${l}${t.dim(this.#O)}`:`${style(a)}${l}${style(o)}${u}`;return n.push(...promptInputRows(d,e,this.#r,!0)),this.#ut(n,e),n}let i=this.#M?t.yellow(this.#ct()):t.dim(this.#r.glyph.dot),a=this.#N.length>0?this.#N:`Ready`,o=this.#M?t.dim(a):a,s=this.#dt(),l=s?`${i} ${o} ${t.dim(this.#r.glyph.dot)} ${s}`:`${i} ${o}`;return n.push(clip(l,e)),this.#ut(n,e),n}#ut(e,t){let n={theme:this.#r,width:t},r=this.#y?.info?.agent.model.id;r!==void 0&&(n.model=r);let i=this.#y?.info?.agent.model.endpoint;i!==void 0&&(n.endpoint=i);let a=this.#Y??0,o=this.#Z??0;if(a>0||o>0){let e={inputTokens:a,outputTokens:o};this.#X!==void 0&&(e.contextSize=this.#X),n.tokens=formatTokenFlow(e,this.#r.glyph)}this.#T!==void 0&&(n.vercel=this.#T);let s=buildStatusLine(n);s!==void 0&&e.push(s)}#dt(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#J,outputTokens:this.#Z,tokensPerSecond:this.#Q},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#ft(){return Math.max(20,this.#t.columns||80)}#pt(){return Math.max(8,this.#t.rows||24)}#mt(){if(this.#ee!==void 0||!this.#u)return;this.#te=``,this.#ne=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#gt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ee=()=>{e(),t()}}#ht(){let e=this.#ee;e!==void 0&&(this.#ee=void 0,e(),this.#te.length>0&&(this.#xt(`stdout`)&&process.stdout.write(`${this.#te}\n`),this.#te=``),this.#ne.length>0&&(this.#xt(`stderr`)&&process.stderr.write(`${this.#ne}\n`),this.#ne=``))}#gt(e,n){let r=(e===`stdout`?this.#te:this.#ne)+n,i=r.lastIndexOf(`
|
|
4
|
-
`),a=i===-1?r:r.slice(i+1);if(e===`stdout`?this.#
|
|
5
|
-
`);t=[],e.trim().length!==0&&this.#
|
|
6
|
-
`)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#
|
|
1
|
+
import{sliceVisible,stripAnsi,stripTerminalControls,visibleLength}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,lineOf,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,nextKey,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{toErrorMessage}from"#shared/errors.js";import{initialSelectState,reduceSelect,selectValueAtCursor}from"#setup/cli/select-state.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e,t){return e?`Interrupted`:t?`Ready`:`Done`}const STATUS={processing:`Working…`,toolResults:`Reading results…`,streaming:`Responding…`,executingTools:`Running tools…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=[];#p=new Map;#m=new Set;#h=[];#g=new Set;#_=new Map;#v=new Set;#y;#b=!1;#x;#S=[];#C;#w=0;#T;#E=``;#D=0;#O=new PromptHistory;#k=!1;#A;#j=!1;#M=STATUS.processing;#N=`Eve`;#P=!1;#F=!1;#I=!0;#L=0;#R;#z;#B;#V=!1;#H;#U=``;#W;#G;#K;#q=!1;#J=!1;#Y;#X;#Z;#Q;#$;#ee;#te;#ne=``;#re=``;#ie;#ae=0;#oe;#se;#ce;#le;setupFlow={begin:e=>this.#fe(e),end:e=>this.#pe(e?.preserveDiagnostics??!0),readSelect:e=>this.#me(e),readEditableSelect:e=>this.#ge(e),readText:e=>this.#_e(e),readAcknowledge:e=>this.#ve(e),readChoice:e=>this.#he(e),setStatus:e=>this.#Ee(e),renderLine:(e,t)=>this.#De(e,t),renderOutput:e=>this.#Oe(e),waitForInterrupt:()=>this.#Ce()};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#i=e?.tools??`auto-collapsed`,this.#a=e?.reasoning??`full`,this.#o=e?.subagents??`auto-collapsed`,this.#s=e?.connectionAuth??`full`,this.#c=e?.assistantResponseStats??`tokensPerSecond`,this.#l=e?.contextSize,this.#Z=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#d=e?.logs??`none`}renderAgentHeader(e){this.#N=e.name,this.#y=e,this.#ke();let t=this.#ct().join(`
|
|
2
|
+
`);if(this.#b){t!==this.#x&&(this.#x=t,this.#He({kind:`agent-header`,body:t,live:!1})),this.#rt();return}this.#b=!0,this.#x=t,this.#n.flush(this.#ct(),[])}async readPrompt(e){this.#ke(e),this.#k=!0,this.#j=!1,this.#M=``;let t=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#O.begin(t.text),this.#ue(t),this.#A=typeaheadFor(PROMPT_COMMANDS,t.text),this.#Le(),this.#rt(),await new Promise((e,r)=>{let apply=e=>{t=e,this.#ze(),this.#ue(t),this.#A=typeaheadFor(PROMPT_COMMANDS,e.text,this.#A),this.#rt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#A=void 0,this.#Re(),this.#Ae(),r(interruptedError())},suggestions=()=>this.#A!==void 0&&isTypeaheadOpen(this.#A)?this.#A:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#H=r=>{let i=applyLineEditorKey(t,r);if(i!==void 0){apply(i);return}switch(r.type){case`up`:{let e=suggestions();e===void 0?recall(this.#O.previous(t.text)):(this.#A=moveTypeaheadSelection(e,-1),this.#rt());break}case`down`:{let e=suggestions();e===void 0?recall(this.#O.next()):(this.#A=moveTypeaheadSelection(e,1),this.#rt());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.#rt());break}case`enter`:{let r=highlighted(),i=r!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(r).trimEnd():t.text;this.#A=void 0,this.#O.add(i),this.#k=!1,this.#Re(),this.#M=STATUS.processing,isPromptControlCommand(i)?this.#He({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#Ue(i),this.#oe=i),this.#ue(EMPTY_LINE),this.#rt(),this.#Me(),e(i);break}case`ctrl-d`:t.text.length===0?interrupt():apply(deleteForward(t));break;case`ctrl-l`:this.#ot();break;case`ctrl-r`:this.#rt();break;case`ctrl-c`:interrupt();break;default:break}},this.#je()})}#ue(e){this.#E=e.text,this.#D=e.cursor}async renderStream(e,t){this.#ke(t),this.#m.clear(),this.#k=!1,this.#j=!0,this.#M=STATUS.processing,this.#We(t?.submittedPrompt),this.#F=!1,this.#Y=void 0,this.#X=void 0,this.#Q=void 0,this.#$=void 0,this.#ee=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#Be(),this.#rt();let r=new Promise(e=>{this.#K=e});this.#H=e=>this.#Ie(e),this.#je();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.#Xe(t,n,i)}}catch(e){this.#Ge(`Error`,toErrorMessage(e))}finally{this.#K=void 0,this.#F&&e.abort?.(),this.#Me(),this.#Ve(),this.#j=!1,this.#M=completedTurnStatus(this.#F,t?.continueSession===!0),this.#Ye(),this.#rt(),(this.#F||!t?.continueSession)&&this.#Ae()}if(this.#F)throw interruptedError()}async readToolApproval(e,t){return this.#ke(t),this.#k=!1,this.#j=!1,this.#M=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#F=!1,this.#rt(),await new Promise((t,n)=>{this.#H=r=>{switch(r.type){case`character`:{let n=r.value.toLowerCase();n===`y`?(this.#M=STATUS.processing,this.#Me(),this.#rt(),t({approved:!0})):n===`n`&&(this.#M=STATUS.processing,this.#de(e.toolCallId),this.#Me(),this.#rt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#rt();break;case`ctrl-c`:this.#F=!0,this.#Ae(),n(interruptedError());break;default:break}},this.#je()})}async readInputQuestion(e,t){this.#ke(t),this.#k=!1,this.#j=!1,this.#F=!1;let r=e.options??[],i=r.length>0,a=(e.allowFreeform===!0||!i)&&i,o=r.length+ +!!a,s=questionSectionId(e.requestId),c=i?`select`:`text`,l=0,u=``,isOnFreeformRow=()=>a&&l===r.length,renderSection=()=>{this.#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.#ue(lineOf(u)),this.#M=``;this.#rt()};renderSection(),c===`text`&&this.#Le(),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.#Re(),this.#Me(),this.#rt();let r={};return t.optionId!==void 0&&(r.optionId=t.optionId),t.text!==void 0&&(r.text=t.text),r};return await new Promise((t,n)=>{this.#H=a=>{if(a.type===`ctrl-c`){this.#F=!0,this.#Re(),this.#Ae(),n(interruptedError());return}if(a.type===`ctrl-r`){this.#rt();return}if(c===`select`){switch(a.type){case`up`:o>0&&(l=(l-1+o)%o,renderSection(),repaintStatus());break;case`down`:o>0&&(l=(l+1)%o,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){c=`text`,u=``,this.#Le(),repaintStatus();break}let e=r[l];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}switch(a.type){case`character`:u+=a.value,this.#ze(),repaintStatus();break;case`backspace`:u=u.slice(0,-1),this.#ze(),repaintStatus();break;case`enter`:{let n=resolveQuestionText(u,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(i){if(u.length>0){u=``,this.#ze(),repaintStatus();break}c=`select`,u=``,this.#k=!1,this.#Re(),repaintStatus();break}u=``,this.#ze(),repaintStatus();break;default:break}},this.#je()})}upsertSubagentStep(e){if(this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),r=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&r.length===0)){if(this.#Ke(e.callId,e.subagentName),this.#o===`collapsed`){this.#rt();return}this.#qe({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:r,live:!e.finalized}),this.#rt()}}upsertSubagentTool(e){if(this.#o===`hidden`)return;if(this.#Ke(e.callId,e.subagentName),this.#o===`collapsed`){this.#rt();return}let t=subagentToolStatus(e.status),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,depth:1,title:stripTerminalControls(e.toolName),subtitle:summarizeToolArgs(e.input),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolInput:e.input};e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=summarizeToolResult(e.output),r.toolOutput=e.output),this.#qe(r),this.#rt()}markChildToolCallId(e){this.#g.add(e);let t=this.#_.get(e);t!==void 0&&(this.#Je(t),this.#_.delete(e),this.#rt())}#de(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.#rt()}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.#rt()):n&&(this.#M=STATUS.processing,this.#rt())}setVercelStatus(e){this.#T=e,this.#rt()}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.#oe=void 0,this.#ie=void 0,this.#w=0,this.#Y=void 0,this.#X=void 0,this.#Q=void 0,this.#$=void 0,this.#ee=void 0,this.#P&&(this.#n.clearAll(),this.#rt())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#ke(),this.#He({kind:`notice`,body:t,live:!1}),this.#rt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#ke(),this.#He({kind:`sandbox`,body:t,live:!1}),this.#rt())}renderSetupWarning(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#ke(),this.#He({kind:`warning`,body:t,live:!1}),this.#rt())}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#ke(),this.#He({kind:`result`,body:t,live:!1}),this.#rt())}#fe(e){this.#ke(),this.#k=!1,this.#j=!1,this.#M=``,this.#se={title:stripTerminalControls(e),lines:[],outputBuffer:[]},this.#Be(),this.#rt()}#pe(e){this.#ce=void 0,this.#Te();let t=this.#se;if(t!==void 0){if(this.#se=void 0,this.#Ve(),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.#He({kind:`flow`,title:`info`,body:e.join(`
|
|
3
|
+
`),live:!1}),this.#He({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#rt()}}async#me(e){let t=this.#ye(),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.#rt(),await this.#Se((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.#rt();return;case`update`:i=s.select,a=void 0,this.#rt();return;case`submit`:r(s.values);return;case`error`:a=s.message,this.#rt();return;case`ignore`:return}}).promise}#he(e){this.#ke();let t=this.#be();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#rt();let r=this.#Se((t,r)=>{let i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#rt();return;case`repaint`:this.#rt();return;case`submit`:n!==void 0&&r(e.actions[n].value);return;case void 0:return}},()=>{t.status=void 0});return{choice:r.promise,close:()=>r.settle(void 0)}}async#ge(e){let t=this.#ye(),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.#Le()):(i=lineOf(``),this.#Re())};return syncEditableRow(),this.#rt(),await this.#Se((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#ze(),this.#rt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#rt()},submit=()=>{let t=selectValueAtCursor([...e.options],r.cursor);if(t===void 0)return;if(t!==e.editable.value){n({kind:`selected`,value:t});return}let o=(i.text||e.editable.defaultValue).trim(),s=e.editable.validate?.(o);if(s!==void 0){a=s,this.#rt();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#rt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Re()).promise}async#_e(e){let t=this.#ye(),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.#Le(),this.#rt(),await this.#Se((t,i)=>{let apply=e=>{n=e,r=void 0,this.#ze(),this.#rt()},a=applyLineEditorKey(n,t);if(a!==void 0){apply(a);return}switch(t.type){case`ctrl-c`:case`escape`:i(void 0);return;case`ctrl-r`:this.#rt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#rt();return}i(t);return}default:return}},()=>this.#Re()).promise}async#ve(e){let t=this.#ye();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#rt(),await this.#Se((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#rt();return;default:return}}).promise}#ye(){return this.#ke(),this.#k=!1,this.#j=!1,this.#M=``,this.#be()}#be(){return this.#se===void 0&&(this.#se={title:``,lines:[],outputBuffer:[]}),this.#se}#xe(){this.#se!==void 0&&(this.#se.question=void 0,this.#se.hideLinesWhileQuestion=!1),this.#H=void 0,this.#Me(),this.#we(),this.#rt()}#Se(e,t){let n=!1,r,i=new Promise(e=>{r=e}),settle=e=>{n||(n=!0,t?.(),this.#xe(),r(e))};return this.#H=t=>e(t,settle),this.#je(),{promise:i,settle}}#Ce(){let e,t=new Promise(t=>{e=t});return this.#ce=e,this.#we(),{promise:t,dispose:()=>{this.#ce===e&&(this.#ce=void 0,this.#Te())}}}#we(){if(this.#ce===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#ce;this.#ce=void 0,this.#Te(),e?.();return}e.type===`ctrl-r`&&this.#rt()};this.#le=consumer,this.#H=consumer,this.#je()}#Te(){this.#le!==void 0&&(this.#H===this.#le&&this.#Me(),this.#le=void 0)}#Ee(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#se!==void 0){this.#se.status=t,t===void 0&&(this.#se.preview=void 0),this.#rt();return}if(t===void 0){this.#j=!1,this.#M=``,this.#Ve(),this.#rt();return}this.#ke(),this.#j=!0,this.#M=t,this.#Be(),this.#rt()}#De(e,t){let r=stripTerminalControls(e);if(r.trim().length===0)return;let i=this.#se;if(i!==void 0){if(i.preview=void 0,t===`warning`||t===`error`)for(let e of i.outputBuffer)i.lines.push({text:e,tone:`info`,evidence:!0});i.outputBuffer=[],i.lines.push({text:r,tone:t}),this.#rt();return}this.#ke(),this.#He({kind:`flow`,title:t,body:r,live:!1}),this.#rt()}#Oe(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let r=this.#se;if(r===void 0){this.#De(t,`info`);return}r.preview=t,r.outputBuffer.push(t),r.outputBuffer.length>40&&r.outputBuffer.shift(),this.#rt()}shutdown(){this.#Ae()}#ke(e){this.#N=e?.title??this.#N,this.#Z=e?.contextSize??this.#l,!this.#P&&(this.#P=!0,this.#n.reset(),this.#n.hideCursor(),this.#gt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume()),this.#G=()=>this.#rt(),this.#t.on(`resize`,this.#G))}#Ae(){this.#Me(),this.#Re(),this.#Ve(),this.#B!==void 0&&(clearTimeout(this.#B),this.#B=void 0),this.#V=!1,this.#P&&=(this.#St(),this.#rt(),this.#n.clear(),this.#n.showCursor(),this.#_t(),this.#n.newline(),this.#e.isTTY&&(this.#e.setRawMode?.(!1),this.#e.pause()),this.#G&&=(this.#t.off(`resize`,this.#G),void 0),!1)}#je(){this.#e.off(`data`,this.#Ne),this.#e.on(`data`,this.#Ne)}#Me(){this.#e.off(`data`,this.#Ne),this.#Fe(),this.#U=``,this.#H=void 0}#Ne=e=>{this.#Fe(),this.#U+=e.toString(`utf8`),this.#Pe(),this.#U===`\x1B`&&(this.#W=setTimeout(()=>{this.#U===`\x1B`&&(this.#U=``,this.#H?.({type:`escape`}))},30),this.#W.unref?.())};#Pe(){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)}}#Fe(){this.#W&&=(clearTimeout(this.#W),void 0)}#Ie(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#rt();break;case`ctrl-c`:this.#F=!0,this.#K?.();break;default:break}}#Le(){this.#Re(),this.#ze(),this.#R=setInterval(()=>{this.#I=!this.#I,this.#rt()},500),this.#R.unref?.()}#Re(){this.#R&&=(clearInterval(this.#R),void 0),this.#I=!0}#ze(){this.#I=!0}#Be(){this.#Ve(),this.#z=setInterval(()=>{this.#L+=1,this.#rt()},90),this.#z.unref?.()}#Ve(){this.#z&&=(clearInterval(this.#z),void 0)}#He(e){e.id!==this.#ie?.id&&this.#St(),this.#f.push(e),e.id&&this.#p.set(e.id,e)}#Ue(e){this.#He({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#rt()}#We(e){if(e!=null){if(this.#oe===e){this.#oe=void 0;return}this.#He({kind:`user`,body:stripTerminalControls(e),live:!1})}}#Ge(e,t,r){let i={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};r!==void 0&&(i.detail=stripTerminalControls(r)),this.#He(i),this.#rt()}#Ke(e,t){this.#v.has(e)||(this.#v.add(e),this.#He({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.#He(e)}#Je(e){this.#f=this.#f.filter(t=>t.id!==e),this.#p.delete(e)}#Ye(){for(let e of this.#f)e.status===`approval`||e.status===`running`||(e.live=!1)}#Xe(e,t,r){switch(e.type){case`step-start`:this.#Ze(r.hasPendingToolResults?STATUS.toolResults:STATUS.processing),r.hasPendingToolResults=!1;break;case`step-finish`:this.#nt(e.usage),this.#rt();break;case`assistant-delta`:{this.#Ze(STATUS.streaming);let t=(r.text.get(e.id)??``)+stripTerminalControls(e.delta);r.text.set(e.id,t),this.#Qe(e.id,t,!0);break}case`assistant-complete`:{let t=r.text.get(e.id)??``,i=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;r.text.set(e.id,i),this.#Qe(e.id,i,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;this.#Ze(STATUS.streaming);let i=(r.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);r.reasoning.set(e.id,i),this.#$e(e.id,i,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let n=r.reasoning.get(e.id)??``;this.#$e(e.id,n,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#Ze(STATUS.executingTools),this.#et({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,r);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let n=r.tools.get(e.toolCallId);if(n===void 0)break;this.#et({...n,status:`approval`},t,r);break}case`tool-result`:{if(t.tools===`hidden`)break;let n=this.#tt(e.toolCallId,r);if(n===void 0)break;r.hasPendingToolResults=!0,this.#Ze(STATUS.toolResults),this.#et({...n,output:e.output,status:`done`},t,r);break}case`tool-error`:{if(t.tools===`hidden`)break;let n=this.#tt(e.toolCallId,r);if(n===void 0)break;r.hasPendingToolResults=!0,this.#Ze(STATUS.toolResults),this.#et({...n,errorText:e.errorText,status:`error`},t,r);break}case`error`:this.#Ge(`Error`,e.errorText,e.detail);break;case`finish`:this.#nt(e.usage),this.#rt();break}}#Ze(e){let t=this.#w>0?STATUS.connectionAuth:e;this.#M!==t&&(this.#M=t,this.#rt())}#Qe(e,t,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#qe({id:e,kind:`assistant`,body:i,live:r}),this.#rt())}#$e(e,t,r,i){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#qe({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(i.reasoning,r),live:r}),this.#rt())}#et(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.#rt()}#tt(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`}}#nt(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#Y=(t??0)+(n??0)),this.#X=t??this.#X,this.#Q=n??this.#Q,this.#Q!=null&&this.#ee!==void 0){let e=(Date.now()-this.#ee)/1e3;e>0&&(this.#$=this.#Q/e)}}#rt(){if(this.#P){if(this.#q){this.#J=!0;return}this.#q=!0;try{do this.#J=!1,this.#it();while(this.#J)}finally{this.#q=!1}}}#it(){if(!this.#P)return;let e=this.#mt(),t=this.#dt(e),n=Math.max(1,this.#ht()-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.#wt(t))continue;let n=this.#lt(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.#wt(t))continue;let n=this.#lt(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)}#at(){if(!this.#P)return;let e=this.#mt(),t=this.#dt(e),n=Math.max(1,this.#ht()-t.length),r=this.#C,i=[];for(let t of this.#f){if(this.#wt(t))continue;let n=this.#lt(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.#ct(),...this.#S],a)}logDisplayMode(){return this.#d}setLogDisplayMode(e){e!==this.#d&&(this.#d=e,this.#st(),this.#P&&this.#at())}#ot(){this.#V=!0,this.#B!==void 0&&clearTimeout(this.#B),this.#B=setTimeout(()=>{this.#V=!1,this.#B=void 0,this.#rt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#d)),this.#rt()}#st(){let e=this.#mt();this.#S.length=0;let t;for(let n of this.#h){if(this.#wt(n))continue;let r=this.#lt(n,e,t);t=previousBlockOf(n),this.#S.push(...r)}this.#C=t}#ct(){let e=this.#y;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#mt()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#lt(e,t,n){let r={spinner:this.#ut()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#ut(){return this.#r.spinner[this.#L%this.#r.spinner.length]??``}#dt(e){let t=this.#r.colors,n=[``],r=this.#se;if(r!==void 0){let t=this.#ut(),i;if(r.question!==void 0){let n=r.question(e);i={kind:`question`,rows:n},r.status!==void 0&&(i={kind:`question`,rows:n,status:{text:r.status,frame:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,frame:t}:{kind:`preview`,text:r.preview,frame:t}:(i={kind:`status`,status:{text:r.status,frame:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,frame:t},preview:r.preview}));let a={title:r.title,lines:r.hideLinesWhileQuestion===!0?[]:r.lines,content:i};return n.push(...renderFlowPanel(a,this.#r,e)),n}if(this.#k){let r=this.#A===void 0?void 0:inlineCommandHint(this.#A);r===void 0&&this.#A!==void 0&&isTypeaheadOpen(this.#A)&&n.push(...renderCommandSuggestions(this.#A,this.#r,e));let i=Math.max(4,e-3),{before:a,after:o}=visibleLine({text:this.#E,cursor:this.#D},i,this.#r.glyph.ellipsis),s=isPromptControlCommand(this.#E),style=e=>s&&e.length>0?t.blue(e):e,l=this.#I?t.cyan(this.#r.glyph.caret):` `,u=r?t.dim(` ${r}`):``,d=`${style(a)}${l}${style(o)}${u}`;return n.push(...promptInputRows(d,e,this.#r,!0)),this.#ft(n,e),n}let i=this.#j?t.yellow(this.#ut()):t.dim(this.#r.glyph.dot),a=this.#M.length>0?this.#M:`Ready`,o=this.#j?t.dim(a):a,s=this.#pt(),l=s?`${i} ${o} ${t.dim(this.#r.glyph.dot)} ${s}`:`${i} ${o}`;return n.push(clip(l,e)),this.#ft(n,e),n}#ft(e,t){let n={theme:this.#r,width:t};this.#V&&(n.logLevel=this.#d);let r=this.#y?.info?.agent.model.id;r!==void 0&&(n.model=r);let i=this.#y?.info?.agent.model.endpoint;i!==void 0&&(n.endpoint=i);let a=this.#X??0,o=this.#Q??0;if(a>0||o>0){let e={inputTokens:a,outputTokens:o};this.#Z!==void 0&&(e.contextSize=this.#Z),n.tokens=formatTokenFlow(e,this.#r.glyph)}this.#T!==void 0&&(n.vercel=this.#T);let s=buildStatusLine(n);s!==void 0&&e.push(s)}#pt(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Y,outputTokens:this.#Q,tokensPerSecond:this.#$},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#mt(){return Math.max(20,this.#t.columns||80)}#ht(){return Math.max(8,this.#t.rows||24)}#gt(){if(this.#te!==void 0||!this.#u)return;this.#ne=``,this.#re=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#vt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#te=()=>{e(),t()}}#_t(){let e=this.#te;e!==void 0&&(this.#te=void 0,e(),this.#ne.length>0&&(this.#Ct(`stdout`)&&process.stdout.write(`${this.#ne}\n`),this.#ne=``),this.#re.length>0&&(this.#Ct(`stderr`)&&process.stderr.write(`${this.#re}\n`),this.#re=``))}#vt(e,n){let r=(e===`stdout`?this.#ne:this.#re)+n,i=r.lastIndexOf(`
|
|
4
|
+
`),a=i===-1?r:r.slice(i+1);if(e===`stdout`?this.#ne=a:this.#re=a,i===-1)return;let o=stripAnsi(r.slice(0,i)).replace(/\s+$/u,``);o.trim().length!==0&&(e===`stdout`?this.#yt(o):this.#He({kind:`log`,title:e,body:o,live:!1}),this.#rt())}#yt(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
|
|
5
|
+
`);t=[],e.trim().length!==0&&this.#He({kind:`log`,title:`stdout`,body:e,live:!1})};for(let n of e.split(`
|
|
6
|
+
`)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#He({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#bt(r,n.trimEnd())}flushPending()}#bt(e,t){let n=this.#xt();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.#ae}`;this.#ae+=1,this.#ie={id:r,summary:t},this.#He({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);return}this.#He({kind:`log`,title:`stdout`,body:t,live:!1})}#xt(){let e=this.#ie;if(e===void 0)return;let t=this.#p.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#St(){let e=this.#ie;if(e===void 0)return;this.#ie=void 0;let t=this.#p.get(e.id);t!==void 0&&(t.live=!1)}#Ct(e){switch(this.#d){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#wt(e){return e.kind===`sandbox`?!this.#Ct(`sandbox`):e.kind===`log`?!this.#Ct(e.title===`stderr`?`stderr`:`stdout`):!1}};function chunkToString(e,t){return typeof e==`string`?e:Buffer.from(e).toString(t)}async function*iterateTUIStream(e){if(e instanceof ReadableStream){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}return}yield*e}function clip(t,n){return visibleLength(t)>n?sliceVisible(t,n):t}function promptInputRows(e,t,n,r){let i=n.colors;return[clip(`${r?i.cyan(n.glyph.prompt):i.dim(n.glyph.prompt)} ${r?e:i.dim(e)}`,t),``]}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function leadsWithGap(e,t){if(e.kind===`sandbox`&&t?.kind===`sandbox`)return!1;if(t?.kind===`sandbox`&&e.kind!==`sandbox`)return!0;if(e.kind===`log`&&t?.kind===`log`)return t.title!==e.title;if(t?.kind===`log`&&e.kind!==`log`)return!0;switch(e.kind){case`user`:case`assistant`:case`reasoning`:case`subagent`:case`error`:case`notice`:case`question`:case`connection-auth`:case`sandbox`:case`log`:case`command`:case`warning`:case`flow`:case`agent-header`:return!0;default:return!1}}function parseSandboxLogLine(e){let t=e.trim();if(!t.startsWith(`Eve: `))return;let n=t.slice(5);return/\bsandbox\b/i.test(n)&&!isLowValueSandboxLogLine(n)?n:void 0}function isLowValueSandboxLogLine(e){return/^initializing (?:\d+ )?sandbox templates?\b/i.test(e)||/^initialized \d+ sandbox\b/i.test(e)||/^reused cached sandbox template\b/i.test(e)||/^sandbox template "[^"]+" \([^)]+\): (checking|reusing|loading microsandbox runtime|microsandbox runtime ready)\b/i.test(e)}function clipLiveRows(e,t,n,r){if(e.length<=t)return[...e];if(t<=1)return[clip(hiddenRowsMarker(e.length,r),n)];let i=t-1;return[clip(hiddenRowsMarker(e.length-i,r),n),...e.slice(e.length-i)]}function hiddenRowsMarker(e,t){let n=e.toLocaleString(),r=e===1?`row`:`rows`;return t.colors.dim(`${t.glyph.dot} ${t.glyph.ellipsis} ${n} earlier ${r} hidden while streaming`)}function collapseReasoning(e,t){switch(e){case`collapsed`:return!0;case`auto-collapsed`:return!t;default:return!1}}function renderNativeToolBlock(e,t,r){let o={id:t,kind:`tool`,title:stripTerminalControls(e.toolName),subtitle:summarizeToolArgs(e.input),status:e.status,live:e.status===`running`||e.status===`approval`,expanded:r,toolInput:e.input};return e.output===void 0?e.errorText!==void 0&&(o.result=stripTerminalControls(e.errorText)):(o.result=summarizeToolResult(e.output),o.toolOutput=e.output),o}function subagentToolStatus(e){switch(e){case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`}}function formatToolApprovalTitle(e){return stripTerminalControls(e.title??e.toolName)}function toolSectionId(e){return`tool:${e}`}function questionSectionId(e){return`question:${e}`}function subagentHeaderId(e){return`subagent:${e}:header`}function subagentStepSectionId(e,t){return`subagent:${e}:step:${t}`}function subagentToolSectionId(e,t){return`subagent:${e}:tool:${t}`}function connectionAuthSectionId(e){return`connection-auth:${e}`}function formatConnectionAuthContent(e){let t=[],r=stripTerminalControls(e.description);r.length>0&&t.push(r);let i=e.challenge;if(i?.url&&t.push(`URL: ${stripTerminalControls(i.url)}`),i?.userCode&&t.push(`Code: ${stripTerminalControls(i.userCode)}`),i?.expiresAt&&t.push(`Expires: ${stripTerminalControls(i.expiresAt)}`),i?.instructions&&t.push(stripTerminalControls(i.instructions)),e.reason!==void 0){let r=stripTerminalControls(e.reason);r.length>0&&t.push(`Reason: ${r}`)}return t.join(`
|
|
7
7
|
`)}function formatQuestionContent(e,t,r){let i=r.colors,a=[],o=e.options??[];if(o.length>0){for(let[e,s]of o.entries()){let o=stripTerminalControls(s.label),c=s.description===void 0?``:stripTerminalControls(s.description),l=c.length>0?` ${i.dim(`— ${c}`)}`:``,u=t===e,d=u?`${i.cyan(r.glyph.pointer)} `:` `,f=u?i.cyan(o):o;a.push(`${d}${f}${l}`)}if(e.allowFreeform===!0){let e=t===o.length,n=e?`${i.cyan(r.glyph.pointer)} `:` `,s=`Type your own answer`;a.push(`${n}${e?i.cyan(s):i.dim(s)}`)}}else a.push(i.dim(` (type your answer)`));return a.join(`
|
|
8
8
|
`)}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};
|
|
@@ -72,8 +72,6 @@ export interface ThemeGlyphs {
|
|
|
72
72
|
dot: string;
|
|
73
73
|
/** `…` — truncation marker. */
|
|
74
74
|
ellipsis: string;
|
|
75
|
-
/** `⁕` — marks the token-flow segment of the status line. */
|
|
76
|
-
tokens: string;
|
|
77
75
|
/** `↑` — input (prompt) tokens in the token-flow segment. */
|
|
78
76
|
arrowUp: string;
|
|
79
77
|
/** `↓` — output (response) tokens in the token-flow segment. */
|
|
@@ -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:`…`,
|
|
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),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,3 +1,5 @@
|
|
|
1
|
+
import type { LogDisplayMode } from "./log-display-mode.js";
|
|
2
|
+
export type { LogDisplayMode };
|
|
1
3
|
/**
|
|
2
4
|
* Controls how terminal UI sections for stream parts are displayed.
|
|
3
5
|
*/
|
|
@@ -6,12 +8,6 @@ export type TerminalPartDisplayMode = "full" | "collapsed" | "auto-collapsed" |
|
|
|
6
8
|
* Controls which usage statistic is shown for assistant responses.
|
|
7
9
|
*/
|
|
8
10
|
export type AssistantResponseStatsMode = "tokens" | "tokensPerSecond";
|
|
9
|
-
/**
|
|
10
|
-
* Controls which in-process server/agent logs the TUI surfaces as inline
|
|
11
|
-
* regions. `all` shows both stdout and stderr; `stderr` shows only stderr;
|
|
12
|
-
* `none` suppresses log regions entirely.
|
|
13
|
-
*/
|
|
14
|
-
export type LogDisplayMode = "all" | "stderr" | "none";
|
|
15
11
|
/**
|
|
16
12
|
* Display options shared by the terminal UI runner and renderer.
|
|
17
13
|
*/
|
|
@@ -59,11 +55,12 @@ export type TuiDisplayOptions = {
|
|
|
59
55
|
*/
|
|
60
56
|
contextSize?: number;
|
|
61
57
|
/**
|
|
62
|
-
* Which
|
|
63
|
-
* Output is always captured and buffered so it
|
|
64
|
-
* this only controls what is rendered. The
|
|
65
|
-
* the mode at runtime, retroactively hiding or
|
|
66
|
-
* lines.
|
|
58
|
+
* Which captured output (stdout, stderr, sandbox lifecycle lines) to
|
|
59
|
+
* surface as inline regions. Output is always captured and buffered so it
|
|
60
|
+
* cannot corrupt the frame; this only controls what is rendered. The
|
|
61
|
+
* `/loglevel` command switches the mode at runtime, retroactively hiding or
|
|
62
|
+
* restoring buffered lines. `TerminalRenderer` defaults to `none`; the
|
|
63
|
+
* `eve dev` CLI defaults to `stderr`.
|
|
67
64
|
*/
|
|
68
65
|
logs?: LogDisplayMode;
|
|
69
66
|
};
|
package/dist/src/cli/run.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{basename}from"node:path";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{eveCliBanner}from"#cli/banner.js";import{Command,CommanderError,InvalidArgumentError}from"#compiled/commander/index.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{registerProjectCommands}from"#cli/commands/register-project-commands.js";import{parseDevelopmentServerUrl}from"#cli/dev/url.js";async function loadBuildHost(){return(await import(`#internal/nitro/host.js`)).buildApplication}async function loadPrintApplicationInfo(){return(await import(`#cli/commands/info.js`)).printApplicationInfo}async function loadRunDevelopmentTui(){return(await import(`#cli/dev/tui/tui.js`)).runDevelopmentTui}async function loadRunEvalCommand(){return(await import(`#evals/cli/eval.js`)).runEvalCommand}async function loadStartHost(){return(await import(`#internal/nitro/host.js`)).startDevelopmentServer}async function loadStartProductionHost(){return(await import(`#internal/nitro/host.js`)).startProductionServer}function shouldPrintCliBootBanner(e){return e.name()===`info`||e.name()===`dev`||e.name()===`init`}async function waitForShutdownSignal(e){await new Promise((t,n)=>{let r=!1,cleanup=()=>{process.off(`SIGINT`,handleSignal),process.off(`SIGTERM`,handleSignal)},handleSignal=()=>{r||(r=!0,cleanup(),e.close().then(t,n))};process.once(`SIGINT`,handleSignal),process.once(`SIGTERM`,handleSignal)})}async function waitForProductionServer(e){await Promise.race([e.wait(),waitForShutdownSignal({close:()=>e.close()})])}function parsePortOption(e){if(!/^-?\d+$/.test(e))throw new InvalidArgumentError(`Expected a numeric port, received "${e}".`);let t=Number(e);if(t<0||t>65535)throw new InvalidArgumentError(`Expected a port between 0 and 65535, received "${e}".`);return t}const DISPLAY_MODES=new Set([`full`,`collapsed`,`auto-collapsed`,`hidden`]),STATS_MODES=new Set([`tokens`,`tokensPerSecond`])
|
|
1
|
+
import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{basename}from"node:path";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{eveCliBanner}from"#cli/banner.js";import{Command,CommanderError,InvalidArgumentError}from"#compiled/commander/index.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{registerProjectCommands}from"#cli/commands/register-project-commands.js";import{LOG_DISPLAY_MODES,parseLogDisplayMode}from"#cli/dev/tui/log-display-mode.js";import{parseDevelopmentServerUrl}from"#cli/dev/url.js";async function loadBuildHost(){return(await import(`#internal/nitro/host.js`)).buildApplication}async function loadPrintApplicationInfo(){return(await import(`#cli/commands/info.js`)).printApplicationInfo}async function loadRunDevelopmentTui(){return(await import(`#cli/dev/tui/tui.js`)).runDevelopmentTui}async function loadRunEvalCommand(){return(await import(`#evals/cli/eval.js`)).runEvalCommand}async function loadStartHost(){return(await import(`#internal/nitro/host.js`)).startDevelopmentServer}async function loadStartProductionHost(){return(await import(`#internal/nitro/host.js`)).startProductionServer}function shouldPrintCliBootBanner(e){return e.name()===`info`||e.name()===`dev`||e.name()===`init`}async function waitForShutdownSignal(e){await new Promise((t,n)=>{let r=!1,cleanup=()=>{process.off(`SIGINT`,handleSignal),process.off(`SIGTERM`,handleSignal)},handleSignal=()=>{r||(r=!0,cleanup(),e.close().then(t,n))};process.once(`SIGINT`,handleSignal),process.once(`SIGTERM`,handleSignal)})}async function waitForProductionServer(e){await Promise.race([e.wait(),waitForShutdownSignal({close:()=>e.close()})])}function parsePortOption(e){if(!/^-?\d+$/.test(e))throw new InvalidArgumentError(`Expected a numeric port, received "${e}".`);let t=Number(e);if(t<0||t>65535)throw new InvalidArgumentError(`Expected a port between 0 and 65535, received "${e}".`);return t}const DISPLAY_MODES=new Set([`full`,`collapsed`,`auto-collapsed`,`hidden`]),STATS_MODES=new Set([`tokens`,`tokensPerSecond`]);function parseDisplayMode(e){if(!DISPLAY_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...DISPLAY_MODES].join(`, `)}, received "${e}".`);return e}function parseStatsMode(e){if(!STATS_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...STATS_MODES].join(`, `)}, received "${e}".`);return e}function parseLogsMode(e){let t=parseLogDisplayMode(e);if(t===void 0)throw new InvalidArgumentError(`Expected one of ${LOG_DISPLAY_MODES.join(`, `)}, received "${e}".`);return t}function parseContextSizeOption(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new InvalidArgumentError(`Expected a positive number, received "${e}".`);return t}function resolveDevUiMode(e){return e.options.ui===!1||!e.interactive?`headless`:`tui`}function resolveTuiTitle(e){if(e.name!==void 0&&e.name.length>0)return e.name;if(e.remoteServerUrl!==void 0)try{return new URL(e.remoteServerUrl).host}catch{return}let n=humanizeProjectName(basename(e.appRoot));return n.length>0?n:void 0}function humanizeProjectName(e){return e.replace(/[-_.]+/gu,` `).trim().split(/\s+/u).filter(e=>e.length>0).map(e=>e[0].toUpperCase()+e.slice(1)).join(` `)}function resolveTuiDisplayOptions(e){let t={logs:e.logs??`stderr`,reasoning:e.reasoning??`full`,tools:e.tools??`auto-collapsed`};return e.subagents!==void 0&&(t.subagents=e.subagents),e.connectionAuth!==void 0&&(t.connectionAuth=e.connectionAuth),e.assistantResponseStats!==void 0&&(t.assistantResponseStats=e.assistantResponseStats),e.contextSize!==void 0&&(t.contextSize=e.contextSize),t}function hasInteractiveTerminal(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function rewriteDevelopmentUrlShorthand(e){let t=e[1];return e[0]!==`dev`||e.length!==2||t===void 0||t.startsWith(`-`)?[...e]:[`dev`,`--url`,t]}function resolveRemoteDevelopmentServerUrl(e){if(e.url){if(e.host!==void 0)throw new InvalidArgumentError(`The --host option cannot be used with --url.`);if(e.port!==void 0)throw new InvalidArgumentError(`The --port option cannot be used with --url.`);if(e.ui===!1)throw new InvalidArgumentError(`The --no-ui option cannot be used with --url.`);return e.url}}function createCliProgram(t,o){let u=resolveApplicationRoot(),d=resolveInstalledPackageInfo().version,f=new Command,p=createCliTheme();f.name(`eve`).description(`Build and run an Eve application.`).version(d).showHelpAfterError().exitOverride().hook(`preAction`,(e,n)=>{shouldPrintCliBootBanner(n)&&t.log(eveCliBanner())}).configureOutput({writeErr:e=>{t.error(e.trimEnd())},writeOut:e=>{t.log(e.trimEnd())}});let m=f.command(`channels`).description(`Manage user-authored channels in the current project.`);return m.command(`add [kind]`).description(`Add channels interactively, or scaffold a channel kind (slack | web).`).option(`-f, --force`,`Overwrite existing channel files`).option(`-y, --yes`,`Assume yes for confirmations; requires an explicit channel kind`).action(async(e,n)=>{let{runChannelsAddCommand:r}=await import(`#cli/commands/channels.js`);await r(t,u,{kind:e,options:n})}),m.command(`list`).description(`List user-authored channels in the current project.`).option(`--json`,`Output as JSON`).action(async e=>{let{runChannelsListCommand:n}=await import(`#cli/commands/channels.js`);await n(t,u,e)}),f.command(`init <target>`).description(`Create a new Eve agent, or add one to an existing project directory.`).option(`--channel-web-nextjs`,`Add the Web Chat application (Next.js)`).action(async(e,n)=>{let{runInitCommand:r}=await import(`#cli/commands/init.js`);await r(t,u,e,n)}),registerProjectCommands({program:f,logger:t,appRoot:u}),f.command(`build`).description(`Build the current Eve application.`).action(async()=>{let{loadDevelopmentEnvironmentFiles:e}=await import(`#cli/dev/environment.js`);e(u);let n=await(o.buildHost??await loadBuildHost())(u);t.log(renderCliTaggedLine(p,{message:`built output at ${n}`,tag:`build`,tone:`success`}))}),f.command(`start`).description(`Start a built Eve application.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,parsePortOption).action(async e=>{let{loadDevelopmentEnvironmentFiles:n}=await import(`#cli/dev/environment.js`);n(u);let i=await(o.startProductionHost??await loadStartProductionHost())(u,{host:e.host,port:e.port});t.log(renderCliTaggedLine(p,{message:`server listening at ${i.url}`,tag:`start`,tone:`success`})),await waitForProductionServer(i)}),f.command(`dev`).description(`Start the Eve development server or connect to an existing URL.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,parsePortOption).option(`-u, --url <url>`,`Connect to an existing server URL`,parseDevelopmentServerUrl).option(`--no-ui`,`Start the server without an interactive UI`).option(`--name <name>`,`Title shown in the terminal UI (defaults to the app folder name)`).option(`--input <text>`,`Pre-fill the prompt input after launching the UI`).option(`--tools <mode>`,`How tool calls render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--reasoning <mode>`,`How reasoning renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--subagents <mode>`,`How subagent sections render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--connection-auth <mode>`,`How connection authorization renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--assistant-response-stats <mode>`,`Assistant header statistic: tokens | tokensPerSecond`,parseStatsMode).option(`--context-size <tokens>`,`Model context window size, shown as a usage percentage`,parseContextSizeOption).option(`--logs <mode>`,`Which server/agent logs to show: all | stderr | sandbox | none`,parseLogsMode).addHelpText(`after`,`
|
|
2
2
|
You can also pass a bare URL as the only argument, for example: eve dev https://example.com
|
|
3
|
-
`).action(async e=>{let n=resolveRemoteDevelopmentServerUrl(e),i=hasInteractiveTerminal(),a=resolveDevUiMode({options:e,interactive:i});if(e.input!==void 0&&a===`headless`)throw new InvalidArgumentError(`--input requires the interactive UI.`);let{loadDevelopmentEnvironmentFiles:c}=await import(`#cli/dev/environment.js`);c(
|
|
3
|
+
`).action(async e=>{let n=resolveRemoteDevelopmentServerUrl(e),i=hasInteractiveTerminal(),a=resolveDevUiMode({options:e,interactive:i});if(e.input!==void 0&&a===`headless`)throw new InvalidArgumentError(`--input requires the interactive UI.`);let{loadDevelopmentEnvironmentFiles:c}=await import(`#cli/dev/environment.js`);c(u);let runInteractiveUi=async r=>{t.log(``);let i=o.runDevelopmentTui??await loadRunDevelopmentTui(),a=resolveTuiDisplayOptions(e),s=resolveTuiTitle({name:e.name,remoteServerUrl:n,appRoot:u});s!==void 0&&(a.name=s);let c={serverUrl:r,...a};n===void 0&&(c.appRoot=u),e.input!==void 0&&(c.initialInput=e.input),await i(c)};if(n){if(t.log(renderCliTaggedLine(p,{message:`connecting to ${n}`,tag:`dev`,tone:`info`})),a===`headless`){t.log(renderCliTaggedLine(p,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`}));return}await runInteractiveUi(n);return}let l=await(o.startHost??await loadStartHost())(u,{host:e.host,port:e.port}),d=!1,closeServer=async()=>{d||(d=!0,await l.close())};try{if(a!==`tui`&&t.log(renderCliTaggedLine(p,{message:`server listening at ${l.url}`,tag:`dev`,tone:`success`})),a===`headless`)return e.ui!==!1&&!i&&t.log(renderCliTaggedLine(p,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`})),await waitForShutdownSignal({close:closeServer});await runInteractiveUi(l.url)}finally{await closeServer()}}),f.command(`info`).description(`Print resolved application information.`).option(`--json`,`Output as JSON`).action(async e=>{await(o.printApplicationInfo??await loadPrintApplicationInfo())(t,u,e)}),f.command(`eval`).description(`Run evals against an Eve agent.`).argument(`[evalIds...]`,`Eval ids (or directory prefixes) to run (all discovered evals when omitted)`).option(`--url <url>`,`Remote agent URL (skip local host startup)`).option(`--tag <tag...>`,`Run only evals carrying a tag`).option(`--strict`,`Fail the exit code when any score falls below its threshold`).option(`--list`,`Print discovered evals without running them`).option(`--timeout <ms>`,`Per-eval timeout in milliseconds`).option(`--max-concurrency <n>`,`Max concurrent eval executions`).option(`--json`,`Output results as JSON`).option(`--junit <path>`,`Write JUnit XML results to a file`).option(`--skip-report`,`Skip eval-defined reporters (e.g. Braintrust)`).option(`--verbose`,`Stream per-eval ctx.log lines to stdout`).action(async(e,n)=>{await(o.runEvalCommand??await loadRunEvalCommand())(e,n,t)}),f}async function runCli(e=process.argv.slice(2),t=console,n={}){let r=createCliProgram(t,n),i=e.length===0?[`dev`]:rewriteDevelopmentUrlShorthand(e);try{await r.parseAsync(i,{from:`user`})}catch(e){if(e instanceof CommanderError){if(e.exitCode===0)return;throw Error(e.message)}throw e}}export{resolveDevUiMode,resolveTuiDisplayOptions,resolveTuiTitle,runCli};
|