eve 0.54.5 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (310) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/src/channel/adapter.d.ts +3 -2
  3. package/dist/src/channel/audience.d.ts +16 -0
  4. package/dist/src/channel/audience.js +1 -0
  5. package/dist/src/channel/conversation-context.d.ts +5 -0
  6. package/dist/src/channel/conversation-context.js +1 -0
  7. package/dist/src/channel/instrumentation.js +1 -1
  8. package/dist/src/channel/types.d.ts +9 -0
  9. package/dist/src/chunks/{use-eve-agent-CxPlg0KL.js → use-eve-agent-CMdMlS7Y.js} +0 -10
  10. package/dist/src/chunks/{use-eve-agent-D-KQzzyW.js → use-eve-agent-RUGSwq8b.js} +0 -10
  11. package/dist/src/cli/commands/agent-prompt/scaffold.md +5 -4
  12. package/dist/src/cli/commands/init-target.js +2 -2
  13. package/dist/src/cli/commands/init.js +1 -1
  14. package/dist/src/cli/commands/registry-metadata.d.ts +0 -18
  15. package/dist/src/cli/commands/registry-metadata.js +1 -1
  16. package/dist/src/cli/commands/registry-pnpm-build-policy-flow.js +1 -1
  17. package/dist/src/cli/commands/registry.js +1 -1
  18. package/dist/src/cli/dev/environment.js +1 -1
  19. package/dist/src/cli/dev/tui/blocks.d.ts +2 -0
  20. package/dist/src/cli/dev/tui/blocks.js +3 -3
  21. package/dist/src/cli/dev/tui/markdown.d.ts +8 -1
  22. package/dist/src/cli/dev/tui/markdown.js +7 -7
  23. package/dist/src/cli/dev/tui/runner.d.ts +4 -1
  24. package/dist/src/cli/dev/tui/runner.js +1 -1
  25. package/dist/src/cli/dev/tui/terminal-renderer.d.ts +5 -1
  26. package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
  27. package/dist/src/cli/dev/tui/tui.d.ts +4 -1
  28. package/dist/src/cli/ui/terminal-text.js +1 -1
  29. package/dist/src/client/agent-info-schema.d.ts +0 -57
  30. package/dist/src/client/agent-info-schema.js +1 -1
  31. package/dist/src/compiled/.vendor-stamp.json +1 -1
  32. package/dist/src/compiler/extension-compatibility.d.ts +26 -16
  33. package/dist/src/compiler/extension-compatibility.js +1 -1
  34. package/dist/src/compiler/manifest.d.ts +12 -11
  35. package/dist/src/compiler/manifest.js +1 -1
  36. package/dist/src/compiler/normalize-manifest.js +1 -1
  37. package/dist/src/compiler/normalize-tool.d.ts +0 -3
  38. package/dist/src/compiler/normalize-tool.js +1 -1
  39. package/dist/src/compiler/validate-artifact.js +1 -1
  40. package/dist/src/context/dynamic-resolve-context.js +1 -1
  41. package/dist/src/context/keys.d.ts +2 -0
  42. package/dist/src/context/keys.js +1 -1
  43. package/dist/src/discover/filesystem.d.ts +3 -1
  44. package/dist/src/discover/filesystem.js +1 -1
  45. package/dist/src/discover/skills.js +1 -1
  46. package/dist/src/dynamic/definition.d.ts +6 -0
  47. package/dist/src/eve-channel/audience.d.ts +3 -0
  48. package/dist/src/eve-channel/audience.js +1 -0
  49. package/dist/src/eve-channel/index.js +1 -1
  50. package/dist/src/eve-channel/types.d.ts +14 -1
  51. package/dist/src/execution/activity-work.d.ts +2 -0
  52. package/dist/src/execution/activity-work.js +1 -1
  53. package/dist/src/execution/channel-context.js +1 -1
  54. package/dist/src/execution/coordination-dispatch-shared.d.ts +1 -0
  55. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  56. package/dist/src/execution/coordination-dispatch-step.d.ts +2 -2
  57. package/dist/src/execution/coordination-dispatch-step.js +1 -1
  58. package/dist/src/execution/create-session-step.js +1 -1
  59. package/dist/src/execution/durable-session-store.d.ts +0 -1
  60. package/dist/src/execution/dynamic-workflow/program-step.d.ts +21 -0
  61. package/dist/src/execution/dynamic-workflow/program-step.js +1 -0
  62. package/dist/src/execution/dynamic-workflow/schema.d.ts +36 -0
  63. package/dist/src/execution/dynamic-workflow/schema.js +1 -0
  64. package/dist/src/execution/dynamic-workflow/security-step.d.ts +3 -0
  65. package/dist/src/execution/dynamic-workflow/security-step.js +1 -0
  66. package/dist/src/execution/dynamic-workflow/tool.d.ts +8 -0
  67. package/dist/src/execution/dynamic-workflow/tool.js +1 -0
  68. package/dist/src/execution/dynamic-workflow/workflow.d.ts +10 -0
  69. package/dist/src/execution/dynamic-workflow/workflow.js +1 -0
  70. package/dist/src/execution/eve-workflow-attributes.d.ts +2 -1
  71. package/dist/src/execution/eve-workflow-attributes.js +1 -1
  72. package/dist/src/execution/inline-turn.js +1 -1
  73. package/dist/src/execution/model-call-batching.js +1 -1
  74. package/dist/src/execution/next-driver-action.d.ts +0 -8
  75. package/dist/src/execution/node-step.d.ts +0 -5
  76. package/dist/src/execution/node-step.js +1 -1
  77. package/dist/src/execution/runtime-context.js +1 -1
  78. package/dist/src/execution/scheduled-launch-delivery.d.ts +7 -0
  79. package/dist/src/execution/scheduled-launch-delivery.js +1 -0
  80. package/dist/src/execution/session-activity.js +1 -1
  81. package/dist/src/execution/session.d.ts +0 -1
  82. package/dist/src/execution/session.js +2 -2
  83. package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
  84. package/dist/src/execution/tasks/child/steps.js +1 -1
  85. package/dist/src/execution/tasks/parent/delegate.d.ts +9 -0
  86. package/dist/src/execution/tasks/parent/delegate.js +1 -1
  87. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  88. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  89. package/dist/src/execution/tools/subagent/invoke-step.d.ts +4 -0
  90. package/dist/src/execution/tools/subagent/invoke-step.js +1 -1
  91. package/dist/src/execution/tools/subagent/start.d.ts +5 -0
  92. package/dist/src/execution/tools/subagent/start.js +1 -1
  93. package/dist/src/execution/turn-workflow.js +1 -1
  94. package/dist/src/execution/wire/session-inbox-contract.d.ts +2 -2
  95. package/dist/src/execution/wire/session-inbox-contract.js +1 -1
  96. package/dist/src/execution/wire/session-inbox-encoder.d.ts +6 -2
  97. package/dist/src/execution/wire/session-inbox-encoder.js +1 -1
  98. package/dist/src/execution/wire/session-inbox-resume.js +1 -1
  99. package/dist/src/execution/wire/session-inbox-wire.js +1 -1
  100. package/dist/src/execution/wire/session-inbox-wire.v7.d.ts +342 -0
  101. package/dist/src/execution/wire/session-inbox-wire.v7.js +1 -0
  102. package/dist/src/execution/workflow-runtime.js +1 -1
  103. package/dist/src/execution/workflow-steps.js +1 -1
  104. package/dist/src/harness/action-presentation.d.ts +5 -0
  105. package/dist/src/harness/action-presentation.js +1 -1
  106. package/dist/src/harness/advertised-tools.d.ts +0 -3
  107. package/dist/src/harness/advertised-tools.js +1 -1
  108. package/dist/src/harness/background-tools.d.ts +3 -1
  109. package/dist/src/harness/emission.js +1 -1
  110. package/dist/src/harness/step-hooks.js +1 -1
  111. package/dist/src/harness/tool-loop.js +2 -2
  112. package/dist/src/harness/tools.js +1 -1
  113. package/dist/src/harness/types.d.ts +0 -21
  114. package/dist/src/instrumentation/channel-delivery.js +1 -1
  115. package/dist/src/instrumentation/content-policy.d.ts +2 -2
  116. package/dist/src/instrumentation/content.js +1 -1
  117. package/dist/src/instrumentation/lifecycle.d.ts +5 -7
  118. package/dist/src/instrumentation/native-events.d.ts +2 -0
  119. package/dist/src/instrumentation/native-events.js +1 -1
  120. package/dist/src/instrumentation/principal-summary.d.ts +3 -3
  121. package/dist/src/instrumentation/runtime-global.d.ts +4 -0
  122. package/dist/src/instrumentation/runtime-global.js +1 -0
  123. package/dist/src/instrumentation/runtime.d.ts +5 -9
  124. package/dist/src/instrumentation/runtime.js +1 -1
  125. package/dist/src/instrumentation/session-context.d.ts +3 -0
  126. package/dist/src/instrumentation/session-context.js +1 -1
  127. package/dist/src/instrumentation/session-init.d.ts +5 -0
  128. package/dist/src/instrumentation/session-init.js +1 -0
  129. package/dist/src/instrumentation/setup-context.js +1 -1
  130. package/dist/src/internal/application/dev-environment.d.ts +3 -0
  131. package/dist/src/internal/application/dev-environment.js +1 -1
  132. package/dist/src/internal/application/output-publication-journal.js +1 -1
  133. package/dist/src/internal/application/output-publication-lock.js +1 -1
  134. package/dist/src/internal/application/package.js +1 -1
  135. package/dist/src/internal/authored-definition/connection.js +1 -1
  136. package/dist/src/internal/authored-definition/schema-backed.d.ts +3 -4
  137. package/dist/src/internal/authored-definition/schema-backed.js +1 -1
  138. package/dist/src/internal/instrumentation.d.ts +1 -12
  139. package/dist/src/internal/instrumentation.js +1 -1
  140. package/dist/src/internal/logging.js +1 -1
  141. package/dist/src/internal/nitro/host/build-application.js +1 -1
  142. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  143. package/dist/src/internal/nitro/host/dev-host-fingerprint.js +1 -1
  144. package/dist/src/internal/nitro/host/workflow-sandbox-runtime-plugin.js +1 -1
  145. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  146. package/dist/src/protocol/activity.d.ts +1 -0
  147. package/dist/src/protocol/activity.js +1 -1
  148. package/dist/src/public/channels/chat-sdk/audience.d.ts +8 -0
  149. package/dist/src/public/channels/chat-sdk/audience.js +1 -1
  150. package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +0 -2
  151. package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +1 -1
  152. package/dist/src/public/channels/discord/audience.js +1 -1
  153. package/dist/src/public/channels/discord/discordChannel.js +1 -1
  154. package/dist/src/public/channels/discord/index.d.ts +0 -1
  155. package/dist/src/public/channels/index.d.ts +2 -3
  156. package/dist/src/public/channels/slack/activity-plan.js +1 -1
  157. package/dist/src/public/channels/slack/defaults.d.ts +2 -2
  158. package/dist/src/public/channels/slack/index.d.ts +1 -1
  159. package/dist/src/public/channels/slack/slackChannel.d.ts +11 -3
  160. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  161. package/dist/src/public/channels/teams/hitl.js +1 -1
  162. package/dist/src/public/channels/teams/index.d.ts +0 -1
  163. package/dist/src/public/channels/teams/teamsChannel.js +1 -1
  164. package/dist/src/public/channels/teams/verify.js +1 -1
  165. package/dist/src/public/channels/telegram/audience.d.ts +7 -0
  166. package/dist/src/public/channels/telegram/audience.js +1 -1
  167. package/dist/src/public/channels/telegram/index.d.ts +0 -1
  168. package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
  169. package/dist/src/public/channels/twilio/twilioChannel.d.ts +0 -2
  170. package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
  171. package/dist/src/public/connections/index.d.ts +1 -1
  172. package/dist/src/public/definitions/channel.d.ts +2 -1
  173. package/dist/src/public/definitions/channel.js +1 -1
  174. package/dist/src/public/definitions/connections/mcp.d.ts +7 -1
  175. package/dist/src/public/definitions/connections/openapi.d.ts +1 -1
  176. package/dist/src/public/definitions/workspace-agent.js +1 -1
  177. package/dist/src/public/models/openai/chatgpt/auth.js +1 -1
  178. package/dist/src/public/models/openai/chatgpt/codex-app-server.js +1 -1
  179. package/dist/src/public/models/openai/chatgpt/credential-store.js +1 -1
  180. package/dist/src/public/next/index.d.ts +6 -4
  181. package/dist/src/public/next/index.js +1 -1
  182. package/dist/src/public/next/server.js +1 -1
  183. package/dist/src/public/next/vercel-output-config.d.ts +1 -0
  184. package/dist/src/public/tools/workflow.d.ts +1 -4
  185. package/dist/src/public/tools/workflow.js +1 -1
  186. package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
  187. package/dist/src/runtime/connections/authorization-tokens.d.ts +2 -4
  188. package/dist/src/runtime/connections/mcp-client.js +1 -1
  189. package/dist/src/runtime/connections/principal.d.ts +6 -6
  190. package/dist/src/runtime/connections/principal.js +1 -1
  191. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  192. package/dist/src/runtime/resolve-agent.js +1 -1
  193. package/dist/src/runtime/resolve-connection.js +1 -1
  194. package/dist/src/runtime/resolve-tool.js +1 -1
  195. package/dist/src/runtime/sessions/runtime-context-keys.js +1 -1
  196. package/dist/src/runtime/types.d.ts +4 -9
  197. package/dist/src/self-modification/agent.d.ts +7 -1
  198. package/dist/src/self-modification/agent.js +1 -1
  199. package/dist/src/self-modification/extension/classify-registry-item.d.ts +3 -3
  200. package/dist/src/self-modification/extension/classify-registry-item.js +1 -1
  201. package/dist/src/self-modification/extension/tools/search_registry.d.ts +1 -7
  202. package/dist/src/self-modification/extension/tools/search_registry.js +1 -1
  203. package/dist/src/setup/flows/chatgpt-auth.js +1 -1
  204. package/dist/src/setup/flows/registry.js +1 -1
  205. package/dist/src/setup/integrations/self-modification/setup.js +1 -1
  206. package/dist/src/setup/provider-settings.js +1 -1
  207. package/dist/src/setup/scaffold/create/project.js +6 -2
  208. package/dist/src/shared/channel-audience.d.ts +0 -3
  209. package/dist/src/shared/channel-definition.d.ts +13 -4
  210. package/dist/src/shared/connection-types.d.ts +20 -7
  211. package/dist/src/shared/conversation-context.d.ts +62 -0
  212. package/dist/src/shared/conversation-context.js +1 -0
  213. package/dist/src/shared/forwarded-trace-policy.d.ts +2 -1
  214. package/dist/src/shared/forwarded-trace-policy.js +1 -1
  215. package/dist/src/shared/instrumentation-channel-kind.d.ts +3 -0
  216. package/dist/src/shared/instrumentation-channel-kind.js +1 -0
  217. package/dist/src/shared/instrumentation-content.d.ts +9 -4
  218. package/dist/src/shared/instrumentation-content.js +1 -1
  219. package/dist/src/shared/trace-policy.d.ts +7 -6
  220. package/dist/src/shared/trace-policy.js +1 -1
  221. package/dist/src/shared/validate-authorization.js +1 -1
  222. package/dist/src/shared/workflow-sandbox.d.ts +18 -12
  223. package/dist/src/shared/workflow-sandbox.js +1 -1
  224. package/dist/src/subagents/handle-dispatch.d.ts +2 -1
  225. package/dist/src/subagents/handle-dispatch.js +1 -1
  226. package/dist/src/subagents/remote-dispatch.js +1 -1
  227. package/dist/src/subagents/start-local.d.ts +1 -0
  228. package/dist/src/subagents/start-local.js +1 -1
  229. package/dist/src/subagents/start-remote.d.ts +2 -0
  230. package/dist/src/subagents/start-remote.js +1 -1
  231. package/dist/src/subagents/tool.d.ts +3 -0
  232. package/dist/src/subagents/tool.js +1 -1
  233. package/dist/src/svelte/index.js +1 -1
  234. package/dist/src/svelte/use-eve-agent.js +1 -1
  235. package/dist/src/tasks/session-index.d.ts +13 -0
  236. package/dist/src/tasks/session-index.js +1 -1
  237. package/dist/src/tools/auth.d.ts +5 -6
  238. package/dist/src/tools/provided/workflow.d.ts +12 -0
  239. package/dist/src/tools/provided/workflow.js +1 -0
  240. package/dist/src/tools/workflow-program-input.d.ts +6 -0
  241. package/dist/src/tools/workflow-program-input.js +1 -0
  242. package/dist/src/tracing/agent-invocation-coordinator.d.ts +3 -2
  243. package/dist/src/tracing/agent-invocation-coordinator.js +1 -1
  244. package/dist/src/tracing/agent-memory-instrumentation.d.ts +3 -1
  245. package/dist/src/tracing/agent-memory-instrumentation.js +1 -1
  246. package/dist/src/tracing/agent-otel-provider.d.ts +2 -0
  247. package/dist/src/tracing/agent-otel-provider.js +2 -2
  248. package/dist/src/tracing/agent-otel-runtime-context.d.ts +2 -1
  249. package/dist/src/tracing/agent-otel-runtime-context.js +1 -1
  250. package/dist/src/tracing/agent-otel-session-context.d.ts +2 -0
  251. package/dist/src/tracing/agent-otel-session-context.js +1 -1
  252. package/dist/src/tracing/agent-trace-context-codec.js +1 -1
  253. package/dist/src/tracing/agent-trace-context-store.js +1 -1
  254. package/dist/src/tracing/agent-trace-state.d.ts +2 -0
  255. package/dist/src/tracing/content-attributes.js +1 -1
  256. package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
  257. package/dist/src/tracing/local-instrumentation-runtime.d.ts +1 -1
  258. package/dist/src/tracing/local-instrumentation-runtime.js +1 -1
  259. package/dist/src/vue/index.js +1 -1
  260. package/dist/src/vue/use-eve-agent.js +1 -1
  261. package/docs/agent-config.md +1 -1
  262. package/docs/channels/chat-sdk.mdx +7 -0
  263. package/docs/channels/custom.mdx +32 -2
  264. package/docs/channels/eve.mdx +39 -0
  265. package/docs/channels/linear.mdx +7 -3
  266. package/docs/channels/overview.mdx +13 -0
  267. package/docs/channels/slack.mdx +41 -1
  268. package/docs/connections/mcp.mdx +18 -1
  269. package/docs/connections/openapi.mdx +8 -2
  270. package/docs/connections/overview.mdx +16 -13
  271. package/docs/getting-started.mdx +1 -1
  272. package/docs/guides/deployment/self-hosting.md +1 -1
  273. package/docs/guides/deployment/vercel.mdx +2 -2
  274. package/docs/guides/dev-tui.md +4 -4
  275. package/docs/guides/dynamic-capabilities.md +4 -4
  276. package/docs/guides/frontend/nextjs.mdx +12 -10
  277. package/docs/guides/hooks.md +1 -1
  278. package/docs/guides/instrumentation/meta.json +4 -0
  279. package/docs/guides/instrumentation/otel.mdx +149 -0
  280. package/docs/guides/instrumentation/overview.md +199 -0
  281. package/docs/guides/instrumentation/providers.mdx +169 -0
  282. package/docs/guides/meta.json +0 -1
  283. package/docs/guides/remote-agents.md +19 -21
  284. package/docs/install-integrations.mdx +3 -5
  285. package/docs/patterns/multi-tenant-auth.md +3 -3
  286. package/docs/reference/cli.md +22 -21
  287. package/docs/reference/typescript-api.md +9 -9
  288. package/docs/subagents/index.mdx +5 -3
  289. package/docs/tools/workflows.mdx +56 -1
  290. package/package.json +1 -1
  291. package/dist/src/cli/commands/registry-package.d.ts +0 -52
  292. package/dist/src/cli/commands/registry-package.js +0 -1
  293. package/dist/src/harness/workflow-continuation-security.d.ts +0 -5
  294. package/dist/src/harness/workflow-continuation-security.js +0 -1
  295. package/dist/src/harness/workflow-interrupt-state.d.ts +0 -20
  296. package/dist/src/harness/workflow-interrupt-state.js +0 -1
  297. package/dist/src/harness/workflow-lifecycle.d.ts +0 -32
  298. package/dist/src/harness/workflow-lifecycle.js +0 -1
  299. package/dist/src/harness/workflow-sandbox.d.ts +0 -28
  300. package/dist/src/harness/workflow-sandbox.js +0 -2
  301. package/dist/src/harness/workflow-subagent-limit.d.ts +0 -28
  302. package/dist/src/harness/workflow-subagent-limit.js +0 -1
  303. package/dist/src/harness/workflow-task-state.d.ts +0 -9
  304. package/dist/src/harness/workflow-task-state.js +0 -1
  305. package/dist/src/harness/workflow-tool-description.d.ts +0 -22
  306. package/dist/src/harness/workflow-tool-description.js +0 -37
  307. package/dist/src/tools/workflow.d.ts +0 -37
  308. package/dist/src/tools/workflow.js +0 -1
  309. package/docs/guides/instrumentation-providers.md +0 -247
  310. package/docs/guides/instrumentation.md +0 -453
