eve 0.66.0 → 0.66.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/dist/src/channel/forwarded-principal.d.ts +26 -6
- package/dist/src/channel/forwarded-principal.js +1 -1
- package/dist/src/chunks/{use-eve-agent-BUeSjwIk.js → use-eve-agent-Di1u2zKu.js} +24 -4
- package/dist/src/chunks/{use-eve-agent-ydPlURM4.js → use-eve-agent-PbSMyJ6e.js} +24 -4
- package/dist/src/cli/commands/deploy.d.ts +3 -1
- package/dist/src/cli/commands/deploy.js +1 -1
- package/dist/src/cli/commands/extension-build.js +1 -1
- package/dist/src/cli/commands/integration-connect.js +1 -1
- package/dist/src/cli/commands/register-project-commands.js +1 -1
- package/dist/src/cli/commands/registry-project.d.ts +2 -1
- package/dist/src/cli/commands/registry-project.js +2 -2
- package/dist/src/cli/commands/registry.js +1 -1
- package/dist/src/cli/commands/trace-detail.d.ts +5 -25
- package/dist/src/cli/commands/trace-detail.js +1 -1
- package/dist/src/cli/commands/trace.js +2 -2
- package/dist/src/cli/commands/vercel-non-interactive.d.ts +7 -0
- package/dist/src/cli/commands/vercel-non-interactive.js +1 -1
- package/dist/src/cli/dev/run-interactive-ui.js +1 -1
- package/dist/src/cli/dev/tui/argument-typeahead.d.ts +1 -1
- package/dist/src/cli/dev/tui/argument-typeahead.js +1 -1
- package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
- package/dist/src/cli/dev/tui/registry-result-message.js +1 -1
- package/dist/src/cli/dev/tui/remote-auth.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +2 -2
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.d.ts +3 -1
- package/dist/src/cli/dev/tui/setup-commands.js +1 -1
- package/dist/src/cli/dev/tui/setup-panel.d.ts +14 -0
- package/dist/src/cli/dev/tui/setup-panel.js +4 -4
- package/dist/src/cli/dev/tui/subagent-pump.d.ts +2 -10
- package/dist/src/cli/dev/tui/subagent-pump.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +2 -2
- package/dist/src/cli/dev/tui/terminal-renderer.js +10 -10
- package/dist/src/cli/dev/tui/traces/trace-conversation.js +1 -1
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/client/client-error.js +1 -1
- package/dist/src/client/open-stream.d.ts +3 -2
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session.d.ts +16 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/discover/filesystem.d.ts +2 -0
- package/dist/src/discover/filesystem.js +1 -1
- package/dist/src/discover/grammar.d.ts +4 -2
- package/dist/src/discover/grammar.js +1 -1
- package/dist/src/discover/sandbox.js +1 -1
- package/dist/src/evals/session.d.ts +3 -2
- package/dist/src/evals/session.js +1 -1
- package/dist/src/evals/types.d.ts +8 -2
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/types.d.ts +12 -4
- package/dist/src/execution/cancel-indexed-session-tasks-step.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/route-child-delivery.js +2 -2
- package/dist/src/execution/session/admission.js +1 -1
- package/dist/src/execution/session/finalization.js +1 -1
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/input-queue.d.ts +12 -10
- package/dist/src/execution/session/input-queue.js +1 -1
- package/dist/src/execution/session/next-input.js +1 -1
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session/turn-step-result.d.ts +3 -1
- package/dist/src/execution/session/turn-step-result.js +1 -1
- package/dist/src/execution/session/turn-step-types.d.ts +7 -2
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session/turn.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/tasks/parent/control-shared.js +1 -1
- package/dist/src/execution/tasks/parent/dispatch.js +1 -1
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.d.ts +1 -0
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/ask-question-workflow.js +1 -1
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/execution/tools/subagent/accept-event-step.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-preparation.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-step.js +1 -1
- package/dist/src/execution/tools/subagent/task-cancel.d.ts +1 -1
- package/dist/src/execution/tools/subagent/task-cancel.js +1 -1
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/turn-tag-state.d.ts +2 -2
- package/dist/src/harness/workflow-tool-runs.d.ts +33 -5
- package/dist/src/harness/workflow-tool-runs.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/instrumentation-layout.js +1 -1
- package/dist/src/internal/model-auth/vercel-cli.d.ts +2 -0
- package/dist/src/internal/model-auth/vercel-cli.js +1 -1
- package/dist/src/internal/nitro/host/build-extension.js +1 -1
- package/dist/src/internal/nitro/host/extension-build-lock.d.ts +9 -0
- package/dist/src/internal/nitro/host/extension-build-lock.js +1 -0
- 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-declarations.js +1 -1
- package/dist/src/internal/nitro/host/extension-distribution.js +1 -1
- package/dist/src/internal/nitro/host/extension-state-usage.d.ts +2 -2
- package/dist/src/internal/nitro/host/extension-state-usage.js +1 -1
- package/dist/src/internal/nitro/host/prepare-application-host.d.ts +5 -4
- package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
- package/dist/src/internal/nitro/host/types.d.ts +2 -2
- package/dist/src/internal/nitro/host/workspace-extensions.d.ts +31 -0
- package/dist/src/internal/nitro/host/workspace-extensions.js +1 -0
- package/dist/src/public/next/index.d.ts +10 -7
- package/dist/src/public/next/index.js +1 -1
- package/dist/src/public/next/server.d.ts +3 -0
- package/dist/src/public/next/server.js +2 -2
- package/dist/src/self-modification/extension/local-only.d.ts +5 -0
- package/dist/src/self-modification/extension/local-only.js +1 -0
- package/dist/src/self-modification/extension/subagents/agent/instructions.js +6 -6
- package/dist/src/self-modification/extension/subagents/agent/skills/trace_analysis.d.ts +10 -0
- package/dist/src/self-modification/extension/subagents/agent/skills/trace_analysis.js +19 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/inspect_trace.d.ts +128 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/inspect_trace.js +1 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/inspect_trace_spans.d.ts +80 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/inspect_trace_spans.js +1 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/registry_add.js +1 -1
- package/dist/src/self-modification/extension/subagents/agent/tools/search_traces.d.ts +53 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/search_traces.js +1 -0
- package/dist/src/self-modification/extension/trace-inspection.d.ts +15 -0
- package/dist/src/self-modification/extension/trace-inspection.js +1 -0
- package/dist/src/self-modification/sandbox.js +1 -1
- package/dist/src/setup/ask.d.ts +2 -0
- package/dist/src/setup/ask.js +1 -1
- package/dist/src/setup/boxes/link-project.d.ts +2 -0
- package/dist/src/setup/boxes/link-project.js +1 -1
- package/dist/src/setup/cli/option-row.d.ts +3 -1
- package/dist/src/setup/cli/option-row.js +1 -1
- package/dist/src/setup/flows/deploy.d.ts +1 -0
- package/dist/src/setup/flows/deploy.js +1 -1
- package/dist/src/setup/flows/install-vercel-cli.js +1 -1
- package/dist/src/setup/flows/login.js +1 -1
- package/dist/src/setup/flows/model-login-connection.js +1 -1
- package/dist/src/setup/flows/model-login.d.ts +4 -0
- package/dist/src/setup/flows/model-login.js +1 -1
- package/dist/src/setup/flows/vercel-model-login.js +1 -1
- package/dist/src/setup/integrations/runner.js +1 -1
- package/dist/src/setup/integrations/web/setup.d.ts +15 -10
- package/dist/src/setup/integrations/web/setup.js +30 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/create/web-template.d.ts +7 -3
- package/dist/src/setup/scaffold/create/web-template.js +39 -20
- package/dist/src/setup/scaffold/update/channels.js +2 -2
- package/dist/src/setup/slackbot.js +1 -1
- package/dist/src/setup/vercel-project.d.ts +2 -0
- package/dist/src/setup/vercel-project.js +0 -0
- package/dist/src/setup/vercel-trace-sampling.d.ts +3 -0
- package/dist/src/setup/vercel-trace-sampling.js +1 -0
- package/dist/src/subagents/parent-notification.d.ts +1 -1
- package/dist/src/subagents/remote-dispatch.d.ts +1 -0
- package/dist/src/subagents/remote-dispatch.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tasks/delivery-context.js +2 -2
- package/dist/src/tasks/notification.d.ts +6 -0
- package/dist/src/tasks/notification.js +1 -1
- package/dist/src/tracing/agent-trace-context-store.js +1 -1
- package/dist/src/tracing/local-trace-analysis.d.ts +51 -0
- package/dist/src/tracing/local-trace-analysis.js +1 -0
- package/dist/src/tracing/local-trace-discovery-index.d.ts +15 -0
- package/dist/src/tracing/local-trace-discovery-index.js +1 -0
- package/dist/src/tracing/local-trace-operations.d.ts +13 -0
- package/dist/src/tracing/local-trace-operations.js +1 -0
- package/dist/src/tracing/local-trace-query.d.ts +17 -0
- package/dist/src/tracing/local-trace-query.js +1 -0
- package/dist/src/tracing/local-trace-span-processor.js +1 -1
- package/dist/src/tracing/local-trace-summary.d.ts +31 -0
- package/dist/src/tracing/local-trace-summary.js +1 -0
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/concepts/project-structure.mdx +2 -4
- package/docs/concepts/sessions-runs-and-streaming.md +2 -2
- package/docs/evals/cases.mdx +1 -0
- package/docs/extensions.md +3 -1
- package/docs/guides/auth-and-route-protection.md +33 -1
- package/docs/guides/client/streaming.mdx +26 -0
- package/docs/guides/deployment/vercel.mdx +5 -5
- package/docs/guides/frontend/nextjs.mdx +20 -7
- package/docs/guides/frontend/overview.mdx +1 -1
- package/docs/guides/instrumentation/agent-runs.mdx +4 -4
- package/docs/guides/remote-agents.md +3 -1
- package/docs/install-integrations.mdx +1 -1
- package/docs/reference/agent-files.md +16 -0
- package/docs/reference/cli.md +1 -1
- package/docs/subagents/index.mdx +8 -2
- package/package.json +1 -1
- package/dist/src/internal/nitro/host/dev-workspace-extensions.d.ts +0 -18
- package/dist/src/internal/nitro/host/dev-workspace-extensions.js +0 -1
- package/dist/src/tasks/session-task-cohorts.d.ts +0 -7
- package/dist/src/tasks/session-task-cohorts.js +0 -1
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{buildAgentHeader}from"./agent-header.js";import{argumentTypeaheadCompletion,argumentTypeaheadFor,argumentTypeaheadLoadingLabel,argumentTypeaheadQuery,moveArgumentTypeaheadSelection,renderArgumentSuggestions,selectedArgumentSuggestion}from"./argument-typeahead.js";import{detectMarkdownRendering}from"./markdown.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.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,KillRing,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{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{enterBadge,flowMessageRows,renderAcknowledgeQuestion,
|
|
2
|
-
`);if(this.#N){t!==this.#P&&(this.#P=t,this.#
|
|
1
|
+
import{buildAgentHeader}from"./agent-header.js";import{argumentTypeaheadCompletion,argumentTypeaheadFor,argumentTypeaheadLoadingLabel,argumentTypeaheadQuery,moveArgumentTypeaheadSelection,renderArgumentSuggestions,selectedArgumentSuggestion}from"./argument-typeahead.js";import{detectMarkdownRendering}from"./markdown.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.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,KillRing,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{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{enterBadge,flowMessageRows,renderAcknowledgeQuestion,renderFlowDrawer,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompleteOsc,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil}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{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{toErrorMessage}from"#shared/errors.js";import{initialSelectState,orderedSelection,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.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`}function turnActivityLabel(e){return e===void 0?`Thinking`:e.runningTools.size>0?`Running`:e.modelActivity}function updateTurnActivity(e,t){switch(t.type){case`turn-start`:case`step-start`:case`reasoning-delta`:e.modelActivity=`Thinking`;break;case`assistant-delta`:case`tool-call-preparing`:e.modelActivity=`Generating`;break;case`assistant-complete`:t.text?.trim()&&(e.modelActivity=`Generating`);break;case`tool-call`:e.runningTools.add(t.toolCallId),e.modelActivity=`Thinking`;break;case`tool-result`:case`tool-error`:case`tool-rejected`:e.runningTools.delete(t.toolCallId)}}const incompletePasteFlushMs=1e3,STATUS={processing:`Thinking`,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=new KillRing;#W=!1;#G;#K;#q;#J=new Map;#Y=new Map;#X=!1;#Z=!1;#Q=new TurnClock;#$;#ee=EMPTY_LINE;#te=!1;#ne={kind:`idle`};#re;#ie=STATUS.processing;#ae;#oe=`eve`;#se=!1;#ce=!1;#le=!1;#ue=!1;#de=!1;#fe=!1;#pe=!1;#me;#he=!0;#ge=0;#_e=Date.now();#ve;#ye;#be;#xe=!1;#Se;#Ce=``;#we=new StringDecoder(`utf8`);#Te;#Ee;#De;#Oe=!1;#ke=!1;#Ae;#je;#Me;#Ne;#Pe;#Fe;#Ie;#Le=``;#Re=``;#ze;#Be;#Ve;#He=!1;#Ue;#We=0;#Ge;#Ke;#qe;#Je;#Ye;#Xe;#Ze=new MessageQueue;#Qe;#$e;#et=!1;#tt;#nt;#rt=!1;#it;#at;#ot;#st;#ct;setupFlow={begin:(e,t)=>this.#_t(e,t),setNavigation:e=>this.#vt(e),end:e=>this.#yt(e?.preserveDiagnostics??!0),readSelect:e=>this.#bt(e),readEditableSelect:e=>this.#St(e),readProviderPicker:e=>this.#Ct(e),readText:e=>this.#wt(e),readAcknowledge:e=>this.#Tt(e),readChoice:e=>this.#xt(e),setStatus:e=>this.#Nt(e),renderLine:(e,t)=>this.#Pt(e,t),replaceContent:e=>this.#Ft(e),renderOutput:e=>this.#It(e),withInheritedStdio:e=>this.#Lt(e),withExclusiveTerminal:e=>this.#Lt(e),waitForInterrupt:e=>this.#At(e)};traceViewer={open:e=>this.#zt(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.#Me=e?.contextSize,this.#d=e?.captureForeignOutput??this.#t===process.stdout,this.#f=e?.diagnostics,this.#me=e?.onExitRequest,this.#q=e?.argumentSuggestions,this.#m=e?.logs??`none`,this.#p=e?.availablePromptCommands??PROMPT_COMMANDS}#lt(e){this.#G=typeaheadFor(this.#p,e,this.#G);let t=argumentTypeaheadQuery(e);if(t===void 0||this.#q===void 0){this.#K=void 0;return}let n=this.#J.get(t.command);if(n===void 0){this.#J.set(t.command,{kind:`loading`,visible:!1});let e=t.command;this.#Y.set(e,setTimeout(()=>{this.#Y.delete(e),this.#J.get(e)?.kind===`loading`&&(this.#J.set(e,{kind:`loading`,visible:!0}),this.#Mn())},500)),this.#q(e).catch(()=>[]).then(t=>{let n=this.#Y.get(e);n!==void 0&&clearTimeout(n),this.#Y.delete(e),this.#J.set(e,{kind:`ready`,suggestions:t}),this.#W&&this.#lt(this.#B),this.#Mn()}),this.#K=void 0;return}if(n.kind===`loading`){this.#K=void 0;return}this.#K=argumentTypeaheadFor(t,n.suggestions,this.#K)}#ut(e){let t=argumentTypeaheadQuery(this.#B),n=t===void 0?void 0:this.#J.get(t.command);return n?.kind===`loading`&&n.visible&&t!==void 0?[clip(this.#i.colors.dim(`Loading ${argumentTypeaheadLoadingLabel(t.command)}…`),e)]:this.#K===void 0?(this.#G===void 0?void 0:inlineCommandHint(this.#G))===void 0&&this.#G!==void 0&&isTypeaheadOpen(this.#G)?renderCommandSuggestions(this.#G,this.#i,e):[]:renderArgumentSuggestions(this.#K,this.#i,e)}setStartupPhase(e){this.#O=e,e===void 0?this.#on():this.#in(),this.#Mn()}renderAgentHeader(e){this.#M=void 0,this.#oe=e.name,(this.#D?.info?.agent.model.routing.kind!==`dynamic`||e.info?.agent.model.routing.kind!==`dynamic`)&&(this.#Ye=void 0),this.#D=e,this.#Ht();let t=this.#Ln().join(`
|
|
2
|
+
`);if(this.#N){t!==this.#P&&(this.#P=t,this.#un({kind:`agent-header`,body:t,live:!1})),this.#Mn();return}this.#N=!0,this.#P=t,this.#n.flush(this.#Ln(),this.#Hn(this.#Zn()))}beginStartupDraft(e){this.#Ht({title:e.title}),this.#W=!0,this.#X=!0,this.#O=`starting`,this.#M={name:e.title},this.#j=Date.now();let t=lineOf(stripPromptControlCharacters(e.initialDraft??``));this.#k=t,this.#ft(t),this.#tn(),this.#in(),this.#Mn();let apply=e=>{t=e,this.#k=e,this.#rn(),this.#ft(t),this.#Mn()};this.#A=e=>{if(e.type===`escape`&&this.#at!==void 0){this.#at(`escape`);return}if(e.type===`ctrl-c`&&this.#at!==void 0){this.#Rt(),this.#at(`ctrl-c`);return}let n=this.#U.apply(t,e,{multiline:!0});if(n!==void 0){apply(n);return}if(e.type===`enter`&&t.text.trim().length>0){this.#Ze.enqueue(t.text)&&apply(EMPTY_LINE);return}e.type===`ctrl-c`&&this.#me?.()},this.#dt()}#dt(){this.#k!==void 0&&this.#A!==void 0&&(this.#Qt(),this.#ft(this.#k),this.#W=!0,this.#Se=this.#A,this.#Gt())}finishStartupDraft(){let e={draft:this.#k?.text??this.#B,queuedPrompt:this.#Ze.takePrompt()};return this.#k=void 0,this.#A=void 0,this.#Kt(),this.#nn(),this.#W=!1,this.#X=!1,e}async readPrompt(e){this.#Ht(e),this.#ln(),this.#fn(),this.#W=!0,this.#X=!0,this.#ne={kind:`idle`},this.#ie=``,this.#fe=this.#pe,this.#pe=!1;let t=this.#Ze.restoreDraft()?.split(`
|
|
3
3
|
`).map(stripPromptControlCharacters).join(`
|
|
4
|
-
`),n=stripPromptControlCharacters(e?.initialDraft??this.#$.text),r=t===void 0?n:n.length===0?t:`${t}\n\n${n}`,i=lineOf(r);return this.#$=EMPTY_LINE,this.#H.begin(i.text),this.#dt(i),this.#ct(i.text),this.#en(),this.#jn(),await new Promise((e,t)=>{this.#ne=t;let apply=e=>{i=e,this.#nn(),this.#dt(i),this.#ct(e.text),this.#jn()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#G=void 0,this.#tn(),this.#Ut(),t(interruptedError())},suggestions=()=>this.#G!==void 0&&isTypeaheadOpen(this.#G)?this.#G:void 0,argumentSuggestions=()=>this.#K?.suggestions.length?this.#K:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#xe=t=>{t.type!==`ctrl-c`&&this.#de&&(this.#de=!1,this.#jn());let n=this.#U.apply(i,t,{multiline:!0});if(n!==void 0){apply(n);return}switch(t.type){case`up`:case`ctrl-p`:{let e=argumentSuggestions();if(e!==void 0){this.#K=moveArgumentTypeaheadSelection(e,-1),this.#jn();break}let t=suggestions();if(t!==void 0){this.#G=moveTypeaheadSelection(t,-1),this.#jn();break}let n=movePromptLine(i,`up`);n===void 0?recall(this.#H.previous(i.text)):apply(n);break}case`down`:case`ctrl-n`:{let e=argumentSuggestions();if(e!==void 0){this.#K=moveArgumentTypeaheadSelection(e,1),this.#jn();break}let t=suggestions();if(t!==void 0){this.#G=moveTypeaheadSelection(t,1),this.#jn();break}let n=movePromptLine(i,`down`);n===void 0?recall(this.#H.next()):apply(n);break}case`tab`:{let e=argumentSuggestions(),t=e===void 0?void 0:selectedArgumentSuggestion(e);if(e!==void 0&&t!==void 0){apply(lineOf(argumentTypeaheadCompletion(e,t)));break}let n=highlighted();n!==void 0&&apply(lineOf(typeaheadCompletion(n)));break}case`escape`:{if(this.#K!==void 0){this.#K=void 0,this.#jn();break}let e=suggestions();e!==void 0&&(this.#G=dismissTypeahead(e),this.#jn());break}case`enter`:{let t=argumentSuggestions(),n=t===void 0?void 0:selectedArgumentSuggestion(t),r=highlighted();if(t!==void 0&&n?.next!==void 0&&t.completed.length===0){apply(lineOf(`${argumentTypeaheadCompletion(t,n)} `));break}if(t===void 0&&r!==void 0&&this.#q!==void 0&&(r.name===`add`||r.name===`model`)){apply(lineOf(typeaheadCompletion(r)));break}let a=t!==void 0&&n!==void 0?argumentTypeaheadCompletion(t,n):r!==void 0&&parsePromptCommand(i.text)===null?typeaheadCompletion(r).trimEnd():i.text;if(a.trim().length===0)break;this.#G=void 0,this.#K=void 0,this.#H.add(a),this.#W=!1,this.#tn(),this.#re=STATUS.processing,isPromptControlCommand(a)?this.#ln({kind:`command`,body:stripTerminalControls(a.trim()),live:!1}):(this.#in(),this.#un(a),this.#We=a,this.#Z.arm()),this.#dt(EMPTY_LINE),this.#jn(),this.#Gt(),e(a);break}case`ctrl-d`:i.text.length===0?(this.#Lt(),interrupt()):apply(deleteForward(i));break;case`ctrl-l`:this.#Pn();break;case`ctrl-r`:this.#jn();break;case`ctrl-c`:if(this.#de){this.#Lt(),interrupt();break}this.#de=!0,apply(EMPTY_LINE)}},this.#Wt()})}#dt(e){this.#B=e.text,this.#V=e.cursor}takeQueuedPrompt(){let e=this.#Xe.view().steering,t=this.#Xe.takePrompt();return t!==void 0&&(this.#tt=e?`steer`:`queue`),t}async renderStream(e,t){this.#Vt(t),this.#_.clear(),this.#W=!1,this.#te.kind!==`waiting`&&(this.#te={kind:`waiting`,startedAtMs:Date.now()}),this.#re=this.#L>0?STATUS.connectionAuth:STATUS.processing,this.#fn(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#f?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#Z.armed&&this.#Z.arm(),this.#le=!1,this.#$e=!1,this.#nt=!1,this.#rt=t?.submittedPrompt,this.#Xe.beginTurn(),this.#Ze=e.cancel,this.#Qe=e.steer,this.#ke=void 0,this.#Ae=void 0,this.#Me=void 0,this.#Ne=void 0,this.#Pe=Date.now();let n={text:new Map,reasoning:new Map,tools:new Map,modelActivity:`Thinking`,runningTools:new Set,cancelled:!1,restoreCancelledPrompt:!0};this.#Q=n;let r={tools:t?.tools??this.#o,reasoning:t?.reasoning??this.#s,assistantResponseStats:t?.assistantResponseStats??this.#u};this.#rn(),this.#ee=!0,this.#jn();let i=new Promise(e=>{this.#Ee=e});this.#xe=e=>this.#Qt(e),this.#Wt();try{for await(let t of takeUntil(iterateTUIStream(e.events),i)){if(this.#le)break;this.#bn(t,r,n)}}catch(e){let t=summarizeKnownError(e);t===null?this.#pn(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#pn(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#Ee=void 0,this.#le&&e.abort?.(),this.#Ze=void 0,this.#Qe=void 0,this.#Gt(),this.#ee=!1,this.#Q=void 0,this.#te.kind===`waiting`&&(this.#te={kind:`idle`}),this.#cn(),this.#re=completedTurnStatus({interrupted:this.#le,cancelled:this.#$e,continueSession:t?.continueSession===!0}),this.#Dn(n),(this.#le||n.cancelled)&&this.#En(n),this.#yn(),this.#cn(),this.#f?.reportStats(),this.#jn(),t?.continueSession||this.#Ut()}}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,modelActivity:`Thinking`,runningTools:new Set,cancelled:!1,restoreCancelledPrompt:!1};try{for await(let t of iterateTUIStream(e.events))this.#bn(t,n,r)}catch(e){let t=summarizeKnownError(e);t===null?this.#pn(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#pn(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#Dn(r),r.cancelled&&this.#En(r),this.#yn(),this.#cn(),this.#f?.reportStats(),this.#jn()}}async readToolApproval(e,t){return this.#Vt(t),this.#an(),this.#W=!1,this.#te={kind:`idle`},this.#re=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#le=!1,this.#jn(),await new Promise((t,n)=>{this.#ne=n,this.#xe=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#in(),this.#re=STATUS.processing,this.#Gt(),this.#jn(),t({approved:!0})):n===`n`&&(this.#in(),this.#re=STATUS.processing,this.#pt(e.toolCallId),this.#Gt(),this.#jn(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#jn();break;case`ctrl-c`:this.#le=!0,this.#Ut(),n(interruptedError())}},this.#Wt()})}async readInputQuestion(e,t){this.#Vt(t),this.#an(),this.#W=!1,this.#Y=!1,this.#te={kind:`idle`},this.#le=!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.#me},this.#i,t),renderTextSection=()=>{this.#hn({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#en():(this.#tn(),this.#nn())};s===`overlay`?(s=`overlay`,this.#W=!1,this.#_n(o),this.#Ge=overlayPanel,this.#re=``,syncFreeformCaret(),this.#jn()):(s=`text`,this.#Ge=void 0,renderTextSection(),this.#W=!0,this.#dt(l),this.#re=``,this.#en(),this.#jn());let finalize=t=>{this.#Ge=void 0,this.#hn({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.#W=!1,this.#in(),this.#re=STATUS.processing,this.#tn(),this.#Gt(),this.#jn();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Ge=void 0,this.#hn({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Skipped. The question stays open.`)}`,preformatted:!0,live:!1}),this.#W=!1,this.#re=``,this.#tn(),this.#Gt(),this.#jn(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#jn())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#ne=r,u=t,this.#xe=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#nn(),s===`text`&&this.#dt(l),this.#jn();return}this.#le=!0,this.#Ge=void 0,this.#tn(),this.#Ut(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#jn();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.#nn(),this.#jn();break}dismiss();break;default:if(isOnFreeformRow()){let e=this.#U.apply(l,t);e!==void 0&&(l=e,this.#nn(),this.#jn());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.#jn())}}return}let a=this.#U.apply(l,t,{multiline:!0});if(a!==void 0){l=a,this.#nn(),this.#dt(l),this.#jn();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#nn(),this.#dt(l),this.#jn());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.#nn(),this.#dt(l),this.#jn();break}dismiss()}},this.#Wt()})}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.#mn(e.callId,e.subagentName),this.#c===`collapsed`){this.#jn();return}this.#gn({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.#jn()}}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.#mn(e.callId,e.subagentName),this.#c===`collapsed`){this.#jn();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#wn({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.#gn(r),this.#ft(e.callId),this.#jn()}#ft(e){applyCohortLiveness(this.#h.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#_n(subagentToolSectionId(e.callId,e.childCallId)),this.#jn()}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.#mn(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.#jn()}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.#vn(e.callId),this.#cn(),this.#jn()}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.#cn(),this.#jn()}}markChildToolCallId(e){this.#y.add(e);let t=this.#b.get(e);t!==void 0&&(this.#_n(t),this.#b.delete(e),this.#jn())}#pt(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.#hn({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.#jn()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#L)return;let n=this.#L>0;this.#L=t,t>0?(this.#re=STATUS.connectionAuth,this.#jn()):n&&(this.#re=STATUS.processing,this.#jn())}setVercelStatus(e){this.#R=e,this.#jn()}setRemoteConnectionStatus(e){this.#z=e,this.#jn()}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.#mt(),this.#X=!1,this.#We=void 0,this.#ze=void 0,this.#L=0,this.#ke=void 0,this.#Ae=void 0,this.#Me=void 0,this.#Ne=void 0,this.#Pe=void 0,this.#oe&&(this.#n.clearAll(),this.#jn())}renderSessionBoundary(){this.#dn(),this.#mt();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#ln({kind:`session-boundary`,body:n,live:!1}),this.#jn()}#mt(){this.#Je=void 0,this.#Ye=void 0,this.#y.clear(),this.#b.clear(),this.#E.clear(),this.#C.clear(),this.#w.clear(),this.#S.clear(),this.#Xe.reset(),this.#tt=void 0,this.#T.clear(),this.#Z.reset(),this.#cn()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Vt(),this.#ln({kind:`notice`,body:t,live:!1}),this.#jn())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#ht();return}this.#Vt(),this.#qe=t,this.#jn()}clearSetupWarning(){this.#ht()}#ht(){this.#qe!==void 0&&(this.#qe=void 0,this.#jn())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#Vt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#ln(r),this.#jn()}renderCommandResult(e,t){let n=stripAnsi(e);n.trim().length!==0&&(this.#Vt(),this.#ln({kind:`result`,body:n,live:!1,status:t===`success`?`done`:void 0}),this.#jn())}#gt(e,t=`spinner`){this.#Vt(),this.#k===void 0&&(this.#W=!1),this.#te={kind:`idle`},this.#re=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ke={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#rn(),this.#jn()}#_t(e){this.#Ke!==void 0&&(this.#Ke.navigation=e,this.#jn())}#vt(e){this.#it=void 0,this.#jt();let t=this.#Ke;if(t!==void 0){if(this.#Ke=void 0,this.#k===void 0?this.#an():this.#ut(),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.#ln({kind:`flow`,title:`info`,body:e.join(`
|
|
5
|
-
`),live:!1}),this.#ln({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#jn()}}async#yt(e){let t=this.#Tt(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.#jn()},loadSearch=async(e,t)=>{l=!0,c=void 0;let o=++u;this.#jn();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.#jn())}},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.#Rn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#jn(),await this.#Ot((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.#jn();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.#jn();return;case`update`:s=m.select,c=void 0,this.#jn();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.#jn();return;case`ignore`:return}}).promise}#bt(e){this.#Vt();let t=this.#Et();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.#jn();let r=this.#Ot((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.#jn();return;case`repaint`:this.#jn();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#xt(e){let t=this.#Tt(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.#me,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.#en():(i=lineOf(``),this.#tn())};return syncEditableRow(),this.#jn(),await this.#Ot((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#nn(),this.#jn()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#jn()},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.#jn();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.#jn();return;case void 0:}if(!onEditableRow())return;let s=this.#U.apply(i,t);s!==void 0&&applyEditor(s)},()=>this.#tn()).promise}async#St(e){this.#U.clear();let t=this.#Tt(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.#me,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.#en():this.#tn()};return syncCaret(),this.#jn(),await this.#Ot((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.#jn();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#jn();return;case`validate`:{n=o.state,syncCaret(),this.#jn();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.#jn();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.#nn(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#tn()}).promise}async#Ct(e){e.mask===!0&&this.#U.clear();let t=this.#Tt(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.#me)},this.#en(),this.#jn(),await this.#Ot((t,i)=>{let apply=e=>{n=e,r=void 0,this.#nn(),this.#jn()},a=e.mask?applyLineEditorKey(n,t):this.#U.apply(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.#jn();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#jn();return}i(t);return}default:return}},()=>this.#tn()).promise}async#wt(e){let t=this.#Tt(e.message);return t.question=t=>renderAcknowledgeQuestion({message:``,lines:e.lines},this.#i,t),this.#jn(),await this.#Ot((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#jn();return;default:return}}).promise}#Tt(e){this.#Vt(),this.#W=!1,this.#te={kind:`idle`},this.#re=``;let t=this.#Et();return t.questionTitle=stripTerminalControls(e),t.status!==void 0&&(t.status=void 0,t.summary=void 0,t.preview=void 0),t}#Et(){return this.#Ke===void 0&&(this.#Ke={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Ke}#Dt(){this.#Ke?.implicit===!0?this.#Ke=void 0:this.#Ke!==void 0&&(this.#Ke.question=void 0,this.#Ke.questionTitle=void 0,this.#Ke.hideLinesWhileQuestion=!1),this.#xe=void 0,this.#Gt(),this.#k===void 0?this.#Ke!==void 0&&this.#At():this.#ut(),this.#Ke===void 0&&this.#jn()}#Ot(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Dt(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Dt(),i(e))};return this.#Zt(),this.#xe=t=>{t.type===`ctrl-c`&&this.#Lt(),e(t,settle,reject)},this.#Wt(),{promise:a,settle}}#kt(e){let t,n=new Promise(e=>{t=e});return this.#it=t,this.#At(e?.interruptible??!0),{promise:n,dispose:()=>{this.#it===t&&(this.#it=void 0,this.#jt())}}}#At(e=!0){if(this.#k!==void 0){this.#ut();return}if(this.#it===void 0)return;let consumer=t=>{if(e&&(t.type===`ctrl-c`||t.type===`escape`)){t.type===`ctrl-c`&&this.#Lt();let e=this.#it;this.#it=void 0,this.#jt(),e?.(t.type===`ctrl-c`?`ctrl-c`:`escape`);return}t.type===`ctrl-r`&&this.#jn()};this.#at=consumer,this.#Zt(),this.#xe=consumer,this.#Wt()}#jt(){this.#at!==void 0&&(this.#xe===this.#at&&this.#Gt(),this.#at=void 0)}#Mt(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.#Ke!==void 0){this.#Ke.status=t,t===void 0&&(this.#Ke.preview=void 0),this.#jn();return}if(!(this.#W||this.#ee)){if(t===void 0){this.#te={kind:`idle`},this.#ie=void 0,this.#an(),this.#jn();return}this.#Vt(),this.#in(),this.#ie=t.text,this.#jn()}}#Nt(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Ke;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.#jn();return}this.#Vt(),this.#ln({kind:`flow`,title:t,body:n,live:!1}),this.#jn()}#Pt(e){let t=this.#Ke;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.#jn())}#Ft(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Ke;if(n===void 0){this.#Nt(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#jn()}async#It(e){this.#Se=``,this.#Zt(),this.#it=void 0,this.#jt(),this.#Gt(),this.#on(),this.#n.clear(),this.#$n(),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.#Se=``,this.#Zt(),this.#n.hideCursor(),this.#Qn(),this.#Ke===void 0?this.#cn():(this.#rn(),this.#At()),this.#n.reset(),this.#jn()}}setSessionId(e){this.#et=e}shutdown(){if(this.#Ut(),this.#se&&!this.#ce){this.#ce=!0;let e=this.#et===void 0?``:` ${this.#i.glyph.dot} session ${this.#et}`;this.#t.write(`${this.#i.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}suspendPromptForInput(){this.#$={cursor:this.#V,text:this.#B},this.#Ut()}requestInterrupt(){this.#le=!0,this.#Ke!==void 0&&this.#xe?.({type:`ctrl-c`}),this.#Ee?.(),this.#Ut()}exitRequested(){return this.#ue}#Lt(){this.#ue=!0,this.#pe?.()}async#Rt(e){if(this.#ot!==void 0||!this.#oe)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#Xn(),height:this.#Zn()}),paint:e=>this.#r.paint(e,this.#Zn()),tracingDisabled:process.env.EVE_TRACES===`off`,copyText:e=>copyTextToClipboard(e,e=>this.#r.writeRaw(e)),terminalBackground:this.#st});this.#ot=t,this.#r.enter(),this.#i.color&&this.#r.writeRaw(BACKGROUND_COLOR_QUERY),await new Promise(e=>{this.#Bt=e,this.#xe=e=>{t.handleKey(e)===`close`&&this.#zt()},this.#Wt(),t.start()})}#zt(){let e=this.#ot;if(e===void 0)return;this.#ot=void 0,e.dispose(),this.#Gt(),this.#r.exit(),this.#n.hideCursor(),this.#jn(),this.#n.showCursor();let t=this.#Bt;this.#Bt=void 0,t?.()}#Bt;#Vt(e){this.#ae=e?.title??this.#ae,e?.contextSize!==void 0&&(this.#je=e.contextSize),!this.#oe&&(this.#oe=!0,this.#se=!0,this.#n.reset(),this.#n.hideCursor(),this.#Qn(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#Te=()=>this.#jn(),this.#t.on(`resize`,this.#Te),process.on(`exit`,this.#Ht))}#Ht=()=>{this.#oe&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#Ut(){this.#zt();let e=this.#ne;if(this.#ne=void 0,e?.(interruptedError()),this.#Gt(),this.#tn(),this.#on(),this.#ye!==void 0&&(clearTimeout(this.#ye),this.#ye=void 0),this.#be=!1,this.#sr(),this.#oe){this.#lr();for(let e of this.#h)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#jn(),this.#n.clear(),this.#n.showCursor(),this.#$n(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#Te&&=(this.#t.off(`resize`,this.#Te),void 0),process.off(`exit`,this.#Ht),this.#oe=!1}}#Wt(){this.#e.off(`data`,this.#Kt),this.#e.on(`data`,this.#Kt),this.#Se.length>0&&queueMicrotask(()=>{this.#xe!==void 0&&this.#Se.length>0&&(this.#Yt(),this.#qt())})}#Gt(){this.#e.off(`data`,this.#Kt),this.#Zt(),this.#xe=void 0}#Kt=e=>{this.#Zt(),this.#Se+=this.#Ce.write(e),this.#Yt(),this.#qt()};#qt(){if(this.#Se===`\x1B`){this.#we=setTimeout(()=>{this.#Se===`\x1B`&&(this.#Se=``,this.#Jt({type:`escape`}))},30),this.#we.unref?.();return}if(isIncompletePaste(this.#Se)){let e=this.#Se;this.#we=setTimeout(()=>{if(this.#Se!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#Se=``,t.length>0&&this.#Jt({type:`text`,value:t,framing:`bracketed-paste`})},incompletePasteFlushMs),this.#we.unref?.();return}if(isIncompleteOsc(this.#Se)){let e=this.#Se;this.#we=setTimeout(()=>{this.#Se===e&&(this.#Se=``)},incompletePasteFlushMs),this.#we.unref?.()}}#Jt(e){this.#U.interruptYank(e),this.#xe?.(e)}#Yt(){for(;this.#Se.length>0;){let e=nextKey(this.#Se);if(e.incomplete)return;if(this.#Se=this.#Se.slice(e.consumed),e.key!==void 0&&e.key.type!==`ignore`){if(e.key.type===`osc`){this.#Xt(e.key.value);continue}this.#Jt(e.key)}}}#Xt(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#st=t,this.#ot?.setTerminalBackground(t))}#Zt(){this.#we&&=(clearTimeout(this.#we),void 0)}#Qt(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#jn();break;case`enter`:{let e=this.#$.text;if(e.trim().length===0)break;if(parsePromptCommand(e)?.type===`cancel`&&this.#Ze!==void 0){this.#$=EMPTY_LINE,this.#Xe.requestCancellation(),this.#nt=!0,this.renderCommandInvocation(e.trim()),this.renderCommandResult(`Turn cancellation requested.`),this.#Ze(),this.#jn();break}let t=this.#Qe;t!==void 0&&parsePromptCommand(e)===null?(this.#$=EMPTY_LINE,this.#$t(e,t)):this.#Xe.enqueue(e)&&(this.#$=EMPTY_LINE),this.#jn();break}case`ctrl-c`:case`escape`:if(e.type===`ctrl-c`&&this.#Xe.view().cancelling){this.#le=!0,this.#fe=!0,this.#te={kind:`idle`},this.#re=`Interrupted`,this.#Ee?.(),this.#jn();break}if(this.#Xe.idle&&this.#Ze===void 0)break;if(this.#Xe.handleEscape()===`steer`){let e=this.#Qe;if(e!==void 0){let t=this.#Xe.takeSteering();this.#$t(t,e)}}else this.#nt=!0,this.#Ze?.();this.#jn();break;default:{let t=this.#U.apply(this.#$,e,{multiline:!0});t!==void 0&&(this.#$=t,this.#jn());break}}}#$t(e,t){this.#tt=`steer`,this.#fn(e),t(e).catch(t=>{this.#Xe.restoreSteering(e),this.#pn(`Steering failed`,toErrorMessage(t)),this.#jn()})}#en(){this.#tn(),this.#nn(),this.#_e=setInterval(()=>{this.#me=!this.#me,this.#jn()},500),this.#_e.unref?.()}#tn(){this.#_e&&=(clearInterval(this.#_e),void 0),this.#me=!0}#nn(){this.#me=!0}#rn(){this.#on(),this.#ve=setInterval(()=>{this.#he+=1,this.#jn()},90),this.#ve.unref?.()}#in(){let e=Date.now();this.#ge=e,this.#te={kind:`waiting`,startedAtMs:e},this.#rn()}#an(){this.#sn()||this.#on()}#on(){this.#ve&&=(clearInterval(this.#ve),void 0)}#sn(){return this.#h.some(e=>e.live&&e.subagentCallId!==void 0&&(this.#C.has(e.subagentCallId)||this.#w.has(e.subagentCallId)))}#cn(){this.#sn()?this.#rn():!this.#ee&&this.#te.kind===`idle`&&this.#on()}#ln(e){e.id!==this.#ze?.id&&this.#lr(),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)}#un(e){this.#X=!0,this.#ln({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#jn()}#dn(){let e=this.#Z.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#Un(e.elapsedMs)}`,n=this.#Ae??0;if(this.#je!==void 0&&this.#je>0&&n>0){let e=Math.round(n/this.#je*100);t+=` ${this.#i.glyph.dot} ${e}% context`}this.#ln({kind:`turn-stats`,body:t,live:!1})}#fn(e){if(e==null)return;let t=this.#tt;if(this.#tt=void 0,this.#We===e){this.#We=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#ln(n)}#pn(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.#ln(c),this.#jn()}#mn(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.#ln(i)}#hn(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.#ln(e)}#gn(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.#ln(e);return}e.id!==this.#ze?.id&&this.#lr(),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)}#_n(e){this.#h=this.#h.filter(t=>t.id!==e),this.#g.delete(e)}#vn(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))}#yn(){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)}#bn(e,t,n){let r=turnActivityLabel(n);switch(updateTurnActivity(n,e),e.type){case`turn-start`:e.turnId!==this.#Ye&&(this.#Ye=e.turnId,this.#Je=void 0,this.#jn());break;case`step-start`:this.#Je=typeof e.modelId==`string`&&stripTerminalControls(e.modelId.slice(0,256)).replace(/\s+/gu,` `).trim()||void 0,this.#jn();break;case`step-finish`:this.#f?.recordStepUsage(e.usage),e.usage!==void 0&&this.#Z.addUsage(e.usage),this.#Dn(n),this.#An(e.usage),this.#jn();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#xn(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.#xn(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.#Sn(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.#Sn(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#Cn({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.#Cn({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.#Cn({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#kn(e.toolCallId,n);if(r===void 0)break;this.#Cn({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#kn(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.#Cn({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#kn(e.toolCallId,n);if(r===void 0)break;this.#Cn({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#pn(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:if(n.cancelled=!0,!n.restoreCancelledPrompt)break;this.#$e=!0,!this.#nt&&this.#rt!==void 0&&this.#$.text.length===0&&(this.#$=lineOf(this.#rt),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#An(e.usage),this.#jn()}n===this.#Q&&turnActivityLabel(n)!==r&&this.#jn()}#xn(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#hn({id:e,kind:`assistant`,body:r,live:n}),this.#jn())}#Sn(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#hn({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#jn())}#Cn(e,t,n){if(n.tools.set(e.toolCallId,e),this.#y.has(e.toolCallId)||isPanelRoutedTool(e.toolName))return;let r=toolSectionId(e.toolCallId);this.#b.set(e.toolCallId,r);let i=this.#wn(e);this.#hn(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#On(n),this.#jn()}#wn(e){e.output!==void 0&&this.#T.observeRead(e.output);let t={};this.#Tn(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}#Tn(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)}#En(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)}}#Dn(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.#_n(r),this.#b.delete(t)}}#On(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)}#kn(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`}}#An(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#ke=(t??0)+(n??0)),this.#Ae=t??this.#Ae,this.#Me=n??this.#Me,this.#Me!=null&&this.#Pe!==void 0){let e=(Date.now()-this.#Pe)/1e3;e>0&&(this.#Ne=this.#Me/e)}}#jn(){if(this.#oe){if(this.#De){this.#Oe=!0;return}this.#De=!0;try{do this.#Oe=!1,this.#Mn();while(this.#Oe)}finally{this.#De=!1}}}#Mn(){if(!this.#oe)return;if(this.#ot!==void 0){this.#ot.repaint();return}let e=this.#Xn(),t=this.#Vn(e),n=this.#M===void 0?[]:this.#In(),r=Math.max(1,this.#Zn()-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.#dr(t.display))continue;let n=this.#Ln(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.#dr(t))continue;let n=this.#Ln(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)}#Nn(){if(!this.#oe)return;let e=this.#Xn(),t=this.#Vn(e),n=Math.max(1,this.#Zn()-t.length),r=this.#I,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#h)){if(this.#dr(t))continue;let n=this.#Ln(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.#In(),...this.#F],a)}logDisplayMode(){return this.#m}setLogDisplayMode(e){e!==this.#m&&(this.#m=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#Fn(),this.#oe&&this.#Nn())}flushDelayedDevBuildErrors(){let e=this.#Re;e!==void 0&&(this.#Re=void 0,this.#ln({kind:`log`,title:`stderr`,body:e,live:!0}),this.#jn())}#Pn(){this.#be=!0,this.#ye!==void 0&&clearTimeout(this.#ye),this.#ye=setTimeout(()=>{this.#be=!1,this.#ye=void 0,this.#jn()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#m)),this.#jn()}#Fn(){let e=this.#Xn();this.#F.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#v,{logCoalescing:`runs`})){if(this.#dr(n))continue;let r=this.#Ln(n,e,t);t=previousBlockOf(n),this.#F.push(...r)}this.#I=t}#In(){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.#Xn()};return e?.info!==void 0&&(n.info=e.info),buildAgentHeader(n)}#Ln(e,t,n){let r={renderMarkdown:this.#a,activityPulse:this.#zn(this.#ge,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}#Rn(){return this.#i.spinner[this.#he%this.#i.spinner.length]??``}#zn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#Bn(e,t){return e.indicator.kind===`spinner`?{glyph:this.#Rn(),color:`yellow`}:{glyph:this.#zn(e.indicator.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#Vn(e){let t=this.#i.colors,n=[``];if(this.#Ge!==void 0)return n.push(...this.#Ge(e),``),this.#qn(n,e),n;let r=this.#Ke;if(r!==void 0&&(this.#k===void 0||r.question!==void 0)){let t=this.#Bn(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.#Jn(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.#qe!==void 0&&n.push(...renderAttentionRows(this.#qe,e,this.#i),``);let i=renderMessageQueueRows({view:this.#Xe.view(),width:e,theme:this.#i,working:this.#ee});if(i.length>0&&n.push(...i,``),this.#W){let r=this.#G===void 0?void 0:inlineCommandHint(this.#G),i=this.#lt(e);this.#de&&n.push(clip(t.dim(`Press Ctrl+C again to exit`),e),``);let a=isPromptControlCommand(this.#B),o=r?t.dim(` ${r}`):``,s=[];this.#qn(s,e);let c=Math.max(1,this.#Zn()-1-n.length-1-i.length-s.length-(i.length>0?2:0)),l={text:this.#B,cursor:this.#V,width:e,theme:this.#i,caretVisible:this.#me,isCommand:a,ghost:o,maxRows:c};this.#Y&&this.#B.length===0&&(l.placeholder=this.#k===void 0?this.#X?``:`Send a message…`:`Message · Enter to queue`);let u=promptInputRows(l);return i.length>0&&u.at(-1)===``&&u.pop(),n.push(...u),i.length>0&&n.push(t.dim(this.#i.glyph.dash.repeat(e))),n.push(...i),i.length>0&&s.length>0&&n.push(t.dim(this.#i.glyph.dash.repeat(e))),n.push(...s),n}let a=this.#te.kind===`waiting`&&this.#ie===void 0;if(this.#ee||a){n.push(this.#Hn(e)),this.#Gn(n,e);let t=[];return this.#qn(t,e),!this.#ee&&t.length>0&&n.push(``),n.push(...t),n}if(this.#$.text.length>0)return this.#Kn(n,e,{inert:!1}),this.#qn(n,e),n;let o=this.#ie??(this.#re.length>0?this.#re:`Ready`),s=this.#Yn(),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.#qn(n,e),n}#Hn(e){let t=this.#i.colors,n=this.#te,r=this.#Z.startedAtMs??this.#Pe??(n.kind===`waiting`?n.startedAtMs:Date.now()),i=Math.max(0,Date.now()-r),a=i%1e3<500?this.#i.unicode?`•`:`*`:` `,o=i<1e3?`0s`:formatTurnDuration(Math.floor(i/1e3)*1e3),s=`${turnActivityLabel(this.#Q)} (${o})`,{inputTokens:c,outputTokens:l}=this.#Z.usage;return clip(`${a} ${s}${c>0||l>0?t.dim(` (${formatTokenFlow({inputTokens:c,outputTokens:l},this.#i.glyph)})`):``}`,e)}#Un(e){return`${formatTurnDuration(e)}${this.#Wn()}`}#Wn(){let{inputTokens:e,outputTokens:t}=this.#Z.usage;return e===0&&t===0?``:` ${this.#i.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#i.glyph)}`}#Gn(e,t){this.#ee&&this.#Kn(e,t,{inert:!0})}#Kn(e,t,n){e.push(``);let r={text:this.#$.text,cursor:this.#$.cursor,width:t,theme:this.#i,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#$.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#qn(e,t){if(this.#O!==void 0){let n=this.#Ke?.status?.text??{starting:`Starting agent…`,connecting:`Reading saved connection…`,updating:`Loading selected model…`}[this.#O],r=this.#zn(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.#Ve&&this.#Be!==void 0&&(i.devBuild=this.#Be),this.#be&&(i.logLevel=this.#m);let a=this.#D?.info?.agent.model;a?.routing.kind===`dynamic`?i.model=this.#Je===void 0?`dynamic model`:`dynamic model · ${this.#Je}`: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))}#Jn(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))}#Yn(){let e=this.#i.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#ke,outputTokens:this.#Me,tokensPerSecond:this.#Ne},this.#u);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#i.glyph.dot} `)):``}#Xn(){return Math.max(20,this.#t.columns||80)}#Zn(){return Math.max(8,this.#t.rows||24)}#Qn(){if(this.#Fe!==void 0||!this.#d)return;this.#Ie=``,this.#Le=``;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.#tr(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#f?.subscribeLogRecords(e=>this.#er(e)),this.#Fe=()=>{this.#f?.unsubscribeLogRecords(),e(),t()}}#$n(){let e=this.#Fe;e!==void 0&&(this.#Fe=void 0,e(),this.#Ie.length>0&&(this.#f?.append({source:`stdout`,detail:this.#Ie}),this.#ur(`stdout`)&&process.stdout.write(`${this.#Ie}\n`),this.#Ie=``),this.#Le.length>0&&(this.#f?.append({source:`stderr`,detail:this.#Le}),this.#ur(`stderr`)&&process.stderr.write(`${this.#Le}\n`),this.#Le=``))}#er(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#rr(`[eve:${e.namespace}] ${e.message}${t}`),this.#jn()}#tr(e,t){let n=(e===`stdout`?this.#Ie:this.#Le)+t;if(e===`stdout`&&parseDevRebuildLogLine(n.trimEnd())!==void 0){this.#Ie=``,this.#f?.append({source:e,detail:n.trimEnd()}),this.#nr(n.trimEnd()),this.#jn();return}let r=n.lastIndexOf(`
|
|
6
|
-
`),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#
|
|
7
|
-
`);t=[],e.trim().length!==0&&this.#
|
|
8
|
-
`)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#
|
|
9
|
-
`),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#f===void 0){this.#
|
|
10
|
-
`);r.trim().length>0&&this.#
|
|
11
|
-
`);this.#
|
|
4
|
+
`),n=stripPromptControlCharacters(e?.initialDraft??this.#ee.text),r=t===void 0?n:n.length===0?t:`${t}\n\n${n}`,i=lineOf(r);return this.#ee=EMPTY_LINE,this.#H.begin(i.text),this.#ft(i),this.#lt(i.text),this.#tn(),this.#Mn(),await new Promise((e,t)=>{this.#re=t;let apply=e=>{i=e,this.#rn(),this.#ft(i),this.#lt(e.text),this.#Mn()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#G=void 0,this.#nn(),this.#Wt(),t(interruptedError())},suggestions=()=>this.#G!==void 0&&isTypeaheadOpen(this.#G)?this.#G:void 0,argumentSuggestions=()=>this.#K?.suggestions.length?this.#K:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#Se=t=>{t.type!==`ctrl-c`&&this.#fe&&(this.#fe=!1,this.#Mn());let n=this.#U.apply(i,t,{multiline:!0});if(n!==void 0){apply(n);return}switch(t.type){case`up`:case`ctrl-p`:{let e=argumentSuggestions();if(e!==void 0){this.#K=moveArgumentTypeaheadSelection(e,-1),this.#Mn();break}let t=suggestions();if(t!==void 0){this.#G=moveTypeaheadSelection(t,-1),this.#Mn();break}let n=movePromptLine(i,`up`);n===void 0?recall(this.#H.previous(i.text)):apply(n);break}case`down`:case`ctrl-n`:{let e=argumentSuggestions();if(e!==void 0){this.#K=moveArgumentTypeaheadSelection(e,1),this.#Mn();break}let t=suggestions();if(t!==void 0){this.#G=moveTypeaheadSelection(t,1),this.#Mn();break}let n=movePromptLine(i,`down`);n===void 0?recall(this.#H.next()):apply(n);break}case`tab`:{let e=argumentSuggestions(),t=e===void 0?void 0:selectedArgumentSuggestion(e);if(e!==void 0&&t!==void 0){apply(lineOf(argumentTypeaheadCompletion(e,t)));break}let n=highlighted();n!==void 0&&apply(lineOf(typeaheadCompletion(n)));break}case`escape`:{if(this.#K!==void 0){this.#K=void 0,this.#Mn();break}let e=suggestions();e!==void 0&&(this.#G=dismissTypeahead(e),this.#Mn());break}case`enter`:{let t=argumentSuggestions(),n=t===void 0?void 0:selectedArgumentSuggestion(t),r=highlighted();if(t!==void 0&&n?.next!==void 0&&t.completed.length===0){apply(lineOf(`${argumentTypeaheadCompletion(t,n)} `));break}if(t===void 0&&r!==void 0&&this.#q!==void 0&&(r.name===`add`||r.name===`login`||r.name===`model`)){apply(lineOf(typeaheadCompletion(r)));break}let a=t!==void 0&&n!==void 0?argumentTypeaheadCompletion(t,n):r!==void 0&&parsePromptCommand(i.text)===null?typeaheadCompletion(r).trimEnd():i.text;if(a.trim().length===0)break;this.#G=void 0,this.#K=void 0,this.#H.add(a),this.#W=!1,this.#nn(),this.#ie=STATUS.processing,isPromptControlCommand(a)?this.#un({kind:`command`,body:stripTerminalControls(a.trim()),live:!1}):(this.#an(),this.#dn(a),this.#Ge=a,this.#Q.arm()),this.#ft(EMPTY_LINE),this.#Mn(),this.#Kt(),e(a);break}case`ctrl-d`:i.text.length===0?(this.#Rt(),interrupt()):apply(deleteForward(i));break;case`ctrl-l`:this.#Fn();break;case`ctrl-r`:this.#Mn();break;case`ctrl-c`:if(this.#fe){this.#Rt(),interrupt();break}this.#fe=!0,apply(EMPTY_LINE)}},this.#Gt()})}#ft(e){this.#B=e.text,this.#V=e.cursor}takeQueuedPrompt(){let e=this.#Ze.view().steering,t=this.#Ze.takePrompt();return t!==void 0&&(this.#nt=e?`steer`:`queue`),t}async renderStream(e,t){this.#Ht(t),this.#_.clear(),this.#W=!1,this.#ne.kind!==`waiting`&&(this.#ne={kind:`waiting`,startedAtMs:Date.now()}),this.#ie=this.#L>0?STATUS.connectionAuth:STATUS.processing,this.#pn(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#f?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#Q.armed&&this.#Q.arm(),this.#ue=!1,this.#et=!1,this.#rt=!1,this.#it=t?.submittedPrompt,this.#Ze.beginTurn(),this.#Qe=e.cancel,this.#$e=e.steer,this.#Ae=void 0,this.#je=void 0,this.#Ne=void 0,this.#Pe=void 0,this.#Fe=Date.now();let n={text:new Map,reasoning:new Map,tools:new Map,modelActivity:`Thinking`,runningTools:new Set,cancelled:!1,restoreCancelledPrompt:!0};this.#$=n;let r={tools:t?.tools??this.#o,reasoning:t?.reasoning??this.#s,assistantResponseStats:t?.assistantResponseStats??this.#u};this.#in(),this.#te=!0,this.#Mn();let i=new Promise(e=>{this.#De=e});this.#Se=e=>this.#$t(e),this.#Gt();try{for await(let t of takeUntil(iterateTUIStream(e.events),i)){if(this.#ue)break;this.#xn(t,r,n)}}catch(e){let t=summarizeKnownError(e);t===null?this.#mn(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#mn(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#De=void 0,this.#ue&&e.abort?.(),this.#Qe=void 0,this.#$e=void 0,this.#Kt(),this.#te=!1,this.#$=void 0,this.#ne.kind===`waiting`&&(this.#ne={kind:`idle`}),this.#ln(),this.#ie=completedTurnStatus({interrupted:this.#ue,cancelled:this.#et,continueSession:t?.continueSession===!0}),this.#On(n),(this.#ue||n.cancelled)&&this.#Dn(n),this.#bn(),this.#ln(),this.#f?.reportStats(),this.#Mn(),t?.continueSession||this.#Wt()}}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,modelActivity:`Thinking`,runningTools:new Set,cancelled:!1,restoreCancelledPrompt:!1};try{for await(let t of iterateTUIStream(e.events))this.#xn(t,n,r)}catch(e){let t=summarizeKnownError(e);t===null?this.#mn(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#mn(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#On(r),r.cancelled&&this.#Dn(r),this.#bn(),this.#ln(),this.#f?.reportStats(),this.#Mn()}}async readToolApproval(e,t){return this.#Ht(t),this.#on(),this.#W=!1,this.#ne={kind:`idle`},this.#ie=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#ue=!1,this.#Mn(),await new Promise((t,n)=>{this.#re=n,this.#Se=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#an(),this.#ie=STATUS.processing,this.#Kt(),this.#Mn(),t({approved:!0})):n===`n`&&(this.#an(),this.#ie=STATUS.processing,this.#mt(e.toolCallId),this.#Kt(),this.#Mn(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#Mn();break;case`ctrl-c`:this.#ue=!0,this.#Wt(),n(interruptedError())}},this.#Gt()})}async readInputQuestion(e,t){this.#Ht(t),this.#on(),this.#W=!1,this.#X=!1,this.#ne={kind:`idle`},this.#ue=!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.#he},this.#i,t),renderTextSection=()=>{this.#gn({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#tn():(this.#nn(),this.#rn())};s===`overlay`?(s=`overlay`,this.#W=!1,this.#vn(o),this.#Ke=overlayPanel,this.#ie=``,syncFreeformCaret(),this.#Mn()):(s=`text`,this.#Ke=void 0,renderTextSection(),this.#W=!0,this.#ft(l),this.#ie=``,this.#tn(),this.#Mn());let finalize=t=>{this.#Ke=void 0,this.#gn({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.#W=!1,this.#an(),this.#ie=STATUS.processing,this.#nn(),this.#Kt(),this.#Mn();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Ke=void 0,this.#gn({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Skipped. The question stays open.`)}`,preformatted:!0,live:!1}),this.#W=!1,this.#ie=``,this.#nn(),this.#Kt(),this.#Mn(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#Mn())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#re=r,u=t,this.#Se=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#rn(),s===`text`&&this.#ft(l),this.#Mn();return}this.#ue=!0,this.#Ke=void 0,this.#nn(),this.#Wt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#Mn();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.#rn(),this.#Mn();break}dismiss();break;default:if(isOnFreeformRow()){let e=this.#U.apply(l,t);e!==void 0&&(l=e,this.#rn(),this.#Mn());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.#Mn())}}return}let a=this.#U.apply(l,t,{multiline:!0});if(a!==void 0){l=a,this.#rn(),this.#ft(l),this.#Mn();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#rn(),this.#ft(l),this.#Mn());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.#rn(),this.#ft(l),this.#Mn();break}dismiss()}},this.#Gt()})}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.#hn(e.callId,e.subagentName),this.#c===`collapsed`){this.#Mn();return}this.#_n({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.#Mn()}}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.#hn(e.callId,e.subagentName),this.#c===`collapsed`){this.#Mn();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#Tn({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.#_n(r),this.#pt(e.callId),this.#Mn()}#pt(e){applyCohortLiveness(this.#h.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#vn(subagentToolSectionId(e.callId,e.childCallId)),this.#Mn()}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.#hn(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.#Mn()}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.#yn(e.callId),this.#ln(),this.#Mn()}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.#ln(),this.#Mn()}}markChildToolCallId(e){this.#y.add(e);let t=this.#b.get(e);t!==void 0&&(this.#vn(t),this.#b.delete(e),this.#Mn())}#mt(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.#gn({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.#Mn()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#L)return;let n=this.#L>0;this.#L=t,t>0?(this.#ie=STATUS.connectionAuth,this.#Mn()):n&&(this.#ie=STATUS.processing,this.#Mn())}setVercelStatus(e){this.#R=e,this.#Mn()}setRemoteConnectionStatus(e){this.#z=e,this.#Mn()}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.#ht(),this.#Z=!1,this.#Ge=void 0,this.#Be=void 0,this.#L=0,this.#Ae=void 0,this.#je=void 0,this.#Ne=void 0,this.#Pe=void 0,this.#Fe=void 0,this.#se&&(this.#n.clearAll(),this.#Mn())}renderSessionBoundary(){this.#fn(),this.#ht();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#un({kind:`session-boundary`,body:n,live:!1}),this.#Mn()}#ht(){this.#Ye=void 0,this.#Xe=void 0,this.#y.clear(),this.#b.clear(),this.#E.clear(),this.#C.clear(),this.#w.clear(),this.#S.clear(),this.#Ze.reset(),this.#nt=void 0,this.#T.clear(),this.#Q.reset(),this.#ln()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ht(),this.#un({kind:`notice`,body:t,live:!1}),this.#Mn())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#gt();return}this.#Ht(),this.#Je=t,this.#Mn()}clearSetupWarning(){this.#gt()}#gt(){this.#Je!==void 0&&(this.#Je=void 0,this.#Mn())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#Ht();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#un(r),this.#Mn()}renderCommandResult(e,t){let n=stripAnsi(e);n.trim().length!==0&&(this.#Ht(),this.#un({kind:`result`,body:n,live:!1,status:t===`success`?`done`:void 0}),this.#Mn())}#_t(e,t=`spinner`){this.#Ht(),this.#k===void 0&&(this.#W=!1),this.#ne={kind:`idle`},this.#ie=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#qe={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#in(),this.#Mn()}#vt(e){this.#qe!==void 0&&(this.#qe.navigation=e,this.#Mn())}#yt(e){this.#at=void 0,this.#Mt();let t=this.#qe;if(t!==void 0){if(this.#qe=void 0,this.#k===void 0?this.#on():this.#dt(),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.#un({kind:`flow`,title:`info`,body:e.join(`
|
|
5
|
+
`),live:!1}),this.#un({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#Mn()}}async#bt(e){let t=this.#Et(e.message),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.kind===`search`&&e.layout===void 0,a=e.options,o=e.navigation?.kind===`planner`,s={options:a,searchAction:r,submitRow:n&&!o};`initialValue`in e&&e.initialValue!==void 0&&(s.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(s.initialValues=e.initialValues);let c=initialSelectState(s),l,u=!1,d=0,isCurrentSearch=e=>e===d,clearSearch=()=>{d+=1,u=!1,c=reduceSelect(c,{type:`clear`},{options:a,searchAction:r,submitRow:n&&!o}),this.#Mn()},loadSearch=async(e,t)=>{u=!0,l=void 0;let i=++d;this.#Mn();try{let s=await t(e);if(!isCurrentSearch(i))return;let l=c.filter;a=s,c={...initialSelectState({options:s,searchAction:r,submitRow:n&&!o}),filter:l}}catch(e){isCurrentSearch(i)&&(l=toErrorMessage(e))}finally{isCurrentSearch(i)&&(u=!1,this.#Mn())}},f=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}));f=e.notices??r,t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,message:``,options:a,select:c};return f!==void 0&&f.length>0&&(t.notices=f),l!==void 0&&(t.error=l),u&&(t.loadingFrame=this.#zn()),i&&(t.caretVisible=this.#he),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),i&&this.#tn(),this.#Mn(),await this.#kt((t,s)=>{let close=e=>{d+=1,s(e)};if(u){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#Mn();return}let f=e.navigation?.kind===`planner`?e.navigation:void 0,p=t.type===`left`&&(f?.activeStep??0)>(f?.firstNavigableStep??0)?`back`:t.type===`right`&&f!==void 0&&f.activeStep>=(f.firstNavigableStep??0)&&f.activeStep<f.steps.length-1?`forward`:void 0;if(p!==void 0){close({kind:`navigate`,direction:p,values:n?orderedSelection(a,c.selected):[]});return}let m={key:t,options:a,searchAction:r,select:c},h=reduceSetupSelectInput(n?{...m,kind:e.kind,required:e.required,plannerNavigation:o||void 0}:{...m,kind:e.kind});switch(h.kind){case`cancel`:close(void 0);return;case`repaint`:this.#Mn();return;case`update`:c=h.select,l=void 0,i&&this.#rn(),this.#Mn();return;case`submit`:{let e=searchActionQuery(h.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(h.values);return}loadSearch(e,t);return}case`error`:l=h.message,this.#Mn();return;case`ignore`:return}},i?()=>this.#nn():void 0).promise}#xt(e){this.#Ht();let t=this.#Dt();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.#Mn();let r=this.#kt((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.#Mn();return;case`repaint`:this.#Mn();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#St(e){let t=this.#Et(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.#he,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.#tn():(i=lineOf(``),this.#nn())};return syncEditableRow(),this.#Mn(),await this.#kt((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#rn(),this.#Mn()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#Mn()},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.#Mn();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.#Mn();return;case void 0:}if(!onEditableRow())return;let s=this.#U.apply(i,t);s!==void 0&&applyEditor(s)},()=>this.#nn()).promise}async#Ct(e){this.#U.clear();let t=this.#Et(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.#he,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.#tn():this.#nn()};return syncCaret(),this.#Mn(),await this.#kt((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.#Mn();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#Mn();return;case`validate`:{n=o.state,syncCaret(),this.#Mn();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.#Mn();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.#rn(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#nn()}).promise}async#wt(e){e.mask===!0&&this.#U.clear();let t=this.#Et(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.#he)},this.#tn(),this.#Mn(),await this.#kt((t,i)=>{let apply=e=>{n=e,r=void 0,this.#rn(),this.#Mn()},a=e.mask?applyLineEditorKey(n,t):this.#U.apply(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.#Mn();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#Mn();return}i(t);return}default:return}},()=>this.#nn()).promise}async#Tt(e){let t=this.#Et(e.message);return t.question=t=>renderAcknowledgeQuestion({message:``,lines:e.lines},this.#i,t),this.#Mn(),await this.#kt((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#Mn();return;default:return}}).promise}#Et(e){this.#Ht(),this.#W=!1,this.#ne={kind:`idle`},this.#ie=``;let t=this.#Dt();return t.questionTitle=stripTerminalControls(e),t.status!==void 0&&(t.status=void 0,t.summary=void 0,t.preview=void 0),t}#Dt(){return this.#qe===void 0&&(this.#qe={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#qe}#Ot(){this.#qe?.implicit===!0?this.#qe=void 0:this.#qe!==void 0&&(this.#qe.question=void 0,this.#qe.questionTitle=void 0,this.#qe.hideLinesWhileQuestion=!1),this.#Se=void 0,this.#Kt(),this.#k===void 0?this.#qe!==void 0&&this.#jt():this.#dt(),this.#qe===void 0&&this.#Mn()}#kt(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Ot(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Ot(),i(e))};return this.#Qt(),this.#Se=t=>{t.type===`ctrl-c`&&this.#Rt(),e(t,settle,reject)},this.#Gt(),{promise:a,settle}}#At(e){let t,n=new Promise(e=>{t=e});return this.#at=t,this.#jt(e?.interruptible??!0),{promise:n,dispose:()=>{this.#at===t&&(this.#at=void 0,this.#Mt())}}}#jt(e=!0){if(this.#k!==void 0){this.#dt();return}if(this.#at===void 0)return;let consumer=t=>{if(e&&(t.type===`ctrl-c`||t.type===`escape`)){t.type===`ctrl-c`&&this.#Rt();let e=this.#at;this.#at=void 0,this.#Mt(),e?.(t.type===`ctrl-c`?`ctrl-c`:`escape`);return}t.type===`ctrl-r`&&this.#Mn()};this.#ot=consumer,this.#Qt(),this.#Se=consumer,this.#Gt()}#Mt(){this.#ot!==void 0&&(this.#Se===this.#ot&&this.#Kt(),this.#ot=void 0)}#Nt(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.#qe!==void 0){this.#qe.status=t,t===void 0&&(this.#qe.preview=void 0),this.#Mn();return}if(!(this.#W||this.#te)){if(t===void 0){this.#ne={kind:`idle`},this.#ae=void 0,this.#on(),this.#Mn();return}this.#Ht(),this.#an(),this.#ae=t.text,this.#Mn()}}#Pt(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#qe;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.#Mn();return}this.#Ht(),this.#un({kind:`flow`,title:t,body:n,live:!1}),this.#Mn()}#Ft(e){let t=this.#qe;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.#Mn())}#It(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#qe;if(n===void 0){this.#Pt(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#Mn()}async#Lt(e){this.#Ce=``,this.#Qt(),this.#at=void 0,this.#Mt(),this.#Kt(),this.#sn(),this.#n.clear(),this.#er(),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.#Ce=``,this.#Qt(),this.#n.hideCursor(),this.#$n(),this.#qe===void 0?this.#ln():(this.#in(),this.#jt()),this.#n.reset(),this.#Mn()}}setSessionId(e){this.#tt=e}shutdown(){this.#Wt();for(let e of this.#Y.values())clearTimeout(e);if(this.#Y.clear(),this.#ce&&!this.#le){this.#le=!0;let e=this.#tt===void 0?``:` ${this.#i.glyph.dot} session ${this.#tt}`;this.#t.write(`${this.#i.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}suspendPromptForInput(){this.#ee={cursor:this.#V,text:this.#B},this.#Wt()}requestInterrupt(){this.#ue=!0,this.#qe!==void 0&&this.#Se?.({type:`ctrl-c`}),this.#De?.(),this.#Wt()}exitRequested(){return this.#de}#Rt(){this.#de=!0,this.#me?.()}async#zt(e){if(this.#st!==void 0||!this.#se)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#Zn(),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.#ct});this.#st=t,this.#r.enter(),this.#i.color&&this.#r.writeRaw(BACKGROUND_COLOR_QUERY),await new Promise(e=>{this.#Vt=e,this.#Se=e=>{t.handleKey(e)===`close`&&this.#Bt()},this.#Gt(),t.start()})}#Bt(){let e=this.#st;if(e===void 0)return;this.#st=void 0,e.dispose(),this.#Kt(),this.#r.exit(),this.#n.hideCursor(),this.#Mn(),this.#n.showCursor();let t=this.#Vt;this.#Vt=void 0,t?.()}#Vt;#Ht(e){this.#oe=e?.title??this.#oe,e?.contextSize!==void 0&&(this.#Me=e.contextSize),!this.#se&&(this.#se=!0,this.#ce=!0,this.#n.reset(),this.#n.hideCursor(),this.#$n(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#Ee=()=>this.#Mn(),this.#t.on(`resize`,this.#Ee),process.on(`exit`,this.#Ut))}#Ut=()=>{this.#se&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#Wt(){this.#Bt();let e=this.#re;if(this.#re=void 0,e?.(interruptedError()),this.#Kt(),this.#nn(),this.#sn(),this.#be!==void 0&&(clearTimeout(this.#be),this.#be=void 0),this.#xe=!1,this.#cr(),this.#se){this.#ur();for(let e of this.#h)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#Mn(),this.#n.clear(),this.#n.showCursor(),this.#er(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#Ee&&=(this.#t.off(`resize`,this.#Ee),void 0),process.off(`exit`,this.#Ut),this.#se=!1}}#Gt(){this.#e.off(`data`,this.#qt),this.#e.on(`data`,this.#qt),this.#Ce.length>0&&queueMicrotask(()=>{this.#Se!==void 0&&this.#Ce.length>0&&(this.#Xt(),this.#Jt())})}#Kt(){this.#e.off(`data`,this.#qt),this.#Qt(),this.#Se=void 0}#qt=e=>{this.#Qt(),this.#Ce+=this.#we.write(e),this.#Xt(),this.#Jt()};#Jt(){if(this.#Ce===`\x1B`){this.#Te=setTimeout(()=>{this.#Ce===`\x1B`&&(this.#Ce=``,this.#Yt({type:`escape`}))},30),this.#Te.unref?.();return}if(isIncompletePaste(this.#Ce)){let e=this.#Ce;this.#Te=setTimeout(()=>{if(this.#Ce!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#Ce=``,t.length>0&&this.#Yt({type:`text`,value:t,framing:`bracketed-paste`})},incompletePasteFlushMs),this.#Te.unref?.();return}if(isIncompleteOsc(this.#Ce)){let e=this.#Ce;this.#Te=setTimeout(()=>{this.#Ce===e&&(this.#Ce=``)},incompletePasteFlushMs),this.#Te.unref?.()}}#Yt(e){this.#U.interruptYank(e),this.#Se?.(e)}#Xt(){for(;this.#Ce.length>0;){let e=nextKey(this.#Ce);if(e.incomplete)return;if(this.#Ce=this.#Ce.slice(e.consumed),e.key!==void 0&&e.key.type!==`ignore`){if(e.key.type===`osc`){this.#Zt(e.key.value);continue}this.#Yt(e.key)}}}#Zt(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#ct=t,this.#st?.setTerminalBackground(t))}#Qt(){this.#Te&&=(clearTimeout(this.#Te),void 0)}#$t(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#Mn();break;case`enter`:{let e=this.#ee.text;if(e.trim().length===0)break;if(parsePromptCommand(e)?.type===`cancel`&&this.#Qe!==void 0){this.#ee=EMPTY_LINE,this.#Ze.requestCancellation(),this.#rt=!0,this.renderCommandInvocation(e.trim()),this.renderCommandResult(`Turn cancellation requested.`),this.#Qe(),this.#Mn();break}let t=this.#$e;t!==void 0&&parsePromptCommand(e)===null?(this.#ee=EMPTY_LINE,this.#en(e,t)):this.#Ze.enqueue(e)&&(this.#ee=EMPTY_LINE),this.#Mn();break}case`ctrl-c`:case`escape`:if(e.type===`ctrl-c`&&this.#Ze.view().cancelling){this.#ue=!0,this.#pe=!0,this.#ne={kind:`idle`},this.#ie=`Interrupted`,this.#De?.(),this.#Mn();break}if(this.#Ze.idle&&this.#Qe===void 0)break;if(this.#Ze.handleEscape()===`steer`){let e=this.#$e;if(e!==void 0){let t=this.#Ze.takeSteering();this.#en(t,e)}}else this.#rt=!0,this.#Qe?.();this.#Mn();break;default:{let t=this.#U.apply(this.#ee,e,{multiline:!0});t!==void 0&&(this.#ee=t,this.#Mn());break}}}#en(e,t){this.#nt=`steer`,this.#pn(e),t(e).catch(t=>{this.#Ze.restoreSteering(e),this.#mn(`Steering failed`,toErrorMessage(t)),this.#Mn()})}#tn(){this.#nn(),this.#rn(),this.#ve=setInterval(()=>{this.#he=!this.#he,this.#Mn()},500),this.#ve.unref?.()}#nn(){this.#ve&&=(clearInterval(this.#ve),void 0),this.#he=!0}#rn(){this.#he=!0}#in(){this.#sn(),this.#ye=setInterval(()=>{this.#ge+=1,this.#Mn()},90),this.#ye.unref?.()}#an(){let e=Date.now();this.#_e=e,this.#ne={kind:`waiting`,startedAtMs:e},this.#in()}#on(){this.#cn()||this.#sn()}#sn(){this.#ye&&=(clearInterval(this.#ye),void 0)}#cn(){return this.#h.some(e=>e.live&&e.subagentCallId!==void 0&&(this.#C.has(e.subagentCallId)||this.#w.has(e.subagentCallId)))}#ln(){this.#cn()?this.#in():!this.#te&&this.#ne.kind===`idle`&&this.#sn()}#un(e){e.id!==this.#Be?.id&&this.#ur(),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)}#dn(e){this.#Z=!0,this.#un({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#Mn()}#fn(){let e=this.#Q.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#Wn(e.elapsedMs)}`,n=this.#je??0;if(this.#Me!==void 0&&this.#Me>0&&n>0){let e=Math.round(n/this.#Me*100);t+=` ${this.#i.glyph.dot} ${e}% context`}this.#un({kind:`turn-stats`,body:t,live:!1})}#pn(e){if(e==null)return;let t=this.#nt;if(this.#nt=void 0,this.#Ge===e){this.#Ge=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#un(n)}#mn(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.#un(c),this.#Mn()}#hn(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.#un(i)}#gn(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.#un(e)}#_n(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.#un(e);return}e.id!==this.#Be?.id&&this.#ur(),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)}#vn(e){this.#h=this.#h.filter(t=>t.id!==e),this.#g.delete(e)}#yn(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))}#bn(){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)}#xn(e,t,n){let r=turnActivityLabel(n);switch(updateTurnActivity(n,e),e.type){case`turn-start`:e.turnId!==this.#Xe&&(this.#Xe=e.turnId,this.#Ye=void 0,this.#Mn());break;case`step-start`:this.#Ye=typeof e.modelId==`string`&&stripTerminalControls(e.modelId.slice(0,256)).replace(/\s+/gu,` `).trim()||void 0,this.#Mn();break;case`step-finish`:this.#f?.recordStepUsage(e.usage),e.usage!==void 0&&this.#Q.addUsage(e.usage),this.#On(n),this.#jn(e.usage),this.#Mn();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#Sn(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.#Sn(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.#Cn(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.#Cn(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#wn({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.#wn({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.#wn({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#An(e.toolCallId,n);if(r===void 0)break;this.#wn({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#An(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.#wn({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#An(e.toolCallId,n);if(r===void 0)break;this.#wn({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#mn(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:if(n.cancelled=!0,!n.restoreCancelledPrompt)break;this.#et=!0,!this.#rt&&this.#it!==void 0&&this.#ee.text.length===0&&(this.#ee=lineOf(this.#it),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#jn(e.usage),this.#Mn()}n===this.#$&&turnActivityLabel(n)!==r&&this.#Mn()}#Sn(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#gn({id:e,kind:`assistant`,body:r,live:n}),this.#Mn())}#Cn(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#gn({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#Mn())}#wn(e,t,n){if(n.tools.set(e.toolCallId,e),this.#y.has(e.toolCallId)||isPanelRoutedTool(e.toolName))return;let r=toolSectionId(e.toolCallId);this.#b.set(e.toolCallId,r);let i=this.#Tn(e);this.#gn(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#kn(n),this.#Mn()}#Tn(e){e.output!==void 0&&this.#T.observeRead(e.output);let t={};this.#En(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}#En(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)}#Dn(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)}}#On(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.#vn(r),this.#b.delete(t)}}#kn(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)}#An(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`}}#jn(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#Ae=(t??0)+(n??0)),this.#je=t??this.#je,this.#Ne=n??this.#Ne,this.#Ne!=null&&this.#Fe!==void 0){let e=(Date.now()-this.#Fe)/1e3;e>0&&(this.#Pe=this.#Ne/e)}}#Mn(){if(this.#se){if(this.#Oe){this.#ke=!0;return}this.#Oe=!0;try{do this.#ke=!1,this.#Nn();while(this.#ke)}finally{this.#Oe=!1}}}#Nn(){if(!this.#se)return;if(this.#st!==void 0){this.#st.repaint();return}let e=this.#Zn(),t=this.#Hn(e),n=this.#M===void 0?[]:this.#Ln(),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.#fr(t.display))continue;let n=this.#Rn(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.#fr(t))continue;let n=this.#Rn(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)}#Pn(){if(!this.#se)return;let e=this.#Zn(),t=this.#Hn(e),n=Math.max(1,this.#Qn()-t.length),r=this.#I,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#h)){if(this.#fr(t))continue;let n=this.#Rn(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.#Ln(),...this.#F],a)}logDisplayMode(){return this.#m}setLogDisplayMode(e){e!==this.#m&&(this.#m=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#In(),this.#se&&this.#Pn())}flushDelayedDevBuildErrors(){let e=this.#ze;e!==void 0&&(this.#ze=void 0,this.#un({kind:`log`,title:`stderr`,body:e,live:!0}),this.#Mn())}#Fn(){this.#xe=!0,this.#be!==void 0&&clearTimeout(this.#be),this.#be=setTimeout(()=>{this.#xe=!1,this.#be=void 0,this.#Mn()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#m)),this.#Mn()}#In(){let e=this.#Zn();this.#F.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#v,{logCoalescing:`runs`})){if(this.#fr(n))continue;let r=this.#Rn(n,e,t);t=previousBlockOf(n),this.#F.push(...r)}this.#I=t}#Ln(){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.#Zn()};return e?.info!==void 0&&(n.info=e.info),buildAgentHeader(n)}#Rn(e,t,n){let r={renderMarkdown:this.#a,activityPulse:this.#Bn(this.#_e,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}#zn(){return this.#i.spinner[this.#ge%this.#i.spinner.length]??``}#Bn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#Vn(e,t){return e.indicator.kind===`spinner`?{glyph:this.#zn(),color:`yellow`}:{glyph:this.#Bn(e.indicator.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#Hn(e){let t=this.#i.colors,n=[``];if(this.#Ke!==void 0)return n.push(...this.#Ke(e),``),this.#Jn(n,e),n;let r=this.#qe;if(r!==void 0&&(this.#k===void 0||r.question!==void 0)){let t=this.#Vn(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},s=renderFlowDrawer(o,this.#i,e);return n.length===1&&n[0]===``&&(n.length=0),n.push(...s.rows),s.controls.length>0&&n.push(...s.controls),this.#Yn(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.#Je!==void 0&&n.push(...renderAttentionRows(this.#Je,e,this.#i),``);let i=renderMessageQueueRows({view:this.#Ze.view(),width:e,theme:this.#i,working:this.#te});if(i.length>0&&n.push(...i,``),this.#W){let r=this.#G===void 0?void 0:inlineCommandHint(this.#G),i=this.#ut(e);this.#fe&&n.push(clip(t.dim(`Press Ctrl+C again to exit`),e),``);let a=isPromptControlCommand(this.#B),o=r?t.dim(` ${r}`):``,s=[];this.#Jn(s,e);let c=Math.max(1,this.#Qn()-1-n.length-1-i.length-s.length-(i.length>0?2:0)),l={text:this.#B,cursor:this.#V,width:e,theme:this.#i,caretVisible:this.#he,isCommand:a,ghost:o,maxRows:c};this.#X&&this.#B.length===0&&(l.placeholder=this.#k===void 0?this.#Z?``:`Send a message…`:`Message · Enter to queue`);let u=promptInputRows(l);return i.length>0&&u.at(-1)===``&&u.pop(),n.push(...u),i.length>0&&n.push(t.dim(this.#i.glyph.dash.repeat(e))),n.push(...i),i.length>0&&s.length>0&&n.push(t.dim(this.#i.glyph.dash.repeat(e))),n.push(...s),n}let a=this.#ne.kind===`waiting`&&this.#ae===void 0;if(this.#te||a){n.push(this.#Un(e)),this.#Kn(n,e);let t=[];return this.#Jn(t,e),!this.#te&&t.length>0&&n.push(``),n.push(...t),n}if(this.#ee.text.length>0)return this.#qn(n,e,{inert:!1}),this.#Jn(n,e),n;let o=this.#ae??(this.#ie.length>0?this.#ie:`Ready`),s=this.#Xn(),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.#Jn(n,e),n}#Un(e){let t=this.#i.colors,n=this.#ne,r=this.#Q.startedAtMs??this.#Fe??(n.kind===`waiting`?n.startedAtMs:Date.now()),i=Math.max(0,Date.now()-r),a=i%1e3<500?this.#i.unicode?`•`:`*`:` `,o=i<1e3?`0s`:formatTurnDuration(Math.floor(i/1e3)*1e3),s=`${turnActivityLabel(this.#$)} (${o})`,{inputTokens:c,outputTokens:l}=this.#Q.usage;return clip(`${a} ${s}${c>0||l>0?t.dim(` (${formatTokenFlow({inputTokens:c,outputTokens:l},this.#i.glyph)})`):``}`,e)}#Wn(e){return`${formatTurnDuration(e)}${this.#Gn()}`}#Gn(){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)}`}#Kn(e,t){this.#te&&this.#qn(e,t,{inert:!0})}#qn(e,t,n){e.push(``);let r={text:this.#ee.text,cursor:this.#ee.cursor,width:t,theme:this.#i,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#ee.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#Jn(e,t){if(this.#O!==void 0){let n=this.#qe?.status?.text??{starting:`Starting agent…`,connecting:`Reading saved connection…`,updating:`Loading selected model…`}[this.#O],r=this.#Bn(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.#He&&this.#Ve!==void 0&&(i.devBuild=this.#Ve),this.#xe&&(i.logLevel=this.#m);let a=this.#D?.info?.agent.model;a?.routing.kind===`dynamic`?i.model=this.#Ye===void 0?`dynamic model`:`dynamic model · ${this.#Ye}`: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))}#Yn(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))}#Xn(){let e=this.#i.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Ae,outputTokens:this.#Ne,tokensPerSecond:this.#Pe},this.#u);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#i.glyph.dot} `)):``}#Zn(){return Math.max(20,this.#t.columns||80)}#Qn(){return Math.max(8,this.#t.rows||24)}#$n(){if(this.#Ie!==void 0||!this.#d)return;this.#Le=``,this.#Re=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#nr(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#f?.subscribeLogRecords(e=>this.#tr(e)),this.#Ie=()=>{this.#f?.unsubscribeLogRecords(),e(),t()}}#er(){let e=this.#Ie;e!==void 0&&(this.#Ie=void 0,e(),this.#Le.length>0&&(this.#f?.append({source:`stdout`,detail:this.#Le}),this.#dr(`stdout`)&&process.stdout.write(`${this.#Le}\n`),this.#Le=``),this.#Re.length>0&&(this.#f?.append({source:`stderr`,detail:this.#Re}),this.#dr(`stderr`)&&process.stderr.write(`${this.#Re}\n`),this.#Re=``))}#tr(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#ir(`[eve:${e.namespace}] ${e.message}${t}`),this.#Mn()}#nr(e,t){let n=(e===`stdout`?this.#Le:this.#Re)+t;if(e===`stdout`&&parseDevRebuildLogLine(n.trimEnd())!==void 0){this.#Le=``,this.#f?.append({source:e,detail:n.trimEnd()}),this.#rr(n.trimEnd()),this.#Mn();return}let r=n.lastIndexOf(`
|
|
6
|
+
`),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#Le=i:this.#Re=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.#rr(a):this.#ir(a),this.#Mn())}#rr(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
|
|
7
|
+
`);t=[],e.trim().length!==0&&this.#un({kind:`log`,title:`stdout`,body:e,live:!0})};for(let n of e.split(`
|
|
8
|
+
`)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#un({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#or(r,n.trimEnd())}flushPending()}#ir(e){let t=e.split(`
|
|
9
|
+
`),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#f===void 0){this.#un({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#f.displayPath);if(t.kind===`inline`){this.#un({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#un({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#un({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
|
|
10
|
+
`);r.trim().length>0&&this.#un({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
|
|
11
|
+
`);this.#ar(i)}#ar(e){if(this.#cr(),this.#m===`all`){if(e.trim().length===0)return;this.#un({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#ze=e}#or(e,t){let n=this.#lr();if(e.kind===`failed`){this.#ar(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(this.#sr({phase:`building`,summary:t}),n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#We}`;this.#We+=1,this.#Be={id:r,summary:t},this.#un({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}let r=n?.state.summary??this.#Ve?.summary;if(r!==void 0&&this.#sr({phase:`complete`,summary:r}),n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#ze=void 0);return}e.kind===`rebuilt`&&(this.#ze=void 0),this.#un({kind:`log`,title:`stdout`,body:t,live:!0})}#sr(e){this.#Ue!==void 0&&clearTimeout(this.#Ue),this.#Ve=e,this.#He=e.phase===`complete`,this.#Ue=setTimeout(()=>{e.phase===`building`?(this.#He=!0,this.#Ue=void 0):this.#cr(),this.#Mn()},e.phase===`building`?250:4e3)}#cr(){this.#Ue!==void 0&&clearTimeout(this.#Ue),this.#Ve=void 0,this.#He=!1,this.#Ue=void 0}#lr(){let e=this.#Be;if(e===void 0)return;let t=this.#g.get(e.id);if(t!==void 0&&t.live===!0)return{state:e,block:t}}#ur(){let e=this.#Be;if(e===void 0)return;this.#Be=void 0;let t=this.#g.get(e.id);t!==void 0&&(t.live=!1)}#dr(e){switch(this.#m){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#fr(e){return e.kind===`sandbox`?!this.#dr(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#m!==`stderr`:e.logVisibility===`all-only`?this.#m!==`all`:!this.#dr(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.bold(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`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(`
|
|
12
12
|
`)}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(`
|
|
13
13
|
`)}function resolveQuestionText(e,t){let n=e.trim();if(n.length===0)return;let r=n.toLowerCase(),i=t.options??[];if(i.length>0){let e=matchQuestionOption(r,i);if(e!==void 0)return{optionId:e.id,label:e.label}}if(t.allowFreeform===!0||i.length===0)return{text:n,label:n}}function matchQuestionOption(e,t){let n=t.find(t=>t.id.toLowerCase()===e);if(n!==void 0)return n;let r=t.find(t=>t.label.toLowerCase()===e);if(r!==void 0)return r;let i=Number(e);if(Number.isInteger(i)&&i>0&&i<=t.length)return t[i-1]}export{TerminalRenderer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{formatCompactTokenCount}from"../stream-format.js";import{formatPayloadContent,wrapPlainText}from"./trace-content.js";import{SURFACE_CLOSE}from"./trace-surfaces.js";import{formatElapsed}from"#cli/format-elapsed.js";import{clipVisible,stripTerminalControls,visibleLength}from"#cli/ui/terminal-text.js";import{
|
|
1
|
+
import{formatCompactTokenCount}from"../stream-format.js";import{formatPayloadContent,wrapPlainText}from"./trace-content.js";import{SURFACE_CLOSE}from"./trace-surfaces.js";import{formatElapsed}from"#cli/format-elapsed.js";import{clipVisible,stripTerminalControls,visibleLength}from"#cli/ui/terminal-text.js";import{localTraceSpanCostUsd}from"#tracing/local-trace-summary.js";import{formatCostUsd}from"#cli/commands/trace-detail.js";import{compareLocalTraceSpans,isAgentTurnSpan}from"#tracing/local-trace-reader.js";import{agentTurnIdentity}from"#tracing/agent-span-contract.js";function buildConversationItems(e){let t=new Map(e.spans.map(e=>[e.spanId,e])),n=new Map;for(let r of e.spans){if(!isAgentTurnSpan(r))continue;let e=agentTurnIdentity(r),i=turnSubagent(r,t);e!==void 0&&i!==void 0&&n.set(e,i)}let r=[],i=[...e.spans].sort(compareLocalTraceSpans).find(e=>isModelSpan(e)&&typeof e.attributes[`ai.prompt.system`]==`string`),a=i?.attributes[`ai.prompt.system`];i!==void 0&&typeof a==`string`&&a.length>0&&r.push({item:{kind:`system`,durationMs:0,error:!1,span:i,subagent:subagentFor(i,n,t),text:a},order:0n});for(let i of e.spans){let e=subagentFor(i,n,t),a=stringAttribute(i,`agent.channel.delivery.input`);if(a!==void 0){let t=deliveryText(a);if(t===void 0)continue;r.push({item:{kind:`user`,durationMs:0,error:!1,span:i,subagent:e,text:t},order:i.startTimeNs});continue}if(isModelSpan(i)){let n=stringAttribute(i,`ai.response.text`),a=stringAttribute(i,`ai.response.reasoning`),o=numberAttribute(i,`agent.usage.input_tokens`)!==void 0||numberAttribute(i,`agent.usage.output_tokens`)!==void 0,s=i.attributes[`ai.response.tool_calls`]!==void 0;if((n===void 0||n.trim().length===0)&&(a===void 0||a.trim().length===0)&&!o&&!s&&i.statusCode!==2)continue;r.push({item:{kind:`assistant`,costUsd:stepCostUsd(i,t),durationMs:spanDurationMs(i),error:i.statusCode===2,inputTokens:numberAttribute(i,`agent.usage.input_tokens`),model:stringAttribute(i,`gen_ai.request.model`),outputTokens:numberAttribute(i,`agent.usage.output_tokens`),reasoning:a,span:i,subagent:e,text:n,toolCallNames:s?parseToolCallNames(stringAttribute(i,`ai.response.tool_calls`)):void 0},order:i.startTimeNs});for(let t of parseProviderToolResults(stringAttribute(i,`ai.response.tool_results`)))r.push({item:{kind:`tool`,args:t.args,durationMs:0,error:t.error,name:stripTerminalControls(t.name),result:t.result,span:i,subagent:e},order:i.startTimeNs});continue}(i.name===`agent.action`||stringAttribute(i,`gen_ai.operation.name`)===`invoke_workflow`)&&r.push({item:{kind:`tool`,args:stringAttribute(i,`gen_ai.tool.call.arguments`),durationMs:spanDurationMs(i),error:i.statusCode===2,name:stripTerminalControls(stringAttribute(i,`agent.action.name`)??stringAttribute(i,`gen_ai.workflow.name`)??`action`),result:unwrapJsonString(stringAttribute(i,`gen_ai.tool.call.result`)),span:i,subagent:e},order:i.startTimeNs})}return r.sort((e,t)=>e.order===t.order?0:e.order<t.order?-1:1).map(e=>e.item)}function subagentFor(e,t,n){let r=e;for(;r!==void 0;){let e=agentTurnIdentity(r);if(e!==void 0)return t.get(e);r=r.parentSpanId===void 0?void 0:n.get(r.parentSpanId)}}function turnSubagent(e,t){let n=stringAttribute(e,`agent.subagent.name`);if(n!==void 0){let t=n??stringAttribute(e,`gen_ai.agent.name`);return{name:t===void 0?void 0:stripTerminalControls(t)}}let r=e.parentSpanId===void 0?void 0:t.get(e.parentSpanId);if(r===void 0||r.name!==`agent.action`)return;let i=stringAttribute(r,`agent.action.kind`);if(i!==`subagent-call`&&i!==`remote-agent-call`)return;let a=stringAttribute(r,`agent.turn.id`);if(a===void 0)return;let o=stringAttribute(r,`agent.action.name`);return{name:o===void 0?void 0:stripTerminalControls(o),parentCallId:stringAttribute(r,`agent.action.call_id`),parentTurnId:a}}function renderConversationItem(e,t,n,r,i,a){let{colors:o,glyph:s}=n,c=Math.max(8,t-8),l=conversationItemExpandable(e,t),u=n.color?a:void 0,d=u?.primaryText??o.white,f,p,m=[];if(e.kind===`tool`){let t=o.bold(d(e.name??`tool`));f=`${foldMarker(i,l,n)}${t}`,p=e.durationMs>0?o.dim(formatElapsed(e.durationMs)):``;let r=e.args===void 0?[]:formatPayloadContent(e.args,c),a=e.result===void 0?[]:formatPayloadContent(e.result,c),s=i?r:capLines(r,c),u=i?a:capLines(a,c);s.length>0&&m.push(``,o.dim(`Input:`),``,...s),u.length>0&&m.push(``,o.dim(`Output:`),``,...u)}else if(e.kind===`system`){f=`${foldMarker(i,l,n)}${o.bold(d(`system`))}`,p=o.dim(`~${formatCompactTokenCount(estimateTokens(e.text??``))} tokens`);let t=wrapPlainText(e.text??``,c);m.push(...i?t:capLines(t,c))}else if(e.kind===`assistant`){f=`${foldMarker(i,l,n)}${o.bold(d(`assistant`))}${e.model===void 0?``:o.dim(` · ${stripTerminalControls(e.model)}`)}`,p=assistantMetrics(e,s,o);let t=e.reasoning===void 0||e.reasoning.trim().length===0?[]:wrapPlainText(e.reasoning,c),r=e.text===void 0||e.text.trim().length===0?[]:wrapPlainText(e.text,c),a=(i?t:capLines(t,c)).map(e=>o.dim(e)),u=i?r:capLines(r,c);if(a.length>0&&(m.push(o.dim(`Thought:`),``,...a),u.length>0&&m.push(``)),m.push(...u),(e.text===void 0||e.text.trim().length===0)&&e.toolCallNames!==void 0&&e.toolCallNames.length>0){a.length>0&&m.push(``);for(let t of e.toolCallNames)m.push(o.dim(`→ ${t}`))}}else{let t=e.kind===`user`&&e.subagent!==void 0?`task`:e.kind;f=`${foldMarker(i,l,n)}${o.bold(d(t))}`,p=``;let r=e.text===void 0||e.text.trim().length===0?[]:wrapPlainText(e.text,c);m.push(...i?r:capLines(r,c))}if(e.subagent!==void 0){let t=e.subagent.name===void 0?`subagent`:`subagent:${e.subagent.name}`;f+=o.dim(` · ${t}`)}e.error&&(f+=` ${o.red(s.error)}`),!i&&l?m.push(`…`,``,o.dim(`Click to expand`)):i&&l&&m.push(``,o.dim(`Click to collapse`));let h=u===void 0?void 0:e.error?u.errorHeader:u.header,g=u===void 0?void 0:e.error?u.errorBody:u.body,_=railCell(n,r,e.error,u);return[cardRow(``,t,n,_,h),cardSplitRow(f,p,t,n,_,h),cardRow(``,t,n,_,h),cardRow(``,t,n,_,g),...m.map(e=>cardRow(e,t,n,_,g)),cardRow(``,t,n,_,g)]}function cardRow(e,t,n,r,i){let a=clipVisible(e,Math.max(1,t-8)),o=` `.repeat(Math.max(0,t-8-visibleLength(a)));return i===void 0||!n.color?` ${r} ${a}${o} `:` ${r}${i} ${a.replaceAll(`\x1B[0m`,`\x1b[0m${i}`)}\x1b[0m${i}${o} ${SURFACE_CLOSE} `}function railCell(e,t,n,r){let{colors:i,glyph:a}=e;if(t){let t=e.unicode?`▌`:a.rule;return r===void 0?i.white(t):r.primaryText(t)}return r===void 0?n?i.red(a.rule):i.dim(a.rule):` `}function cardSplitRow(e,t,n,r,i,a){if(visibleLength(t)===0)return cardRow(e,n,r,i,a);let o=Math.max(1,n-8),s=visibleLength(t),c=Math.max(1,o-s-2),l=clipVisible(e,c);return cardRow(`${l}${` `.repeat(Math.max(2,o-visibleLength(l)-s))}${t}`,n,r,i,a)}function assistantMetrics(e,t,n){let r=[];return e.durationMs>0&&r.push(formatElapsed(e.durationMs)),e.inputTokens!==void 0&&r.push(`${t.arrowUp}${formatCompactTokenCount(e.inputTokens)}`),e.outputTokens!==void 0&&r.push(`${t.arrowDown}${formatCompactTokenCount(e.outputTokens)}`),e.costUsd!==void 0&&r.push(formatCostUsd(e.costUsd)),r.length===0?``:n.dim(r.join(` · `))}function stepCostUsd(e,t){let n=e;for(;n.parentSpanId!==void 0;){if(n=t.get(n.parentSpanId),n===void 0)return;if(n.name===`agent.step`)return localTraceSpanCostUsd(n)}}function foldMarker(e,t,n){return e?`${n.colors.dim(`▾`)} `:t?`${n.colors.dim(`▸`)} `:``}function capLines(e,t){return e.length<=3?[...e]:[...e.slice(0,2),clipVisible(e[2],Math.max(1,t))]}function conversationItemLineCount(e,t,n,r){return renderConversationItem(e,t,n,!1,r).length}function conversationItemExpandable(e,t){let n=Math.max(8,t-8);if(e.kind===`tool`){let t=e.args===void 0?0:formatPayloadContent(e.args,n-2).length,r=e.result===void 0?0:formatPayloadContent(e.result,n-2).length;return t>3||r>3}if(e.kind===`system`)return wrapPlainText(e.text??``,n).length>3;if(e.kind===`user`)return(e.text===void 0||e.text.trim().length===0?0:wrapPlainText(e.text,n).length)>3;let r=e.reasoning===void 0||e.reasoning.trim().length===0?0:wrapPlainText(e.reasoning,n).length,i=e.text===void 0||e.text.trim().length===0?0:wrapPlainText(e.text,n).length;return r>3||i>3}function estimateTokens(e){return Math.ceil(e.length/4)}function deliveryText(e){if(e!==void 0)try{let t=JSON.parse(e);return isRecord(t)&&typeof t.message==`string`?t.message:void 0}catch{return e}}function unwrapJsonString(e){if(e!==void 0)try{let t=JSON.parse(e);return typeof t==`string`?t:e}catch{return e}}function isModelSpan(e){return e.name.startsWith(`ai.`)&&e.name.includes(`do`)||e.attributes[`gen_ai.operation.name`]===`chat`}function parseToolCallNames(e){if(e!==void 0)try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>isRecord(e)&&typeof e.toolName==`string`).map(e=>e.toolName):void 0}catch{return}}function parseProviderToolResults(e){if(e===void 0)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let asText=e=>typeof e==`string`?e:e===void 0?void 0:JSON.stringify(e);return t.filter(isRecord).map(e=>{let t=`error`in e;return{args:asText(e.input),error:t,name:typeof e.toolName==`string`?e.toolName:`tool`,result:asText(t?e.error:e.output)}})}catch{return[]}}function stringAttribute(e,t){let n=e.attributes[t];return typeof n==`string`?n:void 0}function numberAttribute(e,t){let n=e.attributes[t];return typeof n==`number`?n:void 0}function spanDurationMs(e){return Math.max(0,Number(e.endTimeNs-e.startTimeNs)/1e6)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{buildConversationItems,conversationItemExpandable,conversationItemLineCount,renderConversationItem};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{remoteHost}from"./target.js";import{createDevDiagnostics}from"../diagnostics.js";import{promptCommandsFor}from"./prompt-commands.js";import{probeMcpConnection}from"./mcp-connection-status.js";import{createPromptCommandHandler}from"./prompt-command-handler.js";import{formatRemoteAuthChallengeMessage}from"./remote-auth-result.js";import{TerminalRenderer}from"./terminal-renderer.js";import{EveTUIRunner}from"./runner.js";import{Client}from"#client/index.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{toErrorMessage}from"#shared/errors.js";import{resolveDevelopmentOidcToken,resolveLinkedDevelopmentOidcToken}from"#services/dev-client/request-headers.js";import{isVercelAuthChallenge}from"#services/dev-client/vercel-auth-error.js";import{resolveVercelDeployment}from"#setup/vercel-deployment.js";import{appendUserAgentProduct}from"#internal/user-agent.js";import{resolveLocalDevelopmentClientOptions,resolveRemoteDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{createDevelopmentCredentialGate}from"#services/dev-client/credential-gate.js";function inlineArgumentSuggestions(e){return async t=>{if(t===`model`){let{gatewayModelCapabilities:e}=await import(`#setup/boxes/model-capabilities.js`),{fetchGatewayCatalog:t,modelOptionsFromCatalog:n}=await import(`#setup/boxes/select-model.js`),r=await t().catch(()=>void 0);return n(r).map(t=>{let n=e(r,t.value)?.reasoningLevels;return{value:t.value,label:t.value,hint:t.hint,...n===void 0||n.length===0?{}:{next:[{value:`default`,label:`default`},...n.map(e=>({value:e,label:e}))]}}})}let{browseRegistryCatalog:n}=await import(`#cli/commands/registry.js`);return(await n(e)).items.map(e=>({value:e.address,label:e.name,hint:e.description??e.address}))}}async function startDevelopmentTuiStartup(e){let t=await createDevDiagnostics(e.appRoot).catch(()=>void 0),n=new TerminalRenderer({...e,diagnostics:t,argumentSuggestions:inlineArgumentSuggestions(e.appRoot),onExitRequest:e.onExitRequest});return n.beginStartupDraft({initialDraft:e.initialInput,title:e.name??`eve`}),{diagnostics:t,renderer:n,finish:()=>n.finishStartupDraft(),async shutdown(){n.shutdown(),await t?.close()}}}function prepareRemoteTarget(e){return{target:e,credentials:createDevelopmentCredentialGate(e.serverUrl),resolveOidcToken:resolveDevelopmentOidcToken,resolveDeployment:t=>resolveVercelDeployment({workspaceRoot:e.workspaceRoot,host:remoteHost(e),signal:t})}}function prepareDevelopmentTarget(e){return e.kind===`local`?{kind:`local`,target:e}:{kind:`remote`,target:e,remote:prepareRemoteTarget(e)}}function withTuiUserAgent(e){let t=new Headers(e);return appendUserAgentProduct(t,`eve-tui/${resolveInstalledPackageInfo().version}`),Object.fromEntries(t.entries())}async function runDevelopmentTui(e){let{target:t,headers:n,initialInput:r,onboard:i,onOnboardingStep:a,onOnboardingTerminal:o,onBootProgress:s,lifecycle:c,startup:l,withExclusiveTerminal:u,...d}=e,f=prepareDevelopmentTarget(t),{serverUrl:p}=t,m={headers:withTuiUserAgent(n)},h=new Client(f.kind===`local`?resolveLocalDevelopmentClientOptions({...m,interactiveClient:!0,serverUrl:p,token:()=>resolveLinkedDevelopmentOidcToken(f.target.workspaceRoot)}):resolveRemoteDevelopmentClientOptions({...m,serverUrl:p,credentials:f.remote.credentials})),g={...d,client:h,serverUrl:p,promptCommandHandler:createPromptCommandHandler({target:t}),availablePromptCommands:promptCommandsFor(t.kind),...t.kind===`local`?{argumentSuggestions:inlineArgumentSuggestions(t.workspaceRoot)}:{},formatTransportError:e=>isVercelAuthChallenge(e)?formatRemoteAuthChallengeMessage(p):toErrorMessage(e)};f.kind===`local`?(g.appRoot=f.target.workspaceRoot,g.probeMcpConnection=probeMcpConnection):g.remote=f.remote,r!==void 0&&(g.initialInput=r),l!==void 0&&(g.renderer=l.renderer,g.startup=l),i!==void 0&&(g.onboard=i),a!==void 0&&(g.onOnboardingStep=a),o!==void 0&&(g.onOnboardingTerminal=o),s!==void 0&&(g.onBootProgress=s),c!==void 0&&(g.lifecycle=c),u!==void 0&&(g.withExclusiveTerminal=u);let _=l?.diagnostics??(f.kind===`local`?await createDevDiagnostics(f.target.workspaceRoot).catch(()=>void 0):void 0);_!==void 0&&(g.diagnostics=_);try{await new EveTUIRunner(g).run()}finally{await _?.close()}}export{runDevelopmentTui,startDevelopmentTuiStartup};
|
|
1
|
+
import{remoteHost}from"./target.js";import{createDevDiagnostics}from"../diagnostics.js";import{promptCommandsFor}from"./prompt-commands.js";import{probeMcpConnection}from"./mcp-connection-status.js";import{createPromptCommandHandler}from"./prompt-command-handler.js";import{formatRemoteAuthChallengeMessage}from"./remote-auth-result.js";import{TerminalRenderer}from"./terminal-renderer.js";import{EveTUIRunner}from"./runner.js";import{Client}from"#client/index.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{toErrorMessage}from"#shared/errors.js";import{resolveDevelopmentOidcToken,resolveLinkedDevelopmentOidcToken}from"#services/dev-client/request-headers.js";import{isVercelAuthChallenge}from"#services/dev-client/vercel-auth-error.js";import{resolveVercelDeployment}from"#setup/vercel-deployment.js";import{appendUserAgentProduct}from"#internal/user-agent.js";import{resolveLocalDevelopmentClientOptions,resolveRemoteDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{createDevelopmentCredentialGate}from"#services/dev-client/credential-gate.js";function inlineArgumentSuggestions(e){return async t=>{if(t===`login`)return[{value:`vercel`,label:`Vercel account`},{value:`chatgpt`,label:`ChatGPT account`},{value:`vercel-api-key`,label:`API key (Vercel AI Gateway)`},{value:`openai-api-key`,label:`API key (OpenAI)`},{value:`anthropic-api-key`,label:`API key (Anthropic)`}];if(t===`model`){let{gatewayModelCapabilities:e}=await import(`#setup/boxes/model-capabilities.js`),{fetchGatewayCatalog:t,modelOptionsFromCatalog:n}=await import(`#setup/boxes/select-model.js`),r=await t().catch(()=>void 0);return n(r).map(t=>{let n=e(r,t.value)?.reasoningLevels;return{value:t.value,label:t.value,hint:t.hint,...n===void 0||n.length===0?{}:{next:[{value:`default`,label:`default`},...n.map(e=>({value:e,label:e}))]}}})}let{browseRegistryCatalog:n}=await import(`#cli/commands/registry.js`);return(await n(e)).items.map(e=>({value:e.address,label:e.name,hint:e.description??e.address}))}}async function startDevelopmentTuiStartup(e){let t=await createDevDiagnostics(e.appRoot).catch(()=>void 0),n=new TerminalRenderer({...e,diagnostics:t,argumentSuggestions:inlineArgumentSuggestions(e.appRoot),onExitRequest:e.onExitRequest});return n.beginStartupDraft({initialDraft:e.initialInput,title:e.name??`eve`}),{diagnostics:t,renderer:n,finish:()=>n.finishStartupDraft(),async shutdown(){n.shutdown(),await t?.close()}}}function prepareRemoteTarget(e){return{target:e,credentials:createDevelopmentCredentialGate(e.serverUrl),resolveOidcToken:resolveDevelopmentOidcToken,resolveDeployment:t=>resolveVercelDeployment({workspaceRoot:e.workspaceRoot,host:remoteHost(e),signal:t})}}function prepareDevelopmentTarget(e){return e.kind===`local`?{kind:`local`,target:e}:{kind:`remote`,target:e,remote:prepareRemoteTarget(e)}}function withTuiUserAgent(e){let t=new Headers(e);return appendUserAgentProduct(t,`eve-tui/${resolveInstalledPackageInfo().version}`),Object.fromEntries(t.entries())}async function runDevelopmentTui(e){let{target:t,headers:n,initialInput:r,onboard:i,onOnboardingStep:a,onOnboardingTerminal:o,onBootProgress:s,lifecycle:c,startup:l,withExclusiveTerminal:u,...d}=e,f=prepareDevelopmentTarget(t),{serverUrl:p}=t,m={headers:withTuiUserAgent(n)},h=new Client(f.kind===`local`?resolveLocalDevelopmentClientOptions({...m,interactiveClient:!0,serverUrl:p,token:()=>resolveLinkedDevelopmentOidcToken(f.target.workspaceRoot)}):resolveRemoteDevelopmentClientOptions({...m,serverUrl:p,credentials:f.remote.credentials})),g={...d,client:h,serverUrl:p,promptCommandHandler:createPromptCommandHandler({target:t}),availablePromptCommands:promptCommandsFor(t.kind),...t.kind===`local`?{argumentSuggestions:inlineArgumentSuggestions(t.workspaceRoot)}:{},formatTransportError:e=>isVercelAuthChallenge(e)?formatRemoteAuthChallengeMessage(p):toErrorMessage(e)};f.kind===`local`?(g.appRoot=f.target.workspaceRoot,g.probeMcpConnection=probeMcpConnection):g.remote=f.remote,r!==void 0&&(g.initialInput=r),l!==void 0&&(g.renderer=l.renderer,g.startup=l),i!==void 0&&(g.onboard=i),a!==void 0&&(g.onOnboardingStep=a),o!==void 0&&(g.onOnboardingTerminal=o),s!==void 0&&(g.onBootProgress=s),c!==void 0&&(g.lifecycle=c),u!==void 0&&(g.withExclusiveTerminal=u);let _=l?.diagnostics??(f.kind===`local`?await createDevDiagnostics(f.target.workspaceRoot).catch(()=>void 0):void 0);_!==void 0&&(g.diagnostics=_);try{await new EveTUIRunner(g).run()}finally{await _?.close()}}export{runDevelopmentTui,startDevelopmentTuiStartup};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";var ClientError=class extends Error{code;status;body;headers;constructor(e,t,n){let r=t||`Server returned ${e}.`,
|
|
1
|
+
import{isObject}from"#shared/guards.js";var ClientError=class extends Error{code;status;body;headers;constructor(e,t,n){let r=Object.freeze(Object.fromEntries(new Headers(n).entries())),i=r[`content-type`]?.toLowerCase(),a=t||`Server returned ${e}.`,o;try{let e=JSON.parse(t);isObject(e)&&(typeof e.error==`string`&&(a=e.error),typeof e.code==`string`&&(o=e.code))}catch{i?.includes(`text/html`)&&(a=`Server returned ${e} with an HTML response. Check the eve route and development server configuration.`)}super(a),this.name=`ClientError`,this.code=o,this.status=e,this.body=t,this.headers=r}};export{ClientError};
|
|
@@ -26,7 +26,8 @@ interface FollowStreamInput {
|
|
|
26
26
|
readonly streamReadIdleTimeoutMs?: number;
|
|
27
27
|
readonly resolveHeaders: () => Promise<Headers>;
|
|
28
28
|
readonly redirect?: ClientRedirectPolicy;
|
|
29
|
-
|
|
29
|
+
/** eve stream route path, such as a session stream or a parent-origin subagent stream. */
|
|
30
|
+
readonly path: string;
|
|
30
31
|
readonly signal?: AbortSignal;
|
|
31
32
|
readonly startIndex: number;
|
|
32
33
|
/** Follow the live stream after the durable tail (default). `false` bounds the read at the tail. */
|
|
@@ -37,7 +38,7 @@ interface OpenStreamInput extends FollowStreamInput {
|
|
|
37
38
|
readonly requestTailIndex?: boolean;
|
|
38
39
|
}
|
|
39
40
|
/**
|
|
40
|
-
* Follows
|
|
41
|
+
* Follows one durable event stream route from an absolute cursor,
|
|
41
42
|
* transparently reconnecting whenever the transport ends.
|
|
42
43
|
*
|
|
43
44
|
* Transport endings reconnect from the advanced cursor. Progress resets the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{EVE_STREAM_CONTROL_VERSION,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_TAIL_INDEX_HEADER}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";import{readMessageStreamVersion}from"#client/stream-version.js";const DEFAULT_STREAM_RECONNECT_POLICY={retryableErrorStatuses:new Set([404,409,425,500,502,503,504]),streamIdleReconnectPolicy:{baseDelayMs:250,maxAttempts:5,maxDelayMs:4e3},streamOpenReconnectPolicy:{baseDelayMs:250,maxAttempts:12,maxDelayMs:5e3}},NO_STREAM_RECONNECT_POLICY={...DEFAULT_STREAM_RECONNECT_POLICY,streamIdleReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy,maxAttempts:0},streamOpenReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy,maxAttempts:1}};function resolveRetryPolicy(e,t){return{...t,...e}}function resolveStreamReconnectPolicy(e,t=!1){if(e&&`reconnect`in e&&e.reconnect===!1)return NO_STREAM_RECONNECT_POLICY;let n=e;return{retryableErrorStatuses:n?.retryableErrorStatuses?new Set(n.retryableErrorStatuses):DEFAULT_STREAM_RECONNECT_POLICY.retryableErrorStatuses,streamIdleReconnectPolicy:resolveRetryPolicy(n?.streamIdleReconnectPolicy,{...DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy,maxAttempts:t?1/0:DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy.maxAttempts}),streamOpenReconnectPolicy:resolveRetryPolicy(n?.streamOpenReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy)}}async function*followStreamIterable(e){if(e.follow===!1&&e.startIndex<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);let resolvePolicy=()=>resolveStreamReconnectPolicy(e.resolveReconnectPolicy===void 0?e.streamReconnectPolicy:e.resolveReconnectPolicy(),e.keepAlive),t=resolvePolicy(),n=t.streamIdleReconnectPolicy,r=e.startIndex,i=n.baseDelayMs,a=0,o=!0,s,c=!1;for(;;){t=resolvePolicy(),n=t.streamIdleReconnectPolicy;let l;try{l=await openStreamBody({...e,retryPolicy:t,startIndex:r,requestTailIndex:(e.follow===!1||e.onCaughtUp!==void 0)&&s===void 0})}catch(t){if(e.signal?.aborted)return;throw t}if((e.follow===!1||e.onCaughtUp!==void 0)&&s===void 0&&(s=l.tailIndex,s===void 0))throw l.close(),Error(`stream({ follow: false }) requires the server to report the ${EVE_STREAM_TAIL_INDEX_HEADER} header. The agent may be running an older eve version.`);if(!c&&s!==void 0&&r>s&&(c=!0,e.onCaughtUp?.()),e.follow===!1&&s!==void 0&&r>s){l.close();return}let u=!1,d=!1;try{for await(let t of readNdjsonStream(l.body,{signal:e.signal,controlVersion:l.controlVersion,idleTimeoutMs:e.streamReadIdleTimeoutMs??15e3,onLeaseEnded:()=>{d=!0},streamVersion:l.streamVersion}))if(r+=1,u=!0,i=n.baseDelayMs,a=0,yield t,!c&&s!==void 0&&r>s&&(c=!0,e.onCaughtUp?.()),e.follow===!1&&s!==void 0&&r>s)return}catch(e){if(!isStreamDisconnectError(e))throw e}finally{l.close()}if(n=resolvePolicy().streamIdleReconnectPolicy,e.signal?.aborted||e.startIndex<0||n.maxAttempts===0)return;if(!d){if(!u&&!o&&(a+=1)>=n.maxAttempts||(o=!1,await sleep(i,e.signal),e.signal?.aborted))return;i=Math.min(i*2,n.maxDelayMs)}}}async function openStreamBody(e){let t=e.retryPolicy??resolveStreamReconnectPolicy(e.streamReconnectPolicy,e.keepAlive),n=t.streamOpenReconnectPolicy,r,i,a,o=n.baseDelayMs,s=e.startIndex>=0&&t.streamIdleReconnectPolicy.maxAttempts>0?EVE_STREAM_CONTROL_VERSION:void 0,c={};s!==void 0&&(c[EVE_STREAM_CONTROL_VERSION_QUERY]=s),e.startIndex!==0&&(c.startIndex=String(e.startIndex)),e.requestTailIndex===!0&&(c.includeTailIndex=`1`);for(let l=0;l<n.maxAttempts;l+=1){e.signal?.throwIfAborted();let u=createClientUrl(e.host,e.path,Object.keys(c).length>0?c:void 0),d=await e.resolveHeaders();e.signal?.throwIfAborted();let f=new AbortController,p=e.signal?AbortSignal.any([e.signal,f.signal]):f.signal,m;try{m=await fetch(u,{cache:`no-store`,headers:d,redirect:e.redirect,signal:p})}catch(t){if(e.signal?.aborted||!isStreamDisconnectError(t)||l===n.maxAttempts-1)throw t;await sleep(o,e.signal),o=Math.min(o*2,n.maxDelayMs);continue}if(m.ok){if(!m.body)throw new ClientError(m.status,`Response body is null.`,m.headers);let e=!1;return{body:m.body,close:()=>{e||(e=!0,m.body?.cancel().catch(()=>{}),f.abort())},controlVersion:s,streamVersion:readMessageStreamVersion(m.headers),tailIndex:parseTailIndexHeader(m.headers)}}if(r=m.status,i=await m.text(),a=m.headers,!t.retryableErrorStatuses.has(m.status))throw new ClientError(m.status,i,m.headers);l<n.maxAttempts-1&&(await sleep(o,e.signal),o=Math.min(o*2,n.maxDelayMs))}throw new ClientError(r??0,i??`Failed to open message stream.`,a)}function parseTailIndexHeader(e){let t=e.get(EVE_STREAM_TAIL_INDEX_HEADER);if(t===null||!/^-?\d+$/.test(t))return;let n=Number(t);return Number.isSafeInteger(n)?n:void 0}async function sleep(e,t){t?.aborted||await new Promise(n=>{let onAbort=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener(`abort`,onAbort),n()},e);t?.addEventListener(`abort`,onAbort,{once:!0})})}export{followStreamIterable,openStreamBody,sleep};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { MessageStreamEvent } from "#protocol/message.js";
|
|
1
|
+
import type { MessageStreamEvent, SubagentCalledStreamEvent } from "#protocol/message.js";
|
|
2
2
|
import { MessageResponse } from "#client/message-response.js";
|
|
3
3
|
import type { InputResponse } from "#shared/input.js";
|
|
4
4
|
import type { CancelSessionResult, ClearResult, ClientSessionState, CompactResult, ClientRedirectPolicy, CreateSessionOptions, RespondTurnOptions, ResetResult, SendTurnInput, SendTurnOptions, SessionSnapshot, StreamOptions } from "#client/types.js";
|
|
@@ -57,6 +57,21 @@ export declare class ClientSession {
|
|
|
57
57
|
}): Promise<ResetResult>;
|
|
58
58
|
/** Opens this session's durable event stream from its stored cursor. */
|
|
59
59
|
stream(options?: StreamOptions): AsyncIterable<MessageStreamEvent>;
|
|
60
|
+
/**
|
|
61
|
+
* Follows one delegated child's durable event stream through this parent session.
|
|
62
|
+
*
|
|
63
|
+
* Pass a `subagent.called` event from this session. The client reads its
|
|
64
|
+
* `childStreamPath` with this session's host and credentials: a local child's
|
|
65
|
+
* own stream route, or the parent-origin proxy for a remote child, which the
|
|
66
|
+
* parent deployment authenticates to the remote agent. Reading the child never
|
|
67
|
+
* advances this session's cursor. The child cursor starts at `0`; pass
|
|
68
|
+
* `startIndex` to resume. Stop at a child turn boundary with
|
|
69
|
+
* `isCurrentTurnBoundaryEvent`.
|
|
70
|
+
*
|
|
71
|
+
* @throws {Error} When `called` belongs to a different session or has no
|
|
72
|
+
* `childStreamPath` because an older eve version recorded it.
|
|
73
|
+
*/
|
|
74
|
+
streamSubagent(called: SubagentCalledStreamEvent, options?: StreamOptions): AsyncIterable<MessageStreamEvent>;
|
|
60
75
|
[followSession](options: FollowSessionOptions): AsyncIterable<MessageStreamEvent>;
|
|
61
76
|
}
|
|
62
77
|
/** @internal Follow continuously while the frontend owns the session. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{updatePendingAuthorizations}from"#client/session-utils.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{followStreamIterable,sleep}from"#client/open-stream.js";import{cancelClientSession,clearClientSession,compactClientSession,resetClientSession}from"#client/session-controls.js";import{serializeOutputSchema}from"#tools/schema.js";const followSession=Symbol(`followClientSession`);var ClientSession=class ClientSession{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(e,t){let n=await postTurn(e,EVE_SESSION_ROUTE_PATH,t,!0),{sessionId:r}=await readAcceptedMessage(n),i=new ClientSession(e,{sessionId:r,streamIndex:0});return{response:i.#r(n,t,0),session:i}}static async prewarm(e,t={}){let{sessionId:n}=await readAcceptedMessage(await postCreateSession(e,t));return new ClientSession(e,{sessionId:n,streamIndex:0})}get state(){return this.#t}async snapshot(e){e?.signal?.throwIfAborted();let t=[];for await(let n of this.#s({follow:!1,signal:e?.signal,startIndex:0}))t.push(n);return e?.signal?.throwIfAborted(),{events:t,session:{sessionId:this.#t.sessionId,streamIndex:t.length}}}async send(e,t={}){return await this.#n({...t,message:e},!0)}async respond(e,t={}){if(e.length===0)throw Error(`ClientSession.respond() requires at least one input response.`);return await this.#n({...t,inputResponses:e},!1)}async#n(e,t){let n=this.#t.streamIndex,r=createEveSessionRoutePath(this.#t.sessionId),i=t?await postSessionSend(this.#e,r,e):await postTurn(this.#e,r,e,!1),{sessionId:a,deliveryId:o}=await readAcceptedMessage(i,this.#t.sessionId);if(a!==this.#t.sessionId)throw Error(`Message route returned a different session id.`);if(e.message!==void 0&&o===void 0)throw Error(`Message route did not return a delivery id. Update the server before sending with this client.`);return this.#r(i,e,n,e.message===void 0?void 0:o)}async cancel(e){return await cancelClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}async clear(){return await clearClientSession({context:this.#e,sessionId:this.#t.sessionId})}async compact(){return await compactClientSession({context:this.#e,sessionId:this.#t.sessionId})}async reset(e){return await resetClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}stream(e){if(e?.follow===!1&&(e.startIndex??this.#t.streamIndex)<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return this.#a(e)}[followSession](e){return this.#a({...e,keepAlive:!0})}#r(e,t,n,r){return e.body?.cancel().catch(()=>{}),new MessageResponse({cancelTurn:async e=>await this.cancel({turnId:e}),createStream:e=>this.#i(n,t,r,e),deliveryId:r,sessionId:this.#t.sessionId})}async*#i(e,t,n,r){let i=0,a=n===void 0,o=!1,s=new Set;try{for await(let c of r??this.#s({headers:t.headers,keepAlive:!0,signal:t.signal,startIndex:e,streamReconnectPolicy:t.streamReconnectPolicy})){if(i+=1,n!==void 0){let e=c.meta?.deliveryIds?.includes(n)===!0,t=c.type===`session.failed`||c.type===`session.completed`;if(!e&&t&&(!a||c.type===`session.completed`))throw Error(`The session ended before the accepted message reached its turn boundary.`);if(!a&&!e||!t&&c.meta?.deliveryIds!==void 0&&!e)continue;a=!0}if(updatePendingAuthorizations(s,c),o=isCurrentTurnBoundaryEvent(c)&&(c.type!==`session.waiting`||s.size===0),yield c,o)break}if(n!==void 0&&!o&&!t.signal?.aborted)throw Error(`The response stream ended before the accepted message reached its turn boundary.`)}finally{this.#o(e+i)}}async*#a(e){let t=e?.startIndex??this.#t.streamIndex,n=0;for await(let r of this.#s({follow:e?.follow,headers:e?.headers,keepAlive:e?.keepAlive,onCaughtUp:e?.onCaughtUp,resolveHeaders:e?.resolveHeaders,resolveReconnectPolicy:e?.resolveReconnectPolicy,signal:e?.signal,startIndex:t,streamReconnectPolicy:e?.streamReconnectPolicy}))n+=1,t>=0&&this.#o(t+n),yield r}#o(e){this.#t={sessionId:this.#t.sessionId,streamIndex:Math.max(this.#t.streamIndex,e)}}#s(e){return followStreamIterable({onCaughtUp:e.onCaughtUp,follow:e.follow,host:this.#e.host,keepAlive:e.keepAlive,resolveHeaders:()=>this.#e.resolveHeaders(e.resolveHeaders?.()??e.headers),
|
|
1
|
+
import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath,createEveSessionStreamRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{updatePendingAuthorizations}from"#client/session-utils.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{followStreamIterable,sleep}from"#client/open-stream.js";import{cancelClientSession,clearClientSession,compactClientSession,resetClientSession}from"#client/session-controls.js";import{serializeOutputSchema}from"#tools/schema.js";const followSession=Symbol(`followClientSession`);var ClientSession=class ClientSession{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(e,t){let n=await postTurn(e,EVE_SESSION_ROUTE_PATH,t,!0),{sessionId:r}=await readAcceptedMessage(n),i=new ClientSession(e,{sessionId:r,streamIndex:0});return{response:i.#r(n,t,0),session:i}}static async prewarm(e,t={}){let{sessionId:n}=await readAcceptedMessage(await postCreateSession(e,t));return new ClientSession(e,{sessionId:n,streamIndex:0})}get state(){return this.#t}async snapshot(e){e?.signal?.throwIfAborted();let t=[];for await(let n of this.#s({follow:!1,signal:e?.signal,startIndex:0}))t.push(n);return e?.signal?.throwIfAborted(),{events:t,session:{sessionId:this.#t.sessionId,streamIndex:t.length}}}async send(e,t={}){return await this.#n({...t,message:e},!0)}async respond(e,t={}){if(e.length===0)throw Error(`ClientSession.respond() requires at least one input response.`);return await this.#n({...t,inputResponses:e},!1)}async#n(e,t){let n=this.#t.streamIndex,r=createEveSessionRoutePath(this.#t.sessionId),i=t?await postSessionSend(this.#e,r,e):await postTurn(this.#e,r,e,!1),{sessionId:a,deliveryId:o}=await readAcceptedMessage(i,this.#t.sessionId);if(a!==this.#t.sessionId)throw Error(`Message route returned a different session id.`);if(e.message!==void 0&&o===void 0)throw Error(`Message route did not return a delivery id. Update the server before sending with this client.`);return this.#r(i,e,n,e.message===void 0?void 0:o)}async cancel(e){return await cancelClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}async clear(){return await clearClientSession({context:this.#e,sessionId:this.#t.sessionId})}async compact(){return await compactClientSession({context:this.#e,sessionId:this.#t.sessionId})}async reset(e){return await resetClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}stream(e){if(e?.follow===!1&&(e.startIndex??this.#t.streamIndex)<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return this.#a(e)}streamSubagent(e,t){if(e.data.sessionId!==this.#t.sessionId)throw Error(`streamSubagent() requires a subagent.called event from session ${this.#t.sessionId}, but it came from session ${e.data.sessionId}.`);if(typeof e.data.childStreamPath!=`string`)throw Error(`streamSubagent() requires a subagent.called event with childStreamPath, but call ${e.data.callId} has none. The event was recorded by an older eve version.`);let n=t?.startIndex??0;if(t?.follow===!1&&n<0)throw Error(`streamSubagent({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return followStreamIterable({follow:t?.follow,host:this.#e.host,path:e.data.childStreamPath,redirect:this.#e.redirect,resolveHeaders:()=>this.#e.resolveHeaders(),signal:t?.signal,startIndex:n,streamReconnectPolicy:t?.streamReconnectPolicy})}[followSession](e){return this.#a({...e,keepAlive:!0})}#r(e,t,n,r){return e.body?.cancel().catch(()=>{}),new MessageResponse({cancelTurn:async e=>await this.cancel({turnId:e}),createStream:e=>this.#i(n,t,r,e),deliveryId:r,sessionId:this.#t.sessionId})}async*#i(e,t,n,r){let i=0,a=n===void 0,o=!1,s=new Set;try{for await(let c of r??this.#s({headers:t.headers,keepAlive:!0,signal:t.signal,startIndex:e,streamReconnectPolicy:t.streamReconnectPolicy})){if(i+=1,n!==void 0){let e=c.meta?.deliveryIds?.includes(n)===!0,t=c.type===`session.failed`||c.type===`session.completed`;if(!e&&t&&(!a||c.type===`session.completed`))throw Error(`The session ended before the accepted message reached its turn boundary.`);if(!a&&!e||!t&&c.meta?.deliveryIds!==void 0&&!e)continue;a=!0}if(updatePendingAuthorizations(s,c),o=isCurrentTurnBoundaryEvent(c)&&(c.type!==`session.waiting`||s.size===0),yield c,o)break}if(n!==void 0&&!o&&!t.signal?.aborted)throw Error(`The response stream ended before the accepted message reached its turn boundary.`)}finally{this.#o(e+i)}}async*#a(e){let t=e?.startIndex??this.#t.streamIndex,n=0;for await(let r of this.#s({follow:e?.follow,headers:e?.headers,keepAlive:e?.keepAlive,onCaughtUp:e?.onCaughtUp,resolveHeaders:e?.resolveHeaders,resolveReconnectPolicy:e?.resolveReconnectPolicy,signal:e?.signal,startIndex:t,streamReconnectPolicy:e?.streamReconnectPolicy}))n+=1,t>=0&&this.#o(t+n),yield r}#o(e){this.#t={sessionId:this.#t.sessionId,streamIndex:Math.max(this.#t.streamIndex,e)}}#s(e){return followStreamIterable({onCaughtUp:e.onCaughtUp,follow:e.follow,host:this.#e.host,keepAlive:e.keepAlive,resolveHeaders:()=>this.#e.resolveHeaders(e.resolveHeaders?.()??e.headers),path:createEveSessionStreamRoutePath(this.#t.sessionId),redirect:this.#e.redirect,signal:e.signal,startIndex:e.startIndex,streamReconnectPolicy:e.streamReconnectPolicy,resolveReconnectPolicy:e.resolveReconnectPolicy})}};function followClientSession(e,t){return e[followSession](t)}async function postSessionSend(e,t,n){let r=Date.now()+2e4,i=250;for(;;){try{return await postTurn(e,t,n,!1)}catch(e){if(!isSessionNotReady(e))throw e;let t=r-Date.now();if(t<=0)throw e;await sleep(Math.min(i,t),n.signal)}n.signal?.throwIfAborted(),i=Math.min(i*2,2e3)}}async function postCreateSession(e,t){let n=await e.resolveHeaders(t.headers),r=await fetch(createClientUrl(e.host,EVE_SESSION_ROUTE_PATH),{headers:n,method:`POST`,redirect:e.redirect,signal:t.signal??null});if(!r.ok){let e=await r.text();throw new ClientError(r.status,e,r.headers)}return r}function isSessionNotReady(e){return e instanceof ClientError&&e.status===409&&e.code===`session_not_ready`}async function postTurn(e,t,n,r){let i=createMessageBody(n,r);if(i===null)throw Error(r?`Creating a session requires a non-empty message.`:`A session turn requires a non-empty message or inputResponses.`);let a=await e.resolveHeaders(n.headers);a.set(`content-type`,`application/json`);let o=await fetch(createClientUrl(e.host,t),{body:JSON.stringify(i),headers:a,method:`POST`,redirect:e.redirect,signal:n.signal??null});if(!o.ok){let e=await o.text();throw new ClientError(o.status,e,o.headers)}return o}async function readAcceptedMessage(e,t){let n=await e.json(),r=(typeof n.sessionId==`string`?n.sessionId:void 0)??e.headers.get(EVE_SESSION_ID_HEADER)?.trim()??t;if(!r)throw Error(`Message route did not return a session id.`);return{sessionId:r,deliveryId:typeof n.deliveryId==`string`&&n.deliveryId.length>0?n.deliveryId:void 0}}function createMessageBody(e,t){let n={};e.message!==void 0&&(n.message=e.message),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses),!t&&e.message!==void 0&&e.turnPolicy!==void 0&&(n.turnPolicy=e.turnPolicy),e.message!==void 0&&e.taskDeliveryPolicy!==void 0&&(n.taskDeliveryPolicy=e.taskDeliveryPolicy),e.clientContext!==void 0&&(n.clientContext=e.clientContext);let r=serializeOutputSchema(e.outputSchema);return r!==void 0&&(n.outputSchema=r),t&&n.message===void 0||n.message===void 0&&n.inputResponses===void 0?null:n}export{ClientSession,followClientSession};
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
"zod": "4.5.4",
|
|
57
57
|
"zod-validation-error": "5.0.0"
|
|
58
58
|
},
|
|
59
|
-
"scriptHash": "
|
|
59
|
+
"scriptHash": "dbf0ea1c3daf06959bc96021fbad02b134f0aff11b72cbb3f6bfdc73e9fa42a1",
|
|
60
60
|
"toolVersions": {
|
|
61
61
|
"rolldown": "1.2.9",
|
|
62
62
|
"typescript": "7.0.2"
|
|
@@ -64,6 +64,8 @@ export declare function normalizeLogicalPath(input: string): string;
|
|
|
64
64
|
export declare function getSupportedModuleBaseName(name: string): string | null;
|
|
65
65
|
/** Returns whether a filename is a TypeScript declaration module. */
|
|
66
66
|
export declare function isTypeScriptDeclarationFileName(name: string): boolean;
|
|
67
|
+
/** Identifies colocated tests to omit from automatic agent source discovery. */
|
|
68
|
+
export declare function isAuthoredTestPath(path: string): boolean;
|
|
67
69
|
/** Returns whether a filename is a source map for a generated module or declaration. */
|
|
68
70
|
export declare function isGeneratedSourceMapFileName(name: string): boolean;
|
|
69
71
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sep}from"node:path";const SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`],PROJECT_MARKER_FILE_NAMES=[`package.json`,`vercel.json`],PROJECT_MARKER_FILE_NAME_SET=new Set(PROJECT_MARKER_FILE_NAMES),GENERATED_AGENT_DIRECTORY_NAMES=new Set([`.devtools`,`.eve`,`.next`,`.output`,`.vercel`,`node_modules`]);function getDirectoryEntryType(e){return e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function isProjectMarkerEntry(e,t){return t===`file`&&PROJECT_MARKER_FILE_NAME_SET.has(e)}function isDiscoverableAgentRootEntry(e,t){let n=classifyAgentRootEntry(e,t);return n!==`unknown`&&n!==`ignored-directory`&&n!==`lib-directory`&&n!==`memory-directory`}function classifyAgentRootEntry(e,t){if(t===`file`)return matchesSupportedModuleBaseName(e,`agent`)?`agent-config-module`:e.toLowerCase()===`instructions.md`?`instructions-markdown`:matchesSupportedModuleBaseName(e,`instructions`)?`instructions-module`:matchesSupportedModuleBaseName(e,`memory`)?`memory-module`:e.toLowerCase()===`system.md`?`system-markdown`:matchesSupportedModuleBaseName(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(GENERATED_AGENT_DIRECTORY_NAMES.has(e))return`ignored-directory`;if(e===`channels`)return`channels-directory`;if(e===`connections`)return`connections-directory`;if(e===`extensions`)return`extensions-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`instructions`)return`instructions-directory`;if(e===`instrumentation`)return`instrumentation-directory`;if(e===`lib`)return`lib-directory`;if(e===`memory`)return`memory-directory`;if(e===`skills`)return`skills-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`tools`)return`tools-directory`;if(e===`schedules`)return`schedules-directory`;if(e===`subagents`)return`subagents-directory`}return`unknown`}function classifyLocalSubagentEntry(e,t){if(t===`file`)return matchesSupportedModuleBaseName(e,`agent`)?`agent-config-module`:e.toLowerCase()===`instructions.md`?`instructions-markdown`:matchesSupportedModuleBaseName(e,`instructions`)?`instructions-module`:matchesSupportedModuleBaseName(e,`memory`)?`memory-module`:e.toLowerCase()===`system.md`?`system-markdown`:matchesSupportedModuleBaseName(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(GENERATED_AGENT_DIRECTORY_NAMES.has(e))return`ignored-directory`;if(e===`connections`)return`connections-directory`;if(e===`extensions`)return`extensions-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`instructions`)return`instructions-directory`;if(e===`lib`)return`lib-directory`;if(e===`memory`)return`memory-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`skills`)return`skills-directory`;if(e===`tools`)return`tools-directory`;if(e===`subagents`)return`subagents-directory`;if(e===`schedules`)return`invalid-schedules-directory`}return`unknown`}function classifySkillPackageEntry(e,t){if(t===`file`)return e.toLowerCase()===`skill.md`?`skill-markdown`:`skill-resource`;if(t===`directory`){if(e===`scripts`)return`skill-scripts-directory`;if(e===`references`)return`skill-references-directory`;if(e===`assets`)return`skill-assets-directory`}return`skill-resource`}function classifySkillsDirectoryEntry(e,t){if(t===`directory`)return`skill-package-directory`;if(t===`file`){if(isTypeScriptDeclarationFileName(e))return`ignored-declaration`;if(isGeneratedSourceMapFileName(e))return`ignored-source-map`;if(e.toLowerCase().endsWith(`.md`))return`flat-skill-markdown`;if(getSupportedModuleBaseName(e)!==null)return`flat-skill-module`}return`unknown`}function normalizeLogicalPath(e){return e.replaceAll(sep,`/`).replace(/^\.\//,``).replace(/^\/+/,``)}function getSupportedModuleBaseName(e){if(isTypeScriptDeclarationFileName(e))return null;for(let t of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(e.endsWith(t)&&e.length>t.length)return e.slice(0,-t.length);return null}function isTypeScriptDeclarationFileName(e){return/\.d\.(?:cts|mts|ts)$/.test(e)}function isGeneratedSourceMapFileName(e){if(!e.endsWith(`.map`))return!1;let t=e.slice(0,-4);return isTypeScriptDeclarationFileName(t)||getSupportedModuleBaseName(t)!==null}function matchesSupportedModuleBaseName(e,t){return getSupportedModuleBaseName(e)===t}function stripLogicalPathExtension(e){let t=normalizeLogicalPath(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`.`);return r===-1||r<n?t:t.slice(0,r)}export{PROJECT_MARKER_FILE_NAMES,SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS,classifyAgentRootEntry,classifyLocalSubagentEntry,classifySkillPackageEntry,classifySkillsDirectoryEntry,getDirectoryEntryType,getSupportedModuleBaseName,isDiscoverableAgentRootEntry,isGeneratedSourceMapFileName,isProjectMarkerEntry,isTypeScriptDeclarationFileName,matchesSupportedModuleBaseName,normalizeLogicalPath,stripLogicalPathExtension};
|
|
1
|
+
import{sep}from"node:path";const SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`],PROJECT_MARKER_FILE_NAMES=[`package.json`,`vercel.json`],PROJECT_MARKER_FILE_NAME_SET=new Set(PROJECT_MARKER_FILE_NAMES),GENERATED_AGENT_DIRECTORY_NAMES=new Set([`.devtools`,`.eve`,`.next`,`.output`,`.vercel`,`node_modules`]);function getDirectoryEntryType(e){return e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function isProjectMarkerEntry(e,t){return t===`file`&&PROJECT_MARKER_FILE_NAME_SET.has(e)}function isDiscoverableAgentRootEntry(e,t){let n=classifyAgentRootEntry(e,t);return n!==`unknown`&&n!==`ignored-directory`&&n!==`lib-directory`&&n!==`memory-directory`}function classifyAgentRootEntry(e,t){if(t===`file`)return matchesSupportedModuleBaseName(e,`agent`)?`agent-config-module`:e.toLowerCase()===`instructions.md`?`instructions-markdown`:matchesSupportedModuleBaseName(e,`instructions`)?`instructions-module`:matchesSupportedModuleBaseName(e,`memory`)?`memory-module`:e.toLowerCase()===`system.md`?`system-markdown`:matchesSupportedModuleBaseName(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(GENERATED_AGENT_DIRECTORY_NAMES.has(e))return`ignored-directory`;if(e===`channels`)return`channels-directory`;if(e===`connections`)return`connections-directory`;if(e===`extensions`)return`extensions-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`instructions`)return`instructions-directory`;if(e===`instrumentation`)return`instrumentation-directory`;if(e===`lib`)return`lib-directory`;if(e===`memory`)return`memory-directory`;if(e===`skills`)return`skills-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`tools`)return`tools-directory`;if(e===`schedules`)return`schedules-directory`;if(e===`subagents`)return`subagents-directory`}return`unknown`}function classifyLocalSubagentEntry(e,t){if(t===`file`)return matchesSupportedModuleBaseName(e,`agent`)?`agent-config-module`:e.toLowerCase()===`instructions.md`?`instructions-markdown`:matchesSupportedModuleBaseName(e,`instructions`)?`instructions-module`:matchesSupportedModuleBaseName(e,`memory`)?`memory-module`:e.toLowerCase()===`system.md`?`system-markdown`:matchesSupportedModuleBaseName(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(GENERATED_AGENT_DIRECTORY_NAMES.has(e))return`ignored-directory`;if(e===`connections`)return`connections-directory`;if(e===`extensions`)return`extensions-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`instructions`)return`instructions-directory`;if(e===`lib`)return`lib-directory`;if(e===`memory`)return`memory-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`skills`)return`skills-directory`;if(e===`tools`)return`tools-directory`;if(e===`subagents`)return`subagents-directory`;if(e===`schedules`)return`invalid-schedules-directory`}return`unknown`}function classifySkillPackageEntry(e,t){if(t===`file`)return e.toLowerCase()===`skill.md`?`skill-markdown`:`skill-resource`;if(t===`directory`){if(e===`scripts`)return`skill-scripts-directory`;if(e===`references`)return`skill-references-directory`;if(e===`assets`)return`skill-assets-directory`}return`skill-resource`}function classifySkillsDirectoryEntry(e,t){if(t===`directory`)return`skill-package-directory`;if(t===`file`){if(isTypeScriptDeclarationFileName(e))return`ignored-declaration`;if(isGeneratedSourceMapFileName(e))return`ignored-source-map`;if(e.toLowerCase().endsWith(`.md`))return`flat-skill-markdown`;if(getSupportedModuleBaseName(e)!==null)return`flat-skill-module`}return`unknown`}function normalizeLogicalPath(e){return e.replaceAll(sep,`/`).replace(/^\.\//,``).replace(/^\/+/,``)}function getSupportedModuleBaseName(e){if(isTypeScriptDeclarationFileName(e))return null;for(let t of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(e.endsWith(t)&&e.length>t.length)return e.slice(0,-t.length);return null}function isTypeScriptDeclarationFileName(e){return/\.d\.(?:cts|mts|ts)$/.test(e)}function isAuthoredTestPath(e){return/(?:^|[/\\])__tests__(?:[/\\]|$)/.test(e)||/\.(?:test|spec)\.[cm]?[jt]s$/.test(e)}function isGeneratedSourceMapFileName(e){if(!e.endsWith(`.map`))return!1;let t=e.slice(0,-4);return isTypeScriptDeclarationFileName(t)||getSupportedModuleBaseName(t)!==null}function matchesSupportedModuleBaseName(e,t){return getSupportedModuleBaseName(e)===t}function stripLogicalPathExtension(e){let t=normalizeLogicalPath(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`.`);return r===-1||r<n?t:t.slice(0,r)}export{PROJECT_MARKER_FILE_NAMES,SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS,classifyAgentRootEntry,classifyLocalSubagentEntry,classifySkillPackageEntry,classifySkillsDirectoryEntry,getDirectoryEntryType,getSupportedModuleBaseName,isAuthoredTestPath,isDiscoverableAgentRootEntry,isGeneratedSourceMapFileName,isProjectMarkerEntry,isTypeScriptDeclarationFileName,matchesSupportedModuleBaseName,normalizeLogicalPath,stripLogicalPathExtension};
|