eve 0.26.0 → 0.26.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/src/chunks/{use-eve-agent-CruinZmd.js → use-eve-agent-AeQLLhu9.js} +118 -92
- package/dist/src/chunks/{use-eve-agent-BkztZA0v.js → use-eve-agent-PMY2WkAt.js} +118 -92
- package/dist/src/cli/banner.d.ts +5 -0
- package/dist/src/cli/banner.js +1 -1
- package/dist/src/cli/commands/info.d.ts +2 -0
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/dev/tui/blocks.d.ts +56 -8
- package/dist/src/cli/dev/tui/blocks.js +7 -7
- package/dist/src/cli/dev/tui/diagnostic-presentation.d.ts +2 -0
- package/dist/src/cli/dev/tui/diagnostic-presentation.js +3 -2
- package/dist/src/cli/dev/tui/file-content-cache.d.ts +35 -0
- package/dist/src/cli/dev/tui/file-content-cache.js +3 -0
- package/dist/src/cli/dev/tui/line-diff.d.ts +24 -0
- package/dist/src/cli/dev/tui/line-diff.js +1 -0
- package/dist/src/cli/dev/tui/markdown.d.ts +2 -1
- package/dist/src/cli/dev/tui/markdown.js +7 -3
- package/dist/src/cli/dev/tui/prompt-placeholder.d.ts +12 -0
- package/dist/src/cli/dev/tui/prompt-placeholder.js +1 -0
- package/dist/src/cli/dev/tui/question-panel.d.ts +24 -0
- package/dist/src/cli/dev/tui/question-panel.js +1 -0
- package/dist/src/cli/dev/tui/rail.d.ts +15 -0
- package/dist/src/cli/dev/tui/rail.js +1 -0
- package/dist/src/cli/dev/tui/runner.d.ts +22 -65
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.js +1 -1
- package/dist/src/cli/dev/tui/setup-issues.js +1 -1
- package/dist/src/cli/dev/tui/status-line.js +1 -1
- package/dist/src/cli/dev/tui/stream-format.d.ts +16 -3
- package/dist/src/cli/dev/tui/stream-format.js +1 -1
- package/dist/src/cli/dev/tui/subagent-pump.d.ts +127 -0
- package/dist/src/cli/dev/tui/subagent-pump.js +1 -0
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +34 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +11 -10
- package/dist/src/cli/dev/tui/test/mock-terminal.d.ts +7 -0
- package/dist/src/cli/dev/tui/test/mock-terminal.js +1 -1
- package/dist/src/cli/dev/tui/theme.d.ts +16 -2
- package/dist/src/cli/dev/tui/theme.js +1 -1
- package/dist/src/cli/dev/tui/todo-panel.d.ts +44 -0
- package/dist/src/cli/dev/tui/todo-panel.js +1 -0
- package/dist/src/cli/dev/tui/tool-block-groups.d.ts +40 -0
- package/dist/src/cli/dev/tui/tool-block-groups.js +1 -0
- package/dist/src/cli/dev/tui/tool-presentation.d.ts +67 -0
- package/dist/src/cli/dev/tui/tool-presentation.js +1 -0
- package/dist/src/cli/dev/tui/tool-rows.d.ts +15 -0
- package/dist/src/cli/dev/tui/tool-rows.js +2 -0
- package/dist/src/cli/dev/tui/turn-clock.d.ts +36 -0
- package/dist/src/cli/dev/tui/turn-clock.js +1 -0
- package/dist/src/cli/dev/tui/types.d.ts +2 -2
- package/dist/src/cli/dev/ui-options.js +1 -1
- package/dist/src/client/index.js +1 -1
- package/dist/src/client/message-action-parts.d.ts +43 -0
- package/dist/src/client/message-action-parts.js +1 -0
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +6 -5
- package/dist/src/compiled/@chat-adapter/slack/blocks.d.ts +47 -2
- package/dist/src/compiled/@chat-adapter/slack/blocks.js +10 -8
- package/dist/src/compiled/@chat-adapter/slack/index.d.ts +168 -8
- package/dist/src/compiled/@chat-adapter/slack/index.js +28 -28
- package/dist/src/compiled/@chat-adapter/slack/{types-AntsVifS.d.ts → types-CdGmMyOr.d.ts} +1 -1
- package/dist/src/compiled/@chat-adapter/slack/webhook.d.ts +2 -2
- package/dist/src/compiled/@chat-adapter/twilio/index.d.ts +1 -1
- package/dist/src/compiled/@chat-adapter/twilio/index.js +1 -1
- package/dist/src/compiled/@chat-adapter/twilio/webhook.d.ts +2 -2
- package/dist/src/compiled/@vercel/sandbox/index.js +12 -12
- package/dist/src/compiled/_chunks/node/{auth-Cuszvn7l.js → auth-BuQkq4Gr.js} +2 -2
- package/dist/src/compiled/_chunks/node/{dist-CdH_Yoxt.js → dist-BweCayKF.js} +42 -35
- package/dist/src/compiled/_chunks/node/{dist-Drt-_JVK.js → dist-DvkWiagq.js} +6 -4
- package/dist/src/compiled/chat/index.d.ts +17 -6
- package/dist/src/compiled/chat/index.js +1 -1
- package/dist/src/compiled/chat/{jsx-runtime-CzthIo1o.d.ts → jsx-runtime-_JEEAotp.d.ts} +125 -5
- package/dist/src/compiled/marked/LICENSE.md +44 -0
- package/dist/src/compiled/marked/index.d.ts +24 -0
- package/dist/src/compiled/marked/index.js +59 -0
- package/dist/src/compiler/model-catalog.js +1 -1
- package/dist/src/evals/autoevals-client.js +1 -1
- package/dist/src/evals/session.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-credentials.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-lookup.js +1 -1
- package/dist/src/execution/session.d.ts +0 -2
- package/dist/src/execution/session.js +1 -1
- package/dist/src/execution/skills/instructions.d.ts +3 -3
- package/dist/src/execution/skills/instructions.js +2 -2
- package/dist/src/execution/terminal-session-failure-step.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/messages.d.ts +7 -0
- package/dist/src/harness/messages.js +1 -1
- package/dist/src/harness/stale-input-responses.js +2 -2
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/internal/application/compiled-artifacts.js +9 -3
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/gateway.d.ts +19 -0
- package/dist/src/internal/gateway.js +1 -0
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js +1 -1
- package/dist/src/internal/nitro/routes/info.js +1 -1
- package/dist/src/internal/resolve-model-endpoint-status.d.ts +46 -3
- package/dist/src/internal/resolve-model-endpoint-status.js +1 -1
- package/dist/src/internal/user-agent.d.ts +11 -0
- package/dist/src/internal/user-agent.js +1 -0
- package/dist/src/public/tools/defaults.d.ts +3 -3
- package/dist/src/runtime/framework-tools/index.d.ts +3 -2
- package/dist/src/runtime/framework-tools/index.js +1 -1
- package/dist/src/runtime/framework-tools/skill.d.ts +6 -1
- package/dist/src/runtime/framework-tools/skill.js +1 -1
- package/dist/src/runtime/resolve-agent-graph.js +1 -1
- package/dist/src/setup/boxes/select-model.js +1 -1
- package/dist/src/setup/flows/link.d.ts +13 -3
- package/dist/src/setup/flows/link.js +1 -1
- package/dist/src/setup/flows/model.d.ts +4 -3
- package/dist/src/setup/flows/model.js +1 -1
- package/dist/src/setup/flows/provider.d.ts +3 -1
- package/dist/src/setup/flows/provider.js +2 -2
- package/dist/src/setup/gateway-models.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/validate-gateway-key.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +7 -7
- package/docs/reference/cli.md +1 -1
- package/docs/schedules.mdx +1 -1
- package/docs/skills.mdx +1 -1
- package/package.json +6 -5
- package/dist/src/execution/sandbox/bindings/vercel-user-agent.d.ts +0 -6
- package/dist/src/execution/sandbox/bindings/vercel-user-agent.js +0 -1
- package/dist/src/execution/workflow-skill-root.d.ts +0 -6
- package/dist/src/execution/workflow-skill-root.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createTuiPrompter}from"./tui-prompter.js";import{runDeployFlow}from"#setup/flows/deploy.js";import{WizardCancelledError}from"#setup/step.js";import{runLoginFlow}from"#setup/flows/login.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{runChannelsFlow}from"#setup/flows/channels.js";import{runConnectionsFlow}from"#setup/flows/connections.js";import{runInstallVercelCliFlow}from"#setup/flows/install-vercel-cli.js";import{runModelFlow}from"#setup/flows/model.js";import{runProviderFlow}from"#setup/flows/provider.js";import{openUrl}from"#setup/primitives/open-url.js";import{slackMessageDeepLink}from"#setup/slack-connect.js";const SETUP_FLOW_CONFIG={"vc:install":{title:`Install the Vercel CLI`,indicator:`pulse`},"vc:login":{title:`Log in to Vercel`,indicator:`pulse`},model:{title:`Configure the agent model`,indicator:`pulse`},channels:{title:`Agent channels`,indicator:`pulse`},connect:{title:`Agent connections`,indicator:`pulse`},deploy:{title:`Deploy to Vercel`,indicator:`spinner`}};function muteableRenderer(e,t){return{readSelect:n=>t()?Promise.resolve(void 0):e.readSelect(n),readEditableSelect:n=>t()?Promise.resolve(void 0):e.readEditableSelect(n),readProviderPicker:n=>t()?Promise.resolve(void 0):e.readProviderPicker(n),readModelEditor:n=>t()?Promise.resolve(void 0):e.readModelEditor(n),readText:n=>t()?Promise.resolve(void 0):e.readText(n),readAcknowledge:n=>t()?Promise.resolve():e.readAcknowledge(n),readChoice:n=>t()?{choice:Promise.resolve(void 0),close:()=>{}}:e.readChoice(n),setStatus:n=>{t()||e.setStatus(n)},renderLine:(n,r)=>{(!t()||r===`warning`||r===`error`)&&e.renderLine(n,r)},renderOutput:n=>{t()||e.renderOutput(n)}}}async function runTuiSetupCommand(t){let{command:r}=t,i=!1,a=new AbortController,o=muteableRenderer(t.renderer,()=>i),s=(t.createPrompter??createTuiPrompter)(o),c=t.renderer.waitForInterrupt(),l=Symbol(`interrupted`),u=executeSetupCommand(t,s,o,a.signal);try{let e=await Promise.race([u,c.promise.then(()=>l)]);return e===l?(i=!0,a.abort(new WizardCancelledError),{...await u,message:`/${r} interrupted.`,preserveFlowDiagnostics:!0}):e}finally{c.dispose(),t.renderer.setStatus(void 0)}}async function executeSetupCommand(e,i,u,d){let{command:f,appRoot:p}=e,m={runInstallVercelCliFlow,runLoginFlow,runModelFlow,runChannelsFlow,runConnectionsFlow,runDeployFlow,...e.flows};try{switch(f){case`vc:install`:return installVercelCliResultMessage(await m.runInstallVercelCliFlow({appRoot:p,prompter:i,signal:d}));case`vc:login`:return loginResultMessage(await m.runLoginFlow({appRoot:p,prompter:i,signal:d}));case`model`:{let pickProvider=e=>u.readProviderPicker(e),t={appRoot:p,prompter:i,signal:d,deps:{pickModelSettings:e=>u.readModelEditor(e),runProviderFlow:e=>runProviderFlow({...e,picker:pickProvider})}};e.initialModelStep!==void 0&&(t.initialStep=e.initialModelStep);let n=await m.runModelFlow(t);if(n.kind===`cancelled`)return{message:n.discardedDraft===!0?`/model dismissed. Drafted changes were discarded; Done commits them.`:`/model dismissed.`,preserveFlowDiagnostics:!1};let r=[];n.modelMessage!==void 0&&r.push(n.modelMessage),n.providerOutcome!==void 0&&r.push(providerOutcomeMessage(n.providerOutcome));let a={message:r.join(`
|
|
2
|
-
`),preserveFlowDiagnostics:!1};return n.providerOutcome!==void 0&&(a.effect={kind:`model-access-changed`}),a}case`channels`:{let e=await m.runChannelsFlow({appRoot:p,prompter:i,signal:d});switch(e.kind){case`failed`:return pendingChannelsResult(`Channel files changed, but /channels failed: ${e.message}`);case`cancelled`:return{message:`/channels dismissed.`,preserveFlowDiagnostics:!0};case`deploy-and-chat`:return await runDeployAndChat(m,{appRoot:p,prompter:i,signal:d},e.chat);case`done`:return e.addedChannels.length===0?{message:`No channels added.`,preserveFlowDiagnostics:!0}:{message:`Channels added: ${e.addedChannels.join(`, `)} — run /deploy to ship them.`,preserveFlowDiagnostics:!0,effect:{kind:`channels-added`}}}}case`connect`:{let t=await m.runConnectionsFlow({appRoot:p,prompter:i,signal:d,disabledConnectionReasons:e.disabledConnectionReasons});switch(t.kind){case`cancelled`:return{message:`/connect dismissed.`,preserveFlowDiagnostics:!0,effect:{kind:`model-access-changed`}};case`failed`:return{message:t.addedConnections.length===0?`/connect failed: ${t.message}`:`Connection files changed, but /connect failed: ${t.message}`,preserveFlowDiagnostics:!0,effect:t.addedConnections.length===0?{kind:`model-access-changed`}:{kind:`connection-added`}};case`done`:return{message:t.addedConnections.length===0?`No connections added.`:`Connections added: ${t.addedConnections.join(`, `)}.`,preserveFlowDiagnostics:!0,effect:t.addedConnections.length===0?{kind:`model-access-changed`}:{kind:`connection-added`}}}}case`deploy`:{let e=await m.runDeployFlow({appRoot:p,prompter:i,interactive:!0,signal:d});return e.kind===`cancelled`?{message:`/deploy dismissed.`,preserveFlowDiagnostics:!0}:e.kind===`needs-link`?{message:`Not linked to a Vercel project — run /model to connect one first.`,preserveFlowDiagnostics:!0}:{message:e.productionUrl===void 0?`Deployed.`:`Deployed: ${e.productionUrl}`,preserveFlowDiagnostics:!0,effect:{kind:`deployed`}}}}}catch(e){if(e instanceof WizardCancelledError)return{message:`/${f} dismissed.`,preserveFlowDiagnostics:f!==`model`};let t=vercelActionOutcome(e,f);return t===void 0?{message:`/${f} failed: ${e instanceof Error?e.message:String(e)}`,preserveFlowDiagnostics:!0}:t}}function vercelActionOutcome(e,t){if(!(e instanceof HumanActionRequiredError))return;let n=vercelActionMessage(e.action.kind,t);return n===void 0?void 0:{message:n,preserveFlowDiagnostics:!0}}function vercelActionMessage(e,t){switch(e){case`vercel-login`:return`You're not logged in to Vercel — run /vc:login, then retry /${t}.`;case`vercel-forbidden`:return`Vercel denied access to that team — run /vc:login to re-authenticate (for example to complete SSO), or pick a team you can access, then retry /${t}.`;case`vercel-cli-missing`:return`The Vercel CLI isn't installed — run /vc:install to install it, then retry /${t}.`;default:return}}async function runDeployAndChat(e,t,r){let i;try{i=await e.runDeployFlow({...t,interactive:!0})}catch(e){if(e instanceof WizardCancelledError)return pendingChannelsResult(`Channels added, but /deploy was dismissed. Run /deploy to ship them.`);let t=vercelActionOutcome(e,`deploy`);return pendingChannelsResult(t===void 0?`Channels added, but /deploy failed: ${e instanceof Error?e.message:String(e)}`:`Channels added. ${t.message}`)}if(i.kind===`cancelled`)return pendingChannelsResult(`Channels added, but /deploy was dismissed. Run /deploy to ship them.`);if(i.kind===`needs-link`)return pendingChannelsResult(`Channels added, but this directory is not linked to Vercel. Run /model, then /deploy.`);let a=i.productionUrl===void 0?`Deployed.`:`Deployed: ${i.productionUrl}`,o;if(r.chatUrl===void 0)o=`Message your agent in Slack to see it live.`;else{let e=slackMessageDeepLink(r.chatUrl);openUrl(e),o=`Chat with your agent in Slack: ${e}`}return{message:`${a}\n${o}`,preserveFlowDiagnostics:!0,effect:{kind:`deployed`}}}function installVercelCliResultMessage(e){switch(e.kind){case`cancelled`:return{message:`/vc:install dismissed.`,preserveFlowDiagnostics:!1};case`already`:return{message:`The Vercel CLI is already installed.`,preserveFlowDiagnostics:!1};case`failed`:return{message:"Couldn't install the Vercel CLI — install it manually with `npm i -g vercel@latest`.",preserveFlowDiagnostics:!0};case`installed`:return{message:`Installed the Vercel CLI. Run /vc:login next.`,preserveFlowDiagnostics:!1,effect:{kind:`refresh-identity`}}}}function loginResultMessage(e){switch(e.kind){case`cancelled`:return{message:`/vc:login dismissed.`,preserveFlowDiagnostics:!1};case`already`:return{message:`You're already logged in to Vercel.`,preserveFlowDiagnostics:!1};case`cli-missing`:return{message:`The Vercel CLI isn't installed — run /vc:install to install it, then retry /vc:login.`,preserveFlowDiagnostics:!0};case`failed`:return{message:`Vercel login didn't complete — run /vc:login to try again.`,preserveFlowDiagnostics:!0};case`logged-in`:return{message:`Logged in to Vercel.`,preserveFlowDiagnostics:!1,effect:{kind:`refresh-identity`}};case`unavailable`:return{message:`Couldn't reach Vercel — check your connection, then retry /vc:login.`,preserveFlowDiagnostics:!0}}}function pendingChannelsResult(e){return{message:e,preserveFlowDiagnostics:!0,effect:{kind:`channels-added`}}}function providerOutcomeMessage(e){let{
|
|
2
|
+
`),preserveFlowDiagnostics:!1};return n.providerOutcome!==void 0&&(a.effect={kind:`model-access-changed`}),a}case`channels`:{let e=await m.runChannelsFlow({appRoot:p,prompter:i,signal:d});switch(e.kind){case`failed`:return pendingChannelsResult(`Channel files changed, but /channels failed: ${e.message}`);case`cancelled`:return{message:`/channels dismissed.`,preserveFlowDiagnostics:!0};case`deploy-and-chat`:return await runDeployAndChat(m,{appRoot:p,prompter:i,signal:d},e.chat);case`done`:return e.addedChannels.length===0?{message:`No channels added.`,preserveFlowDiagnostics:!0}:{message:`Channels added: ${e.addedChannels.join(`, `)} — run /deploy to ship them.`,preserveFlowDiagnostics:!0,effect:{kind:`channels-added`}}}}case`connect`:{let t=await m.runConnectionsFlow({appRoot:p,prompter:i,signal:d,disabledConnectionReasons:e.disabledConnectionReasons});switch(t.kind){case`cancelled`:return{message:`/connect dismissed.`,preserveFlowDiagnostics:!0,effect:{kind:`model-access-changed`}};case`failed`:return{message:t.addedConnections.length===0?`/connect failed: ${t.message}`:`Connection files changed, but /connect failed: ${t.message}`,preserveFlowDiagnostics:!0,effect:t.addedConnections.length===0?{kind:`model-access-changed`}:{kind:`connection-added`}};case`done`:return{message:t.addedConnections.length===0?`No connections added.`:`Connections added: ${t.addedConnections.join(`, `)}.`,preserveFlowDiagnostics:!0,effect:t.addedConnections.length===0?{kind:`model-access-changed`}:{kind:`connection-added`}}}}case`deploy`:{let e=await m.runDeployFlow({appRoot:p,prompter:i,interactive:!0,signal:d});return e.kind===`cancelled`?{message:`/deploy dismissed.`,preserveFlowDiagnostics:!0}:e.kind===`needs-link`?{message:`Not linked to a Vercel project — run /model to connect one first.`,preserveFlowDiagnostics:!0}:{message:e.productionUrl===void 0?`Deployed.`:`Deployed: ${e.productionUrl}`,preserveFlowDiagnostics:!0,effect:{kind:`deployed`}}}}}catch(e){if(e instanceof WizardCancelledError)return{message:`/${f} dismissed.`,preserveFlowDiagnostics:f!==`model`};let t=vercelActionOutcome(e,f);return t===void 0?{message:`/${f} failed: ${e instanceof Error?e.message:String(e)}`,preserveFlowDiagnostics:!0}:t}}function vercelActionOutcome(e,t){if(!(e instanceof HumanActionRequiredError))return;let n=vercelActionMessage(e.action.kind,t);return n===void 0?void 0:{message:n,preserveFlowDiagnostics:!0}}function vercelActionMessage(e,t){switch(e){case`vercel-login`:return`You're not logged in to Vercel — run /vc:login, then retry /${t}.`;case`vercel-forbidden`:return`Vercel denied access to that team — run /vc:login to re-authenticate (for example to complete SSO), or pick a team you can access, then retry /${t}.`;case`vercel-cli-missing`:return`The Vercel CLI isn't installed — run /vc:install to install it, then retry /${t}.`;default:return}}async function runDeployAndChat(e,t,r){let i;try{i=await e.runDeployFlow({...t,interactive:!0})}catch(e){if(e instanceof WizardCancelledError)return pendingChannelsResult(`Channels added, but /deploy was dismissed. Run /deploy to ship them.`);let t=vercelActionOutcome(e,`deploy`);return pendingChannelsResult(t===void 0?`Channels added, but /deploy failed: ${e instanceof Error?e.message:String(e)}`:`Channels added. ${t.message}`)}if(i.kind===`cancelled`)return pendingChannelsResult(`Channels added, but /deploy was dismissed. Run /deploy to ship them.`);if(i.kind===`needs-link`)return pendingChannelsResult(`Channels added, but this directory is not linked to Vercel. Run /model, then /deploy.`);let a=i.productionUrl===void 0?`Deployed.`:`Deployed: ${i.productionUrl}`,o;if(r.chatUrl===void 0)o=`Message your agent in Slack to see it live.`;else{let e=slackMessageDeepLink(r.chatUrl);openUrl(e),o=`Chat with your agent in Slack: ${e}`}return{message:`${a}\n${o}`,preserveFlowDiagnostics:!0,effect:{kind:`deployed`}}}function installVercelCliResultMessage(e){switch(e.kind){case`cancelled`:return{message:`/vc:install dismissed.`,preserveFlowDiagnostics:!1};case`already`:return{message:`The Vercel CLI is already installed.`,preserveFlowDiagnostics:!1};case`failed`:return{message:"Couldn't install the Vercel CLI — install it manually with `npm i -g vercel@latest`.",preserveFlowDiagnostics:!0};case`installed`:return{message:`Installed the Vercel CLI. Run /vc:login next.`,preserveFlowDiagnostics:!1,effect:{kind:`refresh-identity`}}}}function loginResultMessage(e){switch(e.kind){case`cancelled`:return{message:`/vc:login dismissed.`,preserveFlowDiagnostics:!1};case`already`:return{message:`You're already logged in to Vercel.`,preserveFlowDiagnostics:!1};case`cli-missing`:return{message:`The Vercel CLI isn't installed — run /vc:install to install it, then retry /vc:login.`,preserveFlowDiagnostics:!0};case`failed`:return{message:`Vercel login didn't complete — run /vc:login to try again.`,preserveFlowDiagnostics:!0};case`logged-in`:return{message:`Logged in to Vercel.`,preserveFlowDiagnostics:!1,effect:{kind:`refresh-identity`}};case`unavailable`:return{message:`Couldn't reach Vercel — check your connection, then retry /vc:login.`,preserveFlowDiagnostics:!0}}}function pendingChannelsResult(e){return{message:e,preserveFlowDiagnostics:!0,effect:{kind:`channels-added`}}}function providerOutcomeMessage(e){let{resolution:t,status:n}=e;if(n.kind===`gateway-project`)return t===void 0?`Project linked. No model credential found; set AI_GATEWAY_API_KEY in .env.local.`:t.credential===`oidc`?`Project linked. Connected to AI Gateway via VERCEL_OIDC_TOKEN.`:t.shadowedOidc===void 0?`Project linked. Connected to AI Gateway via AI_GATEWAY_API_KEY.`:`Project linked. AI_GATEWAY_API_KEY (${t.source.kind===`shell`?`shell`:t.source.path}) outranks the project's VERCEL_OIDC_TOKEN and stays the active credential — ${t.source.kind===`shell`?`unset it in your shell`:`remove it from ${t.source.path}`} to run on the project.`;if(n.kind===`gateway-key`){let e=n.source.kind===`shell`?`your shell`:n.source.path;return`Connected to AI Gateway via ${n.envKey} in ${e}.`}return`Provider updated — no gateway credential detected; set AI_GATEWAY_API_KEY in .env.local.`}export{SETUP_FLOW_CONFIG,runTuiSetupCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join}from"node:path";import{pathExists}from"#setup/path-exists.js";
|
|
1
|
+
import{join}from"node:path";import{pathExists}from"#setup/path-exists.js";import{hasEnvValue,resolveGatewayCredential}from"#internal/resolve-model-endpoint-status.js";function resolveModelProviderState(e,t){let n=modelProviderAccess({env:t,info:e});if(e===void 0||n.kind!==`gateway`||n.runtime.status!==`connected`)return e;let{credential:r}=n.runtime,i=e.agent.model,a=i.endpoint;return a?.kind===`gateway`&&a.connected&&a.credential===r?e:{...e,agent:{...e.agent,model:{...i,endpoint:{kind:`gateway`,connected:!0,credential:r}}}}}function modelProviderAccess(e){let t=e.info?.agent.model;if(t?.routing?.kind===`external`)return{kind:`external`};if(t?.routing?.kind!==`gateway`)return{kind:`unknown`};let i=resolveGatewayCredential({apiKeyInEnv:hasEnvValue(e.env.AI_GATEWAY_API_KEY),oidcAvailable:hasEnvValue(e.env.VERCEL_OIDC_TOKEN)});if(i?.credential===`api-key`)return{kind:`gateway`,runtime:{status:`connected`,credential:`api-key`}};let a=t.endpoint;return a?.kind===`gateway`&&a.connected?{kind:`gateway`,runtime:{status:`connected`,credential:a.credential}}:i===void 0?a?.kind===`gateway`?{kind:`gateway`,runtime:{status:`disconnected`}}:{kind:`gateway`,runtime:{status:`unknown`}}:{kind:`gateway`,runtime:{status:`connected`,credential:i.credential}}}const BOOT_DETECTIONS=[{id:`model-provider`,async detect({appRoot:n,env:r,info:i}){let a=modelProviderAccess({env:r,info:i});if(a.kind===`external`)return[];if(a.kind===`gateway`){if(a.runtime.status===`connected`)return[];if(a.runtime.status===`disconnected`)return[{kind:`attention`,label:await pathExists(join(n,`.vercel`,`project.json`))?`AI Gateway credentials missing`:`model provider not linked`,command:`/model`}]}return await pathExists(join(n,`.vercel`,`project.json`))?[{kind:`attention`,label:`AI Gateway credentials missing`,command:`/model`}]:[{kind:`attention`,label:`model provider not linked`,command:`/model`}]}}],LOGIN_SETUP_ISSUE={kind:`attention`,label:`not logged in`,command:`/vc:login`},CLI_MISSING_SETUP_ISSUE={kind:`attention`,label:`Vercel CLI not found`,command:`/vc:install`};async function detectSetupIssues(e,t=BOOT_DETECTIONS){return(await Promise.all(t.map(async t=>{try{return await t.detect(e)}catch{return[]}}))).flat()}function orderedSetupIssues(e,t){return t===void 0?[...e]:[t,...e]}function formatSetupIssuesLine(e){let t=e.length===1?`setup issue`:`setup issues`,n=e.map(e=>`${e.label} · ${e.command}`).join(`, `);return`${e.length} ${t}: ${n}`}export{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{remoteHost}from"./target.js";import{clipVisible,stripAnsi,visibleLength}from"#cli/ui/terminal-text.js";import{formatModelSummary}from"#shared/model-summary.js";function renderModel(e){if(e.model===void 0)return;let t=e.theme.colors,r={model:e.model};if(e.reasoning!==void 0&&(r.reasoning=e.reasoning),e.fastMode===!0&&(r.fastGlyph=e.theme.glyph.fast),e.remote!==void 0){r.model=stripAnsi(e.model).replace(/\s+/gu,` `).trim();let a=stripAnsi(formatModelSummary(r)).replace(/\s+/gu,` `).trim();return t.dim(a)}return t.dim(formatModelSummary(r))}function renderServerPort(e){if(e.remote!==void 0||e.serverPort===void 0)return;let t=e.theme.colors;return t.inverse(t.gray(` :${e.serverPort} `))}function renderEndpoint(e){if(e.remote!==void 0||e.endpoint===void 0)return;let t=e.theme.colors
|
|
1
|
+
import{remoteHost}from"./target.js";import{clipVisible,stripAnsi,visibleLength}from"#cli/ui/terminal-text.js";import{formatModelSummary}from"#shared/model-summary.js";function renderModel(e){if(e.model===void 0)return;let t=e.theme.colors,r={model:e.model};if(e.reasoning!==void 0&&(r.reasoning=e.reasoning),e.fastMode===!0&&(r.fastGlyph=e.theme.glyph.fast),e.remote!==void 0){r.model=stripAnsi(e.model).replace(/\s+/gu,` `).trim();let a=stripAnsi(formatModelSummary(r)).replace(/\s+/gu,` `).trim();return t.dim(a)}return t.dim(formatModelSummary(r))}function renderServerPort(e){if(e.remote!==void 0||e.serverPort===void 0)return;let t=e.theme.colors;return t.inverse(t.gray(` :${e.serverPort} `))}const EXTERNAL_PROVIDER_DISPLAY_NAMES={codex:`chatgpt-sub`};function renderEndpoint(e){if(e.remote!==void 0||e.endpoint===void 0)return;let t=e.theme.colors,n=e.theme.glyph,clause=(e,n)=>`${t.dim(`via `)}${e}${t.dim(n)}`;if(e.endpoint.kind===`external`){let r=EXTERNAL_PROVIDER_DISPLAY_NAMES[e.endpoint.provider]??e.endpoint.provider;return{text:`${t.dim(`via ${r}`)}${n.external}`,standalone:!1}}if(!e.endpoint.connected)return{text:t.yellow(`${n.warning} ai-gateway`),standalone:!0};if(e.endpoint.credential===`api-key`)return{text:clause(`ai-gateway`,`(api-key)`),standalone:!1};let r=e.vercel?.identity?.projectName;return{text:clause(`ai-gateway`,`(${r===void 0?`oidc`:`oidc:${r}`})`),standalone:!1}}function buildStatusLine(e){let{theme:n,width:i}=e,a=n.colors,o=e.logLevel===void 0?void 0:a.cyan(`logs: ${e.logLevel}`),s=renderServerPort(e),c=renderModel(e),l=e.vercel?.pendingDeploy?a.yellow(`/deploy pending`):void 0,u=e.remote===void 0?void 0:formatRemoteStatus(e.remote,n),d=renderEndpoint(e),f=u?.full??s,p=u?.badge??s,m=d!==void 0&&!d.standalone&&c!==void 0,h=m?`${c} ${d.text}`:c,g=d===void 0||m?void 0:d.text,compose=(e,t)=>{let n=t.filter(e=>e!==void 0).join(` `);return e===void 0||n.length===0?e??n:`${e} ${n}`},_=[compose(f,[o,h,g,l]),compose(f,[o,c,l]),compose(f,[o,l]),compose(f,[o]),compose(p,[o]),compose(p,[])];if(_[0].length!==0){for(let e of _)if(e.length>0&&visibleLength(e)<=i)return e;return clipVisible(_.findLast(e=>e.length>0),i)}}function formatRemoteStatus(t,n){let r=n.colors,i=t.deployment===void 0?remoteHost(t.target):`${t.deployment.projectName} (${t.deployment.environment})`,a=formatRemoteBadge(` ${n.unicode?`↗`:`->`} ${i} `,t.connection.state,n),o;switch(t.connection.state){case`checking`:o=r.dim(`Checking access…`);break;case`ready`:break;case`auth-required`:o=r.yellow(`Authenticate via OIDC`);break;case`authenticating`:o=r.dim(`Authenticating via OIDC…`);break;case`auth-failed`:o=r.yellow(`Authentication failed`);break;case`unavailable`:o=r.yellow(`Remote unavailable`);break}return{badge:a,full:o===void 0?a:`${a} ${o}`}}function formatRemoteBadge(e,t,n){let r=n.colors;switch(t){case`checking`:return r.inverse(r.gray(e));case`ready`:return r.inverse(r.blue(e));case`unavailable`:case`auth-required`:case`authenticating`:case`auth-failed`:return r.inverse(r.yellow(e))}}export{buildStatusLine};
|
|
@@ -100,9 +100,22 @@ export declare function takeUntil<T>(source: AsyncIterable<T>, stop: Promise<voi
|
|
|
100
100
|
/** `394.4K`-style compact count: plain below 1000, then K/M with one trimmed decimal. */
|
|
101
101
|
export declare function formatCompactTokenCount(count: number): string;
|
|
102
102
|
/**
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
103
|
+
* Reveals `text` one character per `stepMs` of elapsed time, typewriter
|
|
104
|
+
* style: the first character shows immediately, the full text after
|
|
105
|
+
* `(length - 1) * stepMs`. Painted on the shared ticker beat, so no timer
|
|
106
|
+
* of its own.
|
|
107
|
+
*/
|
|
108
|
+
export declare function typewriterText(text: string, elapsedMs: number, stepMs: number): string;
|
|
109
|
+
/**
|
|
110
|
+
* Formats a turn's wall-clock duration for the end-of-turn stats line:
|
|
111
|
+
* `42s`, `3min 24s`, `1h 12min`. Sub-second turns round up to `1s` — a
|
|
112
|
+
* `0s` coda would read as a measurement error.
|
|
113
|
+
*/
|
|
114
|
+
export declare function formatTurnDuration(elapsedMs: number): string;
|
|
115
|
+
/**
|
|
116
|
+
* The turn bar and coda's token-flow segment: `↑ 394.4K ↓ 4.3K`, input
|
|
117
|
+
* (prompt) tokens up, output tokens down. A known `--context-size` appends
|
|
118
|
+
* the context-fill percentage of the input side.
|
|
106
119
|
*/
|
|
107
120
|
export declare function formatTokenFlow(flow: {
|
|
108
121
|
inputTokens: number;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
const CSI_FINAL=/[\u0040-\u007e]/u,PASTE_START=`\x1B[200~`,PASTE_END=`\x1B[201~`;function sanitizePastedText(e){let t=``;for(let n of e.replace(/\r\n?/gu,`
|
|
2
2
|
`)){if(n===`
|
|
3
3
|
`||n===` `){t+=n;continue}let e=n.codePointAt(0);e!==void 0&&(e<32||e===127||e>=128&&e<=159||(t+=n))}return t}function isIncompletePaste(e){return e.startsWith(PASTE_START)&&!e.includes(PASTE_END,6)}function stripPasteStart(e){return e.startsWith(PASTE_START)?e.slice(6):e}function stripPromptControlCharacters(e){let t=``;for(let n of e)n>=` `&&n!==``&&(t+=n);return t}function nextKey(r){let i=r[0];if(i===void 0)return{consumed:0,incomplete:!0};if(i===`\x1B`){if(r.length===1)return{consumed:0,incomplete:!0};let i=r[1];if(i===`O`)return r.length<3?{consumed:0,incomplete:!0}:{key:parseKey(Buffer.from(r.slice(0,3))),consumed:3};if(i===`[`){if(r.startsWith(PASTE_START)){let e=r.indexOf(PASTE_END,6);return e===-1?{consumed:0,incomplete:!0}:{key:{type:`text`,value:sanitizePastedText(r.slice(6,e)),framing:`bracketed-paste`},consumed:e+6}}for(let t=2;t<r.length;t+=1)if(CSI_FINAL.test(r[t]))return{key:parseKey(Buffer.from(r.slice(0,t+1))),consumed:t+1};return{consumed:0,incomplete:!0}}return{key:{type:`escape`},consumed:1}}if(i<` `||i===``)return{key:parseKey(Buffer.from(i)),consumed:1};let a=1;for(;a<r.length;){let e=r[a];if(e===`\x1B`||e<` `||e===``)break;a+=1}return{key:parseKey(Buffer.from(r.slice(0,a))),consumed:a}}function parseKey(e){let t=e.toString(`utf8`);switch(t){case``:return{type:`ctrl-a`};case``:return{type:`ctrl-e`};case``:return{type:`ctrl-d`};case`\v`:return{type:`ctrl-k`};case``:return{type:`ctrl-n`};case``:return{type:`ctrl-p`};case`\f`:return{type:`ctrl-l`};case``:return{type:`ctrl-r`};case``:return{type:`ctrl-u`};case``:return{type:`ctrl-w`};case``:return{type:`ctrl-c`};case`\r`:case`
|
|
4
|
-
`:return{type:`enter`};case`\x1B[27;2;13~`:case`\x1B[13;2u`:return{type:`newline`};case``:case`\b`:return{type:`backspace`};case`\x1B[A`:case`\x1BOA`:return{type:`up`};case`\x1B[B`:case`\x1BOB`:return{type:`down`};case`\x1B[C`:case`\x1BOC`:return{type:`right`};case`\x1B[D`:case`\x1BOD`:return{type:`left`};case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:return{type:`home`};case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:return{type:`end`};case`\x1B[3~`:return{type:`delete`};case` `:return{type:`tab`};case`\x1B`:return{type:`escape`};default:{let e=stripPromptControlCharacters(t);return e.length>0?{type:`text`,value:e,framing:`unframed`}:{type:`ignore`}}}}async function*takeUntil(e,t){let n=e[Symbol.asyncIterator](),r=t.then(()=>({done:!0,value:void 0}));try{for(;;){let e=n.next();e.catch(()=>{});let t=await Promise.race([e,r]);if(t.done)break;yield t.value}}finally{n.return?.()?.catch(()=>{})}}function formatCompactTokenCount(e){if(e<1e3)return`${e}`;let t=e<1e6?e/1e3:e/1e6,n=e<1e6?`K`:`M`;return`${t.toFixed(1).replace(/\.0$/,``)}${n}`}function formatTokenFlow(e,t){let n=formatCompactTokenCount(e.inputTokens),r=formatCompactTokenCount(e.outputTokens),i=`${t.arrowUp} ${n} ${t.arrowDown} ${r}`,a=formatContextPercentage(e.inputTokens,e.contextSize);return a==null?i:`${i} ${a}`}function formatContextPercentage(e,t){if(!(t==null||t<=0||!Number.isFinite(t)))return`${Math.round(e/t*100).toLocaleString()}%`}function formatAssistantResponseStats(e,t){if(t===`tokensPerSecond`)return formatTokensPerSecond(e.tokensPerSecond);if(e.outputTokens!=null)return`${e.outputTokens.toLocaleString()} output tokens`}function formatTokensPerSecond(e){if(e!=null)return`${formatNumber(e)} tok/s`}function formatNumber(e){return Number.isInteger(e)?e.toLocaleString():e.toLocaleString(void 0,{maximumFractionDigits:1})}export{formatAssistantResponseStats,formatCompactTokenCount,formatTokenFlow,isIncompletePaste,nextKey,parseKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil};
|
|
4
|
+
`:return{type:`enter`};case`\x1B[27;2;13~`:case`\x1B[13;2u`:return{type:`newline`};case``:case`\b`:return{type:`backspace`};case`\x1B[A`:case`\x1BOA`:return{type:`up`};case`\x1B[B`:case`\x1BOB`:return{type:`down`};case`\x1B[C`:case`\x1BOC`:return{type:`right`};case`\x1B[D`:case`\x1BOD`:return{type:`left`};case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:return{type:`home`};case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:return{type:`end`};case`\x1B[3~`:return{type:`delete`};case` `:return{type:`tab`};case`\x1B`:return{type:`escape`};default:{let e=stripPromptControlCharacters(t);return e.length>0?{type:`text`,value:e,framing:`unframed`}:{type:`ignore`}}}}async function*takeUntil(e,t){let n=e[Symbol.asyncIterator](),r=t.then(()=>({done:!0,value:void 0}));try{for(;;){let e=n.next();e.catch(()=>{});let t=await Promise.race([e,r]);if(t.done)break;yield t.value}}finally{n.return?.()?.catch(()=>{})}}function formatCompactTokenCount(e){if(e<1e3)return`${e}`;let t=e<1e6?e/1e3:e/1e6,n=e<1e6?`K`:`M`;return`${t.toFixed(1).replace(/\.0$/,``)}${n}`}function typewriterText(e,t,n){let r=Math.floor(Math.max(0,t)/n)+1;return r>=e.length?e:e.slice(0,r)}function formatTurnDuration(e){let t=Math.max(1,Math.round(e/1e3)),n=t%60,r=Math.floor(t/60);if(r===0)return`${n}s`;let i=r%60,a=Math.floor(r/60);return a===0?n===0?`${i}min`:`${i}min ${n}s`:i===0?`${a}h`:`${a}h ${i}min`}function formatTokenFlow(e,t){let n=formatCompactTokenCount(e.inputTokens),r=formatCompactTokenCount(e.outputTokens),i=`${t.arrowUp} ${n} ${t.arrowDown} ${r}`,a=formatContextPercentage(e.inputTokens,e.contextSize);return a==null?i:`${i} ${a}`}function formatContextPercentage(e,t){if(!(t==null||t<=0||!Number.isFinite(t)))return`${Math.round(e/t*100).toLocaleString()}%`}function formatAssistantResponseStats(e,t){if(t===`tokensPerSecond`)return formatTokensPerSecond(e.tokensPerSecond);if(e.outputTokens!=null)return`${e.outputTokens.toLocaleString()} output tokens`}function formatTokensPerSecond(e){if(e!=null)return`${formatNumber(e)} tok/s`}function formatNumber(e){return Number.isInteger(e)?e.toLocaleString():e.toLocaleString(void 0,{maximumFractionDigits:1})}export{formatAssistantResponseStats,formatCompactTokenCount,formatTokenFlow,formatTurnDuration,isIncompletePaste,nextKey,parseKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The subagent child-stream subsystem: for every `subagent.called` on the
|
|
3
|
+
* parent stream, a parallel pump over the child session folds its events
|
|
4
|
+
* into the renderer's nested subagent view. Extracted from the runner —
|
|
5
|
+
* the subsystem touches nothing but its own run state, the client, and the
|
|
6
|
+
* {@link SubagentView} seam.
|
|
7
|
+
*/
|
|
8
|
+
import type { Client } from "#client/index.js";
|
|
9
|
+
import { type ActionResultStreamEvent, type SubagentCalledStreamEvent } from "#protocol/message.js";
|
|
10
|
+
/**
|
|
11
|
+
* The renderer's subagent surface. One cohesive capability: a renderer that
|
|
12
|
+
* implements it renders whole sections — header, nested steps and tools,
|
|
13
|
+
* ghost sweeps, completion — and a renderer without it simply has no
|
|
14
|
+
* subagent view. Individually-optional methods would let a renderer
|
|
15
|
+
* implement a type-legal subset that ghosts placeholders or duplicates
|
|
16
|
+
* parent tool rows.
|
|
17
|
+
*/
|
|
18
|
+
export interface SubagentView {
|
|
19
|
+
/** Opens a call's section the moment its dispatch is announced. */
|
|
20
|
+
begin(update: {
|
|
21
|
+
callId: string;
|
|
22
|
+
name: string;
|
|
23
|
+
}): void;
|
|
24
|
+
upsertStep(update: SubagentStepUpdate): void;
|
|
25
|
+
upsertTool(update: SubagentToolUpdate): void;
|
|
26
|
+
/** Drops a child tool row whose call never materialized. */
|
|
27
|
+
removeTool(update: {
|
|
28
|
+
callId: string;
|
|
29
|
+
childCallId: string;
|
|
30
|
+
}): void;
|
|
31
|
+
/** Marks a call complete so its section collapses on `└ Done…`. */
|
|
32
|
+
complete(update: {
|
|
33
|
+
callId: string;
|
|
34
|
+
}): void;
|
|
35
|
+
/** Suppresses the parent-level tool row for a child-owned call id. */
|
|
36
|
+
markChildToolCallId(callId: string): void;
|
|
37
|
+
}
|
|
38
|
+
type SubagentChildStep = {
|
|
39
|
+
reasoning: string;
|
|
40
|
+
message: string;
|
|
41
|
+
finalized: boolean;
|
|
42
|
+
};
|
|
43
|
+
type SubagentToolStatus = "preparing" | "approval-requested" | "executing" | "done" | "failed" | "rejected";
|
|
44
|
+
type SubagentToolState = {
|
|
45
|
+
toolName: string;
|
|
46
|
+
input: unknown;
|
|
47
|
+
status: SubagentToolStatus;
|
|
48
|
+
output?: unknown;
|
|
49
|
+
errorText?: string;
|
|
50
|
+
};
|
|
51
|
+
export type SubagentRun = {
|
|
52
|
+
name: string;
|
|
53
|
+
/**
|
|
54
|
+
* The run's one lifecycle authority. `settled` means the final assistant
|
|
55
|
+
* message is in (the child's turn boundary, or the parent's
|
|
56
|
+
* `subagent.completed` fallback); a late child event — a HITL-parked
|
|
57
|
+
* turn resuming — explicitly reopens the run rather than mutating a
|
|
58
|
+
* completed section by accident.
|
|
59
|
+
*/
|
|
60
|
+
status: "running" | "settled";
|
|
61
|
+
/**
|
|
62
|
+
* One entry per logical "child message" — independent of the child's
|
|
63
|
+
* `stepIndex` field, which the harness can reuse across multiple
|
|
64
|
+
* assistant messages within a turn (e.g. a message before a tool call
|
|
65
|
+
* and another message after the tool result both arrive under
|
|
66
|
+
* `stepIndex: 0`). The key is a monotonic counter so each
|
|
67
|
+
* `message.completed` opens a new box on the next inbound delta.
|
|
68
|
+
*/
|
|
69
|
+
steps: Map<number, SubagentChildStep>;
|
|
70
|
+
/**
|
|
71
|
+
* Section currently accepting reasoning/message deltas. `null` means
|
|
72
|
+
* the next delta opens a new section.
|
|
73
|
+
*/
|
|
74
|
+
currentSectionKey: number | null;
|
|
75
|
+
/** Monotonic counter for new section keys. */
|
|
76
|
+
nextSectionKey: number;
|
|
77
|
+
tools: Map<string, SubagentToolState>;
|
|
78
|
+
};
|
|
79
|
+
export type SubagentStepUpdate = {
|
|
80
|
+
callId: string;
|
|
81
|
+
subagentName: string;
|
|
82
|
+
sectionKey: number;
|
|
83
|
+
reasoning: string;
|
|
84
|
+
message: string;
|
|
85
|
+
finalized: boolean;
|
|
86
|
+
};
|
|
87
|
+
export type SubagentToolUpdate = {
|
|
88
|
+
callId: string;
|
|
89
|
+
subagentName: string;
|
|
90
|
+
childCallId: string;
|
|
91
|
+
toolName: string;
|
|
92
|
+
input: unknown;
|
|
93
|
+
status: SubagentToolStatus;
|
|
94
|
+
output?: unknown;
|
|
95
|
+
errorText?: string;
|
|
96
|
+
};
|
|
97
|
+
export interface SubagentPumpOptions {
|
|
98
|
+
client?: Client;
|
|
99
|
+
view?: SubagentView;
|
|
100
|
+
formatActionResultError: (event: ActionResultStreamEvent) => string;
|
|
101
|
+
}
|
|
102
|
+
export declare class SubagentPump {
|
|
103
|
+
#private;
|
|
104
|
+
constructor(options: SubagentPumpOptions);
|
|
105
|
+
/**
|
|
106
|
+
* The moment a dispatch is known to be a subagent call, its section
|
|
107
|
+
* header replaces the parent-level tool row (or its still-preparing
|
|
108
|
+
* placeholder — subagent dispatches never upgrade one, since their
|
|
109
|
+
* actions are not tool-call kind). Without this the placeholder is
|
|
110
|
+
* swept at the step boundary and nothing shows until the child's first
|
|
111
|
+
* content arrives. Idempotent for SSE-resume re-entries, which only
|
|
112
|
+
* refresh the name.
|
|
113
|
+
*/
|
|
114
|
+
begin(called: SubagentCalledStreamEvent): void;
|
|
115
|
+
/**
|
|
116
|
+
* Parent reports subagent.completed. The child stream pump terminates
|
|
117
|
+
* itself on the child's own turn boundary — the authoritative finish
|
|
118
|
+
* signal, which already finalized the section — so this is a fallback
|
|
119
|
+
* for runs whose boundary never reached us (a dropped child stream, a
|
|
120
|
+
* HITL-parked turn resuming later). We do NOT abort the pump here,
|
|
121
|
+
* because the child's `message.completed` event may still be in flight
|
|
122
|
+
* (the parent and child streams are independent HTTP connections).
|
|
123
|
+
*/
|
|
124
|
+
settle(callId: string): void;
|
|
125
|
+
abortAll(): void;
|
|
126
|
+
}
|
|
127
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isAbortLikeError}from"./errors.js";import{toErrorMessage}from"#shared/errors.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";var SubagentPump=class{#e;#t;#n;#r=new Map;#i=new Map;constructor(e){this.#e=e.client,this.#t=e.view,this.#n=e.formatActionResultError}begin(e){let t=e.data.callId,n=this.#r.get(t);n===void 0?this.#r.set(t,{name:e.data.name,status:`running`,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map}):n.name=e.data.name,this.#t?.markChildToolCallId(t),this.#t?.begin({callId:t,name:e.data.name}),this.#a(e)}settle(e){this.#s(e)}abortAll(){for(let e of this.#i.values())e.abort();this.#i.clear(),this.#r.clear()}#a(r){let i=r.data.callId;if(this.#i.has(i))return;let a=this.#e;if(!a)return;let o=new AbortController;this.#i.set(i,o),(async()=>{let s=!1;try{let e=a.session({sessionId:r.data.childSessionId,streamIndex:0}).stream({signal:o.signal});for await(let t of e){if(o.signal.aborted)break;if(this.#l(i,t),isCurrentTurnBoundaryEvent(t)){s=!0;break}}}catch(n){if(!isAbortLikeError(n)){let e=toErrorMessage(n),r=this.#r.get(i);if(r){let{key:t,step:n}=openCurrentSubagentSection(r);n.message=n.message?`${n.message}\n\nstream error: ${e}`:`stream error: ${e}`,n.finalized=!0,r.currentSectionKey=null,this.#t?.upsertStep({callId:i,subagentName:r.name,sectionKey:t,reasoning:n.reasoning,message:n.message,finalized:!0})}}}finally{this.#i.delete(i)}s&&this.#s(i)})()}#o(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={preparing:0,"approval-requested":1,executing:2,done:3,failed:3,rejected:3};e[n.status]>e[r.status]&&(r.status=n.status),n.input!==void 0&&(r.input=n.input)}else t.tools.set(n.childCallId,i);this.#t?.markChildToolCallId(n.childCallId),this.#t?.upsertTool({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#s(e){let t=this.#r.get(e);if(!(!t||t.status===`settled`)){t.status=`settled`;for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#t?.upsertStep({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null,this.#c(e,t),this.#t?.complete({callId:e})}}#c(e,t){for(let[n,r]of t.tools)r.status===`preparing`&&(t.tools.delete(n),this.#t?.removeTool({callId:e,childCallId:n}))}#l(e,t){let n=this.#r.get(e);if(!n)return;n.status===`settled`&&(n.status=`running`,this.#t?.begin({callId:e,name:n.name}));let r=this.#t,emit=(t,i)=>{r?.upsertStep({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(),this.#c(e,n);break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#o(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.#o(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;switch(t.data.status){case`completed`:a.status=`done`,a.output=i.output;break;case`failed`:a.status=`failed`,a.errorText=this.#n(t);break;case`rejected`:a.status=`rejected`,a.errorText=this.#n(t);break}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?.upsertTool(o);break}default:break}}};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{SubagentPump};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { DevDiagnostics } from "../diagnostics.js";
|
|
2
|
-
import type { AgentTUIInputQuestion, AgentTUIInputQuestionResponse, AgentTUIRenderer, AgentTUISessionOptions, AgentTUIStreamResult, AgentTUIToolApprovalRequest, AgentTUIToolApprovalResponse, ConnectionAuthUpdate, SubagentStepUpdate, SubagentToolUpdate } from "./runner.js";
|
|
2
|
+
import type { AgentTUIInputQuestion, AgentTUIInputQuestionResponse, AgentTUIRenderer, AgentTUISessionOptions, AgentTUIStreamResult, AgentTUIToolApprovalRequest, AgentTUIToolApprovalResponse, ConnectionAuthUpdate, SubagentStepUpdate, SubagentView, SubagentToolUpdate } from "./runner.js";
|
|
3
3
|
import { type PromptCommandSpec } from "./prompt-commands.js";
|
|
4
4
|
import type { SetupFlowRenderer } from "./setup-flow.js";
|
|
5
5
|
import type { AssistantResponseStatsMode, LogDisplayMode, TerminalPartDisplayMode } from "./types.js";
|
|
@@ -66,12 +66,45 @@ export declare class TerminalRenderer implements AgentTUIRenderer {
|
|
|
66
66
|
readInputQuestion(question: AgentTUIInputQuestion, options?: AgentTUISessionOptions): Promise<AgentTUIInputQuestionResponse | undefined>;
|
|
67
67
|
upsertSubagentStep(update: SubagentStepUpdate): void;
|
|
68
68
|
upsertSubagentTool(update: SubagentToolUpdate): void;
|
|
69
|
+
removeSubagentTool(update: {
|
|
70
|
+
callId: string;
|
|
71
|
+
childCallId: string;
|
|
72
|
+
}): void;
|
|
73
|
+
/**
|
|
74
|
+
* The runner-facing subagent surface (see {@link SubagentView}); the
|
|
75
|
+
* public methods below are its implementation and the unit tests' seam.
|
|
76
|
+
*/
|
|
77
|
+
readonly subagents: SubagentView;
|
|
78
|
+
/**
|
|
79
|
+
* Opens a subagent's section as soon as the dispatch is announced, so the
|
|
80
|
+
* transcript flows from the `Delegate …` placeholder straight into the
|
|
81
|
+
* `※ subagent(<name>)` header instead of going blank until the child's
|
|
82
|
+
* first content streams in. Re-opening a completed section (a HITL-parked
|
|
83
|
+
* child resuming) clears its Done mark.
|
|
84
|
+
*/
|
|
85
|
+
beginSubagent(update: {
|
|
86
|
+
callId: string;
|
|
87
|
+
name: string;
|
|
88
|
+
}): void;
|
|
89
|
+
/**
|
|
90
|
+
* Marks a subagent call complete — its final message has arrived — so the
|
|
91
|
+
* section's closing corner reports `Done`. The header stays live until the
|
|
92
|
+
* turn finalizes (committing mid-turn would freeze its child window).
|
|
93
|
+
*/
|
|
94
|
+
completeSubagent(update: {
|
|
95
|
+
callId: string;
|
|
96
|
+
}): void;
|
|
69
97
|
markChildToolCallId(callId: string): void;
|
|
70
98
|
upsertConnectionAuth(update: ConnectionAuthUpdate): void;
|
|
71
99
|
setConnectionAuthPendingCount(count: number): void;
|
|
72
100
|
setVercelStatus(status: VercelStatusSnapshot): void;
|
|
73
101
|
setRemoteConnectionStatus(status: RemoteConnectionSnapshot): void;
|
|
74
102
|
reset(): void;
|
|
103
|
+
/**
|
|
104
|
+
* The mid-conversation session boundary: one opening-corner line marking
|
|
105
|
+
* where the server-side context was cut and a fresh session took over.
|
|
106
|
+
*/
|
|
107
|
+
renderSessionBoundary(): void;
|
|
75
108
|
/**
|
|
76
109
|
* Commits a single dim informational line to the transcript (e.g. the
|
|
77
110
|
* session-recovery notice after a terminal server failure). No-op when the
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{
|
|
2
|
-
`);if(this.#x){t!==this.#S&&(this.#S=t,this.#Xe({kind:`agent-header`,body:t,live:!1})),this.#ft();return}this.#x=!0,this.#S=t,this.#n.flush(this.#_t(),[])}async readPrompt(e){this.#Fe(e),this.#Ye(),this.#j=!0,this.#N={kind:`idle`},this.#P=``;let r=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#A.begin(r.text),this.#pe(r),this.#M=typeaheadFor(this.#d,r.text),this.#We(),this.#ft(),await new Promise((e,i)=>{let apply=e=>{r=e,this.#Ke(),this.#pe(r),this.#M=typeaheadFor(this.#d,e.text,this.#M),this.#ft()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#M=void 0,this.#Ge(),this.#Ie(),i(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=i=>{let a=applyLineEditorKey(r,i,{multiline:!0});if(a!==void 0){apply(a);return}switch(i.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#M=moveTypeaheadSelection(e,-1),this.#ft();break}let t=movePromptLine(r,`up`);t===void 0?recall(this.#A.previous(r.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#M=moveTypeaheadSelection(e,1),this.#ft();break}let t=movePromptLine(r,`down`);t===void 0?recall(this.#A.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#M=dismissTypeahead(e),this.#ft());break}case`enter`:{let i=highlighted(),a=i!==void 0&&parsePromptCommand(r.text)===null?typeaheadCompletion(i).trimEnd():r.text;this.#M=void 0,this.#A.add(a),this.#j=!1,this.#Ge(),this.#Je(),this.#P=STATUS.processing,isPromptControlCommand(a)?this.#Xe({kind:`command`,body:stripTerminalControls(a.trim()),live:!1}):(this.#Ze(a),this.#ce=a),this.#pe(EMPTY_LINE),this.#ft(),this.#Re(),e(a);break}case`ctrl-d`:r.text.length===0?interrupt():apply(deleteForward(r));break;case`ctrl-l`:this.#ht();break;case`ctrl-r`:this.#ft();break;case`ctrl-c`:r.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#Le()})}#pe(e){this.#O=e.text,this.#k=e.cursor}async renderStream(e,t){this.#Fe(t),this.#h.clear(),this.#j=!1,this.#N.kind!==`waiting`&&(this.#N={kind:`waiting`,startedAtMs:Date.now()}),this.#P=this.#T>0?STATUS.connectionAuth:STATUS.processing,this.#Qe(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#u?.recordPrompt(),this.#L=!1,this.#Q=void 0,this.#$=void 0,this.#ee=void 0,this.#te=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#qe(),this.#ft();let r=new Promise(e=>{this.#Y=e});this.#W=e=>this.#Ue(e),this.#Le();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.#it(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#$e(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#$e(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#Y=void 0,this.#L&&e.abort?.(),this.#Re(),this.#Ye(),this.#N.kind===`waiting`&&(this.#N={kind:`idle`}),this.#P=completedTurnStatus(this.#L,t?.continueSession===!0),this.#rt(),this.#u?.reportStats(),this.#ft(),t?.continueSession||this.#Ie()}}async readToolApproval(e,t){return this.#Fe(t),this.#Ye(),this.#j=!1,this.#N={kind:`idle`},this.#P=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#L=!1,this.#ft(),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.#Je(),this.#P=STATUS.processing,this.#Re(),this.#ft(),t({approved:!0})):n===`n`&&(this.#Je(),this.#P=STATUS.processing,this.#me(e.toolCallId),this.#Re(),this.#ft(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#ft();break;case`ctrl-c`:this.#L=!0,this.#Ie(),n(interruptedError());break;default:break}},this.#Le()})}async readInputQuestion(e,t){this.#Fe(t),this.#Ye(),this.#j=!1,this.#N={kind:`idle`},this.#L=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`select`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,renderSection=()=>{this.#tt({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,c,this.#r),preformatted:!0,live:!0})},repaintStatus=()=>{if(s===`select`){let e=isOnFreeformRow()?`type`:`select`;this.#P=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#j=!1}else this.#j=!0,this.#pe(l),this.#P=``;this.#ft()};renderSection(),s===`text`&&this.#We(),repaintStatus();let finalize=t=>{this.#tt({id:o,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.#Je(),this.#P=STATUS.processing,this.#Ge(),this.#Re(),this.#ft();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=o=>{if(o.type===`ctrl-c`){if(s===`text`&&l.text.length>0){l=EMPTY_LINE,this.#Ke(),repaintStatus();return}this.#L=!0,this.#Ge(),this.#Ie(),i(interruptedError());return}if(o.type===`ctrl-r`){this.#ft();return}if(s===`select`){switch(o.type){case`up`:case`ctrl-p`:a>0&&(c=(c-1+a)%a,renderSection(),repaintStatus());break;case`down`:case`ctrl-n`:a>0&&(c=(c+1)%a,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){s=`text`,l=EMPTY_LINE,this.#We(),repaintStatus();break}let e=n[c];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}let u=applyLineEditorKey(l,o,{multiline:!0});if(u!==void 0){l=u,this.#Ke(),repaintStatus();return}switch(o.type){case`up`:case`down`:{let e=movePromptLine(l,o.type);e!==void 0&&(l=e,this.#Ke(),repaintStatus());break}case`enter`:{let n=resolveQuestionText(l.text,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(r){if(l.text.length>0){l=EMPTY_LINE,this.#Ke(),repaintStatus();break}s=`select`,l=EMPTY_LINE,this.#j=!1,this.#Ge(),repaintStatus();break}l=EMPTY_LINE,this.#Ke(),repaintStatus();break;default:break}},this.#Le()})}upsertSubagentStep(e){if(this.#u?.recordSubagentDispatch(e.callId),this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#et(e.callId,e.subagentName),this.#o===`collapsed`){this.#ft();return}this.#tt({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:n,live:!e.finalized}),this.#ft()}}upsertSubagentTool(e){if(this.#u?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#u?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#o===`hidden`)return;if(this.#et(e.callId,e.subagentName),this.#o===`collapsed`){this.#ft();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.#tt(n),this.#ft()}markChildToolCallId(e){this.#_.add(e);let t=this.#v.get(e);t!==void 0&&(this.#nt(t),this.#v.delete(e),this.#ft())}#me(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=connectionAuthTerminalMessage(e.state);this.#tt({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#ft()}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.#ft()):n&&(this.#P=STATUS.processing,this.#ft())}setVercelStatus(e){this.#E=e,this.#ft()}setRemoteConnectionStatus(e){this.#D=e,this.#ft()}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.#ce=void 0,this.#oe=void 0,this.#T=0,this.#Q=void 0,this.#$=void 0,this.#ee=void 0,this.#te=void 0,this.#I&&(this.#n.clearAll(),this.#ft())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Fe(),this.#Xe({kind:`notice`,body:t,live:!1}),this.#ft())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#u?.append({source:`sandbox`,detail:t}),this.#Fe(),this.#Xe({kind:`sandbox`,body:t,live:!1}),this.#ft())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#he();return}this.#Fe(),this.#ue=t,this.#ft()}clearSetupWarning(){this.#he()}#he(){this.#ue!==void 0&&(this.#ue=void 0,this.#ft())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#Fe();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Xe(r),this.#ft()}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Fe(),this.#Xe({kind:`result`,body:t,live:!1}),this.#ft())}#ge(e,t=`spinner`){this.#Fe(),this.#j=!1,this.#N={kind:`idle`},this.#P=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#le={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#qe(),this.#ft()}#_e(e){this.#de=void 0,this.#je();let t=this.#le;if(t!==void 0){if(this.#le=void 0,this.#Ye(),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.#Xe({kind:`flow`,title:`info`,body:e.join(`
|
|
3
|
-
`),live:!1}),this.#
|
|
4
|
-
`,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#Ce(e){let t=this.#Te(),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.#We(),this.#ft(),await this.#Oe((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Ke(),this.#ft()},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.#ft();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#ft();return}i(t);return}default:return}},()=>this.#Ge()).promise}async#we(e){let t=this.#Te();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#ft(),await this.#Oe((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#ft();return;default:return}}).promise}#Te(){return this.#Fe(),this.#j=!1,this.#N={kind:`idle`},this.#P=``,this.#Ee()}#Ee(){return this.#le===void 0&&(this.#le={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[]}),this.#le}#De(){this.#le!==void 0&&(this.#le.question=void 0,this.#le.hideLinesWhileQuestion=!1),this.#W=void 0,this.#Re(),this.#Ae(),this.#ft()}#Oe(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#De(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#De(),i(e))};return this.#W=t=>e(t,settle,reject),this.#Le(),{promise:a,settle}}#ke(){let e,t=new Promise(t=>{e=t});return this.#de=e,this.#Ae(),{promise:t,dispose:()=>{this.#de===e&&(this.#de=void 0,this.#je())}}}#Ae(){if(this.#de===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#de;this.#de=void 0,this.#je(),e?.();return}e.type===`ctrl-r`&&this.#ft()};this.#fe=consumer,this.#W=consumer,this.#Le()}#je(){this.#fe!==void 0&&(this.#W===this.#fe&&this.#Re(),this.#fe=void 0)}#Me(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e)}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis)};if(this.#le!==void 0){this.#le.status=t,t===void 0&&(this.#le.preview=void 0),this.#ft();return}if(t===void 0){this.#N={kind:`idle`},this.#P=``,this.#Ye(),this.#ft();return}this.#Fe(),this.#Je(),this.#P=t.text,this.#ft()}#Ne(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#le;if(r!==void 0){if(r.preview=void 0,t===`warning`||t===`error`)for(let e of r.outputBuffer)r.lines.push({text:e,tone:`info`,evidence:!0});r.outputBuffer=[],r.lines.push({text:n,tone:t}),this.#ft();return}this.#Fe(),this.#Xe({kind:`flow`,title:t,body:n,live:!1}),this.#ft()}#Pe(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#le;if(n===void 0){this.#Ne(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#ft()}shutdown(){this.#Ie()}#Fe(e){this.#F=e?.title??this.#F,!this.#I&&(this.#I=!0,this.#n.reset(),this.#n.hideCursor(),this.#Ot(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#J=()=>this.#ft(),this.#t.on(`resize`,this.#J))}#Ie(){this.#Re(),this.#Ge(),this.#Ye(),this.#H!==void 0&&(clearTimeout(this.#H),this.#H=void 0),this.#U=!1,this.#I&&=(this.#Lt(),this.#ft(),this.#n.clear(),this.#n.showCursor(),this.#kt(),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)}#Le(){this.#e.off(`data`,this.#ze),this.#e.on(`data`,this.#ze)}#Re(){this.#e.off(`data`,this.#ze),this.#He(),this.#G=``,this.#K=new StringDecoder(`utf8`),this.#W=void 0}#ze=e=>{this.#He(),this.#G+=this.#K.write(e),this.#Ve(),this.#Be()};#Be(){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?.()}}#Ve(){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)}}#He(){this.#q&&=(clearTimeout(this.#q),void 0)}#Ue(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#ft();break;case`ctrl-c`:this.#L||(this.#L=!0,this.#N={kind:`idle`},this.#P=`Interrupted`,this.#Y?.(),this.#ft());break;default:break}}#We(){this.#Ge(),this.#Ke(),this.#B=setInterval(()=>{this.#R=!this.#R,this.#ft()},500),this.#B.unref?.()}#Ge(){this.#B&&=(clearInterval(this.#B),void 0),this.#R=!0}#Ke(){this.#R=!0}#qe(){this.#Ye(),this.#V=setInterval(()=>{this.#z+=1,this.#ft()},90),this.#V.unref?.()}#Je(){this.#N={kind:`waiting`,startedAtMs:Date.now()},this.#qe()}#Ye(){this.#V&&=(clearInterval(this.#V),void 0)}#Xe(e){e.id!==this.#oe?.id&&this.#Lt(),this.#p.push(e),e.id&&this.#m.set(e.id,e)}#Ze(e){this.#Xe({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#ft()}#Qe(e){if(e!=null){if(this.#ce===e){this.#ce=void 0;return}this.#Xe({kind:`user`,body:stripTerminalControls(e),live:!1})}}#$e(e,t,n={}){let r=stripTerminalControls(e),i=stripTerminalControls(t),a=n.detail===void 0?void 0:stripTerminalControls(n.detail),o=n.hint===void 0?void 0:stripTerminalControls(n.hint),s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#u?.append(o===void 0?s:{...s,hint:o});let c={kind:`error`,title:r,body:i,live:!1};o!==void 0&&(c.hint=o),a!==void 0&&(c.detail=this.#u===void 0?a:`details: ${this.#u.displayPath}`),this.#Xe(c),this.#ft()}#et(e,t){this.#y.has(e)||(this.#y.add(e),this.#Xe({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#tt(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.#Xe(e)}#nt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#rt(){for(let e of this.#p)e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#it(e,t,n){switch(e.type){case`step-start`:this.#at(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#u?.recordStepUsage(e.usage),this.#dt(e.usage),this.#ft();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);this.#ot(t),this.#at(STATUS.streaming),n.text.set(e.id,t),this.#st(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.#ot(r),n.text.set(e.id,r),this.#st(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);this.#ot(r),this.#at(STATUS.streaming),n.reasoning.set(e.id,r),this.#ct(e.id,r,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#ot(r),this.#ct(e.id,r,!1,t);break}case`tool-call`:if(this.#u?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#at(STATUS.executingTools),this.#lt({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.#lt({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#ut(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#at(STATUS.toolResults),this.#lt({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#ut(e.toolCallId,n);if(this.#u?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;n.hasPendingToolResults=!0,this.#at(STATUS.toolResults),this.#lt({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#$e(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`finish`:this.#dt(e.usage),this.#ft();break}}#at(e){let t=this.#T>0?STATUS.connectionAuth:e;this.#P!==t&&(this.#P=t,this.#ft())}#ot(e){e.trim().length>0&&(this.#N={kind:`answering`})}#st(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#tt({id:e,kind:`assistant`,body:r,live:n}),this.#ft())}#ct(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#tt({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#ft())}#lt(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.#tt(renderNativeToolBlock(e,r,t.tools===`full`)),this.#ft()}#ut(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`}}#dt(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#Q=(t??0)+(n??0)),this.#$=n??this.#$,this.#$!=null&&this.#te!==void 0){let e=(Date.now()-this.#te)/1e3;e>0&&(this.#ee=this.#$/e)}}#ft(){if(this.#I){if(this.#X){this.#Z=!0;return}this.#X=!0;try{do this.#Z=!1,this.#pt();while(this.#Z)}finally{this.#X=!1}}}#pt(){if(!this.#I)return;let e=this.#Et(),t=this.#St(e),n=Math.max(1,this.#Dt()-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.#vt(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.#vt(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)}#mt(){if(!this.#I)return;let e=this.#Et(),t=this.#St(e),n=Math.max(1,this.#Dt()-t.length),r=this.#w,i=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#vt(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.#_t(),...this.#C],a)}logDisplayMode(){return this.#f}setLogDisplayMode(e){e!==this.#f&&(this.#f=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#gt(),this.#I&&this.#mt())}flushDelayedDevBuildErrors(){let e=this.#ae;e!==void 0&&(this.#ae=void 0,this.#Xe({kind:`log`,title:`stderr`,body:e,live:!1}),this.#ft())}#ht(){this.#U=!0,this.#H!==void 0&&clearTimeout(this.#H),this.#H=setTimeout(()=>{this.#U=!1,this.#H=void 0,this.#ft()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#f)),this.#ft()}#gt(){let e=this.#Et();this.#C.length=0;let t;for(let n of this.#g){if(this.#zt(n))continue;let r=this.#vt(n,e,t);t=previousBlockOf(n),this.#C.push(...r)}this.#w=t}#_t(){let e=this.#b;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#Et()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#vt(e,t,n){let r={spinner:this.#yt()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#yt(){return this.#r.spinner[this.#z%this.#r.spinner.length]??``}#bt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#xt(e,t){return e.indicator.kind===`spinner`?{glyph:this.#yt(),color:`yellow`}:{glyph:this.#bt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#St(e){let n=this.#r.colors,r=[``],i=this.#le;if(i!==void 0){let t=this.#xt(i,i.status),n=i.status===void 0?void 0:{...i.status,indicator:t},a;if(i.question!==void 0){let t=i.question(e);a={kind:`question`,rows:t},n!==void 0&&(a={kind:`question`,rows:t,status:n})}else n===void 0?a=i.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:i.preview,indicator:t}:(a={kind:`status`,status:n},i.preview!==void 0&&(a={kind:`status`,status:n,preview:i.preview}));let o={title:i.title,lines:i.hideLinesWhileQuestion===!0?[]:i.lines,content:a};return r.push(...renderFlowPanel(o,this.#r,e)),this.#wt(r,e),r}if(this.#ue!==void 0&&r.push(...renderAttentionRows(this.#ue,e,this.#r),``),this.#j){let i=this.#M===void 0?void 0:inlineCommandHint(this.#M);i===void 0&&this.#M!==void 0&&isTypeaheadOpen(this.#M)&&r.push(...renderCommandSuggestions(this.#M,this.#r,e));let a=isPromptControlCommand(this.#O),o=i?n.dim(` ${i}`):``,s=[];this.#Ct(s,e);let c=Math.max(1,this.#Dt()-1-r.length-1-s.length);return r.push(...promptInputRows({text:this.#O,cursor:this.#k,width:e,theme:this.#r,caretVisible:this.#R,isCommand:a,ghost:o,maxRows:c})),r.push(...s),r}let a=this.#N;if(a.kind===`answering`)return this.#Ct(r,e),r;let s=a.kind===`waiting`,c=s?n.green(this.#bt(a.startedAtMs,this.#r.unicode?`⊙`:`o`)):n.dim(this.#r.glyph.dot),d=this.#P.length>0?this.#P:`Ready`,p=s?n.dim(d):d,m=this.#Tt(),h=s?` `:``,g=m?`${h}${c} ${p} ${n.dim(this.#r.glyph.dot)} ${m}`:`${h}${c} ${p}`;r.push(clip(g,e));let _=[];return this.#Ct(_,e),s&&_.length>0&&r.push(``),r.push(..._),r}#Ct(e,t){let n=this.#D===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#r,width:r};this.#U&&(i.logLevel=this.#f);let a=this.#b?.serverUrl;if(a!==void 0&&this.#D===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#b?.info?.agent.model;o?.id!==void 0&&(i.model=o.id),o?.reasoning!==void 0&&o.reasoning!==`provider-default`&&(i.reasoning=o.reasoning),readGatewayServiceTier(o?.providerOptions).kind===`priority`&&(i.fastMode=!0);let s=o?.endpoint;s!==void 0&&(i.endpoint=s),this.#E!==void 0&&(i.vercel=this.#E),this.#D!==void 0&&(i.remote=this.#D);let c=buildStatusLine(i);c!==void 0&&e.push(clip(`${n}${c}`,t))}#wt(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))}#Tt(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Q,outputTokens:this.#$,tokensPerSecond:this.#ee},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#Et(){return Math.max(20,this.#t.columns||80)}#Dt(){return Math.max(8,this.#t.rows||24)}#Ot(){if(this.#ne!==void 0||!this.#l)return;this.#re=``,this.#ie=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#jt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#u?.subscribeLogRecords(e=>this.#At(e)),this.#ne=()=>{this.#u?.unsubscribeLogRecords(),e(),t()}}#kt(){let e=this.#ne;e!==void 0&&(this.#ne=void 0,e(),this.#re.length>0&&(this.#u?.append({source:`stdout`,detail:this.#re}),this.#Rt(`stdout`)&&process.stdout.write(`${this.#re}\n`),this.#re=``),this.#ie.length>0&&(this.#u?.append({source:`stderr`,detail:this.#ie}),this.#Rt(`stderr`)&&process.stderr.write(`${this.#ie}\n`),this.#ie=``))}#At(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#Nt(`[eve:${e.namespace}] ${e.message}${t}`),this.#ft()}#jt(e,t){let n=(e===`stdout`?this.#re:this.#ie)+t,r=n.lastIndexOf(`
|
|
5
|
-
`),
|
|
6
|
-
`);
|
|
7
|
-
`)
|
|
8
|
-
`)
|
|
9
|
-
`);
|
|
10
|
-
`);
|
|
1
|
+
import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.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{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{interruptedError}from"./errors.js";import{FileContentCache}from"./file-content-cache.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{initialModelEditorState,transitionModelEditor}from"./model-editor.js";import{promptPlaceholder}from"./prompt-placeholder.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{enterBadge,renderAcknowledgeQuestion,renderFlowPanel,renderModelEditorQuestion,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{TurnClock}from"./turn-clock.js";import{allTodoItemsSettled,readTodoToolItems,renderFinishedTodoRows,renderTodoPanelRows}from"./todo-panel.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{inspectError}from"#internal/logging.js";import{eveVersionTag}from"#cli/banner.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{LiveRegion}from"#cli/ui/live-region.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";import{readGatewayServiceTier}from"#shared/gateway-service-tier.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e,t){return e?`Interrupted`:t?`Ready`:`Done`}const STATUS={processing:`Working…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=[];#m=new Map;#h=new Set;#g=[];#_=new Set;#v=new Map;#y=0;#b=new Map;#x=new FileContentCache;#S=new Set;#C;#w=!1;#T;#E=[];#D;#O=0;#k;#A;#j=``;#M=0;#N=new PromptHistory;#P=!1;#F;#I=!1;#L=Date.now();#R=!1;#z=new TurnClock;#B=EMPTY_LINE;#V=!1;#H={kind:`idle`};#U;#W=STATUS.processing;#G;#K=`eve`;#q=!1;#J=!1;#Y=!1;#X=!1;#Z=!0;#Q=0;#$=Date.now();#ee;#te;#ne;#re=!1;#ie;#ae=``;#oe=new StringDecoder(`utf8`);#se;#ce;#le;#ue=!1;#de=!1;#fe;#pe;#me;#he;#ge;#_e;#ve;#ye=``;#be=``;#xe;#Se;#Ce=0;#we;#Te;#Ee;#De;#Oe;#ke;#Ae;#je;setupFlow={begin:(e,t)=>this.#Le(e,t),end:e=>this.#Re(e?.preserveDiagnostics??!0),readSelect:e=>this.#ze(e),readEditableSelect:e=>this.#Ve(e),readProviderPicker:e=>this.#He(e),readModelEditor:e=>this.#Ue(e),readText:e=>this.#We(e),readAcknowledge:e=>this.#Ge(e),readChoice:e=>this.#Be(e),setStatus:e=>this.#$e(e),renderLine:(e,t)=>this.#et(e,t),renderOutput:e=>this.#tt(e),waitForInterrupt:()=>this.#Xe()};constructor(t){this.#e=t?.input??process.stdin,this.#t=t?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:t?.color??!0,unicode:t?.unicode??detectUnicode()}),this.#i=t?.tools??`auto-collapsed`,this.#a=t?.reasoning??`auto-collapsed`,this.#o=t?.subagents??`auto-collapsed`,this.#s=t?.connectionAuth??`full`,this.#c=t?.assistantResponseStats??`tokensPerSecond`,this.#me=t?.contextSize,this.#l=t?.captureForeignOutput??this.#t===process.stdout,this.#u=t?.diagnostics,this.#f=t?.logs??`none`,this.#d=t?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#K=e.name,this.#C=e,this.#nt();let t=this.#Ut().join(`
|
|
2
|
+
`);if(this.#w){t!==this.#T&&(this.#T=t,this.#_t({kind:`agent-header`,body:t,live:!1})),this.#Rt();return}this.#w=!0,this.#T=t,this.#n.flush(this.#Ut(),[])}async readPrompt(e){this.#nt(e),this.#gt(),this.#yt(),this.#P=!0,this.#I=!0,this.#H={kind:`idle`},this.#W=``;let r=lineOf(stripPromptControlCharacters(e?.initialDraft??this.#B.text));return this.#B=EMPTY_LINE,this.#N.begin(r.text),this.#Me(r),this.#F=typeaheadFor(this.#d,r.text),this.#dt(),this.#Rt(),await new Promise((e,i)=>{this.#U=i;let apply=e=>{r=e,this.#pt(),this.#Me(r),this.#F=typeaheadFor(this.#d,e.text,this.#F),this.#Rt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#F=void 0,this.#ft(),this.#rt(),i(interruptedError())},suggestions=()=>this.#F!==void 0&&isTypeaheadOpen(this.#F)?this.#F:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ie=i=>{let a=applyLineEditorKey(r,i,{multiline:!0});if(a!==void 0){apply(a);return}switch(i.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#F=moveTypeaheadSelection(e,-1),this.#Rt();break}let t=movePromptLine(r,`up`);t===void 0?recall(this.#N.previous(r.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#F=moveTypeaheadSelection(e,1),this.#Rt();break}let t=movePromptLine(r,`down`);t===void 0?recall(this.#N.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#F=dismissTypeahead(e),this.#Rt());break}case`enter`:{let i=highlighted(),a=i!==void 0&&parsePromptCommand(r.text)===null?typeaheadCompletion(i).trimEnd():r.text;if(a.trim().length===0)break;this.#F=void 0,this.#N.add(a),this.#P=!1,this.#ft(),this.#W=STATUS.processing,isPromptControlCommand(a)?this.#_t({kind:`command`,body:stripTerminalControls(a.trim()),live:!1}):(this.#ht(),this.#vt(a),this.#we=a,this.#z.arm()),this.#Me(EMPTY_LINE),this.#Rt(),this.#at(),e(a);break}case`ctrl-d`:r.text.length===0?interrupt():apply(deleteForward(r));break;case`ctrl-l`:this.#Vt();break;case`ctrl-r`:this.#Rt();break;case`ctrl-c`:r.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#it()})}#Me(e){this.#j=e.text,this.#M=e.cursor}async renderStream(e,t){this.#nt(t),this.#h.clear(),this.#P=!1,this.#H.kind!==`waiting`&&(this.#H={kind:`waiting`,startedAtMs:Date.now()}),this.#W=this.#O>0?STATUS.connectionAuth:STATUS.processing,this.#bt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#u?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#z.armed&&this.#z.arm(),this.#X=!1,this.#fe=void 0,this.#pe=void 0,this.#he=void 0,this.#ge=void 0,this.#_e=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#mt(),this.#V=!0,this.#Rt();let r=new Promise(e=>{this.#le=e});this.#ie=e=>this.#ut(e),this.#it();let i={text:new Map,reasoning:new Map,tools:new Map};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#X)break;this.#Et(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#xt(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#xt(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#le=void 0,this.#X&&e.abort?.(),this.#at(),this.#gt(),this.#V=!1,this.#H.kind===`waiting`&&(this.#H={kind:`idle`}),this.#W=completedTurnStatus(this.#X,t?.continueSession===!0),this.#Nt(i),this.#X&&this.#Mt(),this.#Tt(),this.#u?.reportStats(),this.#Rt(),t?.continueSession||this.#rt()}}async readToolApproval(e,t){return this.#nt(t),this.#gt(),this.#P=!1,this.#H={kind:`idle`},this.#W=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#X=!1,this.#Rt(),await new Promise((t,n)=>{this.#U=n,this.#ie=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#ht(),this.#W=STATUS.processing,this.#at(),this.#Rt(),t({approved:!0})):n===`n`&&(this.#ht(),this.#W=STATUS.processing,this.#Pe(e.toolCallId),this.#at(),this.#Rt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#Rt();break;case`ctrl-c`:this.#X=!0,this.#rt(),n(interruptedError());break;default:break}},this.#it()})}async readInputQuestion(e,t){this.#nt(t),this.#gt(),this.#P=!1,this.#I=!1,this.#H={kind:`idle`},this.#X=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`overlay`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,overlayPanel=t=>renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#Z},this.#r,t),renderTextSection=()=>{this.#Ct({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#r),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#dt():(this.#ft(),this.#pt())};s===`overlay`?(s=`overlay`,this.#P=!1,this.#wt(o),this.#Te=overlayPanel,this.#W=``,syncFreeformCaret(),this.#Rt()):(s=`text`,this.#Te=void 0,renderTextSection(),this.#P=!0,this.#Me(l),this.#W=``,this.#dt(),this.#Rt());let finalize=t=>{this.#Te=void 0,this.#Ct({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#r.colors.dim(this.#r.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#P=!1,this.#ht(),this.#W=STATUS.processing,this.#ft(),this.#at(),this.#Rt();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Te=void 0,this.#Ct({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#r.colors.dim(this.#r.glyph.elbow)} ${this.#r.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#P=!1,this.#W=``,this.#ft(),this.#at(),this.#Rt(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#Rt())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#U=r,u=t,this.#ie=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#pt(),s===`text`&&this.#Me(l),this.#Rt();return}this.#X=!0,this.#Te=void 0,this.#ft(),this.#rt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#Rt();return}if(s===`overlay`){switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#pt(),this.#Rt();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#pt(),this.#Rt());break}if(t.type===`text`&&/^[1-9]$/u.test(t.value)){let e=Number(t.value)-1;e<n.length?selectOptionAt(e):e===n.length&&i&&(c=e,syncFreeformCaret(),this.#Rt())}break}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#pt(),this.#Me(l),this.#Rt();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#pt(),this.#Me(l),this.#Rt());break}case`enter`:{let t=resolveQuestionText(l.text,e);if(t===void 0)break;u(finalize(t));break}case`escape`:if(l.text.length>0){l=EMPTY_LINE,this.#pt(),this.#Me(l),this.#Rt();break}dismiss();break;default:break}},this.#it()})}upsertSubagentStep(e){if(this.#u?.recordSubagentDispatch(e.callId),this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#St(e.callId,e.subagentName),this.#o===`collapsed`){this.#Rt();return}this.#Ct({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#o!==`full`,live:!e.finalized}),this.#Rt()}}upsertSubagentTool(e){if(this.#u?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#u?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#o===`hidden`)return;if(this.#St(e.callId,e.subagentName),this.#o===`collapsed`){this.#Rt();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#At({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#Ct(r),this.#Ne(e.callId),this.#Rt()}#Ne(e){applyCohortLiveness(this.#p.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#wt(subagentToolSectionId(e.callId,e.childCallId)),this.#Rt()}subagents={begin:e=>this.beginSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#o===`hidden`)return;this.#St(e.callId,e.name);let t=this.#m.get(subagentHeaderId(e.callId));t?.status===`done`&&delete t.status,this.#Rt()}completeSubagent(e){let t=this.#m.get(subagentHeaderId(e.callId));t!==void 0&&(t.status=`done`,this.#Rt())}markChildToolCallId(e){this.#_.add(e);let t=this.#v.get(e);t!==void 0&&(this.#wt(t),this.#v.delete(e),this.#Rt())}#Pe(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=connectionAuthTerminalMessage(e.state);this.#Ct({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#Rt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#O)return;let n=this.#O>0;this.#O=t,t>0?(this.#W=STATUS.connectionAuth,this.#Rt()):n&&(this.#W=STATUS.processing,this.#Rt())}setVercelStatus(e){this.#k=e,this.#Rt()}setRemoteConnectionStatus(e){this.#A=e,this.#Rt()}reset(){this.#p=[],this.#m.clear(),this.#h.clear(),this.#D=void 0,this.#E.length=0,this.#g.length=0,this.#w=!1,this.#T=void 0,this.#Fe(),this.#R=!1,this.#we=void 0,this.#Se=void 0,this.#O=0,this.#fe=void 0,this.#pe=void 0,this.#he=void 0,this.#ge=void 0,this.#_e=void 0,this.#q&&(this.#n.clearAll(),this.#Rt())}renderSessionBoundary(){this.#yt(),this.#Fe();let e=this.#r.colors,t=this.#r.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#_t({kind:`session-boundary`,body:n,live:!1}),this.#Rt()}#Fe(){this.#_.clear(),this.#v.clear(),this.#S.clear(),this.#b.clear(),this.#Oe=void 0,this.#ke=void 0,this.#x.clear(),this.#z.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#nt(),this.#_t({kind:`notice`,body:t,live:!1}),this.#Rt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#u?.append({source:`sandbox`,detail:t}),this.#nt(),this.#_t({kind:`sandbox`,body:t,live:!1}),this.#Rt())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#Ie();return}this.#nt(),this.#De=t,this.#Rt()}clearSetupWarning(){this.#Ie()}#Ie(){this.#De!==void 0&&(this.#De=void 0,this.#Rt())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#nt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#_t(r),this.#Rt()}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#nt(),this.#_t({kind:`result`,body:t,live:!1}),this.#Rt())}#Le(e,t=`spinner`){this.#nt(),this.#P=!1,this.#H={kind:`idle`},this.#W=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ee={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#mt(),this.#Rt()}#Re(e){this.#Ae=void 0,this.#Qe();let t=this.#Ee;if(t!==void 0){if(this.#Ee=void 0,this.#gt(),e){let e=[];for(let n of t.lines){if(n.evidence===!0){e.push(n.text);continue}(n.tone===`warning`||n.tone===`error`)&&(e.length>0&&this.#_t({kind:`flow`,title:`info`,body:e.join(`
|
|
3
|
+
`),live:!1}),this.#_t({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#Rt()}}async#ze(e){let t=this.#Ke(),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.#Rt()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#Rt();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.#Rt())}},u=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));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.#Gt()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#Rt(),await this.#Ye((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.#Rt();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.#Rt();return;case`update`:o=d.select,s=void 0,this.#Rt();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.#Rt();return;case`ignore`:return}}).promise}#Be(e){this.#nt();let t=this.#qe();t.status={kind:`progress`,text:stripTerminalControls(e.status)};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#Rt();let r=this.#Ye((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.#Rt();return;case`repaint`:this.#Rt();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#Ve(e){let t=this.#Ke(),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.#Z,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.#dt():(i=lineOf(``),this.#ft())};return syncEditableRow(),this.#Rt(),await this.#Ye((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#pt(),this.#Rt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#Rt()},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.#Rt();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.#Rt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#ft()).promise}async#He(e){let t=this.#Ke(),n=initialProviderPickerState(e.options,e.initialValue),r,cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor),r=e.options.find(e=>e.value===t);if(r!==void 0)return enterBadge(this.#r,r.checked===!0?`change`:void 0)};t.question=t=>{let r=cursorBadge(),i={kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#Z,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#r,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#dt():this.#ft()};return syncCaret(),this.#Rt(),await this.#Ye((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.#Rt();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#Rt();return;case`validate`:{n=o.state,syncCaret(),this.#Rt();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.#Rt();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.#pt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#ft()}).promise}async#Ue(e){let t=this.#Ke(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#r,t),this.#Rt(),await this.#Ye((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#Rt();return;case`cancel`:r(void 0);return;case`settle`:r(i.result);return}},i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:i.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#Rt();return;case void 0:break}if(t.type===`left`||t.type===`right`){dispatch({type:`adjust`,direction:t.type});return}if(t.type===`tab`){dispatch({type:`adjust`,direction:`right`});return}if(t.type===`backspace`){dispatch({type:`backspace`});return}if(t.type===`text`)for(let e of t.value.replaceAll(`
|
|
4
|
+
`,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#We(e){let t=this.#Ke(),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.#Z)},this.#dt(),this.#Rt(),await this.#Ye((t,i)=>{let apply=e=>{n=e,r=void 0,this.#pt(),this.#Rt()},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.#Rt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#Rt();return}i(t);return}default:return}},()=>this.#ft()).promise}async#Ge(e){let t=this.#Ke();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#Rt(),await this.#Ye((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#Rt();return;default:return}}).promise}#Ke(){return this.#nt(),this.#P=!1,this.#H={kind:`idle`},this.#W=``,this.#qe()}#qe(){return this.#Ee===void 0&&(this.#Ee={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Ee}#Je(){this.#Ee?.implicit===!0?this.#Ee=void 0:this.#Ee!==void 0&&(this.#Ee.question=void 0,this.#Ee.hideLinesWhileQuestion=!1),this.#ie=void 0,this.#at(),this.#Ee!==void 0&&this.#Ze(),this.#Rt()}#Ye(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Je(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Je(),i(e))};return this.#lt(),this.#ie=t=>e(t,settle,reject),this.#it(),{promise:a,settle}}#Xe(){let e,t=new Promise(t=>{e=t});return this.#Ae=e,this.#Ze(),{promise:t,dispose:()=>{this.#Ae===e&&(this.#Ae=void 0,this.#Qe())}}}#Ze(){if(this.#Ae===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#Ae;this.#Ae=void 0,this.#Qe(),e?.();return}e.type===`ctrl-r`&&this.#Rt()};this.#je=consumer,this.#lt(),this.#ie=consumer,this.#it()}#Qe(){this.#je!==void 0&&(this.#ie===this.#je&&this.#at(),this.#je=void 0)}#$e(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e)}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis)};if(this.#Ee!==void 0){this.#Ee.status=t,t===void 0&&(this.#Ee.preview=void 0),this.#Rt();return}if(!(this.#P||this.#V)){if(t===void 0){this.#H={kind:`idle`},this.#G=void 0,this.#gt(),this.#Rt();return}this.#nt(),this.#ht(),this.#G=t.text,this.#Rt()}}#et(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Ee;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.#Rt();return}this.#nt(),this.#_t({kind:`flow`,title:t,body:n,live:!1}),this.#Rt()}#tt(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Ee;if(n===void 0){this.#et(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#Rt()}shutdown(){this.#rt(),this.#J&&!this.#Y&&(this.#Y=!0,this.#t.write(`${this.#r.colors.dim(eveVersionTag())}\n`))}#nt(e){this.#K=e?.title??this.#K,e?.contextSize!==void 0&&(this.#me=e.contextSize),!this.#q&&(this.#q=!0,this.#J=!0,this.#n.reset(),this.#n.hideCursor(),this.#an(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#ce=()=>this.#Rt(),this.#t.on(`resize`,this.#ce))}#rt(){let e=this.#U;if(this.#U=void 0,e?.(interruptedError()),this.#at(),this.#ft(),this.#gt(),this.#ne!==void 0&&(clearTimeout(this.#ne),this.#ne=void 0),this.#re=!1,this.#q){this.#mn();for(let e of this.#p)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#Rt(),this.#n.clear(),this.#n.showCursor(),this.#on(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#ce&&=(this.#t.off(`resize`,this.#ce),void 0),this.#q=!1}}#it(){this.#e.off(`data`,this.#ot),this.#e.on(`data`,this.#ot),this.#ae.length>0&&queueMicrotask(()=>{this.#ie!==void 0&&this.#ae.length>0&&(this.#ct(),this.#st())})}#at(){this.#e.off(`data`,this.#ot),this.#lt(),this.#ie=void 0}#ot=e=>{this.#lt(),this.#ae+=this.#oe.write(e),this.#ct(),this.#st()};#st(){if(this.#ae===`\x1B`){this.#se=setTimeout(()=>{this.#ae===`\x1B`&&(this.#ae=``,this.#ie?.({type:`escape`}))},30),this.#se.unref?.();return}if(isIncompletePaste(this.#ae)){let e=this.#ae;this.#se=setTimeout(()=>{if(this.#ae!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#ae=``,t.length>0&&this.#ie?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#se.unref?.()}}#ct(){for(;this.#ae.length>0;){let e=nextKey(this.#ae);if(e.incomplete)return;this.#ae=this.#ae.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#ie?.(e.key)}}#lt(){this.#se&&=(clearTimeout(this.#se),void 0)}#ut(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#Rt();break;case`ctrl-c`:this.#X||(this.#X=!0,this.#H={kind:`idle`},this.#W=`Interrupted`,this.#le?.(),this.#Rt());break;case`enter`:break;default:{let t=applyLineEditorKey(this.#B,e,{multiline:!0});t!==void 0&&(this.#B=t,this.#Rt());break}}}#dt(){this.#ft(),this.#pt(),this.#ee=setInterval(()=>{this.#Z=!this.#Z,this.#Rt()},500),this.#ee.unref?.()}#ft(){this.#ee&&=(clearInterval(this.#ee),void 0),this.#Z=!0}#pt(){this.#Z=!0}#mt(){this.#gt(),this.#te=setInterval(()=>{this.#Q+=1,this.#Rt()},90),this.#te.unref?.()}#ht(){let e=Date.now();this.#$=e,this.#H={kind:`waiting`,startedAtMs:e},this.#mt()}#gt(){this.#te&&=(clearInterval(this.#te),void 0)}#_t(e){e.id!==this.#Se?.id&&this.#mn(),e.updateSeq=++this.#y,this.#p.push(e),e.id&&this.#m.set(e.id,e)}#vt(e){this.#R=!0,this.#_t({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#Rt()}#yt(){let e=this.#z.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#Xt(e.elapsedMs)}`,n=this.#pe??0;if(this.#me!==void 0&&this.#me>0&&n>0){let e=Math.round(n/this.#me*100);t+=` ${this.#r.glyph.dot} ${e}% context`}this.#_t({kind:`turn-stats`,body:t,live:!1})}#bt(e){if(e!=null){if(this.#we===e){this.#we=void 0;return}this.#_t({kind:`user`,body:stripTerminalControls(e),live:!1})}}#xt(e,t,n={}){let r=stripTerminalControls(e),i=stripTerminalControls(t),a=n.detail===void 0?void 0:stripTerminalControls(n.detail),o=n.hint===void 0?void 0:stripTerminalControls(n.hint),s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#u?.append(o===void 0?s:{...s,hint:o});let c={kind:`error`,title:r,body:i,live:!1};o!==void 0&&(c.hint=o),a!==void 0&&(c.detail=this.#u===void 0?a:`details: ${this.#u.displayPath}`),this.#_t(c),this.#Rt()}#St(e,t){if(this.#S.has(e))return;this.#S.add(e);let n=stripTerminalControls(t),r=this.#b.get(n)??[];if(r.push(e),this.#b.set(n,r),r.length===2){let e=this.#m.get(subagentHeaderId(r[0]));e!==void 0&&(e.subtitle=`#1`)}let i={id:subagentHeaderId(e),kind:`subagent`,subagentCallId:e,title:n,live:!0};r.length>1&&(i.subtitle=`#${r.length}`),this.#_t(i)}#Ct(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),t.updateSeq=++this.#y;return}this.#_t(e)}#wt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#Tt(){for(let e of this.#p)e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#Et(e,t,n){switch(e.type){case`step-finish`:this.#u?.recordStepUsage(e.usage),e.usage!==void 0&&this.#z.addUsage(e.usage),this.#Nt(n),this.#Lt(e.usage),this.#Rt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#Dt(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;n.text.set(e.id,r),this.#Dt(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);if(n.reasoning.set(e.id,r),t.reasoning===`full`){this.#Ot(e.id,r,!0,t);break}break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;if(t.reasoning===`full`){this.#Ot(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#kt({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#u?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#kt({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.#kt({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#It(e.toolCallId,n);if(r===void 0)break;this.#kt({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#It(e.toolCallId,n);if(this.#u?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#kt({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#It(e.toolCallId,n);if(r===void 0)break;this.#kt({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#xt(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`finish`:this.#Lt(e.usage),this.#Rt();break}}#Dt(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#Ct({id:e,kind:`assistant`,body:r,live:n}),this.#Rt())}#Ot(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Ct({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#Rt())}#kt(e,t,n){if(n.tools.set(e.toolCallId,e),this.#_.has(e.toolCallId)||this.#Pt(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#v.set(e.toolCallId,r);let i=this.#At(e);this.#Ct(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#Ft(n),this.#Rt()}#At(e){e.output!==void 0&&this.#x.observeRead(e.output);let t={};this.#jt(e.toolName)&&(t.isSubagent=!0);let n=readWriteFileInput(e.toolName,e.input);if(n===void 0)return t.isSubagent===!0?t:void 0;let r=this.#x.observeWrite({path:n.path,content:n.content,callId:e.toolCallId});r!==void 0&&(t.previousContent=r);let i=writeExistedFlag(e.output);return i!==void 0&&(t.existed=i),t}#jt(e){let t=this.#C?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#Mt(){for(let e of this.#p)e.kind!==`tool`&&e.kind!==`subagent-tool`||e.status===`running`&&(e.status=`error`,e.result=`interrupted`,e.live=!1)}#Nt(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#v.get(t)??toolSectionId(t);this.#wt(r),this.#v.delete(t)}}#Pt(e){let t=readTodoToolItems(e.toolName,e.input);if(t===void 0)return!1;if(t.length>0&&allTodoItemsSettled(t)){let e=JSON.stringify(t);this.#ke!==e&&(this.#ke=e,this.#_t({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#rn(),this.#r).join(`
|
|
5
|
+
`),live:!1})),this.#Oe=void 0}else this.#Oe=t.length>0?t:void 0,this.#ke=void 0;return this.#Rt(),!0}#Ft(e){let t=[];for(let n of e.tools.values()){if(this.#_.has(n.toolCallId))continue;let e=this.#v.get(n.toolCallId)??toolSectionId(n.toolCallId),r=this.#m.get(e);r?.kind===`tool`&&t.push({block:r,active:isActiveToolStatus(n.status)})}applyCohortLiveness(t)}#It(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.toolName??i.title??`tool`}}#Lt(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#fe=(t??0)+(n??0)),this.#pe=t??this.#pe,this.#he=n??this.#he,this.#he!=null&&this.#_e!==void 0){let e=(Date.now()-this.#_e)/1e3;e>0&&(this.#ge=this.#he/e)}}#Rt(){if(this.#q){if(this.#ue){this.#de=!0;return}this.#ue=!0;try{do this.#de=!1,this.#zt();while(this.#de)}finally{this.#ue=!1}}}#zt(){if(!this.#q)return;let e=this.#rn(),t=this.#Jt(e),n=Math.max(1,this.#in()-t.length),r=[],i=this.#D,a=groupToolBlocksForDisplay(this.#p),o=0;for(;o<a.length&&a[o].display.live===!1;)o+=1;if(o>0){let e=new Set(a.slice(0,o).flatMap(e=>e.members));for(let t=this.#p.length-1;t>=0;--t)e.has(this.#p[t])&&this.#p.splice(t,1)}for(let t of a.slice(0,o)){for(let e of t.members)this.#g.push(e),e.id&&(this.#h.add(e.id),this.#m.delete(e.id));if(this.#gn(t.display))continue;let n=this.#Wt(t.display,e,i);i=previousBlockOf(t.display),this.#D=i,r.push(...n),this.#E.push(...n)}let s=[];for(let{display:t}of a.slice(o)){if(this.#gn(t))continue;let n=this.#Wt(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)s.push({block:t,row:n[e]})}let c=[...clipLiveRows(s.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,c):this.#n.update(c)}#Bt(){if(!this.#q)return;let e=this.#rn(),t=this.#Jt(e),n=Math.max(1,this.#in()-t.length),r=this.#D,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#p)){if(this.#gn(t))continue;let n=this.#Wt(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.#Ut(),...this.#E],a)}logDisplayMode(){return this.#f}setLogDisplayMode(e){e!==this.#f&&(this.#f=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#Ht(),this.#q&&this.#Bt())}flushDelayedDevBuildErrors(){let e=this.#xe;e!==void 0&&(this.#xe=void 0,this.#_t({kind:`log`,title:`stderr`,body:e,live:!0}),this.#Rt())}#Vt(){this.#re=!0,this.#ne!==void 0&&clearTimeout(this.#ne),this.#ne=setTimeout(()=>{this.#re=!1,this.#ne=void 0,this.#Rt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#f)),this.#Rt()}#Ht(){let e=this.#rn();this.#E.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#g,{logCoalescing:`runs`})){if(this.#gn(n))continue;let r=this.#Wt(n,e,t);t=previousBlockOf(n),this.#E.push(...r)}this.#D=t}#Ut(){let e=this.#C;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#rn()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#Wt(e,t,n){let r={activityPulse:this.#Kt(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#Gt(){return this.#r.spinner[this.#Q%this.#r.spinner.length]??``}#Kt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#qt(e,t){return e.indicator.kind===`spinner`?{glyph:this.#Gt(),color:`yellow`}:{glyph:this.#Kt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#Jt(e){let n=this.#r.colors,r=[``];if(this.#Te!==void 0)return r.push(...this.#Te(e),``),this.#en(r,e),r;let a=this.#Ee;if(a!==void 0){let t=this.#qt(a,a.status),n=a.status===void 0?void 0:{...a.status,indicator:t},i;if(a.question!==void 0){let t=a.question(e);i={kind:`question`,rows:t},n!==void 0&&(i={kind:`question`,rows:t,status:n})}else n===void 0?i=a.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:a.preview,indicator:t}:(i={kind:`status`,status:n},a.preview!==void 0&&(i={kind:`status`,status:n,preview:a.preview}));let o={title:a.title,lines:a.hideLinesWhileQuestion===!0?[]:a.lines,content:i};return r.push(...renderFlowPanel(o,this.#r,e)),this.#tn(r,e),r}if(this.#Oe!==void 0&&r.push(...renderTodoPanelRows({items:this.#Oe,width:e,theme:this.#r,working:this.#V||this.#H.kind===`waiting`,pulse:this.#Kt(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}),``),this.#De!==void 0&&r.push(...renderAttentionRows(this.#De,e,this.#r),``),this.#P){let i=this.#F===void 0?void 0:inlineCommandHint(this.#F);i===void 0&&this.#F!==void 0&&isTypeaheadOpen(this.#F)&&r.push(...renderCommandSuggestions(this.#F,this.#r,e));let a=isPromptControlCommand(this.#j),o=i?n.dim(` ${i}`):``,l=[];this.#en(l,e);let d=Math.max(1,this.#in()-1-r.length-1-l.length),f={text:this.#j,cursor:this.#M,width:e,theme:this.#r,caretVisible:this.#Z,isCommand:a,ghost:o,maxRows:d};return this.#I&&this.#j.length===0&&(f.placeholder=this.#R?``:promptPlaceholder(Date.now()-this.#L)),r.push(...promptInputRows(f)),r.push(...l),r}let o=this.#H.kind===`waiting`&&this.#G===void 0;if(this.#V||o){r.push(this.#Yt(e)),this.#Qt(r,e);let t=[];return this.#en(t,e),!this.#V&&t.length>0&&r.push(``),r.push(...t),r}if(this.#B.text.length>0)return this.#$t(r,e,{inert:!1}),this.#en(r,e),r;let l=this.#G??(this.#W.length>0?this.#W:`Ready`),d=this.#nn(),f=n.dim(this.#r.glyph.dot),p=d?`${f} ${l} ${n.dim(this.#r.glyph.dot)} ${d}`:`${f} ${l}`;return r.push(clip(p,e)),this.#en(r,e),r}#Yt(e){let t=this.#r.colors,n=this.#Kt(this.#$,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),r=this.#H,i=this.#z.startedAtMs??this.#_e??(r.kind===`waiting`?r.startedAtMs:Date.now()),a=Date.now()-i,o=`${typewriterText(`Working for`,a,80)} ${this.#Xt(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#Xt(e){return`${formatTurnDuration(e)}${this.#Zt()}`}#Zt(){let{inputTokens:e,outputTokens:t}=this.#z.usage;return e===0&&t===0?``:` ${this.#r.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#r.glyph)}`}#Qt(e,t){this.#V&&this.#$t(e,t,{inert:!0})}#$t(e,t,n){e.push(``);let r={text:this.#B.text,cursor:this.#B.cursor,width:t,theme:this.#r,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#B.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#en(e,t){let n=this.#A===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#r,width:r};this.#re&&(i.logLevel=this.#f);let a=this.#C?.serverUrl;if(a!==void 0&&this.#A===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#C?.info?.agent.model;o?.id!==void 0&&(i.model=o.id),o?.reasoning!==void 0&&o.reasoning!==`provider-default`&&(i.reasoning=o.reasoning),readGatewayServiceTier(o?.providerOptions).kind===`priority`&&(i.fastMode=!0);let s=o?.endpoint;s!==void 0&&(i.endpoint=s),this.#k!==void 0&&(i.vercel=this.#k),this.#A!==void 0&&(i.remote=this.#A);let c=buildStatusLine(i);c!==void 0&&e.push(clip(`${n}${c}`,t))}#tn(e,t){if(this.#A===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#A,theme:this.#r,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#nn(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#fe,outputTokens:this.#he,tokensPerSecond:this.#ge},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#rn(){return Math.max(20,this.#t.columns||80)}#in(){return Math.max(8,this.#t.rows||24)}#an(){if(this.#ve!==void 0||!this.#l)return;this.#ye=``,this.#be=``;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.#cn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#u?.subscribeLogRecords(e=>this.#sn(e)),this.#ve=()=>{this.#u?.unsubscribeLogRecords(),e(),t()}}#on(){let e=this.#ve;e!==void 0&&(this.#ve=void 0,e(),this.#ye.length>0&&(this.#u?.append({source:`stdout`,detail:this.#ye}),this.#hn(`stdout`)&&process.stdout.write(`${this.#ye}\n`),this.#ye=``),this.#be.length>0&&(this.#u?.append({source:`stderr`,detail:this.#be}),this.#hn(`stderr`)&&process.stderr.write(`${this.#be}\n`),this.#be=``))}#sn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#un(`[eve:${e.namespace}] ${e.message}${t}`),this.#Rt()}#cn(e,t){let n=(e===`stdout`?this.#ye:this.#be)+t,r=n.lastIndexOf(`
|
|
6
|
+
`),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#ye=i:this.#be=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#u?.append({source:e,detail:a}),e===`stdout`?this.#ln(a):this.#un(a),this.#Rt())}#ln(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
|
|
7
|
+
`);t=[],e.trim().length!==0&&this.#_t({kind:`log`,title:`stdout`,body:e,live:!0})};for(let n of e.split(`
|
|
8
|
+
`)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#_t({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#fn(r,n.trimEnd())}flushPending()}#un(e){let t=e.split(`
|
|
9
|
+
`),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#u===void 0){this.#_t({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#u.displayPath);if(t.kind===`inline`){this.#_t({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#_t({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#_t({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
|
|
10
|
+
`);r.trim().length>0&&this.#_t({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
|
|
11
|
+
`);this.#dn(i)}#dn(e){if(this.#f===`all`){if(e.trim().length===0)return;this.#_t({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#xe=e}#fn(e,t){let n=this.#pn();if(e.kind===`failed`){this.#dn(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#Ce}`;this.#Ce+=1,this.#Se={id:r,summary:t},this.#_t({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}if(n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#xe=void 0);return}e.kind===`rebuilt`&&(this.#xe=void 0),this.#_t({kind:`log`,title:`stdout`,body:t,live:!0})}#pn(){let e=this.#Se;if(e===void 0)return;let t=this.#m.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#mn(){let e=this.#Se;if(e===void 0)return;this.#Se=void 0;let t=this.#m.get(e.id);t!==void 0&&(t.live=!1)}#hn(e){switch(this.#f){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#gn(e){return e.kind===`sandbox`?!this.#hn(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#f!==`stderr`:e.logVisibility===`all-only`?this.#f!==`all`:!this.#hn(e.title===`stderr`?`stderr`:`stdout`):!1}};function chunkToString(e,t){return typeof e==`string`?e:Buffer.from(e).toString(t)}async function*iterateTUIStream(e){if(e instanceof ReadableStream){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}return}yield*e}function clip(e,t){return clipVisible(e,t)}function promptInputRows({text:e,cursor:t,width:n,theme:r,caretVisible:i,isCommand:a,ghost:o,maxRows:s,placeholder:c,inert:l}){let u=r.colors;if(e.length===0&&c!==void 0){let e=renderInputWithBlockCursor({...visibleLine({text:c,cursor:0},Math.max(1,n-3),r.glyph.ellipsis),visible:i,inverse:u.inverse,render:e=>u.dim(renderInputText(e))});return[clip(`${u.dim(r.glyph.promptIdle)} ${e}`,n),``]}let style=e=>{let t=renderInputText(e);return a&&t.length>0?u.blue(t):t},d=layoutPromptInput({text:e,cursor:t}),f=Math.min(Math.max(1,s),d.rows.length),p=Math.max(0,Math.min(d.caretRow-f+1,d.rows.length-f)),m=l===!0?u.dim(r.glyph.prompt):u.cyan(r.glyph.prompt),h=u.dim(r.glyph.ellipsis),g=Math.max(1,n-3),_=[];for(let e=p;e<p+f;e+=1){let t=d.rows[e],a=e===0?m:` `;(e===p&&p>0||e===p+f-1&&p+f<d.rows.length)&&(a=h);let s;if(e===d.caretRow){let{before:e,under:n,after:a}=visibleLine({text:t.text,cursor:d.caretOffset},g,r.glyph.ellipsis);s=renderInputWithBlockCursor({before:e,under:n,after:a,visible:i,inverse:u.inverse,render:style}),o.length>0&&d.rows.length===1&&(s+=o)}else s=style(t.text);_.push(clip(`${a} ${s}`,n))}return _.push(``),_}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function isActiveToolStatus(e){return e===`running`||e===`approval`}function applyCohortLiveness(e){let t=e.some(e=>e.active);for(let n of e)n.block.live=t||n.active}function leadsWithGap(e,t){if(e.kind===`tool`&&(t?.kind===`user`||t?.kind===`assistant`||t?.kind===`question`))return!0;if(e.kind===`sandbox`&&t?.kind===`sandbox`)return!1;if(t?.kind===`sandbox`&&e.kind!==`sandbox`||t?.kind===`log`)return!0;switch(e.kind){case`user`:case`assistant`:case`reasoning`:case`subagent`:case`error`:case`notice`:case`question`:case`connection-auth`:case`sandbox`:case`log`:case`command`:case`warning`:case`flow`:case`turn-stats`:case`session-boundary`:case`todo-list`:case`agent-header`:return!0;default:return!1}}function parseSandboxLogLine(e){let t=e.trim();if(!t.startsWith(`eve: `))return;let n=t.slice(5);return/\bsandbox\b/i.test(n)&&!isLowValueSandboxLogLine(n)?n:void 0}function isLowValueSandboxLogLine(e){return/^initializing (?:\d+ )?sandbox templates?\b/i.test(e)||/^initialized \d+ sandbox\b/i.test(e)||/^reused cached sandbox template\b/i.test(e)||/^sandbox template "[^"]+" \([^)]+\): (checking|reusing|loading microsandbox runtime|microsandbox runtime ready)\b/i.test(e)}function clipLiveRows(e,t,n,r){if(e.length<=t)return[...e];if(t<=1)return[clip(hiddenRowsMarker(e.length,r),n)];let i=t-1;return[clip(hiddenRowsMarker(e.length-i,r),n),...e.slice(e.length-i)]}function hiddenRowsMarker(e,t){let n=e.toLocaleString(),r=e===1?`row`:`rows`;return t.colors.dim(`${t.glyph.dot} ${t.glyph.ellipsis} ${n} earlier ${r} hidden while streaming`)}function collapseReasoning(e,t){switch(e){case`collapsed`:return!0;case`auto-collapsed`:return!t;default:return!1}}function renderNativeToolBlock(e,t,n,r){let i=e.preparing===!0?presentPreparingTool(e.toolName,r):presentTool(e.toolName,e.input,r),a={id:t,kind:`tool`,title:stripTerminalControls(i.title),subtitle:stripTerminalControls(i.subtitle),status:e.status,live:e.status===`running`||e.status===`approval`,expanded:n,toolInput:e.input,toolName:e.toolName,toolGroup:i.group};return i.doneTitle!==void 0&&(a.doneTitle=stripTerminalControls(i.doneTitle)),i.detail!==void 0&&(a.detailLines=i.detail,a.keepDetailWhenDone=i.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(a.result=stripTerminalControls(e.errorText)):(a.result=i.summarizeResult(e.output),a.toolOutput=e.output),a}function writeExistedFlag(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.existed;return typeof t==`boolean`?t:void 0}function subagentToolStatus(e){switch(e){case`preparing`:return`running`;case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`;case`rejected`:return`denied`}}function formatToolApprovalTitle(e){return stripTerminalControls(e.title??e.toolName)}function toolSectionId(e){return`tool:${e}`}function questionSectionId(e){return`question:${e}`}function subagentHeaderId(e){return`subagent:${e}:header`}function subagentStepSectionId(e,t){return`subagent:${e}:step:${t}`}function subagentToolSectionId(e,t){return`subagent:${e}:tool:${t}`}function connectionAuthSectionId(e){return`connection-auth:${e}`}function connectionAuthTerminalMessage(e){switch(e){case`authorized`:return`Authorization complete`;case`declined`:return`Authorization declined`;case`failed`:return`Authorization failed`;case`timed-out`:return`Authorization timed out`;case`required`:case`pending`:return}}function formatConnectionAuthContent(e,t){let n=[];if(t!==void 0)n.push(t);else{let t=stripTerminalControls(e.description);t.length>0&&n.push(t);let r=e.challenge;r?.url&&n.push(`URL: ${stripTerminalControls(r.url)}`),r?.userCode&&n.push(`Code: ${stripTerminalControls(r.userCode)}`),r?.expiresAt&&n.push(`Expires: ${stripTerminalControls(r.expiresAt)}`),r?.instructions&&n.push(stripTerminalControls(r.instructions))}if(e.reason!==void 0){let t=stripTerminalControls(e.reason);t.length>0&&n.push(`Reason: ${t}`)}return n.join(`
|
|
11
12
|
`)}function formatQuestionContent(e,t,n){let r=n.colors,i=[],a=e.options??[];if(a.length>0){for(let[e,o]of a.entries()){let a=stripTerminalControls(o.label),s=o.description===void 0?``:stripTerminalControls(o.description),c=t===e,l=s.length>0?`${c?` `:` `}${r.dim(`— ${s}`)}`:``,u=renderCursorRow(c?`${n.glyph.selectedPointer} ${a}`:` ${a}`,c,r);i.push(`${u}${l}`)}if(e.allowFreeform===!0){let e=t===a.length,o=`Type your own answer`,s=e?`${n.glyph.selectedPointer} ${o}`:` ${r.dim(o)}`;i.push(renderCursorRow(s,e,r))}}else i.push(r.dim(` (type your answer)`));return i.join(`
|
|
12
13
|
`)}function resolveQuestionText(e,t){let n=e.trim();if(n.length===0)return;let r=n.toLowerCase(),i=t.options??[];if(i.length>0){let e=matchQuestionOption(r,i);if(e!==void 0)return{optionId:e.id,label:e.label}}if(t.allowFreeform===!0||i.length===0)return{text:n,label:n}}function matchQuestionOption(e,t){let n=t.find(t=>t.id.toLowerCase()===e);if(n!==void 0)return n;let r=t.find(t=>t.label.toLowerCase()===e);if(r!==void 0)return r;let i=Number(e);if(Number.isInteger(i)&&i>0&&i<=t.length)return t[i-1]}export{TerminalRenderer};
|
|
@@ -34,5 +34,12 @@ export declare class MockScreen extends EventEmitter implements TerminalOutput {
|
|
|
34
34
|
resize(columns: number, rows: number): void;
|
|
35
35
|
snapshot(): string;
|
|
36
36
|
rawOutput(): string;
|
|
37
|
+
/**
|
|
38
|
+
* Resolves once the runner parks at an idle prompt: a column-0 `›` row
|
|
39
|
+
* with no live turn bar on screen. A streaming turn keeps an identical
|
|
40
|
+
* `›` prompt anchored (Enter inert), so the glyph alone cannot signal
|
|
41
|
+
* readiness — the bar's absence is the discriminator.
|
|
42
|
+
*/
|
|
43
|
+
waitForIdlePrompt(timeoutMs?: number): Promise<void>;
|
|
37
44
|
waitForText(text: string, timeoutMs?: number, getDebugOutput?: () => string): Promise<void>;
|
|
38
45
|
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{EventEmitter}from"node:events";const ansiControlSequencePattern=RegExp(`^\x1B\\[([0-9?;]*)([ -/]*)([@-~])`);var MockUserInput=class extends EventEmitter{isTTY=!0;rawModes=[];resumeCalls=0;pauseCalls=0;setRawMode(e){return this.rawModes.push(e),this}resume(){return this.resumeCalls+=1,this}pause(){return this.pauseCalls+=1,this}type(e){this.emit(`data`,Buffer.from(e))}send(e){this.emit(`data`,Buffer.from(e))}enter(){this.send(`\r`)}backspace(){this.send(``)}up(){this.send(`\x1B[A`)}down(){this.send(`\x1B[B`)}left(){this.send(`\x1B[D`)}right(){this.send(`\x1B[C`)}ctrlC(){this.send(``)}ctrlN(){this.send(``)}ctrlP(){this.send(``)}},MockScreen=class extends EventEmitter{isTTY=!0;columns;rows;#e=``;#t=[];#n=0;#r=0;#i=[];constructor({columns:e,rows:t}){super(),this.columns=e,this.rows=t}write(e,t,n){let r=String(e);return this.#e+=r,this.#o(r),typeof t==`function`&&t(),n?.(),this.#a(),!0}resize(e,t){this.columns=e,this.rows=t,this.emit(`resize`)}snapshot(){return this.#t.join(`
|
|
2
|
-
`)}rawOutput(){return this.#e}async waitForText(e,t=1e3,n=()=>this.snapshot()){this.snapshot().includes(e)||await new Promise((r,i)=>{let a={text:e,resolve:r,reject:i,timeout:setTimeout(()=>{this.#i=this.#i.filter(e=>e!==a),i(Error(`Timed out waiting for screen text: ${e}\n\nScreen:\n${n()}`))},t)};this.#i.push(a)})}#a(){let e=this.snapshot();for(let t of this.#i.slice())e.includes(t.text)&&(clearTimeout(t.timeout),this.#i=this.#i.filter(e=>e!==t),t.resolve())}#o(e){let t=0;for(;t<e.length;){if(e[t]===`\x1B`){let n=this.#s(e,t);if(n>t){t=n;continue}}let n=e[t];if(t+=1,n!==void 0){if(n===`
|
|
2
|
+
`)}rawOutput(){return this.#e}async waitForIdlePrompt(e=1e3){let t=Array.from({length:11},(e,t)=>`Working for`.slice(0,t+1)),n=RegExp(`^[▪* ] (?:${t.join(`|`)}) \\d`,`mu`),idle=()=>{let e=this.snapshot();return/^[›❯]/mu.test(e)&&!n.test(e)},r=Date.now()+e;for(;Date.now()<r;){if(idle())return;await new Promise(e=>setTimeout(e,25))}throw Error(`Timed out waiting for an idle prompt.\n\nScreen:\n${this.snapshot()}`)}async waitForText(e,t=1e3,n=()=>this.snapshot()){this.snapshot().includes(e)||await new Promise((r,i)=>{let a={text:e,resolve:r,reject:i,timeout:setTimeout(()=>{this.#i=this.#i.filter(e=>e!==a),i(Error(`Timed out waiting for screen text: ${e}\n\nScreen:\n${n()}`))},t)};this.#i.push(a)})}#a(){let e=this.snapshot();for(let t of this.#i.slice())e.includes(t.text)&&(clearTimeout(t.timeout),this.#i=this.#i.filter(e=>e!==t),t.resolve())}#o(e){let t=0;for(;t<e.length;){if(e[t]===`\x1B`){let n=this.#s(e,t);if(n>t){t=n;continue}}let n=e[t];if(t+=1,n!==void 0){if(n===`
|
|
3
3
|
`){this.#n+=1,this.#r=0;continue}if(n===`\r`){this.#r=0;continue}this.#u(n)}}}#s(e,n){let r=e.slice(n).match(ansiControlSequencePattern);if(!r)return n;let[i,a=``,,o]=r,s=a.startsWith(`?`),c=a&&!s?a.split(`;`):[],first=e=>c[0]===void 0||c[0]===``?e:Number(c[0]);if(s)return n+i.length;switch(o){case`H`:case`f`:this.#n=first(1)-1,this.#r=(c[1]?Number(c[1]):1)-1;break;case`A`:this.#n=Math.max(0,this.#n-first(1));break;case`B`:this.#n+=first(1);break;case`C`:this.#r+=first(1);break;case`D`:this.#r=Math.max(0,this.#r-first(1));break;case`E`:this.#n+=first(1),this.#r=0;break;case`F`:this.#n=Math.max(0,this.#n-first(1)),this.#r=0;break;case`G`:this.#r=first(1)-1;break;case`J`:this.#c(first(0));break;case`K`:this.#l(first(0));break;default:break}return n+i.length}#c(e){if(e===2||e===3){this.#t=[],this.#n=0,this.#r=0;return}if(e===1){for(let e=0;e<this.#n;e+=1)this.#t[e]=``;this.#l(1);return}this.#l(0),this.#t.length=Math.min(this.#t.length,this.#n+1)}#l(e){let t=this.#t[this.#n]??``;if(e===2){this.#t[this.#n]=``;return}if(e===1){this.#t[this.#n]=` `.repeat(this.#r)+t.slice(this.#r);return}this.#t[this.#n]=t.slice(0,this.#r)}#u(e){let t=(this.#t[this.#n]??``).padEnd(this.#r,` `),n=t.slice(0,this.#r)+e+t.slice(this.#r+e.length);this.#t[this.#n]=n,this.#r+=e.length}};export{MockScreen,MockUserInput};
|