@@ -1 +1 @@
1
- import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{pickAgentHeaderTip}from"./agent-header.js";import{failureKey,formatFailureDetail,formatFailureHint,formatFailureMessage,isInterruptedError,localFailureHint}from"./errors.js";import{parseLogDisplayMode}from"./log-display-mode.js";import{createMcpConnectionStatusTracker}from"./mcp-connection-status.js";import{createRemoteConnectionController}from"./remote-connection.js";import{SubagentPump}from"./subagent-pump.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,detectSetupIssues,formatSetupIssuesLine,normalizeLocalModelEndpoint,orderedSetupIssues}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import"#client/index.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{inspectApplication}from"#services/inspect-application.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{probeAgentInfo}from"#services/dev-client/agent-info-probe.js";import{renderApplicationInfo}from"#cli/commands/info.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{createDevelopmentRuntimeArtifactRefresher}from"#services/dev-client.js";async function delayMs(e){await new Promise(t=>{setTimeout(t,e).unref?.()})}async function abortableDelay(e,t){t.aborted||await new Promise(n=>{let r=setTimeout(done,e);r.unref?.(),t.addEventListener(`abort`,done,{once:!0});function done(){clearTimeout(r),t.removeEventListener(`abort`,done),n()}})}function authIssueForStatus(e){if(e===`logged-out`)return LOGIN_SETUP_ISSUE;if(e===`cli-missing`)return CLI_MISSING_SETUP_ISSUE}var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y=!1;#b;#x;#S;#C;#w;#T;#E;#D;#O=!1;#k=new AbortController;#A=!1;#j=[];#M;#N;#P;#F;#I;#L=new Map;#R;#z=[];#B;#V=!1;#H;#U=new Map;#W=new Set;#G;#K;#q;constructor(e){this.#e=e.session,e.client!==void 0&&(this.#t=e.client),e.lifecycle!==void 0&&(this.#q=e.lifecycle),this.#n=createRenderer(e);let t={formatActionResultError};if(this.#t!==void 0&&(t.client=this.#t),this.#n.subagents!==void 0&&(t.view=this.#n.subagents),e.appRoot!==void 0&&(t.onToolCompleted=async(e,t)=>{let n=registryHandoffAddress(e,t);n!==void 0&&this.#ce(n)}),this.#H=new SubagentPump(t),this.#r=e.name??`eve`,this.#F=e.startup?.headerTip??pickAgentHeaderTip(),this.#S=e.withExclusiveTerminal,this.#i=e.tools??`full`,this.#a=e.reasoning??`full`,this.#o=e.subagents??`full`,this.#s=e.connectionAuth??`full`,this.#c=e.assistantResponseStats??`tokensPerSecond`,this.#l=e.contextSize,this.#u=e.formatTransportError??toErrorMessage,e.initialInput!==void 0&&(this.#m=e.initialInput),e.startup!==void 0&&(this.#h=e.startup),this.#g=e.onboard===!0,this.#_=e.onOnboardingStep,this.#v=e.onOnboardingTerminal,e.appRoot!==void 0){this.#p=e.appRoot;let t={appRoot:e.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};e.detectProjectIdentity!==void 0&&(t.detectIdentity=e.detectProjectIdentity),this.#N=createVercelStatusTracker(t),e.probeMcpConnection!==void 0&&(this.#P=createMcpConnectionStatusTracker({onChange:()=>{},probe:e.probeMcpConnection}))}if(e.promptCommandHandler!==void 0&&(this.#b=e.promptCommandHandler),this.#x=e.availablePromptCommands??PROMPT_COMMANDS,e.remote!==void 0){if(this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#C=createRemoteConnectionController({client:this.#t,credentials:e.remote.credentials,target:e.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:e.remote.resolveOidcToken,resolveDeployment:e.remote.resolveDeployment})}this.#w=e.bootDetections??BOOT_DETECTIONS,this.#T=e.getVercelAuthStatus??getVercelAuthStatus,this.#E=e.inspectApplication??inspectApplication,e.onBootProgress!==void 0&&(this.#D=e.onBootProgress),e.serverUrl!==void 0&&(this.#f=e.serverUrl),e.serverUrl!==void 0&&e.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactRefresher({serverUrl:e.serverUrl}))}async#J(){if(this.#f===void 0)return this.#X(),this.#g||await this.#ue(void 0),this.#h?.finish()??this.#m;let e;if(this.#C!==void 0){let t=await this.#C.check();t.state===`ready`&&(e=t.info)}else{let t=this.#t;if(t!==void 0)try{let n=await devBootPhase(`connecting to agent`,()=>probeAgentInfo({client:t}),this.#D);n.kind===`ready`&&(e=n.info)}catch{e=void 0}}let t=this.#h?.finish()??this.#m;this.#X();let n=this.#Y(e);return this.#g||await this.#ue(n),t}#Y(e){let t=this.#p===void 0?e:normalizeLocalModelEndpoint(e,process.env);this.#I=t;let n=this.#f;if(n===void 0||this.#y)return t;let r={name:this.#r,serverUrl:n};return t!==void 0&&(r.info=t),this.#p!==void 0&&(r.tip=this.#F),this.#n.renderAgentHeader?.(r),t}#X(){let e=this.#D;this.#D=void 0,e?.({type:`before-first-paint`})}async run(){let onStop=()=>this.#n.requestInterrupt?.();this.#q?.signal.aborted===!0?onStop():this.#q?.signal.addEventListener(`abort`,onStop,{once:!0});try{await this.#Z()}finally{this.#q?.signal.removeEventListener(`abort`,onStop),this.#O=!0,this.#k.abort(),this.#H.abortAll(),this.#K?.(),this.#K=void 0,this.#n.shutdown?.(),this.#N?.dispose(),this.#P?.dispose(),this.#C?.dispose()}}async#Z(){let e=this.#r,t,n,r=!1,i=!1,a=!1,o=await this.#J();if(this.#C?.current().connection.state===`auth-required`&&await this.#ye({type:`extension`,name:`vc:login`,argument:``},e,{trigger:`startup`}),this.#me(),this.#N?.refreshIdentity(),this.#P?.refresh(),this.#g&&this.#p!==void 0&&this.#b!==void 0&&this.#n.setupFlow!==void 0){o=void 0,this.#y=!0;try{await this.#xe(e)}finally{this.#y=!1}}for(;;){if(this.#q?.signal.aborted===!0||this.#n.exitRequested?.()===!0)return;let s=this.#z[0];if(s!==void 0&&n===void 0&&this.#R===void 0){this.#z.shift(),this.#B=s;try{await this.#le(s)}finally{this.#B=void 0}i=!1,a=!1,t=void 0;continue}if(!a){if(t==null){if(!this.#n.readPrompt){if(r)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let n={title:e};o!==void 0&&(n.initialDraft=o,o=void 0);try{this.#V=!0,t=await this.#ne(n)}catch(e){if(isInterruptedError(e)){if(this.#R===void 0&&this.#z.length===0)return;a=!0,t=``}else throw e}finally{this.#V=!1}if(this.#z.length>0&&this.#R===void 0){t=void 0;continue}if(t==null&&this.#R===void 0)return}let s=this.#R===void 0?parsePromptCommand(t):null;if(s?.type===`exit`){this.#q?.requestStop();return}if(s?.type===`cancel`){if(this.#e===void 0){this.#he(`No active turn to cancel.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.cancel();if(this.#he(e.status===`accepted`?`Turn cancellation requested.`:`No active turn to cancel.`),e.status===`no_active_turn`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#he(`Couldn't cancel the turn: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(s?.type===`reset`){if(!await this.#ee()){n=void 0,a=!1,t=void 0;continue}n=void 0,a=!1,t=void 0;continue}if(s?.type===`compact`){if(this.#e===void 0){this.#he(`No active session to compact.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.compact();if(this.#he(e.status===`accepted`?`Compaction requested.`:`No active session to compact.`),e.status===`no_active_session`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#he(`Couldn't compact the session: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(s?.type===`clear`){if(this.#e===void 0){this.#he(`No active session to clear.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.clear();if(this.#he(e.status===`accepted`?`Context clear requested.`:`No active session to clear.`),e.status===`no_active_session`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#he(`Couldn't clear the session: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(s?.type===`help`){this.#he(formatPromptCommandHelp(this.#x)),n=void 0,a=!1,t=void 0;continue}if(s?.type===`info`){await this.#we(),n=void 0,a=!1,t=void 0;continue}if(s?.type===`loglevel`){this.#he(this.#Te(s.argument)),n=void 0,a=!1,t=void 0;continue}if(s?.type===`traces`){await this.#Ce(s.argument),n=void 0,a=!1,t=void 0;continue}if(s?.type===`extension`){try{await this.#ye(s,e,{trigger:`command`})}catch(e){if(isInterruptedError(e))return;throw e}n=void 0,t=void 0,a=!1;continue}r=!0}let c=this.#R;this.#R=void 0;let l=c??(i?this.#oe():await(async()=>(this.#$(),await this.#ie({prompt:a?void 0:t,inputResponses:n})))()),u=this.#e?.state.sessionId;u!==void 0&&this.#n.setSessionId?.(u);let d=t,f=!1;try{for(;;){await this.#n.renderStream(l,{title:e,submittedPrompt:d,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let r=l.turnState?.pendingApprovals??[],i=l.turnState?.pendingQuestions??[];if(r.length>0||i.length>0){let o=[];if(r.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let t of r){let n=await this.#n.readToolApproval(t,{title:e});o.push({requestId:t.approvalId,optionId:n.approved?`approve`:`cancel`}),this.#L.delete(t.approvalId)}}if(i.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let t of i){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let i={requestId:t.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),o.push(i),this.#L.delete(t.requestId)}}if(o.length===0)break;a=!0,n=o,t=void 0,f=!0;break}if(this.#Ae(l)){l=this.#oe(),d=void 0;continue}if(l.turnState&&l.turnState.boundaryEvent===void 0&&!l.turnState.aborted){let e=this.#e?.state.sessionId;this.#n.renderNotice?.(e?`Lost the event stream — the turn may still be running on the server (session ${e}). Your next message resumes this session; use /cancel to stop the turn.`:`Lost the connection to the running turn.`)}break}}catch(e){if(isInterruptedError(e))return;throw e}if(f)continue;i=!1,a=!1,n=void 0,t=void 0;let p=l.turnState?.boundaryEvent;this.#G!==this.#e&&(p===`session.waiting`||p===`session.completed`)&&(t=this.#n.takeQueuedPrompt?.()),this.#$(l.turnState?.aborted===!0)}}#Q(){this.#H.abortAll(),this.#L.clear(),this.#U.clear(),this.#W.clear(),this.#n.setConnectionAuthPendingCount?.(0),this.#e=void 0,this.#d?.clear()}#$(e=!1){let t=this.#G;t!==void 0&&(this.#G=void 0,this.#e===t&&(this.#Q(),e?this.#n.renderNotice?.(`Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server.`):this.#n.renderSessionBoundary===void 0?this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`):this.#n.renderSessionBoundary()))}async#ee(){if(this.#e===void 0)return this.#Q(),this.#n.reset?.(),!0;try{await this.#e.reset()}catch(e){return this.#n.renderNotice?.(`Couldn't reset the session: ${toErrorMessage(e)}`),!1}return this.#Q(),this.#n.reset?.(),!0}async#te(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#d;if(n===void 0)return await t;let r=!1,i=!1,a,o=0,refresh=async()=>{if(!(r||i)){i=!0;try{await n.refreshIdle({onRuntimeArtifactsChanged:()=>this.#Oe()});let e=this.#I?.agent.model.endpoint,t=e?.kind===`chatgpt`&&(e.state===`signed-out`||e.state===`reauth-required`),r=Date.now();if(t&&r-o>=5e3){o=r;let e=await this.#De();e!==void 0&&this.#Y(e)}}finally{i=!1}}},startRefresh=()=>{if(r||i)return;let e=refresh().finally(()=>{a===e&&(a=void 0)});a=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await t}finally{r=!0,clearInterval(s),await a}}async#ne(e){let t=this.#te(e);if(this.#n.renderIdleStream===void 0||this.#e?.state.sessionId===void 0)return await t;let n=new AbortController,r=this.#re(n.signal,e).catch(e=>{n.signal.aborted||this.#n.renderNotice?.(`Stopped following session updates: ${toErrorMessage(e)}`)});try{return await t}finally{n.abort(),await r}}async#re(e,t){let n=this.#e;if(n===void 0)return;let r=100;for(;!e.aborted;){let i=n.stream({signal:e})[Symbol.asyncIterator](),a=!1;try{for(;!e.aborted;){let r=!1,o={async*[Symbol.asyncIterator](){for(;!e.aborted;){let e=await i.next();if(e.done===!0||(r=!0,a=!0,yield e.value,isCurrentTurnBoundaryEvent(e.value)))return}}},s=this.#se(o,()=>{},n);if(await this.#n.renderIdleStream(s,{...t,continueSession:!0}),this.#Ae(s),(s.turnState?.pendingApprovals.length??0)>0||(s.turnState?.pendingQuestions.length??0)>0){this.#R={events:(async function*(){})(),turnState:s.turnState},this.#n.suspendPromptForInput?.();return}if(s.turnState?.boundaryEvent===`session.completed`||s.turnState?.boundaryEvent===`session.failed`)return;if(!r)break}}finally{await i.return?.()}r=a?100:Math.min(r*2,2e3),e.aborted||await abortableDelay(r,e)}}async#ie(e){let t=new AbortController,n={signal:t.signal};e.prompt!==void 0&&(n.message=e.prompt),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses);let r,i=this.#e;try{if(this.#d!==void 0&&await this.#d.refresh({inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#Oe()}),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),this.#e===void 0){if(this.#t===void 0)throw Error(`Cannot create a session without an eve client.`);if(n.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let e=await this.#t.sessions.create({...n,message:n.message});this.#e=e.session,r=e.response}else r=n.inputResponses===void 0?await this.#e.send(n.message,{signal:n.signal,turnPolicy:`queue`}):await this.#e.respond(n.inputResponses,{signal:n.signal})}catch(e){if(isInterruptedError(e))throw e;return this.#C?.reportFailure(e),this.#G=i,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}return this.#se(r,()=>t.abort(),this.#e)}async#ae(e,t){if(e.cancelInFlight!==!0){e.cancelInFlight=!0;try{for(let n=0;n<8;n+=1){if(e.boundaryEvent!==void 0||e.aborted===!0)return;let n=e.turnId;try{if((await t?.cancel(n===void 0?void 0:{turnId:n}))?.status===`accepted`)return}catch{}await delayMs(250)}}finally{e.cancelInFlight=!1}}}#oe(){if(this.#e===void 0)throw Error(`Cannot stream a session before its first turn is accepted.`);let e=new AbortController,t=this.#e;return this.#se(t.stream({signal:e.signal}),()=>e.abort(),t)}#se(e,t,n){let r=createTurnState();return{abort:()=>{r.aborted=!0,this.#G=n,t()},cancel:()=>{this.#ae(r,n)},events:eveEventsToTUIStream({events:e,pendingInputRequests:this.#L,turnState:r,onSubagentCalled:e=>this.#H.begin(e),onSubagentBackgrounded:e=>this.#H.background(e),onSubagentCompleted:e=>this.#H.settle(e),onTurnCancelled:e=>this.#H.settleCancelledTurn(e),onConnectionAuthRequired:e=>this.#ke(e),onConnectionAuthCompleted:e=>this.#je(e),onRegistryHandoff:this.#p===void 0?void 0:async e=>this.#ce(e),onTerminalFailure:()=>{this.#G=n},failureHintOverride:this.#p===void 0?void 0:localFailureHint}),turnState:r}}#ce(e){this.#B===e||this.#z.includes(e)||(this.#z.push(e),this.#V&&this.#n.suspendPromptForInput?.())}async#le(e){await this.#ye({type:`extension`,name:`add`,argument:e},`Add to your agent`,{trigger:`command`})}async#ue(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#j=await detectSetupIssues(t,this.#w),this.#n.renderSetupWarning!==void 0&&(this.#de(),this.#fe())}#de(){let e=orderedSetupIssues(this.#j,this.#M);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#fe(){let e=this.#p;if(e===void 0)return;let t;try{t=await this.#T(e,{signal:this.#k.signal})}catch{return}this.#O||this.#A||(this.#M=authIssueForStatus(t),this.#de())}async#pe(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n={appRoot:t,env:process.env};e!==void 0&&(n.info=e);try{this.#j=await detectSetupIssues(n,this.#w);let e=await this.#T(t,{signal:this.#k.signal});this.#M=authIssueForStatus(e)}catch{return}this.#O||this.#de()}#me(){this.#p!==void 0&&this.#n.renderSandboxLog!==void 0&&this.#K===void 0&&(this.#K=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#he(e,t){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e,t);return}this.#n.renderNotice?.(e)}}async#ge(e,t){let n=this.#b;if(n===void 0)return{message:`/${e.name} is not available in this session.`};let r=this.#I?.agent.model.endpoint,i={...t,renderer:this.#n,chatGptAccountLabel:r?.kind===`chatgpt`&&r.state===`ready`?r.accountLabel:void 0,remoteConnection:this.#C,withExclusiveTerminal:this.#S},a=this.#P?.current(),o=a!==void 0&&Object.keys(a).length>0?{...i,disabledConnectionReasons:a}:i;return t.keepSetupFlowOpen===!0?await n.handle(e,{...o,keepSetupFlowOpen:!0}):await n.handle(e,o)}#_e(e,t,n){if(t!==`startup`)return;let r=this.#C?.current().connection.state,i=n===`error`||r===`auth-failed`||r===`unavailable`?`failed`:void 0,a=e.argument.length===0?``:` ${e.argument}`;this.#n.renderCommandInvocation?.(`/${e.name}${a}`,i)}async#ve(e){if(e?.kind===`model-access-changed`){this.#N?.applyEffect({kind:`refresh-identity`}),this.#A=!0,await this.#Ee();return}e!==void 0&&(this.#N?.applyEffect(e),this.#A=!0,this.#pe(this.#I))}async#ye(e,t,n){let r=await this.#ge(e,{...n,title:t}),i=n.suppressSuccessfulTranscript===!0&&r?.tone!==`error`||n.suppressCancelledTranscript===!0&&r?.cancelled===!0;return i||this.#_e(e,n.trigger,r?.tone),i||this.#he(r?.message,r?.tone),await this.#ve(r?.effect),this.#Se(),r}#be(e){return{kind:`planner`,activeStep:e,firstNavigableStep:1,steps:[{label:`Model`,complete:e>0},{label:`Channels`},{label:`Integrations`},{label:`Review`}]}}async#xe(e){let t={keepSetupFlowOpen:!0,setupFlowTitle:`Set up ${e}`,trigger:`startup`},n=`model_provider`,onOnboardingScreen=e=>{n=e.screen,this.#_?.({flow:`onboarding`,step:e.screen,registrySelectedCount:e.registrySelectedCount})};onOnboardingScreen({screen:`model_provider`});let r;try{r=await this.#ye({type:`extension`,name:`model`,argument:``},e,{...t,suppressSuccessfulTranscript:!0,initialModelStep:`provider`,setupFlowNavigation:this.#be(0),onOnboardingScreen})}catch(e){throw this.#v?.({flow:`onboarding`,step:n,result:`error`}),e}if(r?.tone===`error`||r?.cancelled===!0){this.#v?.({flow:`onboarding`,step:n,result:r.cancelled===!0?`cancelled`:`error`}),this.#n.setupFlow?.end({preserveDiagnostics:r.tone===`error`});return}let i;n=`registry_channels`;let onRegistryScreen=e=>{n=e.screen,this.#_?.({flow:`onboarding`,step:e.screen,registrySelectedCount:e.registrySelectedCount})};try{onRegistryScreen({screen:`registry_channels`}),i=await this.#ye({type:`extension`,name:`add`,argument:``},e,{...t,onOnboardingScreen:onRegistryScreen,registryPlannerContext:{prefixSteps:[{label:`Model`,complete:!0}],reviewMessage:`Review your agent`,primaryActionLabel:`Install and finish setup`,emptyActionLabel:`Finish setup`}})}catch(e){throw this.#v?.({flow:`onboarding`,step:n,result:`error`}),e}finally{i!==void 0&&this.#v?.({flow:`onboarding`,step:n,result:i.cancelled===!0?`cancelled`:i.tone===`error`?`error`:`completed`}),this.#n.setupFlow?.end({preserveDiagnostics:i?.tone===`error`})}}#Se(){if(this.#y)return;let e=this.#C?.current().connection;e?.state===`ready`&&e.info!==this.#I&&(this.#I=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}async#Ce(e){if(this.#p===void 0||this.#n.traceViewer===void 0){this.#he(`/traces is only available in local dev sessions.`);return}try{await this.#n.traceViewer.open({appRoot:this.#p,sessionId:this.#e?.state.sessionId,reference:e===``?void 0:e})}catch(e){if(isInterruptedError(e))return;throw e}}async#we(){let e=this.#p;if(e===void 0){this.#he(`/info is only available in local dev sessions.`);return}try{this.#he(renderApplicationInfo(await this.#E(e)))}catch(e){this.#he(`Couldn't inspect the application: ${toErrorMessage(e)}`,`error`)}}#Te(e){let t=this.#n;if(t.logDisplayMode===void 0||t.setLogDisplayMode===void 0)return`/loglevel is not available in this session.`;if(e===``)return`Logs: ${t.logDisplayMode()}. Use /loglevel all|stderr|sandbox|none — logs stay buffered, so switching also hides or restores past lines.`;let n=parseLogDisplayMode(e);if(n===void 0)return`Unknown log level "${e}". Use all, stderr, sandbox, or none.`;if(n===t.logDisplayMode())return`Logs already set to ${n}.`;switch(t.setLogDisplayMode(n),n){case`none`:return`Logs hidden. Output stays buffered — /loglevel all restores it.`;case`stderr`:return`Showing stderr logs only.`;case`sandbox`:return`Showing sandbox logs only.`;case`all`:return`Showing all logs.`}}async#Ee(){let e=this.#p;if(e===void 0)return;await loadDevelopmentEnvironmentFiles(e),await this.#d?.refreshAfterSourceChange({});let t=this.#Y(await this.#De());this.#pe(t)}async#De(){let e=this.#t;if(e===void 0)return;let t=await probeAgentInfo({client:e});return t.kind===`ready`?t.info:void 0}async#Oe(){let e=this.#I,t=await this.#De();t!==void 0&&this.#Y(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#ke(e){let t={name:e.data.name,description:e.data.description,state:`required`};e.data.authorization!==void 0&&(t.challenge=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),this.#U.set(e.data.name,t),this.#Me(t)}#Ae(e){if(e.turnState?.boundaryEvent!==`session.waiting`)return!1;let t=!1;for(let e of this.#U.values())e.state===`required`&&e.webhookUrl!==void 0&&(e.state=`pending`,this.#W.add(e.name),this.#Me(e),t=!0);return t&&this.#n.setConnectionAuthPendingCount?.(this.#W.size),this.#W.size>0}#je(e){let t=this.#U.get(e.data.name)??{name:e.data.name,description:``,state:e.data.outcome};t.state=e.data.outcome,e.data.reason!==void 0&&(t.reason=e.data.reason),this.#U.set(e.data.name,t),this.#W.delete(e.data.name),this.#Me(t),this.#n.setConnectionAuthPendingCount?.(this.#W.size)}#Me(e){let t={name:e.name,description:e.description,state:e.state};e.challenge!==void 0&&(t.challenge=e.challenge),e.reason!==void 0&&(t.reason=e.reason),this.#n.upsertConnectionAuth?.(t)}};function createRenderer(e){return e.renderer?e.renderer:new TerminalRenderer({tools:e.tools,reasoning:e.reasoning,subagents:e.subagents,connectionAuth:e.connectionAuth,assistantResponseStats:e.assistantResponseStats,contextSize:e.contextSize,logs:e.logs,availablePromptCommands:e.availablePromptCommands,input:e.userInput,output:e.screen,diagnostics:e.diagnostics,onExitRequest:e.lifecycle?.requestStop})}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id,r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}function registryHandoffAddress(e,t){if(e!==`selfmod__registry_add`||typeof t!=`object`||!t)return;let n=t;return n.status===`needs-terminal`&&typeof n.address==`string`?n.address:void 0}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,turnState:r,onSubagentCalled:i,onSubagentBackgrounded:a,onSubagentCompleted:o,onTurnCancelled:s,onConnectionAuthRequired:c,onConnectionAuthCompleted:l,onRegistryHandoff:u,onTerminalFailure:d,failureHintOverride:f}=e,p=new Map,m=new Map,h=new Map,g=createEventDeduper(),_=0,v=new Set,y=new Set,b=new Set,x=!1,S=!1,C;for await(let e of t)if(g.admit(e)&&!(S&&isPostTurnVisibleEvent(e)))switch(e.type){case`session.started`:case`message.received`:break;case`turn.started`:r.turnId=e.data.turnId;break;case`step.started`:_+=1,yield{type:`step-start`};break;case`step.completed`:{let t=e;C=t.data.usage,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`step-finish`,usage:t.data.usage};break}case`message.appended`:{let t=e,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(p,n);if(r.completed){if(_<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}let i=t.data.messageDelta;if(i.length===0)break;r.text+=i,yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:i};break}case`message.completed`:{let t=textPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(p,t),r=e.data.message;if(n.completed){if(r===null||_<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=_,yield{type:`assistant-complete`,id:partGenerationId(t,n.generation),text:r};break}let i=partGenerationId(t,n.generation);if(r!==null){if(n.text.length===0)n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let e=r.slice(n.text.length);e.length>0&&(yield{type:`assistant-delta`,id:i,delta:e}),n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i}}else n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i,text:r}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let t=e,n=reasoningPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(m,n);if(r.completed){if(_<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}let i=t.data.reasoningDelta;if(i.length===0)break;r.text+=i,yield{type:`reasoning-delta`,id:partGenerationId(n,r.generation),delta:i};break}case`reasoning.completed`:{let t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(m,t),r=e.data.reasoning;if(n.completed){if(r.length===0||_<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=_;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}let i=partGenerationId(t,n.generation);if(n.text.length===0&&r.length>0)n.text=r,yield{type:`reasoning-delta`,id:i,delta:r};else if(r.length>0&&!r.startsWith(n.text)){yield{type:`reasoning-complete`,id:i},n.generation+=1,n.text=r,n.completed=!0,n.completedEpoch=_;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}n.completed=!0,n.completedEpoch=_,yield{type:`reasoning-complete`,id:i};break}case`actions.requested`:{let t=e.data.actions.filter(e=>e.kind===`tool-call`);if(t.length===0)break;for(let e of t)h.set(e.callId,e.toolName),!v.has(e.callId)&&(v.add(e.callId),yield{type:`tool-call`,toolCallId:e.callId,toolName:e.toolName,input:e.input});break}case`input.requested`:{let t=e.data.requests.filter(e=>e.action.kind===`tool-call`);if(t.length===0)break;for(let e of t){let t=e.action.callId;if(h.set(t,e.action.toolName),e.kind!==`session-limit`&&!v.has(t)&&(v.add(t),yield{type:`tool-call`,toolCallId:t,toolName:e.action.toolName,input:e.action.input}),!y.has(e.requestId)){if(y.add(e.requestId),n.set(e.requestId,e),e.kind!==`tool-approval`){upsertPendingQuestion(r,e);continue}upsertPendingApproval(r,e),yield{type:`tool-approval-request`,approvalId:e.requestId,toolCallId:t}}}break}case`action.result`:{let t=e;if(t.data.result.kind!==`tool-result`)break;let n=t.data.result.callId;if(!v.has(n))break;switch(t.data.status){case`completed`:{let e=t.data.result.output;yield{type:`tool-result`,toolCallId:n,output:e};let r=registryHandoffAddress(h.get(n),e);r!==void 0&&await u?.(r);break}case`failed`:yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)};break;case`rejected`:yield{type:`tool-rejected`,toolCallId:n,reason:formatActionResultError(t)}}break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,b,f);t&&(yield t);break}case`session.failed`:{r.sawSessionFailure=!0,d?.(e);let t=toFailureEvent(e,b,f);t&&(yield t),r.boundaryEvent=e.type,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C},x=!0;return}case`session.waiting`:case`session.completed`:r.boundaryEvent=e.type,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C},x=!0;return;case`turn.completed`:S=!0,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_);break;case`turn.cancelled`:s?.(e.data.turnId),yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`turn-cancelled`};break;case`subagent.called`:i?.(e);break;case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:{let t=e;t.data.backgroundTask===void 0?o?.(t.data.callId):a?.(t.data.callId);break}case`authorization.required`:c?.(e);break;case`authorization.completed`:l?.(e)}x||(yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{aborted:!1,pendingApprovals:[],pendingQuestions:[],sawSessionFailure:!1}}function upsertPendingApproval(e,t){let n=toAgentTUIToolApprovalRequest(t),r=e.pendingApprovals.findIndex(e=>e.approvalId===n.approvalId);r===-1?e.pendingApprovals.push(n):e.pendingApprovals[r]=n}function toAgentTUIToolApprovalRequest(e){return{approvalId:e.requestId,toolCallId:e.action.callId,toolName:e.action.toolName,input:e.action.input}}function upsertPendingQuestion(e,t){let n=e.pendingQuestions.findIndex(e=>e.requestId===t.requestId);n===-1?e.pendingQuestions.push(t):e.pendingQuestions[n]=t}function textPartId(e,t){return`text:${e}:${t}`}function reasoningPartId(e,t){return`reasoning:${e}:${t}`}function partStateFor(e,t){let n=e.get(t);return n===void 0&&(n={generation:0,text:``,completed:!1,completedEpoch:0},e.set(t,n)),n}function partGenerationId(e,t){return t===0?e:`${e}#${t}`}function*closeOpenParts(e,t,n){for(let[r,i]of e)i.completed||i.text.length===0||(i.completed=!0,i.completedEpoch=n,yield{type:t,id:partGenerationId(r,i.generation)})}function isPostTurnVisibleEvent(e){switch(e.type){case`actions.requested`:case`authorization.completed`:case`authorization.required`:case`input.requested`:case`message.appended`:case`message.completed`:case`reasoning.appended`:case`reasoning.completed`:case`result.completed`:case`step.completed`:case`step.failed`:case`step.started`:case`subagent.called`:case`subagent.completed`:case`subagent.event`:case`subagent.started`:case`turn.completed`:case`turn.failed`:return!0;default:return!1}}function formatActionResultError(e){if(e.data.error?.message)return e.data.error.message;let t=e.data.result.output;if(typeof t==`string`)return t;try{return JSON.stringify(t)}catch{return`Tool execution failed.`}}function toFailureEvent(e,t,n){let r=failureKey(e);if(t.has(r))return;t.add(r);let i={type:`error`,errorText:formatFailureMessage(e)},a=n?.(e)??formatFailureHint(e);a!==void 0&&(i.hint=a);let o=formatFailureDetail(e);return o!==void 0&&(i.detail=o),i}function toAgentTUIInputQuestion(e){let t=e.display===`text`?`text`:e.display===`select`||e.options!==void 0&&e.options.length>0?`select`:`text`,n={requestId:e.requestId,prompt:e.prompt,display:t};return e.options!==void 0&&(n.options=e.options.map(e=>{let t={id:e.id,label:e.label};return e.description!==void 0&&(t.description=e.description),e.style!==void 0&&(t.style=e.style),t})),e.allowFreeform!==void 0&&(n.allowFreeform=e.allowFreeform),n}export{EveTUIRunner,parsePromptCommand,registryHandoffAddress};
1
+ import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{pickAgentHeaderTip}from"./agent-header.js";import{failureKey,formatFailureDetail,formatFailureHint,formatFailureMessage,isInterruptedError,localFailureHint}from"./errors.js";import{parseLogDisplayMode}from"./log-display-mode.js";import{createMcpConnectionStatusTracker}from"./mcp-connection-status.js";import{createRemoteConnectionController}from"./remote-connection.js";import{SubagentPump}from"./subagent-pump.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,detectSetupIssues,formatSetupIssuesLine,normalizeLocalModelEndpoint,orderedSetupIssues}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import"#client/index.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{inspectApplication}from"#services/inspect-application.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{probeAgentInfo}from"#services/dev-client/agent-info-probe.js";import{renderApplicationInfo}from"#cli/commands/info.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{createDevelopmentRuntimeArtifactRefresher}from"#services/dev-client.js";async function delayMs(e){await new Promise(t=>{setTimeout(t,e).unref?.()})}async function abortableDelay(e,t){t.aborted||await new Promise(n=>{let r=setTimeout(done,e);r.unref?.(),t.addEventListener(`abort`,done,{once:!0});function done(){clearTimeout(r),t.removeEventListener(`abort`,done),n()}})}function authIssueForStatus(e){if(e===`logged-out`)return LOGIN_SETUP_ISSUE;if(e===`cli-missing`)return CLI_MISSING_SETUP_ISSUE}var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b=!1;#x;#S;#C;#w;#T;#E;#D;#O;#k=!1;#A=new AbortController;#j=!1;#M=[];#N;#P;#F;#I;#L;#R=new Map;#z;#B=[];#V;#H=!1;#U;#W=new Map;#G=new Set;#K;#q;#J;constructor(e){this.#e=e.session,e.client!==void 0&&(this.#t=e.client),e.lifecycle!==void 0&&(this.#J=e.lifecycle),this.#n=createRenderer(e);let t={formatActionResultError};if(this.#t!==void 0&&(t.client=this.#t),this.#n.subagents!==void 0&&(t.view=this.#n.subagents),e.appRoot!==void 0&&(t.onToolCompleted=async(e,t)=>{let n=registryHandoffAddress(e,t);n!==void 0&&this.#ue(n)}),this.#U=new SubagentPump(t),this.#r=e.name??`eve`,this.#I=e.startup?.headerTip??pickAgentHeaderTip(),this.#C=e.withExclusiveTerminal,this.#i=e.tools??`full`,this.#a=e.reasoning??`full`,this.#o=e.subagents??`full`,this.#s=e.connectionAuth??`full`,this.#c=e.assistantResponseStats??`tokensPerSecond`,this.#l=e.contextSize,this.#u=e.formatTransportError??toErrorMessage,e.initialInput!==void 0&&(this.#m=e.initialInput),e.startup!==void 0&&(this.#h=e.startup),this.#_=e.onboard===!0,this.#v=e.onOnboardingStep,this.#y=e.onOnboardingTerminal,e.appRoot!==void 0){this.#p=e.appRoot;let t={appRoot:e.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};e.detectProjectIdentity!==void 0&&(t.detectIdentity=e.detectProjectIdentity),this.#P=createVercelStatusTracker(t),e.probeMcpConnection!==void 0&&(this.#F=createMcpConnectionStatusTracker({onChange:()=>{},probe:e.probeMcpConnection}))}if(e.promptCommandHandler!==void 0&&(this.#x=e.promptCommandHandler),this.#S=e.availablePromptCommands??PROMPT_COMMANDS,e.remote!==void 0){if(this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#w=createRemoteConnectionController({client:this.#t,credentials:e.remote.credentials,target:e.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:e.remote.resolveOidcToken,resolveDeployment:e.remote.resolveDeployment})}this.#T=e.bootDetections??BOOT_DETECTIONS,this.#E=e.getVercelAuthStatus??getVercelAuthStatus,this.#D=e.inspectApplication??inspectApplication,e.onBootProgress!==void 0&&(this.#O=e.onBootProgress),e.serverUrl!==void 0&&(this.#f=e.serverUrl),e.serverUrl!==void 0&&e.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactRefresher({serverUrl:e.serverUrl}))}async#Y(){if(this.#f===void 0)return this.#Q(),this.#_||await this.#fe(void 0),this.#X();let e;if(this.#w!==void 0){let t=await this.#w.check();t.state===`ready`&&(e=t.info)}else{let t=this.#t;if(t!==void 0)try{let n=await devBootPhase(`connecting to agent`,()=>probeAgentInfo({client:t}),this.#O);n.kind===`ready`&&(e=n.info)}catch{e=void 0}}let t=this.#X();this.#Q();let n=this.#Z(e);return this.#_||await this.#fe(n),t}#X(){let e=this.#h?.finish();return this.#g=e?.queuedPrompt,e?.draft??this.#m}#Z(e){let t=this.#p===void 0?e:normalizeLocalModelEndpoint(e,process.env);this.#L=t;let n=this.#f;if(n===void 0||this.#b)return t;let r={name:this.#r,serverUrl:n};return t!==void 0&&(r.info=t),this.#p!==void 0&&(r.tip=this.#I),this.#n.renderAgentHeader?.(r),t}#Q(){let e=this.#O;this.#O=void 0,e?.({type:`before-first-paint`})}async run(){let onStop=()=>this.#n.requestInterrupt?.();this.#J?.signal.aborted===!0?onStop():this.#J?.signal.addEventListener(`abort`,onStop,{once:!0});try{await this.#$()}finally{this.#J?.signal.removeEventListener(`abort`,onStop),this.#k=!0,this.#A.abort(),this.#U.abortAll(),this.#q?.(),this.#q=void 0,this.#n.shutdown?.(),this.#P?.dispose(),this.#F?.dispose(),this.#w?.dispose()}}async#$(){let e=this.#r,t,n,r=!1,i=!1,a=!1,o=await this.#Y();if(this.#g!==void 0&&(t=this.#g),this.#w?.current().connection.state===`auth-required`&&await this.#xe({type:`extension`,name:`vc:login`,argument:``},e,{trigger:`startup`}),this.#ge(),this.#P?.refreshIdentity(),this.#F?.refresh(),this.#_&&this.#p!==void 0&&this.#x!==void 0&&this.#n.setupFlow!==void 0){o=void 0,this.#b=!0;try{await this.#Ce(e)}finally{this.#b=!1}}for(;;){if(this.#J?.signal.aborted===!0||this.#n.exitRequested?.()===!0)return;let s=this.#B[0];if(s!==void 0&&n===void 0&&this.#z===void 0){this.#B.shift(),this.#V=s;try{await this.#de(s)}finally{this.#V=void 0}i=!1,a=!1,t=void 0;continue}if(!a){if(t==null){if(!this.#n.readPrompt){if(r)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let n={title:e};o!==void 0&&(n.initialDraft=o,o=void 0);try{this.#H=!0,t=await this.#ie(n)}catch(e){if(isInterruptedError(e)){if(this.#z===void 0&&this.#B.length===0)return;a=!0,t=``}else throw e}finally{this.#H=!1}if(this.#B.length>0&&this.#z===void 0){t=void 0;continue}if(t==null&&this.#z===void 0)return}let s=this.#z===void 0?parsePromptCommand(t):null;if(s?.type===`exit`){this.#J?.requestStop();return}if(s?.type===`cancel`){if(this.#e===void 0){this.#_e(`No active turn to cancel.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.cancel();if(this.#_e(e.status===`accepted`?`Turn cancellation requested.`:`No active turn to cancel.`),e.status===`no_active_turn`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#_e(`Couldn't cancel the turn: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(s?.type===`reset`){if(!await this.#ne()){n=void 0,a=!1,t=void 0;continue}n=void 0,a=!1,t=void 0;continue}if(s?.type===`compact`){if(this.#e===void 0){this.#_e(`No active session to compact.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.compact();if(this.#_e(e.status===`accepted`?`Compaction requested.`:`No active session to compact.`),e.status===`no_active_session`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#_e(`Couldn't compact the session: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(s?.type===`clear`){if(this.#e===void 0){this.#_e(`No active session to clear.`),n=void 0,i=!1,a=!1,t=void 0;continue}try{let e=await this.#e.clear();if(this.#_e(e.status===`accepted`?`Context clear requested.`:`No active session to clear.`),e.status===`no_active_session`){n=void 0,i=!1,a=!1,t=void 0;continue}}catch(e){this.#_e(`Couldn't clear the session: ${toErrorMessage(e)}`),n=void 0,i=!1,a=!1,t=void 0;continue}n=void 0,i=!0,a=!1,t=void 0}if(s?.type===`help`){this.#_e(formatPromptCommandHelp(this.#S)),n=void 0,a=!1,t=void 0;continue}if(s?.type===`info`){await this.#Ee(),n=void 0,a=!1,t=void 0;continue}if(s?.type===`loglevel`){this.#_e(this.#De(s.argument)),n=void 0,a=!1,t=void 0;continue}if(s?.type===`traces`){await this.#Te(s.argument),n=void 0,a=!1,t=void 0;continue}if(s?.type===`extension`){try{await this.#xe(s,e,{trigger:`command`})}catch(e){if(isInterruptedError(e))return;throw e}n=void 0,t=void 0,a=!1;continue}r=!0}let c=this.#z;this.#z=void 0;let l=c??(i?this.#ce():await(async()=>(this.#te(),await this.#oe({prompt:a?void 0:t,inputResponses:n})))()),u=this.#e?.state.sessionId;u!==void 0&&this.#n.setSessionId?.(u);let d=t,f=!1;try{for(;;){await this.#n.renderStream(l,{title:e,submittedPrompt:d,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let r=l.turnState?.pendingApprovals??[],i=l.turnState?.pendingQuestions??[];if(r.length>0||i.length>0){let o=[];if(r.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let t of r){let n=await this.#n.readToolApproval(t,{title:e});o.push({requestId:t.approvalId,optionId:n.approved?`approve`:`cancel`}),this.#R.delete(t.approvalId)}}if(i.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let t of i){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let i={requestId:t.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),o.push(i),this.#R.delete(t.requestId)}}if(o.length===0)break;a=!0,n=o,t=void 0,f=!0;break}if(this.#Me(l)){l=this.#ce(),d=void 0;continue}if(l.turnState&&l.turnState.boundaryEvent===void 0&&!l.turnState.aborted){let e=this.#e?.state.sessionId;this.#n.renderNotice?.(e?`Lost the event stream — the turn may still be running on the server (session ${e}). Your next message resumes this session; use /cancel to stop the turn.`:`Lost the connection to the running turn.`)}break}}catch(e){if(isInterruptedError(e))return;throw e}if(f)continue;i=!1,a=!1,n=void 0,t=void 0;let p=l.turnState?.boundaryEvent;this.#K!==this.#e&&(p===`session.waiting`||p===`session.completed`)&&(t=this.#n.takeQueuedPrompt?.()),this.#te(l.turnState?.aborted===!0)}}#ee(){this.#U.abortAll(),this.#R.clear(),this.#W.clear(),this.#G.clear(),this.#n.setConnectionAuthPendingCount?.(0),this.#e=void 0,this.#d?.clear()}#te(e=!1){let t=this.#K;t!==void 0&&(this.#K=void 0,this.#e===t&&(this.#ee(),e?this.#n.renderNotice?.(`Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server.`):this.#n.renderSessionBoundary===void 0?this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`):this.#n.renderSessionBoundary()))}async#ne(){if(this.#e===void 0)return this.#ee(),this.#n.reset?.(),!0;try{await this.#e.reset()}catch(e){return this.#n.renderNotice?.(`Couldn't reset the session: ${toErrorMessage(e)}`),!1}return this.#ee(),this.#n.reset?.(),!0}async#re(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#d;if(n===void 0)return await t;let r=!1,i=!1,a,o=0,refresh=async()=>{if(!(r||i)){i=!0;try{await n.refreshIdle({onRuntimeArtifactsChanged:()=>this.#Ae()});let e=this.#L?.agent.model.endpoint,t=e?.kind===`chatgpt`&&(e.state===`signed-out`||e.state===`reauth-required`),r=Date.now();if(t&&r-o>=5e3){o=r;let e=await this.#ke();e!==void 0&&this.#Z(e)}}finally{i=!1}}},startRefresh=()=>{if(r||i)return;let e=refresh().finally(()=>{a===e&&(a=void 0)});a=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await t}finally{r=!0,clearInterval(s),await a}}async#ie(e){let t=this.#re(e);if(this.#n.renderIdleStream===void 0||this.#e?.state.sessionId===void 0)return await t;let n=new AbortController,r=this.#ae(n.signal,e).catch(e=>{n.signal.aborted||this.#n.renderNotice?.(`Stopped following session updates: ${toErrorMessage(e)}`)});try{return await t}finally{n.abort(),await r}}async#ae(e,t){let n=this.#e;if(n===void 0)return;let r=100;for(;!e.aborted;){let i=n.stream({signal:e})[Symbol.asyncIterator](),a=!1;try{for(;!e.aborted;){let r=!1,o={async*[Symbol.asyncIterator](){for(;!e.aborted;){let e=await i.next();if(e.done===!0||(r=!0,a=!0,yield e.value,isCurrentTurnBoundaryEvent(e.value)))return}}},s=this.#le(o,()=>{},n);if(await this.#n.renderIdleStream(s,{...t,continueSession:!0}),this.#Me(s),(s.turnState?.pendingApprovals.length??0)>0||(s.turnState?.pendingQuestions.length??0)>0){this.#z={events:(async function*(){})(),turnState:s.turnState},this.#n.suspendPromptForInput?.();return}if(s.turnState?.boundaryEvent===`session.completed`||s.turnState?.boundaryEvent===`session.failed`)return;if(!r)break}}finally{await i.return?.()}r=a?100:Math.min(r*2,2e3),e.aborted||await abortableDelay(r,e)}}async#oe(e){let t=new AbortController,n={signal:t.signal};e.prompt!==void 0&&(n.message=e.prompt),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses);let r,i=this.#e;try{if(this.#d!==void 0&&await this.#d.refresh({inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#Ae()}),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),this.#e===void 0){if(this.#t===void 0)throw Error(`Cannot create a session without an eve client.`);if(n.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let e=await this.#t.sessions.create({...n,message:n.message});this.#e=e.session,r=e.response}else r=n.inputResponses===void 0?await this.#e.send(n.message,{signal:n.signal,turnPolicy:`queue`}):await this.#e.respond(n.inputResponses,{signal:n.signal})}catch(e){if(isInterruptedError(e))throw e;return this.#w?.reportFailure(e),this.#K=i,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}return this.#le(r,()=>t.abort(),this.#e)}async#se(e,t){if(e.cancelInFlight!==!0){e.cancelInFlight=!0;try{for(let n=0;n<8;n+=1){if(e.boundaryEvent!==void 0||e.aborted===!0)return;let n=e.turnId;try{if((await t?.cancel(n===void 0?void 0:{turnId:n}))?.status===`accepted`)return}catch{}await delayMs(250)}}finally{e.cancelInFlight=!1}}}#ce(){if(this.#e===void 0)throw Error(`Cannot stream a session before its first turn is accepted.`);let e=new AbortController,t=this.#e;return this.#le(t.stream({signal:e.signal}),()=>e.abort(),t)}#le(e,t,n){let r=createTurnState();return{abort:()=>{r.aborted=!0,this.#K=n,t()},cancel:()=>{this.#se(r,n)},events:eveEventsToTUIStream({events:e,pendingInputRequests:this.#R,turnState:r,onSubagentCalled:e=>this.#U.begin(e),onSubagentBackgrounded:e=>this.#U.background(e),onSubagentCompleted:e=>this.#U.settle(e),onTurnCancelled:e=>this.#U.settleCancelledTurn(e),onConnectionAuthRequired:e=>this.#je(e),onConnectionAuthCompleted:e=>this.#Ne(e),onRegistryHandoff:this.#p===void 0?void 0:async e=>this.#ue(e),onTerminalFailure:()=>{this.#K=n},failureHintOverride:this.#p===void 0?void 0:localFailureHint}),turnState:r}}#ue(e){this.#V===e||this.#B.includes(e)||(this.#B.push(e),this.#H&&this.#n.suspendPromptForInput?.())}async#de(e){await this.#xe({type:`extension`,name:`add`,argument:e},`Add to your agent`,{trigger:`command`})}async#fe(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#M=await detectSetupIssues(t,this.#T),this.#n.renderSetupWarning!==void 0&&(this.#pe(),this.#me())}#pe(){let e=orderedSetupIssues(this.#M,this.#N);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#me(){let e=this.#p;if(e===void 0)return;let t;try{t=await this.#E(e,{signal:this.#A.signal})}catch{return}this.#k||this.#j||(this.#N=authIssueForStatus(t),this.#pe())}async#he(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n={appRoot:t,env:process.env};e!==void 0&&(n.info=e);try{this.#M=await detectSetupIssues(n,this.#T);let e=await this.#E(t,{signal:this.#A.signal});this.#N=authIssueForStatus(e)}catch{return}this.#k||this.#pe()}#ge(){this.#p!==void 0&&this.#n.renderSandboxLog!==void 0&&this.#q===void 0&&(this.#q=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#_e(e,t){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e,t);return}this.#n.renderNotice?.(e)}}async#ve(e,t){let n=this.#x;if(n===void 0)return{message:`/${e.name} is not available in this session.`};let r=this.#L?.agent.model.endpoint,i={...t,renderer:this.#n,chatGptAccountLabel:r?.kind===`chatgpt`&&r.state===`ready`?r.accountLabel:void 0,remoteConnection:this.#w,withExclusiveTerminal:this.#C},a=this.#F?.current(),o=a!==void 0&&Object.keys(a).length>0?{...i,disabledConnectionReasons:a}:i;return t.keepSetupFlowOpen===!0?await n.handle(e,{...o,keepSetupFlowOpen:!0}):await n.handle(e,o)}#ye(e,t,n){if(t!==`startup`)return;let r=this.#w?.current().connection.state,i=n===`error`||r===`auth-failed`||r===`unavailable`?`failed`:void 0,a=e.argument.length===0?``:` ${e.argument}`;this.#n.renderCommandInvocation?.(`/${e.name}${a}`,i)}async#be(e){if(e?.kind===`model-access-changed`){this.#P?.applyEffect({kind:`refresh-identity`}),this.#j=!0,await this.#Oe();return}e!==void 0&&(this.#P?.applyEffect(e),this.#j=!0,this.#he(this.#L))}async#xe(e,t,n){let r=await this.#ve(e,{...n,title:t}),i=n.suppressSuccessfulTranscript===!0&&r?.tone!==`error`||n.suppressCancelledTranscript===!0&&r?.cancelled===!0;return i||this.#ye(e,n.trigger,r?.tone),i||this.#_e(r?.message,r?.tone),await this.#be(r?.effect),this.#we(),r}#Se(e){return{kind:`planner`,activeStep:e,firstNavigableStep:1,steps:[{label:`Model`,complete:e>0},{label:`Channels`},{label:`Integrations`},{label:`Review`}]}}async#Ce(e){let t={keepSetupFlowOpen:!0,setupFlowTitle:`Set up ${e}`,trigger:`startup`},n=`model_provider`,onOnboardingScreen=e=>{n=e.screen,this.#v?.({flow:`onboarding`,step:e.screen,registrySelectedCount:e.registrySelectedCount})};onOnboardingScreen({screen:`model_provider`});let r;try{r=await this.#xe({type:`extension`,name:`model`,argument:``},e,{...t,suppressSuccessfulTranscript:!0,initialModelStep:`provider`,setupFlowNavigation:this.#Se(0),onOnboardingScreen})}catch(e){throw this.#y?.({flow:`onboarding`,step:n,result:`error`}),e}if(r?.tone===`error`||r?.cancelled===!0){this.#y?.({flow:`onboarding`,step:n,result:r.cancelled===!0?`cancelled`:`error`}),this.#n.setupFlow?.end({preserveDiagnostics:r.tone===`error`});return}let i;n=`registry_channels`;let onRegistryScreen=e=>{n=e.screen,this.#v?.({flow:`onboarding`,step:e.screen,registrySelectedCount:e.registrySelectedCount})};try{onRegistryScreen({screen:`registry_channels`}),i=await this.#xe({type:`extension`,name:`add`,argument:``},e,{...t,onOnboardingScreen:onRegistryScreen,registryPlannerContext:{prefixSteps:[{label:`Model`,complete:!0}],reviewMessage:`Review your agent`,primaryActionLabel:`Install and finish setup`,emptyActionLabel:`Finish setup`}})}catch(e){throw this.#y?.({flow:`onboarding`,step:n,result:`error`}),e}finally{i!==void 0&&this.#y?.({flow:`onboarding`,step:n,result:i.cancelled===!0?`cancelled`:i.tone===`error`?`error`:`completed`}),this.#n.setupFlow?.end({preserveDiagnostics:i?.tone===`error`})}}#we(){if(this.#b)return;let e=this.#w?.current().connection;e?.state===`ready`&&e.info!==this.#L&&(this.#L=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}async#Te(e){if(this.#p===void 0||this.#n.traceViewer===void 0){this.#_e(`/traces is only available in local dev sessions.`);return}try{await this.#n.traceViewer.open({appRoot:this.#p,sessionId:this.#e?.state.sessionId,reference:e===``?void 0:e})}catch(e){if(isInterruptedError(e))return;throw e}}async#Ee(){let e=this.#p;if(e===void 0){this.#_e(`/info is only available in local dev sessions.`);return}try{this.#_e(renderApplicationInfo(await this.#D(e)))}catch(e){this.#_e(`Couldn't inspect the application: ${toErrorMessage(e)}`,`error`)}}#De(e){let t=this.#n;if(t.logDisplayMode===void 0||t.setLogDisplayMode===void 0)return`/loglevel is not available in this session.`;if(e===``)return`Logs: ${t.logDisplayMode()}. Use /loglevel all|stderr|sandbox|none — logs stay buffered, so switching also hides or restores past lines.`;let n=parseLogDisplayMode(e);if(n===void 0)return`Unknown log level "${e}". Use all, stderr, sandbox, or none.`;if(n===t.logDisplayMode())return`Logs already set to ${n}.`;switch(t.setLogDisplayMode(n),n){case`none`:return`Logs hidden. Output stays buffered — /loglevel all restores it.`;case`stderr`:return`Showing stderr logs only.`;case`sandbox`:return`Showing sandbox logs only.`;case`all`:return`Showing all logs.`}}async#Oe(){let e=this.#p;if(e===void 0)return;await loadDevelopmentEnvironmentFiles(e),await this.#d?.refreshAfterSourceChange({});let t=this.#Z(await this.#ke());this.#he(t)}async#ke(){let e=this.#t;if(e===void 0)return;let t=await probeAgentInfo({client:e});return t.kind===`ready`?t.info:void 0}async#Ae(){let e=this.#L,t=await this.#ke();t!==void 0&&this.#Z(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#je(e){let t={name:e.data.name,description:e.data.description,state:`required`};e.data.authorization!==void 0&&(t.challenge=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),this.#W.set(e.data.name,t),this.#Pe(t)}#Me(e){if(e.turnState?.boundaryEvent!==`session.waiting`)return!1;let t=!1;for(let e of this.#W.values())e.state===`required`&&e.webhookUrl!==void 0&&(e.state=`pending`,this.#G.add(e.name),this.#Pe(e),t=!0);return t&&this.#n.setConnectionAuthPendingCount?.(this.#G.size),this.#G.size>0}#Ne(e){let t=this.#W.get(e.data.name)??{name:e.data.name,description:``,state:e.data.outcome};t.state=e.data.outcome,e.data.reason!==void 0&&(t.reason=e.data.reason),this.#W.set(e.data.name,t),this.#G.delete(e.data.name),this.#Pe(t),this.#n.setConnectionAuthPendingCount?.(this.#G.size)}#Pe(e){let t={name:e.name,description:e.description,state:e.state};e.challenge!==void 0&&(t.challenge=e.challenge),e.reason!==void 0&&(t.reason=e.reason),this.#n.upsertConnectionAuth?.(t)}};function createRenderer(e){return e.renderer?e.renderer:new TerminalRenderer({tools:e.tools,reasoning:e.reasoning,subagents:e.subagents,connectionAuth:e.connectionAuth,assistantResponseStats:e.assistantResponseStats,contextSize:e.contextSize,logs:e.logs,availablePromptCommands:e.availablePromptCommands,input:e.userInput,output:e.screen,diagnostics:e.diagnostics,onExitRequest:e.lifecycle?.requestStop})}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id,r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}function registryHandoffAddress(e,t){if(e!==`selfmod__registry_add`||typeof t!=`object`||!t)return;let n=t;return n.status===`needs-terminal`&&typeof n.address==`string`?n.address:void 0}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,turnState:r,onSubagentCalled:i,onSubagentBackgrounded:a,onSubagentCompleted:o,onTurnCancelled:s,onConnectionAuthRequired:c,onConnectionAuthCompleted:l,onRegistryHandoff:u,onTerminalFailure:d,failureHintOverride:f}=e,p=new Map,m=new Map,h=new Map,g=createEventDeduper(),_=0,v=new Set,y=new Set,b=new Set,x=!1,S=!1,C;for await(let e of t)if(g.admit(e)&&!(S&&isPostTurnVisibleEvent(e)))switch(e.type){case`session.started`:case`message.received`:break;case`turn.started`:r.turnId=e.data.turnId;break;case`step.started`:_+=1,yield{type:`step-start`};break;case`step.completed`:{let t=e;C=t.data.usage,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`step-finish`,usage:t.data.usage};break}case`message.appended`:{let t=e,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(p,n);if(r.completed){if(_<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}let i=t.data.messageDelta;if(i.length===0)break;r.text+=i,yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:i};break}case`message.completed`:{let t=textPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(p,t),r=e.data.message;if(n.completed){if(r===null||_<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=_,yield{type:`assistant-complete`,id:partGenerationId(t,n.generation),text:r};break}let i=partGenerationId(t,n.generation);if(r!==null){if(n.text.length===0)n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let e=r.slice(n.text.length);e.length>0&&(yield{type:`assistant-delta`,id:i,delta:e}),n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i}}else n.text=r,n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i,text:r}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=_,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let t=e,n=reasoningPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(m,n);if(r.completed){if(_<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}let i=t.data.reasoningDelta;if(i.length===0)break;r.text+=i,yield{type:`reasoning-delta`,id:partGenerationId(n,r.generation),delta:i};break}case`reasoning.completed`:{let t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(m,t),r=e.data.reasoning;if(n.completed){if(r.length===0||_<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=_;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}let i=partGenerationId(t,n.generation);if(n.text.length===0&&r.length>0)n.text=r,yield{type:`reasoning-delta`,id:i,delta:r};else if(r.length>0&&!r.startsWith(n.text)){yield{type:`reasoning-complete`,id:i},n.generation+=1,n.text=r,n.completed=!0,n.completedEpoch=_;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}n.completed=!0,n.completedEpoch=_,yield{type:`reasoning-complete`,id:i};break}case`actions.requested`:{let t=e.data.actions.filter(e=>e.kind===`tool-call`);if(t.length===0)break;for(let e of t)h.set(e.callId,e.toolName),!v.has(e.callId)&&(v.add(e.callId),yield{type:`tool-call`,toolCallId:e.callId,toolName:e.toolName,input:e.input});break}case`input.requested`:{let t=e.data.requests.filter(e=>e.action.kind===`tool-call`);if(t.length===0)break;for(let e of t){let t=e.action.callId;if(h.set(t,e.action.toolName),e.kind!==`session-limit`&&!v.has(t)&&(v.add(t),yield{type:`tool-call`,toolCallId:t,toolName:e.action.toolName,input:e.action.input}),!y.has(e.requestId)){if(y.add(e.requestId),n.set(e.requestId,e),e.kind!==`tool-approval`){upsertPendingQuestion(r,e);continue}upsertPendingApproval(r,e),yield{type:`tool-approval-request`,approvalId:e.requestId,toolCallId:t}}}break}case`action.result`:{let t=e;if(t.data.result.kind!==`tool-result`)break;let n=t.data.result.callId;if(!v.has(n))break;switch(t.data.status){case`completed`:{let e=t.data.result.output;yield{type:`tool-result`,toolCallId:n,output:e};let r=registryHandoffAddress(h.get(n),e);r!==void 0&&await u?.(r);break}case`failed`:yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)};break;case`rejected`:yield{type:`tool-rejected`,toolCallId:n,reason:formatActionResultError(t)}}break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,b,f);t&&(yield t);break}case`session.failed`:{r.sawSessionFailure=!0,d?.(e);let t=toFailureEvent(e,b,f);t&&(yield t),r.boundaryEvent=e.type,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C},x=!0;return}case`session.waiting`:case`session.completed`:r.boundaryEvent=e.type,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C},x=!0;return;case`turn.completed`:S=!0,yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_);break;case`turn.cancelled`:s?.(e.data.turnId),yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`turn-cancelled`};break;case`subagent.called`:i?.(e);break;case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:{let t=e;t.data.backgroundTask===void 0?o?.(t.data.callId):a?.(t.data.callId);break}case`authorization.required`:c?.(e);break;case`authorization.completed`:l?.(e)}x||(yield*closeOpenParts(p,`assistant-complete`,_),yield*closeOpenParts(m,`reasoning-complete`,_),yield{type:`finish`,usage:C})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{aborted:!1,pendingApprovals:[],pendingQuestions:[],sawSessionFailure:!1}}function upsertPendingApproval(e,t){let n=toAgentTUIToolApprovalRequest(t),r=e.pendingApprovals.findIndex(e=>e.approvalId===n.approvalId);r===-1?e.pendingApprovals.push(n):e.pendingApprovals[r]=n}function toAgentTUIToolApprovalRequest(e){return{approvalId:e.requestId,toolCallId:e.action.callId,toolName:e.action.toolName,input:e.action.input}}function upsertPendingQuestion(e,t){let n=e.pendingQuestions.findIndex(e=>e.requestId===t.requestId);n===-1?e.pendingQuestions.push(t):e.pendingQuestions[n]=t}function textPartId(e,t){return`text:${e}:${t}`}function reasoningPartId(e,t){return`reasoning:${e}:${t}`}function partStateFor(e,t){let n=e.get(t);return n===void 0&&(n={generation:0,text:``,completed:!1,completedEpoch:0},e.set(t,n)),n}function partGenerationId(e,t){return t===0?e:`${e}#${t}`}function*closeOpenParts(e,t,n){for(let[r,i]of e)i.completed||i.text.length===0||(i.completed=!0,i.completedEpoch=n,yield{type:t,id:partGenerationId(r,i.generation)})}function isPostTurnVisibleEvent(e){switch(e.type){case`actions.requested`:case`authorization.completed`:case`authorization.required`:case`input.requested`:case`message.appended`:case`message.completed`:case`reasoning.appended`:case`reasoning.completed`:case`result.completed`:case`step.completed`:case`step.failed`:case`step.started`:case`subagent.called`:case`subagent.completed`:case`subagent.event`:case`subagent.started`:case`turn.completed`:case`turn.failed`:return!0;default:return!1}}function formatActionResultError(e){if(e.data.error?.message)return e.data.error.message;let t=e.data.result.output;if(typeof t==`string`)return t;try{return JSON.stringify(t)}catch{return`Tool execution failed.`}}function toFailureEvent(e,t,n){let r=failureKey(e);if(t.has(r))return;t.add(r);let i={type:`error`,errorText:formatFailureMessage(e)},a=n?.(e)??formatFailureHint(e);a!==void 0&&(i.hint=a);let o=formatFailureDetail(e);return o!==void 0&&(i.detail=o),i}function toAgentTUIInputQuestion(e){let t=e.display===`text`?`text`:e.display===`select`||e.options!==void 0&&e.options.length>0?`select`:`text`,n={requestId:e.requestId,prompt:e.prompt,display:t};return e.options!==void 0&&(n.options=e.options.map(e=>{let t={id:e.id,label:e.label};return e.description!==void 0&&(t.description=e.description),e.style!==void 0&&(t.style=e.style),t})),e.allowFreeform!==void 0&&(n.allowFreeform=e.allowFreeform),n}export{EveTUIRunner,parsePromptCommand,registryHandoffAddress};
@@ -36,6 +36,7 @@ export type TerminalRendererOptions = {
36
36
  logs?: LogDisplayMode;
37
37
  color?: boolean;
38
38
  unicode?: boolean;
39
+ renderMarkdown?: boolean;
39
40
  /** The process's diagnostics recorder (log, dump, stats); local sessions only. */
40
41
  diagnostics?: DevDiagnostics;
41
42
  /** Slash commands available in this local or remote session. */
@@ -69,7 +70,10 @@ export declare class TerminalRenderer implements AgentTUIRenderer {
69
70
  tip: string;
70
71
  title: string;
71
72
  }): void;
