eve 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +14 -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/terminal-renderer.js +1 -1
  7. package/dist/src/evals/assertions/collector.d.ts +19 -6
  8. package/dist/src/evals/assertions/collector.js +1 -1
  9. package/dist/src/evals/assertions/run.d.ts +24 -17
  10. package/dist/src/evals/assertions/run.js +2 -2
  11. package/dist/src/evals/assertions/scoped.d.ts +17 -0
  12. package/dist/src/evals/assertions/scoped.js +1 -0
  13. package/dist/src/evals/context.d.ts +1 -0
  14. package/dist/src/evals/context.js +1 -1
  15. package/dist/src/evals/control-flow.d.ts +9 -0
  16. package/dist/src/evals/control-flow.js +1 -0
  17. package/dist/src/evals/define-eval.d.ts +1 -1
  18. package/dist/src/evals/define-eval.js +1 -1
  19. package/dist/src/evals/expect/index.d.ts +5 -3
  20. package/dist/src/evals/expect/index.js +1 -1
  21. package/dist/src/evals/index.d.ts +2 -2
  22. package/dist/src/evals/match.d.ts +50 -13
  23. package/dist/src/evals/match.js +1 -1
  24. package/dist/src/evals/runner/artifacts.js +1 -1
  25. package/dist/src/evals/runner/derive-run-facts.js +1 -1
  26. package/dist/src/evals/runner/execute-eval.js +1 -1
  27. package/dist/src/evals/runner/execute-task.d.ts +1 -0
  28. package/dist/src/evals/runner/execute-task.js +1 -1
  29. package/dist/src/evals/runner/reporters/braintrust.js +1 -1
  30. package/dist/src/evals/runner/reporters/console.js +1 -1
  31. package/dist/src/evals/runner/reporters/junit.js +3 -2
  32. package/dist/src/evals/runner/run-evals.js +1 -1
  33. package/dist/src/evals/runner/verdict.d.ts +1 -0
  34. package/dist/src/evals/runner/verdict.js +1 -1
  35. package/dist/src/evals/session.d.ts +9 -5
  36. package/dist/src/evals/session.js +1 -1
  37. package/dist/src/evals/types.d.ts +69 -47
  38. package/dist/src/harness/emission.d.ts +13 -27
  39. package/dist/src/harness/emission.js +1 -1
  40. package/dist/src/harness/step-hooks.d.ts +3 -3
  41. package/dist/src/harness/step-hooks.js +1 -1
  42. package/dist/src/harness/tool-loop.js +1 -1
  43. package/dist/src/internal/application/compiled-artifacts.js +1 -1
  44. package/dist/src/internal/application/package.d.ts +12 -0
  45. package/dist/src/internal/application/package.js +1 -1
  46. package/dist/src/internal/application/paths.d.ts +6 -0
  47. package/dist/src/internal/application/paths.js +1 -1
  48. package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
  49. package/dist/src/internal/workflow/configure-world.d.ts +6 -0
  50. package/dist/src/internal/workflow/configure-world.js +1 -1
  51. package/dist/src/internal/workflow/world-compatibility.d.ts +32 -0
  52. package/dist/src/internal/workflow/world-compatibility.js +1 -0
  53. package/dist/src/protocol/message.d.ts +7 -5
  54. package/dist/src/runtime/actions/types.d.ts +10 -11
  55. package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
  56. package/dist/src/setup/scaffold/create/project.js +1 -1
  57. package/docs/agent-config.md +13 -3
  58. package/docs/concepts/execution-model-and-durability.md +1 -1
  59. package/docs/concepts/sessions-runs-and-streaming.md +1 -1
  60. package/docs/connections/overview.mdx +40 -2
  61. package/docs/evals/assertions.mdx +97 -39
  62. package/docs/evals/cases.mdx +24 -15
  63. package/docs/evals/judge.mdx +2 -2
  64. package/docs/evals/overview.mdx +7 -5
  65. package/docs/evals/reporters.mdx +2 -2
  66. package/docs/evals/running.mdx +3 -1
  67. package/docs/evals/targets.mdx +2 -2
  68. package/docs/guides/auth-and-route-protection.md +48 -1
  69. package/docs/guides/client/streaming.mdx +1 -1
  70. package/docs/guides/deployment.md +3 -2
  71. package/docs/tutorial/connect-a-warehouse.mdx +2 -0
  72. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # eve
2
2
 
