// @bun
import {
  ensureChatIntegrationReady
} from "./chunk-bqee3sn0.js";
import {
  filterEvals,
  getLatestRun,
  listRunResults,
  loadEvalsFromDir,
  loadRunResult,
  runEvalSuite,
  saveRunResult,
  startBackendServer,
  startSpanIngestServer,
  stopBackendServer,
  stopSpanIngestServer
} from "./chunk-tn4wz24p.js";
import"./chunk-ezj5n8ct.js";
import"./chunk-dnf15380.js";
import {
  buildDevServerHeaders,
  getDevServerUrl
} from "./chunk-91ams3v9.js";
import"./chunk-myhnsbcs.js";
import"./chunk-nkq9jxh8.js";
import"./chunk-gat1vdwz.js";
import"./chunk-1kgmzwze.js";
import {
  setServerConfig
} from "./chunk-81b1nyw9.js";
import"./chunk-sb6ft3r2.js";
import"./chunk-4wmnzrst.js";
import"./chunk-rkjpw96h.js";
import"./chunk-62hm2spv.js";
import {
  ensureJsonOnlyFormat
} from "./chunk-5zqmmchg.js";
import"./chunk-fr1k79kd.js";
import"./chunk-tefbm840.js";
import"./chunk-bexyahs9.js";
import"./chunk-7zvmmxnc.js";
import {
  telemetry_default
} from "./chunk-c18d2qwm.js";
import {
  getAdkVersion
} from "./chunk-p4n31dgt.js";
import {
  resolveCommandContext
} from "./chunk-2jcqy5j6.js";
import"./chunk-9e2nksab.js";
import"./chunk-m2h26j5f.js";
import"./chunk-8gqzjqmb.js";
import {
  findAgentRootOrFail
} from "./chunk-6fad0ts7.js";
import {
  createCliLogger
} from "./chunk-t993tmz7.js";
import"./chunk-px7fts59.js";
import {
  AdkError,
  AgentProject,
  getChatClient
} from "./chunk-7krp2mgz.js";
import"./chunk-np5wcwfv.js";
import"./chunk-je8v6rhj.js";
import"./chunk-6w0knnta.js";
import"./chunk-w15xmtkn.js";
import"./chunk-3sd5p4qp.js";
import"./chunk-nh2akp42.js";
import"./chunk-kat1bv74.js";
import"./chunk-2a5b6azq.js";
import"./chunk-s8cp3qe6.js";
import"./chunk-fv5teh9w.js";
import"./chunk-8ab2w9a1.js";
import {
  Uk
} from "./chunk-3xrpxgq4.js";
import"./chunk-w346ejn9.js";
import"./chunk-n8gath4k.js";
import"./chunk-v3ens42y.js";
import"./chunk-8839jtgk.js";
import"./chunk-s2akeqpw.js";
import"./chunk-6771vrjp.js";
import"./chunk-g8mm42v1.js";
import"./chunk-0q5d80bn.js";
import"./chunk-300xaact.js";
import"./chunk-b8c41yvb.js";
import"./chunk-jsqe5am4.js";
import"./chunk-m4c14gcg.js";
import"./chunk-gspjbr79.js";
import"./chunk-wesykvkp.js";
import"./chunk-gzj56z73.js";
import {
  __require
} from "./chunk-dhs2bg35.js";

