eve 0.54.5 → 0.55.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 (175) hide show
  1. package/CHANGELOG.md +23 -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 +3 -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/cli/commands/agent-prompt/scaffold.md +5 -4
  10. package/dist/src/cli/commands/init-target.js +2 -2
  11. package/dist/src/cli/commands/init.js +1 -1
  12. package/dist/src/cli/dev/environment.js +1 -1
  13. package/dist/src/cli/dev/tui/terminal-renderer.js +9 -9
  14. package/dist/src/compiled/.vendor-stamp.json +1 -1
  15. package/dist/src/compiler/extension-compatibility.d.ts +16 -16
  16. package/dist/src/compiler/extension-compatibility.js +1 -1
  17. package/dist/src/context/dynamic-resolve-context.js +1 -1
  18. package/dist/src/discover/filesystem.d.ts +3 -1
  19. package/dist/src/discover/filesystem.js +1 -1
  20. package/dist/src/discover/skills.js +1 -1
  21. package/dist/src/dynamic/definition.d.ts +6 -0
  22. package/dist/src/eve-channel/audience.d.ts +3 -0
  23. package/dist/src/eve-channel/audience.js +1 -0
  24. package/dist/src/eve-channel/index.js +1 -1
  25. package/dist/src/eve-channel/types.d.ts +14 -1
  26. package/dist/src/execution/activity-work.d.ts +2 -0
  27. package/dist/src/execution/activity-work.js +1 -1
  28. package/dist/src/execution/channel-context.js +1 -1
  29. package/dist/src/execution/coordination-dispatch-shared.d.ts +1 -0
  30. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  31. package/dist/src/execution/eve-workflow-attributes.js +1 -1
  32. package/dist/src/execution/runtime-context.js +1 -1
  33. package/dist/src/execution/scheduled-launch-delivery.d.ts +7 -0
  34. package/dist/src/execution/scheduled-launch-delivery.js +1 -0
  35. package/dist/src/execution/session-activity.js +1 -1
  36. package/dist/src/execution/tasks/child/steps.js +1 -1
  37. package/dist/src/execution/tasks/parent/delegate.d.ts +2 -0
  38. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  39. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  40. package/dist/src/execution/tools/subagent/invoke-step.d.ts +2 -0
  41. package/dist/src/execution/tools/subagent/invoke-step.js +1 -1
  42. package/dist/src/execution/tools/subagent/start.d.ts +5 -0
  43. package/dist/src/execution/tools/subagent/start.js +1 -1
  44. package/dist/src/execution/wire/session-inbox-contract.d.ts +2 -2
  45. package/dist/src/execution/wire/session-inbox-contract.js +1 -1
  46. package/dist/src/execution/wire/session-inbox-encoder.d.ts +6 -2
  47. package/dist/src/execution/wire/session-inbox-encoder.js +1 -1
  48. package/dist/src/execution/wire/session-inbox-resume.js +1 -1
  49. package/dist/src/execution/wire/session-inbox-wire.js +1 -1
  50. package/dist/src/execution/wire/session-inbox-wire.v7.d.ts +342 -0
  51. package/dist/src/execution/wire/session-inbox-wire.v7.js +1 -0
  52. package/dist/src/execution/workflow-steps.js +1 -1
  53. package/dist/src/harness/action-presentation.d.ts +5 -0
  54. package/dist/src/harness/action-presentation.js +1 -1
  55. package/dist/src/harness/background-tools.d.ts +3 -1
  56. package/dist/src/harness/emission.js +1 -1
  57. package/dist/src/harness/step-hooks.js +1 -1
  58. package/dist/src/harness/tool-loop.js +1 -1
  59. package/dist/src/harness/tools.js +1 -1
  60. package/dist/src/harness/workflow-lifecycle.js +1 -1
  61. package/dist/src/instrumentation/channel-delivery.js +1 -1
  62. package/dist/src/instrumentation/content-policy.d.ts +2 -2
  63. package/dist/src/instrumentation/principal-summary.d.ts +3 -3
  64. package/dist/src/instrumentation/runtime-global.d.ts +4 -0
  65. package/dist/src/instrumentation/runtime-global.js +1 -0
  66. package/dist/src/instrumentation/runtime.d.ts +5 -9
  67. package/dist/src/instrumentation/runtime.js +1 -1
  68. package/dist/src/instrumentation/session-context.d.ts +1 -0
  69. package/dist/src/instrumentation/session-context.js +1 -1
  70. package/dist/src/instrumentation/session-init.d.ts +5 -0
  71. package/dist/src/instrumentation/session-init.js +1 -0
  72. package/dist/src/instrumentation/setup-context.js +1 -1
  73. package/dist/src/internal/application/dev-environment.d.ts +3 -0
  74. package/dist/src/internal/application/dev-environment.js +1 -1
  75. package/dist/src/internal/application/output-publication-journal.js +1 -1
  76. package/dist/src/internal/application/output-publication-lock.js +1 -1
  77. package/dist/src/internal/application/package.js +1 -1
  78. package/dist/src/internal/authored-definition/connection.js +1 -1
  79. package/dist/src/internal/instrumentation.d.ts +1 -12
  80. package/dist/src/internal/instrumentation.js +1 -1
  81. package/dist/src/internal/logging.js +1 -1
  82. package/dist/src/internal/nitro/host/build-application.js +1 -1
  83. package/dist/src/protocol/activity.d.ts +1 -0
  84. package/dist/src/protocol/activity.js +1 -1
  85. package/dist/src/public/channels/chat-sdk/audience.d.ts +8 -0
  86. package/dist/src/public/channels/chat-sdk/audience.js +1 -1
  87. package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +0 -2
  88. package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +1 -1
  89. package/dist/src/public/channels/discord/audience.js +1 -1
  90. package/dist/src/public/channels/discord/discordChannel.js +1 -1
  91. package/dist/src/public/channels/discord/index.d.ts +0 -1
  92. package/dist/src/public/channels/index.d.ts +2 -3
  93. package/dist/src/public/channels/slack/activity-plan.js +1 -1
  94. package/dist/src/public/channels/slack/defaults.d.ts +2 -2
  95. package/dist/src/public/channels/slack/index.d.ts +1 -1
  96. package/dist/src/public/channels/slack/slackChannel.d.ts +11 -3
  97. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  98. package/dist/src/public/channels/teams/hitl.js +1 -1
  99. package/dist/src/public/channels/teams/index.d.ts +0 -1
  100. package/dist/src/public/channels/teams/teamsChannel.js +1 -1
  101. package/dist/src/public/channels/teams/verify.js +1 -1
  102. package/dist/src/public/channels/telegram/audience.d.ts +7 -0
  103. package/dist/src/public/channels/telegram/audience.js +1 -1
  104. package/dist/src/public/channels/telegram/index.d.ts +0 -1
  105. package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
  106. package/dist/src/public/channels/twilio/twilioChannel.d.ts +0 -2
  107. package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
  108. package/dist/src/public/definitions/channel.d.ts +2 -1
  109. package/dist/src/public/definitions/channel.js +1 -1
  110. package/dist/src/public/definitions/connections/mcp.d.ts +6 -0
  111. package/dist/src/public/definitions/workspace-agent.js +1 -1
  112. package/dist/src/public/models/openai/chatgpt/auth.js +1 -1
  113. package/dist/src/public/models/openai/chatgpt/codex-app-server.js +1 -1
  114. package/dist/src/public/models/openai/chatgpt/credential-store.js +1 -1
  115. package/dist/src/public/next/index.d.ts +6 -4
  116. package/dist/src/public/next/index.js +1 -1
  117. package/dist/src/public/next/server.js +1 -1
  118. package/dist/src/public/next/vercel-output-config.d.ts +1 -0
  119. package/dist/src/runtime/connections/mcp-client.js +1 -1
  120. package/dist/src/runtime/resolve-connection.js +1 -1
  121. package/dist/src/runtime/sessions/runtime-context-keys.js +1 -1
  122. package/dist/src/runtime/types.d.ts +1 -0
  123. package/dist/src/self-modification/agent.d.ts +7 -1
  124. package/dist/src/self-modification/agent.js +1 -1
  125. package/dist/src/setup/flows/chatgpt-auth.js +1 -1
  126. package/dist/src/setup/flows/registry.js +1 -1
  127. package/dist/src/setup/provider-settings.js +1 -1
  128. package/dist/src/setup/scaffold/create/project.js +1 -1
  129. package/dist/src/shared/channel-audience.d.ts +0 -3
  130. package/dist/src/shared/channel-definition.d.ts +13 -4
  131. package/dist/src/shared/conversation-context.d.ts +47 -0
  132. package/dist/src/shared/conversation-context.js +1 -0
  133. package/dist/src/shared/forwarded-trace-policy.d.ts +2 -1
  134. package/dist/src/shared/forwarded-trace-policy.js +1 -1
  135. package/dist/src/shared/instrumentation-channel-kind.d.ts +3 -0
  136. package/dist/src/shared/instrumentation-channel-kind.js +1 -0
  137. package/dist/src/shared/instrumentation-content.d.ts +9 -4
  138. package/dist/src/shared/instrumentation-content.js +1 -1
  139. package/dist/src/shared/trace-policy.d.ts +7 -6
  140. package/dist/src/shared/trace-policy.js +1 -1
  141. package/dist/src/subagents/handle-dispatch.d.ts +2 -1
  142. package/dist/src/subagents/handle-dispatch.js +1 -1
  143. package/dist/src/subagents/remote-dispatch.js +1 -1
  144. package/dist/src/subagents/start-local.d.ts +1 -0
  145. package/dist/src/subagents/start-local.js +1 -1
  146. package/dist/src/subagents/start-remote.d.ts +2 -0
  147. package/dist/src/subagents/start-remote.js +1 -1
  148. package/dist/src/subagents/tool.d.ts +3 -0
  149. package/dist/src/subagents/tool.js +1 -1
  150. package/dist/src/tasks/session-index.d.ts +2 -0
  151. package/dist/src/tasks/session-index.js +1 -1
  152. package/dist/src/tracing/agent-invocation-coordinator.d.ts +3 -2
  153. package/dist/src/tracing/agent-invocation-coordinator.js +1 -1
  154. package/dist/src/tracing/agent-memory-instrumentation.d.ts +3 -1
  155. package/dist/src/tracing/agent-memory-instrumentation.js +1 -1
  156. package/dist/src/tracing/agent-otel-provider.d.ts +2 -0
  157. package/dist/src/tracing/agent-otel-provider.js +2 -2
  158. package/dist/src/tracing/agent-otel-session-context.d.ts +2 -0
  159. package/dist/src/tracing/agent-otel-session-context.js +1 -1
  160. package/dist/src/tracing/agent-trace-context-store.js +1 -1
  161. package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
  162. package/dist/src/tracing/local-instrumentation-runtime.d.ts +1 -1
  163. package/dist/src/tracing/local-instrumentation-runtime.js +1 -1
  164. package/docs/channels/custom.mdx +22 -2
  165. package/docs/channels/eve.mdx +39 -0
  166. package/docs/channels/slack.mdx +32 -0
  167. package/docs/connections/mcp.mdx +14 -0
  168. package/docs/guides/frontend/nextjs.mdx +12 -10
  169. package/docs/guides/instrumentation-providers.md +10 -8
  170. package/docs/guides/instrumentation.md +2 -2
  171. package/docs/guides/remote-agents.md +1 -1
  172. package/docs/install-integrations.mdx +1 -1
  173. package/docs/reference/cli.md +9 -8
  174. package/docs/subagents/index.mdx +3 -1
  175. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # eve
