Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): store dev diagnostics in a local per-process log (#881)

Rui65a7823a2884
diff --git a/.changeset/dev-diagnostics.md b/.changeset/dev-diagnostics.md
new file mode 100644
index 000000000..46e87ace4
--- /dev/null
+++ b/.changeset/dev-diagnostics.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`eve dev` now writes a private per-process diagnostic log under `.eve/logs/` capturing stderr, stdout (including sandbox and rebuild lines), tool failures, workflow errors, and eve framework log records (stored structured, with level, namespace, and JSON fields). The file is JSON Lines: every line is one JSON record with `at` and `source` fields. Long stderr output collapses in the transcript to a one-line summary pointing at the log file (the raw text stays available in the `all` log mode), and error details reference the log instead of flooding the transcript.
diff --git a/.changeset/dev-environment-dump.md b/.changeset/dev-environment-dump.md
new file mode 100644
index 000000000..d83a7d890
--- /dev/null
+++ b/.changeset/dev-environment-dump.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`eve dev` now writes an environment dump next to each diagnostic log (`.eve/logs/dev-<instance>.dump`): one JSON document capturing eve, Node.js, and Vercel CLI versions, the Vercel CLI path, local session-store size, and running session stats (prompts, token usage, tool calls by name, subagent dispatches). `eve logs --dump` prints the dump and its JSONL log together as one parseable report.
diff --git a/.changeset/dev-model-controls.md b/.changeset/dev-model-controls.md
new file mode 100644
index 000000000..ffce97dc0
--- /dev/null
+++ b/.changeset/dev-model-controls.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+The dev TUI's `/model` "Change model" row now opens a value menu — Model, Reasoning effort, Service tier, Done. Reasoning and tier adjust inline with `←`/`→` (Tab acts as `→`, both wrap as a ring): a `●─◉─○` track slides over the model's supported effort levels — snapping to the closest supported level when a pick changes what the model serves — and the tier flips between `fast ↯` and `normal`; the tier row disappears when the catalog prices no priority tier for the model. Enter on Model opens the searchable catalog as model ids on a `▏` rail — the same railed list component the team and project pickers now render with. All drafted changes commit through one atomic `agent.ts` edit. The provider picker marks and describes the currently-active provider and reports an accepted key as `AI_GATEWAY_API_KEY set.`. Linking an existing project now suggests the team project named after the agent, searching for it when it is not among the recents. Command cancellations now read "dismissed". The status line drops its `·` separators and shows the model as `slug@level ↯`.
diff --git a/.changeset/eve-logs-command.md b/.changeset/eve-logs-command.md
new file mode 100644
index 000000000..c3b0a063f
--- /dev/null
+++ b/.changeset/eve-logs-command.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+New `eve logs` command for reading the diagnostic logs `eve dev` writes under `.eve/logs/`: `eve logs` prints the most recent log, `eve logs ls [--json]` lists them, and `eve logs <logid>` prints a specific log by id, file name, transcript path, or unambiguous prefix.
diff --git a/.changeset/eve-logs-events.md b/.changeset/eve-logs-events.md
new file mode 100644
index 000000000..309f07048
--- /dev/null
+++ b/.changeset/eve-logs-events.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`eve logs --events` interleaves session events (session/turn/step lifecycle, message deltas) into the diagnostic-log output, resolved at query time from the local workflow store — nothing extra is written while `eve dev` runs.
diff --git a/.changeset/semantic-error-catalog.md b/.changeset/semantic-error-catalog.md
new file mode 100644
index 000000000..bad02f5b0
--- /dev/null
+++ b/.changeset/semantic-error-catalog.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Errors that escape a session — not just model-call failures — now pass through a semantic-error catalog: declarative, linter-style rules applied to any thrown error. Rules cover AI Gateway (auth, model-not-found, rate limits, upstream availability), model providers (missing API keys, unsupported capabilities), the durable workflow runtime (store version/access, replay divergence, corrupted event logs), sandbox backends (Docker CLI/daemon, provisioning), and system failures (port in use, disk full, network dials). Matched failures render a stable, actionable summary in the transcript with the raw error routed to the `eve dev` diagnostic log, and failure events carry a stable `semanticErrorId` for correlation.
diff --git a/apps/fixtures/agent-tui-client/agent/tools/always_fail.ts b/apps/fixtures/agent-tui-client/agent/tools/always_fail.ts
new file mode 100644
index 000000000..f46bc0df4
--- /dev/null
+++ b/apps/fixtures/agent-tui-client/agent/tools/always_fail.ts
@@ -0,0 +1,14 @@
+import { defineTool } from "eve/tools";
+import { never } from "eve/tools/approval";
+import { z } from "zod";
+
+export default defineTool({
+ approval: never(),
+ description: "Always throws. Exercises the tool-failure diagnostic path in the dev TUI.",
+ inputSchema: z.object({
+ reason: z.string().optional(),
+ }),
+ execute(input): never {
+ throw new Error(`always_fail: ${input.reason ?? "intentional failure for diagnostics"}`);
+ },
+});
diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.md
index bb08a7c55..655d34bee 100644
--- a/docs/guides/dev-tui.md
+++ b/docs/guides/dev-tui.md
@@ -24,7 +24,7 @@ The conversation streams straight into your terminal's normal scrollback, so you
Each turn renders without boxes. A colored gutter glyph marks who is speaking, tool calls collapse to a one-line summary (`✓ get_weather city="SF" → 73°F`), and a subagent's work is indented beneath its `◆` header. When input is ready, the prompt stays bare until you type. A green circle-dot pulses while the agent is waiting to answer and disappears when reasoning or answer content begins.
-A persistent line beneath the prompt or status shows the model, the session's token flow (`↑ 394.4K ↓ 4.3K`), the linked Vercel project, and a yellow `/deploy pending` marker once a channel added this session still needs `/deploy`. The Vercel segment stays hidden until the directory is linked. Local sessions lead with a gray `:port` badge. Remote sessions lead with a padded `↗ project (environment)` badge, or the host when Vercel cannot resolve the deployment. The badge is gray while checking or unavailable, yellow while authentication is required or failed, and blue when connected. Other status segments use `·` separators. Remote status lines omit AI Gateway endpoint state.
+A persistent line beneath the prompt or status shows the model — with its authored reasoning level and a `↯` marker when the Gateway priority tier is on (`xai/grok-4.5@xhigh ↯`) — the linked Vercel project, and a yellow `/deploy pending` marker once a channel added this session still needs `/deploy`. The Vercel segment stays hidden until the directory is linked. Local sessions lead with a gray `:port` badge. Remote sessions lead with a padded `↗ project (environment)` badge, or the host when Vercel cannot resolve the deployment. The badge is gray while checking or unavailable, yellow while authentication is required or failed, and blue when connected. Status segments separate with plain whitespace. Remote status lines omit AI Gateway endpoint state.
Errors render compactly with docs links highlighted. A code bug escaping your agent's own code shows its stack trace dim beneath the error headline. Dev-server rebuilds condense into one status row that updates in place (`tui/setup-panel.ts changed · rebuilding…`, then `· rebuilt`); only the latest rebuild shows, and paths shrink to their last two components.
@@ -49,9 +49,9 @@ Each command echoes as an invocation line, asks through a bordered panel that ta
### Configure the model and provider
-Bare `/model` opens the configure menu. When no provider is configured, it opens the provider picker directly and Esc returns to the configure menu. "Change model" runs the same searchable model picker setup uses (the Vercel AI Gateway catalog, pre-selected on the model the runtime is serving). A model change is written into your agent's authored source, and the command reports success only after eve confirms the new id. A completed model or provider change closes the menu and returns its result to the transcript; Done or Esc closes it without a change. `/model <provider/model-id>` applies one directly, skipping the menu.
+Bare `/model` opens the configure menu; its Change model row summarizes the draft (`xai/grok-4.5@high ↯`). When no provider is configured, it opens the provider picker directly and Esc returns to the configure menu. "Change model" opens a value menu — **Model**, **Reasoning effort** (a `●─◉─○` track beside the drafted level), **Service tier** (`fast ↯` or `normal`), and **Done**. Reasoning and tier adjust in place: `←`/`→` (Tab acts as `→`) move the highlighted row's value as a ring — past the top wraps to the bottom and vice versa — sliding the reasoning track over the model's supported effort levels or flipping the tier. An unset reasoning draft shows an empty track; the first `→` enters the ring at the lowest level, `←` at the highest. Picking a model snaps a drafted level the new model cannot serve to its closest supported one, clearing it when the model has no adjustable reasoning. Enter on the Model row opens the searchable Vercel AI Gateway catalog as `▏`-railed model ids, pre-selected on the model the runtime is serving; Esc backs out without changing it. A model with no adjustable reasoning says so on a disabled row, and a model the catalog prices no priority tier for shows no tier row at all. The menu's Done hands the draft to the configure menu, whose own Done commits everything through one atomic edit of your agent's authored source, reporting success only after eve confirms the new id. A completed model or provider change closes the menu and returns its result to the transcript; Done without changes or Esc closes it without one, and Esc notes any discarded draft. `/model <provider/model-id>` applies one directly, skipping the menu.
-The provider row opens one menu: AI Gateway via a project, AI Gateway via `AI_GATEWAY_API_KEY`, or **Other providers**. The key option becomes a masked input when highlighted. Enter validates it without replacing the menu. A rejected key shows a red `⨯ Invalid key` beside the masked value; retrying or editing clears that result. With a non-empty key, the first Esc or Ctrl-C clears the input and the second cancels the menu. An accepted key is saved to `.env.local`. The project option asks for a Vercel team, opens that team's recent projects, and lets you search all projects for older matches. Vercel links the selected project, eve verifies its project ID, then pulls its environment into `.env.local`. The **Other providers** option shows direct-provider wiring instructions and leaves the existing setup untouched. The dev server reloads env files and refreshes the status bar automatically, with no restart needed.
+The provider row opens one menu: AI Gateway via a project, AI Gateway via `AI_GATEWAY_API_KEY`, or **Other providers**. The currently-active provider renders checked with its status beneath it ("Linked to **my-project** in team **my-team**", or "`AI_GATEWAY_API_KEY` set in `.env.local`"), and the cursor opens on it with a `↵ change` badge. The key option becomes a masked input on an `⎿` rail when highlighted, with a `↵ validate` badge after it. Enter validates it without replacing the menu — a `▪ validating` badge while it checks, a red `⨯ API key is not valid` badge on rejection; retrying or editing clears that result. With a non-empty key, the first Esc or Ctrl-C clears the input and the second dismisses the menu. An accepted key is saved to `.env.local` and reported as one `AI_GATEWAY_API_KEY set.` line. The project option asks for a Vercel team, opens that team's recent projects with the project named after your agent suggested first (searching the team for it when it is not among the recents), and lets you search all projects for older matches. Vercel links the selected project, eve verifies its project ID, then pulls its environment into `.env.local`. The **Other providers** option shows direct-provider wiring instructions and leaves the existing setup untouched. The dev server reloads env files and refreshes the status bar automatically, with no restart needed.
The provider row demands attention (a bold yellow "Configure model access" with a yellow "Not configured" hint that dims when unselected and uses the terminal foreground when selected) until a link or gateway credential is detected, then names the connection afterward (for example "AI Gateway (Linked to my-project in my-team)"). Setup menus mark the cursor row with a padded, filled-arrow inverse label that inherits the row's accent: blue normally and yellow for warning rows. In stacked menus, the selected row's description appears directly beneath that option. The completed command's outcome stays in the transcript after the panel closes. When a turn fails because AI Gateway authentication is missing or stale, the error points you at `/model` directly.
@@ -100,6 +100,10 @@ By default, `eve dev` shows `stderr` and keeps stdout and sandbox lines buffered
- `--logs <all|stderr|sandbox|none>` sets the starting mode at launch (default `stderr`).
- `Ctrl+L` at the idle prompt cycles `none → all → stderr → sandbox → none`.
+Every captured line, tool failure, workflow error, and eve framework log record also lands in a private per-process diagnostic log under `.eve/logs/`, regardless of the display mode. The file is JSON Lines: each line is one JSON record with `at` and `source` fields (framework log records add `level`, `namespace`, `message`, and `fields`), so it parses with any JSONL tool — `jq -c 'select(.source=="tool")'` — even when a payload spans many stack-trace lines. Long stderr output collapses in the transcript to a one-line summary pointing at the file (the raw text stays available in the `all` mode). Read the logs with `eve logs` — see the [CLI reference](../reference/cli#eve-logs).
+
+Each log has a same-named `.dump` sibling — one JSON document with environment diagnostics (eve, Node.js, and Vercel CLI versions, the Vercel CLI path, and the size of the local session store) plus running session stats: prompts, token usage, tool calls by name, and subagent dispatches. `eve logs --dump` prints the dump and the log together as one parseable report to attach when filing an issue.
+
## Display flags
Density flags control how much of each section renders. They accept `full`, `collapsed`, `auto-collapsed`, or `hidden`.
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index 24f4ff469..c7729130b 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -1,6 +1,6 @@
---
title: "CLI"
-description: "Reference for every eve CLI command: init, info, build, start, dev, link, deploy, eval, channels, and extension."
+description: "Reference for every eve CLI command: init, info, build, start, dev, logs, link, deploy, eval, channels, and extension."
---
The `eve` binary (`bin: eve`) runs from your app root, and every command first loads `.env`/`.env.local` from that root. Running `eve` with no command runs `eve dev`.
@@ -15,6 +15,8 @@ The `eve` binary (`bin: eve`) runs from your app root, and every command first l
| `eve start` | Serve the built `.output/` app; prints the listening URL |
| `eve dev` | Start the local dev server and open the terminal UI |
| `eve dev <url>` | Connect the UI to an existing server URL (e.g. a remote deployment) instead of booting a local server |
+| `eve logs [logid]` | Print an `eve dev` diagnostic log (the most recent when `logid` is omitted) |
+| `eve logs ls` | List `eve dev` diagnostic logs, most recent first |
| `eve link` | Link the directory to a Vercel project and pull AI Gateway credentials |
| `eve deploy` | Deploy the agent to Vercel production (links first if needed) |
| `eve eval` | Run evals against the local app or a remote target |
@@ -173,6 +175,26 @@ Local dev records the last ready URL per resolved app root in `.eve/dev-server-s
Local dev keeps immutable runtime source snapshots under `.eve/dev-runtime/snapshots/` so in-flight turns hold a consistent code revision while new turns pick up rebuilds. The terminal REPL keeps its logical session across successful rebuilds, so the next turn continues the conversation on the latest generation; use `/new` to start a fresh session. After a generation is superseded, `eve dev` retains it for at least 30 minutes and also retains the five most recently superseded generations, regardless of the configured Workflow World. The active generation is never pruned. Old runtime snapshots and local sandbox templates are pruned in the background. For manual cleanup, stop `eve dev` before deleting `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/`. A turn that remains unfinished beyond the automatic retention window can no longer resume after its generation is pruned.
+## `eve logs`
+
+```bash
+eve logs # print the most recent diagnostic log
+eve logs ls # list logs, most recent first
+eve logs <logid> # print a specific log
+eve logs --dump # prepend the log's environment dump
+eve logs --events # interleave session events from the local workflow store
+```
+
+Each interactive `eve dev` process writes a private diagnostic log under `.eve/logs/` capturing stderr, stdout (including sandbox and rebuild lines), tool failures, workflow errors, and eve framework log records — regardless of what the transcript shows. The file is JSON Lines — every line is one JSON record with `at` and `source` fields. `eve logs` reads those files back.
+
+A log id is the file name without `.log` (for example `dev-2026-07-15T12-00-00.000Z-123`). `eve logs <logid>` also accepts the file name, the `.eve/logs/...` path printed in the dev transcript, or any unambiguous prefix of the id with or without the `dev-` lead — so `eve logs 2026-07-15` works when a single log matches. An ambiguous prefix fails and lists the candidates.
+
+`eve logs` prints nothing but records — no path banner on either stream — so `eve logs 2>&1 | jq -c .` always parses. Discover ids and file paths with `eve logs ls`; `eve logs ls --json` emits a machine-readable array with `id`, `path`, `startedAt`, and `sizeBytes`.
+
+`eve logs --events` resolves session events (`session.started`, `turn.failed`, message deltas, …) from the local workflow store (`.eve/.workflow-data`) at query time and interleaves them into the output by timestamp as `source: "event"` records — the log file itself never stores them, so nothing is duplicated at capture time. Selection is by the log's time window (its start through the next log's start), so events from concurrently running `eve dev` processes may appear.
+
+Each log has a same-named `.dump` sibling holding environment diagnostics and session stats as one JSON document. `eve logs --dump` (with or without a log id) prepends that document to the JSONL log body; the combined output is a valid JSON value stream (`eve logs --dump | jq -c .`), one self-contained report to attach to an issue. When a log has no dump, the flag is silently a no-op.
+
## `eve link`
```bash
diff --git a/packages/eve/src/cli/commands/logs-events.integration.test.ts b/packages/eve/src/cli/commands/logs-events.integration.test.ts
new file mode 100644
index 000000000..2e654ac64
--- /dev/null
+++ b/packages/eve/src/cli/commands/logs-events.integration.test.ts
@@ -0,0 +1,66 @@
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createWorld } from "#compiled/@workflow/world-local/index.js";
+import { resolveLocalWorkflowWorldDataDirectory } from "#internal/workflow/local-world-data-directory.js";
+
+import { readDevSessionEvents } from "./logs-events.js";
+
+describe("readDevSessionEvents", () => {
+ const roots: string[] = [];
+
+ afterEach(async () => {
+ await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
+ roots.length = 0;
+ });
+
+ it("returns an empty list without creating a store when none exists", async () => {
+ const root = await mkdtemp(join(tmpdir(), "eve-logs-events-"));
+ roots.push(root);
+
+ const events = await readDevSessionEvents(root, {
+ from: new Date(0),
+ to: new Date("2030-01-01T00:00:00.000Z"),
+ });
+
+ expect(events).toEqual([]);
+ await expect(
+ import("node:fs/promises").then(({ access }) =>
+ access(resolveLocalWorkflowWorldDataDirectory(root)),
+ ),
+ ).rejects.toMatchObject({ code: "ENOENT" });
+ });
+
+ it("skips runs without session streams via the listStreams prefilter", async () => {
+ // A hermetic happy-path test would need serde-encoded chunks, which only
+ // real workflow execution produces (`getWritable` is workflow-context
+ // only); the decode path is exercised against real stores by the TUI
+ // smoke flows. This pins the failure-mode invariants instead: a run with
+ // no session stream contributes nothing and costs a directory listing,
+ // not an idle-timeout wait.
+ const root = await mkdtemp(join(tmpdir(), "eve-logs-events-"));
+ roots.push(root);
+ const world = createWorld({ dataDir: resolveLocalWorkflowWorldDataDirectory(root) });
+ await world.events.create(null, {
+ eventType: "run_created",
+ eventData: {
+ deploymentId: "dpl_test",
+ workflowName: "turnWorkflow",
+ input: [],
+ },
+ });
+
+ const startedAt = Date.now();
+ const events = await readDevSessionEvents(root, {
+ from: new Date(startedAt - 60_000),
+ to: new Date(startedAt + 60_000),
+ });
+
+ expect(events).toEqual([]);
+ // The prefilter answers from storage; no stream is ever opened.
+ expect(Date.now() - startedAt).toBeLessThan(2_000);
+ });
+});
diff --git a/packages/eve/src/cli/commands/logs-events.ts b/packages/eve/src/cli/commands/logs-events.ts
new file mode 100644
index 000000000..8efeca642
--- /dev/null
+++ b/packages/eve/src/cli/commands/logs-events.ts
@@ -0,0 +1,196 @@
+import { access } from "node:fs/promises";
+
+import { resolveLocalWorkflowWorldDataDirectory } from "#internal/workflow/local-world-data-directory.js";
+
+const RUNS_PAGE_LIMIT = 100;
+/**
+ * How long a stream read may sit idle before the reader cancels it. A
+ * crashed `eve dev` never closes its run streams, so a live reader on
+ * such a stream would otherwise wait forever for the next chunk.
+ */
+const STREAM_IDLE_TIMEOUT_MS = 1_000;
+
+/**
+ * One session event read back from the local workflow store, shaped like a
+ * diagnostic-log line so `eve logs --events` output stays one uniform JSONL
+ * stream: `at` and `source` first, then the event identity and payload.
+ */
+export interface DevSessionEventLine {
+ readonly at: string;
+ readonly source: "event";
+ readonly runId: string;
+ readonly type: string;
+ readonly data?: unknown;
+}
+
+/** Time window (inclusive) of events to resolve, in wall-clock event time. */
+export interface DevSessionEventWindow {
+ readonly from: Date;
+ readonly to: Date;
+}
+
+/**
+ * Reads session events for one diagnostic-log window from the local
+ * workflow store (`.eve/.workflow-data`), at query time — nothing is
+ * duplicated at capture time.
+ *
+ * Runs are enumerated through the vendored Workflow World API and each
+ * run's default stream is decoded through `Run.getReadable()` — the same
+ * vendored read path the dev server uses to serve session streams over
+ * HTTP — never by touching the store's private chunk encoding. The world
+ * is opened for storage reads only: `start()` is never called, so queue
+ * redelivery cannot be triggered by a CLI read, and unclosed streams
+ * (crashed processes) are drained with an idle-timeout cancel instead of
+ * waiting for chunks that will never arrive.
+ *
+ * Returns an empty list when the store does not exist. Selection is by
+ * time window: events from any `eve dev` process in the window are
+ * included, since the store does not attribute runs to processes.
+ */
+export async function readDevSessionEvents(
+ appRoot: string,
+ window: DevSessionEventWindow,
+): Promise<DevSessionEventLine[]> {
+ const dataDir = resolveLocalWorkflowWorldDataDirectory(appRoot);
+ try {
+ await access(dataDir);
+ } catch {
+ // No local store yet; do not let createWorld scaffold one as a side
+ // effect of a read.
+ return [];
+ }
+
+ const { createWorld } = await import("#compiled/@workflow/world-local/index.js");
+ const runtime = await import("#internal/workflow/runtime.js");
+ const world = createWorld({ dataDir });
+ // `getRun` resolves its world through the runtime's process-global slot.
+ // A one-shot CLI owns that slot; restore nothing afterwards.
+ runtime.setWorld(world);
+
+ const lines: DevSessionEventLine[] = [];
+ for (const run of await listRunsOverlappingWindow(world, window)) {
+ const text = await drainRunStream(runtime, world, run.runId);
+ lines.push(...parseSessionEventLines(text, run, window));
+ }
+ return lines.sort((a, b) => a.at.localeCompare(b.at));
+}
+
+interface RunSummary {
+ readonly runId: string;
+ readonly createdAt: Date;
+ readonly updatedAt: Date;
+}
+
+type LocalWorld = ReturnType<
+ (typeof import("#compiled/@workflow/world-local/index.js"))["createWorld"]
+>;
+type WorkflowRuntime = typeof import("#internal/workflow/runtime.js");
+
+async function listRunsOverlappingWindow(
+ world: LocalWorld,
+ window: DevSessionEventWindow,
+): Promise<RunSummary[]> {
+ const overlapping: RunSummary[] = [];
+ let cursor: string | undefined;
+ do {
+ const page = await world.runs.list({
+ resolveData: "none",
+ pagination:
+ cursor === undefined ? { limit: RUNS_PAGE_LIMIT } : { cursor, limit: RUNS_PAGE_LIMIT },
+ });
+ for (const run of page.data) {
+ if (run.createdAt <= window.to && run.updatedAt >= window.from) {
+ overlapping.push({ runId: run.runId, createdAt: run.createdAt, updatedAt: run.updatedAt });
+ }
+ }
+ cursor = page.hasMore && page.cursor !== null ? page.cursor : undefined;
+ } while (cursor !== undefined);
+ return overlapping;
+}
+
+/**
+ * Reads a run's decoded session stream until it closes or sits idle for
+ * {@link STREAM_IDLE_TIMEOUT_MS}. Runs without a session stream (non-turn
+ * workflows — roughly half of a typical store) are skipped via a cheap
+ * `listStreams` lookup instead of each paying the full idle-timeout
+ * budget waiting on a stream that does not exist.
+ */
+async function drainRunStream(
+ runtime: WorkflowRuntime,
+ world: LocalWorld,
+ runId: string,
+): Promise<string> {
+ let text = "";
+ const decoder = new TextDecoder();
+ try {
+ const streams = await runtime.listStreams(world, runId);
+ if (!streams.some((name) => name === "user" || name.endsWith("_user"))) return "";
+ const reader = runtime
+ .getRun(runId)
+ .getReadable<string | Uint8Array>({ startIndex: 0 })
+ .getReader();
+ for (;;) {
+ const winner = await Promise.race([
+ reader.read(),
+ new Promise<"idle">((resolve) => {
+ setTimeout(() => resolve("idle"), STREAM_IDLE_TIMEOUT_MS);
+ }),
+ ]);
+ if (winner === "idle") {
+ await reader.cancel();
+ break;
+ }
+ if (winner.done) break;
+ text +=
+ typeof winner.value === "string"
+ ? winner.value
+ : decoder.decode(winner.value, { stream: true });
+ }
+ } catch {
+ return "";
+ }
+ return text;
+}
+
+function parseSessionEventLines(
+ text: string,
+ run: RunSummary,
+ window: DevSessionEventWindow,
+): DevSessionEventLine[] {
+ const lines: DevSessionEventLine[] = [];
+ for (const raw of text.split("\n")) {
+ const event = parseSessionEvent(raw);
+ if (event === undefined) continue;
+ const at = event.at ?? run.createdAt.toISOString();
+ if (at < window.from.toISOString() || at > window.to.toISOString()) continue;
+ const line: { -readonly [Key in keyof DevSessionEventLine]: DevSessionEventLine[Key] } = {
+ at,
+ source: "event",
+ runId: run.runId,
+ type: event.type,
+ };
+ if (event.data !== undefined) line.data = event.data;
+ lines.push(line);
+ }
+ return lines;
+}
+
+function parseSessionEvent(raw: string): { type: string; at?: string; data?: unknown } | undefined {
+ if (raw.trim().length === 0) return undefined;
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (parsed === null || typeof parsed !== "object") return undefined;
+ const { type, data, meta } = parsed as { type?: unknown; data?: unknown; meta?: unknown };
+ if (typeof type !== "string") return undefined;
+ const at =
+ meta !== null && typeof meta === "object" && typeof (meta as { at?: unknown }).at === "string"
+ ? (meta as { at: string }).at
+ : undefined;
+ const event: { type: string; at?: string; data?: unknown } = { type };
+ if (at !== undefined) event.at = at;
+ if (data !== undefined) event.data = data;
+ return event;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/packages/eve/src/cli/commands/logs.integration.test.ts b/packages/eve/src/cli/commands/logs.integration.test.ts
new file mode 100644
index 000000000..491c9a82a
--- /dev/null
+++ b/packages/eve/src/cli/commands/logs.integration.test.ts
@@ -0,0 +1,204 @@
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import {
+ listDevDiagnosticLogs,
+ resolveDevDiagnosticLog,
+ runLogsListCommand,
+ runLogsShowCommand,
+} from "./logs.js";
+
+const FIRST = "dev-2026-07-14T09-30-00.000Z-100.log";
+const SECOND = "dev-2026-07-15T12-00-00.000Z-123.log";
+
+function collectingLogger() {
+ const out: string[] = [];
+ const err: string[] = [];
+ return {
+ out,
+ err,
+ logger: {
+ log: (message: string) => out.push(message),
+ error: (message: string) => err.push(message),
+ },
+ };
+}
+
+describe("eve logs", () => {
+ const roots: string[] = [];
+
+ async function appRootWithLogs(files: Record<string, string>): Promise<string> {
+ const root = await mkdtemp(join(tmpdir(), "eve-logs-cmd-"));
+ roots.push(root);
+ const directory = join(root, ".eve", "logs");
+ await mkdir(directory, { recursive: true });
+ await Promise.all(
+ Object.entries(files).map(([name, content]) => writeFile(join(directory, name), content)),
+ );
+ return root;
+ }
+
+ afterEach(async () => {
+ await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
+ roots.length = 0;
+ });
+
+ it("lists logs most recent first with parsed start times", async () => {
+ const root = await appRootWithLogs({
+ [FIRST]: "older\n",
+ [SECOND]: "newer\n",
+ "not-a-log.txt": "ignored",
+ });
+
+ const logs = await listDevDiagnosticLogs(root);
+
+ expect(logs.map((log) => log.id)).toEqual([
+ "dev-2026-07-15T12-00-00.000Z-123",
+ "dev-2026-07-14T09-30-00.000Z-100",
+ ]);
+ expect(logs[0]!.startedAt?.toISOString()).toBe("2026-07-15T12:00:00.000Z");
+ expect(logs[0]!.sizeBytes).toBe(6);
+ });
+
+ it("returns an empty list when the log directory does not exist", async () => {
+ const root = await mkdtemp(join(tmpdir(), "eve-logs-cmd-"));
+ roots.push(root);
+ expect(await listDevDiagnosticLogs(root)).toEqual([]);
+ });
+
+ it("resolves ids, file names, transcript paths, and unambiguous prefixes", async () => {
+ const root = await appRootWithLogs({ [FIRST]: "a", [SECOND]: "b" });
+ const logs = await listDevDiagnosticLogs(root);
+
+ for (const reference of [
+ "dev-2026-07-15T12-00-00.000Z-123",
+ SECOND,
+ `.eve/logs/${SECOND}`,
+ "2026-07-15",
+ "dev-2026-07-15",
+ ]) {
+ expect(resolveDevDiagnosticLog(logs, reference).id).toBe("dev-2026-07-15T12-00-00.000Z-123");
+ }
+
+ expect(() => resolveDevDiagnosticLog(logs, "2026-07")).toThrow(/matches 2 diagnostic logs/);
+ expect(() => resolveDevDiagnosticLog(logs, "2030")).toThrow(/No diagnostic log matches/);
+ });
+
+ it("shows the most recent log by default and named logs by reference", async () => {
+ const root = await appRootWithLogs({ [FIRST]: "older content\n", [SECOND]: "newer content\n" });
+
+ const mru = collectingLogger();
+ await runLogsShowCommand(mru.logger, root);
+ expect(mru.out).toEqual(["newer content"]);
+ // Output carries records only: nothing on stderr, so `2>&1 | jq` parses.
+ expect(mru.err).toEqual([]);
+
+ const named = collectingLogger();
+ await runLogsShowCommand(named.logger, root, "2026-07-14");
+ expect(named.out).toEqual(["older content"]);
+ });
+
+ it("prepends the environment dump with --dump and falls back when it is absent", async () => {
+ const dump = '{\n "updatedAt": "2026-07-15T12:00:05.000Z",\n "environment": null\n}\n';
+ const root = await appRootWithLogs({
+ [FIRST]: "older content\n",
+ [SECOND]: '{"at":"2026-07-15T12:00:01.000Z","source":"stderr","detail":"newer content"}\n',
+ [SECOND.replace(/\.log$/, ".dump")]: dump,
+ });
+
+ const withDump = collectingLogger();
+ await runLogsShowCommand(withDump.logger, root, undefined, { dump: true });
+ expect(withDump.out).toEqual([
+ `${dump.trimEnd()}\n{"at":"2026-07-15T12:00:01.000Z","source":"stderr","detail":"newer content"}`,
+ ]);
+ expect(withDump.err).toEqual([]);
+
+ const missingDump = collectingLogger();
+ await runLogsShowCommand(missingDump.logger, root, "2026-07-14", { dump: true });
+ expect(missingDump.out).toEqual(["older content"]);
+ expect(missingDump.err).toEqual([]);
+ });
+
+ it("interleaves session events by timestamp with --events and stays silent when none match", async () => {
+ const logLine = (at: string, detail: string) =>
+ `${JSON.stringify({ at, source: "stderr", detail })}\n`;
+ const root = await appRootWithLogs({
+ [FIRST]: logLine("2026-07-14T09:31:00.000Z", "older"),
+ [SECOND]:
+ logLine("2026-07-15T12:00:10.000Z", "early") + logLine("2026-07-15T12:00:30.000Z", "late"),
+ });
+
+ const readEvents = vi.fn().mockResolvedValue([
+ {
+ at: "2026-07-15T12:00:20.000Z",
+ source: "event",
+ runId: "wrun_1",
+ type: "turn.started",
+ },
+ ]);
+ const withEvents = collectingLogger();
+ await runLogsShowCommand(withEvents.logger, root, undefined, {
+ events: true,
+ readEvents,
+ now: () => new Date("2026-07-15T13:00:00.000Z"),
+ });
+
+ // Window: this log's encoded start through `now` (it is the newest log).
+ expect(readEvents).toHaveBeenCalledWith(root, {
+ from: new Date("2026-07-15T12:00:00.000Z"),
+ to: new Date("2026-07-15T13:00:00.000Z"),
+ });
+ const lines = withEvents.out.join("\n").split("\n");
+ expect(lines.map((line) => (JSON.parse(line) as { at: string }).at)).toEqual([
+ "2026-07-15T12:00:10.000Z",
+ "2026-07-15T12:00:20.000Z",
+ "2026-07-15T12:00:30.000Z",
+ ]);
+ expect(withEvents.err).toEqual([]);
+
+ // Older log: window ends at the next log's start; zero events stay silent.
+ const older = collectingLogger();
+ const readNone = vi.fn().mockResolvedValue([]);
+ await runLogsShowCommand(older.logger, root, "2026-07-14", {
+ events: true,
+ readEvents: readNone,
+ });
+ expect(readNone).toHaveBeenCalledWith(root, {
+ from: new Date("2026-07-14T09:30:00.000Z"),
+ to: new Date("2026-07-15T12:00:00.000Z"),
+ });
+ expect(older.err).toEqual([]);
+ });
+
+ it("reports missing logs without failing, but fails for an explicit reference", async () => {
+ const root = await mkdtemp(join(tmpdir(), "eve-logs-cmd-"));
+ roots.push(root);
+
+ const bare = collectingLogger();
+ await runLogsShowCommand(bare.logger, root);
+ expect(bare.out).toEqual(["No dev diagnostic logs found under .eve/logs."]);
+
+ await expect(runLogsShowCommand(collectingLogger().logger, root, "2026")).rejects.toThrow(
+ /No dev diagnostic logs found/,
+ );
+ });
+
+ it("emits machine-readable rows for ls --json", async () => {
+ const root = await appRootWithLogs({ [SECOND]: "content" });
+
+ const { logger, out } = collectingLogger();
+ await runLogsListCommand(logger, root, { json: true });
+
+ expect(JSON.parse(out.join("\n"))).toEqual([
+ {
+ id: "dev-2026-07-15T12-00-00.000Z-123",
+ path: join(root, ".eve", "logs", SECOND),
+ startedAt: "2026-07-15T12:00:00.000Z",
+ sizeBytes: 7,
+ },
+ ]);
+ });
+});
diff --git a/packages/eve/src/cli/commands/logs.ts b/packages/eve/src/cli/commands/logs.ts
new file mode 100644
index 000000000..f1fd1329a
--- /dev/null
+++ b/packages/eve/src/cli/commands/logs.ts
@@ -0,0 +1,279 @@
+import { readdir, readFile, stat } from "node:fs/promises";
+import { basename, join } from "node:path";
+
+import {
+ readDevSessionEvents,
+ type DevSessionEventLine,
+ type DevSessionEventWindow,
+} from "./logs-events.js";
+
+interface CliLogsLogger {
+ error(message: string): void;
+ log(message: string): void;
+}
+
+const LOG_DIRECTORY_SEGMENTS = [".eve", "logs"] as const;
+const LOG_DISPLAY_DIRECTORY = LOG_DIRECTORY_SEGMENTS.join("/");
+const LOG_ID_PATTERN = /^dev-(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.\d{3}Z)-\d+\.log$/;
+
+/** One `eve dev` diagnostic log file under `.eve/logs`. */
+export interface DevDiagnosticLogEntry {
+ /** Stable reference: the file name without the `.log` extension. */
+ readonly id: string;
+ readonly path: string;
+ /** Process start time encoded in the file name, when parseable. */
+ readonly startedAt: Date | undefined;
+ readonly sizeBytes: number;
+}
+
+/**
+ * Lists `eve dev` diagnostic logs for an app root, most recent first. The
+ * sortable timestamp prefix in each file name provides the ordering; a missing
+ * log directory yields an empty list.
+ */
+export async function listDevDiagnosticLogs(appRoot: string): Promise<DevDiagnosticLogEntry[]> {
+ const directory = join(appRoot, ...LOG_DIRECTORY_SEGMENTS);
+ let names: string[];
+ try {
+ names = await readdir(directory);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
+ throw error;
+ }
+
+ const fileNames = names
+ .filter((name) => LOG_ID_PATTERN.test(name))
+ .sort()
+ .reverse();
+ return Promise.all(
+ fileNames.map(async (fileName) => {
+ const path = join(directory, fileName);
+ return {
+ id: fileName.slice(0, -".log".length),
+ path,
+ startedAt: parseStartedAt(fileName),
+ sizeBytes: (await stat(path)).size,
+ };
+ }),
+ );
+}
+
+function parseStartedAt(fileName: string): Date | undefined {
+ const match = LOG_ID_PATTERN.exec(fileName);
+ if (match === null) return undefined;
+ const iso = match[1]!.replace(/T(\d{2})-(\d{2})-(\d{2})/, "T$1:$2:$3");
+ const parsed = new Date(iso);
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;
+}
+
+/**
+ * Resolves a user-supplied log reference to one entry. Accepts the full id,
+ * the file name, the transcript's `.eve/logs/...` path, or any unambiguous
+ * prefix of the id (with or without the `dev-` lead).
+ */
+export function resolveDevDiagnosticLog(
+ logs: readonly DevDiagnosticLogEntry[],
+ reference: string,
+): DevDiagnosticLogEntry {
+ const name = basename(reference.replaceAll("\\", "/"));
+ const normalized = name.endsWith(".log") ? name.slice(0, -".log".length) : name;
+
+ const exact = logs.find((log) => log.id === normalized);
+ if (exact !== undefined) return exact;
+
+ const matches = logs.filter(
+ (log) => log.id.startsWith(normalized) || log.id.startsWith(`dev-${normalized}`),
+ );
+ if (matches.length === 1) return matches[0]!;
+ if (matches.length === 0) {
+ throw new Error(
+ `No diagnostic log matches "${reference}". Run \`eve logs ls\` to see available logs.`,
+ );
+ }
+ throw new Error(
+ [
+ `"${reference}" matches ${matches.length} diagnostic logs:`,
+ ...matches.map((log) => ` ${log.id}`),
+ "Pass a longer prefix or the full id.",
+ ].join("\n"),
+ );
+}
+
+/** Options accepted by {@link runLogsShowCommand}. */
+export interface LogsShowCommandOptions {
+ /** Prepend the log's environment dump (the same-instance `.dump` sibling). */
+ dump?: boolean;
+ /** Interleave session events resolved from the local workflow store. */
+ events?: boolean;
+ /** Injectable event reader and clock; defaults to the real store and `Date.now`. */
+ readEvents?: (appRoot: string, window: DevSessionEventWindow) => Promise<DevSessionEventLine[]>;
+ now?: () => Date;
+}
+
+/**
+ * `eve logs [logid]`: prints one diagnostic log to stdout — the most recent
+ * when `logid` is omitted. The output carries nothing but records (no
+ * resolved-path banner, no progress notes on either stream), so
+ * `eve logs 2>&1 | jq` always parses; discover ids and paths with
+ * `eve logs ls`. With `--dump`, the log's environment dump (a JSON
+ * document) is prepended to the JSONL log body, forming one
+ * self-contained, parseable report. With `--events`, session events are
+ * resolved from the local workflow store at query time — never duplicated
+ * into the log at capture time — and interleaved by timestamp as
+ * `source: "event"` records.
+ */
+export async function runLogsShowCommand(
+ logger: CliLogsLogger,
+ appRoot: string,
+ logId?: string,
+ options: LogsShowCommandOptions = {},
+): Promise<void> {
+ const logs = await listDevDiagnosticLogs(appRoot);
+ if (logs.length === 0) {
+ const message = `No dev diagnostic logs found under ${LOG_DISPLAY_DIRECTORY}.`;
+ if (logId !== undefined) throw new Error(message);
+ logger.log(message);
+ return;
+ }
+
+ const entry = logId === undefined ? logs[0]! : resolveDevDiagnosticLog(logs, logId);
+ let content = await readFile(entry.path, "utf8");
+
+ if (options.events === true) {
+ const window = eventWindowForLog(logs, entry, options.now ?? (() => new Date()));
+ const events = await (options.readEvents ?? readDevSessionEvents)(appRoot, window);
+ if (events.length > 0) {
+ content = mergeLogWithEvents(content, events);
+ }
+ }
+
+ if (options.dump !== true) {
+ logger.log(content.trimEnd());
+ return;
+ }
+
+ const dumpPath = entry.path.slice(0, -".log".length) + ".dump";
+ let dumpContent: string | undefined;
+ try {
+ dumpContent = await readFile(dumpPath, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ }
+ if (dumpContent === undefined) {
+ // No dump for this log (older instance, or the write failed): print the
+ // log alone, silently — same output as without the flag.
+ logger.log(content.trimEnd());
+ return;
+ }
+ // A JSON document followed by JSON Lines is one valid JSON value stream,
+ // so the combined output stays parseable end to end (`... | jq -c .`).
+ logger.log(`${dumpContent.trimEnd()}\n${content.trimEnd()}`);
+}
+
+/**
+ * The wall-clock window one diagnostic log covers: its encoded start time
+ * through the next log's start (logs are per-process and MRU-sorted), or
+ * `now` for the most recent log. The store does not attribute runs to
+ * processes, so window selection is by time; concurrent `eve dev`
+ * processes will see each other's events.
+ */
+function eventWindowForLog(
+ logs: readonly DevDiagnosticLogEntry[],
+ entry: DevDiagnosticLogEntry,
+ now: () => Date,
+): DevSessionEventWindow {
+ const index = logs.findIndex((log) => log.id === entry.id);
+ const nextStart = index > 0 ? logs[index - 1]!.startedAt : undefined;
+ return {
+ from: entry.startedAt ?? new Date(0),
+ to: nextStart ?? now(),
+ };
+}
+
+/**
+ * Interleaves event lines into the JSONL log by each record's `at`. Log
+ * lines keep their relative order; an unparseable line inherits its
+ * predecessor's timestamp so it cannot drift.
+ */
+function mergeLogWithEvents(content: string, events: readonly DevSessionEventLine[]): string {
+ const logLines: { at: string; line: string }[] = [];
+ let lastAt = "";
+ for (const line of content.split("\n")) {
+ if (line.trim().length === 0) continue;
+ try {
+ const at = (JSON.parse(line) as { at?: unknown }).at;
+ if (typeof at === "string") lastAt = at;
+ } catch {
+ // Keep position relative to the previous record.
+ }
+ logLines.push({ at: lastAt, line });
+ }
+
+ const eventLines = events.map((event) => ({ at: event.at, line: JSON.stringify(event) }));
+ const merged: string[] = [];
+ let logIndex = 0;
+ let eventIndex = 0;
+ while (logIndex < logLines.length || eventIndex < eventLines.length) {
+ const nextLog = logLines[logIndex];
+ const nextEvent = eventLines[eventIndex];
+ if (nextEvent === undefined || (nextLog !== undefined && nextLog.at <= nextEvent.at)) {
+ merged.push(nextLog!.line);
+ logIndex += 1;
+ } else {
+ merged.push(nextEvent.line);
+ eventIndex += 1;
+ }
+ }
+ return `${merged.join("\n")}\n`;
+}
+
+/** Options accepted by {@link runLogsListCommand}. */
+export interface LogsListCommandOptions {
+ /** Emit a machine-readable JSON array instead of the human listing. */
+ json?: boolean;
+}
+
+/** Machine-readable row emitted by `eve logs ls --json`. */
+export interface DevDiagnosticLogJson {
+ id: string;
+ path: string;
+ startedAt: string | null;
+ sizeBytes: number;
+}
+
+/** `eve logs ls`: lists diagnostic logs, most recent first. */
+export async function runLogsListCommand(
+ logger: CliLogsLogger,
+ appRoot: string,
+ options: LogsListCommandOptions = {},
+): Promise<void> {
+ const logs = await listDevDiagnosticLogs(appRoot);
+
+ if (options.json) {
+ const rows: DevDiagnosticLogJson[] = logs.map((log) => ({
+ id: log.id,
+ path: log.path,
+ startedAt: log.startedAt?.toISOString() ?? null,
+ sizeBytes: log.sizeBytes,
+ }));
+ logger.log(JSON.stringify(rows, null, 2));
+ return;
+ }
+
+ if (logs.length === 0) {
+ logger.log(`No dev diagnostic logs found under ${LOG_DISPLAY_DIRECTORY}.`);
+ return;
+ }
+
+ for (const log of logs) {
+ const started = log.startedAt?.toISOString() ?? "unknown start";
+ logger.log(`${log.id} ${started} ${formatSize(log.sizeBytes)}`);
+ }
+}
+
+function formatSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ const kib = bytes / 1024;
+ if (kib < 1024) return `${kib.toFixed(1)} KiB`;
+ return `${(kib / 1024).toFixed(1)} MiB`;
+}
diff --git a/packages/eve/src/cli/dev/diagnostic-dump.integration.test.ts b/packages/eve/src/cli/dev/diagnostic-dump.integration.test.ts
new file mode 100644
index 000000000..8b96aac1f
--- /dev/null
+++ b/packages/eve/src/cli/dev/diagnostic-dump.integration.test.ts
@@ -0,0 +1,132 @@
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ createDevDiagnosticDump,
+ measureSessionsDirectory,
+ type DevEnvironmentInfo,
+} from "./diagnostic-dump.js";
+
+const ENVIRONMENT: DevEnvironmentInfo = {
+ eveVersion: "0.9.9",
+ nodeVersion: "v24.0.0",
+ platform: "darwin arm64",
+ vercelCliVersion: "48.1.0",
+ vercelCliPath: "/usr/local/bin/vercel",
+ sessionsDirectory: { path: ".eve/.workflow-data", files: 12, bytes: 2048 },
+};
+
+describe("createDevDiagnosticDump", () => {
+ const roots: string[] = [];
+
+ afterEach(async () => {
+ await Promise.all(
+ roots.map((root) =>
+ rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }),
+ ),
+ );
+ roots.length = 0;
+ });
+
+ async function makeRoot(): Promise<string> {
+ const root = await mkdtemp(join(tmpdir(), "eve-dump-"));
+ roots.push(root);
+ await mkdir(join(root, ".eve", "logs"), { recursive: true });
+ return root;
+ }
+
+ it("derives the dump path from the log instance and writes environment + stats", async () => {
+ const root = await makeRoot();
+ const logPath = join(root, ".eve", "logs", "dev-2026-07-17T12-00-00.000Z-123.log");
+ let nowMs = new Date("2026-07-17T12:00:00.000Z").getTime();
+
+ const dump = createDevDiagnosticDump(root, logPath, {
+ environment: () => Promise.resolve(ENVIRONMENT),
+ now: () => new Date(nowMs),
+ });
+ // Let the environment collection promise settle its write.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ nowMs += 95_000;
+ dump.updateSessionStats({
+ prompts: 2,
+ inputTokens: 140,
+ outputTokens: 25,
+ toolCalls: { bash: 2, weather: 1 },
+ subagents: 1,
+ });
+ await dump.close();
+
+ expect(dump.path).toBe(join(root, ".eve", "logs", "dev-2026-07-17T12-00-00.000Z-123.dump"));
+ expect(dump.displayPath).toBe(".eve/logs/dev-2026-07-17T12-00-00.000Z-123.dump");
+ if (process.platform !== "win32") {
+ // POSIX permission bits only: Windows reports 0o666 and uses ACLs.
+ expect((await stat(dump.path)).mode & 0o777).toBe(0o600);
+ }
+
+ const content = await readFile(dump.path, "utf8");
+ expect(JSON.parse(content)).toEqual({
+ updatedAt: "2026-07-17T12:01:35.000Z",
+ durationMs: 95_000,
+ environment: ENVIRONMENT,
+ session: {
+ prompts: 2,
+ inputTokens: 140,
+ outputTokens: 25,
+ toolCalls: { bash: 2, weather: 1 },
+ subagents: 1,
+ },
+ });
+ });
+
+ it("keeps a pending marker when environment collection fails", async () => {
+ const root = await makeRoot();
+ const logPath = join(root, ".eve", "logs", "dev-2026-07-17T12-00-00.000Z-9.log");
+
+ const dump = createDevDiagnosticDump(root, logPath, {
+ environment: () => Promise.reject(new Error("no network")),
+ now: () => new Date("2026-07-17T12:00:00.000Z"),
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await dump.close();
+
+ expect(JSON.parse(await readFile(dump.path, "utf8"))).toMatchObject({
+ environment: null,
+ session: null,
+ });
+ });
+});
+
+describe("measureSessionsDirectory", () => {
+ const roots: string[] = [];
+
+ afterEach(async () => {
+ await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
+ roots.length = 0;
+ });
+
+ it("measures the local sessions directory when present", async () => {
+ const root = await mkdtemp(join(tmpdir(), "eve-dump-env-"));
+ roots.push(root);
+ const dataDir = join(root, ".eve", ".workflow-data", "runs");
+ await mkdir(dataDir, { recursive: true });
+ await writeFile(join(dataDir, "wrun_1.json"), "0123456789");
+ await writeFile(join(dataDir, "wrun_2.json"), "01234");
+
+ expect(await measureSessionsDirectory(root)).toEqual({
+ path: ".eve/.workflow-data",
+ files: 2,
+ bytes: 15,
+ });
+ });
+
+ it("returns undefined when the store does not exist yet", async () => {
+ const root = await mkdtemp(join(tmpdir(), "eve-dump-env-"));
+ roots.push(root);
+
+ expect(await measureSessionsDirectory(root)).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/cli/dev/diagnostic-dump.ts b/packages/eve/src/cli/dev/diagnostic-dump.ts
new file mode 100644
index 000000000..cdf3e70ec
--- /dev/null
+++ b/packages/eve/src/cli/dev/diagnostic-dump.ts
@@ -0,0 +1,228 @@
+import { access, readdir, stat, writeFile } from "node:fs/promises";
+import { constants } from "node:fs";
+import { delimiter, join, relative, sep } from "node:path";
+
+import { resolveInstalledPackageInfo } from "#internal/application/package.js";
+import { LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH } from "#internal/workflow/local-world-data-directory.js";
+import { captureVercel, resolveVercelInvocation } from "#setup/primitives/run-vercel.js";
+
+const VERCEL_VERSION_TIMEOUT_MS = 5_000;
+
+/**
+ * Environment facts captured once per `eve dev` process, written into the
+ * diagnostic dump so a shared log always travels with the toolchain state
+ * that produced it.
+ */
+export interface DevEnvironmentInfo {
+ readonly eveVersion: string;
+ readonly nodeVersion: string;
+ readonly platform: string;
+ readonly vercelCliVersion?: string;
+ readonly vercelCliPath?: string;
+ /** Local durable session store measurements; absent when the directory does not exist yet. */
+ readonly sessionsDirectory?: {
+ readonly path: string;
+ readonly files: number;
+ readonly bytes: number;
+ };
+}
+
+/**
+ * Aggregate counters for the TUI process's session activity. Reported by
+ * the renderer at each turn boundary so the dump stays current even if
+ * the process dies mid-session.
+ */
+export interface DevSessionStats {
+ readonly prompts: number;
+ readonly inputTokens: number;
+ readonly outputTokens: number;
+ /** Tool invocations observed, keyed by tool name. */
+ readonly toolCalls: Readonly<Record<string, number>>;
+ /** Distinct subagent dispatches that produced observable output. */
+ readonly subagents: number;
+}
+
+export interface DevDiagnosticDump {
+ readonly path: string;
+ /** Project-relative reference, forward slashes on every platform. */
+ readonly displayPath: string;
+ updateSessionStats(stats: DevSessionStats): void;
+ close(): Promise<void>;
+}
+
+export interface CreateDevDiagnosticDumpOptions {
+ /** Injectable environment collector; defaults to {@link collectDevEnvironmentInfo}. */
+ readonly environment?: () => Promise<DevEnvironmentInfo>;
+ readonly now?: () => Date;
+}
+
+/**
+ * Creates the environment dump paired with one dev diagnostic log: the same
+ * instance name with a `.dump` extension. The environment section is
+ * collected in the background and written as soon as it resolves; session
+ * stats rewrite the file on every update. Like the log sink, write failures
+ * disable the dump silently — never through stderr, which the TUI captures.
+ */
+export function createDevDiagnosticDump(
+ appRoot: string,
+ logPath: string,
+ options: CreateDevDiagnosticDumpOptions = {},
+): DevDiagnosticDump {
+ const path = logPath.replace(/\.log$/, ".dump");
+ const now = options.now ?? (() => new Date());
+ const startedAt = now().getTime();
+
+ let environment: DevEnvironmentInfo | undefined;
+ let stats: DevSessionStats | undefined;
+ let queue = Promise.resolve();
+ let failed = false;
+ let closed = false;
+
+ const write = () => {
+ if (closed || failed) return;
+ const content = formatDump({
+ at: now(),
+ durationMs: now().getTime() - startedAt,
+ environment,
+ stats,
+ });
+ queue = queue
+ .then(() => writeFile(path, content, { encoding: "utf8", mode: 0o600 }))
+ .catch(() => {
+ failed = true;
+ });
+ };
+
+ write();
+ void (options.environment ?? (() => collectDevEnvironmentInfo(appRoot)))()
+ .then((collected) => {
+ environment = collected;
+ write();
+ })
+ .catch(() => {
+ // Collection is best-effort; the dump keeps its pending marker.
+ });
+
+ return {
+ path,
+ displayPath: relative(appRoot, path).split(sep).join("/"),
+ updateSessionStats(next) {
+ stats = next;
+ write();
+ },
+ async close() {
+ if (closed) return;
+ write();
+ closed = true;
+ await queue;
+ },
+ };
+}
+
+/**
+ * One pretty-printed JSON document. `environment` is `null` until the
+ * background collection resolves; `session` is `null` until the first
+ * stats report. Parseable standalone (`jq . <file>.dump`) and, because a
+ * JSON document followed by JSON Lines is a valid JSON value stream,
+ * composable with the log by plain concatenation (`eve logs --dump`).
+ */
+function formatDump(input: {
+ readonly at: Date;
+ readonly durationMs: number;
+ readonly environment: DevEnvironmentInfo | undefined;
+ readonly stats: DevSessionStats | undefined;
+}): string {
+ const document = {
+ updatedAt: input.at.toISOString(),
+ durationMs: input.durationMs,
+ environment: input.environment ?? null,
+ session: input.stats ?? null,
+ };
+ return `${JSON.stringify(document, null, 2)}\n`;
+}
+
+/** Collects the real environment facts for {@link createDevDiagnosticDump}. */
+export async function collectDevEnvironmentInfo(appRoot: string): Promise<DevEnvironmentInfo> {
+ const [vercelCli, sessionsDirectory] = await Promise.all([
+ detectVercelCli(appRoot),
+ measureSessionsDirectory(appRoot),
+ ]);
+
+ const info: {
+ -readonly [Key in keyof DevEnvironmentInfo]: DevEnvironmentInfo[Key];
+ } = {
+ eveVersion: resolveInstalledPackageInfo().version,
+ nodeVersion: process.version,
+ platform: `${process.platform} ${process.arch}`,
+ ...vercelCli,
+ };
+ if (sessionsDirectory !== undefined) info.sessionsDirectory = sessionsDirectory;
+ return info;
+}
+
+async function detectVercelCli(
+ appRoot: string,
+): Promise<{ vercelCliVersion?: string; vercelCliPath?: string }> {
+ // `captureVercel` owns the invocation resolution, capture, and hard
+ // deadline; the invocation is re-resolved only to report which binary
+ // answered (a workspace-local install beats the PATH lookup).
+ const invocation = resolveVercelInvocation(appRoot);
+ const [result, path] = await Promise.all([
+ captureVercel(["--version"], {
+ cwd: appRoot,
+ nonInteractive: true,
+ timeoutMs: VERCEL_VERSION_TIMEOUT_MS,
+ }),
+ invocation.command === "vercel" ? findOnPath("vercel") : Promise.resolve(invocation.command),
+ ]);
+ const output = result.ok ? result.stdout : `${result.failure.stdout}\n${result.failure.stderr}`;
+ const version = /(\d+\.\d+\.\d+\S*)/.exec(output)?.[1];
+ const detected: { vercelCliVersion?: string; vercelCliPath?: string } = {};
+ if (version !== undefined) detected.vercelCliVersion = version;
+ if (path !== undefined) detected.vercelCliPath = path;
+ return detected;
+}
+
+async function findOnPath(executable: string): Promise<string | undefined> {
+ const entries = (process.env.PATH ?? "").split(delimiter).filter((entry) => entry.length > 0);
+ for (const entry of entries) {
+ const candidate = join(entry, executable);
+ try {
+ await access(candidate, constants.X_OK);
+ return candidate;
+ } catch {
+ // Not here; keep scanning.
+ }
+ }
+ return undefined;
+}
+
+/**
+ * Counts files and total bytes under the app's local durable session store
+ * (`.eve/.workflow-data`). Returns `undefined` when the directory does not
+ * exist yet.
+ */
+export async function measureSessionsDirectory(
+ appRoot: string,
+): Promise<DevEnvironmentInfo["sessionsDirectory"]> {
+ const directory = join(appRoot, LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH);
+ let entries;
+ try {
+ entries = await readdir(directory, { recursive: true, withFileTypes: true });
+ } catch {
+ return undefined;
+ }
+
+ let files = 0;
+ let bytes = 0;
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ files += 1;
+ try {
+ bytes += (await stat(join(entry.parentPath, entry.name))).size;
+ } catch {
+ // Entries can vanish while a live session compacts; count what remains.
+ }
+ }
+ return { path: LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH, files, bytes };
+}
diff --git a/packages/eve/src/cli/dev/diagnostic-sink.integration.test.ts b/packages/eve/src/cli/dev/diagnostic-sink.integration.test.ts
new file mode 100644
index 000000000..daf3fafbc
--- /dev/null
+++ b/packages/eve/src/cli/dev/diagnostic-sink.integration.test.ts
@@ -0,0 +1,86 @@
+import { mkdir, mkdtemp, readFile, rm, stat } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createDevDiagnosticSink } from "./diagnostic-sink.js";
+
+describe("createDevDiagnosticSink", () => {
+ const roots: string[] = [];
+
+ afterEach(async () => {
+ await Promise.all(
+ roots.map((root) =>
+ rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }),
+ ),
+ );
+ roots.length = 0;
+ });
+
+ it("creates a private per-process log and preserves append order", async () => {
+ const root = await mkdtemp(join(tmpdir(), "eve-diagnostics-"));
+ roots.push(root);
+ const sink = await createDevDiagnosticSink(root, {
+ now: () => new Date("2026-07-15T12:00:00.000Z"),
+ pid: 123,
+ });
+
+ sink.append({ source: "stderr", detail: "first\nwith a stack line" });
+ sink.append({ source: "workflow", summary: "failed", detail: "second" });
+ await sink.close();
+
+ expect(sink.displayPath).toBe(".eve/logs/dev-2026-07-15T12-00-00.000Z-123.log");
+ const content = await readFile(sink.path, "utf8");
+ expect(content.indexOf("first")).toBeLessThan(content.indexOf("second"));
+
+ // JSON Lines: one JSON object per line, `at` and `source` first.
+ const lines = content.trimEnd().split("\n");
+ expect(lines.map((line) => JSON.parse(line) as unknown)).toEqual([
+ {
+ at: "2026-07-15T12:00:00.000Z",
+ source: "stderr",
+ detail: "first\nwith a stack line",
+ },
+ {
+ at: "2026-07-15T12:00:00.000Z",
+ source: "workflow",
+ summary: "failed",
+ detail: "second",
+ },
+ ]);
+ expect(lines[0]!.startsWith('{"at":"2026-07-15T12:00:00.000Z","source":"stderr"')).toBe(true);
+ });
+
+ it.skipIf(process.platform === "win32")(
+ "restricts the log directory and file to the owner",
+ async () => {
+ // POSIX permission bits only: Windows reports 0o666 regardless of the
+ // modes passed to mkdir/open, and relies on ACLs instead.
+ const root = await mkdtemp(join(tmpdir(), "eve-diagnostics-"));
+ roots.push(root);
+ const sink = await createDevDiagnosticSink(root, {
+ now: () => new Date("2026-07-15T12:00:00.000Z"),
+ pid: 123,
+ });
+ await sink.close();
+
+ expect((await stat(join(root, ".eve", "logs"))).mode & 0o777).toBe(0o700);
+ expect((await stat(sink.path)).mode & 0o777).toBe(0o600);
+ },
+ );
+
+ it("uses exclusive creation for deterministic name collisions", async () => {
+ const root = await mkdtemp(join(tmpdir(), "eve-diagnostics-"));
+ roots.push(root);
+ await mkdir(join(root, ".eve"), { recursive: true });
+ const options = {
+ now: () => new Date("2026-07-15T12:00:00.000Z"),
+ pid: 123,
+ };
+ const first = await createDevDiagnosticSink(root, options);
+
+ await expect(createDevDiagnosticSink(root, options)).rejects.toMatchObject({ code: "EEXIST" });
+ await first.close();
+ });
+});
diff --git a/packages/eve/src/cli/dev/diagnostic-sink.ts b/packages/eve/src/cli/dev/diagnostic-sink.ts
new file mode 100644
index 000000000..61399074d
--- /dev/null
+++ b/packages/eve/src/cli/dev/diagnostic-sink.ts
@@ -0,0 +1,103 @@
+import { chmod, mkdir, open, type FileHandle } from "node:fs/promises";
+import { join, relative, sep } from "node:path";
+
+import type { LogLevel } from "#internal/logging.js";
+import type { JsonObject } from "#shared/json.js";
+
+export type DevDiagnosticSource = "stderr" | "stdout" | "sandbox" | "workflow" | "tool" | "log";
+
+/** Captured output or a failure summary attributed to one capture point. */
+export interface DevDiagnosticOutputEntry {
+ readonly source: Exclude<DevDiagnosticSource, "log">;
+ readonly summary?: string;
+ readonly detail: string;
+ /** Structured remediation carried by cataloged failures. */
+ readonly hint?: string;
+}
+
+/** One structured record from eve's own logger. */
+export interface DevDiagnosticLogRecordEntry {
+ readonly source: "log";
+ readonly level: LogLevel;
+ readonly namespace: string;
+ readonly message: string;
+ readonly fields?: JsonObject;
+}
+
+export type DevDiagnosticEntry = DevDiagnosticOutputEntry | DevDiagnosticLogRecordEntry;
+
+export interface DevDiagnosticSink {
+ readonly path: string;
+ /**
+ * Project-relative reference with forward slashes on every platform:
+ * it is a display and correlation token (transcript pointers,
+ * `eve logs <ref>` input), not a filesystem path.
+ */
+ readonly displayPath: string;
+ append(entry: DevDiagnosticEntry): void;
+ close(): Promise<void>;
+}
+
+export interface CreateDevDiagnosticSinkOptions {
+ readonly now?: () => Date;
+ readonly pid?: number;
+}
+
+/** Creates the local, process-owned diagnostics file used by `eve dev`. */
+export async function createDevDiagnosticSink(
+ appRoot: string,
+ options: CreateDevDiagnosticSinkOptions = {},
+): Promise<DevDiagnosticSink> {
+ const directory = join(appRoot, ".eve", "logs");
+ await mkdir(directory, { recursive: true, mode: 0o700 });
+ await chmod(directory, 0o700);
+
+ const now = options.now?.() ?? new Date();
+ const pid = options.pid ?? process.pid;
+ const timestamp = now.toISOString().replaceAll(":", "-");
+ const path = join(directory, `dev-${timestamp}-${pid}.log`);
+ const handle = await open(path, "wx", 0o600);
+ return createOpenSink(appRoot, path, handle, () => options.now?.() ?? new Date());
+}
+
+function createOpenSink(
+ appRoot: string,
+ path: string,
+ handle: FileHandle,
+ now: () => Date,
+): DevDiagnosticSink {
+ let queue = Promise.resolve();
+ let failed = false;
+ let closed = false;
+
+ return {
+ path,
+ displayPath: relative(appRoot, path).split(sep).join("/"),
+ append(entry) {
+ if (closed || failed) return;
+ const record = formatDiagnosticEntry(entry, now());
+ queue = queue
+ .then(() => handle.appendFile(record, "utf8"))
+ .catch(() => {
+ // Never report through stderr: the TUI captures it and would recurse.
+ failed = true;
+ });
+ },
+ async close() {
+ if (closed) return;
+ closed = true;
+ await queue;
+ await handle.close();
+ },
+ };
+}
+
+/**
+ * JSON Lines: each record is one JSON object per line, `at` and `source`
+ * first. Multi-line details (stack traces, inspector dumps) are escaped by
+ * the JSON encoding, so the line-per-record invariant holds and the whole
+ * file parses with any JSONL reader (`jq -c 'select(.source=="tool")'`).
+ */
+function formatDiagnosticEntry(entry: DevDiagnosticEntry, at: Date): string {
+ return `${JSON.stringify({ at: at.toISOString(), ...entry })}\n`;
+}
diff --git a/packages/eve/src/cli/dev/diagnostics.integration.test.ts b/packages/eve/src/cli/dev/diagnostics.integration.test.ts
new file mode 100644
index 000000000..0a74e85a4
--- /dev/null
+++ b/packages/eve/src/cli/dev/diagnostics.integration.test.ts
@@ -0,0 +1,107 @@
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { createLogger } from "#internal/logging.js";
+
+import { createDevDiagnostics } from "./diagnostics.js";
+
+const STUB_ENVIRONMENT = {
+ eveVersion: "0.0.0-test",
+ nodeVersion: process.version,
+ platform: "test",
+};
+
+describe("createDevDiagnostics", () => {
+ const roots: string[] = [];
+
+ afterEach(async () => {
+ await Promise.all(
+ roots.map((root) =>
+ rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }),
+ ),
+ );
+ roots.length = 0;
+ });
+
+ async function makeRecorder() {
+ const root = await mkdtemp(join(tmpdir(), "eve-diagnostics-recorder-"));
+ roots.push(root);
+ // Injected environment: the real collector spawns a `vercel --version`
+ // child whose lingering handle makes Windows tmp-dir cleanup flaky.
+ const diagnostics = await createDevDiagnostics(root, {
+ environment: () => Promise.resolve(STUB_ENVIRONMENT),
+ });
+ return { root, diagnostics };
+ }
+
+ it("persists subscribed log records structured, once, and releases the console", async () => {
+ const { root, diagnostics } = await makeRecorder();
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const displayed: string[] = [];
+ diagnostics.subscribeLogRecords((record) => displayed.push(record.message));
+
+ try {
+ createLogger("harness.tool-loop").error("tool execution failed", {
+ toolName: "always_fail",
+ });
+
+ // Structured, exactly once: the record reaches the sink and the
+ // display callback, never the console.
+ expect(displayed).toEqual(["tool execution failed"]);
+ expect(errorSpy).not.toHaveBeenCalled();
+
+ diagnostics.unsubscribeLogRecords();
+ createLogger("harness.tool-loop").error("after unsubscribe");
+ expect(displayed).toHaveLength(1);
+ expect(errorSpy).toHaveBeenCalledWith("[eve:harness.tool-loop] after unsubscribe");
+ } finally {
+ diagnostics.unsubscribeLogRecords();
+ errorSpy.mockRestore();
+ }
+
+ await diagnostics.close();
+ const log = await readFile(join(root, diagnostics.displayPath), "utf8");
+ const records = log
+ .trimEnd()
+ .split("\n")
+ .map((line) => JSON.parse(line) as Record<string, unknown>);
+ expect(records).toEqual([
+ expect.objectContaining({
+ source: "log",
+ level: "error",
+ namespace: "harness.tool-loop",
+ message: "tool execution failed",
+ fields: { toolName: "always_fail" },
+ }),
+ ]);
+ });
+
+ it("accumulates session stats and reports them into the dump", async () => {
+ const { root, diagnostics } = await makeRecorder();
+
+ diagnostics.recordPrompt();
+ diagnostics.recordStepUsage({ inputTokens: 100, outputTokens: 20 });
+ diagnostics.recordStepUsage({ inputTokens: 40, outputTokens: 5 });
+ diagnostics.recordStepUsage(undefined);
+ diagnostics.recordToolCall("bash");
+ diagnostics.recordToolCall("bash");
+ diagnostics.recordToolCall("weather");
+ diagnostics.recordSubagentDispatch("sub-1");
+ diagnostics.recordSubagentDispatch("sub-1");
+ diagnostics.reportStats();
+ await diagnostics.close();
+
+ const dumpPath = join(root, diagnostics.displayPath.replace(/\.log$/, ".dump"));
+ const dump = JSON.parse(await readFile(dumpPath, "utf8")) as { session: unknown };
+ expect(dump.session).toEqual({
+ prompts: 1,
+ inputTokens: 140,
+ outputTokens: 25,
+ toolCalls: { bash: 2, weather: 1 },
+ subagents: 1,
+ });
+ });
+});
diff --git a/packages/eve/src/cli/dev/diagnostics.ts b/packages/eve/src/cli/dev/diagnostics.ts
new file mode 100644
index 000000000..40363c2a2
--- /dev/null
+++ b/packages/eve/src/cli/dev/diagnostics.ts
@@ -0,0 +1,130 @@
+import { setLogRecordSubscriber, type LogRecord } from "#internal/logging.js";
+
+import {
+ createDevDiagnosticDump,
+ type CreateDevDiagnosticDumpOptions,
+ type DevDiagnosticDump,
+ type DevSessionStats,
+} from "./diagnostic-dump.js";
+import {
+ createDevDiagnosticSink,
+ type DevDiagnosticEntry,
+ type DevDiagnosticSink,
+} from "./diagnostic-sink.js";
+
+/**
+ * The one diagnostics recorder an `eve dev` process owns: the per-process
+ * JSONL log (sink), its environment dump, session-stats accumulation, and
+ * ownership of eve's structured log records. The TUI holds a single
+ * reference and calls in at its capture points; everything stateful about
+ * diagnostics lives here, not in the renderer.
+ */
+export interface DevDiagnostics {
+ /** Project-relative path of the diagnostic log, for transcript pointers. */
+ readonly displayPath: string;
+ /** Appends one captured record to the per-process diagnostic log. */
+ append(entry: DevDiagnosticEntry): void;
+ recordPrompt(): void;
+ recordStepUsage(usage: { inputTokens?: number; outputTokens?: number } | undefined): void;
+ recordToolCall(toolName: string): void;
+ recordSubagentDispatch(callId: string): void;
+ /** Rewrites the environment dump with the stats accumulated so far. */
+ reportStats(): void;
+ /**
+ * Takes ownership of eve's structured log records: each record is
+ * persisted to the log with its structure intact and then handed to
+ * `onRecord` for display. While subscribed, records never reach the
+ * console, so a host that also scrapes stderr sees each record exactly
+ * once.
+ */
+ subscribeLogRecords(onRecord: (record: LogRecord) => void): void;
+ unsubscribeLogRecords(): void;
+ close(): Promise<void>;
+}
+
+/**
+ * Creates the diagnostics recorder for one `eve dev` process: the
+ * exclusive per-process log plus its same-instance environment dump.
+ * Rejects when the log cannot be created (callers run without
+ * diagnostics rather than crash the TUI).
+ */
+export async function createDevDiagnostics(
+ appRoot: string,
+ options: CreateDevDiagnosticDumpOptions = {},
+): Promise<DevDiagnostics> {
+ const sink = await createDevDiagnosticSink(appRoot);
+ const dump = createDevDiagnosticDump(appRoot, sink.path, options);
+ return new DevDiagnosticsRecorder(sink, dump);
+}
+
+class DevDiagnosticsRecorder implements DevDiagnostics {
+ readonly displayPath: string;
+ readonly #sink: DevDiagnosticSink;
+ readonly #dump: DevDiagnosticDump;
+
+ #prompts = 0;
+ #inputTokens = 0;
+ #outputTokens = 0;
+ readonly #toolCalls = new Map<string, number>();
+ readonly #subagentCallIds = new Set<string>();
+
+ constructor(sink: DevDiagnosticSink, dump: DevDiagnosticDump) {
+ this.displayPath = sink.displayPath;
+ this.#sink = sink;
+ this.#dump = dump;
+ }
+
+ append(entry: DevDiagnosticEntry): void {
+ this.#sink.append(entry);
+ }
+
+ recordPrompt(): void {
+ this.#prompts += 1;
+ }
+
+ recordStepUsage(usage: { inputTokens?: number; outputTokens?: number } | undefined): void {
+ this.#inputTokens += usage?.inputTokens ?? 0;
+ this.#outputTokens += usage?.outputTokens ?? 0;
+ }
+
+ recordToolCall(toolName: string): void {
+ this.#toolCalls.set(toolName, (this.#toolCalls.get(toolName) ?? 0) + 1);
+ }
+
+ recordSubagentDispatch(callId: string): void {
+ this.#subagentCallIds.add(callId);
+ }
+
+ reportStats(): void {
+ const stats: DevSessionStats = {
+ prompts: this.#prompts,
+ inputTokens: this.#inputTokens,
+ outputTokens: this.#outputTokens,
+ toolCalls: Object.fromEntries(this.#toolCalls),
+ subagents: this.#subagentCallIds.size,
+ };
+ this.#dump.updateSessionStats(stats);
+ }
+
+ subscribeLogRecords(onRecord: (record: LogRecord) => void): void {
+ setLogRecordSubscriber((record) => {
+ const base = {
+ source: "log" as const,
+ level: record.level,
+ namespace: record.namespace,
+ message: record.message,
+ };
+ this.#sink.append(record.fields === undefined ? base : { ...base, fields: record.fields });
+ onRecord(record);
+ });
+ }
+
+ unsubscribeLogRecords(): void {
+ setLogRecordSubscriber(undefined);
+ }
+
+ async close(): Promise<void> {
+ await this.#dump.close();
+ await this.#sink.close();
+ }
+}
diff --git a/packages/eve/src/cli/dev/tui/blocks.ts b/packages/eve/src/cli/dev/tui/blocks.ts
index 7cc76bbf7..8a11397c0 100644
--- a/packages/eve/src/cli/dev/tui/blocks.ts
+++ b/packages/eve/src/cli/dev/tui/blocks.ts
@@ -66,6 +66,8 @@ export interface Block {
* rendered dim beneath the headline, capped to a handful of lines.
*/
detail?: string;
+ /** Structured remediation shown between an error's body and its detail. */
+ hint?: string;
/** Tool, connection, or synthetic command lifecycle status. */
status?: ToolStatus;
@@ -75,6 +77,8 @@ export interface Block {
collapsed?: boolean;
/** When true, expand tool input/output instead of summarizing. */
expanded?: boolean;
+ /** Captured-log visibility used for concise-vs-raw diagnostic replay. */
+ logVisibility?: "stderr-only" | "all-only";
/** Raw tool input / output for the expanded view. */
toolInput?: unknown;
toolOutput?: unknown;
@@ -312,6 +316,14 @@ function renderError(block: Block, width: number, theme: Theme): string[] {
for (const line of wrap(block.body ?? "", width - 2)) {
rows.push(` ${colorizeError(line, theme)}`);
}
+ if (block.hint !== undefined && block.hint.trim().length > 0) {
+ // Remediation renders distinct from the failure description: calm
+ // color, arrow lead-in, so "what to do" is scannable under "what broke".
+ for (const [index, line] of wrap(block.hint, width - 4).entries()) {
+ const lead = index === 0 ? `${theme.glyph.arrow} ` : " ";
+ rows.push(` ${theme.colors.cyan(`${lead}${line}`)}`);
+ }
+ }
rows.push(...renderErrorDetail(block.detail, width, theme));
return rows;
}
diff --git a/packages/eve/src/cli/dev/tui/diagnostic-presentation.test.ts b/packages/eve/src/cli/dev/tui/diagnostic-presentation.test.ts
new file mode 100644
index 000000000..12bc45687
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/diagnostic-presentation.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from "vitest";
+
+import { formatStoredDiagnostic, presentDiagnostic } from "./diagnostic-presentation.js";
+
+describe("presentDiagnostic", () => {
+ it("keeps short stderr inline", () => {
+ expect(presentDiagnostic("one line", ".eve/logs/dev.log")).toEqual({
+ kind: "inline",
+ text: "one line",
+ });
+ });
+
+ it("collapses long stacks to a summary and path", () => {
+ const presentation = presentDiagnostic(
+ ["Error: request failed", " at first", " at second", " at third", " at fourth"].join(
+ "\n",
+ ),
+ ".eve/logs/dev.log",
+ );
+
+ expect(presentation).toEqual({
+ kind: "stored",
+ summary: "Error: request failed",
+ omittedLines: 4,
+ path: ".eve/logs/dev.log",
+ });
+ if (presentation.kind === "stored") {
+ expect(formatStoredDiagnostic(presentation)).toContain("details: .eve/logs/dev.log");
+ }
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/diagnostic-presentation.ts b/packages/eve/src/cli/dev/tui/diagnostic-presentation.ts
new file mode 100644
index 000000000..1bb9900c4
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/diagnostic-presentation.ts
@@ -0,0 +1,44 @@
+const INLINE_DIAGNOSTIC_MAX_LINES = 4;
+const INLINE_DIAGNOSTIC_MAX_CHARACTERS = 600;
+const DIAGNOSTIC_SUMMARY_MAX_CHARACTERS = 240;
+
+export type DiagnosticPresentation =
+ | { readonly kind: "inline"; readonly text: string }
+ | {
+ readonly kind: "stored";
+ readonly summary: string;
+ readonly omittedLines: number;
+ readonly path: string;
+ };
+
+/** Chooses whether process diagnostics stay inline or collapse to the local sink. */
+export function presentDiagnostic(text: string, path: string): DiagnosticPresentation {
+ const lines = text.split("\n");
+ if (
+ lines.length <= INLINE_DIAGNOSTIC_MAX_LINES &&
+ text.length <= INLINE_DIAGNOSTIC_MAX_CHARACTERS
+ ) {
+ return { kind: "inline", text };
+ }
+
+ const first = lines.find((line) => line.trim().length > 0)?.trim() ?? "Diagnostic output";
+ const summary =
+ first.length <= DIAGNOSTIC_SUMMARY_MAX_CHARACTERS
+ ? first
+ : `${first.slice(0, DIAGNOSTIC_SUMMARY_MAX_CHARACTERS - 1)}…`;
+ return {
+ kind: "stored",
+ summary,
+ omittedLines: Math.max(0, lines.length - 1),
+ path,
+ };
+}
+
+export function formatStoredDiagnostic(
+ presentation: Extract<DiagnosticPresentation, { kind: "stored" }>,
+): string {
+ const count = presentation.omittedLines;
+ const omitted =
+ count === 0 ? "diagnostic details" : `${count} diagnostic line${count === 1 ? "" : "s"}`;
+ return `${presentation.summary}\n… ${omitted} · details: ${presentation.path}`;
+}
diff --git a/packages/eve/src/cli/dev/tui/errors.test.ts b/packages/eve/src/cli/dev/tui/errors.test.ts
index aa0d8e504..7e0273273 100644
--- a/packages/eve/src/cli/dev/tui/errors.test.ts
+++ b/packages/eve/src/cli/dev/tui/errors.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import type { StepFailedStreamEvent } from "#client/index.js";
-import { formatGatewayAuthFailureNotice, isGatewayAuthFailure } from "./errors.js";
+import { failureDetails, localFailureHint } from "./errors.js";
function stepFailed(
details?: Record<string, unknown>,
@@ -19,51 +19,45 @@ function stepFailed(
return { type: "step.failed", data } as StepFailedStreamEvent;
}
-describe("isGatewayAuthFailure", () => {
- it("matches the machine-readable gatewayName the harness merges into details", () => {
- expect(isGatewayAuthFailure(stepFailed({ gatewayName: "GatewayAuthenticationError" }))).toBe(
- true,
+describe("failureDetails", () => {
+ it("projects the structured catalog fields and drops everything else", () => {
+ const details = failureDetails(
+ stepFailed({
+ semanticErrorId: "gateway-auth-invalid-api-key",
+ hint: " Run `eve link`. ",
+ detail: "TypeError: boom\n at x",
+ gatewayName: "GatewayAuthenticationError",
+ }),
);
+ expect(details).toEqual({
+ semanticErrorId: "gateway-auth-invalid-api-key",
+ hint: "Run `eve link`.",
+ detail: "TypeError: boom\n at x",
+ });
});
- it("falls back to the config-summary name", () => {
- expect(isGatewayAuthFailure(stepFailed({ name: "AI Gateway authentication failed" }))).toBe(
- true,
- );
- });
-
- it("rejects other gateway errors and missing details", () => {
- expect(isGatewayAuthFailure(stepFailed({ gatewayName: "GatewayRateLimitError" }))).toBe(false);
- expect(isGatewayAuthFailure(stepFailed({ name: "Model provider API key missing" }))).toBe(
- false,
- );
- expect(isGatewayAuthFailure(stepFailed())).toBe(false);
+ it("returns an empty projection for missing or malformed details", () => {
+ expect(failureDetails(stepFailed())).toEqual({});
+ expect(failureDetails(stepFailed({ hint: " " }))).toEqual({});
});
});
-describe("formatGatewayAuthFailureNotice", () => {
- it("points a rejected API key at /model or the env file", () => {
- const notice = formatGatewayAuthFailureNotice(
- stepFailed({}, "AI Gateway rejected the provided API key. Update or unset…"),
- );
- expect(notice).toContain("rejected your AI_GATEWAY_API_KEY");
- expect(notice).toContain("/model");
- });
-
- it("points a rejected OIDC token at /model", () => {
- const notice = formatGatewayAuthFailureNotice(
- stepFailed({}, "AI Gateway rejected the OIDC token. Run `eve link`…"),
- );
- expect(notice).toContain("OIDC token");
- expect(notice).toContain("/model");
+describe("localFailureHint", () => {
+ it("swaps gateway-auth catalog ids for the in-session /model fix", () => {
+ for (const id of [
+ "gateway-auth-invalid-api-key",
+ "gateway-auth-invalid-oidc-token",
+ "gateway-auth-missing-credentials",
+ ]) {
+ const hint = localFailureHint(stepFailed({ semanticErrorId: id }));
+ expect(hint).toContain("/model");
+ }
});
- it("defaults to the missing-credentials line", () => {
- const notice = formatGatewayAuthFailureNotice(
- stepFailed({}, "AI Gateway received no credentials…"),
- );
- expect(notice).toBe(
- "There is no AI_GATEWAY_API_KEY set. Run /model to connect this to a project and refresh AI Gateway credentials, or set it manually in .env.local.",
- );
+ it("keeps the harness hint for every other failure", () => {
+ expect(
+ localFailureHint(stepFailed({ semanticErrorId: "network-request-failed" })),
+ ).toBeUndefined();
+ expect(localFailureHint(stepFailed())).toBeUndefined();
});
});
diff --git a/packages/eve/src/cli/dev/tui/errors.ts b/packages/eve/src/cli/dev/tui/errors.ts
index 0a1e3cf84..ab988395c 100644
--- a/packages/eve/src/cli/dev/tui/errors.ts
+++ b/packages/eve/src/cli/dev/tui/errors.ts
@@ -9,11 +9,6 @@ import type {
StepFailedStreamEvent,
TurnFailedStreamEvent,
} from "#client/index.js";
-import {
- GATEWAY_AUTH_FAILURE_SUMMARY_NAME,
- GATEWAY_AUTHENTICATION_ERROR_NAME,
-} from "#harness/model-call-error.js";
-
/**
* One of the failure events a session stream can carry. All three share the
* same `{ code, message, details? }` payload shape — the harness emits them
@@ -79,6 +74,39 @@ export function formatFailureMessage(event: FailureStreamEvent): string {
return `${code}: ${message}`;
}
+/**
+ * The structured fields the harness attaches to failure-event details:
+ * the semantic-error catalog's identity and remediation, plus the raw
+ * inspection dump for unrecognized failures. One projection so every
+ * consumer narrows the untyped `details` payload the same way.
+ */
+export interface FailureDetails {
+ readonly semanticErrorId?: string;
+ readonly hint?: string;
+ readonly detail?: string;
+}
+
+export function failureDetails(event: FailureStreamEvent): FailureDetails {
+ const details: unknown = event.data.details;
+ if (details === null || typeof details !== "object") return {};
+ const record = details as { semanticErrorId?: unknown; hint?: unknown; detail?: unknown };
+ const out: { -readonly [Key in keyof FailureDetails]: FailureDetails[Key] } = {};
+ if (typeof record.semanticErrorId === "string") out.semanticErrorId = record.semanticErrorId;
+ if (typeof record.hint === "string" && record.hint.trim().length > 0) {
+ out.hint = record.hint.trim();
+ }
+ if (typeof record.detail === "string") out.detail = record.detail;
+ return out;
+}
+
+/**
+ * Extracts the structured remediation hint attached to a failure event's
+ * details by the semantic-error catalog, if any.
+ */
+export function formatFailureHint(event: FailureStreamEvent): string | undefined {
+ return failureDetails(event).hint;
+}
+
/**
* Extracts the diagnostic dump attached to a failure event, if any.
*
@@ -89,48 +117,34 @@ export function formatFailureMessage(event: FailureStreamEvent): string {
* `undefined` for them and the headline stands alone.
*/
export function formatFailureDetail(event: FailureStreamEvent): string | undefined {
- const details: unknown = event.data.details;
- if (details === null || typeof details !== "object") return undefined;
- const detail = (details as { detail?: unknown }).detail;
- if (typeof detail !== "string") return undefined;
+ const detail = failureDetails(event).detail;
+ if (detail === undefined) return undefined;
const trimmed = detail.trim();
if (trimmed.length === 0 || trimmed === event.data.message.trim()) return undefined;
return trimmed;
}
/**
- * Minimal TUI rendering for a gateway-auth failure when `/model` is available
- * locally. Replaces the harness's full summary — whose remediation names CLI
- * commands and dashboard URLs — with one actionable line; the caller drops
- * the diagnostic detail along with it. The variant is picked off the summary
- * message the harness wrote, so a stale key, an expired OIDC token, and
- * missing credentials each get the fix that actually applies.
+ * Local-TUI hints keyed by the semantic-error catalog id the harness
+ * writes into failure details. When the failing setup can be fixed from
+ * inside the session, the catalog's hint — which names CLI commands and
+ * dashboard URLs — is replaced with the in-session fix.
*/
-export function formatGatewayAuthFailureNotice(event: FailureStreamEvent): string {
- const message = event.data.message;
- if (/rejected the provided API key|Invalid API key/i.test(message)) {
- return "AI Gateway rejected your AI_GATEWAY_API_KEY. Run /model to refresh credentials, or update it in .env.local (a stale shell export can shadow it).";
- }
- if (/rejected the OIDC token|Invalid OIDC token/i.test(message)) {
- return "Your AI Gateway OIDC token is invalid or expired. Run /model to refresh it, or set AI_GATEWAY_API_KEY in .env.local.";
- }
- return "There is no AI_GATEWAY_API_KEY set. Run /model to connect this to a project and refresh AI Gateway credentials, or set it manually in .env.local.";
-}
+const LOCAL_HINT_OVERRIDES: Readonly<Record<string, string>> = {
+ "gateway-auth-invalid-api-key":
+ "Run /model to refresh credentials, or update AI_GATEWAY_API_KEY in .env.local (a stale shell export can shadow it).",
+ "gateway-auth-invalid-oidc-token":
+ "Run /model to refresh the OIDC token, or set AI_GATEWAY_API_KEY in .env.local.",
+ "gateway-auth-missing-credentials":
+ "Run /model to connect this to a project and refresh AI Gateway credentials, or set AI_GATEWAY_API_KEY manually in .env.local.",
+};
/**
- * Recognizes a model-call failure caused by AI Gateway authentication. The
- * primary signal is the machine-readable `gatewayName` the harness merges
- * into every model-call failure's details (`extractModelCallErrorDetails`);
- * the summary name is the fallback for payloads whose gateway error was not
- * preserved on the cause chain. Both identifiers are imported from the
- * harness module that writes them, so the two sides cannot drift.
+ * The surface-local hint for a failure, when the TUI can offer a better
+ * fix than the catalog's (currently: gateway credential failures resolve
+ * in-session via `/model`). Returns `undefined` to keep the harness hint.
*/
-export function isGatewayAuthFailure(event: FailureStreamEvent): boolean {
- const details: unknown = event.data.details;
- if (details === null || typeof details !== "object") return false;
- const record = details as { gatewayName?: unknown; name?: unknown };
- return (
- record.gatewayName === GATEWAY_AUTHENTICATION_ERROR_NAME ||
- record.name === GATEWAY_AUTH_FAILURE_SUMMARY_NAME
- );
+export function localFailureHint(event: FailureStreamEvent): string | undefined {
+ const id = failureDetails(event).semanticErrorId;
+ return id === undefined ? undefined : LOCAL_HINT_OVERRIDES[id];
}
diff --git a/packages/eve/src/cli/dev/tui/model-editor.test.ts b/packages/eve/src/cli/dev/tui/model-editor.test.ts
new file mode 100644
index 000000000..07fdd5657
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/model-editor.test.ts
@@ -0,0 +1,472 @@
+import { describe, expect, it } from "vitest";
+
+import type { GatewayModelCapabilities } from "#setup/boxes/model-capabilities.js";
+import type { ModelSettingsRequest } from "#setup/flows/model.js";
+
+import {
+ initialModelEditorState,
+ modelEditorMenuRows,
+ reasoningPositions,
+ transitionModelEditor,
+ type ModelEditorEvent,
+ type ModelEditorState,
+} from "./model-editor.js";
+
+const OPTIONS = [
+ {
+ id: "anthropic/claude-sonnet-5",
+ value: "anthropic/claude-sonnet-5",
+ label: "Claude Sonnet 5",
+ hint: "Anthropic",
+ featured: true,
+ },
+ { id: "xai/grok-4.5", value: "xai/grok-4.5", label: "Grok 4.5", hint: "xAI" },
+ { id: "test/no-frills", value: "test/no-frills", label: "No Frills", hint: "Test" },
+] as const;
+
+const CAPABILITIES: Record<string, GatewayModelCapabilities> = {
+ "anthropic/claude-sonnet-5": {
+ reasoning: true,
+ reasoningLevels: ["none", "minimal", "low", "medium", "high", "xhigh"],
+ fastMode: true,
+ },
+ "xai/grok-4.5": { reasoning: true, reasoningLevels: ["low", "high"], fastMode: true },
+ "test/no-frills": { reasoning: false, reasoningLevels: [], fastMode: false },
+};
+
+function request(overrides: Partial<ModelSettingsRequest> = {}): ModelSettingsRequest {
+ return {
+ model: { kind: "pick", options: [...OPTIONS], current: "anthropic/claude-sonnet-5" },
+ reasoning: null,
+ serviceTier: { kind: "standard" },
+ settingsEditable: true,
+ externalRouting: false,
+ capabilitiesFor: (modelId) => (modelId === null ? undefined : CAPABILITIES[modelId]),
+ ...overrides,
+ };
+}
+
+/** Applies events in order, asserting none of them settles or cancels. */
+function drive(
+ req: ModelSettingsRequest,
+ state: ModelEditorState,
+ events: ModelEditorEvent[],
+): ModelEditorState {
+ let current = state;
+ for (const event of events) {
+ const transition = transitionModelEditor(current, event, req);
+ if (transition.kind !== "render" && transition.kind !== "ignore") {
+ throw new Error(`Unexpected ${transition.kind} transition for ${JSON.stringify(event)}`);
+ }
+ current = transition.state;
+ }
+ return current;
+}
+
+describe("initialModelEditorState", () => {
+ it("opens the menu on the Model row with the draft seeded from authored values", () => {
+ const req = request({ reasoning: "high", serviceTier: { kind: "priority" } });
+ const state = initialModelEditorState(req);
+
+ expect(state.screen).toEqual({ kind: "menu", cursor: "model" });
+ expect(state.draft).toEqual({
+ modelId: "anthropic/claude-sonnet-5",
+ reasoning: "high",
+ tier: "priority",
+ });
+ expect(state.capabilities?.reasoning).toBe(true);
+ });
+
+ it("opens a fixed-model menu on the first pickable row", () => {
+ const req = request({
+ model: { kind: "fixed", current: "anthropic/claude-sonnet-5", reason: "SDK model call" },
+ });
+ expect(initialModelEditorState(req).screen).toEqual({ kind: "menu", cursor: "reasoning" });
+ });
+
+ it("lands on Done when a fixed no-frills model disables everything else", () => {
+ const req = request({
+ model: { kind: "fixed", current: "test/no-frills", reason: "SDK model call" },
+ });
+ expect(initialModelEditorState(req).screen).toEqual({ kind: "menu", cursor: "done" });
+ });
+});
+
+describe("modelEditorMenuRows", () => {
+ it("derives pickable rows for a fully-capable pick", () => {
+ const state = initialModelEditorState(request());
+ const rows = modelEditorMenuRows(request(), state.draft, state.capabilities);
+ expect(rows.map((row) => [row.value, row.disabled ?? false])).toEqual([
+ ["model", false],
+ ["reasoning", false],
+ ["tier", false],
+ ["done", false],
+ ]);
+ });
+
+ it("disables the model row for an SDK model call, carrying the reason", () => {
+ const req = request({
+ model: { kind: "fixed", current: "anthropic/claude-sonnet-5", reason: "SDK model call" },
+ });
+ const state = initialModelEditorState(req);
+ expect(modelEditorMenuRows(req, state.draft, state.capabilities)[0]).toEqual({
+ value: "model",
+ label: "Model",
+ disabled: true,
+ description: "SDK model call",
+ });
+ });
+
+ it("disables reasoning with its explanation and omits the tier for a no-frills model", () => {
+ const req = request({
+ model: { kind: "pick", options: [...OPTIONS], current: "test/no-frills" },
+ });
+ const state = initialModelEditorState(req);
+ const rows = modelEditorMenuRows(req, state.draft, state.capabilities);
+ expect(rows.map((row) => row.value)).toEqual(["model", "reasoning", "done"]);
+ expect(rows[1]).toMatchObject({
+ disabled: true,
+ description: "Not supported by the selected model",
+ });
+ });
+
+ it("keeps a static tier row for custom tiers and external routing", () => {
+ const state = initialModelEditorState(request());
+ const custom = modelEditorMenuRows(
+ request({ serviceTier: { kind: "custom", value: "flex" } }),
+ state.draft,
+ state.capabilities,
+ );
+ expect(custom.find((row) => row.value === "tier")).toMatchObject({
+ disabled: true,
+ description: "Custom (flex) — authored in agent.ts",
+ });
+
+ const external = modelEditorMenuRows(
+ request({ externalRouting: true }),
+ state.draft,
+ state.capabilities,
+ );
+ expect(external.find((row) => row.value === "tier")).toMatchObject({
+ disabled: true,
+ description: "Disabled for a direct external provider",
+ });
+ });
+});
+
+describe("reasoningPositions", () => {
+ it("orders notches as the supported levels, inserting a drafted stray", () => {
+ expect(reasoningPositions(CAPABILITIES["xai/grok-4.5"], "medium")).toEqual([
+ "low",
+ "medium",
+ "high",
+ ]);
+ });
+
+ it("offers every level when the catalog does not know the model", () => {
+ expect(reasoningPositions(undefined, "default")).toEqual([
+ "none",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ ]);
+ });
+});
+
+describe("menu screen", () => {
+ it("moves the cursor with wrap while skipping disabled rows", () => {
+ const req = request({
+ model: { kind: "pick", options: [...OPTIONS], current: "test/no-frills" },
+ });
+ let state = initialModelEditorState(req);
+ // Rows: model / reasoning(disabled) / done — down skips the disabled row.
+ state = drive(req, state, [{ type: "move", direction: "down" }]);
+ expect(state.screen).toEqual({ kind: "menu", cursor: "done" });
+ state = drive(req, state, [{ type: "move", direction: "down" }]);
+ expect(state.screen).toEqual({ kind: "menu", cursor: "model" });
+ });
+
+ it("cancels straight out from the menu", () => {
+ const req = request();
+ expect(transitionModelEditor(initialModelEditorState(req), { type: "cancel" }, req)).toEqual({
+ kind: "cancel",
+ });
+ });
+
+ it("opens the model list on Enter and walks past inline rows instead", () => {
+ const req = request({ reasoning: "high", serviceTier: { kind: "priority" } });
+ const state = initialModelEditorState(req);
+
+ const model = transitionModelEditor(state, { type: "submit" }, req);
+ expect(model.kind).toBe("render");
+ if (model.kind !== "render") return;
+ expect(model.state.screen.kind).toBe("model");
+
+ // Enter on an inline value row is just a downward step.
+ const onReasoning = drive(req, state, [{ type: "move", direction: "down" }]);
+ const stepped = drive(req, onReasoning, [{ type: "submit" }]);
+ expect(stepped.screen).toEqual({ kind: "menu", cursor: "tier" });
+ expect(stepped.draft.reasoning).toBe("high");
+ });
+});
+
+describe("model sub-screen", () => {
+ it("filters, clears the filter on Esc, and returns to the menu on a second Esc", () => {
+ const req = request();
+ let state = drive(req, initialModelEditorState(req), [{ type: "submit" }]);
+ state = drive(req, state, [
+ { type: "char", char: "g" },
+ { type: "char", char: "r" },
+ ]);
+ expect(state.screen.kind === "model" && state.screen.select.filter).toBe("gr");
+
+ state = drive(req, state, [{ type: "cancel" }]);
+ expect(state.screen.kind === "model" && state.screen.select.filter).toBe("");
+
+ state = drive(req, state, [{ type: "cancel" }]);
+ expect(state.screen).toEqual({ kind: "menu", cursor: "model" });
+ // Esc changed nothing.
+ expect(state.draft.modelId).toBe("anthropic/claude-sonnet-5");
+ });
+
+ it("commits a pick into the draft, recomputes capabilities, and returns to the menu", () => {
+ const req = request();
+ let state = drive(req, initialModelEditorState(req), [
+ { type: "submit" },
+ { type: "char", char: "grok" },
+ ]);
+ state = drive(req, state, [{ type: "submit" }]);
+
+ expect(state.screen).toEqual({ kind: "menu", cursor: "model" });
+ expect(state.draft.modelId).toBe("xai/grok-4.5");
+ expect(state.capabilities?.reasoningLevels).toEqual(["low", "high"]);
+ });
+
+ it("snaps a drafted level the picked model cannot serve to its closest supported one", () => {
+ const req = request({ reasoning: "xhigh" });
+ let state = drive(req, initialModelEditorState(req), [
+ { type: "submit" },
+ { type: "char", char: "grok" },
+ { type: "submit" },
+ ]);
+ // grok supports only low/high: xhigh lands on high, not a stray notch.
+ expect(state.draft.reasoning).toBe("high");
+
+ // A model with no adjustable reasoning clears the level entirely.
+ state = drive(req, state, [
+ { type: "submit" },
+ { type: "char", char: "frills" },
+ { type: "submit" },
+ ]);
+ expect(state.draft.reasoning).toBe("default");
+ });
+
+ it("keeps a supported drafted level and an unset draft across picks", () => {
+ const req = request({ reasoning: "low" });
+ const state = drive(req, initialModelEditorState(req), [
+ { type: "submit" },
+ { type: "char", char: "grok" },
+ { type: "submit" },
+ ]);
+ expect(state.draft.reasoning).toBe("low");
+
+ const unset = request();
+ const picked = drive(unset, initialModelEditorState(unset), [
+ { type: "submit" },
+ { type: "char", char: "frills" },
+ { type: "submit" },
+ ]);
+ expect(picked.draft.reasoning).toBe("default");
+ });
+
+ it("ignores submit when the filter matches nothing", () => {
+ const req = request();
+ const state = drive(req, initialModelEditorState(req), [
+ { type: "submit" },
+ { type: "char", char: "zzz" },
+ ]);
+ expect(transitionModelEditor(state, { type: "submit" }, req).kind).toBe("ignore");
+ });
+});
+
+describe("inline reasoning adjust", () => {
+ function onReasoning(req: ModelSettingsRequest): ModelEditorState {
+ return drive(req, initialModelEditorState(req), [{ type: "move", direction: "down" }]);
+ }
+
+ it("adjusts the draft by one step and wraps as a ring at both ends", () => {
+ const req = request({ reasoning: "high" });
+ let state = onReasoning(req);
+ state = drive(req, state, [{ type: "adjust", direction: "right" }]);
+ expect(state.draft.reasoning).toBe("xhigh");
+ expect(state.screen).toEqual({ kind: "menu", cursor: "reasoning" });
+
+ // Right past the top wraps to the first level; left wraps back.
+ state = drive(req, state, [{ type: "adjust", direction: "right" }]);
+ expect(state.draft.reasoning).toBe("none");
+ state = drive(req, state, [{ type: "adjust", direction: "left" }]);
+ expect(state.draft.reasoning).toBe("xhigh");
+ });
+
+ it("enters the ring from an unset draft: right at the lowest, left at the highest", () => {
+ const req = request();
+ let state = onReasoning(req);
+ expect(state.draft.reasoning).toBe("default");
+
+ const entered = drive(req, state, [{ type: "adjust", direction: "left" }]);
+ expect(entered.draft.reasoning).toBe("xhigh");
+
+ state = drive(req, state, [{ type: "adjust", direction: "right" }]);
+ expect(state.draft.reasoning).toBe("none");
+ });
+
+ it("ignores adjust away from the value rows", () => {
+ const req = request();
+ const state = initialModelEditorState(req);
+ expect(state.screen).toEqual({ kind: "menu", cursor: "model" });
+ expect(transitionModelEditor(state, { type: "adjust", direction: "right" }, req).kind).toBe(
+ "ignore",
+ );
+ });
+});
+
+describe("inline tier adjust", () => {
+ it("flips the tier on either arrow — a two-value ring, so Tab always acts", () => {
+ const req = request();
+ let state = drive(req, initialModelEditorState(req), [
+ { type: "move", direction: "down" },
+ { type: "move", direction: "down" },
+ ]);
+ expect(state.screen).toEqual({ kind: "menu", cursor: "tier" });
+
+ state = drive(req, state, [{ type: "adjust", direction: "right" }]);
+ expect(state.draft.tier).toBe("priority");
+ state = drive(req, state, [{ type: "adjust", direction: "right" }]);
+ expect(state.draft.tier).toBe("standard");
+ state = drive(req, state, [{ type: "adjust", direction: "left" }]);
+ expect(state.draft.tier).toBe("priority");
+ });
+
+ it("drops a drafted priority tier when the picked model prices no fast mode", () => {
+ // Drafted (not authored) priority: the pick must reset it, or the hidden
+ // row leaves it stuck and it leaks into the settle result.
+ const req = request();
+ let state = drive(req, initialModelEditorState(req), [
+ { type: "move", direction: "down" },
+ { type: "move", direction: "down" },
+ { type: "adjust", direction: "right" }, // tier → priority
+ { type: "move", direction: "up" },
+ { type: "move", direction: "up" },
+ { type: "submit" },
+ { type: "char", char: "frills" },
+ { type: "submit" }, // model → test/no-frills, fastMode: false
+ ]);
+ expect(state.draft.tier).toBe("standard");
+
+ // Priority survives a pick between two fast-mode models.
+ const priority = request({ serviceTier: { kind: "priority" } });
+ state = drive(priority, initialModelEditorState(priority), [
+ { type: "submit" },
+ { type: "char", char: "grok" },
+ { type: "submit" },
+ ]);
+ expect(state.draft.tier).toBe("priority");
+ });
+
+ it("hides the tier row after a pick of a model without the tier", () => {
+ const req = request();
+ let state = drive(req, initialModelEditorState(req), [
+ { type: "submit" },
+ { type: "char", char: "frills" },
+ { type: "submit" },
+ ]);
+ const rows = modelEditorMenuRows(req, state.draft, state.capabilities);
+ expect(rows.map((row) => row.value)).toEqual(["model", "reasoning", "done"]);
+ // The menu cursor stays valid: moving down from Model skips to Done.
+ state = drive(req, state, [{ type: "move", direction: "down" }]);
+ expect(state.screen).toEqual({ kind: "menu", cursor: "done" });
+ });
+});
+
+describe("settling", () => {
+ function toDone(req: ModelSettingsRequest, state: ModelEditorState): ModelEditorState {
+ let current = state;
+ for (
+ let i = 0;
+ i < 4 && (current.screen.kind !== "menu" || current.screen.cursor !== "done");
+ i += 1
+ ) {
+ current = drive(req, current, [{ type: "move", direction: "down" }]);
+ }
+ return current;
+ }
+
+ it("settles with only the fields that differ from the authored values", () => {
+ const req = request({ reasoning: "medium" });
+ let state = drive(req, initialModelEditorState(req), [
+ { type: "submit" },
+ { type: "char", char: "grok" },
+ { type: "submit" }, // model → xai/grok-4.5
+ { type: "move", direction: "down" },
+ { type: "adjust", direction: "right" }, // medium (stray between low/high) → high
+ { type: "move", direction: "down" },
+ { type: "adjust", direction: "right" }, // tier → priority
+ ]);
+ state = toDone(req, state);
+
+ expect(transitionModelEditor(state, { type: "submit" }, req)).toEqual({
+ kind: "settle",
+ result: { model: "xai/grok-4.5", reasoning: "high", serviceTier: "priority" },
+ });
+ });
+
+ it("settles with an empty result when nothing changed", () => {
+ const req = request();
+ const state = toDone(req, initialModelEditorState(req));
+ expect(transitionModelEditor(state, { type: "submit" }, req)).toEqual({
+ kind: "settle",
+ result: {},
+ });
+ });
+
+ it("maps a dropped tier to its remove sentinel", () => {
+ const req = request({ serviceTier: { kind: "priority" } });
+ let state = drive(req, initialModelEditorState(req), [
+ { type: "move", direction: "down" },
+ { type: "move", direction: "down" },
+ { type: "adjust", direction: "left" }, // priority → standard
+ ]);
+ state = toDone(req, state);
+
+ expect(transitionModelEditor(state, { type: "submit" }, req)).toEqual({
+ kind: "settle",
+ result: { serviceTier: "standard" },
+ });
+ });
+
+ it("settles an authored priority tier down to standard when the pick loses fast mode", () => {
+ const req = request({ serviceTier: { kind: "priority" } });
+ let state = drive(req, initialModelEditorState(req), [
+ { type: "submit" },
+ { type: "char", char: "frills" },
+ { type: "submit" },
+ ]);
+ state = toDone(req, state);
+
+ expect(transitionModelEditor(state, { type: "submit" }, req)).toEqual({
+ kind: "settle",
+ result: { model: "test/no-frills", serviceTier: "standard" },
+ });
+ });
+
+ it("never reports tier changes for custom configurations", () => {
+ const req = request({ serviceTier: { kind: "custom", value: "flex" } });
+ const state = toDone(req, initialModelEditorState(req));
+ expect(transitionModelEditor(state, { type: "submit" }, req)).toEqual({
+ kind: "settle",
+ result: {},
+ });
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/model-editor.ts b/packages/eve/src/cli/dev/tui/model-editor.ts
new file mode 100644
index 000000000..0beb9db69
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/model-editor.ts
@@ -0,0 +1,402 @@
+import { ALL_REASONING_LEVELS, type ReasoningLevel } from "#setup/boxes/model-capabilities.js";
+import type { GatewayModelCapabilities } from "#setup/boxes/model-capabilities.js";
+import {
+ filterOptions,
+ initialSelectState,
+ reduceSelect,
+ selectValueAtCursor,
+ type SelectState,
+} from "#setup/cli/select-state.js";
+import type { ModelSettingsRequest, ModelSettingsResult } from "#setup/flows/model.js";
+import type { SelectOption } from "#setup/prompter.js";
+
+/** The Change-model menu's rows, in visual order. */
+export type ModelEditorRowId = "model" | "reasoning" | "tier" | "done";
+
+/**
+ * The screen stack, depth two: the value menu, or the model list it opens.
+ * Reasoning and tier adjust inline on their menu rows — only the catalog pick
+ * warrants its own screen. The list carries scratch select state seeded when
+ * opened; Esc drops it, so "returns unchanged" is structural.
+ */
+export type ModelEditorScreen =
+ | { kind: "menu"; cursor: ModelEditorRowId }
+ | { kind: "model"; select: SelectState };
+
+/** The in-progress values; nothing lands in source until the menu's Done. */
+export interface ModelEditorDraft {
+ modelId: string | null;
+ reasoning: "default" | ReasoningLevel;
+ tier: "standard" | "priority";
+}
+
+/** One Change-model interaction, advanced by {@link transitionModelEditor}. */
+export interface ModelEditorState {
+ screen: ModelEditorScreen;
+ draft: ModelEditorDraft;
+ /** Catalog capabilities for `draft.modelId`; recomputed on every pick. */
+ capabilities: GatewayModelCapabilities | undefined;
+}
+
+/** Semantic input after terminal-key decoding. */
+export type ModelEditorEvent =
+ | { type: "move"; direction: "up" | "down" }
+ | { type: "adjust"; direction: "left" | "right" }
+ | { type: "char"; char: string }
+ | { type: "backspace" }
+ | { type: "cancel" }
+ | { type: "submit" };
+
+export type ModelEditorTransition =
+ | { kind: "ignore"; state: ModelEditorState }
+ | { kind: "render"; state: ModelEditorState }
+ | { kind: "cancel" }
+ | { kind: "settle"; result: ModelSettingsResult };
+
+/**
+ * How a value row presents: an adjustable control, a dim explanatory line the
+ * cursor skips, or nothing at all — a control that cannot apply to the
+ * drafted model (no priority tier) is noise, while an authored-but-unowned
+ * state (custom tier, external provider) still explains itself.
+ */
+export type ModelEditorSectionView =
+ | { kind: "interactive" }
+ | { kind: "static"; text: string }
+ | { kind: "hidden" };
+
+const NOT_EDITABLE_TEXT = "No editable agent.ts config object is available";
+
+/**
+ * The reasoning row stays interactive while a level is drafted even when the
+ * catalog disowns reasoning, so the authored value at least stays visible.
+ */
+export function reasoningSectionView(
+ request: ModelSettingsRequest,
+ draft: ModelEditorDraft,
+ capabilities: GatewayModelCapabilities | undefined,
+): ModelEditorSectionView {
+ if (!request.settingsEditable) return { kind: "static", text: NOT_EDITABLE_TEXT };
+ if (capabilities?.reasoning === false && draft.reasoning === "default") {
+ return { kind: "static", text: "Not supported by the selected model" };
+ }
+ return { kind: "interactive" };
+}
+
+/** The tier row's presentation; static or hidden for every state it cannot own. */
+export function tierSectionView(
+ request: ModelSettingsRequest,
+ capabilities: GatewayModelCapabilities | undefined,
+): ModelEditorSectionView {
+ if (!request.settingsEditable) return { kind: "static", text: NOT_EDITABLE_TEXT };
+ if (request.externalRouting) {
+ return { kind: "static", text: "Disabled for a direct external provider" };
+ }
+ if (request.serviceTier.kind === "custom") {
+ return { kind: "static", text: `Custom (${request.serviceTier.value}) — authored in agent.ts` };
+ }
+ // Pure availability: a model the catalog prices no priority tier for never
+ // shows the row, and a model with one always does — the drafted value has
+ // no say, so the row cannot vanish underneath its own toggle.
+ if (capabilities !== undefined && !capabilities.fastMode) {
+ return { kind: "hidden" };
+ }
+ return { kind: "interactive" };
+}
+
+/**
+ * The track's notch positions: the levels the catalog supports (every level
+ * when capabilities are unknown). The provider default is not a notch — an
+ * unset draft renders an empty track and the first right-adjust enters the
+ * scale at the lowest level. A drafted level the catalog does not list is
+ * inserted in canonical level order, so the track never hides the value it
+ * is about to replace.
+ */
+export function reasoningPositions(
+ capabilities: GatewayModelCapabilities | undefined,
+ drafted: "default" | ReasoningLevel,
+): readonly ReasoningLevel[] {
+ const levels = capabilities === undefined ? ALL_REASONING_LEVELS : capabilities.reasoningLevels;
+ const positions: ReasoningLevel[] = [...levels];
+ if (drafted !== "default" && !positions.includes(drafted)) {
+ const rank = ALL_REASONING_LEVELS.indexOf(drafted);
+ const insertAt = positions.findIndex(
+ (position) => ALL_REASONING_LEVELS.indexOf(position) > rank,
+ );
+ if (insertAt === -1) positions.push(drafted);
+ else positions.splice(insertAt, 0, drafted);
+ }
+ return positions;
+}
+
+/**
+ * The drafted level a freshly-picked model can actually serve: kept when the
+ * new model supports it, snapped to the closest supported level by canonical
+ * rank when it does not (ties resolve to the cheaper level), and cleared to
+ * the provider default when the model has no adjustable reasoning at all. An
+ * unset draft stays unset.
+ */
+function snapReasoningToCapabilities(
+ drafted: "default" | ReasoningLevel,
+ capabilities: GatewayModelCapabilities | undefined,
+): "default" | ReasoningLevel {
+ if (drafted === "default" || capabilities === undefined) return drafted;
+ const levels = capabilities.reasoningLevels;
+ if (!capabilities.reasoning || levels.length === 0) return "default";
+ if (levels.includes(drafted)) return drafted;
+ const rank = ALL_REASONING_LEVELS.indexOf(drafted);
+ let closest = levels[0]!;
+ for (const level of levels) {
+ const distance = Math.abs(ALL_REASONING_LEVELS.indexOf(level) - rank);
+ const best = Math.abs(ALL_REASONING_LEVELS.indexOf(closest) - rank);
+ if (distance < best) closest = level;
+ }
+ return closest;
+}
+
+/**
+ * The value menu's rows, derived fresh from the draft on every transition and
+ * paint: interactive sections are pickable rows, static sections are disabled
+ * rows carrying their explanation, and a hidden tier is omitted entirely.
+ * Value hints are the painter's job — it styles them with theme glyphs.
+ */
+export function modelEditorMenuRows(
+ request: ModelSettingsRequest,
+ draft: ModelEditorDraft,
+ capabilities: GatewayModelCapabilities | undefined,
+): SelectOption<ModelEditorRowId>[] {
+ const rows: SelectOption<ModelEditorRowId>[] = [];
+ if (request.model.kind === "pick") {
+ rows.push({ value: "model", label: "Model" });
+ } else {
+ rows.push({
+ value: "model",
+ label: "Model",
+ disabled: true,
+ description: request.model.reason,
+ });
+ }
+
+ const reasoning = reasoningSectionView(request, draft, capabilities);
+ if (reasoning.kind === "static") {
+ rows.push({
+ value: "reasoning",
+ label: "Reasoning effort",
+ disabled: true,
+ description: reasoning.text,
+ });
+ } else {
+ rows.push({ value: "reasoning", label: "Reasoning effort" });
+ }
+
+ const tier = tierSectionView(request, capabilities);
+ if (tier.kind === "interactive") {
+ rows.push({ value: "tier", label: "Service tier" });
+ } else if (tier.kind === "static") {
+ rows.push({ value: "tier", label: "Service tier", disabled: true, description: tier.text });
+ }
+
+ rows.push({ value: "done", label: "Done" });
+ return rows;
+}
+
+/** Creates the screen's state; the cursor opens on the first pickable row. */
+export function initialModelEditorState(request: ModelSettingsRequest): ModelEditorState {
+ const draft: ModelEditorDraft = {
+ modelId: request.model.current,
+ reasoning: request.reasoning ?? "default",
+ tier: request.serviceTier.kind === "priority" ? "priority" : "standard",
+ };
+ const capabilities = request.capabilitiesFor(draft.modelId);
+ const rows = modelEditorMenuRows(request, draft, capabilities);
+ const cursor = rows.find((row) => row.disabled !== true)?.value ?? "done";
+ return { screen: { kind: "menu", cursor }, draft, capabilities };
+}
+
+/** A fresh search list opened on the drafted model with no filter. */
+function expandedModelSelect(request: ModelSettingsRequest, modelId: string | null): SelectState {
+ const options = request.model.kind === "pick" ? request.model.options : [];
+ const input: Parameters<typeof initialSelectState>[0] = { options };
+ if (modelId !== null) input.defaultValue = modelId;
+ return initialSelectState(input);
+}
+
+function ignore(state: ModelEditorState): ModelEditorTransition {
+ return { kind: "ignore", state };
+}
+
+function toMenu(state: ModelEditorState, cursor: ModelEditorRowId): ModelEditorTransition {
+ return { kind: "render", state: { ...state, screen: { kind: "menu", cursor } } };
+}
+
+/** The settle payload: only the fields that differ from the authored values. */
+function settleResult(request: ModelSettingsRequest, draft: ModelEditorDraft): ModelSettingsResult {
+ const result: ModelSettingsResult = {};
+ if (
+ request.model.kind === "pick" &&
+ draft.modelId !== null &&
+ draft.modelId !== request.model.current
+ ) {
+ result.model = draft.modelId;
+ }
+ if (!request.settingsEditable) return result;
+ if (draft.reasoning !== (request.reasoning ?? "default")) result.reasoning = draft.reasoning;
+ const tierOwned = !request.externalRouting && request.serviceTier.kind !== "custom";
+ const authoredTier = request.serviceTier.kind === "priority" ? "priority" : "standard";
+ if (tierOwned && draft.tier !== authoredTier) result.serviceTier = draft.tier;
+ return result;
+}
+
+/** One inline left/right adjustment of the row under the menu cursor. */
+function adjustMenuValue(
+ state: ModelEditorState,
+ request: ModelSettingsRequest,
+ cursor: ModelEditorRowId,
+ direction: "left" | "right",
+): ModelEditorTransition {
+ const delta = direction === "left" ? -1 : 1;
+ if (cursor === "reasoning") {
+ if (reasoningSectionView(request, state.draft, state.capabilities).kind !== "interactive") {
+ return ignore(state);
+ }
+ const positions = reasoningPositions(state.capabilities, state.draft.reasoning);
+ if (positions.length === 0) return ignore(state);
+ // The provider default is not a notch: right enters the ring at the lowest
+ // level and left at the highest. On the ring, both directions wrap.
+ const index =
+ state.draft.reasoning === "default" ? -1 : positions.indexOf(state.draft.reasoning);
+ const next =
+ index === -1
+ ? positions[delta === 1 ? 0 : positions.length - 1]!
+ : positions[(index + delta + positions.length) % positions.length]!;
+ if (next === state.draft.reasoning) return ignore(state);
+ return { kind: "render", state: { ...state, draft: { ...state.draft, reasoning: next } } };
+ }
+ if (cursor === "tier") {
+ if (tierSectionView(request, state.capabilities).kind !== "interactive") {
+ return ignore(state);
+ }
+ // A two-value ring: either arrow (and Tab) flips the tier.
+ const next = state.draft.tier === "priority" ? "standard" : "priority";
+ return { kind: "render", state: { ...state, draft: { ...state.draft, tier: next } } };
+ }
+ return ignore(state);
+}
+
+function transitionMenu(
+ state: ModelEditorState,
+ event: ModelEditorEvent,
+ request: ModelSettingsRequest,
+ cursor: ModelEditorRowId,
+): ModelEditorTransition {
+ const rows = modelEditorMenuRows(request, state.draft, state.capabilities);
+
+ switch (event.type) {
+ case "cancel":
+ return { kind: "cancel" };
+ case "move": {
+ // Shared select stepping over the derived rows: wraps, skips disabled.
+ const index = Math.max(
+ 0,
+ rows.findIndex((row) => row.value === cursor),
+ );
+ const stepped = reduceSelect(
+ { filter: "", cursor: index, selected: new Set() },
+ { type: event.direction },
+ { options: rows },
+ );
+ const next = rows[stepped.cursor]?.value;
+ if (next === undefined || next === cursor) return ignore(state);
+ return toMenu(state, next);
+ }
+ case "adjust":
+ return adjustMenuValue(state, request, cursor, event.direction);
+ case "submit": {
+ const row = rows.find((entry) => entry.value === cursor);
+ if (row === undefined || row.disabled === true) return ignore(state);
+ if (cursor === "model") {
+ return {
+ kind: "render",
+ state: {
+ ...state,
+ screen: { kind: "model", select: expandedModelSelect(request, state.draft.modelId) },
+ },
+ };
+ }
+ if (cursor === "done") {
+ return { kind: "settle", result: settleResult(request, state.draft) };
+ }
+ // Enter on an inline value confirms nothing new — it just walks on.
+ return transitionMenu(state, { type: "move", direction: "down" }, request, cursor);
+ }
+ case "char":
+ case "backspace":
+ return ignore(state);
+ }
+}
+
+function transitionModelScreen(
+ state: ModelEditorState,
+ event: ModelEditorEvent,
+ request: ModelSettingsRequest,
+ select: SelectState,
+): ModelEditorTransition {
+ const options = request.model.kind === "pick" ? request.model.options : [];
+ const renderSelect = (next: SelectState): ModelEditorTransition =>
+ next === select
+ ? ignore(state)
+ : { kind: "render", state: { ...state, screen: { kind: "model", select: next } } };
+
+ switch (event.type) {
+ case "cancel":
+ if (select.filter.length > 0) {
+ return renderSelect(reduceSelect(select, { type: "clear" }, { options }));
+ }
+ return toMenu(state, "model");
+ case "move":
+ return renderSelect(reduceSelect(select, { type: event.direction }, { options }));
+ case "char":
+ return renderSelect(reduceSelect(select, { type: "char", char: event.char }, { options }));
+ case "backspace":
+ return renderSelect(reduceSelect(select, { type: "backspace" }, { options }));
+ case "submit": {
+ const visible = filterOptions(options, select.filter);
+ const value = selectValueAtCursor(visible, select.cursor);
+ if (value === undefined) return ignore(state);
+ const capabilities = request.capabilitiesFor(value);
+ return {
+ kind: "render",
+ state: {
+ screen: { kind: "menu", cursor: "model" },
+ draft: {
+ ...state.draft,
+ modelId: value,
+ // A level the new model cannot serve must not survive the pick.
+ reasoning: snapReasoningToCapabilities(state.draft.reasoning, capabilities),
+ // Nor a priority tier the new model prices no fast mode for — the
+ // hidden tier row would leave it drafted with no way to toggle it
+ // back, and it would leak into the settle result.
+ tier:
+ capabilities !== undefined && !capabilities.fastMode ? "standard" : state.draft.tier,
+ },
+ capabilities,
+ },
+ };
+ }
+ case "adjust":
+ return ignore(state);
+ }
+}
+
+/** Applies one keypress worth of semantics; terminal resources stay in the renderer. */
+export function transitionModelEditor(
+ state: ModelEditorState,
+ event: ModelEditorEvent,
+ request: ModelSettingsRequest,
+): ModelEditorTransition {
+ switch (state.screen.kind) {
+ case "menu":
+ return transitionMenu(state, event, request, state.screen.cursor);
+ case "model":
+ return transitionModelScreen(state, event, request, state.screen.select);
+ }
+}
diff --git a/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts b/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts
index 23feff703..5e2b35038 100644
--- a/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts
+++ b/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts
@@ -35,6 +35,7 @@ function setupFlowRenderer() {
readSelect: vi.fn(async () => undefined),
readEditableSelect: vi.fn(async () => undefined),
readProviderPicker: vi.fn(async () => undefined),
+ readModelEditor: vi.fn(async () => undefined),
readText: vi.fn(async () => undefined),
readAcknowledge: vi.fn(async () => {}),
readChoice: vi.fn(() => ({ choice: Promise.resolve(undefined), close: vi.fn() })),
@@ -227,7 +228,7 @@ describe("createPromptCommandHandler", () => {
},
),
).resolves.toEqual({
- message: "/vc:login cancelled after logging in to Vercel.",
+ message: "/vc:login dismissed after logging in to Vercel.",
});
expect(runLoginFlow).not.toHaveBeenCalled();
expect(setupFlow.begin).toHaveBeenCalledWith("Authenticate via Vercel OIDC", "pulse");
diff --git a/packages/eve/src/cli/dev/tui/prompt-command-handler.ts b/packages/eve/src/cli/dev/tui/prompt-command-handler.ts
index a0402a32d..520d36bb4 100644
--- a/packages/eve/src/cli/dev/tui/prompt-command-handler.ts
+++ b/packages/eve/src/cli/dev/tui/prompt-command-handler.ts
@@ -1,4 +1,4 @@
-import type { ApplyModelOutcome } from "#setup/flows/model.js";
+import type { ApplyModelOutcome } from "#setup/flows/model-source-change.js";
import { toErrorMessage } from "#shared/errors.js";
import type {
@@ -55,11 +55,9 @@ export function createPromptCommandHandler(
const appRoot = target.workspaceRoot;
// Package-loading failures are command outcomes at this CLI boundary.
try {
- const {
- changeAgentModel,
- formatApplyModelOutcome,
- modelChangeRefusalForUneditableModel,
- } = await import("#setup/flows/model.js");
+ const { modelChangeRefusalForUneditableModel } = await import("#setup/flows/model.js");
+ const { changeAgentModel, formatApplyModelOutcome } =
+ await import("#setup/flows/model-source-change.js");
// A source-backed model (an SDK model call) isn't a string literal eve
// can rewrite; refuse with a clear reason rather than silently no-op.
const checkRefusal = options.modelChangeRefusal ?? modelChangeRefusalForUneditableModel;
diff --git a/packages/eve/src/cli/dev/tui/remote-auth-command.ts b/packages/eve/src/cli/dev/tui/remote-auth-command.ts
index a1fb8506d..270dd480f 100644
--- a/packages/eve/src/cli/dev/tui/remote-auth-command.ts
+++ b/packages/eve/src/cli/dev/tui/remote-auth-command.ts
@@ -113,8 +113,8 @@ export async function runRemoteAuthCommand(input: RemoteAuthCommandInput): Promi
: `/vc:login interrupted. Completed before interruption: ${completed.join(", ")}.`;
}
return outcome.completedMutations.some((mutation) => mutation.kind === "vercel-login")
- ? "/vc:login cancelled after logging in to Vercel."
- : "/vc:login cancelled.";
+ ? "/vc:login dismissed after logging in to Vercel."
+ : "/vc:login dismissed.";
}
case "failed":
return outcome.message;
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index 99feac3e8..60c68c4b1 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -204,6 +204,7 @@ function idleSetupFlow(): SetupFlowRenderer {
readSelect: vi.fn(async () => undefined),
readEditableSelect: vi.fn(async () => undefined),
readProviderPicker: vi.fn(async () => undefined),
+ readModelEditor: vi.fn(async () => undefined),
readText: vi.fn(async () => undefined),
readAcknowledge: vi.fn(async () => {}),
readChoice: vi.fn(() => ({ choice: Promise.resolve(undefined), close: vi.fn() })),
@@ -2070,15 +2071,18 @@ describe("EveTUIRunner Vercel status line", () => {
describe("EveTUIRunner gateway-auth failure rendering", () => {
const gatewayFailure = {
code: "MODEL_CALL_FAILED",
- message: "AI Gateway received no credentials. Run `eve link` to populate…",
+ message: "AI Gateway received no credentials.",
details: {
errorId: "err-1",
name: "AI Gateway authentication failed",
- gatewayName: "GatewayAuthenticationError",
+ semanticErrorId: "gateway-auth-missing-credentials",
+ hint: "Run `eve link` to populate `VERCEL_OIDC_TOKEN`, or set `AI_GATEWAY_API_KEY`…",
},
};
- async function errorTextsFor(appRoot?: string): Promise<string[]> {
+ async function errorEventsFor(
+ appRoot?: string,
+ ): Promise<Array<{ errorText: string; hint?: string }>> {
const prompts: Array<string | undefined> = ["hello", undefined];
const emitted: AgentTUIStreamEvent[] = [];
const session = sessionYielding([
@@ -2107,22 +2111,24 @@ describe("EveTUIRunner gateway-auth failure rendering", () => {
return emitted
.filter((event) => event.type === "error")
- .map((event) => (event as { errorText: string }).errorText);
+ .map((event) => event as { errorText: string; hint?: string });
}
- it("collapses the failure to the minimal /model line when setup commands are available", async () => {
- const errors = await errorTextsFor("/tmp/weather-agent");
+ it("swaps the hint for the local /model fix when setup commands are available", async () => {
+ const errors = await errorEventsFor("/tmp/weather-agent");
expect(errors).toHaveLength(1);
- expect(errors[0]).toBe(
- "There is no AI_GATEWAY_API_KEY set. Run /model to connect this to a project and refresh AI Gateway credentials, or set it manually in .env.local.",
+ expect(errors[0]!.errorText).toContain("MODEL_CALL_FAILED");
+ expect(errors[0]!.hint).toBe(
+ "Run /model to connect this to a project and refresh AI Gateway credentials, or set AI_GATEWAY_API_KEY manually in .env.local.",
);
});
- it("keeps the full failure message when the TUI has no local project to link", async () => {
- const errors = await errorTextsFor(undefined);
+ it("keeps the harness hint when the TUI has no local project to link", async () => {
+ const errors = await errorEventsFor(undefined);
expect(errors).toHaveLength(1);
- expect(errors[0]).toContain("MODEL_CALL_FAILED");
- expect(errors[0]).not.toContain("/model");
+ expect(errors[0]!.errorText).toContain("MODEL_CALL_FAILED");
+ expect(errors[0]!.hint).toContain("eve link");
+ expect(errors[0]!.hint).not.toContain("/model");
});
});
@@ -2223,7 +2229,7 @@ describe("EveTUIRunner boot setup detection", () => {
];
const handle = vi.fn(async (command: { name: string }) => {
order.push(command.name);
- return { message: "/model cancelled." };
+ return { message: "/model dismissed." };
});
const renderer = fakeRenderer({
readPrompt: vi.fn(async (options?: AgentTUISessionOptions) => {
@@ -2301,7 +2307,7 @@ describe("EveTUIRunner boot setup detection", () => {
promptCommandHandler: {
handle: async (command) => {
order.push(command.name);
- return { message: "/vc:install cancelled." };
+ return { message: "/vc:install dismissed." };
},
},
});
@@ -2313,7 +2319,7 @@ describe("EveTUIRunner boot setup detection", () => {
});
it("does not auto-open /model outside the prefilled onboarding launch", async () => {
- const handle = vi.fn(async () => ({ message: "/model cancelled." }));
+ const handle = vi.fn(async () => ({ message: "/model dismissed." }));
const runner = new EveTUIRunner({
session: sessionYielding([]),
renderer: fakeRenderer({ setupFlow: createFakeSetupFlowRenderer() }),
@@ -2340,7 +2346,7 @@ describe("EveTUIRunner boot setup detection", () => {
});
it("keeps a prefilled /model editable without a local app root", async () => {
- const handle = vi.fn(async () => ({ message: "/model cancelled." }));
+ const handle = vi.fn(async () => ({ message: "/model dismissed." }));
const readPrompt = vi.fn(async (options?: AgentTUISessionOptions) => {
expect(options?.initialDraft).toBe("/model");
return undefined;
diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.ts
index 0c1ebf2c3..05341165c 100644
--- a/packages/eve/src/cli/dev/tui/runner.ts
+++ b/packages/eve/src/cli/dev/tui/runner.ts
@@ -33,11 +33,11 @@ import {
type FailureStreamEvent,
failureKey,
formatFailureDetail,
+ formatFailureHint,
formatFailureMessage,
- formatGatewayAuthFailureNotice,
isAbortLikeError,
- isGatewayAuthFailure,
isInterruptedError,
+ localFailureHint,
} from "./errors.js";
import { pickAgentHeaderTip } from "./agent-header.js";
@@ -92,6 +92,7 @@ import {
} from "./mcp-connection-status.js";
import type { detectProjectIdentity } from "#setup/project-resolution.js";
import { getVercelAuthStatus, type VercelAuthStatus } from "#setup/vercel-project.js";
+import type { DevDiagnostics } from "../diagnostics.js";
export { parsePromptCommand, type PromptCommand } from "./prompt-commands.js";
@@ -120,7 +121,7 @@ export type AgentTUIStreamEvent =
| { type: "tool-approval-request"; approvalId: string; toolCallId: string }
| { type: "tool-result"; toolCallId: string; output: unknown }
| { type: "tool-error"; toolCallId: string; errorText: string }
- | { type: "error"; errorText: string; detail?: string }
+ | { type: "error"; errorText: string; hint?: string; detail?: string }
| { type: "finish"; usage?: AgentTUIStreamUsage };
export type AgentTUITurnState = {
@@ -383,6 +384,8 @@ export type EveTUIRunnerOptions = TuiDisplayOptions & {
getVercelAuthStatus?: typeof getVercelAuthStatus;
/** Reports phases from this runner's initial local-dev connection. */
onBootProgress?: DevBootProgressReporter;
+ /** Parent-owned diagnostics recorder; omitted for remote and test renderers. */
+ diagnostics?: DevDiagnostics;
};
/** The attention-line issue for a Vercel auth state, or undefined when nothing's wrong. */
@@ -1047,11 +1050,7 @@ export class EveTUIRunner {
onTerminalFailure: () => {
this.#sessionFailed = true;
},
- failureOverride:
- this.#appRoot === undefined
- ? undefined
- : (event) =>
- isGatewayAuthFailure(event) ? formatGatewayAuthFailureNotice(event) : undefined,
+ failureHintOverride: this.#appRoot === undefined ? undefined : localFailureHint,
}),
turnState,
};
@@ -1714,6 +1713,7 @@ function createRenderer(options: EveTUIRunnerOptions): AgentTUIRenderer {
availablePromptCommands: options.availablePromptCommands,
input: options.userInput,
output: options.screen,
+ diagnostics: options.diagnostics,
});
}
@@ -1741,7 +1741,12 @@ type EveStreamTranslatorInput = {
onConnectionAuthRequired?: (event: AuthorizationRequiredStreamEvent) => void;
onConnectionAuthCompleted?: (event: AuthorizationCompletedStreamEvent) => void;
onTerminalFailure?: (event: SessionFailedStreamEvent) => void;
- failureOverride?: (event: FailureStreamEvent) => string | undefined;
+ /**
+ * Replaces a failure's structured hint with a surface-local one (the
+ * local TUI swaps gateway-auth remediation for the in-session `/model`
+ * fix). Returning `undefined` keeps the hint the harness attached.
+ */
+ failureHintOverride?: (event: FailureStreamEvent) => string | undefined;
};
/**
@@ -1762,7 +1767,7 @@ async function* eveEventsToTUIStream(
onConnectionAuthRequired,
onConnectionAuthCompleted,
onTerminalFailure,
- failureOverride,
+ failureHintOverride,
} = input;
const textParts = new Map<string, StreamPartState>();
const reasoningParts = new Map<string, StreamPartState>();
@@ -2024,7 +2029,7 @@ async function* eveEventsToTUIStream(
case "step.failed":
case "turn.failed": {
- const failure = toFailureEvent(event, emittedFailures, failureOverride);
+ const failure = toFailureEvent(event, emittedFailures, failureHintOverride);
if (failure) yield failure;
break;
}
@@ -2034,7 +2039,7 @@ async function* eveEventsToTUIStream(
// recover onto a fresh session before the next prompt.
turnState.sawSessionFailure = true;
onTerminalFailure?.(event as SessionFailedStreamEvent);
- const failure = toFailureEvent(event, emittedFailures, failureOverride);
+ const failure = toFailureEvent(event, emittedFailures, failureHintOverride);
if (failure) yield failure;
turnState.boundaryEvent = event.type;
yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);
@@ -2266,24 +2271,26 @@ function formatActionResultError(event: ActionResultStreamEvent): string {
/**
* Projects one failure event into a renderable `error` stream event, or
* `undefined` when the same underlying failure was already emitted earlier in
- * the cascade. Attaches the diagnostic dump (stack trace) when the failure
- * carries one — i.e. for unrecognized errors escaping user code.
+ * the cascade. Carries the failure as a structured entity: headline, the
+ * catalog's remediation hint (surface overrides win), and the diagnostic
+ * dump when the failure carries one — i.e. for unrecognized errors escaping
+ * user code.
*/
function toFailureEvent(
event: FailureStreamEvent,
emittedFailures: Set<string>,
- failureOverride?: (event: FailureStreamEvent) => string | undefined,
+ failureHintOverride?: (event: FailureStreamEvent) => string | undefined,
): AgentTUIStreamEvent | undefined {
const key = failureKey(event);
if (emittedFailures.has(key)) return undefined;
emittedFailures.add(key);
- const override = failureOverride?.(event);
const failure: AgentTUIStreamEvent = {
type: "error",
- errorText: override ?? formatFailureMessage(event),
+ errorText: formatFailureMessage(event),
};
- if (override !== undefined) return failure;
+ const hint = failureHintOverride?.(event) ?? formatFailureHint(event);
+ if (hint !== undefined) failure.hint = hint;
const detail = formatFailureDetail(event);
if (detail !== undefined) failure.detail = detail;
return failure;
diff --git a/packages/eve/src/cli/dev/tui/setup-commands.test.ts b/packages/eve/src/cli/dev/tui/setup-commands.test.ts
index 1e0afbca4..4be38e3ed 100644
--- a/packages/eve/src/cli/dev/tui/setup-commands.test.ts
+++ b/packages/eve/src/cli/dev/tui/setup-commands.test.ts
@@ -29,6 +29,7 @@ function fakePanelRenderer(): TuiSetupCommandRenderer & {
readSelect: vi.fn(async () => []),
readEditableSelect: vi.fn(async () => undefined),
readProviderPicker: vi.fn(async () => undefined),
+ readModelEditor: vi.fn(async () => undefined),
readText: vi.fn(async () => ""),
readAcknowledge: vi.fn(async () => {}),
readChoice: vi.fn(() => ({ choice: Promise.resolve(undefined), close: vi.fn() })),
@@ -193,7 +194,7 @@ describe("runTuiSetupCommand", () => {
runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async () => ({ kind: "cancelled" })),
});
await expect(run({ command: "model", flows })).resolves.toEqual({
- message: "/model cancelled.",
+ message: "/model dismissed.",
preserveFlowDiagnostics: false,
});
});
@@ -274,7 +275,7 @@ describe("runTuiSetupCommand", () => {
});
await expect(run({ command: "channels", flows })).resolves.toEqual({
- message: "Channels added, but /deploy was cancelled. Run /deploy to ship them.",
+ message: "Channels added, but /deploy was dismissed. Run /deploy to ship them.",
preserveFlowDiagnostics: true,
effect: { kind: "channels-added" },
});
@@ -339,7 +340,7 @@ describe("runTuiSetupCommand", () => {
"No connections added.",
{ kind: "model-access-changed" },
],
- ["cancelled", { kind: "cancelled" }, "/connect cancelled.", { kind: "model-access-changed" }],
+ ["cancelled", { kind: "cancelled" }, "/connect dismissed.", { kind: "model-access-changed" }],
[
"partially failed",
{ kind: "failed", addedConnections: ["linear"], message: "install failed" },
@@ -410,7 +411,7 @@ describe("runTuiSetupCommand", () => {
}),
});
await expect(run({ command: "deploy", flows: cancelling })).resolves.toEqual({
- message: "/deploy cancelled.",
+ message: "/deploy dismissed.",
preserveFlowDiagnostics: true,
});
});
diff --git a/packages/eve/src/cli/dev/tui/setup-commands.ts b/packages/eve/src/cli/dev/tui/setup-commands.ts
index e55454306..8c1fbf2c5 100644
--- a/packages/eve/src/cli/dev/tui/setup-commands.ts
+++ b/packages/eve/src/cli/dev/tui/setup-commands.ts
@@ -37,9 +37,10 @@ export const SETUP_FLOW_CONFIG = {
/** The prompter surface plus the working-state interrupt trap a command races against. */
export type TuiSetupCommandRenderer = TuiPrompterRenderer &
- Pick<SetupFlowRenderer, "readProviderPicker" | "waitForInterrupt">;
+ Pick<SetupFlowRenderer, "readProviderPicker" | "readModelEditor" | "waitForInterrupt">;
-type MuteableSetupRenderer = TuiPrompterRenderer & Pick<SetupFlowRenderer, "readProviderPicker">;
+type MuteableSetupRenderer = TuiPrompterRenderer &
+ Pick<SetupFlowRenderer, "readProviderPicker" | "readModelEditor">;
export interface TuiSetupCommandInput {
command: TuiSetupCommand;
@@ -90,6 +91,8 @@ function muteableRenderer(
isMuted() ? Promise.resolve(undefined) : renderer.readEditableSelect(options),
readProviderPicker: (options) =>
isMuted() ? Promise.resolve(undefined) : renderer.readProviderPicker(options),
+ readModelEditor: (options) =>
+ isMuted() ? Promise.resolve(undefined) : renderer.readModelEditor(options),
readText: (options) => (isMuted() ? Promise.resolve(undefined) : renderer.readText(options)),
readAcknowledge: (options) =>
isMuted() ? Promise.resolve() : renderer.readAcknowledge(options),
@@ -184,6 +187,7 @@ async function executeSetupCommand(
prompter,
signal,
deps: {
+ pickModelSettings: (request) => renderer.readModelEditor(request),
runProviderFlow: (providerInput) =>
runProviderFlow({ ...providerInput, picker: pickProvider }),
},
@@ -193,7 +197,13 @@ async function executeSetupCommand(
}
const result = await flows.runModelFlow(modelInput);
if (result.kind === "cancelled") {
- return { message: "/model cancelled.", preserveFlowDiagnostics: false };
+ return {
+ message:
+ result.discardedDraft === true
+ ? "/model dismissed. Drafted changes were discarded; Done commits them."
+ : "/model dismissed.",
+ preserveFlowDiagnostics: false,
+ };
}
// One line per completed menu action: the apply line (it already
// distinguishes success from a rejected slug), then the provider
@@ -226,7 +236,7 @@ async function executeSetupCommand(
`Channel files changed, but /channels failed: ${result.message}`,
);
case "cancelled":
- return { message: "/channels cancelled.", preserveFlowDiagnostics: true };
+ return { message: "/channels dismissed.", preserveFlowDiagnostics: true };
case "deploy-and-chat":
return await runDeployAndChat(flows, { appRoot, prompter, signal }, result.chat);
case "done":
@@ -250,7 +260,7 @@ async function executeSetupCommand(
switch (result.kind) {
case "cancelled":
return {
- message: "/connect cancelled.",
+ message: "/connect dismissed.",
preserveFlowDiagnostics: true,
effect: { kind: "model-access-changed" },
};
@@ -283,7 +293,7 @@ async function executeSetupCommand(
case "deploy": {
const result = await flows.runDeployFlow({ appRoot, prompter, interactive: true, signal });
if (result.kind === "cancelled") {
- return { message: "/deploy cancelled.", preserveFlowDiagnostics: true };
+ return { message: "/deploy dismissed.", preserveFlowDiagnostics: true };
}
if (result.kind === "needs-link") {
return {
@@ -302,7 +312,7 @@ async function executeSetupCommand(
} catch (error) {
if (error instanceof WizardCancelledError) {
return {
- message: `/${command} cancelled.`,
+ message: `/${command} dismissed.`,
preserveFlowDiagnostics: command !== "model",
};
}
@@ -363,7 +373,7 @@ async function runDeployAndChat(
} catch (error) {
if (error instanceof WizardCancelledError) {
return pendingChannelsResult(
- "Channels added, but /deploy was cancelled. Run /deploy to ship them.",
+ "Channels added, but /deploy was dismissed. Run /deploy to ship them.",
);
}
const routed = vercelActionOutcome(error, "deploy");
@@ -373,7 +383,7 @@ async function runDeployAndChat(
}
if (result.kind === "cancelled") {
return pendingChannelsResult(
- "Channels added, but /deploy was cancelled. Run /deploy to ship them.",
+ "Channels added, but /deploy was dismissed. Run /deploy to ship them.",
);
}
if (result.kind === "needs-link") {
@@ -404,7 +414,7 @@ async function runDeployAndChat(
function installVercelCliResultMessage(result: InstallVercelCliResult): TuiSetupCommandResult {
switch (result.kind) {
case "cancelled":
- return { message: "/vc:install cancelled.", preserveFlowDiagnostics: false };
+ return { message: "/vc:install dismissed.", preserveFlowDiagnostics: false };
case "already":
return { message: "The Vercel CLI is already installed.", preserveFlowDiagnostics: false };
case "failed":
@@ -427,7 +437,7 @@ function installVercelCliResultMessage(result: InstallVercelCliResult): TuiSetup
function loginResultMessage(result: LoginFlowResult): TuiSetupCommandResult {
switch (result.kind) {
case "cancelled":
- return { message: "/vc:login cancelled.", preserveFlowDiagnostics: false };
+ return { message: "/vc:login dismissed.", preserveFlowDiagnostics: false };
case "already":
return { message: "You're already logged in to Vercel.", preserveFlowDiagnostics: false };
case "cli-missing":
diff --git a/packages/eve/src/cli/dev/tui/setup-flow.ts b/packages/eve/src/cli/dev/tui/setup-flow.ts
index affbf616a..cfb35b7f0 100644
--- a/packages/eve/src/cli/dev/tui/setup-flow.ts
+++ b/packages/eve/src/cli/dev/tui/setup-flow.ts
@@ -1,5 +1,6 @@
import type { ChannelSetupChoice, ChannelSetupChoiceOptions } from "#setup/cli/index.js";
import type { SearchActionOption } from "#setup/cli/select-state.js";
+import type { ModelSettingsRequest, ModelSettingsResult } from "#setup/flows/model.js";
import type { ProviderPickerChoice, ProviderPickerRequest } from "#setup/flows/provider.js";
import type { SelectNotice } from "#setup/prompter.js";
@@ -79,6 +80,8 @@ export interface SetupFlowRenderer {
}): Promise<SetupEditableSelectResult | undefined>;
/** Provider-only picker with masked async validation. Not part of Prompter. */
readProviderPicker(options: ProviderPickerRequest): Promise<ProviderPickerChoice | undefined>;
+ /** Composite Change-model screen: catalog list, reasoning slider, tier toggle. Not part of Prompter. */
+ readModelEditor(options: ModelSettingsRequest): Promise<ModelSettingsResult | undefined>;
readText(options: {
message: string;
placeholder?: string;
diff --git a/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts b/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts
index 494810e49..e048b4a92 100644
--- a/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts
+++ b/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts
@@ -104,7 +104,7 @@ describe("BOOT_DETECTIONS against a real directory", () => {
const order: string[] = [];
const handle = vi.fn(async () => {
order.push("model");
- return { message: "/model cancelled." };
+ return { message: "/model dismissed." };
});
const readPrompt = vi.fn(async () => {
order.push("prompt");
diff --git a/packages/eve/src/cli/dev/tui/setup-panel.test.ts b/packages/eve/src/cli/dev/tui/setup-panel.test.ts
index 26c022297..ed99ec650 100644
--- a/packages/eve/src/cli/dev/tui/setup-panel.test.ts
+++ b/packages/eve/src/cli/dev/tui/setup-panel.test.ts
@@ -5,6 +5,7 @@ import { lineOf } from "./line-editor.js";
import {
renderAcknowledgeQuestion,
renderFlowPanel,
+ renderModelEditorQuestion,
renderSelectQuestion,
renderTextQuestion,
type SetupPanelOption,
@@ -392,8 +393,9 @@ describe("renderSelectQuestion", () => {
80,
).join("\n");
- // The reason sits under the row (4-space indent), not as an inline parenthetical.
- expect(text).toContain("Change model\n Disabled here");
+ // The reason sits under the row, indented to the label column, not as an
+ // inline parenthetical.
+ expect(text).toContain("Change model\n Disabled here");
expect(text).not.toContain("Change model (Disabled here)");
});
@@ -539,15 +541,16 @@ describe("renderSelectQuestion", () => {
colorTheme,
width,
);
- const row = rows.find((line) => line.includes("Invalid key"));
+ const row = rows.find((line) => line.includes("API key is not valid"));
const plain = stripAnsi(row ?? "");
expect(plain).toContain("…");
- expect(plain).toContain(" ⨯ Invalid key");
+ expect(plain).toContain("⨯ API key is not valid");
+ // The masked input rides the elbow rail.
+ expect(plain).toContain("⎿ ");
expect(plain.length).toBeLessThanOrEqual(width);
- expect(row).toContain(
- colorTheme.colors.red(`${colorTheme.glyph.error} ${colorTheme.colors.bold("Invalid key")}`),
- );
+ // The failure trails the masked key in plain red — no background.
+ expect(row).toContain(colorTheme.colors.red(`${colorTheme.glyph.error} API key is not valid`));
});
it("hides the rename cursor and hint when the cursor is off the editable row", () => {
@@ -705,6 +708,28 @@ describe("renderSelectQuestion", () => {
expect(unselectedRows).toContain(` ${colorTheme.colors.dim(hint)}`);
});
+ it("keeps a blue accent span inside the selected row's hint", () => {
+ const hint = `xai/grok-4.5${colorTheme.colors.blue("@high ↯")}`;
+ const options: SetupPanelOption[] = [
+ { value: "model", label: "Change model", hint },
+ { value: "done", label: "Done" },
+ ];
+ const rows = renderSelectQuestion(
+ {
+ kind: "stacked",
+ message: "",
+ options,
+ select: initialSelectState({ options, defaultValue: "model" }),
+ },
+ colorTheme,
+ 80,
+ );
+
+ // Blue survives the cursor row's foreground normalization; other authored
+ // colors (see the yellow test above) still strip.
+ expect(rows).toContain(` xai/grok-4.5${colorTheme.colors.blue("@high ↯")}`);
+ });
+
it("keeps a warning row yellow under the cursor highlight", () => {
const options: SetupPanelOption[] = [
{
@@ -776,12 +801,12 @@ describe("renderSelectQuestion", () => {
expect(text).toContain("space to toggle");
});
- it("windows a searchable list and advertises the rest", () => {
+ it("windows the railed list to five rows with an Esc-only footer", () => {
const many = Array.from({ length: 20 }, (_, index) => ({
value: `model-${index}`,
label: `Model ${index}`,
}));
- const text = renderSelectQuestion(
+ const rows = renderSelectQuestion(
{
kind: "search",
message: "Which model?",
@@ -791,12 +816,19 @@ describe("renderSelectQuestion", () => {
},
theme,
60,
- ).join("\n");
+ );
+ const text = rows.join("\n");
- expect(text).toContain("type to filter");
- expect(text).toContain("> type to filter");
- expect(text).toContain("↑↓ 20 options, showing 1–8");
- expect(text).not.toContain("Model 12");
+ // The filter rail sits in the option rows' glyph column.
+ expect(text).toContain(" ▏ type to filter");
+ expect(text).toContain(" ▶ Model 0");
+ expect(text).toContain(" ▏ Model 4");
+ expect(text).not.toContain("Model 5");
+ // The list scrolls silently: no count row, Esc is the whole footer.
+ expect(text).not.toContain("options, showing");
+ expect(text).toContain("esc to cancel");
+ expect(text).not.toContain("type to filter ·");
+ expect(text).not.toContain("↑/↓ move");
});
it("paints a validation error inside the question", () => {
@@ -968,3 +1000,156 @@ describe("renderAcknowledgeQuestion", () => {
expect(rows.filter((row) => row.trim().length > 0)).toHaveLength(2);
});
});
+
+describe("renderModelEditorQuestion", () => {
+ // Editor requests carry id-labeled rows (the flow's modelListRows mapping).
+ const MODEL_IDS = [
+ "anthropic/claude-sonnet-5",
+ "openai/gpt-5.6-sol",
+ "openai/gpt-5.6-terra",
+ "openai/gpt-5.6-luna",
+ "xai/grok-4.5",
+ "google/gemini-3.5",
+ "zai/glm-4.6",
+ "meta/llama-5",
+ "mistral/large-3",
+ "cohere/command-b",
+ ];
+ const MODELS = MODEL_IDS.map((id, index) =>
+ index < 2 ? { value: id, label: id, featured: true } : { value: id, label: id },
+ );
+
+ const CAPS = {
+ reasoning: true,
+ reasoningLevels: ["low", "medium", "high"],
+ fastMode: true,
+ } as const;
+
+ function editorRequest(overrides = {}) {
+ return {
+ model: { kind: "pick", options: MODELS, current: "anthropic/claude-sonnet-5" },
+ reasoning: null,
+ serviceTier: { kind: "standard" },
+ settingsEditable: true,
+ externalRouting: false,
+ capabilitiesFor: () => CAPS,
+ ...overrides,
+ } as never;
+ }
+
+ function editorState(overrides = {}) {
+ return {
+ screen: { kind: "menu", cursor: "model" },
+ draft: { modelId: "anthropic/claude-sonnet-5", reasoning: "medium", tier: "standard" },
+ capabilities: CAPS,
+ ...overrides,
+ } as never;
+ }
+
+ it("paints the value menu with a hint line per row and a bare Done", () => {
+ const text = renderModelEditorQuestion(
+ { request: editorRequest(), state: editorState() },
+ theme,
+ 80,
+ ).join("\n");
+
+ expect(text).toContain("▶ Model");
+ expect(text).toContain("anthropic/claude-sonnet-5");
+ expect(text).toContain("Reasoning effort");
+ // The mini track rides the hint: value first, notches joined by ━.
+ expect(text).toContain("●─◉─○ medium");
+ expect(text).toContain("Service tier");
+ expect(text).toContain("normal");
+ expect(text).toContain("Done");
+ expect(text).toContain("↑/↓ move");
+ });
+
+ it("summarizes a fast-mode draft and an unset level on the menu hints", () => {
+ const text = renderModelEditorQuestion(
+ {
+ request: editorRequest(),
+ state: editorState({
+ draft: { modelId: "anthropic/claude-sonnet-5", reasoning: "default", tier: "priority" },
+ }),
+ },
+ theme,
+ 80,
+ ).join("\n");
+
+ expect(text).toContain("○─○─○ provider default");
+ expect(text).toContain("fast ↯");
+ });
+
+ it("paints the hovered row's covered track stretch blue", () => {
+ const text = renderModelEditorQuestion(
+ {
+ request: editorRequest(),
+ state: editorState({ screen: { kind: "menu", cursor: "reasoning" } }),
+ },
+ colorTheme,
+ 80,
+ ).join("\n");
+
+ expect(text).toContain(`${colorTheme.colors.blue("●─◉")}─○`);
+ });
+
+ it("disables the reasoning row with its reason and omits the tier for a no-frills model", () => {
+ const noFrills = { reasoning: false, reasoningLevels: [], fastMode: false };
+ const text = renderModelEditorQuestion(
+ {
+ request: editorRequest(),
+ state: editorState({
+ capabilities: noFrills,
+ draft: { modelId: "test/no-frills", reasoning: "default", tier: "standard" },
+ }),
+ },
+ theme,
+ 80,
+ ).join("\n");
+
+ expect(text).toContain("Not supported by the selected model");
+ expect(text).not.toContain("Service tier");
+ });
+
+ it("lists model ids on a caret rail with an inverse cursor row and enter badge", () => {
+ const rows = renderModelEditorQuestion(
+ {
+ request: editorRequest(),
+ state: editorState({
+ screen: {
+ kind: "model",
+ select: initialSelectState({ options: MODELS, defaultValue: "openai/gpt-5.6-sol" }),
+ },
+ }),
+ },
+ theme,
+ 80,
+ );
+ const text = rows.join("\n");
+
+ expect(text).toContain("Select the model");
+ expect(text).toContain(" ▏ type to search");
+ expect(text).toContain(" ▶ openai/gpt-5.6-sol ");
+ expect(text).toContain("↵");
+ expect(text).toContain(" ▏ anthropic/claude-sonnet-5");
+ // Five rows in view, no count row, Esc-only footer.
+ expect(text).toContain("openai/gpt-5.6-luna");
+ expect(text).not.toContain("google/gemini-3.5");
+ expect(text).not.toContain("options, showing");
+ expect(text).toContain("esc to cancel");
+ });
+
+ it("falls back to ASCII track glyphs without unicode", () => {
+ const ascii = createTheme({ color: false, unicode: false });
+ const text = renderModelEditorQuestion(
+ {
+ request: editorRequest(),
+ state: editorState({ screen: { kind: "menu", cursor: "reasoning" } }),
+ },
+ ascii,
+ 80,
+ ).join("\n");
+
+ expect(text).toContain("*-O-. medium");
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/setup-panel.ts b/packages/eve/src/cli/dev/tui/setup-panel.ts
index 1babe8a43..b765f3105 100644
--- a/packages/eve/src/cli/dev/tui/setup-panel.ts
+++ b/packages/eve/src/cli/dev/tui/setup-panel.ts
@@ -28,7 +28,14 @@ import {
type SelectState,
} from "#setup/cli/select-state.js";
import type { SelectNotice } from "#setup/prompter.js";
+import type { ModelSettingsRequest } from "#setup/flows/model.js";
+import {
+ modelEditorMenuRows,
+ reasoningPositions,
+ type ModelEditorRowId,
+ type ModelEditorState,
+} from "./model-editor.js";
import type { ProviderPickerPhase } from "./provider-picker.js";
import { maskLine, visibleLine, type LineState } from "./line-editor.js";
import type { Theme } from "./theme.js";
@@ -60,6 +67,8 @@ interface SetupSelectPanelBase extends SetupQuestionPanelBase {
select: SelectState;
/** Live frame rendered beside a searchable input while it loads replacement rows. */
loadingFrame?: string;
+ /** A dim-inverse affordance appended to the cursor row, e.g. ` ↵ change `. */
+ cursorBadge?: string;
}
/**
@@ -190,6 +199,9 @@ export interface FlowPanelState {
/** How many option rows a searchable panel shows before windowing. */
const SEARCH_VIEW_SIZE = 8;
+/** The railed searchable list's constant viewport. */
+const RAILED_VIEW_SIZE = 5;
+
/** The flow panel keeps only the freshest progress in view. */
const FLOW_PANEL_LINE_CAP = 6;
@@ -201,6 +213,8 @@ function questionFooter(hints: readonly string[], theme: Theme): string[] {
const BOLD_OR_DIM_CLOSE = "\x1b[22m";
const DIM_OPEN = "\x1b[2m";
const ANSI_FOREGROUND_COLOR = new RegExp(`${String.fromCharCode(27)}\\[(?:3[0-9]|9[0-7])m`, "g");
+const BLUE_OPEN = "\x1b[34m";
+const FOREGROUND_RESET = "\x1b[39m";
/**
* Dims a line that may carry embedded bold spans (e.g. a flow bolding a
@@ -219,7 +233,21 @@ function solidWithinDim(text: string, theme: Theme): string {
/** A selected row must not inherit an authored hint color. */
function foregroundWithEmphasis(text: string): string {
- return text.replaceAll(DIM_OPEN, "").replace(ANSI_FOREGROUND_COLOR, "");
+ // Blue is the accent the selected row keeps (drafted values, adjust hints);
+ // every other authored color normalizes to the highlight's foreground, and a
+ // reset survives only when it closes a kept blue span.
+ let blueOpen = false;
+ return text.replaceAll(DIM_OPEN, "").replace(ANSI_FOREGROUND_COLOR, (code) => {
+ if (code === BLUE_OPEN) {
+ blueOpen = true;
+ return code;
+ }
+ if (code === FOREGROUND_RESET && blueOpen) {
+ blueOpen = false;
+ return code;
+ }
+ return "";
+ });
}
function toneGlyph(tone: FlowPanelLine["tone"], theme: Theme): string {
@@ -318,18 +346,21 @@ function optionRow(input: {
isCursor: boolean;
isChecked: boolean;
placeholder: boolean;
+ /** Railed lists lead resting rows with the `▏` rail and drop the hint dot. */
+ railed?: boolean;
hintPadding?: number;
theme: Theme;
}): string {
const { option, theme } = input;
+ const railed = input.railed === true;
return renderOptionRow({
colors: theme.colors,
glyphs: {
pointer: theme.glyph.pointer,
selectedPointer: theme.glyph.selectedPointer,
success: theme.glyph.success,
- placeholder: theme.glyph.option,
- dot: theme.glyph.dot,
+ placeholder: railed ? theme.glyph.caret : theme.glyph.option,
+ dot: railed ? "" : theme.glyph.dot,
warning: theme.glyph.warning,
},
label: option.label,
@@ -397,10 +428,16 @@ function searchFilter(
placeholder: string | undefined,
loadingFrame: string | undefined,
theme: Theme,
+ railed: boolean,
): string {
const caret = theme.colors.dim(theme.glyph.caret);
let input = caret;
- if (filter.length > 0) {
+ if (railed) {
+ // The railed list's filter line: `▏ query▏`, or the dim placeholder.
+ input = `${caret} ${
+ filter.length > 0 ? filter + caret : theme.colors.dim(placeholder ?? "type to search")
+ }`;
+ } else if (filter.length > 0) {
input = filter + caret;
} else if (placeholder !== undefined) {
input = theme.colors.dim(`> ${placeholder}`);
@@ -409,13 +446,31 @@ function searchFilter(
return `${input} ${theme.colors.yellow(loadingFrame)}`;
}
+/**
+ * Whether a select renders as the railed searchable list — the one component
+ * behind the model catalog, team, and project pickers: `▏`-railed rows, an
+ * inverse cursor row trailed by the `↵` badge, and a rail-led filter line.
+ */
+function isRailedSearch(presentation: SelectPresentation): boolean {
+ return (
+ presentation.filter !== undefined &&
+ presentation.layout === "plain" &&
+ presentation.selection === "single" &&
+ presentation.edit === undefined
+ );
+}
+
function selectViewSize(input: {
search: boolean;
filter: string;
featuredLead: number;
optionCount: number;
+ railed: boolean;
}): number {
if (!input.search) return input.optionCount;
+ // The railed list keeps a constant five-row viewport; other searchable
+ // presentations open on their featured lead when one exists.
+ if (input.railed) return RAILED_VIEW_SIZE;
if (input.filter === "" && input.featuredLead > 0) {
return Math.min(input.featuredLead, SEARCH_VIEW_SIZE);
}
@@ -461,19 +516,25 @@ function keyHint(
const phase = key.phase;
if (phase.kind === "inactive") return option;
+ const c = theme.colors;
const display = maskLine(phase.editor);
const cursorEnabled = phase.kind !== "validating" && phase.kind !== "invalid";
- let prefix = "";
+ // The state badge trails the input: `↵ validate` while editing, a yellow
+ // `▪ validating` while the check runs, a red refusal afterward — all
+ // background-free.
let suffix = "";
- if (phase.kind === "validating") {
- prefix = "Validating… ";
+ if (phase.kind === "editing") {
+ suffix = ` ${enterBadge(theme, "validate")}`;
+ } else if (phase.kind === "validating") {
+ suffix = ` ${c.yellow(theme.glyph.validating)} ${c.dim("validating")}`;
} else if (phase.kind === "invalid") {
- suffix = ` ${theme.colors.red(`${theme.glyph.error} ${theme.colors.bold("Invalid key")}`)}`;
+ suffix = ` ${c.red(`${theme.glyph.error} API key is not valid`)}`;
}
+ const rail = `${theme.glyph.elbow} `;
const placeholder = phase.editor.text.length === 0 ? "type your key" : undefined;
const cursorLine = placeholder === undefined ? display : { text: placeholder, cursor: 0 };
- const inputWidth = Math.max(1, maxHintWidth - visibleLength(`> ${prefix}${suffix}`));
+ const inputWidth = Math.max(1, maxHintWidth - visibleLength(`${rail}${suffix}`));
const visible = visibleLine(cursorLine, inputWidth, theme.glyph.ellipsis);
const value = cursorEnabled
? renderInputWithBlockCursor({
@@ -482,7 +543,7 @@ function keyHint(
inverse: theme.colors.inverse,
})
: renderInputText(`${visible.before}${visible.under}${visible.after}`);
- return { ...option, hint: `> ${prefix}${value}${suffix}` };
+ return { ...option, hint: `${rail}${value}${suffix}` };
}
/**
@@ -580,15 +641,25 @@ function appendSelectOptionRows(input: {
rendered,
presentation.layout,
);
+ const railed = isRailedSearch(presentation);
+ // Railed lists carry the Enter affordance on the cursor row by default;
+ // an explicit cursorBadge (the provider picker's `↵ change`) still wins.
+ const rowBadge =
+ state.cursorBadge ?? (railed && !isTrailingTaskAction ? enterBadge(theme) : undefined);
+ const badge = isCursor && rowBadge !== undefined ? ` ${rowBadge}` : "";
rows.push(
` ${optionRow({
option: rowOption,
isCursor,
- isChecked: presentation.selection === "multiple" && state.select.selected.has(option.value),
- placeholder: optionUsesPlaceholder(presentation, isTrailingTaskAction),
+ isChecked:
+ presentation.selection === "multiple"
+ ? state.select.selected.has(option.value)
+ : option.checked === true,
+ placeholder: railed || optionUsesPlaceholder(presentation, isTrailingTaskAction),
+ railed,
hintPadding: Math.max(0, visibleLabelWidth - rowOption.label.length),
theme,
- })}`,
+ })}${badge}`,
);
if (stackedHint !== undefined) {
@@ -611,12 +682,7 @@ function appendSelectOptionRows(input: {
// Disabled descriptions explain why an inert row cannot be selected, so
// keep them visible even though the cursor skips that row.
if (option.description !== undefined && (option.disabled === true || isCursor)) {
- const description = c.dim(option.description);
- rows.push(
- presentation.layout === "stacked"
- ? ` ${renderOptionRowContinuation(description)}`
- : ` ${description}`,
- );
+ rows.push(` ${renderOptionRowContinuation(c.dim(option.description))}`);
}
if (presentation.layout === "stacked" && index < end - 1) rows.push("");
}
@@ -729,15 +795,19 @@ export function renderSelectQuestion(
const submitIndex = presentation.selection === "multiple" ? submitRowIndex(visible) : -1;
const cursor = state.select.cursor;
+ const railed = isRailedSearch(presentation);
const rows = selectMessageRows(state.message, presentation.layout, theme);
if (presentation.filter !== undefined) {
+ // The railed filter line indents one extra cell so its rail sits in the
+ // option rows' glyph column.
rows.push(
- ` ${searchFilter(
+ ` ${railed ? " " : ""}${searchFilter(
state.select.filter,
presentation.filter.placeholder,
state.loadingFrame,
theme,
+ railed,
)}`,
);
}
@@ -749,6 +819,7 @@ export function renderSelectQuestion(
filter: state.select.filter,
featuredLead,
optionCount: visible.length,
+ railed,
});
const start = Math.max(
0,
@@ -783,7 +854,9 @@ export function renderSelectQuestion(
});
appendSubmitRow(rows, cursor, submitIndex, theme);
- if (visible.length > end - start) {
+ // The railed list scrolls silently: no count row, and Esc is the only
+ // footer hint — typing, arrows, and the ↵ badge carry themselves.
+ if (!railed && visible.length > end - start) {
rows.push(` ${c.dim(`↑↓ ${visible.length} options, showing ${start + 1}–${end}`)}`);
}
@@ -795,10 +868,165 @@ export function renderSelectQuestion(
rows.push("", ` ${c.red(state.error)}`);
}
- rows.push(...questionFooter(selectFooterHints(presentation, visible, cursor), theme));
+ rows.push(
+ ...questionFooter(
+ railed ? ["esc to cancel"] : selectFooterHints(presentation, visible, cursor),
+ theme,
+ ),
+ );
return rows.map((row) => clip(row, width));
}
+/** The composite Change-model screen's inputs: the resolved request plus live state. */
+export interface ModelEditorPanelInput {
+ request: ModelSettingsRequest;
+ state: ModelEditorState;
+}
+
+const MODEL_EDITOR_MESSAGE = "Select the model";
+
+/**
+ * A dim, background-free selection badge carrying the Enter affordance, e.g.
+ * `↵`, `↵ change`, `↵ validate`.
+ */
+export function enterBadge(theme: Theme, label?: string): string {
+ const c = theme.colors;
+ return c.dim(label === undefined ? theme.glyph.enter : `${theme.glyph.enter} ${label}`);
+}
+
+/**
+ * A discrete reasoning track: `●` below the current notch, `◉` on it, `○`
+ * above, joined by `─` connectors. `accent` paints the covered stretch —
+ * notches and connectors up to the current position — blue. `index` -1 means
+ * unset: an all-`○` track with no fill.
+ */
+export function reasoningTrack(input: {
+ count: number;
+ index: number;
+ connectorWidth: number;
+ accent: boolean;
+ theme: Theme;
+}): string {
+ const { count, index, theme } = input;
+ const glyphs = theme.glyph;
+ const connector = glyphs.trackLine.repeat(input.connectorWidth);
+ const pieces: string[] = [];
+ for (let at = 0; at < count; at += 1) {
+ if (at > 0) pieces.push(connector);
+ pieces.push(
+ at < index ? glyphs.trackFilled : at === index ? glyphs.trackCurrent : glyphs.trackEmpty,
+ );
+ }
+ if (!input.accent || index < 0) return pieces.join("");
+ // Pieces alternate notch/connector; the covered stretch ends at the current
+ // notch, which sits at piece position 2 * index.
+ const covered = pieces.slice(0, 2 * index + 1).join("");
+ return `${theme.colors.blue(covered)}${pieces.slice(2 * index + 1).join("")}`;
+}
+
+/**
+ * Paints the Change-model screen: a value menu whose reasoning and tier rows
+ * adjust inline with left/right, and whose Model row opens the searchable
+ * catalog.
+ */
+export function renderModelEditorQuestion(
+ input: ModelEditorPanelInput,
+ theme: Theme,
+ width: number,
+): string[] {
+ const { request, state } = input;
+ switch (state.screen.kind) {
+ case "menu":
+ return renderModelEditorMenu(input, state.screen.cursor, theme, width);
+ case "model":
+ return renderModelEditorModelScreen(request, state.screen.select, theme, width);
+ }
+}
+
+/**
+ * The value menu rides the ordinary stacked-select painter: each row's hint
+ * line is the drafted value (mini track, `fast ↯`, the slug), dim at rest and
+ * accent-keeping under the cursor.
+ */
+function renderModelEditorMenu(
+ input: ModelEditorPanelInput,
+ cursor: ModelEditorRowId,
+ theme: Theme,
+ width: number,
+): string[] {
+ const { request, state } = input;
+ const { draft } = state;
+ const rows = modelEditorMenuRows(request, draft, state.capabilities);
+
+ const options: SetupPanelOption[] = rows.map((row) => {
+ if (row.disabled === true && row.value === "model") {
+ // The fixed model still shows its id; the description carries the reason.
+ return draft.modelId === null ? { ...row } : { ...row, hint: draft.modelId };
+ }
+ if (row.disabled === true || row.value === "done") return { ...row };
+ switch (row.value) {
+ case "model":
+ return { ...row, hint: draft.modelId ?? undefined };
+ case "reasoning": {
+ const positions = reasoningPositions(state.capabilities, draft.reasoning);
+ const index = draft.reasoning === "default" ? -1 : positions.indexOf(draft.reasoning);
+ const track = reasoningTrack({
+ count: positions.length,
+ index,
+ connectorWidth: 1,
+ accent: row.value === cursor,
+ theme,
+ });
+ const level = draft.reasoning === "default" ? "provider default" : draft.reasoning;
+ // Track first: the notches hold a fixed column while the
+ // variable-width level name trails, so nothing jumps on adjust.
+ return { ...row, hint: `${track} ${level}` };
+ }
+ case "tier":
+ return { ...row, hint: draft.tier === "priority" ? `fast ${theme.glyph.fast}` : "normal" };
+ default:
+ return { ...row };
+ }
+ });
+
+ const index = Math.max(
+ 0,
+ options.findIndex((option) => option.value === cursor),
+ );
+ return renderSelectQuestion(
+ {
+ kind: "stacked",
+ message: "",
+ options,
+ select: { filter: "", cursor: index, selected: new Set() },
+ },
+ theme,
+ width,
+ );
+}
+
+/** The catalog sub-screen: `▏`-railed id rows under a `▏` filter line. */
+function renderModelEditorModelScreen(
+ request: ModelSettingsRequest,
+ select: SelectState,
+ theme: Theme,
+ width: number,
+): string[] {
+ // The catalog list IS the shared railed searchable select — the same
+ // component behind the team and project pickers.
+ return renderSelectQuestion(
+ {
+ kind: "search",
+ message: MODEL_EDITOR_MESSAGE,
+ options: request.model.kind === "pick" ? request.model.options : [],
+ placeholder: "type to search",
+ select,
+ },
+ theme,
+ width,
+ );
+}
+
/** Paints a text question section: message, a block-cursor input line, hints. */
export function renderTextQuestion(
state: SetupTextPanelState,
diff --git a/packages/eve/src/cli/dev/tui/status-line.test.ts b/packages/eve/src/cli/dev/tui/status-line.test.ts
index 03fe30f5a..68651bbd7 100644
--- a/packages/eve/src/cli/dev/tui/status-line.test.ts
+++ b/packages/eve/src/cli/dev/tui/status-line.test.ts
@@ -50,30 +50,66 @@ describe("buildStatusLine", () => {
expect(line).not.toContain("\x1b[7m\x1b[34m :3000 ");
});
- it("renders all segments in order with dot separators", () => {
+ it("renders all segments in order with whitespace separators", () => {
const line = buildStatusLine({
model: "anthropic/claude-sonnet-5",
- tokens: "12,300 tokens 6%",
endpoint: connected,
vercel: { identity, pendingDeploy: true },
theme: plain,
width: 120,
});
- expect(line).toBe(
- "anthropic/claude-sonnet-5 · 12,300 tokens 6% · AI Gateway (my-agent) · /deploy pending",
- );
+ expect(line).toBe("anthropic/claude-sonnet-5 AI Gateway (my-agent) /deploy pending");
+ });
+
+ it("folds the reasoning level and Fast mode marker into the model segment", () => {
+ const line = buildStatusLine({
+ model: "xai/grok-4.5",
+ reasoning: "xhigh",
+ fastMode: true,
+ endpoint: connected,
+ vercel: { identity, pendingDeploy: false },
+ theme: plain,
+ width: 120,
+ });
+
+ expect(line).toBe("xai/grok-4.5@xhigh ↯ AI Gateway (my-agent)");
+ });
+
+ it("dims the whole model segment, reasoning level and fast marker included", () => {
+ const line = buildStatusLine({
+ model: "xai/grok-4.5",
+ reasoning: "xhigh",
+ fastMode: true,
+ theme,
+ width: 120,
+ })!;
+
+ expect(line).toContain("\x1b[2mxai/grok-4.5@xhigh ↯\x1b[22m");
+ });
+
+ it("renders the fast marker with ASCII glyphs when unicode is unavailable", () => {
+ const line = buildStatusLine({
+ model: "xai/grok-4.5",
+ fastMode: true,
+ theme: ascii,
+ width: 120,
+ });
+
+ expect(line).toBe("xai/grok-4.5 >>");
});
it("strips terminal controls from a remote model id", () => {
expect(
buildStatusLine({
model: "openai/gpt\x1b[31m-5\n",
+ reasoning: "high",
+ fastMode: true,
remote: remote({ state: "ready", info: {} as never }),
theme: plain,
width: 120,
}),
- ).toBe(" ↗ vpoke.playground-vercel.tools openai/gpt-5");
+ ).toBe(" ↗ vpoke.playground-vercel.tools openai/gpt-5@high ↯");
});
it("dims every segment except the yellow pending-deploy marker", () => {
@@ -98,7 +134,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(withProject).toBe("m · AI Gateway (my-agent)");
+ expect(withProject).toBe("m AI Gateway (my-agent)");
// Connected without a linked project (a raw key): bare "AI Gateway".
const noProject = buildStatusLine({
@@ -107,7 +143,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(noProject).toBe("m · AI Gateway");
+ expect(noProject).toBe("m AI Gateway");
});
it("renders the pending marker even when no segment else resolved", () => {
@@ -123,14 +159,13 @@ describe("buildStatusLine", () => {
const input = {
logLevel: "sandbox",
model: "anthropic/claude-sonnet-5",
- tokens: "↑ 500 ↓ 300",
endpoint: connected,
vercel: { identity, pendingDeploy: true },
theme: plain,
} as const;
const full = buildStatusLine({ ...input, width: 120 })!;
- expect(full.startsWith("logs: sandbox · ")).toBe(true);
+ expect(full.startsWith("logs: sandbox ")).toBe(true);
// Narrow enough that only the leading hint survives.
expect(buildStatusLine({ ...input, width: 13 })).toBe("logs: sandbox");
@@ -150,7 +185,6 @@ describe("buildStatusLine", () => {
it("drops the endpoint, then the model, as the width narrows", () => {
const input = {
model: "anthropic/claude-sonnet-5",
- tokens: "12,300 tokens",
endpoint: connected,
vercel: { identity, pendingDeploy: true },
theme: plain,
@@ -163,7 +197,7 @@ describe("buildStatusLine", () => {
expect(noEndpoint).toContain("anthropic/claude-sonnet-5");
const noModel = buildStatusLine({ ...input, width: visibleLength(noEndpoint) - 1 })!;
- expect(noModel).toBe("12,300 tokens · /deploy pending");
+ expect(noModel).toBe("/deploy pending");
});
it("renders the three model-endpoint states", () => {
@@ -173,7 +207,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(external).toBe("anthropic/claude-sonnet-5 · External endpoint");
+ expect(external).toBe("anthropic/claude-sonnet-5 External endpoint");
const linked = buildStatusLine({
model: "m",
@@ -182,7 +216,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(linked).toBe("m · AI Gateway (my-agent)");
+ expect(linked).toBe("m AI Gateway (my-agent)");
const notConnected = buildStatusLine({
model: "m",
@@ -190,7 +224,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(notConnected).toBe("m · ⚠ AI Gateway");
+ expect(notConnected).toBe("m ⚠ AI Gateway");
});
it("paints only the not-connected endpoint yellow", () => {
@@ -216,7 +250,7 @@ describe("buildStatusLine", () => {
theme: ascii,
width: 120,
});
- expect(stripAnsi(line!)).toBe("m - ! AI Gateway");
+ expect(stripAnsi(line!)).toBe("m ! AI Gateway");
});
it("renders the remote badge first and projects each authentication state", () => {
@@ -226,7 +260,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
}),
- ).toBe(" ↗ vpoke.playground-vercel.tools · Checking access…");
+ ).toBe(" ↗ vpoke.playground-vercel.tools Checking access…");
expect(
buildStatusLine({
remote: remote({
@@ -236,7 +270,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
}),
- ).toBe(" ↗ vpoke.playground-vercel.tools · Authenticate via OIDC");
+ ).toBe(" ↗ vpoke.playground-vercel.tools Authenticate via OIDC");
expect(
buildStatusLine({
remote: remote({
@@ -246,7 +280,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
}),
- ).toBe(" ↗ vpoke.playground-vercel.tools · Authenticating via OIDC…");
+ ).toBe(" ↗ vpoke.playground-vercel.tools Authenticating via OIDC…");
expect(
buildStatusLine({
remote: remote({
@@ -256,7 +290,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
}),
- ).toBe(" ↗ vpoke.playground-vercel.tools · Authentication failed");
+ ).toBe(" ↗ vpoke.playground-vercel.tools Authentication failed");
expect(
buildStatusLine({
remote: remote({
@@ -266,7 +300,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
}),
- ).toBe(" ↗ vpoke.playground-vercel.tools · Remote unavailable");
+ ).toBe(" ↗ vpoke.playground-vercel.tools Remote unavailable");
expect(
buildStatusLine({
remote: deployedRemote({ state: "ready", info: {} as never }),
@@ -318,7 +352,6 @@ describe("buildStatusLine", () => {
const line = buildStatusLine({
remote: deployedRemote({ state: "ready", info: {} as never }),
model: "openai/gpt-5.5",
- tokens: "↑ 200 ↓ 100",
endpoint: { kind: "gateway", connected: false },
theme,
width: 120,
@@ -330,7 +363,6 @@ describe("buildStatusLine", () => {
buildStatusLine({
remote: deployedRemote({ state: "ready", info: {} as never }),
model: "openai/gpt-5.5",
- tokens: "↑ 200 ↓ 100",
theme: plain,
width: 24,
})!,
@@ -350,12 +382,12 @@ describe("buildStatusLine", () => {
expect(stripAnsi(line ?? "")).toBe(" ↗ inbou");
});
- it("uses the ASCII separator when unicode is unavailable", () => {
+ it("keeps whitespace separators when unicode is unavailable", () => {
const line = buildStatusLine({
remote: remote({ state: "checking" }),
theme: ascii,
width: 120,
});
- expect(line).toBe(" -> vpoke.playground-vercel.tools - Checking access…");
+ expect(line).toBe(" -> vpoke.playground-vercel.tools Checking access…");
});
});
diff --git a/packages/eve/src/cli/dev/tui/status-line.ts b/packages/eve/src/cli/dev/tui/status-line.ts
index 86b3c1a18..24c81c140 100644
--- a/packages/eve/src/cli/dev/tui/status-line.ts
+++ b/packages/eve/src/cli/dev/tui/status-line.ts
@@ -5,14 +5,17 @@ import type { RemoteConnectionSnapshot } from "./remote-connection.js";
import { remoteHost } from "./target.js";
import type { VercelStatusSnapshot } from "./vercel-status.js";
import type { ModelEndpointStatus } from "#shared/model-endpoint-status.js";
+import { formatModelSummary } from "#shared/model-summary.js";
export interface StatusLineInput {
/** Port of the connected local development server; omitted for remote sessions. */
serverPort?: string;
/** Resolved model slug, e.g. "anthropic/claude-sonnet-5"; absent when `/eve/v1/info` failed. */
model?: string;
- /** Preformatted token-flow segment (formatTokenFlow output), e.g. `↑ 394.4K ↓ 4.3K`. */
- tokens?: string;
+ /** Authored reasoning effort, rendered bold after the model id, e.g. `(xhigh)`. */
+ reasoning?: string;
+ /** True when the Gateway priority tier is on; renders a `»fast` marker. */
+ fastMode?: boolean;
/**
* Transient dev-TUI log-display mode shown after a Ctrl+L cycle, e.g.
* `sandbox`. Rendered as a prominent leading `logs: <mode>` segment that
@@ -31,12 +34,22 @@ export interface StatusLineInput {
}
function renderModel(
- input: Pick<StatusLineInput, "model" | "remote" | "theme">,
+ input: Pick<StatusLineInput, "model" | "reasoning" | "fastMode" | "remote" | "theme">,
): string | undefined {
if (input.model === undefined) return undefined;
- const model =
- input.remote === undefined ? input.model : stripAnsi(input.model).replace(/\s+/gu, " ").trim();
- return input.theme.colors.dim(model);
+ const c = input.theme.colors;
+ const summary: Parameters<typeof formatModelSummary>[0] = { model: input.model };
+ if (input.reasoning !== undefined) summary.reasoning = input.reasoning;
+ if (input.fastMode === true) summary.fastGlyph = input.theme.glyph.fast;
+ if (input.remote !== undefined) {
+ // Sanitize the untrusted remote id before appending suffixes, so its
+ // trailing whitespace is trimmed instead of collapsing into an interior
+ // space ahead of the reasoning level.
+ summary.model = stripAnsi(input.model).replace(/\s+/gu, " ").trim();
+ const plain = stripAnsi(formatModelSummary(summary)).replace(/\s+/gu, " ").trim();
+ return c.dim(plain);
+ }
+ return c.dim(formatModelSummary(summary));
}
function renderServerPort(
@@ -61,10 +74,10 @@ function renderEndpoint(
}
/**
- * Builds a leading local `:port` or remote badge followed by model, token, and
- * deploy status segments. Both badges are the final narrow-width fallback.
- * Remote sessions omit endpoint state. Returns undefined when every segment is
- * empty.
+ * Builds a leading local `:port` or remote badge followed by the model (with
+ * its reasoning level and Fast mode marker), endpoint, and deploy status
+ * segments. Both badges are the final narrow-width fallback. Remote sessions
+ * omit endpoint state. Returns undefined when every segment is empty.
*/
export function buildStatusLine(input: StatusLineInput): string | undefined {
const { theme, width } = input;
@@ -73,14 +86,14 @@ export function buildStatusLine(input: StatusLineInput): string | undefined {
const logLevel = input.logLevel === undefined ? undefined : c.cyan(`logs: ${input.logLevel}`);
const serverPort = renderServerPort(input);
const model = renderModel(input);
- const tokens = input.tokens === undefined ? undefined : c.dim(input.tokens);
const pending = input.vercel?.pendingDeploy ? c.yellow("/deploy pending") : undefined;
const remote = input.remote === undefined ? undefined : formatRemoteStatus(input.remote, theme);
const endpoint = renderEndpoint(input);
const leading = remote?.full ?? serverPort;
const badge = remote?.badge ?? serverPort;
- const separator = ` ${c.dim(theme.glyph.dot)} `;
+ // Whitespace separators: the dim segments read as columns without bullets.
+ const separator = " ";
const compose = (
target: string | undefined,
segments: ReadonlyArray<string | undefined>,
@@ -94,9 +107,9 @@ export function buildStatusLine(input: StatusLineInput): string | undefined {
// leads every variant and gets the final stand-alone fallback. Without one,
// the logs hint retains its previous priority.
const variants = [
- compose(leading, [logLevel, model, tokens, endpoint, pending]),
- compose(leading, [logLevel, model, tokens, pending]),
- compose(leading, [logLevel, tokens, pending]),
+ compose(leading, [logLevel, model, endpoint, pending]),
+ compose(leading, [logLevel, model, pending]),
+ compose(leading, [logLevel, pending]),
compose(leading, [logLevel]),
compose(badge, [logLevel]),
compose(badge, []),
@@ -122,7 +135,8 @@ function formatRemoteStatus(
: `${snapshot.deployment.projectName} (${snapshot.deployment.environment})`;
const arrow = theme.unicode ? "↗" : "->";
const badge = formatRemoteBadge(` ${arrow} ${label} `, snapshot.connection.state, theme);
- const separator = `${c.dim(theme.glyph.dot)} `;
+ // The badge carries its own trailing pad, so one space reads as a column gap.
+ const separator = " ";
let suffix: string | undefined;
switch (snapshot.connection.state) {
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
index 92942ea41..28cbcaeb9 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it, vi } from "vitest";
import type { AgentInfoResult } from "#client/index.js";
+import type { LogRecord } from "#internal/logging.js";
+import type { DevDiagnostics } from "../diagnostics.js";
import { searchActionValue } from "#setup/cli/select-state.js";
import {
AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,
@@ -36,9 +38,49 @@ function makeRenderer(columns = 80, rows = 30) {
return { screen, input, renderer };
}
+function stubDiagnostics() {
+ const append = vi.fn();
+ const recordPrompt = vi.fn();
+ const recordStepUsage = vi.fn();
+ const recordToolCall = vi.fn();
+ const recordSubagentDispatch = vi.fn();
+ const reportStats = vi.fn();
+ let subscriber: ((record: LogRecord) => void) | undefined;
+ const diagnostics: DevDiagnostics = {
+ displayPath: ".eve/logs/dev.log",
+ append,
+ recordPrompt,
+ recordStepUsage,
+ recordToolCall,
+ recordSubagentDispatch,
+ reportStats,
+ subscribeLogRecords: (onRecord) => {
+ subscriber = onRecord;
+ },
+ unsubscribeLogRecords: () => {
+ subscriber = undefined;
+ },
+ close: async () => {},
+ };
+ return {
+ diagnostics,
+ append,
+ recordPrompt,
+ recordStepUsage,
+ recordToolCall,
+ recordSubagentDispatch,
+ reportStats,
+ emitLogRecord: (record: LogRecord) => subscriber?.(record),
+ get subscribed() {
+ return subscriber !== undefined;
+ },
+ };
+}
+
function agentInfoWithModel(
modelId: string,
endpoint?: AgentInfoResult["agent"]["model"]["endpoint"],
+ extras?: Partial<AgentInfoResult["agent"]["model"]>,
): AgentInfoResult {
return {
agent: {
@@ -47,6 +89,7 @@ function agentInfoWithModel(
model: {
id: modelId,
endpoint,
+ ...extras,
},
name: "Weather Agent",
},
@@ -817,10 +860,10 @@ describe("TerminalRenderer (inline scrollback)", () => {
it("hangs a command outcome under its invocation with the elbow connector", () => {
const { screen, renderer } = makeRenderer();
- renderer.renderCommandResult("/model cancelled.");
+ renderer.renderCommandResult("/model dismissed.");
renderer.shutdown();
- expect(screen.snapshot()).toContain("\u23bf /model cancelled.");
+ expect(screen.snapshot()).toContain("\u23bf /model dismissed.");
});
it("marks a failed automatic command and keeps its multiline outcome in one result block", () => {
@@ -1209,6 +1252,223 @@ describe("TerminalRenderer (inline scrollback)", () => {
);
});
+ it("stores long stderr diagnostics and shows concise copy by default", () => {
+ const screen = new MockScreen({ columns: 100, rows: 30 });
+ const input = new MockUserInput();
+ const stub = stubDiagnostics();
+ const append = stub.append;
+ const renderer = new TerminalRenderer({
+ input,
+ output: screen,
+ captureForeignOutput: true,
+ logs: "stderr",
+ unicode: true,
+ diagnostics: stub.diagnostics,
+ });
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+ const detail = [
+ "Error: request returned 403",
+ " at first",
+ " at second",
+ " at third",
+ " at fourth",
+ ].join("\n");
+
+ process.stderr.write(`${detail}\n`);
+
+ expect(append).toHaveBeenCalledWith({ source: "stderr", detail });
+ expect(screen.snapshot()).toContain("Error: request returned 403");
+ expect(screen.snapshot()).toContain("details: .eve/logs/dev.log");
+ expect(screen.snapshot()).not.toContain("at fourth");
+
+ renderer.setLogDisplayMode("all");
+ expect(screen.snapshot()).toContain("at fourth");
+ expect(screen.snapshot()).not.toContain("details: .eve/logs/dev.log");
+
+ process.stdout.write("server listening on 3000\n");
+ expect(append).toHaveBeenCalledWith({ source: "stdout", detail: "server listening on 3000" });
+ renderer.shutdown();
+ });
+
+ it("subscribes the recorder to log records, displays them, and releases on shutdown", () => {
+ const screen = new MockScreen({ columns: 120, rows: 30 });
+ const input = new MockUserInput();
+ const stub = stubDiagnostics();
+ const renderer = new TerminalRenderer({
+ input,
+ output: screen,
+ captureForeignOutput: true,
+ logs: "stderr",
+ unicode: true,
+ diagnostics: stub.diagnostics,
+ });
+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
+
+ expect(stub.subscribed).toBe(true);
+ stub.emitLogRecord({
+ level: "error",
+ namespace: "harness.tool-loop",
+ message: "tool execution failed",
+ fields: { toolName: "always_fail" },
+ });
+ expect(screen.snapshot()).toContain("[eve:harness.tool-loop] tool execution failed");
+
+ renderer.shutdown();
+ expect(stub.subscribed).toBe(false);
+ });
+
+ it("records tool failures in the diagnostic log even when tools are hidden", async () => {
+ const screen = new MockScreen({ columns: 80, rows: 30 });
+ const input = new MockUserInput();
+ const stub = stubDiagnostics();
+ const append = stub.append;
+ const renderer = new TerminalRenderer({
+ input,
+ output: screen,
+ captureForeignOutput: false,
+ tools: "hidden",
+ unicode: true,
+ diagnostics: stub.diagnostics,
+ });
+
+ await renderer.renderStream(
+ streamOf([
+ {
+ type: "tool-call",
+ toolCallId: "c1",
+ toolName: "bash",
+ input: { command: "curl https://example.com" },
+ },
+ { type: "tool-error", toolCallId: "c1", errorText: "exit code 7: connection refused" },
+ { type: "error", errorText: "Turn failed." },
+ { type: "finish" },
+ ]),
+ { submittedPrompt: "fetch it", continueSession: false },
+ );
+
+ expect(append).toHaveBeenCalledWith({
+ source: "tool",
+ summary: expect.stringContaining("failed"),
+ detail: "exit code 7: connection refused",
+ });
+ expect(append).toHaveBeenCalledWith({
+ source: "workflow",
+ summary: "Error: Turn failed.",
+ detail: "Turn failed.",
+ });
+ renderer.shutdown();
+ });
+
+ it("renders a cataloged summary for a recognized stream error and logs the raw dump", async () => {
+ const screen = new MockScreen({ columns: 100, rows: 30 });
+ const input = new MockUserInput();
+ const stub = stubDiagnostics();
+ const append = stub.append;
+ const renderer = new TerminalRenderer({
+ input,
+ output: screen,
+ captureForeignOutput: false,
+ unicode: true,
+ diagnostics: stub.diagnostics,
+ });
+
+ const failure = new TypeError("fetch failed", {
+ cause: Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:3000"), {
+ code: "ECONNREFUSED",
+ }),
+ });
+ await renderer.renderStream(
+ {
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ controller.error(failure);
+ },
+ }),
+ },
+ { submittedPrompt: "hello", continueSession: false },
+ );
+
+ // Transcript: curated headline, the structured hint, and the log
+ // pointer — no stack dump.
+ expect(screen.snapshot()).toContain("Network request failed");
+ expect(screen.snapshot()).toContain("Check your internet connection");
+ expect(screen.snapshot()).toContain("details: .eve/logs/dev.log");
+ expect(screen.snapshot()).not.toContain(" at ");
+ // Log: the raw inspection, cause chain included, hint structured.
+ expect(append).toHaveBeenCalledWith({
+ source: "workflow",
+ summary: expect.stringContaining("Network request failed"),
+ detail: expect.stringContaining("ECONNREFUSED"),
+ hint: expect.stringContaining("Check your internet connection"),
+ });
+ renderer.shutdown();
+ });
+
+ it("records session stats past display guards and reports at the turn boundary", async () => {
+ const screen = new MockScreen({ columns: 80, rows: 30 });
+ const input = new MockUserInput();
+ const stub = stubDiagnostics();
+ const renderer = new TerminalRenderer({
+ input,
+ output: screen,
+ captureForeignOutput: false,
+ tools: "hidden",
+ subagents: "hidden",
+ unicode: true,
+ diagnostics: stub.diagnostics,
+ });
+
+ renderer.upsertSubagentTool({
+ callId: "sub-1",
+ subagentName: "echo-marker",
+ childCallId: "child-1",
+ toolName: "echo",
+ input: {},
+ status: "executing",
+ });
+ await renderer.renderStream(
+ streamOf([
+ { type: "tool-call", toolCallId: "c1", toolName: "bash", input: {} },
+ { type: "tool-call", toolCallId: "c2", toolName: "bash", input: {} },
+ { type: "tool-call", toolCallId: "c3", toolName: "weather", input: {} },
+ { type: "step-finish", usage: { inputTokens: 100, outputTokens: 20 } },
+ { type: "step-finish", usage: { inputTokens: 40, outputTokens: 5 } },
+ // `finish` replays the last step's usage; only step-finish records.
+ { type: "finish", usage: { inputTokens: 40, outputTokens: 5 } },
+ ]),
+ { submittedPrompt: "run it", continueSession: false },
+ );
+
+ expect(stub.recordPrompt).toHaveBeenCalledTimes(1);
+ expect(stub.recordSubagentDispatch).toHaveBeenCalledWith("sub-1");
+ expect(stub.recordToolCall.mock.calls.map(([name]) => name)).toEqual([
+ "bash",
+ "bash",
+ "weather",
+ ]);
+ expect(stub.recordStepUsage).toHaveBeenCalledTimes(2);
+ expect(stub.reportStats).toHaveBeenCalled();
+ renderer.shutdown();
+ });
+
+ it("records sandbox log lines in the diagnostic log", () => {
+ const screen = new MockScreen({ columns: 80, rows: 30 });
+ const input = new MockUserInput();
+ const stub = stubDiagnostics();
+ const append = stub.append;
+ const renderer = new TerminalRenderer({
+ input,
+ output: screen,
+ captureForeignOutput: false,
+ unicode: true,
+ diagnostics: stub.diagnostics,
+ });
+
+ renderer.renderSandboxLog('eve: sandbox template "root" (microsandbox): apt-get update');
+ expect(append).toHaveBeenCalledWith({ source: "sandbox", detail: expect.any(String) });
+ renderer.shutdown();
+ });
+
it("hides logs by default, then reveals buffered lines at their original positions", () => {
const screen = new MockScreen({ columns: 80, rows: 30 });
const input = new MockUserInput();
@@ -1958,14 +2218,14 @@ describe("TerminalRenderer setup panel", () => {
expect(screen.snapshot()).toContain("Provider");
expect(screen.snapshot()).toContain("•••••••");
expect(screen.snapshot()).not.toContain("bad-key");
- expect(screen.snapshot()).toContain("Validating…");
+ expect(screen.snapshot()).toContain("▪ validating");
resolveValidation?.({ kind: "invalid", message: "Rejected." });
await vi.waitFor(() => {
- expect(screen.snapshot()).toContain("Invalid key");
+ expect(screen.snapshot()).toContain("API key is not valid");
});
input.type("x");
- expect(screen.snapshot()).not.toContain("Invalid key");
+ expect(screen.snapshot()).not.toContain("API key is not valid");
input.enter();
resolveValidation?.({ kind: "valid" });
@@ -2048,6 +2308,110 @@ describe("TerminalRenderer setup panel", () => {
renderer.shutdown();
});
+ it("walks the model editor from pick to slider to toggle to Done", async () => {
+ const { screen, input, renderer } = makeRenderer(100, 40);
+ renderer.setupFlow.begin("Configure the agent model");
+ const answer = renderer.setupFlow.readModelEditor({
+ model: {
+ kind: "pick",
+ options: [
+ {
+ value: "anthropic/claude-sonnet-5",
+ label: "anthropic/claude-sonnet-5",
+ featured: true,
+ },
+ { value: "xai/grok-4.5", label: "xai/grok-4.5" },
+ ],
+ current: "anthropic/claude-sonnet-5",
+ },
+ reasoning: null,
+ serviceTier: { kind: "standard" },
+ settingsEditable: true,
+ externalRouting: false,
+ capabilitiesFor: () => ({
+ reasoning: true,
+ reasoningLevels: ["low", "high"],
+ fastMode: true,
+ }),
+ });
+
+ // The value menu opens on the Model row.
+ expect(screen.snapshot()).toContain("▶ Model");
+ input.enter();
+ expect(screen.snapshot()).toContain("Select the model");
+ input.type("grok");
+ expect(screen.snapshot()).toContain("xai/grok-4.5");
+ input.enter();
+ // Back on the menu, the model hint carries the pick.
+ expect(screen.snapshot()).toContain("xai/grok-4.5");
+
+ // Reasoning adjusts inline on its row: right enters the scale at the
+ // lowest level, another right (via Tab, which mimics it) walks up.
+ input.down();
+ expect(screen.snapshot()).toContain("▶ Reasoning effort");
+ input.right();
+ expect(screen.snapshot()).toContain("◉─○ low");
+ input.send("\t");
+ expect(screen.snapshot()).toContain("●─◉ high");
+
+ input.down();
+ expect(screen.snapshot()).toContain("▶ Service tier");
+ expect(screen.snapshot()).toContain("normal");
+ input.right();
+ expect(screen.snapshot()).toContain("fast ↯");
+
+ input.down();
+ input.enter();
+
+ await expect(answer).resolves.toEqual({
+ model: "xai/grok-4.5",
+ reasoning: "high",
+ serviceTier: "priority",
+ });
+ renderer.setupFlow.end({ preserveDiagnostics: false });
+ renderer.shutdown();
+ });
+
+ it("unwinds Esc through filter, sub-screen, and menu before cancelling", async () => {
+ const { screen, input, renderer } = makeRenderer(100, 40);
+ renderer.setupFlow.begin("Configure the agent model");
+ const answer = renderer.setupFlow.readModelEditor({
+ model: {
+ kind: "pick",
+ options: [{ value: "anthropic/claude-sonnet-5", label: "Claude Sonnet 5" }],
+ current: "anthropic/claude-sonnet-5",
+ },
+ reasoning: null,
+ serviceTier: { kind: "standard" },
+ settingsEditable: true,
+ externalRouting: false,
+ capabilitiesFor: () => undefined,
+ });
+ let settled = false;
+ void answer.finally(() => {
+ settled = true;
+ });
+
+ input.enter();
+ input.type("sonnet");
+ input.send("\x1b");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(settled).toBe(false);
+ // The first Esc only cleared the filter; the list is still open.
+ expect(screen.snapshot()).toContain("▏ type to search");
+
+ input.send("\x1b");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(settled).toBe(false);
+ // Back on the menu.
+ expect(screen.snapshot()).toContain("▶ Model");
+
+ input.send("\x1b");
+ await expect(answer).resolves.toBeUndefined();
+ renderer.setupFlow.end({ preserveDiagnostics: false });
+ renderer.shutdown();
+ });
+
it("drives the ephemeral flow status through the footer", () => {
const { screen, renderer } = makeRenderer();
@@ -2890,7 +3254,7 @@ describe("TerminalRenderer status line", () => {
"",
" Select your team",
]);
- const status = lines.indexOf(" ↗ vpoke.playground-vercel.tools · Authenticating via OIDC…");
+ const status = lines.indexOf(" ↗ vpoke.playground-vercel.tools Authenticating via OIDC…");
expect(status).toBeGreaterThan(title);
expect(lines[status - 1]).toBe("");
@@ -2900,7 +3264,7 @@ describe("TerminalRenderer status line", () => {
renderer.shutdown();
});
- it("keeps the running token total after the turn indicator disappears", async () => {
+ it("keeps the token flow off the status line after a turn reports usage", async () => {
const { screen, renderer } = makeRenderer();
await renderer.renderStream(
streamOf([
@@ -2912,15 +3276,61 @@ describe("TerminalRenderer status line", () => {
{ submittedPrompt: "hello", continueSession: true },
);
- const lines = screen.snapshot().split("\n");
- const readyRow = lines.find((line) => line.includes("Ready"));
- const statusRow = lines.find((line) => line.includes("↑ 500 ↓ 300"));
- expect(readyRow).toBeUndefined();
- expect(statusRow).toBeDefined();
+ const snapshot = screen.snapshot();
+ expect(snapshot).not.toContain("Ready");
+ expect(snapshot).not.toContain("↑ 500");
+ expect(snapshot).not.toContain("↓ 300");
+ renderer.shutdown();
+ });
+
+ it("renders the reasoning level and fast marker on the model segment", () => {
+ const { screen, renderer } = makeRenderer(100);
+ renderer.renderNotice("anchor");
+ renderer.renderAgentHeader({
+ name: "Weather Agent",
+ serverUrl: "http://localhost:3000",
+ info: agentInfoWithModel(
+ "xai/grok-4.5",
+ { kind: "gateway", connected: true, credential: "oidc" },
+ {
+ reasoning: "xhigh",
+ providerOptions: { gateway: { serviceTier: "priority" } },
+ },
+ ),
+ });
+ // The first header commits with no footer; a Vercel status probe is the
+ // paint that reveals the persistent status line beneath it.
+ renderer.setVercelStatus(vercelStatus);
+
+ expect(screen.snapshot()).toContain("xai/grok-4.5@xhigh ↯");
+ renderer.shutdown();
+ });
+
+ it("hides the provider-default reasoning sentinel and non-priority tiers", () => {
+ const { screen, renderer } = makeRenderer(100);
+ renderer.renderNotice("anchor");
+ renderer.renderAgentHeader({
+ name: "Weather Agent",
+ serverUrl: "http://localhost:3000",
+ info: agentInfoWithModel(
+ "xai/grok-4.5",
+ { kind: "gateway", connected: true, credential: "oidc" },
+ {
+ reasoning: "provider-default",
+ providerOptions: { gateway: { serviceTier: "flex" } },
+ },
+ ),
+ });
+ renderer.setVercelStatus(vercelStatus);
+
+ const snapshot = screen.snapshot();
+ expect(snapshot).toContain("xai/grok-4.5");
+ expect(snapshot).not.toContain("@provider-default");
+ expect(snapshot).not.toContain("↯");
renderer.shutdown();
});
- it("keeps the model and Vercel segments across reset while tokens clear", async () => {
+ it("keeps the model and Vercel segments across reset while tokens stay clear", async () => {
// 100 columns: all four segments fit at full fidelity, no drop order.
const { screen, renderer } = makeRenderer(100);
renderer.renderAgentHeader({
@@ -2942,7 +3352,7 @@ describe("TerminalRenderer status line", () => {
]),
{ submittedPrompt: "hello", continueSession: true },
);
- expect(screen.snapshot()).toContain("↑ 500 ↓ 300");
+ expect(screen.snapshot()).not.toContain("↑ 500 ↓ 300");
renderer.reset();
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
index cd2739e84..9b8abd141 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
@@ -1,4 +1,5 @@
import { StringDecoder } from "node:string_decoder";
+import type { DevDiagnostics } from "../diagnostics.js";
import type {
AgentTUIInputOption,
@@ -34,8 +35,10 @@ import {
type PromptCommandSpec,
} from "./prompt-commands.js";
import {
+ enterBadge,
renderFlowPanel,
renderAcknowledgeQuestion,
+ renderModelEditorQuestion,
renderSelectQuestion,
renderTextQuestion,
type FlowPanelContent,
@@ -45,6 +48,11 @@ import {
type SetupPanelOption,
type SetupSelectPanelState,
} from "./setup-panel.js";
+import {
+ initialModelEditorState,
+ transitionModelEditor,
+ type ModelEditorEvent,
+} from "./model-editor.js";
import type {
SetupEditableSelectResult,
SetupFlowIndicator,
@@ -53,6 +61,7 @@ import type {
SetupSelectRequest,
} from "./setup-flow.js";
import type { SelectNotice } from "#setup/prompter.js";
+import type { ModelSettingsRequest, ModelSettingsResult } from "#setup/flows/model.js";
import type { ProviderPickerChoice, ProviderPickerRequest } from "#setup/flows/provider.js";
import {
initialSelectState,
@@ -68,6 +77,8 @@ import type {
TerminalPartDisplayMode,
} from "./types.js";
import type { AgentInfoResult } from "#client/index.js";
+import { summarizeKnownError } from "#harness/semantic-errors/index.js";
+import { inspectError, type LogRecord } from "#internal/logging.js";
import {
parseDevRebuildLogLine,
type DevRebuildLogUpdate,
@@ -112,15 +123,16 @@ import {
import type { VercelStatusSnapshot } from "./vercel-status.js";
import type { RemoteConnectionSnapshot } from "./remote-connection.js";
import { summarizeToolArgs, summarizeToolResult } from "./tool-format.js";
+import { formatStoredDiagnostic, presentDiagnostic } from "./diagnostic-presentation.js";
import { reduceSetupSelectInput, setupSelectionIntent } from "./setup-selection-input.js";
import {
isProgressPulseVisible,
PROGRESS_PULSE_ASCII_GLYPH,
PROGRESS_PULSE_GLYPH,
} from "#cli/ui/progress-pulse.js";
+import { readGatewayServiceTier } from "#shared/gateway-service-tier.js";
import {
formatAssistantResponseStats,
- formatTokenFlow,
isIncompletePaste,
nextKey,
sanitizePastedText,
@@ -228,6 +240,8 @@ export type TerminalRendererOptions = {
logs?: LogDisplayMode;
color?: boolean;
unicode?: boolean;
+ /** The process's diagnostics recorder (log, dump, stats); local sessions only. */
+ diagnostics?: DevDiagnostics;
/** Slash commands available in this local or remote session. */
availablePromptCommands?: readonly PromptCommandSpec[];
};
@@ -295,8 +309,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
readonly #subagents: TerminalPartDisplayMode;
readonly #connectionAuth: TerminalPartDisplayMode;
readonly #assistantResponseStats: AssistantResponseStatsMode;
- readonly #defaultContextSize?: number;
readonly #captureForeignOutput: boolean;
+ readonly #diagnostics?: DevDiagnostics;
readonly #availablePromptCommands: readonly PromptCommandSpec[];
/** Which captured log sources render. Mutable via {@link setLogDisplayMode}. */
#logs: LogDisplayMode;
@@ -376,9 +390,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
#paintAgain = false;
#totalTokens?: number;
- /** Input (prompt) tokens from the latest usage report — the ↑ side. */
- #promptTokens?: number;
- #contextSize?: number;
#assistantOutputTokens?: number;
#assistantTokensPerSecond?: number;
/** Wall-clock start of the current stream, for the tok/s status stat. */
@@ -413,6 +424,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
readSelect: (options) => this.#readSetupSelect(options),
readEditableSelect: (options) => this.#readSetupEditableSelect(options),
readProviderPicker: (options) => this.#readProviderPicker(options),
+ readModelEditor: (options) => this.#readModelEditor(options),
readText: (options) => this.#readSetupText(options),
readAcknowledge: (options) => this.#readSetupAcknowledge(options),
readChoice: (options) => this.#readSetupChoice(options),
@@ -439,9 +451,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#subagents = options?.subagents ?? "auto-collapsed";
this.#connectionAuth = options?.connectionAuth ?? "full";
this.#assistantResponseStats = options?.assistantResponseStats ?? defaultAssistantResponseStats;
- this.#defaultContextSize = options?.contextSize;
- this.#contextSize = options?.contextSize;
this.#captureForeignOutput = options?.captureForeignOutput ?? this.#output === process.stdout;
+ this.#diagnostics = options?.diagnostics;
this.#logs = options?.logs ?? "none";
this.#availablePromptCommands = options?.availablePromptCommands ?? PROMPT_COMMANDS;
}
@@ -651,9 +662,9 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
this.#status = this.#connectionAuthPendingCount > 0 ? STATUS.connectionAuth : STATUS.processing;
this.#addSubmittedPrompt(options?.submittedPrompt);
+ if (options?.submittedPrompt !== undefined) this.#diagnostics?.recordPrompt();
this.#interrupted = false;
this.#totalTokens = undefined;
- this.#promptTokens = undefined;
this.#assistantOutputTokens = undefined;
this.#assistantTokensPerSecond = undefined;
this.#streamStartedAt = Date.now();
@@ -683,7 +694,18 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#applyStreamEvent(event, displayModes, turnState);
}
} catch (error) {
- this.#addErrorBlock("Error", toErrorMessage(error));
+ // Cataloged failures render their curated headline; either way the
+ // raw inspection travels as detail so the diagnostic log keeps the
+ // evidence and the transcript shows only the pointer.
+ const summary = summarizeKnownError(error);
+ if (summary === null) {
+ this.#addErrorBlock("Error", toErrorMessage(error), { detail: inspectError(error) });
+ } else {
+ this.#addErrorBlock(summary.name, summary.message, {
+ detail: inspectError(error),
+ hint: summary.hint,
+ });
+ }
} finally {
this.#resolveStreamInterrupt = undefined;
if (this.#interrupted) result.abort?.();
@@ -694,6 +716,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
this.#status = completedTurnStatus(this.#interrupted, options?.continueSession === true);
this.#finalizeAllBlocks();
+ this.#diagnostics?.reportStats();
this.#paint();
if (!options?.continueSession) {
@@ -942,6 +965,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
upsertSubagentStep(update: SubagentStepUpdate): void {
+ this.#diagnostics?.recordSubagentDispatch(update.callId);
if (this.#subagents === "hidden") return;
const reasoningText = stripTerminalControls(update.reasoning ?? "").trim();
const messageText = stripTerminalControls(update.message ?? "").trim();
@@ -965,6 +989,16 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
upsertSubagentTool(update: SubagentToolUpdate): void {
+ this.#diagnostics?.recordSubagentDispatch(update.callId);
+ if (update.status === "failed" && update.errorText !== undefined) {
+ // Captured before the display guards: hidden or collapsed subagent
+ // views must not keep tool failures out of the diagnostic log.
+ this.#diagnostics?.append({
+ source: "tool",
+ summary: `${update.toolName} failed (subagent ${update.subagentName})`,
+ detail: update.errorText,
+ });
+ }
if (this.#subagents === "hidden") return;
this.#ensureSubagentHeader(update.callId, update.subagentName);
if (this.#subagents === "collapsed") {
@@ -1076,7 +1110,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#devRebuild = undefined;
this.#connectionAuthPendingCount = 0;
this.#totalTokens = undefined;
- this.#promptTokens = undefined;
this.#assistantOutputTokens = undefined;
this.#assistantTokensPerSecond = undefined;
this.#streamStartedAt = undefined;
@@ -1103,6 +1136,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
const content = stripTerminalControls(text);
const sandboxMessage = parseSandboxLogLine(content);
if (sandboxMessage === undefined) return;
+ this.#diagnostics?.append({ source: "sandbox", detail: sandboxMessage });
this.#start();
this.#pushBlock({ kind: "sandbox", body: sandboxMessage, live: false });
this.#paint();
@@ -1558,23 +1592,34 @@ export class TerminalRenderer implements AgentTUIRenderer {
let interaction = initialProviderPickerState(opts.options, opts.initialValue);
let validation: AbortController | undefined;
- flow.question = (width) =>
- renderSelectQuestion(
- {
- kind: "inline-edit",
- layout: "stacked",
- message: opts.message,
- options: opts.options,
- select: interaction.select,
- edit: {
- optionValue: "own-key",
- caretVisible: this.#caretVisible,
- editor: { kind: "key", phase: interaction.phase },
- },
+ // The cursor row's Enter affordance: `↵ change` on the currently-active
+ // provider, a bare `↵` elsewhere. The key row's own phases (editing,
+ // validating, invalid) carry their badge on the input line instead.
+ const cursorBadge = (): string | undefined => {
+ if (interaction.phase.kind !== "inactive") return undefined;
+ const value = selectValueAtCursor([...opts.options], interaction.select.cursor);
+ const row = opts.options.find((option) => option.value === value);
+ if (row === undefined) return undefined;
+ return enterBadge(this.#theme, row.checked === true ? "change" : undefined);
+ };
+
+ flow.question = (width) => {
+ const badge = cursorBadge();
+ const panel: SetupSelectPanelState = {
+ kind: "inline-edit",
+ layout: "stacked",
+ message: opts.message,
+ options: opts.options,
+ select: interaction.select,
+ edit: {
+ optionValue: "own-key",
+ caretVisible: this.#caretVisible,
+ editor: { kind: "key", phase: interaction.phase },
},
- this.#theme,
- width,
- );
+ };
+ if (badge !== undefined) panel.cursorBadge = badge;
+ return renderSelectQuestion(panel, this.#theme, width);
+ };
const syncCaret = () => {
if (interaction.phase.kind === "editing" || interaction.phase.kind === "invalid") {
@@ -1675,6 +1720,82 @@ export class TerminalRenderer implements AgentTUIRenderer {
return await question.promise;
}
+ /**
+ * The composite Change-model screen: the searchable catalog, the reasoning
+ * slider, and the service-tier toggle on one panel, driven by the pure
+ * model-editor reducer. Resolves the drafted changes on Done, or `undefined`
+ * on Esc/Ctrl-C.
+ */
+ async #readModelEditor(opts: ModelSettingsRequest): Promise<ModelSettingsResult | undefined> {
+ const flow = this.#beginSetupQuestion();
+ let interaction = initialModelEditorState(opts);
+
+ flow.question = (width) =>
+ renderModelEditorQuestion({ request: opts, state: interaction }, this.#theme, width);
+ this.#paint();
+
+ const question = this.#captureSetupQuestion<ModelSettingsResult | undefined>((key, settle) => {
+ const dispatch = (event: ModelEditorEvent): void => {
+ const transition = transitionModelEditor(interaction, event, opts);
+ switch (transition.kind) {
+ case "ignore":
+ return;
+ case "render":
+ interaction = transition.state;
+ this.#paint();
+ return;
+ case "cancel":
+ settle(undefined);
+ return;
+ case "settle":
+ settle(transition.result);
+ return;
+ }
+ };
+
+ const intent = setupSelectionIntent(key);
+ switch (intent?.kind) {
+ case "cancel":
+ dispatch({ type: "cancel" });
+ return;
+ case "move":
+ dispatch({ type: "move", direction: intent.direction });
+ return;
+ case "submit":
+ dispatch({ type: "submit" });
+ return;
+ case "repaint":
+ this.#paint();
+ return;
+ case undefined:
+ break;
+ }
+
+ // Left/right adjust the inline value under the menu cursor, and Tab
+ // mimics right. The shared intent grammar deliberately drops the
+ // horizontal arrows (line editors own them elsewhere), so this surface
+ // consumes them locally.
+ if (key.type === "left" || key.type === "right") {
+ dispatch({ type: "adjust", direction: key.type });
+ return;
+ }
+ if (key.type === "tab") {
+ dispatch({ type: "adjust", direction: "right" });
+ return;
+ }
+ if (key.type === "backspace") {
+ dispatch({ type: "backspace" });
+ return;
+ }
+ if (key.type === "text") {
+ for (const char of key.value.replaceAll("\n", " ")) {
+ if (char >= " " && char !== "\u007f") dispatch({ type: "char", char });
+ }
+ }
+ });
+ return await question.promise;
+ }
+
/**
* Asks one text question through the bordered setup panel. `mask` renders
* bullets (passwords); `validate` paints its message red inside the panel
@@ -1995,7 +2116,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
#start(options?: AgentTUISessionOptions) {
this.#title = options?.title ?? this.#title;
- this.#contextSize = options?.contextSize ?? this.#defaultContextSize;
if (this.#isInteractive) return;
@@ -2235,14 +2355,36 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#pushBlock({ kind: "user", body: stripTerminalControls(prompt), live: false });
}
- #addErrorBlock(title: string, content: string, detail?: string) {
+ #addErrorBlock(
+ title: string,
+ content: string,
+ extras: { detail?: string | undefined; hint?: string | undefined } = {},
+ ) {
+ const cleanTitle = stripTerminalControls(title);
+ const cleanBody = stripTerminalControls(content);
+ const cleanDetail =
+ extras.detail === undefined ? undefined : stripTerminalControls(extras.detail);
+ const cleanHint = extras.hint === undefined ? undefined : stripTerminalControls(extras.hint);
+ // Every error block lands in the log, detail or not, so the file is a
+ // complete failure record for the session. The hint stays a structured
+ // field of the record, mirroring the failure event's shape.
+ const entry = {
+ source: "workflow" as const,
+ summary: `${cleanTitle}: ${cleanBody}`,
+ detail: cleanDetail ?? cleanBody,
+ };
+ this.#diagnostics?.append(cleanHint === undefined ? entry : { ...entry, hint: cleanHint });
const block: Block = {
kind: "error",
- title: stripTerminalControls(title),
- body: stripTerminalControls(content),
+ title: cleanTitle,
+ body: cleanBody,
live: false,
};
- if (detail !== undefined) block.detail = stripTerminalControls(detail);
+ if (cleanHint !== undefined) block.hint = cleanHint;
+ if (cleanDetail !== undefined) {
+ block.detail =
+ this.#diagnostics === undefined ? cleanDetail : `details: ${this.#diagnostics.displayPath}`;
+ }
this.#pushBlock(block);
this.#paint();
}
@@ -2305,6 +2447,10 @@ export class TerminalRenderer implements AgentTUIRenderer {
break;
case "step-finish":
+ // Step usage reports are per-step deltas (extractStepUsage in the
+ // harness), so summing them yields true session totals. The
+ // `finish` event replays the last step's usage — don't sum there.
+ this.#diagnostics?.recordStepUsage(event.usage);
this.#applyUsage(event.usage);
this.#paint();
break;
@@ -2349,6 +2495,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
case "tool-call":
+ this.#diagnostics?.recordToolCall(event.toolName);
if (displayModes.tools === "hidden") break;
this.#setStreamStatus(STATUS.executingTools);
this.#upsertNativeTool(
@@ -2386,8 +2533,14 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
case "tool-error": {
- if (displayModes.tools === "hidden") break;
const existing = this.#resolveNativeToolState(event.toolCallId, turnState);
+ // Tool failures reach the log even when tool display is hidden.
+ this.#diagnostics?.append({
+ source: "tool",
+ summary: `${existing?.toolName ?? event.toolCallId} failed`,
+ detail: event.errorText,
+ });
+ if (displayModes.tools === "hidden") break;
if (existing === undefined) break;
turnState.hasPendingToolResults = true;
this.#setStreamStatus(STATUS.toolResults);
@@ -2400,7 +2553,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
case "error":
- this.#addErrorBlock("Error", event.errorText, event.detail);
+ this.#addErrorBlock("Error", event.errorText, { detail: event.detail, hint: event.hint });
break;
case "finish":
@@ -2487,7 +2640,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (inputTokens != null || outputTokens != null) {
this.#totalTokens = (inputTokens ?? 0) + (outputTokens ?? 0);
}
- this.#promptTokens = inputTokens ?? this.#promptTokens;
this.#assistantOutputTokens = outputTokens ?? this.#assistantOutputTokens;
if (this.#assistantOutputTokens != null && this.#streamStartedAt !== undefined) {
@@ -2846,21 +2998,19 @@ export class TerminalRenderer implements AgentTUIRenderer {
const serverPort = new URL(serverUrl).port;
if (serverPort.length > 0) input.serverPort = serverPort;
}
- const model = this.#agentHeader?.info?.agent.model.id;
- if (model !== undefined) input.model = model;
+ const agentModel = this.#agentHeader?.info?.agent.model;
+ if (agentModel?.id !== undefined) input.model = agentModel.id;
+ // "provider-default" is the absent-setting sentinel, not a level worth showing.
+ if (agentModel?.reasoning !== undefined && agentModel.reasoning !== "provider-default") {
+ input.reasoning = agentModel.reasoning;
+ }
+ if (readGatewayServiceTier(agentModel?.providerOptions).kind === "priority") {
+ input.fastMode = true;
+ }
// The runner resolves model-provider state with `/info` before caching this
// header, so the status bar consumes that shared snapshot.
- const endpoint = this.#agentHeader?.info?.agent.model.endpoint;
+ const endpoint = agentModel?.endpoint;
if (endpoint !== undefined) input.endpoint = endpoint;
- // Skip the token segment entirely until a turn moves a token — a `↑ 0 ↓ 0`
- // row is noise before the first prompt.
- const inputTokens = this.#promptTokens ?? 0;
- const outputTokens = this.#assistantOutputTokens ?? 0;
- if (inputTokens > 0 || outputTokens > 0) {
- const flow: Parameters<typeof formatTokenFlow>[0] = { inputTokens, outputTokens };
- if (this.#contextSize !== undefined) flow.contextSize = this.#contextSize;
- input.tokens = formatTokenFlow(flow, this.#theme.glyph);
- }
if (this.#vercelStatus !== undefined) input.vercel = this.#vercelStatus;
if (this.#remoteConnection !== undefined) input.remote = this.#remoteConnection;
const line = buildStatusLine(input);
@@ -2937,7 +3087,14 @@ export class TerminalRenderer implements AgentTUIRenderer {
const restoreStdout = capture(process.stdout, "stdout");
const restoreStderr = capture(process.stderr, "stderr");
+ // The recorder takes ownership of eve's own structured log records for
+ // the same window the stream capture is installed: it persists each one
+ // structured, then hands it here for display. Records never reach the
+ // console, so the stderr scrape below only carries genuinely foreign
+ // output.
+ this.#diagnostics?.subscribeLogRecords((record) => this.#displayLogRecord(record));
this.#restoreLogCapture = () => {
+ this.#diagnostics?.unsubscribeLogRecords();
restoreStdout();
restoreStderr();
};
@@ -2950,15 +3107,29 @@ export class TerminalRenderer implements AgentTUIRenderer {
restore();
if (this.#stdoutLogBuffer.length > 0) {
+ this.#diagnostics?.append({ source: "stdout", detail: this.#stdoutLogBuffer });
if (this.#shouldRenderLog("stdout")) process.stdout.write(`${this.#stdoutLogBuffer}\n`);
this.#stdoutLogBuffer = "";
}
if (this.#stderrLogBuffer.length > 0) {
+ this.#diagnostics?.append({ source: "stderr", detail: this.#stderrLogBuffer });
if (this.#shouldRenderLog("stderr")) process.stderr.write(`${this.#stderrLogBuffer}\n`);
this.#stderrLogBuffer = "";
}
}
+ /**
+ * Displays one structured record from eve's own logger (the diagnostics
+ * recorder already persisted it). Routed through the stderr path so
+ * `/loglevel` semantics and long-output collapsing match what the same
+ * record looked like when it arrived as scraped console output.
+ */
+ #displayLogRecord(record: LogRecord): void {
+ const fieldsText = record.fields === undefined ? "" : ` ${JSON.stringify(record.fields)}`;
+ this.#handleCapturedStderr(`[eve:${record.namespace}] ${record.message}${fieldsText}`);
+ this.#paint();
+ }
+
#handleForeignOutput(source: "stdout" | "stderr", text: string): void {
const combined = (source === "stdout" ? this.#stdoutLogBuffer : this.#stderrLogBuffer) + text;
const lastNewline = combined.lastIndexOf("\n");
@@ -2984,6 +3155,9 @@ export class TerminalRenderer implements AgentTUIRenderer {
// applied at render time, so `/loglevel` can reveal them later. The dev
// server's rebuild lifecycle lines are the one exception — they cycle
// through a single in-place status block instead of stacking.
+ // Capture at the dispatch point so every captured line — including
+ // sandbox and rebuild lines riding stdout — reaches the diagnostic log.
+ this.#diagnostics?.append({ source, detail: content });
if (source === "stdout") this.#handleCapturedStdout(content);
else this.#handleCapturedStderr(content);
this.#paint();
@@ -3030,7 +3204,29 @@ export class TerminalRenderer implements AgentTUIRenderer {
return parseDevRebuildLogLine(line.trimEnd())?.kind === "failed";
});
if (failedIndex === -1) {
- this.#pushBlock({ kind: "log", title: "stderr", body: content, live: false });
+ if (this.#diagnostics === undefined) {
+ this.#pushBlock({ kind: "log", title: "stderr", body: content, live: false });
+ return;
+ }
+ const presentation = presentDiagnostic(content, this.#diagnostics.displayPath);
+ if (presentation.kind === "inline") {
+ this.#pushBlock({ kind: "log", title: "stderr", body: presentation.text, live: false });
+ return;
+ }
+ this.#pushBlock({
+ kind: "log",
+ title: "stderr",
+ body: formatStoredDiagnostic(presentation),
+ logVisibility: "stderr-only",
+ live: false,
+ });
+ this.#pushBlock({
+ kind: "log",
+ title: "stderr",
+ body: content,
+ logVisibility: "all-only",
+ live: false,
+ });
return;
}
@@ -3135,6 +3331,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
#isHiddenLog(block: Block): boolean {
if (block.kind === "sandbox") return !this.#shouldRenderLog("sandbox");
if (block.kind !== "log") return false;
+ if (block.logVisibility === "stderr-only") return this.#logs !== "stderr";
+ if (block.logVisibility === "all-only") return this.#logs !== "all";
return !this.#shouldRenderLog(block.title === "stderr" ? "stderr" : "stdout");
}
}
diff --git a/packages/eve/src/cli/dev/tui/test/fake-setup-flow-renderer.ts b/packages/eve/src/cli/dev/tui/test/fake-setup-flow-renderer.ts
index 941538a93..53e3f2676 100644
--- a/packages/eve/src/cli/dev/tui/test/fake-setup-flow-renderer.ts
+++ b/packages/eve/src/cli/dev/tui/test/fake-setup-flow-renderer.ts
@@ -3,13 +3,18 @@ import type { SetupFlowRenderer } from "../setup-flow.js";
export function createFakeSetupFlowRenderer(
overrides: Partial<SetupFlowRenderer> = {},
): SetupFlowRenderer {
- const { readProviderPicker = async () => undefined, ...rest } = overrides;
+ const {
+ readProviderPicker = async () => undefined,
+ readModelEditor = async () => undefined,
+ ...rest
+ } = overrides;
return {
begin: () => {},
end: () => {},
readSelect: async () => undefined,
readEditableSelect: async () => undefined,
readProviderPicker,
+ readModelEditor,
readText: async () => undefined,
readAcknowledge: async () => {},
readChoice: () => ({ choice: Promise.resolve(undefined), close: () => {} }),
diff --git a/packages/eve/src/cli/dev/tui/theme.ts b/packages/eve/src/cli/dev/tui/theme.ts
index 8afcbe0f8..d20cf71b3 100644
--- a/packages/eve/src/cli/dev/tui/theme.ts
+++ b/packages/eve/src/cli/dev/tui/theme.ts
@@ -103,6 +103,20 @@ export interface ThemeGlyphs {
arrowUp: string;
/** `↓` — output (response) tokens in the token-flow segment. */
arrowDown: string;
+ /** `↯` — Fast mode (Gateway priority tier) marker beside a model id. */
+ fast: string;
+ /** `●` — a track notch below the current position (already covered). */
+ trackFilled: string;
+ /** `◉` — the track notch at the current position. */
+ trackCurrent: string;
+ /** `○` — a track notch above the current position. */
+ trackEmpty: string;
+ /** `─` — the connector segment between track notches. */
+ trackLine: string;
+ /** `↵` — the Enter affordance inside a selection badge. */
+ enter: string;
+ /** `▪` — the marker beside an in-flight validation badge. */
+ validating: string;
}
const UNICODE_GLYPHS: ThemeGlyphs = {
@@ -128,6 +142,13 @@ const UNICODE_GLYPHS: ThemeGlyphs = {
ellipsis: "…",
arrowUp: "↑",
arrowDown: "↓",
+ fast: "↯",
+ trackFilled: "●",
+ trackCurrent: "◉",
+ trackEmpty: "○",
+ trackLine: "─",
+ enter: "↵",
+ validating: "▪",
};
const ASCII_GLYPHS: ThemeGlyphs = {
@@ -153,6 +174,13 @@ const ASCII_GLYPHS: ThemeGlyphs = {
ellipsis: "...",
arrowUp: "^",
arrowDown: "v",
+ fast: ">>",
+ trackFilled: "*",
+ trackCurrent: "O",
+ trackEmpty: ".",
+ trackLine: "-",
+ enter: "<-'",
+ validating: "o",
};
const UNICODE_SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
diff --git a/packages/eve/src/cli/dev/tui/tui.ts b/packages/eve/src/cli/dev/tui/tui.ts
index 0b3d15127..d6fff057e 100644
--- a/packages/eve/src/cli/dev/tui/tui.ts
+++ b/packages/eve/src/cli/dev/tui/tui.ts
@@ -12,6 +12,7 @@ import {
import { isVercelAuthChallenge } from "#services/dev-client/vercel-auth-error.js";
import { resolveVercelDeployment } from "#setup/vercel-deployment.js";
import { toErrorMessage } from "#shared/errors.js";
+import { createDevDiagnostics } from "../diagnostics.js";
import { createPromptCommandHandler } from "./prompt-command-handler.js";
import { promptCommandsFor } from "./prompt-commands.js";
@@ -119,5 +120,14 @@ export async function runDevelopmentTui(input: RunDevelopmentTuiInput): Promise<
if (initialInput !== undefined) options.initialInput = initialInput;
if (onBootProgress !== undefined) options.onBootProgress = onBootProgress;
- await new EveTUIRunner(options).run();
+ const diagnostics =
+ prepared.kind === "local"
+ ? await createDevDiagnostics(prepared.target.workspaceRoot).catch(() => undefined)
+ : undefined;
+ if (diagnostics !== undefined) options.diagnostics = diagnostics;
+ try {
+ await new EveTUIRunner(options).run();
+ } finally {
+ await diagnostics?.close();
+ }
}
diff --git a/packages/eve/src/cli/run.test.ts b/packages/eve/src/cli/run.test.ts
index df11f2a3f..4a4119a24 100644
--- a/packages/eve/src/cli/run.test.ts
+++ b/packages/eve/src/cli/run.test.ts
@@ -54,6 +54,20 @@ describe("CLI command registration", () => {
expect(help).toContain("deploy");
expect(help).not.toContain("setup");
});
+
+ it("registers the diagnostic logs commands", async () => {
+ const output: string[] = [];
+ const logger = {
+ error: (message: string) => output.push(message),
+ log: (message: string) => output.push(message),
+ };
+
+ await runCli(["logs", "--help"], logger).catch(() => {});
+
+ const help = output.join("\n");
+ expect(help).toContain("show [options] [logid]");
+ expect(help).toContain("ls");
+ });
});
describe("eve init compatibility flags", () => {
diff --git a/packages/eve/src/cli/run.ts b/packages/eve/src/cli/run.ts
index 9646fcd43..9f31469fd 100644
--- a/packages/eve/src/cli/run.ts
+++ b/packages/eve/src/cli/run.ts
@@ -585,6 +585,29 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
}
});
+ const logs = program
+ .command("logs")
+ .description("Inspect local `eve dev` diagnostic logs (.eve/logs).");
+
+ logs
+ .command("show [logid]", { isDefault: true })
+ .description("Print a diagnostic log (the most recent when logid is omitted).")
+ .option("--dump", "Prepend the log's environment dump (.dump sibling)")
+ .option("--events", "Interleave session events from the local workflow store")
+ .action(async (logId: string | undefined, options: { dump?: boolean; events?: boolean }) => {
+ const { runLogsShowCommand } = await import("#cli/commands/logs.js");
+ await runLogsShowCommand(logger, appRoot, logId, options);
+ });
+
+ logs
+ .command("ls")
+ .description("List diagnostic logs, most recent first.")
+ .option("--json", "Output as JSON")
+ .action(async (options: { json?: boolean }) => {
+ const { runLogsListCommand } = await import("#cli/commands/logs.js");
+ await runLogsListCommand(logger, appRoot, options);
+ });
+
program
.command("info")
.description("Print resolved application information.")
diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.ts
index 2ceda11d4..67a461e8c 100644
--- a/packages/eve/src/client/agent-info-schema.ts
+++ b/packages/eve/src/client/agent-info-schema.ts
@@ -129,6 +129,11 @@ export const AgentInfoResultSchema = z.object({
contextWindowTokens: z.number().optional(),
id: z.string(),
providerOptions: z.unknown().optional(),
+ // An unrecognized future effort level degrades to absent, not a parse failure.
+ reasoning: z
+ .enum(["provider-default", "none", "minimal", "low", "medium", "high", "xhigh"])
+ .optional()
+ .catch(undefined),
source: source.optional(),
routing: modelRouting.optional(),
endpoint: modelEndpoint.optional(),
diff --git a/packages/eve/src/execution/sandbox/bindings/docker-cli.ts b/packages/eve/src/execution/sandbox/bindings/docker-cli.ts
index da564fa76..52862f368 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker-cli.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker-cli.ts
@@ -52,15 +52,17 @@ export interface DockerCli {
* installed or not on `PATH`).
*/
export class DockerUnavailableError extends Error {
+ /** Structured remediation, surfaced by the semantic-error catalog. */
+ readonly hint =
+ "Install and start Docker Desktop, OrbStack, Colima, or another runtime exposing a " +
+ "Docker-compatible `docker` CLI (or point EVE_DOCKER_PATH at one, e.g. Podman). " +
+ "Alternatively use microsandbox(), the dependency-free justbash(), " +
+ "vercel(), or defaultSandbox() to pick by availability.";
+
constructor(cause?: unknown) {
- super(
- "The Docker sandbox backend requires Docker, but the `docker` CLI was not found. " +
- "Install and start Docker Desktop, OrbStack, Colima, or another runtime exposing a " +
- "Docker-compatible `docker` CLI (or point EVE_DOCKER_PATH at one, e.g. Podman). " +
- "Alternatively use microsandbox(), the dependency-free justbash(), " +
- "vercel(), or defaultSandbox() to pick by availability.",
- { cause },
- );
+ super("The Docker sandbox backend requires Docker, but the `docker` CLI was not found.", {
+ cause,
+ });
this.name = "DockerUnavailableError";
}
}
@@ -69,13 +71,17 @@ export class DockerUnavailableError extends Error {
* Raised when the `docker` CLI exists but the daemon is not reachable.
*/
export class DockerDaemonUnavailableError extends Error {
+ /** Structured remediation, surfaced by the semantic-error catalog. */
+ readonly hint =
+ "Start Docker Desktop (or your Docker-compatible runtime) and retry. Alternatively use " +
+ "microsandbox(), the dependency-free justbash() (installed automatically " +
+ "by `eve dev`, or `pnpm add -D just-bash`), vercel(), or defaultSandbox() " +
+ "to pick by availability.";
+
constructor(detail: string) {
super(
"The Docker sandbox backend requires a running Docker daemon, but it is not reachable. " +
- "Start Docker Desktop (or your Docker-compatible runtime) and retry. Alternatively use " +
- "microsandbox(), the dependency-free justbash() (installed automatically " +
- "by `eve dev`, or `pnpm add -D just-bash`), vercel(), or defaultSandbox() " +
- `to pick by availability. Docker reported: ${detail}`,
+ `Docker reported: ${detail}`,
);
this.name = "DockerDaemonUnavailableError";
}
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-create.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-create.ts
index 72ea38689..9336ae1e0 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-create.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-create.ts
@@ -51,15 +51,24 @@ export function enrichMicrosandboxError(input: {
const codeLabel = code === undefined ? "" : ` [${code}]`;
const detail = toErrorMessage(input.error);
const detailSentence = /[.!?]$/u.test(detail) ? detail : `${detail}.`;
- const hint = microsandboxErrorHint(code);
- const hintSuffix = hint === undefined ? "" : ` ${hint}`;
- return new MicrosandboxDiagnosticError(
- `${input.context}${codeLabel}: ${detailSentence}${hintSuffix}`,
- { cause: input.error },
- );
+ return new MicrosandboxDiagnosticError(`${input.context}${codeLabel}: ${detailSentence}`, {
+ cause: input.error,
+ hint: microsandboxErrorHint(code),
+ });
}
-class MicrosandboxDiagnosticError extends Error {}
+class MicrosandboxDiagnosticError extends Error {
+ /** Structured per-error-code remediation, surfaced by the semantic-error catalog. */
+ readonly hint?: string;
+
+ constructor(message: string, options?: ErrorOptions & { hint?: string }) {
+ super(message, options);
+ // Stable discriminator for the semantic-error catalog's sandbox rules;
+ // subclassing alone leaves `name` as "Error".
+ this.name = "MicrosandboxDiagnosticError";
+ if (options?.hint !== undefined) this.hint = options.hint;
+ }
+}
async function reportMicrosandboxCreateProgress(
events: AsyncIterable<PullProgressEvent>,
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts
index 46b2cb46d..6c4df4171 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox-runtime.test.ts
@@ -373,9 +373,10 @@ describe.skipIf(process.platform === "win32")("createPreparedMicrosandbox", () =
cause,
message: expect.stringContaining(
`Failed to create microsandbox VM from image "${MICROSANDBOX_DEFAULT_IMAGE}" ` +
- "while resolving the image [imageNotFound]: manifest was not found. " +
- "Check that the image exists and that the registry credentials can pull it.",
+ "while resolving the image [imageNotFound]: manifest was not found.",
),
+ // The per-code remediation travels as a structured hint, not prose.
+ hint: "Check that the image exists and that the registry credentials can pull it.",
});
});
diff --git a/packages/eve/src/execution/sandbox/bindings/microsandbox.test.ts b/packages/eve/src/execution/sandbox/bindings/microsandbox.test.ts
index e6ce4e39d..4f8aae65f 100644
--- a/packages/eve/src/execution/sandbox/bindings/microsandbox.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/microsandbox.test.ts
@@ -62,10 +62,12 @@ describe.skipIf(onWindows)("createMicrosandboxSandboxBackend", () => {
cause,
message: expect.stringContaining(
'Failed to prewarm microsandbox template "template-key" [database]: ' +
- "Migration file of version 'm20260606_000001_named_volume_kinds' is missing. " +
- "Check that the microsandbox npm package and installed VM runtime use the same version. " +
- "If versions changed, use a clean MSB_HOME or migrate the existing database.",
+ "Migration file of version 'm20260606_000001_named_volume_kinds' is missing.",
),
+ // The per-code remediation travels as a structured hint, not prose.
+ hint:
+ "Check that the microsandbox npm package and installed VM runtime use the same version. " +
+ "If versions changed, use a clean MSB_HOME or migrate the existing database.",
});
});
});
diff --git a/packages/eve/src/execution/terminal-session-failure-step.ts b/packages/eve/src/execution/terminal-session-failure-step.ts
index c9a0e1080..3a7735cdc 100644
--- a/packages/eve/src/execution/terminal-session-failure-step.ts
+++ b/packages/eve/src/execution/terminal-session-failure-step.ts
@@ -1,6 +1,7 @@
import { buildAdapterContext } from "#channel/adapter-context.js";
import { callAdapterEventHandler } from "#channel/adapter.js";
import { deserializeContext } from "#context/serialize.js";
+import { summarizeKnownError } from "#harness/semantic-errors/index.js";
import { createLogger, formatError } from "#internal/logging.js";
import {
createSessionFailedEvent,
@@ -19,7 +20,21 @@ export async function emitTerminalSessionFailureStep(input: {
}): Promise<void> {
"use step";
- const details = formatError(input.error);
+ // Cataloged failures replace the raw identity with the curated one; the
+ // `detail` dump stays attached so the local diagnostic log keeps the
+ // raw evidence while the transcript shows the actionable summary.
+ const formatted = formatError(input.error);
+ const summary = summarizeKnownError(input.error);
+ let details = formatted;
+ if (summary !== null) {
+ const curated = {
+ ...formatted,
+ message: summary.message,
+ name: summary.name,
+ semanticErrorId: summary.id,
+ };
+ details = summary.hint === undefined ? curated : { ...curated, hint: summary.hint };
+ }
const code = typeof details.name === "string" ? details.name : "WORKFLOW_EXECUTION_FAILED";
const message = typeof details.message === "string" ? details.message : String(input.error);
const sessionId = (input.serializedContext["eve.sessionId"] as string | undefined) ?? "";
@@ -29,6 +44,7 @@ export async function emitTerminalSessionFailureStep(input: {
errorId: typeof details.errorId === "string" ? details.errorId : undefined,
code,
message,
+ hint: summary?.hint,
detail: typeof details.detail === "string" ? details.detail : undefined,
});
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index 248a86205..5b5180e49 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -1219,6 +1219,46 @@ describe("emitTerminalSessionFailureStep", () => {
expect(writes.length).toBe(1);
});
+ it("replaces cataloged failures with their semantic summary while keeping the raw dump", async () => {
+ const sessionFailedCalls: Array<{ data: unknown }> = [];
+ const capturingAdapter: ChannelAdapter = {
+ kind: "thread-context",
+ async "session.failed"(data) {
+ sessionFailedCalls.push({ data });
+ },
+ };
+
+ const serialized = buildSerializedContextWithAdapter(capturingAdapter, "session-semantic");
+
+ const error = new TypeError("fetch failed", {
+ cause: Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:443"), {
+ code: "ECONNREFUSED",
+ }),
+ });
+
+ await emitTerminalSessionFailureStep({
+ error,
+ parentWritable: createTestWritable(),
+ serializedContext: serialized,
+ });
+
+ expect(sessionFailedCalls).toHaveLength(1);
+ const { data } = sessionFailedCalls[0] as {
+ data: {
+ code: string;
+ message: string;
+ details?: { detail?: string; hint?: string; semanticErrorId?: string };
+ };
+ };
+ expect(data.code).toBe("Network request failed");
+ expect(data.message).toContain("ECONNREFUSED");
+ expect(data.details?.semanticErrorId).toBe("network-request-failed");
+ expect(data.details?.hint).toContain("Check your internet connection");
+ // The raw inspection stays attached so the diagnostic log keeps the
+ // evidence the curated message summarizes away.
+ expect(data.details?.detail).toContain("fetch failed");
+ });
+
it("does not throw when the adapter handler itself throws", async () => {
// A throwing handler must not prevent the event from reaching
// the durable stream. This mirrors `callAdapterEventHandler`'s
diff --git a/packages/eve/src/harness/model-call-error.test.ts b/packages/eve/src/harness/model-call-error.test.ts
index 116626df4..730607a21 100644
--- a/packages/eve/src/harness/model-call-error.test.ts
+++ b/packages/eve/src/harness/model-call-error.test.ts
@@ -7,8 +7,7 @@ import {
extractUnsupportedProviderToolTypes,
isNoOutputGeneratedError,
normalizeModelStreamError,
- summarizeKnownModelCallConfigError,
- summarizeKnownModelCallRequestError,
+ extractUpstreamRejectionMessage,
} from "#harness/model-call-error.js";
import { TurnCancelledError } from "#harness/turn-cancellation.js";
@@ -25,9 +24,7 @@ function noOutputGeneratedError(): Error {
/**
* Builds a fake `GatewayAuthenticationError` shape matching what
- * `@ai-sdk/gateway` produces, so we can exercise the three-way
- * disambiguation in `summarizeKnownModelCallConfigError` without
- * importing the upstream class.
+ * `@ai-sdk/gateway` produces, without importing the upstream class.
*/
function gatewayAuthError(message: string): Error {
const error = new Error(message);
@@ -239,14 +236,18 @@ describe("classifyModelCallError", () => {
expect(classifyModelCallError(outer)).toBe("retry");
});
- it("treats common network error messages as retry-worthy", () => {
+ it("treats known network failures as retry-worthy, by structural signals only", () => {
const econnreset = Object.assign(new Error("socket error"), {
- cause: new Error("ECONNRESET fired"),
+ cause: Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" }),
});
expect(classifyModelCallError(econnreset)).toBe("retry");
const fetchFailed = new Error("fetch failed");
expect(classifyModelCallError(fetchFailed)).toBe("retry");
+
+ // The old substring policy is gone: prose that merely mentions a
+ // network token no longer forces a retry loop.
+ expect(classifyModelCallError(new Error("network configuration invalid"))).toBe("recoverable");
});
it("falls back to recoverable for unknown errors so the session parks instead of dying", () => {
@@ -256,51 +257,9 @@ describe("classifyModelCallError", () => {
});
});
-describe("summarizeKnownModelCallConfigError", () => {
- it("tells the user to update or unset AI_GATEWAY_API_KEY when the gateway rejects the api key", () => {
- // This is the path users hit when a stale `AI_GATEWAY_API_KEY` in
- // their shell profile shadows the OIDC fallback.
- const summary = summarizeKnownModelCallConfigError(
- gatewayAuthError(
- "AI Gateway authentication failed: Invalid API key.\n\nCreate a new API key…",
- ),
- );
- expect(summary?.name).toBe("AI Gateway authentication failed");
- expect(summary?.message).toMatch(/AI_GATEWAY_API_KEY/);
- expect(summary?.message).toMatch(/unset/i);
- });
-
- it("tells the user to refresh the OIDC token when the gateway rejects it", () => {
- const summary = summarizeKnownModelCallConfigError(
- gatewayAuthError(
- "AI Gateway authentication failed: Invalid OIDC token.\n\nRun 'npx vercel link'…",
- ),
- );
- expect(summary?.name).toBe("AI Gateway authentication failed");
- expect(summary?.message).toMatch(/eve link/);
- expect(summary?.message).toMatch(/VERCEL_OIDC_TOKEN/);
- });
-
- it("tells the user to provide credentials when neither was offered", () => {
- const summary = summarizeKnownModelCallConfigError(
- gatewayAuthError(
- "AI Gateway authentication failed: No authentication provided.\n\nOption 1…",
- ),
- );
- expect(summary?.name).toBe("AI Gateway authentication failed");
- expect(summary?.message).toMatch(/eve link/);
- expect(summary?.message).toMatch(/AI_GATEWAY_API_KEY/);
- });
-
- it("returns null for unrelated errors so the harness uses the raw SDK message", () => {
- expect(summarizeKnownModelCallConfigError(new Error("something else broke"))).toBeNull();
- expect(summarizeKnownModelCallConfigError(null)).toBeNull();
- });
-});
-
-describe("summarizeKnownModelCallRequestError", () => {
+describe("extractUpstreamRejectionMessage", () => {
it("summarizes Gateway 400 model request failures without blaming tool input", () => {
- const summary = summarizeKnownModelCallRequestError(
+ const summary = extractUpstreamRejectionMessage(
gatewayModelCallError({
gatewayName: "GatewayInternalServerError",
gatewayType: "internal_server_error",
@@ -324,7 +283,7 @@ describe("summarizeKnownModelCallRequestError", () => {
type: "invalid_request_error",
},
};
- const summary = summarizeKnownModelCallRequestError(
+ const summary = extractUpstreamRejectionMessage(
directApiCallError({
data,
responseBody: JSON.stringify(data),
@@ -339,7 +298,7 @@ describe("summarizeKnownModelCallRequestError", () => {
});
it("uses the direct API error message when there is no response body", () => {
- const summary = summarizeKnownModelCallRequestError(
+ const summary = extractUpstreamRejectionMessage(
directApiCallError({
message: "No endpoints found for anthropic/claude-3.5-haiku",
statusCode: 404,
@@ -359,7 +318,7 @@ describe("summarizeKnownModelCallRequestError", () => {
type: "invalid_request_error",
},
});
- const summary = summarizeKnownModelCallRequestError(
+ const summary = extractUpstreamRejectionMessage(
directApiCallError({
responseBody,
statusCode: 400,
@@ -380,7 +339,7 @@ describe("summarizeKnownModelCallRequestError", () => {
param: "input",
},
};
- const summary = summarizeKnownModelCallRequestError(
+ const summary = extractUpstreamRejectionMessage(
directApiCallError({
data,
responseBody: JSON.stringify(data),
@@ -396,7 +355,7 @@ describe("summarizeKnownModelCallRequestError", () => {
// A 503/429 that exhausts retries is an availability problem, not a
// request rejection; summarizing it as "rejected" sends users to debug
// their configuration.
- const summary = summarizeKnownModelCallRequestError(
+ const summary = extractUpstreamRejectionMessage(
gatewayModelCallError({
gatewayName: "GatewayInternalServerError",
gatewayType: "overloaded_error",
diff --git a/packages/eve/src/harness/model-call-error.ts b/packages/eve/src/harness/model-call-error.ts
index 540006b77..91e32f73e 100644
--- a/packages/eve/src/harness/model-call-error.ts
+++ b/packages/eve/src/harness/model-call-error.ts
@@ -1,6 +1,7 @@
import { isObject } from "#shared/guards.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
-import { toError } from "#shared/errors.js";
+import { toError, walkCauseChain } from "#shared/errors.js";
+import { summarizeKnownError } from "#harness/semantic-errors/index.js";
import { isTurnCancellation } from "#harness/turn-cancellation.js";
const RESPONSE_BODY_SNIPPET_LIMIT = 1_000;
@@ -8,20 +9,6 @@ const API_ERROR_SUMMARY_LIMIT = 800;
const GATEWAY_MODEL_REQUEST_REJECTED_MESSAGE =
"AI Gateway rejected the model request before the agent produced a response.";
-/**
- * The upstream error name the AI Gateway uses for authentication failures.
- * Exported so consumers of `step.failed` details (the dev TUI's `/model`
- * hint) match the same identifier this module classifies on.
- */
-export const GATEWAY_AUTHENTICATION_ERROR_NAME = "GatewayAuthenticationError";
-
-/**
- * The summary `name` this module assigns to recognized gateway-auth
- * failures, carried into failure-event details. Exported for the same
- * consumers as {@link GATEWAY_AUTHENTICATION_ERROR_NAME}.
- */
-export const GATEWAY_AUTH_FAILURE_SUMMARY_NAME = "AI Gateway authentication failed";
-
/**
* Anchored regex for the upstream "unsupported tool" rejection message
* that AI Gateway returns when a fallback provider cannot serve a
@@ -35,15 +22,12 @@ export const GATEWAY_AUTH_FAILURE_SUMMARY_NAME = "AI Gateway authentication fail
const UNSUPPORTED_TOOL_TYPE_REGEX = /tool type ['"]([\w.-]+)['"] is not supported/i;
/**
- * One human-readable summary of a known model-call configuration failure.
- *
- * Returned by {@link summarizeKnownModelCallConfigError} for terminal
- * failures that point at a fixable setup mistake (missing API key,
- * gateway auth failure). Surfaces actionable text in REPL output and in
- * structured `step.failed` events without dumping the full SDK error
- * inspection into user-facing logs.
+ * The most informative human-readable rejection a model-call error
+ * carries, extracted from the upstream response. Not a semantic-error
+ * classification: the message is arbitrary provider prose, so it carries
+ * no catalog id — `semanticErrorId` is reserved for registered rules.
*/
-export interface ModelCallConfigErrorSummary {
+export interface UpstreamRejectionSummary {
readonly name: string;
readonly message: string;
}
@@ -62,75 +46,13 @@ interface ModelCallErrorSignals {
}
/**
- * Returns a concise actionable summary for known terminal configuration
- * errors raised during a model call. Returns `null` for everything else
- * so the caller falls back to the raw SDK message.
- */
-export function summarizeKnownModelCallConfigError(
- error: unknown,
-): ModelCallConfigErrorSummary | null {
- const rawName = readErrorName(error);
- const rawMessage = readErrorMessage(error);
-
- if (
- rawName === GATEWAY_AUTHENTICATION_ERROR_NAME ||
- /AI Gateway authentication/i.test(rawMessage)
- ) {
- // The upstream `GatewayAuthenticationError` builds one of three
- // contextual messages depending on which credential was offered
- // (api-key, oidc, neither). Surface a remediation that matches the
- // one that actually failed — collapsing all three into a single
- // "set AI_GATEWAY_API_KEY" hint misleads users whose shell already
- // exports a stale `AI_GATEWAY_API_KEY` that shadows the OIDC fallback.
- if (/Invalid API key/i.test(rawMessage)) {
- return {
- name: GATEWAY_AUTH_FAILURE_SUMMARY_NAME,
- message:
- "AI Gateway rejected the provided API key. Update or unset `AI_GATEWAY_API_KEY` (check your shell profile if you did not set it for this project) — manage keys at https://vercel.com/dashboard/ai/api-keys. Unsetting it falls back to OIDC via `eve link`.",
- };
- }
- if (/Invalid OIDC token/i.test(rawMessage)) {
- return {
- name: GATEWAY_AUTH_FAILURE_SUMMARY_NAME,
- message:
- "AI Gateway rejected the OIDC token. Run `eve link` to refresh `VERCEL_OIDC_TOKEN` in `.env.local`, or set `AI_GATEWAY_API_KEY` — create a key at https://vercel.com/dashboard/ai/api-keys.",
- };
- }
- return {
- name: GATEWAY_AUTH_FAILURE_SUMMARY_NAME,
- message:
- "AI Gateway received no credentials. Run `eve link` to populate `VERCEL_OIDC_TOKEN`, or set `AI_GATEWAY_API_KEY` — create a key at https://vercel.com/dashboard/ai/api-keys.",
- };
- }
-
- if (rawName === "LoadAPIKeyError" || /API key is missing/i.test(rawMessage)) {
- return {
- name: "Model provider API key missing",
- message:
- "The model provider could not load an API key. Export the provider's API key environment variable (for example `AI_GATEWAY_API_KEY` or `OPENAI_API_KEY`) and try again.",
- };
- }
-
- return null;
-}
-
-/**
- * Returns a concise summary for known model-call request failures that are not
- * configuration errors. These failures happen before the agent can produce a
- * response, so the user-facing message should avoid implying a bad tool call.
+ * Extracts the most informative upstream rejection message from a
+ * model-call error that the semantic-error catalog did not recognize.
+ * These failures happen before the agent can produce a response, so the
+ * user-facing message should avoid implying a bad tool call. Returns
+ * `null` when the error carries nothing better than its raw message.
*/
-export function summarizeKnownModelCallRequestError(
- error: unknown,
-): ModelCallConfigErrorSummary | null {
- // Known benign shape: skip the inspector dump and the stack (which would
- // point at the harness's own throw site, not upstream evidence).
- if (error instanceof EmptyModelResponseError) {
- return {
- name: "Empty model response",
- message: error.message,
- };
- }
-
+export function extractUpstreamRejectionMessage(error: unknown): UpstreamRejectionSummary | null {
const signals = readModelCallErrorSignals(error);
// Transient upstream failures (throttles, overloads) keep the generic
@@ -142,12 +64,7 @@ export function summarizeKnownModelCallRequestError(
const apiSummary = signals.apiErrorMessage;
if (apiSummary !== undefined) {
- return {
- name: isGatewayErrorSignal(signals)
- ? "AI Gateway model request rejected"
- : "Model provider API error",
- message: apiSummary,
- };
+ return { name: upstreamRejectionName(signals), message: apiSummary };
}
if (signals.statusCode === 400 && isGatewayErrorSignal(signals)) {
@@ -159,17 +76,18 @@ export function summarizeKnownModelCallRequestError(
const apiCallSummary = formatApiCallErrorFallback(signals);
if (apiCallSummary !== undefined) {
- return {
- name: isGatewayErrorSignal(signals)
- ? "AI Gateway model request rejected"
- : "Model provider API error",
- message: apiCallSummary,
- };
+ return { name: upstreamRejectionName(signals), message: apiCallSummary };
}
return null;
}
+function upstreamRejectionName(signals: ModelCallErrorSignals): string {
+ return isGatewayErrorSignal(signals)
+ ? "AI Gateway model request rejected"
+ : "Model provider API error";
+}
+
function isTransientHttpStatus(status: number | undefined): boolean {
return status === 408 || status === 429 || (status !== undefined && status >= 500);
}
@@ -361,17 +279,29 @@ export function classifyModelCallError(error: unknown): "retry" | "recoverable"
return "retry";
}
- if (summarizeKnownModelCallConfigError(error) !== null) {
+ // The catalog's tags carry the recovery judgment for every failure
+ // shape it can see on the cause chain: a fixable configuration mistake
+ // is terminal (repeating the request cannot fix a credential), a
+ // transient provider condition retries.
+ const summary = summarizeKnownError(error);
+ if (summary?.tags.includes("config") === true) {
return "terminal";
}
+ if (summary?.tags.includes("transient") === true) {
+ return "retry";
+ }
const signals = readModelCallErrorSignals(error);
- if (isRetryableGatewayType(signals.gatewayType) || isRetryableGatewayType(signals.upstreamType)) {
+ // The catalog matches structural fields on the chain; these checks
+ // cover the one channel it deliberately does not model — discriminators
+ // that only exist inside the deep-parsed upstream response body — plus
+ // the invalid-request shape, whose message is too free-form to catalog.
+ if (isRetryableGatewayType(signals.upstreamType)) {
return "retry";
}
if (
- isTerminalGatewayType(signals.gatewayType) ||
isTerminalGatewayType(signals.upstreamType) ||
+ signals.gatewayType === "invalid_request_error" ||
signals.gatewayName === "GatewayInvalidRequestError"
) {
return "terminal";
@@ -388,10 +318,6 @@ export function classifyModelCallError(error: unknown): "retry" | "recoverable"
if (status >= 400 && status < 500) return "terminal";
}
- if (isLikelyNetworkError(error)) {
- return "retry";
- }
-
return "recoverable";
}
@@ -404,25 +330,6 @@ function hasRetryableFlag(error: unknown): boolean {
return false;
}
-function isLikelyNetworkError(error: unknown): boolean {
- if (!(error instanceof Error)) return false;
- const message = error.message.toLowerCase();
- if (
- message.includes("econnreset") ||
- message.includes("etimedout") ||
- message.includes("eai_again") ||
- message.includes("socket hang up") ||
- message.includes("network") ||
- message.includes("fetch failed")
- ) {
- return true;
- }
- if (error.cause !== undefined && error.cause !== error) {
- return isLikelyNetworkError(error.cause);
- }
- return false;
-}
-
function readModelCallErrorSignals(error: unknown): ModelCallErrorSignals {
const gatewayError = findGatewayError(error);
const upstreamError = findUpstreamApiCallError(error);
@@ -650,16 +557,6 @@ function isAmbiguousGatewayInternalBadRequest(signals: ModelCallErrorSignals): b
);
}
-function* walkCauseChain(error: unknown): Generator<unknown> {
- const seen = new Set<unknown>();
- let current = error;
- while (isObject(current) && !seen.has(current)) {
- seen.add(current);
- yield current;
- current = current.cause;
- }
-}
-
function appendJsonField(target: Record<string, JsonValue>, key: string, value: unknown): void {
if (typeof value === "string" && value.length > 0) {
target[key] = value;
diff --git a/packages/eve/src/harness/semantic-errors/index.ts b/packages/eve/src/harness/semantic-errors/index.ts
new file mode 100644
index 000000000..4a92fa0c2
--- /dev/null
+++ b/packages/eve/src/harness/semantic-errors/index.ts
@@ -0,0 +1,43 @@
+import {
+ evaluateSemanticErrorRules,
+ type SemanticErrorRule,
+ type SemanticErrorSummary,
+} from "./rule.js";
+import { extractErrorSignals } from "./signals.js";
+import { GATEWAY_RULES } from "./rules/gateway.js";
+import { MODEL_PROVIDER_RULES } from "./rules/model-provider.js";
+import { SANDBOX_RULES } from "./rules/sandbox.js";
+import { SYSTEM_RULES } from "./rules/system.js";
+import { WORKFLOW_RULES } from "./rules/workflow.js";
+
+export type { ErrorLink, ErrorSignals } from "./signals.js";
+export type { LinkPredicate, SemanticErrorRule, SemanticErrorSummary } from "./rule.js";
+
+/**
+ * The semantic-error catalog: an ordered list of declarative rules, linter
+ * style, applied to any thrown error to classify it. Domain modules under
+ * `rules/` each contribute independent rules keyed on structural signals
+ * (`name`, `code`, gateway `type`, exact messages) — never on volatile
+ * message prose — and the first matching rule wins, so specific rules come
+ * before general ones and the broad network fallback comes last.
+ *
+ * This is the growth point: when a new raw error shows up in diagnostic
+ * logs often enough to deserve a curated message, add a rule to the
+ * matching domain module with a new stable `id`.
+ */
+const CATALOG: readonly SemanticErrorRule[] = [
+ ...GATEWAY_RULES,
+ ...MODEL_PROVIDER_RULES,
+ ...WORKFLOW_RULES,
+ ...SANDBOX_RULES,
+ ...SYSTEM_RULES,
+];
+
+/**
+ * Projects any thrown error into its cataloged semantic summary, or
+ * `null` when no rule matches — callers then fall back to the raw
+ * message plus the full diagnostic dump routed to the log.
+ */
+export function summarizeKnownError(error: unknown): SemanticErrorSummary | null {
+ return evaluateSemanticErrorRules(CATALOG, extractErrorSignals(error));
+}
diff --git a/packages/eve/src/harness/semantic-errors/rule.ts b/packages/eve/src/harness/semantic-errors/rule.ts
new file mode 100644
index 000000000..7c8b34467
--- /dev/null
+++ b/packages/eve/src/harness/semantic-errors/rule.ts
@@ -0,0 +1,133 @@
+import type { ErrorLink, ErrorSignals } from "./signals.js";
+
+/**
+ * Classification tags a rule carries in addition to its domain:
+ *
+ * - `config` — the failure points at a fixable setup mistake (missing or
+ * invalid credentials, unknown model id). The model-call classifier
+ * treats a matched `config` rule as terminal.
+ * - `transient` — the failure is expected to clear on retry.
+ */
+export type SemanticErrorTag =
+ | "gateway"
+ | "model-provider"
+ | "workflow"
+ | "sandbox"
+ | "system"
+ | "config"
+ | "transient";
+
+/** A predicate over one extracted cause-chain link. */
+export type LinkPredicate = (link: ErrorLink) => boolean;
+
+/**
+ * One catalog rule, in the linter shape: a stable id, a headline, a
+ * declarative predicate over extracted {@link ErrorLink} facts, and the
+ * remediation copy. Rules are pure and independent; the catalog is an
+ * ordered list where the first match wins, so put specific rules before
+ * general ones.
+ */
+export interface SemanticErrorRule {
+ /** Stable kebab-case catalog identifier, greppable across logs and code. */
+ readonly id: string;
+ /** Short human-readable failure title used as the display headline. */
+ readonly name: string;
+ readonly tags: readonly SemanticErrorTag[];
+ /** Matches when ANY link on the cause chain satisfies the predicate. */
+ readonly when: LinkPredicate;
+ /**
+ * What happened — one factual sentence, or a projection of the matched
+ * link (e.g. pass-through for eve-authored error messages).
+ */
+ readonly message: string | ((link: ErrorLink) => string);
+ /**
+ * What to do about it. Structured separately from `message` so render
+ * surfaces can style, replace, or suppress the remediation
+ * independently of the description (the dev TUI swaps in local
+ * `/model` hints; a channel adapter may drop CLI advice entirely).
+ */
+ readonly hint?: string | ((link: ErrorLink) => string | undefined);
+}
+
+/** A matched rule projected into a displayable summary. */
+export interface SemanticErrorSummary {
+ readonly id: string;
+ readonly name: string;
+ /**
+ * The matched rule's tags, carried so consumers with a recovery policy
+ * (the model-call classifier) can read the catalog's judgment —
+ * `config` is terminal, `transient` retries — without a second registry
+ * of the same knowledge.
+ */
+ readonly tags: readonly SemanticErrorTag[];
+ /** What happened. */
+ readonly message: string;
+ /** What to do about it, when the rule carries remediation. */
+ readonly hint?: string;
+}
+
+/** Evaluates an ordered rule list against extracted signals; first match wins. */
+export function evaluateSemanticErrorRules(
+ rules: readonly SemanticErrorRule[],
+ signals: ErrorSignals,
+): SemanticErrorSummary | null {
+ for (const rule of rules) {
+ const link = signals.chain.find((candidate) => rule.when(candidate));
+ if (link === undefined) continue;
+ const summary: {
+ -readonly [Key in keyof SemanticErrorSummary]: SemanticErrorSummary[Key];
+ } = {
+ id: rule.id,
+ name: rule.name,
+ tags: rule.tags,
+ message: typeof rule.message === "string" ? rule.message : rule.message(link),
+ };
+ const hint = typeof rule.hint === "function" ? rule.hint(link) : rule.hint;
+ if (hint !== undefined && hint.length > 0) summary.hint = hint;
+ return summary;
+ }
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// Predicate combinators — the declarative vocabulary rules are written in.
+// ---------------------------------------------------------------------------
+
+/** Matches when the link's `name` equals any of the given class names. */
+export function nameIs(...names: readonly string[]): LinkPredicate {
+ return (link) => link.name !== undefined && names.includes(link.name);
+}
+
+/** Matches when the link's `code` equals any of the given codes. */
+export function codeIs(...codes: readonly string[]): LinkPredicate {
+ return (link) => link.code !== undefined && codes.includes(link.code);
+}
+
+/** Matches when the link's gateway body `type` equals any of the given types. */
+export function typeIs(...types: readonly string[]): LinkPredicate {
+ return (link) => link.type !== undefined && types.includes(link.type);
+}
+
+/**
+ * Matches when the link's message equals one of the given strings exactly
+ * (after trimming). Exact equality, not containment: a user error that
+ * merely *mentions* a known failure string must not be reclassified.
+ */
+export function messageIs(...messages: readonly string[]): LinkPredicate {
+ return (link) => messages.includes(link.message.trim());
+}
+
+/** Matches when the link's message matches the pattern. */
+export function messageMatches(pattern: RegExp): LinkPredicate {
+ return (link) => pattern.test(link.message);
+}
+
+/** Matches when every given predicate matches the same link. */
+export function allOf(...predicates: readonly LinkPredicate[]): LinkPredicate {
+ return (link) => predicates.every((predicate) => predicate(link));
+}
+
+/** Matches when any given predicate matches the link. */
+export function anyOf(...predicates: readonly LinkPredicate[]): LinkPredicate {
+ return (link) => predicates.some((predicate) => predicate(link));
+}
diff --git a/packages/eve/src/harness/semantic-errors/rules/gateway.ts b/packages/eve/src/harness/semantic-errors/rules/gateway.ts
new file mode 100644
index 000000000..1fcb3363b
--- /dev/null
+++ b/packages/eve/src/harness/semantic-errors/rules/gateway.ts
@@ -0,0 +1,84 @@
+import { allOf, anyOf, messageMatches, nameIs, typeIs, type SemanticErrorRule } from "../rule.js";
+
+/** The summary `name` shared by the gateway-auth rule variants. */
+const GATEWAY_AUTH_FAILURE_SUMMARY_NAME = "AI Gateway authentication failed";
+
+/**
+ * The upstream `GatewayAuthenticationError` builds one of exactly three
+ * contextual messages depending on which credential was offered — verbatim
+ * in the vendored `@ai-sdk/gateway` source: "AI Gateway authentication
+ * failed: Invalid API key." / ": Invalid OIDC token." / ": No
+ * authentication provided.". Each variant gets its own rule so the
+ * remediation matches the credential that actually failed — collapsing all
+ * three into a single "set AI_GATEWAY_API_KEY" hint misleads users whose
+ * shell already exports a stale `AI_GATEWAY_API_KEY` that shadows the OIDC
+ * fallback.
+ */
+const gatewayAuthenticationFailure = anyOf(
+ nameIs("GatewayAuthenticationError"),
+ typeIs("authentication_error"),
+ messageMatches(/AI Gateway authentication/i),
+);
+
+/**
+ * Error class names and body `type` discriminators are verified against
+ * the vendored `@ai-sdk/gateway` source: the `Gateway*Error` classes and
+ * the body types `authentication_error`, `invalid_request_error`,
+ * `model_not_found`, `rate_limit_exceeded`, `timeout_error`,
+ * `internal_server_error` all appear there verbatim. `overloaded_error`
+ * is not gateway vocabulary — it is the Anthropic upstream error type the
+ * gateway relays on provider overload.
+ */
+export const GATEWAY_RULES: readonly SemanticErrorRule[] = [
+ {
+ id: "gateway-auth-invalid-api-key",
+ name: GATEWAY_AUTH_FAILURE_SUMMARY_NAME,
+ tags: ["gateway", "config"],
+ when: allOf(gatewayAuthenticationFailure, messageMatches(/Invalid API key/i)),
+ message: "AI Gateway rejected the provided API key.",
+ hint: "Update or unset `AI_GATEWAY_API_KEY` (check your shell profile if you did not set it for this project) — manage keys at https://vercel.com/dashboard/ai/api-keys. Unsetting it falls back to OIDC via `eve link`.",
+ },
+ {
+ id: "gateway-auth-invalid-oidc-token",
+ name: GATEWAY_AUTH_FAILURE_SUMMARY_NAME,
+ tags: ["gateway", "config"],
+ when: allOf(gatewayAuthenticationFailure, messageMatches(/Invalid OIDC token/i)),
+ message: "AI Gateway rejected the OIDC token.",
+ hint: "Run `eve link` to refresh `VERCEL_OIDC_TOKEN` in `.env.local`, or set `AI_GATEWAY_API_KEY` — create a key at https://vercel.com/dashboard/ai/api-keys.",
+ },
+ {
+ id: "gateway-auth-missing-credentials",
+ name: GATEWAY_AUTH_FAILURE_SUMMARY_NAME,
+ tags: ["gateway", "config"],
+ when: gatewayAuthenticationFailure,
+ message: "AI Gateway received no credentials.",
+ hint: "Run `eve link` to populate `VERCEL_OIDC_TOKEN`, or set `AI_GATEWAY_API_KEY` — create a key at https://vercel.com/dashboard/ai/api-keys.",
+ },
+ {
+ id: "model-not-found",
+ name: "Model not found",
+ tags: ["gateway", "config"],
+ when: anyOf(
+ nameIs("GatewayModelNotFoundError", "AI_NoSuchModelError"),
+ typeIs("model_not_found"),
+ ),
+ message: "The requested model is not available.",
+ hint: "Check the model id in `agent.ts` (`model:`) or switch models with `/model` in `eve dev` — browse available models at https://vercel.com/ai-gateway/models.",
+ },
+ {
+ id: "gateway-rate-limited",
+ name: "AI Gateway rate limit exceeded",
+ tags: ["gateway", "transient"],
+ when: anyOf(nameIs("GatewayRateLimitError"), typeIs("rate_limit_exceeded")),
+ message: "AI Gateway rate-limited the request.",
+ hint: "Retries are automatic; if it persists, reduce request volume or review your plan limits at https://vercel.com/ai-gateway.",
+ },
+ {
+ id: "gateway-upstream-unavailable",
+ name: "Model provider unavailable",
+ tags: ["gateway", "transient"],
+ when: anyOf(nameIs("GatewayTimeoutError"), typeIs("timeout_error", "overloaded_error")),
+ message: "The model provider is overloaded or timing out upstream of AI Gateway.",
+ hint: "This is transient — retry shortly, or switch models with `/model` in `eve dev`.",
+ },
+];
diff --git a/packages/eve/src/harness/semantic-errors/rules/model-provider.ts b/packages/eve/src/harness/semantic-errors/rules/model-provider.ts
new file mode 100644
index 000000000..af5a5d157
--- /dev/null
+++ b/packages/eve/src/harness/semantic-errors/rules/model-provider.ts
@@ -0,0 +1,44 @@
+import { anyOf, messageMatches, nameIs, type SemanticErrorRule } from "../rule.js";
+
+/**
+ * Discriminators verified against the vendored `@ai-sdk/provider` /
+ * `@ai-sdk/provider-utils` source: the error classes set
+ * `name = "AI_LoadAPIKeyError"` / `"AI_UnsupportedFunctionalityError"`,
+ * and `loadApiKey` builds its message as
+ * `"<provider> API key is missing. Pass it using the …"`. The bare
+ * `LoadAPIKeyError` spelling is defensive, for provider adapters that
+ * rethrow under the unprefixed class name.
+ */
+export const MODEL_PROVIDER_RULES: readonly SemanticErrorRule[] = [
+ {
+ id: "model-provider-api-key-missing",
+ name: "Model provider API key missing",
+ tags: ["model-provider", "config"],
+ when: anyOf(
+ nameIs("LoadAPIKeyError", "AI_LoadAPIKeyError"),
+ messageMatches(/API key is missing/i),
+ ),
+ message: "The model provider could not load an API key.",
+ hint: "Export the provider's API key environment variable (for example `AI_GATEWAY_API_KEY` or `OPENAI_API_KEY`) and try again.",
+ },
+ {
+ // eve's own EmptyModelResponseError (harness/model-call-error.ts); its
+ // message is authored for end users, so it passes through. The
+ // model-call classifier special-cases this shape *before* consulting
+ // tags — a same-hooks retry would read a stale step result.
+ id: "empty-model-response",
+ name: "Empty model response",
+ tags: ["model-provider", "transient"],
+ when: nameIs("EmptyModelResponseError"),
+ message: (link) => link.message,
+ },
+ {
+ id: "model-capability-unsupported",
+ name: "Model capability not supported",
+ tags: ["model-provider"],
+ when: nameIs("AI_UnsupportedFunctionalityError"),
+ message:
+ "The selected model does not support a capability this agent uses (a tool type, modality, or feature).",
+ hint: "Remove the unsupported tool or switch to a model that supports it.",
+ },
+];
diff --git a/packages/eve/src/harness/semantic-errors/rules/sandbox.ts b/packages/eve/src/harness/semantic-errors/rules/sandbox.ts
new file mode 100644
index 000000000..1b3b13ee2
--- /dev/null
+++ b/packages/eve/src/harness/semantic-errors/rules/sandbox.ts
@@ -0,0 +1,45 @@
+import { nameIs, type SemanticErrorRule } from "../rule.js";
+
+const passThroughMessage = (link: { readonly message: string }) => link.message;
+const passThroughHint = (link: { readonly hint?: string }) => link.hint;
+
+/**
+ * Error class names come from eve's own sandbox backends —
+ * `DockerUnavailableError` / `DockerDaemonUnavailableError` in
+ * `execution/sandbox/bindings/docker-cli.ts` and
+ * `MicrosandboxDiagnosticError` in
+ * `execution/sandbox/bindings/microsandbox-create.ts` — each of which
+ * assigns `this.name` explicitly. Those classes already author actionable
+ * remediation messages at the failure site — where the missing binary or
+ * unreachable daemon is actually known — so these rules contribute the
+ * stable catalog identity and pass the message through. Matching is by
+ * name string rather than `instanceof` because the harness must not
+ * import from `execution/` and the classes survive structured clone as
+ * plain shapes.
+ */
+export const SANDBOX_RULES: readonly SemanticErrorRule[] = [
+ {
+ id: "sandbox-docker-cli-missing",
+ name: "Docker CLI not found",
+ tags: ["sandbox", "config"],
+ when: nameIs("DockerUnavailableError"),
+ message: passThroughMessage,
+ hint: passThroughHint,
+ },
+ {
+ id: "sandbox-docker-daemon-unreachable",
+ name: "Docker daemon unreachable",
+ tags: ["sandbox", "config"],
+ when: nameIs("DockerDaemonUnavailableError"),
+ message: passThroughMessage,
+ hint: passThroughHint,
+ },
+ {
+ id: "sandbox-provisioning-failed",
+ name: "Sandbox provisioning failed",
+ tags: ["sandbox"],
+ when: nameIs("MicrosandboxDiagnosticError"),
+ message: passThroughMessage,
+ hint: passThroughHint,
+ },
+];
diff --git a/packages/eve/src/harness/semantic-errors/rules/system.ts b/packages/eve/src/harness/semantic-errors/rules/system.ts
new file mode 100644
index 000000000..6abc3b36e
--- /dev/null
+++ b/packages/eve/src/harness/semantic-errors/rules/system.ts
@@ -0,0 +1,71 @@
+import { codeIs, messageIs, type SemanticErrorRule } from "../rule.js";
+
+/**
+ * Node/undici error codes that identify a failed network dial or a
+ * connection dropped mid-request, independent of what the surrounding
+ * library wrapped them in.
+ */
+const NETWORK_ERROR_CODES = [
+ "ECONNREFUSED",
+ "ECONNRESET",
+ "EAI_AGAIN",
+ "ENOTFOUND",
+ "EPIPE",
+ "ETIMEDOUT",
+ "UND_ERR_CONNECT_TIMEOUT",
+ "UND_ERR_SOCKET",
+] as const;
+
+const NETWORK_FAILURE_HINT =
+ "Check your internet connection and that the target service is reachable, then try again.";
+
+export const SYSTEM_RULES: readonly SemanticErrorRule[] = [
+ {
+ id: "port-already-in-use",
+ name: "Port already in use",
+ tags: ["system", "config"],
+ when: codeIs("EADDRINUSE"),
+ message:
+ "The port is already in use — another process (perhaps another `eve dev`) is listening on it.",
+ hint: "Stop that process or pass a different `--port`.",
+ },
+ {
+ id: "disk-full",
+ name: "Disk full",
+ tags: ["system"],
+ when: codeIs("ENOSPC"),
+ message: "The disk is full, so writes are failing.",
+ hint: "Free up space and retry.",
+ },
+ // One failure shape, two detection signals in priority order: a
+ // structured code anywhere on the chain beats a message match, because
+ // undici wraps the coded socket error under a generic `fetch failed`
+ // and the code is the evidence worth naming in the summary.
+ {
+ id: "network-request-failed",
+ name: "Network request failed",
+ tags: ["system", "transient"],
+ when: codeIs(...NETWORK_ERROR_CODES),
+ message: (link) => networkFailureMessage(link.code ?? "network error"),
+ hint: NETWORK_FAILURE_HINT,
+ },
+ {
+ // Exact-equality message fallback, verified empirically on Node 26:
+ // a failed `fetch` rejects with a TypeError whose message is exactly
+ // "fetch failed" (the coded cause is sometimes stripped in transit),
+ // and a peer-destroyed HTTP socket errors with exactly "socket hang
+ // up" (code ECONNRESET — the code rule above normally wins).
+ // Equality, never containment: a user error that merely mentions
+ // "fetch failed" must not be reclassified as a connectivity problem.
+ id: "network-request-failed",
+ name: "Network request failed",
+ tags: ["system", "transient"],
+ when: messageIs("fetch failed", "socket hang up"),
+ message: (link) => networkFailureMessage(link.message.trim()),
+ hint: NETWORK_FAILURE_HINT,
+ },
+];
+
+function networkFailureMessage(evidence: string): string {
+ return `A network request failed before completing (${evidence}).`;
+}
diff --git a/packages/eve/src/harness/semantic-errors/rules/workflow.ts b/packages/eve/src/harness/semantic-errors/rules/workflow.ts
new file mode 100644
index 000000000..332d6b849
--- /dev/null
+++ b/packages/eve/src/harness/semantic-errors/rules/workflow.ts
@@ -0,0 +1,53 @@
+import { nameIs, type SemanticErrorRule } from "../rule.js";
+
+/**
+ * Error class names verified against the vendored `@workflow/errors` and
+ * `@workflow/world-local` source: every class assigns `this.name`
+ * explicitly in its constructor (`this.name = 'ReplayDivergenceError'`,
+ * `'DataDirVersionError'`, …), so the discriminator is stable and
+ * survives structured clone across workflow step boundaries.
+ */
+export const WORKFLOW_RULES: readonly SemanticErrorRule[] = [
+ {
+ id: "workflow-store-version-mismatch",
+ name: "Local session store incompatible",
+ tags: ["workflow"],
+ when: nameIs("DataDirVersionError"),
+ message:
+ "The local workflow store (`.eve/.workflow-data`) was created by an incompatible version.",
+ hint: "Remove that directory to reset local sessions, then retry.",
+ },
+ {
+ id: "workflow-store-inaccessible",
+ name: "Local session store inaccessible",
+ tags: ["workflow"],
+ when: nameIs("DataDirAccessError"),
+ message: "The local workflow store (`.eve/.workflow-data`) could not be created or accessed.",
+ hint: "Check filesystem permissions and free disk space, then retry.",
+ },
+ {
+ id: "workflow-replay-divergence",
+ name: "Durable replay diverged",
+ tags: ["workflow"],
+ when: nameIs("ReplayDivergenceError"),
+ message:
+ "The durable workflow replay diverged from the recorded run — usually caused by code changing mid-session in a way the runtime cannot reconcile.",
+ hint: "Start a fresh session (`/new` in `eve dev`).",
+ },
+ {
+ id: "workflow-event-log-corrupted",
+ name: "Durable event log corrupted",
+ tags: ["workflow"],
+ when: nameIs("CorruptedEventLogError"),
+ message: "The durable event log for this run is corrupted.",
+ hint: "Remove `.eve/.workflow-data` to reset local sessions, then retry.",
+ },
+ {
+ id: "workflow-run-not-found",
+ name: "Session run not found",
+ tags: ["workflow"],
+ when: nameIs("WorkflowRunNotFoundError"),
+ message: "This session's durable run no longer exists (the local store was reset or pruned).",
+ hint: "Start a new session.",
+ },
+];
diff --git a/packages/eve/src/harness/semantic-errors/semantic-errors.test.ts b/packages/eve/src/harness/semantic-errors/semantic-errors.test.ts
new file mode 100644
index 000000000..8189a0b58
--- /dev/null
+++ b/packages/eve/src/harness/semantic-errors/semantic-errors.test.ts
@@ -0,0 +1,268 @@
+import { describe, expect, it } from "vitest";
+
+import { summarizeKnownError } from "./index.js";
+import { allOf, anyOf, codeIs, evaluateSemanticErrorRules, messageIs, nameIs } from "./rule.js";
+import { extractErrorSignals } from "./signals.js";
+
+function named(name: string, message: string, extra?: Record<string, unknown>): Error {
+ const error = new Error(message);
+ error.name = name;
+ return Object.assign(error, extra);
+}
+
+describe("summarizeKnownError (catalog table)", () => {
+ const cases: readonly {
+ readonly title: string;
+ readonly error: unknown;
+ readonly id: string;
+ }[] = [
+ {
+ title: "gateway invalid api key",
+ error: named(
+ "GatewayAuthenticationError",
+ "AI Gateway authentication failed: Invalid API key provided.",
+ ),
+ id: "gateway-auth-invalid-api-key",
+ },
+ {
+ title: "gateway invalid oidc token",
+ error: named(
+ "GatewayAuthenticationError",
+ "AI Gateway authentication failed: Invalid OIDC token.",
+ ),
+ id: "gateway-auth-invalid-oidc-token",
+ },
+ {
+ title: "gateway auth without a recognizable variant",
+ error: named(
+ "GatewayAuthenticationError",
+ "AI Gateway authentication failed: No authentication provided.",
+ ),
+ id: "gateway-auth-missing-credentials",
+ },
+ {
+ title: "gateway model not found by name",
+ error: named("GatewayModelNotFoundError", "model not found"),
+ id: "model-not-found",
+ },
+ {
+ title: "model not found by gateway body type",
+ error: Object.assign(new Error("bad request"), { type: "model_not_found" }),
+ id: "model-not-found",
+ },
+ {
+ title: "ai sdk unknown model id",
+ error: named("AI_NoSuchModelError", "no such model"),
+ id: "model-not-found",
+ },
+ {
+ title: "gateway rate limit",
+ error: named("GatewayRateLimitError", "rate limited"),
+ id: "gateway-rate-limited",
+ },
+ {
+ title: "gateway upstream overloaded",
+ error: Object.assign(new Error("overloaded"), { type: "overloaded_error" }),
+ id: "gateway-upstream-unavailable",
+ },
+ {
+ title: "provider api key missing",
+ error: named("LoadAPIKeyError", "OpenAI API key is missing."),
+ id: "model-provider-api-key-missing",
+ },
+ {
+ title: "empty model response",
+ error: named(
+ "EmptyModelResponseError",
+ "The model did not return a response. Please try again.",
+ ),
+ id: "empty-model-response",
+ },
+ {
+ title: "unsupported model capability",
+ error: named("AI_UnsupportedFunctionalityError", "tool type not supported"),
+ id: "model-capability-unsupported",
+ },
+ {
+ title: "workflow store version mismatch",
+ error: named("DataDirVersionError", "data dir was created by a newer version"),
+ id: "workflow-store-version-mismatch",
+ },
+ {
+ title: "workflow store inaccessible",
+ error: named("DataDirAccessError", "EACCES"),
+ id: "workflow-store-inaccessible",
+ },
+ {
+ title: "workflow replay divergence",
+ error: named("ReplayDivergenceError", "replay diverged at step 3"),
+ id: "workflow-replay-divergence",
+ },
+ {
+ title: "workflow event log corrupted",
+ error: named("CorruptedEventLogError", "corrupted"),
+ id: "workflow-event-log-corrupted",
+ },
+ {
+ title: "workflow run not found",
+ error: named("WorkflowRunNotFoundError", "wrun_x not found"),
+ id: "workflow-run-not-found",
+ },
+ {
+ title: "docker cli missing",
+ error: named("DockerUnavailableError", "Docker CLI not found. Install Docker Desktop."),
+ id: "sandbox-docker-cli-missing",
+ },
+ {
+ title: "docker daemon unreachable",
+ error: named(
+ "DockerDaemonUnavailableError",
+ "The Docker sandbox backend requires a running Docker daemon.",
+ ),
+ id: "sandbox-docker-daemon-unreachable",
+ },
+ {
+ title: "microsandbox provisioning failure",
+ error: named("MicrosandboxDiagnosticError", "pulling template [T001]: registry unreachable."),
+ id: "sandbox-provisioning-failed",
+ },
+ {
+ title: "port in use",
+ error: Object.assign(new Error("listen EADDRINUSE: address already in use"), {
+ code: "EADDRINUSE",
+ }),
+ id: "port-already-in-use",
+ },
+ {
+ title: "disk full",
+ error: Object.assign(new Error("write failed"), { code: "ENOSPC" }),
+ id: "disk-full",
+ },
+ {
+ title: "network failure by code on the cause chain",
+ error: new TypeError("fetch failed", {
+ cause: Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:3000"), {
+ code: "ECONNREFUSED",
+ }),
+ }),
+ id: "network-request-failed",
+ },
+ {
+ title: "bare fetch failure without a structured code",
+ error: new TypeError("fetch failed"),
+ id: "network-request-failed",
+ },
+ ];
+
+ for (const testCase of cases) {
+ it(`classifies ${testCase.title}`, () => {
+ expect(summarizeKnownError(testCase.error)?.id).toBe(testCase.id);
+ });
+ }
+
+ it("prefers the structured code as network evidence over the generic wrapper message", () => {
+ const error = new TypeError("fetch failed", {
+ cause: Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:3000"), {
+ code: "ECONNREFUSED",
+ }),
+ });
+ expect(summarizeKnownError(error)?.message).toContain("ECONNREFUSED");
+ });
+
+ it("splits what happened (message) from what to do (hint)", () => {
+ const summary = summarizeKnownError(
+ named("GatewayAuthenticationError", "AI Gateway authentication failed: Invalid API key."),
+ );
+ expect(summary?.message).toBe("AI Gateway rejected the provided API key.");
+ expect(summary?.hint).toContain("AI_GATEWAY_API_KEY");
+ expect(summary?.message).not.toContain("AI_GATEWAY_API_KEY");
+ });
+
+ it("passes structured hints authored at the throw site through", () => {
+ const summary = summarizeKnownError(
+ named("DockerUnavailableError", "the `docker` CLI was not found.", {
+ hint: "Install and start Docker Desktop.",
+ }),
+ );
+ expect(summary?.message).toBe("the `docker` CLI was not found.");
+ expect(summary?.hint).toBe("Install and start Docker Desktop.");
+ });
+
+ it("passes eve-authored sandbox messages through unchanged", () => {
+ const summary = summarizeKnownError(
+ named("MicrosandboxDiagnosticError", "pulling template [T001]: registry unreachable."),
+ );
+ expect(summary?.message).toBe("pulling template [T001]: registry unreachable.");
+ });
+
+ it("matches plain-object throwables that crossed a workflow step boundary", () => {
+ const summary = summarizeKnownError({
+ name: "DataDirVersionError",
+ message: "created by a newer version",
+ });
+ expect(summary?.id).toBe("workflow-store-version-mismatch");
+ });
+
+ it("requires exact message equality, never containment", () => {
+ expect(summarizeKnownError(new Error("upstream fetch failed for user 42"))).toBeNull();
+ expect(summarizeKnownError(new Error("network configuration invalid"))).toBeNull();
+ });
+
+ it("returns null for unrecognized errors and non-error throwables", () => {
+ expect(summarizeKnownError(new Error("something else went wrong"))).toBeNull();
+ expect(summarizeKnownError("string throw")).toBeNull();
+ expect(summarizeKnownError(null)).toBeNull();
+ expect(summarizeKnownError(undefined)).toBeNull();
+ });
+});
+
+describe("summary tags", () => {
+ it("carries the rule's recovery judgment so classifiers need no second registry", () => {
+ expect(
+ summarizeKnownError(named("GatewayModelNotFoundError", "model not found"))?.tags,
+ ).toContain("config");
+ expect(summarizeKnownError(named("GatewayRateLimitError", "rate limited"))?.tags).toContain(
+ "transient",
+ );
+ expect(summarizeKnownError(new TypeError("fetch failed"))?.tags).toContain("transient");
+ });
+});
+
+describe("rule engine", () => {
+ it("evaluates rules in order, first match wins, on any chain link", () => {
+ const signals = extractErrorSignals(
+ new Error("outer", { cause: Object.assign(new Error("inner"), { code: "X" }) }),
+ );
+ const summary = evaluateSemanticErrorRules(
+ [
+ { id: "second", name: "b", tags: ["system"], when: codeIs("X"), message: "late" },
+ { id: "first", name: "a", tags: ["system"], when: codeIs("X"), message: "never wins" },
+ ],
+ signals,
+ );
+ expect(summary).toEqual({ id: "second", name: "b", tags: ["system"], message: "late" });
+ });
+
+ it("allOf requires all predicates on the same link", () => {
+ const signals = extractErrorSignals(
+ // `name` matches the outer link, `message` only the inner one — no
+ // single link satisfies both.
+ named("Split", "outer", { cause: new Error("target") }),
+ );
+ const rule = {
+ id: "x",
+ name: "x",
+ tags: ["system"] as const,
+ when: allOf(nameIs("Split"), messageIs("target")),
+ message: "m",
+ };
+ expect(evaluateSemanticErrorRules([rule], signals)).toBeNull();
+ });
+
+ it("anyOf matches when either predicate holds", () => {
+ const predicate = anyOf(nameIs("A"), codeIs("B"));
+ expect(predicate({ message: "", name: "A" })).toBe(true);
+ expect(predicate({ message: "", code: "B" })).toBe(true);
+ expect(predicate({ message: "" })).toBe(false);
+ });
+});
diff --git a/packages/eve/src/harness/semantic-errors/signals.ts b/packages/eve/src/harness/semantic-errors/signals.ts
new file mode 100644
index 000000000..ad56f32ea
--- /dev/null
+++ b/packages/eve/src/harness/semantic-errors/signals.ts
@@ -0,0 +1,58 @@
+import { walkCauseChain } from "#shared/errors.js";
+import { isObject } from "#shared/guards.js";
+
+/**
+ * The structural facts extracted from one throwable on a cause chain.
+ * Rules match on these fields only — never on live objects — so the
+ * same rule works for real Errors and for plain-object shapes that
+ * crossed a workflow step boundary (structured clone strips prototypes
+ * but keeps own fields).
+ */
+export interface ErrorLink {
+ readonly name?: string;
+ readonly message: string;
+ /** Node/undici style error code (`ECONNREFUSED`, `EADDRINUSE`, …). */
+ readonly code?: string;
+ readonly statusCode?: number;
+ /** Gateway error body discriminator (`rate_limit_exceeded`, …). */
+ readonly type?: string;
+ /**
+ * Structured remediation authored at the throw site (eve's own error
+ * classes carry it as an own property, so it survives structured
+ * clone). Pass-through rules surface it as the summary hint.
+ */
+ readonly hint?: string;
+}
+
+/** The full cause chain of a throwable, outermost first. */
+export interface ErrorSignals {
+ readonly chain: readonly ErrorLink[];
+}
+
+/** Projects a throwable into the flat signals the rule engine matches on. */
+export function extractErrorSignals(error: unknown): ErrorSignals {
+ const chain: ErrorLink[] = [];
+ for (const candidate of walkCauseChain(error)) {
+ if (!isObject(candidate)) continue;
+ const link: { -readonly [Key in keyof ErrorLink]: ErrorLink[Key] } = {
+ message: typeof candidate.message === "string" ? candidate.message : "",
+ };
+ if (typeof candidate.name === "string" && candidate.name.length > 0) {
+ link.name = candidate.name;
+ }
+ if (typeof candidate.code === "string" && candidate.code.length > 0) {
+ link.code = candidate.code;
+ }
+ if (typeof candidate.statusCode === "number") {
+ link.statusCode = candidate.statusCode;
+ }
+ if (typeof candidate.type === "string" && candidate.type.length > 0) {
+ link.type = candidate.type;
+ }
+ if (typeof candidate.hint === "string" && candidate.hint.length > 0) {
+ link.hint = candidate.hint;
+ }
+ chain.push(link);
+ }
+ return { chain };
+}
diff --git a/packages/eve/src/harness/tool-loop-stream-retry.integration.test.ts b/packages/eve/src/harness/tool-loop-stream-retry.integration.test.ts
index 085d451ed..e93aa74a8 100644
--- a/packages/eve/src/harness/tool-loop-stream-retry.integration.test.ts
+++ b/packages/eve/src/harness/tool-loop-stream-retry.integration.test.ts
@@ -159,7 +159,16 @@ describe("tool loop streamed provider retries", () => {
});
expect(doStream).toHaveBeenCalledTimes(3);
- expect(result.next).toMatchObject({ done: true, isError: true, output: "Overloaded" });
+ // The exhausted failure reports the catalog's curated summary for the
+ // overloaded shape rather than the provider's raw "Overloaded", with
+ // the remediation hint riding along in the parent-facing output.
+ expect(result.next).toMatchObject({
+ done: true,
+ isError: true,
+ output:
+ "The model provider is overloaded or timing out upstream of AI Gateway. " +
+ "This is transient — retry shortly, or switch models with `/model` in `eve dev`.",
+ });
expect(events.filter((event) => event.type === "step.failed")).toHaveLength(1);
expect(events.filter((event) => event.type === "turn.failed")).toHaveLength(1);
expect(events.filter((event) => event.type === "session.failed")).toHaveLength(1);
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index dcb98481a..1d3381ca4 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -127,10 +127,10 @@ import {
extractModelCallErrorDetails,
extractUnsupportedProviderToolTypes,
isNoOutputGeneratedError,
- type ModelCallConfigErrorSummary,
- summarizeKnownModelCallConfigError,
- summarizeKnownModelCallRequestError,
+ type UpstreamRejectionSummary,
+ extractUpstreamRejectionMessage,
} from "#harness/model-call-error.js";
+import { summarizeKnownError, type SemanticErrorSummary } from "#harness/semantic-errors/index.js";
import { throwIfTurnAborted } from "#harness/turn-cancellation.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
import {
@@ -895,7 +895,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
// the fix, and the terminal-failure path logs the one-line summary
// and emits the structured step.failed. Unrecognized errors keep
// the full dump so they stay loud.
- if (summarizeKnownModelCallConfigError(event.error) !== null) return;
+ if (summarizeKnownError(event.error)?.tags.includes("config") === true) return;
logError(log, "tool-loop stream error", event.error);
},
onStepFinish: hooks.onStepFinish,
@@ -1128,42 +1128,49 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
const classification = classifyModelCallError(finalError);
const errorId = createErrorId();
- const configSummary =
- classification === "terminal" ? summarizeKnownModelCallConfigError(finalError) : null;
- const requestSummary =
- configSummary === null ? summarizeKnownModelCallRequestError(finalError) : null;
+ const catalogSummary = summarizeKnownError(finalError);
+ const upstreamRejection =
+ catalogSummary === null ? extractUpstreamRejectionMessage(finalError) : null;
const errorMessage =
- configSummary?.message ?? requestSummary?.message ?? toErrorMessage(finalError);
+ catalogSummary?.message ?? upstreamRejection?.message ?? toErrorMessage(finalError);
+ // Task failures surface as the parent agent's tool-result text, so
+ // the remediation rides along in prose — the parent can act on it
+ // or relay it. Event payloads keep hint structured in details.
+ const taskFailureOutput =
+ catalogSummary?.hint === undefined
+ ? errorMessage
+ : `${errorMessage} ${catalogSummary.hint}`;
const modelCallDetails = extractModelCallErrorDetails(finalError);
const details = buildModelCallFailureDetails({
- configSummary,
+ catalogSummary,
error: finalError,
errorId,
modelCallDetails,
- requestSummary,
+ upstreamRejection,
});
const modelCallLogFields = buildModelCallFailureLogFields({
error: finalError,
errorId,
modelCallDetails,
- requestSummary,
+ recognized: catalogSummary !== null || upstreamRejection !== null,
sessionId: session.sessionId,
turnId: emissionState.turnId,
});
if (classification === "terminal") {
- if (configSummary !== null) {
+ if (catalogSummary !== null) {
// Recognized configuration failure: log a concise single line
// and skip the structured SDK dump so the user sees an
// actionable hint instead of a wall of inspector output.
- log.error(`${configSummary.name}: ${configSummary.message}`, {
+ log.error(`${catalogSummary.name}: ${catalogSummary.message}`, {
errorId,
+ hint: catalogSummary.hint,
sessionId: session.sessionId,
turnId: emissionState.turnId,
});
} else {
log.error(
- requestSummary?.message ?? "model call failed terminally",
+ upstreamRejection?.message ?? "model call failed terminally",
modelCallLogFields,
);
}
@@ -1180,7 +1187,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
return {
next:
config.mode === "task"
- ? { done: true, isError: true, output: errorMessage }
+ ? { done: true, isError: true, output: taskFailureOutput }
: { done: true, output: "" },
session,
};
@@ -1196,7 +1203,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
// that did not already consume the in-process transient budget or
// the dedicated empty-response reissue.
log.warn(
- requestSummary?.message ??
+ upstreamRejection?.message ??
"model call failed recoverably in task mode — rethrowing for durable step retry",
modelCallLogFields,
);
@@ -1208,7 +1215,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
// here only after their bounded in-process retries are exhausted;
// empty responses already received their specialized reissue.
log.error(
- requestSummary?.message ?? "model call failed; failing the task run",
+ upstreamRejection?.message ?? "model call failed; failing the task run",
modelCallLogFields,
);
await emitFailedStep(emit, emissionState, {
@@ -1218,13 +1225,13 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
sessionId: session.sessionId,
});
return {
- next: { done: true, isError: true, output: errorMessage },
+ next: { done: true, isError: true, output: taskFailureOutput },
session,
};
}
log.error(
- requestSummary?.message ?? "model call failed — parking session for retry by the user",
+ upstreamRejection?.message ?? "model call failed — parking session for retry by the user",
modelCallLogFields,
);
emissionState = await emitRecoverableFailedTurn(emit, emissionState, {
@@ -1341,10 +1348,11 @@ function readGatewayMetadata(
* Projects a model-call failure into the `step.failed` / `turn.failed`
* `details` payload. Three mutually exclusive branches:
*
- * 1. Config summary (known terminal: missing key, gateway auth) → friendly
- * `name` + `message`, no SDK inspector dump.
- * 2. Request summary (ambiguous gateway 4xx that we recover from) → raw
- * error `message`, friendly `name`, no inspector dump.
+ * 1. Catalog match → the rule's curated `name`/`message`/`hint` plus its
+ * registered `semanticErrorId`, no SDK inspector dump.
+ * 2. Upstream rejection → raw error `message` with the extracted upstream
+ * identity, no inspector dump. No `semanticErrorId`: the message is
+ * arbitrary provider prose, not a registered failure shape.
* 3. Fallback → full {@link formatError} projection (cause chain via
* `util.inspect`) so unrecognized failures still carry the upstream
* stack to log aggregators.
@@ -1354,28 +1362,31 @@ function readGatewayMetadata(
* `responseBodySnippet`, ...) always show up next to the message.
*/
function buildModelCallFailureDetails(input: {
- readonly configSummary: ModelCallConfigErrorSummary | null;
+ readonly catalogSummary: SemanticErrorSummary | null;
readonly error: unknown;
readonly errorId: string;
readonly modelCallDetails: JsonObject;
- readonly requestSummary: ModelCallConfigErrorSummary | null;
+ readonly upstreamRejection: UpstreamRejectionSummary | null;
}): JsonObject {
- const { configSummary, error, errorId, modelCallDetails, requestSummary } = input;
+ const { catalogSummary, error, errorId, modelCallDetails, upstreamRejection } = input;
- if (configSummary !== null) {
- return {
+ if (catalogSummary !== null) {
+ const details: Record<string, JsonValue> = {
errorId,
- message: configSummary.message,
- name: configSummary.name,
+ message: catalogSummary.message,
+ name: catalogSummary.name,
+ semanticErrorId: catalogSummary.id,
...modelCallDetails,
};
+ if (catalogSummary.hint !== undefined) details.hint = catalogSummary.hint;
+ return details;
}
- if (requestSummary !== null) {
+ if (upstreamRejection !== null) {
return {
errorId,
message: toErrorMessage(error),
- name: requestSummary.name,
+ name: upstreamRejection.name,
...modelCallDetails,
};
}
@@ -1384,18 +1395,19 @@ function buildModelCallFailureDetails(input: {
}
/**
- * Builds the structured log fields for a model-call failure. When we
- * recognized the failure as an ambiguous gateway request rejection, attach
- * the compact `details` payload and *omit* the raw `error` so the logger's
- * `util.inspect` of the cause chain (which would render `[object Object]`
- * for upstream `APICallError` shapes) is bypassed. Otherwise fall back to
- * the raw error so unrecognized failures keep their full stack in logs.
+ * Builds the structured log fields for a model-call failure. When the
+ * failure was recognized (catalog match or extracted upstream rejection),
+ * attach the compact `details` payload and *omit* the raw `error` so the
+ * logger's `util.inspect` of the cause chain (which would render
+ * `[object Object]` for upstream `APICallError` shapes) is bypassed.
+ * Otherwise fall back to the raw error so unrecognized failures keep
+ * their full stack in logs.
*/
function buildModelCallFailureLogFields(input: {
readonly error: unknown;
readonly errorId: string;
readonly modelCallDetails: JsonObject;
- readonly requestSummary: ModelCallConfigErrorSummary | null;
+ readonly recognized: boolean;
readonly sessionId: string;
readonly turnId: string;
}): Record<string, unknown> {
@@ -1404,7 +1416,7 @@ function buildModelCallFailureLogFields(input: {
sessionId: input.sessionId,
turnId: input.turnId,
};
- if (input.requestSummary !== null) {
+ if (input.recognized) {
return { ...base, details: input.modelCallDetails };
}
return { ...base, error: input.error };
diff --git a/packages/eve/src/internal/logging.test.ts b/packages/eve/src/internal/logging.test.ts
index 18b7fba08..8b1871580 100644
--- a/packages/eve/src/internal/logging.test.ts
+++ b/packages/eve/src/internal/logging.test.ts
@@ -1,6 +1,13 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { createErrorId, createLogger, formatError, logError } from "#internal/logging.js";
+import {
+ createErrorId,
+ createLogger,
+ formatError,
+ logError,
+ setLogRecordSubscriber,
+ type LogRecord,
+} from "#internal/logging.js";
// ---------------------------------------------------------------------------
// createErrorId
@@ -103,6 +110,46 @@ describe("createLogger", () => {
expect(errorSpy).toHaveBeenCalledTimes(1);
});
+ it("delivers structured records to the registered subscriber instead of the console", () => {
+ const records: LogRecord[] = [];
+ setLogRecordSubscriber((record) => records.push(record));
+ try {
+ const logger = createLogger("harness.tool-loop");
+ const cause = Object.assign(new Error("upstream"), { statusCode: 429 });
+ logger.error("tool execution failed", { toolName: "always_fail", error: cause });
+
+ expect(records).toHaveLength(1);
+ expect(records[0]).toMatchObject({
+ level: "error",
+ namespace: "harness.tool-loop",
+ message: "tool execution failed",
+ fields: {
+ toolName: "always_fail",
+ error: { message: expect.stringContaining("upstream") as string },
+ },
+ });
+ expect(errorSpy).not.toHaveBeenCalled();
+ } finally {
+ setLogRecordSubscriber(undefined);
+ }
+
+ const logger = createLogger("harness.tool-loop");
+ logger.error("after unsubscribe");
+ expect(errorSpy).toHaveBeenCalledWith("[eve:harness.tool-loop] after unsubscribe");
+ });
+
+ it("falls back to the console when the subscriber throws", () => {
+ setLogRecordSubscriber(() => {
+ throw new Error("subscriber broke");
+ });
+ try {
+ createLogger("cli").error("still visible");
+ expect(errorSpy).toHaveBeenCalledWith("[eve:cli] still visible");
+ } finally {
+ setLogRecordSubscriber(undefined);
+ }
+ });
+
it("renders Error fields through formatError so cause chain flows through", () => {
const logger = createLogger("slack.route");
const cause = Object.assign(new Error("upstream"), { statusCode: 429 });
diff --git a/packages/eve/src/internal/logging.ts b/packages/eve/src/internal/logging.ts
index 282ae2939..bda9fa52e 100644
--- a/packages/eve/src/internal/logging.ts
+++ b/packages/eve/src/internal/logging.ts
@@ -21,7 +21,7 @@ const INSPECT_DEPTH = 10;
* Exposed so the logger API is composable with future sinks that want
* to filter or route by severity.
*/
-type LogLevel = "debug" | "info" | "warn" | "error";
+export type LogLevel = "debug" | "info" | "warn" | "error";
/** Numeric severity per level, gated against {@link resolveThreshold}. */
const LEVEL_SEVERITY: Record<LogLevel, number> = {
@@ -263,10 +263,56 @@ export function isLogLevelEnabled(level: LogLevel): boolean {
return LEVEL_SEVERITY[level] >= resolveThreshold();
}
+/**
+ * One structured log record, as delivered to the process-wide subscriber
+ * registered via {@link setLogRecordSubscriber}. `fields` carries the
+ * {@link renderFields} projection — Errors already replaced by their
+ * `formatError` shape — so subscribers receive JSON, never live objects.
+ */
+export interface LogRecord {
+ readonly level: LogLevel;
+ readonly namespace: string;
+ readonly message: string;
+ readonly fields?: JsonObject;
+}
+
+let logRecordSubscriber: ((record: LogRecord) => void) | undefined;
+
+/**
+ * Registers the process-wide structured log subscriber, replacing any
+ * previous one; pass `undefined` to restore plain console output.
+ *
+ * A registered subscriber takes ownership of rendering: records it
+ * handles skip the console entirely, so a host that both displays and
+ * persists logs (the dev TUI, which would otherwise scrape its own
+ * console output back off stderr) sees each record exactly once, still
+ * structured. If the subscriber throws, the record falls through to the
+ * console so a broken subscriber can never swallow logs. Single slot by
+ * design — one interactive host per process.
+ */
+export function setLogRecordSubscriber(
+ subscriber: ((record: LogRecord) => void) | undefined,
+): void {
+ logRecordSubscriber = subscriber;
+}
+
function write(level: LogLevel, namespace: string, message: string, fields?: LogFields): void {
if (LEVEL_SEVERITY[level] < resolveThreshold()) {
return;
}
+ const subscriber = logRecordSubscriber;
+ if (subscriber !== undefined) {
+ try {
+ subscriber(
+ fields === undefined
+ ? { level, namespace, message }
+ : { level, namespace, message, fields: renderFields(fields) },
+ );
+ return;
+ } catch {
+ // Fall through to the console path below.
+ }
+ }
// `debug` routes through `console.log` because most runtimes
// default-silence `console.debug` and the aggregators we target
// treat the stderr path (info/warn/error) as canonical. Look up
@@ -337,7 +383,13 @@ function isFormattedError(
return isObject(value) && typeof value.errorId === "string" && typeof value.message === "string";
}
-function inspectError(error: unknown): string {
+/**
+ * Renders a throwable's full cause chain via `util.inspect`, bounded to
+ * the logger's inline-detail budget. Exported for callers that route a
+ * raw error into a diagnostic sink outside a log record (the dev TUI's
+ * client-side stream-error capture).
+ */
+export function inspectError(error: unknown): string {
return truncate(
inspect(error, {
breakLength: Number.POSITIVE_INFINITY,
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts
index c47451987..3d052ce1c 100644
--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts
+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts
@@ -88,6 +88,7 @@ export function buildAgentInfoResponseFromManifest(
contextWindowTokens: manifest.config.model.contextWindowTokens,
id: manifest.config.model.id,
providerOptions: manifest.config.model.providerOptions,
+ reasoning: manifest.config.reasoning,
source: manifest.config.model.source ? toSource(manifest.config.model.source) : undefined,
routing: manifest.config.model.routing,
endpoint: resolveModelEndpointStatus(
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
index 5a4218a33..86422057a 100644
--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
@@ -24,7 +24,7 @@ import type {
import { serializeInputSchema, serializeOutputSchema } from "#shared/tool-schema.js";
import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";
import { WORKFLOW_TOOL_NAME } from "#shared/workflow-sandbox.js";
-import type { ModelRouting } from "#shared/agent-definition.js";
+import type { AgentReasoningDefinition, ModelRouting } from "#shared/agent-definition.js";
import type { ModelEndpointStatus } from "#shared/model-endpoint-status.js";
export interface AgentInfoSource {
@@ -172,6 +172,8 @@ export interface AgentInfoResponse {
readonly contextWindowTokens?: number;
readonly id: string;
readonly providerOptions?: unknown;
+ /** The agent's authored reasoning effort, forwarded to the model call. */
+ readonly reasoning?: AgentReasoningDefinition;
readonly source?: AgentInfoSource;
readonly routing?: ModelRouting;
readonly endpoint?: ModelEndpointStatus;
@@ -230,6 +232,7 @@ export function buildAgentInfoResponse(
contextWindowTokens: agent.config.model.contextWindowTokens,
id: agent.config.model.id,
providerOptions: agent.config.model.providerOptions,
+ reasoning: agent.config.reasoning,
source: agent.config.model.source ? toSource(agent.config.model.source) : undefined,
},
name: agent.config.name,
diff --git a/packages/eve/src/setup/boxes/model-capabilities.test.ts b/packages/eve/src/setup/boxes/model-capabilities.test.ts
new file mode 100644
index 000000000..2e18b9ecf
--- /dev/null
+++ b/packages/eve/src/setup/boxes/model-capabilities.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from "vitest";
+
+import { gatewayModelCapabilities } from "./model-capabilities.js";
+import type { GatewayCatalogModel } from "./select-model.js";
+
+function entry(overrides: Partial<GatewayCatalogModel> & { id: string }): GatewayCatalogModel {
+ return {
+ name: overrides.id,
+ type: "language",
+ owned_by: overrides.id.split("/")[0] ?? "",
+ ...overrides,
+ };
+}
+
+const CATALOG: GatewayCatalogModel[] = [
+ entry({
+ id: "openai/gpt-5.5",
+ tags: ["reasoning", "web-search"],
+ pricing: { service_tiers: { priority: {}, flex: {} } },
+ }),
+ entry({ id: "xai/grok-4.5", tags: ["reasoning", "web-search"] }),
+ entry({ id: "deepseek/deepseek-v4-pro", tags: ["reasoning"] }),
+ entry({ id: "xai/grok-4.20-non-reasoning", tags: ["web-search"], pricing: {} }),
+];
+
+describe("gatewayModelCapabilities", () => {
+ it("reads reasoning from the catalog tag and Fast mode from the priority tier", () => {
+ expect(gatewayModelCapabilities(CATALOG, "openai/gpt-5.5")).toEqual({
+ reasoning: true,
+ reasoningLevels: ["none", "minimal", "low", "medium", "high", "xhigh"],
+ fastMode: true,
+ });
+ expect(gatewayModelCapabilities(CATALOG, "xai/grok-4.20-non-reasoning")).toEqual({
+ reasoning: false,
+ reasoningLevels: [],
+ fastMode: false,
+ });
+ });
+
+ it("narrows reasoning levels per provider and falls back to the common core", () => {
+ expect(gatewayModelCapabilities(CATALOG, "xai/grok-4.5")?.reasoningLevels).toEqual([
+ "low",
+ "high",
+ ]);
+ expect(gatewayModelCapabilities(CATALOG, "deepseek/deepseek-v4-pro")?.reasoningLevels).toEqual([
+ "none",
+ "low",
+ "medium",
+ "high",
+ ]);
+ });
+
+ it("returns undefined without a catalog, a model id, or a catalog entry", () => {
+ expect(gatewayModelCapabilities(undefined, "openai/gpt-5.5")).toBeUndefined();
+ expect(gatewayModelCapabilities(CATALOG, null)).toBeUndefined();
+ expect(gatewayModelCapabilities(CATALOG, "meta/llama-3.3-70b")).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/setup/boxes/model-capabilities.ts b/packages/eve/src/setup/boxes/model-capabilities.ts
new file mode 100644
index 000000000..79706bffa
--- /dev/null
+++ b/packages/eve/src/setup/boxes/model-capabilities.ts
@@ -0,0 +1,66 @@
+import type { AgentReasoningDefinition } from "#shared/agent-definition.js";
+
+import type { GatewayCatalogModel } from "./select-model.js";
+
+/** A concrete reasoning effort level — every choice except the provider default. */
+export type ReasoningLevel = Exclude<AgentReasoningDefinition, "provider-default">;
+
+/**
+ * What the AI Gateway catalog says a model supports, resolved before the
+ * `/model` menu paints so unsupported controls never present as available.
+ */
+export interface GatewayModelCapabilities {
+ /** Whether the model advertises adjustable reasoning (the `reasoning` catalog tag). */
+ readonly reasoning: boolean;
+ /** Effort levels worth offering for the model; empty when reasoning is unsupported. */
+ readonly reasoningLevels: readonly ReasoningLevel[];
+ /** Whether AI Gateway prices a `priority` service tier (Fast mode) for the model. */
+ readonly fastMode: boolean;
+}
+
+/** Every effort level eve can author, offered when capabilities are unknown. */
+export const ALL_REASONING_LEVELS: readonly ReasoningLevel[] = [
+ "none",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+];
+
+// The catalog carries no per-model level list, so levels are a best-effort
+// read of what each provider's API accepts today; unknown reasoning-capable
+// providers get the common core every provider maps.
+const REASONING_LEVELS_BY_PROVIDER: Record<string, readonly ReasoningLevel[]> = {
+ anthropic: ALL_REASONING_LEVELS,
+ openai: ALL_REASONING_LEVELS,
+ google: ["none", "low", "medium", "high"],
+ xai: ["low", "high"],
+};
+
+const DEFAULT_REASONING_LEVELS: readonly ReasoningLevel[] = ["none", "low", "medium", "high"];
+
+/**
+ * Capabilities for `modelId` from a fetched catalog, or undefined when the
+ * catalog is unavailable or does not list the model — the caller then treats
+ * every control as potentially available.
+ */
+export function gatewayModelCapabilities(
+ catalog: readonly GatewayCatalogModel[] | undefined,
+ modelId: string | null,
+): GatewayModelCapabilities | undefined {
+ if (catalog === undefined || modelId === null) return undefined;
+ const model = catalog.find((entry) => entry.id === modelId);
+ if (model === undefined) return undefined;
+
+ const reasoning = (model.tags ?? []).includes("reasoning");
+ const provider = modelId.split("/")[0] ?? "";
+ const tiers = model.pricing?.service_tiers;
+ return {
+ reasoning,
+ reasoningLevels: reasoning
+ ? (REASONING_LEVELS_BY_PROVIDER[provider] ?? DEFAULT_REASONING_LEVELS)
+ : [],
+ fastMode: tiers !== undefined && Object.hasOwn(tiers, "priority"),
+ };
+}
diff --git a/packages/eve/src/setup/boxes/resolve-provisioning.ts b/packages/eve/src/setup/boxes/resolve-provisioning.ts
index c4aea58bd..6704893dd 100644
--- a/packages/eve/src/setup/boxes/resolve-provisioning.ts
+++ b/packages/eve/src/setup/boxes/resolve-provisioning.ts
@@ -350,8 +350,11 @@ export function resolveProvisioning(
modelWiring: "gateway",
};
}
+ // Creating would name the project after the agent, so linking suggests
+ // the existing project already carrying that name.
const pickedProject = await deps.pickProject(prompter, parent(), team, {
allowCreateWhenEmpty: options.projectSelection !== "existing-only",
+ suggestedName: agentName,
signal,
});
return {
diff --git a/packages/eve/src/setup/boxes/select-model.test.ts b/packages/eve/src/setup/boxes/select-model.test.ts
index ec89876b4..a19127ed6 100644
--- a/packages/eve/src/setup/boxes/select-model.test.ts
+++ b/packages/eve/src/setup/boxes/select-model.test.ts
@@ -8,7 +8,13 @@ import type { Prompter, PrompterValue, SingleSelectOptions } from "../prompter.j
import { createDefaultSetupState } from "../state.js";
import type { OutputSink } from "../step.js";
import { runHeadless, runInteractive } from "../runner.js";
-import { selectModel, type GatewayCatalogModel, type SelectModelDeps } from "./select-model.js";
+import {
+ modelOptionsFromCatalog,
+ parseGatewayCatalog,
+ selectModel,
+ type GatewayCatalogModel,
+ type SelectModelDeps,
+} from "./select-model.js";
const silentSink: OutputSink = { write: () => {} };
@@ -18,6 +24,7 @@ const CATALOG: GatewayCatalogModel[] = [
name: "GLM 4.6",
type: "language",
owned_by: "zai",
+ released: 300,
tags: ["web-search"],
},
{
@@ -25,6 +32,7 @@ const CATALOG: GatewayCatalogModel[] = [
name: "GPT-5 mini",
type: "language",
owned_by: "openai",
+ released: 200,
tags: ["web-search"],
},
{
@@ -32,6 +40,7 @@ const CATALOG: GatewayCatalogModel[] = [
name: "Claude Sonnet 5",
type: "language",
owned_by: "anthropic",
+ released: 100,
tags: ["web-search"],
},
// Filtered out: not a language model.
@@ -74,6 +83,29 @@ function createSelectPrompter(handler: SingleHandler): {
return { prompter: createFakePrompter({ single }).prompter, single };
}
+describe("modelOptionsFromCatalog", () => {
+ it("filters, sorts newest-first behind the featured lead, and marks the shortlist", () => {
+ const options = modelOptionsFromCatalog(CATALOG);
+
+ expect(options.map((option) => option.value)).toEqual([
+ "anthropic/claude-sonnet-5",
+ "zai/glm-4.6",
+ "openai/gpt-5-mini",
+ ]);
+ expect(options.filter((option) => option.featured).map((o) => o.value)).toEqual([
+ "anthropic/claude-sonnet-5",
+ ]);
+ });
+
+ it("falls back to the static shortlist without a catalog or matches", () => {
+ for (const catalog of [undefined, [] as GatewayCatalogModel[]]) {
+ const values = modelOptionsFromCatalog(catalog).map((option) => option.value);
+ expect(values).toContain(DEFAULT_AGENT_MODEL_ID);
+ expect(values).toContain("google/gemini-3.5");
+ }
+ });
+});
+
describe("selectModel box", () => {
it("short-circuits both runners on a preset model", async () => {
const deps = unexpectedFetch();
@@ -90,7 +122,7 @@ describe("selectModel box", () => {
expect(deps.fetchModels).not.toHaveBeenCalled();
});
- it("offers a searchable picker over the filtered, popularity-sorted catalog", async () => {
+ it("offers a searchable picker over the filtered, release-sorted catalog", async () => {
let captured: SingleSelectOptions<PrompterValue> | undefined;
const { prompter } = createSelectPrompter((opts) => {
captured = opts;
@@ -104,11 +136,11 @@ describe("selectModel box", () => {
if (result.kind !== "done") return;
expect(result.state.modelId).toBe("anthropic/claude-sonnet-5");
expect(captured?.search).toBe(true);
- // Language + web-search models only, anthropic/openai/google sorted first.
+ // The featured default remains first; the rest are newest release first.
expect(captured?.options.map((option) => option.value)).toEqual([
"anthropic/claude-sonnet-5",
- "openai/gpt-5-mini",
"zai/glm-4.6",
+ "openai/gpt-5-mini",
]);
// Cursor defaults to the top catalog entry when no default is configured.
expect(captured?.initialValue).toBe("anthropic/claude-sonnet-5");
@@ -128,6 +160,7 @@ describe("selectModel box", () => {
name: "Claude Opus 4.8",
type: "language",
owned_by: "anthropic",
+ released: 400,
tags: ["web-search"],
},
...CATALOG,
@@ -141,8 +174,8 @@ describe("selectModel box", () => {
expect(captured?.options.map((option) => option.value)).toEqual([
"anthropic/claude-sonnet-5",
"anthropic/claude-opus-4.8",
- "openai/gpt-5-mini",
"zai/glm-4.6",
+ "openai/gpt-5-mini",
]);
// Only the curated entries are featured: the picker's default view shows
// them alone, and scrolling or search surfaces the rest of the catalog.
@@ -153,6 +186,60 @@ describe("selectModel box", () => {
expect(captured?.initialValue).toBe(DEFAULT_AGENT_MODEL_ID);
});
+ it("sorts undated models after dated models with deterministic ties", async () => {
+ let captured: SingleSelectOptions<PrompterValue> | undefined;
+ const { prompter } = createSelectPrompter((opts) => {
+ captured = opts;
+ return "acme/newer";
+ });
+ const models: GatewayCatalogModel[] = [
+ {
+ id: "acme/undated",
+ name: "Undated",
+ type: "language",
+ owned_by: "acme",
+ tags: ["web-search"],
+ },
+ {
+ id: "acme/zeta",
+ name: "Same release Zeta",
+ type: "language",
+ owned_by: "acme",
+ released: 100,
+ tags: ["web-search"],
+ },
+ {
+ id: "acme/alpha",
+ name: "Same release Alpha",
+ type: "language",
+ owned_by: "acme",
+ released: 100,
+ tags: ["web-search"],
+ },
+ {
+ id: "acme/newer",
+ name: "Newer",
+ type: "language",
+ owned_by: "acme",
+ released: 200,
+ tags: ["web-search"],
+ },
+ ];
+
+ await runInteractive(
+ [selectModel({ asker: interactiveAsker(prompter), deps: catalogDeps(models) })],
+ createDefaultSetupState(),
+ silentSink,
+ );
+
+ expect(captured?.options.map((option) => option.value)).toEqual([
+ "acme/newer",
+ "acme/alpha",
+ "acme/zeta",
+ "acme/undated",
+ ]);
+ });
+
it("pre-selects the configured default model when present in the catalog", async () => {
let captured: SingleSelectOptions<PrompterValue> | undefined;
const { prompter } = createSelectPrompter((opts) => {
@@ -170,6 +257,47 @@ describe("selectModel box", () => {
expect(captured?.initialValue).toBe("openai/gpt-5-mini");
});
+ it("skips malformed catalog entries instead of rejecting the whole catalog", () => {
+ const models = parseGatewayCatalog({
+ data: [
+ CATALOG[0],
+ { id: "vendor/experimental", shape: "unrecognized" },
+ "not even an object",
+ CATALOG[1],
+ ],
+ });
+
+ expect(models.map((model) => model.id)).toEqual(["zai/glm-4.6", "openai/gpt-5-mini"]);
+ });
+
+ it("keeps a model when only its optional catalog metadata is malformed", () => {
+ expect(
+ parseGatewayCatalog({
+ data: [
+ {
+ id: "vendor/experimental",
+ name: "Experimental",
+ type: "language",
+ owned_by: "vendor",
+ released: "unannounced",
+ tags: null,
+ },
+ ],
+ }),
+ ).toEqual([
+ {
+ id: "vendor/experimental",
+ name: "Experimental",
+ type: "language",
+ owned_by: "vendor",
+ },
+ ]);
+ });
+
+ it("rejects a catalog payload without a data array", () => {
+ expect(() => parseGatewayCatalog({ models: [] })).toThrow("invalid model catalog");
+ });
+
it("falls back to the static shortlist when the catalog fetch fails", async () => {
let captured: SingleSelectOptions<PrompterValue> | undefined;
const { prompter } = createSelectPrompter((opts) => {
diff --git a/packages/eve/src/setup/boxes/select-model.ts b/packages/eve/src/setup/boxes/select-model.ts
index bbcccc800..e0ce99b71 100644
--- a/packages/eve/src/setup/boxes/select-model.ts
+++ b/packages/eve/src/setup/boxes/select-model.ts
@@ -1,3 +1,4 @@
+import { z } from "#compiled/zod/index.js";
import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";
import { select, type Asker, type SelectOption } from "../ask.js";
@@ -6,18 +7,33 @@ import type { SetupBox } from "../step.js";
const AI_GATEWAY_URL = "https://ai-gateway.vercel.sh/v1/models";
const FETCH_TIMEOUT_MS = 5000;
-const POPULAR_PROVIDERS: readonly string[] = ["anthropic", "openai", "google"];
const WEB_SEARCH_TAG = "web-search";
const MODEL_PROMPT_MESSAGE = "Which model should your agent use?";
+const gatewayCatalogModelSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ type: z.string(),
+ owned_by: z.string(),
+ /** Public release timestamp in Unix seconds. Missing values sort last. */
+ released: z.number().finite().optional().catch(undefined),
+ tags: z.array(z.string()).optional().catch(undefined),
+ /** Per-tier pricing; the `service_tiers` keys reveal Fast mode (priority) support. */
+ pricing: z
+ .object({ service_tiers: z.record(z.string(), z.unknown()).optional().catch(undefined) })
+ .optional()
+ .catch(undefined),
+});
+
+const gatewayCatalogSchema = z.object({ data: z.array(z.unknown()) }).transform(({ data }) =>
+ data.flatMap((entry) => {
+ const result = gatewayCatalogModelSchema.safeParse(entry);
+ return result.success ? [result.data] : [];
+ }),
+);
+
/** One model entry from the AI Gateway catalog response. */
-export interface GatewayCatalogModel {
- id: string;
- name: string;
- type: string;
- owned_by: string;
- tags?: readonly string[];
-}
+export type GatewayCatalogModel = z.infer<typeof gatewayCatalogModelSchema>;
function modelOption(
value: string,
@@ -46,14 +62,17 @@ const FALLBACK_MODELS: SelectOption<string>[] = [
modelOption("google/gemini-3.5", "Gemini 3.5", "Google", false),
];
+// Brand capitalizations first-letter uppercasing cannot produce.
+const PROVIDER_BRANDS: Record<string, string> = {
+ openai: "OpenAI",
+ xai: "xAI",
+ deepseek: "DeepSeek",
+ moonshotai: "Moonshot AI",
+};
+
function providerLabel(provider: string): string {
if (provider.length === 0) return "";
- return provider.charAt(0).toUpperCase() + provider.slice(1);
-}
-
-function providerPriority(provider: string): number {
- const index = POPULAR_PROVIDERS.indexOf(provider);
- return index === -1 ? POPULAR_PROVIDERS.length : index;
+ return PROVIDER_BRANDS[provider] ?? provider.charAt(0).toUpperCase() + provider.slice(1);
}
/** Fetches the raw AI Gateway catalog. The default for {@link SelectModelDeps}. */
@@ -65,13 +84,26 @@ export async function fetchGatewayCatalog(signal?: AbortSignal): Promise<Gateway
const requestSignal =
signal === undefined ? controller.signal : AbortSignal.any([signal, controller.signal]);
const res = await fetch(AI_GATEWAY_URL, { signal: requestSignal });
- const json = (await res.json()) as { data: GatewayCatalogModel[] };
- return json.data;
+ if (!res.ok) throw new Error(`AI Gateway model catalog request failed (${res.status}).`);
+ return parseGatewayCatalog(await res.json());
} finally {
clearTimeout(timeout);
}
}
+/**
+ * Validates a Gateway catalog response. A malformed payload throws (the
+ * picker then falls back to the static shortlist), but a malformed entry is
+ * skipped: one experimental entry shape must not take down the whole catalog.
+ */
+export function parseGatewayCatalog(input: unknown): GatewayCatalogModel[] {
+ const result = gatewayCatalogSchema.safeParse(input);
+ if (!result.success) {
+ throw new Error("AI Gateway returned an invalid model catalog.");
+ }
+ return result.data;
+}
+
/** Position in the curated shortlist, or its length for everything else. */
function featuredPriority(id: string): number {
const index = FEATURED_MODEL_IDS.indexOf(id);
@@ -79,49 +111,57 @@ function featuredPriority(id: string): number {
}
/**
- * Builds the picker options from the catalog (filtered to language models with
- * the `web-search` tag), with the curated shortlist first in its own order and
- * the rest sorted popular providers first. Catalog entries on the shortlist
- * are marked `featured`, so the picker opens on just them and scrolling or
- * filtering reaches the rest. Falls back to a static shortlist when the fetch
- * fails or yields nothing.
+ * Builds picker options from a fetched catalog (filtered to language models
+ * with the `web-search` tag), with the curated shortlist first in its own
+ * order and the rest sorted newest release first. Catalog entries on the
+ * shortlist are marked `featured`, so a searchable picker opens on just them
+ * and scrolling or filtering reaches the rest. Falls back to a static
+ * shortlist when the catalog is missing or yields nothing.
*/
+export function modelOptionsFromCatalog(
+ catalog: readonly GatewayCatalogModel[] | undefined,
+): SelectOption<string>[] {
+ if (catalog === undefined) return FALLBACK_MODELS;
+
+ const models = catalog
+ .filter((m) => m.type === "language" && (m.tags ?? []).includes(WEB_SEARCH_TAG))
+ .map((m) => {
+ const provider = m.id.split("/")[0] ?? "";
+ return {
+ value: m.id,
+ label: m.name,
+ hint: providerLabel(provider),
+ provider,
+ released: m.released,
+ };
+ })
+ .sort((a, b) => {
+ const featuredDiff = featuredPriority(a.value) - featuredPriority(b.value);
+ if (featuredDiff !== 0) return featuredDiff;
+ const releasedDiff =
+ (b.released ?? Number.NEGATIVE_INFINITY) - (a.released ?? Number.NEGATIVE_INFINITY);
+ if (releasedDiff !== 0) return releasedDiff;
+ const labelDiff = a.label.localeCompare(b.label);
+ if (labelDiff !== 0) return labelDiff;
+ return a.value.localeCompare(b.value);
+ });
+
+ if (models.length === 0) return FALLBACK_MODELS;
+ return models.map(({ value, label, hint }) => ({
+ id: value,
+ label,
+ value,
+ hint,
+ featured: FEATURED_MODEL_IDS.includes(value) || undefined,
+ }));
+}
+
async function buildModelOptions(
fetchModels: (signal?: AbortSignal) => Promise<GatewayCatalogModel[]>,
signal?: AbortSignal,
): Promise<SelectOption<string>[]> {
try {
- const data = await fetchModels(signal);
-
- const models = data
- .filter((m) => m.type === "language" && (m.tags ?? []).includes(WEB_SEARCH_TAG))
- .map((m) => {
- const provider = m.id.split("/")[0] ?? "";
- return {
- value: m.id,
- label: m.name,
- hint: providerLabel(provider),
- provider,
- };
- })
- .sort((a, b) => {
- const featuredDiff = featuredPriority(a.value) - featuredPriority(b.value);
- if (featuredDiff !== 0) return featuredDiff;
- const priorityDiff = providerPriority(a.provider) - providerPriority(b.provider);
- if (priorityDiff !== 0) return priorityDiff;
- const providerDiff = a.provider.localeCompare(b.provider);
- if (providerDiff !== 0) return providerDiff;
- return a.label.localeCompare(b.label);
- });
-
- if (models.length === 0) return FALLBACK_MODELS;
- return models.map(({ value, label, hint }) => ({
- id: value,
- label,
- value,
- hint,
- featured: FEATURED_MODEL_IDS.includes(value) || undefined,
- }));
+ return modelOptionsFromCatalog(await fetchModels(signal));
} catch {
signal?.throwIfAborted();
return FALLBACK_MODELS;
diff --git a/packages/eve/src/setup/cli/option-row.test.ts b/packages/eve/src/setup/cli/option-row.test.ts
index 458293b25..390e58975 100644
--- a/packages/eve/src/setup/cli/option-row.test.ts
+++ b/packages/eve/src/setup/cli/option-row.test.ts
@@ -81,14 +81,15 @@ describe("renderOptionRow", () => {
);
});
- test("hovering a row takes over the icon column, even when checked", () => {
+ test("hovering a checked row keeps its check inside the highlight", () => {
+ // The highlight says "active", not "press to activate": the check stays.
expect(
row({
label: "Web Chat",
isCursor: true,
state: { kind: "available", checked: true },
}),
- ).toBe("<inverse><blue> ▶ Web Chat </blue></inverse>");
+ ).toBe("<inverse><blue> ✓ Web Chat </blue></inverse>");
});
test("a completed row under the cursor reads as inert: a dim pointer and dim label", () => {
diff --git a/packages/eve/src/setup/cli/option-row.ts b/packages/eve/src/setup/cli/option-row.ts
index 7620ed5a1..6ab59313d 100644
--- a/packages/eve/src/setup/cli/option-row.ts
+++ b/packages/eve/src/setup/cli/option-row.ts
@@ -145,8 +145,10 @@ function optionRowPresentation(input: OptionRowInput): OptionRowPresentation {
switch (state.kind) {
case "available":
if (input.isCursor) {
+ // A checked row keeps its check under the cursor — the highlight says
+ // "active", not "press to activate".
return {
- glyph: glyphs.selectedPointer,
+ glyph: state.checked ? glyphs.success : glyphs.selectedPointer,
label: input.label,
};
}
diff --git a/packages/eve/src/setup/cli/prompt-ui.test.ts b/packages/eve/src/setup/cli/prompt-ui.test.ts
index 757ca3955..7c8d6d8f2 100644
--- a/packages/eve/src/setup/cli/prompt-ui.test.ts
+++ b/packages/eve/src/setup/cli/prompt-ui.test.ts
@@ -122,8 +122,9 @@ describe("renderSelectPrompt", () => {
state: "active",
});
+ // The description indents to the option label column.
expect(rendered).toContain(
- "<inverse><blue> ▶ No </blue></inverse>\n│ <dim>Set up locally and wire yourself</dim>",
+ "<inverse><blue> ▶ No </blue></inverse>\n│ <dim>Set up locally and wire yourself</dim>",
);
// The non-highlighted option keeps its description hidden.
expect(rendered).not.toContain("Fastest path to production");
diff --git a/packages/eve/src/setup/cli/prompt-ui.ts b/packages/eve/src/setup/cli/prompt-ui.ts
index 2553b5993..09c50edda 100644
--- a/packages/eve/src/setup/cli/prompt-ui.ts
+++ b/packages/eve/src/setup/cli/prompt-ui.ts
@@ -5,6 +5,7 @@ import { wrapTextWithPrefix } from "@clack/core";
import {
renderCursorRow,
renderOptionRow,
+ renderOptionRowContinuation,
resolveOptionRowState,
UNICODE_ROW_GLYPHS,
} from "./option-row.js";
@@ -75,6 +76,8 @@ export interface PromptOption<T extends PromptValue> {
* to the front. Meaningless without `search`.
*/
featured?: boolean;
+ /** Marks the currently-active value: renders a green check beside the row. */
+ checked?: boolean;
}
/** Vertical rail glyph used by the onboarding-style terminal UI. */
@@ -353,7 +356,7 @@ function descriptionLine<T extends PromptValue>(
colors: PromptColors,
): string {
return isCursor && option.description && !option.disabled
- ? `\n${rail} ${colors.dim(option.description)}`
+ ? `\n${rail} ${renderOptionRowContinuation(colors.dim(option.description))}`
: "";
}
diff --git a/packages/eve/src/setup/flows/link.test.ts b/packages/eve/src/setup/flows/link.test.ts
index b9ae1516c..24040b3d2 100644
--- a/packages/eve/src/setup/flows/link.test.ts
+++ b/packages/eve/src/setup/flows/link.test.ts
@@ -110,11 +110,12 @@ describe("runLinkFlow", () => {
"This directory is already linked to\nweather-app in Acme",
);
expect(deps.resolveProvisioning?.pickTeam).toHaveBeenCalled();
+ // Linking suggests the project a create would have named after the agent.
expect(deps.resolveProvisioning?.pickProject).toHaveBeenCalledWith(
expect.anything(),
APP_ROOT,
"acme",
- { allowCreateWhenEmpty: false },
+ { allowCreateWhenEmpty: false, suggestedName: "my-agent" },
);
expect(deps.resolveProvisioning?.pickNewProjectName).not.toHaveBeenCalled();
expect(deps.linkProject?.linkProject).toHaveBeenCalled();
diff --git a/packages/eve/src/setup/flows/model-source-change.ts b/packages/eve/src/setup/flows/model-source-change.ts
new file mode 100644
index 000000000..20e369390
--- /dev/null
+++ b/packages/eve/src/setup/flows/model-source-change.ts
@@ -0,0 +1,136 @@
+import { join } from "node:path";
+
+import { createCompiledRuntimeModelCatalogLoader } from "#compiler/model-catalog.js";
+import { discoverAgent } from "#discover/discover-agent.js";
+import { formatLanguageModelGatewayId } from "#internal/runtime-model.js";
+import type { AgentReasoningDefinition } from "#shared/agent-definition.js";
+import type {
+ AgentModelSetting,
+ AgentModelSettingsPatch,
+} from "#source-change/apply-agent-model-settings.js";
+import { createStaticSourceChange } from "#source-change/static-source-change.js";
+
+import pc from "picocolors";
+
+export type ApplyModelSettingsOutcome =
+ | {
+ kind: "changed";
+ changed: readonly AgentModelSetting[];
+ model?: string;
+ reasoning?: AgentReasoningDefinition | null;
+ fastMode?: boolean;
+ }
+ | { kind: "unchanged" }
+ | { kind: "rejected"; message: string };
+
+export function formatApplyModelSettingsOutcome(outcome: ApplyModelSettingsOutcome): string {
+ if (outcome.kind === "rejected") return outcome.message;
+ if (outcome.kind === "unchanged") return "Model settings are already up to date.";
+ if (
+ outcome.changed.length === 1 &&
+ outcome.changed[0] === "model" &&
+ outcome.model !== undefined
+ ) {
+ return `Model changed to ${pc.bold(outcome.model)}. Live on your next prompt.`;
+ }
+ const labels = outcome.changed.map((setting) => {
+ if (setting === "model") return `model ${outcome.model ?? "updated"}`;
+ if (setting === "reasoning") return `reasoning ${outcome.reasoning ?? "provider default"}`;
+ return `Fast mode ${outcome.fastMode ? "on" : "off"}`;
+ });
+ return `Model settings updated: ${labels.join(", ")}. Live on your next prompt.`;
+}
+
+/** The outcome of applying a model slug to the agent's authored source. */
+export type ApplyModelOutcome =
+ | { kind: "changed"; to: string }
+ | { kind: "unchanged"; model: string }
+ | { kind: "rejected"; message: string };
+
+/** The one-line transcript form of an apply outcome (`/model <slug>`'s reply). */
+export function formatApplyModelOutcome(outcome: ApplyModelOutcome): string {
+ switch (outcome.kind) {
+ case "changed":
+ return `Model changed to ${pc.bold(outcome.to)}. Live on your next prompt.`;
+ case "unchanged":
+ return `Model is already \`${outcome.model}\`.`;
+ case "rejected":
+ return outcome.message;
+ }
+}
+
+/** Applies one completed `/model` draft through a single atomic source write. */
+export async function changeAgentModelSettings(input: {
+ readonly appRoot: string;
+ readonly patch: AgentModelSettingsPatch;
+}): Promise<ApplyModelSettingsOutcome> {
+ const { appRoot, patch } = input;
+ if (patch.model.kind === "set") {
+ const rejection = await validateModelSlug(appRoot, patch.model.value);
+ if (rejection !== null) return { kind: "rejected", message: rejection };
+ }
+
+ const agentRoot = join(appRoot, "agent");
+ const { manifest } = await discoverAgent({ agentRoot, appRoot });
+ const result = await createStaticSourceChange(manifest).updateModelSettings(patch);
+ if (result.kind === "bail") {
+ return {
+ kind: "rejected",
+ message: `Couldn't edit ${result.at.logicalPath}: ${result.reason}. Change the model settings by hand.`,
+ };
+ }
+ if (result.changed.length === 0) return { kind: "unchanged" };
+
+ const outcome: Extract<ApplyModelSettingsOutcome, { kind: "changed" }> = {
+ kind: "changed",
+ changed: result.changed,
+ };
+ if (patch.model.kind === "set") outcome.model = patch.model.value;
+ if (patch.reasoning.kind !== "keep") {
+ outcome.reasoning = patch.reasoning.kind === "set" ? patch.reasoning.value : null;
+ }
+ if (patch.gatewayServiceTier.kind !== "keep") {
+ outcome.fastMode = patch.gatewayServiceTier.kind === "set";
+ }
+ return outcome;
+}
+
+/** Applies a validated `/model <slug>` change to authored source. */
+export async function changeAgentModel(input: {
+ readonly appRoot: string;
+ readonly slug: string;
+}): Promise<ApplyModelOutcome> {
+ const { appRoot, slug } = input;
+ const rejection = await validateModelSlug(appRoot, slug);
+ if (rejection !== null) return { kind: "rejected", message: rejection };
+
+ const agentRoot = join(appRoot, "agent");
+ const { manifest } = await discoverAgent({ agentRoot, appRoot });
+ const result = await createStaticSourceChange(manifest).updateModelName(slug);
+ if (result.kind === "bail") {
+ return {
+ kind: "rejected",
+ message: `Couldn't edit ${result.at.logicalPath}: ${result.reason}. Change \`model\` by hand.`,
+ };
+ }
+ return result.from === result.to
+ ? { kind: "unchanged", model: result.to }
+ : { kind: "changed", to: result.to };
+}
+
+async function validateModelSlug(appRoot: string, slug: string): Promise<string | null> {
+ if (!slug.includes("/")) {
+ return `\`${slug}\` isn't a provider/model id (e.g. anthropic/claude-sonnet-5).`;
+ }
+
+ const catalog = createCompiledRuntimeModelCatalogLoader(appRoot);
+ try {
+ const limits = await catalog.getModelLimits(formatLanguageModelGatewayId(slug));
+ if (limits === null) {
+ return `I couldn't confirm \`${slug}\` in the AI Gateway model catalog, so I didn't change agent.ts.`;
+ }
+ } catch {
+ return null;
+ }
+ return null;
+}
diff --git a/packages/eve/src/setup/flows/model.test.ts b/packages/eve/src/setup/flows/model.test.ts
index 82fc38de7..61fba624d 100644
--- a/packages/eve/src/setup/flows/model.test.ts
+++ b/packages/eve/src/setup/flows/model.test.ts
@@ -11,7 +11,12 @@ import type {
} from "#setup/prompter.js";
import { WizardCancelledError } from "#setup/step.js";
-import { MODEL_MENU_MESSAGE, runModelFlow, type ModelFlowDeps } from "./model.js";
+import {
+ MODEL_MENU_MESSAGE,
+ runModelFlow,
+ type ModelFlowDeps,
+ type ModelSettingsRequest,
+} from "./model.js";
const APP_ROOT = "/app/my-agent";
@@ -21,13 +26,24 @@ const CATALOG: GatewayCatalogModel[] = [
name: "Claude Sonnet 5",
type: "language",
owned_by: "anthropic",
- tags: ["web-search"],
+ tags: ["reasoning", "web-search"],
+ pricing: { service_tiers: { priority: {} } },
},
{
id: "openai/gpt-5.5",
name: "GPT-5.5",
type: "language",
owned_by: "openai",
+ tags: ["reasoning", "web-search"],
+ pricing: { service_tiers: { priority: {} } },
+ },
+ // Advertises neither the reasoning tag nor a priority tier, so capability
+ // lookups have a catalog-listed model with no adjustable controls.
+ {
+ id: "test/no-frills",
+ name: "No Frills",
+ type: "language",
+ owned_by: "test",
tags: ["web-search"],
},
];
@@ -37,13 +53,21 @@ function flowDeps(overrides: Partial<ModelFlowDeps> = {}): Partial<ModelFlowDeps
readCurrentModel: vi.fn(async () => ({
id: "anthropic/claude-sonnet-5",
routing: { kind: "gateway", target: "anthropic" } as const,
+ reasoning: null,
+ serviceTier: { kind: "standard" } as const,
editable: true,
+ settingsEditable: true,
})),
- applyModel: vi.fn(
- async ({ slug }: { appRoot: string; slug: string }) =>
- ({ kind: "changed", to: slug }) as const,
+ applySettings: vi.fn(
+ async ({ patch }: Parameters<ModelFlowDeps["applySettings"]>[0]) =>
+ ({
+ kind: "changed",
+ changed: ["model"],
+ model: patch.model.kind === "set" ? patch.model.value : undefined,
+ }) as const,
),
selectModel: { fetchModels: async () => CATALOG },
+ pickModelSettings: vi.fn(async () => undefined),
detectProviderStatus: vi.fn(
async () => ({ kind: "gateway-project", projectName: "my-agent" }) as const,
),
@@ -62,34 +86,28 @@ interface MenuPaint {
}
/**
- * Answers the menu prompt from a script (throwing the cancel error for
- * "esc"), records every painted menu, and answers each catalog picker
- * prompt from the `picker` queue ("esc" cancels that picker).
+ * Answers the root menu from a script (throwing the cancel error for "esc")
+ * and records every painted menu. The composite model screen is not a prompter
+ * question — tests script it through the `pickModelSettings` dep instead.
*/
-function scriptedPrompter(input: { menu: (PrompterValue | "esc")[]; picker?: string[] }) {
+function scriptedPrompter(input: { menu: (PrompterValue | "esc")[] }) {
const menuPaints: MenuPaint[] = [];
const menuScript = [...input.menu];
- const pickerScript = [...(input.picker ?? [])];
const fake = createFakePrompter({
single: (opts: SingleSelectOptions<PrompterValue>) => {
- if (opts.message === MODEL_MENU_MESSAGE) {
- menuPaints.push({
- options: opts.options,
- notices: opts.notices ?? [],
- hintLayout: opts.hintLayout,
- initialValue: opts.initialValue,
- });
- const next = menuScript.shift();
- if (next === undefined) throw new Error("Menu painted more times than scripted.");
- if (next === "esc") throw new WizardCancelledError();
- return next;
+ if (opts.message !== MODEL_MENU_MESSAGE) {
+ throw new Error(`Unexpected prompt: "${opts.message}"`);
}
- const answer = pickerScript.shift();
- if (answer === undefined) {
- throw new Error(`Unexpected picker prompt: "${opts.message}"`);
- }
- if (answer === "esc") throw new WizardCancelledError();
- return answer;
+ menuPaints.push({
+ options: opts.options,
+ notices: opts.notices ?? [],
+ hintLayout: opts.hintLayout,
+ initialValue: opts.initialValue,
+ });
+ const next = menuScript.shift();
+ if (next === undefined) throw new Error("Menu painted more times than scripted.");
+ if (next === "esc") throw new WizardCancelledError();
+ return next;
},
});
return { ...fake, menuPaints };
@@ -110,7 +128,7 @@ describe("runModelFlow", () => {
value: "model",
label: "Change model",
hint: "anthropic/claude-sonnet-5",
- description: "The model your agent uses",
+ description: "The model, its reasoning effort, and the Gateway service tier",
},
{
value: "provider",
@@ -118,7 +136,7 @@ describe("runModelFlow", () => {
hint: `AI Gateway (Linked to ${pc.bold("my-agent")})`,
description: "How your agent reaches the model provider",
},
- { value: "done", label: "Done", description: "Return to the prompt" },
+ { value: "done", label: "Done" },
],
notices: [],
hintLayout: "stacked",
@@ -127,13 +145,34 @@ describe("runModelFlow", () => {
]);
});
- it("disables both rows for an external-provider model and never asks to configure a provider", async () => {
+ it("summarizes authored reasoning and Fast mode on the model row hint", async () => {
+ const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });
+ const deps = flowDeps({
+ readCurrentModel: vi.fn(async () => ({
+ id: "xai/grok-4.5",
+ routing: { kind: "gateway", target: "xai" } as const,
+ reasoning: "high" as const,
+ serviceTier: { kind: "priority" } as const,
+ editable: true,
+ settingsEditable: true,
+ })),
+ });
+
+ await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
+
+ expect(menuPaints[0]?.options[0]?.hint).toBe("xai/grok-4.5@high ↯");
+ });
+
+ it("keeps the model row for an external-provider model and never asks to configure a provider", async () => {
const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });
const deps = flowDeps({
readCurrentModel: vi.fn(async () => ({
id: "anthropic/claude-sonnet-5",
routing: { kind: "external", provider: "anthropic" } as const,
+ reasoning: null,
+ serviceTier: { kind: "standard" } as const,
editable: false,
+ settingsEditable: true,
})),
// Even though detection finds nothing, external routing must NOT surface
// the "Configure model access" gateway UX.
@@ -150,8 +189,9 @@ describe("runModelFlow", () => {
{
value: "model",
label: "Change model",
- disabled: true,
- description: "Set via an SDK model call in agent.ts; edit the source to change it",
+ hint: "anthropic/claude-sonnet-5",
+ description:
+ "Reasoning and service tier; the model itself is an SDK model call in agent.ts",
},
{
value: "provider",
@@ -159,29 +199,92 @@ describe("runModelFlow", () => {
disabled: true,
description: "Disabled in external endpoint mode",
},
- { value: "done", label: "Done", description: "Return to the prompt" },
+ { value: "done", label: "Done" },
],
notices: [
{
tone: "warning",
- text: "`agent.ts` specifies a model provider directly. In-TUI configuration is restricted to AI Gateway endpoints.",
+ text: "`agent.ts` specifies the model provider directly. Model, provider, and service-tier changes stay source-owned; reasoning remains configurable here.",
},
],
hintLayout: "stacked",
- initialValue: "done",
+ initialValue: "model",
},
]);
});
- it("disables only Change model for a gateway-routed SDK model call, keeping the provider row", async () => {
+ it("disables the Change model row only when nothing at all is editable", async () => {
const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });
+ const deps = flowDeps({
+ readCurrentModel: vi.fn(async () => ({
+ id: "anthropic/claude-sonnet-5",
+ routing: { kind: "gateway", target: "anthropic" } as const,
+ reasoning: null,
+ serviceTier: { kind: "standard" } as const,
+ editable: false,
+ settingsEditable: false,
+ })),
+ });
+
+ await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
+
+ expect(menuPaints[0]?.options[0]).toEqual({
+ value: "model",
+ label: "Change model",
+ disabled: true,
+ description: "Set via an SDK model call in agent.ts; edit the source to change it",
+ });
+ expect(menuPaints[0]?.initialValue).toBe("provider");
+ });
+
+ it("opens the composite screen with catalog options, authored values, and capabilities", async () => {
+ const { prompter } = scriptedPrompter({ menu: ["model", "esc"] });
+ let captured: ModelSettingsRequest | undefined;
+ const pickModelSettings = vi.fn(async (request: ModelSettingsRequest) => {
+ captured = request;
+ return undefined;
+ });
+ const deps = flowDeps({ pickModelSettings });
+
+ await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
+
+ expect(captured?.model).toEqual({
+ kind: "pick",
+ options: expect.arrayContaining([
+ expect.objectContaining({ value: "anthropic/claude-sonnet-5", featured: true }),
+ expect.objectContaining({ value: "test/no-frills" }),
+ ]),
+ current: "anthropic/claude-sonnet-5",
+ });
+ expect(captured?.reasoning).toBeNull();
+ expect(captured?.serviceTier).toEqual({ kind: "standard" });
+ expect(captured?.settingsEditable).toBe(true);
+ expect(captured?.externalRouting).toBe(false);
+ expect(captured?.capabilitiesFor("test/no-frills")).toEqual({
+ reasoning: false,
+ reasoningLevels: [],
+ fastMode: false,
+ });
+ expect(captured?.capabilitiesFor("unknown/model")).toBeUndefined();
+ });
+
+ it("fixes the model section for a gateway-routed SDK model call", async () => {
+ const { prompter, menuPaints } = scriptedPrompter({ menu: ["model", "esc"] });
+ let captured: ModelSettingsRequest | undefined;
const deps = flowDeps({
// `gateway("…")` instance: gateway-routed, but not a string literal eve can rewrite.
readCurrentModel: vi.fn(async () => ({
id: "anthropic/claude-sonnet-5",
routing: { kind: "gateway", target: "anthropic" } as const,
+ reasoning: null,
+ serviceTier: { kind: "standard" } as const,
editable: false,
+ settingsEditable: true,
})),
+ pickModelSettings: vi.fn(async (request: ModelSettingsRequest) => {
+ captured = request;
+ return undefined;
+ }),
detectProviderStatus: vi.fn(
async () =>
({ kind: "gateway-key", envKey: "AI_GATEWAY_API_KEY", envFile: ".env.local" }) as const,
@@ -190,21 +293,11 @@ describe("runModelFlow", () => {
await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
- expect(menuPaints[0]?.options).toEqual([
- {
- value: "model",
- label: "Change model",
- disabled: true,
- description: "Set via an SDK model call in agent.ts; edit the source to change it",
- },
- {
- value: "provider",
- label: "Change provider",
- hint: "AI Gateway (AI_GATEWAY_API_KEY in .env.local)",
- description: "How your agent reaches the model provider",
- },
- { value: "done", label: "Done", description: "Return to the prompt" },
- ]);
+ expect(captured?.model).toEqual({
+ kind: "fixed",
+ current: "anthropic/claude-sonnet-5",
+ reason: "Set via an SDK model call in agent.ts; edit the source to change it",
+ });
// Gateway routing gets no external-restriction notice.
expect(menuPaints[0]?.notices).toEqual([]);
});
@@ -260,31 +353,40 @@ describe("runModelFlow", () => {
});
});
- it("applies the model and returns to the prompt", async () => {
+ it("applies a picked model once on Done and returns to the prompt", async () => {
const { prompter, menuPaints, selectMessages } = scriptedPrompter({
- menu: ["model"],
- picker: ["openai/gpt-5.5"],
+ menu: ["model", "done"],
+ });
+ const deps = flowDeps({
+ pickModelSettings: vi.fn(async () => ({ model: "openai/gpt-5.5" })),
});
- const deps = flowDeps();
await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
kind: "done",
modelMessage: `Model changed to ${pc.bold("openai/gpt-5.5")}. Live on your next prompt.`,
});
- expect(selectMessages).toEqual([MODEL_MENU_MESSAGE, "Which model should your agent use?"]);
- expect(menuPaints).toHaveLength(1);
- expect(deps.applyModel).toHaveBeenCalledWith({ appRoot: APP_ROOT, slug: "openai/gpt-5.5" });
+ expect(selectMessages).toEqual([MODEL_MENU_MESSAGE, MODEL_MENU_MESSAGE]);
+ expect(menuPaints).toHaveLength(2);
+ // The second lap lands on Done and shows the drafted slug on the hint.
+ expect(menuPaints[1]?.initialValue).toBe("done");
+ expect(menuPaints[1]?.options[0]?.hint).toBe("openai/gpt-5.5");
+ expect(deps.applySettings).toHaveBeenCalledWith({
+ appRoot: APP_ROOT,
+ patch: {
+ model: { kind: "set", value: "openai/gpt-5.5" },
+ reasoning: { kind: "keep" },
+ gatewayServiceTier: { kind: "keep" },
+ },
+ });
expect(deps.readCurrentModel).toHaveBeenCalledTimes(1);
});
it("returns a rejected model result without claiming the model changed", async () => {
- const { prompter, menuPaints } = scriptedPrompter({
- menu: ["model"],
- picker: ["openai/gpt-5.5"],
- });
+ const { prompter, menuPaints } = scriptedPrompter({ menu: ["model", "done"] });
const deps = flowDeps({
- applyModel: vi.fn(
+ pickModelSettings: vi.fn(async () => ({ model: "openai/gpt-5.5" })),
+ applySettings: vi.fn(
async () => ({ kind: "rejected", message: "Couldn't confirm the id." }) as const,
),
});
@@ -294,7 +396,118 @@ describe("runModelFlow", () => {
modelMessage: "Couldn't confirm the id.",
});
- expect(menuPaints).toHaveLength(1);
+ expect(menuPaints).toHaveLength(2);
+ });
+
+ it("drafts reasoning and Fast mode from the screen, then applies both once on Done", async () => {
+ const { prompter, menuPaints } = scriptedPrompter({ menu: ["model", "done"] });
+ const deps = flowDeps({
+ pickModelSettings: vi.fn(async () => ({
+ reasoning: "high" as const,
+ serviceTier: "priority" as const,
+ })),
+ applySettings: vi.fn<ModelFlowDeps["applySettings"]>(async () => ({
+ kind: "changed" as const,
+ changed: ["reasoning", "fast-mode"] as const,
+ reasoning: "high" as const,
+ fastMode: true,
+ })),
+ });
+
+ await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
+ kind: "done",
+ modelMessage:
+ "Model settings updated: reasoning high, Fast mode on. Live on your next prompt.",
+ });
+
+ expect(menuPaints).toHaveLength(2);
+ expect(menuPaints[1]?.options[0]?.hint).toBe("anthropic/claude-sonnet-5@high ↯");
+ expect(deps.applySettings).toHaveBeenCalledTimes(1);
+ expect(deps.applySettings).toHaveBeenCalledWith({
+ appRoot: APP_ROOT,
+ patch: {
+ model: { kind: "keep" },
+ reasoning: { kind: "set", value: "high" },
+ gatewayServiceTier: { kind: "set", value: "priority" },
+ },
+ });
+ });
+
+ it("maps the remove sentinels onto remove patches", async () => {
+ const { prompter } = scriptedPrompter({ menu: ["model", "done"] });
+ const deps = flowDeps({
+ readCurrentModel: vi.fn(async () => ({
+ id: "anthropic/claude-sonnet-5",
+ routing: { kind: "gateway", target: "anthropic" } as const,
+ reasoning: "high" as const,
+ serviceTier: { kind: "priority" } as const,
+ editable: true,
+ settingsEditable: true,
+ })),
+ pickModelSettings: vi.fn(async () => ({
+ reasoning: "default" as const,
+ serviceTier: "standard" as const,
+ })),
+ });
+
+ await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
+
+ expect(deps.applySettings).toHaveBeenCalledWith({
+ appRoot: APP_ROOT,
+ patch: {
+ model: { kind: "keep" },
+ reasoning: { kind: "remove" },
+ gatewayServiceTier: { kind: "remove" },
+ },
+ });
+ });
+
+ it("discards a model-settings draft when the root menu is cancelled, and says so", async () => {
+ const { prompter } = scriptedPrompter({ menu: ["model", "esc"] });
+ const deps = flowDeps({
+ pickModelSettings: vi.fn(async () => ({ reasoning: "low" as const })),
+ });
+
+ await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
+ kind: "cancelled",
+ discardedDraft: true,
+ });
+ expect(deps.applySettings).not.toHaveBeenCalled();
+ });
+
+ it("passes a custom Gateway service tier through to the screen untouched", async () => {
+ const { prompter, menuPaints } = scriptedPrompter({ menu: ["model", "esc"] });
+ let captured: ModelSettingsRequest | undefined;
+ const deps = flowDeps({
+ readCurrentModel: vi.fn(async () => ({
+ id: "anthropic/claude-sonnet-5",
+ routing: { kind: "gateway", target: "anthropic" } as const,
+ reasoning: "medium" as const,
+ serviceTier: { kind: "custom", value: "flex" } as const,
+ editable: true,
+ settingsEditable: true,
+ })),
+ pickModelSettings: vi.fn(async (request: ModelSettingsRequest) => {
+ captured = request;
+ return undefined;
+ }),
+ });
+
+ await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
+
+ expect(captured?.serviceTier).toEqual({ kind: "custom", value: "flex" });
+ // A custom tier is not Fast mode: no marker on the root hint.
+ expect(menuPaints[0]?.options[0]?.hint).toBe("anthropic/claude-sonnet-5@medium");
+ });
+
+ it("folds an unchanged screen and a Done exit into a cancel", async () => {
+ const { prompter } = scriptedPrompter({ menu: ["model", "done"] });
+ const deps = flowDeps({ pickModelSettings: vi.fn(async () => ({})) });
+
+ await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
+ kind: "cancelled",
+ });
+ expect(deps.applySettings).not.toHaveBeenCalled();
});
it("opens provider setup directly when none is configured", async () => {
@@ -316,7 +529,10 @@ describe("runModelFlow", () => {
},
});
- expect(runProviderFlow).toHaveBeenCalledWith(expect.objectContaining({ appRoot: APP_ROOT }));
+ // The sub-flow learns the detected provider so its menu can mark the active row.
+ expect(runProviderFlow).toHaveBeenCalledWith(
+ expect.objectContaining({ appRoot: APP_ROOT, currentProvider: { kind: "unset" } }),
+ );
expect(detectProviderStatus).toHaveBeenCalledTimes(2);
expect(menuPaints).toHaveLength(0);
});
@@ -416,22 +632,7 @@ describe("runModelFlow", () => {
expect(deps.detectProviderStatus).toHaveBeenCalledTimes(1);
expect(menuPaints).toHaveLength(2);
expect(menuPaints[1]?.notices).toEqual([]);
- expect(deps.applyModel).not.toHaveBeenCalled();
- });
-
- it("folds a cancelled picker without touching the source", async () => {
- const { prompter, menuPaints } = scriptedPrompter({
- menu: ["model", "esc"],
- picker: ["esc"],
- });
- const deps = flowDeps();
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "cancelled",
- });
- // The cancelled picker lands back on the menu before the empty exit.
- expect(menuPaints).toHaveLength(2);
- expect(deps.applyModel).not.toHaveBeenCalled();
+ expect(deps.applySettings).not.toHaveBeenCalled();
});
describe("cursor pre-selection", () => {
@@ -468,7 +669,7 @@ describe("runModelFlow", () => {
});
expect(provider.menuPaints[1]?.initialValue).toBe("provider");
- const model = scriptedPrompter({ menu: ["model", "esc"], picker: ["esc"] });
+ const model = scriptedPrompter({ menu: ["model", "esc"] });
await runModelFlow({ appRoot: APP_ROOT, prompter: model.prompter, deps: flowDeps() });
expect(model.menuPaints[1]?.initialValue).toBe("model");
});
diff --git a/packages/eve/src/setup/flows/model.ts b/packages/eve/src/setup/flows/model.ts
index 535f2f3e0..4b9bc7a82 100644
--- a/packages/eve/src/setup/flows/model.ts
+++ b/packages/eve/src/setup/flows/model.ts
@@ -1,48 +1,98 @@
-import { join } from "node:path";
-
-import { createCompiledRuntimeModelCatalogLoader } from "#compiler/model-catalog.js";
-import { discoverAgent } from "#discover/discover-agent.js";
-import { formatLanguageModelGatewayId } from "#internal/runtime-model.js";
import { inspectApplication } from "#services/inspect-application.js";
-import { createStaticSourceChange } from "#source-change/static-source-change.js";
+import type {
+ AgentModelSettingsPatch,
+ FieldPatch,
+} from "#source-change/apply-agent-model-settings.js";
import pc from "picocolors";
import { AI_GATEWAY_API_KEY_ENV_VAR } from "../ai-gateway-api-key.js";
-import { interactiveAsker } from "../ask.js";
import { findEnvFileWithKey } from "../boxes/detect-ai-gateway.js";
import {
fetchGatewayCatalog,
- selectModel,
+ modelOptionsFromCatalog,
+ type GatewayCatalogModel,
type SelectModelDeps,
- type SelectModelOptions,
} from "../boxes/select-model.js";
+import {
+ gatewayModelCapabilities,
+ type GatewayModelCapabilities,
+ type ReasoningLevel,
+} from "../boxes/model-capabilities.js";
import {
detectProjectIdentity,
type VercelProjectOperationOptions,
} from "../project-resolution.js";
-import type { ModelRouting } from "#shared/agent-definition.js";
+import type { AgentReasoningDefinition, ModelRouting } from "#shared/agent-definition.js";
+import {
+ readGatewayServiceTier,
+ type GatewayServiceTierState,
+} from "#shared/gateway-service-tier.js";
+import { formatModelSummary } from "#shared/model-summary.js";
import type { Prompter, SelectNotice, SelectOption } from "../prompter.js";
-import { runInteractive } from "../runner.js";
-import { snapshotSetupState } from "../state.js";
import { WizardCancelledError } from "../step.js";
import { withSpinner } from "../with-spinner.js";
-
-import { inProjectSetupState, prompterSink } from "./in-project.js";
-import { runProviderFlow } from "./provider.js";
+import {
+ changeAgentModelSettings,
+ formatApplyModelSettingsOutcome,
+ type ApplyModelSettingsOutcome,
+} from "./model-source-change.js";
+import { runProviderFlow, type ModelProviderStatus } from "./provider.js";
/** The current model id, its routing, and whether `/model` can rewrite it. */
export interface CurrentAgentModel {
id: string | null;
routing: ModelRouting | null;
+ reasoning: AgentReasoningDefinition | null;
+ serviceTier: GatewayServiceTierState;
/**
* The authored `model` is a string the source editor can rewrite. False for a
* source-backed SDK model call (`gateway(...)`, `anthropic(...)`), which is
* not a string literal — independent of how the model routes.
*/
editable: boolean;
+ /** Whether the top-level agent config object can carry reasoning/tier edits. */
+ settingsEditable: boolean;
+}
+
+export type { GatewayServiceTierState };
+
+/**
+ * Everything the composite Change-model screen edits, resolved before it
+ * opens. The model section is a searchable catalog pick, or a fixed line when
+ * the authored model is a source-backed SDK call `/model` cannot rewrite.
+ */
+export interface ModelSettingsRequest {
+ model:
+ | { kind: "pick"; options: readonly SelectOption<string>[]; current: string | null }
+ | { kind: "fixed"; current: string | null; reason: string };
+ /** Authored reasoning effort; null means the provider default. */
+ reasoning: ReasoningLevel | null;
+ /** Authored Gateway service tier. */
+ serviceTier: GatewayServiceTierState;
+ /** Whether the agent config object can carry reasoning/tier edits. */
+ settingsEditable: boolean;
+ /** True for a direct external provider, where Gateway tiers do not apply. */
+ externalRouting: boolean;
+ /** Capability lookup over the already-fetched catalog; called on every pick. */
+ capabilitiesFor(modelId: string | null): GatewayModelCapabilities | undefined;
+}
+
+/**
+ * The screen's draft on Done. Each field is present only when it differs from
+ * the authored value; `"default"` and `"standard"` mean "remove the setting".
+ */
+export interface ModelSettingsResult {
+ model?: string;
+ reasoning?: "default" | ReasoningLevel;
+ serviceTier?: "standard" | "priority";
}
+/** Renderer-owned composite model screen; only the dev TUI implements this. */
+export type ModelSettingsPicker = (
+ request: ModelSettingsRequest,
+) => Promise<ModelSettingsResult | undefined>;
+
/** Injected for tests; defaults to the real reads, fetches, and source edit. */
export interface ModelFlowDeps {
/**
@@ -50,30 +100,22 @@ export interface ModelFlowDeps {
* before the first compile.
*/
readCurrentModel: (appRoot: string) => Promise<CurrentAgentModel>;
- /** Applies the picked slug to authored source. */
- applyModel: (input: { appRoot: string; slug: string }) => Promise<ApplyModelOutcome>;
+ /** Applies one completed `/model` draft to authored source. */
+ applySettings: (input: {
+ appRoot: string;
+ patch: AgentModelSettingsPatch;
+ }) => Promise<ApplyModelSettingsOutcome>;
/** Catalog fetch behind the shared model picker. */
selectModel?: SelectModelDeps;
+ /** The composite Change-model screen; the dev TUI renderer implements it. */
+ pickModelSettings?: ModelSettingsPicker;
/** Reads how the model is backed right now, for the menu's provider row. */
detectProviderStatus: typeof detectModelProviderStatus;
/** The provider sub-flow behind the menu's provider row. */
runProviderFlow: typeof runProviderFlow;
}
-/**
- * How the agent's model is backed right now, as far as the local directory
- * shows: a linked Vercel project, a gateway credential in an env file, or
- * nothing detectable. An external provider (own ANTHROPIC_API_KEY etc.)
- * leaves no marker eve owns, so it reads as `unset`.
- */
-export type ModelProviderStatus =
- | { kind: "unset" }
- | { kind: "gateway-project"; projectName: string; teamName?: string }
- | {
- kind: "gateway-key";
- envKey: typeof AI_GATEWAY_API_KEY_ENV_VAR | "VERCEL_OIDC_TOKEN";
- envFile: string;
- };
+export type { ModelProviderStatus };
/**
* A provider sub-flow run that actually moved the provider: the credential
@@ -89,7 +131,11 @@ export interface ModelProviderOutcome {
}
export type ModelFlowResult =
- | { kind: "cancelled" }
+ | {
+ kind: "cancelled";
+ /** True when Esc dropped drafted setting changes that Done would commit. */
+ discardedDraft?: boolean;
+ }
| {
kind: "done";
/** The last apply line, when the model was changed this session. */
@@ -124,30 +170,71 @@ function providerStatusHint(
}
/**
- * The two-row configure menu. The two rows answer independent questions.
+ * The composite screen's catalog rows: the ids themselves as labels, so the
+ * railed list shows slugs and the editor's filter matches exactly what the
+ * painter windows. Onboarding keeps the name-labeled options.
+ */
+function modelListRows(
+ catalog: readonly GatewayCatalogModel[] | undefined,
+): SelectOption<string>[] {
+ return modelOptionsFromCatalog(catalog).map((option) => {
+ const row: SelectOption<string> = { value: option.value, label: option.value };
+ if (option.featured === true) row.featured = true;
+ return row;
+ });
+}
+
+/**
+ * The Change model row's value line: the drafted slug plus its reasoning level
+ * and Fast mode marker, mirroring the status line's model segment
+ * (`xai/grok-4.5@high ↯`).
+ */
+function formatModelDraftHint(
+ model: string,
+ reasoning: ReasoningLevel | null,
+ serviceTier: GatewayServiceTierState,
+): string {
+ const summary: Parameters<typeof formatModelSummary>[0] = { model };
+ if (reasoning !== null) summary.reasoning = reasoning;
+ if (serviceTier.kind === "priority") summary.fastGlyph = "↯";
+ return formatModelSummary(summary);
+}
+
+/**
+ * The model configuration menu. The Change model row opens the composite
+ * screen owning the model id, reasoning effort, and service tier; Done is the
+ * only row that commits drafted source changes.
*
- * The model row keys off `editable`: eve can rewrite `model` only when it is a
- * string literal, so an SDK model call (`gateway(...)` / `anthropic(...)`) is
- * disabled regardless of how it routes. The provider row keys off routing: an
- * external endpoint disables it (gateway credentials don't apply); a gateway
- * endpoint gates it bold-yellow "Configure model access" until a link or credential
- * is detectable (the genuine "no provider connected" state), then "Change
+ * The model row stays enabled while either the model string or the config
+ * object is rewritable — for an SDK model call (`gateway(...)`,
+ * `anthropic(...)`) the composite opens with the model fixed and only the
+ * settings adjustable. The provider row keys off routing: an external endpoint
+ * disables it (gateway credentials don't apply); a gateway endpoint gates it
+ * bold-yellow "Configure model access" until a link or credential is
+ * detectable (the genuine "no provider connected" state), then "Change
* provider" naming it.
*/
function modelMenuRows(
current: string | null,
+ reasoning: ReasoningLevel | null,
+ serviceTier: GatewayServiceTierState,
provider: ModelProviderStatus,
routing: ModelRouting | null,
editable: boolean,
+ settingsEditable: boolean,
): SelectOption<ModelMenuRow>[] {
let modelRow: SelectOption<ModelMenuRow>;
- if (editable) {
+ if (editable || settingsEditable) {
modelRow = {
value: "model",
label: "Change model",
- description: "The model your agent uses",
+ description: editable
+ ? "The model, its reasoning effort, and the Gateway service tier"
+ : "Reasoning and service tier; the model itself is an SDK model call in agent.ts",
};
- if (current !== null) modelRow.hint = current;
+ if (current !== null) {
+ modelRow.hint = formatModelDraftHint(current, reasoning, serviceTier);
+ }
} else {
modelRow = {
value: "model",
@@ -184,11 +271,7 @@ function modelMenuRows(
// An explicit exit row, like the channels list — Esc works too, but the menu
// must not make Esc the only way out.
- return [
- modelRow,
- providerRow,
- { value: "done", label: "Done", description: "Return to the prompt" },
- ];
+ return [modelRow, providerRow, { value: "done", label: "Done" }];
}
/**
@@ -224,16 +307,13 @@ export async function detectModelProviderStatus(
}
/**
- * THE MODEL FLOW for the dev TUI's `/model`: a two-row action menu that
- * loops, uniting the model pick and the provider setup behind one entry
- * point. "Change model" runs the same searchable AI Gateway catalog picker
- * onboarding uses ({@link selectModel}), pre-selected on the model the
- * runtime currently serves, then the static source edit that bakes the
- * choice into `agent.ts` (activation is the dev server's HMR watcher).
- * The provider row runs {@link runProviderFlow}, whose single menu chooses a
- * project-backed gateway, an inline gateway key, or an external provider.
- * A completed model or provider change returns to the prompt with its result.
- * Cancelled flows and external-provider instructions return to the menu.
+ * THE MODEL FLOW for the dev TUI's `/model`: a root menu whose Change model
+ * row opens the composite model screen (catalog pick, reasoning-effort slider,
+ * service-tier toggle) and whose provider row runs {@link runProviderFlow}.
+ * Authored setting changes stay in memory until Done, then land through one
+ * source transform and atomic rename. A completed provider change commits the
+ * current draft and returns to the prompt; cancelled flows and
+ * external-provider instructions return to the menu.
*/
export async function runModelFlow(input: {
appRoot: string;
@@ -246,32 +326,54 @@ export async function runModelFlow(input: {
const { appRoot, prompter, signal } = input;
const deps: ModelFlowDeps = {
readCurrentModel: readCurrentAgentModel,
- applyModel: changeAgentModel,
+ applySettings: changeAgentModelSettings,
detectProviderStatus: detectModelProviderStatus,
runProviderFlow,
...input.deps,
};
- // The model read is local, the provider status is a `vercel` round-trip;
- // one ephemeral spinner covers both so the menu paints with no persisted
- // loading lines.
+ // The model read is local; the provider status and the catalog are round
+ // trips. One ephemeral spinner covers all three so the menu paints with no
+ // persisted loading lines and already knows what the model supports. A
+ // failed catalog fetch degrades to unknown capabilities, never to an error.
const detectProvider = (useFlowSignal = true): Promise<ModelProviderStatus> =>
deps.detectProviderStatus(appRoot, useFlowSignal && signal !== undefined ? { signal } : {});
- let [{ id: current, routing, editable }, provider] = await withSpinner(
+ const fetchCatalog = deps.selectModel?.fetchModels ?? fetchGatewayCatalog;
+ const [currentModel, initialProvider, catalog] = await withSpinner(
prompter,
"Checking the project…",
- () => Promise.all([deps.readCurrentModel(appRoot), detectProvider()]),
+ () =>
+ Promise.all([
+ deps.readCurrentModel(appRoot),
+ detectProvider(),
+ fetchCatalog(signal).catch((): GatewayCatalogModel[] | undefined => undefined),
+ ]),
);
signal?.throwIfAborted();
- let lastApply: ApplyModelOutcome | undefined;
+ let { id: current, routing, serviceTier, editable, settingsEditable } = currentModel;
+ // An authored "provider-default" is the absent-setting sentinel, not a level.
+ let reasoning: ReasoningLevel | null =
+ currentModel.reasoning === "provider-default" ? null : currentModel.reasoning;
+ let provider = initialProvider;
+ const patch: {
+ model: FieldPatch<string>;
+ reasoning: FieldPatch<AgentReasoningDefinition>;
+ gatewayServiceTier: FieldPatch<"priority">;
+ } = {
+ model: { kind: "keep" },
+ reasoning: { kind: "keep" },
+ gatewayServiceTier: { kind: "keep" },
+ };
+
+ let lastApply: ApplyModelSettingsOutcome | undefined;
let providerOutcome: ModelProviderOutcome | undefined;
- // Explains, once, why every row is inert for an external-provider model.
+ let commitDraft = false;
const externalNotice: SelectNotice | undefined =
routing?.kind === "external"
? {
tone: "warning",
- text: "`agent.ts` specifies a model provider directly. In-TUI configuration is restricted to AI Gateway endpoints.",
+ text: "`agent.ts` specifies the model provider directly. Model, provider, and service-tier changes stay source-owned; reasoning remains configurable here.",
}
: undefined;
@@ -279,11 +381,9 @@ export async function runModelFlow(input: {
let nextSelection: ModelMenuRow =
provider.kind === "unset" && routing?.kind !== "external"
? "provider"
- : editable
+ : editable || settingsEditable
? "model"
- : routing?.kind === "external"
- ? "done"
- : "provider";
+ : "provider";
// A gateway model with no provider cannot run. Skip the menu's extra Enter
// and open provider setup as soon as that state is confirmed.
let openProviderFirst =
@@ -298,38 +398,86 @@ export async function runModelFlow(input: {
try {
pick = await prompter.select<ModelMenuRow>({
message: MODEL_MENU_MESSAGE,
- options: modelMenuRows(current, provider, routing, editable),
+ options: modelMenuRows(
+ current,
+ reasoning,
+ serviceTier,
+ provider,
+ routing,
+ editable,
+ settingsEditable,
+ ),
hintLayout: "stacked",
initialValue: nextSelection,
notices: externalNotice === undefined ? [] : [externalNotice],
});
} catch (error) {
if (!(error instanceof WizardCancelledError)) throw error;
+ // Esc discards the draft. Say so: before drafts existed, a completed
+ // model pick applied immediately, so a silent drop reads as success.
+ if (hasModelSettingsChanges(patch)) return { kind: "cancelled", discardedDraft: true };
break;
}
}
- if (pick === "done") break;
+ if (pick === "done") {
+ commitDraft = true;
+ break;
+ }
if (pick === "model") {
- const slug = await pickModelFromCatalog({
- appRoot,
- prompter,
- current,
- signal,
- deps: deps.selectModel,
- });
- if (slug === undefined) {
+ const pickModelSettings = deps.pickModelSettings;
+ if (pickModelSettings === undefined) {
+ throw new Error("runModelFlow requires a pickModelSettings dep to open the model screen.");
+ }
+ const request: ModelSettingsRequest = {
+ model: editable
+ ? { kind: "pick", options: modelListRows(catalog), current }
+ : {
+ kind: "fixed",
+ current,
+ reason: "Set via an SDK model call in agent.ts; edit the source to change it",
+ },
+ reasoning,
+ serviceTier,
+ settingsEditable,
+ externalRouting: routing?.kind === "external",
+ capabilitiesFor: (modelId) => gatewayModelCapabilities(catalog, modelId),
+ };
+ const result = await pickModelSettings(request);
+ signal?.throwIfAborted();
+ if (result === undefined) {
nextSelection = "model";
continue;
}
- signal?.throwIfAborted();
- lastApply = await deps.applyModel({ appRoot, slug });
- signal?.throwIfAborted();
- break;
+ if (result.model !== undefined) {
+ current = result.model;
+ routing = { kind: "gateway", target: result.model.split("/")[0] ?? "" };
+ patch.model = { kind: "set", value: result.model };
+ }
+ if (result.reasoning !== undefined) {
+ reasoning = result.reasoning === "default" ? null : result.reasoning;
+ patch.reasoning =
+ reasoning === null ? { kind: "remove" } : { kind: "set", value: reasoning };
+ }
+ if (result.serviceTier !== undefined) {
+ serviceTier =
+ result.serviceTier === "priority" ? { kind: "priority" } : { kind: "standard" };
+ patch.gatewayServiceTier =
+ result.serviceTier === "priority"
+ ? { kind: "set", value: "priority" }
+ : { kind: "remove" };
+ }
+ nextSelection = "done";
+ continue;
}
- const result = await deps.runProviderFlow({ appRoot, prompter, signal });
+ const result = await deps.runProviderFlow({
+ appRoot,
+ prompter,
+ signal,
+ currentProvider: provider,
+ });
// Backing out of the provider sub-flow changed nothing; the cursor stays on
// the provider row so a retry is one keypress away.
if (result.kind === "cancelled") {
@@ -350,131 +498,30 @@ export async function runModelFlow(input: {
provider = await withSpinner(prompter, "Checking the project…", () => detectProvider(false));
providerOutcome = { status: provider };
if (result.credential !== undefined) providerOutcome.credential = result.credential;
+ commitDraft = true;
break;
}
+ if (commitDraft && hasModelSettingsChanges(patch)) {
+ lastApply = await deps.applySettings({ appRoot, patch });
+ signal?.throwIfAborted();
+ }
+
if (lastApply === undefined && providerOutcome === undefined) {
return { kind: "cancelled" };
}
const done: Extract<ModelFlowResult, { kind: "done" }> = { kind: "done" };
- if (lastApply !== undefined) done.modelMessage = formatApplyModelOutcome(lastApply);
+ if (lastApply !== undefined) done.modelMessage = formatApplyModelSettingsOutcome(lastApply);
if (providerOutcome !== undefined) done.providerOutcome = providerOutcome;
return done;
}
-/**
- * The "Change model" sub-flow: the shared catalog picker pre-selected on
- * `current`. Resolves to the picked slug, or undefined when cancelled —
- * the menu loop treats both as "back to the menu".
- */
-async function pickModelFromCatalog(input: {
- appRoot: string;
- prompter: Prompter;
- current: string | null;
- signal?: AbortSignal;
- deps?: SelectModelDeps;
-}): Promise<string | undefined> {
- const { appRoot, prompter, current, signal } = input;
- const baseFetch = input.deps?.fetchModels ?? fetchGatewayCatalog;
- const options: SelectModelOptions = {
- asker: interactiveAsker(prompter),
- deps: {
- // The box fetches inside its gather, so the catalog spinner has to ride
- // the fetch itself to bracket exactly the slow part.
- fetchModels: (requestSignal) =>
- withSpinner(prompter, "Loading the model catalog...", () => baseFetch(requestSignal)),
- },
- };
- if (current !== null) options.defaultModel = current;
-
- const result = await runInteractive(
- [selectModel(options)],
- inProjectSetupState(appRoot, { kind: "unresolved" }),
- prompterSink(prompter),
- { snapshot: snapshotSetupState, signal },
+function hasModelSettingsChanges(patch: AgentModelSettingsPatch): boolean {
+ return (
+ patch.model.kind !== "keep" ||
+ patch.reasoning.kind !== "keep" ||
+ patch.gatewayServiceTier.kind !== "keep"
);
- return result.kind === "cancelled" ? undefined : result.state.modelId;
-}
-
-/** The outcome of applying a model slug to the agent's authored source. */
-export type ApplyModelOutcome =
- | { kind: "changed"; to: string }
- | { kind: "unchanged"; model: string }
- /** Invalid slug or an uneditable source — `message` says which and why. */
- | { kind: "rejected"; message: string };
-
-/** The one-line transcript form of an apply outcome (`/model <slug>`'s reply). */
-export function formatApplyModelOutcome(outcome: ApplyModelOutcome): string {
- switch (outcome.kind) {
- case "changed":
- return `Model changed to ${pc.bold(outcome.to)}. Live on your next prompt.`;
- case "unchanged":
- return `Model is already \`${outcome.model}\`.`;
- case "rejected":
- return outcome.message;
- }
-}
-
-/**
- * Applies a `/model <slug>` change to the local agent's authored source.
- *
- * This is the caller layer for the static source-change registry: it
- * validates the slug against the AI Gateway model catalog, then edits
- * `agent.ts` via {@link createStaticSourceChange}. Activation is the dev
- * server's HMR watcher; {@link formatApplyModelOutcome} renders the outcome
- * as the TUI's one-line reply.
- */
-export async function changeAgentModel(input: {
- readonly appRoot: string;
- readonly slug: string;
-}): Promise<ApplyModelOutcome> {
- const { appRoot, slug } = input;
-
- const rejection = await validateModelSlug(appRoot, slug);
- if (rejection !== null) {
- return { kind: "rejected", message: rejection };
- }
-
- const agentRoot = join(appRoot, "agent");
- const { manifest } = await discoverAgent({ agentRoot, appRoot });
- const result = await createStaticSourceChange(manifest).updateModelName(slug);
-
- if (result.kind === "bail") {
- return {
- kind: "rejected",
- message: `Couldn't edit ${result.at.logicalPath}: ${result.reason}. Change \`model\` by hand.`,
- };
- }
- if (result.from === result.to) {
- return { kind: "unchanged", model: result.to };
- }
- return { kind: "changed", to: result.to };
-}
-
-/**
- * Returns a rejection message when `slug` is malformed or absent from the
- * model catalog, or null when it is safe to apply.
- *
- * UX note: `/model` only reports success after eve confirms the id. A real
- * turn still needs Gateway/provider access, so treating an offline catalog as
- * success would give a false "model changed" result.
- */
-async function validateModelSlug(appRoot: string, slug: string): Promise<string | null> {
- if (!slug.includes("/")) {
- return `\`${slug}\` isn't a provider/model id (e.g. anthropic/claude-sonnet-5).`;
- }
-
- const catalog = createCompiledRuntimeModelCatalogLoader(appRoot);
- try {
- const limits = await catalog.getModelLimits(formatLanguageModelGatewayId(slug));
- if (limits === null) {
- return `I couldn't confirm \`${slug}\` in the AI Gateway model catalog, so I didn't change agent.ts.`;
- }
- } catch {
- return null;
- }
-
- return null;
}
/**
@@ -485,16 +532,27 @@ async function validateModelSlug(appRoot: string, slug: string): Promise<string
async function readCurrentAgentModel(appRoot: string): Promise<CurrentAgentModel> {
try {
const { compiledState } = await inspectApplication(appRoot);
- const model = compiledState?.manifest.config.model;
+ const config = compiledState?.manifest.config;
+ const model = config?.model;
// A source-backed model (an SDK model call) carries `source`; a string id
// does not, and only a string is a literal the editor can rewrite.
return {
id: model?.id ?? null,
routing: model?.routing ?? null,
+ reasoning: config?.reasoning ?? null,
+ serviceTier: readGatewayServiceTier(model?.providerOptions),
editable: model !== undefined && model.source === undefined,
+ settingsEditable: config?.source !== undefined,
};
} catch {
- return { id: null, routing: null, editable: false };
+ return {
+ id: null,
+ routing: null,
+ reasoning: null,
+ serviceTier: { kind: "standard" },
+ editable: false,
+ settingsEditable: false,
+ };
}
}
diff --git a/packages/eve/src/setup/flows/provider.test.ts b/packages/eve/src/setup/flows/provider.test.ts
index 9fa951a38..0fbac32f0 100644
--- a/packages/eve/src/setup/flows/provider.test.ts
+++ b/packages/eve/src/setup/flows/provider.test.ts
@@ -1,3 +1,4 @@
+import pc from "picocolors";
import { describe, expect, it, vi } from "vitest";
import { createFakePrompter } from "#internal/testing/fake-prompter.js";
@@ -61,6 +62,67 @@ describe("runProviderFlow", () => {
});
});
+ it("checks and describes the active provider, opening the cursor on it", async () => {
+ const fake = createFakePrompter();
+ const deps = createDeps();
+ const linked: ProviderPicker = async (request) => {
+ expect(request.initialValue).toBe("project");
+ expect(request.options[0]).toMatchObject({
+ value: "project",
+ checked: true,
+ hint: `Linked to ${pc.bold("my-agent")} in team ${pc.bold("my-team")}`,
+ });
+ expect(request.options[1]?.checked).toBeUndefined();
+ return undefined;
+ };
+ await runProviderFlow({
+ appRoot: APP_ROOT,
+ prompter: fake.prompter,
+ picker: linked,
+ currentProvider: {
+ kind: "gateway-project",
+ projectName: "my-agent",
+ teamName: "my-team",
+ },
+ deps,
+ });
+
+ const keyed: ProviderPicker = async (request) => {
+ expect(request.initialValue).toBe("own-key");
+ expect(request.options[1]).toMatchObject({
+ value: "own-key",
+ checked: true,
+ hint: "AI_GATEWAY_API_KEY set in .env.local",
+ });
+ return undefined;
+ };
+ await runProviderFlow({
+ appRoot: APP_ROOT,
+ prompter: fake.prompter,
+ picker: keyed,
+ currentProvider: {
+ kind: "gateway-key",
+ envKey: "AI_GATEWAY_API_KEY",
+ envFile: ".env.local",
+ },
+ deps,
+ });
+ });
+
+ it("reports a committed key as one set line", async () => {
+ const fake = createFakePrompter();
+ const deps = createDeps();
+
+ await runProviderFlow({
+ appRoot: APP_ROOT,
+ prompter: fake.prompter,
+ picker: async () => ({ kind: "inline-key", key: "sk-inline", validation: { kind: "valid" } }),
+ deps,
+ });
+
+ expect(fake.prompter.log.success).toHaveBeenCalledExactlyOnceWith("AI_GATEWAY_API_KEY set.");
+ });
+
it("persists the accepted inline key and does not revalidate it after submission", async () => {
const fake = createFakePrompter();
const deps = createDeps();
diff --git a/packages/eve/src/setup/flows/provider.ts b/packages/eve/src/setup/flows/provider.ts
index 98a7422a2..ee2483a28 100644
--- a/packages/eve/src/setup/flows/provider.ts
+++ b/packages/eve/src/setup/flows/provider.ts
@@ -20,6 +20,21 @@ import { runLinkFlow, type LinkFlowResult } from "./link.js";
export type ProviderConnection = "project" | "own-key" | "external";
+/**
+ * How the agent's model is backed right now, as far as the local directory
+ * shows: a linked Vercel project, a gateway credential in an env file, or
+ * nothing detectable. An external provider (own ANTHROPIC_API_KEY etc.)
+ * leaves no marker eve owns, so it reads as `unset`.
+ */
+export type ModelProviderStatus =
+ | { kind: "unset" }
+ | { kind: "gateway-project"; projectName: string; teamName?: string }
+ | {
+ kind: "gateway-key";
+ envKey: typeof AI_GATEWAY_API_KEY_ENV_VAR | "VERCEL_OIDC_TOKEN";
+ envFile: string;
+ };
+
export const PROVIDER_QUESTION = "Which model provider do you want to use?";
export const EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE = "Using another model provider";
@@ -86,14 +101,29 @@ function projectConnectionOption(
function providerOptions(
authStatus: VercelAuthStatus | undefined,
+ current: ModelProviderStatus | undefined,
): SelectOption<ProviderConnection>[] {
+ let project = projectConnectionOption(authStatus);
+ if (current?.kind === "gateway-project") {
+ const where =
+ current.teamName === undefined
+ ? pc.bold(current.projectName)
+ : `${pc.bold(current.projectName)} in team ${pc.bold(current.teamName)}`;
+ project = { ...project, checked: true, hint: `Linked to ${where}` };
+ }
+
+ let ownKey: SelectOption<ProviderConnection> = {
+ value: "own-key",
+ label: `AI Gateway via ${AI_GATEWAY_API_KEY_ENV_VAR}`,
+ hint: "⎿ type your key",
+ };
+ if (current?.kind === "gateway-key") {
+ ownKey = { ...ownKey, checked: true, hint: `${current.envKey} set in ${current.envFile}` };
+ }
+
return [
- projectConnectionOption(authStatus),
- {
- value: "own-key",
- label: `AI Gateway via ${AI_GATEWAY_API_KEY_ENV_VAR}`,
- hint: "> type your key",
- },
+ project,
+ ownKey,
{
value: "external",
label: "Other providers",
@@ -135,6 +165,8 @@ export async function runProviderFlow(input: {
prompter: Prompter;
signal?: AbortSignal;
picker?: ProviderPicker;
+ /** The detected provider, so the chooser can mark and describe the active row. */
+ currentProvider?: ModelProviderStatus;
deps?: Partial<ProviderFlowDeps>;
}): Promise<ProviderFlowResult> {
const { appRoot, prompter, signal } = input;
@@ -147,14 +179,17 @@ export async function runProviderFlow(input: {
};
let authStatus: VercelAuthStatus | undefined;
- let initialValue: ProviderConnection = "project";
+ // The cursor opens on the active provider; a Vercel auth blocker still
+ // re-homes it onto the key row below.
+ let initialValue: ProviderConnection =
+ input.currentProvider?.kind === "gateway-key" ? "own-key" : "project";
let keyChoice: Extract<ProviderPickerChoice, { kind: "inline-key" }>;
try {
while (true) {
const choice = await selectProvider({
picker: input.picker,
- options: providerOptions(authStatus),
+ options: providerOptions(authStatus, input.currentProvider),
initialValue,
validateInlineKey: (key, validationSignal) =>
deps.validateGatewayApiKey(
@@ -212,8 +247,6 @@ export async function runProviderFlow(input: {
prompter.log.warning(
`Couldn't reach the gateway to validate (${validation.message}). Saving the key anyway.`,
);
- } else {
- prompter.log.success(`${pc.green("✓")} ${pc.bold("Valid key")}`);
}
const location = await writeAiGatewayApiKey({
@@ -224,6 +257,6 @@ export async function runProviderFlow(input: {
// The env write is the commit point. A concurrent interrupt may mute the
// remaining UI, but the caller must still refresh model access for the key
// that is now on disk.
- prompter.log.success(`Saved ${location.envKey} to ${location.envFile}.`);
+ prompter.log.success(`${location.envKey} set.`);
return { kind: "done", credential: location.envKey };
}
diff --git a/packages/eve/src/setup/prompter.ts b/packages/eve/src/setup/prompter.ts
index 256aaf413..4bf9d5a01 100644
--- a/packages/eve/src/setup/prompter.ts
+++ b/packages/eve/src/setup/prompter.ts
@@ -75,6 +75,8 @@ export interface SelectOption<T extends PrompterValue> {
* to the front. Meaningless without `search`.
*/
featured?: boolean;
+ /** Marks the currently-active value: renders a green check beside the row. */
+ checked?: boolean;
}
/**
diff --git a/packages/eve/src/setup/vercel-project.test.ts b/packages/eve/src/setup/vercel-project.test.ts
index 1e48e38df..2319627e3 100644
--- a/packages/eve/src/setup/vercel-project.test.ts
+++ b/packages/eve/src/setup/vercel-project.test.ts
@@ -195,6 +195,88 @@ describe("pickProject", () => {
expect(stop).toHaveBeenCalledTimes(1);
});
+ it("suggests a recent project matching the suggested name without a lookup", async () => {
+ mockedCaptureVercel.mockResolvedValueOnce(
+ captured({
+ projects: [
+ { id: "prj_other", name: "other" },
+ { id: "prj_mine", name: "my-agent" },
+ ],
+ }),
+ );
+ const single = vi.fn().mockImplementationOnce((options) => {
+ // The match floats to the top, carries the marker, and holds the cursor.
+ expect(options.options[0]).toEqual({
+ value: "prj_mine",
+ label: "my-agent",
+ hint: "suggested",
+ });
+ expect(options.initialValue).toBe("prj_mine");
+ return "prj_mine";
+ });
+ const { prompter } = createFakePrompter({ single });
+
+ await expect(
+ pickProject(prompter, "/repo", "team-a", { suggestedName: "my-agent" }),
+ ).resolves.toEqual({
+ kind: "existing",
+ project: { projectId: "prj_mine", projectName: "my-agent" },
+ team: "team-a",
+ });
+ // The recents already held the match: no extra lookup round trip.
+ expect(mockedCaptureVercel).toHaveBeenCalledTimes(1);
+ });
+
+ it("searches the team for the suggested name when the recents miss it", async () => {
+ mockedCaptureVercel
+ .mockResolvedValueOnce(captured({ projects: [{ id: "prj_other", name: "other" }] }))
+ .mockResolvedValueOnce(captured(JSON.stringify({ id: "prj_mine", name: "my-agent" })));
+ const single = vi.fn().mockImplementationOnce((options) => {
+ expect(options.options.map((option: { label: string }) => option.label)).toEqual([
+ "my-agent",
+ "other",
+ ]);
+ expect(options.initialValue).toBe("prj_mine");
+ return "prj_mine";
+ });
+ const { prompter } = createFakePrompter({ single });
+
+ await expect(
+ pickProject(prompter, "/repo", "team-a", { suggestedName: "my-agent" }),
+ ).resolves.toEqual({
+ kind: "existing",
+ project: { projectId: "prj_mine", projectName: "my-agent" },
+ team: "team-a",
+ });
+ expect(mockedCaptureVercel).toHaveBeenNthCalledWith(
+ 2,
+ ["api", "/v9/projects/my-agent", "--scope", "team-a", "--raw"],
+ { cwd: "/repo", signal: undefined, timeoutMs: 15_000 },
+ );
+ });
+
+ it("degrades to the plain recents list when the suggestion lookup fails", async () => {
+ mockedCaptureVercel
+ .mockResolvedValueOnce(captured({ projects: [{ id: "prj_other", name: "other" }] }))
+ .mockResolvedValueOnce(
+ failedCapture(JSON.stringify({ error: { code: "internal", message: "boom" } })),
+ );
+ const single = vi.fn().mockImplementationOnce((options) => {
+ expect(options.options).toEqual([{ value: "prj_other", label: "other" }]);
+ expect(options.initialValue).toBe("prj_other");
+ return "prj_other";
+ });
+ const { prompter } = createFakePrompter({ single });
+
+ await expect(
+ pickProject(prompter, "/repo", "team-a", { suggestedName: "my-agent" }),
+ ).resolves.toEqual({
+ kind: "existing",
+ project: { projectId: "prj_other", projectName: "other" },
+ team: "team-a",
+ });
+ });
+
it("falls back to one ranked project-search page when no exact project exists", async () => {
mockedCaptureVercel
.mockResolvedValueOnce(
diff --git a/packages/eve/src/setup/vercel-project.ts b/packages/eve/src/setup/vercel-project.ts
index 312b44f4b..c075d8441 100644
--- a/packages/eve/src/setup/vercel-project.ts
+++ b/packages/eve/src/setup/vercel-project.ts
@@ -41,6 +41,12 @@ const VercelProjectReferenceSchema = z.object({
export interface PickProjectOptions extends VercelProjectOperationOptions {
/** Whether an empty project list may fall back to entering a name to create. */
allowCreateWhenEmpty?: boolean;
+ /**
+ * Searches the team for a project with this name before the list opens and
+ * suggests the best match: floated to the top, cursor on it, marked
+ * "suggested". Best-effort — a failed lookup falls back to the plain list.
+ */
+ suggestedName?: string;
}
export interface PickTeamOptions extends VercelProjectOperationOptions {
@@ -390,6 +396,29 @@ async function findProjectSearchResults(
return await searchProjects(projectRoot, team, search, { ...options, next });
}
+/**
+ * Finds the project to suggest for `name`: an exact hit in the already-listed
+ * recents, or the team's best name-search match. Best-effort — failures mean
+ * "no suggestion", never an aborted picker.
+ */
+async function findSuggestedProject(
+ projectRoot: string,
+ team: string,
+ name: string,
+ recents: readonly VercelProjectListEntry[],
+ options: VercelProjectOperationOptions,
+): Promise<VercelProjectListEntry | undefined> {
+ const inRecents = recents.find((project) => project.name === name);
+ if (inRecents !== undefined) return inRecents;
+ try {
+ const found = await findProjectSearchResults(projectRoot, team, name, options);
+ return rankProjectSearchResults(found.projects, name)[0];
+ } catch {
+ options.signal?.throwIfAborted();
+ return undefined;
+ }
+}
+
/** Picks an existing project under a team, or a name to create when none exist. */
export async function pickProject(
prompter: Prompter,
@@ -397,13 +426,31 @@ export async function pickProject(
team: string,
options: PickProjectOptions = {},
): Promise<ResolvedVercelProjectSpec> {
- let projects = await withSpinner(prompter, whimsyFor("projects", team), () =>
- listRecentProjects(projectRoot, team, options),
- );
+ const suggestedName = options.suggestedName?.trim();
+ const listed = await withSpinner(prompter, whimsyFor("projects", team), async () => {
+ const recents = await listRecentProjects(projectRoot, team, options);
+ const suggested =
+ suggestedName === undefined || suggestedName.length === 0
+ ? undefined
+ : await findSuggestedProject(projectRoot, team, suggestedName, recents, options);
+ return { recents, suggested };
+ });
+ const suggestedId = listed.suggested?.id;
+ let projects =
+ listed.suggested === undefined
+ ? listed.recents
+ : prioritizeSearchResults(listed.recents, [listed.suggested]);
let searchResults: readonly VercelProjectListEntry[] = [];
let searchContinuation: ProjectSearchContinuation | undefined;
const projectOptions = () => {
- const result = projects.map((project) => ({ value: project.id, label: project.name }));
+ const result = projects.map((project) => {
+ const option: { value: string; label: string; hint?: string } = {
+ value: project.id,
+ label: project.name,
+ };
+ if (project.id === suggestedId) option.hint = "suggested";
+ return option;
+ });
if (searchContinuation !== undefined) {
result.push({
value: searchMoreProjectsValue(searchContinuation),
@@ -454,7 +501,7 @@ export async function pickProject(
},
},
options: projectOptions(),
- initialValue: projects[0]?.id,
+ initialValue: suggestedId ?? projects[0]?.id,
});
const continuation = searchContinuation;
if (continuation !== undefined && selected === searchMoreProjectsValue(continuation)) {
diff --git a/packages/eve/src/shared/errors.ts b/packages/eve/src/shared/errors.ts
index 2ae58fa64..4759a22b7 100644
--- a/packages/eve/src/shared/errors.ts
+++ b/packages/eve/src/shared/errors.ts
@@ -57,6 +57,20 @@ export function toError(raw: unknown): Error {
return error;
}
+/**
+ * Yields the error itself and every object on its `cause` chain, once
+ * each. Cycles terminate the walk instead of looping.
+ */
+export function* walkCauseChain(error: unknown): Generator<unknown> {
+ const seen = new Set<unknown>();
+ let current = error;
+ while (isObject(current) && !seen.has(current)) {
+ seen.add(current);
+ yield current;
+ current = current.cause;
+ }
+}
+
function safeJsonStringify(value: unknown): string {
try {
const stringified = JSON.stringify(value);
diff --git a/packages/eve/src/shared/gateway-service-tier.test.ts b/packages/eve/src/shared/gateway-service-tier.test.ts
new file mode 100644
index 000000000..a555384db
--- /dev/null
+++ b/packages/eve/src/shared/gateway-service-tier.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+
+import { readGatewayServiceTier } from "./gateway-service-tier.js";
+
+describe("readGatewayServiceTier", () => {
+ it("reads the priority tier eve's Fast mode writes", () => {
+ expect(readGatewayServiceTier({ gateway: { serviceTier: "priority" } })).toEqual({
+ kind: "priority",
+ });
+ });
+
+ it("surfaces any other authored tier as custom", () => {
+ expect(readGatewayServiceTier({ gateway: { serviceTier: "flex" } })).toEqual({
+ kind: "custom",
+ value: "flex",
+ });
+ });
+
+ it("treats absent or malformed provider options as standard", () => {
+ expect(readGatewayServiceTier(undefined)).toEqual({ kind: "standard" });
+ expect(readGatewayServiceTier(null)).toEqual({ kind: "standard" });
+ expect(readGatewayServiceTier("priority")).toEqual({ kind: "standard" });
+ expect(readGatewayServiceTier([])).toEqual({ kind: "standard" });
+ expect(readGatewayServiceTier({})).toEqual({ kind: "standard" });
+ expect(readGatewayServiceTier({ gateway: [] })).toEqual({ kind: "standard" });
+ expect(readGatewayServiceTier({ gateway: { serviceTier: 3 } })).toEqual({ kind: "standard" });
+ });
+});
diff --git a/packages/eve/src/shared/gateway-service-tier.ts b/packages/eve/src/shared/gateway-service-tier.ts
new file mode 100644
index 000000000..cd5440b7e
--- /dev/null
+++ b/packages/eve/src/shared/gateway-service-tier.ts
@@ -0,0 +1,31 @@
+/**
+ * The AI Gateway service tier a model's `providerOptions` requests:
+ * `standard` (no tier authored), the `priority` tier eve's Fast mode writes,
+ * or any other authored `custom` tier value.
+ */
+export type GatewayServiceTierState =
+ | { kind: "standard" }
+ | { kind: "priority" }
+ | { kind: "custom"; value: string };
+
+/**
+ * Reads `gateway.serviceTier` from an unknown-shaped `providerOptions` value
+ * (compiled manifest or `/eve/v1/info` payload). Anything absent or malformed
+ * reads as `standard`.
+ */
+export function readGatewayServiceTier(providerOptions: unknown): GatewayServiceTierState {
+ if (
+ providerOptions === null ||
+ typeof providerOptions !== "object" ||
+ Array.isArray(providerOptions)
+ ) {
+ return { kind: "standard" };
+ }
+ const gateway = (providerOptions as Record<string, unknown>).gateway;
+ if (gateway === null || typeof gateway !== "object" || Array.isArray(gateway)) {
+ return { kind: "standard" };
+ }
+ const value = (gateway as Record<string, unknown>).serviceTier;
+ if (typeof value !== "string") return { kind: "standard" };
+ return value === "priority" ? { kind: "priority" } : { kind: "custom", value };
+}
diff --git a/packages/eve/src/shared/model-summary.ts b/packages/eve/src/shared/model-summary.ts
new file mode 100644
index 000000000..56659b96b
--- /dev/null
+++ b/packages/eve/src/shared/model-summary.ts
@@ -0,0 +1,16 @@
+/**
+ * The one-line model summary grammar shared by the dev TUI's status line and
+ * the /model menu's Change model hint: `slug@level ↯`. One implementation so
+ * the two surfaces cannot drift.
+ */
+export function formatModelSummary(input: {
+ model: string;
+ /** Authored reasoning level; omitted renders the bare slug. */
+ reasoning?: string;
+ /** The Fast mode marker glyph, present only when the priority tier is on. */
+ fastGlyph?: string;
+}): string {
+ const level = input.reasoning === undefined ? "" : `@${input.reasoning}`;
+ const fast = input.fastGlyph === undefined ? "" : ` ${input.fastGlyph}`;
+ return `${input.model}${level}${fast}`;
+}
diff --git a/packages/eve/src/source-change/agent-config-ast.ts b/packages/eve/src/source-change/agent-config-ast.ts
new file mode 100644
index 000000000..e96183f64
--- /dev/null
+++ b/packages/eve/src/source-change/agent-config-ast.ts
@@ -0,0 +1,156 @@
+import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
+
+/**
+ * The AST plumbing shared by the agent-config source editors: the loose
+ * Rolldown node shapes, the parse-and-locate-`defineAgent({ ... })` pipeline,
+ * and the string-splicing helpers. Editors own their edit policies; this
+ * module owns how an agent config is read.
+ */
+
+export type Program = { readonly body?: readonly AstNode[] };
+
+export type AstNode = {
+ readonly arguments?: readonly AstNode[];
+ readonly callee?: AstNode;
+ readonly computed?: boolean;
+ readonly declaration?: AstNode | null;
+ readonly end?: number;
+ readonly expression?: AstNode | null;
+ readonly key?: AstNode;
+ readonly name?: string;
+ readonly properties?: readonly AstNode[];
+ readonly raw?: string;
+ readonly start?: number;
+ readonly type?: string;
+ readonly value?: AstNode | string | number | boolean | null;
+};
+
+export type ObjectExpression = AstNode & {
+ readonly end: number;
+ readonly properties: readonly AstNode[];
+ readonly start: number;
+ readonly type: "ObjectExpression";
+};
+
+type ParsedSource = Program & {
+ readonly errors?: readonly ParseError[];
+ readonly program?: Program;
+};
+
+type ParseError = {
+ readonly labels?: readonly { readonly start?: number }[];
+ readonly loc?: { readonly line?: number };
+ readonly message?: string;
+ readonly start?: number;
+};
+
+export type ParsedAgentObject =
+ | { readonly kind: "ok"; readonly object: ObjectExpression }
+ | { readonly kind: "bail"; readonly reason: string; readonly line: number };
+
+/** Parses a source and locates the `export default defineAgent({ ... })` object. */
+export async function parseAgentObject(sourceText: string): Promise<ParsedAgentObject> {
+ let parsed: ParsedSource;
+ try {
+ parsed = (await parseWithNitroRolldownAst("agent.ts", sourceText)) as ParsedSource;
+ } catch (error) {
+ const parseError = error as ParseError;
+ return {
+ kind: "bail",
+ reason: `agent.ts does not parse: ${parseError.message ?? "unknown parse error"}`,
+ line: parseErrorLine(sourceText, parseError),
+ };
+ }
+
+ if ((parsed.errors?.length ?? 0) > 0) {
+ const first = parsed.errors?.[0];
+ return {
+ kind: "bail",
+ reason: `agent.ts does not parse: ${first?.message ?? "unknown parse error"}`,
+ line: parseErrorLine(sourceText, first),
+ };
+ }
+
+ const object = findDefineAgentObject(parsed.program ?? parsed);
+ return object === undefined
+ ? { kind: "bail", reason: "no `export default defineAgent({ ... })` call found", line: 1 }
+ : { kind: "ok", object };
+}
+
+/**
+ * The write-guard invariant: an edited source must still parse and still
+ * carry the `defineAgent({ ... })` object. Returns the failure reason, or
+ * undefined when the source is sound. Callers bail instead of writing, so an
+ * editor bug degrades to a "change it by hand" message rather than a broken
+ * agent.ts.
+ */
+export async function checkAgentConfigSource(sourceText: string): Promise<string | undefined> {
+ const parsed = await parseAgentObject(sourceText);
+ return parsed.kind === "bail" ? parsed.reason : undefined;
+}
+
+function findDefineAgentObject(program: Program): ObjectExpression | undefined {
+ for (const statement of program.body ?? []) {
+ if (statement.type !== "ExportDefaultDeclaration" || statement.declaration == null) continue;
+ const call = unwrapExpression(statement.declaration);
+ if (
+ call.type !== "CallExpression" ||
+ call.callee?.type !== "Identifier" ||
+ call.callee.name !== "defineAgent"
+ ) {
+ continue;
+ }
+ const argument = call.arguments?.[0];
+ if (argument === undefined || argument.type === "SpreadElement") continue;
+ const object = unwrapExpression(argument);
+ if (
+ object.type === "ObjectExpression" &&
+ object.start !== undefined &&
+ object.end !== undefined &&
+ object.properties !== undefined
+ ) {
+ return object as ObjectExpression;
+ }
+ }
+ return undefined;
+}
+
+/** Strips `as`, `satisfies`, and parentheses to reach the underlying expression. */
+export function unwrapExpression(expression: AstNode): AstNode {
+ let node = expression;
+ while (
+ node.type === "ParenthesizedExpression" ||
+ node.type === "TSAsExpression" ||
+ node.type === "TSSatisfiesExpression"
+ ) {
+ if (node.expression == null) return node;
+ node = node.expression;
+ }
+ return node;
+}
+
+export function keyMatches(key: AstNode | undefined, name: string): boolean {
+ if (key?.type === "Identifier") return key.name === name;
+ return key?.type === "Literal" && typeof key.value === "string" && key.value === name;
+}
+
+export function isAstNode(value: unknown): value is AstNode {
+ return value !== null && typeof value === "object" && typeof (value as AstNode).type === "string";
+}
+
+export function escapeForQuote(value: string, quote: '"' | "'"): string {
+ return value.replaceAll("\\", "\\\\").replaceAll(quote, `\\${quote}`);
+}
+
+export function lineAt(source: string, offset: number): number {
+ let line = 1;
+ for (let index = 0; index < offset && index < source.length; index += 1) {
+ if (source[index] === "\n") line += 1;
+ }
+ return line;
+}
+
+function parseErrorLine(source: string, error: ParseError | undefined): number {
+ if (typeof error?.loc?.line === "number") return error.loc.line;
+ return lineAt(source, error?.labels?.[0]?.start ?? error?.start ?? 0);
+}
diff --git a/packages/eve/src/source-change/agent-config-string-path.ts b/packages/eve/src/source-change/agent-config-string-path.ts
new file mode 100644
index 000000000..9fa9b5882
--- /dev/null
+++ b/packages/eve/src/source-change/agent-config-string-path.ts
@@ -0,0 +1,232 @@
+import {
+ escapeForQuote,
+ isAstNode,
+ keyMatches,
+ lineAt,
+ parseAgentObject,
+ unwrapExpression,
+ type AstNode,
+ type ObjectExpression,
+} from "./agent-config-ast.js";
+
+export { checkAgentConfigSource } from "./agent-config-ast.js";
+
+type PropertyNode = AstNode & {
+ readonly end: number;
+ readonly start: number;
+ readonly type: "Property";
+};
+
+export type AgentConfigStringPathPatch =
+ | { readonly kind: "set"; readonly value: string }
+ | { readonly kind: "remove"; readonly removable?: (value: string) => boolean };
+
+export type AgentConfigStringPathEdit =
+ | { readonly kind: "applied"; readonly nextSource: string }
+ | { readonly kind: "bail"; readonly reason: string; readonly line: number };
+
+/** Safely applies one literal string leaf below `defineAgent({ ... })`. */
+export async function applyAgentConfigStringPath(
+ sourceText: string,
+ path: readonly [string, ...string[]],
+ patch: AgentConfigStringPathPatch,
+): Promise<AgentConfigStringPathEdit> {
+ const parsed = await parseAgentObject(sourceText);
+ if (parsed.kind === "bail") return parsed;
+
+ const objects: ObjectExpression[] = [parsed.object];
+ const pathProperties: PropertyNode[] = [];
+ let object = parsed.object;
+
+ for (const [index, key] of path.slice(0, -1).entries()) {
+ const found = findProperty(object, key);
+ if (found.kind === "bail") return { ...found, line: lineAt(sourceText, object.start) };
+ if (found.property === undefined) {
+ if (patch.kind === "remove") return { kind: "applied", nextSource: sourceText };
+ const value = nestedObjectSource(path.slice(index + 1), patch.value);
+ return {
+ kind: "applied",
+ nextSource: insertProperty(sourceText, object, key, value),
+ };
+ }
+
+ const value = propertyObjectValue(found.property);
+ if (value === undefined) {
+ return {
+ kind: "bail",
+ reason: `\`${key}\` is not an object literal that eve can edit safely`,
+ line: lineAt(sourceText, found.property.start),
+ };
+ }
+ pathProperties.push(found.property);
+ objects.push(value);
+ object = value;
+ }
+
+ const leaf = path.at(-1)!;
+ const found = findProperty(object, leaf);
+ if (found.kind === "bail") return { ...found, line: lineAt(sourceText, object.start) };
+
+ if (found.property === undefined) {
+ if (patch.kind === "remove") return { kind: "applied", nextSource: sourceText };
+ return {
+ kind: "applied",
+ nextSource: insertProperty(sourceText, object, leaf, JSON.stringify(patch.value)),
+ };
+ }
+
+ const current = propertyStringValue(found.property);
+ if (current === undefined) {
+ return {
+ kind: "bail",
+ reason: `\`${path.join(".")}\` is not a string literal that eve can edit safely`,
+ line: lineAt(sourceText, found.property.start),
+ };
+ }
+
+ if (patch.kind === "set") {
+ if (current.value === patch.value) return { kind: "applied", nextSource: sourceText };
+ const quote = current.raw?.[0] === "'" ? "'" : '"';
+ const replacement = `${quote}${escapeForQuote(patch.value, quote)}${quote}`;
+ return {
+ kind: "applied",
+ nextSource: sourceText.slice(0, current.start) + replacement + sourceText.slice(current.end),
+ };
+ }
+
+ if (patch.removable !== undefined && !patch.removable(current.value)) {
+ return {
+ kind: "bail",
+ reason: `\`${path.join(".")}\` has the custom value ${JSON.stringify(current.value)}`,
+ line: lineAt(sourceText, found.property.start),
+ };
+ }
+
+ let removalProperty = found.property;
+ let containingObject = object;
+ for (let index = objects.length - 1; index > 0; index -= 1) {
+ if (containingObject.properties.length !== 1) break;
+ removalProperty = pathProperties[index - 1]!;
+ containingObject = objects[index - 1]!;
+ }
+ return {
+ kind: "applied",
+ nextSource: removeProperty(sourceText, containingObject, removalProperty),
+ };
+}
+
+function findProperty(
+ object: ObjectExpression,
+ key: string,
+):
+ | { readonly kind: "ok"; readonly property?: PropertyNode }
+ | { readonly kind: "bail"; readonly reason: string } {
+ if (
+ object.properties.some(
+ (property) => property.type === "SpreadElement" || property.computed === true,
+ )
+ ) {
+ return { kind: "bail", reason: `\`${key}\` may be supplied by a spread or computed property` };
+ }
+ const matches = object.properties.filter(
+ (property) =>
+ property.type === "Property" && !property.computed && keyMatches(property.key, key),
+ );
+ if (matches.length > 1) return { kind: "bail", reason: `\`${key}\` is defined more than once` };
+ const match = matches[0];
+ if (match !== undefined && match.start !== undefined && match.end !== undefined) {
+ return { kind: "ok", property: match as PropertyNode };
+ }
+ return { kind: "ok" };
+}
+
+function propertyObjectValue(property: PropertyNode): ObjectExpression | undefined {
+ const raw = property.value;
+ if (!isAstNode(raw)) return undefined;
+ const value = unwrapExpression(raw);
+ return value.type === "ObjectExpression" &&
+ value.start !== undefined &&
+ value.end !== undefined &&
+ value.properties !== undefined
+ ? (value as ObjectExpression)
+ : undefined;
+}
+
+function propertyStringValue(
+ property: PropertyNode,
+):
+ | { readonly start: number; readonly end: number; readonly value: string; readonly raw?: string }
+ | undefined {
+ const raw = property.value;
+ if (!isAstNode(raw)) return undefined;
+ const value = unwrapExpression(raw);
+ if (
+ value.type !== "Literal" ||
+ typeof value.value !== "string" ||
+ value.start === undefined ||
+ value.end === undefined
+ ) {
+ return undefined;
+ }
+ const literal = {
+ start: value.start,
+ end: value.end,
+ value: value.value,
+ };
+ return value.raw === undefined ? literal : { ...literal, raw: value.raw };
+}
+
+function nestedObjectSource(path: readonly string[], value: string): string {
+ let result = JSON.stringify(value);
+ for (const key of [...path].reverse()) result = `{ ${key}: ${result} }`;
+ return result;
+}
+
+function insertProperty(
+ source: string,
+ object: ObjectExpression,
+ key: string,
+ valueSource: string,
+): string {
+ const closeBrace = object.end - 1;
+ const last = object.properties.at(-1);
+ if (last === undefined || last.end === undefined) {
+ return source.slice(0, closeBrace) + ` ${key}: ${valueSource} ` + source.slice(closeBrace);
+ }
+
+ const closingLineStart = source.lastIndexOf("\n", closeBrace - 1) + 1;
+ if (closingLineStart > object.start) {
+ const closeIndent = source.slice(closingLineStart, closeBrace);
+ const propertyIndent = `${closeIndent} `;
+ const gap = source.slice(last.end, closingLineStart);
+ let next = source;
+ if (!gap.includes(",")) next = next.slice(0, last.end) + "," + next.slice(last.end);
+ const adjustedLineStart = closingLineStart + (gap.includes(",") ? 0 : 1);
+ return (
+ next.slice(0, adjustedLineStart) +
+ `${propertyIndent}${key}: ${valueSource},\n` +
+ next.slice(adjustedLineStart)
+ );
+ }
+
+ const gap = source.slice(last.end, closeBrace);
+ const separator = gap.includes(",") ? " " : ", ";
+ return (
+ source.slice(0, closeBrace) + `${separator}${key}: ${valueSource}` + source.slice(closeBrace)
+ );
+}
+
+function removeProperty(source: string, object: ObjectExpression, property: PropertyNode): string {
+ const index = object.properties.indexOf(property);
+ const previous = index > 0 ? object.properties[index - 1] : undefined;
+ const next = index >= 0 ? object.properties[index + 1] : undefined;
+ if (next?.start !== undefined) return source.slice(0, property.start) + source.slice(next.start);
+ if (previous?.end !== undefined) {
+ // The text after the removed span (a trailing comma, whitespace) becomes
+ // the previous property's trailer, which stays valid.
+ return source.slice(0, previous.end) + source.slice(property.end);
+ }
+ // Sole property: empty the braces outright. Slicing out only the property
+ // would leave its trailing comma behind (`{ , }`), which does not parse.
+ return source.slice(0, object.start + 1) + source.slice(object.end - 1);
+}
diff --git a/packages/eve/src/source-change/apply-agent-model-settings.test.ts b/packages/eve/src/source-change/apply-agent-model-settings.test.ts
new file mode 100644
index 000000000..c7ab80661
--- /dev/null
+++ b/packages/eve/src/source-change/apply-agent-model-settings.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it } from "vitest";
+
+import { checkAgentConfigSource } from "./agent-config-string-path.js";
+import { applyAgentModelSettingsToSource, type FieldPatch } from "./apply-agent-model-settings.js";
+
+const keep = { kind: "keep" } as const;
+const remove = { kind: "remove" } as const;
+const set = <T>(value: T): FieldPatch<T> => ({ kind: "set", value });
+
+const SCAFFOLD = `import { defineAgent } from "eve";
+
+export default defineAgent({
+ model: "anthropic/claude-sonnet-5",
+});
+`;
+
+describe("applyAgentModelSettingsToSource", () => {
+ it("applies model, reasoning, and Fast mode in one in-memory edit", async () => {
+ const result = await applyAgentModelSettingsToSource(SCAFFOLD, {
+ model: set("openai/gpt-5.5"),
+ reasoning: set("high"),
+ gatewayServiceTier: set("priority"),
+ });
+
+ expect(result.kind).toBe("applied");
+ if (result.kind !== "applied") return;
+ expect(result.changed).toEqual(["model", "reasoning", "fast-mode"]);
+ expect(result.nextSource).toContain('model: "openai/gpt-5.5"');
+ expect(result.nextSource).toContain('reasoning: "high"');
+ expect(result.nextSource).toContain(
+ 'modelOptions: { providerOptions: { gateway: { serviceTier: "priority" } } }',
+ );
+ });
+
+ it("preserves sibling Gateway and provider options", async () => {
+ const source = `export default defineAgent({
+ model: "a/b",
+ modelOptions: {
+ providerOptions: {
+ gateway: { byok: "anthropic", caching: "auto" },
+ anthropic: { thinking: { type: "adaptive" } },
+ },
+ },
+});
+`;
+ const result = await applyAgentModelSettingsToSource(source, {
+ model: keep,
+ reasoning: keep,
+ gatewayServiceTier: set("priority"),
+ });
+
+ expect(result.kind).toBe("applied");
+ if (result.kind !== "applied") return;
+ expect(result.nextSource).toContain('byok: "anthropic"');
+ expect(result.nextSource).toContain('caching: "auto"');
+ expect(result.nextSource).toContain('anthropic: { thinking: { type: "adaptive" } }');
+ expect(result.nextSource).toContain('serviceTier: "priority"');
+ });
+
+ it("removes provider-default reasoning and only the priority tier", async () => {
+ const source = `export default defineAgent({
+ model: "a/b",
+ reasoning: "high",
+ modelOptions: {
+ providerOptions: {
+ gateway: { byok: "anthropic", serviceTier: "priority" },
+ },
+ },
+});
+`;
+ const result = await applyAgentModelSettingsToSource(source, {
+ model: keep,
+ reasoning: remove,
+ gatewayServiceTier: remove,
+ });
+
+ expect(result.kind).toBe("applied");
+ if (result.kind !== "applied") return;
+ expect(result.nextSource).not.toContain("reasoning:");
+ expect(result.nextSource).not.toContain("serviceTier:");
+ expect(result.nextSource).toContain('byok: "anthropic"');
+ });
+
+ it("prunes wrappers emptied by disabling Fast mode", async () => {
+ const source = `export default defineAgent({
+ model: "a/b",
+ modelOptions: { providerOptions: { gateway: { serviceTier: "priority" } } },
+});
+`;
+ const result = await applyAgentModelSettingsToSource(source, {
+ model: keep,
+ reasoning: keep,
+ gatewayServiceTier: remove,
+ });
+
+ expect(result.kind).toBe("applied");
+ if (result.kind !== "applied") return;
+ expect(result.nextSource).not.toContain("modelOptions");
+ expect(result.nextSource).toContain('model: "a/b"');
+ });
+
+ it("refuses to overwrite a custom service tier", async () => {
+ const source = `export default defineAgent({
+ model: "a/b",
+ modelOptions: { providerOptions: { gateway: { serviceTier: "flex" } } },
+});
+`;
+ const result = await applyAgentModelSettingsToSource(source, {
+ model: keep,
+ reasoning: keep,
+ gatewayServiceTier: remove,
+ });
+
+ expect(result).toMatchObject({ kind: "bail", reason: expect.stringContaining("custom") });
+ });
+
+ it("bails without returning a partial edit for unsafe nested source", async () => {
+ const source = `export default defineAgent({
+ model: "a/b",
+ modelOptions: getModelOptions(),
+});
+`;
+ const result = await applyAgentModelSettingsToSource(source, {
+ model: set("c/d"),
+ reasoning: set("high"),
+ gatewayServiceTier: set("priority"),
+ });
+
+ expect(result).toMatchObject({ kind: "bail" });
+ expect("nextSource" in result).toBe(false);
+ });
+
+ it("refuses explicit settings when a spread can override their value", async () => {
+ const source = `export default defineAgent({
+ model: "a/b",
+ reasoning: "low",
+ ...sharedSettings,
+});
+`;
+ const result = await applyAgentModelSettingsToSource(source, {
+ model: keep,
+ reasoning: set("high"),
+ gatewayServiceTier: keep,
+ });
+
+ expect(result).toMatchObject({ kind: "bail", reason: expect.stringContaining("spread") });
+ expect("nextSource" in result).toBe(false);
+ });
+
+ it("empties the braces when removing a sole property with a trailing comma", async () => {
+ for (const source of [
+ 'export default defineAgent({ reasoning: "high", });\n',
+ 'export default defineAgent({\n reasoning: "high",\n});\n',
+ ]) {
+ const result = await applyAgentModelSettingsToSource(source, {
+ model: keep,
+ reasoning: remove,
+ gatewayServiceTier: keep,
+ });
+
+ expect(result.kind).toBe("applied");
+ if (result.kind !== "applied") return;
+ // Slicing out only the property used to strand its trailing comma as
+ // `defineAgent({ , })` — unparseable source written to agent.ts.
+ expect(result.nextSource).not.toContain(",");
+ await expect(checkAgentConfigSource(result.nextSource)).resolves.toBeUndefined();
+ }
+ });
+
+ it("prunes a sole modelOptions chain without stranding its trailing comma", async () => {
+ const source = `export default defineAgent({
+ modelOptions: {
+ providerOptions: {
+ gateway: { serviceTier: "priority" },
+ },
+ },
+});
+`;
+ const result = await applyAgentModelSettingsToSource(source, {
+ model: keep,
+ reasoning: keep,
+ gatewayServiceTier: remove,
+ });
+
+ expect(result.kind).toBe("applied");
+ if (result.kind !== "applied") return;
+ expect(result.nextSource).not.toContain("modelOptions");
+ await expect(checkAgentConfigSource(result.nextSource)).resolves.toBeUndefined();
+ });
+});
+
+describe("checkAgentConfigSource", () => {
+ it("accepts a sound config and names the failure for a broken one", async () => {
+ await expect(
+ checkAgentConfigSource('export default defineAgent({ model: "a/b" });'),
+ ).resolves.toBeUndefined();
+
+ await expect(checkAgentConfigSource("export default defineAgent({ , });")).resolves.toContain(
+ "parse",
+ );
+
+ await expect(checkAgentConfigSource("const x = 1;")).resolves.toContain("defineAgent");
+ });
+});
diff --git a/packages/eve/src/source-change/apply-agent-model-settings.ts b/packages/eve/src/source-change/apply-agent-model-settings.ts
new file mode 100644
index 000000000..82d61acf1
--- /dev/null
+++ b/packages/eve/src/source-change/apply-agent-model-settings.ts
@@ -0,0 +1,72 @@
+import type { AgentReasoningDefinition } from "#shared/agent-definition.js";
+
+import { applyAgentConfigStringPath } from "./agent-config-string-path.js";
+import { applyModelNameToSource } from "./apply-model-name.js";
+
+export type FieldPatch<T> =
+ | { readonly kind: "keep" }
+ | { readonly kind: "set"; readonly value: T }
+ | { readonly kind: "remove" };
+
+export interface AgentModelSettingsPatch {
+ readonly model: FieldPatch<string>;
+ readonly reasoning: FieldPatch<AgentReasoningDefinition>;
+ readonly gatewayServiceTier: FieldPatch<"priority">;
+}
+
+export type AgentModelSetting = "model" | "reasoning" | "fast-mode";
+
+export type AgentModelSettingsEdit =
+ | {
+ readonly kind: "applied";
+ readonly changed: readonly AgentModelSetting[];
+ readonly nextSource: string;
+ }
+ | { readonly kind: "bail"; readonly reason: string; readonly line: number };
+
+/** Applies every model-setting change in memory; callers own the atomic write. */
+export async function applyAgentModelSettingsToSource(
+ sourceText: string,
+ patch: AgentModelSettingsPatch,
+): Promise<AgentModelSettingsEdit> {
+ let nextSource = sourceText;
+ const changed: AgentModelSetting[] = [];
+
+ if (patch.model.kind === "remove") {
+ return { kind: "bail", reason: "the required `model` property cannot be removed", line: 1 };
+ }
+ if (patch.model.kind === "set") {
+ const edit = await applyModelNameToSource(nextSource, patch.model.value);
+ if (edit.kind === "bail") return edit;
+ if (edit.nextSource !== nextSource) changed.push("model");
+ nextSource = edit.nextSource;
+ }
+
+ if (patch.reasoning.kind !== "keep") {
+ const edit = await applyAgentConfigStringPath(
+ nextSource,
+ ["reasoning"],
+ patch.reasoning.kind === "set"
+ ? { kind: "set", value: patch.reasoning.value }
+ : { kind: "remove" },
+ );
+ if (edit.kind === "bail") return edit;
+ if (edit.nextSource !== nextSource) changed.push("reasoning");
+ nextSource = edit.nextSource;
+ }
+
+ if (patch.gatewayServiceTier.kind !== "keep") {
+ const edit = await applyAgentConfigStringPath(
+ nextSource,
+ ["modelOptions", "providerOptions", "gateway", "serviceTier"],
+ patch.gatewayServiceTier.kind === "set"
+ ? { kind: "set", value: patch.gatewayServiceTier.value }
+ : { kind: "remove", removable: (value) => value === "priority" },
+ );
+ if (edit.kind === "bail") return edit;
+ if (edit.nextSource !== nextSource) changed.push("fast-mode");
+ nextSource = edit.nextSource;
+ }
+
+ return { kind: "applied", changed, nextSource };
+}
diff --git a/packages/eve/src/source-change/apply-model-name.ts b/packages/eve/src/source-change/apply-model-name.ts
index d85a25d42..86473f85a 100644
--- a/packages/eve/src/source-change/apply-model-name.ts
+++ b/packages/eve/src/source-change/apply-model-name.ts
@@ -1,4 +1,13 @@
-import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
+import {
+ escapeForQuote,
+ isAstNode,
+ keyMatches,
+ lineAt,
+ parseAgentObject,
+ unwrapExpression,
+ type AstNode,
+ type ObjectExpression,
+} from "./agent-config-ast.js";
/**
* Outcome of a source-to-source edit attempt. Pure data. On success it carries
@@ -17,45 +26,6 @@ export type SourceEdit =
readonly line: number;
};
-const AGENT_FACTORY = "defineAgent";
-
-type Program = {
- readonly body?: readonly AstNode[];
-};
-
-type AstNode = {
- readonly arguments?: readonly AstNode[];
- readonly callee?: AstNode;
- readonly computed?: boolean;
- readonly declaration?: AstNode | null;
- readonly end?: number;
- readonly expression?: AstNode | null;
- readonly key?: AstNode;
- readonly name?: string;
- readonly properties?: readonly AstNode[];
- readonly raw?: string;
- readonly start?: number;
- readonly type?: string;
- readonly value?: AstNode | string | number | boolean | null;
-};
-
-type ParsedSource = Program & {
- readonly errors?: readonly ParseError[];
- readonly program?: Program;
-};
-
-type ParseError = {
- readonly labels?: readonly { readonly start?: number }[];
- readonly loc?: { readonly line?: number };
- readonly message?: string;
- readonly start?: number;
-};
-
-type ObjectExpression = AstNode & {
- readonly properties: readonly AstNode[];
- readonly type: "ObjectExpression";
-};
-
type StringLiteral = AstNode & {
readonly end: number;
readonly start: number;
@@ -76,29 +46,9 @@ export async function applyModelNameToSource(
sourceText: string,
modelName: string,
): Promise<SourceEdit> {
- const parsed = await parseAgentSource(sourceText);
- if ("kind" in parsed) {
- return parsed;
- }
-
- if ((parsed.errors?.length ?? 0) > 0) {
- const first = parsed.errors?.[0];
- return {
- kind: "bail",
- reason: `agent.ts does not parse: ${first?.message ?? "unknown parse error"}`,
- line: parseErrorLine(sourceText, first),
- };
- }
-
- const program = parsed.program ?? parsed;
- const object = findDefineAgentObject(program, AGENT_FACTORY);
- if (object === undefined) {
- return {
- kind: "bail",
- reason: `no \`export default ${AGENT_FACTORY}({ ... })\` call found`,
- line: 1,
- };
- }
+ const parsed = await parseAgentObject(sourceText);
+ if (parsed.kind === "bail") return parsed;
+ const object = parsed.object;
const literal = findStringLiteralProperty(object, "model");
if (literal === undefined) {
@@ -106,7 +56,7 @@ export async function applyModelNameToSource(
kind: "bail",
reason:
"`model` is absent or is not a string literal (e.g. an env reference, a template, an inlined SDK model, or a defineDynamic() dynamic model)",
- line: lineAt(sourceText, object.start ?? 0),
+ line: lineAt(sourceText, object.start),
};
}
@@ -123,76 +73,12 @@ export async function applyModelNameToSource(
return { kind: "applied", from, to: modelName, nextSource };
}
-async function parseAgentSource(sourceText: string): Promise<ParsedSource | SourceEdit> {
- try {
- return (await parseWithNitroRolldownAst("agent.ts", sourceText)) as ParsedSource;
- } catch (error) {
- const parseError = error as ParseError;
- return {
- kind: "bail",
- reason: `agent.ts does not parse: ${parseError.message ?? "unknown parse error"}`,
- line: parseErrorLine(sourceText, parseError),
- };
- }
-}
-
-/** Strips `as`, `satisfies`, and parentheses to reach the underlying expression. */
-function unwrapExpression(expression: AstNode): AstNode {
- let node: AstNode = expression;
- while (
- node.type === "ParenthesizedExpression" ||
- node.type === "TSAsExpression" ||
- node.type === "TSSatisfiesExpression"
- ) {
- if (node.expression === undefined || node.expression === null) {
- return node;
- }
- node = node.expression;
- }
- return node;
-}
-
-/** Locates the object literal of a top-level `export default factory({ ... })`. */
-function findDefineAgentObject(program: Program, factory: string): ObjectExpression | undefined {
- for (const statement of program.body ?? []) {
- if (statement.type !== "ExportDefaultDeclaration") {
- continue;
- }
- const declaration = statement.declaration;
- if (declaration === undefined || declaration === null) {
- continue;
- }
- if (
- declaration.type !== "CallExpression" &&
- declaration.type !== "ParenthesizedExpression" &&
- declaration.type !== "TSAsExpression" &&
- declaration.type !== "TSSatisfiesExpression"
- ) {
- continue;
- }
- const call = unwrapExpression(declaration);
- if (call.type !== "CallExpression" || !isFactoryCallee(call.callee, factory)) {
- continue;
- }
- const firstArgument = call.arguments?.[0];
- if (firstArgument === undefined || firstArgument.type === "SpreadElement") {
- continue;
- }
- const argument = unwrapExpression(firstArgument);
- if (argument.type === "ObjectExpression") {
- return argument as ObjectExpression;
- }
- }
- return undefined;
-}
-
-function isFactoryCallee(callee: AstNode | undefined, factory: string): boolean {
- return callee?.type === "Identifier" && callee.name === factory;
-}
-
/**
* Returns the string-literal value node for `key`, or undefined when the
* property is missing, spread, computed, or resolves to a non-string value.
+ * Deliberately more permissive than the path editor's lookup: a spread
+ * elsewhere in the object does not block rewriting an explicit `model`
+ * literal, matching the original `/model <slug>` contract.
*/
function findStringLiteralProperty(
object: ObjectExpression,
@@ -220,42 +106,3 @@ function findStringLiteralProperty(
}
return undefined;
}
-
-function keyMatches(key: AstNode | undefined, name: string): boolean {
- if (key === undefined) {
- return false;
- }
- if (key.type === "Identifier") {
- return key.name === name;
- }
- if (key.type === "Literal") {
- return typeof key.value === "string" && key.value === name;
- }
- return false;
-}
-
-function isAstNode(value: unknown): value is AstNode {
- return value !== null && typeof value === "object" && typeof (value as AstNode).type === "string";
-}
-
-function parseErrorLine(source: string, error: ParseError | undefined): number {
- if (typeof error?.loc?.line === "number") {
- return error.loc.line;
- }
- const offset = error?.labels?.[0]?.start ?? error?.start;
- return lineAt(source, offset ?? 0);
-}
-
-function escapeForQuote(value: string, quote: '"' | "'"): string {
- return value.replaceAll("\\", "\\\\").replaceAll(quote, `\\${quote}`);
-}
-
-function lineAt(source: string, offset: number): number {
- let line = 1;
- for (let index = 0; index < offset && index < source.length; index += 1) {
- if (source[index] === "\n") {
- line += 1;
- }
- }
- return line;
-}
diff --git a/packages/eve/src/source-change/static-source-change.integration.test.ts b/packages/eve/src/source-change/static-source-change.integration.test.ts
index 38c3f9756..614410a67 100644
--- a/packages/eve/src/source-change/static-source-change.integration.test.ts
+++ b/packages/eve/src/source-change/static-source-change.integration.test.ts
@@ -70,4 +70,23 @@ describe("createStaticSourceChange.updateModelName", () => {
expect(result.kind).toBe("bail");
});
+
+ it("atomically applies model, reasoning, and Fast mode settings", async () => {
+ const { agentRoot, manifest } = await scaffoldAgent();
+
+ const result = await createStaticSourceChange(manifest).updateModelSettings({
+ model: { kind: "set", value: "openai/gpt-5.5" },
+ reasoning: { kind: "set", value: "high" },
+ gatewayServiceTier: { kind: "set", value: "priority" },
+ });
+
+ expect(result).toEqual({
+ kind: "applied",
+ changed: ["model", "reasoning", "fast-mode"],
+ });
+ const written = await readFile(join(agentRoot, "agent.ts"), "utf8");
+ expect(written).toContain('model: "openai/gpt-5.5"');
+ expect(written).toContain('reasoning: "high"');
+ expect(written).toContain('serviceTier: "priority"');
+ });
});
diff --git a/packages/eve/src/source-change/static-source-change.ts b/packages/eve/src/source-change/static-source-change.ts
index 068f7460e..2d4ff33b2 100644
--- a/packages/eve/src/source-change/static-source-change.ts
+++ b/packages/eve/src/source-change/static-source-change.ts
@@ -2,6 +2,12 @@ import { readFile, rename, writeFile } from "node:fs/promises";
import { join } from "node:path";
import type { AgentSourceManifest } from "#discover/manifest.js";
+import { checkAgentConfigSource } from "#source-change/agent-config-string-path.js";
+import {
+ applyAgentModelSettingsToSource,
+ type AgentModelSetting,
+ type AgentModelSettingsPatch,
+} from "#source-change/apply-agent-model-settings.js";
import { applyModelNameToSource } from "#source-change/apply-model-name.js";
/**
@@ -16,6 +22,14 @@ export type ApplyResult =
readonly at: { readonly logicalPath: string; readonly line: number };
};
+export type ApplyModelSettingsResult =
+ | { readonly kind: "applied"; readonly changed: readonly AgentModelSetting[] }
+ | {
+ readonly kind: "bail";
+ readonly reason: string;
+ readonly at: { readonly logicalPath: string; readonly line: number };
+ };
+
/**
* Central, flat API for applying targeted edits to an agent's authored source.
*
@@ -30,6 +44,8 @@ export interface StaticSourceChange {
* the caller can offer a manual fix.
*/
updateModelName(modelName: string): Promise<ApplyResult>;
+ /** Applies the `/model` draft in one source transform and one atomic rename. */
+ updateModelSettings(patch: AgentModelSettingsPatch): Promise<ApplyModelSettingsResult>;
}
/**
@@ -38,9 +54,41 @@ export interface StaticSourceChange {
export function createStaticSourceChange(manifest: AgentSourceManifest): StaticSourceChange {
return {
updateModelName: (modelName) => updateAgentModelName(manifest, modelName),
+ updateModelSettings: (patch) => updateAgentModelSettings(manifest, patch),
};
}
+async function updateAgentModelSettings(
+ manifest: AgentSourceManifest,
+ patch: AgentModelSettingsPatch,
+): Promise<ApplyModelSettingsResult> {
+ const source = manifest.configModule;
+ if (source === undefined) {
+ return {
+ kind: "bail",
+ reason: "agent has no agent.ts config module to edit",
+ at: { logicalPath: "agent.ts", line: 1 },
+ };
+ }
+
+ const absolutePath = join(manifest.agentRoot, source.logicalPath);
+ const sourceText = await readFile(absolutePath, "utf8");
+ const edit = await applyAgentModelSettingsToSource(sourceText, patch);
+ if (edit.kind === "bail") {
+ return {
+ kind: "bail",
+ reason: edit.reason,
+ at: { logicalPath: source.logicalPath, line: edit.line },
+ };
+ }
+
+ const refused = await editedSourceBail(sourceText, edit.nextSource, source.logicalPath);
+ if (refused !== undefined) return refused;
+
+ await writeSourceIfChanged(absolutePath, sourceText, edit.nextSource);
+ return { kind: "applied", changed: edit.changed };
+}
+
async function updateAgentModelName(
manifest: AgentSourceManifest,
modelName: string,
@@ -66,13 +114,44 @@ async function updateAgentModelName(
};
}
- if (edit.nextSource !== sourceText) {
- // Write atomically (temp + rename) so a crash mid-write can't truncate
- // the user's authored source.
- const temporaryPath = `${absolutePath}.${process.pid}.eve-tmp`;
- await writeFile(temporaryPath, edit.nextSource, "utf8");
- await rename(temporaryPath, absolutePath);
- }
+ const refused = await editedSourceBail(sourceText, edit.nextSource, source.logicalPath);
+ if (refused !== undefined) return refused;
+
+ await writeSourceIfChanged(absolutePath, sourceText, edit.nextSource);
return { kind: "applied", from: edit.from, to: edit.to };
}
+
+async function writeSourceIfChanged(
+ absolutePath: string,
+ sourceText: string,
+ nextSource: string,
+): Promise<void> {
+ if (nextSource === sourceText) return;
+ // Write atomically so a crash cannot truncate the user's authored source.
+ const temporaryPath = `${absolutePath}.${process.pid}.eve-tmp`;
+ await writeFile(temporaryPath, nextSource, "utf8");
+ await rename(temporaryPath, absolutePath);
+}
+
+/**
+ * Refuses an edit whose output no longer parses as an agent config. The
+ * transforms are AST-guided string surgery, so this invariant turns any
+ * editor bug into a bail instead of a broken agent.ts.
+ */
+async function editedSourceBail(
+ sourceText: string,
+ nextSource: string,
+ logicalPath: string,
+): Promise<
+ { kind: "bail"; reason: string; at: { logicalPath: string; line: number } } | undefined
+> {
+ if (nextSource === sourceText) return undefined;
+ const invalid = await checkAgentConfigSource(nextSource);
+ if (invalid === undefined) return undefined;
+ return {
+ kind: "bail",
+ reason: `the edit produced source eve refuses to write (${invalid})`,
+ at: { logicalPath, line: 1 },
+ };
+}
diff --git a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts
index 322dbb654..090508618 100644
--- a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts
+++ b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts
@@ -767,8 +767,11 @@ describe("app runtime dependency tracing", () => {
expect(vercelFunctionsSource).not.toContain("chokidar");
expect(vercelFunctionsSource).not.toContain("[eve:dev]");
expect(vercelFunctionsSource).not.toContain("rollup:reload");
+ // The world-local canary is its config env var, not its error-class
+ // names: the semantic-error catalog legitimately embeds names like
+ // `DataDirAccessError` as matcher strings without bundling any
+ // world-local code.
expect(vercelFunctionsSource).not.toContain("WORKFLOW_LOCAL_DATA_DIR");
- expect(vercelFunctionsSource).not.toContain("DataDirAccessError");
}, 30_000);
it("loads instrumentation runtime dependencies from hosted Vercel output", async () => {
diff --git a/packages/eve/test/tui-client/tui-packed-install-model.ts b/packages/eve/test/tui-client/tui-packed-install-model.ts
index 8bb2a6ebf..70310a608 100644
--- a/packages/eve/test/tui-client/tui-packed-install-model.ts
+++ b/packages/eve/test/tui-client/tui-packed-install-model.ts
@@ -142,7 +142,7 @@ void (async () => {
input.send("\x1b");
await screen.waitForText("Change model", 5_000);
input.send("\x1b");
- await screen.waitForText("/model cancelled.", 5_000);
+ await screen.waitForText("/model dismissed.", 5_000);
await screen.waitForText("❯", 5_000);
input.type("/exit");
diff --git a/packages/eve/test/tui-client/tui-slash-commands.ts b/packages/eve/test/tui-client/tui-slash-commands.ts
index 8adafb263..2c1d6e4f2 100644
--- a/packages/eve/test/tui-client/tui-slash-commands.ts
+++ b/packages/eve/test/tui-client/tui-slash-commands.ts
@@ -134,7 +134,7 @@ async function runLocalChannelsCancellation(): Promise<void> {
input.enter();
await screen.waitForText("Where will you chat with your agent?", 10_000);
input.send("\x1b");
- await screen.waitForText("/channels cancelled.", 5_000);
+ await screen.waitForText("/channels dismissed.", 5_000);
await screen.waitForText("❯", 5_000);
console.log(theme.muted("[tui-slash-commands] local /channels cancelled back to prompt"));
diff --git a/research/anchored-thread-midturn-resume.md b/research/anchored-thread-midturn-resume.md
new file mode 100644
index 000000000..5a5c537b4
--- /dev/null
+++ b/research/anchored-thread-midturn-resume.md
@@ -0,0 +1,68 @@
+---
+issue: https://github.com/vercel/eve/issues/982
+status: proposed
+last_updated: "2026-07-20"
+---
+
+# Anchored threads must resume across the whole turn
+
+A follow-up delivered to an anchored channel thread while the session's
+turn is still running forks a new session instead of resuming, and the
+forked run dies with `HookConflictError` when both runs claim the thread
+token. Any user replying quickly in an anchored thread mid-turn can hit
+this; it surfaced as a deterministic `tui-connection-auth-user` failure
+once a fixture model change moved the smoke's follow-up inside the
+exposure window (bisect-verified on PR #881).
+
+## Cause
+
+The session's delivery hook is one rotating slot.
+
+```
+session start mid-turn (connection auth) park
+ │ │ │
+ ▼ ▼ ▼
+ anchor claimed ──rekey──▶ auth token claimed ──rekey──▶ anchor reclaimed
+ (anchor DISPOSED — thread deliveries
+ now HookNotFound → new session)
+```
+
+- `execution/workflow-entry.ts` claims the anchored thread token before
+ the first turn, so resume works while the session is parked.
+- `execution/turn-control-receiver.ts` rotates the slot to in-turn
+ continuation tokens (`deliveryHook.rekey(...)`), and
+ `execution/session-delivery-hook.ts#rekey` disposes the previous hook
+ once the candidate is claimed. While rotated away, the thread token
+ resolves to nothing: `resumeHook` → `HookNotFoundError` →
+ `RuntimeNoActiveSessionError` → the channel route starts a new
+ session. Both runs later claim the anchor; the loser fails terminally.
+
+## Invariant to establish
+
+A session anchored to a channel thread is resumable by that thread token
+for the session's entire lifetime — parked or mid-turn.
+
+## Directions
+
+1. **Durable anchor, additive continuations.** The anchor hook stays
+ claimed for the session; in-turn continuation tokens become additional
+ armed hooks rather than replacements of the single active slot. The
+ hook state machine already tracks `retired` states for reads — the
+ change is that rotation must not dispose the anchor's claim.
+2. **Attributed fallback on miss.** On `HookNotFoundError` for a token
+ the world can attribute to a live run, enqueue the delivery for that
+ run instead of creating a session. Weaker: keeps the window, moves the
+ failure.
+
+Direction 1 matches the invariant; direction 2 is a mitigation if hook
+multiplicity is costly in the workflow world.
+
+## Repro
+
+With `apps/fixtures/agent-tui-client` on `openai/gpt-5.6-luna` +
+`reasoning: "medium"` (the pre-`8c161c54` fixture):
+
+```sh
+cd packages/eve && pnpm run build:js
+PORT=3210 node test/tui-client/tui-connection-auth-user.ts
+```