// src/commands/adk-evals.ts
import path from "path";
var INDENT = "  ";
function ansi(color, s) {
  const codes = {
    gray: "90",
    red: "31",
    green: "32",
    yellow: "33",
    blue: "34",
    cyan: "36"
  };
  const code = codes[color];
  if (!code)
    return s;
  return `\x1B[${code}m${s}\x1B[0m`;
}
function ansiBold(s) {
  return `\x1B[1m${s}\x1B[22m`;
}
function ansiBoldColor(color, s) {
  return ansiBold(ansi(color, s));
}
var icons = {
  pass: ansi("green", "\u2713"),
  fail: ansi("red", "\u2717"),
  error: ansi("red", "\u26A0"),
  run: ansi("cyan", "\u25CF"),
  dot: ansi("gray", "\xB7")
};
function dim(s) {
  return ansi("gray", s);
}
function duration(ms) {
  if (ms < 1000)
    return `${ms}ms`;
  return `${(ms / 1000).toFixed(1)}s`;
}
function truncate(s, max) {
  const oneLine = s.replace(/\n/g, " ").trim();
  if (oneLine.length <= max)
    return oneLine;
  return oneLine.slice(0, max - 1) + "\u2026";
}
function assertionSummary(report) {
  const turnTotal = report.turns.reduce((n, t) => n + t.assertions.length, 0);
  const turnPassed = report.turns.reduce((n, t) => n + t.assertions.filter((a) => a.pass).length, 0);
  const outcomeTotal = report.outcomeAssertions?.length || 0;
  const outcomePassed = report.outcomeAssertions?.filter((a) => a.pass).length || 0;
  const total = turnTotal + outcomeTotal;
  const passed = turnPassed + outcomePassed;
  return { total, passed, failed: total - passed };
}
function turnSummaryIcons(turns) {
  return turns.map((t) => t.pass ? icons.pass : icons.fail).join(" ");
}
function bar(passed, total, width = 30) {
  if (total === 0)
    return "";
  const filled = Math.round(passed / total * width);
  const empty = width - filled;
  const pct = Math.round(passed / total * 100);
  const color = pct === 100 ? "green" : pct >= 80 ? "yellow" : "red";
  return ansi(color, "\u2501".repeat(filled)) + dim("\u2501".repeat(empty)) + ` ${pct}%`;
}
function createSpinner(text) {
  const spinnerLogger = createCliLogger();
  const frames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
  let i = 0;
  let currentText = text;
  const clearLine = () => spinnerLogger.stdout(`\r\x1B[2K`);
  const tick = () => {
    clearLine();
    spinnerLogger.stdout(`\r${INDENT}${ansi("cyan", frames[i % frames.length])} ${currentText}`);
    i++;
  };
  let interval = setInterval(tick, 80);
  return {
    update(next) {
      currentText = next;
    },
    stop(result) {
      if (interval)
        clearInterval(interval);
      interval = null;
      clearLine();
      spinnerLogger.stdout(`\r${INDENT}${result}
`);
    },
    printAbove(line) {
      if (interval)
        clearInterval(interval);
      clearLine();
      spinnerLogger.stdout(`${line}
`);
      i = 0;
      interval = setInterval(tick, 80);
    }
  };
}
function toEvalRunnerCredentials(credentials) {
  return {
    token: credentials.token,
    apiUrl: credentials.apiUrl,
    botId: credentials.devBotId,
    workspaceId: credentials.workspaceId
  };
}
function createDevServerClient(credentials) {
  return new Uk({
    token: credentials.token,
    apiUrl: credentials.apiUrl,
    workspaceId: credentials.workspaceId,
    botId: credentials.devBotId,
    headers: {
      "x-multiple-integrations": "true"
    }
  });
}
function isLocalUrl(url) {
  try {
    const host = new URL(url).hostname;
    return host === "localhost" || host === "127.0.0.1" || host === "::1";
  } catch {
    return false;
  }
}
async function isDevServerRunning(serverUrl, headers) {
  try {
    const res = await fetch(`${serverUrl}/api/health`, {
      headers,
      signal: AbortSignal.timeout(2000)
    });
    return res.ok;
  } catch {
    return false;
  }
}
async function getCredentialsFromDevServer(serverUrl, headers) {
  const res = await fetch(`${serverUrl}/api/config`, {
    headers
  });
  if (!res.ok) {
    throw new AdkError({
      code: "DEV_SERVER_DOWN",
      message: `Dev server not responding at ${serverUrl}. Is "adk dev" running?`,
      expected: true
    });
  }
  const config = await res.json();
  const { token, devBotId, apiUrl } = config.credentials || {};
  if (!token || !devBotId) {
    throw new AdkError({
      code: "MISSING_CREDENTIALS",
      message: "Missing credentials from dev server config.",
      expected: true
    });
  }
  return { token, devBotId, apiUrl: apiUrl || "https://api.botpress.cloud" };
}
async function ensureDevServer(serverUrl, agentRoot) {
  const noop = () => {};
  const headers = buildDevServerHeaders(agentRoot);
  if (await isDevServerRunning(serverUrl, headers)) {
    const credentials2 = await getCredentialsFromDevServer(serverUrl, headers);
    return { credentials: credentials2, serverUrl, devServerHeaders: headers, cleanup: noop, lightweight: false };
  }
  if (!isLocalUrl(serverUrl)) {
    throw new AdkError({
      code: "DEV_SERVER_DOWN",
      message: `Dev server not responding at ${serverUrl}. Is "adk dev" running?`,
      expected: true
    });
  }
  const context = await resolveCommandContext({
    cwd: agentRoot,
    target: "dev",
    require: ["project", "credentials", "workspace", "bot"]
  });
  const project = context.project;
  const devId = context.botId;
  const credentials = context.credentials;
  if (!credentials.token) {
    throw new AdkError({
      code: "AUTH_REQUIRED",
      message: "No authentication token found. Run `adk login` first.",
      expected: true
    });
  }
  const backend = startBackendServer(agentRoot);
  startSpanIngestServer();
  setServerConfig({
    port: backend.port,
    agentPath: agentRoot,
    project,
    adkVersion: getAdkVersion(),
    credentials: {
      token: credentials.token,
      apiUrl: credentials.apiUrl,
      workspaceId: credentials.workspaceId,
      devBotId: devId
    }
  });
  const devCredentials = {
    token: credentials.token,
    devBotId: devId,
    apiUrl: credentials.apiUrl || "https://api.botpress.cloud",
    workspaceId: credentials.workspaceId
  };
  return {
    credentials: devCredentials,
    serverUrl: `http://127.0.0.1:${backend.port}`,
    devServerHeaders: {},
    cleanup: () => {
      stopSpanIngestServer();
      stopBackendServer();
    },
    lightweight: true
  };
}
function renderEvalResult(report, _verbose) {
  const { total, passed } = assertionSummary(report);
  if (report.error) {
    return `${icons.error} ${ansiBold(report.name)}  ${dim(duration(report.duration))}  ${ansi("red", `ERROR: ${report.error}`)}`;
  }
  const status = report.pass ? icons.pass : icons.fail;
  const name = report.pass ? ansiBold(report.name) : ansiBoldColor("red", report.name);
  const assertText = total > 0 ? dim(`${passed}/${total} assertions`) : dim("no assertions");
  const turns = report.turns.length > 1 ? `  ${dim("turns:")} ${turnSummaryIcons(report.turns)}` : "";
  return `${status} ${name}  ${dim(duration(report.duration))}  ${assertText}${turns}`;
}
function renderOutcomeAssertions(report) {
  if (!report.outcomeAssertions?.length)
    return [];
  const lines = ["", `${INDENT}${INDENT}${dim("Outcome assertions:")}`];
  for (const a of report.outcomeAssertions) {
    if (a.pass) {
      lines.push(`${INDENT}${INDENT}  ${icons.pass} ${dim(a.assertion)}`);
    } else {
      lines.push(`${INDENT}${INDENT}  ${icons.fail} ${ansi("red", a.assertion)}`);
      lines.push(`${INDENT}${INDENT}    ${dim("expected:")} ${a.expected}`);
      lines.push(`${INDENT}${INDENT}    ${dim("actual:")}   ${a.actual}`);
    }
  }
  return lines;
}
function renderFailureDetails(report) {
  const lines = [];
  for (const turn of report.turns) {
    const turnLabel = report.turns.length > 1 ? dim(`Turn ${turn.turnNumber}: `) : "";
    const turnStatus = turn.pass ? `${turnLabel}${icons.pass} ${dim("passed")}` : `${turnLabel}${icons.fail} ${ansi("red", "failed")}`;
    lines.push(`${INDENT}${INDENT}${turnStatus}`);
    if (!turn.pass) {
      lines.push(`${INDENT}${INDENT}${dim("User:")} ${truncate(turn.userMessage, 80)}`);
      lines.push(`${INDENT}${INDENT}${dim("Bot:")}  ${truncate(turn.botResponse, 80)}`);
      lines.push("");
      for (const a of turn.assertions) {
        if (a.pass) {
          lines.push(`${INDENT}${INDENT}  ${icons.pass} ${dim(a.assertion)}`);
        } else {
          lines.push(`${INDENT}${INDENT}  ${icons.fail} ${ansi("red", a.assertion)}`);
          lines.push(`${INDENT}${INDENT}    ${dim("expected:")} ${a.expected}`);
          lines.push(`${INDENT}${INDENT}    ${dim("actual:")}   ${a.actual}`);
        }
      }
    }
  }
  lines.push(...renderOutcomeAssertions(report));
  return lines.join(`
`);
}
function renderSingleTurn(turn, isMultiTurn) {
  const lines = [];
  const turnTime = dim(duration(turn.botDuration + turn.evalDuration));
  if (isMultiTurn) {
    lines.push(`${INDENT}${INDENT}${dim(`Turn ${turn.turnNumber}`)}  ${turnTime}`);
  }
  lines.push(`${INDENT}${INDENT}${dim("User:")} ${truncate(turn.userMessage, 80)}`);
  lines.push(`${INDENT}${INDENT}${dim("Bot:")}  ${truncate(turn.botResponse, 80)}`);
  for (const a of turn.assertions) {
    if (a.pass) {
      lines.push(`${INDENT}${INDENT}  ${icons.pass} ${dim(a.assertion)}`);
    } else {
      lines.push(`${INDENT}${INDENT}  ${icons.fail} ${ansi("red", a.assertion)}`);
      lines.push(`${INDENT}${INDENT}    ${dim("expected:")} ${a.expected}`);
      lines.push(`${INDENT}${INDENT}    ${dim("actual:")}   ${a.actual}`);
    }
  }
  return lines;
}
function renderVerboseDetails(report) {
  const lines = [];
  const isMulti = report.turns.length > 1;
  for (const turn of report.turns) {
    lines.push(...renderSingleTurn(turn, isMulti));
    if (turn !== report.turns[report.turns.length - 1])
      lines.push("");
  }
  lines.push(...renderOutcomeAssertions(report));
  return lines.join(`
`);
}
function renderSuiteSummary(reports) {
  const total = reports.length;
  const passed = reports.filter((r) => r.pass).length;
  const failed = total - passed;
  const totalTime = reports.reduce((t, r) => t + r.duration, 0);
  const totalAssertions = reports.reduce((n, r) => {
    const turnAssertions = r.turns.reduce((tn, t) => tn + t.assertions.length, 0);
    const outcomeCount = r.outcomeAssertions?.length || 0;
    return n + turnAssertions + outcomeCount;
  }, 0);
  const passedAssertions = reports.reduce((n, r) => {
    const turnPassed = r.turns.reduce((tn, t) => tn + t.assertions.filter((a) => a.pass).length, 0);
    const outcomePassed = r.outcomeAssertions?.filter((a) => a.pass).length || 0;
    return n + turnPassed + outcomePassed;
  }, 0);
  const lines = [];
  lines.push("");
  lines.push(`${INDENT}${bar(passed, total)}`);
  lines.push("");
  const evalSummary = failed > 0 ? `${ansiBoldColor("green", String(passed))} passed ${dim("/")} ${ansiBoldColor("red", String(failed))} failed` : ansiBoldColor("green", `${passed} passed`);
  const assertSummary = totalAssertions > 0 ? dim(`${passedAssertions}/${totalAssertions} assertions`) : "";
  lines.push(`${INDENT}${ansiBold("Evals:")}       ${evalSummary} ${dim("of")} ${total}`);
  if (totalAssertions > 0) {
    lines.push(`${INDENT}${ansiBold("Assertions:")}  ${assertSummary}`);
  }
  lines.push(`${INDENT}${ansiBold("Duration:")}    ${dim(duration(totalTime))}`);
  return lines.join(`
`);
}
function renderRunSummaryRow(run, index) {
  const date = new Date(run.timestamp);
  const dateStr = date.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit"
  });
  const status = run.failed > 0 ? ansi("red", `${run.failed} failed`) : run.total > 0 ? ansi("green", "all passed") : dim("empty");
  const idShort = run.id.slice(0, 8);
  return `${INDENT}${dim(`${index + 1}.`)} ${ansiBold(idShort)}  ${dim(dateStr)}  ${status}  ${dim(`${run.passed}/${run.total}`)}  ${dim(duration(run.duration))}`;
}
function renderRunDetail(run, verbose) {
  const lines = [];
  lines.push("");
  lines.push(`${INDENT}${ansiBold("Run")} ${run.id}`);
  lines.push(`${INDENT}${dim(new Date(run.timestamp).toLocaleString())}`);
  lines.push("");
  for (const report of run.evals) {
    lines.push(`${INDENT}${renderEvalResult(report, verbose)}`);
    if (!report.pass && !report.error) {
      lines.push(renderFailureDetails(report));
      lines.push("");
    } else if (verbose && !report.error) {
      lines.push(renderVerboseDetails(report));
      lines.push("");
    }
  }
  lines.push(renderSuiteSummary(run.evals));
  lines.push("");
  return lines.join(`
`);
}
async function adkEvalsRun(name, opts) {
  ensureJsonOnlyFormat(opts.format);
  const logger = createCliLogger({ format: opts.format });
  const serverUrl = opts.server || getDevServerUrl();
  const agentRoot = await findAgentRootOrFail(process.cwd());
  const evalsDir = path.join(agentRoot, "evals");
  const project = await AgentProject.load(agentRoot);
  const botEvalOptions = {
    idleTimeout: project.config?.evals?.idleTimeout,
    judgePassThreshold: project.config?.evals?.judgePassThreshold,
    judgeModel: opts.judgeModel ?? project.config?.evals?.judgeModel
  };
  let evals = await loadEvalsFromDir(evalsDir);
  if (evals.length === 0) {
    logger.warn(`No eval files found in ${evalsDir}/`).result({ success: false, error: `No eval files found in ${evalsDir}/` });
    process.exit(0);
  }
  const filter = {};
  if (name)
    filter.names = [name];
  if (opts.tag)
    filter.tags = [opts.tag];
  if (opts.type)
    filter.type = opts.type;
  evals = filterEvals(evals, filter);
  if (evals.length === 0) {
    const message = name ? `No eval found with name "${name}"` : "No evals match the given filters.";
    if (name) {
      logger.error(message).result({ success: false, error: message });
    } else {
      logger.warn(message).result({ success: false, error: message });
    }
    process.exit(1);
  }
  if (opts.format === "json") {
    let server2;
    try {
      server2 = await ensureDevServer(serverUrl, agentRoot);
    } catch (err) {
      logger.error(err.message).result({ success: false, error: err.message });
      process.exit(1);
    }
    try {
      const jsonPrompt = async () => {
        throw new AdkError({
          code: "EVAL_RUN_FAILED",
          message: [
            "The `chat` integration is not installed on this bot \u2014 `adk evals` requires it.",
            "",
            "To fix:",
            "  1. Install it:    adk add chat",
            "  2. Redeploy:      adk dev   (or: adk deploy)"
          ].join(`
`)
        });
      };
      await ensureChatIntegrationReady(agentRoot, server2.credentials.devBotId, {
        promptForInstall: jsonPrompt,
        project,
        client: createDevServerClient(server2.credentials)
      });
    } catch (err) {
      logger.error(err.message).result({ success: false, error: err.message });
      server2.cleanup();
      process.exit(1);
    }
    try {
      const config = {
        credentials: toEvalRunnerCredentials(server2.credentials),
        agentPath: agentRoot,
        devServerUrl: server2.serverUrl,
        devServerHeaders: server2.devServerHeaders,
        chatClient: getChatClient(),
        evalOptions: botEvalOptions,
        onException: (error, properties) => telemetry_default.captureException(error, properties)
      };
      const report = await runEvalSuite(config, filter);
      try {
        saveRunResult(agentRoot, report);
      } catch {}
      logger.info("Eval suite completed").result(report);
      process.exit(report.evals.every((r) => r.pass) ? 0 : 1);
    } finally {
      server2.cleanup();
    }
  }
  logger.newline();
  logger.info(`${INDENT}${ansiBold("adk evals")} ${dim(`running ${evals.length} eval${evals.length === 1 ? "" : "s"}`)}`);
  logger.newline();
  const spinner = createSpinner(`Connecting to dev server at ${serverUrl}...`);
  let server;
  try {
    server = await ensureDevServer(serverUrl, agentRoot);
    if (server.lightweight) {
      spinner.stop(`${icons.pass} ${dim("Lightweight server started (no running adk dev detected)")}`);
    } else {
      spinner.stop(`${icons.pass} ${dim("Connected to dev server")}`);
    }
  } catch (err) {
    spinner.stop(`${icons.error} ${ansi("red", `Failed to connect: ${err.message}`)}`);
    process.exit(1);
  }
  const chatSpinner = createSpinner("Checking chat integration...");
  let promptShown = false;
  try {
    const interactivePrompt = async (message) => {
      chatSpinner.stop(`${icons.run} ${dim("Chat integration not found")}`);
      promptShown = true;
      const { createInterface } = await import("readline/promises");
      const rl = createInterface({ input: process.stdin, output: process.stderr });
      try {
        const answer = await rl.question(`${INDENT}${message}`);
        const normalized = answer.trim().toLowerCase();
        return normalized === "y" || normalized === "yes";
      } finally {
        rl.close();
      }
    };
    const chatResult = await ensureChatIntegrationReady(agentRoot, server.credentials.devBotId, {
      promptForInstall: interactivePrompt,
      project,
      client: createDevServerClient(server.credentials)
    });
    if (promptShown) {
      logger.info(`${INDENT}${icons.pass} ${dim("Chat integration installed and enabled")}`);
    } else if (chatResult.syncedToBot) {
      chatSpinner.stop(`${icons.pass} ${dim("Chat integration synced")}`);
    } else {
      chatSpinner.stop(`${icons.pass} ${dim("Chat integration ready")}`);
    }
  } catch (err) {
    if (!promptShown) {
      chatSpinner.stop(`${icons.error} ${ansi("red", err.message)}`);
    } else {
      logger.error(`${INDENT}${icons.error} ${ansi("red", err.message)}`);
    }
    server.cleanup();
    process.exit(1);
  }
  logger.newline();
  try {
    const reports = [];
    let currentSpinner = null;
    const config = {
      credentials: toEvalRunnerCredentials(server.credentials),
      agentPath: agentRoot,
      devServerUrl: server.serverUrl,
      devServerHeaders: server.devServerHeaders,
      chatClient: getChatClient(),
      evalOptions: botEvalOptions,
      logger: {
        info: (msg) => logger.info(`${INDENT}${icons.dot} ${dim(msg)}`),
        warn: (msg) => logger.warn(`${INDENT}${icons.error} ${msg}`),
        error: (msg) => logger.error(`${INDENT}${icons.error} ${msg}`)
      },
      onException: (error, properties) => telemetry_default.captureException(error, properties),
      onProgress: (event) => {
        switch (event.type) {
          case "eval_start": {
            if (event.index > 0) {
              const cols = process.stdout.columns || 80;
              logger.info(`${INDENT}${dim("\u2500".repeat(Math.max(cols - INDENT.length, 20)))}`);
              logger.newline();
            }
            const turnCount = event.totalTurns;
            currentSpinner = createSpinner(`${ansiBold(event.evalName)} ${dim(`(${turnCount} turn${turnCount === 1 ? "" : "s"})`)}`);
            break;
          }
          case "turn_start": {
            if (currentSpinner && event.totalTurns > 1) {
              currentSpinner.update(`${ansiBold(event.evalName)} ${dim(`(turn ${event.turnNumber}/${event.totalTurns})`)}`);
            }
            break;
          }
          case "turn_complete": {
            if (currentSpinner && opts.verbose) {
              const lines = renderSingleTurn(event.turnReport, event.totalTurns > 1);
              currentSpinner.printAbove(lines.join(`
`));
            }
            break;
          }
          case "eval_complete": {
            const report = event.report;
            reports.push(report);
            if (currentSpinner) {
              currentSpinner.stop(renderEvalResult(report, !!opts.verbose));
            }
            if (opts.verbose && !report.error) {
              const outcomeLines = renderOutcomeAssertions(report);
              if (outcomeLines.length > 0) {
                logger.info(outcomeLines.join(`
`));
              }
              logger.newline();
            } else if (!report.pass && !report.error) {
              logger.info(renderFailureDetails(report));
              logger.newline();
            }
            break;
          }
        }
      }
    };
    const suiteReport = await runEvalSuite(config, filter);
    try {
      saveRunResult(agentRoot, suiteReport);
    } catch {}
    logger.info(renderSuiteSummary(reports));
    logger.newline();
    if (server.lightweight) {
      logger.info(`${INDENT}${icons.pass} ${dim("Lightweight server stopped")}`);
      logger.newline();
      logger.info(`${INDENT}To inspect results in a browser, run: adk dev`, "gray");
      logger.info(`${INDENT}To view this run in the terminal:    adk evals runs ${suiteReport.id}`, "gray");
      logger.newline();
    }
    process.exit(suiteReport.evals.every((r) => r.pass) ? 0 : 1);
  } finally {
    server.cleanup();
  }
}
async function adkEvalsRuns(runId, opts) {
  ensureJsonOnlyFormat(opts.format);
  const logger = createCliLogger({ format: opts.format });
  const agentRoot = await findAgentRootOrFail(process.cwd());
  if (opts.latest) {
    const run = getLatestRun(agentRoot);
    if (!run) {
      logger.warn("No eval runs found.");
      process.exit(0);
    }
    logger.info(renderRunDetail(run, !!opts.verbose)).result(run);
    return;
  }
  if (runId) {
    const run = loadRunResult(agentRoot, runId);
    if (!run) {
      logger.error(`No run found matching "${runId}"`);
      process.exit(1);
    }
    logger.info(renderRunDetail(run, !!opts.verbose)).result(run);
    return;
  }
  const limit = parseInt(opts.limit || "10");
  const runs = listRunResults(agentRoot, limit);
  if (runs.length === 0) {
    logger.warn("No eval runs found. Run `adk evals` to create one.");
    process.exit(0);
  }
  const summaries = runs.map((r) => ({
    id: r.id,
    timestamp: r.timestamp,
    passed: r.passed,
    failed: r.failed,
    total: r.total,
    duration: r.duration
  }));
  logger.info(`${INDENT}${ansiBold("Eval Runs")} ${dim(`(${runs.length} most recent)`)}`).result(summaries);
  logger.newline();
  for (let i = 0;i < runs.length; i++) {
    logger.info(renderRunSummaryRow(runs[i], i));
  }
  logger.newline();
  logger.info(`${INDENT}Run \`adk evals runs <id>\` to see details, or \`adk evals runs --latest\` for the latest.`, "gray");
  logger.newline();
}
export {
  adkEvalsRuns,
  adkEvalsRun
};
