eve 0.6.0-beta.17 → 0.6.0-beta.18

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 (142) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -2
  3. package/dist/docs/public/advanced/auth-and-route-protection.md +2 -0
  4. package/dist/docs/public/agent-config.md +1 -1
  5. package/dist/docs/public/connections.mdx +3 -1
  6. package/dist/docs/public/getting-started.mdx +19 -8
  7. package/dist/docs/public/reference/cli.md +0 -1
  8. package/dist/src/chunks/{use-eve-agent-tFYnZx_b.js → use-eve-agent-DErQj5hs.js} +2 -1
  9. package/dist/src/chunks/{use-eve-agent-q1isCIFv.js → use-eve-agent-DoR8C4i6.js} +2 -1
  10. package/dist/src/cli/commands/init.d.ts +14 -6
  11. package/dist/src/cli/commands/init.js +1 -1
  12. package/dist/src/cli/dev/tui/blocks.d.ts +1 -1
  13. package/dist/src/cli/dev/tui/blocks.js +2 -1
  14. package/dist/src/cli/dev/tui/runner.js +1 -1
  15. package/dist/src/cli/dev/tui/stream-format.js +1 -1
  16. package/dist/src/cli/dev/tui/terminal-renderer.d.ts +5 -5
  17. package/dist/src/cli/dev/tui/terminal-renderer.js +3 -2
  18. package/dist/src/cli/dev/tui/tui.d.ts +0 -8
  19. package/dist/src/cli/dev/tui/tui.js +1 -1
  20. package/dist/src/cli/run.d.ts +3 -16
  21. package/dist/src/cli/run.js +2 -2
  22. package/dist/src/client/index.js +1 -1
  23. package/dist/src/client/open-stream.js +1 -1
  24. package/dist/src/client/session.js +1 -1
  25. package/dist/src/compiler/normalize-channel.d.ts +2 -1
  26. package/dist/src/compiler/normalize-channel.js +1 -1
  27. package/dist/src/compiler/normalize-connection.d.ts +2 -1
  28. package/dist/src/compiler/normalize-connection.js +1 -1
  29. package/dist/src/compiler/normalize-helpers.d.ts +5 -0
  30. package/dist/src/compiler/normalize-helpers.js +1 -1
  31. package/dist/src/compiler/normalize-instructions.d.ts +3 -2
  32. package/dist/src/compiler/normalize-instructions.js +1 -1
  33. package/dist/src/compiler/normalize-manifest.js +2 -2
  34. package/dist/src/compiler/normalize-sandbox.d.ts +2 -1
  35. package/dist/src/compiler/normalize-sandbox.js +1 -1
  36. package/dist/src/compiler/normalize-schedule.d.ts +2 -1
  37. package/dist/src/compiler/normalize-schedule.js +1 -1
  38. package/dist/src/compiler/normalize-skill.d.ts +2 -1
  39. package/dist/src/compiler/normalize-skill.js +1 -1
  40. package/dist/src/compiler/normalize-subagent.d.ts +4 -1
  41. package/dist/src/compiler/normalize-subagent.js +1 -1
  42. package/dist/src/compiler/normalize-tool.d.ts +2 -1
  43. package/dist/src/compiler/normalize-tool.js +1 -1
  44. package/dist/src/evals/cli/eval.js +1 -1
  45. package/dist/src/evals/session.js +1 -1
  46. package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
  47. package/dist/src/execution/workflow-steps.js +1 -1
  48. package/dist/src/harness/code-mode-lifecycle.js +1 -1
  49. package/dist/src/harness/emission.js +1 -1
  50. package/dist/src/harness/tool-loop.js +1 -1
  51. package/dist/src/harness/turn-tag-state.d.ts +4 -0
  52. package/dist/src/harness/turn-tag-state.js +1 -1
  53. package/dist/src/internal/application/package.js +1 -1
  54. package/dist/src/internal/authored-module-loader.d.ts +4 -1
  55. package/dist/src/internal/authored-module-loader.js +2 -2
  56. package/dist/src/internal/authored-module-map-loader.js +1 -1
  57. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  58. package/dist/src/internal/nitro/host/server-external-packages.d.ts +1 -1
  59. package/dist/src/internal/nitro/host/server-external-packages.js +1 -1
  60. package/dist/src/node_modules/.pnpm/@clack_core@1.3.1/node_modules/@clack/core/dist/index.js +4 -4
  61. package/dist/src/protocol/message.d.ts +7 -0
  62. package/dist/src/protocol/message.js +1 -1
  63. package/dist/src/public/channels/slack/defaults.js +1 -1
  64. package/dist/src/public/channels/teams/defaults.js +1 -1
  65. package/dist/src/public/connections/errors.d.ts +8 -0
  66. package/dist/src/public/next/index.d.ts +1 -1
  67. package/dist/src/public/next/server.js +1 -1
  68. package/dist/src/public/nuxt/dev-server.js +1 -1
  69. package/dist/src/public/sveltekit/dev-server.js +1 -1
  70. package/dist/src/public/sveltekit/index.d.ts +1 -1
  71. package/dist/src/runtime/connections/scoped-authorization.d.ts +12 -0
  72. package/dist/src/runtime/connections/scoped-authorization.js +1 -1
  73. package/dist/src/runtime/connections/types.d.ts +9 -0
  74. package/dist/src/runtime/connections/validate-authorization.js +1 -1
  75. package/dist/src/runtime/framework-tools/connection-search-dynamic.js +1 -1
  76. package/dist/src/services/dev-client/client-options.d.ts +4 -4
  77. package/dist/src/services/dev-client.d.ts +0 -46
  78. package/dist/src/services/dev-client.js +1 -1
  79. package/dist/src/setup/boxes/add-channels.d.ts +5 -3
  80. package/dist/src/setup/boxes/add-channels.js +1 -1
  81. package/dist/src/setup/boxes/deploy-project.d.ts +4 -2
  82. package/dist/src/setup/boxes/deploy-project.js +1 -1
  83. package/dist/src/setup/boxes/one-shot-next-steps.d.ts +3 -0
  84. package/dist/src/setup/boxes/one-shot-next-steps.js +1 -1
  85. package/dist/src/setup/boxes/select-channels.d.ts +1 -1
  86. package/dist/src/setup/boxes/select-channels.js +1 -1
  87. package/dist/src/setup/boxes/select-chat.d.ts +1 -1
  88. package/dist/src/setup/boxes/select-chat.js +1 -1
  89. package/dist/src/setup/flows/channels.js +1 -1
  90. package/dist/src/setup/index.d.ts +1 -1
  91. package/dist/src/setup/index.js +1 -1
  92. package/dist/src/setup/package-manager.d.ts +27 -0
  93. package/dist/src/setup/package-manager.js +1 -0
  94. package/dist/src/setup/primitives/index.d.ts +2 -1
  95. package/dist/src/setup/primitives/index.js +1 -1
  96. package/dist/src/setup/primitives/pm/bun.d.ts +10 -0
  97. package/dist/src/setup/primitives/pm/bun.js +1 -0
  98. package/dist/src/setup/primitives/pm/index.d.ts +11 -0
  99. package/dist/src/setup/primitives/pm/index.js +1 -0
  100. package/dist/src/setup/primitives/pm/npm.d.ts +10 -0
  101. package/dist/src/setup/primitives/pm/npm.js +1 -0
  102. package/dist/src/setup/primitives/pm/pnpm.d.ts +27 -0
  103. package/dist/src/setup/primitives/pm/pnpm.js +8 -0
  104. package/dist/src/setup/primitives/pm/run.d.ts +23 -0
  105. package/dist/src/setup/primitives/pm/run.js +1 -0
  106. package/dist/src/setup/primitives/pm/shared.d.ts +8 -0
  107. package/dist/src/setup/primitives/pm/shared.js +1 -0
  108. package/dist/src/setup/primitives/pm/types.d.ts +37 -0
  109. package/dist/src/setup/primitives/pm/types.js +1 -0
  110. package/dist/src/setup/primitives/pm/yarn.d.ts +10 -0
  111. package/dist/src/setup/primitives/pm/yarn.js +1 -0
  112. package/dist/src/setup/primitives/run-pnpm.d.ts +1 -17
  113. package/dist/src/setup/primitives/run-pnpm.js +1 -1
  114. package/dist/src/setup/scaffold/create/add-to-project.d.ts +26 -0
  115. package/dist/src/setup/scaffold/create/add-to-project.js +1 -0
  116. package/dist/src/setup/scaffold/create/project.d.ts +17 -0
  117. package/dist/src/setup/scaffold/create/project.js +11 -11
  118. package/dist/src/setup/scaffold/update/channels.d.ts +3 -0
  119. package/dist/src/setup/scaffold/update/channels.js +2 -2
  120. package/dist/src/setup/scaffold/update/connections.js +3 -3
  121. package/dist/src/shared/agent-definition.d.ts +5 -3
  122. package/dist/src/svelte/index.js +1 -1
  123. package/dist/src/svelte/use-eve-agent.js +1 -1
  124. package/dist/src/vue/index.js +1 -1
  125. package/dist/src/vue/use-eve-agent.js +1 -1
  126. package/package.json +1 -1
  127. package/dist/src/cli/dev/repl/input-requests.d.ts +0 -38
  128. package/dist/src/cli/dev/repl/input-requests.js +0 -1
  129. package/dist/src/cli/dev/repl/input.d.ts +0 -19
  130. package/dist/src/cli/dev/repl/input.js +0 -1
  131. package/dist/src/cli/dev/repl/repl.d.ts +0 -62
  132. package/dist/src/cli/dev/repl/repl.js +0 -2
  133. package/dist/src/cli/dev/repl/terminal.d.ts +0 -21
  134. package/dist/src/cli/dev/repl/terminal.js +0 -5
  135. package/dist/src/services/dev-client/stream.d.ts +0 -5
  136. package/dist/src/services/dev-client/stream.js +0 -1
  137. package/dist/src/services/dev-client/url.d.ts +0 -11
  138. package/dist/src/services/dev-client/url.js +0 -1
  139. package/dist/src/setup/primitives/pnpm-invocation.d.ts +0 -12
  140. package/dist/src/setup/primitives/pnpm-invocation.js +0 -1
  141. package/dist/src/setup/scaffold/update/pnpm-workspace.d.ts +0 -3
  142. package/dist/src/setup/scaffold/update/pnpm-workspace.js +0 -8
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # eve
2
2
 
3
+ ## 0.6.0-beta.18
4
+
5
+ ### Minor Changes
6
+
7
+ - aa5cfdc: Connection and tool `auth` definitions accept an optional `displayName`, and authorization challenges carry it to channels — sign-in buttons now show e.g. "Sign in with Salesforce" instead of a title-cased file name. The value is presentation-only (scope, token cache keys, and callback URLs stay keyed by the path-derived name), a definition-level `displayName` wins over one the strategy stamps on the challenge, and channels keep title-casing the name when neither is set.
8
+ - e55bb46: `eve init` now accepts an existing project directory as its target (e.g. `eve init .`): the project must have a `package.json` and use npm, pnpm, or yarn (bun is not supported yet), the `agent/` files must not already exist, and the missing `eve`/`ai`/`zod` dependencies are added without touching anything else the project owns. pnpm projects additionally receive the pnpm workspace policy. In both modes the final handoff now runs the `eve dev` binary through the project's package manager instead of the project's `dev` script, which in an existing app could start unrelated processes.
9
+
10
+ The bootstrap install disables npm's and pnpm's minimum-release-age cooldown for that single run — the scaffold pins versions younger than typical windows, so the gate would fail every fresh bootstrap. Later installs follow the project's own configuration.
11
+
12
+ - e55bb46: `eve init <name>` now scaffolds the new project with the package manager that launched it: `npx` produces an npm-managed project and `yarn dlx` a yarn one, while `pnpm dlx` and direct binary runs keep today's pnpm scaffold. Non-pnpm scaffolds no longer receive `pnpm-workspace.yaml`, `--channel-web-nextjs` requires a pnpm launch, and a bun launch is rejected until bun support lands.
13
+ - ca290a0: Remove the legacy `eve dev --repl` line-based REPL. The terminal UI is the only interactive dev UI; `--no-ui` starts the server headless. The deprecated `--no-repl` alias is no longer accepted — pass `--no-ui` instead.
14
+ - e55bb46: Run setup and generated-project configuration through package-manager strategies for npm, pnpm, Yarn, and Bun. `eve init --channel-web-nextjs` now works with every supported manager instead of requiring a pnpm launch.
15
+
16
+ ### Patch Changes
17
+
18
+ - 1acc94e: Apply `build.externalDependencies` to authored module bundling and hosted output tracing, including imports from workspace packages and subagents.
19
+ - 8afd7bc: Emit `$eve.cache_write_tokens` as a per-turn observability tag, alongside the existing `$eve.input_tokens`, `$eve.output_tokens`, and `$eve.cache_read_tokens`. The value is read from the AI SDK's `usage.inputTokenDetails.cacheWriteTokens` and accumulated across tool-loop steps within a turn.
20
+ - ca290a0: Ctrl+C during a streaming `eve dev` response now aborts the underlying HTTP stream and releases its iterator instead of leaving the connection dangling.
21
+ - ca290a0: `eve dev` no longer clears the terminal (including native scrollback) when a source edit refreshes the agent header — the refreshed header is committed beneath the existing transcript instead.
22
+
3
23
  ## 0.6.0-beta.17
4
24
 
5
25
  ### Minor Changes
