eve 0.14.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/src/channel/compiled-channel.js +2 -1
  3. package/dist/src/cli/dev/tui/runner.js +1 -1
  4. package/dist/src/cli/dev/tui/setup-panel.d.ts +3 -4
  5. package/dist/src/cli/dev/tui/setup-panel.js +2 -2
  6. package/dist/src/cli/dev/tui/status-line.d.ts +6 -3
  7. package/dist/src/cli/dev/tui/status-line.js +1 -1
  8. package/dist/src/cli/dev/tui/terminal-renderer.js +1 -1
  9. package/dist/src/cli/dev/tui/vercel-status.d.ts +2 -2
  10. package/dist/src/cli/dev/tui/vercel-status.js +1 -1
  11. package/dist/src/cli/run.d.ts +2 -2
  12. package/dist/src/cli/run.js +2 -2
  13. package/dist/src/evals/assertions/collector.d.ts +19 -6
  14. package/dist/src/evals/assertions/collector.js +1 -1
  15. package/dist/src/evals/assertions/run.d.ts +24 -17
  16. package/dist/src/evals/assertions/run.js +2 -2
  17. package/dist/src/evals/assertions/scoped.d.ts +17 -0
  18. package/dist/src/evals/assertions/scoped.js +1 -0
  19. package/dist/src/evals/cli/eval.js +1 -1
  20. package/dist/src/evals/context.d.ts +1 -0
  21. package/dist/src/evals/context.js +1 -1
  22. package/dist/src/evals/control-flow.d.ts +9 -0
  23. package/dist/src/evals/control-flow.js +1 -0
  24. package/dist/src/evals/define-eval.d.ts +1 -1
  25. package/dist/src/evals/define-eval.js +1 -1
  26. package/dist/src/evals/expect/index.d.ts +5 -3
  27. package/dist/src/evals/expect/index.js +1 -1
  28. package/dist/src/evals/index.d.ts +2 -2
  29. package/dist/src/evals/match.d.ts +50 -13
  30. package/dist/src/evals/match.js +1 -1
  31. package/dist/src/evals/runner/artifacts.js +1 -1
  32. package/dist/src/evals/runner/derive-run-facts.js +1 -1
  33. package/dist/src/evals/runner/execute-eval.js +1 -1
  34. package/dist/src/evals/runner/execute-task.d.ts +1 -0
  35. package/dist/src/evals/runner/execute-task.js +1 -1
  36. package/dist/src/evals/runner/reporters/braintrust.js +1 -1
  37. package/dist/src/evals/runner/reporters/console.js +1 -1
  38. package/dist/src/evals/runner/reporters/junit.js +3 -2
  39. package/dist/src/evals/runner/run-evals.js +1 -1
  40. package/dist/src/evals/runner/verdict.d.ts +1 -0
  41. package/dist/src/evals/runner/verdict.js +1 -1
  42. package/dist/src/evals/session.d.ts +9 -5
  43. package/dist/src/evals/session.js +1 -1
  44. package/dist/src/evals/types.d.ts +69 -47
  45. package/dist/src/execution/workflow-callback-url.d.ts +8 -0
  46. package/dist/src/execution/workflow-callback-url.js +1 -1
  47. package/dist/src/execution/workflow-entry.js +1 -1
  48. package/dist/src/execution/workflow-steps.js +1 -1
  49. package/dist/src/harness/emission.d.ts +13 -27
  50. package/dist/src/harness/emission.js +1 -1
  51. package/dist/src/harness/step-hooks.d.ts +3 -3
  52. package/dist/src/harness/step-hooks.js +1 -1
  53. package/dist/src/harness/tool-loop.js +1 -1
  54. package/dist/src/internal/application/compiled-artifacts.js +1 -1
  55. package/dist/src/internal/application/package.d.ts +12 -0
  56. package/dist/src/internal/application/package.js +1 -1
  57. package/dist/src/internal/application/paths.d.ts +6 -0
  58. package/dist/src/internal/application/paths.js +1 -1
  59. package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
  60. package/dist/src/internal/nitro/host/dev-server-state.d.ts +20 -0
  61. package/dist/src/internal/nitro/host/dev-server-state.js +1 -0
  62. package/dist/src/internal/nitro/host/start-development-server.d.ts +12 -5
  63. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  64. package/dist/src/internal/nitro/host/types.d.ts +25 -3
  65. package/dist/src/internal/nitro/host.d.ts +2 -2
  66. package/dist/src/internal/nitro/host.js +1 -1
  67. package/dist/src/internal/workflow/configure-world.d.ts +6 -0
  68. package/dist/src/internal/workflow/configure-world.js +1 -1
  69. package/dist/src/internal/workflow/world-compatibility.d.ts +32 -0
  70. package/dist/src/internal/workflow/world-compatibility.js +1 -0
  71. package/dist/src/protocol/message.d.ts +7 -5
  72. package/dist/src/runtime/actions/types.d.ts +10 -11
  73. package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
  74. package/dist/src/setup/scaffold/create/project.js +1 -1
  75. package/dist/src/shared/eve-server-health.d.ts +5 -0
  76. package/dist/src/shared/eve-server-health.js +1 -0
  77. package/dist/src/shared/network-address.d.ts +12 -0
  78. package/dist/src/shared/network-address.js +1 -1
  79. package/dist/src/shared/result.d.ts +12 -0
  80. package/dist/src/shared/result.js +1 -0
  81. package/docs/agent-config.md +13 -3
  82. package/docs/concepts/execution-model-and-durability.md +1 -1
  83. package/docs/concepts/sessions-runs-and-streaming.md +1 -1
  84. package/docs/connections/overview.mdx +40 -2
  85. package/docs/evals/assertions.mdx +97 -39
  86. package/docs/evals/cases.mdx +24 -15
  87. package/docs/evals/judge.mdx +2 -2
  88. package/docs/evals/overview.mdx +7 -5
  89. package/docs/evals/reporters.mdx +2 -2
  90. package/docs/evals/running.mdx +3 -1
  91. package/docs/evals/targets.mdx +2 -2
  92. package/docs/guides/auth-and-route-protection.md +48 -1
  93. package/docs/guides/client/streaming.mdx +1 -1
  94. package/docs/guides/deployment.md +3 -2
  95. package/docs/guides/dev-tui.md +1 -1
  96. package/docs/reference/cli.md +1 -1
  97. package/docs/tutorial/connect-a-warehouse.mdx +2 -0
  98. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # eve
2
2
 
3
+ ## 0.15.1
4
+
5
+ ### Patch Changes
6
+
7
+ - b049756: Use the active eve development server URL for connection authorization callbacks. Local Vercel Connect flows now return to eve's actual port instead of Workflow's port 3000 fallback.
8
+ - 2933ab2: The local `eve dev` status bar now shows a gray `:port` badge and retains it as terminal width narrows. Status segments now use tighter spacing.
9
+ - 2e4e15d: `eve init` now accepts `--yes` as a no-op compatibility flag and warns before continuing.
10
+ - 2933ab2: Running `eve dev` interactively now reconnects to the healthy loopback dev server recorded for the same app root, with a fresh session for each attached terminal UI. Eve replaces stale or malformed state when it starts a new server. `--host`, `--port`, or `PORT` skips reconnection and reports a healthy recorded server instead.
11
+
12
+ ## 0.15.0
13
+
14
+ ### Minor Changes
15
+
16
+ - 194a8bb: Add snapshot-based turn and session assertions, lifecycle-aware tool and subagent matching, typed event checks, recorded requirements, and explicit skipped results. The simplified API uses `succeeded`/`parked`, completed calls by default, exact `count` options, and `require*` lookups so evals no longer need manual event scans or thrown assertion errors.
17
+
18
+ ### Patch Changes
19
+
20
+ - f618bef: New Vercel project names now show the suggested name as a placeholder, so typing replaces it instead of editing a prefilled value.
21
+ - 194a8bb: Make `isChannel` recognize authored channel imports evaluated in a different local runtime bundle from the route instance.
22
+ - d83b418: eve's health endpoint (`/eve/v1/health`) now responds to `HEAD` requests, not just `GET`, so load balancers and uptime monitors that probe with `HEAD` (UptimeRobot, Kubernetes probes, and others) no longer report a healthy deployment as down.
23
+ - e5ccf93: Self-hosted `eve start` now registers the workflow queue handler for custom (non-Vercel) worlds, so jobs dispatched by a configured world no longer return `Unhandled queue` or leave runs stuck `pending` — and you no longer need `eve dev --no-ui` to run a local world in production. eve also fails fast at boot with an actionable error when a configured workflow world's `@workflow/*` version is incompatible with the line eve bundles, instead of surfacing a cryptic `ZodError` deep in workflow replay.
24
+ - 3865605: Stream `actions.requested` as each model tool call arrives, before the tool finishes or a runtime action is dispatched.
25
+
3
26
  ## 0.14.0
4
27
 
5
28
  ### Minor Changes