2
2
 
3
+ ## 0.55.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 0e0f3cc: - Adds `audience(input)` to `defineChannel` and a durable conversation context for trace policies.
8
+ - `eveChannel` now defaults anonymous callers to public and authenticated callers to private. Trace content is public-or-development by default.
9
+ - `metadata().audience` is deprecated. Channel epoch 19 extensions keep working through a warned fallback; move classification to `audience(input)`.
10
+
11
+ ### Patch Changes
12
+
13
+ - c500167: Pass `defaultDeliver()` to custom Slack input handlers so they can delegate selected requests to eve's standard thread or private DM delivery.
14
+ - 520f498: Keep local subagent workflow visibility metadata aligned with the inherited trace decision so Agent Runs does not hide content that was exported for the child.
15
+ - d63d6b7: Attribute local and remote background agent tool activity to its task, including when continuing or steering an existing agent. Each task keeps one progress item, and new work no longer reports against the previous task.
16
+ - bf1175d: Ignore generated module and declaration source maps when discovering skills, so they are not reported as unrecognized skill files.
17
+ - 15c7a2e: Allow `eve init` to add an agent to an existing package without requiring a literal `.` target. You can now initialize the current package or pass the path to an existing package directly.
18
+ - 7a63a68: Keep completed foreground turns in native terminal scrollback while a background subagent continues streaming, rather than hiding them behind the live viewport.
19
+ - bef74fe: Add `protocolVersionDiscovery` to MCP client connections. Set it to `false` to use the initialization handshake for servers that reject modern discovery, while keeping discovery enabled by default.
20
+ - dafa558: Scheduled runs that start background work now stay open and silent until the result is available, then deliver the final response once.
21
+ - 7ad2740: Allow the self-modification agent arguments to set the reasoning effort used by its subagent.
22
+ - 0f79075: Make `withEve()` discover project-level `agents/` workspace members, mounting each named agent through a Next.js app without repeating the agent map in `next.config.ts`. Workspace peers declared with `defineWorkspaceAgent()` route through the named Next.js mount automatically.
23
+ - 09425a0: Move the self-modification registry item to `eve/self-modification`, remove its experimental label and separate production address, and run its production setup flow when added directly.
24
+ - 638aed5: Background task activity now uses a tool's per-call label when one is provided, while retaining the tool or subagent name for execution identity.
25
+
3
26
  ## 0.54.5
4
27
 
5
28
  ### Patch Changes
@@ -4,7 +4,7 @@ import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
4
4
  import type { SessionHandle } from "#channel/session.js";
5
5
  import type { DeliverPayload } from "#channel/types.js";
6
6
  import type { FetchFileContext, FetchFileResult, FetchFileFunction } from "#shared/channel-definition.js";
7
- import type { ChannelAudienceMetadata } from "#shared/channel-audience.js";
7
+ import type { ChannelAudienceProjector } from "#channel/audience.js";
8
8
  /**
9
9
  * Context available to every adapter handler (`deliver` and event handlers).
10
10
  *
@@ -73,7 +73,7 @@ export type ChannelEventHandlers<TCtx extends ChannelAdapterContext<any> = Chann
73
73
  * channel populated at ingestion time.
74
74
  */
75
75
  export type { FetchFileContext, FetchFileResult };
76
- export type ChannelInstrumentationMetadata = Readonly<Record<string, unknown> & ChannelAudienceMetadata>;
76
+ export type ChannelInstrumentationMetadata = Readonly<Record<string, unknown>>;
77
77
  export type ChannelInstrumentationMetadataProjector = (state: Record<string, unknown> | undefined) => ChannelInstrumentationMetadata;
78
78
  /**
79
79
  * Plain-object channel adapter with durable state, an optional inbound
@@ -132,6 +132,7 @@ export type ChannelAdapter<TCtx extends ChannelAdapterContext<any> = ChannelAdap
132
132
  */
133
133
  readonly instrumentation?: {
134
134
  readonly metadata?: ChannelInstrumentationMetadataProjector;
135
+ readonly audience?: ChannelAudienceProjector;
135
136
  };
136
137
  } & ChannelEventHandlers<TCtx>;
137
138
  /**
@@ -0,0 +1,16 @@
1
+ import type { ChannelAudience } from "#shared/channel-audience.js";
2
+ import type { AudienceInput } from "#shared/conversation-context.js";
3
+ type ChannelAudienceSource = {
4
+ readonly kind: string;
5
+ readonly state?: Record<string, unknown> | undefined;
6
+ readonly instrumentation?: {
7
+ readonly audience?: ChannelAudienceProjector;
8
+ readonly metadata?: (state: Record<string, unknown> | undefined) => unknown;
9
+ };
10
+ };
11
+ export type ChannelAudienceProjector = (input: AudienceInput<Record<string, unknown> | undefined>) => ChannelAudience;
12
+ export declare function resolveAudience(adapter: ChannelAudienceSource, input: AudienceInput<Record<string, unknown> | undefined>): ChannelAudience;
13
+ export declare function createMetadataAudienceProjector(source: {
14
+ readonly kind: string;
15
+ }, metadata: (state: Record<string, unknown> | undefined) => unknown): ChannelAudienceProjector;
16
+ export {};
@@ -0,0 +1 @@
1
+ import{normalizeChannelAudience}from"#shared/channel-audience.js";import{isThenable}from"#shared/guards.js";const deprecatedAudienceChannels=new Set;function warnDeprecatedMetadataAudience(e){deprecatedAudienceChannels.has(e)||(deprecatedAudienceChannels.add(e),console.warn(`channel ${e} uses deprecated metadata audience; move it to the audience() hook`))}function resolveAudience(e,t){return normalize(e,t)}function createMetadataAudienceProjector(e,t){return n=>resolveAudience({kind:e.kind,state:n.state,instrumentation:{metadata:t}},n)}function normalize(e,t){let n=e.instrumentation,r=n?.audience;if(r===void 0){let t=n?.metadata;if(t===void 0)return`unknown`;let r;try{r=t(e.state)}catch{return console.warn(`ignoring deprecated channel audience metadata for channel ${e.kind}`),`unknown`}if(isThenable(r))return console.warn(`ignoring deprecated channel audience metadata for channel ${e.kind}`),Promise.resolve(r).catch(()=>void 0),`unknown`;if(typeof r!=`object`||!r)return`unknown`;let i=r.audience;return i===void 0?`unknown`:(warnDeprecatedMetadataAudience(e.kind),normalizeChannelAudience(i))}try{let e=r(t);return isThenable(e)?(console.warn(`ignoring channel audience classifier because it returned a Promise`),Promise.resolve(e).catch(()=>void 0),`unknown`):normalizeChannelAudience(e)}catch{return console.warn(`ignoring channel audience classifier after failure`),`unknown`}}export{createMetadataAudienceProjector,resolveAudience};
@@ -0,0 +1,3 @@
1
+ import type { RunInput } from "#channel/types.js";
2
+ import { type ConversationContext, type ConversationEnvironment } from "#shared/conversation-context.js";
3
+ export declare function buildConversationContext(run: RunInput, environment: ConversationEnvironment): ConversationContext;
@@ -0,0 +1 @@
1
+ import{resolveAudience}from"#channel/audience.js";import{buildChannelInstrumentationProjection}from"#channel/instrumentation.js";import{normalizeInstrumentationChannelKind}from"#shared/instrumentation-channel-kind.js";import{resolveConversationContext}from"#shared/conversation-context.js";import{readForwardedTraceAssertion}from"#shared/forwarded-trace-policy.js";function buildConversationContext(e,t){let n=Object.hasOwn(e,`audienceAuth`)?e.audienceAuth??null:e.auth,r=buildChannelInstrumentationProjection({adapter:e.adapter,channelName:e.channelName}),i={kind:normalizeInstrumentationChannelKind(r.kind),name:e.channelName},a=e.inheritedConversation,o=readForwardedTraceAssertion(e.parentTraceContext?.forwardedTracePolicy),s=o?.originAudience??a?.audience??resolveAudience(e.adapter,{state:e.adapter.state,auth:n,channel:i,mode:e.mode,environment:t});return{...resolveConversationContext(void 0,{channelKind:r.kind,environment:t,forwardedTracePolicy:o,mode:e.mode,principalType:n?.principalType}),audience:s,channel:i}}export{buildConversationContext};
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{getAdapterKind}from"#channel/adapter.js";import{isInstrumentationChannelKind,resolveInstrumentationProjection}from"#internal/instrumentation.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";const log=createLogger(`channel.instrumentation`);function buildChannelInstrumentationProjection(e){let{adapter:t,channelName:n,existingKind:r}=e;return{channelType:getAdapterKind(t),kind:resolveKind({adapter:t,channelName:n,existingKind:r}),metadata:resolveMetadata(t)}}function resolveKind(e){let{adapter:t,channelName:n,existingKind:r}=e;if(r!==void 0)return r;if(n!==void 0&&n.length>0)return`channel:${n}`;let i=getAdapterKind(t);return isInstrumentationChannelKind(i)?i:`channel:${i}`}function resolveMetadata(e){let t=e.instrumentation?.metadata;if(t===void 0)return{audience:`unknown`};let n=resolveInstrumentationProjection({invoke:()=>t(e.state),log,source:getAdapterKind(e)});return{...n,audience:normalizeChannelAudience(n?.audience)}}export{buildChannelInstrumentationProjection};
1
+ import{createLogger}from"#internal/logging.js";import{getAdapterKind}from"#channel/adapter.js";import{isInstrumentationChannelKind,resolveInstrumentationProjection}from"#internal/instrumentation.js";const log=createLogger(`channel.instrumentation`);function buildChannelInstrumentationProjection(e){let{adapter:t,channelName:n,existingKind:r}=e;return{channelType:getAdapterKind(t),kind:resolveKind({adapter:t,channelName:n,existingKind:r}),metadata:resolveMetadata(t)}}function resolveKind(e){let{adapter:t,channelName:n,existingKind:r}=e;if(r!==void 0)return r;if(n!==void 0&&n.length>0)return`channel:${n}`;let i=getAdapterKind(t);return isInstrumentationChannelKind(i)?i:`channel:${i}`}function resolveMetadata(e){let t=e.instrumentation?.metadata;if(t===void 0)return{};let{audience:n,...r}=resolveInstrumentationProjection({invoke:()=>t(e.state),log,source:getAdapterKind(e)})??{};return r}export{buildChannelInstrumentationProjection};
@@ -10,6 +10,7 @@ import type { AgentLimitsDefinition } from "#shared/agent-definition.js";
10
10
  import type { JsonObject } from "#shared/json.js";
11
11
  import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
12
12
  import type { ForwardedTraceAssertion } from "#shared/forwarded-trace-policy.js";
13
+ import type { ConversationContext } from "#shared/conversation-context.js";
13
14
  import type { TaskAgentRequestDelivery, TaskAuthorizationEventDelivery, TaskInputRequestDelivery, TaskView } from "#tasks/types.js";
14
15
  export type { ContextAccessor } from "#context/key.js";
15
16
  export type { ChannelInstrumentationProjection } from "#channel/instrumentation.js";
@@ -388,6 +389,8 @@ export interface RunInput {
388
389
  */
