eve 0.13.4 → 0.13.6
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 +25 -0
- package/dist/src/channel/schedule-auth.d.ts +7 -0
- package/dist/src/channel/schedule-auth.js +1 -0
- package/dist/src/channel/schedule.d.ts +2 -6
- package/dist/src/channel/schedule.js +1 -1
- package/dist/src/channel/send.d.ts +3 -1
- package/dist/src/channel/send.js +1 -1
- package/dist/src/channel/types.d.ts +6 -0
- package/dist/src/chunks/{use-eve-agent-C8UVUMA4.js → use-eve-agent-8X2UMr8q.js} +31 -20
- package/dist/src/chunks/{use-eve-agent-BLv-Mj5g.js → use-eve-agent-9ZNiSFMb.js} +31 -20
- package/dist/src/cli/dev/tui/blocks.d.ts +1 -1
- package/dist/src/cli/dev/tui/blocks.js +1 -1
- package/dist/src/cli/dev/tui/prompt-command-handler.d.ts +5 -1
- package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.d.ts +7 -7
- package/dist/src/cli/dev/tui/prompt-commands.js +2 -2
- package/dist/src/cli/dev/tui/remote-auth-command.d.ts +11 -0
- package/dist/src/cli/dev/tui/remote-auth-command.js +3 -0
- package/dist/src/cli/dev/tui/remote-auth-result.d.ts +5 -0
- package/dist/src/cli/dev/tui/remote-auth-result.js +2 -1
- package/dist/src/cli/dev/tui/remote-auth.d.ts +30 -0
- package/dist/src/cli/dev/tui/remote-auth.js +1 -0
- package/dist/src/cli/dev/tui/remote-connection-probe.d.ts +3 -1
- package/dist/src/cli/dev/tui/remote-connection-probe.js +1 -1
- package/dist/src/cli/dev/tui/remote-connection-types.d.ts +2 -1
- package/dist/src/cli/dev/tui/remote-connection.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +18 -1
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.d.ts +4 -4
- package/dist/src/cli/dev/tui/setup-commands.js +2 -2
- package/dist/src/cli/dev/tui/setup-issues.d.ts +1 -1
- package/dist/src/cli/dev/tui/setup-issues.js +1 -1
- package/dist/src/cli/dev/tui/status-line.d.ts +6 -14
- package/dist/src/cli/dev/tui/status-line.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +8 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +9 -9
- package/dist/src/cli/dev/tui/test/index.d.ts +1 -0
- package/dist/src/cli/dev/tui/test/index.js +1 -1
- package/dist/src/cli/dev/tui/tui.d.ts +1 -1
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/cli/dev/tui/vercel-trusted-sources.js +1 -1
- package/dist/src/cli/run.js +1 -1
- package/dist/src/client/agent-info-error.d.ts +17 -0
- package/dist/src/client/agent-info-error.js +1 -0
- package/dist/src/client/client.d.ts +4 -0
- package/dist/src/client/client.js +1 -1
- package/dist/src/client/index.d.ts +1 -0
- package/dist/src/client/index.js +1 -1
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/client/ndjson.js +3 -3
- package/dist/src/context/keys.d.ts +1 -0
- package/dist/src/context/keys.js +1 -1
- package/dist/src/evals/cli/eval-client.js +1 -1
- package/dist/src/execution/delegated-parent-notification.js +1 -1
- package/dist/src/execution/durable-session-store.js +1 -1
- package/dist/src/execution/eve-workflow-attributes.d.ts +8 -0
- package/dist/src/execution/eve-workflow-attributes.js +1 -1
- package/dist/src/execution/hook-ownership.d.ts +7 -0
- package/dist/src/execution/hook-ownership.js +1 -0
- package/dist/src/execution/ndjson-stream.d.ts +19 -0
- package/dist/src/execution/ndjson-stream.js +3 -0
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/subagent-adapter.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.d.ts +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -3
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/action-result-helpers.d.ts +2 -3
- package/dist/src/harness/action-result-helpers.js +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/messages.js +1 -1
- package/dist/src/harness/provider-tools.d.ts +4 -27
- package/dist/src/harness/provider-tools.js +1 -1
- package/dist/src/harness/step-hooks.d.ts +0 -13
- package/dist/src/harness/step-hooks.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/harness/tool-output-serialization.d.ts +17 -0
- package/dist/src/harness/tool-output-serialization.js +1 -0
- package/dist/src/harness/tools.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/configure-nitro-routes.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/workflow/configure-world.js +1 -1
- package/dist/src/internal/workflow/queue-namespace.d.ts +0 -1
- package/dist/src/internal/workflow/queue-namespace.js +1 -1
- package/dist/src/internal/workflow/runtime.d.ts +4 -0
- package/dist/src/internal/workflow/runtime.js +1 -0
- package/dist/src/internal/workflow-bundle/builder-support.js +6 -6
- package/dist/src/internal/workflow-bundle/builder.js +2 -2
- package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-core-shim.d.ts +10 -8
- package/dist/src/public/channels/github/dispatch.d.ts +22 -1
- package/dist/src/public/channels/github/dispatch.js +1 -1
- package/dist/src/public/channels/github/githubChannel.d.ts +21 -3
- package/dist/src/public/channels/github/githubChannel.js +1 -1
- package/dist/src/public/channels/github/inbound.d.ts +46 -1
- package/dist/src/public/channels/github/inbound.js +2 -2
- package/dist/src/public/channels/github/index.d.ts +1 -1
- package/dist/src/public/channels/github/state.d.ts +3 -1
- package/dist/src/public/channels/github/state.js +1 -1
- package/dist/src/public/channels/slack/defaults.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/runtime/connections/callback-route.js +1 -1
- package/dist/src/runtime/framework-tools/web-search.d.ts +2 -2
- package/dist/src/runtime/framework-tools/web-search.js +1 -1
- package/dist/src/runtime/session-callback-route.js +1 -1
- package/dist/src/services/dev-client/request-headers.d.ts +2 -0
- package/dist/src/services/dev-client/request-headers.js +1 -1
- package/dist/src/services/dev-client/vercel-auth-error.d.ts +12 -14
- package/dist/src/services/dev-client/vercel-auth-error.js +9 -2
- package/dist/src/setup/flows/install-vercel-cli.d.ts +1 -1
- package/dist/src/setup/flows/login.d.ts +3 -1
- package/dist/src/setup/flows/login.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/vercel-deployment.d.ts +12 -5
- package/dist/src/setup/vercel-deployment.js +1 -1
- package/dist/src/setup/vercel-project-api.d.ts +13 -2
- package/dist/src/setup/vercel-project-api.js +1 -1
- package/dist/src/setup/vercel-project.d.ts +5 -1
- package/dist/src/setup/vercel-project.js +0 -0
- package/dist/src/setup/verified-remote-client.js +1 -1
- package/dist/src/shared/empty-delivery.d.ts +3 -0
- package/dist/src/shared/empty-delivery.js +1 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/custom.mdx +1 -1
- package/docs/channels/eve.mdx +1 -1
- package/docs/channels/github.mdx +13 -1
- package/docs/channels/slack.mdx +1 -1
- package/docs/concepts/execution-model-and-durability.md +2 -0
- package/docs/guides/client/continuations.mdx +4 -0
- package/docs/guides/client/streaming.mdx +6 -0
- package/docs/guides/dev-tui.md +22 -12
- package/docs/guides/frontend/overview.mdx +28 -8
- package/docs/schedules.mdx +5 -3
- package/docs/tools/overview.mdx +2 -0
- package/package.json +1 -1
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { type AgentInfoResult, type ConnectionAuthorizationOutcome, type InputRequest, Client, ClientSession } from "#client/index.js";
|
|
2
2
|
import { type DevBootProgressReporter } from "#internal/dev-boot-progress.js";
|
|
3
|
-
import { type PromptCommand } from "./prompt-commands.js";
|
|
3
|
+
import { type PromptCommand, type PromptCommandSpec } from "./prompt-commands.js";
|
|
4
|
+
import { type RemoteConnectionController, type RemoteConnectionControllerOptions, type RemoteConnectionSnapshot } from "./remote-connection.js";
|
|
5
|
+
import type { DevelopmentCredentialGate } from "#services/dev-client/credential-gate.js";
|
|
4
6
|
import { type BootDetection } from "./setup-issues.js";
|
|
5
7
|
import type { SetupFlowRenderer } from "./setup-flow.js";
|
|
8
|
+
import type { RemoteDevelopmentTarget } from "./target.js";
|
|
6
9
|
import type { AssistantResponseStatsMode, LogDisplayMode, TerminalPartDisplayMode, TuiDisplayOptions } from "./types.js";
|
|
7
10
|
import { type TerminalInput, type TerminalOutput } from "./terminal-renderer.js";
|
|
8
11
|
import { type VercelStatusEffect, type VercelStatusSnapshot } from "./vercel-status.js";
|
|
@@ -141,6 +144,8 @@ export type AgentTUIRenderer = {
|
|
|
141
144
|
renderSetupWarning?(text: string): void;
|
|
142
145
|
/** Clears the setup attention line once its issue is resolved. */
|
|
143
146
|
clearSetupWarning?(): void;
|
|
147
|
+
/** Commits the startup `/vc:login` invocation to the transcript. */
|
|
148
|
+
renderCommandInvocation?(text: string, status?: "failed"): void;
|
|
144
149
|
renderCommandResult?(text: string): void;
|
|
145
150
|
readonly setupFlow?: SetupFlowRenderer;
|
|
146
151
|
readPrompt?(options?: AgentTUISessionOptions): Promise<string | undefined>;
|
|
@@ -206,6 +211,8 @@ export type AgentTUIRenderer = {
|
|
|
206
211
|
* line ignore it.
|
|
207
212
|
*/
|
|
208
213
|
setVercelStatus?(status: VercelStatusSnapshot): void;
|
|
214
|
+
/** Sets the remote deployment badge and its current connection/authentication state. */
|
|
215
|
+
setRemoteConnectionStatus?(status: RemoteConnectionSnapshot): void;
|
|
209
216
|
/**
|
|
210
217
|
* Clears the rendered transcript and resets per-conversation display
|
|
211
218
|
* state, leaving the UI interactive on a fresh screen. Used by the
|
|
@@ -223,6 +230,7 @@ export interface PromptCommandHandlerContext {
|
|
|
223
230
|
readonly title: string;
|
|
224
231
|
/** Provider entry authorized by confirmed boot-time model-access evidence. */
|
|
225
232
|
readonly initialModelStep?: "provider";
|
|
233
|
+
readonly remoteConnection?: RemoteConnectionController;
|
|
226
234
|
}
|
|
227
235
|
/** What one handled slash command leaves behind for the runner to apply. */
|
|
228
236
|
export interface PromptCommandOutcome {
|
|
@@ -275,6 +283,15 @@ export type EveTUIRunnerOptions = TuiDisplayOptions & {
|
|
|
275
283
|
initialInput?: string;
|
|
276
284
|
/** Handles non-core slash commands without adding feature branches to the runner. */
|
|
277
285
|
promptCommandHandler?: PromptCommandHandler;
|
|
286
|
+
/** Commands shown in discovery for this local or remote session. */
|
|
287
|
+
availablePromptCommands?: readonly PromptCommandSpec[];
|
|
288
|
+
/** Remote target and mutable OIDC token source, when connected through `--url`. */
|
|
289
|
+
remote?: {
|
|
290
|
+
readonly target: RemoteDevelopmentTarget;
|
|
291
|
+
readonly credentials: DevelopmentCredentialGate;
|
|
292
|
+
readonly resolveOidcToken: NonNullable<RemoteConnectionControllerOptions["resolveOidcToken"]>;
|
|
293
|
+
readonly resolveDeployment: NonNullable<RemoteConnectionControllerOptions["resolveDeployment"]>;
|
|
294
|
+
};
|
|
278
295
|
/** Boot-time installation-state checks; defaults to the built-ins. */
|
|
279
296
|
bootDetections?: readonly BootDetection[];
|
|
280
297
|
/** Test seam for the status line's Vercel link probe; defaults to the real one. */
|
|
@@ -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{parseLogDisplayMode}from"./log-display-mode.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,automaticSetupCommand,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState}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{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createDevelopmentRuntimeArtifactSessionRefresher}from"#services/dev-client.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";function authIssueForStatus(e){if(e===`logged-out`)return LOGIN_SETUP_ISSUE;if(e===`cli-missing`)return CLI_MISSING_SETUP_ISSUE}var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y=!1;#b=new AbortController;#x=!1;#S=[];#C;#w;#T=pickAgentHeaderTip();#E;#D=new Map;#O=new Map;#k=new Map;#A=new Map;#j=new Set;#M=!1;#N;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.#w=createVercelStatusTracker(t)}e.promptCommandHandler!==void 0&&(this.#h=e.promptCommandHandler),this.#g=e.bootDetections??BOOT_DETECTIONS,this.#_=e.getVercelAuthStatus??getVercelAuthStatus,e.onBootProgress!==void 0&&(this.#v=e.onBootProgress),e.serverUrl!==void 0&&(this.#f=e.serverUrl,this.#d=createDevelopmentRuntimeArtifactSessionRefresher({serverUrl:e.serverUrl}))}async#P(){if(this.#f===void 0){this.#I(),await this.#V(void 0);return}let e;try{e=await devBootPhase(`connecting to agent`,()=>this.#t?this.#t.info():Promise.resolve(void 0),this.#v)}catch{e=void 0}this.#I();let t=this.#F(e);await this.#V(t)}#F(e){let t=this.#p===void 0?e:resolveModelProviderState(e,process.env);this.#E=t;let n=this.#f;if(n===void 0)return t;let r={name:this.#r,serverUrl:n};return t!==void 0&&(r.info=t),this.#p!==void 0&&(r.tip=this.#T),this.#n.renderAgentHeader?.(r),t}#I(){let e=this.#v;this.#v=void 0,e?.({type:`before-first-paint`})}async run(){try{await this.#L()}finally{this.#y=!0,this.#b.abort(),this.#N?.(),this.#N=void 0,this.#n.shutdown?.(),this.#w?.dispose()}}async#L(){let e=this.#r,r,i,a,o=!1,s=!1,c=this.#m;for(await this.#P(),this.#G(),this.#w?.refreshIdentity(),this.#h!==void 0&&this.#n.setupFlow!==void 0&&(i=automaticSetupCommand(this.#S),r=i?.prompt);;){if(!s){if(r==null){if(!this.#n.readPrompt){if(o)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let t={title:e};c!==void 0&&(t.initialDraft=c,c=void 0);try{r=await this.#z(t)}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let u=parsePromptCommand(r);if(u?.type===`exit`)return;if(u?.type===`new`){this.#R(),a=void 0,s=!1,r=void 0,this.#n.reset?.();continue}if(u?.type===`help`){this.#K(formatPromptCommandHelp()),a=void 0,s=!1,r=void 0;continue}if(u?.type===`loglevel`){this.#K(this.#q(u.argument)),a=void 0,s=!1,r=void 0;continue}if(u?.type===`extension`){try{let t=u.name===`model`?i?.initialModelStep:void 0,n=t===void 0?{renderer:this.#n,title:e}:{renderer:this.#n,title:e,initialModelStep:t};i=void 0;let r=this.#h===void 0?{message:`/${u.name} is not available in this session.`}:await this.#h.handle(u,n);r?.message!==void 0&&this.#K(r.message);let a=r?.effect;a?.kind===`model-access-changed`?(this.#w?.applyEffect({kind:`refresh-identity`}),this.#x=!0,await this.#J()):a!==void 0&&(this.#w?.applyEffect(a),this.#x=!0,this.#W(this.#E))}catch(e){if(isInterruptedError(e))return;throw e}a=void 0,r=void 0,s=!1;continue}o=!0}let u=await this.#B({prompt:s?void 0:r,inputResponses:a});try{await this.#n.renderStream(u,{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=u.turnState?.pendingApprovals??[],n=u.turnState?.pendingQuestions??[];if(t.length>0||n.length>0){let i=[];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});i.push({requestId:n.approvalId,optionId:t.approved?`approve`:`deny`}),this.#D.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 a={requestId:t.requestId};r.optionId!==void 0&&(a.optionId=r.optionId),r.text!==void 0&&(a.text=r.text),i.push(a),this.#D.delete(t.requestId)}}s=!0,a=i,r=void 0;continue}u.turnState&&u.turnState.boundaryEvent===void 0&&(this.#M=!0)}catch(e){if(isInterruptedError(e))return;throw e}s=!1,a=void 0,r=void 0,this.#M&&(this.#M=!1,this.#R(),this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`))}}#R(){for(let e of this.#k.values())e.abort();this.#k.clear(),this.#O.clear(),this.#D.clear(),this.#A.clear(),this.#j.clear(),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}async#z(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.#X(),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#B(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.#X(),session:this.#e})),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),r=await this.#e.send(n)}catch(e){if(isInterruptedError(e))throw e;return this.#M=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}let i=createTurnState();return{abort:()=>t.abort(),events:eveEventsToTUIStream({events:r,pendingInputRequests:this.#D,subagentRuns:this.#O,turnState:i,onSubagentCalled:e=>this.#ee(e),onSubagentCompleted:e=>this.#ne(e),onConnectionAuthRequired:e=>this.#Z(e),onConnectionAuthCompleted:e=>this.#Q(e),onTerminalFailure:()=>{this.#M=!0},failureOverride:this.#p===void 0?void 0:e=>isGatewayAuthFailure(e)?formatGatewayAuthFailureNotice(e):void 0}),turnState:i}}async#V(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#S=await detectSetupIssues(t,this.#g),this.#n.renderSetupWarning!==void 0&&(this.#H(),this.#U())}#H(){let e=orderedSetupIssues(this.#S,this.#C);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#U(){let e=this.#p;if(e===void 0)return;let t;try{t=await this.#_(e,{signal:this.#b.signal})}catch{return}this.#y||this.#x||(this.#C=authIssueForStatus(t),this.#H())}async#W(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n={appRoot:t,env:process.env};e!==void 0&&(n.info=e);try{this.#S=await detectSetupIssues(n,this.#g);let e=await this.#_(t,{signal:this.#b.signal});this.#C=authIssueForStatus(e)}catch{return}this.#y||this.#H()}#G(){this.#p===void 0||this.#n.renderSandboxLog===void 0||this.#N===void 0&&(this.#N=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#K(e){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}#q(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#J(){let e=this.#p;if(e===void 0)return;loadDevelopmentEnvironmentFiles(e);let t=this.#F(await this.#Y());this.#W(t)}async#Y(){try{return await this.#t?.info()}catch{return}}async#X(){let e=this.#E,t=await this.#Y();t!==void 0&&this.#F(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#Z(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.#A.set(e.data.name,t),this.#$(t)}#Q(e){let t=this.#A.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.#A.set(e.data.name,t),this.#j.delete(e.data.name),this.#$(t),this.#n.setConnectionAuthPendingCount?.(this.#j.size)}#$(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)}#ee(e){let t=e.data.callId;if(this.#k.has(t))return;let n=this.#t;if(!n)return;let r=new AbortController;this.#k.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.#re(t,e),isCurrentTurnBoundaryEvent(e)))break}catch(e){if(!isAbortLikeError(e)){let n=toErrorMessage(e),r=this.#O.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.#k.delete(t)}})()}#te(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})}#ne(e){let t=this.#O.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}}#re(e,t){let n=this.#O.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.#te(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.#te(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
|
+
import{pickAgentHeaderTip}from"./agent-header.js";import{PROMPT_COMMANDS,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{createRemoteConnectionController}from"./remote-connection.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,automaticSetupCommand,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{isCurrentTurnBoundaryEvent}from"#client/index.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createDevelopmentRuntimeArtifactSessionRefresher}from"#services/dev-client.js";import{devBootPhase}from"#internal/dev-boot-progress.js";function authIssueForStatus(e){if(e===`logged-out`)return LOGIN_SETUP_ISSUE;if(e===`cli-missing`)return CLI_MISSING_SETUP_ISSUE}var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x=!1;#S=new AbortController;#C=!1;#w=[];#T;#E;#D=pickAgentHeaderTip();#O;#k=new Map;#A=new Map;#j=new Map;#M=new Map;#N=new Set;#P=!1;#F;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.#E=createVercelStatusTracker(t)}if(e.promptCommandHandler!==void 0&&(this.#h=e.promptCommandHandler),this.#g=e.availablePromptCommands??PROMPT_COMMANDS,e.remote!==void 0){if(this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#_=createRemoteConnectionController({client:this.#t,credentials:e.remote.credentials,target:e.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:e.remote.resolveOidcToken,resolveDeployment:e.remote.resolveDeployment})}this.#v=e.bootDetections??BOOT_DETECTIONS,this.#y=e.getVercelAuthStatus??getVercelAuthStatus,e.onBootProgress!==void 0&&(this.#b=e.onBootProgress),e.serverUrl!==void 0&&(this.#f=e.serverUrl),e.serverUrl!==void 0&&e.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactSessionRefresher({serverUrl:e.serverUrl}))}async#I(){if(this.#f===void 0){this.#R(),await this.#U(void 0);return}let e;if(this.#_!==void 0){let t=await this.#_.check();t.state===`ready`&&(e=t.info)}else try{e=await devBootPhase(`connecting to agent`,()=>this.#t?this.#t.info():Promise.resolve(void 0),this.#b)}catch{e=void 0}this.#R();let t=this.#L(e);await this.#U(t)}#L(e){let t=this.#p===void 0?e:resolveModelProviderState(e,process.env);this.#O=t;let n=this.#f;if(n===void 0)return t;let r={name:this.#r,serverUrl:n};return t!==void 0&&(r.info=t),this.#p!==void 0&&(r.tip=this.#D),this.#n.renderAgentHeader?.(r),t}#R(){let e=this.#b;this.#b=void 0,e?.({type:`before-first-paint`})}async run(){try{await this.#z()}finally{this.#x=!0,this.#S.abort(),this.#F?.(),this.#F=void 0,this.#n.shutdown?.(),this.#E?.dispose(),this.#_?.dispose()}}async#z(){let e=this.#r,t,i,a,o=!1,s=!1,c=this.#m;for(await this.#I(),this.#_?.current().connection.state===`auth-required`&&await this.#Q({type:`extension`,name:`vc:login`,argument:``},e,`startup`),this.#q(),this.#E?.refreshIdentity(),this.#h!==void 0&&this.#n.setupFlow!==void 0&&(i=automaticSetupCommand(this.#w),t=i?.prompt);;){if(!s){if(t==null){if(!this.#n.readPrompt){if(o)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let n={title:e};c!==void 0&&(n.initialDraft=c,c=void 0);try{t=await this.#V(n)}catch(e){if(isInterruptedError(e))return;throw e}if(t==null)return}let l=parsePromptCommand(t);if(l?.type===`exit`)return;if(l?.type===`new`){this.#B(),a=void 0,s=!1,t=void 0,this.#n.reset?.();continue}if(l?.type===`help`){this.#J(formatPromptCommandHelp(this.#g)),a=void 0,s=!1,t=void 0;continue}if(l?.type===`loglevel`){this.#J(this.#ee(l.argument)),a=void 0,s=!1,t=void 0;continue}if(l?.type===`extension`){try{let t=l.name===`model`?i?.initialModelStep:void 0;i=void 0,await this.#Q(l,e,`command`,t)}catch(e){if(isInterruptedError(e))return;throw e}a=void 0,t=void 0,s=!1;continue}o=!0}let l=await this.#H({prompt:s?void 0:t,inputResponses:a});try{await this.#n.renderStream(l,{title:e,submittedPrompt:t,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let n=l.turnState?.pendingApprovals??[],r=l.turnState?.pendingQuestions??[];if(n.length>0||r.length>0){let i=[];if(n.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let t of n){let n=await this.#n.readToolApproval(t,{title:e});i.push({requestId:t.approvalId,optionId:n.approved?`approve`:`deny`}),this.#k.delete(t.approvalId)}}if(r.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 r){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let a={requestId:t.requestId};r.optionId!==void 0&&(a.optionId=r.optionId),r.text!==void 0&&(a.text=r.text),i.push(a),this.#k.delete(t.requestId)}}s=!0,a=i,t=void 0;continue}l.turnState&&l.turnState.boundaryEvent===void 0&&(this.#P=!0)}catch(e){if(isInterruptedError(e))return;throw e}s=!1,a=void 0,t=void 0,this.#P&&(this.#P=!1,this.#B(),this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`))}}#B(){for(let e of this.#j.values())e.abort();this.#j.clear(),this.#A.clear(),this.#k.clear(),this.#M.clear(),this.#N.clear(),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}async#V(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.#re(),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#H(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.#re(),session:this.#e})),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),r=await this.#e.send(n)}catch(e){if(isInterruptedError(e))throw e;return this.#_?.reportFailure(e),this.#P=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}let i=createTurnState();return{abort:()=>t.abort(),events:eveEventsToTUIStream({events:r,pendingInputRequests:this.#k,subagentRuns:this.#A,turnState:i,onSubagentCalled:e=>this.#se(e),onSubagentCompleted:e=>this.#le(e),onConnectionAuthRequired:e=>this.#ie(e),onConnectionAuthCompleted:e=>this.#ae(e),onTerminalFailure:()=>{this.#P=!0},failureOverride:this.#p===void 0?void 0:e=>isGatewayAuthFailure(e)?formatGatewayAuthFailureNotice(e):void 0}),turnState:i}}async#U(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#w=await detectSetupIssues(t,this.#v),this.#n.renderSetupWarning!==void 0&&(this.#W(),this.#G())}#W(){let e=orderedSetupIssues(this.#w,this.#T);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#G(){let e=this.#p;if(e===void 0)return;let t;try{t=await this.#y(e,{signal:this.#S.signal})}catch{return}this.#x||this.#C||(this.#T=authIssueForStatus(t),this.#W())}async#K(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n={appRoot:t,env:process.env};e!==void 0&&(n.info=e);try{this.#w=await detectSetupIssues(n,this.#v);let e=await this.#y(t,{signal:this.#S.signal});this.#T=authIssueForStatus(e)}catch{return}this.#x||this.#W()}#q(){this.#p===void 0||this.#n.renderSandboxLog===void 0||this.#F===void 0&&(this.#F=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#J(e){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}}async#Y(e,t){let n=this.#h;return n===void 0?{message:`/${e.name} is not available in this session.`}:await n.handle(e,{renderer:this.#n,title:t.title,initialModelStep:t.initialModelStep,remoteConnection:this.#_})}#X(e,t){if(t!==`startup`)return;let n=this.#_?.current().connection.state,r=n===`auth-failed`||n===`unavailable`?`failed`:void 0,i=e.argument.length===0?``:` ${e.argument}`;this.#n.renderCommandInvocation?.(`/${e.name}${i}`,r)}async#Z(e){if(e?.kind===`model-access-changed`){this.#E?.applyEffect({kind:`refresh-identity`}),this.#C=!0,await this.#te();return}e!==void 0&&(this.#E?.applyEffect(e),this.#C=!0,this.#K(this.#O))}async#Q(e,t,n,r){let i=await this.#Y(e,{initialModelStep:r,title:t});this.#X(e,n),this.#J(i?.message),await this.#Z(i?.effect),this.#$()}#$(){let e=this.#_?.current().connection;e?.state!==`ready`||e.info===this.#O||(this.#O=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}#ee(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#te(){let e=this.#p;if(e===void 0)return;loadDevelopmentEnvironmentFiles(e);let t=this.#L(await this.#ne());this.#K(t)}async#ne(){try{return await this.#t?.info()}catch{return}}async#re(){let e=this.#O,t=await this.#ne();t!==void 0&&this.#L(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#ie(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.#M.set(e.data.name,t),this.#oe(t)}#ae(e){let t=this.#M.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.#M.set(e.data.name,t),this.#N.delete(e.data.name),this.#oe(t),this.#n.setConnectionAuthPendingCount?.(this.#N.size)}#oe(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)}#se(e){let t=e.data.callId;if(this.#j.has(t))return;let n=this.#t;if(!n)return;let r=new AbortController;this.#j.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.#ue(t,e),isCurrentTurnBoundaryEvent(e)))break}catch(e){if(!isAbortLikeError(e)){let n=toErrorMessage(e),r=this.#A.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.#j.delete(t)}})()}#ce(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})}#le(e){let t=this.#A.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}}#ue(e,t){let n=this.#A.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.#ce(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.#ce(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,availablePromptCommands:e.availablePromptCommands,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 r=failureKey(e);if(t.has(r))return;t.add(r);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};
|
|
@@ -15,13 +15,13 @@ export type TuiSetupCommand = PromptCommandExtensionName;
|
|
|
15
15
|
* move past their opening question.
|
|
16
16
|
*/
|
|
17
17
|
export declare const SETUP_FLOW_CONFIG: {
|
|
18
|
-
vc: {
|
|
18
|
+
"vc:install": {
|
|
19
19
|
title: string;
|
|
20
|
-
indicator: "
|
|
20
|
+
indicator: "pulse";
|
|
21
21
|
};
|
|
22
|
-
login: {
|
|
22
|
+
"vc:login": {
|
|
23
23
|
title: string;
|
|
24
|
-
indicator: "
|
|
24
|
+
indicator: "pulse";
|
|
25
25
|
};
|
|
26
26
|
model: {
|
|
27
27
|
title: string;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createTuiPrompter}from"./tui-prompter.js";import{runDeployFlow}from"#setup/flows/deploy.js";import{WizardCancelledError}from"#setup/step.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{runChannelsFlow}from"#setup/flows/channels.js";import{runInstallVercelCliFlow}from"#setup/flows/install-vercel-cli.js";import{
|
|
2
|
-
`),preserveFlowDiagnostics:!1};return n.providerOutcome!==void 0&&(a.effect={kind:`model-access-changed`}),a}case`channels`:{let e=await p.runChannelsFlow({appRoot:f,prompter:
|
|
1
|
+
import{createTuiPrompter}from"./tui-prompter.js";import{runDeployFlow}from"#setup/flows/deploy.js";import{WizardCancelledError}from"#setup/step.js";import{runLoginFlow}from"#setup/flows/login.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{runChannelsFlow}from"#setup/flows/channels.js";import{runInstallVercelCliFlow}from"#setup/flows/install-vercel-cli.js";import{runModelFlow}from"#setup/flows/model.js";import{runProviderFlow}from"#setup/flows/provider.js";import{openUrl}from"#setup/primitives/open-url.js";import{slackMessageDeepLink}from"#setup/slack-connect.js";const SETUP_FLOW_CONFIG={"vc:install":{title:`Install the Vercel CLI`,indicator:`pulse`},"vc:login":{title:`Log in to Vercel`,indicator:`pulse`},model:{title:`Configure the agent model`,indicator:`pulse`},channels:{title:`Agent channels`,indicator:`pulse`},deploy:{title:`Deploy to Vercel`,indicator:`spinner`}};function muteableRenderer(e,t){return{readSelect:n=>t()?Promise.resolve(void 0):e.readSelect(n),readEditableSelect:n=>t()?Promise.resolve(void 0):e.readEditableSelect(n),readProviderPicker:n=>t()?Promise.resolve(void 0):e.readProviderPicker(n),readText:n=>t()?Promise.resolve(void 0):e.readText(n),readAcknowledge:n=>t()?Promise.resolve():e.readAcknowledge(n),readChoice:n=>t()?{choice:Promise.resolve(void 0),close:()=>{}}:e.readChoice(n),setStatus:n=>{t()||e.setStatus(n)},renderLine:(n,r)=>{(!t()||r===`warning`||r===`error`)&&e.renderLine(n,r)},renderOutput:n=>{t()||e.renderOutput(n)}}}async function runTuiSetupCommand(t){let{command:r}=t,i=!1,a=new AbortController,o=muteableRenderer(t.renderer,()=>i),s=(t.createPrompter??createTuiPrompter)(o),c=t.renderer.waitForInterrupt(),l=Symbol(`interrupted`),u=executeSetupCommand(t,s,o,a.signal);try{let e=await Promise.race([u,c.promise.then(()=>l)]);return e===l?(i=!0,a.abort(new WizardCancelledError),{...await u,message:`/${r} interrupted.`,preserveFlowDiagnostics:!0}):e}finally{c.dispose(),t.renderer.setStatus(void 0)}}async function executeSetupCommand(e,i,l,u){let{command:d,appRoot:f}=e,p={runInstallVercelCliFlow,runLoginFlow,runModelFlow,runChannelsFlow,runDeployFlow,...e.flows};try{switch(d){case`vc:install`:return installVercelCliResultMessage(await p.runInstallVercelCliFlow({appRoot:f,prompter:i,signal:u}));case`vc:login`:return loginResultMessage(await p.runLoginFlow({appRoot:f,prompter:i,signal:u}));case`model`:{let pickProvider=e=>l.readProviderPicker(e),t={appRoot:f,prompter:i,signal:u,deps:{runProviderFlow:e=>runProviderFlow({...e,picker:pickProvider})}};e.initialModelStep!==void 0&&(t.initialStep=e.initialModelStep);let n=await p.runModelFlow(t);if(n.kind===`cancelled`)return{message:`/model cancelled.`,preserveFlowDiagnostics:!1};let r=[];n.modelMessage!==void 0&&r.push(n.modelMessage),n.providerOutcome!==void 0&&r.push(providerOutcomeMessage(n.providerOutcome));let a={message:r.join(`
|
|
2
|
+
`),preserveFlowDiagnostics:!1};return n.providerOutcome!==void 0&&(a.effect={kind:`model-access-changed`}),a}case`channels`:{let e=await p.runChannelsFlow({appRoot:f,prompter:i,signal:u});switch(e.kind){case`failed`:return pendingChannelsResult(`Channel files changed, but /channels failed: ${e.message}`);case`cancelled`:return{message:`/channels cancelled.`,preserveFlowDiagnostics:!0};case`deploy-and-chat`:return await runDeployAndChat(p,{appRoot:f,prompter:i,signal:u},e.chat);case`done`:return e.addedChannels.length===0?{message:`No channels added.`,preserveFlowDiagnostics:!0}:{message:`Channels added: ${e.addedChannels.join(`, `)} — run /deploy to ship them.`,preserveFlowDiagnostics:!0,effect:{kind:`channels-added`}}}}case`deploy`:{let e=await p.runDeployFlow({appRoot:f,prompter:i,interactive:!0,signal:u});return e.kind===`cancelled`?{message:`/deploy cancelled.`,preserveFlowDiagnostics:!0}:e.kind===`needs-link`?{message:`Not linked to a Vercel project — run /model to connect one first.`,preserveFlowDiagnostics:!0}:{message:e.productionUrl===void 0?`Deployed.`:`Deployed: ${e.productionUrl}`,preserveFlowDiagnostics:!0,effect:{kind:`deployed`}}}}}catch(e){if(e instanceof WizardCancelledError)return{message:`/${d} cancelled.`,preserveFlowDiagnostics:d!==`model`};let t=vercelActionOutcome(e,d);return t===void 0?{message:`/${d} failed: ${e instanceof Error?e.message:String(e)}`,preserveFlowDiagnostics:!0}:t}}function vercelActionOutcome(e,t){if(!(e instanceof HumanActionRequiredError))return;let n=vercelActionMessage(e.action.kind,t);return n===void 0?void 0:{message:n,preserveFlowDiagnostics:!0}}function vercelActionMessage(e,t){switch(e){case`vercel-login`:return`You're not logged in to Vercel — run /vc:login, then retry /${t}.`;case`vercel-forbidden`:return`Vercel denied access to that team — run /vc:login to re-authenticate (for example to complete SSO), or pick a team you can access, then retry /${t}.`;case`vercel-cli-missing`:return`The Vercel CLI isn't installed — run /vc:install to install it, then retry /${t}.`;default:return}}async function runDeployAndChat(e,t,r){let i;try{i=await e.runDeployFlow({...t,interactive:!0})}catch(e){if(e instanceof WizardCancelledError)return pendingChannelsResult(`Channels added, but /deploy was cancelled. Run /deploy to ship them.`);let t=vercelActionOutcome(e,`deploy`);return pendingChannelsResult(t===void 0?`Channels added, but /deploy failed: ${e instanceof Error?e.message:String(e)}`:`Channels added. ${t.message}`)}if(i.kind===`cancelled`)return pendingChannelsResult(`Channels added, but /deploy was cancelled. Run /deploy to ship them.`);if(i.kind===`needs-link`)return pendingChannelsResult(`Channels added, but this directory is not linked to Vercel. Run /model, then /deploy.`);let a=i.productionUrl===void 0?`Deployed.`:`Deployed: ${i.productionUrl}`,o;if(r.chatUrl===void 0)o=`Message your agent in Slack to see it live.`;else{let e=slackMessageDeepLink(r.chatUrl);openUrl(e),o=`Chat with your agent in Slack: ${e}`}return{message:`${a}\n${o}`,preserveFlowDiagnostics:!0,effect:{kind:`deployed`}}}function installVercelCliResultMessage(e){switch(e.kind){case`cancelled`:return{message:`/vc:install cancelled.`,preserveFlowDiagnostics:!1};case`already`:return{message:`The Vercel CLI is already installed.`,preserveFlowDiagnostics:!1};case`failed`:return{message:"Couldn't install the Vercel CLI — install it manually with `npm i -g vercel@latest`.",preserveFlowDiagnostics:!0};case`installed`:return{message:`Installed the Vercel CLI. Run /vc:login next.`,preserveFlowDiagnostics:!1,effect:{kind:`refresh-identity`}}}}function loginResultMessage(e){switch(e.kind){case`cancelled`:return{message:`/vc:login cancelled.`,preserveFlowDiagnostics:!1};case`already`:return{message:`You're already logged in to Vercel.`,preserveFlowDiagnostics:!1};case`cli-missing`:return{message:`The Vercel CLI isn't installed — run /vc:install to install it, then retry /vc:login.`,preserveFlowDiagnostics:!0};case`failed`:return{message:`Vercel login didn't complete — run /vc:login to try again.`,preserveFlowDiagnostics:!0};case`logged-in`:return{message:`Logged in to Vercel.`,preserveFlowDiagnostics:!1,effect:{kind:`refresh-identity`}};case`unavailable`:return{message:`Couldn't reach Vercel — check your connection, then retry /vc:login.`,preserveFlowDiagnostics:!0}}}function pendingChannelsResult(e){return{message:e,preserveFlowDiagnostics:!0,effect:{kind:`channels-added`}}}function providerOutcomeMessage(e){let{credential:t,status:n}=e;return n.kind===`gateway-project`?t===void 0?`Project linked. No model credential found; set AI_GATEWAY_API_KEY in .env.local.`:`Project linked. Connected to AI Gateway via ${t}.`:n.kind===`gateway-key`?`Connected to AI Gateway via ${n.envKey} in ${n.envFile}.`:`Provider updated — no gateway credential detected; set AI_GATEWAY_API_KEY in .env.local.`}export{SETUP_FLOW_CONFIG,runTuiSetupCommand};
|
|
@@ -52,7 +52,7 @@ export declare const LOGIN_SETUP_ISSUE: SetupIssue;
|
|
|
52
52
|
* The CLI-missing hint, surfaced by the same off-critical-path probe as
|
|
53
53
|
* {@link LOGIN_SETUP_ISSUE}. When the `vercel` binary is absent the probe
|
|
54
54
|
* reports this instead of the login hint, so the diagnostic points at its fix
|
|
55
|
-
* command (`/vc`) rather than a logged-out state the probe can't determine.
|
|
55
|
+
* command (`/vc:install`) rather than a logged-out state the probe can't determine.
|
|
56
56
|
*/
|
|
57
57
|
export declare const CLI_MISSING_SETUP_ISSUE: SetupIssue;
|
|
58
58
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join}from"node:path";import{pathExists}from"#setup/path-exists.js";function hasEnvValue(e,t){let n=e[t];return n!==void 0&&n.trim().length>0}function resolveModelProviderState(e,t){let n=modelProviderAccess({env:t,info:e});if(e===void 0||n.kind!==`gateway`||n.runtime.status!==`connected`)return e;let{credential:r}=n.runtime,i=e.agent.model,a=i.endpoint;return a?.kind===`gateway`&&a.connected&&a.credential===r?e:{...e,agent:{...e.agent,model:{...i,endpoint:{kind:`gateway`,connected:!0,credential:r}}}}}function modelProviderAccess(e){let t=e.info?.agent.model;if(t?.routing?.kind===`external`)return{kind:`external`};if(t?.routing?.kind!==`gateway`)return{kind:`unknown`};if(hasEnvValue(e.env,`AI_GATEWAY_API_KEY`))return{kind:`gateway`,runtime:{status:`connected`,credential:`api-key`}};let n=t.endpoint;return n?.kind===`gateway`&&n.connected?{kind:`gateway`,runtime:{status:`connected`,credential:n.credential}}:hasEnvValue(e.env,`VERCEL_OIDC_TOKEN`)?{kind:`gateway`,runtime:{status:`connected`,credential:`oidc`}}:n?.kind===`gateway`?{kind:`gateway`,runtime:{status:`disconnected`}}:{kind:`gateway`,runtime:{status:`unknown`}}}const BOOT_DETECTIONS=[{id:`model-provider`,async detect({appRoot:n,env:r,info:i}){let a=modelProviderAccess({env:r,info:i});if(a.kind===`external`)return[];if(a.kind===`gateway`){if(a.runtime.status===`connected`)return[];if(a.runtime.status===`disconnected`)return[{kind:`model-provider-unconfigured`,label:await pathExists(join(n,`.vercel`,`project.json`))?`AI Gateway credentials missing`:`model provider not linked`,command:`/model`}]}return await pathExists(join(n,`.vercel`,`project.json`))?[{kind:`attention`,label:`AI Gateway credentials missing`,command:`/model`}]:[{kind:`attention`,label:`model provider not linked`,command:`/model`}]}}],LOGIN_SETUP_ISSUE={kind:`attention`,label:`not logged in`,command:`/login`},CLI_MISSING_SETUP_ISSUE={kind:`attention`,label:`Vercel CLI not found`,command:`/vc`};async function detectSetupIssues(e,t=BOOT_DETECTIONS){return(await Promise.all(t.map(async t=>{try{return await t.detect(e)}catch{return[]}}))).flat()}function orderedSetupIssues(e,t){return t===void 0?[...e]:[t,...e]}function automaticSetupCommand(e){return e.some(e=>e.kind===`model-provider-unconfigured`)?{prompt:`/model`,initialModelStep:`provider`}:void 0}function formatSetupIssuesLine(e){let t=e.length===1?`setup issue`:`setup issues`,n=e.map(e=>`${e.label} · ${e.command}`).join(`, `);return`${e.length} ${t}: ${n}`}export{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,automaticSetupCommand,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState};
|
|
1
|
+
import{join}from"node:path";import{pathExists}from"#setup/path-exists.js";function hasEnvValue(e,t){let n=e[t];return n!==void 0&&n.trim().length>0}function resolveModelProviderState(e,t){let n=modelProviderAccess({env:t,info:e});if(e===void 0||n.kind!==`gateway`||n.runtime.status!==`connected`)return e;let{credential:r}=n.runtime,i=e.agent.model,a=i.endpoint;return a?.kind===`gateway`&&a.connected&&a.credential===r?e:{...e,agent:{...e.agent,model:{...i,endpoint:{kind:`gateway`,connected:!0,credential:r}}}}}function modelProviderAccess(e){let t=e.info?.agent.model;if(t?.routing?.kind===`external`)return{kind:`external`};if(t?.routing?.kind!==`gateway`)return{kind:`unknown`};if(hasEnvValue(e.env,`AI_GATEWAY_API_KEY`))return{kind:`gateway`,runtime:{status:`connected`,credential:`api-key`}};let n=t.endpoint;return n?.kind===`gateway`&&n.connected?{kind:`gateway`,runtime:{status:`connected`,credential:n.credential}}:hasEnvValue(e.env,`VERCEL_OIDC_TOKEN`)?{kind:`gateway`,runtime:{status:`connected`,credential:`oidc`}}:n?.kind===`gateway`?{kind:`gateway`,runtime:{status:`disconnected`}}:{kind:`gateway`,runtime:{status:`unknown`}}}const BOOT_DETECTIONS=[{id:`model-provider`,async detect({appRoot:n,env:r,info:i}){let a=modelProviderAccess({env:r,info:i});if(a.kind===`external`)return[];if(a.kind===`gateway`){if(a.runtime.status===`connected`)return[];if(a.runtime.status===`disconnected`)return[{kind:`model-provider-unconfigured`,label:await pathExists(join(n,`.vercel`,`project.json`))?`AI Gateway credentials missing`:`model provider not linked`,command:`/model`}]}return await pathExists(join(n,`.vercel`,`project.json`))?[{kind:`attention`,label:`AI Gateway credentials missing`,command:`/model`}]:[{kind:`attention`,label:`model provider not linked`,command:`/model`}]}}],LOGIN_SETUP_ISSUE={kind:`attention`,label:`not logged in`,command:`/vc:login`},CLI_MISSING_SETUP_ISSUE={kind:`attention`,label:`Vercel CLI not found`,command:`/vc:install`};async function detectSetupIssues(e,t=BOOT_DETECTIONS){return(await Promise.all(t.map(async t=>{try{return await t.detect(e)}catch{return[]}}))).flat()}function orderedSetupIssues(e,t){return t===void 0?[...e]:[t,...e]}function automaticSetupCommand(e){return e.some(e=>e.kind===`model-provider-unconfigured`)?{prompt:`/model`,initialModelStep:`provider`}:void 0}function formatSetupIssuesLine(e){let t=e.length===1?`setup issue`:`setup issues`,n=e.map(e=>`${e.label} · ${e.command}`).join(`, `);return`${e.length} ${t}: ${n}`}export{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,automaticSetupCommand,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Theme } from "./theme.js";
|
|
2
2
|
import type { LogDisplayMode } from "./log-display-mode.js";
|
|
3
|
+
import type { RemoteConnectionSnapshot } from "./remote-connection.js";
|
|
3
4
|
import type { VercelStatusSnapshot } from "./vercel-status.js";
|
|
4
5
|
import type { ModelEndpointStatus } from "#shared/model-endpoint-status.js";
|
|
5
6
|
export interface StatusLineInput {
|
|
@@ -18,23 +19,14 @@ export interface StatusLineInput {
|
|
|
18
19
|
endpoint?: ModelEndpointStatus;
|
|
19
20
|
/** Workspace-scoped Vercel state; identity absent while unlinked or still resolving. */
|
|
20
21
|
vercel?: VercelStatusSnapshot;
|
|
22
|
+
/** Remote server identity and its current connection/authentication state. */
|
|
23
|
+
remote?: RemoteConnectionSnapshot;
|
|
21
24
|
theme: Theme;
|
|
22
25
|
width: number;
|
|
23
26
|
}
|
|
24
27
|
/**
|
|
25
|
-
* Builds
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
* The model-endpoint segment folds in the linked project name when connected
|
|
30
|
-
* (`AI Gateway (project)`), drops to a bare `AI Gateway` when connected without
|
|
31
|
-
* a linked project, and goes yellow with a `⚠` when the gateway has no usable
|
|
32
|
-
* credential. Everything else renders dim except the yellow action signals (a
|
|
33
|
-
* pending deploy, the not-connected gateway). On narrow widths segments degrade
|
|
34
|
-
* in order, the endpoint first and then the model, keeping tokens and the
|
|
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.
|
|
28
|
+
* Builds `↗ project (environment) · model · tokens · /deploy pending`.
|
|
29
|
+
* Remote sessions omit endpoint state and keep their badge as the final
|
|
30
|
+
* narrow-width fallback. Returns undefined when every segment is empty.
|
|
39
31
|
*/
|
|
40
32
|
export declare function buildStatusLine(input: StatusLineInput): string | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{clipVisible,stripAnsi,visibleLength}from"./terminal-text.js";import{remoteHost}from"./target.js";function renderModel(e){if(e.model===void 0)return;let n=e.remote===void 0?e.model:stripAnsi(e.model).replace(/\s+/gu,` `).trim();return e.theme.colors.dim(n)}function renderEndpoint(e){if(e.remote!==void 0||e.endpoint===void 0)return;let t=e.theme.colors;if(e.endpoint.kind===`external`)return t.dim(`External endpoint`);if(!e.endpoint.connected)return t.yellow(`${e.theme.glyph.warning} AI Gateway`);let n=e.vercel?.identity?.projectName;return t.dim(n===void 0?`AI Gateway`:`AI Gateway (${n})`)}function buildStatusLine(t){let{theme:r,width:i}=t,a=r.colors,o=t.logLevel===void 0?void 0:a.cyan(`logs: ${t.logLevel}`),s=renderModel(t),c=t.tokens===void 0?void 0:a.dim(t.tokens),l=t.vercel?.pendingDeploy?a.yellow(`/deploy pending`):void 0,u=t.remote===void 0?void 0:formatRemoteStatus(t.remote,r),d=renderEndpoint(t),f=` ${a.dim(r.glyph.dot)} `,compose=e=>e.filter(e=>e!==void 0).join(f),p=[compose([u?.full,o,s,c,d,l]),compose([u?.full,o,s,c,l]),compose([u?.full,o,c,l]),compose([u?.full,o]),compose([u?.badge,o]),compose([u?.badge])];if(p[0].length!==0){for(let e of p)if(e.length>0&&visibleLength(e)<=i)return e;return clipVisible(p.findLast(e=>e.length>0),i)}}function formatRemoteStatus(e,t){let n=t.colors,i=e.deployment===void 0?remoteHost(e.target):`${e.deployment.projectName} (${e.deployment.environment})`,a=formatRemoteBadge(` ${t.unicode?`↗`:`->`} ${i} `,e.connection.state,t),o=` ${n.dim(t.glyph.dot)} `,s;switch(e.connection.state){case`checking`:s=n.dim(`Checking access…`);break;case`ready`:break;case`auth-required`:s=n.yellow(`Authenticate via OIDC`);break;case`authenticating`:s=n.dim(`Authenticating via OIDC…`);break;case`auth-failed`:s=n.yellow(`Authentication failed`);break;case`unavailable`:s=n.yellow(`Remote unavailable`);break}return{badge:a,full:s===void 0?a:`${a}${o}${s}`}}function formatRemoteBadge(e,t,n){let r=n.colors;switch(t){case`checking`:return r.inverse(r.gray(e));case`ready`:return r.inverse(r.blue(e));case`unavailable`:case`auth-required`:case`authenticating`:case`auth-failed`:return r.inverse(r.yellow(e))}}export{buildStatusLine};
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { AgentTUIInputQuestion, AgentTUIInputQuestionResponse, AgentTUIRenderer, AgentTUISessionOptions, AgentTUIStreamResult, AgentTUIToolApprovalRequest, AgentTUIToolApprovalResponse, ConnectionAuthUpdate, SubagentStepUpdate, SubagentToolUpdate } from "./runner.js";
|
|
2
|
+
import { type PromptCommandSpec } from "./prompt-commands.js";
|
|
2
3
|
import type { SetupFlowRenderer } from "./setup-flow.js";
|
|
3
4
|
import type { AssistantResponseStatsMode, LogDisplayMode, TerminalPartDisplayMode } from "./types.js";
|
|
4
5
|
import type { AgentInfoResult } from "#client/index.js";
|
|
5
6
|
import type { VercelStatusSnapshot } from "./vercel-status.js";
|
|
7
|
+
import type { RemoteConnectionSnapshot } from "./remote-connection.js";
|
|
6
8
|
export type TerminalInput = {
|
|
7
9
|
isTTY?: boolean;
|
|
8
10
|
on(event: "data", listener: (chunk: Buffer) => void): TerminalInput;
|
|
@@ -32,6 +34,8 @@ export type TerminalRendererOptions = {
|
|
|
32
34
|
logs?: LogDisplayMode;
|
|
33
35
|
color?: boolean;
|
|
34
36
|
unicode?: boolean;
|
|
37
|
+
/** Slash commands available in this local or remote session. */
|
|
38
|
+
availablePromptCommands?: readonly PromptCommandSpec[];
|
|
35
39
|
};
|
|
36
40
|
export type AgentHeaderOptions = {
|
|
37
41
|
name: string;
|
|
@@ -63,6 +67,7 @@ export declare class TerminalRenderer implements AgentTUIRenderer {
|
|
|
63
67
|
upsertConnectionAuth(update: ConnectionAuthUpdate): void;
|
|
64
68
|
setConnectionAuthPendingCount(count: number): void;
|
|
65
69
|
setVercelStatus(status: VercelStatusSnapshot): void;
|
|
70
|
+
setRemoteConnectionStatus(status: RemoteConnectionSnapshot): void;
|
|
66
71
|
reset(): void;
|
|
67
72
|
/**
|
|
68
73
|
* Commits a single dim informational line to the transcript (e.g. the
|
|
@@ -74,13 +79,15 @@ export declare class TerminalRenderer implements AgentTUIRenderer {
|
|
|
74
79
|
/**
|
|
75
80
|
* Sets the setup attention line (yellow `⚠`, commands blue) as a live footer
|
|
76
81
|
* element above the prompt. Unlike committed scrollback, it can be cleared:
|
|
77
|
-
* once the underlying issue is fixed (e.g. `/login` succeeds) the runner calls
|
|
82
|
+
* once the underlying issue is fixed (e.g. `/vc:login` succeeds) the runner calls
|
|
78
83
|
* {@link clearSetupWarning} and the line disappears rather than lingering
|
|
79
84
|
* stale in the transcript.
|
|
80
85
|
*/
|
|
81
86
|
renderSetupWarning(text: string): void;
|
|
82
87
|
/** Removes the setup attention line once its issue is resolved. */
|
|
83
88
|
clearSetupWarning(): void;
|
|
89
|
+
/** Commits a slash-command invocation that was started without prompt input. */
|
|
90
|
+
renderCommandInvocation(text: string, status?: "failed"): void;
|
|
84
91
|
/**
|
|
85
92
|
* Commits one command's outcome under its invocation with the elbow
|
|
86
93
|
* connector (` ⎿ /model cancelled.`), Claude Code's sub-result grammar.
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{toErrorMessage}from"#shared/errors.js";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{StringDecoder}from"node:string_decoder";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.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=[];#
|
|
2
|
-
`);if(this.#
|
|
3
|
-
`),live:!1}),this.#Ye({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#dt()}}async#ve(e){let t=this.#we(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a={options:i,searchAction:r,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(a.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(a.initialValues=e.initialValues);let o=initialSelectState(a),s,c=!1,l=0,isCurrentSearch=e=>e===l,clearSearch=()=>{l+=1,c=!1,o=reduceSelect(o,{type:`clear`},{options:i,searchAction:r,submitRow:n}),this.#dt()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#dt();try{let s=await t(e);if(!isCurrentSearch(a))return;let c=o.filter;i=s,o={...initialSelectState({options:s,searchAction:r,submitRow:n}),filter:c}}catch(e){isCurrentSearch(a)&&(s=toErrorMessage(e))}finally{isCurrentSearch(a)&&(c=!1,this.#dt())}},u=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}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#vt()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#dt(),await this.#De((t,a)=>{let close=e=>{l+=1,a(e)};if(c){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#dt();return}let u={key:t,options:i,searchAction:r,select:o},d=reduceSetupSelectInput(n?{...u,kind:e.kind,required:e.required}:{...u,kind:e.kind});switch(d.kind){case`cancel`:close(void 0);return;case`repaint`:this.#dt();return;case`update`:o=d.select,s=void 0,this.#dt();return;case`submit`:{let e=searchActionQuery(d.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(d.values);return}loadSearch(e,t);return}case`error`:s=d.message,this.#dt();return;case`ignore`:return}}).promise}#ye(e){this.#Pe();let t=this.#Te();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#dt();let r=this.#De((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.#dt();return;case`repaint`:this.#dt();return;case`submit`:n!==void 0&&r(e.actions[n].value);return;case void 0:return}},()=>{t.status=void 0});return{choice:r.promise,close:()=>r.settle(void 0)}}async#be(e){let t=this.#we(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#I,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?(i.text.length===0&&(i=lineOf(e.editable.defaultValue)),this.#Ue()):(i=lineOf(``),this.#We())};return syncEditableRow(),this.#dt(),await this.#De((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Ge(),this.#dt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#dt()},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.#dt();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.#dt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#We()).promise}async#xe(e){let t=this.#we(),n=initialProviderPickerState(e.options,e.initialValue),r;t.question=t=>renderSelectQuestion({kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#I,editor:{kind:`key`,phase:n.phase}}},this.#r,t);let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#Ue():this.#We()};return syncCaret(),this.#dt(),await this.#De((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#dt();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#dt();return;case`validate`:{n=o.state,syncCaret(),this.#dt();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#dt();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#Ge(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#We()}).promise}async#Se(e){let t=this.#we(),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.#Ue(),this.#dt(),await this.#De((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Ge(),this.#dt()},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.#dt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#dt();return}i(t);return}default:return}},()=>this.#We()).promise}async#Ce(e){let t=this.#we();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#dt(),await this.#De((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#dt();return;default:return}}).promise}#we(){return this.#Pe(),this.#k=!1,this.#j={kind:`idle`},this.#M=``,this.#Te()}#Te(){return this.#le===void 0&&(this.#le={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[]}),this.#le}#Ee(){this.#le!==void 0&&(this.#le.question=void 0,this.#le.hideLinesWhileQuestion=!1),this.#H=void 0,this.#Le(),this.#ke(),this.#dt()}#De(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Ee(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Ee(),i(e))};return this.#H=t=>e(t,settle,reject),this.#Ie(),{promise:a,settle}}#Oe(){let e,t=new Promise(t=>{e=t});return this.#de=e,this.#ke(),{promise:t,dispose:()=>{this.#de===e&&(this.#de=void 0,this.#Ae())}}}#ke(){if(this.#de===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#de;this.#de=void 0,this.#Ae(),e?.();return}e.type===`ctrl-r`&&this.#dt()};this.#fe=consumer,this.#H=consumer,this.#Ie()}#Ae(){this.#fe!==void 0&&(this.#H===this.#fe&&this.#Le(),this.#fe=void 0)}#je(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#le!==void 0){this.#le.status=t,t===void 0&&(this.#le.preview=void 0),this.#dt();return}if(t===void 0){this.#j={kind:`idle`},this.#M=``,this.#Je(),this.#dt();return}this.#Pe(),this.#qe(),this.#M=t,this.#dt()}#Me(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#le;if(r!==void 0){if(r.preview=void 0,t===`warning`||t===`error`)for(let e of r.outputBuffer)r.lines.push({text:e,tone:`info`,evidence:!0});r.outputBuffer=[],r.lines.push({text:n,tone:t}),this.#dt();return}this.#Pe(),this.#Ye({kind:`flow`,title:t,body:n,live:!1}),this.#dt()}#Ne(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#le;if(n===void 0){this.#Me(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#dt()}shutdown(){this.#Fe()}#Pe(e){this.#N=e?.title??this.#N,this.#Q=e?.contextSize??this.#l,!this.#P&&(this.#P=!0,this.#n.reset(),this.#n.hideCursor(),this.#Et(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#K=()=>this.#dt(),this.#t.on(`resize`,this.#K))}#Fe(){this.#Le(),this.#We(),this.#Je(),this.#B!==void 0&&(clearTimeout(this.#B),this.#B=void 0),this.#V=!1,this.#P&&=(this.#Pt(),this.#dt(),this.#n.clear(),this.#n.showCursor(),this.#Dt(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#K&&=(this.#t.off(`resize`,this.#K),void 0),!1)}#Ie(){this.#e.off(`data`,this.#Re),this.#e.on(`data`,this.#Re)}#Le(){this.#e.off(`data`,this.#Re),this.#Ve(),this.#U=``,this.#W=new StringDecoder(`utf8`),this.#H=void 0}#Re=e=>{this.#Ve(),this.#U+=this.#W.write(e),this.#Be(),this.#ze()};#ze(){if(this.#U===`\x1B`){this.#G=setTimeout(()=>{this.#U===`\x1B`&&(this.#U=``,this.#H?.({type:`escape`}))},30),this.#G.unref?.();return}if(isIncompletePaste(this.#U)){let e=this.#U;this.#G=setTimeout(()=>{if(this.#U!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#U=``,t.length>0&&this.#H?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#G.unref?.()}}#Be(){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)}}#Ve(){this.#G&&=(clearTimeout(this.#G),void 0)}#He(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#dt();break;case`ctrl-c`:this.#F||(this.#F=!0,this.#j={kind:`idle`},this.#M=`Interrupted`,this.#q?.(),this.#dt());break;default:break}}#Ue(){this.#We(),this.#Ge(),this.#R=setInterval(()=>{this.#I=!this.#I,this.#dt()},500),this.#R.unref?.()}#We(){this.#R&&=(clearInterval(this.#R),void 0),this.#I=!0}#Ge(){this.#I=!0}#Ke(){this.#Je(),this.#z=setInterval(()=>{this.#L+=1,this.#dt()},90),this.#z.unref?.()}#qe(){this.#j={kind:`waiting`,startedAtMs:Date.now()},this.#Ke()}#Je(){this.#z&&=(clearInterval(this.#z),void 0)}#Ye(e){e.id!==this.#oe?.id&&this.#Pt(),this.#f.push(e),e.id&&this.#p.set(e.id,e)}#Xe(e){this.#Ye({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#dt()}#Ze(e){if(e!=null){if(this.#ce===e){this.#ce=void 0;return}this.#Ye({kind:`user`,body:stripTerminalControls(e),live:!1})}}#Qe(e,t,n){let r={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};n!==void 0&&(r.detail=stripTerminalControls(n)),this.#Ye(r),this.#dt()}#$e(e,t){this.#v.has(e)||(this.#v.add(e),this.#Ye({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#et(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.#Ye(e)}#tt(e){this.#f=this.#f.filter(t=>t.id!==e),this.#p.delete(e)}#nt(){for(let e of this.#f)e.status===`approval`||e.status===`running`||(e.live=!1)}#rt(e,t,n){switch(e.type){case`step-start`:this.#it(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#ut(e.usage),this.#dt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);this.#at(t),this.#it(STATUS.streaming),n.text.set(e.id,t),this.#ot(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;this.#at(r),n.text.set(e.id,r),this.#ot(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);this.#at(r),this.#it(STATUS.streaming),n.reasoning.set(e.id,r),this.#st(e.id,r,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#at(r),this.#st(e.id,r,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#it(STATUS.executingTools),this.#ct({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;this.#ct({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#lt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#it(STATUS.toolResults),this.#ct({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{if(t.tools===`hidden`)break;let r=this.#lt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#it(STATUS.toolResults),this.#ct({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#Qe(`Error`,e.errorText,e.detail);break;case`finish`:this.#ut(e.usage),this.#dt();break}}#it(e){let t=this.#w>0?STATUS.connectionAuth:e;this.#M!==t&&(this.#M=t,this.#dt())}#at(e){e.trim().length>0&&(this.#j={kind:`answering`})}#ot(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#et({id:e,kind:`assistant`,body:r,live:n}),this.#dt())}#st(e,t,n,r){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#et({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#dt())}#ct(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.#et(renderNativeToolBlock(e,r,t.tools===`full`)),this.#dt()}#lt(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`}}#ut(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#X=(t??0)+(n??0)),this.#Z=t??this.#Z,this.#$=n??this.#$,this.#$!=null&&this.#te!==void 0){let e=(Date.now()-this.#te)/1e3;e>0&&(this.#ee=this.#$/e)}}#dt(){if(this.#P){if(this.#J){this.#Y=!0;return}this.#J=!0;try{do this.#Y=!1,this.#ft();while(this.#Y)}finally{this.#J=!1}}}#ft(){if(!this.#P)return;let e=this.#wt(),t=this.#xt(e),n=Math.max(1,this.#Tt()-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.#It(t))continue;let n=this.#_t(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.#It(t))continue;let n=this.#_t(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)}#pt(){if(!this.#P)return;let e=this.#wt(),t=this.#xt(e),n=Math.max(1,this.#Tt()-t.length),r=this.#C,i=[];for(let t of this.#f){if(this.#It(t))continue;let n=this.#_t(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.#gt(),...this.#S],a)}logDisplayMode(){return this.#d}setLogDisplayMode(e){e!==this.#d&&(this.#d=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#ht(),this.#P&&this.#pt())}flushDelayedDevBuildErrors(){let e=this.#ae;e!==void 0&&(this.#ae=void 0,this.#Ye({kind:`log`,title:`stderr`,body:e,live:!1}),this.#dt())}#mt(){this.#V=!0,this.#B!==void 0&&clearTimeout(this.#B),this.#B=setTimeout(()=>{this.#V=!1,this.#B=void 0,this.#dt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#d)),this.#dt()}#ht(){let e=this.#wt();this.#S.length=0;let t;for(let n of this.#h){if(this.#It(n))continue;let r=this.#_t(n,e,t);t=previousBlockOf(n),this.#S.push(...r)}this.#C=t}#gt(){let e=this.#y;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#wt()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#_t(e,t,n){let r={spinner:this.#vt()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#vt(){return this.#r.spinner[this.#L%this.#r.spinner.length]??``}#yt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#bt(e){return e.indicator.kind===`spinner`?{glyph:this.#vt(),color:`yellow`}:{glyph:this.#yt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:`green`}}#xt(e){let t=this.#r.colors,n=[``],r=this.#le;if(r!==void 0){let t=this.#bt(r),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,indicator:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(i={kind:`status`,status:{text:r.status,indicator:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,indicator:t},preview:r.preview}));let a={title:r.title,lines:r.hideLinesWhileQuestion===!0?[]:r.lines,content:i};return n.push(...renderFlowPanel(a,this.#r,e)),n}if(this.#ue!==void 0&&n.push(...renderAttentionRows(this.#ue,e,this.#r),``),this.#k){let r=this.#A===void 0?void 0:inlineCommandHint(this.#A);r===void 0&&this.#A!==void 0&&isTypeaheadOpen(this.#A)&&n.push(...renderCommandSuggestions(this.#A,this.#r,e));let i=isPromptControlCommand(this.#E),a=r?t.dim(` ${r}`):``,o=[];this.#St(o,e);let s=Math.max(1,this.#Tt()-1-n.length-1-o.length);return n.push(...promptInputRows({text:this.#E,cursor:this.#D,width:e,theme:this.#r,caretVisible:this.#I,isCommand:i,ghost:a,maxRows:s})),n.push(...o),n}let i=this.#j;if(i.kind===`answering`)return this.#St(n,e),n;let a=i.kind===`waiting`,o=a?t.green(this.#yt(i.startedAtMs,this.#r.unicode?`⊙`:`o`)):t.dim(this.#r.glyph.dot),s=this.#M.length>0?this.#M:`Ready`,c=a?t.dim(s):s,u=this.#Ct(),f=a?` `:``,p=u?`${f}${o} ${c} ${t.dim(this.#r.glyph.dot)} ${u}`:`${f}${o} ${c}`;n.push(clip(p,e));let g=[];return this.#St(g,e),a&&g.length>0&&n.push(``),n.push(...g),n}#St(e,t){let n={theme:this.#r,width:t};this.#V&&(n.logLevel=this.#d);let r=this.#y?.info?.agent.model.id;r!==void 0&&(n.model=r);let i=this.#y?.info?.agent.model.endpoint;i!==void 0&&(n.endpoint=i);let a=this.#Z??0,o=this.#$??0;if(a>0||o>0){let e={inputTokens:a,outputTokens:o};this.#Q!==void 0&&(e.contextSize=this.#Q),n.tokens=formatTokenFlow(e,this.#r.glyph)}this.#T!==void 0&&(n.vercel=this.#T);let s=buildStatusLine(n);s!==void 0&&e.push(s)}#Ct(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#X,outputTokens:this.#$,tokensPerSecond:this.#ee},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#wt(){return Math.max(20,this.#t.columns||80)}#Tt(){return Math.max(8,this.#t.rows||24)}#Et(){if(this.#ne!==void 0||!this.#u)return;this.#re=``,this.#ie=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#Ot(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ne=()=>{e(),t()}}#Dt(){let e=this.#ne;e!==void 0&&(this.#ne=void 0,e(),this.#re.length>0&&(this.#Ft(`stdout`)&&process.stdout.write(`${this.#re}\n`),this.#re=``),this.#ie.length>0&&(this.#Ft(`stderr`)&&process.stderr.write(`${this.#ie}\n`),this.#ie=``))}#Ot(e,t){let n=(e===`stdout`?this.#re:this.#ie)+t,i=n.lastIndexOf(`
|
|
4
|
-
`),a=i===-1?n:n.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.#
|
|
7
|
-
`),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){this.#
|
|
8
|
-
`);r.trim().length>0&&this.#
|
|
9
|
-
`);this.#
|
|
1
|
+
import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{toErrorMessage}from"#shared/errors.js";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{StringDecoder}from"node:string_decoder";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.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=[];#m=new Map;#h=new Set;#g=[];#_=new Set;#v=new Map;#y=new Set;#b;#x=!1;#S;#C=[];#w;#T=0;#E;#D;#O=``;#k=0;#A=new PromptHistory;#j=!1;#M;#N={kind:`idle`};#P=STATUS.processing;#F=`eve`;#I=!1;#L=!1;#R=!0;#z=0;#B;#V;#H;#U=!1;#W;#G=``;#K=new StringDecoder(`utf8`);#q;#J;#Y;#X=!1;#Z=!1;#Q;#$;#ee;#te;#ne;#re;#ie;#ae=``;#oe=``;#se;#ce;#le=0;#ue;#de;#fe;#pe;#me;setupFlow={begin:(e,t)=>this.#ve(e,t),end:e=>this.#ye(e?.preserveDiagnostics??!0),readSelect:e=>this.#be(e),readEditableSelect:e=>this.#Se(e),readProviderPicker:e=>this.#Ce(e),readText:e=>this.#we(e),readAcknowledge:e=>this.#Te(e),readChoice:e=>this.#xe(e),setStatus:e=>this.#Ne(e),renderLine:(e,t)=>this.#Pe(e,t),renderOutput:e=>this.#Fe(e),waitForInterrupt:()=>this.#Ae()};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.#ee=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#f=e?.logs??`none`,this.#d=e?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#F=e.name,this.#b=e,this.#Ie();let t=this.#vt().join(`
|
|
2
|
+
`);if(this.#x){t!==this.#S&&(this.#S=t,this.#Ze({kind:`agent-header`,body:t,live:!1})),this.#pt();return}this.#x=!0,this.#S=t,this.#n.flush(this.#vt(),[])}async readPrompt(e){this.#Ie(e),this.#Xe(),this.#j=!0,this.#N={kind:`idle`},this.#P=``;let t=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#A.begin(t.text),this.#he(t),this.#M=typeaheadFor(this.#d,t.text),this.#Ge(),this.#pt(),await new Promise((e,n)=>{let apply=e=>{t=e,this.#qe(),this.#he(t),this.#M=typeaheadFor(this.#d,e.text,this.#M),this.#pt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#M=void 0,this.#Ke(),this.#Le(),n(interruptedError())},suggestions=()=>this.#M!==void 0&&isTypeaheadOpen(this.#M)?this.#M:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#W=n=>{let r=applyLineEditorKey(t,n,{multiline:!0});if(r!==void 0){apply(r);return}switch(n.type){case`up`:{let e=suggestions();if(e!==void 0){this.#M=moveTypeaheadSelection(e,-1),this.#pt();break}let n=movePromptLine(t,`up`);n===void 0?recall(this.#A.previous(t.text)):apply(n);break}case`down`:{let e=suggestions();if(e!==void 0){this.#M=moveTypeaheadSelection(e,1),this.#pt();break}let n=movePromptLine(t,`down`);n===void 0?recall(this.#A.next()):apply(n);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#M=dismissTypeahead(e),this.#pt());break}case`enter`:{let n=highlighted(),r=n!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(n).trimEnd():t.text;this.#M=void 0,this.#A.add(r),this.#j=!1,this.#Ke(),this.#Ye(),this.#P=STATUS.processing,isPromptControlCommand(r)?this.#Ze({kind:`command`,body:stripTerminalControls(r.trim()),live:!1}):(this.#Qe(r),this.#ue=r),this.#he(EMPTY_LINE),this.#pt(),this.#ze(),e(r);break}case`ctrl-d`:t.text.length===0?interrupt():apply(deleteForward(t));break;case`ctrl-l`:this.#gt();break;case`ctrl-r`:this.#pt();break;case`ctrl-c`:t.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#Re()})}#he(e){this.#O=e.text,this.#k=e.cursor}async renderStream(e,t){this.#Ie(t),this.#h.clear(),this.#j=!1,this.#N.kind!==`waiting`&&(this.#N={kind:`waiting`,startedAtMs:Date.now()}),this.#P=STATUS.processing,this.#$e(t?.submittedPrompt),this.#L=!1,this.#Q=void 0,this.#$=void 0,this.#te=void 0,this.#ne=void 0,this.#re=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#Je(),this.#pt();let r=new Promise(e=>{this.#Y=e});this.#W=e=>this.#We(e),this.#Re();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.#L)break;this.#at(t,n,i)}}catch(e){this.#et(`Error`,toErrorMessage(e))}finally{this.#Y=void 0,this.#L&&e.abort?.(),this.#ze(),this.#Xe(),this.#N.kind===`waiting`&&(this.#N={kind:`idle`}),this.#P=completedTurnStatus(this.#L,t?.continueSession===!0),this.#it(),this.#pt(),t?.continueSession||this.#Le()}}async readToolApproval(e,t){return this.#Ie(t),this.#Xe(),this.#j=!1,this.#N={kind:`idle`},this.#P=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#L=!1,this.#pt(),await new Promise((t,n)=>{this.#W=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Ye(),this.#P=STATUS.processing,this.#ze(),this.#pt(),t({approved:!0})):n===`n`&&(this.#Ye(),this.#P=STATUS.processing,this.#ge(e.toolCallId),this.#ze(),this.#pt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#pt();break;case`ctrl-c`:this.#L=!0,this.#Le(),n(interruptedError());break;default:break}},this.#Re()})}async readInputQuestion(e,t){this.#Ie(t),this.#Xe(),this.#j=!1,this.#N={kind:`idle`},this.#L=!1;let n=e.options??[],r=n.length>0,a=(e.allowFreeform===!0||!r)&&r,o=n.length+ +!!a,s=questionSectionId(e.requestId),c=r?`select`:`text`,l=0,u=EMPTY_LINE,isOnFreeformRow=()=>a&&l===n.length,renderSection=()=>{this.#nt({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.#P=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#j=!1}else this.#j=!0,this.#he(u),this.#P=``;this.#pt()};renderSection(),c===`text`&&this.#Ge(),repaintStatus();let finalize=t=>{this.#nt({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.#j=!1,this.#Ye(),this.#P=STATUS.processing,this.#Ke(),this.#ze(),this.#pt();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n};return await new Promise((t,i)=>{this.#W=a=>{if(a.type===`ctrl-c`){if(c===`text`&&u.text.length>0){u=EMPTY_LINE,this.#qe(),repaintStatus();return}this.#L=!0,this.#Ke(),this.#Le(),i(interruptedError());return}if(a.type===`ctrl-r`){this.#pt();return}if(c===`select`){switch(a.type){case`up`:o>0&&(l=(l-1+o)%o,renderSection(),repaintStatus());break;case`down`:o>0&&(l=(l+1)%o,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){c=`text`,u=EMPTY_LINE,this.#Ge(),repaintStatus();break}let e=n[l];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}let s=applyLineEditorKey(u,a,{multiline:!0});if(s!==void 0){u=s,this.#qe(),repaintStatus();return}switch(a.type){case`up`:case`down`:{let e=movePromptLine(u,a.type);e!==void 0&&(u=e,this.#qe(),repaintStatus());break}case`enter`:{let n=resolveQuestionText(u.text,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(r){if(u.text.length>0){u=EMPTY_LINE,this.#qe(),repaintStatus();break}c=`select`,u=EMPTY_LINE,this.#j=!1,this.#Ke(),repaintStatus();break}u=EMPTY_LINE,this.#qe(),repaintStatus();break;default:break}},this.#Re()})}upsertSubagentStep(e){if(this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#tt(e.callId,e.subagentName),this.#o===`collapsed`){this.#pt();return}this.#nt({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:n,live:!e.finalized}),this.#pt()}}upsertSubagentTool(e){if(this.#o===`hidden`)return;if(this.#tt(e.callId,e.subagentName),this.#o===`collapsed`){this.#pt();return}let t=subagentToolStatus(e.status),n={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,depth:1,title:stripTerminalControls(e.toolName),subtitle:summarizeToolArgs(e.input),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolInput:e.input};e.output===void 0?e.errorText!==void 0&&(n.result=stripTerminalControls(e.errorText)):(n.result=summarizeToolResult(e.output),n.toolOutput=e.output),this.#nt(n),this.#pt()}markChildToolCallId(e){this.#_.add(e);let t=this.#v.get(e);t!==void 0&&(this.#rt(t),this.#v.delete(e),this.#pt())}#ge(e){let t=this.#m.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=e.state===`authorized`||e.state===`declined`||e.state===`failed`||e.state===`timed-out`;this.#nt({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e),preformatted:!0,live:!t}),this.#pt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#T)return;let n=this.#T>0;this.#T=t,t>0?(this.#P=STATUS.connectionAuth,this.#pt()):n&&(this.#P=STATUS.processing,this.#pt())}setVercelStatus(e){this.#E=e,this.#pt()}setRemoteConnectionStatus(e){this.#D=e,this.#pt()}reset(){this.#p=[],this.#m.clear(),this.#h.clear(),this.#w=void 0,this.#C.length=0,this.#g.length=0,this.#x=!1,this.#S=void 0,this.#_.clear(),this.#v.clear(),this.#y.clear(),this.#ue=void 0,this.#ce=void 0,this.#T=0,this.#Q=void 0,this.#$=void 0,this.#te=void 0,this.#ne=void 0,this.#re=void 0,this.#I&&(this.#n.clearAll(),this.#pt())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ie(),this.#Ze({kind:`notice`,body:t,live:!1}),this.#pt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#Ie(),this.#Ze({kind:`sandbox`,body:t,live:!1}),this.#pt())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#_e();return}this.#Ie(),this.#fe=t,this.#pt()}clearSetupWarning(){this.#_e()}#_e(){this.#fe!==void 0&&(this.#fe=void 0,this.#pt())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#Ie();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Ze(r),this.#pt()}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ie(),this.#Ze({kind:`result`,body:t,live:!1}),this.#pt())}#ve(e,t=`spinner`){this.#Ie(),this.#j=!1,this.#N={kind:`idle`},this.#P=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#de={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Je(),this.#pt()}#ye(e){this.#pe=void 0,this.#Me();let t=this.#de;if(t!==void 0){if(this.#de=void 0,this.#Xe(),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.#Ze({kind:`flow`,title:`info`,body:e.join(`
|
|
3
|
+
`),live:!1}),this.#Ze({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#pt()}}async#be(e){let t=this.#Ee(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a={options:i,searchAction:r,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(a.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(a.initialValues=e.initialValues);let o=initialSelectState(a),s,c=!1,l=0,isCurrentSearch=e=>e===l,clearSearch=()=>{l+=1,c=!1,o=reduceSelect(o,{type:`clear`},{options:i,searchAction:r,submitRow:n}),this.#pt()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#pt();try{let s=await t(e);if(!isCurrentSearch(a))return;let c=o.filter;i=s,o={...initialSelectState({options:s,searchAction:r,submitRow:n}),filter:c}}catch(e){isCurrentSearch(a)&&(s=toErrorMessage(e))}finally{isCurrentSearch(a)&&(c=!1,this.#pt())}},u=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}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#bt()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#pt(),await this.#ke((t,a)=>{let close=e=>{l+=1,a(e)};if(c){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#pt();return}let u={key:t,options:i,searchAction:r,select:o},d=reduceSetupSelectInput(n?{...u,kind:e.kind,required:e.required}:{...u,kind:e.kind});switch(d.kind){case`cancel`:close(void 0);return;case`repaint`:this.#pt();return;case`update`:o=d.select,s=void 0,this.#pt();return;case`submit`:{let e=searchActionQuery(d.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(d.values);return}loadSearch(e,t);return}case`error`:s=d.message,this.#pt();return;case`ignore`:return}}).promise}#xe(e){this.#Ie();let t=this.#De();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#pt();let r=this.#ke((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.#pt();return;case`repaint`:this.#pt();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#Se(e){let t=this.#Ee(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#R,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?(i.text.length===0&&(i=lineOf(e.editable.defaultValue)),this.#Ge()):(i=lineOf(``),this.#Ke())};return syncEditableRow(),this.#pt(),await this.#ke((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#qe(),this.#pt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#pt()},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.#pt();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.#pt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ke()).promise}async#Ce(e){let t=this.#Ee(),n=initialProviderPickerState(e.options,e.initialValue),r;t.question=t=>renderSelectQuestion({kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#R,editor:{kind:`key`,phase:n.phase}}},this.#r,t);let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#Ge():this.#Ke()};return syncCaret(),this.#pt(),await this.#ke((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#pt();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#pt();return;case`validate`:{n=o.state,syncCaret(),this.#pt();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#pt();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#qe(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Ke()}).promise}async#we(e){let t=this.#Ee(),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.#R)},this.#Ge(),this.#pt(),await this.#ke((t,i)=>{let apply=e=>{n=e,r=void 0,this.#qe(),this.#pt()},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.#pt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#pt();return}i(t);return}default:return}},()=>this.#Ke()).promise}async#Te(e){let t=this.#Ee();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#pt(),await this.#ke((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#pt();return;default:return}}).promise}#Ee(){return this.#Ie(),this.#j=!1,this.#N={kind:`idle`},this.#P=``,this.#De()}#De(){return this.#de===void 0&&(this.#de={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[]}),this.#de}#Oe(){this.#de!==void 0&&(this.#de.question=void 0,this.#de.hideLinesWhileQuestion=!1),this.#W=void 0,this.#ze(),this.#je(),this.#pt()}#ke(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Oe(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Oe(),i(e))};return this.#W=t=>e(t,settle,reject),this.#Re(),{promise:a,settle}}#Ae(){let e,t=new Promise(t=>{e=t});return this.#pe=e,this.#je(),{promise:t,dispose:()=>{this.#pe===e&&(this.#pe=void 0,this.#Me())}}}#je(){if(this.#pe===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#pe;this.#pe=void 0,this.#Me(),e?.();return}e.type===`ctrl-r`&&this.#pt()};this.#me=consumer,this.#W=consumer,this.#Re()}#Me(){this.#me!==void 0&&(this.#W===this.#me&&this.#ze(),this.#me=void 0)}#Ne(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#de!==void 0){this.#de.status=t,t===void 0&&(this.#de.preview=void 0),this.#pt();return}if(t===void 0){this.#N={kind:`idle`},this.#P=``,this.#Xe(),this.#pt();return}this.#Ie(),this.#Ye(),this.#P=t,this.#pt()}#Pe(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#de;if(r!==void 0){if(r.preview=void 0,t===`warning`||t===`error`)for(let e of r.outputBuffer)r.lines.push({text:e,tone:`info`,evidence:!0});r.outputBuffer=[],r.lines.push({text:n,tone:t}),this.#pt();return}this.#Ie(),this.#Ze({kind:`flow`,title:t,body:n,live:!1}),this.#pt()}#Fe(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#de;if(n===void 0){this.#Pe(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#pt()}shutdown(){this.#Le()}#Ie(e){this.#F=e?.title??this.#F,this.#ee=e?.contextSize??this.#l,!this.#I&&(this.#I=!0,this.#n.reset(),this.#n.hideCursor(),this.#kt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#J=()=>this.#pt(),this.#t.on(`resize`,this.#J))}#Le(){this.#ze(),this.#Ke(),this.#Xe(),this.#H!==void 0&&(clearTimeout(this.#H),this.#H=void 0),this.#U=!1,this.#I&&=(this.#Lt(),this.#pt(),this.#n.clear(),this.#n.showCursor(),this.#At(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#J&&=(this.#t.off(`resize`,this.#J),void 0),!1)}#Re(){this.#e.off(`data`,this.#Be),this.#e.on(`data`,this.#Be)}#ze(){this.#e.off(`data`,this.#Be),this.#Ue(),this.#G=``,this.#K=new StringDecoder(`utf8`),this.#W=void 0}#Be=e=>{this.#Ue(),this.#G+=this.#K.write(e),this.#He(),this.#Ve()};#Ve(){if(this.#G===`\x1B`){this.#q=setTimeout(()=>{this.#G===`\x1B`&&(this.#G=``,this.#W?.({type:`escape`}))},30),this.#q.unref?.();return}if(isIncompletePaste(this.#G)){let e=this.#G;this.#q=setTimeout(()=>{if(this.#G!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#G=``,t.length>0&&this.#W?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#q.unref?.()}}#He(){for(;this.#G.length>0;){let e=nextKey(this.#G);if(e.incomplete)return;this.#G=this.#G.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#W?.(e.key)}}#Ue(){this.#q&&=(clearTimeout(this.#q),void 0)}#We(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#pt();break;case`ctrl-c`:this.#L||(this.#L=!0,this.#N={kind:`idle`},this.#P=`Interrupted`,this.#Y?.(),this.#pt());break;default:break}}#Ge(){this.#Ke(),this.#qe(),this.#B=setInterval(()=>{this.#R=!this.#R,this.#pt()},500),this.#B.unref?.()}#Ke(){this.#B&&=(clearInterval(this.#B),void 0),this.#R=!0}#qe(){this.#R=!0}#Je(){this.#Xe(),this.#V=setInterval(()=>{this.#z+=1,this.#pt()},90),this.#V.unref?.()}#Ye(){this.#N={kind:`waiting`,startedAtMs:Date.now()},this.#Je()}#Xe(){this.#V&&=(clearInterval(this.#V),void 0)}#Ze(e){e.id!==this.#ce?.id&&this.#Lt(),this.#p.push(e),e.id&&this.#m.set(e.id,e)}#Qe(e){this.#Ze({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#pt()}#$e(e){if(e!=null){if(this.#ue===e){this.#ue=void 0;return}this.#Ze({kind:`user`,body:stripTerminalControls(e),live:!1})}}#et(e,t,n){let r={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};n!==void 0&&(r.detail=stripTerminalControls(n)),this.#Ze(r),this.#pt()}#tt(e,t){this.#y.has(e)||(this.#y.add(e),this.#Ze({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#nt(e){if(e.id&&this.#h.has(e.id))return;let t=e.id?this.#m.get(e.id):void 0;if(t){Object.assign(t,e);return}this.#Ze(e)}#rt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#it(){for(let e of this.#p)e.status===`approval`||e.status===`running`||(e.live=!1)}#at(e,t,n){switch(e.type){case`step-start`:this.#ot(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#ft(e.usage),this.#pt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);this.#st(t),this.#ot(STATUS.streaming),n.text.set(e.id,t),this.#ct(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;this.#st(r),n.text.set(e.id,r),this.#ct(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);this.#st(r),this.#ot(STATUS.streaming),n.reasoning.set(e.id,r),this.#lt(e.id,r,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#st(r),this.#lt(e.id,r,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#ot(STATUS.executingTools),this.#ut({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;this.#ut({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#dt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#ot(STATUS.toolResults),this.#ut({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{if(t.tools===`hidden`)break;let r=this.#dt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#ot(STATUS.toolResults),this.#ut({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#et(`Error`,e.errorText,e.detail);break;case`finish`:this.#ft(e.usage),this.#pt();break}}#ot(e){let t=this.#T>0?STATUS.connectionAuth:e;this.#P!==t&&(this.#P=t,this.#pt())}#st(e){e.trim().length>0&&(this.#N={kind:`answering`})}#ct(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#nt({id:e,kind:`assistant`,body:r,live:n}),this.#pt())}#lt(e,t,n,r){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#nt({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#pt())}#ut(e,t,n){if(n.tools.set(e.toolCallId,e),this.#_.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#v.set(e.toolCallId,r),this.#nt(renderNativeToolBlock(e,r,t.tools===`full`)),this.#pt()}#dt(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#v.get(e)??toolSectionId(e),i=this.#m.get(r);if(!(i===void 0||i.kind!==`tool`))return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.title??`tool`}}#ft(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#Q=(t??0)+(n??0)),this.#$=t??this.#$,this.#te=n??this.#te,this.#te!=null&&this.#re!==void 0){let e=(Date.now()-this.#re)/1e3;e>0&&(this.#ne=this.#te/e)}}#pt(){if(this.#I){if(this.#X){this.#Z=!0;return}this.#X=!0;try{do this.#Z=!1,this.#mt();while(this.#Z)}finally{this.#X=!1}}}#mt(){if(!this.#I)return;let e=this.#Dt(),t=this.#Ct(e),n=Math.max(1,this.#Ot()-t.length),r=[],i=this.#w;for(;this.#p.length>0&&this.#p[0].live===!1;){let t=this.#p.shift();if(this.#g.push(t),t.id&&(this.#h.add(t.id),this.#m.delete(t.id)),this.#zt(t))continue;let n=this.#yt(t,e,i);i=previousBlockOf(t),this.#w=i,r.push(...n),this.#C.push(...n)}let a=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#yt(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)}#ht(){if(!this.#I)return;let e=this.#Dt(),t=this.#Ct(e),n=Math.max(1,this.#Ot()-t.length),r=this.#w,i=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#yt(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.#vt(),...this.#C],a)}logDisplayMode(){return this.#f}setLogDisplayMode(e){e!==this.#f&&(this.#f=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#_t(),this.#I&&this.#ht())}flushDelayedDevBuildErrors(){let e=this.#se;e!==void 0&&(this.#se=void 0,this.#Ze({kind:`log`,title:`stderr`,body:e,live:!1}),this.#pt())}#gt(){this.#U=!0,this.#H!==void 0&&clearTimeout(this.#H),this.#H=setTimeout(()=>{this.#U=!1,this.#H=void 0,this.#pt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#f)),this.#pt()}#_t(){let e=this.#Dt();this.#C.length=0;let t;for(let n of this.#g){if(this.#zt(n))continue;let r=this.#yt(n,e,t);t=previousBlockOf(n),this.#C.push(...r)}this.#w=t}#vt(){let e=this.#b;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#Dt()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#yt(e,t,n){let r={spinner:this.#bt()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#bt(){return this.#r.spinner[this.#z%this.#r.spinner.length]??``}#xt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#St(e){return e.indicator.kind===`spinner`?{glyph:this.#bt(),color:`yellow`}:{glyph:this.#xt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:`green`}}#Ct(e){let t=this.#r.colors,n=[``],r=this.#de;if(r!==void 0){let t=this.#St(r),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,indicator:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(i={kind:`status`,status:{text:r.status,indicator:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,indicator: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)),this.#Tt(n,e),n}if(this.#fe!==void 0&&n.push(...renderAttentionRows(this.#fe,e,this.#r),``),this.#j){let r=this.#M===void 0?void 0:inlineCommandHint(this.#M);r===void 0&&this.#M!==void 0&&isTypeaheadOpen(this.#M)&&n.push(...renderCommandSuggestions(this.#M,this.#r,e));let i=isPromptControlCommand(this.#O),a=r?t.dim(` ${r}`):``,o=[];this.#wt(o,e);let s=Math.max(1,this.#Ot()-1-n.length-1-o.length);return n.push(...promptInputRows({text:this.#O,cursor:this.#k,width:e,theme:this.#r,caretVisible:this.#R,isCommand:i,ghost:a,maxRows:s})),n.push(...o),n}let i=this.#N;if(i.kind===`answering`)return this.#wt(n,e),n;let a=i.kind===`waiting`,o=a?t.green(this.#xt(i.startedAtMs,this.#r.unicode?`⊙`:`o`)):t.dim(this.#r.glyph.dot),s=this.#P.length>0?this.#P:`Ready`,c=a?t.dim(s):s,u=this.#Et(),f=a?` `:``,p=u?`${f}${o} ${c} ${t.dim(this.#r.glyph.dot)} ${u}`:`${f}${o} ${c}`;n.push(clip(p,e));let g=[];return this.#wt(g,e),a&&g.length>0&&n.push(``),n.push(...g),n}#wt(e,t){let n=this.#D===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#r,width:r};this.#U&&(i.logLevel=this.#f);let a=this.#b?.info?.agent.model.id;a!==void 0&&(i.model=a);let o=this.#b?.info?.agent.model.endpoint;o!==void 0&&(i.endpoint=o);let s=this.#$??0,c=this.#te??0;if(s>0||c>0){let e={inputTokens:s,outputTokens:c};this.#ee!==void 0&&(e.contextSize=this.#ee),i.tokens=formatTokenFlow(e,this.#r.glyph)}this.#E!==void 0&&(i.vercel=this.#E),this.#D!==void 0&&(i.remote=this.#D);let l=buildStatusLine(i);l!==void 0&&e.push(clip(`${n}${l}`,t))}#Tt(e,t){if(this.#D===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#D,theme:this.#r,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Et(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Q,outputTokens:this.#te,tokensPerSecond:this.#ne},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#Dt(){return Math.max(20,this.#t.columns||80)}#Ot(){return Math.max(8,this.#t.rows||24)}#kt(){if(this.#ie!==void 0||!this.#u)return;this.#ae=``,this.#oe=``;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.#jt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ie=()=>{e(),t()}}#At(){let e=this.#ie;e!==void 0&&(this.#ie=void 0,e(),this.#ae.length>0&&(this.#Rt(`stdout`)&&process.stdout.write(`${this.#ae}\n`),this.#ae=``),this.#oe.length>0&&(this.#Rt(`stderr`)&&process.stderr.write(`${this.#oe}\n`),this.#oe=``))}#jt(e,t){let n=(e===`stdout`?this.#ae:this.#oe)+t,i=n.lastIndexOf(`
|
|
4
|
+
`),a=i===-1?n:n.slice(i+1);if(e===`stdout`?this.#ae=a:this.#oe=a,i===-1)return;let o=stripAnsi(n.slice(0,i)).replace(/\s+$/u,``);o.trim().length!==0&&(e===`stdout`?this.#Mt(o):this.#Nt(o),this.#pt())}#Mt(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
|
|
5
|
+
`);t=[],e.trim().length!==0&&this.#Ze({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.#Ze({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#Ft(r,n.trimEnd())}flushPending()}#Nt(e){let t=e.split(`
|
|
7
|
+
`),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){this.#Ze({kind:`log`,title:`stderr`,body:e,live:!1});return}let r=t.slice(0,n).join(`
|
|
8
|
+
`);r.trim().length>0&&this.#Ze({kind:`log`,title:`stderr`,body:r,live:!1});let i=t.slice(n).join(`
|
|
9
|
+
`);this.#Pt(i)}#Pt(e){if(this.#f===`all`){if(e.trim().length===0)return;this.#Ze({kind:`log`,title:`stderr`,body:e,live:!1});return}this.#se=e}#Ft(e,t){let n=this.#It();if(e.kind===`failed`){this.#Pt(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#le}`;this.#le+=1,this.#ce={id:r,summary:t},this.#Ze({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}if(n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#se=void 0);return}e.kind===`rebuilt`&&(this.#se=void 0),this.#Ze({kind:`log`,title:`stdout`,body:t,live:!1})}#It(){let e=this.#ce;if(e===void 0)return;let t=this.#m.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#Lt(){let e=this.#ce;if(e===void 0)return;this.#ce=void 0;let t=this.#m.get(e.id);t!==void 0&&(t.live=!1)}#Rt(e){switch(this.#f){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#zt(e){return e.kind===`sandbox`?!this.#Rt(`sandbox`):e.kind===`log`?!this.#Rt(e.title===`stderr`?`stderr`:`stdout`):!1}};function chunkToString(e,t){return typeof e==`string`?e:Buffer.from(e).toString(t)}async function*iterateTUIStream(e){if(e instanceof ReadableStream){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}return}yield*e}function clip(t,n){return clipVisible(t,n)}function promptInputRows({text:e,cursor:r,width:i,theme:a,caretVisible:o,isCommand:s,ghost:c,maxRows:l}){let u=a.colors,style=e=>{let n=renderInputText(e);return s&&n.length>0?u.blue(n):n},d=layoutPromptInput({text:e,cursor:r}),f=Math.min(Math.max(1,l),d.rows.length),p=Math.max(0,Math.min(d.caretRow-f+1,d.rows.length-f)),m=u.cyan(a.glyph.prompt),h=u.dim(a.glyph.ellipsis),g=Math.max(1,i-4),_=[];for(let e=p;e<p+f;e+=1){let t=d.rows[e],r=e===0?m:` `;(e===p&&p>0||e===p+f-1&&p+f<d.rows.length)&&(r=h);let s;if(e===d.caretRow){let{before:e,under:r,after:i}=visibleLine({text:t.text,cursor:d.caretOffset},g,a.glyph.ellipsis);s=renderInputWithBlockCursor({before:e,under:r,after:i,visible:o,inverse:u.inverse,render:style}),c.length>0&&d.rows.length===1&&(s+=c)}else s=style(t.text);_.push(clip(` ${r} ${s}`,i))}return _.push(``),_}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function leadsWithGap(e,t){if(e.kind===`sandbox`&&t?.kind===`sandbox`)return!1;if(t?.kind===`sandbox`&&e.kind!==`sandbox`)return!0;if(e.kind===`log`&&t?.kind===`log`)return t.title!==e.title;if(t?.kind===`log`&&e.kind!==`log`)return!0;switch(e.kind){case`user`:case`assistant`:case`reasoning`:case`subagent`:case`error`:case`notice`:case`question`:case`connection-auth`:case`sandbox`:case`log`:case`command`:case`warning`:case`flow`:case`agent-header`:return!0;default:return!1}}function parseSandboxLogLine(e){let t=e.trim();if(!t.startsWith(`eve: `))return;let n=t.slice(5);return/\bsandbox\b/i.test(n)&&!isLowValueSandboxLogLine(n)?n:void 0}function isLowValueSandboxLogLine(e){return/^initializing (?:\d+ )?sandbox templates?\b/i.test(e)||/^initialized \d+ sandbox\b/i.test(e)||/^reused cached sandbox template\b/i.test(e)||/^sandbox template "[^"]+" \([^)]+\): (checking|reusing|loading microsandbox runtime|microsandbox runtime ready)\b/i.test(e)}function clipLiveRows(e,t,n,r){if(e.length<=t)return[...e];if(t<=1)return[clip(hiddenRowsMarker(e.length,r),n)];let i=t-1;return[clip(hiddenRowsMarker(e.length-i,r),n),...e.slice(e.length-i)]}function hiddenRowsMarker(e,t){let n=e.toLocaleString(),r=e===1?`row`:`rows`;return t.colors.dim(`${t.glyph.dot} ${t.glyph.ellipsis} ${n} earlier ${r} hidden while streaming`)}function collapseReasoning(e,t){switch(e){case`collapsed`:return!0;case`auto-collapsed`:return!t;default:return!1}}function renderNativeToolBlock(e,t,n){let r={id:t,kind:`tool`,title:stripTerminalControls(e.toolName),subtitle:summarizeToolArgs(e.input),status:e.status,live:e.status===`running`||e.status===`approval`,expanded:n,toolInput:e.input};return e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=summarizeToolResult(e.output),r.toolOutput=e.output),r}function subagentToolStatus(e){switch(e){case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`}}function formatToolApprovalTitle(e){return stripTerminalControls(e.title??e.toolName)}function toolSectionId(e){return`tool:${e}`}function questionSectionId(e){return`question:${e}`}function subagentHeaderId(e){return`subagent:${e}:header`}function subagentStepSectionId(e,t){return`subagent:${e}:step:${t}`}function subagentToolSectionId(e,t){return`subagent:${e}:tool:${t}`}function connectionAuthSectionId(e){return`connection-auth:${e}`}function formatConnectionAuthContent(e){let t=[],n=stripTerminalControls(e.description);n.length>0&&t.push(n);let r=e.challenge;if(r?.url&&t.push(`URL: ${stripTerminalControls(r.url)}`),r?.userCode&&t.push(`Code: ${stripTerminalControls(r.userCode)}`),r?.expiresAt&&t.push(`Expires: ${stripTerminalControls(r.expiresAt)}`),r?.instructions&&t.push(stripTerminalControls(r.instructions)),e.reason!==void 0){let n=stripTerminalControls(e.reason);n.length>0&&t.push(`Reason: ${n}`)}return t.join(`
|
|
10
10
|
`)}function formatQuestionContent(e,t,n){let r=n.colors,a=[],o=e.options??[];if(o.length>0){for(let[e,s]of o.entries()){let o=stripTerminalControls(s.label),c=s.description===void 0?``:stripTerminalControls(s.description),l=t===e,u=c.length>0?`${l?` `:` `}${r.dim(`— ${c}`)}`:``,d=renderCursorRow(l?`${n.glyph.selectedPointer} ${o}`:` ${o}`,l,r);a.push(`${d}${u}`)}if(e.allowFreeform===!0){let e=t===o.length,i=`Type your own answer`,s=e?`${n.glyph.selectedPointer} ${i}`:` ${r.dim(i)}`;a.push(renderCursorRow(s,e,r))}}else a.push(r.dim(` (type your answer)`));return a.join(`
|
|
11
11
|
`)}function resolveQuestionText(e,t){let n=e.trim();if(n.length===0)return;let r=n.toLowerCase(),i=t.options??[];if(i.length>0){let e=matchQuestionOption(r,i);if(e!==void 0)return{optionId:e.id,label:e.label}}if(t.allowFreeform===!0||i.length===0)return{text:n,label:n}}function matchQuestionOption(e,t){let n=t.find(t=>t.id.toLowerCase()===e);if(n!==void 0)return n;let r=t.find(t=>t.label.toLowerCase()===e);if(r!==void 0)return r;let i=Number(e);if(Number.isInteger(i)&&i>0&&i<=t.length)return t[i-1]}export{TerminalRenderer};
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
export { EveTUIRunner } from "../runner.js";
|
|
9
9
|
export type { EveTUIRunnerOptions } from "../runner.js";
|
|
10
10
|
export { createPromptCommandHandler } from "../prompt-command-handler.js";
|
|
11
|
+
export { promptCommandsFor } from "../prompt-commands.js";
|
|
11
12
|
export { TerminalRenderer } from "../terminal-renderer.js";
|
|
12
13
|
export { MockScreen, MockUserInput } from "./mock-terminal.js";
|
|
13
14
|
export { AUTHORED_ARTIFACTS_UPDATED_LOG_LINE, formatChangeDetectedLogLine, } from "#internal/nitro/host/dev-watcher-log.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createPromptCommandHandler}from"../prompt-command-handler.js";import{TerminalRenderer}from"../terminal-renderer.js";import{EveTUIRunner}from"../runner.js";import{MockScreen,MockUserInput}from"./mock-terminal.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";export{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,EveTUIRunner,MockScreen,MockUserInput,TerminalRenderer,createPromptCommandHandler,formatChangeDetectedLogLine};
|
|
1
|
+
import{promptCommandsFor}from"../prompt-commands.js";import{createPromptCommandHandler}from"../prompt-command-handler.js";import{TerminalRenderer}from"../terminal-renderer.js";import{EveTUIRunner}from"../runner.js";import{MockScreen,MockUserInput}from"./mock-terminal.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";export{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,EveTUIRunner,MockScreen,MockUserInput,TerminalRenderer,createPromptCommandHandler,formatChangeDetectedLogLine,promptCommandsFor};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";
|
|
2
|
-
import type
|
|
2
|
+
import { type DevelopmentTuiTarget } from "./target.js";
|
|
3
3
|
import type { TuiDisplayOptions } from "./types.js";
|
|
4
4
|
export type { DevelopmentTuiTarget } from "./target.js";
|
|
5
5
|
export interface RunDevelopmentTuiInput extends TuiDisplayOptions {
|