@@ -1 +1,2 @@
1
- const CHANNEL_SENTINEL=`eve:channel`,CHANNEL_INSTRUMENTATION_KIND=Symbol.for(`eve.channel.instrumentationKind`);function isCompiledChannel(e){return typeof e==`object`&&!!e&&e.__kind===`eve:channel`}function getChannelInstrumentationKind(e){if(!isCompiledChannel(e))return;let t=Reflect.get(e,CHANNEL_INSTRUMENTATION_KIND);if(typeof t==`string`&&t.length>0)return t;let n=e.adapter.kind;return typeof n==`string`&&n.startsWith(`channel:`)?n:void 0}function setChannelInstrumentationKind(e,t){Object.defineProperty(e,CHANNEL_INSTRUMENTATION_KIND,{configurable:!0,enumerable:!1,value:t})}export{CHANNEL_SENTINEL,getChannelInstrumentationKind,isCompiledChannel,setChannelInstrumentationKind};
1
+ const CHANNEL_SENTINEL=`eve:channel`,CHANNEL_INSTRUMENTATION_KIND=Symbol.for(`eve.channel.instrumentationKind`),CHANNEL_INSTRUMENTATION_KINDS=Symbol.for(`eve.channel.instrumentationKinds`),channelInstrumentationKindGlobal=globalThis;channelInstrumentationKindGlobal[CHANNEL_INSTRUMENTATION_KINDS]??=new Map;const channelInstrumentationKinds=channelInstrumentationKindGlobal[CHANNEL_INSTRUMENTATION_KINDS];function isCompiledChannel(e){return typeof e==`object`&&!!e&&e.__kind===`eve:channel`}function getChannelInstrumentationKind(e){if(!isCompiledChannel(e))return;let t=Reflect.get(e,CHANNEL_INSTRUMENTATION_KIND);if(typeof t==`string`&&t.length>0)return t;let n=e.adapter.kind;if(typeof n==`string`&&n.startsWith(`channel:`))return n;let r=channelRouteSignature(e);return r===void 0?void 0:channelInstrumentationKinds.get(r)}function setChannelInstrumentationKind(e,t){Object.defineProperty(e,CHANNEL_INSTRUMENTATION_KIND,{configurable:!0,enumerable:!1,value:t});let n=channelRouteSignature(e);n!==void 0&&channelInstrumentationKinds.set(n,t)}function channelRouteSignature(e){if(e.routes.length!==0)return e.routes.map(e=>`${e.method.toUpperCase()} ${e.path}`).sort().join(`
2
+ `)}export{CHANNEL_SENTINEL,getChannelInstrumentationKind,isCompiledChannel,setChannelInstrumentationKind};
@@ -1 +1 @@
1
- import{pickAgentHeaderTip}from"./agent-header.js";import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{failureKey,formatFailureDetail,formatFailureMessage,formatGatewayAuthFailureNotice,isAbortLikeError,isGatewayAuthFailure,isInterruptedError}from"./errors.js";import{parseLogDisplayMode}from"./log-display-mode.js";import{createRemoteConnectionController}from"./remote-connection.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,automaticSetupCommand,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{isCurrentTurnBoundaryEvent}from"#client/index.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createDevelopmentRuntimeArtifactSessionRefresher}from"#services/dev-client.js";import{devBootPhase}from"#internal/dev-boot-progress.js";function authIssueForStatus(e){if(e===`logged-out`)return LOGIN_SETUP_ISSUE;if(e===`cli-missing`)return CLI_MISSING_SETUP_ISSUE}var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x=!1;#S=new AbortController;#C=!1;#w=[];#T;#E;#D=pickAgentHeaderTip();#O;#k=new Map;#A=new Map;#j=new Map;#M=new Map;#N=new Set;#P=!1;#F;constructor(e){if(this.#e=e.session,e.client!==void 0&&(this.#t=e.client),this.#n=createRenderer(e),this.#r=e.name??`eve`,this.#i=e.tools??`full`,this.#a=e.reasoning??`full`,this.#o=e.subagents??`full`,this.#s=e.connectionAuth??`full`,this.#c=e.assistantResponseStats??`tokensPerSecond`,this.#l=e.contextSize,this.#u=e.formatTransportError??toErrorMessage,e.initialInput!==void 0&&(this.#m=e.initialInput),e.appRoot!==void 0){this.#p=e.appRoot;let t={appRoot:e.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};e.detectProjectIdentity!==void 0&&(t.detectIdentity=e.detectProjectIdentity),this.#E=createVercelStatusTracker(t)}if(e.promptCommandHandler!==void 0&&(this.#h=e.promptCommandHandler),this.#g=e.availablePromptCommands??PROMPT_COMMANDS,e.remote!==void 0){if(this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#_=createRemoteConnectionController({client:this.#t,credentials:e.remote.credentials,target:e.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:e.remote.resolveOidcToken,resolveDeployment:e.remote.resolveDeployment})}this.#v=e.bootDetections??BOOT_DETECTIONS,this.#y=e.getVercelAuthStatus??getVercelAuthStatus,e.onBootProgress!==void 0&&(this.#b=e.onBootProgress),e.serverUrl!==void 0&&(this.#f=e.serverUrl),e.serverUrl!==void 0&&e.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactSessionRefresher({serverUrl:e.serverUrl}))}async#I(){if(this.#f===void 0){this.#R(),await this.#U(void 0);return}let e;if(this.#_!==void 0){let t=await this.#_.check();t.state===`ready`&&(e=t.info)}else try{e=await devBootPhase(`connecting to agent`,()=>this.#t?this.#t.info():Promise.resolve(void 0),this.#b)}catch{e=void 0}this.#R();let t=this.#L(e);await this.#U(t)}#L(e){let t=this.#p===void 0?e:resolveModelProviderState(e,process.env);this.#O=t;let n=this.#f;if(n===void 0)return t;let r={name:this.#r,serverUrl:n};return t!==void 0&&(r.info=t),this.#p!==void 0&&(r.tip=this.#D),this.#n.renderAgentHeader?.(r),t}#R(){let e=this.#b;this.#b=void 0,e?.({type:`before-first-paint`})}async run(){try{await this.#z()}finally{this.#x=!0,this.#S.abort(),this.#F?.(),this.#F=void 0,this.#n.shutdown?.(),this.#E?.dispose(),this.#_?.dispose()}}async#z(){let e=this.#r,t,i,a,o=!1,s=!1,c=this.#m;for(await this.#I(),this.#_?.current().connection.state===`auth-required`&&await this.#Q({type:`extension`,name:`vc:login`,argument:``},e,`startup`),this.#q(),this.#E?.refreshIdentity(),this.#h!==void 0&&this.#n.setupFlow!==void 0&&(i=automaticSetupCommand(this.#w),t=i?.prompt);;){if(!s){if(t==null){if(!this.#n.readPrompt){if(o)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let n={title:e};c!==void 0&&(n.initialDraft=c,c=void 0);try{t=await this.#V(n)}catch(e){if(isInterruptedError(e))return;throw e}if(t==null)return}let l=parsePromptCommand(t);if(l?.type===`exit`)return;if(l?.type===`new`){this.#B(),a=void 0,s=!1,t=void 0,this.#n.reset?.();continue}if(l?.type===`help`){this.#J(formatPromptCommandHelp(this.#g)),a=void 0,s=!1,t=void 0;continue}if(l?.type===`loglevel`){this.#J(this.#ee(l.argument)),a=void 0,s=!1,t=void 0;continue}if(l?.type===`extension`){try{let t=l.name===`model`?i?.initialModelStep:void 0;i=void 0,await this.#Q(l,e,`command`,t)}catch(e){if(isInterruptedError(e))return;throw e}a=void 0,t=void 0,s=!1;continue}o=!0}let l=await this.#H({prompt:s?void 0:t,inputResponses:a});try{await this.#n.renderStream(l,{title:e,submittedPrompt:t,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let n=l.turnState?.pendingApprovals??[],r=l.turnState?.pendingQuestions??[];if(n.length>0||r.length>0){let i=[];if(n.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let t of n){let n=await this.#n.readToolApproval(t,{title:e});i.push({requestId:t.approvalId,optionId:n.approved?`approve`:`deny`}),this.#k.delete(t.approvalId)}}if(r.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let t of r){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let a={requestId:t.requestId};r.optionId!==void 0&&(a.optionId=r.optionId),r.text!==void 0&&(a.text=r.text),i.push(a),this.#k.delete(t.requestId)}}s=!0,a=i,t=void 0;continue}l.turnState&&l.turnState.boundaryEvent===void 0&&(this.#P=!0)}catch(e){if(isInterruptedError(e))return;throw e}s=!1,a=void 0,t=void 0,this.#P&&(this.#P=!1,this.#B(),this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`))}}#B(){for(let e of this.#j.values())e.abort();this.#j.clear(),this.#A.clear(),this.#k.clear(),this.#M.clear(),this.#N.clear(),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}async#V(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#t,r=this.#d;if(n===void 0||r===void 0)return await t;let i=!1,a=!1,o,refresh=async()=>{if(!(i||a)){a=!0;try{this.#e=await r.refreshIdle({createSession:()=>n.session(),onRuntimeArtifactsChanged:()=>this.#re(),session:this.#e})}finally{a=!1}}},startRefresh=()=>{if(i||a)return;let e=refresh().finally(()=>{o===e&&(o=void 0)});o=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await t}finally{i=!0,clearInterval(s),await o}}async#H(e){let t=new AbortController,n={signal:t.signal};e.prompt!==void 0&&(n.message=e.prompt),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses);let r;try{let e=this.#t;e!==void 0&&this.#d!==void 0&&(this.#e=await this.#d.refresh({createSession:()=>e.session(),inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#re(),session:this.#e})),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),r=await this.#e.send(n)}catch(e){if(isInterruptedError(e))throw e;return this.#_?.reportFailure(e),this.#P=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}let i=createTurnState();return{abort:()=>t.abort(),events:eveEventsToTUIStream({events:r,pendingInputRequests:this.#k,subagentRuns:this.#A,turnState:i,onSubagentCalled:e=>this.#se(e),onSubagentCompleted:e=>this.#le(e),onConnectionAuthRequired:e=>this.#ie(e),onConnectionAuthCompleted:e=>this.#ae(e),onTerminalFailure:()=>{this.#P=!0},failureOverride:this.#p===void 0?void 0:e=>isGatewayAuthFailure(e)?formatGatewayAuthFailureNotice(e):void 0}),turnState:i}}async#U(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#w=await detectSetupIssues(t,this.#v),this.#n.renderSetupWarning!==void 0&&(this.#W(),this.#G())}#W(){let e=orderedSetupIssues(this.#w,this.#T);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#G(){let e=this.#p;if(e===void 0)return;let t;try{t=await this.#y(e,{signal:this.#S.signal})}catch{return}this.#x||this.#C||(this.#T=authIssueForStatus(t),this.#W())}async#K(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n={appRoot:t,env:process.env};e!==void 0&&(n.info=e);try{this.#w=await detectSetupIssues(n,this.#v);let e=await this.#y(t,{signal:this.#S.signal});this.#T=authIssueForStatus(e)}catch{return}this.#x||this.#W()}#q(){this.#p===void 0||this.#n.renderSandboxLog===void 0||this.#F===void 0&&(this.#F=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#J(e){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}}async#Y(e,t){let n=this.#h;return n===void 0?{message:`/${e.name} is not available in this session.`}:await n.handle(e,{renderer:this.#n,title:t.title,initialModelStep:t.initialModelStep,remoteConnection:this.#_})}#X(e,t){if(t!==`startup`)return;let n=this.#_?.current().connection.state,r=n===`auth-failed`||n===`unavailable`?`failed`:void 0,i=e.argument.length===0?``:` ${e.argument}`;this.#n.renderCommandInvocation?.(`/${e.name}${i}`,r)}async#Z(e){if(e?.kind===`model-access-changed`){this.#E?.applyEffect({kind:`refresh-identity`}),this.#C=!0,await this.#te();return}e!==void 0&&(this.#E?.applyEffect(e),this.#C=!0,this.#K(this.#O))}async#Q(e,t,n,r){let i=await this.#Y(e,{initialModelStep:r,title:t});this.#X(e,n),this.#J(i?.message),await this.#Z(i?.effect),this.#$()}#$(){let e=this.#_?.current().connection;e?.state!==`ready`||e.info===this.#O||(this.#O=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}#ee(e){let t=this.#n;if(t.logDisplayMode===void 0||t.setLogDisplayMode===void 0)return`/loglevel is not available in this session.`;if(e===``)return`Logs: ${t.logDisplayMode()}. Use /loglevel all|stderr|sandbox|none — logs stay buffered, so switching also hides or restores past lines.`;let n=parseLogDisplayMode(e);if(n===void 0)return`Unknown log level "${e}". Use all, stderr, sandbox, or none.`;if(n===t.logDisplayMode())return`Logs already set to ${n}.`;switch(t.setLogDisplayMode(n),n){case`none`:return`Logs hidden. Output stays buffered — /loglevel all restores it.`;case`stderr`:return`Showing stderr logs only.`;case`sandbox`:return`Showing sandbox logs only.`;case`all`:return`Showing all logs.`}}async#te(){let e=this.#p;if(e===void 0)return;loadDevelopmentEnvironmentFiles(e);let t=this.#L(await this.#ne());this.#K(t)}async#ne(){try{return await this.#t?.info()}catch{return}}async#re(){let e=this.#O,t=await this.#ne();t!==void 0&&this.#L(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#ie(e){let t={name:e.data.name,description:e.data.description,state:`required`};e.data.authorization!==void 0&&(t.challenge=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),this.#M.set(e.data.name,t),this.#oe(t)}#ae(e){let t=this.#M.get(e.data.name)??{name:e.data.name,description:``,state:e.data.outcome};t.state=e.data.outcome,e.data.reason!==void 0&&(t.reason=e.data.reason),this.#M.set(e.data.name,t),this.#N.delete(e.data.name),this.#oe(t),this.#n.setConnectionAuthPendingCount?.(this.#N.size)}#oe(e){let t={name:e.name,description:e.description,state:e.state};e.challenge!==void 0&&(t.challenge=e.challenge),e.reason!==void 0&&(t.reason=e.reason),this.#n.upsertConnectionAuth?.(t)}#se(e){let t=e.data.callId;if(this.#j.has(t))return;let n=this.#t;if(!n)return;let r=new AbortController;this.#j.set(t,r),(async()=>{try{let i=n.session({sessionId:e.data.childSessionId,streamIndex:0}).stream({signal:r.signal});for await(let e of i)if(r.signal.aborted||(this.#ue(t,e),isCurrentTurnBoundaryEvent(e)))break}catch(e){if(!isAbortLikeError(e)){let n=toErrorMessage(e),r=this.#A.get(t);if(r){let{key:e,step:i}=openCurrentSubagentSection(r);i.message=i.message?`${i.message}\n\nstream error: ${n}`:`stream error: ${n}`,i.finalized=!0,r.currentSectionKey=null,this.#n.upsertSubagentStep?.({callId:t,subagentName:r.name,sectionKey:e,reasoning:i.reasoning,message:i.message,finalized:!0})}}}finally{this.#j.delete(t)}})()}#ce(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={"approval-requested":0,executing:1,done:2,failed:2};e[n.status]>e[r.status]&&(r.status=n.status),r.input=n.input}else t.tools.set(n.childCallId,i);this.#n.markChildToolCallId?.(n.childCallId),this.#n.upsertSubagentTool?.({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#le(e){let t=this.#A.get(e);if(t){for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#n.upsertSubagentStep?.({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null}}#ue(e,t){let n=this.#A.get(e);if(!n)return;let r=this.#n,emit=(t,i)=>{r.upsertSubagentStep?.({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent();break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#ce(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#ce(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;t.data.status===`failed`?(a.status=`failed`,a.errorText=formatActionResultError(t)):(a.status=`done`,a.output=i.output);let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r.upsertSubagentTool?.(o);break}default:break}}};function createRenderer(e){return e.renderer?e.renderer:new TerminalRenderer({tools:e.tools,reasoning:e.reasoning,subagents:e.subagents,connectionAuth:e.connectionAuth,assistantResponseStats:e.assistantResponseStats,contextSize:e.contextSize,logs:e.logs,availablePromptCommands:e.availablePromptCommands,input:e.userInput,output:e.screen})}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id,r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,subagentRuns:r,turnState:i,onSubagentCalled:a,onSubagentCompleted:o,onConnectionAuthRequired:s,onConnectionAuthCompleted:c,onTerminalFailure:l,failureOverride:u}=e,d=new Map,f=new Map,p=0,m=new Set,h=new Set,g=new Set,_=new Set,v=!1,y=!1,b;for await(let e of t)if(!(y&&isPostTurnVisibleEvent(e)))switch(e.type){case`session.started`:case`turn.started`:case`message.received`:break;case`step.started`:p+=1,yield{type:`step-start`};break;case`step.completed`:{let t=e;b=t.data.usage,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`step-finish`,usage:t.data.usage};break}case`message.appended`:{let t=e,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(d,n),i=t.data.messageSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`message.completed`:{let t=textPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(d,t),r=e.data.message;if(n.completed){if(r===null||r===n.text||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p,yield{type:`assistant-complete`,id:partGenerationId(t,n.generation),text:r};break}let i=partGenerationId(t,n.generation);if(r!==null){if(n.text.length===0)n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let e=r.slice(n.text.length);e.length>0&&(yield{type:`assistant-delta`,id:i,delta:e}),n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i}}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let t=e,n=reasoningPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(f,n),i=t.data.reasoningSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`reasoning-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`reasoning.completed`:{let t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(f,t),r=e.data.reasoning;if(n.completed){if(r.length===0||r===n.text||n.text.startsWith(r)||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}let i=partGenerationId(t,n.generation);if(n.text.length===0&&r.length>0)n.text=r,yield{type:`reasoning-delta`,id:i,delta:r};else if(r.length>0&&!r.startsWith(n.text))break;n.completed=!0,n.completedEpoch=p,yield{type:`reasoning-complete`,id:i};break}case`actions.requested`:{let t=e.data,n=t.actions.filter(e=>e.kind===`tool-call`);if(n.length===0)break;let r=toolBatchKey(`actions.requested`,t.turnId,t.stepIndex,n);if(g.has(r)){for(let e of n)m.has(e.callId)||h.add(e.callId);break}g.add(r);for(let e of n)m.has(e.callId)||(m.add(e.callId),yield{type:`tool-call`,toolCallId:e.callId,toolName:e.toolName,input:e.input});break}case`input.requested`:{let t=e.data,r=t.requests.filter(e=>e.action.kind===`tool-call`);if(r.length===0)break;let a=inputRequestBatchKey(t.turnId,t.stepIndex,r);if(g.has(a)){for(let e of r)m.has(e.action.callId)||h.add(e.action.callId);break}g.add(a);for(let e of r){let t=e.action.callId;if(m.has(t)||(m.add(t),yield{type:`tool-call`,toolCallId:t,toolName:e.action.toolName,input:e.action.input}),n.set(e.requestId,e),isQuestionRequest(e)){upsertPendingQuestion(i,e);continue}upsertPendingApproval(i,e),yield{type:`tool-approval-request`,approvalId:e.requestId,toolCallId:t}}break}case`action.result`:{let t=e;if(t.data.result.kind!==`tool-result`)break;let n=t.data.result.callId;if(h.has(n)||!m.has(n))break;t.data.status===`failed`?yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)}:yield{type:`tool-result`,toolCallId:n,output:t.data.result.output};break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,_,u);t&&(yield t);break}case`session.failed`:{i.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,_,u);t&&(yield t),i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b},v=!0;return}case`session.waiting`:case`session.completed`:i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b},v=!0;return;case`turn.completed`:y=!0,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p);break;case`subagent.called`:{let t=e;if(!r.has(t.data.callId))r.set(t.data.callId,{name:t.data.name,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map});else{let e=r.get(t.data.callId);e&&(e.name=t.data.name)}a?.(t);break}case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:o?.(e.data.callId);break;case`authorization.required`:s?.(e);break;case`authorization.completed`:c?.(e);break;default:break}v||(yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{pendingApprovals:[],pendingQuestions:[],sawSessionFailure:!1}}function upsertPendingApproval(e,t){let n=toAgentTUIToolApprovalRequest(t),r=e.pendingApprovals.findIndex(e=>e.approvalId===n.approvalId);r===-1?e.pendingApprovals.push(n):e.pendingApprovals[r]=n}function toAgentTUIToolApprovalRequest(e){return{approvalId:e.requestId,toolCallId:e.action.callId,toolName:e.action.toolName,input:e.action.input}}function upsertPendingQuestion(e,t){let n=e.pendingQuestions.findIndex(e=>e.requestId===t.requestId);n===-1?e.pendingQuestions.push(t):e.pendingQuestions[n]=t}function textPartId(e,t){return`text:${e}:${t}`}function reasoningPartId(e,t){return`reasoning:${e}:${t}`}function partStateFor(e,t){let n=e.get(t);return n===void 0&&(n={generation:0,text:``,completed:!1,completedEpoch:0},e.set(t,n)),n}function partGenerationId(e,t){return t===0?e:`${e}#${t}`}function*closeOpenParts(e,t,n){for(let[r,i]of e)i.completed||i.text.length===0||(i.completed=!0,i.completedEpoch=n,yield{type:t,id:partGenerationId(r,i.generation)})}function isPostTurnVisibleEvent(e){switch(e.type){case`actions.requested`:case`authorization.completed`:case`authorization.required`:case`input.requested`:case`message.appended`:case`message.completed`:case`reasoning.appended`:case`reasoning.completed`:case`result.completed`:case`step.completed`:case`step.failed`:case`step.started`:case`subagent.called`:case`subagent.completed`:case`subagent.event`:case`subagent.started`:case`turn.completed`:case`turn.failed`:return!0;default:return!1}}function toolBatchKey(e,t,n,r){return`${e}:${t}:${String(n)}:${stableStringify(r.map(e=>({input:e.input,toolName:e.toolName})))}`}function inputRequestBatchKey(e,t,n){return toolBatchKey(`input.requested`,e,t,n.map(e=>({input:e.action.input,toolName:e.action.toolName})))}function stableStringify(e){return JSON.stringify(toStableJson(e))??`undefined`}function toStableJson(e,t=new WeakSet){if(typeof e!=`object`||!e)return e;if(t.has(e))return`[Circular]`;if(t.add(e),Array.isArray(e))return e.map(e=>toStableJson(e,t));let n=e,r={};for(let e of Object.keys(n).sort())r[e]=toStableJson(n[e],t);return r}function formatActionResultError(e){if(e.data.error?.message)return e.data.error.message;let t=e.data.result.output;if(typeof t==`string`)return t;try{return JSON.stringify(t)}catch{return`Tool execution failed.`}}function toFailureEvent(e,t,n){let r=failureKey(e);if(t.has(r))return;t.add(r);let s=n?.(e),c={type:`error`,errorText:s??formatFailureMessage(e)};if(s!==void 0)return c;let l=formatFailureDetail(e);return l!==void 0&&(c.detail=l),c}function isQuestionRequest(e){return e.display===`select`||e.display===`text`?!0:e.display===`confirmation`?!1:e.options!==void 0&&e.options.length>0}function toAgentTUIInputQuestion(e){let t=e.display===`text`?`text`:e.display===`select`||e.options!==void 0&&e.options.length>0?`select`:`text`,n={requestId:e.requestId,prompt:e.prompt,display:t};return e.options!==void 0&&(n.options=e.options.map(e=>{let t={id:e.id,label:e.label};return e.description!==void 0&&(t.description=e.description),e.style!==void 0&&(t.style=e.style),t})),e.allowFreeform!==void 0&&(n.allowFreeform=e.allowFreeform),n}function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{EveTUIRunner,parsePromptCommand};
1
+ import{pickAgentHeaderTip}from"./agent-header.js";import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{failureKey,formatFailureDetail,formatFailureMessage,formatGatewayAuthFailureNotice,isAbortLikeError,isGatewayAuthFailure,isInterruptedError}from"./errors.js";import{parseLogDisplayMode}from"./log-display-mode.js";import{createRemoteConnectionController}from"./remote-connection.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,automaticSetupCommand,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{isCurrentTurnBoundaryEvent}from"#client/index.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createDevelopmentRuntimeArtifactSessionRefresher}from"#services/dev-client.js";import{devBootPhase}from"#internal/dev-boot-progress.js";function authIssueForStatus(e){if(e===`logged-out`)return LOGIN_SETUP_ISSUE;if(e===`cli-missing`)return CLI_MISSING_SETUP_ISSUE}var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x=!1;#S=new AbortController;#C=!1;#w=[];#T;#E;#D=pickAgentHeaderTip();#O;#k=new Map;#A=new Map;#j=new Map;#M=new Map;#N=new Set;#P=!1;#F;constructor(e){if(this.#e=e.session,e.client!==void 0&&(this.#t=e.client),this.#n=createRenderer(e),this.#r=e.name??`eve`,this.#i=e.tools??`full`,this.#a=e.reasoning??`full`,this.#o=e.subagents??`full`,this.#s=e.connectionAuth??`full`,this.#c=e.assistantResponseStats??`tokensPerSecond`,this.#l=e.contextSize,this.#u=e.formatTransportError??toErrorMessage,e.initialInput!==void 0&&(this.#m=e.initialInput),e.appRoot!==void 0){this.#p=e.appRoot;let t={appRoot:e.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};e.detectProjectIdentity!==void 0&&(t.detectIdentity=e.detectProjectIdentity),this.#E=createVercelStatusTracker(t)}if(e.promptCommandHandler!==void 0&&(this.#h=e.promptCommandHandler),this.#g=e.availablePromptCommands??PROMPT_COMMANDS,e.remote!==void 0){if(this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#_=createRemoteConnectionController({client:this.#t,credentials:e.remote.credentials,target:e.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:e.remote.resolveOidcToken,resolveDeployment:e.remote.resolveDeployment})}this.#v=e.bootDetections??BOOT_DETECTIONS,this.#y=e.getVercelAuthStatus??getVercelAuthStatus,e.onBootProgress!==void 0&&(this.#b=e.onBootProgress),e.serverUrl!==void 0&&(this.#f=e.serverUrl),e.serverUrl!==void 0&&e.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactSessionRefresher({serverUrl:e.serverUrl}))}async#I(){if(this.#f===void 0){this.#R(),await this.#W(void 0);return}let e;if(this.#_!==void 0){let t=await this.#_.check();t.state===`ready`&&(e=t.info)}else try{e=await devBootPhase(`connecting to agent`,()=>this.#t?this.#t.info():Promise.resolve(void 0),this.#b)}catch{e=void 0}this.#R();let t=this.#L(e);await this.#W(t)}#L(e){let t=this.#p===void 0?e:resolveModelProviderState(e,process.env);this.#O=t;let n=this.#f;if(n===void 0)return t;let r={name:this.#r,serverUrl:n};return t!==void 0&&(r.info=t),this.#p!==void 0&&(r.tip=this.#D),this.#n.renderAgentHeader?.(r),t}#R(){let e=this.#b;this.#b=void 0,e?.({type:`before-first-paint`})}async run(){try{await this.#z()}finally{this.#x=!0,this.#S.abort(),this.#V(),this.#F?.(),this.#F=void 0,this.#n.shutdown?.(),this.#E?.dispose(),this.#_?.dispose()}}async#z(){let e=this.#r,t,i,a,o=!1,s=!1,c=this.#m;for(await this.#I(),this.#_?.current().connection.state===`auth-required`&&await this.#$({type:`extension`,name:`vc:login`,argument:``},e,`startup`),this.#J(),this.#E?.refreshIdentity(),this.#h!==void 0&&this.#n.setupFlow!==void 0&&(i=automaticSetupCommand(this.#w),t=i?.prompt);;){if(!s){if(t==null){if(!this.#n.readPrompt){if(o)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let n={title:e};c!==void 0&&(n.initialDraft=c,c=void 0);try{t=await this.#H(n)}catch(e){if(isInterruptedError(e))return;throw e}if(t==null)return}let l=parsePromptCommand(t);if(l?.type===`exit`)return;if(l?.type===`new`){this.#B(),a=void 0,s=!1,t=void 0,this.#n.reset?.();continue}if(l?.type===`help`){this.#Y(formatPromptCommandHelp(this.#g)),a=void 0,s=!1,t=void 0;continue}if(l?.type===`loglevel`){this.#Y(this.#te(l.argument)),a=void 0,s=!1,t=void 0;continue}if(l?.type===`extension`){try{let t=l.name===`model`?i?.initialModelStep:void 0;i=void 0,await this.#$(l,e,`command`,t)}catch(e){if(isInterruptedError(e))return;throw e}a=void 0,t=void 0,s=!1;continue}o=!0}let l=await this.#U({prompt:s?void 0:t,inputResponses:a});try{await this.#n.renderStream(l,{title:e,submittedPrompt:t,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let n=l.turnState?.pendingApprovals??[],r=l.turnState?.pendingQuestions??[];if(n.length>0||r.length>0){let i=[];if(n.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let t of n){let n=await this.#n.readToolApproval(t,{title:e});i.push({requestId:t.approvalId,optionId:n.approved?`approve`:`deny`}),this.#k.delete(t.approvalId)}}if(r.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let t of r){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let a={requestId:t.requestId};r.optionId!==void 0&&(a.optionId=r.optionId),r.text!==void 0&&(a.text=r.text),i.push(a),this.#k.delete(t.requestId)}}s=!0,a=i,t=void 0;continue}l.turnState&&l.turnState.boundaryEvent===void 0&&(this.#P=!0)}catch(e){if(isInterruptedError(e))return;throw e}s=!1,a=void 0,t=void 0,this.#P&&(this.#P=!1,this.#B(),this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`))}}#B(){this.#V(),this.#A.clear(),this.#k.clear(),this.#M.clear(),this.#N.clear(),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}#V(){for(let e of this.#j.values())e.abort();this.#j.clear()}async#H(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#t,r=this.#d;if(n===void 0||r===void 0)return await t;let i=!1,a=!1,o,refresh=async()=>{if(!(i||a)){a=!0;try{this.#e=await r.refreshIdle({createSession:()=>n.session(),onRuntimeArtifactsChanged:()=>this.#ie(),session:this.#e})}finally{a=!1}}},startRefresh=()=>{if(i||a)return;let e=refresh().finally(()=>{o===e&&(o=void 0)});o=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await t}finally{i=!0,clearInterval(s),await o}}async#U(e){let t=new AbortController,n={signal:t.signal};e.prompt!==void 0&&(n.message=e.prompt),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses);let r;try{let e=this.#t;e!==void 0&&this.#d!==void 0&&(this.#e=await this.#d.refresh({createSession:()=>e.session(),inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#ie(),session:this.#e})),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),r=await this.#e.send(n)}catch(e){if(isInterruptedError(e))throw e;return this.#_?.reportFailure(e),this.#P=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}let i=createTurnState();return{abort:()=>t.abort(),events:eveEventsToTUIStream({events:r,pendingInputRequests:this.#k,subagentRuns:this.#A,turnState:i,onSubagentCalled:e=>this.#ce(e),onSubagentCompleted:e=>this.#ue(e),onConnectionAuthRequired:e=>this.#ae(e),onConnectionAuthCompleted:e=>this.#oe(e),onTerminalFailure:()=>{this.#P=!0},failureOverride:this.#p===void 0?void 0:e=>isGatewayAuthFailure(e)?formatGatewayAuthFailureNotice(e):void 0}),turnState:i}}async#W(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#w=await detectSetupIssues(t,this.#v),this.#n.renderSetupWarning!==void 0&&(this.#G(),this.#K())}#G(){let e=orderedSetupIssues(this.#w,this.#T);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#K(){let e=this.#p;if(e===void 0)return;let t;try{t=await this.#y(e,{signal:this.#S.signal})}catch{return}this.#x||this.#C||(this.#T=authIssueForStatus(t),this.#G())}async#q(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n={appRoot:t,env:process.env};e!==void 0&&(n.info=e);try{this.#w=await detectSetupIssues(n,this.#v);let e=await this.#y(t,{signal:this.#S.signal});this.#T=authIssueForStatus(e)}catch{return}this.#x||this.#G()}#J(){this.#p===void 0||this.#n.renderSandboxLog===void 0||this.#F===void 0&&(this.#F=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#Y(e){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}}async#X(e,t){let n=this.#h;return n===void 0?{message:`/${e.name} is not available in this session.`}:await n.handle(e,{renderer:this.#n,title:t.title,initialModelStep:t.initialModelStep,remoteConnection:this.#_})}#Z(e,t){if(t!==`startup`)return;let n=this.#_?.current().connection.state,r=n===`auth-failed`||n===`unavailable`?`failed`:void 0,i=e.argument.length===0?``:` ${e.argument}`;this.#n.renderCommandInvocation?.(`/${e.name}${i}`,r)}async#Q(e){if(e?.kind===`model-access-changed`){this.#E?.applyEffect({kind:`refresh-identity`}),this.#C=!0,await this.#ne();return}e!==void 0&&(this.#E?.applyEffect(e),this.#C=!0,this.#q(this.#O))}async#$(e,t,n,r){let i=await this.#X(e,{initialModelStep:r,title:t});this.#Z(e,n),this.#Y(i?.message),await this.#Q(i?.effect),this.#ee()}#ee(){let e=this.#_?.current().connection;e?.state!==`ready`||e.info===this.#O||(this.#O=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}#te(e){let t=this.#n;if(t.logDisplayMode===void 0||t.setLogDisplayMode===void 0)return`/loglevel is not available in this session.`;if(e===``)return`Logs: ${t.logDisplayMode()}. Use /loglevel all|stderr|sandbox|none — logs stay buffered, so switching also hides or restores past lines.`;let n=parseLogDisplayMode(e);if(n===void 0)return`Unknown log level "${e}". Use all, stderr, sandbox, or none.`;if(n===t.logDisplayMode())return`Logs already set to ${n}.`;switch(t.setLogDisplayMode(n),n){case`none`:return`Logs hidden. Output stays buffered — /loglevel all restores it.`;case`stderr`:return`Showing stderr logs only.`;case`sandbox`:return`Showing sandbox logs only.`;case`all`:return`Showing all logs.`}}async#ne(){let e=this.#p;if(e===void 0)return;loadDevelopmentEnvironmentFiles(e);let t=this.#L(await this.#re());this.#q(t)}async#re(){try{return await this.#t?.info()}catch{return}}async#ie(){let e=this.#O,t=await this.#re();t!==void 0&&this.#L(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#ae(e){let t={name:e.data.name,description:e.data.description,state:`required`};e.data.authorization!==void 0&&(t.challenge=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),this.#M.set(e.data.name,t),this.#se(t)}#oe(e){let t=this.#M.get(e.data.name)??{name:e.data.name,description:``,state:e.data.outcome};t.state=e.data.outcome,e.data.reason!==void 0&&(t.reason=e.data.reason),this.#M.set(e.data.name,t),this.#N.delete(e.data.name),this.#se(t),this.#n.setConnectionAuthPendingCount?.(this.#N.size)}#se(e){let t={name:e.name,description:e.description,state:e.state};e.challenge!==void 0&&(t.challenge=e.challenge),e.reason!==void 0&&(t.reason=e.reason),this.#n.upsertConnectionAuth?.(t)}#ce(e){let t=e.data.callId;if(this.#j.has(t))return;let n=this.#t;if(!n)return;let r=new AbortController;this.#j.set(t,r),(async()=>{try{let i=n.session({sessionId:e.data.childSessionId,streamIndex:0}).stream({signal:r.signal});for await(let e of i)if(r.signal.aborted||(this.#de(t,e),isCurrentTurnBoundaryEvent(e)))break}catch(e){if(!isAbortLikeError(e)){let n=toErrorMessage(e),r=this.#A.get(t);if(r){let{key:e,step:i}=openCurrentSubagentSection(r);i.message=i.message?`${i.message}\n\nstream error: ${n}`:`stream error: ${n}`,i.finalized=!0,r.currentSectionKey=null,this.#n.upsertSubagentStep?.({callId:t,subagentName:r.name,sectionKey:e,reasoning:i.reasoning,message:i.message,finalized:!0})}}}finally{this.#j.delete(t)}})()}#le(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={"approval-requested":0,executing:1,done:2,failed:2};e[n.status]>e[r.status]&&(r.status=n.status),r.input=n.input}else t.tools.set(n.childCallId,i);this.#n.markChildToolCallId?.(n.childCallId),this.#n.upsertSubagentTool?.({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#ue(e){let t=this.#A.get(e);if(t){for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#n.upsertSubagentStep?.({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null}}#de(e,t){let n=this.#A.get(e);if(!n)return;let r=this.#n,emit=(t,i)=>{r.upsertSubagentStep?.({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent();break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#le(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#le(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;t.data.status===`failed`?(a.status=`failed`,a.errorText=formatActionResultError(t)):(a.status=`done`,a.output=i.output);let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r.upsertSubagentTool?.(o);break}default:break}}};function createRenderer(e){return e.renderer?e.renderer:new TerminalRenderer({tools:e.tools,reasoning:e.reasoning,subagents:e.subagents,connectionAuth:e.connectionAuth,assistantResponseStats:e.assistantResponseStats,contextSize:e.contextSize,logs:e.logs,availablePromptCommands:e.availablePromptCommands,input:e.userInput,output:e.screen})}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id,r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,subagentRuns:r,turnState:i,onSubagentCalled:a,onSubagentCompleted:o,onConnectionAuthRequired:s,onConnectionAuthCompleted:c,onTerminalFailure:l,failureOverride:u}=e,d=new Map,f=new Map,p=0,m=new Set,h=new Set,g=new Set,_=!1,v=!1,y;for await(let e of t)if(!(v&&isPostTurnVisibleEvent(e)))switch(e.type){case`session.started`:case`turn.started`:case`message.received`:break;case`step.started`:p+=1,yield{type:`step-start`};break;case`step.completed`:{let t=e;y=t.data.usage,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`step-finish`,usage:t.data.usage};break}case`message.appended`:{let t=e,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(d,n),i=t.data.messageSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`message.completed`:{let t=textPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(d,t),r=e.data.message;if(n.completed){if(r===null||r===n.text||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p,yield{type:`assistant-complete`,id:partGenerationId(t,n.generation),text:r};break}let i=partGenerationId(t,n.generation);if(r!==null){if(n.text.length===0)n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let e=r.slice(n.text.length);e.length>0&&(yield{type:`assistant-delta`,id:i,delta:e}),n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i}}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let t=e,n=reasoningPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(f,n),i=t.data.reasoningSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`reasoning-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`reasoning.completed`:{let t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(f,t),r=e.data.reasoning;if(n.completed){if(r.length===0||r===n.text||n.text.startsWith(r)||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}let i=partGenerationId(t,n.generation);if(n.text.length===0&&r.length>0)n.text=r,yield{type:`reasoning-delta`,id:i,delta:r};else if(r.length>0&&!r.startsWith(n.text))break;n.completed=!0,n.completedEpoch=p,yield{type:`reasoning-complete`,id:i};break}case`actions.requested`:{let t=e.data.actions.filter(e=>e.kind===`tool-call`);if(t.length===0)break;for(let e of t)m.has(e.callId)||(m.add(e.callId),yield{type:`tool-call`,toolCallId:e.callId,toolName:e.toolName,input:e.input});break}case`input.requested`:{let t=e.data.requests.filter(e=>e.action.kind===`tool-call`);if(t.length===0)break;for(let e of t){let t=e.action.callId;if(m.has(t)||(m.add(t),yield{type:`tool-call`,toolCallId:t,toolName:e.action.toolName,input:e.action.input}),!h.has(e.requestId)){if(h.add(e.requestId),n.set(e.requestId,e),isQuestionRequest(e)){upsertPendingQuestion(i,e);continue}upsertPendingApproval(i,e),yield{type:`tool-approval-request`,approvalId:e.requestId,toolCallId:t}}}break}case`action.result`:{let t=e;if(t.data.result.kind!==`tool-result`)break;let n=t.data.result.callId;if(!m.has(n))break;t.data.status===`failed`?yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)}:yield{type:`tool-result`,toolCallId:n,output:t.data.result.output};break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,g,u);t&&(yield t);break}case`session.failed`:{i.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,g,u);t&&(yield t),i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:y},_=!0;return}case`session.waiting`:case`session.completed`:i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:y},_=!0;return;case`turn.completed`:v=!0,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p);break;case`subagent.called`:{let t=e;if(!r.has(t.data.callId))r.set(t.data.callId,{name:t.data.name,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map});else{let e=r.get(t.data.callId);e&&(e.name=t.data.name)}a?.(t);break}case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:o?.(e.data.callId);break;case`authorization.required`:s?.(e);break;case`authorization.completed`:c?.(e);break;default:break}_||(yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:y})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{pendingApprovals:[],pendingQuestions:[],sawSessionFailure:!1}}function upsertPendingApproval(e,t){let n=toAgentTUIToolApprovalRequest(t),r=e.pendingApprovals.findIndex(e=>e.approvalId===n.approvalId);r===-1?e.pendingApprovals.push(n):e.pendingApprovals[r]=n}function toAgentTUIToolApprovalRequest(e){return{approvalId:e.requestId,toolCallId:e.action.callId,toolName:e.action.toolName,input:e.action.input}}function upsertPendingQuestion(e,t){let n=e.pendingQuestions.findIndex(e=>e.requestId===t.requestId);n===-1?e.pendingQuestions.push(t):e.pendingQuestions[n]=t}function textPartId(e,t){return`text:${e}:${t}`}function reasoningPartId(e,t){return`reasoning:${e}:${t}`}function partStateFor(e,t){let n=e.get(t);return n===void 0&&(n={generation:0,text:``,completed:!1,completedEpoch:0},e.set(t,n)),n}function partGenerationId(e,t){return t===0?e:`${e}#${t}`}function*closeOpenParts(e,t,n){for(let[r,i]of e)i.completed||i.text.length===0||(i.completed=!0,i.completedEpoch=n,yield{type:t,id:partGenerationId(r,i.generation)})}function isPostTurnVisibleEvent(e){switch(e.type){case`actions.requested`:case`authorization.completed`:case`authorization.required`:case`input.requested`:case`message.appended`:case`message.completed`:case`reasoning.appended`:case`reasoning.completed`:case`result.completed`:case`step.completed`:case`step.failed`:case`step.started`:case`subagent.called`:case`subagent.completed`:case`subagent.event`:case`subagent.started`:case`turn.completed`:case`turn.failed`:return!0;default:return!1}}function formatActionResultError(e){if(e.data.error?.message)return e.data.error.message;let t=e.data.result.output;if(typeof t==`string`)return t;try{return JSON.stringify(t)}catch{return`Tool execution failed.`}}function toFailureEvent(e,t,n){let r=failureKey(e);if(t.has(r))return;t.add(r);let s=n?.(e),c={type:`error`,errorText:s??formatFailureMessage(e)};if(s!==void 0)return c;let l=formatFailureDetail(e);return l!==void 0&&(c.detail=l),c}function isQuestionRequest(e){return e.display===`select`||e.display===`text`?!0:e.display===`confirmation`?!1:e.options!==void 0&&e.options.length>0}function toAgentTUIInputQuestion(e){let t=e.display===`text`?`text`:e.display===`select`||e.options!==void 0&&e.options.length>0?`select`:`text`,n={requestId:e.requestId,prompt:e.prompt,display:t};return e.options!==void 0&&(n.options=e.options.map(e=>{let t={id:e.id,label:e.label};return e.description!==void 0&&(t.description=e.description),e.style!==void 0&&(t.style=e.style),t})),e.allowFreeform!==void 0&&(n.allowFreeform=e.allowFreeform),n}function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{EveTUIRunner,parsePromptCommand};
@@ -38,10 +38,9 @@ interface SetupSelectPanelBase extends SetupQuestionPanelBase {
38
38
  * A menu row that turns into an inline editor while the cursor rests on it.
39
39
  * `optionValue` names the row; the `editor` discriminant chooses the widget —
40
40
  * an in-place rename field, or a masked provider-key field with its own
41
- * validation phases. Hovering the row makes it editable directly (typing and
42
- * backspace edit in place), so the editor's text and a blinking caret render
43
- * only on that row. Layout and inline editing are orthogonal, so the editor
44
- * travels as a payload rather than as its own panel `kind`.
41
+ * validation phases. Rename defaults stay placeholders until typing begins;
42
+ * provider keys edit in place. Layout and inline editing are orthogonal, so
43
+ * the editor travels as a payload rather than as its own panel `kind`.
45
44
  */
46
45
  interface SetupInlineEditRow {
47
46
  optionValue: string;
@@ -1,4 +1,4 @@
1
- import{clipVisible,renderInputText,renderInputWithBlockCursor,visibleLength,wrapVisibleLine}from"./terminal-text.js";import{maskLine,visibleLine}from"./line-editor.js";import{renderCursorRow,renderOptionRow,renderOptionRowContinuation,resolveOptionRowState}from"#setup/cli/option-row.js";import{filterOptions,submitRowIndex}from"#setup/cli/select-state.js";function clip(t,n){return clipVisible(t,n)}function questionFooter(e,t){let n=t.colors;return[``,` ${n.dim(n.italic(e.join(` ${t.glyph.dot} `)))}`]}const BOLD_OR_DIM_CLOSE=`\x1B[22m`,DIM_OPEN=`\x1B[2m`,ANSI_FOREGROUND_COLOR=RegExp(`\x1B\\[(?:3[0-9]|9[0-7])m`,`g`);function dimWithEmphasis(e,t){return t.colors.dim(e.replaceAll(BOLD_OR_DIM_CLOSE,`${BOLD_OR_DIM_CLOSE}${DIM_OPEN}`))}function foregroundWithEmphasis(e){return e.replaceAll(DIM_OPEN,``).replace(ANSI_FOREGROUND_COLOR,``)}function toneGlyph(e,t){let n=t.colors;switch(e){case`success`:return n.green(t.glyph.success);case`warning`:return n.yellow(t.glyph.warning);case`error`:return n.red(t.glyph.error);case`info`:return n.dim(t.glyph.dot)}}function renderIndicator(e,t){return e.color===`green`?t.colors.green(e.glyph):t.colors.yellow(e.glyph)}function renderFlowPanel(e,t,n){let r=t.colors,i=[r.dim(t.glyph.hrule.repeat(Math.max(1,n)))];e.title.length>0&&i.push(` ${r.bold(e.title)}`),i.push(``);let a=e.lines.slice(-6);for(let e of a){let n=e.tone===`info`?r.dim(e.text):e.text;i.push(` ${toneGlyph(e.tone,t)} ${n}`)}switch(a.length>0&&i.push(``),e.content.kind){case`question`:e.content.status!==void 0&&i.push(` ${renderIndicator(e.content.status.indicator,t)} ${r.dim(e.content.status.text)}`,``),i.push(...e.content.rows);break;case`status`:i.push(` ${renderIndicator(e.content.status.indicator,t)} ${r.dim(e.content.status.text)}`),e.content.preview!==void 0&&i.push(` ${r.dim(e.content.preview)}`);break;case`preview`:i.push(` ${renderIndicator(e.content.indicator,t)} ${r.dim(e.content.text)}`);break;case`idle`:i.push(` ${renderIndicator(e.content.indicator,t)} ${r.dim(`Working…`)}`);break}return i.map((e,t)=>t===0||e.length===0?clip(e,n):clip(` ${e}`,n))}function optionRow(e){let{option:t,theme:n}=e;return renderOptionRow({colors:n.colors,glyphs:{pointer:n.glyph.pointer,selectedPointer:n.glyph.selectedPointer,success:n.glyph.success,placeholder:n.glyph.option,dot:n.glyph.dot},label:t.label,hint:t.hint,focusHint:t.focusHint,accent:t.accent,isCursor:e.isCursor,state:resolveOptionRowState(t,e.isChecked),placeholder:e.placeholder,hintPadding:e.hintPadding})}function selectPresentation(e){switch(e.kind){case`single`:return{selection:`single`,filter:void 0,layout:`plain`,edit:void 0};case`search`:return{selection:`single`,filter:{placeholder:e.placeholder},layout:`plain`,edit:void 0};case`multi`:return{selection:`multiple`,filter:void 0,layout:`plain`,edit:void 0};case`searchable-multi`:return{selection:`multiple`,filter:{placeholder:e.placeholder},layout:`plain`,edit:void 0};case`stacked`:return{selection:`single`,filter:void 0,layout:`stacked`,edit:void 0};case`task-list`:return{selection:`single`,filter:void 0,layout:`task-list`,edit:void 0};case`inline-edit`:return{selection:`single`,filter:void 0,layout:e.layout,edit:e.edit}}}function selectMessageRows(e,t,n){if(e===``)return[];let r=e.split(`
2
- `).map((e,r)=>` ${t===`stacked`||r>0?n.colors.bold(e):e}`);return r.push(``),r}function searchFilter(e,t,n,r){let i=r.colors.dim(r.glyph.caret),a=i;return e.length>0?a=e+i:t!==void 0&&(a=r.colors.dim(`> ${t}`)),n===void 0?a:`${a} ${r.colors.yellow(n)}`}function selectViewSize(e){return e.search?e.filter===``&&e.featuredLead>0?Math.min(e.featuredLead,8):8:e.optionCount}function noticeBody(e,t,n){return e.tone===`info`?n.colors.dim(e.text):e.tone===`success`&&t===`task-list`?n.colors.bold(e.text):e.text}function renameHint(e,t,n,r){let i=n.editor.text||n.defaultValue,a=n.editor.text.length===0?i.length:n.editor.cursor,o=t?r.colors.cyan(r.glyph.caret):``,s=`${i.slice(0,a)}${o}${i.slice(a)}`;return{...e,hint:n.formatHint(s)}}function keyHint(e,i,s,c,l){let u=s.phase;if(u.kind===`inactive`)return e;let d=maskLine(u.editor),f=u.kind!==`validating`&&u.kind!==`invalid`,p=``,m=``;u.kind===`validating`?p=`Validating… `:u.kind===`invalid`&&(m=` ${c.colors.red(`${c.glyph.error} ${c.colors.bold(`Invalid key`)}`)}`);let h=u.editor.text.length===0?`type your key`:void 0,g=visibleLine(h===void 0?d:{text:h,cursor:0},Math.max(1,l-visibleLength(`> ${p}${m}`)),c.glyph.ellipsis),_=f?renderInputWithBlockCursor({...g,visible:i,inverse:c.colors.inverse}):renderInputText(`${g.before}${g.under}${g.after}`);return{...e,hint:`> ${p}${_}${m}`}}function inlineEditOption(e,t,n,r,i){if(!t||n===void 0||e.value!==n.optionValue)return e;switch(n.editor.kind){case`rename`:return renameHint(e,n.caretVisible,n.editor,r);case`key`:return keyHint(e,n.caretVisible,n.editor,r,i)}}function optionWithoutStackedHint(e,t){if(t!==`stacked`||e.hint===void 0)return{option:e,stackedHint:void 0};let{hint:n,...r}=e;return{option:r,stackedHint:n}}function optionUsesPlaceholder(e,t,n){let r=e.filter!==void 0,i=e.layout===`task-list`&&t===n-1,a=e.selection===`multiple`,o=e.layout!==`plain`;return!r&&!i&&(a||o)}function appendSelectOptionRows(e){let{rows:t,state:n,presentation:r,visible:i,start:a,end:o,cursor:s,visibleLabelWidth:c,width:u,theme:d}=e,f=d.colors;for(let e=a;e<o;e+=1){let p=i[e],m=e===s;r.layout===`task-list`&&e===o-1&&e>a&&t.push(``);let h=r.layout===`stacked`?Math.max(1,u-6):Math.max(1,u-Math.max(c,p.label.length)-9),{option:g,stackedHint:_}=optionWithoutStackedHint(inlineEditOption(p,m,r.edit,d,h),r.layout);if(t.push(` ${optionRow({option:g,isCursor:m,isChecked:r.selection===`multiple`&&n.select.selected.has(p.value),placeholder:optionUsesPlaceholder(r,e,i.length),hintPadding:Math.max(0,c-g.label.length),theme:d})}`),_!==void 0){let e=r.edit,n=m&&e!==void 0&&e.optionValue===p.value&&e.editor.kind===`key`&&e.editor.phase.kind!==`inactive`;for(let e of _.split(`
1
+ import{clipVisible,renderInputText,renderInputWithBlockCursor,visibleLength,wrapVisibleLine}from"./terminal-text.js";import{maskLine,visibleLine}from"./line-editor.js";import{renderCursorRow,renderOptionRow,renderOptionRowContinuation,resolveOptionRowState}from"#setup/cli/option-row.js";import{filterOptions,submitRowIndex}from"#setup/cli/select-state.js";function clip(t,n){return clipVisible(t,n)}function questionFooter(e,t){let n=t.colors;return[``,` ${n.dim(n.italic(e.join(` ${t.glyph.dot} `)))}`]}const BOLD_OR_DIM_CLOSE=`\x1B[22m`,DIM_OPEN=`\x1B[2m`,ANSI_FOREGROUND_COLOR=RegExp(`\x1B\\[(?:3[0-9]|9[0-7])m`,`g`);function dimWithEmphasis(e,t){return t.colors.dim(e.replaceAll(BOLD_OR_DIM_CLOSE,`${BOLD_OR_DIM_CLOSE}${DIM_OPEN}`))}function solidWithinDim(e,t){return t.color?`${BOLD_OR_DIM_CLOSE}${e}${DIM_OPEN}`:e}function foregroundWithEmphasis(e){return e.replaceAll(DIM_OPEN,``).replace(ANSI_FOREGROUND_COLOR,``)}function toneGlyph(e,t){let n=t.colors;switch(e){case`success`:return n.green(t.glyph.success);case`warning`:return n.yellow(t.glyph.warning);case`error`:return n.red(t.glyph.error);case`info`:return n.dim(t.glyph.dot)}}function renderIndicator(e,t){return e.color===`green`?t.colors.green(e.glyph):t.colors.yellow(e.glyph)}function renderFlowPanel(e,t,n){let r=t.colors,i=[r.dim(t.glyph.hrule.repeat(Math.max(1,n)))];e.title.length>0&&i.push(` ${r.bold(e.title)}`),i.push(``);let a=e.lines.slice(-6);for(let e of a){let n=e.tone===`info`?r.dim(e.text):e.text;i.push(` ${toneGlyph(e.tone,t)} ${n}`)}switch(a.length>0&&i.push(``),e.content.kind){case`question`:e.content.status!==void 0&&i.push(` ${renderIndicator(e.content.status.indicator,t)} ${r.dim(e.content.status.text)}`,``),i.push(...e.content.rows);break;case`status`:i.push(` ${renderIndicator(e.content.status.indicator,t)} ${r.dim(e.content.status.text)}`),e.content.preview!==void 0&&i.push(` ${r.dim(e.content.preview)}`);break;case`preview`:i.push(` ${renderIndicator(e.content.indicator,t)} ${r.dim(e.content.text)}`);break;case`idle`:i.push(` ${renderIndicator(e.content.indicator,t)} ${r.dim(`Working…`)}`);break}return i.map((e,t)=>t===0||e.length===0?clip(e,n):clip(` ${e}`,n))}function optionRow(e){let{option:t,theme:n}=e;return renderOptionRow({colors:n.colors,glyphs:{pointer:n.glyph.pointer,selectedPointer:n.glyph.selectedPointer,success:n.glyph.success,placeholder:n.glyph.option,dot:n.glyph.dot},label:t.label,hint:t.hint,focusHint:t.focusHint,accent:t.accent,isCursor:e.isCursor,state:resolveOptionRowState(t,e.isChecked),placeholder:e.placeholder,hintPadding:e.hintPadding})}function selectPresentation(e){switch(e.kind){case`single`:return{selection:`single`,filter:void 0,layout:`plain`,edit:void 0};case`search`:return{selection:`single`,filter:{placeholder:e.placeholder},layout:`plain`,edit:void 0};case`multi`:return{selection:`multiple`,filter:void 0,layout:`plain`,edit:void 0};case`searchable-multi`:return{selection:`multiple`,filter:{placeholder:e.placeholder},layout:`plain`,edit:void 0};case`stacked`:return{selection:`single`,filter:void 0,layout:`stacked`,edit:void 0};case`task-list`:return{selection:`single`,filter:void 0,layout:`task-list`,edit:void 0};case`inline-edit`:return{selection:`single`,filter:void 0,layout:e.layout,edit:e.edit}}}function selectMessageRows(e,t,n){if(e===``)return[];let r=e.split(`
2
+ `).map((e,r)=>` ${t===`stacked`||r>0?n.colors.bold(e):e}`);return r.push(``),r}function searchFilter(e,t,n,r){let i=r.colors.dim(r.glyph.caret),a=i;return e.length>0?a=e+i:t!==void 0&&(a=r.colors.dim(`> ${t}`)),n===void 0?a:`${a} ${r.colors.yellow(n)}`}function selectViewSize(e){return e.search?e.filter===``&&e.featuredLead>0?Math.min(e.featuredLead,8):8:e.optionCount}function noticeBody(e,t,n){return e.tone===`info`?n.colors.dim(e.text):e.tone===`success`&&t===`task-list`?n.colors.bold(e.text):e.text}function renameHint(e,t,r,i){let a=renderInputWithBlockCursor({...visibleLine({text:r.editor.text||r.defaultValue,cursor:r.editor.cursor},1/0),visible:t,inverse:i.colors.inverse});return r.editor.text.length>0&&(a=solidWithinDim(a,i)),{...e,hint:r.formatHint(a)}}function keyHint(e,i,s,c,l){let u=s.phase;if(u.kind===`inactive`)return e;let d=maskLine(u.editor),f=u.kind!==`validating`&&u.kind!==`invalid`,p=``,m=``;u.kind===`validating`?p=`Validating… `:u.kind===`invalid`&&(m=` ${c.colors.red(`${c.glyph.error} ${c.colors.bold(`Invalid key`)}`)}`);let h=u.editor.text.length===0?`type your key`:void 0,g=visibleLine(h===void 0?d:{text:h,cursor:0},Math.max(1,l-visibleLength(`> ${p}${m}`)),c.glyph.ellipsis),_=f?renderInputWithBlockCursor({...g,visible:i,inverse:c.colors.inverse}):renderInputText(`${g.before}${g.under}${g.after}`);return{...e,hint:`> ${p}${_}${m}`}}function inlineEditOption(e,t,n,r,i){if(!t||n===void 0||e.value!==n.optionValue)return e;switch(n.editor.kind){case`rename`:return renameHint(e,n.caretVisible,n.editor,r);case`key`:return keyHint(e,n.caretVisible,n.editor,r,i)}}function optionWithoutStackedHint(e,t){if(t!==`stacked`||e.hint===void 0)return{option:e,stackedHint:void 0};let{hint:n,...r}=e;return{option:r,stackedHint:n}}function optionUsesPlaceholder(e,t,n){let r=e.filter!==void 0,i=e.layout===`task-list`&&t===n-1,a=e.selection===`multiple`,o=e.layout!==`plain`;return!r&&!i&&(a||o)}function appendSelectOptionRows(e){let{rows:t,state:n,presentation:r,visible:i,start:a,end:o,cursor:s,visibleLabelWidth:c,width:u,theme:d}=e,f=d.colors;for(let e=a;e<o;e+=1){let p=i[e],m=e===s;r.layout===`task-list`&&e===o-1&&e>a&&t.push(``);let h=r.layout===`stacked`?Math.max(1,u-6):Math.max(1,u-Math.max(c,p.label.length)-9),{option:g,stackedHint:_}=optionWithoutStackedHint(inlineEditOption(p,m,r.edit,d,h),r.layout);if(t.push(` ${optionRow({option:g,isCursor:m,isChecked:r.selection===`multiple`&&n.select.selected.has(p.value),placeholder:optionUsesPlaceholder(r,e,i.length),hintPadding:Math.max(0,c-g.label.length),theme:d})}`),_!==void 0){let e=r.edit,n=m&&e!==void 0&&e.optionValue===p.value&&e.editor.kind===`key`&&e.editor.phase.kind!==`inactive`;for(let e of _.split(`
3
3
  `)){let r=m?n?e:foregroundWithEmphasis(e):dimWithEmphasis(e,d);t.push(` ${renderOptionRowContinuation(r)}`)}}if(p.description!==void 0&&(p.disabled===!0||m)){let e=f.dim(p.description);t.push(r.layout===`stacked`?` ${renderOptionRowContinuation(e)}`:` ${e}`)}r.layout===`stacked`&&e<o-1&&t.push(``)}}function appendSubmitRow(e,t,n,r){if(n<0)return;let i=t===n,a=i?`${r.glyph.selectedPointer} ${r.colors.bold(`Submit`)}`:` Submit`;e.push(``,` ${renderCursorRow(a,i,r.colors)}`)}function appendSelectNotices(e,t,n,a,o){if(!(t===void 0||t.length===0)){e.push(``);for(let s of t){let t=toneGlyph(s.tone,a),c=` `.repeat(visibleLength(t)+1),l=Math.max(1,o-2-visibleLength(t)-1),u=wrapVisibleLine(s.text,l);for(let[r,i]of u.entries()){let o=noticeBody({...s,text:i},n,a);e.push(r===0?` ${t} ${o}`:` ${c}${o}`)}}}}function selectFooterHints(e,t,n){let r=[],i=`esc to cancel`,a=e.edit;if(a!==void 0&&t[n]?.value===a.optionValue)if(a.editor.kind===`key`){let e=a.editor.phase;if(e.kind!==`inactive`&&e.editor.text.length>0&&(i=`esc to clear`),e.kind===`validating`)return[i];r.push(`type your key`)}else r.push(`type to rename`);return e.filter!==void 0&&r.push(`type to filter`),r.push(`↑/↓ move`),r.push(e.selection===`multiple`?`space to toggle`:`enter to select`),e.selection===`multiple`&&r.push(`enter on Submit to confirm`),r.push(i),r}function renderActionQuestion(e,t,n){let r=[` ${t.colors.dim(`${t.glyph.dot} ${e.context}`)}`,``];for(let[n,i]of e.actions.entries())r.push(` ${optionRow({option:i,isCursor:n===e.cursor,isChecked:!1,placeholder:!0,hintPadding:0,theme:t})}`);return r.push(...questionFooter([`↑/↓ move`,`enter to select`,`esc to cancel`],t)),r.map(e=>clip(e,n))}function renderSelectQuestion(e,t,n){if(e.kind===`actions`)return renderActionQuestion(e,t,n);let r=t.colors,i=selectPresentation(e),a=i.filter?filterOptions(e.options,e.select.filter,e.searchAction):e.options,o=i.selection===`multiple`?submitRowIndex(a):-1,s=e.select.cursor,c=selectMessageRows(e.message,i.layout,t);i.filter!==void 0&&c.push(` ${searchFilter(e.select.filter,i.filter.placeholder,e.loadingFrame,t)}`);let l=0;for(;a[l]?.featured;)l+=1;let u=selectViewSize({search:i.filter!==void 0,filter:e.select.filter,featuredLead:l,optionCount:a.length}),p=Math.max(0,Math.min(s-Math.floor(u/2),Math.max(0,a.length-u))),m=Math.min(p+u,a.length),h=a.slice(p,m).filter(e=>e.hint!==void 0||e.focusHint!==void 0).reduce((e,t)=>Math.max(e,t.label.length),0);return a.length===0&&c.push(` ${r.dim(`(no matches)`)}`),appendSelectOptionRows({rows:c,state:e,presentation:i,visible:a,start:p,end:m,cursor:s,visibleLabelWidth:h,width:n,theme:t}),appendSubmitRow(c,s,o,t),a.length>m-p&&c.push(` ${r.dim(`↑↓ ${a.length} options, showing ${p+1}–${m}`)}`),appendSelectNotices(c,e.notices,i.layout,t,n),e.error!==void 0&&c.push(``,` ${r.red(e.error)}`),c.push(...questionFooter(selectFooterHints(i,a,s),t)),c.map(e=>clip(e,n))}function renderTextQuestion(e,r,i,s){let c=r.colors,l=[];for(let t of e.notices??[]){let e=t.tone===`info`?c.dim(t.text):t.text;l.push(`${toneGlyph(t.tone,r)} ${e}`)}l.push(...e.message.split(`
4
4
  `).map(e=>` ${c.bold(e)}`));let u=Math.max(4,i-4),d=e.mask?maskLine(e.editor):e.editor,f=e.editor.text.length===0?e.placeholder:void 0,p=renderInputWithBlockCursor({...visibleLine(f===void 0?d:{text:f,cursor:0},u,r.glyph.ellipsis),visible:s,inverse:c.inverse,render:f===void 0?renderInputText:e=>c.dim(renderInputText(e))});return l.push(` ${p}`),e.error!==void 0&&l.push(``,` ${c.red(e.error)}`),l.push(...questionFooter([`enter to submit`,`esc to cancel`],r)),l.map(e=>clip(e,i))}function renderAcknowledgeQuestion(e,t,n){let r=t.colors,i=[` ${r.bold(e.message)}`];if(e.lines.length>0){i.push(``);for(let t of e.lines)i.push(` ${r.dim(t)}`)}return i.push(...questionFooter([`enter to continue`],t)),i.map(e=>clip(e,n))}export{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion};
@@ -4,6 +4,8 @@ import type { RemoteConnectionSnapshot } from "./remote-connection.js";
4
4
  import type { VercelStatusSnapshot } from "./vercel-status.js";
5
5
  import type { ModelEndpointStatus } from "#shared/model-endpoint-status.js";
6
6
  export interface StatusLineInput {
7
+ /** Port of the connected local development server; omitted for remote sessions. */
8
+ serverPort?: string;
7
9
  /** Resolved model slug, e.g. "anthropic/claude-sonnet-4-6"; absent when `/eve/v1/info` failed. */
8
10
  model?: string;
9
11
  /** Preformatted token-flow segment (formatTokenFlow output), e.g. `↑ 394.4K ↓ 4.3K`. */
@@ -25,8 +27,9 @@ export interface StatusLineInput {
25
27
  width: number;
26
28
  }
27
29
  /**
28
- * Builds `↗ project (environment) · model · tokens · /deploy pending`.
29
- * Remote sessions omit endpoint state and keep their badge as the final
30
- * narrow-width fallback. Returns undefined when every segment is empty.
30
+ * Builds a leading local `:port` or remote badge followed by model, token, and
31
+ * deploy status segments. Both badges are the final narrow-width fallback.
32
+ * Remote sessions omit endpoint state. Returns undefined when every segment is
33
+ * empty.
31
34
  */
32
35
  export declare function buildStatusLine(input: StatusLineInput): string | undefined;
@@ -1 +1 @@
1
- import{clipVisible,stripAnsi,visibleLength}from"./terminal-text.js";import{remoteHost}from"./target.js";function renderModel(e){if(e.model===void 0)return;let n=e.remote===void 0?e.model:stripAnsi(e.model).replace(/\s+/gu,` `).trim();return e.theme.colors.dim(n)}function renderEndpoint(e){if(e.remote!==void 0||e.endpoint===void 0)return;let t=e.theme.colors;if(e.endpoint.kind===`external`)return t.dim(`External endpoint`);if(!e.endpoint.connected)return t.yellow(`${e.theme.glyph.warning} AI Gateway`);let n=e.vercel?.identity?.projectName;return t.dim(n===void 0?`AI Gateway`:`AI Gateway (${n})`)}function buildStatusLine(t){let{theme:r,width:i}=t,a=r.colors,o=t.logLevel===void 0?void 0:a.cyan(`logs: ${t.logLevel}`),s=renderModel(t),c=t.tokens===void 0?void 0:a.dim(t.tokens),l=t.vercel?.pendingDeploy?a.yellow(`/deploy pending`):void 0,u=t.remote===void 0?void 0:formatRemoteStatus(t.remote,r),d=renderEndpoint(t),f=` ${a.dim(r.glyph.dot)} `,compose=e=>e.filter(e=>e!==void 0).join(f),p=[compose([u?.full,o,s,c,d,l]),compose([u?.full,o,s,c,l]),compose([u?.full,o,c,l]),compose([u?.full,o]),compose([u?.badge,o]),compose([u?.badge])];if(p[0].length!==0){for(let e of p)if(e.length>0&&visibleLength(e)<=i)return e;return clipVisible(p.findLast(e=>e.length>0),i)}}function formatRemoteStatus(e,t){let n=t.colors,i=e.deployment===void 0?remoteHost(e.target):`${e.deployment.projectName} (${e.deployment.environment})`,a=formatRemoteBadge(` ${t.unicode?`↗`:`->`} ${i} `,e.connection.state,t),o=` ${n.dim(t.glyph.dot)} `,s;switch(e.connection.state){case`checking`:s=n.dim(`Checking access…`);break;case`ready`:break;case`auth-required`:s=n.yellow(`Authenticate via OIDC`);break;case`authenticating`:s=n.dim(`Authenticating via OIDC…`);break;case`auth-failed`:s=n.yellow(`Authentication failed`);break;case`unavailable`:s=n.yellow(`Remote unavailable`);break}return{badge:a,full:s===void 0?a:`${a}${o}${s}`}}function formatRemoteBadge(e,t,n){let r=n.colors;switch(t){case`checking`:return r.inverse(r.gray(e));case`ready`:return r.inverse(r.blue(e));case`unavailable`:case`auth-required`:case`authenticating`:case`auth-failed`:return r.inverse(r.yellow(e))}}export{buildStatusLine};
1
+ import{clipVisible,stripAnsi,visibleLength}from"./terminal-text.js";import{remoteHost}from"./target.js";function renderModel(e){if(e.model===void 0)return;let n=e.remote===void 0?e.model:stripAnsi(e.model).replace(/\s+/gu,` `).trim();return e.theme.colors.dim(n)}function renderServerPort(e){if(e.remote!==void 0||e.serverPort===void 0)return;let t=e.theme.colors;return t.inverse(t.gray(` :${e.serverPort} `))}function renderEndpoint(e){if(e.remote!==void 0||e.endpoint===void 0)return;let t=e.theme.colors;if(e.endpoint.kind===`external`)return t.dim(`External endpoint`);if(!e.endpoint.connected)return t.yellow(`${e.theme.glyph.warning} AI Gateway`);let n=e.vercel?.identity?.projectName;return t.dim(n===void 0?`AI Gateway`:`AI Gateway (${n})`)}function buildStatusLine(t){let{theme:r,width:i}=t,a=r.colors,o=t.logLevel===void 0?void 0:a.cyan(`logs: ${t.logLevel}`),s=renderServerPort(t),c=renderModel(t),l=t.tokens===void 0?void 0:a.dim(t.tokens),u=t.vercel?.pendingDeploy?a.yellow(`/deploy pending`):void 0,d=t.remote===void 0?void 0:formatRemoteStatus(t.remote,r),f=renderEndpoint(t),p=d?.full??s,m=d?.badge??s,h=` ${a.dim(r.glyph.dot)} `,compose=(e,t)=>{let n=t.filter(e=>e!==void 0).join(h);return e===void 0||n.length===0?e??n:`${e} ${n}`},g=[compose(p,[o,c,l,f,u]),compose(p,[o,c,l,u]),compose(p,[o,l,u]),compose(p,[o]),compose(m,[o]),compose(m,[])];if(g[0].length!==0){for(let e of g)if(e.length>0&&visibleLength(e)<=i)return e;return clipVisible(g.findLast(e=>e.length>0),i)}}function formatRemoteStatus(e,t){let n=t.colors,i=e.deployment===void 0?remoteHost(e.target):`${e.deployment.projectName} (${e.deployment.environment})`,a=formatRemoteBadge(` ${t.unicode?`↗`:`->`} ${i} `,e.connection.state,t),o=`${n.dim(t.glyph.dot)} `,s;switch(e.connection.state){case`checking`:s=n.dim(`Checking access…`);break;case`ready`:break;case`auth-required`:s=n.yellow(`Authenticate via OIDC`);break;case`authenticating`:s=n.dim(`Authenticating via OIDC…`);break;case`auth-failed`:s=n.yellow(`Authentication failed`);break;case`unavailable`:s=n.yellow(`Remote unavailable`);break}return{badge:a,full:s===void 0?a:`${a}${o}${s}`}}function formatRemoteBadge(e,t,n){let r=n.colors;switch(t){case`checking`:return r.inverse(r.gray(e));case`ready`:return r.inverse(r.blue(e));case`unavailable`:case`auth-required`:case`authenticating`:case`auth-failed`:return r.inverse(r.yellow(e))}}export{buildStatusLine};
@@ -1,6 +1,6 @@
1
1
  import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{toErrorMessage}from"#shared/errors.js";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{StringDecoder}from"node:string_decoder";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e,t){return e?`Interrupted`:t?`Ready`:`Done`}const STATUS={processing:`Working…`,toolResults:`Reading results…`,streaming:`Responding…`,executingTools:`Running tools…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=[];#m=new Map;#h=new Set;#g=[];#_=new Set;#v=new Map;#y=new Set;#b;#x=!1;#S;#C=[];#w;#T=0;#E;#D;#O=``;#k=0;#A=new PromptHistory;#j=!1;#M;#N={kind:`idle`};#P=STATUS.processing;#F=`eve`;#I=!1;#L=!1;#R=!0;#z=0;#B;#V;#H;#U=!1;#W;#G=``;#K=new StringDecoder(`utf8`);#q;#J;#Y;#X=!1;#Z=!1;#Q;#$;#ee;#te;#ne;#re;#ie;#ae=``;#oe=``;#se;#ce;#le=0;#ue;#de;#fe;#pe;#me;setupFlow={begin:(e,t)=>this.#ve(e,t),end:e=>this.#ye(e?.preserveDiagnostics??!0),readSelect:e=>this.#be(e),readEditableSelect:e=>this.#Se(e),readProviderPicker:e=>this.#Ce(e),readText:e=>this.#we(e),readAcknowledge:e=>this.#Te(e),readChoice:e=>this.#xe(e),setStatus:e=>this.#Ne(e),renderLine:(e,t)=>this.#Pe(e,t),renderOutput:e=>this.#Fe(e),waitForInterrupt:()=>this.#Ae()};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#i=e?.tools??`auto-collapsed`,this.#a=e?.reasoning??`full`,this.#o=e?.subagents??`auto-collapsed`,this.#s=e?.connectionAuth??`full`,this.#c=e?.assistantResponseStats??`tokensPerSecond`,this.#l=e?.contextSize,this.#ee=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#f=e?.logs??`none`,this.#d=e?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#F=e.name,this.#b=e,this.#Ie();let t=this.#vt().join(`
2
2
  `);if(this.#x){t!==this.#S&&(this.#S=t,this.#Ze({kind:`agent-header`,body:t,live:!1})),this.#pt();return}this.#x=!0,this.#S=t,this.#n.flush(this.#vt(),[])}async readPrompt(e){this.#Ie(e),this.#Xe(),this.#j=!0,this.#N={kind:`idle`},this.#P=``;let t=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#A.begin(t.text),this.#he(t),this.#M=typeaheadFor(this.#d,t.text),this.#Ge(),this.#pt(),await new Promise((e,n)=>{let apply=e=>{t=e,this.#qe(),this.#he(t),this.#M=typeaheadFor(this.#d,e.text,this.#M),this.#pt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#M=void 0,this.#Ke(),this.#Le(),n(interruptedError())},suggestions=()=>this.#M!==void 0&&isTypeaheadOpen(this.#M)?this.#M:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#W=n=>{let r=applyLineEditorKey(t,n,{multiline:!0});if(r!==void 0){apply(r);return}switch(n.type){case`up`:{let e=suggestions();if(e!==void 0){this.#M=moveTypeaheadSelection(e,-1),this.#pt();break}let n=movePromptLine(t,`up`);n===void 0?recall(this.#A.previous(t.text)):apply(n);break}case`down`:{let e=suggestions();if(e!==void 0){this.#M=moveTypeaheadSelection(e,1),this.#pt();break}let n=movePromptLine(t,`down`);n===void 0?recall(this.#A.next()):apply(n);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#M=dismissTypeahead(e),this.#pt());break}case`enter`:{let n=highlighted(),r=n!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(n).trimEnd():t.text;this.#M=void 0,this.#A.add(r),this.#j=!1,this.#Ke(),this.#Ye(),this.#P=STATUS.processing,isPromptControlCommand(r)?this.#Ze({kind:`command`,body:stripTerminalControls(r.trim()),live:!1}):(this.#Qe(r),this.#ue=r),this.#he(EMPTY_LINE),this.#pt(),this.#ze(),e(r);break}case`ctrl-d`:t.text.length===0?interrupt():apply(deleteForward(t));break;case`ctrl-l`:this.#gt();break;case`ctrl-r`:this.#pt();break;case`ctrl-c`:t.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#Re()})}#he(e){this.#O=e.text,this.#k=e.cursor}async renderStream(e,t){this.#Ie(t),this.#h.clear(),this.#j=!1,this.#N.kind!==`waiting`&&(this.#N={kind:`waiting`,startedAtMs:Date.now()}),this.#P=STATUS.processing,this.#$e(t?.submittedPrompt),this.#L=!1,this.#Q=void 0,this.#$=void 0,this.#te=void 0,this.#ne=void 0,this.#re=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#Je(),this.#pt();let r=new Promise(e=>{this.#Y=e});this.#W=e=>this.#We(e),this.#Re();let i={text:new Map,reasoning:new Map,tools:new Map,hasPendingToolResults:!1};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#L)break;this.#at(t,n,i)}}catch(e){this.#et(`Error`,toErrorMessage(e))}finally{this.#Y=void 0,this.#L&&e.abort?.(),this.#ze(),this.#Xe(),this.#N.kind===`waiting`&&(this.#N={kind:`idle`}),this.#P=completedTurnStatus(this.#L,t?.continueSession===!0),this.#it(),this.#pt(),t?.continueSession||this.#Le()}}async readToolApproval(e,t){return this.#Ie(t),this.#Xe(),this.#j=!1,this.#N={kind:`idle`},this.#P=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#L=!1,this.#pt(),await new Promise((t,n)=>{this.#W=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Ye(),this.#P=STATUS.processing,this.#ze(),this.#pt(),t({approved:!0})):n===`n`&&(this.#Ye(),this.#P=STATUS.processing,this.#ge(e.toolCallId),this.#ze(),this.#pt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#pt();break;case`ctrl-c`:this.#L=!0,this.#Le(),n(interruptedError());break;default:break}},this.#Re()})}async readInputQuestion(e,t){this.#Ie(t),this.#Xe(),this.#j=!1,this.#N={kind:`idle`},this.#L=!1;let n=e.options??[],r=n.length>0,a=(e.allowFreeform===!0||!r)&&r,o=n.length+ +!!a,s=questionSectionId(e.requestId),c=r?`select`:`text`,l=0,u=EMPTY_LINE,isOnFreeformRow=()=>a&&l===n.length,renderSection=()=>{this.#nt({id:s,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,l,this.#r),preformatted:!0,live:!0})},repaintStatus=()=>{if(c===`select`){let e=isOnFreeformRow()?`type`:`select`;this.#P=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#j=!1}else this.#j=!0,this.#he(u),this.#P=``;this.#pt()};renderSection(),c===`text`&&this.#Ge(),repaintStatus();let finalize=t=>{this.#nt({id:s,kind:`question`,title:stripTerminalControls(e.prompt),body:` ${this.#r.colors.green(this.#r.glyph.success)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#j=!1,this.#Ye(),this.#P=STATUS.processing,this.#Ke(),this.#ze(),this.#pt();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n};return await new Promise((t,i)=>{this.#W=a=>{if(a.type===`ctrl-c`){if(c===`text`&&u.text.length>0){u=EMPTY_LINE,this.#qe(),repaintStatus();return}this.#L=!0,this.#Ke(),this.#Le(),i(interruptedError());return}if(a.type===`ctrl-r`){this.#pt();return}if(c===`select`){switch(a.type){case`up`:o>0&&(l=(l-1+o)%o,renderSection(),repaintStatus());break;case`down`:o>0&&(l=(l+1)%o,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){c=`text`,u=EMPTY_LINE,this.#Ge(),repaintStatus();break}let e=n[l];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}let s=applyLineEditorKey(u,a,{multiline:!0});if(s!==void 0){u=s,this.#qe(),repaintStatus();return}switch(a.type){case`up`:case`down`:{let e=movePromptLine(u,a.type);e!==void 0&&(u=e,this.#qe(),repaintStatus());break}case`enter`:{let n=resolveQuestionText(u.text,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(r){if(u.text.length>0){u=EMPTY_LINE,this.#qe(),repaintStatus();break}c=`select`,u=EMPTY_LINE,this.#j=!1,this.#Ke(),repaintStatus();break}u=EMPTY_LINE,this.#qe(),repaintStatus();break;default:break}},this.#Re()})}upsertSubagentStep(e){if(this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#tt(e.callId,e.subagentName),this.#o===`collapsed`){this.#pt();return}this.#nt({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:n,live:!e.finalized}),this.#pt()}}upsertSubagentTool(e){if(this.#o===`hidden`)return;if(this.#tt(e.callId,e.subagentName),this.#o===`collapsed`){this.#pt();return}let t=subagentToolStatus(e.status),n={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,depth:1,title:stripTerminalControls(e.toolName),subtitle:summarizeToolArgs(e.input),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolInput:e.input};e.output===void 0?e.errorText!==void 0&&(n.result=stripTerminalControls(e.errorText)):(n.result=summarizeToolResult(e.output),n.toolOutput=e.output),this.#nt(n),this.#pt()}markChildToolCallId(e){this.#_.add(e);let t=this.#v.get(e);t!==void 0&&(this.#rt(t),this.#v.delete(e),this.#pt())}#ge(e){let t=this.#m.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=e.state===`authorized`||e.state===`declined`||e.state===`failed`||e.state===`timed-out`;this.#nt({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e),preformatted:!0,live:!t}),this.#pt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#T)return;let n=this.#T>0;this.#T=t,t>0?(this.#P=STATUS.connectionAuth,this.#pt()):n&&(this.#P=STATUS.processing,this.#pt())}setVercelStatus(e){this.#E=e,this.#pt()}setRemoteConnectionStatus(e){this.#D=e,this.#pt()}reset(){this.#p=[],this.#m.clear(),this.#h.clear(),this.#w=void 0,this.#C.length=0,this.#g.length=0,this.#x=!1,this.#S=void 0,this.#_.clear(),this.#v.clear(),this.#y.clear(),this.#ue=void 0,this.#ce=void 0,this.#T=0,this.#Q=void 0,this.#$=void 0,this.#te=void 0,this.#ne=void 0,this.#re=void 0,this.#I&&(this.#n.clearAll(),this.#pt())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ie(),this.#Ze({kind:`notice`,body:t,live:!1}),this.#pt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#Ie(),this.#Ze({kind:`sandbox`,body:t,live:!1}),this.#pt())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#_e();return}this.#Ie(),this.#fe=t,this.#pt()}clearSetupWarning(){this.#_e()}#_e(){this.#fe!==void 0&&(this.#fe=void 0,this.#pt())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#Ie();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Ze(r),this.#pt()}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ie(),this.#Ze({kind:`result`,body:t,live:!1}),this.#pt())}#ve(e,t=`spinner`){this.#Ie(),this.#j=!1,this.#N={kind:`idle`},this.#P=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#de={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Je(),this.#pt()}#ye(e){this.#pe=void 0,this.#Me();let t=this.#de;if(t!==void 0){if(this.#de=void 0,this.#Xe(),e){let e=[];for(let n of t.lines){if(n.evidence===!0){e.push(n.text);continue}(n.tone===`warning`||n.tone===`error`)&&(e.length>0&&this.#Ze({kind:`flow`,title:`info`,body:e.join(`
3
- `),live:!1}),this.#Ze({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#pt()}}async#be(e){let t=this.#Ee(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a={options:i,searchAction:r,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(a.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(a.initialValues=e.initialValues);let o=initialSelectState(a),s,c=!1,l=0,isCurrentSearch=e=>e===l,clearSearch=()=>{l+=1,c=!1,o=reduceSelect(o,{type:`clear`},{options:i,searchAction:r,submitRow:n}),this.#pt()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#pt();try{let s=await t(e);if(!isCurrentSearch(a))return;let c=o.filter;i=s,o={...initialSelectState({options:s,searchAction:r,submitRow:n}),filter:c}}catch(e){isCurrentSearch(a)&&(s=toErrorMessage(e))}finally{isCurrentSearch(a)&&(c=!1,this.#pt())}},u=e.notices;if(e.kind===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#bt()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#pt(),await this.#ke((t,a)=>{let close=e=>{l+=1,a(e)};if(c){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#pt();return}let u={key:t,options:i,searchAction:r,select:o},d=reduceSetupSelectInput(n?{...u,kind:e.kind,required:e.required}:{...u,kind:e.kind});switch(d.kind){case`cancel`:close(void 0);return;case`repaint`:this.#pt();return;case`update`:o=d.select,s=void 0,this.#pt();return;case`submit`:{let e=searchActionQuery(d.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(d.values);return}loadSearch(e,t);return}case`error`:s=d.message,this.#pt();return;case`ignore`:return}}).promise}#xe(e){this.#Ie();let t=this.#De();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#pt();let r=this.#ke((t,r)=>{let i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#pt();return;case`repaint`:this.#pt();return;case`submit`:n!==void 0&&r(e.actions[n].value);return;case void 0:return}},()=>{t.status=void 0});return{choice:r.promise,close:()=>r.settle(void 0)}}async#Se(e){let t=this.#Ee(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#R,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?(i.text.length===0&&(i=lineOf(e.editable.defaultValue)),this.#Ge()):(i=lineOf(``),this.#Ke())};return syncEditableRow(),this.#pt(),await this.#ke((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#qe(),this.#pt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#pt()},submit=()=>{let t=selectValueAtCursor([...e.options],r.cursor);if(t===void 0)return;if(t!==e.editable.value){n({kind:`selected`,value:t});return}let o=(i.text||e.editable.defaultValue).trim(),s=e.editable.validate?.(o);if(s!==void 0){a=s,this.#pt();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#pt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ke()).promise}async#Ce(e){let t=this.#Ee(),n=initialProviderPickerState(e.options,e.initialValue),r;t.question=t=>renderSelectQuestion({kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#R,editor:{kind:`key`,phase:n.phase}}},this.#r,t);let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#Ge():this.#Ke()};return syncCaret(),this.#pt(),await this.#ke((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#pt();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#pt();return;case`validate`:{n=o.state,syncCaret(),this.#pt();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#pt();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#qe(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Ke()}).promise}async#we(e){let t=this.#Ee(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder!==void 0&&(i.placeholder=e.placeholder),e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#r,t,this.#R)},this.#Ge(),this.#pt(),await this.#ke((t,i)=>{let apply=e=>{n=e,r=void 0,this.#qe(),this.#pt()},a=applyLineEditorKey(n,t);if(a!==void 0){apply(a);return}switch(t.type){case`ctrl-c`:case`escape`:i(void 0);return;case`ctrl-r`:this.#pt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#pt();return}i(t);return}default:return}},()=>this.#Ke()).promise}async#Te(e){let t=this.#Ee();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#pt(),await this.#ke((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#pt();return;default:return}}).promise}#Ee(){return this.#Ie(),this.#j=!1,this.#N={kind:`idle`},this.#P=``,this.#De()}#De(){return this.#de===void 0&&(this.#de={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[]}),this.#de}#Oe(){this.#de!==void 0&&(this.#de.question=void 0,this.#de.hideLinesWhileQuestion=!1),this.#W=void 0,this.#ze(),this.#je(),this.#pt()}#ke(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Oe(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Oe(),i(e))};return this.#W=t=>e(t,settle,reject),this.#Re(),{promise:a,settle}}#Ae(){let e,t=new Promise(t=>{e=t});return this.#pe=e,this.#je(),{promise:t,dispose:()=>{this.#pe===e&&(this.#pe=void 0,this.#Me())}}}#je(){if(this.#pe===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#pe;this.#pe=void 0,this.#Me(),e?.();return}e.type===`ctrl-r`&&this.#pt()};this.#me=consumer,this.#W=consumer,this.#Re()}#Me(){this.#me!==void 0&&(this.#W===this.#me&&this.#ze(),this.#me=void 0)}#Ne(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#de!==void 0){this.#de.status=t,t===void 0&&(this.#de.preview=void 0),this.#pt();return}if(t===void 0){this.#N={kind:`idle`},this.#P=``,this.#Xe(),this.#pt();return}this.#Ie(),this.#Ye(),this.#P=t,this.#pt()}#Pe(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#de;if(r!==void 0){if(r.preview=void 0,t===`warning`||t===`error`)for(let e of r.outputBuffer)r.lines.push({text:e,tone:`info`,evidence:!0});r.outputBuffer=[],r.lines.push({text:n,tone:t}),this.#pt();return}this.#Ie(),this.#Ze({kind:`flow`,title:t,body:n,live:!1}),this.#pt()}#Fe(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#de;if(n===void 0){this.#Pe(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#pt()}shutdown(){this.#Le()}#Ie(e){this.#F=e?.title??this.#F,this.#ee=e?.contextSize??this.#l,!this.#I&&(this.#I=!0,this.#n.reset(),this.#n.hideCursor(),this.#kt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#J=()=>this.#pt(),this.#t.on(`resize`,this.#J))}#Le(){this.#ze(),this.#Ke(),this.#Xe(),this.#H!==void 0&&(clearTimeout(this.#H),this.#H=void 0),this.#U=!1,this.#I&&=(this.#Lt(),this.#pt(),this.#n.clear(),this.#n.showCursor(),this.#At(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#J&&=(this.#t.off(`resize`,this.#J),void 0),!1)}#Re(){this.#e.off(`data`,this.#Be),this.#e.on(`data`,this.#Be)}#ze(){this.#e.off(`data`,this.#Be),this.#Ue(),this.#G=``,this.#K=new StringDecoder(`utf8`),this.#W=void 0}#Be=e=>{this.#Ue(),this.#G+=this.#K.write(e),this.#He(),this.#Ve()};#Ve(){if(this.#G===`\x1B`){this.#q=setTimeout(()=>{this.#G===`\x1B`&&(this.#G=``,this.#W?.({type:`escape`}))},30),this.#q.unref?.();return}if(isIncompletePaste(this.#G)){let e=this.#G;this.#q=setTimeout(()=>{if(this.#G!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#G=``,t.length>0&&this.#W?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#q.unref?.()}}#He(){for(;this.#G.length>0;){let e=nextKey(this.#G);if(e.incomplete)return;this.#G=this.#G.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#W?.(e.key)}}#Ue(){this.#q&&=(clearTimeout(this.#q),void 0)}#We(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#pt();break;case`ctrl-c`:this.#L||(this.#L=!0,this.#N={kind:`idle`},this.#P=`Interrupted`,this.#Y?.(),this.#pt());break;default:break}}#Ge(){this.#Ke(),this.#qe(),this.#B=setInterval(()=>{this.#R=!this.#R,this.#pt()},500),this.#B.unref?.()}#Ke(){this.#B&&=(clearInterval(this.#B),void 0),this.#R=!0}#qe(){this.#R=!0}#Je(){this.#Xe(),this.#V=setInterval(()=>{this.#z+=1,this.#pt()},90),this.#V.unref?.()}#Ye(){this.#N={kind:`waiting`,startedAtMs:Date.now()},this.#Je()}#Xe(){this.#V&&=(clearInterval(this.#V),void 0)}#Ze(e){e.id!==this.#ce?.id&&this.#Lt(),this.#p.push(e),e.id&&this.#m.set(e.id,e)}#Qe(e){this.#Ze({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#pt()}#$e(e){if(e!=null){if(this.#ue===e){this.#ue=void 0;return}this.#Ze({kind:`user`,body:stripTerminalControls(e),live:!1})}}#et(e,t,n){let r={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};n!==void 0&&(r.detail=stripTerminalControls(n)),this.#Ze(r),this.#pt()}#tt(e,t){this.#y.has(e)||(this.#y.add(e),this.#Ze({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#nt(e){if(e.id&&this.#h.has(e.id))return;let t=e.id?this.#m.get(e.id):void 0;if(t){Object.assign(t,e);return}this.#Ze(e)}#rt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#it(){for(let e of this.#p)e.status===`approval`||e.status===`running`||(e.live=!1)}#at(e,t,n){switch(e.type){case`step-start`:this.#ot(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#ft(e.usage),this.#pt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);this.#st(t),this.#ot(STATUS.streaming),n.text.set(e.id,t),this.#ct(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;this.#st(r),n.text.set(e.id,r),this.#ct(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);this.#st(r),this.#ot(STATUS.streaming),n.reasoning.set(e.id,r),this.#lt(e.id,r,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#st(r),this.#lt(e.id,r,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#ot(STATUS.executingTools),this.#ut({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;this.#ut({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#dt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#ot(STATUS.toolResults),this.#ut({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{if(t.tools===`hidden`)break;let r=this.#dt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#ot(STATUS.toolResults),this.#ut({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#et(`Error`,e.errorText,e.detail);break;case`finish`:this.#ft(e.usage),this.#pt();break}}#ot(e){let t=this.#T>0?STATUS.connectionAuth:e;this.#P!==t&&(this.#P=t,this.#pt())}#st(e){e.trim().length>0&&(this.#N={kind:`answering`})}#ct(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#nt({id:e,kind:`assistant`,body:r,live:n}),this.#pt())}#lt(e,t,n,r){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#nt({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#pt())}#ut(e,t,n){if(n.tools.set(e.toolCallId,e),this.#_.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#v.set(e.toolCallId,r),this.#nt(renderNativeToolBlock(e,r,t.tools===`full`)),this.#pt()}#dt(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#v.get(e)??toolSectionId(e),i=this.#m.get(r);if(!(i===void 0||i.kind!==`tool`))return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.title??`tool`}}#ft(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#Q=(t??0)+(n??0)),this.#$=t??this.#$,this.#te=n??this.#te,this.#te!=null&&this.#re!==void 0){let e=(Date.now()-this.#re)/1e3;e>0&&(this.#ne=this.#te/e)}}#pt(){if(this.#I){if(this.#X){this.#Z=!0;return}this.#X=!0;try{do this.#Z=!1,this.#mt();while(this.#Z)}finally{this.#X=!1}}}#mt(){if(!this.#I)return;let e=this.#Dt(),t=this.#Ct(e),n=Math.max(1,this.#Ot()-t.length),r=[],i=this.#w;for(;this.#p.length>0&&this.#p[0].live===!1;){let t=this.#p.shift();if(this.#g.push(t),t.id&&(this.#h.add(t.id),this.#m.delete(t.id)),this.#zt(t))continue;let n=this.#yt(t,e,i);i=previousBlockOf(t),this.#w=i,r.push(...n),this.#C.push(...n)}let a=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#yt(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)a.push({block:t,row:n[e]})}let o=[...clipLiveRows(a.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,o):this.#n.update(o)}#ht(){if(!this.#I)return;let e=this.#Dt(),t=this.#Ct(e),n=Math.max(1,this.#Ot()-t.length),r=this.#w,i=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#yt(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#r),...t];this.#n.clearAll(),this.#n.flush([...this.#vt(),...this.#C],a)}logDisplayMode(){return this.#f}setLogDisplayMode(e){e!==this.#f&&(this.#f=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#_t(),this.#I&&this.#ht())}flushDelayedDevBuildErrors(){let e=this.#se;e!==void 0&&(this.#se=void 0,this.#Ze({kind:`log`,title:`stderr`,body:e,live:!1}),this.#pt())}#gt(){this.#U=!0,this.#H!==void 0&&clearTimeout(this.#H),this.#H=setTimeout(()=>{this.#U=!1,this.#H=void 0,this.#pt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#f)),this.#pt()}#_t(){let e=this.#Dt();this.#C.length=0;let t;for(let n of this.#g){if(this.#zt(n))continue;let r=this.#yt(n,e,t);t=previousBlockOf(n),this.#C.push(...r)}this.#w=t}#vt(){let e=this.#b;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#Dt()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#yt(e,t,n){let r={spinner:this.#bt()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#bt(){return this.#r.spinner[this.#z%this.#r.spinner.length]??``}#xt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#St(e){return e.indicator.kind===`spinner`?{glyph:this.#bt(),color:`yellow`}:{glyph:this.#xt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:`green`}}#Ct(e){let t=this.#r.colors,n=[``],r=this.#de;if(r!==void 0){let t=this.#St(r),i;if(r.question!==void 0){let n=r.question(e);i={kind:`question`,rows:n},r.status!==void 0&&(i={kind:`question`,rows:n,status:{text:r.status,indicator:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(i={kind:`status`,status:{text:r.status,indicator:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,indicator:t},preview:r.preview}));let a={title:r.title,lines:r.hideLinesWhileQuestion===!0?[]:r.lines,content:i};return n.push(...renderFlowPanel(a,this.#r,e)),this.#Tt(n,e),n}if(this.#fe!==void 0&&n.push(...renderAttentionRows(this.#fe,e,this.#r),``),this.#j){let r=this.#M===void 0?void 0:inlineCommandHint(this.#M);r===void 0&&this.#M!==void 0&&isTypeaheadOpen(this.#M)&&n.push(...renderCommandSuggestions(this.#M,this.#r,e));let i=isPromptControlCommand(this.#O),a=r?t.dim(` ${r}`):``,o=[];this.#wt(o,e);let s=Math.max(1,this.#Ot()-1-n.length-1-o.length);return n.push(...promptInputRows({text:this.#O,cursor:this.#k,width:e,theme:this.#r,caretVisible:this.#R,isCommand:i,ghost:a,maxRows:s})),n.push(...o),n}let i=this.#N;if(i.kind===`answering`)return this.#wt(n,e),n;let a=i.kind===`waiting`,o=a?t.green(this.#xt(i.startedAtMs,this.#r.unicode?`⊙`:`o`)):t.dim(this.#r.glyph.dot),s=this.#P.length>0?this.#P:`Ready`,c=a?t.dim(s):s,u=this.#Et(),f=a?` `:``,p=u?`${f}${o} ${c} ${t.dim(this.#r.glyph.dot)} ${u}`:`${f}${o} ${c}`;n.push(clip(p,e));let g=[];return this.#wt(g,e),a&&g.length>0&&n.push(``),n.push(...g),n}#wt(e,t){let n=this.#D===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#r,width:r};this.#U&&(i.logLevel=this.#f);let a=this.#b?.info?.agent.model.id;a!==void 0&&(i.model=a);let o=this.#b?.info?.agent.model.endpoint;o!==void 0&&(i.endpoint=o);let s=this.#$??0,c=this.#te??0;if(s>0||c>0){let e={inputTokens:s,outputTokens:c};this.#ee!==void 0&&(e.contextSize=this.#ee),i.tokens=formatTokenFlow(e,this.#r.glyph)}this.#E!==void 0&&(i.vercel=this.#E),this.#D!==void 0&&(i.remote=this.#D);let l=buildStatusLine(i);l!==void 0&&e.push(clip(`${n}${l}`,t))}#Tt(e,t){if(this.#D===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#D,theme:this.#r,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Et(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Q,outputTokens:this.#te,tokensPerSecond:this.#ne},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#Dt(){return Math.max(20,this.#t.columns||80)}#Ot(){return Math.max(8,this.#t.rows||24)}#kt(){if(this.#ie!==void 0||!this.#u)return;this.#ae=``,this.#oe=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#jt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ie=()=>{e(),t()}}#At(){let e=this.#ie;e!==void 0&&(this.#ie=void 0,e(),this.#ae.length>0&&(this.#Rt(`stdout`)&&process.stdout.write(`${this.#ae}\n`),this.#ae=``),this.#oe.length>0&&(this.#Rt(`stderr`)&&process.stderr.write(`${this.#oe}\n`),this.#oe=``))}#jt(e,t){let n=(e===`stdout`?this.#ae:this.#oe)+t,i=n.lastIndexOf(`
3
+ `),live:!1}),this.#Ze({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#pt()}}async#be(e){let t=this.#Ee(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a={options:i,searchAction:r,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(a.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(a.initialValues=e.initialValues);let o=initialSelectState(a),s,c=!1,l=0,isCurrentSearch=e=>e===l,clearSearch=()=>{l+=1,c=!1,o=reduceSelect(o,{type:`clear`},{options:i,searchAction:r,submitRow:n}),this.#pt()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#pt();try{let s=await t(e);if(!isCurrentSearch(a))return;let c=o.filter;i=s,o={...initialSelectState({options:s,searchAction:r,submitRow:n}),filter:c}}catch(e){isCurrentSearch(a)&&(s=toErrorMessage(e))}finally{isCurrentSearch(a)&&(c=!1,this.#pt())}},u=e.notices;if(e.kind===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#bt()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#pt(),await this.#ke((t,a)=>{let close=e=>{l+=1,a(e)};if(c){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#pt();return}let u={key:t,options:i,searchAction:r,select:o},d=reduceSetupSelectInput(n?{...u,kind:e.kind,required:e.required}:{...u,kind:e.kind});switch(d.kind){case`cancel`:close(void 0);return;case`repaint`:this.#pt();return;case`update`:o=d.select,s=void 0,this.#pt();return;case`submit`:{let e=searchActionQuery(d.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(d.values);return}loadSearch(e,t);return}case`error`:s=d.message,this.#pt();return;case`ignore`:return}}).promise}#xe(e){this.#Ie();let t=this.#De();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#pt();let r=this.#ke((t,r)=>{let i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#pt();return;case`repaint`:this.#pt();return;case`submit`:n!==void 0&&r(e.actions[n].value);return;case void 0:return}},()=>{t.status=void 0});return{choice:r.promise,close:()=>r.settle(void 0)}}async#Se(e){let t=this.#Ee(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#R,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#Ge():(i=lineOf(``),this.#Ke())};return syncEditableRow(),this.#pt(),await this.#ke((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#qe(),this.#pt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#pt()},submit=()=>{let t=selectValueAtCursor([...e.options],r.cursor);if(t===void 0)return;if(t!==e.editable.value){n({kind:`selected`,value:t});return}let o=(i.text||e.editable.defaultValue).trim(),s=e.editable.validate?.(o);if(s!==void 0){a=s,this.#pt();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#pt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ke()).promise}async#Ce(e){let t=this.#Ee(),n=initialProviderPickerState(e.options,e.initialValue),r;t.question=t=>renderSelectQuestion({kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#R,editor:{kind:`key`,phase:n.phase}}},this.#r,t);let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#Ge():this.#Ke()};return syncCaret(),this.#pt(),await this.#ke((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#pt();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#pt();return;case`validate`:{n=o.state,syncCaret(),this.#pt();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#pt();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#qe(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Ke()}).promise}async#we(e){let t=this.#Ee(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder!==void 0&&(i.placeholder=e.placeholder),e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#r,t,this.#R)},this.#Ge(),this.#pt(),await this.#ke((t,i)=>{let apply=e=>{n=e,r=void 0,this.#qe(),this.#pt()},a=applyLineEditorKey(n,t);if(a!==void 0){apply(a);return}switch(t.type){case`ctrl-c`:case`escape`:i(void 0);return;case`ctrl-r`:this.#pt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#pt();return}i(t);return}default:return}},()=>this.#Ke()).promise}async#Te(e){let t=this.#Ee();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#pt(),await this.#ke((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#pt();return;default:return}}).promise}#Ee(){return this.#Ie(),this.#j=!1,this.#N={kind:`idle`},this.#P=``,this.#De()}#De(){return this.#de===void 0&&(this.#de={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[]}),this.#de}#Oe(){this.#de!==void 0&&(this.#de.question=void 0,this.#de.hideLinesWhileQuestion=!1),this.#W=void 0,this.#ze(),this.#je(),this.#pt()}#ke(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Oe(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Oe(),i(e))};return this.#W=t=>e(t,settle,reject),this.#Re(),{promise:a,settle}}#Ae(){let e,t=new Promise(t=>{e=t});return this.#pe=e,this.#je(),{promise:t,dispose:()=>{this.#pe===e&&(this.#pe=void 0,this.#Me())}}}#je(){if(this.#pe===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#pe;this.#pe=void 0,this.#Me(),e?.();return}e.type===`ctrl-r`&&this.#pt()};this.#me=consumer,this.#W=consumer,this.#Re()}#Me(){this.#me!==void 0&&(this.#W===this.#me&&this.#ze(),this.#me=void 0)}#Ne(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#de!==void 0){this.#de.status=t,t===void 0&&(this.#de.preview=void 0),this.#pt();return}if(t===void 0){this.#N={kind:`idle`},this.#P=``,this.#Xe(),this.#pt();return}this.#Ie(),this.#Ye(),this.#P=t,this.#pt()}#Pe(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#de;if(r!==void 0){if(r.preview=void 0,t===`warning`||t===`error`)for(let e of r.outputBuffer)r.lines.push({text:e,tone:`info`,evidence:!0});r.outputBuffer=[],r.lines.push({text:n,tone:t}),this.#pt();return}this.#Ie(),this.#Ze({kind:`flow`,title:t,body:n,live:!1}),this.#pt()}#Fe(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#de;if(n===void 0){this.#Pe(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#pt()}shutdown(){this.#Le()}#Ie(e){this.#F=e?.title??this.#F,this.#ee=e?.contextSize??this.#l,!this.#I&&(this.#I=!0,this.#n.reset(),this.#n.hideCursor(),this.#kt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#J=()=>this.#pt(),this.#t.on(`resize`,this.#J))}#Le(){this.#ze(),this.#Ke(),this.#Xe(),this.#H!==void 0&&(clearTimeout(this.#H),this.#H=void 0),this.#U=!1,this.#I&&=(this.#Lt(),this.#pt(),this.#n.clear(),this.#n.showCursor(),this.#At(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#J&&=(this.#t.off(`resize`,this.#J),void 0),!1)}#Re(){this.#e.off(`data`,this.#Be),this.#e.on(`data`,this.#Be)}#ze(){this.#e.off(`data`,this.#Be),this.#Ue(),this.#G=``,this.#K=new StringDecoder(`utf8`),this.#W=void 0}#Be=e=>{this.#Ue(),this.#G+=this.#K.write(e),this.#He(),this.#Ve()};#Ve(){if(this.#G===`\x1B`){this.#q=setTimeout(()=>{this.#G===`\x1B`&&(this.#G=``,this.#W?.({type:`escape`}))},30),this.#q.unref?.();return}if(isIncompletePaste(this.#G)){let e=this.#G;this.#q=setTimeout(()=>{if(this.#G!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#G=``,t.length>0&&this.#W?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#q.unref?.()}}#He(){for(;this.#G.length>0;){let e=nextKey(this.#G);if(e.incomplete)return;this.#G=this.#G.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#W?.(e.key)}}#Ue(){this.#q&&=(clearTimeout(this.#q),void 0)}#We(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#pt();break;case`ctrl-c`:this.#L||(this.#L=!0,this.#N={kind:`idle`},this.#P=`Interrupted`,this.#Y?.(),this.#pt());break;default:break}}#Ge(){this.#Ke(),this.#qe(),this.#B=setInterval(()=>{this.#R=!this.#R,this.#pt()},500),this.#B.unref?.()}#Ke(){this.#B&&=(clearInterval(this.#B),void 0),this.#R=!0}#qe(){this.#R=!0}#Je(){this.#Xe(),this.#V=setInterval(()=>{this.#z+=1,this.#pt()},90),this.#V.unref?.()}#Ye(){this.#N={kind:`waiting`,startedAtMs:Date.now()},this.#Je()}#Xe(){this.#V&&=(clearInterval(this.#V),void 0)}#Ze(e){e.id!==this.#ce?.id&&this.#Lt(),this.#p.push(e),e.id&&this.#m.set(e.id,e)}#Qe(e){this.#Ze({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#pt()}#$e(e){if(e!=null){if(this.#ue===e){this.#ue=void 0;return}this.#Ze({kind:`user`,body:stripTerminalControls(e),live:!1})}}#et(e,t,n){let r={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};n!==void 0&&(r.detail=stripTerminalControls(n)),this.#Ze(r),this.#pt()}#tt(e,t){this.#y.has(e)||(this.#y.add(e),this.#Ze({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#nt(e){if(e.id&&this.#h.has(e.id))return;let t=e.id?this.#m.get(e.id):void 0;if(t){Object.assign(t,e);return}this.#Ze(e)}#rt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#it(){for(let e of this.#p)e.status===`approval`||e.status===`running`||(e.live=!1)}#at(e,t,n){switch(e.type){case`step-start`:this.#ot(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#ft(e.usage),this.#pt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);this.#st(t),this.#ot(STATUS.streaming),n.text.set(e.id,t),this.#ct(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;this.#st(r),n.text.set(e.id,r),this.#ct(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);this.#st(r),this.#ot(STATUS.streaming),n.reasoning.set(e.id,r),this.#lt(e.id,r,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#st(r),this.#lt(e.id,r,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#ot(STATUS.executingTools),this.#ut({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;this.#ut({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#dt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#ot(STATUS.toolResults),this.#ut({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{if(t.tools===`hidden`)break;let r=this.#dt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#ot(STATUS.toolResults),this.#ut({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#et(`Error`,e.errorText,e.detail);break;case`finish`:this.#ft(e.usage),this.#pt();break}}#ot(e){let t=this.#T>0?STATUS.connectionAuth:e;this.#P!==t&&(this.#P=t,this.#pt())}#st(e){e.trim().length>0&&(this.#N={kind:`answering`})}#ct(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#nt({id:e,kind:`assistant`,body:r,live:n}),this.#pt())}#lt(e,t,n,r){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#nt({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#pt())}#ut(e,t,n){if(n.tools.set(e.toolCallId,e),this.#_.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#v.set(e.toolCallId,r),this.#nt(renderNativeToolBlock(e,r,t.tools===`full`)),this.#pt()}#dt(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#v.get(e)??toolSectionId(e),i=this.#m.get(r);if(!(i===void 0||i.kind!==`tool`))return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.title??`tool`}}#ft(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#Q=(t??0)+(n??0)),this.#$=t??this.#$,this.#te=n??this.#te,this.#te!=null&&this.#re!==void 0){let e=(Date.now()-this.#re)/1e3;e>0&&(this.#ne=this.#te/e)}}#pt(){if(this.#I){if(this.#X){this.#Z=!0;return}this.#X=!0;try{do this.#Z=!1,this.#mt();while(this.#Z)}finally{this.#X=!1}}}#mt(){if(!this.#I)return;let e=this.#Dt(),t=this.#Ct(e),n=Math.max(1,this.#Ot()-t.length),r=[],i=this.#w;for(;this.#p.length>0&&this.#p[0].live===!1;){let t=this.#p.shift();if(this.#g.push(t),t.id&&(this.#h.add(t.id),this.#m.delete(t.id)),this.#zt(t))continue;let n=this.#yt(t,e,i);i=previousBlockOf(t),this.#w=i,r.push(...n),this.#C.push(...n)}let a=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#yt(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)a.push({block:t,row:n[e]})}let o=[...clipLiveRows(a.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,o):this.#n.update(o)}#ht(){if(!this.#I)return;let e=this.#Dt(),t=this.#Ct(e),n=Math.max(1,this.#Ot()-t.length),r=this.#w,i=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#yt(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#r),...t];this.#n.clearAll(),this.#n.flush([...this.#vt(),...this.#C],a)}logDisplayMode(){return this.#f}setLogDisplayMode(e){e!==this.#f&&(this.#f=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#_t(),this.#I&&this.#ht())}flushDelayedDevBuildErrors(){let e=this.#se;e!==void 0&&(this.#se=void 0,this.#Ze({kind:`log`,title:`stderr`,body:e,live:!1}),this.#pt())}#gt(){this.#U=!0,this.#H!==void 0&&clearTimeout(this.#H),this.#H=setTimeout(()=>{this.#U=!1,this.#H=void 0,this.#pt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#f)),this.#pt()}#_t(){let e=this.#Dt();this.#C.length=0;let t;for(let n of this.#g){if(this.#zt(n))continue;let r=this.#yt(n,e,t);t=previousBlockOf(n),this.#C.push(...r)}this.#w=t}#vt(){let e=this.#b;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#Dt()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#yt(e,t,n){let r={spinner:this.#bt()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#bt(){return this.#r.spinner[this.#z%this.#r.spinner.length]??``}#xt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#St(e){return e.indicator.kind===`spinner`?{glyph:this.#bt(),color:`yellow`}:{glyph:this.#xt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:`green`}}#Ct(e){let t=this.#r.colors,n=[``],r=this.#de;if(r!==void 0){let t=this.#St(r),i;if(r.question!==void 0){let n=r.question(e);i={kind:`question`,rows:n},r.status!==void 0&&(i={kind:`question`,rows:n,status:{text:r.status,indicator:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(i={kind:`status`,status:{text:r.status,indicator:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,indicator:t},preview:r.preview}));let a={title:r.title,lines:r.hideLinesWhileQuestion===!0?[]:r.lines,content:i};return n.push(...renderFlowPanel(a,this.#r,e)),this.#Tt(n,e),n}if(this.#fe!==void 0&&n.push(...renderAttentionRows(this.#fe,e,this.#r),``),this.#j){let r=this.#M===void 0?void 0:inlineCommandHint(this.#M);r===void 0&&this.#M!==void 0&&isTypeaheadOpen(this.#M)&&n.push(...renderCommandSuggestions(this.#M,this.#r,e));let i=isPromptControlCommand(this.#O),a=r?t.dim(` ${r}`):``,o=[];this.#wt(o,e);let s=Math.max(1,this.#Ot()-1-n.length-1-o.length);return n.push(...promptInputRows({text:this.#O,cursor:this.#k,width:e,theme:this.#r,caretVisible:this.#R,isCommand:i,ghost:a,maxRows:s})),n.push(...o),n}let i=this.#N;if(i.kind===`answering`)return this.#wt(n,e),n;let a=i.kind===`waiting`,o=a?t.green(this.#xt(i.startedAtMs,this.#r.unicode?`⊙`:`o`)):t.dim(this.#r.glyph.dot),s=this.#P.length>0?this.#P:`Ready`,c=a?t.dim(s):s,u=this.#Et(),f=a?` `:``,p=u?`${f}${o} ${c} ${t.dim(this.#r.glyph.dot)} ${u}`:`${f}${o} ${c}`;n.push(clip(p,e));let g=[];return this.#wt(g,e),a&&g.length>0&&n.push(``),n.push(...g),n}#wt(e,t){let n=this.#D===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#r,width:r};this.#U&&(i.logLevel=this.#f);let a=this.#b?.serverUrl;if(a!==void 0&&this.#D===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#b?.info?.agent.model.id;o!==void 0&&(i.model=o);let s=this.#b?.info?.agent.model.endpoint;s!==void 0&&(i.endpoint=s);let c=this.#$??0,l=this.#te??0;if(c>0||l>0){let e={inputTokens:c,outputTokens:l};this.#ee!==void 0&&(e.contextSize=this.#ee),i.tokens=formatTokenFlow(e,this.#r.glyph)}this.#E!==void 0&&(i.vercel=this.#E),this.#D!==void 0&&(i.remote=this.#D);let u=buildStatusLine(i);u!==void 0&&e.push(clip(`${n}${u}`,t))}#Tt(e,t){if(this.#D===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#D,theme:this.#r,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Et(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Q,outputTokens:this.#te,tokensPerSecond:this.#ne},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#Dt(){return Math.max(20,this.#t.columns||80)}#Ot(){return Math.max(8,this.#t.rows||24)}#kt(){if(this.#ie!==void 0||!this.#u)return;this.#ae=``,this.#oe=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#jt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ie=()=>{e(),t()}}#At(){let e=this.#ie;e!==void 0&&(this.#ie=void 0,e(),this.#ae.length>0&&(this.#Rt(`stdout`)&&process.stdout.write(`${this.#ae}\n`),this.#ae=``),this.#oe.length>0&&(this.#Rt(`stderr`)&&process.stderr.write(`${this.#oe}\n`),this.#oe=``))}#jt(e,t){let n=(e===`stdout`?this.#ae:this.#oe)+t,i=n.lastIndexOf(`
4
4
  `),a=i===-1?n:n.slice(i+1);if(e===`stdout`?this.#ae=a:this.#oe=a,i===-1)return;let o=stripAnsi(n.slice(0,i)).replace(/\s+$/u,``);o.trim().length!==0&&(e===`stdout`?this.#Mt(o):this.#Nt(o),this.#pt())}#Mt(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
5
5
  `);t=[],e.trim().length!==0&&this.#Ze({kind:`log`,title:`stdout`,body:e,live:!1})};for(let n of e.split(`
6
6
  `)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#Ze({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#Ft(r,n.trimEnd())}flushPending()}#Nt(e){let t=e.split(`
@@ -36,11 +36,11 @@ export interface VercelStatusTrackerOptions {
36
36
  * which hides the segment.
37
37
  */
38
38
  export interface VercelStatusTracker {
39
- /** Fire-and-forget identity re-probe; stale resolutions are discarded. */
39
+ /** Fire-and-forget identity re-probe; superseded probes are aborted. */
40
40
  refreshIdentity(): void;
41
41
  applyEffect(effect: VercelStatusEffect): void;
42
42
  current(): VercelStatusSnapshot;
43
- /** Stops future onChange emissions; in-flight probe results are dropped. */
43
+ /** Stops future changes and aborts the in-flight identity probe. */
44
44
  dispose(): void;
45
45
  }
46
46
  /** Creates the {@link VercelStatusTracker} for one dev TUI session. */
@@ -1 +1 @@
1
- import{detectProjectIdentity}from"#setup/project-resolution.js";function createVercelStatusTracker(t){let n=t.detectIdentity??detectProjectIdentity,r,i=!1,a=0,o=!1,snapshot=()=>{let e={pendingDeploy:i};return r!==void 0&&(e.identity=r),e},emit=()=>{o||t.onChange(snapshot())},refreshIdentity=()=>{a+=1;let e=a;(async()=>{let i;try{i=await n(t.appRoot)}catch{return}o||e!==a||(r=i,emit())})()};return{refreshIdentity,applyEffect(e){switch(e.kind){case`channels-added`:i=!0,emit();return;case`deployed`:i=!1,emit(),refreshIdentity();return;case`refresh-identity`:refreshIdentity();return}},current:snapshot,dispose(){o=!0,a+=1}}}export{createVercelStatusTracker};
1
+ import{detectProjectIdentity}from"#setup/project-resolution.js";function createVercelStatusTracker(t){let n=t.detectIdentity??detectProjectIdentity,r,i=!1,a=0,o=!1,s,snapshot=()=>{let e={pendingDeploy:i};return r!==void 0&&(e.identity=r),e},emit=()=>{o||t.onChange(snapshot())},refreshIdentity=()=>{if(o)return;s?.abort();let e=new AbortController;s=e,a+=1;let i=a;(async()=>{let c;try{c=await n(t.appRoot,{signal:e.signal})}catch{return}finally{s===e&&(s=void 0)}o||i!==a||(r=c,emit())})()};return{refreshIdentity,applyEffect(e){if(!o)switch(e.kind){case`channels-added`:i=!0,emit();return;case`deployed`:i=!1,emit(),refreshIdentity();return;case`refresh-identity`:refreshIdentity();return}},current:snapshot,dispose(){o||(o=!0,a+=1,s?.abort(),s=void 0)}}}export{createVercelStatusTracker};
@@ -1,5 +1,5 @@
1
1
  import type { RunDevelopmentTuiInput } from "#cli/dev/tui/tui.js";
2
- import type { DevelopmentServerHandle, DevelopmentServerOptions, ProductionServerHandle } from "#internal/nitro/host/types.js";
2
+ import type { DevelopmentServer, DevelopmentServerOptions, ProductionServerHandle } from "#internal/nitro/host/types.js";
3
3
  import type { AssistantResponseStatsMode, LogDisplayMode, TerminalPartDisplayMode, TuiDisplayOptions } from "#cli/dev/tui/types.js";
4
4
  interface CliLogger {
5
5
  error(message: string): void;
@@ -28,7 +28,7 @@ interface CliRuntimeDependencies {
28
28
  }): Promise<void>;
29
29
  runDevelopmentTui(input: RunDevelopmentTuiInput): Promise<void>;
30
30
  runEvalCommand(evalIds: readonly string[], options: EvalCliOptions, logger: CliLogger): Promise<void>;
31
- startHost(appRoot: string, options?: DevelopmentServerOptions): Promise<DevelopmentServerHandle>;
31
+ startHost(appRoot: string, options?: DevelopmentServerOptions): DevelopmentServer;
32
32
  startProductionHost(appRoot: string, options?: {
33
33
  host?: string;
34
34
  port?: number;
@@ -1,3 +1,3 @@
1
- import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{isCodingAgentLaunch}from"#cli/agent-detection.js";import{eveCliBanner}from"#cli/banner.js";import{startCliLiveRow}from"#cli/ui/live-row.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{Command,CommanderError,InvalidArgumentError}from"#compiled/commander/index.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{registerProjectCommands}from"#cli/commands/register-project-commands.js";import{LOG_DISPLAY_MODES,parseLogDisplayMode}from"#cli/dev/tui/log-display-mode.js";import{resolveTuiTitle}from"#cli/dev/tui/target.js";import{parseDevelopmentServerUrl}from"#cli/dev/url.js";const devBootLog=createLogger(`dev.boot`);function createDevBootProgressReporter(e){return t=>{switch(t.type){case`phase-started`:e?.update(`Building your agent`,t.phase),devBootLog.debug(t.phase);return;case`phase-finished`:devBootLog.debug(`${t.phase} finished`,{ms:t.elapsedMs});return;case`before-first-paint`:e?.stop();return;default:return t}}}async function loadBuildHost(){return(await import(`#internal/nitro/host.js`)).buildApplication}async function loadPrintApplicationInfo(){return(await import(`#cli/commands/info.js`)).printApplicationInfo}async function loadRunDevelopmentTui(){return(await import(`#cli/dev/tui/tui.js`)).runDevelopmentTui}async function loadRunEvalCommand(){return(await import(`#evals/cli/eval.js`)).runEvalCommand}async function loadStartHost(){return(await import(`#internal/nitro/host.js`)).startDevelopmentServer}async function loadStartProductionHost(){return(await import(`#internal/nitro/host.js`)).startProductionServer}function shouldPrintCliBootBanner(e){return e.name()===`info`||e.name()===`dev`||e.name()===`init`}async function waitForShutdownSignal(e){await new Promise((t,n)=>{let r=!1,cleanup=()=>{process.off(`SIGINT`,handleSignal),process.off(`SIGTERM`,handleSignal)},handleSignal=()=>{r||(r=!0,cleanup(),e.close().then(t,n))};process.once(`SIGINT`,handleSignal),process.once(`SIGTERM`,handleSignal)})}async function waitForProductionServer(e){await Promise.race([e.wait(),waitForShutdownSignal({close:()=>e.close()})])}function parsePortOption(e){if(!/^-?\d+$/.test(e))throw new InvalidArgumentError(`Expected a numeric port, received "${e}".`);let t=Number(e);if(t<0||t>65535)throw new InvalidArgumentError(`Expected a port between 0 and 65535, received "${e}".`);return t}const DISPLAY_MODES=new Set([`full`,`collapsed`,`auto-collapsed`,`hidden`]),STATS_MODES=new Set([`tokens`,`tokensPerSecond`]);function parseDisplayMode(e){if(!DISPLAY_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...DISPLAY_MODES].join(`, `)}, received "${e}".`);return e}function parseStatsMode(e){if(!STATS_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...STATS_MODES].join(`, `)}, received "${e}".`);return e}function parseLogsMode(e){let t=parseLogDisplayMode(e);if(t===void 0)throw new InvalidArgumentError(`Expected one of ${LOG_DISPLAY_MODES.join(`, `)}, received "${e}".`);return t}function parseContextSizeOption(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new InvalidArgumentError(`Expected a positive number, received "${e}".`);return t}function resolveDevUiMode(e){return e.options.ui===!1||!e.interactive?`headless`:`tui`}function resolveTuiDisplayOptions(e){let t={logs:e.logs??`stderr`,reasoning:e.reasoning??`full`,tools:e.tools??`auto-collapsed`};return e.subagents!==void 0&&(t.subagents=e.subagents),e.connectionAuth!==void 0&&(t.connectionAuth=e.connectionAuth),e.assistantResponseStats!==void 0&&(t.assistantResponseStats=e.assistantResponseStats),e.contextSize!==void 0&&(t.contextSize=e.contextSize),t}function hasInteractiveTerminal(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function rewriteDevelopmentUrlShorthand(e){let t=e[1];return e[0]!==`dev`||e.length!==2||t===void 0||t.startsWith(`-`)?[...e]:[`dev`,`--url`,t]}function resolveRemoteDevelopmentServerUrl(e){if(e.url){if(e.host!==void 0)throw new InvalidArgumentError(`The --host option cannot be used with --url.`);if(e.port!==void 0)throw new InvalidArgumentError(`The --port option cannot be used with --url.`);if(e.ui===!1)throw new InvalidArgumentError(`The --no-ui option cannot be used with --url.`);return e.url}}function createCliProgram(e,i){let c=resolveApplicationRoot(),f=resolveInstalledPackageInfo().version,p=new Command,h=createCliTheme();p.name(`eve`).description(`Build and run an eve application.`).version(f).showHelpAfterError().exitOverride().hook(`preAction`,(t,n)=>{shouldPrintCliBootBanner(n)&&e.log(eveCliBanner())}).configureOutput({writeErr:t=>{e.error(t.trimEnd())},writeOut:t=>{e.log(t.trimEnd())}});let g=p.command(`channels`).description(`Manage user-authored channels in the current project.`);return g.command(`add [kind]`).description(`Add channels interactively, or scaffold a channel kind (slack | web).`).option(`-f, --force`,`Overwrite existing channel files`).option(`-y, --yes`,`Assume yes for confirmations; requires an explicit channel kind`).action(async(t,n)=>{let{runChannelsAddCommand:r}=await import(`#cli/commands/channels.js`);await r(e,c,{kind:t,options:n})}),g.command(`list`).description(`List user-authored channels in the current project.`).option(`--json`,`Output as JSON`).action(async t=>{let{runChannelsListCommand:n}=await import(`#cli/commands/channels.js`);await n(e,c,t)}),p.command(`init [target]`).description(`Create a new eve agent, or add one to an existing project directory.`).option(`--channel-web-nextjs`,`Add the Web Chat application (Next.js)`).action(async(t,n)=>{let{runInitCommand:r}=await import(`#cli/commands/init.js`);await r(e,c,t,n)}),registerProjectCommands({program:p,logger:e,appRoot:c}),p.command(`build`).description(`Build the current eve application.`).action(async()=>{let{loadDevelopmentEnvironmentFiles:t}=await import(`#cli/dev/environment.js`);t(c);let n=await(i.buildHost??await loadBuildHost())(c);e.log(renderCliTaggedLine(h,{message:`built output at ${n}`,tag:`build`,tone:`success`}))}),p.command(`start`).description(`Start a built eve application.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,parsePortOption).action(async t=>{let{loadDevelopmentEnvironmentFiles:n}=await import(`#cli/dev/environment.js`);n(c);let a=await(i.startProductionHost??await loadStartProductionHost())(c,{host:t.host,port:t.port});e.log(renderCliTaggedLine(h,{message:`server listening at ${a.url}`,tag:`start`,tone:`success`})),await waitForProductionServer(a)}),p.command(`dev`).description(`Start the eve development server or connect to an existing URL.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 2000)`,parsePortOption).option(`-u, --url <url>`,`Connect to an existing server URL`,parseDevelopmentServerUrl).option(`--no-ui`,`Start the server without an interactive UI`).option(`--name <name>`,`Title shown in the terminal UI (defaults to the app folder name)`).option(`--input <text>`,`Pre-fill the prompt input after launching the UI`).option(`--tools <mode>`,`How tool calls render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--reasoning <mode>`,`How reasoning renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--subagents <mode>`,`How subagent sections render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--connection-auth <mode>`,`How connection authorization renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--assistant-response-stats <mode>`,`Assistant header statistic: tokens | tokensPerSecond`,parseStatsMode).option(`--context-size <tokens>`,`Model context window size, shown as a usage percentage`,parseContextSizeOption).option(`--logs <mode>`,`Which server/agent logs to show: all | stderr | sandbox | none`,parseLogsMode).addHelpText(`after`,`
1
+ import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{isCodingAgentLaunch}from"#cli/agent-detection.js";import{eveCliBanner}from"#cli/banner.js";import{startCliLiveRow}from"#cli/ui/live-row.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{Command,CommanderError,InvalidArgumentError}from"#compiled/commander/index.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{registerProjectCommands}from"#cli/commands/register-project-commands.js";import{LOG_DISPLAY_MODES,parseLogDisplayMode}from"#cli/dev/tui/log-display-mode.js";import{resolveTuiTitle}from"#cli/dev/tui/target.js";import{parseDevelopmentServerUrl}from"#cli/dev/url.js";const devBootLog=createLogger(`dev.boot`);function createDevBootProgressReporter(e){return t=>{switch(t.type){case`phase-started`:e?.update(`Building your agent`,t.phase),devBootLog.debug(t.phase);return;case`phase-finished`:devBootLog.debug(`${t.phase} finished`,{ms:t.elapsedMs});return;case`before-first-paint`:e?.stop();return;default:return t}}}async function loadBuildHost(){return(await import(`#internal/nitro/host.js`)).buildApplication}async function loadPrintApplicationInfo(){return(await import(`#cli/commands/info.js`)).printApplicationInfo}async function loadRunDevelopmentTui(){return(await import(`#cli/dev/tui/tui.js`)).runDevelopmentTui}async function loadRunEvalCommand(){return(await import(`#evals/cli/eval.js`)).runEvalCommand}async function loadStartHost(){return(await import(`#internal/nitro/host.js`)).createDevelopmentServer}async function loadStartProductionHost(){return(await import(`#internal/nitro/host.js`)).startProductionServer}function shouldPrintCliBootBanner(e){return e.name()===`info`||e.name()===`dev`||e.name()===`init`}async function waitForShutdownSignal(e){await new Promise((t,n)=>{let r=!1,cleanup=()=>{process.off(`SIGINT`,handleSignal),process.off(`SIGTERM`,handleSignal)},handleSignal=()=>{r||(r=!0,cleanup(),e.close().then(t,n))};process.once(`SIGINT`,handleSignal),process.once(`SIGTERM`,handleSignal)})}async function waitForProductionServer(e){await Promise.race([e.wait(),waitForShutdownSignal({close:()=>e.close()})])}function parsePortOption(e){if(!/^-?\d+$/.test(e))throw new InvalidArgumentError(`Expected a numeric port, received "${e}".`);let t=Number(e);if(t<0||t>65535)throw new InvalidArgumentError(`Expected a port between 0 and 65535, received "${e}".`);return t}const DISPLAY_MODES=new Set([`full`,`collapsed`,`auto-collapsed`,`hidden`]),STATS_MODES=new Set([`tokens`,`tokensPerSecond`]);function parseDisplayMode(e){if(!DISPLAY_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...DISPLAY_MODES].join(`, `)}, received "${e}".`);return e}function parseStatsMode(e){if(!STATS_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...STATS_MODES].join(`, `)}, received "${e}".`);return e}function parseLogsMode(e){let t=parseLogDisplayMode(e);if(t===void 0)throw new InvalidArgumentError(`Expected one of ${LOG_DISPLAY_MODES.join(`, `)}, received "${e}".`);return t}function parseContextSizeOption(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new InvalidArgumentError(`Expected a positive number, received "${e}".`);return t}function resolveDevUiMode(e){return e.options.ui===!1||!e.interactive?`headless`:`tui`}function resolveTuiDisplayOptions(e){let t={logs:e.logs??`stderr`,reasoning:e.reasoning??`full`,tools:e.tools??`auto-collapsed`};return e.subagents!==void 0&&(t.subagents=e.subagents),e.connectionAuth!==void 0&&(t.connectionAuth=e.connectionAuth),e.assistantResponseStats!==void 0&&(t.assistantResponseStats=e.assistantResponseStats),e.contextSize!==void 0&&(t.contextSize=e.contextSize),t}function hasInteractiveTerminal(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function rewriteDevelopmentUrlShorthand(e){let t=e[1];return e[0]!==`dev`||e.length!==2||t===void 0||t.startsWith(`-`)?[...e]:[`dev`,`--url`,t]}function resolveRemoteDevelopmentServerUrl(e){if(e.url){if(e.host!==void 0)throw new InvalidArgumentError(`The --host option cannot be used with --url.`);if(e.port!==void 0)throw new InvalidArgumentError(`The --port option cannot be used with --url.`);if(e.ui===!1)throw new InvalidArgumentError(`The --no-ui option cannot be used with --url.`);return e.url}}function createCliProgram(e,i){let c=resolveApplicationRoot(),f=resolveInstalledPackageInfo().version,p=new Command,m=createCliTheme();p.name(`eve`).description(`Build and run an eve application.`).version(f).showHelpAfterError().exitOverride().hook(`preAction`,(t,n)=>{shouldPrintCliBootBanner(n)&&e.log(eveCliBanner())}).configureOutput({writeErr:t=>{e.error(t.trimEnd())},writeOut:t=>{e.log(t.trimEnd())}});let h=p.command(`channels`).description(`Manage user-authored channels in the current project.`);return h.command(`add [kind]`).description(`Add channels interactively, or scaffold a channel kind (slack | web).`).option(`-f, --force`,`Overwrite existing channel files`).option(`-y, --yes`,`Assume yes for confirmations; requires an explicit channel kind`).action(async(t,n)=>{let{runChannelsAddCommand:r}=await import(`#cli/commands/channels.js`);await r(e,c,{kind:t,options:n})}),h.command(`list`).description(`List user-authored channels in the current project.`).option(`--json`,`Output as JSON`).action(async t=>{let{runChannelsListCommand:n}=await import(`#cli/commands/channels.js`);await n(e,c,t)}),p.command(`init [target]`).description(`Create a new eve agent, or add one to an existing project directory.`).option(`--channel-web-nextjs`,`Add the Web Chat application (Next.js)`).option(`-y, --yes`,`Accepted for compatibility; has no effect`).action(async(t,n)=>{n.yes&&e.error(`warning: --yes has no effect for eve init.`);let{runInitCommand:r}=await import(`#cli/commands/init.js`);await r(e,c,t,{channelWebNextjs:n.channelWebNextjs})}),registerProjectCommands({program:p,logger:e,appRoot:c}),p.command(`build`).description(`Build the current eve application.`).action(async()=>{let{loadDevelopmentEnvironmentFiles:t}=await import(`#cli/dev/environment.js`);t(c);let n=await(i.buildHost??await loadBuildHost())(c);e.log(renderCliTaggedLine(m,{message:`built output at ${n}`,tag:`build`,tone:`success`}))}),p.command(`start`).description(`Start a built eve application.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,parsePortOption).action(async t=>{let{loadDevelopmentEnvironmentFiles:n}=await import(`#cli/dev/environment.js`);n(c);let a=await(i.startProductionHost??await loadStartProductionHost())(c,{host:t.host,port:t.port});e.log(renderCliTaggedLine(m,{message:`server listening at ${a.url}`,tag:`start`,tone:`success`})),await waitForProductionServer(a)}),p.command(`dev`).description(`Start the eve development server or connect to an existing URL.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 2000)`,parsePortOption).option(`-u, --url <url>`,`Connect to an existing server URL`,parseDevelopmentServerUrl).option(`--no-ui`,`Start the server without an interactive UI`).option(`--name <name>`,`Title shown in the terminal UI (defaults to the app folder name)`).option(`--input <text>`,`Pre-fill the prompt input after launching the UI`).option(`--tools <mode>`,`How tool calls render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--reasoning <mode>`,`How reasoning renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--subagents <mode>`,`How subagent sections render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--connection-auth <mode>`,`How connection authorization renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--assistant-response-stats <mode>`,`Assistant header statistic: tokens | tokensPerSecond`,parseStatsMode).option(`--context-size <tokens>`,`Model context window size, shown as a usage percentage`,parseContextSizeOption).option(`--logs <mode>`,`Which server/agent logs to show: all | stderr | sandbox | none`,parseLogsMode).addHelpText(`after`,`
2
2
  You can also pass a bare URL as the only argument, for example: eve dev https://example.com
3
- `).action(async t=>{let n=resolveRemoteDevelopmentServerUrl(t),a=hasInteractiveTerminal(),s=resolveDevUiMode({options:t,interactive:a});if(t.input!==void 0&&s===`headless`)throw new InvalidArgumentError(`--input requires the interactive UI.`);let{loadDevelopmentEnvironmentFiles:u}=await import(`#cli/dev/environment.js`);u(c);let runInteractiveUi=async(e,r)=>{let a=await devBootPhase(`loading interactive UI`,async()=>i.runDevelopmentTui??await loadRunDevelopmentTui(),r),o=resolveTuiDisplayOptions(t),s=n===void 0?{kind:`local`,serverUrl:e,workspaceRoot:c}:{kind:`remote`,serverUrl:e,workspaceRoot:c},l=resolveTuiTitle({name:t.name,target:s});l!==void 0&&(o.name=l),await a({target:s,initialInput:t.input,onBootProgress:r,...o})};if(n){if(e.log(`↗ remote mode targeting ${h.info(new URL(n).host)}`),s===`headless`){e.log(renderCliTaggedLine(h,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`}));return}e.log(``),await runInteractiveUi(n);return}s===`tui`&&e.log(``);let d=s===`tui`?startCliLiveRow(e):void 0,f=createDevBootProgressReporter(d);d?.update(`Building your agent`);let p=!1,m,closeServer=async()=>{p||m===void 0||(p=!0,await m.close())};try{if(m=await(i.startHost??await loadStartHost())(c,{host:t.host,onBootProgress:f,port:t.port}),s!==`tui`&&e.log(renderCliTaggedLine(h,{message:`server listening at ${m.url}`,tag:`dev`,tone:`success`})),s===`headless`)return t.ui!==!1&&!a&&e.log(renderCliTaggedLine(h,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`})),await waitForShutdownSignal({close:closeServer});await runInteractiveUi(m.url,f)}finally{d?.stop(),await closeServer()}}),p.command(`info`).description(`Print resolved application information.`).option(`--json`,`Output as JSON`).action(async t=>{await(i.printApplicationInfo??await loadPrintApplicationInfo())(e,c,t)}),p.command(`eval`).description(`Run evals against an eve agent.`).argument(`[evalIds...]`,`Eval ids (or directory prefixes) to run (all discovered evals when omitted)`).option(`--url <url>`,`Remote agent URL (skip local host startup)`,parseDevelopmentServerUrl).option(`--tag <tag...>`,`Run only evals carrying a tag`).option(`--strict`,`Fail the exit code when any score falls below its threshold`).option(`--list`,`Print discovered evals without running them`).option(`--timeout <ms>`,`Per-eval timeout in milliseconds`).option(`--max-concurrency <n>`,`Max concurrent eval executions`).option(`--json`,`Output results as JSON`).option(`--junit <path>`,`Write JUnit XML results to a file`).option(`--skip-report`,`Skip eval-defined reporters (e.g. Braintrust)`).option(`--verbose`,`Stream per-eval t.log lines to stdout`).action(async(t,n)=>{await(i.runEvalCommand??await loadRunEvalCommand())(t,n,e)}),p}async function runCli(e=process.argv.slice(2),t=console,n={}){let r=createCliProgram(t,n),a=e.length===0?[`dev`]:rewriteDevelopmentUrlShorthand(e);try{await r.parseAsync(a,{from:`user`})}catch(e){if(e instanceof CommanderError){if(e.exitCode===0)return;let r=await(n.isCodingAgentLaunch??isCodingAgentLaunch)();if(a[0]===`init`&&r){let{initAgentInstructions:e}=await import(`#cli/commands/agent-instructions.js`);t.log(e())}throw Error(e.message)}throw e}}export{resolveDevUiMode,resolveTuiDisplayOptions,runCli};
3
+ `).action(async t=>{let n=resolveRemoteDevelopmentServerUrl(t),a=hasInteractiveTerminal(),s=resolveDevUiMode({options:t,interactive:a});if(t.input!==void 0&&s===`headless`)throw new InvalidArgumentError(`--input requires the interactive UI.`);let runInteractiveUi=async(e,r)=>{let a=await devBootPhase(`loading interactive UI`,async()=>i.runDevelopmentTui??await loadRunDevelopmentTui(),r),o=resolveTuiDisplayOptions(t),s=n===void 0?{kind:`local`,serverUrl:e.serverUrl,workspaceRoot:e.appRoot??c}:{kind:`remote`,serverUrl:e.serverUrl,workspaceRoot:c},l=resolveTuiTitle({name:t.name,target:s});l!==void 0&&(o.name=l),await a({target:s,initialInput:t.input,onBootProgress:r,...o})};if(n){let{loadDevelopmentEnvironmentFiles:t}=await import(`#cli/dev/environment.js`);if(t(c),e.log(`↗ remote mode targeting ${m.info(new URL(n).host)}`),s===`headless`){e.log(renderCliTaggedLine(m,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`}));return}e.log(``),await runInteractiveUi({serverUrl:n});return}s===`tui`&&e.log(``);let u=s===`tui`?startCliLiveRow(e):void 0,d=createDevBootProgressReporter(u);u?.update(`Building your agent`);let f=!1,p,closeServer=async()=>{f||p===void 0||(f=!0,await p.close())};try{p=(i.startHost??await loadStartHost())(c,{existing:s===`tui`?`attach-if-unconfigured`:`reject`,host:t.host,onBootProgress:d,port:t.port});let n=await p.start();if(s!==`tui`&&e.log(renderCliTaggedLine(m,{message:`server listening at ${n.url}`,tag:`dev`,tone:`success`})),s===`headless`)return t.ui!==!1&&!a&&e.log(renderCliTaggedLine(m,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`})),await waitForShutdownSignal({close:closeServer});await runInteractiveUi({appRoot:n.appRoot,serverUrl:n.url},d)}finally{u?.stop(),await closeServer()}}),p.command(`info`).description(`Print resolved application information.`).option(`--json`,`Output as JSON`).action(async t=>{await(i.printApplicationInfo??await loadPrintApplicationInfo())(e,c,t)}),p.command(`eval`).description(`Run evals against an eve agent.`).argument(`[evalIds...]`,`Eval ids (or directory prefixes) to run (all discovered evals when omitted)`).option(`--url <url>`,`Remote agent URL (skip local host startup)`,parseDevelopmentServerUrl).option(`--tag <tag...>`,`Run only evals carrying a tag`).option(`--strict`,`Fail the exit code when any score falls below its threshold`).option(`--list`,`Print discovered evals without running them`).option(`--timeout <ms>`,`Per-eval timeout in milliseconds`).option(`--max-concurrency <n>`,`Max concurrent eval executions`).option(`--json`,`Output results as JSON`).option(`--junit <path>`,`Write JUnit XML results to a file`).option(`--skip-report`,`Skip eval-defined reporters (e.g. Braintrust)`).option(`--verbose`,`Stream per-eval t.log lines to stdout`).action(async(t,n)=>{await(i.runEvalCommand??await loadRunEvalCommand())(t,n,e)}),p}async function runCli(e=process.argv.slice(2),t=console,n={}){let r=createCliProgram(t,n),a=e.length===0?[`dev`]:rewriteDevelopmentUrlShorthand(e);try{await r.parseAsync(a,{from:`user`})}catch(e){if(e instanceof CommanderError){if(e.exitCode===0)return;let r=await(n.isCodingAgentLaunch??isCodingAgentLaunch)();if(a[0]===`init`&&r){let{initAgentInstructions:e}=await import(`#cli/commands/agent-instructions.js`);t.log(e())}throw Error(e.message)}throw e}}export{resolveDevUiMode,resolveTuiDisplayOptions,runCli};
@@ -1,4 +1,5 @@
1
1
  import type { AssertionHandle, AssertionResult, AssertionSeverity, EveEvalTaskResult } from "#evals/types.js";
2
+ import type { EveEvalAssertionSubject } from "#evals/assertions/run.js";
2
3
  /**
3
4
  * Outcome of evaluating one assertion: a 0–1 score (boolean assertions use
4
5
  * exactly 0 or 1) with optional human-readable detail and metadata.
@@ -9,13 +10,12 @@ export interface AssertionOutcome {
9
10
  readonly metadata?: Readonly<Record<string, unknown>>;
10
11
  }
11
12
  /**
12
- * A run-level assertion (e.g. `t.completed()`), evaluated lazily against the
13
- * final task result after `test(t)` returns. The evaluation is deferred so
14
- * the assertion always sees the complete run regardless of call order.
13
+ * A scoped assertion evaluated lazily after `test(t)` returns. The selected
14
+ * subject may be the aggregate run, one session, or one immutable turn.
15
15
  */
16
16
  export interface RunAssertion {
17
17
  readonly name: string;
18
- evaluate(result: EveEvalTaskResult): AssertionOutcome | Promise<AssertionOutcome>;
18
+ evaluate(result: EveEvalAssertionSubject): AssertionOutcome | Promise<AssertionOutcome>;
19
19
  }
20
20
  /**
21
21
  * Collects the assertions recorded by an eval's `test(t)`. Run-level
@@ -26,8 +26,10 @@ export interface RunAssertion {
26
26
  */
27
27
  export declare class AssertionCollector {
28
28
  #private;
29
- /** Register a run-level assertion evaluated against the final result. */
30
- recordRun(spec: RunAssertion, severity?: AssertionSeverity): AssertionHandle;
29
+ /** Whether the eval has already recorded an assertion. */
30
+ get hasEntries(): boolean;
31
+ /** Register a deferred assertion against a turn or session scope. */
32
+ recordScoped(spec: RunAssertion, selectSubject: (result: EveEvalTaskResult) => EveEvalAssertionSubject, severity?: AssertionSeverity): AssertionHandle;
31
33
  /** Register a value/judge assertion, evaluating the captured value now. */
32
34
  recordValue(input: {
33
35
  readonly name: string;
@@ -35,6 +37,17 @@ export declare class AssertionCollector {
35
37
  readonly threshold?: number;
36
38
  readonly score: () => Promise<AssertionOutcome>;
37
39
  }): AssertionHandle;
40
+ /** Record an already-computed assertion outcome and return whether it passed. */
41
+ recordOutcome(input: {
42
+ readonly name: string;
43
+ readonly outcome: AssertionOutcome;
44
+ }): boolean;
45
+ /** Record and await a required value assertion, returning whether it passed. */
46
+ recordRequirement(input: {
47
+ readonly name: string;
48
+ readonly threshold?: number;
49
+ readonly score: () => Promise<AssertionOutcome>;
50
+ }): Promise<boolean>;
38
51
  /**
39
52
  * Awaits every pending value/judge assertion, evaluates the deferred
40
53
  * run-level assertions against `result`, and returns the recorded results.
@@ -1 +1 @@
1
- import{toErrorMessage}from"#shared/errors.js";var AssertionCollector=class{#e=[];#t=[];recordRun(e,t=`gate`){let n={name:e.name,severity:t,threshold:void 0,kind:`deferred`,spec:e,score:0,failed:!1};return this.#e.push(n),makeHandle(n,Promise.resolve())}recordValue(t){let n={name:t.name,severity:t.severity,threshold:t.threshold,kind:`resolved`,score:0,failed:!1};this.#e.push(n);let r=t.score().then(e=>{n.score=e.score,n.message=e.message,n.metadata=e.metadata}).catch(t=>{n.score=0,n.severity=`gate`,n.threshold=void 0,n.message=toErrorMessage(t),n.failed=!0});return this.#t.push(r),makeHandle(n,r)}async finalize(e){await Promise.all(this.#t);let t=[];for(let n of this.#e){if(n.kind===`deferred`&&n.spec!==void 0){let t=await n.spec.evaluate(e);n.score=t.score,n.message=t.message,n.metadata=t.metadata}t.push({name:n.name,score:n.score,severity:n.severity,threshold:n.threshold,passed:computePassed(n.severity,n.threshold,n.score,n.failed),message:n.message,metadata:n.metadata})}return t}};function computePassed(e,t,n,r){if(r)return!1;let i=t??(e===`gate`?1:void 0);return i===void 0||n>=i}function makeHandle(e,t){let n={gate(t){return e.severity=`gate`,e.threshold=t,n},soft(t){return e.severity=`soft`,e.threshold=t,n},atLeast(t){return e.severity=`soft`,e.threshold=t,n},then(e,n){return t.then(e,n)}};return n}export{AssertionCollector};
1
+ import{toErrorMessage}from"#shared/errors.js";var AssertionCollector=class{#e=[];#t=[];get hasEntries(){return this.#e.length>0}recordScoped(e,t,n=`gate`){let r={name:e.name,severity:n,threshold:void 0,kind:`deferred`,spec:e,selectSubject:t,score:0,failed:!1};return this.#e.push(r),makeHandle(r)}recordValue(e){let t={name:e.name,severity:e.severity,threshold:e.threshold,kind:`resolved`,score:0,failed:!1};this.#e.push(t);let n=settleEntry(t,e.score);return this.#t.push(n),makeHandle(t)}recordOutcome(e){let t={name:e.name,severity:`gate`,threshold:void 0,kind:`resolved`,score:e.outcome.score,message:e.outcome.message,metadata:e.outcome.metadata,failed:!1};return this.#e.push(t),computePassed(t.severity,t.threshold,t.score,t.failed)}async recordRequirement(e){let t={name:e.name,severity:`gate`,threshold:e.threshold,kind:`resolved`,score:0,failed:!1};return this.#e.push(t),await settleEntry(t,e.score),computePassed(t.severity,t.threshold,t.score,t.failed)}async finalize(e){await Promise.all(this.#t);let t=[];for(let n of this.#e){if(n.kind===`deferred`&&n.spec!==void 0){let t=await n.spec.evaluate(n.selectSubject?.(e)??e);n.score=t.score,n.message=t.message,n.metadata=t.metadata}t.push({name:n.name,score:n.score,severity:n.severity,threshold:n.threshold,passed:computePassed(n.severity,n.threshold,n.score,n.failed),message:n.message,metadata:n.metadata})}return t}};function computePassed(e,t,n,r){if(r)return!1;let i=t??(e===`gate`?1:void 0);return i===void 0||n>=i}async function settleEntry(t,n){try{let e=await n();t.score=e.score,t.message=e.message,t.metadata=e.metadata}catch(n){t.score=0,t.severity=`gate`,t.threshold=void 0,t.message=toErrorMessage(n),t.failed=!0}}function makeHandle(e){let t={gate(n){return e.severity=`gate`,e.threshold=n,t},soft(n){return e.severity=`soft`,e.threshold=n,t},atLeast(n){return e.severity=`soft`,e.threshold=n,t}};return t}export{AssertionCollector};