389
390
  readonly channelName?: string;
390
391
  readonly channelMetadata?: ChannelInstrumentationProjection;
392
+ /** Parent conversation classification inherited by a local subagent. */
393
+ readonly inheritedConversation?: ConversationContext;
391
394
  /** Inbound channel operation that created this session. */
392
395
  readonly delivery?: ChannelDeliveryMetadata;
393
396
  /**
@@ -395,6 +398,12 @@ export interface RunInput {
395
398
  * request was accepted with no credentials.
396
399
  */
397
400
  readonly auth: SessionAuthContext | null;
401
+ /**
402
+ * Route-authenticated principal used to classify the conversation. This
403
+ * stays separate from `auth` because a channel may project a different
404
+ * principal into session auth after route authentication.
405
+ */
406
+ readonly audienceAuth?: SessionAuthContext | null;
398
407
  /**
399
408
  * Session-level capabilities. When omitted, every flag is
400
409
  * interpreted as `false`. Channel routes that can reach a human
@@ -16,9 +16,10 @@ the interactive terminal UI.
16
16
  If the user wants a reusable extension package instead of an agent, run
17
17
  `npx eve@latest extension init <name>` and follow that command's next steps.
18
18
 
19
- For an existing app, run `npx eve@latest init .` from its directory. This adds the
20
- agent and missing dependencies while leaving the existing Git repository and app
21
- scripts alone. Append `--model provider/model-id` or `--reasoning effort` to
22
- either init command when the user chose those settings. If init cannot be used,
19
+ For an existing app, run `npx eve@latest init` from its directory, or pass its
20
+ path with `npx eve@latest init path/to/app`. This adds the agent and missing
21
+ dependencies while leaving the existing Git repository and app scripts alone.
22
+ Append `--model provider/model-id` or `--reasoning effort` to either init command
23
+ when the user chose those settings. If init cannot be used,
23
24
  install by hand with
24
25
  `npm install eve@latest ai zod`; manual installation does not add package scripts.
@@ -1,2 +1,2 @@
1
- import{InitTargetError}from"./init-telemetry.js";import{readdir,stat}from"node:fs/promises";import{basename,isAbsolute,relative,resolve,sep}from"node:path";import{PROJECT_NAME_ERROR,parseProjectName}from"#setup/project-name.js";import{classifyAgentRootEntry,getDirectoryEntryType}from"#discover/filesystem.js";const ENVIRONMENT_ONLY_ENTRIES=new Set([`.DS_Store`,`.editorconfig`,`.gitattributes`,`.gitignore`,`.git`,`.idea`,`.vscode`]);async function pathKind(e){let t=await stat(e).catch(e=>{if(e.code!==`ENOENT`)throw e});return t===void 0?`missing`:t.isDirectory()?`directory`:`other`}function isEnvironmentOnly(e){return e.every(e=>ENVIRONMENT_ONLY_ENTRIES.has(e))}async function isAgentRoot(e){return(await readdir(e,{withFileTypes:!0}).catch(()=>[])).some(e=>{let t=classifyAgentRootEntry(e.name,getDirectoryEntryType(e));return t!==`unknown`&&t!==`ignored-directory`&&t!==`lib-directory`})}async function isExistingEveProject(e,t){return await isAgentRoot(e)?!0:(t.includes(`package.json`)||t.includes(`vercel.json`))&&t.includes(`agent`)&&await isAgentRoot(resolve(e,`agent`))}function listEntries(e){return e.map(e=>` - ${e}`).join(`
2
- `)}function assertTargetStaysWithinParent(e,t,n){if(t===void 0||isAbsolute(t))return;let r=relative(e,n);if(r===`..`||r.startsWith(`..${sep}`))throw new InitTargetError(`target_invalid`,PROJECT_NAME_ERROR)}async function resolveInitTarget(e){let t=resolve(e.parentDirectory),n=e.target!==void 0,r=resolve(t,e.target??`.`);assertTargetStaysWithinParent(t,e.target,r);let i=r===t,a;try{a=await pathKind(r)}catch(e){throw new InitTargetError(`target_filesystem`,`Could not access the initialization target: ${e instanceof Error?e.message:String(e)}`)}if(a===`other`)throw new InitTargetError(`target_invalid`,`Cannot initialize an agent because "${r}" is not a directory.`);if(a===`missing`){let e;try{e=parseProjectName(basename(r))}catch(e){throw new InitTargetError(`target_invalid`,e instanceof Error?e.message:String(e))}return{createInPlace:!1,failurePolicy:`remove`,kind:`fresh`,overwriteExisting:!1,preservedEntries:[],projectName:e,projectPath:r}}let o;try{o=(await readdir(r)).sort()}catch(e){throw new InitTargetError(`target_filesystem`,`Could not read the initialization target: ${e instanceof Error?e.message:String(e)}`)}if(o.length===0||isEnvironmentOnly(o)){let e;try{e=i?`.`:parseProjectName(basename(r))}catch(e){throw new InitTargetError(`target_invalid`,e instanceof Error?e.message:String(e))}return{createInPlace:i||o.length>0,failurePolicy:`clear`,kind:`fresh`,overwriteExisting:!1,preservedEntries:o,projectName:e,projectPath:r}}if(await isExistingEveProject(r,o))throw new InitTargetError(`target_conflict`,`An eve project already exists at "${r}". Run an existing-project command from that directory instead.`);if(o.includes(`package.json`)){if(!n||e.target!==`.`)throw new InitTargetError(`target_conflict`,`Adding eve to an existing package requires an explicit \`eve init .\` from "${r}".`);return{kind:`existing`,projectPath:r}}throw new InitTargetError(`target_conflict`,`Cannot initialize an agent in the non-empty directory "${r}". Move or remove these entries, or choose an empty target:\n${listEntries(o)}`)}export{resolveInitTarget};
1
+ import{InitTargetError}from"./init-telemetry.js";import{readdir,stat}from"node:fs/promises";import{basename,isAbsolute,relative,resolve,sep}from"node:path";import{PROJECT_NAME_ERROR,parseProjectName}from"#setup/project-name.js";import{classifyAgentRootEntry,getDirectoryEntryType}from"#discover/filesystem.js";const ENVIRONMENT_ONLY_ENTRIES=new Set([`.DS_Store`,`.editorconfig`,`.gitattributes`,`.gitignore`,`.git`,`.idea`,`.vscode`]);async function pathKind(e){let t=await stat(e).catch(e=>{if(e.code!==`ENOENT`)throw e});return t===void 0?`missing`:t.isDirectory()?`directory`:`other`}function isEnvironmentOnly(e){return e.every(e=>ENVIRONMENT_ONLY_ENTRIES.has(e))}async function isAgentRoot(e){return(await readdir(e,{withFileTypes:!0}).catch(()=>[])).some(e=>{let t=classifyAgentRootEntry(e.name,getDirectoryEntryType(e));return t!==`unknown`&&t!==`ignored-directory`&&t!==`lib-directory`})}async function isExistingEveProject(e,t){if(await isAgentRoot(e)||(t.includes(`package.json`)||t.includes(`vercel.json`))&&t.includes(`agent`)&&await isAgentRoot(resolve(e,`agent`)))return!0;if(!t.includes(`agents`))return!1;let n=await readdir(resolve(e,`agents`),{withFileTypes:!0}).catch(()=>[]);if(!t.includes(`package.json`))return!1;for(let t of n){if(!t.isDirectory()||t.name.startsWith(`.`))continue;let n=resolve(e,`agents`,t.name);if(await pathKind(resolve(n,`agent`))===`directory`||await isAgentRoot(n))return!0}return!1}function listEntries(e){return e.map(e=>` - ${e}`).join(`
2
+ `)}function assertTargetStaysWithinParent(e,t,n){if(t===void 0||isAbsolute(t))return;let r=relative(e,n);if(r===`..`||r.startsWith(`..${sep}`))throw new InitTargetError(`target_invalid`,PROJECT_NAME_ERROR)}async function resolveInitTarget(e){let t=resolve(e.parentDirectory),n=resolve(t,e.target??`.`);assertTargetStaysWithinParent(t,e.target,n);let r=n===t,i;try{i=await pathKind(n)}catch(e){throw new InitTargetError(`target_filesystem`,`Could not access the initialization target: ${e instanceof Error?e.message:String(e)}`)}if(i===`other`)throw new InitTargetError(`target_invalid`,`Cannot initialize an agent because "${n}" is not a directory.`);if(i===`missing`){let e;try{e=parseProjectName(basename(n))}catch(e){throw new InitTargetError(`target_invalid`,e instanceof Error?e.message:String(e))}return{createInPlace:!1,failurePolicy:`remove`,kind:`fresh`,overwriteExisting:!1,preservedEntries:[],projectName:e,projectPath:n}}let a;try{a=(await readdir(n)).sort()}catch(e){throw new InitTargetError(`target_filesystem`,`Could not read the initialization target: ${e instanceof Error?e.message:String(e)}`)}if(a.length===0||isEnvironmentOnly(a)){let e;try{e=r?`.`:parseProjectName(basename(n))}catch(e){throw new InitTargetError(`target_invalid`,e instanceof Error?e.message:String(e))}return{createInPlace:r||a.length>0,failurePolicy:`clear`,kind:`fresh`,overwriteExisting:!1,preservedEntries:a,projectName:e,projectPath:n}}if(await isExistingEveProject(n,a))throw new InitTargetError(`target_conflict`,`An eve project already exists at "${n}". Run \`eve dev\` from that directory, or use an existing-project command.`);if(a.includes(`package.json`))return{kind:`existing`,projectPath:n};throw new InitTargetError(`target_conflict`,`Cannot initialize an agent in the non-empty directory "${n}". Move or remove these entries, or choose an empty target:\n${listEntries(a)}`)}export{resolveInitTarget};
@@ -1 +1 @@
1
- import{initAgentDevHandoff,initAgentReadySummary,initAgentReplPrompt}from"./agent-instructions.js";import{tryInitializeGit}from"./init-git.js";import{InitTargetError}from"./init-telemetry.js";import{addAgentsToWorkspace,convertScaffoldToAgentWorkspace,formatWorkspaceRootMutationWarning}from"./init-agent-workspace.js";import{NPM_NOISE_LINE,installProgressDetail,packageManagerInstallFailureCode}from"./init-install.js";import{reportExistingProjectChanges}from"./init-project.js";import{cleanupFreshInitTarget,workspaceFailureNote}from"./init-recovery.js";import{selectInitHandoff,spawnCodingAgentRepl}from"./init-repl.js";import{selectInitSelfModification}from"./init-self-modification.js";import{resolveInitTarget}from"./init-target.js";import{mkdtemp,readdir,rename,rm}from"node:fs/promises";import{createLogger,isLogLevelEnabled}from"#internal/logging.js";import{basename,join,resolve}from"node:path";import pc from"#compiled/picocolors/index.js";import{DEFAULT_AGENT_MODEL_ID}from"#shared/default-agent-model.js";import{ensureChannel,scaffoldBaseProject}from"#setup/scaffold/index.js";import{eveDevArguments,packageManagerInstallFailureMessage,packageManagerInstallSucceeded,resultSucceeded,runPackageManagerInstall,spawnPackageManager}from"#setup/primitives/index.js";import{performance}from"node:perf_hooks";import{isCodingAgentLaunch}from"#cli/agent-detection.js";import{EVE_WORDMARK}from"#cli/banner.js";import{formatElapsed}from"#cli/format-elapsed.js";import{startCliLiveRow}from"#cli/ui/live-row.js";import{detectInvokingPackageManager,detectPackageManager}from"#setup/package-manager.js";import{pathExists}from"#setup/path-exists.js";import{DEFAULT_EVE_PACKAGE_CONTRACT}from"#setup/scaffold/create/project.js";import{validateModelSlug}from"#setup/flows/model-source-change.js";import{addAgentToProject}from"#setup/scaffold/create/add-to-project.js";import{WizardCancelledError}from"#setup/step.js";import{isPackageManagerWorkspaceMember}from"#setup/scaffold/workspace-root.js";const defaultDependencies={addAgentToProject,detectInvokingPackageManager,detectPackageManager,ensureChannel,isCodingAgentLaunch,now:()=>performance.now(),runPackageManagerInstall,scaffoldBaseProject,selectInitHandoff,selectInitSelfModification,installSelfModification:async e=>{let{installRegistryItem:t}=await import(`./registry.js`);await t(e,`experimental/self-modification`,{silent:!0})},spawnCodingAgentRepl,spawnPackageManager,tryInitializeGit,validateModelSlug},EVE_INIT_PACKAGE_SPEC_ENV=`EVE_INIT_PACKAGE_SPEC`,initLog=createLogger(`init`);async function moveDirectoryContents(e,t){for(let n of await readdir(e))await rename(join(e,n),join(t,n))}function uniqueWorkspaceRootMutations(e){let t=new Map;for(let n of e){let e=`${n.kind}:${n.path}`,r=t.get(e);t.set(e,{...n,nodeEngineOverride:n.nodeEngineOverride??r?.nodeEngineOverride})}return[...t.values()]}async function addToExistingProject(e,t,n,r){if(t.channelWebNextjs===!0)throw Error("`--channel-web-nextjs` is not supported when adding an agent to an existing project. Run `eve add channel/web` from the project afterwards instead.");if(t.model!==void 0){let r=await n.validateModelSlug(e,t.model);if(r!==null)throw Error(r)}let i=await n.detectPackageManager(e),a=await n.addAgentToProject({projectRoot:e,model:t.model??DEFAULT_AGENT_MODEL_ID,reasoning:t.reasoning,packageManager:i.kind,evePackage:r});return{configurationFilesChanged:a.configurationFilesChanged,dependenciesAdded:a.dependenciesAdded,filesWritten:a.filesWritten,packageManager:i.kind,nodeEngineOverride:a.nodeEngineOverride}}async function resolveScaffoldPackageManager(e,t){let n=await t.detectPackageManager(e);return n.source==="default"?t.detectInvokingPackageManager()??`pnpm`:n.kind}async function scaffoldProject(e,t,n,r,i,a,o,s){let c=resolve(e,`..`),l=!n&&await pathExists(e)&&(await readdir(e)).length===0;if(!n&&await pathExists(e)&&!l)throw Error(`Cannot create project because "${e}" already exists.`);let u=n&&s?void 0:await mkdtemp(join(c,`.eve-init-`)),d=[];try{let c=u??e;if(i.model!==void 0){let e=await a.validateModelSlug(c,i.model);if(e!==null)throw Error(e)}let f={projectName:u===void 0?`.`:n?basename(e):t,model:i.model??DEFAULT_AGENT_MODEL_ID,reasoning:i.reasoning,evePackage:o,targetDirectory:c,overwriteExisting:s,workspaceProbeDirectory:e,packageManager:r,onWorkspaceRootMutation:e=>{d.push(e)}},p=await a.scaffoldBaseProject(f);return i.agents!==void 0&&await convertScaffoldToAgentWorkspace(p,i.agents,i),i.channelWebNextjs===!0&&await a.ensureChannel({projectRoot:p,kind:`web`,packageManager:r,force:s,workspaceProbeDirectory:e,configureVercelServices:!1,onWorkspaceRootMutation:e=>{d.push(e)}}),u!==void 0&&(n||l?await moveDirectoryContents(p,e):await rename(p,e)),{projectPath:e,workspaceRootMutations:uniqueWorkspaceRootMutations(d)}}finally{u!==void 0&&await rm(u,{recursive:!0,force:!0})}}async function runInitSteps(e){let{agentLaunched:t,dependencies:n,logger:r,options:i,parentDirectory:a,target:o,trackStep:s,trackTerminal:c}=e,l=isLogLevelEnabled(`debug`),u=await resolveInitTarget({parentDirectory:a,target:o}),d=resolveInitEvePackageOverride(),f=!t&&i.agents===void 0&&await n.selectInitSelfModification(),p=startCliLiveRow(r),m=`scaffold`,h;p.update(`Preparing project`);try{let e=u.kind===`fresh`?`creating agent`:`adding agent`;s?.(m),p.update(u.kind===`fresh`?`Creating agent`:`Adding agent`),initLog.debug(e);let a=n.now(),o;if(u.kind===`fresh`){let e=await resolveScaffoldPackageManager(u.projectPath,n),t=isPackageManagerWorkspaceMember(e,u.projectPath),r;try{r=await scaffoldProject(u.projectPath,u.projectName,u.createInPlace,e,i,n,d,u.overwriteExisting)}catch(e){if(u.failurePolicy===`clear`){let n=await cleanupFreshInitTarget(u.projectPath,u.failurePolicy,u.preservedEntries),r=e instanceof Error?e.message:String(e),i=n?`eve restored "${u.projectPath}" to its original state.`:`eve could not completely clean "${u.projectPath}".`;throw Error(`${r}\n\n${i}${workspaceFailureNote(t)}`)}if(u.failurePolicy===`remove`&&t){let t=e instanceof Error?e.message:String(e);throw Error(`${t}${workspaceFailureNote(!0)}`)}throw e}o={failurePolicy:u.failurePolicy,kind:`created`,packageManager:e,preservedTargetEntries:u.preservedEntries,projectPath:r.projectPath,retryCommand:`eve init ${u.projectPath}`,workspaceMember:t,workspaceRootMutations:r.workspaceRootMutations}}else{let e=await addToExistingProject(u.projectPath,i,n,d);o=e.nodeEngineOverride===void 0?{configurationFilesChanged:e.configurationFilesChanged,dependenciesAdded:e.dependenciesAdded,failurePolicy:`preserve`,filesWritten:e.filesWritten,kind:`added`,packageManager:e.packageManager,projectPath:u.projectPath}:{configurationFilesChanged:e.configurationFilesChanged,dependenciesAdded:e.dependenciesAdded,failurePolicy:`preserve`,filesWritten:e.filesWritten,kind:`added`,nodeEngineOverride:e.nodeEngineOverride,packageManager:e.packageManager,projectPath:u.projectPath}}let c=n.now()-a;initLog.debug(`${e} done`,{ms:c}),o.kind===`added`&&(p.stop(),reportExistingProjectChanges(r,o),p=startCliLiveRow(r)),m=`install_dependencies`,s?.(m),p.update(`Installing dependencies`,`${o.packageManager} install`),initLog.debug(`installing dependencies with ${o.packageManager}`);let g=n.now(),_=[],v=[],y=await n.runPackageManagerInstall(o.packageManager,o.projectPath,{progressDetails:process.stdout.isTTY===!0&&!l,onOutput:e=>{e.text.trim()!==``&&(v.push(e.text),v.length>20&&v.shift(),NPM_NOISE_LINE.test(e.text)||_.push(e.text)),l&&initLog.debug(e.text);let t=installProgressDetail(o.packageManager,e);t!==void 0&&p.update(`Installing dependencies`,t)}}),b=n.now()-g;if(!packageManagerInstallSucceeded(y)){h=packageManagerInstallFailureCode(y),initLog.debug(`dependency installation failed`,{ms:b}),p.stop();let e=_.length>0?_:v;for(let t of e)r.error(t);if(e.length===0){let e=packageManagerInstallFailureMessage(y);e!==void 0&&r.error(e)}if(o.failurePolicy!==`preserve`){if(await cleanupFreshInitTarget(o.projectPath,o.failurePolicy,o.preservedTargetEntries)){let e=o.failurePolicy===`remove`?`eve removed the incomplete project at "${o.projectPath}".`:`eve restored "${o.projectPath}" to its original state.`,t=o.workspaceMember||o.workspaceRootMutations.length>0;throw Error(`Failed to install dependencies.\n\n${e}\n\nResolve the package-manager error above, then retry:\n ${o.retryCommand}${workspaceFailureNote(t)}`)}let e=o.workspaceMember||o.workspaceRootMutations.length>0;throw Error(`Failed to install dependencies, and eve could not completely clean "${o.projectPath}".\n\nResolve the package-manager error above, then install dependencies with ${o.packageManager} in that directory. Or clean the target manually before rerunning eve init.${workspaceFailureNote(e)}`)}throw Error(`The eve agent was added, but dependency installation failed.\n\nResolve the package-manager error above, then install dependencies with ${o.packageManager} in "${o.projectPath}".\n\nDo not rerun eve init; the agent is already configured.`)}return initLog.debug(`dependencies installed`,{ms:b}),f&&(m=`registry_install`,s?.(m),p.update(`Enabling self-modification`),await n.installSelfModification(o.projectPath)),o.kind===`created`?(m=`initialize_git`,s?.(m),p.update(`Initializing Git repository`),initLog.debug(`initializing git repository`),{...o,agentElapsedMs:c,agentLaunched:t,gitResult:await n.tryInitializeGit(o.projectPath),installElapsedMs:b,selfModificationEnabled:f}):{...o,agentElapsedMs:c,agentLaunched:t,installElapsedMs:b,selfModificationEnabled:f}}catch(e){throw c?.(m,`error`,m===`install_dependencies`?h:void 0),e}finally{p.stop()}}async function runInitCommand(e,t,n,r,i=defaultDependencies,a,o){a?.(`resolve_target`);let s;try{if(await addAgentsToWorkspace(e,t,n,r,i.validateModelSlug)){a?.(`handoff`),o?.(`handoff`,`completed`);return}s=await runInitSteps({agentLaunched:await i.isCodingAgentLaunch(),dependencies:i,logger:e,options:r,parentDirectory:t,target:n,trackStep:a,trackTerminal:o})}catch(e){if(e instanceof WizardCancelledError){o?.(`resolve_target`,`cancelled`);return}throw e instanceof InitTargetError&&o?.(`resolve_target`,`error`,e.failureCode),e}if(a?.(`handoff`),s.kind===`created`){e.log(`${pc.green(`✓`)} Created an ${EVE_WORDMARK} agent in ${pc.bold(s.projectPath)} ${pc.dim(`in ${formatElapsed(s.agentElapsedMs)}`)}`);for(let t of s.workspaceRootMutations)e.log(pc.yellow(`⚠ ${formatWorkspaceRootMutationWarning(t)}`))}else e.log(`${pc.green(`✓`)} Added an ${EVE_WORDMARK} agent to ${pc.bold(s.projectPath)} ${pc.dim(`in ${formatElapsed(s.agentElapsedMs)}`)}`);e.log(`${pc.green(`✓`)} Installed dependencies ${pc.dim(`in ${formatElapsed(s.installElapsedMs)}`)}`),s.selfModificationEnabled&&e.log(`${pc.green(`✓`)} Enabled self-modification`),s.kind===`created`&&s.gitResult.kind===`failed`&&(e.error(pc.yellow(`Git initialization failed during ${s.gitResult.stage}: ${s.gitResult.reason}`)),s.gitResult.stage===`commit`&&e.error(pc.yellow(`The eve agent was created successfully. Git repository metadata and staged files were preserved at "${s.projectPath}"; the initial commit is optional.\n\nTo create it later, configure Git identity and run:\n git -C ${JSON.stringify(s.projectPath)} commit -m "Initial commit from eve"`)));let c=eveDevArguments(s.packageManager),l=[s.packageManager,...c].join(` `),u=initAgentDevHandoff({projectPath:s.projectPath,devCommand:l});if(s.agentLaunched){e.log(initAgentReadySummary(r.model,s.projectPath,{workspace:r.agents!==void 0})),e.log(u);return}let d;if(s.selfModificationEnabled)d=`eve-dev`;else try{d=await i.selectInitHandoff({agentName:basename(s.projectPath)})}catch(e){if(e instanceof WizardCancelledError)return;throw e}if(d===`exit`)return;if(d!==`eve-dev`){if(e.log(pc.dim(`$ ${d}`)),!await i.spawnCodingAgentRepl({command:d,cwd:s.projectPath,prompt:initAgentReplPrompt({devCommand:l}),onPromptUnseeded:t=>{e.log(pc.yellow(`Could not seed ${d} automatically. Paste this prompt into it:`)),e.log(t)}}))throw Error(`Coding-agent REPL exited unsuccessfully in "${s.projectPath}".`);return}let f=s.kind===`created`?[...c,`--onboard`]:c;if(e.log(pc.dim(`$ eve dev`)),!resultSucceeded(await i.spawnPackageManager(s.packageManager,s.projectPath,f)))throw Error(`Development server exited unsuccessfully in "${s.projectPath}".`)}function resolveInitEvePackageOverride(){let e=process.env[EVE_INIT_PACKAGE_SPEC_ENV]?.trim();if(e!==void 0&&e.length!==0)return{nodeEngine:DEFAULT_EVE_PACKAGE_CONTRACT.nodeEngine,version:e}}export{EVE_INIT_PACKAGE_SPEC_ENV,runInitCommand};
1
+ import{initAgentDevHandoff,initAgentReadySummary,initAgentReplPrompt}from"./agent-instructions.js";import{tryInitializeGit}from"./init-git.js";import{InitTargetError}from"./init-telemetry.js";import{addAgentsToWorkspace,convertScaffoldToAgentWorkspace,formatWorkspaceRootMutationWarning}from"./init-agent-workspace.js";import{NPM_NOISE_LINE,installProgressDetail,packageManagerInstallFailureCode}from"./init-install.js";import{reportExistingProjectChanges}from"./init-project.js";import{cleanupFreshInitTarget,workspaceFailureNote}from"./init-recovery.js";import{selectInitHandoff,spawnCodingAgentRepl}from"./init-repl.js";import{selectInitSelfModification}from"./init-self-modification.js";import{resolveInitTarget}from"./init-target.js";import{mkdtemp,readdir,rename,rm}from"node:fs/promises";import{createLogger,isLogLevelEnabled}from"#internal/logging.js";import{basename,join,resolve}from"node:path";import pc from"#compiled/picocolors/index.js";import{DEFAULT_AGENT_MODEL_ID}from"#shared/default-agent-model.js";import{ensureChannel,scaffoldBaseProject}from"#setup/scaffold/index.js";import{eveDevArguments,packageManagerInstallFailureMessage,packageManagerInstallSucceeded,resultSucceeded,runPackageManagerInstall,spawnPackageManager}from"#setup/primitives/index.js";import{performance}from"node:perf_hooks";import{isCodingAgentLaunch}from"#cli/agent-detection.js";import{EVE_WORDMARK}from"#cli/banner.js";import{formatElapsed}from"#cli/format-elapsed.js";import{startCliLiveRow}from"#cli/ui/live-row.js";import{detectInvokingPackageManager,detectPackageManager}from"#setup/package-manager.js";import{pathExists}from"#setup/path-exists.js";import{DEFAULT_EVE_PACKAGE_CONTRACT}from"#setup/scaffold/create/project.js";import{validateModelSlug}from"#setup/flows/model-source-change.js";import{addAgentToProject}from"#setup/scaffold/create/add-to-project.js";import{WizardCancelledError}from"#setup/step.js";import{isPackageManagerWorkspaceMember}from"#setup/scaffold/workspace-root.js";const defaultDependencies={addAgentToProject,detectInvokingPackageManager,detectPackageManager,ensureChannel,isCodingAgentLaunch,now:()=>performance.now(),runPackageManagerInstall,scaffoldBaseProject,selectInitHandoff,selectInitSelfModification,installSelfModification:async e=>{let{installRegistryItem:t}=await import(`./registry.js`);await t(e,`eve/self-modification`,{silent:!0,skipSetup:!0})},spawnCodingAgentRepl,spawnPackageManager,tryInitializeGit,validateModelSlug},EVE_INIT_PACKAGE_SPEC_ENV=`EVE_INIT_PACKAGE_SPEC`,initLog=createLogger(`init`);async function moveDirectoryContents(e,t){for(let n of await readdir(e))await rename(join(e,n),join(t,n))}function uniqueWorkspaceRootMutations(e){let t=new Map;for(let n of e){let e=`${n.kind}:${n.path}`,r=t.get(e);t.set(e,{...n,nodeEngineOverride:n.nodeEngineOverride??r?.nodeEngineOverride})}return[...t.values()]}async function addToExistingProject(e,t,n,r){if(t.channelWebNextjs===!0)throw Error("`--channel-web-nextjs` is not supported when adding an agent to an existing project. Run `eve add channel/web` from the project afterwards instead.");if(t.model!==void 0){let r=await n.validateModelSlug(e,t.model);if(r!==null)throw Error(r)}let i=await n.detectPackageManager(e),a=await n.addAgentToProject({projectRoot:e,model:t.model??DEFAULT_AGENT_MODEL_ID,reasoning:t.reasoning,packageManager:i.kind,evePackage:r});return{configurationFilesChanged:a.configurationFilesChanged,dependenciesAdded:a.dependenciesAdded,filesWritten:a.filesWritten,packageManager:i.kind,nodeEngineOverride:a.nodeEngineOverride}}async function resolveScaffoldPackageManager(e,t){let n=await t.detectPackageManager(e);return n.source==="default"?t.detectInvokingPackageManager()??`pnpm`:n.kind}async function scaffoldProject(e,t,n,r,i,a,o,s){let c=resolve(e,`..`),l=!n&&await pathExists(e)&&(await readdir(e)).length===0;if(!n&&await pathExists(e)&&!l)throw Error(`Cannot create project because "${e}" already exists.`);let u=n&&s?void 0:await mkdtemp(join(c,`.eve-init-`)),d=[];try{let c=u??e;if(i.model!==void 0){let e=await a.validateModelSlug(c,i.model);if(e!==null)throw Error(e)}let f={projectName:u===void 0?`.`:n?basename(e):t,model:i.model??DEFAULT_AGENT_MODEL_ID,reasoning:i.reasoning,evePackage:o,targetDirectory:c,overwriteExisting:s,workspaceProbeDirectory:e,packageManager:r,onWorkspaceRootMutation:e=>{d.push(e)}},p=await a.scaffoldBaseProject(f);return i.agents!==void 0&&await convertScaffoldToAgentWorkspace(p,i.agents,i),i.channelWebNextjs===!0&&await a.ensureChannel({projectRoot:p,kind:`web`,packageManager:r,force:s,workspaceProbeDirectory:e,configureVercelServices:!1,onWorkspaceRootMutation:e=>{d.push(e)}}),u!==void 0&&(n||l?await moveDirectoryContents(p,e):await rename(p,e)),{projectPath:e,workspaceRootMutations:uniqueWorkspaceRootMutations(d)}}finally{u!==void 0&&await rm(u,{recursive:!0,force:!0})}}async function runInitSteps(e){let{agentLaunched:t,dependencies:n,logger:r,options:i,parentDirectory:a,target:o,trackStep:s,trackTerminal:c}=e,l=isLogLevelEnabled(`debug`),u=await resolveInitTarget({parentDirectory:a,target:o}),d=resolveInitEvePackageOverride(),f=!t&&i.agents===void 0&&await n.selectInitSelfModification(),p=startCliLiveRow(r),m=`scaffold`,h;p.update(`Preparing project`);try{let e=u.kind===`fresh`?`creating agent`:`adding agent`;s?.(m),p.update(u.kind===`fresh`?`Creating agent`:`Adding agent`),initLog.debug(e);let a=n.now(),o;if(u.kind===`fresh`){let e=await resolveScaffoldPackageManager(u.projectPath,n),t=isPackageManagerWorkspaceMember(e,u.projectPath),r;try{r=await scaffoldProject(u.projectPath,u.projectName,u.createInPlace,e,i,n,d,u.overwriteExisting)}catch(e){if(u.failurePolicy===`clear`){let n=await cleanupFreshInitTarget(u.projectPath,u.failurePolicy,u.preservedEntries),r=e instanceof Error?e.message:String(e),i=n?`eve restored "${u.projectPath}" to its original state.`:`eve could not completely clean "${u.projectPath}".`;throw Error(`${r}\n\n${i}${workspaceFailureNote(t)}`)}if(u.failurePolicy===`remove`&&t){let t=e instanceof Error?e.message:String(e);throw Error(`${t}${workspaceFailureNote(!0)}`)}throw e}o={failurePolicy:u.failurePolicy,kind:`created`,packageManager:e,preservedTargetEntries:u.preservedEntries,projectPath:r.projectPath,retryCommand:`eve init ${u.projectPath}`,workspaceMember:t,workspaceRootMutations:r.workspaceRootMutations}}else{let e=await addToExistingProject(u.projectPath,i,n,d);o=e.nodeEngineOverride===void 0?{configurationFilesChanged:e.configurationFilesChanged,dependenciesAdded:e.dependenciesAdded,failurePolicy:`preserve`,filesWritten:e.filesWritten,kind:`added`,packageManager:e.packageManager,projectPath:u.projectPath}:{configurationFilesChanged:e.configurationFilesChanged,dependenciesAdded:e.dependenciesAdded,failurePolicy:`preserve`,filesWritten:e.filesWritten,kind:`added`,nodeEngineOverride:e.nodeEngineOverride,packageManager:e.packageManager,projectPath:u.projectPath}}let c=n.now()-a;initLog.debug(`${e} done`,{ms:c}),o.kind===`added`&&(p.stop(),reportExistingProjectChanges(r,o),p=startCliLiveRow(r)),m=`install_dependencies`,s?.(m),p.update(`Installing dependencies`,`${o.packageManager} install`),initLog.debug(`installing dependencies with ${o.packageManager}`);let g=n.now(),_=[],v=[],y=await n.runPackageManagerInstall(o.packageManager,o.projectPath,{progressDetails:process.stdout.isTTY===!0&&!l,onOutput:e=>{e.text.trim()!==``&&(v.push(e.text),v.length>20&&v.shift(),NPM_NOISE_LINE.test(e.text)||_.push(e.text)),l&&initLog.debug(e.text);let t=installProgressDetail(o.packageManager,e);t!==void 0&&p.update(`Installing dependencies`,t)}}),b=n.now()-g;if(!packageManagerInstallSucceeded(y)){h=packageManagerInstallFailureCode(y),initLog.debug(`dependency installation failed`,{ms:b}),p.stop();let e=_.length>0?_:v;for(let t of e)r.error(t);if(e.length===0){let e=packageManagerInstallFailureMessage(y);e!==void 0&&r.error(e)}if(o.failurePolicy!==`preserve`){if(await cleanupFreshInitTarget(o.projectPath,o.failurePolicy,o.preservedTargetEntries)){let e=o.failurePolicy===`remove`?`eve removed the incomplete project at "${o.projectPath}".`:`eve restored "${o.projectPath}" to its original state.`,t=o.workspaceMember||o.workspaceRootMutations.length>0;throw Error(`Failed to install dependencies.\n\n${e}\n\nResolve the package-manager error above, then retry:\n ${o.retryCommand}${workspaceFailureNote(t)}`)}let e=o.workspaceMember||o.workspaceRootMutations.length>0;throw Error(`Failed to install dependencies, and eve could not completely clean "${o.projectPath}".\n\nResolve the package-manager error above, then install dependencies with ${o.packageManager} in that directory. Or clean the target manually before rerunning eve init.${workspaceFailureNote(e)}`)}throw Error(`The eve agent was added, but dependency installation failed.\n\nResolve the package-manager error above, then install dependencies with ${o.packageManager} in "${o.projectPath}".\n\nDo not rerun eve init; the agent is already configured.`)}return initLog.debug(`dependencies installed`,{ms:b}),f&&(m=`registry_install`,s?.(m),p.update(`Enabling self-modification`),await n.installSelfModification(o.projectPath)),o.kind===`created`?(m=`initialize_git`,s?.(m),p.update(`Initializing Git repository`),initLog.debug(`initializing git repository`),{...o,agentElapsedMs:c,agentLaunched:t,gitResult:await n.tryInitializeGit(o.projectPath),installElapsedMs:b,selfModificationEnabled:f}):{...o,agentElapsedMs:c,agentLaunched:t,installElapsedMs:b,selfModificationEnabled:f}}catch(e){throw c?.(m,`error`,m===`install_dependencies`?h:void 0),e}finally{p.stop()}}async function runInitCommand(e,t,n,r,i=defaultDependencies,a,o){a?.(`resolve_target`);let s;try{if(await addAgentsToWorkspace(e,t,n,r,i.validateModelSlug)){a?.(`handoff`),o?.(`handoff`,`completed`);return}s=await runInitSteps({agentLaunched:await i.isCodingAgentLaunch(),dependencies:i,logger:e,options:r,parentDirectory:t,target:n,trackStep:a,trackTerminal:o})}catch(e){if(e instanceof WizardCancelledError){o?.(`resolve_target`,`cancelled`);return}throw e instanceof InitTargetError&&o?.(`resolve_target`,`error`,e.failureCode),e}if(a?.(`handoff`),s.kind===`created`){e.log(`${pc.green(`✓`)} Created an ${EVE_WORDMARK} agent in ${pc.bold(s.projectPath)} ${pc.dim(`in ${formatElapsed(s.agentElapsedMs)}`)}`);for(let t of s.workspaceRootMutations)e.log(pc.yellow(`⚠ ${formatWorkspaceRootMutationWarning(t)}`))}else e.log(`${pc.green(`✓`)} Added an ${EVE_WORDMARK} agent to ${pc.bold(s.projectPath)} ${pc.dim(`in ${formatElapsed(s.agentElapsedMs)}`)}`);e.log(`${pc.green(`✓`)} Installed dependencies ${pc.dim(`in ${formatElapsed(s.installElapsedMs)}`)}`),s.selfModificationEnabled&&e.log(`${pc.green(`✓`)} Enabled self-modification`),s.kind===`created`&&s.gitResult.kind===`failed`&&(e.error(pc.yellow(`Git initialization failed during ${s.gitResult.stage}: ${s.gitResult.reason}`)),s.gitResult.stage===`commit`&&e.error(pc.yellow(`The eve agent was created successfully. Git repository metadata and staged files were preserved at "${s.projectPath}"; the initial commit is optional.\n\nTo create it later, configure Git identity and run:\n git -C ${JSON.stringify(s.projectPath)} commit -m "Initial commit from eve"`)));let c=eveDevArguments(s.packageManager),l=[s.packageManager,...c].join(` `),u=initAgentDevHandoff({projectPath:s.projectPath,devCommand:l});if(s.agentLaunched){e.log(initAgentReadySummary(r.model,s.projectPath,{workspace:r.agents!==void 0})),e.log(u);return}let d;if(s.selfModificationEnabled)d=`eve-dev`;else try{d=await i.selectInitHandoff({agentName:basename(s.projectPath)})}catch(e){if(e instanceof WizardCancelledError)return;throw e}if(d===`exit`)return;if(d!==`eve-dev`){if(e.log(pc.dim(`$ ${d}`)),!await i.spawnCodingAgentRepl({command:d,cwd:s.projectPath,prompt:initAgentReplPrompt({devCommand:l}),onPromptUnseeded:t=>{e.log(pc.yellow(`Could not seed ${d} automatically. Paste this prompt into it:`)),e.log(t)}}))throw Error(`Coding-agent REPL exited unsuccessfully in "${s.projectPath}".`);return}let f=s.kind===`created`?[...c,`--onboard`]:c;if(e.log(pc.dim(`$ eve dev`)),!resultSucceeded(await i.spawnPackageManager(s.packageManager,s.projectPath,f)))throw Error(`Development server exited unsuccessfully in "${s.projectPath}".`)}function resolveInitEvePackageOverride(){let e=process.env[EVE_INIT_PACKAGE_SPEC_ENV]?.trim();if(e!==void 0&&e.length!==0)return{nodeEngine:DEFAULT_EVE_PACKAGE_CONTRACT.nodeEngine,version:e}}export{EVE_INIT_PACKAGE_SPEC_ENV,runInitCommand};
@@ -1 +1 @@
1
- import{join,resolve}from"node:path";import{readFileSync}from"node:fs";import{parseEnv}from"node:util";import{findEveProjectRoot}from"#internal/eve-project-root.js";import{isObject}from"#shared/guards.js";import{readProviderSelectionSync}from"#setup/provider-settings.js";const DEVELOPMENT_ENV_FILE_NAMES=[`.env.development.local`,`.env.local`,`.env.development`,`.env`];function isMissingEnvironmentFileError(e){return isObject(e)&&e.code===`ENOENT`}const developmentEnvironmentLoaders=new Map;function getDevelopmentEnvironmentFilePaths(e){return DEVELOPMENT_ENV_FILE_NAMES.map(t=>join(getDevelopmentEnvironmentLoader(e).environmentRoot,t))}async function loadDevelopmentEnvironmentFiles(e){let t=resolve(e);getDevelopmentEnvironmentLoader(t,await findEveProjectRoot(t)).reload()}function stageDevelopmentEnvironmentFiles(e){return getDevelopmentEnvironmentLoader(e).stageReload()}function readDevelopmentEnvironmentHostValues(e){let t={},n=readDevelopmentEnvironmentValues(getDevelopmentEnvironmentLoader(e).environmentRoot),r=new Set(n.keys());r.add(`AI_GATEWAY_API_KEY`);for(let e of[...r].sort((e,t)=>e.localeCompare(t)))t[e]=process.env[e]??null;return t}function getDevelopmentEnvironmentLoader(e,t){let n=resolve(e),r=developmentEnvironmentLoaders.get(n);if(r!==void 0&&t===void 0)return r;let i=resolve(t??n);if(r?.environmentRoot===i)return r;let a=createDevelopmentEnvironmentLoader(n,i);return developmentEnvironmentLoaders.set(n,a),a}function createDevelopmentEnvironmentLoader(e,t){let n=new Map(Object.entries(process.env)),r=new Set(n.keys()),i=new Map,stageReload=()=>{let a=new Map(i),o=readDevelopmentEnvironmentValues(t),s=applyProviderSelection(e,o),c=new Set([...i.keys(),...o.keys()]);s?(c.add(`AI_GATEWAY_API_KEY`),r.delete(`AI_GATEWAY_API_KEY`)):n.has(`AI_GATEWAY_API_KEY`)&&(r.add(`AI_GATEWAY_API_KEY`),process.env.AI_GATEWAY_API_KEY=n.get(`AI_GATEWAY_API_KEY`));let l=new Map([...c].map(e=>[e,process.env[e]])),u=!1;return s&&delete process.env.AI_GATEWAY_API_KEY,applyDevelopmentEnvironmentValues({managedValues:i,nextValues:o,protectedKeys:r}),{commit(){u=!0},rollback(){if(!u){u=!0,i.clear();for(let[e,t]of a)i.set(e,t);for(let[e,t]of l)t===void 0?delete process.env[e]:process.env[e]=t}}}};return{environmentRoot:t,reload(){stageReload().commit()},stageReload}}function applyProviderSelection(e,t){return readProviderSelectionSync(e)===`ai-gateway-project`&&(t.delete(`AI_GATEWAY_API_KEY`),!0)}function applyDevelopmentEnvironmentValues(e){for(let[t,n]of e.managedValues)e.nextValues.has(t)||e.protectedKeys.has(t)||(process.env[t]===n&&delete process.env[t],e.managedValues.delete(t));for(let[t,n]of e.nextValues)e.protectedKeys.has(t)||(process.env[t]=n,e.managedValues.set(t,n))}function readDevelopmentEnvironmentValues(e){let t=new Map;for(let n of[...DEVELOPMENT_ENV_FILE_NAMES].reverse())try{let r=parseEnv(readFileSync(join(e,n),`utf8`));for(let[e,n]of Object.entries(r))n!==void 0&&t.set(e,n)}catch(e){if(!isMissingEnvironmentFileError(e))throw e}return t}export{DEVELOPMENT_ENV_FILE_NAMES,getDevelopmentEnvironmentFilePaths,loadDevelopmentEnvironmentFiles,readDevelopmentEnvironmentHostValues,stageDevelopmentEnvironmentFiles};
1
+ import{isObject}from"#shared/guards.js";import{join,resolve}from"node:path";import{readFileSync}from"node:fs";import{parseEnv}from"node:util";import{findEveProjectRoot}from"#internal/eve-project-root.js";import{readProviderSelectionSync}from"#setup/provider-settings.js";const DEVELOPMENT_ENV_FILE_NAMES=[`.env.development.local`,`.env.local`,`.env.development`,`.env`];function isMissingEnvironmentFileError(e){return isObject(e)&&e.code===`ENOENT`}const developmentEnvironmentLoaders=new Map;function getDevelopmentEnvironmentFilePaths(e){return DEVELOPMENT_ENV_FILE_NAMES.map(t=>join(getDevelopmentEnvironmentLoader(e).environmentRoot,t))}async function loadDevelopmentEnvironmentFiles(e){let t=resolve(e);getDevelopmentEnvironmentLoader(t,await findEveProjectRoot(t)).reload()}function stageDevelopmentEnvironmentFiles(e){return getDevelopmentEnvironmentLoader(e).stageReload()}function readDevelopmentEnvironmentHostValues(e){let t={},n=readDevelopmentEnvironmentValues(getDevelopmentEnvironmentLoader(e).environmentRoot),r=new Set(n.keys());r.add(`AI_GATEWAY_API_KEY`);for(let e of[...r].sort((e,t)=>e.localeCompare(t)))t[e]=process.env[e]??null;return t}function getDevelopmentEnvironmentLoader(e,t){let n=resolve(e),r=developmentEnvironmentLoaders.get(n);if(r!==void 0&&t===void 0)return r;let i=resolve(t??n);if(r?.environmentRoot===i)return r;let a=createDevelopmentEnvironmentLoader(n,i);return developmentEnvironmentLoaders.set(n,a),a}function createDevelopmentEnvironmentLoader(e,t){let n=new Map(Object.entries(process.env)),r=new Set(n.keys()),i=new Map,stageReload=()=>{let a=new Map(i),o=readDevelopmentEnvironmentValues(t),s=applyProviderSelection(e,o),c=new Set([...i.keys(),...o.keys()]);s?(c.add(`AI_GATEWAY_API_KEY`),r.delete(`AI_GATEWAY_API_KEY`)):n.has(`AI_GATEWAY_API_KEY`)&&(r.add(`AI_GATEWAY_API_KEY`),process.env.AI_GATEWAY_API_KEY=n.get(`AI_GATEWAY_API_KEY`));let l=new Map([...c].map(e=>[e,process.env[e]])),u=!1;return s&&delete process.env.AI_GATEWAY_API_KEY,applyDevelopmentEnvironmentValues({managedValues:i,nextValues:o,protectedKeys:r}),{commit(){u=!0},rollback(){if(!u){u=!0,i.clear();for(let[e,t]of a)i.set(e,t);for(let[e,t]of l)t===void 0?delete process.env[e]:process.env[e]=t}}}};return{environmentRoot:t,reload(){stageReload().commit()},stageReload}}function applyProviderSelection(e,t){return readProviderSelectionSync(e)===`ai-gateway-project`&&(t.delete(`AI_GATEWAY_API_KEY`),!0)}function applyDevelopmentEnvironmentValues(e){for(let[t,n]of e.managedValues)e.nextValues.has(t)||e.protectedKeys.has(t)||(process.env[t]===n&&delete process.env[t],e.managedValues.delete(t));for(let[t,n]of e.nextValues)e.protectedKeys.has(t)||(process.env[t]=n,e.managedValues.set(t,n))}function readDevelopmentEnvironmentValues(e){let t=new Map;for(let n of[...DEVELOPMENT_ENV_FILE_NAMES].reverse())try{let r=parseEnv(readFileSync(join(e,n),`utf8`));for(let[e,n]of Object.entries(r))n!==void 0&&t.set(e,n)}catch(e){if(!isMissingEnvironmentFileError(e))throw e}return t}export{DEVELOPMENT_ENV_FILE_NAMES,getDevelopmentEnvironmentFilePaths,loadDevelopmentEnvironmentFiles,readDevelopmentEnvironmentHostValues,stageDevelopmentEnvironmentFiles};
@@ -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{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.#bn().join(`
2
+ `);if(this.#O){t!==this.#k&&(this.#k=t,this.#Kt({kind:`agent-header`,body:t,live:!1})),this.#hn();return}this.#O=!0,this.#k=t,this.#n.flush(this.#bn(),[])}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.#hn();let apply=e=>{t=e,this.#Ht(),this.#Qe(t),this.#hn()};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(`
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(`
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.#hn(),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.#hn()},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.#hn());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.#hn();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.#hn();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.#hn());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.#hn(),this.#Nt(),e(n);break}case`ctrl-d`:i.text.length===0?(this.#Tt(),interrupt()):apply(deleteForward(i));break;case`ctrl-l`:this.#vn();break;case`ctrl-r`:this.#hn();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.#hn();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.#rn(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.#un(i),(this.#ee||i.cancelled)&&this.#ln(i),this.#nn(),this.#d?.reportStats(),this.#hn(),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.#rn(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.#un(r),r.cancelled&&this.#ln(r),this.#nn(),this.#d?.reportStats(),this.#hn()}}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.#hn(),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.#hn(),t({approved:!0})):n===`n`&&(this.#Wt(),this.#J=STATUS.processing,this.#et(e.toolCallId),this.#Nt(),this.#hn(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#hn();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.#hn()):(s=`text`,this.#Ie=void 0,renderTextSection(),this.#R=!0,this.#Qe(l),this.#J=``,this.#Bt(),this.#hn());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.#hn();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.#hn(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#hn())},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.#hn();return}this.#ee=!0,this.#Ie=void 0,this.#Vt(),this.#jt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#hn();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.#hn();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#Ht(),this.#hn());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.#hn())}}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#Ht(),this.#Qe(l),this.#hn();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.#hn());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.#hn();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.#hn();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.#hn()}}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.#hn();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#sn({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.#hn()}#$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.#hn()}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.#hn()}backgroundSubagent(e){let t=this.#h.get(subagentHeaderId(e.callId));if(t===void 0||this.#g.has(subagentHeaderId(e.callId)))return;t.status=`running`,t.live=!0,t.updateSeq=++this.#b;let n=this.#S.has(e.callId);this.#S.add(e.callId),n||this.#tn(e.callId),this.#hn()}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.#hn()}}markChildToolCallId(e){this.#v.add(e);let t=this.#y.get(e);t!==void 0&&(this.#en(t),this.#y.delete(e),this.#hn())}#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.#hn()}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.#hn()):n&&(this.#J=STATUS.processing,this.#hn())}setVercelStatus(e){this.#N=e,this.#hn()}setRemoteConnectionStatus(e){this.#P=e,this.#hn()}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.#hn())}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.#hn()}#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.#hn())}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.#hn())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#nt();return}this.#kt(),this.#Re=t,this.#hn()}clearSetupWarning(){this.#nt()}#nt(){this.#Re!==void 0&&(this.#Re=void 0,this.#hn())}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.#hn()}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.#hn())}#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.#hn()}#it(e){this.#Le!==void 0&&(this.#Le.navigation=e,this.#hn())}#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.#hn()}}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.#hn()},loadSearch=async(e,t)=>{l=!0,c=void 0;let o=++u;this.#hn();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.#hn())}},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.#Sn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#hn(),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.#hn();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.#hn();return;case`update`:s=m.select,c=void 0,this.#hn();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.#hn();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.#hn();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.#hn();return;case`repaint`:this.#hn();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.#hn(),await this.#gt((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Ht(),this.#hn()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#hn()},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.#hn();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.#hn();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.#hn(),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.#hn();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#hn();return;case`validate`:{n=o.state,syncCaret(),this.#hn();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.#hn();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.#hn(),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.#hn();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.#hn();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.#hn(),await this.#gt((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Ht(),this.#hn()},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.#hn();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#hn();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.#hn(),await this.#gt((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#hn();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.#hn()}#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.#hn()};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.#hn();return}if(!(this.#R||this.#G)){if(t===void 0){this.#K={kind:`idle`},this.#Y=void 0,this.#Gt(),this.#hn();return}this.#kt(),this.#Wt(),this.#Y=t.text,this.#hn()}}#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.#hn();return}this.#kt(),this.#Kt({kind:`flow`,title:t,body:n,live:!1}),this.#hn()}#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.#hn())}#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.#hn()}async#wt(e){this.#pe=``,this.#Rt(),this.#Je=void 0,this.#yt(),this.#Nt(),this.#Gt(),this.#n.clear(),this.#Ln(),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.#In(),this.#Le!==void 0&&(this.#Ut(),this.#vt()),this.#n.reset(),this.#hn()}}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.#Pn(),height:this.#Fn()}),paint:e=>this.#r.paint(e,this.#Fn()),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.#hn(),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.#In(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#ge=()=>this.#hn(),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.#Gn(),this.#Z){this.#qn();for(let e of this.#m)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#hn(),this.#n.clear(),this.#n.showCursor(),this.#Ln(),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.#hn();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.#hn();break}this.#Ve.enqueue(e)&&(this.#W=EMPTY_LINE),this.#hn();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.#hn();break}if(this.#Ve.idle&&this.#He===void 0)break;this.#Ve.handleEscape(),this.#Ke=!0,this.#He?.(),this.#hn();break;default:{let t=applyLineEditorKey(this.#W,e,{multiline:!0});t!==void 0&&(this.#W=t,this.#hn());break}}}#Bt(){this.#Vt(),this.#Ht(),this.#ce=setInterval(()=>{this.#ae=!this.#ae,this.#hn()},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.#hn()},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.#qn(),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.#hn()}#Jt(){let e=this.#U.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#Dn(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.#hn()}#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.#qn(),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(e){let t=this.#m.filter(t=>t.subagentCallId===e);t.length!==0&&(this.#m=this.#m.filter(t=>t.subagentCallId!==e),this.#m.push(...t))}#nn(){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)}#rn(e,t,n){switch(e.type){case`step-finish`:this.#d?.recordStepUsage(e.usage),e.usage!==void 0&&this.#U.addUsage(e.usage),this.#un(n),this.#mn(e.usage),this.#hn();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#in(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.#in(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.#an(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.#an(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#on({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.#on({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.#on({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#pn(e.toolCallId,n);if(r===void 0)break;this.#on({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#pn(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.#on({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#pn(e.toolCallId,n);if(r===void 0)break;this.#on({...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.#mn(e.usage),this.#hn()}}#in(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#Qt({id:e,kind:`assistant`,body:r,live:n}),this.#hn())}#an(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.#hn())}#on(e,t,n){if(n.tools.set(e.toolCallId,e),this.#v.has(e.toolCallId)||this.#dn(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#y.set(e.toolCallId,r);let i=this.#sn(e);this.#Qt(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#fn(n),this.#hn()}#sn(e){e.output!==void 0&&this.#w.observeRead(e.output);let t={};this.#cn(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}#cn(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)}#ln(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)}}#un(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)}}#dn(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.#Pn(),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.#hn(),!0}#fn(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)}#pn(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`}}#mn(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)}}#hn(){if(this.#Z){if(this.#ve){this.#ye=!0;return}this.#ve=!0;try{do this.#ye=!1,this.#gn();while(this.#ye)}finally{this.#ve=!1}}}#gn(){if(!this.#Z)return;if(this.#Xe!==void 0){this.#Xe.repaint();return}let e=this.#Pn(),t=this.#Tn(e),n=this.#D===void 0?[]:this.#bn(),r=Math.max(1,this.#Fn()-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.#Yn(t.display))continue;let n=this.#xn(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.#Yn(t))continue;let n=this.#xn(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)}#_n(){if(!this.#Z)return;let e=this.#Pn(),t=this.#Tn(e),n=Math.max(1,this.#Fn()-t.length),r=this.#j,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#m)){if(this.#Yn(t))continue;let n=this.#xn(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.#bn(),...this.#A],a)}logDisplayMode(){return this.#p}setLogDisplayMode(e){e!==this.#p&&(this.#p=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#yn(),this.#Z&&this.#_n())}flushDelayedDevBuildErrors(){let e=this.#ke;e!==void 0&&(this.#ke=void 0,this.#Kt({kind:`log`,title:`stderr`,body:e,live:!0}),this.#hn())}#vn(){this.#de=!0,this.#ue!==void 0&&clearTimeout(this.#ue),this.#ue=setTimeout(()=>{this.#de=!1,this.#ue=void 0,this.#hn()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#p)),this.#hn()}#yn(){let e=this.#Pn();this.#A.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#_,{logCoalescing:`runs`})){if(this.#Yn(n))continue;let r=this.#xn(n,e,t);t=previousBlockOf(n),this.#A.push(...r)}this.#j=t}#bn(){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.#Pn()};e?.info!==void 0&&(n.info=e.info);let r=e?.tip??t?.tip;return r!==void 0&&(n.tip=r),buildAgentHeader(n)}#xn(e,t,n){let r={activityPulse:this.#Cn(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}#Sn(){return this.#i.spinner[this.#oe%this.#i.spinner.length]??``}#Cn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#wn(e,t){return e.indicator.kind===`spinner`?{glyph:this.#Sn(),color:`yellow`}:{glyph:this.#Cn(e.indicator.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#Tn(e){let t=this.#i.colors,n=[``];if(this.#Ie!==void 0)return n.push(...this.#Ie(e),``),this.#jn(n,e),n;let r=this.#Le;if(r!==void 0){let t=this.#wn(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.#Mn(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.#Cn(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.#jn(o,e);let s=Math.max(1,this.#Fn()-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.#En(e)),this.#kn(n,e);let t=[];return this.#jn(t,e),!this.#G&&t.length>0&&n.push(``),n.push(...t),n}if(this.#W.text.length>0)return this.#An(n,e,{inert:!1}),this.#jn(n,e),n;let o=this.#Y??(this.#J.length>0?this.#J:`Ready`),s=this.#Nn(),c=t.dim(this.#i.glyph.dot),l=s?`${c} ${o} ${t.dim(this.#i.glyph.dot)} ${s}`:`${c} ${o}`;return n.push(clip(l,e)),this.#jn(n,e),n}#En(e){let t=this.#i.colors,n=this.#Cn(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.#Dn(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#Dn(e){return`${formatTurnDuration(e)}${this.#On()}`}#On(){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)}`}#kn(e,t){this.#G&&this.#An(e,t,{inert:!0})}#An(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))}#jn(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))}#Mn(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))}#Nn(){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} `)):``}#Pn(){return Math.max(20,this.#t.columns||80)}#Fn(){return Math.max(8,this.#t.rows||24)}#In(){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.#zn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#d?.subscribeLogRecords(e=>this.#Rn(e)),this.#Ee=()=>{this.#d?.unsubscribeLogRecords(),e(),t()}}#Ln(){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.#Jn(`stdout`)&&process.stdout.write(`${this.#De}\n`),this.#De=``),this.#Oe.length>0&&(this.#d?.append({source:`stderr`,detail:this.#Oe}),this.#Jn(`stderr`)&&process.stderr.write(`${this.#Oe}\n`),this.#Oe=``))}#Rn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#Vn(`[eve:${e.namespace}] ${e.message}${t}`),this.#hn()}#zn(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.#Bn(n.trimEnd()),this.#hn();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.#Bn(a):this.#Vn(a),this.#hn())}#Bn(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
9
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(`
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.#Un(r,n.trimEnd())}flushPending()}#Vn(e){let t=e.split(`
11
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
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(`
13
+ `);this.#Hn(i)}#Hn(e){if(this.#Gn(),this.#p===`all`){if(e.trim().length===0)return;this.#Kt({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#ke=e}#Un(e,t){let n=this.#Kn();if(e.kind===`failed`){this.#Hn(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(this.#Wn({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.#Wn({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})}#Wn(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.#Gn(),this.#hn()},e.phase===`building`?250:4e3)}#Gn(){this.#Ne!==void 0&&clearTimeout(this.#Ne),this.#je=void 0,this.#Me=!1,this.#Ne=void 0}#Kn(){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}}#qn(){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)}#Jn(e){switch(this.#p){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#Yn(e){return e.kind===`sandbox`?!this.#Jn(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#p!==`stderr`:e.logVisibility===`all-only`?this.#p!==`all`:!this.#Jn(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};
@@ -56,7 +56,7 @@
56
56
  "zod": "4.5.4",
57
57
  "zod-validation-error": "5.0.0"
58
58
  },
59
- "scriptHash": "6dd35b7b0dab12a3395adfefa5f9a84d9e04ce6137d3d64434c468df5419375e",
59
+ "scriptHash": "3665e8d69fd9c7e91180444a928e03e29c91908b62ab1637eb66792dda79cd4d",
60
60
  "toolVersions": {
61
61
  "rolldown": "1.2.7",
62
62
  "typescript": "7.0.2"