72
- finishStartupDraft(): string;
73
+ finishStartupDraft(): {
74
+ draft: string;
75
+ queuedPrompt: string | undefined;
76
+ };
73
77
  readPrompt(options?: AgentTUISessionOptions): Promise<string>;
74
78
  /**
75
79
  * Consumes the next prompt produced by mid-turn input — the staged Esc
@@ -1,15 +1,15 @@
1
- import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{copyTextToClipboard}from"./clipboard.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{interruptedError}from"./errors.js";import{FileContentCache}from"./file-content-cache.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{MessageQueue,renderMessageQueueRows}from"./message-queue.js";import{initialModelEditorState,transitionModelEditor}from"./model-editor.js";import{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{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompleteOsc,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{TraceViewerSession}from"./traces/trace-viewer-session.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{TurnClock}from"./turn-clock.js";import{allTodoItemsSettled,readTodoToolItems,renderFinishedTodoRows,renderTodoPanelRows}from"./todo-panel.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{BACKGROUND_COLOR_QUERY,parseBackgroundColorReply}from"./terminal-background.js";import{inspectError}from"#internal/logging.js";import{eveVersionTag}from"#cli/banner.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{initialSelectState,orderedSelection,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{LiveRegion}from"#cli/ui/live-region.js";import{AltScreen}from"#cli/ui/alt-screen.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";import{readGatewayServiceTier}from"#shared/gateway-service-tier.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e){return e.interrupted?`Interrupted`:e.cancelled?`Cancelled`:e.continueSession?`Ready`:`Done`}const incompletePasteFlushMs=1e3,STATUS={processing:`Working…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=[];#h=new Map;#g=new Set;#_=[];#v=new Set;#y=new Map;#b=0;#x=new Map;#S=new Set;#C=new Set;#w=new FileContentCache;#T=new Set;#E;#D;#O=!1;#k;#A=[];#j;#M=0;#N;#P;#F=``;#I=0;#L=new PromptHistory;#R=!1;#z;#B=!1;#V=Date.now();#H=!1;#U=new TurnClock;#W=EMPTY_LINE;#G=!1;#K={kind:`idle`};#q;#J=STATUS.processing;#Y;#X=`eve`;#Z=!1;#Q=!1;#$=!1;#ee=!1;#te=!1;#ne=!1;#re=!1;#ie;#ae=!0;#oe=0;#se=Date.now();#ce;#le;#ue;#de=!1;#fe;#pe=``;#me=new StringDecoder(`utf8`);#he;#ge;#_e;#ve=!1;#ye=!1;#be;#xe;#Se;#Ce;#we;#Te;#Ee;#De=``;#Oe=``;#ke;#Ae;#je;#Me=!1;#Ne;#Pe=0;#Fe;#Ie;#Le;#Re;#ze;#Be;#Ve=new MessageQueue;#He;#Ue=!1;#We;#Ge;#Ke=!1;#qe;#Je;#Ye;#Xe;#Ze;setupFlow={begin:(e,t)=>this.#rt(e,t),setNavigation:e=>this.#it(e),end:e=>this.#at(e?.preserveDiagnostics??!0),readSelect:e=>this.#ot(e),readEditableSelect:e=>this.#ct(e),readProviderPicker:e=>this.#lt(e),readModelEditor:e=>this.#ut(e),readText:e=>this.#dt(e),readAcknowledge:e=>this.#ft(e),readChoice:e=>this.#st(e),setStatus:e=>this.#bt(e),renderLine:(e,t)=>this.#xt(e,t),replaceContent:e=>this.#St(e),renderOutput:e=>this.#Ct(e),withInheritedStdio:e=>this.#wt(e),withExclusiveTerminal:e=>this.#wt(e),waitForInterrupt:e=>this.#_t(e)};traceViewer={open:e=>this.#Et(e)};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=new AltScreen(this.#t),this.#i=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#a=e?.tools??`auto-collapsed`,this.#o=e?.reasoning??`auto-collapsed`,this.#s=e?.subagents??`auto-collapsed`,this.#c=e?.connectionAuth??`full`,this.#l=e?.assistantResponseStats??`tokensPerSecond`,this.#Se=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#d=e?.diagnostics,this.#ie=e?.onExitRequest,this.#p=e?.logs??`none`,this.#f=e?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#X=e.name,this.#E=e,this.#kt();let t=this.#yn().join(`
2
- `);if(this.#O){t!==this.#k&&(this.#k=t,this.#Kt({kind:`agent-header`,body:t,live:!1})),this.#mn();return}this.#O=!0,this.#k=t,this.#n.flush(this.#yn(),[])}beginStartupDraft(e){this.#kt({title:e.title}),this.#R=!0,this.#B=!0,this.#D={name:e.title,tip:e.tip};let t=lineOf(stripPromptControlCharacters(e.initialDraft??``));this.#Qe(t),this.#Bt(),this.#mn();let apply=e=>{t=e,this.#Ht(),this.#Qe(t),this.#mn()};this.#fe=e=>{let n=applyLineEditorKey(t,e,{multiline:!0});if(n!==void 0){apply(n);return}e.type===`ctrl-c`&&this.#ie?.()},this.#Mt()}finishStartupDraft(){let e=this.#F;return this.#Nt(),this.#Vt(),this.#R=!1,this.#D=void 0,this.#B=!1,e}async readPrompt(e){this.#kt(e),this.#Gt(),this.#Jt(),this.#R=!0,this.#B=!0,this.#K={kind:`idle`},this.#J=``,this.#ne=this.#re,this.#re=!1;let t=this.#Ve.restoreDraft()?.split(`
1
+ import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.js";import{detectMarkdownRendering}from"./markdown.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{copyTextToClipboard}from"./clipboard.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{interruptedError}from"./errors.js";import{FileContentCache}from"./file-content-cache.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{MessageQueue,renderMessageQueueRows}from"./message-queue.js";import{initialModelEditorState,transitionModelEditor}from"./model-editor.js";import{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{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompleteOsc,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{TraceViewerSession}from"./traces/trace-viewer-session.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{TurnClock}from"./turn-clock.js";import{allTodoItemsSettled,readTodoToolItems,renderFinishedTodoRows,renderTodoPanelRows}from"./todo-panel.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{BACKGROUND_COLOR_QUERY,parseBackgroundColorReply}from"./terminal-background.js";import{inspectError}from"#internal/logging.js";import{eveVersionTag}from"#cli/banner.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{initialSelectState,orderedSelection,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{LiveRegion}from"#cli/ui/live-region.js";import{AltScreen}from"#cli/ui/alt-screen.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";import{readGatewayServiceTier}from"#shared/gateway-service-tier.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e){return e.interrupted?`Interrupted`:e.cancelled?`Cancelled`:e.continueSession?`Ready`:`Done`}const incompletePasteFlushMs=1e3,STATUS={processing:`Working…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h=[];#g=new Map;#_=new Set;#v=[];#y=new Set;#b=new Map;#x=0;#S=new Map;#C=new Set;#w=new Set;#T=new FileContentCache;#E=new Set;#D;#O;#k=!1;#A;#j=[];#M;#N=0;#P;#F;#I=``;#L=0;#R=new PromptHistory;#z=!1;#B;#V=!1;#H=Date.now();#U=!1;#W=new TurnClock;#G=EMPTY_LINE;#K=!1;#q={kind:`idle`};#J;#Y=STATUS.processing;#X;#Z=`eve`;#Q=!1;#$=!1;#ee=!1;#te=!1;#ne=!1;#re=!1;#ie=!1;#ae;#oe=!0;#se=0;#ce=Date.now();#le;#ue;#de;#fe=!1;#pe;#me=``;#he=new StringDecoder(`utf8`);#ge;#_e;#ve;#ye=!1;#be=!1;#xe;#Se;#Ce;#we;#Te;#Ee;#De;#Oe=``;#ke=``;#Ae;#je;#Me;#Ne=!1;#Pe;#Fe=0;#Ie;#Le;#Re;#ze;#Be;#Ve;#He=new MessageQueue;#Ue;#We=!1;#Ge;#Ke;#qe=!1;#Je;#Ye;#Xe;#Ze;#Qe;setupFlow={begin:(e,t)=>this.#it(e,t),setNavigation:e=>this.#at(e),end:e=>this.#ot(e?.preserveDiagnostics??!0),readSelect:e=>this.#st(e),readEditableSelect:e=>this.#lt(e),readProviderPicker:e=>this.#ut(e),readModelEditor:e=>this.#dt(e),readText:e=>this.#ft(e),readAcknowledge:e=>this.#pt(e),readChoice:e=>this.#ct(e),setStatus:e=>this.#xt(e),renderLine:(e,t)=>this.#St(e,t),replaceContent:e=>this.#Ct(e),renderOutput:e=>this.#wt(e),withInheritedStdio:e=>this.#Tt(e),withExclusiveTerminal:e=>this.#Tt(e),waitForInterrupt:e=>this.#vt(e)};traceViewer={open:e=>this.#Dt(e)};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=new AltScreen(this.#t),this.#i=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#a=e?.renderMarkdown??detectMarkdownRendering(),this.#o=e?.tools??`auto-collapsed`,this.#s=e?.reasoning??`auto-collapsed`,this.#c=e?.subagents??`auto-collapsed`,this.#l=e?.connectionAuth??`full`,this.#u=e?.assistantResponseStats??`tokensPerSecond`,this.#Ce=e?.contextSize,this.#d=e?.captureForeignOutput??this.#t===process.stdout,this.#f=e?.diagnostics,this.#ae=e?.onExitRequest,this.#m=e?.logs??`none`,this.#p=e?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#Z=e.name,this.#D=e,this.#At();let t=this.#xn().join(`
2
+ `);if(this.#k){t!==this.#A&&(this.#A=t,this.#qt({kind:`agent-header`,body:t,live:!1})),this.#gn();return}this.#k=!0,this.#A=t,this.#n.flush(this.#xn(),[])}beginStartupDraft(e){this.#At({title:e.title}),this.#z=!0,this.#V=!0,this.#O={name:e.title,tip:e.tip};let t=lineOf(stripPromptControlCharacters(e.initialDraft??``));this.#$e(t),this.#Vt(),this.#gn();let apply=e=>{t=e,this.#Ut(),this.#$e(t),this.#gn()};this.#pe=e=>{let n=applyLineEditorKey(t,e,{multiline:!0});if(n!==void 0){apply(n);return}if(e.type===`enter`&&t.text.trim().length>0){this.#He.enqueue(t.text)&&apply(EMPTY_LINE);return}e.type===`ctrl-c`&&this.#ae?.()},this.#Nt()}finishStartupDraft(){let e={draft:this.#I,queuedPrompt:this.#He.takePrompt()};return this.#Pt(),this.#Ht(),this.#z=!1,this.#O=void 0,this.#V=!1,e}async readPrompt(e){this.#At(e),this.#Kt(),this.#Yt(),this.#z=!0,this.#V=!0,this.#q={kind:`idle`},this.#Y=``,this.#re=this.#ie,this.#ie=!1;let t=this.#He.restoreDraft()?.split(`
3
3
  `).map(stripPromptControlCharacters).join(`
4
- `),n=stripPromptControlCharacters(e?.initialDraft??this.#W.text),r=t===void 0?n:n.length===0?t:`${t}\n\n${n}`,i=lineOf(r);return this.#W=EMPTY_LINE,this.#L.begin(i.text),this.#Qe(i),this.#z=typeaheadFor(this.#f,i.text),this.#Bt(),this.#mn(),await new Promise((e,t)=>{this.#q=t;let apply=e=>{i=e,this.#Ht(),this.#Qe(i),this.#z=typeaheadFor(this.#f,e.text,this.#z),this.#mn()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#z=void 0,this.#Vt(),this.#jt(),t(interruptedError())},suggestions=()=>this.#z!==void 0&&isTypeaheadOpen(this.#z)?this.#z:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#fe=t=>{t.type!==`ctrl-c`&&this.#ne&&(this.#ne=!1,this.#mn());let n=applyLineEditorKey(i,t,{multiline:!0});if(n!==void 0){apply(n);return}switch(t.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#z=moveTypeaheadSelection(e,-1),this.#mn();break}let t=movePromptLine(i,`up`);t===void 0?recall(this.#L.previous(i.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#z=moveTypeaheadSelection(e,1),this.#mn();break}let t=movePromptLine(i,`down`);t===void 0?recall(this.#L.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.#z=dismissTypeahead(e),this.#mn());break}case`enter`:{let t=highlighted(),n=t!==void 0&&parsePromptCommand(i.text)===null?typeaheadCompletion(t).trimEnd():i.text;if(n.trim().length===0)break;this.#z=void 0,this.#L.add(n),this.#R=!1,this.#Vt(),this.#J=STATUS.processing,isPromptControlCommand(n)?this.#Kt({kind:`command`,body:stripTerminalControls(n.trim()),live:!1}):(this.#Wt(),this.#qt(n),this.#Fe=n,this.#U.arm()),this.#Qe(EMPTY_LINE),this.#mn(),this.#Nt(),e(n);break}case`ctrl-d`:i.text.length===0?(this.#Tt(),interrupt()):apply(deleteForward(i));break;case`ctrl-l`:this.#_n();break;case`ctrl-r`:this.#mn();break;case`ctrl-c`:if(this.#ne){this.#Tt(),interrupt();break}this.#ne=!0,apply(EMPTY_LINE)}},this.#Mt()})}#Qe(e){this.#F=e.text,this.#I=e.cursor}takeQueuedPrompt(){let e=this.#Ve.view().steering,t=this.#Ve.takePrompt();return t!==void 0&&(this.#Ge=e?`steer`:`queue`),t}async renderStream(e,t){this.#kt(t),this.#g.clear(),this.#R=!1,this.#K.kind!==`waiting`&&(this.#K={kind:`waiting`,startedAtMs:Date.now()}),this.#J=this.#M>0?STATUS.connectionAuth:STATUS.processing,this.#Yt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#d?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#U.armed&&this.#U.arm(),this.#ee=!1,this.#Ue=!1,this.#Ke=!1,this.#qe=t?.submittedPrompt,this.#Ve.beginTurn(),this.#He=e.cancel,this.#be=void 0,this.#xe=void 0,this.#Ce=void 0,this.#we=void 0,this.#Te=Date.now();let n={tools:t?.tools??this.#a,reasoning:t?.reasoning??this.#o,assistantResponseStats:t?.assistantResponseStats??this.#l};this.#Ut(),this.#G=!0,this.#mn();let r=new Promise(e=>{this.#_e=e});this.#fe=e=>this.#zt(e),this.#Mt();let i={text:new Map,reasoning:new Map,tools:new Map,cancelled:!1,restoreCancelledPrompt:!0};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#ee)break;this.#nn(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.#_e=void 0,this.#ee&&e.abort?.(),this.#He=void 0,this.#Nt(),this.#Gt(),this.#G=!1,this.#K.kind===`waiting`&&(this.#K={kind:`idle`}),this.#J=completedTurnStatus({interrupted:this.#ee,cancelled:this.#Ue,continueSession:t?.continueSession===!0}),this.#ln(i),(this.#ee||i.cancelled)&&this.#cn(i),this.#tn(),this.#d?.reportStats(),this.#mn(),t?.continueSession||this.#jt()}}async renderIdleStream(e,t){let n={tools:t?.tools??this.#a,reasoning:t?.reasoning??this.#o,assistantResponseStats:t?.assistantResponseStats??this.#l},r={text:new Map,reasoning:new Map,tools:new Map,cancelled:!1,restoreCancelledPrompt:!1};try{for await(let t of iterateTUIStream(e.events))this.#nn(t,n,r)}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.#ln(r),r.cancelled&&this.#cn(r),this.#tn(),this.#d?.reportStats(),this.#mn()}}async readToolApproval(e,t){return this.#kt(t),this.#Gt(),this.#R=!1,this.#K={kind:`idle`},this.#J=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#ee=!1,this.#mn(),await new Promise((t,n)=>{this.#q=n,this.#fe=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Wt(),this.#J=STATUS.processing,this.#Nt(),this.#mn(),t({approved:!0})):n===`n`&&(this.#Wt(),this.#J=STATUS.processing,this.#et(e.toolCallId),this.#Nt(),this.#mn(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#mn();break;case`ctrl-c`:this.#ee=!0,this.#jt(),n(interruptedError())}},this.#Mt()})}async readInputQuestion(e,t){this.#kt(t),this.#Gt(),this.#R=!1,this.#B=!1,this.#K={kind:`idle`},this.#ee=!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.#ae},this.#i,t),renderTextSection=()=>{this.#Qt({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#Bt():(this.#Vt(),this.#Ht())};s===`overlay`?(s=`overlay`,this.#R=!1,this.#en(o),this.#Ie=overlayPanel,this.#J=``,syncFreeformCaret(),this.#mn()):(s=`text`,this.#Ie=void 0,renderTextSection(),this.#R=!0,this.#Qe(l),this.#J=``,this.#Bt(),this.#mn());let finalize=t=>{this.#Ie=void 0,this.#Qt({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#R=!1,this.#Wt(),this.#J=STATUS.processing,this.#Vt(),this.#Nt(),this.#mn();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Ie=void 0,this.#Qt({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#R=!1,this.#J=``,this.#Vt(),this.#Nt(),this.#mn(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#mn())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#q=r,u=t,this.#fe=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#Ht(),s===`text`&&this.#Qe(l),this.#mn();return}this.#ee=!0,this.#Ie=void 0,this.#Vt(),this.#jt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#mn();return}if(s===`overlay`){let r=setupSelectionIntent(t,{textNavigation:!isOnFreeformRow()});if(r?.kind===`move`){moveCursor(r.direction===`up`?-1:1);return}switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#Ht(),this.#mn();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#Ht(),this.#mn());break}if(t.type===`text`&&/^[1-9]$/u.test(t.value)){let e=Number(t.value)-1;e<n.length?selectOptionAt(e):e===n.length&&i&&(c=e,syncFreeformCaret(),this.#mn())}}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#Ht(),this.#Qe(l),this.#mn();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Ht(),this.#Qe(l),this.#mn());break}case`enter`:{let t=resolveQuestionText(l.text,e);if(t===void 0)break;u(finalize(t));break}case`escape`:if(l.text.length>0){l=EMPTY_LINE,this.#Ht(),this.#Qe(l),this.#mn();break}dismiss()}},this.#Mt()})}upsertSubagentStep(e){if(this.#d?.recordSubagentDispatch(e.callId),this.#s===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(t.length!==0||n.length!==0){if(this.#Zt(e.callId,e.subagentName),this.#s===`collapsed`){this.#mn();return}this.#$t({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#s!==`full`,live:!e.finalized}),this.#mn()}}upsertSubagentTool(e){if(this.#d?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#d?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#s===`hidden`)return;if(this.#Zt(e.callId,e.subagentName),this.#s===`collapsed`){this.#mn();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#on({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.#s===`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.#$t(r),this.#$e(e.callId),this.#mn()}#$e(e){applyCohortLiveness(this.#m.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#en(subagentToolSectionId(e.callId,e.childCallId)),this.#mn()}subagents={begin:e=>this.beginSubagent(e),background:e=>this.backgroundSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#s===`hidden`)return;this.#Zt(e.callId,e.name);let t=this.#h.get(subagentHeaderId(e.callId));t!==void 0&&(t.status===`done`&&delete t.status,t.live=!0),this.#C.delete(e.callId),this.#mn()}backgroundSubagent(e){let t=this.#h.get(subagentHeaderId(e.callId));t===void 0||this.#g.has(subagentHeaderId(e.callId))||(t.status=`running`,t.live=!0,t.updateSeq=++this.#b,this.#S.add(e.callId),this.#mn())}completeSubagent(e){let t=this.#h.get(subagentHeaderId(e.callId));if(t!==void 0){if(t.status=`done`,e.authoritative){this.#S.delete(e.callId),this.#C.delete(e.callId);for(let t of this.#m)t.subagentCallId===e.callId&&(t.live=!1)}else{this.#C.add(e.callId);for(let t of this.#m)t.subagentCallId===e.callId&&(t.live=!0)}this.#mn()}}markChildToolCallId(e){this.#v.add(e);let t=this.#y.get(e);t!==void 0&&(this.#en(t),this.#y.delete(e),this.#mn())}#et(e){let t=this.#h.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#c===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#Qt({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#mn()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#M)return;let n=this.#M>0;this.#M=t,t>0?(this.#J=STATUS.connectionAuth,this.#mn()):n&&(this.#J=STATUS.processing,this.#mn())}setVercelStatus(e){this.#N=e,this.#mn()}setRemoteConnectionStatus(e){this.#P=e,this.#mn()}reset(){this.#m=[],this.#h.clear(),this.#g.clear(),this.#j=void 0,this.#A.length=0,this.#_.length=0,this.#O=!1,this.#k=void 0,this.#tt(),this.#H=!1,this.#Fe=void 0,this.#Ae=void 0,this.#M=0,this.#be=void 0,this.#xe=void 0,this.#Ce=void 0,this.#we=void 0,this.#Te=void 0,this.#Z&&(this.#n.clearAll(),this.#mn())}renderSessionBoundary(){this.#Jt(),this.#tt();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#Kt({kind:`session-boundary`,body:n,live:!1}),this.#mn()}#tt(){this.#v.clear(),this.#y.clear(),this.#T.clear(),this.#S.clear(),this.#C.clear(),this.#x.clear(),this.#ze=void 0,this.#Be=void 0,this.#Ve.reset(),this.#Ge=void 0,this.#w.clear(),this.#U.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#kt(),this.#Kt({kind:`notice`,body:t,live:!1}),this.#mn())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#d?.append({source:`sandbox`,detail:t}),this.#kt(),this.#Kt({kind:`sandbox`,body:t,live:!1}),this.#mn())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#nt();return}this.#kt(),this.#Re=t,this.#mn()}clearSetupWarning(){this.#nt()}#nt(){this.#Re!==void 0&&(this.#Re=void 0,this.#mn())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#kt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Kt(r),this.#mn()}renderCommandResult(e,t){let n=stripAnsi(e);n.trim().length!==0&&(this.#kt(),this.#Kt({kind:`result`,body:n,live:!1,status:t===`success`?`done`:void 0}),this.#mn())}#rt(e,t=`spinner`){this.#kt(),this.#R=!1,this.#K={kind:`idle`},this.#J=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Le={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Ut(),this.#mn()}#it(e){this.#Le!==void 0&&(this.#Le.navigation=e,this.#mn())}#at(e){this.#Je=void 0,this.#yt();let t=this.#Le;if(t!==void 0){if(this.#Le=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.#Kt({kind:`flow`,title:`info`,body:e.join(`
5
- `),live:!1}),this.#Kt({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#mn()}}async#ot(e){let t=this.#pt(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a=e.navigation?.kind===`planner`,o={options:i,searchAction:r,submitRow:n&&!a};`initialValue`in e&&e.initialValue!==void 0&&(o.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(o.initialValues=e.initialValues);let s=initialSelectState(o),c,l=!1,u=0,isCurrentSearch=e=>e===u,clearSearch=()=>{u+=1,l=!1,s=reduceSelect(s,{type:`clear`},{options:i,searchAction:r,submitRow:n&&!a}),this.#mn()},loadSearch=async(e,t)=>{l=!0,c=void 0;let o=++u;this.#mn();try{let c=await t(e);if(!isCurrentSearch(o))return;let l=s.filter;i=c,s={...initialSelectState({options:c,searchAction:r,submitRow:n&&!a}),filter:l}}catch(e){isCurrentSearch(o)&&(c=toErrorMessage(e))}finally{isCurrentSearch(o)&&(l=!1,this.#mn())}},d=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));d=e.notices??r,t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:s};return d!==void 0&&d.length>0&&(t.notices=d),c!==void 0&&(t.error=c),l&&(t.loadingFrame=this.#xn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#mn(),await this.#gt((t,o)=>{let close=e=>{u+=1,o(e)};if(l){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#mn();return}let d=e.navigation?.kind===`planner`?e.navigation:void 0,f=t.type===`left`&&(d?.activeStep??0)>(d?.firstNavigableStep??0)?`back`:t.type===`right`&&d!==void 0&&d.activeStep>=(d.firstNavigableStep??0)&&d.activeStep<d.steps.length-1?`forward`:void 0;if(f!==void 0){close({kind:`navigate`,direction:f,values:n?orderedSelection(i,s.selected):[]});return}let p={key:t,options:i,searchAction:r,select:s},m=reduceSetupSelectInput(n?{...p,kind:e.kind,required:e.required,plannerNavigation:a||void 0}:{...p,kind:e.kind});switch(m.kind){case`cancel`:close(void 0);return;case`repaint`:this.#mn();return;case`update`:s=m.select,c=void 0,this.#mn();return;case`submit`:{let e=searchActionQuery(m.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(m.values);return}loadSearch(e,t);return}case`error`:c=m.message,this.#mn();return;case`ignore`:return}}).promise}#st(e){this.#kt();let t=this.#mt();t.status={kind:`progress`,text:stripTerminalControls(e.status),startedAtMs:Date.now()};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#i,t),this.#mn();let r=this.#gt((t,r)=>{let i=setupSelectionIntent(t,{textNavigation:!0});switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#mn();return;case`repaint`:this.#mn();return;case`submit`:n!==void 0&&r(e.actions[n].value);return;case void 0:return}},()=>{t.status=void 0});return{choice:r.promise,close:()=>r.settle(void 0)}}async#ct(e){let t=this.#pt(),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.#ae,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#i,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#Bt():(i=lineOf(``),this.#Vt())};return syncEditableRow(),this.#mn(),await this.#gt((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Ht(),this.#mn()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#mn()},submit=()=>{let t=selectValueAtCursor([...e.options],r.cursor);if(t===void 0)return;if(t!==e.editable.value){n({kind:`selected`,value:t});return}let o=(i.text||e.editable.defaultValue).trim(),s=e.editable.validate?.(o);if(s!==void 0){a=s,this.#mn();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t,{textNavigation:!onEditableRow()});switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#mn();return;case void 0:}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Vt()).promise}async#lt(e){let t=this.#pt(),n=initialProviderPickerState(e.options,e.initialValue),r,cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor),r=e.options.find(e=>e.value===t);if(r!==void 0)return enterBadge(this.#i,r.checked===!0?`change`:void 0)};t.question=t=>{let r=cursorBadge(),i={kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`ai-gateway-key`,caretVisible:this.#ae,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#i,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#Bt():this.#Vt()};return syncCaret(),this.#mn(),await this.#gt((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#mn();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#mn();return;case`validate`:{n=o.state,syncCaret(),this.#mn();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t,{textNavigation:n.phase.kind===`inactive`});switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#mn();return;case void 0:}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#Ht(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Vt()}).promise}async#ut(e){let t=this.#pt(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#i,t),this.#mn(),await this.#gt((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#mn();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.#mn();return;case void 0:}if(t.type===`left`||t.type===`right`){dispatch({type:`adjust`,direction:t.type});return}if(t.type===`tab`){dispatch({type:`adjust`,direction:`right`});return}if(t.type===`backspace`){dispatch({type:`backspace`});return}if(t.type===`text`)for(let e of t.value.replaceAll(`
6
- `,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#dt(e){let t=this.#pt(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder===void 0?e.defaultValue!==void 0&&(i.placeholder=e.defaultValue):i.placeholder=e.placeholder,e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#i,t,this.#ae)},this.#Bt(),this.#mn(),await this.#gt((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Ht(),this.#mn()},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.#mn();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#mn();return}i(t);return}default:return}},()=>this.#Vt()).promise}async#ft(e){let t=this.#pt();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#i,t),this.#mn(),await this.#gt((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#mn();return;default:return}}).promise}#pt(){this.#kt(),this.#R=!1,this.#K={kind:`idle`},this.#J=``;let e=this.#mt();return e.status!==void 0&&(e.status=void 0,e.summary=void 0,e.preview=void 0),e}#mt(){return this.#Le===void 0&&(this.#Le={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Le}#ht(){this.#Le?.implicit===!0?this.#Le=void 0:this.#Le!==void 0&&(this.#Le.question=void 0,this.#Le.hideLinesWhileQuestion=!1),this.#fe=void 0,this.#Nt(),this.#Le!==void 0&&this.#vt(),this.#mn()}#gt(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#ht(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#ht(),i(e))};return this.#Rt(),this.#fe=t=>{t.type===`ctrl-c`&&this.#Tt(),e(t,settle,reject)},this.#Mt(),{promise:a,settle}}#_t(e){let t,n=new Promise(e=>{t=e});return this.#Je=t,this.#vt(e?.interruptible??!0),{promise:n,dispose:()=>{this.#Je===t&&(this.#Je=void 0,this.#yt())}}}#vt(e=!0){if(this.#Je===void 0)return;let consumer=t=>{if(e&&(t.type===`ctrl-c`||t.type===`escape`)){t.type===`ctrl-c`&&this.#Tt();let e=this.#Je;this.#Je=void 0,this.#yt(),e?.(t.type===`ctrl-c`?`ctrl-c`:`escape`);return}t.type===`ctrl-r`&&this.#mn()};this.#Ye=consumer,this.#Rt(),this.#fe=consumer,this.#Mt()}#yt(){this.#Ye!==void 0&&(this.#fe===this.#Ye&&this.#Nt(),this.#Ye=void 0)}#bt(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e),startedAtMs:Date.now()}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis),startedAtMs:Date.now()};if(this.#Le!==void 0){this.#Le.status=t,t===void 0&&(this.#Le.preview=void 0),this.#mn();return}if(!(this.#R||this.#G)){if(t===void 0){this.#K={kind:`idle`},this.#Y=void 0,this.#Gt(),this.#mn();return}this.#kt(),this.#Wt(),this.#Y=t.text,this.#mn()}}#xt(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.#mn();return}this.#kt(),this.#Kt({kind:`flow`,title:t,body:n,live:!1}),this.#mn()}#St(e){let t=this.#Le;t!==void 0&&(t.lines=[],t.outputBuffer=[],t.preview=void 0,t.status=void 0,t.summary=e===void 0?void 0:{headline:stripTerminalControls(e.headline),facts:e.facts.map(e=>({label:stripTerminalControls(e.label),value:stripTerminalControls(e.value)}))},this.#mn())}#Ct(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Le;if(n===void 0){this.#xt(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#mn()}async#wt(e){this.#pe=``,this.#Rt(),this.#Je=void 0,this.#yt(),this.#Nt(),this.#Gt(),this.#n.clear(),this.#In(),this.#r.enter({cursor:`visible`,mouse:!1}),this.#e.isTTY&&this.#e.setRawMode?.(!1),this.#e.pause();try{return await e()}finally{this.#r.exit(),this.#e.isTTY&&this.#e.setRawMode?.(!0),this.#e.resume(),this.#pe=``,this.#Rt(),this.#n.hideCursor(),this.#Fn(),this.#Le!==void 0&&(this.#Ut(),this.#vt()),this.#n.reset(),this.#mn()}}setSessionId(e){this.#We=e}shutdown(){if(this.#jt(),this.#Q&&!this.#$){this.#$=!0;let e=this.#We===void 0?``:` ${this.#i.glyph.dot} session ${this.#We}`;this.#t.write(`${this.#i.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}suspendPromptForInput(){this.#W={cursor:this.#I,text:this.#F},this.#jt()}requestInterrupt(){this.#ee=!0,this.#Le!==void 0&&this.#fe?.({type:`ctrl-c`}),this.#_e?.(),this.#jt()}exitRequested(){return this.#te}#Tt(){this.#te=!0,this.#ie?.()}async#Et(e){if(this.#Xe!==void 0||!this.#Z)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#Nn(),height:this.#Pn()}),paint:e=>this.#r.paint(e,this.#Pn()),tracingDisabled:process.env.EVE_TRACES===`off`,copyText:e=>copyTextToClipboard(e,e=>this.#r.writeRaw(e)),terminalBackground:this.#Ze});this.#Xe=t,this.#r.enter(),this.#i.color&&this.#r.writeRaw(BACKGROUND_COLOR_QUERY),await new Promise(e=>{this.#Ot=e,this.#fe=e=>{t.handleKey(e)===`close`&&this.#Dt()},this.#Mt(),t.start()})}#Dt(){let e=this.#Xe;if(e===void 0)return;this.#Xe=void 0,e.dispose(),this.#Nt(),this.#r.exit(),this.#n.hideCursor(),this.#mn(),this.#n.showCursor();let t=this.#Ot;this.#Ot=void 0,t?.()}#Ot;#kt(e){this.#X=e?.title??this.#X,e?.contextSize!==void 0&&(this.#Se=e.contextSize),!this.#Z&&(this.#Z=!0,this.#Q=!0,this.#n.reset(),this.#n.hideCursor(),this.#Fn(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#ge=()=>this.#mn(),this.#t.on(`resize`,this.#ge),process.on(`exit`,this.#At))}#At=()=>{this.#Z&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#jt(){this.#Dt();let e=this.#q;if(this.#q=void 0,e?.(interruptedError()),this.#Nt(),this.#Vt(),this.#Gt(),this.#ue!==void 0&&(clearTimeout(this.#ue),this.#ue=void 0),this.#de=!1,this.#Wn(),this.#Z){this.#Kn();for(let e of this.#m)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#mn(),this.#n.clear(),this.#n.showCursor(),this.#In(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#ge&&=(this.#t.off(`resize`,this.#ge),void 0),process.off(`exit`,this.#At),this.#Z=!1}}#Mt(){this.#e.off(`data`,this.#Pt),this.#e.on(`data`,this.#Pt),this.#pe.length>0&&queueMicrotask(()=>{this.#fe!==void 0&&this.#pe.length>0&&(this.#It(),this.#Ft())})}#Nt(){this.#e.off(`data`,this.#Pt),this.#Rt(),this.#fe=void 0}#Pt=e=>{this.#Rt(),this.#pe+=this.#me.write(e),this.#It(),this.#Ft()};#Ft(){if(this.#pe===`\x1B`){this.#he=setTimeout(()=>{this.#pe===`\x1B`&&(this.#pe=``,this.#fe?.({type:`escape`}))},30),this.#he.unref?.();return}if(isIncompletePaste(this.#pe)){let e=this.#pe;this.#he=setTimeout(()=>{if(this.#pe!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#pe=``,t.length>0&&this.#fe?.({type:`text`,value:t,framing:`bracketed-paste`})},incompletePasteFlushMs),this.#he.unref?.();return}if(isIncompleteOsc(this.#pe)){let e=this.#pe;this.#he=setTimeout(()=>{this.#pe===e&&(this.#pe=``)},incompletePasteFlushMs),this.#he.unref?.()}}#It(){for(;this.#pe.length>0;){let e=nextKey(this.#pe);if(e.incomplete)return;if(this.#pe=this.#pe.slice(e.consumed),e.key!==void 0&&e.key.type!==`ignore`){if(e.key.type===`osc`){this.#Lt(e.key.value);continue}this.#fe?.(e.key)}}}#Lt(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#Ze=t,this.#Xe?.setTerminalBackground(t))}#Rt(){this.#he&&=(clearTimeout(this.#he),void 0)}#zt(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#mn();break;case`enter`:{let e=this.#W.text;if(e.trim().length===0)break;if(parsePromptCommand(e)?.type===`cancel`&&this.#He!==void 0){this.#W=EMPTY_LINE,this.#Ve.requestCancellation(),this.#Ke=!0,this.renderCommandInvocation(e.trim()),this.renderCommandResult(`Turn cancellation requested.`),this.#He(),this.#mn();break}this.#Ve.enqueue(e)&&(this.#W=EMPTY_LINE),this.#mn();break}case`ctrl-c`:case`escape`:if(e.type===`ctrl-c`&&this.#Ve.view().cancelling){this.#ee=!0,this.#re=!0,this.#K={kind:`idle`},this.#J=`Interrupted`,this.#_e?.(),this.#mn();break}if(this.#Ve.idle&&this.#He===void 0)break;this.#Ve.handleEscape(),this.#Ke=!0,this.#He?.(),this.#mn();break;default:{let t=applyLineEditorKey(this.#W,e,{multiline:!0});t!==void 0&&(this.#W=t,this.#mn());break}}}#Bt(){this.#Vt(),this.#Ht(),this.#ce=setInterval(()=>{this.#ae=!this.#ae,this.#mn()},500),this.#ce.unref?.()}#Vt(){this.#ce&&=(clearInterval(this.#ce),void 0),this.#ae=!0}#Ht(){this.#ae=!0}#Ut(){this.#Gt(),this.#le=setInterval(()=>{this.#oe+=1,this.#mn()},90),this.#le.unref?.()}#Wt(){let e=Date.now();this.#se=e,this.#K={kind:`waiting`,startedAtMs:e},this.#Ut()}#Gt(){this.#le&&=(clearInterval(this.#le),void 0)}#Kt(e){e.id!==this.#Ae?.id&&this.#Kn(),e.updateSeq=++this.#b;let t=e.subagentCallId!==void 0&&this.#S.has(e.subagentCallId)?-1:this.#m.findIndex(e=>e.subagentCallId!==void 0&&this.#S.has(e.subagentCallId));t<0?this.#m.push(e):this.#m.splice(t,0,e),e.id&&this.#h.set(e.id,e)}#qt(e){this.#H=!0,this.#Kt({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#mn()}#Jt(){let e=this.#U.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#En(e.elapsedMs)}`,n=this.#xe??0;if(this.#Se!==void 0&&this.#Se>0&&n>0){let e=Math.round(n/this.#Se*100);t+=` ${this.#i.glyph.dot} ${e}% context`}this.#Kt({kind:`turn-stats`,body:t,live:!1})}#Yt(e){if(e==null)return;let t=this.#Ge;if(this.#Ge=void 0,this.#Fe===e){this.#Fe=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#Kt(n)}#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.#d?.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.#d===void 0?a:`details: ${this.#d.displayPath}`),this.#Kt(c),this.#mn()}#Zt(e,t){if(this.#T.has(e))return;this.#T.add(e);let n=stripTerminalControls(t),r=this.#x.get(n)??[];if(r.push(e),this.#x.set(n,r),r.length===2){let e=this.#h.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.#Kt(i)}#Qt(e){if(e.id&&this.#g.has(e.id))return;let t=e.id?this.#h.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#b;return}this.#Kt(e)}#$t(e){if(e.id&&this.#g.has(e.id))return;let t=e.id?this.#h.get(e.id):void 0;if(t!==void 0){Object.assign(t,e),t.updateSeq=++this.#b;return}let n=e.subagentCallId;if(n===void 0){this.#Kt(e);return}e.id!==this.#Ae?.id&&this.#Kn(),e.updateSeq=++this.#b;let r=-1;for(let e=0;e<this.#m.length;e+=1)this.#m[e]?.subagentCallId===n&&(r=e);this.#m.splice(r<0?this.#m.length:r+1,0,e),e.id!==void 0&&this.#h.set(e.id,e)}#en(e){this.#m=this.#m.filter(t=>t.id!==e),this.#h.delete(e)}#tn(){for(let e of this.#m)e.subagentCallId!==void 0&&this.#C.has(e.subagentCallId)||e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#nn(e,t,n){switch(e.type){case`step-finish`:this.#d?.recordStepUsage(e.usage),e.usage!==void 0&&this.#U.addUsage(e.usage),this.#ln(n),this.#pn(e.usage),this.#mn();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#rn(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=typeof e.text==`string`?stripTerminalControls(e.text):t;n.text.set(e.id,r),this.#rn(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.#in(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.#in(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#an({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#d?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#an({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.#an({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#fn(e.toolCallId,n);if(r===void 0)break;this.#an({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#fn(e.toolCallId,n);if(this.#d?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#an({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#fn(e.toolCallId,n);if(r===void 0)break;this.#an({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#Xt(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:if(n.cancelled=!0,!n.restoreCancelledPrompt)break;this.#Ue=!0,!this.#Ke&&this.#qe!==void 0&&this.#W.text.length===0&&(this.#W=lineOf(this.#qe),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#pn(e.usage),this.#mn()}}#rn(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#Qt({id:e,kind:`assistant`,body:r,live:n}),this.#mn())}#in(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Qt({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#mn())}#an(e,t,n){if(n.tools.set(e.toolCallId,e),this.#v.has(e.toolCallId)||this.#un(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#y.set(e.toolCallId,r);let i=this.#on(e);this.#Qt(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#dn(n),this.#mn()}#on(e){e.output!==void 0&&this.#w.observeRead(e.output);let t={};this.#sn(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.#w.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}#sn(e){let t=this.#E?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#cn(e){for(let t of e.tools.keys()){if(this.#v.has(t))continue;let e=this.#y.get(t)??toolSectionId(t),n=this.#h.get(e);n?.kind===`tool`&&n.status===`running`&&(n.status=`error`,n.result=`interrupted`,n.live=!1)}}#ln(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#y.get(t)??toolSectionId(t);this.#en(r),this.#y.delete(t)}}#un(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.#Be!==e&&(this.#Be=e,this.#Kt({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#Nn(),this.#i).join(`
7
- `),live:!1})),this.#ze=void 0}else this.#ze=t.length>0?t:void 0,this.#Be=void 0;return this.#mn(),!0}#dn(e){let t=[];for(let n of e.tools.values()){if(this.#v.has(n.toolCallId))continue;let e=this.#y.get(n.toolCallId)??toolSectionId(n.toolCallId),r=this.#h.get(e);r?.kind===`tool`&&t.push({block:r,active:isActiveToolStatus(n.status)})}applyCohortLiveness(t)}#fn(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#y.get(e)??toolSectionId(e),i=this.#h.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`}}#pn(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#be=(t??0)+(n??0)),this.#xe=t??this.#xe,this.#Ce=n??this.#Ce,this.#Ce!=null&&this.#Te!==void 0){let e=(Date.now()-this.#Te)/1e3;e>0&&(this.#we=this.#Ce/e)}}#mn(){if(this.#Z){if(this.#ve){this.#ye=!0;return}this.#ve=!0;try{do this.#ye=!1,this.#hn();while(this.#ye)}finally{this.#ve=!1}}}#hn(){if(!this.#Z)return;if(this.#Xe!==void 0){this.#Xe.repaint();return}let e=this.#Nn(),t=this.#wn(e),n=this.#D===void 0?[]:this.#yn(),r=Math.max(1,this.#Pn()-n.length-t.length),i=[],a=this.#j,o=groupToolBlocksForDisplay(this.#m),s=0;for(;s<o.length&&o[s].display.live===!1;)s+=1;if(s>0){let e=new Set(o.slice(0,s).flatMap(e=>e.members));for(let t=this.#m.length-1;t>=0;--t)e.has(this.#m[t])&&this.#m.splice(t,1)}for(let t of o.slice(0,s)){for(let e of t.members)this.#_.push(e),e.id&&(this.#g.add(e.id),this.#h.delete(e.id));if(this.#Jn(t.display))continue;let n=this.#bn(t.display,e,a);a=previousBlockOf(t.display),this.#j=a,i.push(...n),this.#A.push(...n)}let c=[];for(let{display:t}of o.slice(s)){if(this.#Jn(t))continue;let n=this.#bn(t,e,a);a=previousBlockOf(t);for(let e=0;e<n.length;e+=1)c.push({block:t,row:n[e]})}let l=[...n,...clipLiveRows(c.map(e=>e.row),r,e,this.#i),...t];i.length>0?this.#n.flush(i,l):this.#n.update(l)}#gn(){if(!this.#Z)return;let e=this.#Nn(),t=this.#wn(e),n=Math.max(1,this.#Pn()-t.length),r=this.#j,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#m)){if(this.#Jn(t))continue;let n=this.#bn(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#i),...t];this.#n.clearAll(),this.#n.flush([...this.#yn(),...this.#A],a)}logDisplayMode(){return this.#p}setLogDisplayMode(e){e!==this.#p&&(this.#p=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#vn(),this.#Z&&this.#gn())}flushDelayedDevBuildErrors(){let e=this.#ke;e!==void 0&&(this.#ke=void 0,this.#Kt({kind:`log`,title:`stderr`,body:e,live:!0}),this.#mn())}#_n(){this.#de=!0,this.#ue!==void 0&&clearTimeout(this.#ue),this.#ue=setTimeout(()=>{this.#de=!1,this.#ue=void 0,this.#mn()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#p)),this.#mn()}#vn(){let e=this.#Nn();this.#A.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#_,{logCoalescing:`runs`})){if(this.#Jn(n))continue;let r=this.#bn(n,e,t);t=previousBlockOf(n),this.#A.push(...r)}this.#j=t}#yn(){let e=this.#E,t=this.#D;if(e===void 0&&t===void 0)return[];let n={name:e?.name??t?.name,theme:this.#i,width:this.#Nn()};e?.info!==void 0&&(n.info=e.info);let r=e?.tip??t?.tip;return r!==void 0&&(n.tip=r),buildAgentHeader(n)}#bn(e,t,n){let r={activityPulse:this.#Sn(this.#se,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#i,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#xn(){return this.#i.spinner[this.#oe%this.#i.spinner.length]??``}#Sn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#Cn(e,t){return e.indicator.kind===`spinner`?{glyph:this.#xn(),color:`yellow`}:{glyph:this.#Sn(e.indicator.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#wn(e){let t=this.#i.colors,n=[``];if(this.#Ie!==void 0)return n.push(...this.#Ie(e),``),this.#An(n,e),n;let r=this.#Le;if(r!==void 0){let t=this.#Cn(r,r.status),i;if(r.status!==void 0){let{startedAtMs:e,...n}=r.status,a=Date.now()-e,o=a>=5e3?` ${formatTurnDuration(a)}`:``;i={...n,text:`${n.text}${o}`,indicator:t}}let a;if(r.question!==void 0){let t=r.question(e);a={kind:`question`,rows:t},i!==void 0&&(a={kind:`question`,rows:t,status:i})}else i===void 0?a=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(a={kind:`status`,status:i},r.preview!==void 0&&(a={kind:`status`,status:i,preview:r.preview}));let o={title:r.title,navigation:r.navigation,lines:r.summary===void 0?r.hideLinesWhileQuestion===!0?[]:r.lines:[{text:r.summary.headline,tone:`success`},...r.summary.facts.map(e=>({text:`${e.label}: ${e.value}`,tone:`info`}))],content:a};return n.push(...renderFlowPanel(o,this.#i,e)),this.#jn(n,e),n}this.#Re!==void 0&&n.push(...renderAttentionRows(this.#Re,e,this.#i),``),this.#ze!==void 0&&n.push(...renderTodoPanelRows({items:this.#ze,width:e,theme:this.#i,working:this.#G||this.#K.kind===`waiting`,pulse:this.#Sn(this.#se,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}),``);let i=renderMessageQueueRows({view:this.#Ve.view(),width:e,theme:this.#i,working:this.#G});if(i.length>0&&n.push(...i,``),this.#R){let r=this.#z===void 0?void 0:inlineCommandHint(this.#z);r===void 0&&this.#z!==void 0&&isTypeaheadOpen(this.#z)&&n.push(...renderCommandSuggestions(this.#z,this.#i,e)),this.#ne&&n.push(clip(t.dim(`Press Ctrl+C again to exit`),e),``);let i=isPromptControlCommand(this.#F),a=r?t.dim(` ${r}`):``,o=[];this.#D!==void 0&&o.push(clip(t.dim(`${this.#i.glyph.dot} Building your agent…`),e)),this.#An(o,e);let s=Math.max(1,this.#Pn()-1-n.length-1-o.length),c={text:this.#F,cursor:this.#I,width:e,theme:this.#i,caretVisible:this.#ae,isCommand:i,ghost:a,maxRows:s};return this.#B&&this.#F.length===0&&(c.placeholder=this.#H?``:promptPlaceholder(Date.now()-this.#V)),n.push(...promptInputRows(c)),n.push(...o),n}let a=this.#K.kind===`waiting`&&this.#Y===void 0;if(this.#G||a){n.push(this.#Tn(e)),this.#On(n,e);let t=[];return this.#An(t,e),!this.#G&&t.length>0&&n.push(``),n.push(...t),n}if(this.#W.text.length>0)return this.#kn(n,e,{inert:!1}),this.#An(n,e),n;let o=this.#Y??(this.#J.length>0?this.#J:`Ready`),s=this.#Mn(),c=t.dim(this.#i.glyph.dot),l=s?`${c} ${o} ${t.dim(this.#i.glyph.dot)} ${s}`:`${c} ${o}`;return n.push(clip(l,e)),this.#An(n,e),n}#Tn(e){let t=this.#i.colors,n=this.#Sn(this.#se,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),r=this.#K,i=this.#U.startedAtMs??this.#Te??(r.kind===`waiting`?r.startedAtMs:Date.now()),a=Date.now()-i,o=`${typewriterText(`Working for`,a,80)} ${this.#En(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#En(e){return`${formatTurnDuration(e)}${this.#Dn()}`}#Dn(){let{inputTokens:e,outputTokens:t}=this.#U.usage;return e===0&&t===0?``:` ${this.#i.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#i.glyph)}`}#On(e,t){this.#G&&this.#kn(e,t,{inert:!0})}#kn(e,t,n){e.push(``);let r={text:this.#W.text,cursor:this.#W.cursor,width:t,theme:this.#i,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#W.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#An(e,t){let n=this.#P===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#i,width:r};this.#Me&&this.#je!==void 0&&(i.devBuild=this.#je),this.#de&&(i.logLevel=this.#p);let a=this.#E?.serverUrl;if(a!==void 0&&this.#P===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#E?.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.#N!==void 0&&(i.vercel=this.#N),this.#P!==void 0&&(i.remote=this.#P);let c=buildStatusLine(i);c!==void 0&&e.push(clip(`${n}${c}`,t))}#jn(e,t){if(this.#P===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#P,theme:this.#i,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Mn(){let e=this.#i.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#be,outputTokens:this.#Ce,tokensPerSecond:this.#we},this.#l);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#i.glyph.dot} `)):``}#Nn(){return Math.max(20,this.#t.columns||80)}#Pn(){return Math.max(8,this.#t.rows||24)}#Fn(){if(this.#Ee!==void 0||!this.#u)return;this.#De=``,this.#Oe=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#Rn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#d?.subscribeLogRecords(e=>this.#Ln(e)),this.#Ee=()=>{this.#d?.unsubscribeLogRecords(),e(),t()}}#In(){let e=this.#Ee;e!==void 0&&(this.#Ee=void 0,e(),this.#De.length>0&&(this.#d?.append({source:`stdout`,detail:this.#De}),this.#qn(`stdout`)&&process.stdout.write(`${this.#De}\n`),this.#De=``),this.#Oe.length>0&&(this.#d?.append({source:`stderr`,detail:this.#Oe}),this.#qn(`stderr`)&&process.stderr.write(`${this.#Oe}\n`),this.#Oe=``))}#Ln(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#Bn(`[eve:${e.namespace}] ${e.message}${t}`),this.#mn()}#Rn(e,t){let n=(e===`stdout`?this.#De:this.#Oe)+t;if(e===`stdout`&&parseDevRebuildLogLine(n.trimEnd())!==void 0){this.#De=``,this.#d?.append({source:e,detail:n.trimEnd()}),this.#zn(n.trimEnd()),this.#mn();return}let r=n.lastIndexOf(`
8
- `),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#De=i:this.#Oe=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#d?.append({source:e,detail:a}),e===`stdout`?this.#zn(a):this.#Bn(a),this.#mn())}#zn(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
9
- `);t=[],e.trim().length!==0&&this.#Kt({kind:`log`,title:`stdout`,body:e,live:!0})};for(let n of e.split(`
10
- `)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#Kt({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#Hn(r,n.trimEnd())}flushPending()}#Bn(e){let t=e.split(`
11
- `),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#d===void 0){this.#Kt({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#d.displayPath);if(t.kind===`inline`){this.#Kt({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#Kt({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#Kt({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
12
- `);r.trim().length>0&&this.#Kt({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
13
- `);this.#Vn(i)}#Vn(e){if(this.#Wn(),this.#p===`all`){if(e.trim().length===0)return;this.#Kt({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#ke=e}#Hn(e,t){let n=this.#Gn();if(e.kind===`failed`){this.#Vn(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(this.#Un({phase:`building`,summary:t}),n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#Pe}`;this.#Pe+=1,this.#Ae={id:r,summary:t},this.#Kt({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}let r=n?.state.summary??this.#je?.summary;if(r!==void 0&&this.#Un({phase:`complete`,summary:r}),n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#ke=void 0);return}e.kind===`rebuilt`&&(this.#ke=void 0),this.#Kt({kind:`log`,title:`stdout`,body:t,live:!0})}#Un(e){this.#Ne!==void 0&&clearTimeout(this.#Ne),this.#je=e,this.#Me=e.phase===`complete`,this.#Ne=setTimeout(()=>{e.phase===`building`?(this.#Me=!0,this.#Ne=void 0):this.#Wn(),this.#mn()},e.phase===`building`?250:4e3)}#Wn(){this.#Ne!==void 0&&clearTimeout(this.#Ne),this.#je=void 0,this.#Me=!1,this.#Ne=void 0}#Gn(){let e=this.#Ae;if(e===void 0)return;let t=this.#h.get(e.id);if(t!==void 0&&t.live===!0)return{state:e,block:t}}#Kn(){let e=this.#Ae;if(e===void 0)return;this.#Ae=void 0;let t=this.#h.get(e.id);t!==void 0&&(t.live=!1)}#qn(e){switch(this.#p){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#Jn(e){return e.kind===`sandbox`?!this.#qn(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#p!==`stderr`:e.logVisibility===`all-only`?this.#p!==`all`:!this.#qn(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(`
4
+ `),n=stripPromptControlCharacters(e?.initialDraft??this.#G.text),r=t===void 0?n:n.length===0?t:`${t}\n\n${n}`,i=lineOf(r);return this.#G=EMPTY_LINE,this.#R.begin(i.text),this.#$e(i),this.#B=typeaheadFor(this.#p,i.text),this.#Vt(),this.#gn(),await new Promise((e,t)=>{this.#J=t;let apply=e=>{i=e,this.#Ut(),this.#$e(i),this.#B=typeaheadFor(this.#p,e.text,this.#B),this.#gn()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#B=void 0,this.#Ht(),this.#Mt(),t(interruptedError())},suggestions=()=>this.#B!==void 0&&isTypeaheadOpen(this.#B)?this.#B:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#pe=t=>{t.type!==`ctrl-c`&&this.#re&&(this.#re=!1,this.#gn());let n=applyLineEditorKey(i,t,{multiline:!0});if(n!==void 0){apply(n);return}switch(t.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#B=moveTypeaheadSelection(e,-1),this.#gn();break}let t=movePromptLine(i,`up`);t===void 0?recall(this.#R.previous(i.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#B=moveTypeaheadSelection(e,1),this.#gn();break}let t=movePromptLine(i,`down`);t===void 0?recall(this.#R.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.#B=dismissTypeahead(e),this.#gn());break}case`enter`:{let t=highlighted(),n=t!==void 0&&parsePromptCommand(i.text)===null?typeaheadCompletion(t).trimEnd():i.text;if(n.trim().length===0)break;this.#B=void 0,this.#R.add(n),this.#z=!1,this.#Ht(),this.#Y=STATUS.processing,isPromptControlCommand(n)?this.#qt({kind:`command`,body:stripTerminalControls(n.trim()),live:!1}):(this.#Gt(),this.#Jt(n),this.#Ie=n,this.#W.arm()),this.#$e(EMPTY_LINE),this.#gn(),this.#Pt(),e(n);break}case`ctrl-d`:i.text.length===0?(this.#Et(),interrupt()):apply(deleteForward(i));break;case`ctrl-l`:this.#yn();break;case`ctrl-r`:this.#gn();break;case`ctrl-c`:if(this.#re){this.#Et(),interrupt();break}this.#re=!0,apply(EMPTY_LINE)}},this.#Nt()})}#$e(e){this.#I=e.text,this.#L=e.cursor}takeQueuedPrompt(){let e=this.#He.view().steering,t=this.#He.takePrompt();return t!==void 0&&(this.#Ke=e?`steer`:`queue`),t}async renderStream(e,t){this.#At(t),this.#_.clear(),this.#z=!1,this.#q.kind!==`waiting`&&(this.#q={kind:`waiting`,startedAtMs:Date.now()}),this.#Y=this.#N>0?STATUS.connectionAuth:STATUS.processing,this.#Xt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#f?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#W.armed&&this.#W.arm(),this.#te=!1,this.#We=!1,this.#qe=!1,this.#Je=t?.submittedPrompt,this.#He.beginTurn(),this.#Ue=e.cancel,this.#xe=void 0,this.#Se=void 0,this.#we=void 0,this.#Te=void 0,this.#Ee=Date.now();let n={tools:t?.tools??this.#o,reasoning:t?.reasoning??this.#s,assistantResponseStats:t?.assistantResponseStats??this.#u};this.#Wt(),this.#K=!0,this.#gn();let r=new Promise(e=>{this.#ve=e});this.#pe=e=>this.#Bt(e),this.#Nt();let i={text:new Map,reasoning:new Map,tools:new Map,cancelled:!1,restoreCancelledPrompt:!0};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#te)break;this.#in(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#Zt(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#Zt(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#ve=void 0,this.#te&&e.abort?.(),this.#Ue=void 0,this.#Pt(),this.#Kt(),this.#K=!1,this.#q.kind===`waiting`&&(this.#q={kind:`idle`}),this.#Y=completedTurnStatus({interrupted:this.#te,cancelled:this.#We,continueSession:t?.continueSession===!0}),this.#dn(i),(this.#te||i.cancelled)&&this.#un(i),this.#rn(),this.#f?.reportStats(),this.#gn(),t?.continueSession||this.#Mt()}}async renderIdleStream(e,t){let n={tools:t?.tools??this.#o,reasoning:t?.reasoning??this.#s,assistantResponseStats:t?.assistantResponseStats??this.#u},r={text:new Map,reasoning:new Map,tools:new Map,cancelled:!1,restoreCancelledPrompt:!1};try{for await(let t of iterateTUIStream(e.events))this.#in(t,n,r)}catch(e){let t=summarizeKnownError(e);t===null?this.#Zt(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#Zt(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#dn(r),r.cancelled&&this.#un(r),this.#rn(),this.#f?.reportStats(),this.#gn()}}async readToolApproval(e,t){return this.#At(t),this.#Kt(),this.#z=!1,this.#q={kind:`idle`},this.#Y=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#te=!1,this.#gn(),await new Promise((t,n)=>{this.#J=n,this.#pe=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Gt(),this.#Y=STATUS.processing,this.#Pt(),this.#gn(),t({approved:!0})):n===`n`&&(this.#Gt(),this.#Y=STATUS.processing,this.#tt(e.toolCallId),this.#Pt(),this.#gn(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#gn();break;case`ctrl-c`:this.#te=!0,this.#Mt(),n(interruptedError())}},this.#Nt()})}async readInputQuestion(e,t){this.#At(t),this.#Kt(),this.#z=!1,this.#V=!1,this.#q={kind:`idle`},this.#te=!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.#oe},this.#i,t),renderTextSection=()=>{this.#$t({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#Vt():(this.#Ht(),this.#Ut())};s===`overlay`?(s=`overlay`,this.#z=!1,this.#tn(o),this.#Le=overlayPanel,this.#Y=``,syncFreeformCaret(),this.#gn()):(s=`text`,this.#Le=void 0,renderTextSection(),this.#z=!0,this.#$e(l),this.#Y=``,this.#Vt(),this.#gn());let finalize=t=>{this.#Le=void 0,this.#$t({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#z=!1,this.#Gt(),this.#Y=STATUS.processing,this.#Ht(),this.#Pt(),this.#gn();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#Le=void 0,this.#$t({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#z=!1,this.#Y=``,this.#Ht(),this.#Pt(),this.#gn(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#gn())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#J=r,u=t,this.#pe=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#Ut(),s===`text`&&this.#$e(l),this.#gn();return}this.#te=!0,this.#Le=void 0,this.#Ht(),this.#Mt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#gn();return}if(s===`overlay`){let r=setupSelectionIntent(t,{textNavigation:!isOnFreeformRow()});if(r?.kind===`move`){moveCursor(r.direction===`up`?-1:1);return}switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#Ut(),this.#gn();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#Ut(),this.#gn());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.#gn())}}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#Ut(),this.#$e(l),this.#gn();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Ut(),this.#$e(l),this.#gn());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.#Ut(),this.#$e(l),this.#gn();break}dismiss()}},this.#Nt()})}upsertSubagentStep(e){if(this.#f?.recordSubagentDispatch(e.callId),this.#c===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(t.length!==0||n.length!==0){if(this.#Qt(e.callId,e.subagentName),this.#c===`collapsed`){this.#gn();return}this.#en({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#c!==`full`,live:!e.finalized}),this.#gn()}}upsertSubagentTool(e){if(this.#f?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#f?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#c===`hidden`)return;if(this.#Qt(e.callId,e.subagentName),this.#c===`collapsed`){this.#gn();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#cn({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#c===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#en(r),this.#et(e.callId),this.#gn()}#et(e){applyCohortLiveness(this.#h.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#tn(subagentToolSectionId(e.callId,e.childCallId)),this.#gn()}subagents={begin:e=>this.beginSubagent(e),background:e=>this.backgroundSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#c===`hidden`)return;this.#Qt(e.callId,e.name);let t=this.#g.get(subagentHeaderId(e.callId));t!==void 0&&(t.status===`done`&&delete t.status,t.live=!0),this.#w.delete(e.callId),this.#gn()}backgroundSubagent(e){let t=this.#g.get(subagentHeaderId(e.callId));if(t===void 0||this.#_.has(subagentHeaderId(e.callId)))return;t.status=`running`,t.live=!0,t.updateSeq=++this.#x;let n=this.#C.has(e.callId);this.#C.add(e.callId),n||this.#nn(e.callId),this.#gn()}completeSubagent(e){let t=this.#g.get(subagentHeaderId(e.callId));if(t!==void 0){if(t.status=`done`,e.authoritative){this.#C.delete(e.callId),this.#w.delete(e.callId);for(let t of this.#h)t.subagentCallId===e.callId&&(t.live=!1)}else{this.#w.add(e.callId);for(let t of this.#h)t.subagentCallId===e.callId&&(t.live=!0)}this.#gn()}}markChildToolCallId(e){this.#y.add(e);let t=this.#b.get(e);t!==void 0&&(this.#tn(t),this.#b.delete(e),this.#gn())}#tt(e){let t=this.#g.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#l===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#$t({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.#gn()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#N)return;let n=this.#N>0;this.#N=t,t>0?(this.#Y=STATUS.connectionAuth,this.#gn()):n&&(this.#Y=STATUS.processing,this.#gn())}setVercelStatus(e){this.#P=e,this.#gn()}setRemoteConnectionStatus(e){this.#F=e,this.#gn()}reset(){this.#h=[],this.#g.clear(),this.#_.clear(),this.#M=void 0,this.#j.length=0,this.#v.length=0,this.#k=!1,this.#A=void 0,this.#nt(),this.#U=!1,this.#Ie=void 0,this.#je=void 0,this.#N=0,this.#xe=void 0,this.#Se=void 0,this.#we=void 0,this.#Te=void 0,this.#Ee=void 0,this.#Q&&(this.#n.clearAll(),this.#gn())}renderSessionBoundary(){this.#Yt(),this.#nt();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#qt({kind:`session-boundary`,body:n,live:!1}),this.#gn()}#nt(){this.#y.clear(),this.#b.clear(),this.#E.clear(),this.#C.clear(),this.#w.clear(),this.#S.clear(),this.#Be=void 0,this.#Ve=void 0,this.#He.reset(),this.#Ke=void 0,this.#T.clear(),this.#W.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#At(),this.#qt({kind:`notice`,body:t,live:!1}),this.#gn())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#f?.append({source:`sandbox`,detail:t}),this.#At(),this.#qt({kind:`sandbox`,body:t,live:!1}),this.#gn())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#rt();return}this.#At(),this.#ze=t,this.#gn()}clearSetupWarning(){this.#rt()}#rt(){this.#ze!==void 0&&(this.#ze=void 0,this.#gn())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#At();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#qt(r),this.#gn()}renderCommandResult(e,t){let n=stripAnsi(e);n.trim().length!==0&&(this.#At(),this.#qt({kind:`result`,body:n,live:!1,status:t===`success`?`done`:void 0}),this.#gn())}#it(e,t=`spinner`){this.#At(),this.#z=!1,this.#q={kind:`idle`},this.#Y=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Re={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Wt(),this.#gn()}#at(e){this.#Re!==void 0&&(this.#Re.navigation=e,this.#gn())}#ot(e){this.#Ye=void 0,this.#bt();let t=this.#Re;if(t!==void 0){if(this.#Re=void 0,this.#Kt(),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.#qt({kind:`flow`,title:`info`,body:e.join(`
5
+ `),live:!1}),this.#qt({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#gn()}}async#st(e){let t=this.#mt(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a=e.navigation?.kind===`planner`,o={options:i,searchAction:r,submitRow:n&&!a};`initialValue`in e&&e.initialValue!==void 0&&(o.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(o.initialValues=e.initialValues);let s=initialSelectState(o),c,l=!1,u=0,isCurrentSearch=e=>e===u,clearSearch=()=>{u+=1,l=!1,s=reduceSelect(s,{type:`clear`},{options:i,searchAction:r,submitRow:n&&!a}),this.#gn()},loadSearch=async(e,t)=>{l=!0,c=void 0;let o=++u;this.#gn();try{let c=await t(e);if(!isCurrentSearch(o))return;let l=s.filter;i=c,s={...initialSelectState({options:c,searchAction:r,submitRow:n&&!a}),filter:l}}catch(e){isCurrentSearch(o)&&(c=toErrorMessage(e))}finally{isCurrentSearch(o)&&(l=!1,this.#gn())}},d=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));d=e.notices??r,t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:s};return d!==void 0&&d.length>0&&(t.notices=d),c!==void 0&&(t.error=c),l&&(t.loadingFrame=this.#Cn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#gn(),await this.#_t((t,o)=>{let close=e=>{u+=1,o(e)};if(l){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#gn();return}let d=e.navigation?.kind===`planner`?e.navigation:void 0,f=t.type===`left`&&(d?.activeStep??0)>(d?.firstNavigableStep??0)?`back`:t.type===`right`&&d!==void 0&&d.activeStep>=(d.firstNavigableStep??0)&&d.activeStep<d.steps.length-1?`forward`:void 0;if(f!==void 0){close({kind:`navigate`,direction:f,values:n?orderedSelection(i,s.selected):[]});return}let p={key:t,options:i,searchAction:r,select:s},m=reduceSetupSelectInput(n?{...p,kind:e.kind,required:e.required,plannerNavigation:a||void 0}:{...p,kind:e.kind});switch(m.kind){case`cancel`:close(void 0);return;case`repaint`:this.#gn();return;case`update`:s=m.select,c=void 0,this.#gn();return;case`submit`:{let e=searchActionQuery(m.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(m.values);return}loadSearch(e,t);return}case`error`:c=m.message,this.#gn();return;case`ignore`:return}}).promise}#ct(e){this.#At();let t=this.#ht();t.status={kind:`progress`,text:stripTerminalControls(e.status),startedAtMs:Date.now()};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#i,t),this.#gn();let r=this.#_t((t,r)=>{let i=setupSelectionIntent(t,{textNavigation:!0});switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#gn();return;case`repaint`:this.#gn();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#lt(e){let t=this.#mt(),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.#oe,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#i,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#Vt():(i=lineOf(``),this.#Ht())};return syncEditableRow(),this.#gn(),await this.#_t((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Ut(),this.#gn()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#gn()},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.#gn();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t,{textNavigation:!onEditableRow()});switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#gn();return;case void 0:}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ht()).promise}async#ut(e){let t=this.#mt(),n=initialProviderPickerState(e.options,e.initialValue),r,cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor),r=e.options.find(e=>e.value===t);if(r!==void 0)return enterBadge(this.#i,r.checked===!0?`change`:void 0)};t.question=t=>{let r=cursorBadge(),i={kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`ai-gateway-key`,caretVisible:this.#oe,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#i,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#Vt():this.#Ht()};return syncCaret(),this.#gn(),await this.#_t((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.#gn();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#gn();return;case`validate`:{n=o.state,syncCaret(),this.#gn();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t,{textNavigation:n.phase.kind===`inactive`});switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#gn();return;case void 0:}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#Ut(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Ht()}).promise}async#dt(e){let t=this.#mt(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#i,t),this.#gn(),await this.#_t((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#gn();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.#gn();return;case void 0:}if(t.type===`left`||t.type===`right`){dispatch({type:`adjust`,direction:t.type});return}if(t.type===`tab`){dispatch({type:`adjust`,direction:`right`});return}if(t.type===`backspace`){dispatch({type:`backspace`});return}if(t.type===`text`)for(let e of t.value.replaceAll(`
6
+ `,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#ft(e){let t=this.#mt(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder===void 0?e.defaultValue!==void 0&&(i.placeholder=e.defaultValue):i.placeholder=e.placeholder,e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#i,t,this.#oe)},this.#Vt(),this.#gn(),await this.#_t((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Ut(),this.#gn()},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.#gn();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#gn();return}i(t);return}default:return}},()=>this.#Ht()).promise}async#pt(e){let t=this.#mt();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#i,t),this.#gn(),await this.#_t((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#gn();return;default:return}}).promise}#mt(){this.#At(),this.#z=!1,this.#q={kind:`idle`},this.#Y=``;let e=this.#ht();return e.status!==void 0&&(e.status=void 0,e.summary=void 0,e.preview=void 0),e}#ht(){return this.#Re===void 0&&(this.#Re={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Re}#gt(){this.#Re?.implicit===!0?this.#Re=void 0:this.#Re!==void 0&&(this.#Re.question=void 0,this.#Re.hideLinesWhileQuestion=!1),this.#pe=void 0,this.#Pt(),this.#Re!==void 0&&this.#yt(),this.#gn()}#_t(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#gt(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#gt(),i(e))};return this.#zt(),this.#pe=t=>{t.type===`ctrl-c`&&this.#Et(),e(t,settle,reject)},this.#Nt(),{promise:a,settle}}#vt(e){let t,n=new Promise(e=>{t=e});return this.#Ye=t,this.#yt(e?.interruptible??!0),{promise:n,dispose:()=>{this.#Ye===t&&(this.#Ye=void 0,this.#bt())}}}#yt(e=!0){if(this.#Ye===void 0)return;let consumer=t=>{if(e&&(t.type===`ctrl-c`||t.type===`escape`)){t.type===`ctrl-c`&&this.#Et();let e=this.#Ye;this.#Ye=void 0,this.#bt(),e?.(t.type===`ctrl-c`?`ctrl-c`:`escape`);return}t.type===`ctrl-r`&&this.#gn()};this.#Xe=consumer,this.#zt(),this.#pe=consumer,this.#Nt()}#bt(){this.#Xe!==void 0&&(this.#pe===this.#Xe&&this.#Pt(),this.#Xe=void 0)}#xt(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e),startedAtMs:Date.now()}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis),startedAtMs:Date.now()};if(this.#Re!==void 0){this.#Re.status=t,t===void 0&&(this.#Re.preview=void 0),this.#gn();return}if(!(this.#z||this.#K)){if(t===void 0){this.#q={kind:`idle`},this.#X=void 0,this.#Kt(),this.#gn();return}this.#At(),this.#Gt(),this.#X=t.text,this.#gn()}}#St(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Re;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.#gn();return}this.#At(),this.#qt({kind:`flow`,title:t,body:n,live:!1}),this.#gn()}#Ct(e){let t=this.#Re;t!==void 0&&(t.lines=[],t.outputBuffer=[],t.preview=void 0,t.status=void 0,t.summary=e===void 0?void 0:{headline:stripTerminalControls(e.headline),facts:e.facts.map(e=>({label:stripTerminalControls(e.label),value:stripTerminalControls(e.value)}))},this.#gn())}#wt(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Re;if(n===void 0){this.#St(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#gn()}async#Tt(e){this.#me=``,this.#zt(),this.#Ye=void 0,this.#bt(),this.#Pt(),this.#Kt(),this.#n.clear(),this.#Rn(),this.#r.enter({cursor:`visible`,mouse:!1}),this.#e.isTTY&&this.#e.setRawMode?.(!1),this.#e.pause();try{return await e()}finally{this.#r.exit(),this.#e.isTTY&&this.#e.setRawMode?.(!0),this.#e.resume(),this.#me=``,this.#zt(),this.#n.hideCursor(),this.#Ln(),this.#Re!==void 0&&(this.#Wt(),this.#yt()),this.#n.reset(),this.#gn()}}setSessionId(e){this.#Ge=e}shutdown(){if(this.#Mt(),this.#$&&!this.#ee){this.#ee=!0;let e=this.#Ge===void 0?``:` ${this.#i.glyph.dot} session ${this.#Ge}`;this.#t.write(`${this.#i.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}suspendPromptForInput(){this.#G={cursor:this.#L,text:this.#I},this.#Mt()}requestInterrupt(){this.#te=!0,this.#Re!==void 0&&this.#pe?.({type:`ctrl-c`}),this.#ve?.(),this.#Mt()}exitRequested(){return this.#ne}#Et(){this.#ne=!0,this.#ae?.()}async#Dt(e){if(this.#Ze!==void 0||!this.#Q)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#Fn(),height:this.#In()}),paint:e=>this.#r.paint(e,this.#In()),tracingDisabled:process.env.EVE_TRACES===`off`,copyText:e=>copyTextToClipboard(e,e=>this.#r.writeRaw(e)),terminalBackground:this.#Qe});this.#Ze=t,this.#r.enter(),this.#i.color&&this.#r.writeRaw(BACKGROUND_COLOR_QUERY),await new Promise(e=>{this.#kt=e,this.#pe=e=>{t.handleKey(e)===`close`&&this.#Ot()},this.#Nt(),t.start()})}#Ot(){let e=this.#Ze;if(e===void 0)return;this.#Ze=void 0,e.dispose(),this.#Pt(),this.#r.exit(),this.#n.hideCursor(),this.#gn(),this.#n.showCursor();let t=this.#kt;this.#kt=void 0,t?.()}#kt;#At(e){this.#Z=e?.title??this.#Z,e?.contextSize!==void 0&&(this.#Ce=e.contextSize),!this.#Q&&(this.#Q=!0,this.#$=!0,this.#n.reset(),this.#n.hideCursor(),this.#Ln(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#_e=()=>this.#gn(),this.#t.on(`resize`,this.#_e),process.on(`exit`,this.#jt))}#jt=()=>{this.#Q&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#Mt(){this.#Ot();let e=this.#J;if(this.#J=void 0,e?.(interruptedError()),this.#Pt(),this.#Ht(),this.#Kt(),this.#de!==void 0&&(clearTimeout(this.#de),this.#de=void 0),this.#fe=!1,this.#Kn(),this.#Q){this.#Jn();for(let e of this.#h)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#gn(),this.#n.clear(),this.#n.showCursor(),this.#Rn(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#_e&&=(this.#t.off(`resize`,this.#_e),void 0),process.off(`exit`,this.#jt),this.#Q=!1}}#Nt(){this.#e.off(`data`,this.#Ft),this.#e.on(`data`,this.#Ft),this.#me.length>0&&queueMicrotask(()=>{this.#pe!==void 0&&this.#me.length>0&&(this.#Lt(),this.#It())})}#Pt(){this.#e.off(`data`,this.#Ft),this.#zt(),this.#pe=void 0}#Ft=e=>{this.#zt(),this.#me+=this.#he.write(e),this.#Lt(),this.#It()};#It(){if(this.#me===`\x1B`){this.#ge=setTimeout(()=>{this.#me===`\x1B`&&(this.#me=``,this.#pe?.({type:`escape`}))},30),this.#ge.unref?.();return}if(isIncompletePaste(this.#me)){let e=this.#me;this.#ge=setTimeout(()=>{if(this.#me!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#me=``,t.length>0&&this.#pe?.({type:`text`,value:t,framing:`bracketed-paste`})},incompletePasteFlushMs),this.#ge.unref?.();return}if(isIncompleteOsc(this.#me)){let e=this.#me;this.#ge=setTimeout(()=>{this.#me===e&&(this.#me=``)},incompletePasteFlushMs),this.#ge.unref?.()}}#Lt(){for(;this.#me.length>0;){let e=nextKey(this.#me);if(e.incomplete)return;if(this.#me=this.#me.slice(e.consumed),e.key!==void 0&&e.key.type!==`ignore`){if(e.key.type===`osc`){this.#Rt(e.key.value);continue}this.#pe?.(e.key)}}}#Rt(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#Qe=t,this.#Ze?.setTerminalBackground(t))}#zt(){this.#ge&&=(clearTimeout(this.#ge),void 0)}#Bt(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#gn();break;case`enter`:{let e=this.#G.text;if(e.trim().length===0)break;if(parsePromptCommand(e)?.type===`cancel`&&this.#Ue!==void 0){this.#G=EMPTY_LINE,this.#He.requestCancellation(),this.#qe=!0,this.renderCommandInvocation(e.trim()),this.renderCommandResult(`Turn cancellation requested.`),this.#Ue(),this.#gn();break}this.#He.enqueue(e)&&(this.#G=EMPTY_LINE),this.#gn();break}case`ctrl-c`:case`escape`:if(e.type===`ctrl-c`&&this.#He.view().cancelling){this.#te=!0,this.#ie=!0,this.#q={kind:`idle`},this.#Y=`Interrupted`,this.#ve?.(),this.#gn();break}if(this.#He.idle&&this.#Ue===void 0)break;this.#He.handleEscape(),this.#qe=!0,this.#Ue?.(),this.#gn();break;default:{let t=applyLineEditorKey(this.#G,e,{multiline:!0});t!==void 0&&(this.#G=t,this.#gn());break}}}#Vt(){this.#Ht(),this.#Ut(),this.#le=setInterval(()=>{this.#oe=!this.#oe,this.#gn()},500),this.#le.unref?.()}#Ht(){this.#le&&=(clearInterval(this.#le),void 0),this.#oe=!0}#Ut(){this.#oe=!0}#Wt(){this.#Kt(),this.#ue=setInterval(()=>{this.#se+=1,this.#gn()},90),this.#ue.unref?.()}#Gt(){let e=Date.now();this.#ce=e,this.#q={kind:`waiting`,startedAtMs:e},this.#Wt()}#Kt(){this.#ue&&=(clearInterval(this.#ue),void 0)}#qt(e){e.id!==this.#je?.id&&this.#Jn(),e.updateSeq=++this.#x;let t=e.subagentCallId!==void 0&&this.#C.has(e.subagentCallId)?-1:this.#h.findIndex(e=>e.subagentCallId!==void 0&&this.#C.has(e.subagentCallId));t<0?this.#h.push(e):this.#h.splice(t,0,e),e.id&&this.#g.set(e.id,e)}#Jt(e){this.#U=!0,this.#qt({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#gn()}#Yt(){let e=this.#W.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#On(e.elapsedMs)}`,n=this.#Se??0;if(this.#Ce!==void 0&&this.#Ce>0&&n>0){let e=Math.round(n/this.#Ce*100);t+=` ${this.#i.glyph.dot} ${e}% context`}this.#qt({kind:`turn-stats`,body:t,live:!1})}#Xt(e){if(e==null)return;let t=this.#Ke;if(this.#Ke=void 0,this.#Ie===e){this.#Ie=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#qt(n)}#Zt(e,t,n={}){let r=stripTerminalControls(e),i=stripTerminalControls(t),a=n.detail===void 0?void 0:stripTerminalControls(n.detail),o=n.hint===void 0?void 0:stripTerminalControls(n.hint),s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#f?.append(o===void 0?s:{...s,hint:o});let c={kind:`error`,title:r,body:i,live:!1};o!==void 0&&(c.hint=o),a!==void 0&&(c.detail=this.#f===void 0?a:`details: ${this.#f.displayPath}`),this.#qt(c),this.#gn()}#Qt(e,t){if(this.#E.has(e))return;this.#E.add(e);let n=stripTerminalControls(t),r=this.#S.get(n)??[];if(r.push(e),this.#S.set(n,r),r.length===2){let e=this.#g.get(subagentHeaderId(r[0]));e!==void 0&&(e.subtitle=`#1`)}let i={id:subagentHeaderId(e),kind:`subagent`,subagentCallId:e,title:n,live:!0};r.length>1&&(i.subtitle=`#${r.length}`),this.#qt(i)}#$t(e){if(e.id&&this.#_.has(e.id))return;let t=e.id?this.#g.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#x;return}this.#qt(e)}#en(e){if(e.id&&this.#_.has(e.id))return;let t=e.id?this.#g.get(e.id):void 0;if(t!==void 0){Object.assign(t,e),t.updateSeq=++this.#x;return}let n=e.subagentCallId;if(n===void 0){this.#qt(e);return}e.id!==this.#je?.id&&this.#Jn(),e.updateSeq=++this.#x;let r=-1;for(let e=0;e<this.#h.length;e+=1)this.#h[e]?.subagentCallId===n&&(r=e);this.#h.splice(r<0?this.#h.length:r+1,0,e),e.id!==void 0&&this.#g.set(e.id,e)}#tn(e){this.#h=this.#h.filter(t=>t.id!==e),this.#g.delete(e)}#nn(e){let t=this.#h.filter(t=>t.subagentCallId===e);t.length!==0&&(this.#h=this.#h.filter(t=>t.subagentCallId!==e),this.#h.push(...t))}#rn(){for(let e of this.#h)e.subagentCallId!==void 0&&this.#w.has(e.subagentCallId)||e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#in(e,t,n){switch(e.type){case`step-finish`:this.#f?.recordStepUsage(e.usage),e.usage!==void 0&&this.#W.addUsage(e.usage),this.#dn(n),this.#hn(e.usage),this.#gn();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#an(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=typeof e.text==`string`?stripTerminalControls(e.text):t;n.text.set(e.id,r),this.#an(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.#on(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.#on(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#sn({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#f?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#sn({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.#sn({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#mn(e.toolCallId,n);if(r===void 0)break;this.#sn({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#mn(e.toolCallId,n);if(this.#f?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#sn({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#mn(e.toolCallId,n);if(r===void 0)break;this.#sn({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#Zt(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:if(n.cancelled=!0,!n.restoreCancelledPrompt)break;this.#We=!0,!this.#qe&&this.#Je!==void 0&&this.#G.text.length===0&&(this.#G=lineOf(this.#Je),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#hn(e.usage),this.#gn()}}#an(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#$t({id:e,kind:`assistant`,body:r,live:n}),this.#gn())}#on(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#$t({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#gn())}#sn(e,t,n){if(n.tools.set(e.toolCallId,e),this.#y.has(e.toolCallId)||this.#fn(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#b.set(e.toolCallId,r);let i=this.#cn(e);this.#$t(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#pn(n),this.#gn()}#cn(e){e.output!==void 0&&this.#T.observeRead(e.output);let t={};this.#ln(e.toolName)&&(t.isSubagent=!0);let n=readWriteFileInput(e.toolName,e.input);if(n===void 0)return t.isSubagent===!0?t:void 0;let r=this.#T.observeWrite({path:n.path,content:n.content,callId:e.toolCallId});r!==void 0&&(t.previousContent=r);let i=writeExistedFlag(e.output);return i!==void 0&&(t.existed=i),t}#ln(e){let t=this.#D?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#un(e){for(let t of e.tools.keys()){if(this.#y.has(t))continue;let e=this.#b.get(t)??toolSectionId(t),n=this.#g.get(e);n?.kind===`tool`&&n.status===`running`&&(n.status=`error`,n.result=`interrupted`,n.live=!1)}}#dn(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#b.get(t)??toolSectionId(t);this.#tn(r),this.#b.delete(t)}}#fn(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.#Ve!==e&&(this.#Ve=e,this.#qt({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#Fn(),this.#i).join(`
7
+ `),live:!1})),this.#Be=void 0}else this.#Be=t.length>0?t:void 0,this.#Ve=void 0;return this.#gn(),!0}#pn(e){let t=[];for(let n of e.tools.values()){if(this.#y.has(n.toolCallId))continue;let e=this.#b.get(n.toolCallId)??toolSectionId(n.toolCallId),r=this.#g.get(e);r?.kind===`tool`&&t.push({block:r,active:isActiveToolStatus(n.status)})}applyCohortLiveness(t)}#mn(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#b.get(e)??toolSectionId(e),i=this.#g.get(r);if(i!==void 0&&i.kind===`tool`)return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.toolName??i.title??`tool`}}#hn(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#xe=(t??0)+(n??0)),this.#Se=t??this.#Se,this.#we=n??this.#we,this.#we!=null&&this.#Ee!==void 0){let e=(Date.now()-this.#Ee)/1e3;e>0&&(this.#Te=this.#we/e)}}#gn(){if(this.#Q){if(this.#ye){this.#be=!0;return}this.#ye=!0;try{do this.#be=!1,this.#_n();while(this.#be)}finally{this.#ye=!1}}}#_n(){if(!this.#Q)return;if(this.#Ze!==void 0){this.#Ze.repaint();return}let e=this.#Fn(),t=this.#En(e),n=this.#O===void 0?[]:this.#xn(),r=Math.max(1,this.#In()-n.length-t.length),i=[],a=this.#M,o=groupToolBlocksForDisplay(this.#h),s=0;for(;s<o.length&&o[s].display.live===!1;)s+=1;if(s>0){let e=new Set(o.slice(0,s).flatMap(e=>e.members));for(let t=this.#h.length-1;t>=0;--t)e.has(this.#h[t])&&this.#h.splice(t,1)}for(let t of o.slice(0,s)){for(let e of t.members)this.#v.push(e),e.id&&(this.#_.add(e.id),this.#g.delete(e.id));if(this.#Xn(t.display))continue;let n=this.#Sn(t.display,e,a);a=previousBlockOf(t.display),this.#M=a,i.push(...n),this.#j.push(...n)}let c=[];for(let{display:t}of o.slice(s)){if(this.#Xn(t))continue;let n=this.#Sn(t,e,a);a=previousBlockOf(t);for(let e=0;e<n.length;e+=1)c.push({block:t,row:n[e]})}let l=[...n,...clipLiveRows(c.map(e=>e.row),r,e,this.#i),...t];i.length>0?this.#n.flush(i,l):this.#n.update(l)}#vn(){if(!this.#Q)return;let e=this.#Fn(),t=this.#En(e),n=Math.max(1,this.#In()-t.length),r=this.#M,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#h)){if(this.#Xn(t))continue;let n=this.#Sn(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#i),...t];this.#n.clearAll(),this.#n.flush([...this.#xn(),...this.#j],a)}logDisplayMode(){return this.#m}setLogDisplayMode(e){e!==this.#m&&(this.#m=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#bn(),this.#Q&&this.#vn())}flushDelayedDevBuildErrors(){let e=this.#Ae;e!==void 0&&(this.#Ae=void 0,this.#qt({kind:`log`,title:`stderr`,body:e,live:!0}),this.#gn())}#yn(){this.#fe=!0,this.#de!==void 0&&clearTimeout(this.#de),this.#de=setTimeout(()=>{this.#fe=!1,this.#de=void 0,this.#gn()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#m)),this.#gn()}#bn(){let e=this.#Fn();this.#j.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#v,{logCoalescing:`runs`})){if(this.#Xn(n))continue;let r=this.#Sn(n,e,t);t=previousBlockOf(n),this.#j.push(...r)}this.#M=t}#xn(){let e=this.#D,t=this.#O;if(e===void 0&&t===void 0)return[];let n={name:e?.name??t?.name,theme:this.#i,width:this.#Fn()};e?.info!==void 0&&(n.info=e.info);let r=e?.tip??t?.tip;return r!==void 0&&(n.tip=r),buildAgentHeader(n)}#Sn(e,t,n){let r={renderMarkdown:this.#a,activityPulse:this.#wn(this.#ce,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#i,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#Cn(){return this.#i.spinner[this.#se%this.#i.spinner.length]??``}#wn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#Tn(e,t){return e.indicator.kind===`spinner`?{glyph:this.#Cn(),color:`yellow`}:{glyph:this.#wn(e.indicator.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#En(e){let t=this.#i.colors,n=[``];if(this.#Le!==void 0)return n.push(...this.#Le(e),``),this.#Mn(n,e),n;let r=this.#Re;if(r!==void 0){let t=this.#Tn(r,r.status),i;if(r.status!==void 0){let{startedAtMs:e,...n}=r.status,a=Date.now()-e,o=a>=5e3?` ${formatTurnDuration(a)}`:``;i={...n,text:`${n.text}${o}`,indicator:t}}let a;if(r.question!==void 0){let t=r.question(e);a={kind:`question`,rows:t},i!==void 0&&(a={kind:`question`,rows:t,status:i})}else i===void 0?a=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(a={kind:`status`,status:i},r.preview!==void 0&&(a={kind:`status`,status:i,preview:r.preview}));let o={title:r.title,navigation:r.navigation,lines:r.summary===void 0?r.hideLinesWhileQuestion===!0?[]:r.lines:[{text:r.summary.headline,tone:`success`},...r.summary.facts.map(e=>({text:`${e.label}: ${e.value}`,tone:`info`}))],content:a};return n.push(...renderFlowPanel(o,this.#i,e)),this.#Nn(n,e),n}this.#ze!==void 0&&n.push(...renderAttentionRows(this.#ze,e,this.#i),``),this.#Be!==void 0&&n.push(...renderTodoPanelRows({items:this.#Be,width:e,theme:this.#i,working:this.#K||this.#q.kind===`waiting`,pulse:this.#wn(this.#ce,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}),``);let i=renderMessageQueueRows({view:this.#He.view(),width:e,theme:this.#i,working:this.#K});if(i.length>0&&n.push(...i,``),this.#z){let r=this.#B===void 0?void 0:inlineCommandHint(this.#B);r===void 0&&this.#B!==void 0&&isTypeaheadOpen(this.#B)&&n.push(...renderCommandSuggestions(this.#B,this.#i,e)),this.#re&&n.push(clip(t.dim(`Press Ctrl+C again to exit`),e),``);let i=isPromptControlCommand(this.#I),a=r?t.dim(` ${r}`):``,o=[];this.#O!==void 0&&o.push(clip(t.dim(`${this.#i.glyph.dot} Building your agent…`),e)),this.#Mn(o,e);let s=Math.max(1,this.#In()-1-n.length-1-o.length),c={text:this.#I,cursor:this.#L,width:e,theme:this.#i,caretVisible:this.#oe,isCommand:i,ghost:a,maxRows:s};return this.#V&&this.#I.length===0&&(c.placeholder=this.#U?``:promptPlaceholder(Date.now()-this.#H)),n.push(...promptInputRows(c)),n.push(...o),n}let a=this.#q.kind===`waiting`&&this.#X===void 0;if(this.#K||a){n.push(this.#Dn(e)),this.#An(n,e);let t=[];return this.#Mn(t,e),!this.#K&&t.length>0&&n.push(``),n.push(...t),n}if(this.#G.text.length>0)return this.#jn(n,e,{inert:!1}),this.#Mn(n,e),n;let o=this.#X??(this.#Y.length>0?this.#Y:`Ready`),s=this.#Pn(),c=t.dim(this.#i.glyph.dot),l=s?`${c} ${o} ${t.dim(this.#i.glyph.dot)} ${s}`:`${c} ${o}`;return n.push(clip(l,e)),this.#Mn(n,e),n}#Dn(e){let t=this.#i.colors,n=this.#wn(this.#ce,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),r=this.#q,i=this.#W.startedAtMs??this.#Ee??(r.kind===`waiting`?r.startedAtMs:Date.now()),a=Date.now()-i,o=`${typewriterText(`Working for`,a,80)} ${this.#On(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#On(e){return`${formatTurnDuration(e)}${this.#kn()}`}#kn(){let{inputTokens:e,outputTokens:t}=this.#W.usage;return e===0&&t===0?``:` ${this.#i.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#i.glyph)}`}#An(e,t){this.#K&&this.#jn(e,t,{inert:!0})}#jn(e,t,n){e.push(``);let r={text:this.#G.text,cursor:this.#G.cursor,width:t,theme:this.#i,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#G.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#Mn(e,t){let n=this.#F===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#i,width:r};this.#Ne&&this.#Me!==void 0&&(i.devBuild=this.#Me),this.#fe&&(i.logLevel=this.#m);let a=this.#D?.serverUrl;if(a!==void 0&&this.#F===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#D?.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.#P!==void 0&&(i.vercel=this.#P),this.#F!==void 0&&(i.remote=this.#F);let c=buildStatusLine(i);c!==void 0&&e.push(clip(`${n}${c}`,t))}#Nn(e,t){if(this.#F===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#F,theme:this.#i,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Pn(){let e=this.#i.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#xe,outputTokens:this.#we,tokensPerSecond:this.#Te},this.#u);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#i.glyph.dot} `)):``}#Fn(){return Math.max(20,this.#t.columns||80)}#In(){return Math.max(8,this.#t.rows||24)}#Ln(){if(this.#De!==void 0||!this.#d)return;this.#Oe=``,this.#ke=``;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.#Bn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#f?.subscribeLogRecords(e=>this.#zn(e)),this.#De=()=>{this.#f?.unsubscribeLogRecords(),e(),t()}}#Rn(){let e=this.#De;e!==void 0&&(this.#De=void 0,e(),this.#Oe.length>0&&(this.#f?.append({source:`stdout`,detail:this.#Oe}),this.#Yn(`stdout`)&&process.stdout.write(`${this.#Oe}\n`),this.#Oe=``),this.#ke.length>0&&(this.#f?.append({source:`stderr`,detail:this.#ke}),this.#Yn(`stderr`)&&process.stderr.write(`${this.#ke}\n`),this.#ke=``))}#zn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#Hn(`[eve:${e.namespace}] ${e.message}${t}`),this.#gn()}#Bn(e,t){let n=(e===`stdout`?this.#Oe:this.#ke)+t;if(e===`stdout`&&parseDevRebuildLogLine(n.trimEnd())!==void 0){this.#Oe=``,this.#f?.append({source:e,detail:n.trimEnd()}),this.#Vn(n.trimEnd()),this.#gn();return}let r=n.lastIndexOf(`
8
+ `),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#Oe=i:this.#ke=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#f?.append({source:e,detail:a}),e===`stdout`?this.#Vn(a):this.#Hn(a),this.#gn())}#Vn(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
9
+ `);t=[],e.trim().length!==0&&this.#qt({kind:`log`,title:`stdout`,body:e,live:!0})};for(let n of e.split(`
10
+ `)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#qt({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#Wn(r,n.trimEnd())}flushPending()}#Hn(e){let t=e.split(`
11
+ `),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#f===void 0){this.#qt({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#f.displayPath);if(t.kind===`inline`){this.#qt({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#qt({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#qt({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
12
+ `);r.trim().length>0&&this.#qt({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
13
+ `);this.#Un(i)}#Un(e){if(this.#Kn(),this.#m===`all`){if(e.trim().length===0)return;this.#qt({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#Ae=e}#Wn(e,t){let n=this.#qn();if(e.kind===`failed`){this.#Un(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(this.#Gn({phase:`building`,summary:t}),n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#Fe}`;this.#Fe+=1,this.#je={id:r,summary:t},this.#qt({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}let r=n?.state.summary??this.#Me?.summary;if(r!==void 0&&this.#Gn({phase:`complete`,summary:r}),n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#Ae=void 0);return}e.kind===`rebuilt`&&(this.#Ae=void 0),this.#qt({kind:`log`,title:`stdout`,body:t,live:!0})}#Gn(e){this.#Pe!==void 0&&clearTimeout(this.#Pe),this.#Me=e,this.#Ne=e.phase===`complete`,this.#Pe=setTimeout(()=>{e.phase===`building`?(this.#Ne=!0,this.#Pe=void 0):this.#Kn(),this.#gn()},e.phase===`building`?250:4e3)}#Kn(){this.#Pe!==void 0&&clearTimeout(this.#Pe),this.#Me=void 0,this.#Ne=!1,this.#Pe=void 0}#qn(){let e=this.#je;if(e===void 0)return;let t=this.#g.get(e.id);if(t!==void 0&&t.live===!0)return{state:e,block:t}}#Jn(){let e=this.#je;if(e===void 0)return;this.#je=void 0;let t=this.#g.get(e.id);t!==void 0&&(t.live=!1)}#Yn(e){switch(this.#m){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#Xn(e){return e.kind===`sandbox`?!this.#Yn(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#m!==`stderr`:e.logVisibility===`all-only`?this.#m!==`all`:!this.#Yn(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(`
14
14
  `)}function formatQuestionContent(e,t,n){let r=n.colors,i=[],a=e.options??[];if(a.length>0){for(let[e,o]of a.entries()){let a=stripTerminalControls(o.label),s=o.description===void 0?``:stripTerminalControls(o.description),c=t===e,l=s.length>0?`${c?` `:` `}${r.dim(`— ${s}`)}`:``,u=c?`${n.glyph.selectedPointer} ${a}`:` ${a}`,d=renderCursorRow(u,c,r);i.push(`${d}${l}`)}if(e.allowFreeform===!0){let e=t===a.length,o=`Type your own answer`,s=e?`${n.glyph.selectedPointer} ${o}`:` ${r.dim(o)}`;i.push(renderCursorRow(s,e,r))}}else i.push(r.dim(` (type your answer)`));return i.join(`
15
15
  `)}function resolveQuestionText(e,t){let n=e.trim();if(n.length===0)return;let r=n.toLowerCase(),i=t.options??[];if(i.length>0){let e=matchQuestionOption(r,i);if(e!==void 0)return{optionId:e.id,label:e.label}}if(t.allowFreeform===!0||i.length===0)return{text:n,label:n}}function matchQuestionOption(e,t){let n=t.find(t=>t.id.toLowerCase()===e);if(n!==void 0)return n;let r=t.find(t=>t.label.toLowerCase()===e);if(r!==void 0)return r;let i=Number(e);if(Number.isInteger(i)&&i>0&&i<=t.length)return t[i-1]}export{TerminalRenderer};
@@ -30,7 +30,10 @@ export interface DevelopmentTuiStartup {
30
30
  readonly diagnostics: DevDiagnostics | undefined;
31
31
  readonly headerTip: string;
32
32
  readonly renderer: TerminalRenderer;
33
- finish(): string;
33
+ finish(): {
34
+ draft: string;
35
+ queuedPrompt: string | undefined;
36
+ };
34
37
  shutdown(): Promise<void>;
35
38
  }
36
39
  export declare function startDevelopmentTuiStartup(input: TuiDisplayOptions & {
@@ -1 +1 @@
1
- import{graphemes}from"#shared/text-boundaries.js";const ansiPattern=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),ansiPrefixPattern=RegExp(`^\x1B\\[[0-?]*[ -/]*[@-~]`),emojiPresentationPattern=/\p{Emoji_Presentation}/u,extendedPictographicPattern=/\p{Extended_Pictographic}/u,keycapPattern=/^[#*0-9]\u{fe0f}?\u{20e3}$/u;function stripAnsi(e){return stripTerminalControls(e.replaceAll(ansiPattern,``))}function stripTerminalControls(e){let t=``,n=0;for(;n<e.length;){let r=e.codePointAt(n);if(r==null)break;let i=String.fromCodePoint(r);n+=i.length,!isUnsafeTerminalControlCodePoint(r)&&(t+=i)}return t}function visibleLength(e){let t=0;for(let n of terminalTextUnits(e))t+=n.width;return t}function sliceVisible(e,t){return sliceUnits(terminalTextUnits(e),0,t)}function sliceUnits(e,t,n){if(n<=0)return``;let r=``,i=0,a=t;for(;a<e.length&&i<n;){let t=e[a];if(t.width>0&&i+t.width>n)break;r+=t.text,i+=t.width,a+=1}for(;e[a]?.ansi===!0;)r+=e[a].text,a+=1;return r}function clipVisible(e,t){if(visibleLength(e)<=t)return e;let n=sliceVisible(e,t);return n.includes(`\x1B`)?`${n}`:n}function inputTextWidth(e){let t=0;for(let n of graphemes(e))t+=terminalGraphemeWidth(n.text);return t}function renderInputText(e){return e.replaceAll(` `,` `)}function renderInputWithBlockCursor(e){let t=e.render??renderInputText,n=e.under.length>0?e.under:` `,r=e.visible?e.inverse(renderInputText(n)):t(n);return`${t(e.before)}${r}${t(e.after)}`}function offsetAtVisibleColumn(e,t){if(t<=0)return 0;let n=0;for(let r of graphemes(e)){let e=n+terminalGraphemeWidth(r.text);if(e>t)return r.start;if(e===t)return r.end;n=e}return e.length}function terminalGraphemeWidth(e){let t=0;for(let n of e){let e=n.codePointAt(0);e!==void 0&&(t=Math.max(t,codePointWidth(e)))}return emojiPresentationPattern.test(e)||keycapPattern.test(e)||e.includes(`️`)&&extendedPictographicPattern.test(e)?Math.max(2,t):t}function terminalTextUnits(e){let t=[],n=0;for(;n<e.length;){let r=e.slice(n),i=r.match(ansiPrefixPattern);if(i!==null){t.push({text:i[0],width:0,ansi:!0}),n+=i[0].length;continue}let a=r.search(ansiPattern),o=r.slice(0,a===-1?r.length:a);for(let e of graphemes(o))t.push({text:e.text,width:terminalGraphemeWidth(e.text),ansi:!1});n+=o.length}return t}function wrapVisibleLine(e,t){if(t<=0)return[e];let n=terminalTextUnits(e),r=0;for(let e of n)r+=e.width;let i=[],a=0,o=0,consume=()=>{let e=n[a];o+=e.text.length,r-=e.width,a+=1};for(;r>t;){let r=findVisibleBreakPoint(n,a,t);i.push(e.slice(o,o+r).trimEnd());let s=o+r;for(;o<s&&a<n.length;)consume();for(;a<n.length;){let e=n[a];if(e.ansi||e.text.trimStart().length>0)break;consume()}}let s=e.slice(o);return(s.length>0||i.length===0)&&i.push(s),i}function findVisibleBreakPoint(e,t,n){let r=sliceUnits(e,t,n+1).lastIndexOf(` `);if(r>0)return r;let i=sliceUnits(e,t,n);if(visibleLength(i)>0)return i.length;let a=0,o=!1;for(let n=t;n<e.length;n+=1){let t=e[n];if(o&&t.width>0)return a;a+=t.text.length,t.width>0&&(o=!0)}return a}function codePointWidth(e){return e===9?4:e<32||e>=127&&e<160||isZeroWidthCodePoint(e)?0:isWideCodePoint(e)?2:1}function isUnsafeTerminalControlCodePoint(e){return e>=0&&e<=8||e>=11&&e<=31||e>=127&&e<=159}function isZeroWidthCodePoint(e){return e>=768&&e<=879||e>=1155&&e<=1161||e>=1425&&e<=1469||e===1471||e>=1473&&e<=1474||e>=1476&&e<=1477||e===1479||e>=1552&&e<=1562||e>=1611&&e<=1631||e===1648||e>=1750&&e<=1756||e>=1759&&e<=1764||e>=1767&&e<=1768||e>=1770&&e<=1773||e===1809||e>=1840&&e<=1866||e>=1958&&e<=1968||e>=2027&&e<=2035||e>=2070&&e<=2073||e>=2075&&e<=2083||e>=2085&&e<=2087||e>=2089&&e<=2093||e>=2137&&e<=2139||e>=2259&&e<=2306||e===2362||e===2364||e>=2369&&e<=2376||e===2381||e>=2385&&e<=2391||e===8205||e>=65024&&e<=65039||e>=917760&&e<=917999}function isWideCodePoint(e){return e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=127744&&e<=128591||e>=129280&&e<=129535||e>=131072&&e<=262141)}export{clipVisible,inputTextWidth,offsetAtVisibleColumn,renderInputText,renderInputWithBlockCursor,sliceVisible,stripAnsi,stripTerminalControls,visibleLength,wrapVisibleLine};
1
+ import{graphemes}from"#shared/text-boundaries.js";const ansiPattern=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),ansiPrefixPattern=RegExp(`^\x1B\\[[0-?]*[ -/]*[@-~]`),oscPattern=RegExp(`\x1B\\][^\x1B\\x07]*(?:\\x07|\x1B\\\\)`,`g`),oscPrefixPattern=RegExp(`^\x1B\\][^\x1B\\x07]*(?:\\x07|\x1B\\\\)`),emojiPresentationPattern=/\p{Emoji_Presentation}/u,extendedPictographicPattern=/\p{Extended_Pictographic}/u,keycapPattern=/^[#*0-9]\u{fe0f}?\u{20e3}$/u;function stripAnsi(e){return stripTerminalControls(e.replaceAll(ansiPattern,``).replaceAll(oscPattern,``))}function stripTerminalControls(e){let t=``,n=0;for(;n<e.length;){let r=e.codePointAt(n);if(r==null)break;let i=String.fromCodePoint(r);n+=i.length,!isUnsafeTerminalControlCodePoint(r)&&(t+=i)}return t}function visibleLength(e){let t=0;for(let n of terminalTextUnits(e))t+=n.width;return t}function sliceVisible(e,t){return sliceUnits(terminalTextUnits(e),0,t)}function sliceUnits(e,t,n){if(n<=0)return``;let r=``,i=0,a=t;for(;a<e.length&&i<n;){let t=e[a];if(t.width>0&&i+t.width>n)break;r+=t.text,i+=t.width,a+=1}for(;e[a]?.ansi===!0;)r+=e[a].text,a+=1;return r}function clipVisible(e,t){if(visibleLength(e)<=t)return e;let n=sliceVisible(e,t);return n.includes(`\x1B`)?`${n}`:n}function inputTextWidth(e){let t=0;for(let n of graphemes(e))t+=terminalGraphemeWidth(n.text);return t}function renderInputText(e){return e.replaceAll(` `,` `)}function renderInputWithBlockCursor(e){let t=e.render??renderInputText,n=e.under.length>0?e.under:` `,r=e.visible?e.inverse(renderInputText(n)):t(n);return`${t(e.before)}${r}${t(e.after)}`}function offsetAtVisibleColumn(e,t){if(t<=0)return 0;let n=0;for(let r of graphemes(e)){let e=n+terminalGraphemeWidth(r.text);if(e>t)return r.start;if(e===t)return r.end;n=e}return e.length}function terminalGraphemeWidth(e){let t=0;for(let n of e){let e=n.codePointAt(0);e!==void 0&&(t=Math.max(t,codePointWidth(e)))}return emojiPresentationPattern.test(e)||keycapPattern.test(e)||e.includes(`️`)&&extendedPictographicPattern.test(e)?Math.max(2,t):t}function terminalTextUnits(e){let t=[],n=0;for(;n<e.length;){let r=e.slice(n),i=terminalControlPrefix(r);if(i!==void 0){t.push({text:i,width:0,ansi:!0}),n+=i.length;continue}let a=r.search(ansiPattern),o=r.search(oscPattern),s=a===-1?o:o===-1?a:Math.min(a,o),c=r.slice(0,s===-1?r.length:s);for(let e of graphemes(c))t.push({text:e.text,width:terminalGraphemeWidth(e.text),ansi:!1});n+=c.length}return t}function terminalControlPrefix(e){return e.match(ansiPrefixPattern)?.[0]??e.match(oscPrefixPattern)?.[0]}function wrapVisibleLine(e,t){if(t<=0)return[e];let n=terminalTextUnits(e),r=0;for(let e of n)r+=e.width;let i=[],a=0,o=0,consume=()=>{let e=n[a];o+=e.text.length,r-=e.width,a+=1};for(;r>t;){let r=findVisibleBreakPoint(n,a,t);i.push(e.slice(o,o+r).trimEnd());let s=o+r;for(;o<s&&a<n.length;)consume();for(;a<n.length;){let e=n[a];if(e.ansi||e.text.trimStart().length>0)break;consume()}}let s=e.slice(o);return(s.length>0||i.length===0)&&i.push(s),i}function findVisibleBreakPoint(e,t,n){let r=sliceUnits(e,t,n+1).lastIndexOf(` `);if(r>0)return r;let i=sliceUnits(e,t,n);if(visibleLength(i)>0)return i.length;let a=0,o=!1;for(let n=t;n<e.length;n+=1){let t=e[n];if(o&&t.width>0)return a;a+=t.text.length,t.width>0&&(o=!0)}return a}function codePointWidth(e){return e===9?4:e<32||e>=127&&e<160||isZeroWidthCodePoint(e)?0:isWideCodePoint(e)?2:1}function isUnsafeTerminalControlCodePoint(e){return e>=0&&e<=8||e>=11&&e<=31||e>=127&&e<=159}function isZeroWidthCodePoint(e){return e>=768&&e<=879||e>=1155&&e<=1161||e>=1425&&e<=1469||e===1471||e>=1473&&e<=1474||e>=1476&&e<=1477||e===1479||e>=1552&&e<=1562||e>=1611&&e<=1631||e===1648||e>=1750&&e<=1756||e>=1759&&e<=1764||e>=1767&&e<=1768||e>=1770&&e<=1773||e===1809||e>=1840&&e<=1866||e>=1958&&e<=1968||e>=2027&&e<=2035||e>=2070&&e<=2073||e>=2075&&e<=2083||e>=2085&&e<=2087||e>=2089&&e<=2093||e>=2137&&e<=2139||e>=2259&&e<=2306||e===2362||e===2364||e>=2369&&e<=2376||e===2381||e>=2385&&e<=2391||e===8205||e>=65024&&e<=65039||e>=917760&&e<=917999}function isWideCodePoint(e){return e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=127744&&e<=128591||e>=129280&&e<=129535||e>=131072&&e<=262141)}export{clipVisible,inputTextWidth,offsetAtVisibleColumn,renderInputText,renderInputWithBlockCursor,sliceVisible,stripAnsi,stripTerminalControls,visibleLength,wrapVisibleLine};