3
+ ## 0.15.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 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.
8
+
9
+ ### Patch Changes
10
+
11
+ - f618bef: New Vercel project names now show the suggested name as a placeholder, so typing replaces it instead of editing a prefilled value.
12
+ - 194a8bb: Make `isChannel` recognize authored channel imports evaluated in a different local runtime bundle from the route instance.
13
+ - 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.
14
+ - 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.
15
+ - 3865605: Stream `actions.requested` as each model tool call arrives, before the tool finishes or a runtime action is dispatched.
16
+
3
17
  ## 0.14.0
4
18
 
5
19
  ### 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.#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,_=!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};
@@ -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?.info?.agent.model.id;a!==void 0&&(i.model=a);let o=this.#b?.info?.agent.model.endpoint;o!==void 0&&(i.endpoint=o);let s=this.#$??0,c=this.#te??0;if(s>0||c>0){let e={inputTokens:s,outputTokens:c};this.#ee!==void 0&&(e.contextSize=this.#ee),i.tokens=formatTokenFlow(e,this.#r.glyph)}this.#E!==void 0&&(i.vercel=this.#E),this.#D!==void 0&&(i.remote=this.#D);let l=buildStatusLine(i);l!==void 0&&e.push(clip(`${n}${l}`,t))}#Tt(e,t){if(this.#D===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#D,theme:this.#r,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Et(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Q,outputTokens:this.#te,tokensPerSecond:this.#ne},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#Dt(){return Math.max(20,this.#t.columns||80)}#Ot(){return Math.max(8,this.#t.rows||24)}#kt(){if(this.#ie!==void 0||!this.#u)return;this.#ae=``,this.#oe=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#jt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ie=()=>{e(),t()}}#At(){let e=this.#ie;e!==void 0&&(this.#ie=void 0,e(),this.#ae.length>0&&(this.#Rt(`stdout`)&&process.stdout.write(`${this.#ae}\n`),this.#ae=``),this.#oe.length>0&&(this.#Rt(`stderr`)&&process.stderr.write(`${this.#oe}\n`),this.#oe=``))}#jt(e,t){let n=(e===`stdout`?this.#ae:this.#oe)+t,i=n.lastIndexOf(`
4
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(`
@@ -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};
@@ -1,37 +1,38 @@
1
1
  import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
2
2
  import type { HandleMessageStreamEvent } from "#protocol/message.js";
3
3
  import { type EveEvalSkillLoadMatchOptions, type EveEvalSubagentCallMatchOptions, type EveEvalToolCallMatchOptions } from "#evals/match.js";
4
+ import type { EveEvalEventMatch } from "#evals/match.js";
4
5
  import type { RunAssertion } from "#evals/assertions/collector.js";
6
+ /** Minimal captured scope consumed by deterministic eval assertions. */
7
+ export interface EveEvalAssertionSubject {
8
+ readonly derived: import("#evals/types.js").EveEvalDerivedFacts;
9
+ readonly events: readonly HandleMessageStreamEvent[];
10
+ readonly output: unknown;
11
+ readonly status: "completed" | "failed" | "waiting";
12
+ }
5
13
  /**
6
- * Asserts the run ran to completion: it did not fail and did not park on an
14
+ * Asserts the run finished successfully: it did not fail and did not park on an
7
15
  * unanswered HITL input request.
8
16
  */
9
- export declare function completed(): RunAssertion;
17
+ export declare function succeeded(): RunAssertion;
10
18
  /**
11
- * Asserts the run ended parked on HITL input. For approval gates and
12
- * ask-question flows.
19
+ * Asserts the run ended cleanly parked on HITL input.
13
20
  */
14
- export declare function waiting(): RunAssertion;
15
- /**
16
- * Asserts the run did not fail: terminal status is not `"failed"` and no
17
- * `turn.failed` / `step.failed` events were emitted. Parked runs pass; use
18
- * {@link completed} to also reject parking.
19
- */
20
- export declare function didNotFail(): RunAssertion;
21
+ export declare function parked(): RunAssertion;
21
22
  /**
22
23
  * Asserts the joined assistant message text contains `token` (substring for
23
24
  * strings, `test` for RegExps).
24
25
  */
25
26
  export declare function messageIncludes(token: string | RegExp): RunAssertion;
26
27
  /**
27
- * Asserts a tool call with `name` happened. Options constrain the call
28
- * further: `input` partial-deep-matches, `output` matches the result,
29
- * `isError` constrains error state, and `times` requires an exact count.
28
+ * Asserts a completed tool call with `name` happened. Options constrain the
29
+ * call further: `input` partial-deep-matches, `output` matches the result,
30
+ * `status` overrides the lifecycle state, and `count` requires an exact count.
30
31
  */
31
32
  export declare function calledTool(name: string, options?: EveEvalToolCallMatchOptions): RunAssertion;
32
33
  /**
33
34
  * Sugar over {@link calledTool} for the framework `load_skill` tool: asserts a
34
- * skill with id `skill` was loaded. `output`/`isError`/`times` constrain the
35
+ * skill with id `skill` was loaded. `output`/`status`/`count` constrain the
35
36
  * matching call exactly as for `calledTool`.
36
37
  */
37
38
  export declare function loadedSkill(skill: string, options?: EveEvalSkillLoadMatchOptions): RunAssertion;
@@ -40,7 +41,7 @@ export declare function loadedSkill(skill: string, options?: EveEvalSkillLoadMat
40
41
  */
41
42
  export declare function notCalledTool(name: string): RunAssertion;
42
43
  /**
43
- * Asserts the named tools were called in the given order (subsequence match:
44
+ * Asserts the named tools were requested in the given order (subsequence match:
44
45
  * other calls may interleave).
45
46
  */
46
47
  export declare function toolOrder(names: readonly string[]): RunAssertion;
@@ -66,7 +67,13 @@ export declare function calledSubagent(name: string, options?: EveEvalSubagentCa
66
67
  * Escape hatch: asserts an arbitrary predicate over the full typed event
67
68
  * stream. `label` names the assertion in reports.
68
69
  */
69
- export declare function event(predicate: (events: readonly HandleMessageStreamEvent[]) => boolean, label: string): RunAssertion;
70
+ export declare function eventsSatisfy(label: string, predicate: (events: readonly HandleMessageStreamEvent[]) => boolean): RunAssertion;
71
+ /** Asserts a typed stream event exists, optionally with an exact count. */
72
+ export declare function typedEvent(matcher: EveEvalEventMatch): RunAssertion;
73
+ /** Asserts no typed stream event matches. */
74
+ export declare function notEvent(matcher: EveEvalEventMatch): RunAssertion;
75
+ /** Asserts typed event groups occur in order, ignoring unrelated events. */
76
+ export declare function eventOrder(matchers: readonly EveEvalEventMatch[]): RunAssertion;
70
77
  /**
71
78
  * Asserts `result.output` (the final assistant message) deep-equals `value`.
72
79
  */
@@ -1,2 +1,2 @@
1
- import{deepEquals,subagentCallMatches,testRegExp,toolCallMatches}from"#evals/match.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";const PASS={score:1},fail=(e,t)=>({score:0,message:e,metadata:t});function completed(){return{name:`completed`,evaluate(e){return e.status===`failed`?fail(failureDetail(`run failed`,e.derived.failureCode)):e.derived.parked?fail(`run parked on ${e.derived.inputRequests.length} unanswered input request(s)`):PASS}}}function waiting(){return{name:`waiting`,evaluate(e){return e.derived.parked?PASS:fail(`expected the run to park on HITL input; it ended "${e.status}" with no pending requests`)}}}function didNotFail(){return{name:`didNotFail`,evaluate(e){if(e.status===`failed`)return fail(failureDetail(`run failed`,e.derived.failureCode));let t=e.events.find(e=>e.type===`turn.failed`||e.type===`step.failed`);return t===void 0?PASS:fail(`${t.type} (${t.data.code}): ${t.data.message}`)}}}function messageIncludes(e){return{name:`messageIncludes(${String(e)})`,evaluate(t){let r=joinCompletedMessages(t.events);return(typeof e==`string`?r.includes(e):testRegExp(e,r))?PASS:fail(`assistant messages did not include ${String(e)}; got: ${truncate(r)}`)}}}function calledTool(e,t={}){return{name:`calledTool(${e})`,evaluate(n){let i=n.derived.toolCalls.filter(t=>t.name===e),a=i.filter(e=>toolCallMatches(e,t));if(t.times===void 0?a.length>0:a.length===t.times)return{score:1,metadata:{matchingCalls:a.length}};let o=i.length>0?`observed ${e} calls: ${i.map(e=>truncate(JSON.stringify(e.input))).join(`, `)}`:`observed tools: [${n.derived.toolCalls.map(e=>e.name).join(`, `)}]`;return fail(`${t.times===void 0?`expected a matching call to "${e}"`:`expected exactly ${t.times} matching call(s), found ${a.length}`}; ${o}`)}}}function loadedSkill(e,t={}){return{...calledTool(LOAD_SKILL_TOOL_NAME,{...t,input:{skill:e}}),name:`loadedSkill(${e})`}}function notCalledTool(e){return{name:`notCalledTool(${e})`,evaluate(t){let n=t.derived.toolCalls.filter(t=>t.name===e).length;return n===0?PASS:fail(`"${e}" was called ${n} time(s)`)}}}function toolOrder(e){return{name:`toolOrder(${e.join(` → `)})`,evaluate(t){let n=t.derived.toolCalls.map(e=>e.name),r=0;for(let t of n)if(t===e[r]&&(r+=1),r===e.length)break;return r===e.length?PASS:fail(`missing "${e[r]}" after [${e.slice(0,r).join(`, `)}]; observed order: [${n.join(`, `)}]`)}}}function usedNoTools(){return{name:`usedNoTools`,evaluate(e){let t=e.derived.toolCallCount;return t===0?PASS:fail(`expected no tool calls, got ${t}`,{toolCallCount:t})}}}function maxToolCalls(e){return{name:`maxToolCalls(${e})`,evaluate(t){let n=t.derived.toolCallCount;return n<=e?PASS:fail(`expected at most ${e} tool calls, got ${n}`,{maxAllowed:e,toolCallCount:n})}}}function noFailedActions(){return{name:`noFailedActions`,evaluate(e){let t=e.events.filter(e=>e.type===`action.result`&&(e.data.status===`failed`||e.data.result.isError===!0));if(t.length===0)return PASS;let n=t.map(e=>e.data.result.kind===`tool-result`?e.data.result.toolName:e.data.result.kind);return fail(`${t.length} failed action(s): ${n.join(`, `)}`)}}}function calledSubagent(e,n={}){return{name:`calledSubagent(${e})`,evaluate(r){let i=r.derived.subagentCalls.filter(t=>t.name===e);return i.filter(e=>subagentCallMatches(e,n)).length>0?PASS:i.length===0?fail(`subagent "${e}" was never called; observed: [${r.derived.subagentCalls.map(e=>e.name).join(`, `)}]`,{observedSubagentCalls:r.derived.subagentCalls}):fail(`subagent "${e}" was called but no call matched the constraints`,{observedSubagentCalls:i})}}}function event(e,t){return{name:`event(${t})`,evaluate(n){return e(n.events)?PASS:fail(`event predicate "${t}" did not hold`)}}}function outputEquals(t){return{name:`outputEquals`,evaluate(n){return deepEquals(n.output,t)?PASS:fail(`output ${truncate(JSON.stringify(n.output))} does not equal expected ${truncate(JSON.stringify(t))}`)}}}function outputMatches(e){return{name:`outputMatches`,async evaluate(t){let n=await e[`~standard`].validate(t.output);return!(`issues`in n)||n.issues===void 0?PASS:fail(`output failed schema validation: ${n.issues.map(e=>e.message).join(`; `)}`)}}}function joinCompletedMessages(e){let t=[];for(let n of e)n.type===`message.completed`&&n.data.message!==null&&t.push(n.data.message);return t.join(`
2
- `)}function failureDetail(e,t){return t===void 0?e:`${e} (code: ${t})`}function truncate(e,t=200){return e===void 0?`undefined`:e.length<=t?e:`${e.slice(0,t)}…`}export{calledSubagent,calledTool,completed,didNotFail,event,loadedSkill,maxToolCalls,messageIncludes,noFailedActions,notCalledTool,outputEquals,outputMatches,toolOrder,usedNoTools,waiting};
1
+ import{deepEquals,eventMatches,subagentCallMatches,testRegExp,toolCallMatches}from"#evals/match.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";const PASS={score:1},fail=(e,t)=>({score:0,message:e,metadata:t});function succeeded(){return{name:`succeeded`,evaluate(e){let t=runFailure(e);return t===void 0?e.derived.parked?fail(`run parked on ${e.derived.inputRequests.length} unanswered input request(s)`):PASS:t}}}function parked(){return{name:`parked`,evaluate(e){let t=runFailure(e);return t===void 0?e.derived.parked?PASS:fail(`expected the run to park on HITL input; it ended "${e.status}" with no pending requests`):t}}}function messageIncludes(e){return{name:`messageIncludes(${String(e)})`,evaluate(t){let n=joinCompletedMessages(t.events);return(typeof e==`string`?n.includes(e):testRegExp(e,n))?PASS:fail(`assistant messages did not include ${String(e)}; got: ${truncate(n)}`)}}}function calledTool(e,t={}){return validateCount(t.count),{name:`calledTool(${e})`,evaluate(n){let r=n.derived.toolCalls.filter(t=>t.name===e),a=r.filter(e=>toolCallMatches(e,t));if(t.count===void 0?a.length>0:a.length===t.count)return{score:1,metadata:{matchingCalls:a.length}};let o=r.length>0?`observed ${e} calls: ${r.map(e=>truncate(JSON.stringify(e.input))).join(`, `)}`:`observed tools: [${n.derived.toolCalls.map(e=>e.name).join(`, `)}]`;return fail(`${t.count===void 0?`expected a matching call to "${e}"`:`expected exactly ${t.count} matching call(s), found ${a.length}`}; ${o}`)}}}function loadedSkill(e,t={}){return{...calledTool(LOAD_SKILL_TOOL_NAME,{...t,input:{skill:e}}),name:`loadedSkill(${e})`}}function notCalledTool(e){return{name:`notCalledTool(${e})`,evaluate(t){let n=t.derived.toolCalls.filter(t=>t.name===e).length;return n===0?PASS:fail(`"${e}" was called ${n} time(s)`)}}}function toolOrder(e){return{name:`toolOrder(${e.join(` → `)})`,evaluate(t){let n=requestedTools(t.events).map(e=>e.name),r=missingOrderedName(e,n);return r===void 0?PASS:fail(`missing "${r.name}" after [${e.slice(0,r.cursor).join(`, `)}]; observed request order: [${n.join(`, `)}]`)}}}function usedNoTools(){return{name:`usedNoTools`,evaluate(e){let t=e.derived.toolCallCount;return t===0?PASS:fail(`expected no tool calls, got ${t}`,{toolCallCount:t})}}}function maxToolCalls(e){return validateCount(e),{name:`maxToolCalls(${e})`,evaluate(t){let n=t.derived.toolCallCount;return n<=e?PASS:fail(`expected at most ${e} tool calls, got ${n}`,{maxAllowed:e,toolCallCount:n})}}}function noFailedActions(){return{name:`noFailedActions`,evaluate(e){let t=e.events.filter(e=>e.type===`action.result`&&(e.data.status===`failed`||e.data.result.isError===!0));if(t.length===0)return PASS;let n=t.map(e=>e.data.result.kind===`tool-result`?e.data.result.toolName:e.data.result.kind);return fail(`${t.length} failed action(s): ${n.join(`, `)}`)}}}function calledSubagent(e,t={}){return validateCount(t.count),{name:`calledSubagent(${e})`,evaluate(r){let i=r.derived.subagentCalls.filter(t=>t.name===e),a=i.filter(e=>subagentCallMatches(e,t));return(t.count===void 0?a.length>0:a.length===t.count)?{score:1,metadata:{matchingCalls:a.length}}:i.length===0?fail(`subagent "${e}" was never called; observed: [${r.derived.subagentCalls.map(e=>e.name).join(`, `)}]`,{observedSubagentCalls:r.derived.subagentCalls}):fail(`subagent "${e}" was called but ${a.length} call(s) matched the constraints`,{observedSubagentCalls:i})}}}function eventsSatisfy(e,t){return{name:`eventsSatisfy(${e})`,evaluate(n){return t(n.events)?PASS:fail(`event predicate "${e}" did not hold`)}}}function typedEvent(e){return validateCount(e.count),{name:`event(${e.type})`,evaluate(n){let r=n.events.filter(n=>eventMatches(n,e));return(e.count===void 0?r.length>0:r.length===e.count)?{score:1,metadata:{matchingEvents:r.length}}:fail(`expected ${e.count===void 0?`at least one`:`exactly ${e.count}`} matching ${e.type} event(s), found ${r.length}; observed: [${n.events.map(e=>e.type).join(`, `)}]`)}}}function notEvent(e){return{name:`notEvent(${e.type})`,evaluate(n){let r=n.events.filter(n=>eventMatches(n,e));return r.length===0?PASS:fail(`expected no matching ${e.type} events, found ${r.length}`)}}}function eventOrder(e){for(let t of e)validateCount(t.count);return{name:`eventOrder(${e.map(e=>e.type).join(` → `)})`,evaluate(n){let r=-1;for(let i of e){let e=n.events.flatMap((e,n)=>eventMatches(e,i)?[n]:[]);if(!(i.count===void 0?e.length>0:e.length===i.count))return fail(`expected ${i.count===void 0?`at least one`:`exactly ${i.count}`} matching ${i.type} event(s), found ${e.length}`);let a=e[0];if(a===void 0||a<=r)return fail(`event group ${i.type} did not occur after the previous group`);r=e[e.length-1]??r}return PASS}}}function outputEquals(t){return{name:`outputEquals`,evaluate(n){return deepEquals(n.output,t)?PASS:fail(`output ${truncate(JSON.stringify(n.output))} does not equal expected ${truncate(JSON.stringify(t))}`)}}}function outputMatches(e){return{name:`outputMatches`,async evaluate(t){let n=await e[`~standard`].validate(t.output);return!(`issues`in n)||n.issues===void 0?PASS:fail(`output failed schema validation: ${n.issues.map(e=>e.message).join(`; `)}`)}}}function joinCompletedMessages(e){let t=[];for(let n of e)n.type===`message.completed`&&n.data.message!==null&&t.push(n.data.message);return t.join(`
2
+ `)}function failureDetail(e,t){return t===void 0?e:`${e} (code: ${t})`}function runFailure(e){if(e.status===`failed`)return fail(failureDetail(`run failed`,e.derived.failureCode));let t=e.events.find(e=>e.type===`turn.failed`||e.type===`step.failed`);return t===void 0?void 0:fail(`${t.type} (${t.data.code}): ${t.data.message}`)}function truncate(e,t=200){return e===void 0?`undefined`:e.length<=t?e:`${e.slice(0,t)}…`}function validateCount(e){if(e!==void 0&&(!Number.isInteger(e)||e<0))throw TypeError(`Assertion count must be a non-negative integer; received ${e}.`)}function missingOrderedName(e,t){let n=0;for(let r of t)if(r===e[n]&&(n+=1),n===e.length)return;let r=e[n];return r===void 0?void 0:{cursor:n,name:r}}function requestedTools(e){let t=[],n=new Set,append=(e,r)=>{n.has(e)||(n.add(e),t.push({callId:e,name:r}))};for(let t of e)if(t.type===`actions.requested`)for(let e of t.data.actions)e.kind===`tool-call`&&append(e.callId,e.toolName);else if(t.type===`input.requested`)for(let e of t.data.requests){let{action:t}=e;t.kind===`tool-call`&&append(t.callId,t.toolName)}return t}export{calledSubagent,calledTool,eventOrder,eventsSatisfy,loadedSkill,maxToolCalls,messageIncludes,noFailedActions,notCalledTool,notEvent,outputEquals,outputMatches,parked,succeeded,toolOrder,typedEvent,usedNoTools};
@@ -0,0 +1,17 @@
1
+ import { AssertionCollector } from "#evals/assertions/collector.js";
2
+ import type { EveEvalAssertionSubject } from "#evals/assertions/run.js";
3
+ import type { EveEvalAssertions, EveEvalOutputAssertions, EveEvalTaskResult } from "#evals/types.js";
4
+ type AssertionScope = {
5
+ readonly timing: "final";
6
+ select(result: EveEvalTaskResult): EveEvalAssertionSubject;
7
+ } | {
8
+ readonly timing: "snapshot";
9
+ select(): EveEvalAssertionSubject;
10
+ };
11
+ /** Binds the shared assertion vocabulary to one aggregate, session, or turn scope. */
12
+ export declare function createScopedAssertions(collector: AssertionCollector, scope: AssertionScope): EveEvalAssertions;
13
+ /** Binds output-only assertions to a session or immutable turn snapshot. */
14
+ export declare function createOutputAssertions(collector: AssertionCollector, scope: Extract<AssertionScope, {
15
+ timing: "snapshot";
16
+ }>): EveEvalOutputAssertions;
17
+ export {};
@@ -0,0 +1 @@
1
+ import"#evals/assertions/collector.js";import*as RunAssertions from"#evals/assertions/run.js";function createScopedAssertions(t,n){let r=createRecorder(t,n);return{succeeded:()=>r(RunAssertions.succeeded()),parked:()=>r(RunAssertions.parked()),messageIncludes:t=>r(RunAssertions.messageIncludes(t)),calledTool:(t,n)=>r(RunAssertions.calledTool(t,n)),loadedSkill:(t,n)=>r(RunAssertions.loadedSkill(t,n)),notCalledTool:t=>r(RunAssertions.notCalledTool(t)),toolOrder:t=>r(RunAssertions.toolOrder(t)),usedNoTools:()=>r(RunAssertions.usedNoTools()),maxToolCalls:t=>r(RunAssertions.maxToolCalls(t)),calledSubagent:(t,n)=>r(RunAssertions.calledSubagent(t,n)),noFailedActions:()=>r(RunAssertions.noFailedActions()),event:(t,n)=>r(RunAssertions.typedEvent({...n,type:t})),notEvent:(t,n)=>r(RunAssertions.notEvent({...n,type:t})),eventOrder:t=>r(RunAssertions.eventOrder(t)),eventsSatisfy:(t,n)=>r(RunAssertions.eventsSatisfy(t,n))}}function createOutputAssertions(t,n){let r=createRecorder(t,n);return{outputEquals:t=>r(RunAssertions.outputEquals(t)),outputMatches:t=>r(RunAssertions.outputMatches(t))}}function createRecorder(e,t){return t.timing===`final`?n=>e.recordScoped(n,t.select):n=>{let r=t.select();return e.recordScoped(n,()=>r)}}export{createOutputAssertions,createScopedAssertions};
@@ -9,6 +9,7 @@ import type { EveEvalContext, EveEvalJudgeConfig, EveEvalTargetHandle } from "#e
9
9
  */
10
10
  export declare function createEvalContext(deps: {
11
11
  readonly manager: EvalSessionManager;
12
+ readonly collector: AssertionCollector;
12
13
  readonly target: EveEvalTargetHandle;
13
14
  readonly signal: AbortSignal;
14
15
  readonly judge: EveEvalJudgeConfig | undefined;
@@ -1 +1 @@
1
- import"#evals/session.js";import{AssertionCollector}from"#evals/assertions/collector.js";import*as RunAssertions from"#evals/assertions/run.js";import{buildJudgeContext}from"#evals/judge.js";function createEvalContext(r){let i=new AssertionCollector,a=``,primary=()=>r.manager.primary,replyMessage=()=>r.manager.lastTurnSession()?.lastTurn?.message??null,o=buildJudgeContext({collector:i,getReply:replyMessage,getInput:()=>a,judge:r.judge});return{context:{get events(){return primary().events},get pendingInputRequests(){return primary().pendingInputRequests},get state(){return primary().state},get sessionId(){return primary().sessionId},expectInputRequests:e=>primary().expectInputRequests(e),respond:(...e)=>primary().respond(...e),respondAll:e=>primary().respondAll(e),send:e=>(a=promptText(e),primary().send(e)),sendFile:(e,t,n)=>(a=e,primary().sendFile(e,t,n)),signal:r.signal,target:r.target,get reply(){return replyMessage()},log:r.log,sleep:e=>sleep(e,r.signal),newSession:()=>r.manager.newSession(),completed:()=>i.recordRun(RunAssertions.completed()),didNotFail:()=>i.recordRun(RunAssertions.didNotFail()),waiting:()=>i.recordRun(RunAssertions.waiting()),messageIncludes:e=>i.recordRun(RunAssertions.messageIncludes(e)),calledTool:(e,n)=>i.recordRun(RunAssertions.calledTool(e,n)),loadedSkill:(e,n)=>i.recordRun(RunAssertions.loadedSkill(e,n)),notCalledTool:e=>i.recordRun(RunAssertions.notCalledTool(e)),toolOrder:e=>i.recordRun(RunAssertions.toolOrder(e)),usedNoTools:()=>i.recordRun(RunAssertions.usedNoTools()),maxToolCalls:e=>i.recordRun(RunAssertions.maxToolCalls(e)),calledSubagent:(e,n)=>i.recordRun(RunAssertions.calledSubagent(e,n)),noFailedActions:()=>i.recordRun(RunAssertions.noFailedActions()),event:(e,n)=>i.recordRun(RunAssertions.event(e,n)),outputEquals:e=>i.recordRun(RunAssertions.outputEquals(e)),outputMatches:e=>i.recordRun(RunAssertions.outputMatches(e)),check:(e,t)=>recordCheck(i,e,t),judge:o},collector:i}}function recordCheck(e,t,n){return e.recordValue({name:n.name,severity:n.severity,threshold:n.threshold,score:async()=>({score:await n.score(t)})})}function promptText(e){if(typeof e==`string`)return e;let t=e.message;return typeof t==`string`?t:``}function sleep(e=1e3,t){if(!Number.isFinite(e)||e<0)throw Error(`sleep() duration must be a non-negative finite number.`);return t?.aborted?Promise.reject(t.reason):new Promise((n,r)=>{let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(t.reason)},{once:!0})})}export{createEvalContext};
1
+ import"#evals/assertions/collector.js";import"#evals/session.js";import{createScopedAssertions}from"#evals/assertions/scoped.js";import{buildJudgeContext}from"#evals/judge.js";import{EvalRequirementFailed,EvalSkipped}from"#evals/control-flow.js";function createEvalContext(n){let i=n.collector,a=``,primary=()=>n.manager.primary,replyMessage=()=>n.manager.lastTurnSession()?.lastTurn?.message??null,o=buildJudgeContext({collector:i,getReply:replyMessage,getInput:()=>a,judge:n.judge});return{context:{get events(){return primary().events},get pendingInputRequests(){return primary().pendingInputRequests},get state(){return primary().state},get sessionId(){return primary().sessionId},requireInputRequest:e=>primary().requireInputRequest(e),respond:(...e)=>primary().respond(...e),respondAll:e=>primary().respondAll(e),send:e=>(a=promptText(e),primary().send(e)),sendFile:(e,t,n)=>(a=e,primary().sendFile(e,t,n)),signal:n.signal,target:n.target,get reply(){return replyMessage()},log:n.log,sleep:e=>sleep(e,n.signal),newSession:()=>n.manager.newSession(),...createScopedAssertions(i,{timing:`final`,select:e=>e}),check:(e,t)=>recordCheck(i,e,t),require:(e,t)=>requireCheck(i,e,t),skip:e=>{throw e.trim().length===0?Error(`skip() requires a non-empty reason.`):i.hasEntries||n.manager.hasActivity()?Error(`skip() must be called before sending messages or recording assertions.`):new EvalSkipped(e)},judge:o},collector:i}}async function requireCheck(e,t,r){let i=r.gate(r.threshold);if(!await e.recordRequirement({name:i.name,threshold:i.threshold,score:async()=>({score:await i.score(t)})}))throw new EvalRequirementFailed;return t}function recordCheck(e,t,n){return e.recordValue({name:n.name,severity:n.severity,threshold:n.threshold,score:async()=>({score:await n.score(t)})})}function promptText(e){if(typeof e==`string`)return e;let t=e.message;return typeof t==`string`?t:``}function sleep(e=1e3,t){if(!Number.isFinite(e)||e<0)throw Error(`sleep() duration must be a non-negative finite number.`);return t?.aborted?Promise.reject(t.reason):new Promise((n,r)=>{let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(t.reason)},{once:!0})})}export{createEvalContext};
@@ -0,0 +1,9 @@
1
+ /** Internal signal used to stop an eval after a recorded required assertion fails. */
2
+ export declare class EvalRequirementFailed extends Error {
3
+ constructor();
4
+ }
5
+ /** Internal signal used by `t.skip()` to produce a skipped verdict. */
6
+ export declare class EvalSkipped extends Error {
7
+ readonly reason: string;
8
+ constructor(reason: string);
9
+ }
@@ -0,0 +1 @@
1
+ var EvalRequirementFailed=class extends Error{constructor(){super(`A required eval assertion failed.`),this.name=`EvalRequirementFailed`}},EvalSkipped=class extends Error{reason;constructor(e){super(e),this.name=`EvalSkipped`,this.reason=e}};export{EvalRequirementFailed,EvalSkipped};
@@ -2,7 +2,7 @@ import type { EveEvalDefinition, EveEvalInput } from "#evals/types.js";
2
2
  /**
3
3
  * Defines one eve eval. Each eval file is exactly one case: an imperative
4
4
  * `test(t)` function that drives the agent (`t.send`, `t.respond`, …) and
5
- * asserts on what it produced (`t.completed()`, `t.check(...)`,
5
+ * asserts on what it produced (`t.succeeded()`, `t.check(...)`,
6
6
  * `t.judge.autoevals.*`). Organize related evals with directory nesting under
7
7
  * `evals/`, or default-export an array of evals to fan one file out over a
8
8
  * dataset.