package/README.md CHANGED
@@ -108,9 +108,11 @@ export default defineAgent({
108
108
  pnpm dlx eve@beta init my-agent
109
109
  ```
110
110
 
111
- `eve init` writes a new agent with Eve's default model. Pass `--web` to add the
111
+ `eve init` writes a new agent with Eve's default model. Pass `--channel-web-nextjs` to add the
112
112
  Web Chat application. It installs dependencies, initializes Git, and starts the
113
- development server. It does not create a Vercel project or deploy the agent.
113
+ development server. Targeting an existing npm, pnpm, or yarn project directory (`eve init .`)
114
+ adds the agent files and missing dependencies instead. It does not create a
115
+ Vercel project or deploy the agent.
114
116
 
115
117
  CLI commands:
116
118
 
@@ -263,6 +263,8 @@ Declaring `auth` adds two accessors to the tool's `ctx`:
263
263
 
264
264
  Throw `ConnectionAuthorizationRequiredError` anywhere in `execute` (directly, via `requireAuth()`, or implicitly from `getToken()`) and you trigger the consent flow, keyed by the tool's name. Calling either accessor on a tool that does not declare `auth` throws.
265
265
 
266
+ By default the sign-in affordance title-cases the tool's path-derived name — a tool file named `sfdc_lookup.ts` renders "Sign in with Sfdc_lookup". Set `displayName` on the `auth` definition to control what users see instead: `auth: { ...connect("sfdc"), displayName: "Salesforce" }`. It is presentation-only; the tool's name still keys the authorization scope, token cache, and callback URL, and a definition-level `displayName` wins over one the strategy stamps on the challenge.
267
+
266
268
  ## What to read next
267
269
 
268
270
  - [Security model](./security-model): trust boundaries and the pre-production checklist
@@ -64,7 +64,7 @@ A structured return type for task-mode runs: a subagent, schedule, or remote job
64
64
 
65
65
  ### `build`
66
66
 
67
- Hosted-build packaging, such as `externalDependencies` to keep listed packages external and trace them into the hosted output.
67
+ Build packaging controls. `externalDependencies` keeps listed packages external while Eve compiles authored modules such as tools and channels, and traces those packages into the hosted output.
68
68
 
69
69
  ## Where adjacent settings live
70
70
 
@@ -168,7 +168,9 @@ export default defineMcpClientConnection({
168
168
  });
169
169
  ```
170
170
 
171
- `getToken` runs before every tool call. `startAuthorization` and `completeAuthorization` are both-or-neither: provide one without the other and you get a definition error. The `challenge` rides along verbatim on the `authorization.required` event. Set `url` for redirect/device flows, `userCode` for a device code, and `instructions` as the call to action when there's no URL. Drop `resume` when the provider keeps flow state server-side, so nothing has to cross the step boundary.
171
+ `getToken` runs before every tool call. `startAuthorization` and `completeAuthorization` are both-or-neither: provide one without the other and you get a definition error. The `challenge` rides along verbatim on the `authorization.required` event. Set `url` for redirect/device flows, `userCode` for a device code, `instructions` as the call to action when there's no URL, and `displayName` for the human-readable provider name channels show on the sign-in affordance (e.g. "Salesforce"). Drop `resume` when the provider keeps flow state server-side, so nothing has to cross the step boundary.
172
+
173
+ `displayName` is presentation-only — the connection's path-derived name still keys the authorization scope, token cache, and callback URL. You can also set `displayName` on the `auth` definition itself (e.g. `auth: { ...connect("sfdc"), displayName: "Salesforce" }`); that definition-level value wins over one the strategy stamps on the challenge, and channels fall back to title-casing the connection name when neither is set.
172
174
 
173
175
  ### Signaling authorization state
174
176
 
@@ -14,18 +14,29 @@ You also need a model credential. Set the provider or gateway key your model str
14
14
 
15
15
  ## Create Your Agent
16
16
 
17
- Run `eve init` through `pnpm dlx` before Eve is installed locally:
17
+ Run `eve init` through your package manager before Eve is installed locally:
18
18
 
19
19
  ```bash
20
20
  pnpm dlx eve@beta init my-agent
21
21
  ```
22
22
 
23
23
  The command creates a child directory, uses Eve's default model, installs
24
- dependencies, initializes Git, and starts the development server. Pass `--web`
25
- to add the Web Chat application. Stop the server before editing the generated
26
- agent. The command does not create a Vercel project or deploy.
27
-
28
- To add Eve to an existing app instead:
24
+ dependencies, initializes Git, and starts the development server. Whichever
25
+ manager launches the command owns the new project: `pnpm dlx` scaffolds a
26
+ pnpm project, `npx` an npm one, and `yarn dlx` a yarn one (bun is not
27
+ supported yet). Pass `--channel-web-nextjs` to add the Web Chat
28
+ application; it currently requires a pnpm launch. Stop the server before
29
+ editing the generated agent. The command does not create a Vercel project or
30
+ deploy.
31
+
32
+ The target can also be an existing npm, pnpm, or yarn project directory
33
+ (`eve init .`): the project must have a `package.json`, the `agent/` files
34
+ must not exist yet, and the missing `eve`, `ai`, and `zod` dependencies are
35
+ added without touching anything else the project owns. Either way the final
36
+ handoff runs the `eve dev` binary through the project's package manager,
37
+ never the project's own `dev` script.
38
+
39
+ To add only the dependency to an existing app instead:
29
40
 
30
41
  ```bash
31
42
  pnpm add eve@beta
@@ -156,7 +167,7 @@ See [Sessions, runs & streaming](./advanced/sessions-runs-and-streaming) for the
156
167
 
157
168
  If a coding agent (Claude Code, Cursor, and the like) is doing the setup, hand it this prompt:
158
169
 
159
- <CopyPrompt text="Set up an Eve agent for the user. Eve is a filesystem-first TypeScript framework for durable agents, published as the npm package eve. Read its docs: once eve is installed they are bundled in the package at node_modules/eve/dist/docs/public; before eve is installed, read the published Introduction and Getting Started pages. If the project has no Eve app, scaffold one with `pnpm dlx eve@beta init <name>`; add `--web` only when the user wants Web Chat. The init command installs dependencies, initializes Git, and starts the dev server, so run it in a controllable process and stop it before editing. To add Eve to an existing app, run `pnpm add eve@beta`. Make sure agent/agent.ts and agent/instructions.md exist, then add a first typed tool at agent/tools/get_weather.ts using defineTool from eve/tools with a Zod inputSchema and an inline execute. Start the dev server again, then exercise the HTTP API: create a session with POST /eve/v1/session, attach to GET /eve/v1/session/:id/stream, and send a follow-up with the returned continuationToken. Verify with the project's typecheck, adapt model and provider choices to the project, and do not commit unless the user asks.">
170
+ <CopyPrompt text="Set up an Eve agent for the user. Eve is a filesystem-first TypeScript framework for durable agents, published as the npm package eve. Read its docs: once eve is installed they are bundled in the package at node_modules/eve/dist/docs/public; before eve is installed, read the published Introduction and Getting Started pages. If the project has no Eve app, scaffold one with `pnpm dlx eve@beta init <name>`; add `--channel-web-nextjs` only when the user wants Web Chat. The init command installs dependencies, initializes Git, and starts the dev server, so run it in a controllable process and stop it before editing. To add Eve to an existing app, run `pnpm add eve@beta`. Make sure agent/agent.ts and agent/instructions.md exist, then add a first typed tool at agent/tools/get_weather.ts using defineTool from eve/tools with a Zod inputSchema and an inline execute. Start the dev server again, then exercise the HTTP API: create a session with POST /eve/v1/session, attach to GET /eve/v1/session/:id/stream, and send a follow-up with the returned continuationToken. Verify with the project's typecheck, adapt model and provider choices to the project, and do not commit unless the user asks.">
160
171
  Set up an Eve agent: read the Eve docs (bundled at node_modules/eve/dist/docs/public once eve is
161
172
  installed), scaffold with `pnpm dlx eve@beta init <name>` (or `pnpm add eve@beta` in an existing app), add
162
173
  a typed tool at agent/tools/get_weather.ts, run it with `pnpm dev`, then create a session, stream
@@ -167,7 +178,7 @@ Once `eve` is a dependency, the full docs are bundled in the package, so the age
167
178
 
168
179
  - Docs: `node_modules/eve/dist/docs/public/`
169
180
 
170
- `eve init <name>` creates the base agent. Add `--web` for Web Chat, or run
181
+ `eve init <name>` creates the base agent; `eve init .` adds one to an existing npm, pnpm, or yarn project. Add `--channel-web-nextjs` for Web Chat, or run
171
182
  `eve channels add slack` later from an interactive terminal.
172
183
 
173
184
  ## What to read next
@@ -79,7 +79,6 @@ Pass a bare URL as the only argument and the UI connects to that server instead
79
79
  | `--host <host>` | Host interface to bind |
80
80
  | `--port <port>` | Port to listen on (defaults to `$PORT`, then `3000`) |
81
81
  | `-u, --url <url>` | Connect to an existing server URL instead of starting one |
82
- | `--repl` | Use the classic line-based REPL instead of the terminal UI |
83
82
  | `--no-ui` | Start the server without an interactive UI |
84
83
  | `--name <name>` | Title shown in the terminal UI (defaults to the app folder name) |
85
84
  | `--tools <mode>` | Tool-call rendering: `full` \| `collapsed` \| `auto-collapsed` \| `hidden` |
@@ -288,7 +288,7 @@ async function* openStreamIterable(input) {
288
288
  if (!isStreamDisconnectError(error)) throw error;
289
289
  disconnected = true;
290
290
  }
291
- if (!disconnected || remainingReconnectAttempts <= 0) return;
291
+ if (!disconnected || input.signal?.aborted || remainingReconnectAttempts <= 0) return;
292
292
  remainingReconnectAttempts -= 1;
293
293
  }
294
294
  }
@@ -394,6 +394,7 @@ var ClientSession = class {
394
394
  if (!isStreamDisconnectError(error)) throw error;
395
395
  }
396
396
  if (foundBoundary) break;
397
+ if (input.signal?.aborted) break;
397
398
  if (remainingReconnectAttempts <= 0) break;
398
399
  remainingReconnectAttempts -= 1;
399
400
  }
@@ -288,7 +288,7 @@ async function* openStreamIterable(input) {
288
288
  if (!isStreamDisconnectError(error)) throw error;
289
289
  disconnected = true;
290
290
  }
291
- if (!disconnected || remainingReconnectAttempts <= 0) return;
291
+ if (!disconnected || input.signal?.aborted || remainingReconnectAttempts <= 0) return;
292
292
  remainingReconnectAttempts -= 1;
293
293
  }
294
294
  }
@@ -394,6 +394,7 @@ var ClientSession = class {
394
394
  if (!isStreamDisconnectError(error)) throw error;
395
395
  }
396
396
  if (foundBoundary) break;
397
+ if (input.signal?.aborted) break;
397
398
  if (remainingReconnectAttempts <= 0) break;
398
399
  remainingReconnectAttempts -= 1;
399
400
  }
@@ -1,4 +1,6 @@
1
- import { runPnpmInstall, spawnPnpm } from "#setup/primitives/index.js";
1
+ import { detectInvokingPackageManager, detectPackageManager } from "#setup/package-manager.js";
2
+ import { runPackageManagerInstall, spawnPackageManager } from "#setup/primitives/index.js";
3
+ import { addAgentToProject } from "#setup/scaffold/create/add-to-project.js";
2
4
  import { ensureChannel, scaffoldBaseProject } from "#setup/scaffold/index.js";
3
5
  import { tryInitializeGit } from "./init-git.js";
4
6
  export interface InitCliLogger {
@@ -6,16 +8,22 @@ export interface InitCliLogger {
6
8
  log(message: string): void;
7
9
  }
8
10
  export interface InitCommandOptions {
9
- web?: boolean;
11
+ /** Add the Web Chat channel (a Next.js app). Set by `--channel-web-nextjs`. */
12
+ channelWebNextjs?: boolean;
10
13
  }
11
14
  export interface InitCommandDependencies {
15
+ addAgentToProject: typeof addAgentToProject;
16
+ detectInvokingPackageManager: typeof detectInvokingPackageManager;
17
+ detectPackageManager: typeof detectPackageManager;
12
18
  ensureChannel: typeof ensureChannel;
13
- runPnpmInstall: typeof runPnpmInstall;
19
+ runPackageManagerInstall: typeof runPackageManagerInstall;
14
20
  scaffoldBaseProject: typeof scaffoldBaseProject;
15
- spawnPnpm: typeof spawnPnpm;
21
+ spawnPackageManager: typeof spawnPackageManager;
16
22
  tryInitializeGit: typeof tryInitializeGit;
17
23
  }
18
24
  /**
19
- * Creates a new Eve agent without prompts or external provisioning.
25
+ * Creates a new Eve agent (`target` is a project name), or adds one to an
26
+ * existing project (`target` is a directory), without prompts or external
27
+ * provisioning.
20
28
  */
21
- export declare function runInitCommand(logger: InitCliLogger, parentDirectory: string, name: string, options: InitCommandOptions, dependencies?: InitCommandDependencies): Promise<void>;
29
+ export declare function runInitCommand(logger: InitCliLogger, parentDirectory: string, target: string, options: InitCommandOptions, dependencies?: InitCommandDependencies): Promise<void>;
@@ -1 +1 @@
1
- import{__toESM}from"../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{tryInitializeGit}from"./init-git.js";import{join,resolve}from"node:path";import{ensureChannel,scaffoldBaseProject}from"#setup/scaffold/index.js";import{mkdtemp,rename,rm}from"node:fs/promises";import{EVE_WORDMARK}from"#cli/banner.js";import{DEFAULT_AGENT_MODEL_ID}from"#shared/default-agent-model.js";import{SPINNER_FRAMES,SPINNER_FRAME_MS}from"#setup/cli/rail-log.js";import{pathExists}from"#setup/path-exists.js";import{parseProjectName}from"#setup/project-name.js";import{runPnpmInstall,spawnPnpm}from"#setup/primitives/index.js";var import_picocolors=__toESM(require_picocolors(),1);const defaultDependencies={ensureChannel,runPnpmInstall,scaffoldBaseProject,spawnPnpm,tryInitializeGit},EVE_INIT_PACKAGE_VERSION=`beta`;async function scaffoldProject(e,t,n,a){let o=resolve(e),u=join(o,t);if(await pathExists(u))throw Error(`Cannot create project because "${u}" already exists.`);let d=await mkdtemp(join(o,`.eve-init-`));try{let e=await a.scaffoldBaseProject({projectName:t,model:DEFAULT_AGENT_MODEL_ID,targetDirectory:d,evePackageVersion:EVE_INIT_PACKAGE_VERSION});return n.web===!0&&await a.ensureChannel({projectRoot:e,kind:`web`,configureVercelServices:!1,webPackageVersions:{evePackageVersion:EVE_INIT_PACKAGE_VERSION}}),await rename(e,u),u}finally{await rm(d,{recursive:!0,force:!0})}}function startSpinner(e,t){if(process.stdout.isTTY!==!0)return e.log(t),{stop(){}};let row=e=>`${import_picocolors.default.green(e)} ${t}`;process.stdout.write(row(SPINNER_FRAMES[0]));let n=0,r=setInterval(()=>{n+=1;let e=SPINNER_FRAMES[n%SPINNER_FRAMES.length]??SPINNER_FRAMES[0];process.stdout.write(`\r\u001B[K${row(e)}`)},SPINNER_FRAME_MS);r.unref?.();let i=!1;return{stop(){i||(i=!0,clearInterval(r),process.stdout.write(`\r\x1B[K`))}}}async function runInitCommand(e,t,n,r,i=defaultDependencies){let a=await scaffoldProject(t,parseProjectName(n),r,i);e.log(`${import_picocolors.default.green(`✓`)} Created an ${EVE_WORDMARK} agent in ${import_picocolors.default.bold(a)}`);let o=[],s=startSpinner(e,`Installing dependencies...`),c;try{c=await i.runPnpmInstall(a,{onOutput:e=>o.push(e.text)})}finally{s.stop()}if(!c){for(let t of o)e.error(t);throw Error(`Failed to install dependencies in "${a}".`)}e.log(`${import_picocolors.default.green(`✓`)} Installed dependencies`);let l=i.tryInitializeGit(a);if(l.kind===`failed`&&e.error(import_picocolors.default.yellow(`Git initialization failed: ${l.reason}`)),!await i.spawnPnpm(a,[`run`,`dev`]))throw Error(`Development server exited unsuccessfully in "${a}".`)}export{runInitCommand};
1
+ import{__toESM}from"../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{tryInitializeGit}from"./init-git.js";import{join,resolve}from"node:path";import{ensureChannel,scaffoldBaseProject}from"#setup/scaffold/index.js";import{mkdtemp,rename,rm,stat}from"node:fs/promises";import{EVE_WORDMARK}from"#cli/banner.js";import{DEFAULT_AGENT_MODEL_ID}from"#shared/default-agent-model.js";import{SPINNER_FRAMES,SPINNER_FRAME_MS}from"#setup/cli/rail-log.js";import{detectInvokingPackageManager,detectPackageManager}from"#setup/package-manager.js";import{pathExists}from"#setup/path-exists.js";import{parseProjectName}from"#setup/project-name.js";import{eveDevArguments,runPackageManagerInstall,spawnPackageManager}from"#setup/primitives/index.js";import{addAgentToProject}from"#setup/scaffold/create/add-to-project.js";var import_picocolors=__toESM(require_picocolors(),1);const defaultDependencies={addAgentToProject,detectInvokingPackageManager,detectPackageManager,ensureChannel,runPackageManagerInstall,scaffoldBaseProject,spawnPackageManager,tryInitializeGit};async function resolveTargetDirectory(e,t){let n=resolve(e,t);return(await stat(n).catch(()=>void 0))?.isDirectory()?n:void 0}async function addToExistingProject(e,t,n){if(t.channelWebNextjs===!0)throw Error("`--channel-web-nextjs` is not supported when adding an agent to an existing project. Run `eve channels add web` from the project afterwards instead.");let r=await n.detectPackageManager(e);return await n.addAgentToProject({projectRoot:e,model:DEFAULT_AGENT_MODEL_ID,packageManager:r.kind}),r.kind}function resolveScaffoldPackageManager(e){return e.detectInvokingPackageManager()??`pnpm`}const EVE_INIT_PACKAGE_VERSION=`beta`;async function scaffoldProject(e,t,n,a,o){let u=resolve(e),d=join(u,t);if(await pathExists(d))throw Error(`Cannot create project because "${d}" already exists.`);let f=await mkdtemp(join(u,`.eve-init-`));try{let e=await o.scaffoldBaseProject({projectName:t,model:DEFAULT_AGENT_MODEL_ID,packageManager:n,targetDirectory:f,evePackageVersion:EVE_INIT_PACKAGE_VERSION});return a.channelWebNextjs===!0&&await o.ensureChannel({projectRoot:e,kind:`web`,packageManager:n,configureVercelServices:!1,webPackageVersions:{evePackageVersion:EVE_INIT_PACKAGE_VERSION}}),await rename(e,d),d}finally{await rm(f,{recursive:!0,force:!0})}}function startSpinner(e,t){if(process.stdout.isTTY!==!0)return e.log(t),{stop(){}};let row=e=>`${import_picocolors.default.green(e)} ${t}`;process.stdout.write(row(SPINNER_FRAMES[0]));let n=0,r=setInterval(()=>{n+=1;let e=SPINNER_FRAMES[n%SPINNER_FRAMES.length]??SPINNER_FRAMES[0];process.stdout.write(`\r\u001B[K${row(e)}`)},SPINNER_FRAME_MS);r.unref?.();let i=!1;return{stop(){i||(i=!0,clearInterval(r),process.stdout.write(`\r\x1B[K`))}}}async function runInitCommand(e,t,n,r,i=defaultDependencies){let a=await resolveTargetDirectory(t,n),o,s;a===void 0?(o=resolveScaffoldPackageManager(i),s=await scaffoldProject(t,parseProjectName(n),o,r,i),e.log(`${import_picocolors.default.green(`✓`)} Created an ${EVE_WORDMARK} agent in ${import_picocolors.default.bold(s)}`)):(o=await addToExistingProject(a,r,i),s=a,e.log(`${import_picocolors.default.green(`✓`)} Added an ${EVE_WORDMARK} agent to ${import_picocolors.default.bold(s)}`));let c=[],l=startSpinner(e,`Installing dependencies...`),u;try{u=await i.runPackageManagerInstall(o,s,{bypassMinimumReleaseAge:!0,onOutput:e=>c.push(e.text)})}finally{l.stop()}if(!u){for(let t of c)e.error(t);throw Error(`Failed to install dependencies in "${s}".`)}if(e.log(`${import_picocolors.default.green(`✓`)} Installed dependencies`),a===void 0){let t=i.tryInitializeGit(s);t.kind===`failed`&&e.error(import_picocolors.default.yellow(`Git initialization failed: ${t.reason}`))}if(e.log(import_picocolors.default.dim(`$ eve dev`)),!await i.spawnPackageManager(o,s,eveDevArguments(o)))throw Error(`Development server exited unsuccessfully in "${s}".`)}export{runInitCommand};
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import type { Theme } from "./theme.js";
13
13
  export type ToolStatus = "running" | "done" | "error" | "denied" | "approval";
14
- export type BlockKind = "user" | "assistant" | "reasoning" | "tool" | "error" | "notice" | "warning" | "result" | "flow" | "command" | "question" | "subagent" | "subagent-step" | "subagent-tool" | "connection-auth" | "log";
14
+ export type BlockKind = "user" | "assistant" | "reasoning" | "tool" | "error" | "notice" | "warning" | "result" | "flow" | "command" | "question" | "subagent" | "subagent-step" | "subagent-tool" | "connection-auth" | "log" | "agent-header";
15
15
  /**
16
16
  * One renderable transcript unit. Fields are interpreted per `kind`; unset
17
17
  * fields are simply omitted from the rendered output.
@@ -1,4 +1,5 @@
1
- import{formatValuePretty,truncate}from"./tool-format.js";import{sliceVisible,visibleLength,wrapVisibleLine}from"./terminal-text.js";import{renderMarkdown}from"./markdown.js";import{isPromptControlCommand}from"./prompt-commands.js";function renderBlockLines(e,t,n,i){let a=nestingPrefix(e.depth??0,n);return renderBody(e,Math.max(8,t-visibleLength(a)),n,i).map(e=>`${a}${e}`)}function nestingPrefix(e,t){return e<=0?``:`${t.colors.orange(t.glyph.rule)} `.repeat(e)}function renderBody(e,t,n,r){switch(e.kind){case`user`:return renderUser(e,t,n);case`assistant`:case`subagent-step`:return renderProse(e,t,n);case`reasoning`:return renderReasoning(e,t,n);case`tool`:case`subagent-tool`:return renderTool(e,t,n,r);case`error`:return renderError(e,t,n);case`notice`:return renderNotice(e,t,n);case`warning`:return renderWarning(e,t,n);case`result`:return renderResult(e,t,n);case`flow`:return renderFlow(e,t,n);case`command`:return renderCommand(e,n);case`question`:case`connection-auth`:return renderPreformatted(e,t,n);case`log`:return renderLog(e,t,n,r);case`subagent`:return renderSubagentHeader(e,t,n)}}function renderUser(e,t,n){let r=n.colors.cyan(n.glyph.user);return wrap(e.body??``,t-2).map(e=>`${r} ${e}`)}function renderProse(e,t,n){let r=[],o=e.kind===`subagent-step`,s=o?``:`${n.colors.bold(n.colors.white(n.glyph.brand))} `,c=o?``:` `;e.reasoning&&e.reasoning.trim().length>0&&r.push(...renderReasoningLines(e.reasoning,t,n));let l=(e.body??``).trim();return l.length===0&&r.length===0?[`${s}${n.colors.dim(`thinking${n.glyph.ellipsis}`)}`]:(l.length>0&&renderMarkdown(l).split(`
1
+ import{formatValuePretty,truncate}from"./tool-format.js";import{sliceVisible,visibleLength,wrapVisibleLine}from"./terminal-text.js";import{renderMarkdown}from"./markdown.js";import{isPromptControlCommand}from"./prompt-commands.js";function renderBlockLines(e,t,n,i){let a=nestingPrefix(e.depth??0,n);return renderBody(e,Math.max(8,t-visibleLength(a)),n,i).map(e=>`${a}${e}`)}function nestingPrefix(e,t){return e<=0?``:`${t.colors.orange(t.glyph.rule)} `.repeat(e)}function renderBody(e,t,n,r){switch(e.kind){case`user`:return renderUser(e,t,n);case`assistant`:case`subagent-step`:return renderProse(e,t,n);case`reasoning`:return renderReasoning(e,t,n);case`tool`:case`subagent-tool`:return renderTool(e,t,n,r);case`error`:return renderError(e,t,n);case`notice`:return renderNotice(e,t,n);case`warning`:return renderWarning(e,t,n);case`result`:return renderResult(e,t,n);case`flow`:return renderFlow(e,t,n);case`command`:return renderCommand(e,n);case`question`:case`connection-auth`:return renderPreformatted(e,t,n);case`log`:return renderLog(e,t,n,r);case`subagent`:return renderSubagentHeader(e,t,n);case`agent-header`:return(e.body??``).split(`
2
+ `)}}function renderUser(e,t,n){let r=n.colors.cyan(n.glyph.user);return wrap(e.body??``,t-2).map(e=>`${r} ${e}`)}function renderProse(e,t,n){let r=[],o=e.kind===`subagent-step`,s=o?``:`${n.colors.bold(n.colors.white(n.glyph.brand))} `,c=o?``:` `;e.reasoning&&e.reasoning.trim().length>0&&r.push(...renderReasoningLines(e.reasoning,t,n));let l=(e.body??``).trim();return l.length===0&&r.length===0?[`${s}${n.colors.dim(`thinking${n.glyph.ellipsis}`)}`]:(l.length>0&&renderMarkdown(l).split(`
2
3
  `).flatMap(e=>wrapVisibleLine(e,t-c.length)).forEach((e,t)=>{t===0&&!o&&r.length===0?r.push(`${s}${e}`):r.push(`${c}${e}`)}),r.length>0?r:[`${s}`])}function renderReasoning(e,t,n){return e.collapsed?[`${n.colors.gray(n.glyph.reasoning)} ${n.colors.dim(`thinking`)}`]:renderReasoningLines(e.body??``,t,n,n.glyph.reasoning)}function renderReasoningLines(e,t,n,r){let i=r?2:0,a=wrap(e.trim(),t-i);return a.length===0?[]:a.map((e,t)=>`${r?t===0?`${n.colors.gray(r)} `:` `:``}${n.colors.dim(n.colors.italic(e))}`)}function renderTool(e,n,r,i){let{icon:a,accent:o}=toolGlyph(e.status??`running`,r,i),s=e.title??`tool`,c=n-2,l=truncatePlain(s,c),u=`${a} ${r.colors.bold(l)}`,d=c-l.length-2,f=e.subtitle??``;f.length>0&&d>=6&&(u+=` ${r.colors.gray(truncate(f,d))}`);let p=[u];return e.expanded?p.push(...renderToolExpanded(e,n,r)):e.status===`done`&&e.result&&e.result.length>0?p.push(resultLine(r.glyph.arrow,e.result,n,r,o)):e.status===`error`&&e.result?p.push(resultLine(r.glyph.arrow,e.result,n,r,r.colors.red)):e.status===`denied`&&p.push(resultLine(r.glyph.arrow,`denied`,n,r,r.colors.yellow)),p}function renderToolExpanded(t,n,r){let i=[],push=(t,a,o)=>{if(a!==void 0){i.push(` ${r.colors.dim(t)}`);for(let t of wrap(formatValuePretty(a),n-4))i.push(` ${o(t)}`)}};return push(`input`,t.toolInput,r.colors.gray),t.status===`error`&&t.result?push(`error`,t.result,r.colors.red):push(`output`,t.toolOutput,r.colors.gray),i}function resultLine(e,n,r,i,a){let o=r-4;return` ${i.colors.dim(e)} ${a(truncate(n,o))}`}function toolGlyph(e,t,n){switch(e){case`done`:return{icon:t.colors.green(t.glyph.success),accent:t.colors.gray};case`error`:return{icon:t.colors.red(t.glyph.error),accent:t.colors.red};case`denied`:return{icon:t.colors.yellow(t.glyph.warning),accent:t.colors.yellow};case`approval`:return{icon:t.colors.yellow(t.glyph.question),accent:t.colors.yellow};default:return{icon:t.colors.yellow(n.spinner),accent:t.colors.gray}}}function renderError(e,t,n){let r=n.colors.red(n.colors.bold(n.glyph.error)),i=e.title??`Error`,a=[`${r} ${n.colors.red(n.colors.bold(i))}`];for(let r of wrap(e.body??``,t-2))a.push(` ${colorizeError(r,n)}`);return a.push(...renderErrorDetail(e.detail,t,n)),a}function renderErrorDetail(e,t,n){if(e===void 0||e.trim().length===0)return[];let r=e.split(`
3
4
  `),i=r.slice(0,12),a=i.map(e=>` ${n.colors.dim(truncatePlain(e,Math.max(1,t-2)))}`),o=r.length-i.length;return o>0&&a.push(` ${n.colors.dim(`${n.glyph.ellipsis} +${o} more line${o===1?``:`s`}`)}`),a}const URL_PATTERN=/(https?:\/\/\S+)/u;function colorizeError(e,t){return URL_PATTERN.test(e)?e.split(URL_PATTERN).map((e,n)=>n%2==1?t.colors.cyan(e):t.colors.red(e)).join(``):t.colors.red(e)}function renderNotice(e,t,n){let r=n.colors.dim(n.glyph.dot),i=wrap(e.body??``,t-2);return i.length===0?[r]:i.map(e=>`${r} ${n.colors.dim(e)}`)}function renderWarning(e,t,n){let r=n.colors.yellow(n.glyph.warning);return wrap(e.body??``,t-2).map((e,t)=>`${t===0?r:` `} ${paintCommands(e,n)}`)}function paintCommands(e,t){return e.replace(/\/[a-z-]+/g,e=>isPromptControlCommand(e)?t.colors.blue(e):e)}function renderCommand(e,t){let n=t.colors;return[`${n.cyan(t.glyph.user)} ${n.blue(e.body??``)}`]}function renderFlow(e,t,n){let r=n.colors,i=e.title??`info`,a=i===`success`?r.green(n.glyph.success):i===`warning`?r.yellow(n.glyph.warning):i===`error`?r.red(n.glyph.error):r.dim(n.glyph.dot),o=wrap(e.body??``,t-2),paint=e=>i===`info`?r.dim(e):e;return o.map((e,t)=>`${t===0?a:` `} ${paint(e)}`)}function renderResult(e,t,n){let r=n.colors.dim(n.glyph.elbow),i=wrap(e.body??``,t-7);return i.length===0?[` ${r}`]:i.map((e,t)=>t===0?` ${r} ${n.colors.dim(e)}`:` ${n.colors.dim(e)}`)}function renderPreformatted(e,t,n){let r=e.kind===`connection-auth`?n.colors.yellow(n.glyph.connection):n.colors.yellow(n.colors.bold(n.glyph.question)),a=e.title??``,o=[`${r} ${n.colors.bold(a)}`];for(let n of(e.body??``).split(`
4
5
  `))for(let e of wrapVisibleLine(n,t-2))o.push(` ${e}`);return o}function renderLog(e,t,n,a){let o=e.title===`stderr`,s=o?n.colors.red:n.colors.gray,c=n.colors.dim(n.glyph.rule),l=o?`stderr`:`stdout`,u=n.colors.dim(`${l} ${n.glyph.dot} `),d=visibleLength(u),f=` `.repeat(d),p=a.previous?.kind===`log`&&a.previous.title===e.title,m=(e.body??``).split(`
@@ -1 +1 @@
1
- import{formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{failureKey,formatFailureDetail,formatFailureMessage,formatGatewayAuthFailureNotice,isAbortLikeError,isGatewayAuthFailure,isInterruptedError}from"./errors.js";import{BOOT_DETECTIONS,detectSetupIssues,formatSetupIssuesLine}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{toErrorMessage}from"#shared/errors.js";import{createDevelopmentRuntimeArtifactSessionRefresher}from"#services/dev-client.js";import{isCurrentTurnBoundaryEvent}from"#client/index.js";var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_=new Map;#v=new Map;#y=new Map;#b=new Map;#x=new Set;#S=!1;constructor(e){this.#e=e.session,e.client!==void 0&&(this.#t=e.client),this.#n=createRenderer(e),this.#r=e.name??`Eve`,this.#i=e.tools??`full`,this.#a=e.reasoning??`full`,this.#o=e.subagents??`full`,this.#s=e.connectionAuth??`full`,this.#c=e.assistantResponseStats??`tokensPerSecond`,this.#l=e.contextSize,this.#u=e.formatTransportError??toErrorMessage,e.appRoot!==void 0&&(this.#p=e.appRoot),e.promptCommandHandler!==void 0&&(this.#m=e.promptCommandHandler),this.#h=e.bootDetections??BOOT_DETECTIONS,e.serverUrl!==void 0&&(this.#f=e.serverUrl,this.#d=createDevelopmentRuntimeArtifactSessionRefresher({serverUrl:e.serverUrl}))}async#C(){let e=this.#f;if(e===void 0){await this.#D(void 0);return}let t;try{t=await this.#t?.info()}catch{t=void 0}this.#g=t;let n={name:this.#r,serverUrl:e};t!==void 0&&(n.info=t),this.#p!==void 0&&(n.setupCommands=!0),this.#n.renderAgentHeader?.(n),await this.#D(t)}async run(){let n=this.#r,r,i,a=!1,o=!1;for(await this.#C();;){if(!o){if(r==null){if(!this.#n.readPrompt){if(a)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}try{r=await this.#T({title:n})}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let s=parsePromptCommand(r);if(s?.type===`exit`){this.#n.shutdown?.();return}if(s?.type===`new`){this.#w(),i=void 0,o=!1,r=void 0,this.#n.reset?.();continue}if(s?.type===`help`){this.#O(formatPromptCommandHelp()),i=void 0,o=!1,r=void 0;continue}if(s?.type===`extension`){try{let e=this.#m===void 0?`/${s.name} is not available in this session.`:await this.#m.handle(s,{renderer:this.#n,title:n});e!==void 0&&this.#O(e)}catch(e){if(isInterruptedError(e))return;throw e}i=void 0,r=void 0,o=!1;continue}a=!0}let s=await this.#E({prompt:o?void 0:r,inputResponses:i});try{await this.#n.renderStream(s,{title:n,submittedPrompt:r,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let e=s.turnState?.pendingApprovals??[],t=s.turnState?.pendingQuestions??[];if(e.length>0||t.length>0){let a=[];if(e.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let t of e){let e=await this.#n.readToolApproval(t,{title:n});a.push({requestId:t.approvalId,optionId:e.approved?`approve`:`deny`}),this.#_.delete(t.approvalId)}}if(t.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let e of t){let t=toAgentTUIInputQuestion(e),r=await this.#n.readInputQuestion(t,{title:n});if(r===void 0)continue;let i={requestId:e.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),a.push(i),this.#_.delete(e.requestId)}}o=!0,i=a,r=void 0;continue}s.turnState&&s.turnState.boundaryEvent===void 0&&(this.#S=!0)}catch(e){if(isInterruptedError(e))return;throw e}o=!1,i=void 0,r=void 0,this.#S&&(this.#S=!1,this.#w(),this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`))}}#w(){for(let e of this.#y.values())e.abort();this.#y.clear(),this.#v.clear(),this.#_.clear(),this.#b.clear(),this.#x.clear(),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}async#T(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#t,r=this.#d;if(n===void 0||r===void 0)return await t;let i=!1,a=!1,o,refresh=async()=>{if(!(i||a)){a=!0;try{this.#e=await r.refreshIdle({createSession:()=>n.session(),onRuntimeArtifactsChanged:()=>this.#k(),session:this.#e})}finally{a=!1}}},startRefresh=()=>{if(i||a)return;let e=refresh().finally(()=>{o===e&&(o=void 0)});o=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await t}finally{i=!0,clearInterval(s),await o}}async#E(e){let t={};e.prompt!==void 0&&(t.message=e.prompt),e.inputResponses!==void 0&&e.inputResponses.length>0&&(t.inputResponses=e.inputResponses);let n;try{let e=this.#t;e!==void 0&&this.#d!==void 0&&(this.#e=await this.#d.refresh({createSession:()=>e.session(),inputResponses:t.inputResponses,message:t.message,onRuntimeArtifactsChanged:()=>this.#k(),session:this.#e})),n=await this.#e.send(t)}catch(e){if(isInterruptedError(e))throw e;return this.#S=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}let r=createTurnState();return{events:eveEventsToTUIStream({events:n,pendingInputRequests:this.#_,subagentRuns:this.#v,turnState:r,onSubagentCalled:e=>this.#N(e),onSubagentCompleted:e=>this.#F(e),onConnectionAuthRequired:e=>this.#A(e),onConnectionAuthCompleted:e=>this.#j(e),onTerminalFailure:()=>{this.#S=!0},failureOverride:this.#p===void 0?void 0:e=>isGatewayAuthFailure(e)?formatGatewayAuthFailureNotice(e):void 0}),turnState:r}}async#D(e){if(this.#p===void 0||this.#n.renderSetupWarning===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e);let n=await detectSetupIssues(t,this.#h);n.length!==0&&this.#n.renderSetupWarning(formatSetupIssuesLine(n))}#O(e){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}async#k(){let e=this.#g,t;try{t=await this.#t?.info()}catch{t=void 0}t!==void 0&&(this.#g=t,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:t,name:this.#r,serverUrl:this.#f,setupCommands:this.#p!==void 0})),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#A(e){let t={name:e.data.name,description:e.data.description,state:`required`};e.data.authorization!==void 0&&(t.challenge=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),this.#b.set(e.data.name,t),this.#M(t)}#j(e){let t=this.#b.get(e.data.name)??{name:e.data.name,description:``,state:e.data.outcome};t.state=e.data.outcome,e.data.reason!==void 0&&(t.reason=e.data.reason),this.#b.set(e.data.name,t),this.#x.delete(e.data.name),this.#M(t),this.#n.setConnectionAuthPendingCount?.(this.#x.size)}#M(e){let t={name:e.name,description:e.description,state:e.state};e.challenge!==void 0&&(t.challenge=e.challenge),e.reason!==void 0&&(t.reason=e.reason),this.#n.upsertConnectionAuth?.(t)}#N(e){let t=e.data.callId;if(this.#y.has(t))return;let n=this.#t;if(!n)return;let r=new AbortController;this.#y.set(t,r),(async()=>{try{let i=n.session({sessionId:e.data.childSessionId,streamIndex:0}).stream({signal:r.signal});for await(let e of i)if(r.signal.aborted||(this.#I(t,e),isCurrentTurnBoundaryEvent(e)))break}catch(e){if(!isAbortLikeError(e)){let n=toErrorMessage(e),r=this.#v.get(t);if(r){let{key:e,step:i}=openCurrentSubagentSection(r);i.message=i.message?`${i.message}\n\nstream error: ${n}`:`stream error: ${n}`,i.finalized=!0,r.currentSectionKey=null,this.#n.upsertSubagentStep?.({callId:t,subagentName:r.name,sectionKey:e,reasoning:i.reasoning,message:i.message,finalized:!0})}}}finally{this.#y.delete(t)}})()}#P(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={"approval-requested":0,executing:1,done:2,failed:2};e[n.status]>e[r.status]&&(r.status=n.status),r.input=n.input}else t.tools.set(n.childCallId,i);this.#n.markChildToolCallId?.(n.childCallId),this.#n.upsertSubagentTool?.({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#F(e){let t=this.#v.get(e);if(t){for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#n.upsertSubagentStep?.({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null}}#I(e,t){let n=this.#v.get(e);if(!n)return;let r=this.#n,emit=(t,i)=>{r.upsertSubagentStep?.({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent();break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#P(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#P(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;t.data.status===`failed`?(a.status=`failed`,a.errorText=formatActionResultError(t)):(a.status=`done`,a.output=i.output);let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r.upsertSubagentTool?.(o);break}default:break}}};function createRenderer(e){return e.renderer?e.renderer:new TerminalRenderer({tools:e.tools,reasoning:e.reasoning,subagents:e.subagents,connectionAuth:e.connectionAuth,assistantResponseStats:e.assistantResponseStats,contextSize:e.contextSize,logs:e.logs,input:e.userInput,output:e.screen})}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id,r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,subagentRuns:r,turnState:i,onSubagentCalled:a,onSubagentCompleted:o,onConnectionAuthRequired:s,onConnectionAuthCompleted:c,onTerminalFailure:l,failureOverride:u}=e,d=new Map,f=new Map,p=0,m=new Set,h=new Set,g=new Set,_=new Set,v=!1,y=!1,b;for await(let e of t)if(!(y&&isPostTurnVisibleEvent(e)))switch(e.type){case`session.started`:case`turn.started`:case`message.received`:break;case`step.started`:p+=1,yield{type:`step-start`};break;case`step.completed`:{let t=e;b=t.data.usage,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`step-finish`,usage:t.data.usage};break}case`message.appended`:{let t=e,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(d,n),i=t.data.messageSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`message.completed`:{let t=textPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(d,t),r=e.data.message;if(n.completed){if(r===null||r===n.text||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p,yield{type:`assistant-complete`,id:partGenerationId(t,n.generation),text:r};break}let i=partGenerationId(t,n.generation);if(r!==null){if(n.text.length===0)n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let e=r.slice(n.text.length);e.length>0&&(yield{type:`assistant-delta`,id:i,delta:e}),n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i}}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let t=e,n=reasoningPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(f,n),i=t.data.reasoningSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`reasoning-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`reasoning.completed`:{let t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(f,t),r=e.data.reasoning;if(n.completed){if(r.length===0||r===n.text||n.text.startsWith(r)||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}let i=partGenerationId(t,n.generation);if(n.text.length===0&&r.length>0)n.text=r,yield{type:`reasoning-delta`,id:i,delta:r};else if(r.length>0&&!r.startsWith(n.text))break;n.completed=!0,n.completedEpoch=p,yield{type:`reasoning-complete`,id:i};break}case`actions.requested`:{let t=e.data,n=t.actions.filter(e=>e.kind===`tool-call`);if(n.length===0)break;let r=toolBatchKey(`actions.requested`,t.turnId,t.stepIndex,n);if(g.has(r)){for(let e of n)m.has(e.callId)||h.add(e.callId);break}g.add(r);for(let e of n)m.has(e.callId)||(m.add(e.callId),yield{type:`tool-call`,toolCallId:e.callId,toolName:e.toolName,input:e.input});break}case`input.requested`:{let t=e.data,r=t.requests.filter(e=>e.action.kind===`tool-call`);if(r.length===0)break;let a=inputRequestBatchKey(t.turnId,t.stepIndex,r);if(g.has(a)){for(let e of r)m.has(e.action.callId)||h.add(e.action.callId);break}g.add(a);for(let e of r){let t=e.action.callId;if(m.has(t)||(m.add(t),yield{type:`tool-call`,toolCallId:t,toolName:e.action.toolName,input:e.action.input}),n.set(e.requestId,e),isQuestionRequest(e)){upsertPendingQuestion(i,e);continue}upsertPendingApproval(i,e),yield{type:`tool-approval-request`,approvalId:e.requestId,toolCallId:t}}break}case`action.result`:{let t=e;if(t.data.result.kind!==`tool-result`)break;let n=t.data.result.callId;if(h.has(n)||!m.has(n))break;t.data.status===`failed`?yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)}:yield{type:`tool-result`,toolCallId:n,output:t.data.result.output};break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,_,u);t&&(yield t);break}case`session.failed`:{i.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,_,u);t&&(yield t),i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b},v=!0;return}case`session.waiting`:case`session.completed`:i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b},v=!0;return;case`turn.completed`:y=!0,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p);break;case`subagent.called`:{let t=e;if(!r.has(t.data.callId))r.set(t.data.callId,{name:t.data.name,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map});else{let e=r.get(t.data.callId);e&&(e.name=t.data.name)}a?.(t);break}case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:o?.(e.data.callId);break;case`authorization.required`:s?.(e);break;case`authorization.completed`:c?.(e);break;default:break}v||(yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{pendingApprovals:[],pendingQuestions:[],sawSessionFailure:!1}}function upsertPendingApproval(e,t){let n=toAgentTUIToolApprovalRequest(t),r=e.pendingApprovals.findIndex(e=>e.approvalId===n.approvalId);r===-1?e.pendingApprovals.push(n):e.pendingApprovals[r]=n}function toAgentTUIToolApprovalRequest(e){return{approvalId:e.requestId,toolCallId:e.action.callId,toolName:e.action.toolName,input:e.action.input}}function upsertPendingQuestion(e,t){let n=e.pendingQuestions.findIndex(e=>e.requestId===t.requestId);n===-1?e.pendingQuestions.push(t):e.pendingQuestions[n]=t}function textPartId(e,t){return`text:${e}:${t}`}function reasoningPartId(e,t){return`reasoning:${e}:${t}`}function partStateFor(e,t){let n=e.get(t);return n===void 0&&(n={generation:0,text:``,completed:!1,completedEpoch:0},e.set(t,n)),n}function partGenerationId(e,t){return t===0?e:`${e}#${t}`}function*closeOpenParts(e,t,n){for(let[r,i]of e)i.completed||i.text.length===0||(i.completed=!0,i.completedEpoch=n,yield{type:t,id:partGenerationId(r,i.generation)})}function isPostTurnVisibleEvent(e){switch(e.type){case`action.result`:case`actions.requested`:case`authorization.completed`:case`authorization.required`:case`input.requested`:case`message.appended`:case`message.completed`:case`reasoning.appended`:case`reasoning.completed`:case`result.completed`:case`step.completed`:case`step.failed`:case`step.started`:case`subagent.called`:case`subagent.completed`:case`subagent.event`:case`subagent.started`:case`turn.completed`:case`turn.failed`:return!0;default:return!1}}function toolBatchKey(e,t,n,r){return`${e}:${t}:${String(n)}:${stableStringify(r.map(e=>({input:e.input,toolName:e.toolName})))}`}function inputRequestBatchKey(e,t,n){return toolBatchKey(`input.requested`,e,t,n.map(e=>({input:e.action.input,toolName:e.action.toolName})))}function stableStringify(e){return JSON.stringify(toStableJson(e))??`undefined`}function toStableJson(e,t=new WeakSet){if(typeof e!=`object`||!e)return e;if(t.has(e))return`[Circular]`;if(t.add(e),Array.isArray(e))return e.map(e=>toStableJson(e,t));let n=e,r={};for(let e of Object.keys(n).sort())r[e]=toStableJson(n[e],t);return r}function formatActionResultError(e){if(e.data.error?.message)return e.data.error.message;let t=e.data.result.output;if(typeof t==`string`)return t;try{return JSON.stringify(t)}catch{return`Tool execution failed.`}}function toFailureEvent(e,t,a){let o=failureKey(e);if(t.has(o))return;t.add(o);let s=a?.(e),c={type:`error`,errorText:s??formatFailureMessage(e)};if(s!==void 0)return c;let l=formatFailureDetail(e);return l!==void 0&&(c.detail=l),c}function isQuestionRequest(e){return e.display===`select`||e.display===`text`?!0:e.display===`confirmation`?!1:e.options!==void 0&&e.options.length>0}function toAgentTUIInputQuestion(e){let t=e.display===`text`?`text`:e.display===`select`||e.options!==void 0&&e.options.length>0?`select`:`text`,n={requestId:e.requestId,prompt:e.prompt,display:t};return e.options!==void 0&&(n.options=e.options.map(e=>{let t={id:e.id,label:e.label};return e.description!==void 0&&(t.description=e.description),e.style!==void 0&&(t.style=e.style),t})),e.allowFreeform!==void 0&&(n.allowFreeform=e.allowFreeform),n}function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{EveTUIRunner,parsePromptCommand};
1
+ import{formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{failureKey,formatFailureDetail,formatFailureMessage,formatGatewayAuthFailureNotice,isAbortLikeError,isGatewayAuthFailure,isInterruptedError}from"./errors.js";import{BOOT_DETECTIONS,detectSetupIssues,formatSetupIssuesLine}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{isCurrentTurnBoundaryEvent}from"#client/index.js";import{createDevelopmentRuntimeArtifactSessionRefresher}from"#services/dev-client.js";import{toErrorMessage}from"#shared/errors.js";var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_=new Map;#v=new Map;#y=new Map;#b=new Map;#x=new Set;#S=!1;constructor(e){this.#e=e.session,e.client!==void 0&&(this.#t=e.client),this.#n=createRenderer(e),this.#r=e.name??`Eve`,this.#i=e.tools??`full`,this.#a=e.reasoning??`full`,this.#o=e.subagents??`full`,this.#s=e.connectionAuth??`full`,this.#c=e.assistantResponseStats??`tokensPerSecond`,this.#l=e.contextSize,this.#u=e.formatTransportError??toErrorMessage,e.appRoot!==void 0&&(this.#p=e.appRoot),e.promptCommandHandler!==void 0&&(this.#m=e.promptCommandHandler),this.#h=e.bootDetections??BOOT_DETECTIONS,e.serverUrl!==void 0&&(this.#f=e.serverUrl,this.#d=createDevelopmentRuntimeArtifactSessionRefresher({serverUrl:e.serverUrl}))}async#C(){let e=this.#f;if(e===void 0){await this.#D(void 0);return}let t;try{t=await this.#t?.info()}catch{t=void 0}this.#g=t;let n={name:this.#r,serverUrl:e};t!==void 0&&(n.info=t),this.#p!==void 0&&(n.setupCommands=!0),this.#n.renderAgentHeader?.(n),await this.#D(t)}async run(){let n=this.#r,r,i,a=!1,o=!1;for(await this.#C();;){if(!o){if(r==null){if(!this.#n.readPrompt){if(a)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}try{r=await this.#T({title:n})}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let s=parsePromptCommand(r);if(s?.type===`exit`){this.#n.shutdown?.();return}if(s?.type===`new`){this.#w(),i=void 0,o=!1,r=void 0,this.#n.reset?.();continue}if(s?.type===`help`){this.#O(formatPromptCommandHelp()),i=void 0,o=!1,r=void 0;continue}if(s?.type===`extension`){try{let e=this.#m===void 0?`/${s.name} is not available in this session.`:await this.#m.handle(s,{renderer:this.#n,title:n});e!==void 0&&this.#O(e)}catch(e){if(isInterruptedError(e))return;throw e}i=void 0,r=void 0,o=!1;continue}a=!0}let s=await this.#E({prompt:o?void 0:r,inputResponses:i});try{await this.#n.renderStream(s,{title:n,submittedPrompt:r,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let e=s.turnState?.pendingApprovals??[],t=s.turnState?.pendingQuestions??[];if(e.length>0||t.length>0){let a=[];if(e.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let t of e){let e=await this.#n.readToolApproval(t,{title:n});a.push({requestId:t.approvalId,optionId:e.approved?`approve`:`deny`}),this.#_.delete(t.approvalId)}}if(t.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let e of t){let t=toAgentTUIInputQuestion(e),r=await this.#n.readInputQuestion(t,{title:n});if(r===void 0)continue;let i={requestId:e.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),a.push(i),this.#_.delete(e.requestId)}}o=!0,i=a,r=void 0;continue}s.turnState&&s.turnState.boundaryEvent===void 0&&(this.#S=!0)}catch(e){if(isInterruptedError(e))return;throw e}o=!1,i=void 0,r=void 0,this.#S&&(this.#S=!1,this.#w(),this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`))}}#w(){for(let e of this.#y.values())e.abort();this.#y.clear(),this.#v.clear(),this.#_.clear(),this.#b.clear(),this.#x.clear(),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}async#T(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#t,r=this.#d;if(n===void 0||r===void 0)return await t;let i=!1,a=!1,o,refresh=async()=>{if(!(i||a)){a=!0;try{this.#e=await r.refreshIdle({createSession:()=>n.session(),onRuntimeArtifactsChanged:()=>this.#k(),session:this.#e})}finally{a=!1}}},startRefresh=()=>{if(i||a)return;let e=refresh().finally(()=>{o===e&&(o=void 0)});o=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await t}finally{i=!0,clearInterval(s),await o}}async#E(e){let t=new AbortController,n={signal:t.signal};e.prompt!==void 0&&(n.message=e.prompt),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses);let r;try{let e=this.#t;e!==void 0&&this.#d!==void 0&&(this.#e=await this.#d.refresh({createSession:()=>e.session(),inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#k(),session:this.#e})),r=await this.#e.send(n)}catch(e){if(isInterruptedError(e))throw e;return this.#S=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}let i=createTurnState();return{abort:()=>t.abort(),events:eveEventsToTUIStream({events:r,pendingInputRequests:this.#_,subagentRuns:this.#v,turnState:i,onSubagentCalled:e=>this.#N(e),onSubagentCompleted:e=>this.#F(e),onConnectionAuthRequired:e=>this.#A(e),onConnectionAuthCompleted:e=>this.#j(e),onTerminalFailure:()=>{this.#S=!0},failureOverride:this.#p===void 0?void 0:e=>isGatewayAuthFailure(e)?formatGatewayAuthFailureNotice(e):void 0}),turnState:i}}async#D(e){if(this.#p===void 0||this.#n.renderSetupWarning===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e);let n=await detectSetupIssues(t,this.#h);n.length!==0&&this.#n.renderSetupWarning(formatSetupIssuesLine(n))}#O(e){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e);return}this.#n.renderNotice?.(e)}async#k(){let e=this.#g,t;try{t=await this.#t?.info()}catch{t=void 0}t!==void 0&&(this.#g=t,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:t,name:this.#r,serverUrl:this.#f,setupCommands:this.#p!==void 0})),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#A(e){let t={name:e.data.name,description:e.data.description,state:`required`};e.data.authorization!==void 0&&(t.challenge=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),this.#b.set(e.data.name,t),this.#M(t)}#j(e){let t=this.#b.get(e.data.name)??{name:e.data.name,description:``,state:e.data.outcome};t.state=e.data.outcome,e.data.reason!==void 0&&(t.reason=e.data.reason),this.#b.set(e.data.name,t),this.#x.delete(e.data.name),this.#M(t),this.#n.setConnectionAuthPendingCount?.(this.#x.size)}#M(e){let t={name:e.name,description:e.description,state:e.state};e.challenge!==void 0&&(t.challenge=e.challenge),e.reason!==void 0&&(t.reason=e.reason),this.#n.upsertConnectionAuth?.(t)}#N(e){let t=e.data.callId;if(this.#y.has(t))return;let n=this.#t;if(!n)return;let r=new AbortController;this.#y.set(t,r),(async()=>{try{let i=n.session({sessionId:e.data.childSessionId,streamIndex:0}).stream({signal:r.signal});for await(let e of i)if(r.signal.aborted||(this.#I(t,e),isCurrentTurnBoundaryEvent(e)))break}catch(e){if(!isAbortLikeError(e)){let n=toErrorMessage(e),r=this.#v.get(t);if(r){let{key:e,step:i}=openCurrentSubagentSection(r);i.message=i.message?`${i.message}\n\nstream error: ${n}`:`stream error: ${n}`,i.finalized=!0,r.currentSectionKey=null,this.#n.upsertSubagentStep?.({callId:t,subagentName:r.name,sectionKey:e,reasoning:i.reasoning,message:i.message,finalized:!0})}}}finally{this.#y.delete(t)}})()}#P(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={"approval-requested":0,executing:1,done:2,failed:2};e[n.status]>e[r.status]&&(r.status=n.status),r.input=n.input}else t.tools.set(n.childCallId,i);this.#n.markChildToolCallId?.(n.childCallId),this.#n.upsertSubagentTool?.({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#F(e){let t=this.#v.get(e);if(t){for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#n.upsertSubagentStep?.({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null}}#I(e,t){let n=this.#v.get(e);if(!n)return;let r=this.#n,emit=(t,i)=>{r.upsertSubagentStep?.({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent();break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#P(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#P(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;t.data.status===`failed`?(a.status=`failed`,a.errorText=formatActionResultError(t)):(a.status=`done`,a.output=i.output);let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r.upsertSubagentTool?.(o);break}default:break}}};function createRenderer(e){return e.renderer?e.renderer:new TerminalRenderer({tools:e.tools,reasoning:e.reasoning,subagents:e.subagents,connectionAuth:e.connectionAuth,assistantResponseStats:e.assistantResponseStats,contextSize:e.contextSize,logs:e.logs,input:e.userInput,output:e.screen})}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id,r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,subagentRuns:r,turnState:i,onSubagentCalled:a,onSubagentCompleted:o,onConnectionAuthRequired:s,onConnectionAuthCompleted:c,onTerminalFailure:l,failureOverride:u}=e,d=new Map,f=new Map,p=0,m=new Set,h=new Set,g=new Set,_=new Set,v=!1,y=!1,b;for await(let e of t)if(!(y&&isPostTurnVisibleEvent(e)))switch(e.type){case`session.started`:case`turn.started`:case`message.received`:break;case`step.started`:p+=1,yield{type:`step-start`};break;case`step.completed`:{let t=e;b=t.data.usage,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`step-finish`,usage:t.data.usage};break}case`message.appended`:{let t=e,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(d,n),i=t.data.messageSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`message.completed`:{let t=textPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(d,t),r=e.data.message;if(n.completed){if(r===null||r===n.text||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p,yield{type:`assistant-complete`,id:partGenerationId(t,n.generation),text:r};break}let i=partGenerationId(t,n.generation);if(r!==null){if(n.text.length===0)n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let e=r.slice(n.text.length);e.length>0&&(yield{type:`assistant-delta`,id:i,delta:e}),n.text=r,n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i}}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=p,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let t=e,n=reasoningPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(f,n),i=t.data.reasoningSoFar;if(r.completed){if(r.text.startsWith(i)||p<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`reasoning-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`reasoning.completed`:{let t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(f,t),r=e.data.reasoning;if(n.completed){if(r.length===0||r===n.text||n.text.startsWith(r)||p<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=p;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}let i=partGenerationId(t,n.generation);if(n.text.length===0&&r.length>0)n.text=r,yield{type:`reasoning-delta`,id:i,delta:r};else if(r.length>0&&!r.startsWith(n.text))break;n.completed=!0,n.completedEpoch=p,yield{type:`reasoning-complete`,id:i};break}case`actions.requested`:{let t=e.data,n=t.actions.filter(e=>e.kind===`tool-call`);if(n.length===0)break;let r=toolBatchKey(`actions.requested`,t.turnId,t.stepIndex,n);if(g.has(r)){for(let e of n)m.has(e.callId)||h.add(e.callId);break}g.add(r);for(let e of n)m.has(e.callId)||(m.add(e.callId),yield{type:`tool-call`,toolCallId:e.callId,toolName:e.toolName,input:e.input});break}case`input.requested`:{let t=e.data,r=t.requests.filter(e=>e.action.kind===`tool-call`);if(r.length===0)break;let a=inputRequestBatchKey(t.turnId,t.stepIndex,r);if(g.has(a)){for(let e of r)m.has(e.action.callId)||h.add(e.action.callId);break}g.add(a);for(let e of r){let t=e.action.callId;if(m.has(t)||(m.add(t),yield{type:`tool-call`,toolCallId:t,toolName:e.action.toolName,input:e.action.input}),n.set(e.requestId,e),isQuestionRequest(e)){upsertPendingQuestion(i,e);continue}upsertPendingApproval(i,e),yield{type:`tool-approval-request`,approvalId:e.requestId,toolCallId:t}}break}case`action.result`:{let t=e;if(t.data.result.kind!==`tool-result`)break;let n=t.data.result.callId;if(h.has(n)||!m.has(n))break;t.data.status===`failed`?yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)}:yield{type:`tool-result`,toolCallId:n,output:t.data.result.output};break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,_,u);t&&(yield t);break}case`session.failed`:{i.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,_,u);t&&(yield t),i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b},v=!0;return}case`session.waiting`:case`session.completed`:i.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b},v=!0;return;case`turn.completed`:y=!0,yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p);break;case`subagent.called`:{let t=e;if(!r.has(t.data.callId))r.set(t.data.callId,{name:t.data.name,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map});else{let e=r.get(t.data.callId);e&&(e.name=t.data.name)}a?.(t);break}case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:o?.(e.data.callId);break;case`authorization.required`:s?.(e);break;case`authorization.completed`:c?.(e);break;default:break}v||(yield*closeOpenParts(d,`assistant-complete`,p),yield*closeOpenParts(f,`reasoning-complete`,p),yield{type:`finish`,usage:b})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{pendingApprovals:[],pendingQuestions:[],sawSessionFailure:!1}}function upsertPendingApproval(e,t){let n=toAgentTUIToolApprovalRequest(t),r=e.pendingApprovals.findIndex(e=>e.approvalId===n.approvalId);r===-1?e.pendingApprovals.push(n):e.pendingApprovals[r]=n}function toAgentTUIToolApprovalRequest(e){return{approvalId:e.requestId,toolCallId:e.action.callId,toolName:e.action.toolName,input:e.action.input}}function upsertPendingQuestion(e,t){let n=e.pendingQuestions.findIndex(e=>e.requestId===t.requestId);n===-1?e.pendingQuestions.push(t):e.pendingQuestions[n]=t}function textPartId(e,t){return`text:${e}:${t}`}function reasoningPartId(e,t){return`reasoning:${e}:${t}`}function partStateFor(e,t){let n=e.get(t);return n===void 0&&(n={generation:0,text:``,completed:!1,completedEpoch:0},e.set(t,n)),n}function partGenerationId(e,t){return t===0?e:`${e}#${t}`}function*closeOpenParts(e,t,n){for(let[r,i]of e)i.completed||i.text.length===0||(i.completed=!0,i.completedEpoch=n,yield{type:t,id:partGenerationId(r,i.generation)})}function isPostTurnVisibleEvent(e){switch(e.type){case`action.result`:case`actions.requested`:case`authorization.completed`:case`authorization.required`:case`input.requested`:case`message.appended`:case`message.completed`:case`reasoning.appended`:case`reasoning.completed`:case`result.completed`:case`step.completed`:case`step.failed`:case`step.started`:case`subagent.called`:case`subagent.completed`:case`subagent.event`:case`subagent.started`:case`turn.completed`:case`turn.failed`:return!0;default:return!1}}function toolBatchKey(e,t,n,r){return`${e}:${t}:${String(n)}:${stableStringify(r.map(e=>({input:e.input,toolName:e.toolName})))}`}function inputRequestBatchKey(e,t,n){return toolBatchKey(`input.requested`,e,t,n.map(e=>({input:e.action.input,toolName:e.action.toolName})))}function stableStringify(e){return JSON.stringify(toStableJson(e))??`undefined`}function toStableJson(e,t=new WeakSet){if(typeof e!=`object`||!e)return e;if(t.has(e))return`[Circular]`;if(t.add(e),Array.isArray(e))return e.map(e=>toStableJson(e,t));let n=e,r={};for(let e of Object.keys(n).sort())r[e]=toStableJson(n[e],t);return r}function formatActionResultError(e){if(e.data.error?.message)return e.data.error.message;let t=e.data.result.output;if(typeof t==`string`)return t;try{return JSON.stringify(t)}catch{return`Tool execution failed.`}}function toFailureEvent(e,t,a){let o=failureKey(e);if(t.has(o))return;t.add(o);let s=a?.(e),c={type:`error`,errorText:s??formatFailureMessage(e)};if(s!==void 0)return c;let l=formatFailureDetail(e);return l!==void 0&&(c.detail=l),c}function isQuestionRequest(e){return e.display===`select`||e.display===`text`?!0:e.display===`confirmation`?!1:e.options!==void 0&&e.options.length>0}function toAgentTUIInputQuestion(e){let t=e.display===`text`?`text`:e.display===`select`||e.options!==void 0&&e.options.length>0?`select`:`text`,n={requestId:e.requestId,prompt:e.prompt,display:t};return e.options!==void 0&&(n.options=e.options.map(e=>{let t={id:e.id,label:e.label};return e.description!==void 0&&(t.description=e.description),e.style!==void 0&&(t.style=e.style),t})),e.allowFreeform!==void 0&&(n.allowFreeform=e.allowFreeform),n}function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{EveTUIRunner,parsePromptCommand};
@@ -1,2 +1,2 @@
1
1
  const CSI_FINAL=/[\u0040-\u007e]/u;function nextKey(t){let n=t[0];if(n===void 0)return{consumed:0,incomplete:!0};if(n===`\x1B`){if(t.length===1)return{consumed:0,incomplete:!0};let n=t[1];if(n===`O`)return t.length<3?{consumed:0,incomplete:!0}:{key:parseKey(Buffer.from(t.slice(0,3))),consumed:3};if(n===`[`){for(let n=2;n<t.length;n+=1)if(CSI_FINAL.test(t[n]))return{key:parseKey(Buffer.from(t.slice(0,n+1))),consumed:n+1};return{consumed:0,incomplete:!0}}return{key:{type:`escape`},consumed:1}}if(n<` `||n===``)return{key:parseKey(Buffer.from(n)),consumed:1};let r=1;for(;r<t.length;){let e=t[r];if(e===`\x1B`||e<` `||e===``)break;r+=1}return{key:parseKey(Buffer.from(t.slice(0,r))),consumed:r}}function parseKey(e){let t=e.toString(`utf8`);switch(t){case``:return{type:`ctrl-a`};case``:return{type:`ctrl-e`};case``:return{type:`ctrl-d`};case`\v`:return{type:`ctrl-k`};case`\f`:return{type:`ctrl-l`};case``:return{type:`ctrl-r`};case``:return{type:`ctrl-u`};case``:return{type:`ctrl-w`};case``:return{type:`ctrl-c`};case`\r`:case`
2
- `:return{type:`enter`};case``:case`\b`:return{type:`backspace`};case`\x1B[A`:case`\x1BOA`:return{type:`up`};case`\x1B[B`:case`\x1BOB`:return{type:`down`};case`\x1B[C`:case`\x1BOC`:return{type:`right`};case`\x1B[D`:case`\x1BOD`:return{type:`left`};case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:return{type:`home`};case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:return{type:`end`};case`\x1B[3~`:return{type:`delete`};case` `:return{type:`tab`};case`\x1B`:return{type:`escape`};default:{let e=``;for(let n of t)n>=` `&&n!==``&&(e+=n);return e.length>0?{type:`character`,value:e}:{type:`ignore`}}}}async function*takeUntil(e,t){let n=e[Symbol.asyncIterator](),r=t.then(()=>({done:!0,value:void 0}));for(;;){let e=await Promise.race([n.next(),r]);if(e.done)break;yield e.value}}function formatTokenCount(e,t){if(e==null)return;let n=`${e.toLocaleString()} ${e===1?`token`:`tokens`}`,r=formatContextPercentage(e,t);return r==null?n:`${n} ${r}`}function formatContextPercentage(e,t){if(!(t==null||t<=0||!Number.isFinite(t)))return`${Math.round(e/t*100).toLocaleString()}%`}function formatAssistantResponseStats(e,t){if(t===`tokensPerSecond`)return formatTokensPerSecond(e.tokensPerSecond);if(e.outputTokens!=null)return`${e.outputTokens.toLocaleString()} output tokens`}function formatTokensPerSecond(e){if(e!=null)return`${formatNumber(e)} tok/s`}function formatNumber(e){return Number.isInteger(e)?e.toLocaleString():e.toLocaleString(void 0,{maximumFractionDigits:1})}export{formatAssistantResponseStats,formatTokenCount,nextKey,parseKey,takeUntil};
2
+ `:return{type:`enter`};case``:case`\b`:return{type:`backspace`};case`\x1B[A`:case`\x1BOA`:return{type:`up`};case`\x1B[B`:case`\x1BOB`:return{type:`down`};case`\x1B[C`:case`\x1BOC`:return{type:`right`};case`\x1B[D`:case`\x1BOD`:return{type:`left`};case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:return{type:`home`};case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:return{type:`end`};case`\x1B[3~`:return{type:`delete`};case` `:return{type:`tab`};case`\x1B`:return{type:`escape`};default:{let e=``;for(let n of t)n>=` `&&n!==``&&(e+=n);return e.length>0?{type:`character`,value:e}:{type:`ignore`}}}}async function*takeUntil(e,t){let n=e[Symbol.asyncIterator](),r=t.then(()=>({done:!0,value:void 0}));try{for(;;){let e=n.next();e.catch(()=>{});let t=await Promise.race([e,r]);if(t.done)break;yield t.value}}finally{n.return?.()?.catch(()=>{})}}function formatTokenCount(e,t){if(e==null)return;let n=`${e.toLocaleString()} ${e===1?`token`:`tokens`}`,r=formatContextPercentage(e,t);return r==null?n:`${n} ${r}`}function formatContextPercentage(e,t){if(!(t==null||t<=0||!Number.isFinite(t)))return`${Math.round(e/t*100).toLocaleString()}%`}function formatAssistantResponseStats(e,t){if(t===`tokensPerSecond`)return formatTokensPerSecond(e.tokensPerSecond);if(e.outputTokens!=null)return`${e.outputTokens.toLocaleString()} output tokens`}function formatTokensPerSecond(e){if(e!=null)return`${formatNumber(e)} tok/s`}function formatNumber(e){return Number.isInteger(e)?e.toLocaleString():e.toLocaleString(void 0,{maximumFractionDigits:1})}export{formatAssistantResponseStats,formatTokenCount,nextKey,parseKey,takeUntil};
@@ -1,4 +1,4 @@
1
- import type { AgentTUIInputQuestion, AgentTUIInputQuestionResponse, AgentTUISessionOptions, AgentTUIStreamResult, AgentTUIToolApprovalRequest, AgentTUIToolApprovalResponse, ConnectionAuthUpdate, SubagentStepUpdate, SubagentToolUpdate } from "./runner.js";
1
+ import type { AgentTUIInputQuestion, AgentTUIInputQuestionResponse, AgentTUIRenderer, AgentTUISessionOptions, AgentTUIStreamResult, AgentTUIToolApprovalRequest, AgentTUIToolApprovalResponse, ConnectionAuthUpdate, SubagentStepUpdate, SubagentToolUpdate } from "./runner.js";
2
2
  import type { SetupFlowRenderer } from "./setup-flow.js";
3
3
  import type { AssistantResponseStatsMode, LogDisplayMode, TerminalPartDisplayMode } from "./types.js";
4
4
  import type { AgentInfoResult } from "#client/index.js";
@@ -39,15 +39,15 @@ export type AgentHeaderOptions = {
39
39
  /** Mention the setup slash commands in the key hints (local sessions only). */
40
40
  setupCommands?: boolean;
41
41
  };
42
- export declare class TerminalRenderer {
42
+ export declare class TerminalRenderer implements AgentTUIRenderer {
43
43
  #private;
44
44
  readonly setupFlow: SetupFlowRenderer;
45
45
  constructor(options?: TerminalRendererOptions);
46
46
  /**
47
47
  * Commits the startup agent header (brand mark + resolved configuration) to
48
- * scrollback before the first prompt. Later calls replace the committed
49
- * header and replay the transcript beneath it so dev HMR can refresh fields
50
- * such as the resolved model.
48
+ * scrollback before the first prompt. Later calls (dev HMR refreshing fields
49
+ * such as the resolved model) commit a fresh header beneath the existing
50
+ * transcript; committed scrollback is never cleared or replayed.
51
51
  */
52
52
  renderAgentHeader(options: AgentHeaderOptions): void;
53
53
  readPrompt(options?: AgentTUISessionOptions): Promise<string>;
@@ -1,4 +1,5 @@
1
- import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{sliceVisible,stripAnsi,visibleLength}from"./terminal-text.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderBlockLines}from"./blocks.js";import{dismissTypeahead,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,backspace,deleteForward,deleteWord,insert,killToEnd,killToStart,lineOf,moveEnd,moveHome,moveLeft,moveRight,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{numbersSelectRows,renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{createTheme,detectUnicode}from"./theme.js";import{formatAssistantResponseStats,formatTokenCount,nextKey,takeUntil}from"./stream-format.js";import{toErrorMessage}from"#shared/errors.js";import{filterOptions,initialSelectState,orderedSelection,reduceSelect,selectValueAtCursor,submitRowIndex}from"#setup/cli/select-state.js";const STATUS={processing:`Working…`,toolResults:`Reading results…`,streaming:`Responding…`,executingTools:`Running tools…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=[];#p=new Map;#m=new Set;#h=new Set;#g=new Map;#_=new Set;#v;#y=!1;#b=[];#x;#S=0;#C=``;#w=0;#T=new PromptHistory;#E=!1;#D;#O=!1;#k=STATUS.processing;#A=`Eve`;#j=!1;#M=!1;#N=!0;#P=0;#F;#I;#L;#R=``;#z;#B;#V;#H=!1;#U=!1;#W;#G;#K;#q;#J;#Y;#X=``;#Z=``;#Q;#$;setupFlow={begin:e=>this.#ne(e),end:e=>this.#re(e?.preserveDiagnostics??!0),readSelect:e=>this.#ie(e),readText:e=>this.#ae(e),readAcknowledge:e=>this.#oe(e),setStatus:e=>this.#le(e),renderLine:(e,t)=>this.#ue(e,t),renderOutput:e=>this.#de(e)};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#i=e?.tools??`auto-collapsed`,this.#a=e?.reasoning??`full`,this.#o=e?.subagents??`auto-collapsed`,this.#s=e?.connectionAuth??`full`,this.#c=e?.assistantResponseStats??`tokensPerSecond`,this.#l=e?.contextSize,this.#G=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#d=e?.logs??`all`}renderAgentHeader(e){if(this.#A=e.name,this.#v=e,this.#fe(),this.#y){this.#Ve();return}this.#y=!0,this.#n.flush(this.#He(),[])}async readPrompt(e){this.#fe(e),this.#E=!0,this.#O=!1,this.#k=``;let t=lineOf(``);return this.#T.begin(t.text),this.#ee(t),this.#D=typeaheadFor(PROMPT_COMMANDS,t.text),this.#be(),this.#ze(),await new Promise((e,n)=>{let apply=e=>{t=e,this.#Se(),this.#ee(t),this.#D=typeaheadFor(PROMPT_COMMANDS,e.text,this.#D),this.#ze()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#D=void 0,this.#xe(),this.#pe(),n(interruptedError())},suggestions=()=>this.#D!==void 0&&isTypeaheadOpen(this.#D)?this.#D:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#L=n=>{switch(n.type){case`character`:apply(insert(t,n.value));break;case`backspace`:apply(backspace(t));break;case`delete`:apply(deleteForward(t));break;case`left`:apply(moveLeft(t));break;case`right`:apply(moveRight(t));break;case`home`:case`ctrl-a`:apply(moveHome(t));break;case`end`:case`ctrl-e`:apply(moveEnd(t));break;case`ctrl-k`:apply(killToEnd(t));break;case`ctrl-u`:apply(killToStart(t));break;case`ctrl-w`:apply(deleteWord(t));break;case`up`:{let e=suggestions();e===void 0?recall(this.#T.previous(t.text)):(this.#D=moveTypeaheadSelection(e,-1),this.#ze());break}case`down`:{let e=suggestions();e===void 0?recall(this.#T.next()):(this.#D=moveTypeaheadSelection(e,1),this.#ze());break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#D=dismissTypeahead(e),this.#ze());break}case`enter`:{let n=highlighted(),r=n!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(n).trimEnd():t.text;this.#D=void 0,this.#T.add(r),this.#E=!1,this.#xe(),this.#k=STATUS.processing,isPromptControlCommand(r)?this.#Te({kind:`command`,body:r.trim(),live:!1}):(this.#Ee(r),this.#Q=r),this.#ee(EMPTY_LINE),this.#ze(),this.#he(),e(r);break}case`ctrl-d`:t.text.length===0?interrupt():apply(deleteForward(t));break;case`ctrl-l`:case`ctrl-r`:this.#ze();break;case`ctrl-c`:interrupt();break;default:break}},this.#me()})}#ee(e){this.#C=e.text,this.#w=e.cursor}async renderStream(e,t){this.#fe(t),this.#m.clear(),this.#E=!1,this.#O=!0,this.#k=STATUS.processing,this.#De(t?.submittedPrompt),this.#M=!1,this.#W=void 0,this.#K=void 0,this.#q=void 0,this.#J=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#Ce(),this.#ze();let r=new Promise(e=>{this.#V=e});this.#L=e=>this.#ye(e),this.#me();let i={text:new Map,reasoning:new Map,tools:new Map,hasPendingToolResults:!1};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#M)break;this.#Ne(t,n,i)}}catch(e){this.#Oe(`Error`,toErrorMessage(e))}finally{this.#V=void 0,this.#M&&e.abort?.(),this.#he(),this.#we(),this.#O=!1,this.#k=this.#M?`Interrupted`:t?.continueSession?`Ready`:`Done`,this.#Me(),this.#ze(),(this.#M||!t?.continueSession)&&this.#pe()}if(this.#M)throw interruptedError()}async readToolApproval(e,t){return this.#fe(t),this.#E=!1,this.#O=!1,this.#k=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#M=!1,this.#ze(),await new Promise((t,n)=>{this.#L=r=>{switch(r.type){case`character`:{let n=r.value.toLowerCase();n===`y`?(this.#k=STATUS.processing,this.#he(),this.#ze(),t({approved:!0})):n===`n`&&(this.#k=STATUS.processing,this.#te(e.toolCallId),this.#he(),this.#ze(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#ze();break;case`ctrl-c`:this.#M=!0,this.#pe(),n(interruptedError());break;default:break}},this.#me()})}async readInputQuestion(e,t){this.#fe(t),this.#E=!1,this.#O=!1,this.#M=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`select`:`text`,c=0,l=``,isOnFreeformRow=()=>i&&c===n.length,renderSection=()=>{this.#Ae({id:o,kind:`question`,title:e.prompt,body:formatQuestionContent(e,c,this.#r),preformatted:!0,live:!0})},repaintStatus=()=>{if(s===`select`){let e=isOnFreeformRow()?`type`:`select`;this.#k=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#E=!1}else this.#E=!0,this.#ee(lineOf(l)),this.#k=``;this.#ze()};renderSection(),s===`text`&&this.#be(),repaintStatus();let finalize=t=>{this.#Ae({id:o,kind:`question`,title:e.prompt,body:` ${this.#r.colors.green(this.#r.glyph.success)} ${t.label}`,preformatted:!0,live:!1}),this.#E=!1,this.#k=STATUS.processing,this.#xe(),this.#he(),this.#ze();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n};return await new Promise((t,i)=>{this.#L=o=>{if(o.type===`ctrl-c`){this.#M=!0,this.#xe(),this.#pe(),i(interruptedError());return}if(o.type===`ctrl-r`){this.#ze();return}if(s===`select`){switch(o.type){case`up`:a>0&&(c=(c-1+a)%a,renderSection(),repaintStatus());break;case`down`:a>0&&(c=(c+1)%a,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){s=`text`,l=``,this.#be(),repaintStatus();break}let e=n[c];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}switch(o.type){case`character`:l+=o.value,this.#Se(),repaintStatus();break;case`backspace`:l=l.slice(0,-1),this.#Se(),repaintStatus();break;case`enter`:{let n=resolveQuestionText(l,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(r){if(l.length>0){l=``,this.#Se(),repaintStatus();break}s=`select`,l=``,this.#E=!1,this.#xe(),repaintStatus();break}l=``,this.#Se(),repaintStatus();break;default:break}},this.#me()})}upsertSubagentStep(e){if(this.#o===`hidden`)return;let t=e.reasoning?.trim()??``,n=e.message?.trim()??``;if(!(t.length===0&&n.length===0)){if(this.#ke(e.callId,e.subagentName),this.#o===`collapsed`){this.#ze();return}this.#Ae({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:n,live:!e.finalized}),this.#ze()}}upsertSubagentTool(n){if(this.#o===`hidden`)return;if(this.#ke(n.callId,n.subagentName),this.#o===`collapsed`){this.#ze();return}let r=subagentToolStatus(n.status),i={id:subagentToolSectionId(n.callId,n.childCallId),kind:`subagent-tool`,depth:1,title:n.toolName,subtitle:summarizeToolArgs(n.input),status:r,live:r===`running`||r===`approval`,expanded:this.#o===`full`,toolInput:n.input};n.output===void 0?n.errorText!==void 0&&(i.result=n.errorText):(i.result=summarizeToolResult(n.output),i.toolOutput=n.output),this.#Ae(i),this.#ze()}markChildToolCallId(e){this.#h.add(e);let t=this.#g.get(e);t!==void 0&&(this.#je(t),this.#g.delete(e),this.#ze())}#te(e){let t=this.#p.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=e.state===`authorized`||e.state===`declined`||e.state===`failed`||e.state===`timed-out`;this.#Ae({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${e.name} · authorization · ${e.state}`,body:formatConnectionAuthContent(e),preformatted:!0,live:!t}),this.#ze()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#S)return;let n=this.#S>0;this.#S=t,t>0?(this.#k=STATUS.connectionAuth,this.#ze()):n&&(this.#k=STATUS.processing,this.#ze())}reset(){this.#f=[],this.#p.clear(),this.#m.clear(),this.#x=void 0,this.#b.length=0,this.#v=void 0,this.#y=!1,this.#h.clear(),this.#g.clear(),this.#_.clear(),this.#Q=void 0,this.#S=0,this.#W=void 0,this.#K=void 0,this.#q=void 0,this.#J=void 0,this.#j&&(this.#n.clearAll(),this.#ze())}renderNotice(e){e.trim().length!==0&&(this.#fe(),this.#Te({kind:`notice`,body:e,live:!1}),this.#ze())}renderSetupWarning(e){e.trim().length!==0&&(this.#fe(),this.#Te({kind:`warning`,body:e,live:!1}),this.#ze())}renderCommandResult(e){e.trim().length!==0&&(this.#fe(),this.#Te({kind:`result`,body:e,live:!1}),this.#ze())}#ne(e){this.#fe(),this.#E=!1,this.#O=!1,this.#k=``,this.#$={title:e,lines:[],outputBuffer:[]},this.#Ce(),this.#ze()}#re(e){let t=this.#$;if(t!==void 0){if(this.#$=void 0,this.#we(),e)for(let e of t.lines)(e.tone===`warning`||e.tone===`error`)&&this.#Te({kind:`flow`,title:e.tone,body:e.text,live:!1});this.#ze()}}async#ie(e){this.#fe(),this.#E=!1,this.#O=!1,this.#k=``;let t={options:e.options,submitRow:e.multiple},n={options:e.options,submitRow:e.multiple};e.initialValue!==void 0&&(n.defaultValue=e.initialValue),e.initialValues!==void 0&&(n.initialValues=e.initialValues);let r=initialSelectState(n),i,a=this.#se(),panelState=()=>{let t={message:e.message,options:e.options,multiple:e.multiple,search:e.search,select:r};return e.placeholder!==void 0&&(t.placeholder=e.placeholder),i!==void 0&&(t.error=i),t};return a.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#ze(),await new Promise(n=>{let settle=e=>{this.#ce(),n(e)},apply=e=>{r=reduceSelect(r,e,t),i=void 0,this.#ze()};this.#L=n=>{switch(n.type){case`ctrl-c`:case`escape`:settle(void 0);return;case`ctrl-r`:this.#ze();return;case`up`:apply({type:`up`});return;case`down`:apply({type:`down`});return;case`backspace`:e.search&&apply({type:`backspace`});return;case`character`:if(e.multiple&&n.value===` `){apply({type:`toggle`});return}if(numbersSelectRows(e)&&/^[1-9]$/.test(n.value)){let t=Number(n.value)-1,a=e.options[t];a!==void 0&&!a.disabled&&!a.locked&&(r={...r,cursor:t},i=void 0,this.#ze());return}if(e.search){for(let e of n.value)e>=` `&&e!==``&&(r=reduceSelect(r,{type:`char`,char:e},t));i=void 0,this.#ze()}return;case`enter`:{let t=e.search?filterOptions(e.options,r.filter):[...e.options];if(e.multiple){if(r.cursor===submitRowIndex(t)){if(e.required&&r.selected.size===0){i=`Select at least one option, then submit.`,this.#ze();return}settle(orderedSelection(e.options,r.selected));return}apply({type:`toggle`});return}let n=selectValueAtCursor(t,r.cursor);if(n===void 0){i=`Type to match an option, then press enter.`,this.#ze();return}settle([n]);return}default:return}},this.#me()})}async#ae(e){this.#fe(),this.#E=!1,this.#O=!1,this.#k=``;let t=lineOf(``),n,r=this.#se();return r.question=r=>{let i={message:e.message,editor:t,mask:e.mask===!0};return e.placeholder!==void 0&&(i.placeholder=e.placeholder),n!==void 0&&(i.error=n),renderTextQuestion(i,this.#r,r,this.#N)},this.#be(),this.#ze(),await new Promise(r=>{let settle=e=>{this.#xe(),this.#ce(),r(e)},apply=e=>{t=e,n=void 0,this.#Se(),this.#ze()};this.#L=r=>{switch(r.type){case`ctrl-c`:case`escape`:settle(void 0);return;case`ctrl-r`:this.#ze();return;case`character`:apply(insert(t,r.value));return;case`backspace`:apply(backspace(t));return;case`delete`:apply(deleteForward(t));return;case`left`:apply(moveLeft(t));return;case`right`:apply(moveRight(t));return;case`home`:case`ctrl-a`:apply(moveHome(t));return;case`end`:case`ctrl-e`:apply(moveEnd(t));return;case`ctrl-k`:apply(killToEnd(t));return;case`ctrl-u`:apply(killToStart(t));return;case`ctrl-w`:apply(deleteWord(t));return;case`enter`:{let r=t.text.length>0?t.text:e.defaultValue??``,i=e.validate?.(r);if(i!==void 0){n=i,this.#ze();return}settle(r);return}default:return}},this.#me()})}async#oe(e){this.#fe(),this.#E=!1,this.#O=!1,this.#k=``;let t=this.#se();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#ze(),await new Promise(e=>{this.#L=t=>{switch(t.type){case`enter`:case`escape`:case`ctrl-c`:this.#ce(),e();return;case`ctrl-r`:this.#ze();return;default:return}},this.#me()})}#se(){return this.#$===void 0&&(this.#$={title:``,lines:[],outputBuffer:[]}),this.#$}#ce(){this.#$!==void 0&&(this.#$.question=void 0),this.#L=void 0,this.#he(),this.#ze()}#le(e){if(this.#$!==void 0){this.#$.status=e,e===void 0&&(this.#$.preview=void 0),this.#ze();return}if(e===void 0){this.#O=!1,this.#k=``,this.#we(),this.#ze();return}this.#fe(),this.#O=!0,this.#k=e,this.#Ce(),this.#ze()}#ue(e,t){if(e.trim().length===0)return;let n=this.#$;if(n!==void 0){if(n.preview=void 0,t===`warning`||t===`error`)for(let e of n.outputBuffer)n.lines.push({text:e,tone:`info`});n.outputBuffer=[],n.lines.push({text:e,tone:t}),this.#ze();return}this.#fe(),this.#Te({kind:`flow`,title:t,body:e,live:!1}),this.#ze()}#de(e){if(e.trim().length===0)return;let t=this.#$;if(t===void 0){this.#ue(e,`info`);return}t.preview=e,t.outputBuffer.push(e),t.outputBuffer.length>8&&t.outputBuffer.shift(),this.#ze()}shutdown(){this.#pe()}#fe(e){this.#A=e?.title??this.#A,this.#G=e?.contextSize??this.#l,!this.#j&&(this.#j=!0,this.#n.reset(),this.#n.hideCursor(),this.#Ye(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume()),this.#B=()=>this.#ze(),this.#t.on(`resize`,this.#B))}#pe(){this.#he(),this.#xe(),this.#we(),this.#j&&=(this.#ze(),this.#n.clear(),this.#n.showCursor(),this.#Xe(),this.#n.newline(),this.#e.isTTY&&(this.#e.setRawMode?.(!1),this.#e.pause()),this.#B&&=(this.#t.off(`resize`,this.#B),void 0),!1)}#me(){this.#e.on(`data`,this.#ge)}#he(){this.#e.off(`data`,this.#ge),this.#ve(),this.#R=``,this.#L=void 0}#ge=e=>{this.#ve(),this.#R+=e.toString(`utf8`),this.#_e(),this.#R===`\x1B`&&(this.#z=setTimeout(()=>{this.#R===`\x1B`&&(this.#R=``,this.#L?.({type:`escape`}))},30),this.#z.unref?.())};#_e(){for(;this.#R.length>0;){let e=nextKey(this.#R);if(e.incomplete)return;this.#R=this.#R.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#L?.(e.key)}}#ve(){this.#z&&=(clearTimeout(this.#z),void 0)}#ye(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#ze();break;case`ctrl-c`:this.#M=!0,this.#V?.();break;default:break}}#be(){this.#xe(),this.#Se(),this.#F=setInterval(()=>{this.#N=!this.#N,this.#ze()},500),this.#F.unref?.()}#xe(){this.#F&&=(clearInterval(this.#F),void 0),this.#N=!0}#Se(){this.#N=!0}#Ce(){this.#we(),this.#I=setInterval(()=>{this.#P+=1,this.#ze()},90),this.#I.unref?.()}#we(){this.#I&&=(clearInterval(this.#I),void 0)}#Te(e){this.#f.push(e),e.id&&this.#p.set(e.id,e)}#Ee(e){this.#Te({kind:`user`,body:e,live:!1}),this.#ze()}#De(e){if(e!=null){if(this.#Q===e){this.#Q=void 0;return}this.#Te({kind:`user`,body:e,live:!1})}}#Oe(e,t,n){let r={kind:`error`,title:e,body:t,live:!1};n!==void 0&&(r.detail=n),this.#Te(r),this.#ze()}#ke(e,t){this.#_.has(e)||(this.#_.add(e),this.#Te({id:subagentHeaderId(e),kind:`subagent`,title:t,live:!1}))}#Ae(e){if(e.id&&this.#m.has(e.id))return;let t=e.id?this.#p.get(e.id):void 0;if(t){Object.assign(t,e);return}this.#Te(e)}#je(e){this.#f=this.#f.filter(t=>t.id!==e),this.#p.delete(e)}#Me(){for(let e of this.#f)e.status!==`approval`&&(e.live=!1)}#Ne(e,t,n){switch(e.type){case`step-start`:this.#Pe(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#Re(e.usage),this.#ze();break;case`assistant-delta`:{this.#Pe(STATUS.streaming);let t=(n.text.get(e.id)??``)+e.delta;n.text.set(e.id,t),this.#Fe(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?e.text??``:t;n.text.set(e.id,r),this.#Fe(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;this.#Pe(STATUS.streaming);let r=(n.reasoning.get(e.id)??``)+e.delta;n.reasoning.set(e.id,r),this.#Ie(e.id,r,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#Ie(e.id,r,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#Pe(STATUS.executingTools),this.#Le({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.#Le({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;n.hasPendingToolResults=!0,this.#Pe(STATUS.toolResults),this.#Le({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;n.hasPendingToolResults=!0,this.#Pe(STATUS.toolResults),this.#Le({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#Oe(`Error`,e.errorText,e.detail);break;case`finish`:this.#Re(e.usage),this.#ze();break}}#Pe(e){let t=this.#S>0?STATUS.connectionAuth:e;this.#k!==t&&(this.#k=t,this.#ze())}#Fe(e,t,n){let r=t.trim();r.length!==0&&(this.#Ae({id:e,kind:`assistant`,body:r,live:n}),this.#ze())}#Ie(e,t,n,r){let i=t.trim();i.length!==0&&(this.#Ae({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#ze())}#Le(e,t,n){if(n.tools.set(e.toolCallId,e),this.#h.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#g.set(e.toolCallId,r),this.#Ae(renderNativeToolBlock(e,r,t.tools===`full`)),this.#ze()}#Re(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#W=(t??0)+(n??0)),this.#K=n??this.#K,this.#K!=null&&this.#J!==void 0){let e=(Date.now()-this.#J)/1e3;e>0&&(this.#q=this.#K/e)}}#ze(){if(this.#j){if(this.#H){this.#U=!0;return}this.#H=!0;try{do this.#U=!1,this.#Be();while(this.#U)}finally{this.#H=!1}}}#Be(){if(!this.#j)return;let e=this.#qe(),t=this.#Ge(e),n=Math.max(1,this.#Je()-t.length),r=[],i=this.#x;for(;this.#f.length>0&&this.#f[0].live===!1;){let t=this.#f.shift(),n=this.#Ue(t,e,i);i=previousBlockOf(t),this.#x=i,r.push(...n),this.#b.push(...n),t.id&&(this.#m.add(t.id),this.#p.delete(t.id))}let a=[];for(let t of this.#f){let n=this.#Ue(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)a.push({block:t,row:n[e]})}let o=[...clipLiveRows(a.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,o):this.#n.update(o)}#Ve(){if(!this.#j)return;let e=this.#qe(),t=this.#Ge(e),n=Math.max(1,this.#Je()-t.length),r=this.#x,i=[];for(let t of this.#f){let n=this.#Ue(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#r),...t];this.#n.clearAll(),this.#n.flush([...this.#He(),...this.#b],a)}#He(){let e=this.#v;if(e===void 0)return[];let t={name:e.name,serverUrl:e.serverUrl,theme:this.#r,width:this.#qe()};return e.info!==void 0&&(t.info=e.info),e.setupCommands!==void 0&&(t.setupCommands=e.setupCommands),buildAgentHeader(t)}#Ue(e,t,n){let r={spinner:this.#We()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#We(){return this.#r.spinner[this.#P%this.#r.spinner.length]??``}#Ge(e){let t=this.#r.colors,n=[``],r=this.#$;if(r!==void 0){let t={title:r.title,lines:r.lines,frame:this.#We()};return r.question===void 0?(r.status!==void 0&&(t.status={text:r.status,frame:this.#We()}),r.preview!==void 0&&(t.preview=r.preview)):t.question=r.question(e),n.push(...renderFlowPanel(t,this.#r,e)),n}if(this.#E){this.#D!==void 0&&isTypeaheadOpen(this.#D)&&n.push(...renderCommandSuggestions(this.#D,this.#r,e));let r=Math.max(4,e-3),{before:i,after:a}=visibleLine({text:this.#C,cursor:this.#w},r,this.#r.glyph.ellipsis),o=isPromptControlCommand(this.#C),style=e=>o&&e.length>0?t.blue(e):e,c=this.#N?t.cyan(this.#r.glyph.caret):` `;return n.push(`${t.cyan(this.#r.glyph.prompt)} ${style(i)}${c}${style(a)}`),n}let i=this.#O?t.yellow(this.#We()):t.dim(this.#r.glyph.dot),a=this.#k.length>0?this.#k:`Ready`,o=this.#O?t.dim(a):a,c=this.#Ke(),l=c?`${i} ${o} ${t.dim(this.#r.glyph.dot)} ${c}`:`${i} ${o}`;return n.push(clip(l,e)),n}#Ke(){let e=this.#r.colors,t=[],n=formatTokenCount(this.#W,this.#G);n&&t.push(n);let r=formatAssistantResponseStats({totalTokens:this.#W,outputTokens:this.#K,tokensPerSecond:this.#q},this.#c);return r&&t.push(r),this.#O&&t.push(`Ctrl+C to interrupt`),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#qe(){return Math.max(20,this.#t.columns||80)}#Je(){return Math.max(8,this.#t.rows||24)}#Ye(){if(this.#Y!==void 0||!this.#u)return;this.#X=``,this.#Z=``;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.#Ze(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#Y=()=>{e(),t()}}#Xe(){let e=this.#Y;e!==void 0&&(this.#Y=void 0,e(),this.#X.length>0&&(this.#Qe(`stdout`)&&process.stdout.write(`${this.#X}\n`),this.#X=``),this.#Z.length>0&&(this.#Qe(`stderr`)&&process.stderr.write(`${this.#Z}\n`),this.#Z=``))}#Ze(e,t){let n=(e===`stdout`?this.#X:this.#Z)+t,r=n.lastIndexOf(`
2
- `),a=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#X=a:this.#Z=a,r===-1||!this.#Qe(e))return;let o=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);o.trim().length!==0&&(this.#Te({kind:`log`,title:e,body:o,live:!1}),this.#ze())}#Qe(e){switch(this.#d){case`none`:return!1;case`stderr`:return e===`stderr`;case`all`:return!0}}};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 visibleLength(e)>t?sliceVisible(e,t):e}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function leadsWithGap(e,t){if(e.kind===`log`&&t?.kind===`log`)return t.title!==e.title;if(t?.kind===`log`&&e.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`log`:case`command`:case`warning`:case`flow`:return!0;default:return!1}}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(n,r,i){let a={id:r,kind:`tool`,title:n.toolName,subtitle:summarizeToolArgs(n.input),status:n.status,live:n.status===`running`||n.status===`approval`,expanded:i,toolInput:n.input};return n.output===void 0?n.errorText!==void 0&&(a.result=n.errorText):(a.result=summarizeToolResult(n.output),a.toolOutput=n.output),a}function subagentToolStatus(e){switch(e){case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`}}function formatToolApprovalTitle(e){return 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 formatConnectionAuthContent(e){let t=[];e.description.length>0&&t.push(e.description);let n=e.challenge;return n?.url&&t.push(`URL: ${n.url}`),n?.userCode&&t.push(`Code: ${n.userCode}`),n?.expiresAt&&t.push(`Expires: ${n.expiresAt}`),n?.instructions&&t.push(n.instructions),e.reason!==void 0&&e.reason.length>0&&t.push(`Reason: ${e.reason}`),t.join(`
1
+ import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{sliceVisible,stripAnsi,visibleLength}from"./terminal-text.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderBlockLines}from"./blocks.js";import{dismissTypeahead,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,backspace,deleteForward,deleteWord,insert,killToEnd,killToStart,lineOf,moveEnd,moveHome,moveLeft,moveRight,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{numbersSelectRows,renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{createTheme,detectUnicode}from"./theme.js";import{formatAssistantResponseStats,formatTokenCount,nextKey,takeUntil}from"./stream-format.js";import{toErrorMessage}from"#shared/errors.js";import{filterOptions,initialSelectState,orderedSelection,reduceSelect,selectValueAtCursor,submitRowIndex}from"#setup/cli/select-state.js";const STATUS={processing:`Working…`,toolResults:`Reading results…`,streaming:`Responding…`,executingTools:`Running tools…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=[];#p=new Map;#m=new Set;#h=new Set;#g=new Map;#_=new Set;#v;#y=!1;#b;#x=0;#S=``;#C=0;#w=new PromptHistory;#T=!1;#E;#D=!1;#O=STATUS.processing;#k=`Eve`;#A=!1;#j=!1;#M=!0;#N=0;#P;#F;#I;#L=``;#R;#z;#B;#V=!1;#H=!1;#U;#W;#G;#K;#q;#J;#Y=``;#X=``;#Z;#Q;setupFlow={begin:e=>this.#te(e),end:e=>this.#ne(e?.preserveDiagnostics??!0),readSelect:e=>this.#re(e),readText:e=>this.#ie(e),readAcknowledge:e=>this.#ae(e),setStatus:e=>this.#ce(e),renderLine:(e,t)=>this.#le(e,t),renderOutput:e=>this.#ue(e)};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#i=e?.tools??`auto-collapsed`,this.#a=e?.reasoning??`full`,this.#o=e?.subagents??`auto-collapsed`,this.#s=e?.connectionAuth??`full`,this.#c=e?.assistantResponseStats??`tokensPerSecond`,this.#l=e?.contextSize,this.#W=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#d=e?.logs??`all`}renderAgentHeader(e){if(this.#k=e.name,this.#v=e,this.#de(),this.#y){this.#we({kind:`agent-header`,body:this.#Be().join(`
2
+ `),live:!1}),this.#Re();return}this.#y=!0,this.#n.flush(this.#Be(),[])}async readPrompt(e){this.#de(e),this.#T=!0,this.#D=!1,this.#O=``;let t=lineOf(``);return this.#w.begin(t.text),this.#$(t),this.#E=typeaheadFor(PROMPT_COMMANDS,t.text),this.#ye(),this.#Re(),await new Promise((e,n)=>{let apply=e=>{t=e,this.#xe(),this.#$(t),this.#E=typeaheadFor(PROMPT_COMMANDS,e.text,this.#E),this.#Re()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#E=void 0,this.#be(),this.#fe(),n(interruptedError())},suggestions=()=>this.#E!==void 0&&isTypeaheadOpen(this.#E)?this.#E:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#I=n=>{switch(n.type){case`character`:apply(insert(t,n.value));break;case`backspace`:apply(backspace(t));break;case`delete`:apply(deleteForward(t));break;case`left`:apply(moveLeft(t));break;case`right`:apply(moveRight(t));break;case`home`:case`ctrl-a`:apply(moveHome(t));break;case`end`:case`ctrl-e`:apply(moveEnd(t));break;case`ctrl-k`:apply(killToEnd(t));break;case`ctrl-u`:apply(killToStart(t));break;case`ctrl-w`:apply(deleteWord(t));break;case`up`:{let e=suggestions();e===void 0?recall(this.#w.previous(t.text)):(this.#E=moveTypeaheadSelection(e,-1),this.#Re());break}case`down`:{let e=suggestions();e===void 0?recall(this.#w.next()):(this.#E=moveTypeaheadSelection(e,1),this.#Re());break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#E=dismissTypeahead(e),this.#Re());break}case`enter`:{let n=highlighted(),r=n!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(n).trimEnd():t.text;this.#E=void 0,this.#w.add(r),this.#T=!1,this.#be(),this.#O=STATUS.processing,isPromptControlCommand(r)?this.#we({kind:`command`,body:r.trim(),live:!1}):(this.#Te(r),this.#Z=r),this.#$(EMPTY_LINE),this.#Re(),this.#me(),e(r);break}case`ctrl-d`:t.text.length===0?interrupt():apply(deleteForward(t));break;case`ctrl-l`:case`ctrl-r`:this.#Re();break;case`ctrl-c`:interrupt();break;default:break}},this.#pe()})}#$(e){this.#S=e.text,this.#C=e.cursor}async renderStream(e,t){this.#de(t),this.#m.clear(),this.#T=!1,this.#D=!0,this.#O=STATUS.processing,this.#Ee(t?.submittedPrompt),this.#j=!1,this.#U=void 0,this.#G=void 0,this.#K=void 0,this.#q=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#Se(),this.#Re();let r=new Promise(e=>{this.#B=e});this.#I=e=>this.#ve(e),this.#pe();let i={text:new Map,reasoning:new Map,tools:new Map,hasPendingToolResults:!1};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#j)break;this.#Me(t,n,i)}}catch(e){this.#De(`Error`,toErrorMessage(e))}finally{this.#B=void 0,this.#j&&e.abort?.(),this.#me(),this.#Ce(),this.#D=!1,this.#O=this.#j?`Interrupted`:t?.continueSession?`Ready`:`Done`,this.#je(),this.#Re(),(this.#j||!t?.continueSession)&&this.#fe()}if(this.#j)throw interruptedError()}async readToolApproval(e,t){return this.#de(t),this.#T=!1,this.#D=!1,this.#O=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#j=!1,this.#Re(),await new Promise((t,n)=>{this.#I=r=>{switch(r.type){case`character`:{let n=r.value.toLowerCase();n===`y`?(this.#O=STATUS.processing,this.#me(),this.#Re(),t({approved:!0})):n===`n`&&(this.#O=STATUS.processing,this.#ee(e.toolCallId),this.#me(),this.#Re(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#Re();break;case`ctrl-c`:this.#j=!0,this.#fe(),n(interruptedError());break;default:break}},this.#pe()})}async readInputQuestion(e,t){this.#de(t),this.#T=!1,this.#D=!1,this.#j=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`select`:`text`,c=0,l=``,isOnFreeformRow=()=>i&&c===n.length,renderSection=()=>{this.#ke({id:o,kind:`question`,title:e.prompt,body:formatQuestionContent(e,c,this.#r),preformatted:!0,live:!0})},repaintStatus=()=>{if(s===`select`){let e=isOnFreeformRow()?`type`:`select`;this.#O=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#T=!1}else this.#T=!0,this.#$(lineOf(l)),this.#O=``;this.#Re()};renderSection(),s===`text`&&this.#ye(),repaintStatus();let finalize=t=>{this.#ke({id:o,kind:`question`,title:e.prompt,body:` ${this.#r.colors.green(this.#r.glyph.success)} ${t.label}`,preformatted:!0,live:!1}),this.#T=!1,this.#O=STATUS.processing,this.#be(),this.#me(),this.#Re();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n};return await new Promise((t,i)=>{this.#I=o=>{if(o.type===`ctrl-c`){this.#j=!0,this.#be(),this.#fe(),i(interruptedError());return}if(o.type===`ctrl-r`){this.#Re();return}if(s===`select`){switch(o.type){case`up`:a>0&&(c=(c-1+a)%a,renderSection(),repaintStatus());break;case`down`:a>0&&(c=(c+1)%a,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){s=`text`,l=``,this.#ye(),repaintStatus();break}let e=n[c];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}switch(o.type){case`character`:l+=o.value,this.#xe(),repaintStatus();break;case`backspace`:l=l.slice(0,-1),this.#xe(),repaintStatus();break;case`enter`:{let n=resolveQuestionText(l,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(r){if(l.length>0){l=``,this.#xe(),repaintStatus();break}s=`select`,l=``,this.#T=!1,this.#be(),repaintStatus();break}l=``,this.#xe(),repaintStatus();break;default:break}},this.#pe()})}upsertSubagentStep(e){if(this.#o===`hidden`)return;let t=e.reasoning?.trim()??``,n=e.message?.trim()??``;if(!(t.length===0&&n.length===0)){if(this.#Oe(e.callId,e.subagentName),this.#o===`collapsed`){this.#Re();return}this.#ke({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:n,live:!e.finalized}),this.#Re()}}upsertSubagentTool(n){if(this.#o===`hidden`)return;if(this.#Oe(n.callId,n.subagentName),this.#o===`collapsed`){this.#Re();return}let r=subagentToolStatus(n.status),i={id:subagentToolSectionId(n.callId,n.childCallId),kind:`subagent-tool`,depth:1,title:n.toolName,subtitle:summarizeToolArgs(n.input),status:r,live:r===`running`||r===`approval`,expanded:this.#o===`full`,toolInput:n.input};n.output===void 0?n.errorText!==void 0&&(i.result=n.errorText):(i.result=summarizeToolResult(n.output),i.toolOutput=n.output),this.#ke(i),this.#Re()}markChildToolCallId(e){this.#h.add(e);let t=this.#g.get(e);t!==void 0&&(this.#Ae(t),this.#g.delete(e),this.#Re())}#ee(e){let t=this.#p.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=e.state===`authorized`||e.state===`declined`||e.state===`failed`||e.state===`timed-out`;this.#ke({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${e.name} · authorization · ${e.state}`,body:formatConnectionAuthContent(e),preformatted:!0,live:!t}),this.#Re()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#x)return;let n=this.#x>0;this.#x=t,t>0?(this.#O=STATUS.connectionAuth,this.#Re()):n&&(this.#O=STATUS.processing,this.#Re())}reset(){this.#f=[],this.#p.clear(),this.#m.clear(),this.#b=void 0,this.#v=void 0,this.#y=!1,this.#h.clear(),this.#g.clear(),this.#_.clear(),this.#Z=void 0,this.#x=0,this.#U=void 0,this.#G=void 0,this.#K=void 0,this.#q=void 0,this.#A&&(this.#n.clearAll(),this.#Re())}renderNotice(e){e.trim().length!==0&&(this.#de(),this.#we({kind:`notice`,body:e,live:!1}),this.#Re())}renderSetupWarning(e){e.trim().length!==0&&(this.#de(),this.#we({kind:`warning`,body:e,live:!1}),this.#Re())}renderCommandResult(e){e.trim().length!==0&&(this.#de(),this.#we({kind:`result`,body:e,live:!1}),this.#Re())}#te(e){this.#de(),this.#T=!1,this.#D=!1,this.#O=``,this.#Q={title:e,lines:[],outputBuffer:[]},this.#Se(),this.#Re()}#ne(e){let t=this.#Q;if(t!==void 0){if(this.#Q=void 0,this.#Ce(),e)for(let e of t.lines)(e.tone===`warning`||e.tone===`error`)&&this.#we({kind:`flow`,title:e.tone,body:e.text,live:!1});this.#Re()}}async#re(e){this.#de(),this.#T=!1,this.#D=!1,this.#O=``;let t={options:e.options,submitRow:e.multiple},n={options:e.options,submitRow:e.multiple};e.initialValue!==void 0&&(n.defaultValue=e.initialValue),e.initialValues!==void 0&&(n.initialValues=e.initialValues);let r=initialSelectState(n),i,a=this.#oe(),panelState=()=>{let t={message:e.message,options:e.options,multiple:e.multiple,search:e.search,select:r};return e.placeholder!==void 0&&(t.placeholder=e.placeholder),i!==void 0&&(t.error=i),t};return a.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#Re(),await new Promise(n=>{let settle=e=>{this.#se(),n(e)},apply=e=>{r=reduceSelect(r,e,t),i=void 0,this.#Re()};this.#I=n=>{switch(n.type){case`ctrl-c`:case`escape`:settle(void 0);return;case`ctrl-r`:this.#Re();return;case`up`:apply({type:`up`});return;case`down`:apply({type:`down`});return;case`backspace`:e.search&&apply({type:`backspace`});return;case`character`:if(e.multiple&&n.value===` `){apply({type:`toggle`});return}if(numbersSelectRows(e)&&/^[1-9]$/.test(n.value)){let t=Number(n.value)-1,a=e.options[t];a!==void 0&&!a.disabled&&!a.locked&&(r={...r,cursor:t},i=void 0,this.#Re());return}if(e.search){for(let e of n.value)e>=` `&&e!==``&&(r=reduceSelect(r,{type:`char`,char:e},t));i=void 0,this.#Re()}return;case`enter`:{let t=e.search?filterOptions(e.options,r.filter):[...e.options];if(e.multiple){if(r.cursor===submitRowIndex(t)){if(e.required&&r.selected.size===0){i=`Select at least one option, then submit.`,this.#Re();return}settle(orderedSelection(e.options,r.selected));return}apply({type:`toggle`});return}let n=selectValueAtCursor(t,r.cursor);if(n===void 0){i=`Type to match an option, then press enter.`,this.#Re();return}settle([n]);return}default:return}},this.#pe()})}async#ie(e){this.#de(),this.#T=!1,this.#D=!1,this.#O=``;let t=lineOf(``),n,r=this.#oe();return r.question=r=>{let i={message:e.message,editor:t,mask:e.mask===!0};return e.placeholder!==void 0&&(i.placeholder=e.placeholder),n!==void 0&&(i.error=n),renderTextQuestion(i,this.#r,r,this.#M)},this.#ye(),this.#Re(),await new Promise(r=>{let settle=e=>{this.#be(),this.#se(),r(e)},apply=e=>{t=e,n=void 0,this.#xe(),this.#Re()};this.#I=r=>{switch(r.type){case`ctrl-c`:case`escape`:settle(void 0);return;case`ctrl-r`:this.#Re();return;case`character`:apply(insert(t,r.value));return;case`backspace`:apply(backspace(t));return;case`delete`:apply(deleteForward(t));return;case`left`:apply(moveLeft(t));return;case`right`:apply(moveRight(t));return;case`home`:case`ctrl-a`:apply(moveHome(t));return;case`end`:case`ctrl-e`:apply(moveEnd(t));return;case`ctrl-k`:apply(killToEnd(t));return;case`ctrl-u`:apply(killToStart(t));return;case`ctrl-w`:apply(deleteWord(t));return;case`enter`:{let r=t.text.length>0?t.text:e.defaultValue??``,i=e.validate?.(r);if(i!==void 0){n=i,this.#Re();return}settle(r);return}default:return}},this.#pe()})}async#ae(e){this.#de(),this.#T=!1,this.#D=!1,this.#O=``;let t=this.#oe();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#Re(),await new Promise(e=>{this.#I=t=>{switch(t.type){case`enter`:case`escape`:case`ctrl-c`:this.#se(),e();return;case`ctrl-r`:this.#Re();return;default:return}},this.#pe()})}#oe(){return this.#Q===void 0&&(this.#Q={title:``,lines:[],outputBuffer:[]}),this.#Q}#se(){this.#Q!==void 0&&(this.#Q.question=void 0),this.#I=void 0,this.#me(),this.#Re()}#ce(e){if(this.#Q!==void 0){this.#Q.status=e,e===void 0&&(this.#Q.preview=void 0),this.#Re();return}if(e===void 0){this.#D=!1,this.#O=``,this.#Ce(),this.#Re();return}this.#de(),this.#D=!0,this.#O=e,this.#Se(),this.#Re()}#le(e,t){if(e.trim().length===0)return;let n=this.#Q;if(n!==void 0){if(n.preview=void 0,t===`warning`||t===`error`)for(let e of n.outputBuffer)n.lines.push({text:e,tone:`info`});n.outputBuffer=[],n.lines.push({text:e,tone:t}),this.#Re();return}this.#de(),this.#we({kind:`flow`,title:t,body:e,live:!1}),this.#Re()}#ue(e){if(e.trim().length===0)return;let t=this.#Q;if(t===void 0){this.#le(e,`info`);return}t.preview=e,t.outputBuffer.push(e),t.outputBuffer.length>8&&t.outputBuffer.shift(),this.#Re()}shutdown(){this.#fe()}#de(e){this.#k=e?.title??this.#k,this.#W=e?.contextSize??this.#l,!this.#A&&(this.#A=!0,this.#n.reset(),this.#n.hideCursor(),this.#qe(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume()),this.#z=()=>this.#Re(),this.#t.on(`resize`,this.#z))}#fe(){this.#me(),this.#be(),this.#Ce(),this.#A&&=(this.#Re(),this.#n.clear(),this.#n.showCursor(),this.#Je(),this.#n.newline(),this.#e.isTTY&&(this.#e.setRawMode?.(!1),this.#e.pause()),this.#z&&=(this.#t.off(`resize`,this.#z),void 0),!1)}#pe(){this.#e.on(`data`,this.#he)}#me(){this.#e.off(`data`,this.#he),this.#_e(),this.#L=``,this.#I=void 0}#he=e=>{this.#_e(),this.#L+=e.toString(`utf8`),this.#ge(),this.#L===`\x1B`&&(this.#R=setTimeout(()=>{this.#L===`\x1B`&&(this.#L=``,this.#I?.({type:`escape`}))},30),this.#R.unref?.())};#ge(){for(;this.#L.length>0;){let e=nextKey(this.#L);if(e.incomplete)return;this.#L=this.#L.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#I?.(e.key)}}#_e(){this.#R&&=(clearTimeout(this.#R),void 0)}#ve(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#Re();break;case`ctrl-c`:this.#j=!0,this.#B?.();break;default:break}}#ye(){this.#be(),this.#xe(),this.#P=setInterval(()=>{this.#M=!this.#M,this.#Re()},500),this.#P.unref?.()}#be(){this.#P&&=(clearInterval(this.#P),void 0),this.#M=!0}#xe(){this.#M=!0}#Se(){this.#Ce(),this.#F=setInterval(()=>{this.#N+=1,this.#Re()},90),this.#F.unref?.()}#Ce(){this.#F&&=(clearInterval(this.#F),void 0)}#we(e){this.#f.push(e),e.id&&this.#p.set(e.id,e)}#Te(e){this.#we({kind:`user`,body:e,live:!1}),this.#Re()}#Ee(e){if(e!=null){if(this.#Z===e){this.#Z=void 0;return}this.#we({kind:`user`,body:e,live:!1})}}#De(e,t,n){let r={kind:`error`,title:e,body:t,live:!1};n!==void 0&&(r.detail=n),this.#we(r),this.#Re()}#Oe(e,t){this.#_.has(e)||(this.#_.add(e),this.#we({id:subagentHeaderId(e),kind:`subagent`,title:t,live:!1}))}#ke(e){if(e.id&&this.#m.has(e.id))return;let t=e.id?this.#p.get(e.id):void 0;if(t){Object.assign(t,e);return}this.#we(e)}#Ae(e){this.#f=this.#f.filter(t=>t.id!==e),this.#p.delete(e)}#je(){for(let e of this.#f)e.status!==`approval`&&(e.live=!1)}#Me(e,t,n){switch(e.type){case`step-start`:this.#Ne(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#Le(e.usage),this.#Re();break;case`assistant-delta`:{this.#Ne(STATUS.streaming);let t=(n.text.get(e.id)??``)+e.delta;n.text.set(e.id,t),this.#Pe(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?e.text??``:t;n.text.set(e.id,r),this.#Pe(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;this.#Ne(STATUS.streaming);let r=(n.reasoning.get(e.id)??``)+e.delta;n.reasoning.set(e.id,r),this.#Fe(e.id,r,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#Fe(e.id,r,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#Ne(STATUS.executingTools),this.#Ie({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.#Ie({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;n.hasPendingToolResults=!0,this.#Ne(STATUS.toolResults),this.#Ie({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;n.hasPendingToolResults=!0,this.#Ne(STATUS.toolResults),this.#Ie({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#De(`Error`,e.errorText,e.detail);break;case`finish`:this.#Le(e.usage),this.#Re();break}}#Ne(e){let t=this.#x>0?STATUS.connectionAuth:e;this.#O!==t&&(this.#O=t,this.#Re())}#Pe(e,t,n){let r=t.trim();r.length!==0&&(this.#ke({id:e,kind:`assistant`,body:r,live:n}),this.#Re())}#Fe(e,t,n,r){let i=t.trim();i.length!==0&&(this.#ke({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#Re())}#Ie(e,t,n){if(n.tools.set(e.toolCallId,e),this.#h.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#g.set(e.toolCallId,r),this.#ke(renderNativeToolBlock(e,r,t.tools===`full`)),this.#Re()}#Le(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#U=(t??0)+(n??0)),this.#G=n??this.#G,this.#G!=null&&this.#q!==void 0){let e=(Date.now()-this.#q)/1e3;e>0&&(this.#K=this.#G/e)}}#Re(){if(this.#A){if(this.#V){this.#H=!0;return}this.#V=!0;try{do this.#H=!1,this.#ze();while(this.#H)}finally{this.#V=!1}}}#ze(){if(!this.#A)return;let e=this.#Ge(),t=this.#Ue(e),n=Math.max(1,this.#Ke()-t.length),r=[],i=this.#b;for(;this.#f.length>0&&this.#f[0].live===!1;){let t=this.#f.shift(),n=this.#Ve(t,e,i);i=previousBlockOf(t),this.#b=i,r.push(...n),t.id&&(this.#m.add(t.id),this.#p.delete(t.id))}let a=[];for(let t of this.#f){let n=this.#Ve(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)a.push({block:t,row:n[e]})}let o=[...clipLiveRows(a.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,o):this.#n.update(o)}#Be(){let e=this.#v;if(e===void 0)return[];let t={name:e.name,serverUrl:e.serverUrl,theme:this.#r,width:this.#Ge()};return e.info!==void 0&&(t.info=e.info),e.setupCommands!==void 0&&(t.setupCommands=e.setupCommands),buildAgentHeader(t)}#Ve(e,t,n){let r={spinner:this.#He()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#He(){return this.#r.spinner[this.#N%this.#r.spinner.length]??``}#Ue(e){let t=this.#r.colors,n=[``],r=this.#Q;if(r!==void 0){let t={title:r.title,lines:r.lines,frame:this.#He()};return r.question===void 0?(r.status!==void 0&&(t.status={text:r.status,frame:this.#He()}),r.preview!==void 0&&(t.preview=r.preview)):t.question=r.question(e),n.push(...renderFlowPanel(t,this.#r,e)),n}if(this.#T){this.#E!==void 0&&isTypeaheadOpen(this.#E)&&n.push(...renderCommandSuggestions(this.#E,this.#r,e));let r=Math.max(4,e-3),{before:i,after:a}=visibleLine({text:this.#S,cursor:this.#C},r,this.#r.glyph.ellipsis),o=isPromptControlCommand(this.#S),style=e=>o&&e.length>0?t.blue(e):e,c=this.#M?t.cyan(this.#r.glyph.caret):` `;return n.push(`${t.cyan(this.#r.glyph.prompt)} ${style(i)}${c}${style(a)}`),n}let i=this.#D?t.yellow(this.#He()):t.dim(this.#r.glyph.dot),a=this.#O.length>0?this.#O:`Ready`,o=this.#D?t.dim(a):a,c=this.#We(),l=c?`${i} ${o} ${t.dim(this.#r.glyph.dot)} ${c}`:`${i} ${o}`;return n.push(clip(l,e)),n}#We(){let e=this.#r.colors,t=[],n=formatTokenCount(this.#U,this.#W);n&&t.push(n);let r=formatAssistantResponseStats({totalTokens:this.#U,outputTokens:this.#G,tokensPerSecond:this.#K},this.#c);return r&&t.push(r),this.#D&&t.push(`Ctrl+C to interrupt`),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#Ge(){return Math.max(20,this.#t.columns||80)}#Ke(){return Math.max(8,this.#t.rows||24)}#qe(){if(this.#J!==void 0||!this.#u)return;this.#Y=``,this.#X=``;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.#Ye(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#J=()=>{e(),t()}}#Je(){let e=this.#J;e!==void 0&&(this.#J=void 0,e(),this.#Y.length>0&&(this.#Xe(`stdout`)&&process.stdout.write(`${this.#Y}\n`),this.#Y=``),this.#X.length>0&&(this.#Xe(`stderr`)&&process.stderr.write(`${this.#X}\n`),this.#X=``))}#Ye(e,t){let n=(e===`stdout`?this.#Y:this.#X)+t,r=n.lastIndexOf(`
3
+ `),a=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#Y=a:this.#X=a,r===-1||!this.#Xe(e))return;let o=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);o.trim().length!==0&&(this.#we({kind:`log`,title:e,body:o,live:!1}),this.#Re())}#Xe(e){switch(this.#d){case`none`:return!1;case`stderr`:return e===`stderr`;case`all`:return!0}}};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 visibleLength(e)>t?sliceVisible(e,t):e}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function leadsWithGap(e,t){if(e.kind===`log`&&t?.kind===`log`)return t.title!==e.title;if(t?.kind===`log`&&e.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`log`:case`command`:case`warning`:case`flow`:case`agent-header`:return!0;default:return!1}}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(n,r,i){let a={id:r,kind:`tool`,title:n.toolName,subtitle:summarizeToolArgs(n.input),status:n.status,live:n.status===`running`||n.status===`approval`,expanded:i,toolInput:n.input};return n.output===void 0?n.errorText!==void 0&&(a.result=n.errorText):(a.result=summarizeToolResult(n.output),a.toolOutput=n.output),a}function subagentToolStatus(e){switch(e){case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`}}function formatToolApprovalTitle(e){return 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 formatConnectionAuthContent(e){let t=[];e.description.length>0&&t.push(e.description);let n=e.challenge;return n?.url&&t.push(`URL: ${n.url}`),n?.userCode&&t.push(`Code: ${n.userCode}`),n?.expiresAt&&t.push(`Expires: ${n.expiresAt}`),n?.instructions&&t.push(n.instructions),e.reason!==void 0&&e.reason.length>0&&t.push(`Reason: ${e.reason}`),t.join(`
3
4
  `)}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=o.description?` ${r.dim(`— ${o.description}`)}`:``,s=t===e,c=s?`${r.cyan(n.glyph.pointer)} `:` `,l=s?r.cyan(o.label):o.label;i.push(`${c}${l}${a}`)}if(e.allowFreeform===!0){let e=t===a.length,o=e?`${r.cyan(n.glyph.pointer)} `:` `,s=`Type your own answer`;i.push(`${o}${e?r.cyan(s):r.dim(s)}`)}}else i.push(r.dim(` (type your answer)`));return i.join(`
4
5
  `)}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};
@@ -1,4 +1,3 @@
1
- import type { ClientOptions } from "#client/index.js";
2
1
  import type { TuiDisplayOptions } from "./types.js";
3
2
  /**
4
3
  * Options for running the `eve dev` terminal UI against a server URL.
@@ -16,13 +15,6 @@ export interface RunDevelopmentTuiInput extends TuiDisplayOptions {
16
15
  */
17
16
  readonly appRoot?: string;
18
17
  }
19
- /**
20
- * Builds the client options the `eve dev` TUI connects with, matching the
21
- * REPL's dev client: local hosts skip the Vercel OIDC bearer (the framework's
22
- * `localDev()` channel auth accepts unauthenticated calls); remote hosts
23
- * attach it alongside any protection-bypass headers resolved per request.
24
- */
25
- export declare function resolveDevTuiClientOptions(serverUrl: string): ClientOptions;
26
18
  /**
27
19
  * Runs the `eve dev` terminal UI against the given server URL until the
28
20
  * user exits.
@@ -1 +1 @@
1
- import{createPromptCommandHandler}from"./prompt-command-handler.js";import{EveTUIRunner}from"./runner.js";import{toErrorMessage}from"#shared/errors.js";import{isLocalDevelopmentServerUrl,resolveDevelopmentClientHeaders,resolveDevelopmentOidcToken}from"#services/dev-client/request-headers.js";import{formatVercelAuthChallengeMessage,isVercelAuthChallenge}from"#services/dev-client/vercel-auth-error.js";import{Client}from"#client/index.js";function resolveDevTuiClientOptions(e){let t={headers:()=>resolveDevelopmentClientHeaders({serverUrl:e}),host:e};return isLocalDevelopmentServerUrl(e)?t:{...t,auth:{bearer:resolveDevelopmentOidcToken}}}async function runDevelopmentTui(n){let{serverUrl:r,appRoot:i,...a}=n,o=new Client(resolveDevTuiClientOptions(r)),s={...a,session:o.session(),client:o,serverUrl:r,promptCommandHandler:createPromptCommandHandler({appRoot:i}),formatTransportError:e=>isVercelAuthChallenge(e)?formatVercelAuthChallengeMessage({serverUrl:r}):toErrorMessage(e)};i!==void 0&&(s.appRoot=i),await new EveTUIRunner(s).run()}export{resolveDevTuiClientOptions,runDevelopmentTui};
1
+ import{createPromptCommandHandler}from"./prompt-command-handler.js";import{EveTUIRunner}from"./runner.js";import{Client}from"#client/index.js";import{toErrorMessage}from"#shared/errors.js";import{resolveDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{formatVercelAuthChallengeMessage,isVercelAuthChallenge}from"#services/dev-client/vercel-auth-error.js";async function runDevelopmentTui(t){let{serverUrl:n,appRoot:r,...i}=t,a=new Client(resolveDevelopmentClientOptions(n)),o={...i,session:a.session(),client:a,serverUrl:n,promptCommandHandler:createPromptCommandHandler({appRoot:r}),formatTransportError:e=>isVercelAuthChallenge(e)?formatVercelAuthChallengeMessage({serverUrl:n}):toErrorMessage(e)};r!==void 0&&(o.appRoot=r),await new EveTUIRunner(o).run()}export{runDevelopmentTui};