eve 0.58.0 → 0.59.0
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 +28 -0
- package/README.md +1 -0
- package/dist/src/channel/session.d.ts +2 -0
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +8 -1
- package/dist/src/chunks/{use-eve-agent-X0asmJg-.js → use-eve-agent-Dmc6sX4d.js} +558 -233
- package/dist/src/chunks/{use-eve-agent-CxWcZCsU.js → use-eve-agent-jSR8P4nK.js} +565 -235
- package/dist/src/cli/dev/tui/runner.d.ts +4 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-issues.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
- package/dist/src/client/eve-agent-projection.d.ts +10 -0
- package/dist/src/client/eve-agent-projection.js +1 -0
- package/dist/src/client/eve-agent-store-helpers.d.ts +6 -2
- package/dist/src/client/eve-agent-store-helpers.js +2 -2
- package/dist/src/client/eve-agent-store-state.d.ts +54 -1
- package/dist/src/client/eve-agent-store.d.ts +12 -82
- package/dist/src/client/eve-agent-store.js +1 -1
- package/dist/src/client/index.d.ts +2 -2
- package/dist/src/client/index.js +1 -1
- package/dist/src/client/message-response.d.ts +5 -1
- package/dist/src/client/message-response.js +1 -1
- package/dist/src/client/ndjson.d.ts +1 -0
- package/dist/src/client/ndjson.js +2 -2
- package/dist/src/client/open-stream.d.ts +4 -1
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session-event-stream.d.ts +30 -0
- package/dist/src/client/session-event-stream.js +1 -0
- package/dist/src/client/session-utils.d.ts +2 -1
- package/dist/src/client/session-utils.js +1 -1
- package/dist/src/client/session.d.ts +14 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/sessions.d.ts +8 -2
- package/dist/src/client/sessions.js +1 -1
- package/dist/src/client/types.d.ts +7 -0
- package/dist/src/compiled/.vendor-stamp.json +2 -3
- package/dist/src/compiled/@vercel/sandbox/api-client/api-client.d.ts +88 -1
- package/dist/src/compiled/@vercel/sandbox/api-client/index.d.ts +1 -1
- package/dist/src/compiled/@vercel/sandbox/api-client/validators.d.ts +41 -1
- package/dist/src/compiled/@vercel/sandbox/constants.d.ts +3 -3
- package/dist/src/compiled/@vercel/{sandbox-drives → sandbox}/drive.d.ts +13 -2
- package/dist/src/compiled/@vercel/sandbox/index.d.ts +3 -2
- package/dist/src/compiled/@vercel/sandbox/index.js +15 -9
- package/dist/src/compiled/@vercel/sandbox/sandbox.d.ts +40 -5
- package/dist/src/compiled/_chunks/node/auth-DDrvYko5.js +2 -0
- package/dist/src/compiled/_chunks/node/version-C__MqbLM.js +1 -0
- package/dist/src/compiler/extension-compatibility.d.ts +14 -14
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/context/build-dynamic-tools.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/context/memory-tools.js +1 -1
- package/dist/src/evals/context.d.ts +1 -1
- package/dist/src/evals/context.js +1 -1
- package/dist/src/evals/define-eval.d.ts +1 -1
- package/dist/src/evals/define-eval.js +1 -1
- package/dist/src/evals/index.js +1 -1
- package/dist/src/evals/judge.d.ts +1 -1
- package/dist/src/evals/runner/execute-task.d.ts +1 -1
- package/dist/src/evals/runner/execute-task.js +1 -1
- package/dist/src/evals/session-manager.d.ts +27 -0
- package/dist/src/evals/session-manager.js +1 -0
- package/dist/src/evals/session.d.ts +8 -28
- package/dist/src/evals/session.js +2 -1
- package/dist/src/evals/target.d.ts +1 -1
- package/dist/src/evals/target.js +1 -1
- package/dist/src/evals/types.d.ts +19 -15
- package/dist/src/eve-channel/create-request.d.ts +24 -0
- package/dist/src/eve-channel/create-request.js +1 -0
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/request.d.ts +3 -12
- package/dist/src/eve-channel/request.js +2 -2
- package/dist/src/eve-channel/types.d.ts +4 -2
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/legacy-session/turn-workflow.js +1 -1
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-lifecycle.d.ts +3 -3
- package/dist/src/execution/sandbox/bindings/vercel-lifecycle.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-sdk-types.d.ts +1 -4
- package/dist/src/execution/sandbox/bindings/vercel.d.ts +1 -2
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/session/entry.js +1 -1
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/program.d.ts +2 -0
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session/turn.js +1 -1
- package/dist/src/execution/session-inbox/protocol.js +1 -1
- package/dist/src/execution/tools/connection-search.js +1 -1
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/experimental/evaluate/auto-model.js +2 -2
- package/dist/src/experimental/evaluate/evaluate.d.ts +7 -0
- package/dist/src/experimental/evaluate/evaluate.js +1 -0
- package/dist/src/harness/compaction.d.ts +3 -3
- package/dist/src/harness/compaction.js +1 -1
- package/dist/src/harness/request-envelope.d.ts +11 -0
- package/dist/src/harness/request-envelope.js +1 -0
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/instrumentation/prepare-trace-context.d.ts +2 -1
- package/dist/src/instrumentation/prepare-trace-context.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-module-loader.d.ts +4 -1
- package/dist/src/internal/authored-module-loader.js +1 -1
- package/dist/src/internal/bundler/nitro-rolldown.d.ts +2 -0
- package/dist/src/internal/model-auth/transport.d.ts +3 -1
- package/dist/src/internal/model-auth/transport.js +1 -1
- package/dist/src/internal/nitro/host/build-extension.js +1 -1
- package/dist/src/internal/nitro/host/extension-capability-requirements.d.ts +1 -0
- package/dist/src/internal/nitro/host/extension-capability-requirements.js +1 -1
- package/dist/src/internal/nitro/host/extension-distribution.d.ts +1 -1
- package/dist/src/internal/nitro/host/extension-distribution.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +1 -1
- package/dist/src/public/experimental/evaluate/index.d.ts +1 -0
- package/dist/src/public/experimental/evaluate/index.js +1 -1
- package/dist/src/public/models/anthropic/index.js +1 -1
- package/dist/src/public/sandbox/vercel-sandbox.d.ts +1 -1
- package/dist/src/public/sandbox/vercel.d.ts +1 -1
- package/dist/src/public/sandbox/vercel.js +1 -1
- package/dist/src/public/tools/index.d.ts +1 -0
- package/dist/src/public/tools/index.js +1 -1
- package/dist/src/react/use-eve-agent.d.ts +4 -0
- package/dist/src/react/use-eve-agent.js +1 -1
- package/dist/src/runtime/agent/resolve-model.js +1 -1
- package/dist/src/setup/flows/model-login-connection.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/subagents/handle-dispatch.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.d.ts +4 -0
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/definition.d.ts +2 -0
- package/dist/src/tools/definition.js +1 -1
- package/dist/src/tools/durable-callbacks.d.ts +8 -2
- package/dist/src/tools/durable-callbacks.js +1 -1
- package/dist/src/tools/durable-schema.d.ts +16 -0
- package/dist/src/tools/durable-schema.js +1 -0
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.d.ts +4 -0
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/README.md +1 -0
- package/docs/channels/eve.mdx +20 -10
- package/docs/concepts/context-control.md +4 -0
- package/docs/concepts/sessions-runs-and-streaming.md +18 -3
- package/docs/evals/assertions.mdx +6 -6
- package/docs/evals/cases.mdx +59 -23
- package/docs/evals/judge.mdx +10 -8
- package/docs/evals/overview.mdx +6 -6
- package/docs/evals/reporters.mdx +1 -1
- package/docs/evals/targets.mdx +5 -0
- package/docs/guides/client/messages.mdx +5 -5
- package/docs/guides/client/overview.mdx +15 -1
- package/docs/guides/dynamic-capabilities.md +22 -0
- package/docs/guides/evaluate.md +58 -4
- package/docs/guides/frontend/overview.mdx +54 -5
- package/docs/guides/frontend/use-eve-agent-svelte.mdx +13 -8
- package/docs/guides/frontend/use-eve-agent-vue.mdx +13 -8
- package/docs/reference/typescript-api.md +38 -36
- package/package.json +2 -3
- package/dist/src/compiled/@vercel/sandbox-drives/LICENSE +0 -201
- package/dist/src/compiled/@vercel/sandbox-drives/_async-retry.d.ts +0 -8
- package/dist/src/compiled/@vercel/sandbox-drives/_workflow-serde.d.ts +0 -5
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/api-client.d.ts +0 -1815
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/api-error.d.ts +0 -29
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/base-client.d.ts +0 -39
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/file-writer.d.ts +0 -66
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/index.d.ts +0 -2
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/validators.d.ts +0 -932
- package/dist/src/compiled/@vercel/sandbox-drives/api-client/with-retry.d.ts +0 -10
- package/dist/src/compiled/@vercel/sandbox-drives/auth/error.d.ts +0 -15
- package/dist/src/compiled/@vercel/sandbox-drives/auth/file.d.ts +0 -18
- package/dist/src/compiled/@vercel/sandbox-drives/auth/index.d.ts +0 -6
- package/dist/src/compiled/@vercel/sandbox-drives/auth/oauth.d.ts +0 -111
- package/dist/src/compiled/@vercel/sandbox-drives/auth/poll-for-token.d.ts +0 -28
- package/dist/src/compiled/@vercel/sandbox-drives/auth/project.d.ts +0 -40
- package/dist/src/compiled/@vercel/sandbox-drives/command.d.ts +0 -292
- package/dist/src/compiled/@vercel/sandbox-drives/constants.d.ts +0 -15
- package/dist/src/compiled/@vercel/sandbox-drives/execution-context.d.ts +0 -116
- package/dist/src/compiled/@vercel/sandbox-drives/filesystem.d.ts +0 -258
- package/dist/src/compiled/@vercel/sandbox-drives/index.d.ts +0 -14
- package/dist/src/compiled/@vercel/sandbox-drives/index.js +0 -9
- package/dist/src/compiled/@vercel/sandbox-drives/network-policy.d.ts +0 -169
- package/dist/src/compiled/@vercel/sandbox-drives/proxy.d.ts +0 -55
- package/dist/src/compiled/@vercel/sandbox-drives/sandbox-user.d.ts +0 -211
- package/dist/src/compiled/@vercel/sandbox-drives/sandbox.d.ts +0 -1287
- package/dist/src/compiled/@vercel/sandbox-drives/session.d.ts +0 -435
- package/dist/src/compiled/@vercel/sandbox-drives/snapshot.d.ts +0 -238
- package/dist/src/compiled/@vercel/sandbox-drives/utils/get-credentials.d.ts +0 -21
- package/dist/src/compiled/@vercel/sandbox-drives/utils/paginator.d.ts +0 -16
- package/dist/src/compiled/@vercel/sandbox-drives/utils/resolveSignal.d.ts +0 -15
- package/dist/src/compiled/@vercel/sandbox-drives/utils/sandbox-snapshot.d.ts +0 -11
- package/dist/src/compiled/@vercel/sandbox-drives/utils/types.d.ts +0 -11
- package/dist/src/compiled/_chunks/node/auth-8aQozzfi.js +0 -2
- package/dist/src/compiled/_chunks/node/auth-Bvv0xGTY.js +0 -2
- package/dist/src/compiled/_chunks/node/esm-Fqlolk7e.js +0 -7
- package/dist/src/compiled/_chunks/node/version-BC6t2Txc.js +0 -1
- package/dist/src/compiled/_chunks/node/version-DSQqVZ5T.js +0 -1
- package/dist/src/compiled/_chunks/node/xdg-app-paths-F-QHrdza.js +0 -1
|
@@ -43,7 +43,11 @@ export type AgentTUIStreamUsage = {
|
|
|
43
43
|
outputTokens?: number;
|
|
44
44
|
};
|
|
45
45
|
export type AgentTUIStreamEvent = {
|
|
46
|
+
type: "turn-start";
|
|
47
|
+
turnId: string;
|
|
48
|
+
} | {
|
|
46
49
|
type: "step-start";
|
|
50
|
+
modelId?: string;
|
|
47
51
|
} | {
|
|
48
52
|
type: "step-finish";
|
|
49
53
|
usage?: AgentTUIStreamUsage;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{pickAgentHeaderTip}from"./agent-header.js";import{failureKey,formatFailureDetail,formatFailureHint,formatFailureMessage,isInterruptedError,localFailureHint}from"./errors.js";import{parseLogDisplayMode}from"./log-display-mode.js";import{createMcpConnectionStatusTracker}from"./mcp-connection-status.js";import{describeRemoteAuthCompletedMutations}from"./remote-auth-result.js";import{createRemoteConnectionController}from"./remote-connection.js";import{prepareRemoteTuiAccess}from"./remote-startup.js";import{SubagentPump}from"./subagent-pump.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,detectSetupIssues,formatSetupIssuesLine,normalizeLocalModelEndpoint,orderedSetupIssues}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import"#client/index.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{inspectApplication}from"#services/inspect-application.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{probeAgentInfo}from"#services/dev-client/agent-info-probe.js";import{SteeringStream}from"#cli/dev/tui/steering-stream.js";import{renderApplicationInfo}from"#cli/commands/info.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{createDevelopmentRuntimeArtifactRefresher}from"#services/dev-client.js";async function delayMs(e){await new Promise(t=>{setTimeout(t,e).unref?.()})}async function abortableDelay(e,t){t.aborted||await new Promise(n=>{let r=setTimeout(done,e);r.unref?.(),t.addEventListener(`abort`,done,{once:!0});function done(){clearTimeout(r),t.removeEventListener(`abort`,done),n()}})}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=!1;#y;#b;#x=!0;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j=!1;#M=new AbortController;#N=!1;#P=0;#F=0;#I=[];#L;#R;#z;#B;#V;#H=new Map;#U;#W=[];#G;#K=!1;#q;#J=new Map;#Y=new Set;#X;#Z;#Q;constructor(e){this.#e=e.session,e.client!==void 0&&(this.#t=e.client),e.lifecycle!==void 0&&(this.#Q=e.lifecycle),this.#n=createRenderer(e);let t={formatActionResultError};if(this.#t!==void 0&&(t.client=this.#t),this.#n.subagents!==void 0&&(t.view=this.#n.subagents),e.appRoot!==void 0&&(t.onToolCompleted=async(e,t)=>{let n=registryHandoffAddress(e,t);n!==void 0&&this.#me(n)}),this.#q=new SubagentPump(t),this.#r=e.name??`eve`,this.#B=e.startup?.headerTip??pickAgentHeaderTip(),this.#w=e.withExclusiveTerminal,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.startup!==void 0&&(this.#h=e.startup),this.#_=e.onboard===!0,this.#y=e.onOnboardingStep,this.#b=e.onOnboardingTerminal,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.#R=createVercelStatusTracker(t),e.probeMcpConnection!==void 0&&(this.#z=createMcpConnectionStatusTracker({onChange:()=>{},probe:e.probeMcpConnection}))}if(e.promptCommandHandler!==void 0&&(this.#S=e.promptCommandHandler),this.#C=e.availablePromptCommands??PROMPT_COMMANDS,e.remote!==void 0){if(this.#E=e.remote.runAuthFlow,this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#T=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.#D=e.bootDetections??BOOT_DETECTIONS,this.#O=e.getVercelAuthStatus??getVercelAuthStatus,this.#k=e.inspectApplication??inspectApplication,e.onBootProgress!==void 0&&(this.#A=e.onBootProgress),e.serverUrl!==void 0&&(this.#f=e.serverUrl),e.serverUrl!==void 0&&e.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactRefresher({serverUrl:e.serverUrl}))}async#$(){if(this.#f===void 0){this.#ne(),this.#_||await this.#ge(void 0);return}let e;if(this.#T!==void 0){let t=await this.#T.check();t.state===`ready`&&(e=t.info)}else{let t=this.#t;if(t!==void 0)try{let n=await devBootPhase(`connecting to agent`,()=>probeAgentInfo({client:t}),this.#A);n.kind===`ready`&&(e=n.info)}catch{e=void 0}}this.#ne();let t=this.#te(e);this.#_||await this.#ge(t)}#ee(){let e=this.#h?.finish();return this.#g=e?.queuedPrompt,e?.draft??this.#m}#te(e){let t=this.#p===void 0?e:normalizeLocalModelEndpoint(e,process.env);this.#V=t;let n=this.#f;if(n===void 0||this.#x)return t;let r={name:this.#r,serverUrl:n};return t!==void 0&&(r.info=t),this.#p!==void 0&&!this.#_&&(r.tip=this.#B),this.#n.renderAgentHeader?.(r),t}#ne(){let e=this.#A;this.#A=void 0,e?.({type:`before-first-paint`})}async run(){let onStop=()=>this.#n.requestInterrupt?.();this.#Q?.signal.aborted===!0?onStop():this.#Q?.signal.addEventListener(`abort`,onStop,{once:!0});try{await this.#re()}finally{this.#Q?.signal.removeEventListener(`abort`,onStop),this.#j=!0,this.#M.abort(),this.#q.abortAll(),this.#Z?.(),this.#Z=void 0,this.#n.shutdown?.(),this.#R?.dispose(),this.#z?.dispose(),this.#T?.dispose()}}async#re(){let e=this.#r,t,n,r=!1,i=!1,a=!1;this.#n.setStartupPhase?.(`starting`),await this.#$(),this.#be(),this.#R?.refreshIdentity(),this.#z?.refresh();let o=(this.#_||this.#V?.agent.model.endpoint?.kind===`gateway`&&!this.#V.agent.model.endpoint.connected)&&this.#p!==void 0&&this.#S!==void 0&&this.#n.setupFlow!==void 0,s;if(this.#T!==void 0&&this.#n.setupFlow!==void 0){let e=await prepareRemoteTuiAccess({connection:this.#T,renderer:this.#n.setupFlow,signal:this.#Q?.signal,runAuthFlow:this.#E});if(e?.kind===`authenticated`){let e=this.#T.current().connection;e.state===`ready`&&this.#te(e.info)}else e?.kind===`failed`||e?.kind===`unavailable`?s={tone:`error`,message:e.kind===`failed`?e.message:e.failure.message}:e?.kind===`cancelled`&&(s={cancelled:!0},e.completedMutations.length>0&&(s.message=`Completed before cancellation: ${describeRemoteAuthCompletedMutations(e.completedMutations).join(`, `)}.`))}o&&(this.#n.setStartupPhase?.(`connecting`),s=await this.#De(e));let c=this.#ee();for(s?.cancelled||s?.tone===`error`?c=[this.#g,c].filter(Boolean).join(`
|
|
2
2
|
|
|
3
|
-
`)||void 0:t=this.#g,this.#x=!1,this.#te(this.#V),this.#_e(),this.#n.setStartupPhase?.(void 0),o&&this.#Ce({type:`extension`,name:`login`,argument:``},`startup`,s?.tone),this.#xe(s?.message,s?.tone);;){if(this.#Q?.signal.aborted===!0||this.#n.exitRequested?.()===!0)return;let o=this.#W[0];if(o!==void 0&&n===void 0&&this.#U===void 0){this.#W.shift(),this.#G=o;try{await this.#he(o)}finally{this.#G=void 0}i=!1,a=!1,t=void 0;continue}if(!a){if(t==null){if(!this.#n.readPrompt){if(r)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{this.#K=!0,t=await this.#ce(n)}catch(e){if(isInterruptedError(e)){if(this.#U===void 0&&this.#W.length===0)return;a=!0,t=``}else throw e}finally{this.#K=!1}if(this.#W.length>0&&this.#U===void 0){t=void 0;continue}if(t==null&&this.#U===void 0)return}let o=this.#U===void 0?parsePromptCommand(t):null;if(o?.type===`exit`){this.#Q?.requestStop();return}if(o?.type===`cancel`){if(this.#e===void 0){this.#xe(`No active turn to cancel.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.cancel();if(this.#xe(e.status===`accepted`?`Turn cancellation requested.`:`No active turn to cancel.`),e.status===`no_active_turn`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#xe(`Couldn't cancel the turn: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(o?.type===`reset`){if(!await this.#oe()){n=void 0,a=!1,t=void 0;continue}n=void 0,a=!1,t=void 0;continue}if(o?.type===`compact`){if(this.#e===void 0){this.#xe(`No active session to compact.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.compact();if(this.#xe(e.status===`accepted`?`Compaction requested.`:`No active session to compact.`),e.status===`no_active_session`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#xe(`Couldn't compact the session: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(o?.type===`clear`){if(this.#e===void 0){this.#xe(`No active session to clear.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.clear();if(this.#xe(e.status===`accepted`?`Context clear requested.`:`No active session to clear.`),e.status===`no_active_session`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#xe(`Couldn't clear the session: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(o?.type===`help`){this.#xe(formatPromptCommandHelp(this.#C)),n=void 0,a=!1,t=void 0;continue}if(o?.type===`info`){await this.#Ae(),n=void 0,a=!1,t=void 0;continue}if(o?.type===`loglevel`){this.#xe(this.#je(o.argument)),n=void 0,a=!1,t=void 0;continue}if(o?.type===`traces`){await this.#ke(o.argument),n=void 0,a=!1,t=void 0;continue}if(o?.type===`extension`){try{await this.#Ee(o,e,{trigger:`command`})}catch(e){if(isInterruptedError(e))return;throw e}n=void 0,t=void 0,a=!1;continue}r=!0}let s=this.#U;this.#U=void 0;let l=s??(i?this.#fe():await(async()=>(this.#ae(),await this.#ue({prompt:a?void 0:t,inputResponses:n})))()),u=this.#e?.state.sessionId;u!==void 0&&this.#n.setSessionId?.(u);let d=t,f=!1;try{for(;;){await this.#n.renderStream(l,{title:e,submittedPrompt:d,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let r=l.turnState?.pendingApprovals??[],i=l.turnState?.pendingQuestions??[];if(r.length>0||i.length>0){let o=[];if(r.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 r){let n=await this.#n.readToolApproval(t,{title:e});o.push({requestId:t.approvalId,optionId:n.approved?`approve`:`cancel`}),this.#H.delete(t.approvalId)}}if(i.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 i){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let i={requestId:t.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),o.push(i),this.#H.delete(t.requestId)}}if(o.length===0)break;a=!0,n=o,t=void 0,f=!0;break}if(this.#Le(l)){l=this.#fe(),d=void 0;continue}if(l.turnState&&l.turnState.boundaryEvent===void 0&&!l.turnState.aborted){let e=this.#e?.state.sessionId;this.#n.renderNotice?.(e?`Lost the event stream — the turn may still be running on the server (session ${e}). Your next message resumes this session; use /cancel to stop the turn.`:`Lost the connection to the running turn.`)}break}}catch(e){if(isInterruptedError(e))return;throw e}if(f)continue;i=!1,a=!1,n=void 0,t=void 0;let p=l.turnState?.boundaryEvent;this.#X!==this.#e&&(p===`session.waiting`||p===`session.completed`)&&(t=this.#n.takeQueuedPrompt?.()),this.#ae(l.turnState?.aborted===!0)}}#ie(){this.#q.abortAll(),this.#H.clear(),this.#J.clear(),this.#Y.clear(),this.#n.setConnectionAuthPendingCount?.(0),this.#e=void 0,this.#d?.clear()}#ae(e=!1){let t=this.#X;t!==void 0&&(this.#X=void 0,this.#e===t&&(this.#ie(),e?this.#n.renderNotice?.(`Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server.`):this.#n.renderSessionBoundary===void 0?this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`):this.#n.renderSessionBoundary()))}async#oe(){if(this.#e===void 0)return this.#ie(),this.#n.reset?.(),!0;try{await this.#e.reset()}catch(e){return this.#n.renderNotice?.(`Couldn't reset the session: ${toErrorMessage(e)}`),!1}return this.#ie(),this.#n.reset?.(),!0}async#se(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#d;if(n===void 0)return await t;let r=!1,i=!1,a,o=0,refresh=async()=>{if(!(r||i)){i=!0;try{await n.refreshIdle({onRuntimeArtifactsChanged:()=>this.#Fe()});let e=this.#V?.agent.model.endpoint,t=e?.kind===`chatgpt`&&(e.state===`signed-out`||e.state===`reauth-required`),r=Date.now();t&&r-o>=5e3&&(o=r,this.#Ne())}finally{i=!1}}},startRefresh=()=>{if(r||i)return;let e=refresh().finally(()=>{a===e&&(a=void 0)});a=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await t}finally{r=!0,clearInterval(s),await a}}async#ce(e){let t=this.#se(e);if(this.#n.renderIdleStream===void 0||this.#e?.state.sessionId===void 0)return await t;let n=new AbortController,r=this.#le(n.signal,e).catch(e=>{n.signal.aborted||this.#n.renderNotice?.(`Stopped following session updates: ${toErrorMessage(e)}`)});try{return await t}finally{n.abort(),await r}}async#le(e,t){let n=this.#e;if(n===void 0)return;let r=100;for(;!e.aborted;){let i=n.stream({signal:e})[Symbol.asyncIterator](),a=!1;try{for(;!e.aborted;){let r=!1,o={async*[Symbol.asyncIterator](){for(;!e.aborted;){let e=await i.next();if(e.done===!0||(r=!0,a=!0,yield e.value,isCurrentTurnBoundaryEvent(e.value)))return}}},s=this.#pe(o,()=>{},n);if(await this.#n.renderIdleStream(s,{...t,continueSession:!0}),this.#Le(s),(s.turnState?.pendingApprovals.length??0)>0||(s.turnState?.pendingQuestions.length??0)>0){this.#U={events:(async function*(){})(),turnState:s.turnState},this.#n.suspendPromptForInput?.();return}if(s.turnState?.boundaryEvent===`session.completed`||s.turnState?.boundaryEvent===`session.failed`)return;if(!r)break}}finally{await i.return?.()}r=a?100:Math.min(r*2,2e3),e.aborted||await abortableDelay(r,e)}}async#ue(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,i=this.#e;try{if(this.#d!==void 0&&await this.#d.refresh({inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#Fe()}),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),this.#e===void 0){if(this.#t===void 0)throw Error(`Cannot create a session without an eve client.`);if(n.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let e=await this.#t.sessions.create({...n,message:n.message});this.#e=e.session,r=e.response}else r=n.inputResponses===void 0?await this.#e.send(n.message,{signal:n.signal,turnPolicy:`queue`}):await this.#e.respond(n.inputResponses,{signal:n.signal})}catch(e){if(isInterruptedError(e))throw e;return this.#T?.reportFailure(e),this.#X=i,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}return this.#pe(r,()=>t.abort(),this.#e)}async#de(e,t){if(e.cancelInFlight!==!0){e.cancelInFlight=!0;try{for(let n=0;n<8;n+=1){if(e.boundaryEvent!==void 0||e.aborted===!0)return;let n=e.turnId;try{if((await t?.cancel(n===void 0?void 0:{turnId:n}))?.status===`accepted`)return}catch{}await delayMs(250)}}finally{e.cancelInFlight=!1}}}#fe(){if(this.#e===void 0)throw Error(`Cannot stream a session before its first turn is accepted.`);let e=new AbortController,t=this.#e;return this.#pe(t.stream({signal:e.signal}),()=>e.abort(),t)}#pe(e,t,n){let r=createTurnState(),i=n===void 0?void 0:new SteeringStream(e,n);return{steer:i===void 0?void 0:e=>i.send(e),abort:()=>{r.aborted=!0,this.#X=n,i?.abort(),t()},cancel:()=>{this.#de(r,n)},events:eveEventsToTUIStream({onAssistantResponse:()=>{this.#_&&!this.#v&&(this.#v=!0,this.#y?.({flow:`onboarding`,step:`first_response`}))},events:i??e,pendingInputRequests:this.#H,turnState:r,onSubagentCalled:e=>this.#q.begin(e),onSubagentBackgrounded:e=>this.#q.background(e),onSubagentCompleted:e=>this.#q.settle(e),onTurnCancelled:e=>this.#q.settleCancelledTurn(e),onConnectionAuthRequired:e=>this.#Ie(e),onConnectionAuthCompleted:e=>this.#Re(e),onRegistryHandoff:this.#p===void 0?void 0:async e=>this.#me(e),onTerminalFailure:()=>{this.#X=n},failureHintOverride:this.#p===void 0?void 0:localFailureHint}),turnState:r}}#me(e){this.#G===e||this.#W.includes(e)||(this.#W.push(e),this.#K&&this.#n.suspendPromptForInput?.())}async#he(e){await this.#Ee({type:`extension`,name:`add`,argument:e},`Add to your agent`,{trigger:`command`})}async#ge(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#I=await detectSetupIssues(t,this.#D),this.#n.renderSetupWarning!==void 0&&(this.#_e(),this.#ve())}#_e(){if(this.#x)return;let e=orderedSetupIssues(this.#I,this.#L);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#ve(){let e=this.#p;if(e===void 0||process.env.EVE_MODEL_CONNECTION!==`ai-gateway-project`)return;let t;try{t=await this.#O(e,{signal:this.#M.signal})}catch{return}this.#j||this.#N||(this.#L=authIssueForStatus(t),this.#_e())}async#ye(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n=++this.#P,r={appRoot:t,env:process.env};e!==void 0&&(r.info=e);try{let[e,i]=await Promise.all([detectSetupIssues(r,this.#D),process.env.EVE_MODEL_CONNECTION===`ai-gateway-project`?this.#O(t,{signal:this.#M.signal}):void 0]);if(this.#j||n!==this.#P)return;this.#I=e,this.#L=i===void 0?void 0:authIssueForStatus(i),this.#_e()}catch{return}}#be(){this.#p!==void 0&&this.#n.renderSandboxLog!==void 0&&this.#Z===void 0&&(this.#Z=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#xe(e,t){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e,t);return}this.#n.renderNotice?.(e)}}async#Se(e,t){let n=this.#S;if(n===void 0)return{message:`/${e.name} is not available in this session.`};let r=this.#V?.agent.model.endpoint,i={...t,renderer:this.#n,settleOutcome:e=>this.#Te(e),chatGptAccountLabel:r?.kind===`chatgpt`&&r.state===`ready`?r.accountLabel:void 0,withExclusiveTerminal:this.#w},a=this.#z?.current(),o=a!==void 0&&Object.keys(a).length>0?{...i,disabledConnectionReasons:a}:i;return await n.handle(e,o)}#Ce(e,t,n){if(t!==`startup`)return;let r=this.#T?.current().connection.state,i=n===`error`||r===`auth-failed`||r===`unavailable`?`failed`:void 0,a=e.argument.length===0?``:` ${e.argument}`;this.#n.renderCommandInvocation?.(`/${e.name}${a}`,i)}async#we(e){if(e?.kind===`model-access-changed`){this.#R?.applyEffect({kind:`refresh-identity`}),this.#N=!0,await this.#Me(e);return}e!==void 0&&(this.#R?.applyEffect(e),this.#N=!0,this.#ye(this.#V))}async#Te(e){if(e.effect===void 0)return e;let t=e.effect.kind===`model-access-changed`&&e.effect.reload?setTimeout(()=>{this.#x&&this.#n.setStartupPhase?.(`updating`),this.#n.setupFlow?.setStatus(`Loading selected model…`)},150):void 0;try{await this.#we(e.effect);let{effect:t,...n}=e;return n}catch{return{tone:`error`,message:`Settings were saved, but the agent could not reload. Retry the command or restart eve dev.`}}finally{clearTimeout(t)}}async#Ee(e,t,n){let r=await this.#Se(e,{...n,title:t}),i=r===void 0?void 0:await this.#Te(r);return!(n.suppressSuccessfulTranscript===!0&&i?.tone!==`error`||n.suppressCancelledTranscript===!0&&i?.cancelled===!0)&&n.trigger!==`startup`&&this.#xe(i?.message,i?.tone),this.#Oe(),i}async#De(e){this.#y?.({flow:`onboarding`,step:`model_provider`});let t=await this.#Ee({type:`extension`,name:`login`,argument:``},e,{trigger:`startup`,initialModelStep:`provider`});return!t?.cancelled&&t?.tone!==`error`&&this.#y?.({flow:`onboarding`,step:`connection_ready`}),this.#b?.({flow:`onboarding`,step:`model_provider`,result:t?.cancelled?`cancelled`:t?.tone===`error`?`error`:`completed`}),t}#Oe(){if(this.#x)return;let e=this.#T?.current().connection;e?.state===`ready`&&e.info!==this.#V&&(this.#V=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}async#ke(e){if(this.#p===void 0||this.#n.traceViewer===void 0){this.#xe(`/traces is only available in local dev sessions.`);return}try{await this.#n.traceViewer.open({appRoot:this.#p,sessionId:this.#e?.state.sessionId,reference:e===``?void 0:e})}catch(e){if(isInterruptedError(e))return;throw e}}async#Ae(){let e=this.#p;if(e===void 0){this.#xe(`/info is only available in local dev sessions.`);return}try{this.#xe(renderApplicationInfo(await this.#k(e)))}catch(e){this.#xe(`Couldn't inspect the application: ${toErrorMessage(e)}`,`error`)}}#je(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#Me(e){let t=this.#p;t!==void 0&&(++this.#F,++this.#P,await loadDevelopmentEnvironmentFiles(t),e.reload&&await this.#d?.refreshAfterSourceChange({}),e.model&&this.#V?this.#te({...this.#V,agent:{...this.#V.agent,model:{...this.#V.agent.model,...e.model}}}):this.#te(this.#V),this.#I=[],this.#L=void 0,this.#_e(),this.#Ne())}async#Ne(e=!1){let t=this.#V,n=++this.#F,r=await this.#Pe();this.#j||n!==this.#F||r===void 0||(this.#te(r),e&&!this.#n.renderAgentHeader&&this.#n.renderNotice?.(formatAgentUpdateNotice(t,r)),this.#ye(this.#V))}async#Pe(){let e=this.#t;if(e===void 0)return;let t=await probeAgentInfo({client:e});return t.kind===`ready`?t.info:void 0}#Fe(){this.#Ne(!0)}#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.#J.set(e.data.name,t),this.#ze(t)}#Le(e){if(e.turnState?.boundaryEvent!==`session.waiting`)return!1;let t=!1;for(let e of this.#J.values())e.state===`required`&&e.webhookUrl!==void 0&&(e.state=`pending`,this.#Y.add(e.name),this.#ze(e),t=!0);return t&&this.#n.setConnectionAuthPendingCount?.(this.#Y.size),this.#Y.size>0}#Re(e){let t=this.#J.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.#J.set(e.data.name,t),this.#Y.delete(e.data.name),this.#ze(t),this.#n.setConnectionAuthPendingCount?.(this.#Y.size)}#ze(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)}};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,diagnostics:e.diagnostics,onExitRequest:e.lifecycle?.requestStop})}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.`}function registryHandoffAddress(e,t){if(e!==`selfmod__registry_add`||typeof t!=`object`||!t)return;let n=t;return n.status===`needs-terminal`&&typeof n.address==`string`?n.address:void 0}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,turnState:r,onSubagentCalled:i,onSubagentBackgrounded:a,onSubagentCompleted:o,onTurnCancelled:s,onConnectionAuthRequired:c,onConnectionAuthCompleted:l,onRegistryHandoff:u,onTerminalFailure:d,failureHintOverride:f}=e,p=new Map,m=new Map,h=new Map,g=createEventDeduper(),_=0,v=new Set,y=new Set,b=new Set,x=!1,S=!1,C;for await(let w of t)if(g.admit(w)&&!(S&&isPostTurnVisibleEvent(w)))switch(w.type){case`session.started`:case`message.received`:break;case`turn.started`:w.data.turnId!==r.turnId&&(S=!1),r.turnId=w.data.turnId;break;case`step.started`:_+=1,yield{type:`step-start`};break;case`step.completed`:{let e=w;C=e.data.usage,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`step-finish`,usage:e.data.usage};break}case`message.appended`:{let t=w,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(p,n);if(r.completed){if(_<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}let i=t.data.messageDelta;if(i.length===0)break;r.text+=i,i&&e.onAssistantResponse?.(),yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:i};break}case`message.completed`:{let t=textPartId(w.data.turnId,w.data.stepIndex),n=partStateFor(p,t),r=w.data.message;if(n.completed){if(r===null||_<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=_,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=_,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let t=r.slice(n.text.length);t.length>0&&(t&&e.onAssistantResponse?.(),yield{type:`assistant-delta`,id:i,delta:t}),n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i}}else n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i,text:r}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let e=w,t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(m,t);if(n.completed){if(_<=n.completedEpoch)break;n.generation+=1,n.text=``,n.completed=!1}let r=e.data.reasoningDelta;if(r.length===0)break;n.text+=r,yield{type:`reasoning-delta`,id:partGenerationId(t,n.generation),delta:r};break}case`reasoning.completed`:{let e=reasoningPartId(w.data.turnId,w.data.stepIndex),t=partStateFor(m,e),n=w.data.reasoning;if(t.completed){if(n.length===0||_<=t.completedEpoch)break;t.generation+=1,t.text=n,t.completedEpoch=_;let r=partGenerationId(e,t.generation);yield{type:`reasoning-delta`,id:r,delta:n},yield{type:`reasoning-complete`,id:r};break}let r=partGenerationId(e,t.generation);if(t.text.length===0&&n.length>0)t.text=n,yield{type:`reasoning-delta`,id:r,delta:n};else if(n.length>0&&!n.startsWith(t.text)){yield{type:`reasoning-complete`,id:r},t.generation+=1,t.text=n,t.completed=!0,t.completedEpoch=_;let i=partGenerationId(e,t.generation);yield{type:`reasoning-delta`,id:i,delta:n},yield{type:`reasoning-complete`,id:i};break}t.completed=!0,t.completedEpoch=_,yield{type:`reasoning-complete`,id:r};break}case`actions.requested`:{let e=w.data.actions.filter(e=>e.kind===`tool-call`);if(e.length===0)break;for(let t of e)h.set(t.callId,t.toolName),!v.has(t.callId)&&(v.add(t.callId),yield{type:`tool-call`,toolCallId:t.callId,toolName:t.toolName,input:t.input});break}case`input.requested`:{let e=w.data.requests.filter(e=>e.action.kind===`tool-call`);if(e.length===0)break;for(let t of e){let e=t.action.callId;if(h.set(e,t.action.toolName),t.kind!==`session-limit`&&!v.has(e)&&(v.add(e),yield{type:`tool-call`,toolCallId:e,toolName:t.action.toolName,input:t.action.input}),!y.has(t.requestId)){if(y.add(t.requestId),n.set(t.requestId,t),t.kind!==`tool-approval`){upsertPendingQuestion(r,t);continue}upsertPendingApproval(r,t),yield{type:`tool-approval-request`,approvalId:t.requestId,toolCallId:e}}}break}case`action.result`:{let e=w;if(e.data.result.kind!==`tool-result`)break;let t=e.data.result.callId;if(!v.has(t))break;switch(e.data.status){case`completed`:{let n=e.data.result.output;yield{type:`tool-result`,toolCallId:t,output:n};let r=registryHandoffAddress(h.get(t),n);r!==void 0&&await u?.(r);break}case`failed`:yield{type:`tool-error`,toolCallId:t,errorText:formatActionResultError(e)};break;case`rejected`:yield{type:`tool-rejected`,toolCallId:t,reason:formatActionResultError(e)}}break}case`step.failed`:case`turn.failed`:{let e=toFailureEvent(w,b,f);e&&(yield e);break}case`session.failed`:{r.sawSessionFailure=!0,d?.(w);let e=toFailureEvent(w,b,f);e&&(yield e),r.boundaryEvent=w.type,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C},x=!0;return}case`session.waiting`:case`session.completed`:r.boundaryEvent=w.type,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C},x=!0;return;case`turn.completed`:S=!0,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_);break;case`turn.cancelled`:s?.(w.data.turnId),yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`turn-cancelled`};break;case`subagent.called`:i?.(w);break;case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:{let e=w;e.data.backgroundTask===void 0?o?.(e.data.callId):a?.(e.data.callId);break}case`authorization.required`:c?.(w);break;case`authorization.completed`:l?.(w)}x||(yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{aborted:!1,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 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 i={type:`error`,errorText:formatFailureMessage(e)},a=n?.(e)??formatFailureHint(e);a!==void 0&&(i.hint=a);let o=formatFailureDetail(e);return o!==void 0&&(i.detail=o),i}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}export{EveTUIRunner,parsePromptCommand,registryHandoffAddress};
|
|
3
|
+
`)||void 0:t=this.#g,this.#x=!1,this.#te(this.#V),this.#_e(),this.#n.setStartupPhase?.(void 0),o&&this.#Ce({type:`extension`,name:`login`,argument:``},`startup`,s?.tone),this.#xe(s?.message,s?.tone);;){if(this.#Q?.signal.aborted===!0||this.#n.exitRequested?.()===!0)return;let o=this.#W[0];if(o!==void 0&&n===void 0&&this.#U===void 0){this.#W.shift(),this.#G=o;try{await this.#he(o)}finally{this.#G=void 0}i=!1,a=!1,t=void 0;continue}if(!a){if(t==null){if(!this.#n.readPrompt){if(r)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{this.#K=!0,t=await this.#ce(n)}catch(e){if(isInterruptedError(e)){if(this.#U===void 0&&this.#W.length===0)return;a=!0,t=``}else throw e}finally{this.#K=!1}if(this.#W.length>0&&this.#U===void 0){t=void 0;continue}if(t==null&&this.#U===void 0)return}let o=this.#U===void 0?parsePromptCommand(t):null;if(o?.type===`exit`){this.#Q?.requestStop();return}if(o?.type===`cancel`){if(this.#e===void 0){this.#xe(`No active turn to cancel.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.cancel();if(this.#xe(e.status===`accepted`?`Turn cancellation requested.`:`No active turn to cancel.`),e.status===`no_active_turn`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#xe(`Couldn't cancel the turn: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(o?.type===`reset`){if(!await this.#oe()){n=void 0,a=!1,t=void 0;continue}n=void 0,a=!1,t=void 0;continue}if(o?.type===`compact`){if(this.#e===void 0){this.#xe(`No active session to compact.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.compact();if(this.#xe(e.status===`accepted`?`Compaction requested.`:`No active session to compact.`),e.status===`no_active_session`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#xe(`Couldn't compact the session: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(o?.type===`clear`){if(this.#e===void 0){this.#xe(`No active session to clear.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.clear();if(this.#xe(e.status===`accepted`?`Context clear requested.`:`No active session to clear.`),e.status===`no_active_session`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#xe(`Couldn't clear the session: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(o?.type===`help`){this.#xe(formatPromptCommandHelp(this.#C)),n=void 0,a=!1,t=void 0;continue}if(o?.type===`info`){await this.#Ae(),n=void 0,a=!1,t=void 0;continue}if(o?.type===`loglevel`){this.#xe(this.#je(o.argument)),n=void 0,a=!1,t=void 0;continue}if(o?.type===`traces`){await this.#ke(o.argument),n=void 0,a=!1,t=void 0;continue}if(o?.type===`extension`){try{await this.#Ee(o,e,{trigger:`command`})}catch(e){if(isInterruptedError(e))return;throw e}n=void 0,t=void 0,a=!1;continue}r=!0}let s=this.#U;this.#U=void 0;let l=s??(i?this.#fe():await(async()=>(this.#ae(),await this.#ue({prompt:a?void 0:t,inputResponses:n})))()),u=this.#e?.state.sessionId;u!==void 0&&this.#n.setSessionId?.(u);let d=t,f=!1;try{for(;;){await this.#n.renderStream(l,{title:e,submittedPrompt:d,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let r=l.turnState?.pendingApprovals??[],i=l.turnState?.pendingQuestions??[];if(r.length>0||i.length>0){let o=[];if(r.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 r){let n=await this.#n.readToolApproval(t,{title:e});o.push({requestId:t.approvalId,optionId:n.approved?`approve`:`cancel`}),this.#H.delete(t.approvalId)}}if(i.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 i){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let i={requestId:t.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),o.push(i),this.#H.delete(t.requestId)}}if(o.length===0)break;a=!0,n=o,t=void 0,f=!0;break}if(this.#Le(l)){l=this.#fe(),d=void 0;continue}if(l.turnState&&l.turnState.boundaryEvent===void 0&&!l.turnState.aborted){let e=this.#e?.state.sessionId;this.#n.renderNotice?.(e?`Lost the event stream — the turn may still be running on the server (session ${e}). Your next message resumes this session; use /cancel to stop the turn.`:`Lost the connection to the running turn.`)}break}}catch(e){if(isInterruptedError(e))return;throw e}if(f)continue;i=!1,a=!1,n=void 0,t=void 0;let p=l.turnState?.boundaryEvent;this.#X!==this.#e&&(p===`session.waiting`||p===`session.completed`)&&(t=this.#n.takeQueuedPrompt?.()),this.#ae(l.turnState?.aborted===!0)}}#ie(){this.#q.abortAll(),this.#H.clear(),this.#J.clear(),this.#Y.clear(),this.#n.setConnectionAuthPendingCount?.(0),this.#e=void 0,this.#d?.clear()}#ae(e=!1){let t=this.#X;t!==void 0&&(this.#X=void 0,this.#e===t&&(this.#ie(),e?this.#n.renderNotice?.(`Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server.`):this.#n.renderSessionBoundary===void 0?this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`):this.#n.renderSessionBoundary()))}async#oe(){if(this.#e===void 0)return this.#ie(),this.#n.reset?.(),!0;try{await this.#e.reset()}catch(e){return this.#n.renderNotice?.(`Couldn't reset the session: ${toErrorMessage(e)}`),!1}return this.#ie(),this.#n.reset?.(),!0}async#se(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#d;if(n===void 0)return await t;let r=!1,i=!1,a,o=0,refresh=async()=>{if(!(r||i)){i=!0;try{await n.refreshIdle({onRuntimeArtifactsChanged:()=>this.#Fe()});let e=this.#V?.agent.model.endpoint,t=e?.kind===`chatgpt`&&(e.state===`signed-out`||e.state===`reauth-required`),r=Date.now();t&&r-o>=5e3&&(o=r,this.#Ne())}finally{i=!1}}},startRefresh=()=>{if(r||i)return;let e=refresh().finally(()=>{a===e&&(a=void 0)});a=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await t}finally{r=!0,clearInterval(s),await a}}async#ce(e){let t=this.#se(e);if(this.#n.renderIdleStream===void 0||this.#e?.state.sessionId===void 0)return await t;let n=new AbortController,r=this.#le(n.signal,e).catch(e=>{n.signal.aborted||this.#n.renderNotice?.(`Stopped following session updates: ${toErrorMessage(e)}`)});try{return await t}finally{n.abort(),await r}}async#le(e,t){let n=this.#e;if(n===void 0)return;let r=100;for(;!e.aborted;){let i=n.stream({signal:e})[Symbol.asyncIterator](),a=!1;try{for(;!e.aborted;){let r=!1,o={async*[Symbol.asyncIterator](){for(;!e.aborted;){let e=await i.next();if(e.done===!0||(r=!0,a=!0,yield e.value,isCurrentTurnBoundaryEvent(e.value)))return}}},s=this.#pe(o,()=>{},n);if(await this.#n.renderIdleStream(s,{...t,continueSession:!0}),this.#Le(s),(s.turnState?.pendingApprovals.length??0)>0||(s.turnState?.pendingQuestions.length??0)>0){this.#U={events:(async function*(){})(),turnState:s.turnState},this.#n.suspendPromptForInput?.();return}if(s.turnState?.boundaryEvent===`session.completed`||s.turnState?.boundaryEvent===`session.failed`)return;if(!r)break}}finally{await i.return?.()}r=a?100:Math.min(r*2,2e3),e.aborted||await abortableDelay(r,e)}}async#ue(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,i=this.#e;try{if(this.#d!==void 0&&await this.#d.refresh({inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#Fe()}),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),this.#e===void 0){if(this.#t===void 0)throw Error(`Cannot create a session without an eve client.`);if(n.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let e=await this.#t.sessions.create({...n,message:n.message});this.#e=e.session,r=e.response}else r=n.inputResponses===void 0?await this.#e.send(n.message,{signal:n.signal,turnPolicy:`queue`}):await this.#e.respond(n.inputResponses,{signal:n.signal})}catch(e){if(isInterruptedError(e))throw e;return this.#T?.reportFailure(e),this.#X=i,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}return this.#pe(r,()=>t.abort(),this.#e)}async#de(e,t){if(e.cancelInFlight!==!0){e.cancelInFlight=!0;try{for(let n=0;n<8;n+=1){if(e.boundaryEvent!==void 0||e.aborted===!0)return;let n=e.turnId;try{if((await t?.cancel(n===void 0?void 0:{turnId:n}))?.status===`accepted`)return}catch{}await delayMs(250)}}finally{e.cancelInFlight=!1}}}#fe(){if(this.#e===void 0)throw Error(`Cannot stream a session before its first turn is accepted.`);let e=new AbortController,t=this.#e;return this.#pe(t.stream({signal:e.signal}),()=>e.abort(),t)}#pe(e,t,n){let r=createTurnState(),i=n===void 0?void 0:new SteeringStream(e,n);return{steer:i===void 0?void 0:e=>i.send(e),abort:()=>{r.aborted=!0,this.#X=n,i?.abort(),t()},cancel:()=>{this.#de(r,n)},events:eveEventsToTUIStream({onAssistantResponse:()=>{this.#_&&!this.#v&&(this.#v=!0,this.#y?.({flow:`onboarding`,step:`first_response`}))},events:i??e,pendingInputRequests:this.#H,turnState:r,onSubagentCalled:e=>this.#q.begin(e),onSubagentBackgrounded:e=>this.#q.background(e),onSubagentCompleted:e=>this.#q.settle(e),onTurnCancelled:e=>this.#q.settleCancelledTurn(e),onConnectionAuthRequired:e=>this.#Ie(e),onConnectionAuthCompleted:e=>this.#Re(e),onRegistryHandoff:this.#p===void 0?void 0:async e=>this.#me(e),onTerminalFailure:()=>{this.#X=n},failureHintOverride:this.#p===void 0?void 0:localFailureHint}),turnState:r}}#me(e){this.#G===e||this.#W.includes(e)||(this.#W.push(e),this.#K&&this.#n.suspendPromptForInput?.())}async#he(e){await this.#Ee({type:`extension`,name:`add`,argument:e},`Add to your agent`,{trigger:`command`})}async#ge(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#I=await detectSetupIssues(t,this.#D),this.#n.renderSetupWarning!==void 0&&(this.#_e(),this.#ve())}#_e(){if(this.#x)return;let e=orderedSetupIssues(this.#I,this.#L);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#ve(){let e=this.#p;if(e===void 0||process.env.EVE_MODEL_CONNECTION!==`ai-gateway-project`)return;let t;try{t=await this.#O(e,{signal:this.#M.signal})}catch{return}this.#j||this.#N||(this.#L=authIssueForStatus(t),this.#_e())}async#ye(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n=++this.#P,r={appRoot:t,env:process.env};e!==void 0&&(r.info=e);try{let[e,i]=await Promise.all([detectSetupIssues(r,this.#D),process.env.EVE_MODEL_CONNECTION===`ai-gateway-project`?this.#O(t,{signal:this.#M.signal}):void 0]);if(this.#j||n!==this.#P)return;this.#I=e,this.#L=i===void 0?void 0:authIssueForStatus(i),this.#_e()}catch{return}}#be(){this.#p!==void 0&&this.#n.renderSandboxLog!==void 0&&this.#Z===void 0&&(this.#Z=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#xe(e,t){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e,t);return}this.#n.renderNotice?.(e)}}async#Se(e,t){let n=this.#S;if(n===void 0)return{message:`/${e.name} is not available in this session.`};let r=this.#V?.agent.model.endpoint,i={...t,renderer:this.#n,settleOutcome:e=>this.#Te(e),chatGptAccountLabel:r?.kind===`chatgpt`&&r.state===`ready`?r.accountLabel:void 0,withExclusiveTerminal:this.#w},a=this.#z?.current(),o=a!==void 0&&Object.keys(a).length>0?{...i,disabledConnectionReasons:a}:i;return await n.handle(e,o)}#Ce(e,t,n){if(t!==`startup`)return;let r=this.#T?.current().connection.state,i=n===`error`||r===`auth-failed`||r===`unavailable`?`failed`:void 0,a=e.argument.length===0?``:` ${e.argument}`;this.#n.renderCommandInvocation?.(`/${e.name}${a}`,i)}async#we(e){if(e?.kind===`model-access-changed`){this.#R?.applyEffect({kind:`refresh-identity`}),this.#N=!0,await this.#Me(e);return}e!==void 0&&(this.#R?.applyEffect(e),this.#N=!0,this.#ye(this.#V))}async#Te(e){if(e.effect===void 0)return e;let t=e.effect.kind===`model-access-changed`&&e.effect.reload?setTimeout(()=>{this.#x&&this.#n.setStartupPhase?.(`updating`),this.#n.setupFlow?.setStatus(`Loading selected model…`)},150):void 0;try{await this.#we(e.effect);let{effect:t,...n}=e;return n}catch{return{tone:`error`,message:`Settings were saved, but the agent could not reload. Retry the command or restart eve dev.`}}finally{clearTimeout(t)}}async#Ee(e,t,n){let r=await this.#Se(e,{...n,title:t}),i=r===void 0?void 0:await this.#Te(r);return!(n.suppressSuccessfulTranscript===!0&&i?.tone!==`error`||n.suppressCancelledTranscript===!0&&i?.cancelled===!0)&&n.trigger!==`startup`&&this.#xe(i?.message,i?.tone),this.#Oe(),i}async#De(e){this.#y?.({flow:`onboarding`,step:`model_provider`});let t=await this.#Ee({type:`extension`,name:`login`,argument:``},e,{trigger:`startup`,initialModelStep:`provider`});return!t?.cancelled&&t?.tone!==`error`&&this.#y?.({flow:`onboarding`,step:`connection_ready`}),this.#b?.({flow:`onboarding`,step:`model_provider`,result:t?.cancelled?`cancelled`:t?.tone===`error`?`error`:`completed`}),t}#Oe(){if(this.#x)return;let e=this.#T?.current().connection;e?.state===`ready`&&e.info!==this.#V&&(this.#V=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}async#ke(e){if(this.#p===void 0||this.#n.traceViewer===void 0){this.#xe(`/traces is only available in local dev sessions.`);return}try{await this.#n.traceViewer.open({appRoot:this.#p,sessionId:this.#e?.state.sessionId,reference:e===``?void 0:e})}catch(e){if(isInterruptedError(e))return;throw e}}async#Ae(){let e=this.#p;if(e===void 0){this.#xe(`/info is only available in local dev sessions.`);return}try{this.#xe(renderApplicationInfo(await this.#k(e)))}catch(e){this.#xe(`Couldn't inspect the application: ${toErrorMessage(e)}`,`error`)}}#je(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#Me(e){let t=this.#p;t!==void 0&&(++this.#F,++this.#P,await loadDevelopmentEnvironmentFiles(t),e.reload&&await this.#d?.refreshAfterSourceChange({}),e.model&&this.#V?this.#te({...this.#V,agent:{...this.#V.agent,model:{...this.#V.agent.model,...e.model}}}):this.#te(this.#V),this.#I=[],this.#L=void 0,this.#_e(),this.#Ne())}async#Ne(e=!1){let t=this.#V,n=++this.#F,r=await this.#Pe();this.#j||n!==this.#F||r===void 0||(this.#te(r),e&&!this.#n.renderAgentHeader&&this.#n.renderNotice?.(formatAgentUpdateNotice(t,r)),this.#ye(this.#V))}async#Pe(){let e=this.#t;if(e===void 0)return;let t=await probeAgentInfo({client:e});return t.kind===`ready`?t.info:void 0}#Fe(){this.#Ne(!0)}#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.#J.set(e.data.name,t),this.#ze(t)}#Le(e){if(e.turnState?.boundaryEvent!==`session.waiting`)return!1;let t=!1;for(let e of this.#J.values())e.state===`required`&&e.webhookUrl!==void 0&&(e.state=`pending`,this.#Y.add(e.name),this.#ze(e),t=!0);return t&&this.#n.setConnectionAuthPendingCount?.(this.#Y.size),this.#Y.size>0}#Re(e){let t=this.#J.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.#J.set(e.data.name,t),this.#Y.delete(e.data.name),this.#ze(t),this.#n.setConnectionAuthPendingCount?.(this.#Y.size)}#ze(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)}};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,diagnostics:e.diagnostics,onExitRequest:e.lifecycle?.requestStop})}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.`}function registryHandoffAddress(e,t){if(e!==`selfmod__registry_add`||typeof t!=`object`||!t)return;let n=t;return n.status===`needs-terminal`&&typeof n.address==`string`?n.address:void 0}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,turnState:r,onSubagentCalled:i,onSubagentBackgrounded:a,onSubagentCompleted:o,onTurnCancelled:s,onConnectionAuthRequired:c,onConnectionAuthCompleted:l,onRegistryHandoff:u,onTerminalFailure:d,failureHintOverride:f}=e,p=new Map,m=new Map,h=new Map,g=createEventDeduper(),_=0,v=new Set,y=new Set,b=new Set,x=!1,S=!1,C;for await(let w of t)if(g.admit(w)&&!(S&&isPostTurnVisibleEvent(w)))switch(w.type){case`session.started`:case`message.received`:break;case`turn.started`:w.data.turnId!==r.turnId&&(S=!1),r.turnId=w.data.turnId,yield{type:`turn-start`,turnId:w.data.turnId};break;case`step.started`:_+=1,yield{type:`step-start`,modelId:w.data.modelId};break;case`step.completed`:{let e=w;C=e.data.usage,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`step-finish`,usage:e.data.usage};break}case`message.appended`:{let t=w,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(p,n);if(r.completed){if(_<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}let i=t.data.messageDelta;if(i.length===0)break;r.text+=i,i&&e.onAssistantResponse?.(),yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:i};break}case`message.completed`:{let t=textPartId(w.data.turnId,w.data.stepIndex),n=partStateFor(p,t),r=w.data.message;if(n.completed){if(r===null||_<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=_,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=_,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let t=r.slice(n.text.length);t.length>0&&(t&&e.onAssistantResponse?.(),yield{type:`assistant-delta`,id:i,delta:t}),n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i}}else n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i,text:r}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let e=w,t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(m,t);if(n.completed){if(_<=n.completedEpoch)break;n.generation+=1,n.text=``,n.completed=!1}let r=e.data.reasoningDelta;if(r.length===0)break;n.text+=r,yield{type:`reasoning-delta`,id:partGenerationId(t,n.generation),delta:r};break}case`reasoning.completed`:{let e=reasoningPartId(w.data.turnId,w.data.stepIndex),t=partStateFor(m,e),n=w.data.reasoning;if(t.completed){if(n.length===0||_<=t.completedEpoch)break;t.generation+=1,t.text=n,t.completedEpoch=_;let r=partGenerationId(e,t.generation);yield{type:`reasoning-delta`,id:r,delta:n},yield{type:`reasoning-complete`,id:r};break}let r=partGenerationId(e,t.generation);if(t.text.length===0&&n.length>0)t.text=n,yield{type:`reasoning-delta`,id:r,delta:n};else if(n.length>0&&!n.startsWith(t.text)){yield{type:`reasoning-complete`,id:r},t.generation+=1,t.text=n,t.completed=!0,t.completedEpoch=_;let i=partGenerationId(e,t.generation);yield{type:`reasoning-delta`,id:i,delta:n},yield{type:`reasoning-complete`,id:i};break}t.completed=!0,t.completedEpoch=_,yield{type:`reasoning-complete`,id:r};break}case`actions.requested`:{let e=w.data.actions.filter(e=>e.kind===`tool-call`);if(e.length===0)break;for(let t of e)h.set(t.callId,t.toolName),!v.has(t.callId)&&(v.add(t.callId),yield{type:`tool-call`,toolCallId:t.callId,toolName:t.toolName,input:t.input});break}case`input.requested`:{let e=w.data.requests.filter(e=>e.action.kind===`tool-call`);if(e.length===0)break;for(let t of e){let e=t.action.callId;if(h.set(e,t.action.toolName),t.kind!==`session-limit`&&!v.has(e)&&(v.add(e),yield{type:`tool-call`,toolCallId:e,toolName:t.action.toolName,input:t.action.input}),!y.has(t.requestId)){if(y.add(t.requestId),n.set(t.requestId,t),t.kind!==`tool-approval`){upsertPendingQuestion(r,t);continue}upsertPendingApproval(r,t),yield{type:`tool-approval-request`,approvalId:t.requestId,toolCallId:e}}}break}case`action.result`:{let e=w;if(e.data.result.kind!==`tool-result`)break;let t=e.data.result.callId;if(!v.has(t))break;switch(e.data.status){case`completed`:{let n=e.data.result.output;yield{type:`tool-result`,toolCallId:t,output:n};let r=registryHandoffAddress(h.get(t),n);r!==void 0&&await u?.(r);break}case`failed`:yield{type:`tool-error`,toolCallId:t,errorText:formatActionResultError(e)};break;case`rejected`:yield{type:`tool-rejected`,toolCallId:t,reason:formatActionResultError(e)}}break}case`step.failed`:case`turn.failed`:{let e=toFailureEvent(w,b,f);e&&(yield e);break}case`session.failed`:{r.sawSessionFailure=!0,d?.(w);let e=toFailureEvent(w,b,f);e&&(yield e),r.boundaryEvent=w.type,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C},x=!0;return}case`session.waiting`:case`session.completed`:r.boundaryEvent=w.type,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C},x=!0;return;case`turn.completed`:S=!0,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_);break;case`turn.cancelled`:s?.(w.data.turnId),yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`turn-cancelled`};break;case`subagent.called`:i?.(w);break;case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:{let e=w;e.data.backgroundTask===void 0?o?.(e.data.callId):a?.(e.data.callId);break}case`authorization.required`:c?.(w);break;case`authorization.completed`:l?.(w)}x||(yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{aborted:!1,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 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 i={type:`error`,errorText:formatFailureMessage(e)},a=n?.(e)??formatFailureHint(e);a!==void 0&&(i.hint=a);let o=formatFailureDetail(e);return o!==void 0&&(i.detail=o),i}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}export{EveTUIRunner,parsePromptCommand,registryHandoffAddress};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join}from"node:path";import{pathExists}from"#setup/path-exists.js";import{hasEnvValue,resolveGatewayCredential}from"#internal/resolve-model-endpoint-status.js";function normalizeLocalModelEndpoint(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;if(i.id===void 0||i.routing.kind!==`gateway`)return e;let a=i.endpoint;if(a?.kind===`gateway`&&a.connected&&a.credential===r)return e;let o={connected:!0,credential:r,kind:`gateway`};return{...e,agent:{...e.agent,model:{contextWindowTokens:i.contextWindowTokens,endpoint:o,id:i.id,providerOptions:i.providerOptions,reasoning:i.reasoning,routing:i.routing,source:i.source}}}}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`};let n=e.env.EVE_MODEL_CONNECTION,r=resolveGatewayCredential({apiKeyInEnv:(n===void 0||n===`ai-gateway-key`&&e.env.EVE_MODEL_KEY_SOURCE!==`secret`)&&hasEnvValue(e.env.AI_GATEWAY_API_KEY),oidcAvailable:(n===void 0||n===`ai-gateway-project`)&&hasEnvValue(e.env.VERCEL_OIDC_TOKEN)});if(r?.credential===`api-key`)return{kind:`gateway`,runtime:{status:`connected`,credential:`api-key`}};let i=t.endpoint;return i?.kind===`gateway`&&i.connected?{kind:`gateway`,runtime:{status:`connected`,credential:i.credential}}:r===void 0?i?.kind===`gateway`?{kind:`gateway`,runtime:{status:`disconnected`}}:{kind:`gateway`,runtime:{status:`unknown`}}:{kind:`gateway`,runtime:{status:`connected`,credential:r.credential}}}const BOOT_DETECTIONS=[{id:`model-provider`,async detect({appRoot:e,env:t,info:n}){let r=modelProviderAccess({env:t,info:n});if(r.kind===`external`)return[];if(r.kind===`gateway`){if(r.runtime.status===`connected`)return[];if(r.runtime.status===`disconnected`)return[{kind:`attention`,label:await pathExists(join(e,`.vercel`,`project.json`))?`AI Gateway credentials missing`:`connect a model`,command:`/login`}]}return await pathExists(join(e,`.vercel`,`project.json`))?[{kind:`attention`,label:`AI Gateway credentials missing`,command:`/login`}]:[{kind:`attention`,label:`connect a model`,command:`/login`}]}}],LOGIN_SETUP_ISSUE={kind:`attention`,label:`not logged in`,command:`/deploy`},CLI_MISSING_SETUP_ISSUE={kind:`attention`,label:`Vercel CLI not found`,command:`/deploy`};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 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,detectSetupIssues,formatSetupIssuesLine,normalizeLocalModelEndpoint,orderedSetupIssues};
|
|
1
|
+
import{join}from"node:path";import{pathExists}from"#setup/path-exists.js";import{hasEnvValue,resolveGatewayCredential}from"#internal/resolve-model-endpoint-status.js";function normalizeLocalModelEndpoint(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;if(i.id===void 0||i.routing.kind!==`gateway`)return e;let a=i.endpoint;if(a?.kind===`gateway`&&a.connected&&a.credential===r)return e;let o={connected:!0,credential:r,kind:`gateway`};return{...e,agent:{...e.agent,model:{contextWindowTokens:i.contextWindowTokens,endpoint:o,id:i.id,providerOptions:i.providerOptions,reasoning:i.reasoning,routing:i.routing,source:i.source}}}}function modelProviderAccess(e){let t=e.info?.agent.model;if(t?.routing?.kind===`dynamic`)return{kind:`dynamic`};if(t?.routing?.kind===`external`)return{kind:`external`};if(t?.routing?.kind!==`gateway`)return{kind:`unknown`};let n=e.env.EVE_MODEL_CONNECTION,r=resolveGatewayCredential({apiKeyInEnv:(n===void 0||n===`ai-gateway-key`&&e.env.EVE_MODEL_KEY_SOURCE!==`secret`)&&hasEnvValue(e.env.AI_GATEWAY_API_KEY),oidcAvailable:(n===void 0||n===`ai-gateway-project`)&&hasEnvValue(e.env.VERCEL_OIDC_TOKEN)});if(r?.credential===`api-key`)return{kind:`gateway`,runtime:{status:`connected`,credential:`api-key`}};let i=t.endpoint;return i?.kind===`gateway`&&i.connected?{kind:`gateway`,runtime:{status:`connected`,credential:i.credential}}:r===void 0?i?.kind===`gateway`?{kind:`gateway`,runtime:{status:`disconnected`}}:{kind:`gateway`,runtime:{status:`unknown`}}:{kind:`gateway`,runtime:{status:`connected`,credential:r.credential}}}const BOOT_DETECTIONS=[{id:`model-provider`,async detect({appRoot:e,env:t,info:n}){let r=modelProviderAccess({env:t,info:n});if(r.kind===`external`||r.kind===`dynamic`)return[];if(r.kind===`gateway`){if(r.runtime.status===`connected`)return[];if(r.runtime.status===`disconnected`)return[{kind:`attention`,label:await pathExists(join(e,`.vercel`,`project.json`))?`AI Gateway credentials missing`:`connect a model`,command:`/login`}]}return await pathExists(join(e,`.vercel`,`project.json`))?[{kind:`attention`,label:`AI Gateway credentials missing`,command:`/login`}]:[{kind:`attention`,label:`connect a model`,command:`/login`}]}}],LOGIN_SETUP_ISSUE={kind:`attention`,label:`not logged in`,command:`/deploy`},CLI_MISSING_SETUP_ISSUE={kind:`attention`,label:`Vercel CLI not found`,command:`/deploy`};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 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,detectSetupIssues,formatSetupIssuesLine,normalizeLocalModelEndpoint,orderedSetupIssues};
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.js";import{detectMarkdownRendering}from"./markdown.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{copyTextToClipboard}from"./clipboard.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{interruptedError}from"./errors.js";import{FileContentCache}from"./file-content-cache.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{MessageQueue,renderMessageQueueRows}from"./message-queue.js";import{initialModelEditorState,transitionModelEditor}from"./model-editor.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{enterBadge,flowMessageRows,renderAcknowledgeQuestion,renderFlowPanel,renderModelEditorQuestion,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompleteOsc,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{TraceViewerSession}from"./traces/trace-viewer-session.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{TurnClock}from"./turn-clock.js";import{allTodoItemsSettled,readTodoToolItems,renderFinishedTodoRows,renderTodoPanelRows}from"./todo-panel.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{BACKGROUND_COLOR_QUERY,parseBackgroundColorReply}from"./terminal-background.js";import{inspectError}from"#internal/logging.js";import{eveVersionTag}from"#cli/banner.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{initialSelectState,orderedSelection,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{LiveRegion}from"#cli/ui/live-region.js";import{AltScreen}from"#cli/ui/alt-screen.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";import{readGatewayServiceTier}from"#shared/gateway-service-tier.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e){return e.interrupted?`Interrupted`:e.cancelled?`Cancelled`:e.continueSession?`Ready`:`Done`}const incompletePasteFlushMs=1e3,STATUS={processing:`Working…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h=[];#g=new Map;#_=new Set;#v=[];#y=new Set;#b=new Map;#x=0;#S=new Map;#C=new Set;#w=new Set;#T=new FileContentCache;#E=new Set;#D;#O;#k;#A;#j=0;#M;#N=!1;#P;#F=[];#I;#L=0;#R;#z;#B=``;#V=0;#H=new PromptHistory;#U=!1;#W;#G=!1;#K=!1;#q=new TurnClock;#J=EMPTY_LINE;#Y=!1;#X={kind:`idle`};#Z;#Q=STATUS.processing;#$;#ee=`eve`;#te=!1;#ne=!1;#re=!1;#ie=!1;#ae=!1;#oe=!1;#se=!1;#ce;#le=!0;#ue=0;#de=Date.now();#fe;#pe;#me;#he=!1;#ge;#_e=``;#ve=new StringDecoder(`utf8`);#ye;#be;#xe;#Se=!1;#Ce=!1;#we;#Te;#Ee;#De;#Oe;#ke;#Ae;#je=``;#Me=``;#Ne;#Pe;#Fe;#Ie=!1;#Le;#Re=0;#ze;#Be;#Ve;#He;#Ue;#We;#Ge=new MessageQueue;#
|
|
2
|
-
`);if(this.#N){t!==this.#P&&(this.#P=t,this
|
|
1
|
+
import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.js";import{detectMarkdownRendering}from"./markdown.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{copyTextToClipboard}from"./clipboard.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{interruptedError}from"./errors.js";import{FileContentCache}from"./file-content-cache.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{MessageQueue,renderMessageQueueRows}from"./message-queue.js";import{initialModelEditorState,transitionModelEditor}from"./model-editor.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{enterBadge,flowMessageRows,renderAcknowledgeQuestion,renderFlowPanel,renderModelEditorQuestion,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompleteOsc,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{TraceViewerSession}from"./traces/trace-viewer-session.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{TurnClock}from"./turn-clock.js";import{allTodoItemsSettled,readTodoToolItems,renderFinishedTodoRows,renderTodoPanelRows}from"./todo-panel.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{BACKGROUND_COLOR_QUERY,parseBackgroundColorReply}from"./terminal-background.js";import{inspectError}from"#internal/logging.js";import{eveVersionTag}from"#cli/banner.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{initialSelectState,orderedSelection,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{LiveRegion}from"#cli/ui/live-region.js";import{AltScreen}from"#cli/ui/alt-screen.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";import{readGatewayServiceTier}from"#shared/gateway-service-tier.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e){return e.interrupted?`Interrupted`:e.cancelled?`Cancelled`:e.continueSession?`Ready`:`Done`}const incompletePasteFlushMs=1e3,STATUS={processing:`Working…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h=[];#g=new Map;#_=new Set;#v=[];#y=new Set;#b=new Map;#x=0;#S=new Map;#C=new Set;#w=new Set;#T=new FileContentCache;#E=new Set;#D;#O;#k;#A;#j=0;#M;#N=!1;#P;#F=[];#I;#L=0;#R;#z;#B=``;#V=0;#H=new PromptHistory;#U=!1;#W;#G=!1;#K=!1;#q=new TurnClock;#J=EMPTY_LINE;#Y=!1;#X={kind:`idle`};#Z;#Q=STATUS.processing;#$;#ee=`eve`;#te=!1;#ne=!1;#re=!1;#ie=!1;#ae=!1;#oe=!1;#se=!1;#ce;#le=!0;#ue=0;#de=Date.now();#fe;#pe;#me;#he=!1;#ge;#_e=``;#ve=new StringDecoder(`utf8`);#ye;#be;#xe;#Se=!1;#Ce=!1;#we;#Te;#Ee;#De;#Oe;#ke;#Ae;#je=``;#Me=``;#Ne;#Pe;#Fe;#Ie=!1;#Le;#Re=0;#ze;#Be;#Ve;#He;#Ue;#We;#Ge;#Ke;#qe=new MessageQueue;#Je;#Ye;#Xe=!1;#Ze;#Qe;#$e=!1;#et;#tt;#nt;#rt;#it;setupFlow={begin:(e,t)=>this.#dt(e,t),setNavigation:e=>this.#ft(e),end:e=>this.#pt(e?.preserveDiagnostics??!0),readSelect:e=>this.#mt(e),readEditableSelect:e=>this.#gt(e),readProviderPicker:e=>this.#_t(e),readModelEditor:e=>this.#vt(e),readText:e=>this.#yt(e),readAcknowledge:e=>this.#bt(e),readChoice:e=>this.#ht(e),setStatus:e=>this.#Ot(e),renderLine:(e,t)=>this.#kt(e,t),replaceContent:e=>this.#At(e),renderOutput:e=>this.#jt(e),withInheritedStdio:e=>this.#Mt(e),withExclusiveTerminal:e=>this.#Mt(e),waitForInterrupt:e=>this.#Tt(e)};traceViewer={open:e=>this.#Pt(e)};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=new AltScreen(this.#t),this.#i=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#a=e?.renderMarkdown??detectMarkdownRendering(),this.#o=e?.tools??`auto-collapsed`,this.#s=e?.reasoning??`auto-collapsed`,this.#c=e?.subagents??`auto-collapsed`,this.#l=e?.connectionAuth??`full`,this.#u=e?.assistantResponseStats??`tokensPerSecond`,this.#Ee=e?.contextSize,this.#d=e?.captureForeignOutput??this.#t===process.stdout,this.#f=e?.diagnostics,this.#ce=e?.onExitRequest,this.#m=e?.logs??`none`,this.#p=e?.availablePromptCommands??PROMPT_COMMANDS}setStartupPhase(e){this.#O=e,e===void 0?this.#en():this.#Qt(),this.#Dn()}renderAgentHeader(e){this.#M=void 0,this.#ee=e.name,(this.#D?.info?.agent.model.routing.kind!==`dynamic`||e.info?.agent.model.routing.kind!==`dynamic`)&&(this.#Ue=void 0),this.#D=e,this.#Lt();let t=this.#Mn().join(`
|
|
2
|
+
`);if(this.#N){t!==this.#P&&(this.#P=t,this.#in({kind:`agent-header`,body:t,live:!1})),this.#Dn();return}this.#N=!0,this.#P=t,this.#n.flush(this.#Mn(),this.#Ln(this.#Kn()))}beginStartupDraft(e){this.#Lt({title:e.title}),this.#U=!0,this.#G=!0,this.#O=`starting`,this.#M={name:e.title,tip:e.tip},this.#j=Date.now();let t=lineOf(stripPromptControlCharacters(e.initialDraft??``));this.#k=t,this.#ot(t),this.#Yt(),this.#Qt(),this.#Dn();let apply=e=>{t=e,this.#k=e,this.#Zt(),this.#ot(t),this.#Dn()};this.#A=e=>{if(e.type===`escape`&&this.#tt!==void 0){this.#tt(`escape`);return}if(e.type===`ctrl-c`&&this.#tt!==void 0){this.#Nt(),this.#tt(`ctrl-c`);return}let n=applyLineEditorKey(t,e,{multiline:!0});if(n!==void 0){apply(n);return}if(e.type===`enter`&&t.text.trim().length>0){this.#qe.enqueue(t.text)&&apply(EMPTY_LINE);return}e.type===`ctrl-c`&&this.#ce?.()},this.#at()}#at(){this.#k!==void 0&&this.#A!==void 0&&(this.#Kt(),this.#ot(this.#k),this.#U=!0,this.#ge=this.#A,this.#Bt())}finishStartupDraft(){let e={draft:this.#k?.text??this.#B,queuedPrompt:this.#qe.takePrompt()};return this.#k=void 0,this.#A=void 0,this.#Vt(),this.#Xt(),this.#U=!1,this.#G=!1,e}async readPrompt(e){this.#Lt(e),this.#rn(),this.#on(),this.#U=!0,this.#G=!0,this.#X={kind:`idle`},this.#Q=``,this.#oe=this.#se,this.#se=!1;let t=this.#qe.restoreDraft()?.split(`
|
|
3
3
|
`).map(stripPromptControlCharacters).join(`
|
|
4
|
-
`),n=stripPromptControlCharacters(e?.initialDraft??this.#J.text),r=t===void 0?n:n.length===0?t:`${t}\n\n${n}`,i=lineOf(r);return this.#J=EMPTY_LINE,this.#H.begin(i.text),this.#it(i),this.#W=typeaheadFor(this.#p,i.text),this.#qt(),this.#Sn(),await new Promise((e,t)=>{this.#Z=t;let apply=e=>{i=e,this.#Yt(),this.#it(i),this.#W=typeaheadFor(this.#p,e.text,this.#W),this.#Sn()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#W=void 0,this.#Jt(),this.#Lt(),t(interruptedError())},suggestions=()=>this.#W!==void 0&&isTypeaheadOpen(this.#W)?this.#W:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ge=t=>{t.type!==`ctrl-c`&&this.#oe&&(this.#oe=!1,this.#Sn());let n=applyLineEditorKey(i,t,{multiline:!0});if(n!==void 0){apply(n);return}switch(t.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#W=moveTypeaheadSelection(e,-1),this.#Sn();break}let t=movePromptLine(i,`up`);t===void 0?recall(this.#H.previous(i.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#W=moveTypeaheadSelection(e,1),this.#Sn();break}let t=movePromptLine(i,`down`);t===void 0?recall(this.#H.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#W=dismissTypeahead(e),this.#Sn());break}case`enter`:{let t=highlighted(),n=t!==void 0&&parsePromptCommand(i.text)===null?typeaheadCompletion(t).trimEnd():i.text;if(n.trim().length===0)break;this.#W=void 0,this.#H.add(n),this.#U=!1,this.#Jt(),this.#Q=STATUS.processing,isPromptControlCommand(n)?this.#$t({kind:`command`,body:stripTerminalControls(n.trim()),live:!1}):(this.#Zt(),this.#en(n),this.#ze=n,this.#q.arm()),this.#it(EMPTY_LINE),this.#Sn(),this.#zt(),e(n);break}case`ctrl-d`:i.text.length===0?(this.#jt(),interrupt()):apply(deleteForward(i));break;case`ctrl-l`:this.#Tn();break;case`ctrl-r`:this.#Sn();break;case`ctrl-c`:if(this.#oe){this.#jt(),interrupt();break}this.#oe=!0,apply(EMPTY_LINE)}},this.#Rt()})}#it(e){this.#B=e.text,this.#V=e.cursor}takeQueuedPrompt(){let e=this.#Ge.view().steering,t=this.#Ge.takePrompt();return t!==void 0&&(this.#Xe=e?`steer`:`queue`),t}async renderStream(e,t){this.#Ft(t),this.#_.clear(),this.#U=!1,this.#X.kind!==`waiting`&&(this.#X={kind:`waiting`,startedAtMs:Date.now()}),this.#Q=this.#L>0?STATUS.connectionAuth:STATUS.processing,this.#nn(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#f?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#q.armed&&this.#q.arm(),this.#ie=!1,this.#Je=!1,this.#Ze=!1,this.#Qe=t?.submittedPrompt,this.#Ge.beginTurn(),this.#Ke=e.cancel,this.#qe=e.steer,this.#we=void 0,this.#Te=void 0,this.#De=void 0,this.#Oe=void 0,this.#ke=Date.now();let n={tools:t?.tools??this.#o,reasoning:t?.reasoning??this.#s,assistantResponseStats:t?.assistantResponseStats??this.#u};this.#Xt(),this.#Y=!0,this.#Sn();let r=new Promise(e=>{this.#xe=e});this.#ge=e=>this.#Gt(e),this.#Rt();let i={text:new Map,reasoning:new Map,tools:new Map,cancelled:!1,restoreCancelledPrompt:!0};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#ie)break;this.#un(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#rn(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#rn(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#xe=void 0,this.#ie&&e.abort?.(),this.#Ke=void 0,this.#qe=void 0,this.#zt(),this.#Qt(),this.#Y=!1,this.#X.kind===`waiting`&&(this.#X={kind:`idle`}),this.#Q=completedTurnStatus({interrupted:this.#ie,cancelled:this.#Je,continueSession:t?.continueSession===!0}),this.#_n(i),(this.#ie||i.cancelled)&&this.#gn(i),this.#ln(),this.#f?.reportStats(),this.#Sn(),t?.continueSession||this.#Lt()}}async renderIdleStream(e,t){let n={tools:t?.tools??this.#o,reasoning:t?.reasoning??this.#s,assistantResponseStats:t?.assistantResponseStats??this.#u},r={text:new Map,reasoning:new Map,tools:new Map,cancelled:!1,restoreCancelledPrompt:!1};try{for await(let t of iterateTUIStream(e.events))this.#un(t,n,r)}catch(e){let t=summarizeKnownError(e);t===null?this.#rn(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#rn(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#_n(r),r.cancelled&&this.#gn(r),this.#ln(),this.#f?.reportStats(),this.#Sn()}}async readToolApproval(e,t){return this.#Ft(t),this.#Qt(),this.#U=!1,this.#X={kind:`idle`},this.#Q=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#ie=!1,this.#Sn(),await new Promise((t,n)=>{this.#Z=n,this.#ge=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Zt(),this.#Q=STATUS.processing,this.#zt(),this.#Sn(),t({approved:!0})):n===`n`&&(this.#Zt(),this.#Q=STATUS.processing,this.#ot(e.toolCallId),this.#zt(),this.#Sn(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#Sn();break;case`ctrl-c`:this.#ie=!0,this.#Lt(),n(interruptedError())}},this.#Rt()})}async readInputQuestion(e,t){this.#Ft(t),this.#Qt(),this.#U=!1,this.#G=!1,this.#X={kind:`idle`},this.#ie=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`overlay`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,overlayPanel=t=>renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#le},this.#i,t),renderTextSection=()=>{this.#an({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#qt():(this.#Jt(),this.#Yt())};s===`overlay`?(s=`overlay`,this.#U=!1,this.#sn(o),this.#Be=overlayPanel,this.#Q=``,syncFreeformCaret(),this.#Sn()):(s=`text`,this.#Be=void 0,renderTextSection(),this.#U=!0,this.#it(l),this.#Q=``,this.#qt(),this.#Sn());let finalize=t=>{this.#Be=void 0,this.#an({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#U=!1,this.#Zt(),this.#Q=STATUS.processing,this.#Jt(),this.#zt(),this.#Sn();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Be=void 0,this.#an({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#U=!1,this.#Q=``,this.#Jt(),this.#zt(),this.#Sn(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#Sn())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#Z=r,u=t,this.#ge=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#Yt(),s===`text`&&this.#it(l),this.#Sn();return}this.#ie=!0,this.#Be=void 0,this.#Jt(),this.#Lt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#Sn();return}if(s===`overlay`){let r=setupSelectionIntent(t,{textNavigation:!isOnFreeformRow()});if(r?.kind===`move`){moveCursor(r.direction===`up`?-1:1);return}switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#Yt(),this.#Sn();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#Yt(),this.#Sn());break}if(t.type===`text`&&/^[1-9]$/u.test(t.value)){let e=Number(t.value)-1;e<n.length?selectOptionAt(e):e===n.length&&i&&(c=e,syncFreeformCaret(),this.#Sn())}}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#Yt(),this.#it(l),this.#Sn();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Yt(),this.#it(l),this.#Sn());break}case`enter`:{let t=resolveQuestionText(l.text,e);if(t===void 0)break;u(finalize(t));break}case`escape`:if(l.text.length>0){l=EMPTY_LINE,this.#Yt(),this.#it(l),this.#Sn();break}dismiss()}},this.#Rt()})}upsertSubagentStep(e){if(this.#f?.recordSubagentDispatch(e.callId),this.#c===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(t.length!==0||n.length!==0){if(this.#in(e.callId,e.subagentName),this.#c===`collapsed`){this.#Sn();return}this.#on({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#c!==`full`,live:!e.finalized}),this.#Sn()}}upsertSubagentTool(e){if(this.#f?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#f?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#c===`hidden`)return;if(this.#in(e.callId,e.subagentName),this.#c===`collapsed`){this.#Sn();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#mn({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#c===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#on(r),this.#at(e.callId),this.#Sn()}#at(e){applyCohortLiveness(this.#h.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#sn(subagentToolSectionId(e.callId,e.childCallId)),this.#Sn()}subagents={begin:e=>this.beginSubagent(e),background:e=>this.backgroundSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#c===`hidden`)return;this.#in(e.callId,e.name);let t=this.#g.get(subagentHeaderId(e.callId));t!==void 0&&(t.status===`done`&&delete t.status,t.live=!0),this.#w.delete(e.callId),this.#Sn()}backgroundSubagent(e){let t=this.#g.get(subagentHeaderId(e.callId));if(t===void 0||this.#_.has(subagentHeaderId(e.callId)))return;t.status=`running`,t.live=!0,t.updateSeq=++this.#x;let n=this.#C.has(e.callId);this.#C.add(e.callId),n||this.#cn(e.callId),this.#Sn()}completeSubagent(e){let t=this.#g.get(subagentHeaderId(e.callId));if(t!==void 0){if(t.status=`done`,e.authoritative){this.#C.delete(e.callId),this.#w.delete(e.callId);for(let t of this.#h)t.subagentCallId===e.callId&&(t.live=!1)}else{this.#w.add(e.callId);for(let t of this.#h)t.subagentCallId===e.callId&&(t.live=!0)}this.#Sn()}}markChildToolCallId(e){this.#y.add(e);let t=this.#b.get(e);t!==void 0&&(this.#sn(t),this.#b.delete(e),this.#Sn())}#ot(e){let t=this.#g.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#l===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#an({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#Sn()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#L)return;let n=this.#L>0;this.#L=t,t>0?(this.#Q=STATUS.connectionAuth,this.#Sn()):n&&(this.#Q=STATUS.processing,this.#Sn())}setVercelStatus(e){this.#R=e,this.#Sn()}setRemoteConnectionStatus(e){this.#z=e,this.#Sn()}reset(){this.#h=[],this.#g.clear(),this.#_.clear(),this.#I=void 0,this.#F.length=0,this.#v.length=0,this.#N=!1,this.#P=void 0,this.#st(),this.#K=!1,this.#ze=void 0,this.#Pe=void 0,this.#L=0,this.#we=void 0,this.#Te=void 0,this.#De=void 0,this.#Oe=void 0,this.#ke=void 0,this.#te&&(this.#n.clearAll(),this.#Sn())}renderSessionBoundary(){this.#tn(),this.#st();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#$t({kind:`session-boundary`,body:n,live:!1}),this.#Sn()}#st(){this.#y.clear(),this.#b.clear(),this.#E.clear(),this.#C.clear(),this.#w.clear(),this.#S.clear(),this.#Ue=void 0,this.#We=void 0,this.#Ge.reset(),this.#Xe=void 0,this.#T.clear(),this.#q.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ft(),this.#$t({kind:`notice`,body:t,live:!1}),this.#Sn())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#f?.append({source:`sandbox`,detail:t}),this.#Ft(),this.#$t({kind:`sandbox`,body:t,live:!1}),this.#Sn())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#ct();return}this.#Ft(),this.#He=t,this.#Sn()}clearSetupWarning(){this.#ct()}#ct(){this.#He!==void 0&&(this.#He=void 0,this.#Sn())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#Ft();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#$t(r),this.#Sn()}renderCommandResult(e,t){let n=stripAnsi(e);n.trim().length!==0&&(this.#Ft(),this.#$t({kind:`result`,body:n,live:!1,status:t===`success`?`done`:void 0}),this.#Sn())}#lt(e,t=`spinner`){this.#Ft(),this.#k===void 0&&(this.#U=!1),this.#X={kind:`idle`},this.#Q=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ve={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Xt(),this.#Sn()}#ut(e){this.#Ve!==void 0&&(this.#Ve.navigation=e,this.#Sn())}#dt(e){this.#$e=void 0,this.#Tt();let t=this.#Ve;if(t!==void 0){if(this.#Ve=void 0,this.#k===void 0?this.#Qt():this.#rt(),e){let e=[];for(let n of t.lines){if(n.evidence===!0){e.push(n.text);continue}(n.tone===`warning`||n.tone===`error`)&&(e.length>0&&this.#$t({kind:`flow`,title:`info`,body:e.join(`
|
|
5
|
-
`),live:!1}),this
|
|
6
|
-
`,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#_t(e){let t=this.#yt(e.message),n=lineOf(``),r;return t.question=t=>{let i={message:``,editor:n,mask:e.mask===!0};return e.placeholder===void 0?e.defaultValue!==void 0&&(i.placeholder=e.defaultValue):i.placeholder=e.placeholder,e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#i,t,this.#le)},this.#qt(),this.#Sn(),await this.#St((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Yt(),this.#Sn()},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.#Sn();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#Sn();return}i(t);return}default:return}},()=>this.#Jt()).promise}async#vt(e){let t=this.#yt(e.message);return t.question=t=>renderAcknowledgeQuestion({message:``,lines:e.lines},this.#i,t),this.#Sn(),await this.#St((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#Sn();return;default:return}}).promise}#yt(e){this.#Ft(),this.#U=!1,this.#X={kind:`idle`},this.#Q=``;let t=this.#bt();return t.questionTitle=stripTerminalControls(e),t.status!==void 0&&(t.status=void 0,t.summary=void 0,t.preview=void 0),t}#bt(){return this.#Ve===void 0&&(this.#Ve={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Ve}#xt(){this.#Ve?.implicit===!0?this.#Ve=void 0:this.#Ve!==void 0&&(this.#Ve.question=void 0,this.#Ve.questionTitle=void 0,this.#Ve.hideLinesWhileQuestion=!1),this.#ge=void 0,this.#zt(),this.#k===void 0?this.#Ve!==void 0&&this.#wt():this.#rt(),this.#Ve===void 0&&this.#Sn()}#St(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#xt(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#xt(),i(e))};return this.#Wt(),this.#ge=t=>{t.type===`ctrl-c`&&this.#jt(),e(t,settle,reject)},this.#Rt(),{promise:a,settle}}#Ct(e){let t,n=new Promise(e=>{t=e});return this.#$e=t,this.#wt(e?.interruptible??!0),{promise:n,dispose:()=>{this.#$e===t&&(this.#$e=void 0,this.#Tt())}}}#wt(e=!0){if(this.#k!==void 0){this.#rt();return}if(this.#$e===void 0)return;let consumer=t=>{if(e&&(t.type===`ctrl-c`||t.type===`escape`)){t.type===`ctrl-c`&&this.#jt();let e=this.#$e;this.#$e=void 0,this.#Tt(),e?.(t.type===`ctrl-c`?`ctrl-c`:`escape`);return}t.type===`ctrl-r`&&this.#Sn()};this.#et=consumer,this.#Wt(),this.#ge=consumer,this.#Rt()}#Tt(){this.#et!==void 0&&(this.#ge===this.#et&&this.#zt(),this.#et=void 0)}#Et(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e),startedAtMs:Date.now()}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis),startedAtMs:Date.now()};if(this.#Ve!==void 0){this.#Ve.status=t,t===void 0&&(this.#Ve.preview=void 0),this.#Sn();return}if(!(this.#U||this.#Y)){if(t===void 0){this.#X={kind:`idle`},this.#$=void 0,this.#Qt(),this.#Sn();return}this.#Ft(),this.#Zt(),this.#$=t.text,this.#Sn()}}#Dt(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Ve;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.#Sn();return}this.#Ft(),this.#$t({kind:`flow`,title:t,body:n,live:!1}),this.#Sn()}#Ot(e){let t=this.#Ve;t!==void 0&&(t.lines=[],t.outputBuffer=[],t.preview=void 0,t.status=void 0,t.summary=e===void 0?void 0:{headline:stripTerminalControls(e.headline),facts:e.facts.map(e=>({label:stripTerminalControls(e.label),value:stripTerminalControls(e.value)}))},this.#Sn())}#kt(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Ve;if(n===void 0){this.#Dt(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#Sn()}async#At(e){this.#_e=``,this.#Wt(),this.#$e=void 0,this.#Tt(),this.#zt(),this.#Qt(),this.#n.clear(),this.#Wn(),this.#r.enter({cursor:`visible`,mouse:!1}),this.#e.isTTY&&this.#e.setRawMode?.(!1),this.#e.pause();try{return await e()}finally{this.#r.exit(),this.#e.isTTY&&this.#e.setRawMode?.(!0),this.#e.resume(),this.#_e=``,this.#Wt(),this.#n.hideCursor(),this.#Un(),this.#Ve!==void 0&&(this.#Xt(),this.#wt()),this.#n.reset(),this.#Sn()}}setSessionId(e){this.#Ye=e}shutdown(){if(this.#Lt(),this.#ne&&!this.#re){this.#re=!0;let e=this.#Ye===void 0?``:` ${this.#i.glyph.dot} session ${this.#Ye}`;this.#t.write(`${this.#i.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}suspendPromptForInput(){this.#J={cursor:this.#V,text:this.#B},this.#Lt()}requestInterrupt(){this.#ie=!0,this.#Ve!==void 0&&this.#ge?.({type:`ctrl-c`}),this.#xe?.(),this.#Lt()}exitRequested(){return this.#ae}#jt(){this.#ae=!0,this.#ce?.()}async#Mt(e){if(this.#tt!==void 0||!this.#te)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#Vn(),height:this.#Hn()}),paint:e=>this.#r.paint(e,this.#Hn()),tracingDisabled:process.env.EVE_TRACES===`off`,copyText:e=>copyTextToClipboard(e,e=>this.#r.writeRaw(e)),terminalBackground:this.#nt});this.#tt=t,this.#r.enter(),this.#i.color&&this.#r.writeRaw(BACKGROUND_COLOR_QUERY),await new Promise(e=>{this.#Pt=e,this.#ge=e=>{t.handleKey(e)===`close`&&this.#Nt()},this.#Rt(),t.start()})}#Nt(){let e=this.#tt;if(e===void 0)return;this.#tt=void 0,e.dispose(),this.#zt(),this.#r.exit(),this.#n.hideCursor(),this.#Sn(),this.#n.showCursor();let t=this.#Pt;this.#Pt=void 0,t?.()}#Pt;#Ft(e){this.#ee=e?.title??this.#ee,e?.contextSize!==void 0&&(this.#Ee=e.contextSize),!this.#te&&(this.#te=!0,this.#ne=!0,this.#n.reset(),this.#n.hideCursor(),this.#Un(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#be=()=>this.#Sn(),this.#t.on(`resize`,this.#be),process.on(`exit`,this.#It))}#It=()=>{this.#te&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#Lt(){this.#Nt();let e=this.#Z;if(this.#Z=void 0,e?.(interruptedError()),this.#zt(),this.#Jt(),this.#Qt(),this.#me!==void 0&&(clearTimeout(this.#me),this.#me=void 0),this.#he=!1,this.#Qn(),this.#te){this.#er();for(let e of this.#h)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#Sn(),this.#n.clear(),this.#n.showCursor(),this.#Wn(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#be&&=(this.#t.off(`resize`,this.#be),void 0),process.off(`exit`,this.#It),this.#te=!1}}#Rt(){this.#e.off(`data`,this.#Bt),this.#e.on(`data`,this.#Bt),this.#_e.length>0&&queueMicrotask(()=>{this.#ge!==void 0&&this.#_e.length>0&&(this.#Ht(),this.#Vt())})}#zt(){this.#e.off(`data`,this.#Bt),this.#Wt(),this.#ge=void 0}#Bt=e=>{this.#Wt(),this.#_e+=this.#ve.write(e),this.#Ht(),this.#Vt()};#Vt(){if(this.#_e===`\x1B`){this.#ye=setTimeout(()=>{this.#_e===`\x1B`&&(this.#_e=``,this.#ge?.({type:`escape`}))},30),this.#ye.unref?.();return}if(isIncompletePaste(this.#_e)){let e=this.#_e;this.#ye=setTimeout(()=>{if(this.#_e!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#_e=``,t.length>0&&this.#ge?.({type:`text`,value:t,framing:`bracketed-paste`})},incompletePasteFlushMs),this.#ye.unref?.();return}if(isIncompleteOsc(this.#_e)){let e=this.#_e;this.#ye=setTimeout(()=>{this.#_e===e&&(this.#_e=``)},incompletePasteFlushMs),this.#ye.unref?.()}}#Ht(){for(;this.#_e.length>0;){let e=nextKey(this.#_e);if(e.incomplete)return;if(this.#_e=this.#_e.slice(e.consumed),e.key!==void 0&&e.key.type!==`ignore`){if(e.key.type===`osc`){this.#Ut(e.key.value);continue}this.#ge?.(e.key)}}}#Ut(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#nt=t,this.#tt?.setTerminalBackground(t))}#Wt(){this.#ye&&=(clearTimeout(this.#ye),void 0)}#Gt(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#Sn();break;case`enter`:{let e=this.#J.text;if(e.trim().length===0)break;if(parsePromptCommand(e)?.type===`cancel`&&this.#Ke!==void 0){this.#J=EMPTY_LINE,this.#Ge.requestCancellation(),this.#Ze=!0,this.renderCommandInvocation(e.trim()),this.renderCommandResult(`Turn cancellation requested.`),this.#Ke(),this.#Sn();break}let t=this.#qe;t!==void 0&&parsePromptCommand(e)===null?(this.#J=EMPTY_LINE,this.#Kt(e,t)):this.#Ge.enqueue(e)&&(this.#J=EMPTY_LINE),this.#Sn();break}case`ctrl-c`:case`escape`:if(e.type===`ctrl-c`&&this.#Ge.view().cancelling){this.#ie=!0,this.#se=!0,this.#X={kind:`idle`},this.#Q=`Interrupted`,this.#xe?.(),this.#Sn();break}if(this.#Ge.idle&&this.#Ke===void 0)break;if(this.#Ge.handleEscape()===`steer`){let e=this.#qe;if(e!==void 0){let t=this.#Ge.takeSteering();this.#Kt(t,e)}}else this.#Ze=!0,this.#Ke?.();this.#Sn();break;default:{let t=applyLineEditorKey(this.#J,e,{multiline:!0});t!==void 0&&(this.#J=t,this.#Sn());break}}}#Kt(e,t){this.#Xe=`steer`,this.#nn(e),t(e).catch(t=>{this.#Ge.restoreSteering(e),this.#rn(`Steering failed`,toErrorMessage(t)),this.#Sn()})}#qt(){this.#Jt(),this.#Yt(),this.#fe=setInterval(()=>{this.#le=!this.#le,this.#Sn()},500),this.#fe.unref?.()}#Jt(){this.#fe&&=(clearInterval(this.#fe),void 0),this.#le=!0}#Yt(){this.#le=!0}#Xt(){this.#Qt(),this.#pe=setInterval(()=>{this.#ue+=1,this.#Sn()},90),this.#pe.unref?.()}#Zt(){let e=Date.now();this.#de=e,this.#X={kind:`waiting`,startedAtMs:e},this.#Xt()}#Qt(){this.#pe&&=(clearInterval(this.#pe),void 0)}#$t(e){e.id!==this.#Pe?.id&&this.#er(),e.updateSeq=++this.#x;let t=e.subagentCallId!==void 0&&this.#C.has(e.subagentCallId)?-1:this.#h.findIndex(e=>e.subagentCallId!==void 0&&this.#C.has(e.subagentCallId));t<0?this.#h.push(e):this.#h.splice(t,0,e),e.id&&this.#g.set(e.id,e)}#en(e){this.#K=!0,this.#$t({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#Sn()}#tn(){let e=this.#q.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#Pn(e.elapsedMs)}`,n=this.#Te??0;if(this.#Ee!==void 0&&this.#Ee>0&&n>0){let e=Math.round(n/this.#Ee*100);t+=` ${this.#i.glyph.dot} ${e}% context`}this.#$t({kind:`turn-stats`,body:t,live:!1})}#nn(e){if(e==null)return;let t=this.#Xe;if(this.#Xe=void 0,this.#ze===e){this.#ze=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#$t(n)}#rn(e,t,n={}){let r=stripTerminalControls(e),i=stripTerminalControls(t),a=n.detail===void 0?void 0:stripTerminalControls(n.detail),o=n.hint===void 0?void 0:stripTerminalControls(n.hint),s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#f?.append(o===void 0?s:{...s,hint:o});let c={kind:`error`,title:r,body:i,live:!1};o!==void 0&&(c.hint=o),a!==void 0&&(c.detail=this.#f===void 0?a:`details: ${this.#f.displayPath}`),this.#$t(c),this.#Sn()}#in(e,t){if(this.#E.has(e))return;this.#E.add(e);let n=stripTerminalControls(t),r=this.#S.get(n)??[];if(r.push(e),this.#S.set(n,r),r.length===2){let e=this.#g.get(subagentHeaderId(r[0]));e!==void 0&&(e.subtitle=`#1`)}let i={id:subagentHeaderId(e),kind:`subagent`,subagentCallId:e,title:n,live:!0};r.length>1&&(i.subtitle=`#${r.length}`),this.#$t(i)}#an(e){if(e.id&&this.#_.has(e.id))return;let t=e.id?this.#g.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#x;return}this.#$t(e)}#on(e){if(e.id&&this.#_.has(e.id))return;let t=e.id?this.#g.get(e.id):void 0;if(t!==void 0){Object.assign(t,e),t.updateSeq=++this.#x;return}let n=e.subagentCallId;if(n===void 0){this.#$t(e);return}e.id!==this.#Pe?.id&&this.#er(),e.updateSeq=++this.#x;let r=-1;for(let e=0;e<this.#h.length;e+=1)this.#h[e]?.subagentCallId===n&&(r=e);this.#h.splice(r<0?this.#h.length:r+1,0,e),e.id!==void 0&&this.#g.set(e.id,e)}#sn(e){this.#h=this.#h.filter(t=>t.id!==e),this.#g.delete(e)}#cn(e){let t=this.#h.filter(t=>t.subagentCallId===e);t.length!==0&&(this.#h=this.#h.filter(t=>t.subagentCallId!==e),this.#h.push(...t))}#ln(){for(let e of this.#h)e.subagentCallId!==void 0&&this.#w.has(e.subagentCallId)||e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#un(e,t,n){switch(e.type){case`step-finish`:this.#f?.recordStepUsage(e.usage),e.usage!==void 0&&this.#q.addUsage(e.usage),this.#_n(n),this.#xn(e.usage),this.#Sn();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#dn(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=typeof e.text==`string`?stripTerminalControls(e.text):t;n.text.set(e.id,r),this.#dn(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);if(n.reasoning.set(e.id,r),t.reasoning===`full`){this.#fn(e.id,r,!0,t);break}break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;if(t.reasoning===`full`){this.#fn(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#pn({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#f?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#pn({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.#pn({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#bn(e.toolCallId,n);if(r===void 0)break;this.#pn({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#bn(e.toolCallId,n);if(this.#f?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#pn({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#bn(e.toolCallId,n);if(r===void 0)break;this.#pn({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#rn(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:if(n.cancelled=!0,!n.restoreCancelledPrompt)break;this.#Je=!0,!this.#Ze&&this.#Qe!==void 0&&this.#J.text.length===0&&(this.#J=lineOf(this.#Qe),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#xn(e.usage),this.#Sn()}}#dn(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#an({id:e,kind:`assistant`,body:r,live:n}),this.#Sn())}#fn(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#an({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#Sn())}#pn(e,t,n){if(n.tools.set(e.toolCallId,e),this.#y.has(e.toolCallId)||this.#vn(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#b.set(e.toolCallId,r);let i=this.#mn(e);this.#an(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#yn(n),this.#Sn()}#mn(e){e.output!==void 0&&this.#T.observeRead(e.output);let t={};this.#hn(e.toolName)&&(t.isSubagent=!0);let n=readWriteFileInput(e.toolName,e.input);if(n===void 0)return t.isSubagent===!0?t:void 0;let r=this.#T.observeWrite({path:n.path,content:n.content,callId:e.toolCallId});r!==void 0&&(t.previousContent=r);let i=writeExistedFlag(e.output);return i!==void 0&&(t.existed=i),t}#hn(e){let t=this.#D?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#gn(e){for(let t of e.tools.keys()){if(this.#y.has(t))continue;let e=this.#b.get(t)??toolSectionId(t),n=this.#g.get(e);n?.kind===`tool`&&n.status===`running`&&(n.status=`error`,n.result=`interrupted`,n.live=!1)}}#_n(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#b.get(t)??toolSectionId(t);this.#sn(r),this.#b.delete(t)}}#vn(e){let t=readTodoToolItems(e.toolName,e.input);if(t===void 0)return!1;if(t.length>0&&allTodoItemsSettled(t)){let e=JSON.stringify(t);this.#We!==e&&(this.#We=e,this.#$t({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#Vn(),this.#i).join(`
|
|
7
|
-
`),live:!1})),this.#
|
|
8
|
-
`),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#je=i:this.#Me=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#f?.append({source:e,detail:a}),e===`stdout`?this.#
|
|
9
|
-
`);t=[],e.trim().length!==0&&this
|
|
10
|
-
`)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this
|
|
11
|
-
`),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#f===void 0){this
|
|
12
|
-
`);r.trim().length>0&&this
|
|
13
|
-
`);this.#
|
|
4
|
+
`),n=stripPromptControlCharacters(e?.initialDraft??this.#J.text),r=t===void 0?n:n.length===0?t:`${t}\n\n${n}`,i=lineOf(r);return this.#J=EMPTY_LINE,this.#H.begin(i.text),this.#ot(i),this.#W=typeaheadFor(this.#p,i.text),this.#Yt(),this.#Dn(),await new Promise((e,t)=>{this.#Z=t;let apply=e=>{i=e,this.#Zt(),this.#ot(i),this.#W=typeaheadFor(this.#p,e.text,this.#W),this.#Dn()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#W=void 0,this.#Xt(),this.#zt(),t(interruptedError())},suggestions=()=>this.#W!==void 0&&isTypeaheadOpen(this.#W)?this.#W:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ge=t=>{t.type!==`ctrl-c`&&this.#oe&&(this.#oe=!1,this.#Dn());let n=applyLineEditorKey(i,t,{multiline:!0});if(n!==void 0){apply(n);return}switch(t.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#W=moveTypeaheadSelection(e,-1),this.#Dn();break}let t=movePromptLine(i,`up`);t===void 0?recall(this.#H.previous(i.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#W=moveTypeaheadSelection(e,1),this.#Dn();break}let t=movePromptLine(i,`down`);t===void 0?recall(this.#H.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#W=dismissTypeahead(e),this.#Dn());break}case`enter`:{let t=highlighted(),n=t!==void 0&&parsePromptCommand(i.text)===null?typeaheadCompletion(t).trimEnd():i.text;if(n.trim().length===0)break;this.#W=void 0,this.#H.add(n),this.#U=!1,this.#Xt(),this.#Q=STATUS.processing,isPromptControlCommand(n)?this.#in({kind:`command`,body:stripTerminalControls(n.trim()),live:!1}):(this.#$t(),this.#an(n),this.#ze=n,this.#q.arm()),this.#ot(EMPTY_LINE),this.#Dn(),this.#Vt(),e(n);break}case`ctrl-d`:i.text.length===0?(this.#Nt(),interrupt()):apply(deleteForward(i));break;case`ctrl-l`:this.#An();break;case`ctrl-r`:this.#Dn();break;case`ctrl-c`:if(this.#oe){this.#Nt(),interrupt();break}this.#oe=!0,apply(EMPTY_LINE)}},this.#Bt()})}#ot(e){this.#B=e.text,this.#V=e.cursor}takeQueuedPrompt(){let e=this.#qe.view().steering,t=this.#qe.takePrompt();return t!==void 0&&(this.#Qe=e?`steer`:`queue`),t}async renderStream(e,t){this.#Lt(t),this.#_.clear(),this.#U=!1,this.#X.kind!==`waiting`&&(this.#X={kind:`waiting`,startedAtMs:Date.now()}),this.#Q=this.#L>0?STATUS.connectionAuth:STATUS.processing,this.#sn(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#f?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#q.armed&&this.#q.arm(),this.#ie=!1,this.#Xe=!1,this.#$e=!1,this.#et=t?.submittedPrompt,this.#qe.beginTurn(),this.#Je=e.cancel,this.#Ye=e.steer,this.#we=void 0,this.#Te=void 0,this.#De=void 0,this.#Oe=void 0,this.#ke=Date.now();let n={tools:t?.tools??this.#o,reasoning:t?.reasoning??this.#s,assistantResponseStats:t?.assistantResponseStats??this.#u};this.#Qt(),this.#Y=!0,this.#Dn();let r=new Promise(e=>{this.#xe=e});this.#ge=e=>this.#qt(e),this.#Bt();let i={text:new Map,reasoning:new Map,tools:new Map,cancelled:!1,restoreCancelledPrompt:!0};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#ie)break;this.#hn(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#cn(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#cn(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#xe=void 0,this.#ie&&e.abort?.(),this.#Je=void 0,this.#Ye=void 0,this.#Vt(),this.#Y=!1,this.#X.kind===`waiting`&&(this.#X={kind:`idle`}),this.#rn(),this.#Q=completedTurnStatus({interrupted:this.#ie,cancelled:this.#Xe,continueSession:t?.continueSession===!0}),this.#Sn(i),(this.#ie||i.cancelled)&&this.#xn(i),this.#mn(),this.#rn(),this.#f?.reportStats(),this.#Dn(),t?.continueSession||this.#zt()}}async renderIdleStream(e,t){let n={tools:t?.tools??this.#o,reasoning:t?.reasoning??this.#s,assistantResponseStats:t?.assistantResponseStats??this.#u},r={text:new Map,reasoning:new Map,tools:new Map,cancelled:!1,restoreCancelledPrompt:!1};try{for await(let t of iterateTUIStream(e.events))this.#hn(t,n,r)}catch(e){let t=summarizeKnownError(e);t===null?this.#cn(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#cn(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#Sn(r),r.cancelled&&this.#xn(r),this.#mn(),this.#rn(),this.#f?.reportStats(),this.#Dn()}}async readToolApproval(e,t){return this.#Lt(t),this.#en(),this.#U=!1,this.#X={kind:`idle`},this.#Q=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#ie=!1,this.#Dn(),await new Promise((t,n)=>{this.#Z=n,this.#ge=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#$t(),this.#Q=STATUS.processing,this.#Vt(),this.#Dn(),t({approved:!0})):n===`n`&&(this.#$t(),this.#Q=STATUS.processing,this.#ct(e.toolCallId),this.#Vt(),this.#Dn(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#Dn();break;case`ctrl-c`:this.#ie=!0,this.#zt(),n(interruptedError())}},this.#Bt()})}async readInputQuestion(e,t){this.#Lt(t),this.#en(),this.#U=!1,this.#G=!1,this.#X={kind:`idle`},this.#ie=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`overlay`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,overlayPanel=t=>renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#le},this.#i,t),renderTextSection=()=>{this.#un({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#Yt():(this.#Xt(),this.#Zt())};s===`overlay`?(s=`overlay`,this.#U=!1,this.#fn(o),this.#Be=overlayPanel,this.#Q=``,syncFreeformCaret(),this.#Dn()):(s=`text`,this.#Be=void 0,renderTextSection(),this.#U=!0,this.#ot(l),this.#Q=``,this.#Yt(),this.#Dn());let finalize=t=>{this.#Be=void 0,this.#un({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#U=!1,this.#$t(),this.#Q=STATUS.processing,this.#Xt(),this.#Vt(),this.#Dn();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Be=void 0,this.#un({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#U=!1,this.#Q=``,this.#Xt(),this.#Vt(),this.#Dn(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#Dn())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#Z=r,u=t,this.#ge=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#Zt(),s===`text`&&this.#ot(l),this.#Dn();return}this.#ie=!0,this.#Be=void 0,this.#Xt(),this.#zt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#Dn();return}if(s===`overlay`){let r=setupSelectionIntent(t,{textNavigation:!isOnFreeformRow()});if(r?.kind===`move`){moveCursor(r.direction===`up`?-1:1);return}switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#Zt(),this.#Dn();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#Zt(),this.#Dn());break}if(t.type===`text`&&/^[1-9]$/u.test(t.value)){let e=Number(t.value)-1;e<n.length?selectOptionAt(e):e===n.length&&i&&(c=e,syncFreeformCaret(),this.#Dn())}}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#Zt(),this.#ot(l),this.#Dn();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Zt(),this.#ot(l),this.#Dn());break}case`enter`:{let t=resolveQuestionText(l.text,e);if(t===void 0)break;u(finalize(t));break}case`escape`:if(l.text.length>0){l=EMPTY_LINE,this.#Zt(),this.#ot(l),this.#Dn();break}dismiss()}},this.#Bt()})}upsertSubagentStep(e){if(this.#f?.recordSubagentDispatch(e.callId),this.#c===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(t.length!==0||n.length!==0){if(this.#ln(e.callId,e.subagentName),this.#c===`collapsed`){this.#Dn();return}this.#dn({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#c!==`full`,live:!e.finalized}),this.#Dn()}}upsertSubagentTool(e){if(this.#f?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#f?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#c===`hidden`)return;if(this.#ln(e.callId,e.subagentName),this.#c===`collapsed`){this.#Dn();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#yn({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#c===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#dn(r),this.#st(e.callId),this.#Dn()}#st(e){applyCohortLiveness(this.#h.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#fn(subagentToolSectionId(e.callId,e.childCallId)),this.#Dn()}subagents={begin:e=>this.beginSubagent(e),background:e=>this.backgroundSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#c===`hidden`)return;this.#ln(e.callId,e.name);let t=this.#g.get(subagentHeaderId(e.callId));t!==void 0&&(t.status===`done`&&delete t.status,t.live=!0),this.#w.delete(e.callId),this.#Dn()}backgroundSubagent(e){let t=this.#g.get(subagentHeaderId(e.callId));if(t===void 0||this.#_.has(subagentHeaderId(e.callId)))return;t.status=`running`,t.live=!0,t.updateSeq=++this.#x;let n=this.#C.has(e.callId);this.#C.add(e.callId),n||this.#pn(e.callId),this.#rn(),this.#Dn()}completeSubagent(e){let t=this.#g.get(subagentHeaderId(e.callId));if(t!==void 0){if(t.status=`done`,e.authoritative){this.#C.delete(e.callId),this.#w.delete(e.callId);for(let t of this.#h)t.subagentCallId===e.callId&&(t.live=!1)}else{this.#w.add(e.callId);for(let t of this.#h)t.subagentCallId===e.callId&&(t.live=!0)}this.#rn(),this.#Dn()}}markChildToolCallId(e){this.#y.add(e);let t=this.#b.get(e);t!==void 0&&(this.#fn(t),this.#b.delete(e),this.#Dn())}#ct(e){let t=this.#g.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#l===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#un({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#Dn()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#L)return;let n=this.#L>0;this.#L=t,t>0?(this.#Q=STATUS.connectionAuth,this.#Dn()):n&&(this.#Q=STATUS.processing,this.#Dn())}setVercelStatus(e){this.#R=e,this.#Dn()}setRemoteConnectionStatus(e){this.#z=e,this.#Dn()}reset(){this.#h=[],this.#g.clear(),this.#_.clear(),this.#I=void 0,this.#F.length=0,this.#v.length=0,this.#N=!1,this.#P=void 0,this.#lt(),this.#K=!1,this.#ze=void 0,this.#Pe=void 0,this.#L=0,this.#we=void 0,this.#Te=void 0,this.#De=void 0,this.#Oe=void 0,this.#ke=void 0,this.#te&&(this.#n.clearAll(),this.#Dn())}renderSessionBoundary(){this.#on(),this.#lt();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#in({kind:`session-boundary`,body:n,live:!1}),this.#Dn()}#lt(){this.#Ue=void 0,this.#We=void 0,this.#y.clear(),this.#b.clear(),this.#E.clear(),this.#C.clear(),this.#w.clear(),this.#S.clear(),this.#Ge=void 0,this.#Ke=void 0,this.#qe.reset(),this.#Qe=void 0,this.#T.clear(),this.#q.reset(),this.#rn()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Lt(),this.#in({kind:`notice`,body:t,live:!1}),this.#Dn())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#f?.append({source:`sandbox`,detail:t}),this.#Lt(),this.#in({kind:`sandbox`,body:t,live:!1}),this.#Dn())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#ut();return}this.#Lt(),this.#He=t,this.#Dn()}clearSetupWarning(){this.#ut()}#ut(){this.#He!==void 0&&(this.#He=void 0,this.#Dn())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#Lt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#in(r),this.#Dn()}renderCommandResult(e,t){let n=stripAnsi(e);n.trim().length!==0&&(this.#Lt(),this.#in({kind:`result`,body:n,live:!1,status:t===`success`?`done`:void 0}),this.#Dn())}#dt(e,t=`spinner`){this.#Lt(),this.#k===void 0&&(this.#U=!1),this.#X={kind:`idle`},this.#Q=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ve={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Qt(),this.#Dn()}#ft(e){this.#Ve!==void 0&&(this.#Ve.navigation=e,this.#Dn())}#pt(e){this.#tt=void 0,this.#Dt();let t=this.#Ve;if(t!==void 0){if(this.#Ve=void 0,this.#k===void 0?this.#en():this.#at(),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.#in({kind:`flow`,title:`info`,body:e.join(`
|
|
5
|
+
`),live:!1}),this.#in({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#Dn()}}async#mt(e){let t=this.#xt(e.message),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a=e.navigation?.kind===`planner`,o={options:i,searchAction:r,submitRow:n&&!a};`initialValue`in e&&e.initialValue!==void 0&&(o.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(o.initialValues=e.initialValues);let s=initialSelectState(o),c,l=!1,u=0,isCurrentSearch=e=>e===u,clearSearch=()=>{u+=1,l=!1,s=reduceSelect(s,{type:`clear`},{options:i,searchAction:r,submitRow:n&&!a}),this.#Dn()},loadSearch=async(e,t)=>{l=!0,c=void 0;let o=++u;this.#Dn();try{let c=await t(e);if(!isCurrentSearch(o))return;let l=s.filter;i=c,s={...initialSelectState({options:c,searchAction:r,submitRow:n&&!a}),filter:l}}catch(e){isCurrentSearch(o)&&(c=toErrorMessage(e))}finally{isCurrentSearch(o)&&(l=!1,this.#Dn())}},d=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));d=e.notices??r,t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,message:``,options:i,select:s};return d!==void 0&&d.length>0&&(t.notices=d),c!==void 0&&(t.error=c),l&&(t.loadingFrame=this.#Pn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#Dn(),await this.#wt((t,o)=>{let close=e=>{u+=1,o(e)};if(l){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#Dn();return}let d=e.navigation?.kind===`planner`?e.navigation:void 0,f=t.type===`left`&&(d?.activeStep??0)>(d?.firstNavigableStep??0)?`back`:t.type===`right`&&d!==void 0&&d.activeStep>=(d.firstNavigableStep??0)&&d.activeStep<d.steps.length-1?`forward`:void 0;if(f!==void 0){close({kind:`navigate`,direction:f,values:n?orderedSelection(i,s.selected):[]});return}let p={key:t,options:i,searchAction:r,select:s},m=reduceSetupSelectInput(n?{...p,kind:e.kind,required:e.required,plannerNavigation:a||void 0}:{...p,kind:e.kind});switch(m.kind){case`cancel`:close(void 0);return;case`repaint`:this.#Dn();return;case`update`:s=m.select,c=void 0,this.#Dn();return;case`submit`:{let e=searchActionQuery(m.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(m.values);return}loadSearch(e,t);return}case`error`:c=m.message,this.#Dn();return;case`ignore`:return}}).promise}#ht(e){this.#Lt();let t=this.#St();t.status={kind:`progress`,text:stripTerminalControls(e.status),startedAtMs:Date.now()};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#i,t),this.#Dn();let r=this.#wt((t,r)=>{let i=setupSelectionIntent(t,{textNavigation:!0});switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#Dn();return;case`repaint`:this.#Dn();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#gt(e){let t=this.#xt(e.message),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:``,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#le,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#i,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#Yt():(i=lineOf(``),this.#Xt())};return syncEditableRow(),this.#Dn(),await this.#wt((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Zt(),this.#Dn()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#Dn()},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.#Dn();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t,{textNavigation:!onEditableRow()});switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#Dn();return;case void 0:}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Xt()).promise}async#_t(e){let t=this.#xt(e.message),n=initialProviderPickerState(e.options,e.initialValue),r,cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor),r=e.options.find(e=>e.value===t);if(r!==void 0)return enterBadge(this.#i,r.checked===!0?`change`:void 0)};t.question=t=>{let r=cursorBadge(),i={kind:`inline-edit`,layout:`stacked`,message:``,options:e.options,select:n.select,edit:{optionValue:`ai-gateway-key`,caretVisible:this.#le,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#i,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#Yt():this.#Xt()};return syncCaret(),this.#Dn(),await this.#wt((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.#Dn();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#Dn();return;case`validate`:{n=o.state,syncCaret(),this.#Dn();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,{textNavigation:n.phase.kind===`inactive`});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.#Dn();return;case void 0:}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#Zt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Xt()}).promise}async#vt(e){let t=this.#xt(`Select the model`),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#i,t,``),this.#Dn(),await this.#wt((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#Dn();return;case`cancel`:r(void 0);return;case`settle`:r(i.result);return}},i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:i.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#Dn();return;case void 0:}if(t.type===`left`||t.type===`right`){dispatch({type:`adjust`,direction:t.type});return}if(t.type===`tab`){dispatch({type:`adjust`,direction:`right`});return}if(t.type===`backspace`){dispatch({type:`backspace`});return}if(t.type===`text`)for(let e of t.value.replaceAll(`
|
|
6
|
+
`,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#yt(e){let t=this.#xt(e.message),n=lineOf(``),r;return t.question=t=>{let i={message:``,editor:n,mask:e.mask===!0};return e.placeholder===void 0?e.defaultValue!==void 0&&(i.placeholder=e.defaultValue):i.placeholder=e.placeholder,e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#i,t,this.#le)},this.#Yt(),this.#Dn(),await this.#wt((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Zt(),this.#Dn()},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.#Dn();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#Dn();return}i(t);return}default:return}},()=>this.#Xt()).promise}async#bt(e){let t=this.#xt(e.message);return t.question=t=>renderAcknowledgeQuestion({message:``,lines:e.lines},this.#i,t),this.#Dn(),await this.#wt((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#Dn();return;default:return}}).promise}#xt(e){this.#Lt(),this.#U=!1,this.#X={kind:`idle`},this.#Q=``;let t=this.#St();return t.questionTitle=stripTerminalControls(e),t.status!==void 0&&(t.status=void 0,t.summary=void 0,t.preview=void 0),t}#St(){return this.#Ve===void 0&&(this.#Ve={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Ve}#Ct(){this.#Ve?.implicit===!0?this.#Ve=void 0:this.#Ve!==void 0&&(this.#Ve.question=void 0,this.#Ve.questionTitle=void 0,this.#Ve.hideLinesWhileQuestion=!1),this.#ge=void 0,this.#Vt(),this.#k===void 0?this.#Ve!==void 0&&this.#Et():this.#at(),this.#Ve===void 0&&this.#Dn()}#wt(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Ct(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Ct(),i(e))};return this.#Kt(),this.#ge=t=>{t.type===`ctrl-c`&&this.#Nt(),e(t,settle,reject)},this.#Bt(),{promise:a,settle}}#Tt(e){let t,n=new Promise(e=>{t=e});return this.#tt=t,this.#Et(e?.interruptible??!0),{promise:n,dispose:()=>{this.#tt===t&&(this.#tt=void 0,this.#Dt())}}}#Et(e=!0){if(this.#k!==void 0){this.#at();return}if(this.#tt===void 0)return;let consumer=t=>{if(e&&(t.type===`ctrl-c`||t.type===`escape`)){t.type===`ctrl-c`&&this.#Nt();let e=this.#tt;this.#tt=void 0,this.#Dt(),e?.(t.type===`ctrl-c`?`ctrl-c`:`escape`);return}t.type===`ctrl-r`&&this.#Dn()};this.#nt=consumer,this.#Kt(),this.#ge=consumer,this.#Bt()}#Dt(){this.#nt!==void 0&&(this.#ge===this.#nt&&this.#Vt(),this.#nt=void 0)}#Ot(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e),startedAtMs:Date.now()}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis),startedAtMs:Date.now()};if(this.#Ve!==void 0){this.#Ve.status=t,t===void 0&&(this.#Ve.preview=void 0),this.#Dn();return}if(!(this.#U||this.#Y)){if(t===void 0){this.#X={kind:`idle`},this.#$=void 0,this.#en(),this.#Dn();return}this.#Lt(),this.#$t(),this.#$=t.text,this.#Dn()}}#kt(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Ve;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.#Dn();return}this.#Lt(),this.#in({kind:`flow`,title:t,body:n,live:!1}),this.#Dn()}#At(e){let t=this.#Ve;t!==void 0&&(t.lines=[],t.outputBuffer=[],t.preview=void 0,t.status=void 0,t.summary=e===void 0?void 0:{headline:stripTerminalControls(e.headline),facts:e.facts.map(e=>({label:stripTerminalControls(e.label),value:stripTerminalControls(e.value)}))},this.#Dn())}#jt(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Ve;if(n===void 0){this.#kt(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#Dn()}async#Mt(e){this.#_e=``,this.#Kt(),this.#tt=void 0,this.#Dt(),this.#Vt(),this.#tn(),this.#n.clear(),this.#Yn(),this.#r.enter({cursor:`visible`,mouse:!1}),this.#e.isTTY&&this.#e.setRawMode?.(!1),this.#e.pause();try{return await e()}finally{this.#r.exit(),this.#e.isTTY&&this.#e.setRawMode?.(!0),this.#e.resume(),this.#_e=``,this.#Kt(),this.#n.hideCursor(),this.#Jn(),this.#Ve===void 0?this.#rn():(this.#Qt(),this.#Et()),this.#n.reset(),this.#Dn()}}setSessionId(e){this.#Ze=e}shutdown(){if(this.#zt(),this.#ne&&!this.#re){this.#re=!0;let e=this.#Ze===void 0?``:` ${this.#i.glyph.dot} session ${this.#Ze}`;this.#t.write(`${this.#i.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}suspendPromptForInput(){this.#J={cursor:this.#V,text:this.#B},this.#zt()}requestInterrupt(){this.#ie=!0,this.#Ve!==void 0&&this.#ge?.({type:`ctrl-c`}),this.#xe?.(),this.#zt()}exitRequested(){return this.#ae}#Nt(){this.#ae=!0,this.#ce?.()}async#Pt(e){if(this.#rt!==void 0||!this.#te)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#Kn(),height:this.#qn()}),paint:e=>this.#r.paint(e,this.#qn()),tracingDisabled:process.env.EVE_TRACES===`off`,copyText:e=>copyTextToClipboard(e,e=>this.#r.writeRaw(e)),terminalBackground:this.#it});this.#rt=t,this.#r.enter(),this.#i.color&&this.#r.writeRaw(BACKGROUND_COLOR_QUERY),await new Promise(e=>{this.#It=e,this.#ge=e=>{t.handleKey(e)===`close`&&this.#Ft()},this.#Bt(),t.start()})}#Ft(){let e=this.#rt;if(e===void 0)return;this.#rt=void 0,e.dispose(),this.#Vt(),this.#r.exit(),this.#n.hideCursor(),this.#Dn(),this.#n.showCursor();let t=this.#It;this.#It=void 0,t?.()}#It;#Lt(e){this.#ee=e?.title??this.#ee,e?.contextSize!==void 0&&(this.#Ee=e.contextSize),!this.#te&&(this.#te=!0,this.#ne=!0,this.#n.reset(),this.#n.hideCursor(),this.#Jn(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#be=()=>this.#Dn(),this.#t.on(`resize`,this.#be),process.on(`exit`,this.#Rt))}#Rt=()=>{this.#te&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#zt(){this.#Ft();let e=this.#Z;if(this.#Z=void 0,e?.(interruptedError()),this.#Vt(),this.#Xt(),this.#tn(),this.#me!==void 0&&(clearTimeout(this.#me),this.#me=void 0),this.#he=!1,this.#rr(),this.#te){this.#ar();for(let e of this.#h)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#Dn(),this.#n.clear(),this.#n.showCursor(),this.#Yn(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#be&&=(this.#t.off(`resize`,this.#be),void 0),process.off(`exit`,this.#Rt),this.#te=!1}}#Bt(){this.#e.off(`data`,this.#Ht),this.#e.on(`data`,this.#Ht),this.#_e.length>0&&queueMicrotask(()=>{this.#ge!==void 0&&this.#_e.length>0&&(this.#Wt(),this.#Ut())})}#Vt(){this.#e.off(`data`,this.#Ht),this.#Kt(),this.#ge=void 0}#Ht=e=>{this.#Kt(),this.#_e+=this.#ve.write(e),this.#Wt(),this.#Ut()};#Ut(){if(this.#_e===`\x1B`){this.#ye=setTimeout(()=>{this.#_e===`\x1B`&&(this.#_e=``,this.#ge?.({type:`escape`}))},30),this.#ye.unref?.();return}if(isIncompletePaste(this.#_e)){let e=this.#_e;this.#ye=setTimeout(()=>{if(this.#_e!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#_e=``,t.length>0&&this.#ge?.({type:`text`,value:t,framing:`bracketed-paste`})},incompletePasteFlushMs),this.#ye.unref?.();return}if(isIncompleteOsc(this.#_e)){let e=this.#_e;this.#ye=setTimeout(()=>{this.#_e===e&&(this.#_e=``)},incompletePasteFlushMs),this.#ye.unref?.()}}#Wt(){for(;this.#_e.length>0;){let e=nextKey(this.#_e);if(e.incomplete)return;if(this.#_e=this.#_e.slice(e.consumed),e.key!==void 0&&e.key.type!==`ignore`){if(e.key.type===`osc`){this.#Gt(e.key.value);continue}this.#ge?.(e.key)}}}#Gt(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#it=t,this.#rt?.setTerminalBackground(t))}#Kt(){this.#ye&&=(clearTimeout(this.#ye),void 0)}#qt(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#Dn();break;case`enter`:{let e=this.#J.text;if(e.trim().length===0)break;if(parsePromptCommand(e)?.type===`cancel`&&this.#Je!==void 0){this.#J=EMPTY_LINE,this.#qe.requestCancellation(),this.#$e=!0,this.renderCommandInvocation(e.trim()),this.renderCommandResult(`Turn cancellation requested.`),this.#Je(),this.#Dn();break}let t=this.#Ye;t!==void 0&&parsePromptCommand(e)===null?(this.#J=EMPTY_LINE,this.#Jt(e,t)):this.#qe.enqueue(e)&&(this.#J=EMPTY_LINE),this.#Dn();break}case`ctrl-c`:case`escape`:if(e.type===`ctrl-c`&&this.#qe.view().cancelling){this.#ie=!0,this.#se=!0,this.#X={kind:`idle`},this.#Q=`Interrupted`,this.#xe?.(),this.#Dn();break}if(this.#qe.idle&&this.#Je===void 0)break;if(this.#qe.handleEscape()===`steer`){let e=this.#Ye;if(e!==void 0){let t=this.#qe.takeSteering();this.#Jt(t,e)}}else this.#$e=!0,this.#Je?.();this.#Dn();break;default:{let t=applyLineEditorKey(this.#J,e,{multiline:!0});t!==void 0&&(this.#J=t,this.#Dn());break}}}#Jt(e,t){this.#Qe=`steer`,this.#sn(e),t(e).catch(t=>{this.#qe.restoreSteering(e),this.#cn(`Steering failed`,toErrorMessage(t)),this.#Dn()})}#Yt(){this.#Xt(),this.#Zt(),this.#fe=setInterval(()=>{this.#le=!this.#le,this.#Dn()},500),this.#fe.unref?.()}#Xt(){this.#fe&&=(clearInterval(this.#fe),void 0),this.#le=!0}#Zt(){this.#le=!0}#Qt(){this.#tn(),this.#pe=setInterval(()=>{this.#ue+=1,this.#Dn()},90),this.#pe.unref?.()}#$t(){let e=Date.now();this.#de=e,this.#X={kind:`waiting`,startedAtMs:e},this.#Qt()}#en(){this.#nn()||this.#tn()}#tn(){this.#pe&&=(clearInterval(this.#pe),void 0)}#nn(){return this.#h.some(e=>e.live&&e.subagentCallId!==void 0&&(this.#C.has(e.subagentCallId)||this.#w.has(e.subagentCallId)))}#rn(){this.#nn()?this.#Qt():!this.#Y&&this.#X.kind===`idle`&&this.#tn()}#in(e){e.id!==this.#Pe?.id&&this.#ar(),e.updateSeq=++this.#x;let t=e.subagentCallId!==void 0&&this.#C.has(e.subagentCallId)?-1:this.#h.findIndex(e=>e.subagentCallId!==void 0&&this.#C.has(e.subagentCallId));t<0?this.#h.push(e):this.#h.splice(t,0,e),e.id&&this.#g.set(e.id,e)}#an(e){this.#K=!0,this.#in({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#Dn()}#on(){let e=this.#q.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#zn(e.elapsedMs)}`,n=this.#Te??0;if(this.#Ee!==void 0&&this.#Ee>0&&n>0){let e=Math.round(n/this.#Ee*100);t+=` ${this.#i.glyph.dot} ${e}% context`}this.#in({kind:`turn-stats`,body:t,live:!1})}#sn(e){if(e==null)return;let t=this.#Qe;if(this.#Qe=void 0,this.#ze===e){this.#ze=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#in(n)}#cn(e,t,n={}){let r=stripTerminalControls(e),i=stripTerminalControls(t),a=n.detail===void 0?void 0:stripTerminalControls(n.detail),o=n.hint===void 0?void 0:stripTerminalControls(n.hint),s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#f?.append(o===void 0?s:{...s,hint:o});let c={kind:`error`,title:r,body:i,live:!1};o!==void 0&&(c.hint=o),a!==void 0&&(c.detail=this.#f===void 0?a:`details: ${this.#f.displayPath}`),this.#in(c),this.#Dn()}#ln(e,t){if(this.#E.has(e))return;this.#E.add(e);let n=stripTerminalControls(t),r=this.#S.get(n)??[];if(r.push(e),this.#S.set(n,r),r.length===2){let e=this.#g.get(subagentHeaderId(r[0]));e!==void 0&&(e.subtitle=`#1`)}let i={id:subagentHeaderId(e),kind:`subagent`,subagentCallId:e,title:n,live:!0};r.length>1&&(i.subtitle=`#${r.length}`),this.#in(i)}#un(e){if(e.id&&this.#_.has(e.id))return;let t=e.id?this.#g.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#x;return}this.#in(e)}#dn(e){if(e.id&&this.#_.has(e.id))return;let t=e.id?this.#g.get(e.id):void 0;if(t!==void 0){Object.assign(t,e),t.updateSeq=++this.#x;return}let n=e.subagentCallId;if(n===void 0){this.#in(e);return}e.id!==this.#Pe?.id&&this.#ar(),e.updateSeq=++this.#x;let r=-1;for(let e=0;e<this.#h.length;e+=1)this.#h[e]?.subagentCallId===n&&(r=e);this.#h.splice(r<0?this.#h.length:r+1,0,e),e.id!==void 0&&this.#g.set(e.id,e)}#fn(e){this.#h=this.#h.filter(t=>t.id!==e),this.#g.delete(e)}#pn(e){let t=this.#h.filter(t=>t.subagentCallId===e);t.length!==0&&(this.#h=this.#h.filter(t=>t.subagentCallId!==e),this.#h.push(...t))}#mn(){for(let e of this.#h)e.subagentCallId!==void 0&&this.#w.has(e.subagentCallId)||e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#hn(e,t,n){switch(e.type){case`turn-start`:e.turnId!==this.#We&&(this.#We=e.turnId,this.#Ue=void 0,this.#Dn());break;case`step-start`:this.#Ue=typeof e.modelId==`string`&&stripTerminalControls(e.modelId.slice(0,256)).replace(/\s+/gu,` `).trim()||void 0,this.#Dn();break;case`step-finish`:this.#f?.recordStepUsage(e.usage),e.usage!==void 0&&this.#q.addUsage(e.usage),this.#Sn(n),this.#En(e.usage),this.#Dn();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#gn(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=typeof e.text==`string`?stripTerminalControls(e.text):t;n.text.set(e.id,r),this.#gn(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);if(n.reasoning.set(e.id,r),t.reasoning===`full`){this.#_n(e.id,r,!0,t);break}break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;if(t.reasoning===`full`){this.#_n(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#vn({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#f?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#vn({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.#vn({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#Tn(e.toolCallId,n);if(r===void 0)break;this.#vn({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#Tn(e.toolCallId,n);if(this.#f?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#vn({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#Tn(e.toolCallId,n);if(r===void 0)break;this.#vn({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#cn(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:if(n.cancelled=!0,!n.restoreCancelledPrompt)break;this.#Xe=!0,!this.#$e&&this.#et!==void 0&&this.#J.text.length===0&&(this.#J=lineOf(this.#et),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#En(e.usage),this.#Dn()}}#gn(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#un({id:e,kind:`assistant`,body:r,live:n}),this.#Dn())}#_n(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#un({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#Dn())}#vn(e,t,n){if(n.tools.set(e.toolCallId,e),this.#y.has(e.toolCallId)||this.#Cn(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#b.set(e.toolCallId,r);let i=this.#yn(e);this.#un(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#wn(n),this.#Dn()}#yn(e){e.output!==void 0&&this.#T.observeRead(e.output);let t={};this.#bn(e.toolName)&&(t.isSubagent=!0);let n=readWriteFileInput(e.toolName,e.input);if(n===void 0)return t.isSubagent===!0?t:void 0;let r=this.#T.observeWrite({path:n.path,content:n.content,callId:e.toolCallId});r!==void 0&&(t.previousContent=r);let i=writeExistedFlag(e.output);return i!==void 0&&(t.existed=i),t}#bn(e){let t=this.#D?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#xn(e){for(let t of e.tools.keys()){if(this.#y.has(t))continue;let e=this.#b.get(t)??toolSectionId(t),n=this.#g.get(e);n?.kind===`tool`&&n.status===`running`&&(n.status=`error`,n.result=`interrupted`,n.live=!1)}}#Sn(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#b.get(t)??toolSectionId(t);this.#fn(r),this.#b.delete(t)}}#Cn(e){let t=readTodoToolItems(e.toolName,e.input);if(t===void 0)return!1;if(t.length>0&&allTodoItemsSettled(t)){let e=JSON.stringify(t);this.#Ke!==e&&(this.#Ke=e,this.#in({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#Kn(),this.#i).join(`
|
|
7
|
+
`),live:!1})),this.#Ge=void 0}else this.#Ge=t.length>0?t:void 0,this.#Ke=void 0;return this.#Dn(),!0}#wn(e){let t=[];for(let n of e.tools.values()){if(this.#y.has(n.toolCallId))continue;let e=this.#b.get(n.toolCallId)??toolSectionId(n.toolCallId),r=this.#g.get(e);r?.kind===`tool`&&t.push({block:r,active:isActiveToolStatus(n.status)})}applyCohortLiveness(t)}#Tn(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#b.get(e)??toolSectionId(e),i=this.#g.get(r);if(i!==void 0&&i.kind===`tool`)return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.toolName??i.title??`tool`}}#En(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#we=(t??0)+(n??0)),this.#Te=t??this.#Te,this.#De=n??this.#De,this.#De!=null&&this.#ke!==void 0){let e=(Date.now()-this.#ke)/1e3;e>0&&(this.#Oe=this.#De/e)}}#Dn(){if(this.#te){if(this.#Se){this.#Ce=!0;return}this.#Se=!0;try{do this.#Ce=!1,this.#On();while(this.#Ce)}finally{this.#Se=!1}}}#On(){if(!this.#te)return;if(this.#rt!==void 0){this.#rt.repaint();return}let e=this.#Kn(),t=this.#Ln(e),n=this.#M===void 0?[]:this.#Mn(),r=Math.max(1,this.#qn()-n.length-t.length),i=[],a=this.#I,o=groupToolBlocksForDisplay(this.#h),s=0;for(;s<o.length&&o[s].display.live===!1;)s+=1;if(s>0){let e=new Set(o.slice(0,s).flatMap(e=>e.members));for(let t=this.#h.length-1;t>=0;--t)e.has(this.#h[t])&&this.#h.splice(t,1)}for(let t of o.slice(0,s)){for(let e of t.members)this.#v.push(e),e.id&&(this.#_.add(e.id),this.#g.delete(e.id));if(this.#sr(t.display))continue;let n=this.#Nn(t.display,e,a);a=previousBlockOf(t.display),this.#I=a,i.push(...n),this.#F.push(...n)}let c=[];for(let{display:t}of o.slice(s)){if(this.#sr(t))continue;let n=this.#Nn(t,e,a);a=previousBlockOf(t);for(let e=0;e<n.length;e+=1)c.push({block:t,row:n[e]})}let l=[...n,...clipLiveRows(c.map(e=>e.row),r,e,this.#i),...t];i.length>0?this.#n.flush(i,l):this.#n.update(l)}#kn(){if(!this.#te)return;let e=this.#Kn(),t=this.#Ln(e),n=Math.max(1,this.#qn()-t.length),r=this.#I,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#h)){if(this.#sr(t))continue;let n=this.#Nn(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#i),...t];this.#n.clearAll(),this.#n.flush([...this.#Mn(),...this.#F],a)}logDisplayMode(){return this.#m}setLogDisplayMode(e){e!==this.#m&&(this.#m=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#jn(),this.#te&&this.#kn())}flushDelayedDevBuildErrors(){let e=this.#Ne;e!==void 0&&(this.#Ne=void 0,this.#in({kind:`log`,title:`stderr`,body:e,live:!0}),this.#Dn())}#An(){this.#he=!0,this.#me!==void 0&&clearTimeout(this.#me),this.#me=setTimeout(()=>{this.#he=!1,this.#me=void 0,this.#Dn()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#m)),this.#Dn()}#jn(){let e=this.#Kn();this.#F.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#v,{logCoalescing:`runs`})){if(this.#sr(n))continue;let r=this.#Nn(n,e,t);t=previousBlockOf(n),this.#F.push(...r)}this.#I=t}#Mn(){let e=this.#D,t=this.#M;if(e===void 0&&t===void 0)return[];let n={name:e?.name??t?.name,theme:this.#i,width:this.#Kn()};e?.info!==void 0&&(n.info=e.info);let r=e?.tip??t?.tip;return r!==void 0&&(n.tip=r),buildAgentHeader(n)}#Nn(e,t,n){let r={renderMarkdown:this.#a,activityPulse:this.#Fn(this.#de,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#i,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#Pn(){return this.#i.spinner[this.#ue%this.#i.spinner.length]??``}#Fn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#In(e,t){return e.indicator.kind===`spinner`?{glyph:this.#Pn(),color:`yellow`}:{glyph:this.#Fn(e.indicator.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#Ln(e){let t=this.#i.colors,n=[``];if(this.#Be!==void 0)return n.push(...this.#Be(e),``),this.#Un(n,e),n;let r=this.#Ve;if(r!==void 0&&(this.#k===void 0||r.question!==void 0)){let t=this.#In(r,r.status),i;if(r.status!==void 0){let{startedAtMs:e,...n}=r.status,a=Date.now()-e,o=a>=5e3?` ${formatTurnDuration(a)}`:``;i={...n,text:`${n.text}${o}`,indicator:t}}let a;if(r.question!==void 0){let t=r.question(e);a={kind:`question`,title:r.questionTitle,rows:t},i!==void 0&&(a={kind:`question`,title:r.questionTitle,rows:t,status:i})}else i===void 0?a=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(a={kind:`status`,status:i},r.preview!==void 0&&(a={kind:`status`,status:i,preview:r.preview}));let o={title:r.title,navigation:r.navigation,lines:r.summary===void 0?r.hideLinesWhileQuestion===!0?[]:r.lines:[{text:r.summary.headline,tone:`success`},...r.summary.facts.map(e=>({text:`${e.label}: ${e.value}`,tone:`info`}))],content:a};return n.push(...renderFlowPanel(o,this.#i,e)),this.#Wn(n,e),n}r!==void 0&&n.push(...flowMessageRows(r.lines,this.#i).map(t=>t.length===0?``:clip(` ${t}`,e))),this.#O===void 0&&this.#He!==void 0&&n.push(...renderAttentionRows(this.#He,e,this.#i),``),this.#Ge!==void 0&&n.push(...renderTodoPanelRows({items:this.#Ge,width:e,theme:this.#i,working:this.#Y||this.#X.kind===`waiting`,pulse:this.#Fn(this.#de,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}),``);let i=renderMessageQueueRows({view:this.#qe.view(),width:e,theme:this.#i,working:this.#Y});if(i.length>0&&n.push(...i,``),this.#U){let r=this.#W===void 0?void 0:inlineCommandHint(this.#W);r===void 0&&this.#W!==void 0&&isTypeaheadOpen(this.#W)&&n.push(...renderCommandSuggestions(this.#W,this.#i,e)),this.#oe&&n.push(clip(t.dim(`Press Ctrl+C again to exit`),e),``);let i=isPromptControlCommand(this.#B),a=r?t.dim(` ${r}`):``,o=[];this.#Un(o,e);let s=Math.max(1,this.#qn()-1-n.length-1-o.length),c={text:this.#B,cursor:this.#V,width:e,theme:this.#i,caretVisible:this.#le,isCommand:i,ghost:a,maxRows:s};return this.#G&&this.#B.length===0&&(c.placeholder=this.#k===void 0?this.#K?``:`Send a message…`:`Message · Enter to queue`),n.push(...promptInputRows(c)),n.push(...o),n}let a=this.#X.kind===`waiting`&&this.#$===void 0;if(this.#Y||a){n.push(this.#Rn(e)),this.#Vn(n,e);let t=[];return this.#Un(t,e),!this.#Y&&t.length>0&&n.push(``),n.push(...t),n}if(this.#J.text.length>0)return this.#Hn(n,e,{inert:!1}),this.#Un(n,e),n;let o=this.#$??(this.#Q.length>0?this.#Q:`Ready`),s=this.#Gn(),c=t.dim(this.#i.glyph.dot),l=s?`${c} ${o} ${t.dim(this.#i.glyph.dot)} ${s}`:`${c} ${o}`;return n.push(clip(l,e)),this.#Un(n,e),n}#Rn(e){let t=this.#i.colors,n=this.#Fn(this.#de,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),r=this.#X,i=this.#q.startedAtMs??this.#ke??(r.kind===`waiting`?r.startedAtMs:Date.now()),a=Date.now()-i,o=`${typewriterText(`Working for`,a,80)} ${this.#zn(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#zn(e){return`${formatTurnDuration(e)}${this.#Bn()}`}#Bn(){let{inputTokens:e,outputTokens:t}=this.#q.usage;return e===0&&t===0?``:` ${this.#i.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#i.glyph)}`}#Vn(e,t){this.#Y&&this.#Hn(e,t,{inert:!0})}#Hn(e,t,n){e.push(``);let r={text:this.#J.text,cursor:this.#J.cursor,width:t,theme:this.#i,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#J.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#Un(e,t){if(this.#O!==void 0){let n=this.#Ve?.status?.text??{starting:`Starting agent…`,connecting:`Reading saved connection…`,updating:`Loading selected model…`}[this.#O],r=this.#Fn(this.#j,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH);e.push(clip(this.#i.colors.dim(`${r} ${n}`),t));return}let n=this.#z===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#i,width:r};this.#Ie&&this.#Fe!==void 0&&(i.devBuild=this.#Fe),this.#he&&(i.logLevel=this.#m);let a=this.#D?.info?.agent.model;a?.routing.kind===`dynamic`?i.model=this.#Ue===void 0?`dynamic model`:`dynamic model · ${this.#Ue}`:a?.id!==void 0&&(i.model=a.id),a?.reasoning!==void 0&&a.reasoning!==`provider-default`&&(i.reasoning=a.reasoning),readGatewayServiceTier(a?.providerOptions).kind===`priority`&&(i.fastMode=!0);let o=a?.endpoint;o!==void 0&&(i.endpoint=o),this.#R!==void 0&&(i.vercel=this.#R),this.#z!==void 0&&(i.remote=this.#z);let s=buildStatusLine(i);s!==void 0&&e.push(clip(`${n}${s}`,t))}#Wn(e,t){if(this.#z===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#z,theme:this.#i,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Gn(){let e=this.#i.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#we,outputTokens:this.#De,tokensPerSecond:this.#Oe},this.#u);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#i.glyph.dot} `)):``}#Kn(){return Math.max(20,this.#t.columns||80)}#qn(){return Math.max(8,this.#t.rows||24)}#Jn(){if(this.#Ae!==void 0||!this.#d)return;this.#je=``,this.#Me=``;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.#Zn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#f?.subscribeLogRecords(e=>this.#Xn(e)),this.#Ae=()=>{this.#f?.unsubscribeLogRecords(),e(),t()}}#Yn(){let e=this.#Ae;e!==void 0&&(this.#Ae=void 0,e(),this.#je.length>0&&(this.#f?.append({source:`stdout`,detail:this.#je}),this.#or(`stdout`)&&process.stdout.write(`${this.#je}\n`),this.#je=``),this.#Me.length>0&&(this.#f?.append({source:`stderr`,detail:this.#Me}),this.#or(`stderr`)&&process.stderr.write(`${this.#Me}\n`),this.#Me=``))}#Xn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#$n(`[eve:${e.namespace}] ${e.message}${t}`),this.#Dn()}#Zn(e,t){let n=(e===`stdout`?this.#je:this.#Me)+t;if(e===`stdout`&&parseDevRebuildLogLine(n.trimEnd())!==void 0){this.#je=``,this.#f?.append({source:e,detail:n.trimEnd()}),this.#Qn(n.trimEnd()),this.#Dn();return}let r=n.lastIndexOf(`
|
|
8
|
+
`),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#je=i:this.#Me=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#f?.append({source:e,detail:a}),e===`stdout`?this.#Qn(a):this.#$n(a),this.#Dn())}#Qn(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
|
|
9
|
+
`);t=[],e.trim().length!==0&&this.#in({kind:`log`,title:`stdout`,body:e,live:!0})};for(let n of e.split(`
|
|
10
|
+
`)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#in({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#tr(r,n.trimEnd())}flushPending()}#$n(e){let t=e.split(`
|
|
11
|
+
`),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#f===void 0){this.#in({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#f.displayPath);if(t.kind===`inline`){this.#in({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#in({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#in({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
|
|
12
|
+
`);r.trim().length>0&&this.#in({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
|
|
13
|
+
`);this.#er(i)}#er(e){if(this.#rr(),this.#m===`all`){if(e.trim().length===0)return;this.#in({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#Ne=e}#tr(e,t){let n=this.#ir();if(e.kind===`failed`){this.#er(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(this.#nr({phase:`building`,summary:t}),n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#Re}`;this.#Re+=1,this.#Pe={id:r,summary:t},this.#in({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}let r=n?.state.summary??this.#Fe?.summary;if(r!==void 0&&this.#nr({phase:`complete`,summary:r}),n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#Ne=void 0);return}e.kind===`rebuilt`&&(this.#Ne=void 0),this.#in({kind:`log`,title:`stdout`,body:t,live:!0})}#nr(e){this.#Le!==void 0&&clearTimeout(this.#Le),this.#Fe=e,this.#Ie=e.phase===`complete`,this.#Le=setTimeout(()=>{e.phase===`building`?(this.#Ie=!0,this.#Le=void 0):this.#rr(),this.#Dn()},e.phase===`building`?250:4e3)}#rr(){this.#Le!==void 0&&clearTimeout(this.#Le),this.#Fe=void 0,this.#Ie=!1,this.#Le=void 0}#ir(){let e=this.#Pe;if(e===void 0)return;let t=this.#g.get(e.id);if(t!==void 0&&t.live===!0)return{state:e,block:t}}#ar(){let e=this.#Pe;if(e===void 0)return;this.#Pe=void 0;let t=this.#g.get(e.id);t!==void 0&&(t.live=!1)}#or(e){switch(this.#m){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#sr(e){return e.kind===`sandbox`?!this.#or(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#m!==`stderr`:e.logVisibility===`all-only`?this.#m!==`all`:!this.#or(e.title===`stderr`?`stderr`:`stdout`):!1}};function chunkToString(e,t){return typeof e==`string`?e:Buffer.from(e).toString(t)}async function*iterateTUIStream(e){if(e instanceof ReadableStream){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}return}yield*e}function clip(e,t){return clipVisible(e,t)}function promptInputRows({text:e,cursor:t,width:n,theme:r,caretVisible:i,isCommand:a,ghost:o,maxRows:s,placeholder:c,inert:l}){let u=r.colors;if(e.length===0&&c!==void 0){let e=renderInputWithBlockCursor({...visibleLine({text:c,cursor:0},Math.max(1,n-3),r.glyph.ellipsis),visible:i,inverse:u.inverse,render:e=>u.dim(renderInputText(e))});return[clip(`${r.glyph.prompt} ${e}`,n),``]}let style=e=>{let t=renderInputText(e);return a&&t.length>0?u.blue(t):t},d=layoutPromptInput({text:e,cursor:t}),f=Math.min(Math.max(1,s),d.rows.length),p=Math.max(0,Math.min(d.caretRow-f+1,d.rows.length-f)),m=l===!0?u.dim(r.glyph.prompt):u.cyan(r.glyph.prompt),h=u.dim(r.glyph.ellipsis),g=Math.max(1,n-3),_=[];for(let e=p;e<p+f;e+=1){let t=d.rows[e],a=e===0?m:` `;(e===p&&p>0||e===p+f-1&&p+f<d.rows.length)&&(a=h);let s;if(e===d.caretRow){let{before:e,under:n,after:a}=visibleLine({text:t.text,cursor:d.caretOffset},g,r.glyph.ellipsis);s=renderInputWithBlockCursor({before:e,under:n,after:a,visible:i,inverse:u.inverse,render:style}),o.length>0&&d.rows.length===1&&(s+=o)}else s=style(t.text);_.push(clip(`${a} ${s}`,n))}return _.push(``),_}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function isActiveToolStatus(e){return e===`running`||e===`approval`}function applyCohortLiveness(e){let t=e.some(e=>e.active);for(let n of e)n.block.live=t||n.active}function leadsWithGap(e,t){if(e.kind===`tool`&&(t?.kind===`user`||t?.kind===`assistant`||t?.kind===`question`))return!0;if(e.kind===`sandbox`&&t?.kind===`sandbox`)return!1;if(t?.kind===`sandbox`&&e.kind!==`sandbox`||t?.kind===`log`)return!0;switch(e.kind){case`user`:case`assistant`:case`reasoning`:case`subagent`:case`error`:case`notice`:case`question`:case`connection-auth`:case`sandbox`:case`log`:case`command`:case`warning`:case`flow`:case`turn-stats`:case`session-boundary`:case`todo-list`:case`agent-header`:return!0;default:return!1}}function parseSandboxLogLine(e){let t=e.trim();if(!t.startsWith(`eve: `))return;let n=t.slice(5);return/\bsandbox\b/i.test(n)&&!isLowValueSandboxLogLine(n)?n:void 0}function isLowValueSandboxLogLine(e){return/^initializing (?:\d+ )?sandbox templates?\b/i.test(e)||/^initialized \d+ sandbox\b/i.test(e)||/^reused cached sandbox template\b/i.test(e)||/^sandbox template "[^"]+" \([^)]+\): (checking|reusing|loading microsandbox runtime|microsandbox runtime ready)\b/i.test(e)}function clipLiveRows(e,t,n,r){if(e.length<=t)return[...e];if(t<=1)return[clip(hiddenRowsMarker(e.length,r),n)];let i=t-1;return[clip(hiddenRowsMarker(e.length-i,r),n),...e.slice(e.length-i)]}function hiddenRowsMarker(e,t){let n=e.toLocaleString(),r=e===1?`row`:`rows`;return t.colors.dim(`${t.glyph.dot} ${t.glyph.ellipsis} ${n} earlier ${r} hidden while streaming`)}function collapseReasoning(e,t){switch(e){case`collapsed`:return!0;case`auto-collapsed`:return!t;default:return!1}}function renderNativeToolBlock(e,t,n,r){let i=e.preparing===!0?presentPreparingTool(e.toolName,r):presentTool(e.toolName,e.input,r),a={id:t,kind:`tool`,title:stripTerminalControls(i.title),subtitle:stripTerminalControls(i.subtitle),status:e.status,live:e.status===`running`||e.status===`approval`,expanded:n,toolInput:e.input,toolName:e.toolName,toolGroup:i.group};return i.doneTitle!==void 0&&(a.doneTitle=stripTerminalControls(i.doneTitle)),i.detail!==void 0&&(a.detailLines=i.detail,a.keepDetailWhenDone=i.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(a.result=stripTerminalControls(e.errorText)):(a.result=i.summarizeResult(e.output),a.toolOutput=e.output),a}function writeExistedFlag(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.existed;return typeof t==`boolean`?t:void 0}function subagentToolStatus(e){switch(e){case`preparing`:return`running`;case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`;case`rejected`:return`denied`}}function formatToolApprovalTitle(e){return stripTerminalControls(e.title??e.toolName)}function toolSectionId(e){return`tool:${e}`}function questionSectionId(e){return`question:${e}`}function subagentHeaderId(e){return`subagent:${e}:header`}function subagentStepSectionId(e,t){return`subagent:${e}:step:${t}`}function subagentToolSectionId(e,t){return`subagent:${e}:tool:${t}`}function connectionAuthSectionId(e){return`connection-auth:${e}`}function connectionAuthTerminalMessage(e){switch(e){case`authorized`:return`Authorization complete`;case`declined`:return`Authorization declined`;case`failed`:return`Authorization failed`;case`timed-out`:return`Authorization timed out`;case`required`:case`pending`:return}}function formatConnectionAuthContent(e,t){let n=[];if(t!==void 0)n.push(t);else{let t=stripTerminalControls(e.description);t.length>0&&n.push(t);let r=e.challenge;r?.url&&n.push(`URL: ${stripTerminalControls(r.url)}`),r?.userCode&&n.push(`Code: ${stripTerminalControls(r.userCode)}`),r?.expiresAt&&n.push(`Expires: ${stripTerminalControls(r.expiresAt)}`),r?.instructions&&n.push(stripTerminalControls(r.instructions))}if(e.reason!==void 0){let t=stripTerminalControls(e.reason);t.length>0&&n.push(`Reason: ${t}`)}return n.join(`
|
|
14
14
|
`)}function formatQuestionContent(e,t,n){let r=n.colors,i=[],a=e.options??[];if(a.length>0){for(let[e,o]of a.entries()){let a=stripTerminalControls(o.label),s=o.description===void 0?``:stripTerminalControls(o.description),c=t===e,l=s.length>0?`${c?` `:` `}${r.dim(`— ${s}`)}`:``,u=c?`${n.glyph.selectedPointer} ${a}`:` ${a}`,d=renderCursorRow(u,c,r);i.push(`${d}${l}`)}if(e.allowFreeform===!0){let e=t===a.length,o=`Type your own answer`,s=e?`${n.glyph.selectedPointer} ${o}`:` ${r.dim(o)}`;i.push(renderCursorRow(s,e,r))}}else i.push(r.dim(` (type your answer)`));return i.join(`
|
|
15
15
|
`)}function resolveQuestionText(e,t){let n=e.trim();if(n.length===0)return;let r=n.toLowerCase(),i=t.options??[];if(i.length>0){let e=matchQuestionOption(r,i);if(e!==void 0)return{optionId:e.id,label:e.label}}if(t.allowFreeform===!0||i.length===0)return{text:n,label:n}}function matchQuestionOption(e,t){let n=t.find(t=>t.id.toLowerCase()===e);if(n!==void 0)return n;let r=t.find(t=>t.label.toLowerCase()===e);if(r!==void 0)return r;let i=Number(e);if(Number.isInteger(i)&&i>0&&i<=t.length)return t[i-1]}export{TerminalRenderer};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { EveAgentReducer, EveAgentReducerEvent } from "#client/reducer.js";
|
|
2
|
+
/** Owns reducer replay when optimistic events are replaced by server events. */
|
|
3
|
+
export declare class EveAgentProjection<TData> {
|
|
4
|
+
#private;
|
|
5
|
+
constructor(reducer: EveAgentReducer<TData>, events: readonly EveAgentReducerEvent[]);
|
|
6
|
+
get data(): TData;
|
|
7
|
+
reset(): void;
|
|
8
|
+
append(event: EveAgentReducerEvent): void;
|
|
9
|
+
replace(predicate: (event: EveAgentReducerEvent) => boolean, replacement: EveAgentReducerEvent): void;
|
|
10
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var EveAgentProjection=class{#e;#t;#n;constructor(e,t){this.#e=e,this.#t=t,this.#n=this.#r()}get data(){return this.#n}reset(){this.#t=[],this.#n=this.#e.initial()}append(e){this.#t=[...this.#t,e],this.#n=this.#e.reduce(this.#n,e)}replace(e,t){let n=this.#t.findIndex(e);this.#t=n===-1?[...this.#t,t]:this.#t.map((e,r)=>r===n?t:e),this.#n=this.#r()}#r(){let e=this.#e.initial();for(let t of this.#t)e=this.#e.reduce(e,t);return e}};export{EveAgentProjection};
|
|
@@ -1,12 +1,16 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ActiveTurn } from "#client/eve-agent-store-state.js";
|
|
2
|
+
import type { CancelSessionResult, SendTurnPayload } from "#client/types.js";
|
|
2
3
|
import { type MessageStreamEvent } from "#protocol/message.js";
|
|
3
4
|
import type { UserContent } from "ai";
|
|
4
5
|
export declare function isSettledSessionTail(events: readonly MessageStreamEvent[]): boolean;
|
|
5
6
|
export declare function collectPendingAuthorizations(events: readonly MessageStreamEvent[]): Set<string>;
|
|
6
|
-
export declare function updatePendingAuthorizations(pending: Set<string>, event: MessageStreamEvent): void;
|
|
7
7
|
export declare function assertExclusiveTurnInput(input: SendTurnPayload): void;
|
|
8
8
|
export declare function createSubmissionId(): string;
|
|
9
9
|
export declare function createAbortSignal(first: AbortSignal | undefined, second: AbortSignal): AbortSignal;
|
|
10
10
|
export declare function summarizeUserContent(message: string | UserContent): string;
|
|
11
11
|
export declare function isAbortError(error: unknown): boolean;
|
|
12
12
|
export declare function toTerminalStreamFailureError(event: MessageStreamEvent): Error | undefined;
|
|
13
|
+
export declare function createActiveTurn(cancel: (turn: ActiveTurn) => Promise<CancelSessionResult>): ActiveTurn;
|
|
14
|
+
export declare function followSteeredTurns(turn: ActiveTurn, events: AsyncIterable<MessageStreamEvent>, isActive: () => boolean): Promise<void>;
|
|
15
|
+
/** Aborts a caller's wait without cancelling shared work owned by the store. */
|
|
16
|
+
export declare function waitWithSignal<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";function isSettledSessionTail(e){let t=e.at(-1);return t!==void 0&&isCurrentTurnBoundaryEvent(t)&&(t.type!==`session.waiting`||collectPendingAuthorizations(e).size===0)}function collectPendingAuthorizations(e){let t=new Set;for(let n of e)updatePendingAuthorizations(t,n);return t}function
|
|
2
|
-
`)}function isAbortError(e){return e instanceof Error&&e.name===`AbortError`}function toTerminalStreamFailureError(e){if(e.type!==`session.failed`)return;let t=Error(e.data.message);return t.name=e.data.code,t}export{assertExclusiveTurnInput,collectPendingAuthorizations,createAbortSignal,createSubmissionId,isAbortError,isSettledSessionTail,summarizeUserContent,toTerminalStreamFailureError,
|
|
1
|
+
import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{updatePendingAuthorizations}from"#client/session-utils.js";function isSettledSessionTail(e){let t=e.at(-1);return t!==void 0&&isCurrentTurnBoundaryEvent(t)&&(t.type!==`session.waiting`||collectPendingAuthorizations(e).size===0)}function collectPendingAuthorizations(e){let t=new Set;for(let n of e)updatePendingAuthorizations(t,n);return t}function assertExclusiveTurnInput(e){if(e.message!==void 0==(e.inputResponses!==void 0))throw Error(`A turn requires exactly one of message or inputResponses.`)}let submissionSequence=0;function createSubmissionId(){let e=globalThis.crypto?.randomUUID;return e===void 0?(submissionSequence+=1,`submission_${submissionSequence.toString()}`):e.call(globalThis.crypto)}function createAbortSignal(e,t){return e?AbortSignal.any([e,t]):t}function summarizeUserContent(e){if(typeof e==`string`)return e;let t=[];for(let n of e)n.type===`text`?t.push(n.text):n.type===`file`&&t.push(n.filename?`[file: ${n.filename}]`:`[file]`);return t.join(`
|
|
2
|
+
`)}function isAbortError(e){return e instanceof Error&&e.name===`AbortError`}function toTerminalStreamFailureError(e){if(e.type!==`session.failed`)return;let t=Error(e.data.message);return t.name=e.data.code,t}function createActiveTurn(e){let t=Promise.withResolvers(),n=Promise.withResolvers(),r={abortController:new AbortController,acceptedFollowUps:0,cancel:()=>e(r),completion:n.promise,followUpDispatches:new Set,receivedFollowUps:0,receivedFollowUpEvents:new Set,followUpSubmissionIds:new Set,resolveCompletion:n.resolve,response:t.promise,resolveResponse:t.resolve};return r}async function followSteeredTurns(e,t,n){for(;e.followUpDispatches.size>0;)await Promise.allSettled(e.followUpDispatches);if(!(e.receivedFollowUps>=e.acceptedFollowUps))for await(let r of t){if(!n())return;if(e.receivedFollowUpEvents.delete(r)&&(e.receivedFollowUps+=1),isCurrentTurnBoundaryEvent(r)){for(;e.followUpDispatches.size>0;)await Promise.allSettled(e.followUpDispatches);if(e.receivedFollowUps>=e.acceptedFollowUps)return}}}async function waitWithSignal(e,t){if(t===void 0)return await e;let n=Promise.withResolvers(),onAbort=()=>n.reject(t.reason);t.addEventListener(`abort`,onAbort,{once:!0}),t.aborted&&onAbort();try{return await Promise.race([n.promise,e])}finally{t.removeEventListener(`abort`,onAbort)}}export{assertExclusiveTurnInput,collectPendingAuthorizations,createAbortSignal,createActiveTurn,createSubmissionId,followSteeredTurns,isAbortError,isSettledSessionTail,summarizeUserContent,toTerminalStreamFailureError,waitWithSignal};
|