#!/usr/bin/env node
import {
  buildOpenApi,
  handleVersion,
  runRpcBatch,
  runRpcOnce,
  startServerAsync
} from "./chunk-FO7HEH76.js";
import {
  runRolloutReleaseCli
} from "./chunk-IPYXE555.js";
import "./chunk-MAX3TN3C.js";
import "./chunk-J5SQWP6Y.js";
import "./chunk-WS3NZZQQ.js";
import "./chunk-VI2UW6B6.js";
import "./chunk-PC4UYEBM.js";
import "./chunk-ONWEPEDO.js";
import "./chunk-PZ5AY32C.js";

// src/cli.ts
import { writeFileSync } from "fs";

// src/cli-config.ts
function resolveCliLlmConfig(env = process.env) {
  const explicitBaseUrl = nonEmpty(env.AGENT_EVAL_LLM_BASE_URL);
  const explicitApiKey = nonEmpty(env.AGENT_EVAL_LLM_API_KEY);
  const openAiApiKey = nonEmpty(env.OPENAI_API_KEY);
  const tangleApiKey = nonEmpty(env.TANGLE_API_KEY);
  const baseUrl = explicitBaseUrl ?? nonEmpty(env.OPENAI_BASE_URL) ?? nonEmpty(env.TANGLE_ROUTER_URL) ?? (openAiApiKey ? "https://api.openai.com/v1" : void 0) ?? (tangleApiKey ? "https://router.tangle.tools/v1" : void 0);
  const apiKey = explicitApiKey ?? openAiApiKey ?? tangleApiKey;
  const model = nonEmpty(env.AGENT_EVAL_LLM_MODEL) ?? nonEmpty(env.OPENAI_MODEL) ?? nonEmpty(env.TANGLE_MODEL);
  const client = baseUrl || apiKey ? { ...baseUrl ? { baseUrl } : {}, ...apiKey ? { apiKey } : {} } : void 0;
  return { ...client ? { client } : {}, ...model ? { model } : {} };
}
function nonEmpty(value) {
  const trimmed = value?.trim();
  return trimmed ? trimmed : void 0;
}

// src/cli.ts
function parseArgs(argv) {
  const [command, ...rest] = argv;
  const positional = [];
  const flags = {};
  for (let i = 0; i < rest.length; i++) {
    const tok = rest[i];
    if (tok.startsWith("--")) {
      const raw = tok.slice(2);
      const equalsAt = raw.indexOf("=");
      if (equalsAt >= 0) {
        flags[raw.slice(0, equalsAt)] = raw.slice(equalsAt + 1);
        continue;
      }
      const key = raw;
      if (key === "help") {
        flags[key] = "true";
        continue;
      }
      const next = rest[i + 1];
      if (next != null && !next.startsWith("--")) {
        flags[key] = next;
        i++;
      } else {
        flags[key] = "true";
      }
    } else if (tok === "-h") {
      flags.help = "true";
    } else {
      positional.push(tok);
    }
  }
  return { command: command ?? "help", positional, flags };
}
var HELP = `agent-eval: evaluation RPC and HTTP server.

Commands:
  serve [--port 5005] [--host 127.0.0.1]
        Start the HTTP server. POST /v1/judge, GET /v1/rubrics, GET /v1/version, GET /openapi.json.
  rpc <method>
        Read one JSON object from stdin (the params for <method>), write one
        JSON object to stdout. Methods: judge, listRubrics, version.
  rpc-batch <method>
        Like 'rpc' but JSONL in / JSONL out.
  openapi [--out openapi.json]
        Write the OpenAPI 3.1 spec.
  rollout-release <ledger.jsonl...> --out <dir> [--formats sft,verifiers,rft,raw] [--include-proposers] [--push <org/name>]
        Build a HuggingFace-ready dataset dir from tangle.rollout.v1 ledgers:
        validate, fail-closed split filter, scrub, export formats + card.
  version
        Print server + wire-protocol version JSON.

Judge provider:
  Set AGENT_EVAL_LLM_BASE_URL, AGENT_EVAL_LLM_API_KEY, and AGENT_EVAL_LLM_MODEL.
  OPENAI_* and TANGLE_* equivalents are also accepted.

Without arguments, prints this help.`;
async function main() {
  const { command, positional, flags } = parseArgs(process.argv.slice(2));
  assertKnownFlags(command, flags);
  if (flags.help === "true") {
    process.stdout.write(`${HELP}
`);
    return 0;
  }
  switch (command) {
    case "serve": {
      const port = parsePort(flags.port ?? "5005");
      const host = flags.host ?? "127.0.0.1";
      const llm = resolveCliLlmConfig();
      const { server } = await startServerAsync({
        port,
        host,
        llm: llm.client,
        judgeModel: llm.model,
        llmRouteRequirements: { requireExplicitBaseUrl: true }
      });
      const shutdown = (sig) => {
        console.log(`[agent-eval] received ${sig}, shutting down`);
        server.close(() => process.exit(0));
        setTimeout(() => process.exit(1), 5e3).unref();
      };
      process.on("SIGINT", () => shutdown("SIGINT"));
      process.on("SIGTERM", () => shutdown("SIGTERM"));
      await new Promise(() => {
      });
      return 0;
    }
    case "rpc": {
      const [method] = positional;
      const llm = resolveCliLlmConfig();
      return await runRpcOnce(method, {
        llm: llm.client,
        judgeModel: llm.model,
        llmRouteRequirements: { requireExplicitBaseUrl: true }
      });
    }
    case "rpc-batch": {
      const [method] = positional;
      const llm = resolveCliLlmConfig();
      return await runRpcBatch(method, {
        llm: llm.client,
        judgeModel: llm.model,
        llmRouteRequirements: { requireExplicitBaseUrl: true }
      });
    }
    case "openapi": {
      const out = flags.out ?? "openapi.json";
      const spec = buildOpenApi(handleVersion().version);
      writeFileSync(out, `${JSON.stringify(spec, null, 2)}
`, "utf-8");
      console.log(`[agent-eval] wrote OpenAPI 3.1 spec to ${out}`);
      return 0;
    }
    case "rollout-release": {
      return await runRolloutReleaseCli(process.argv.slice(3));
    }
    case "version": {
      process.stdout.write(`${JSON.stringify(handleVersion(), null, 2)}
`);
      return 0;
    }
    case "--version": {
      process.stdout.write(`${handleVersion().version}
`);
      return 0;
    }
    case "help":
    case "--help":
    case "-h":
    case "":
      process.stdout.write(`${HELP}
`);
      return 0;
    default:
      process.stderr.write(`unknown command: ${command}
${HELP}
`);
      return 1;
  }
}
var FLAGS_BY_COMMAND = {
  serve: /* @__PURE__ */ new Set(["help", "host", "port"]),
  rpc: /* @__PURE__ */ new Set(["help"]),
  "rpc-batch": /* @__PURE__ */ new Set(["help"]),
  openapi: /* @__PURE__ */ new Set(["help", "out"]),
  version: /* @__PURE__ */ new Set(["help"]),
  help: /* @__PURE__ */ new Set(),
  "--help": /* @__PURE__ */ new Set(),
  "-h": /* @__PURE__ */ new Set(),
  "--version": /* @__PURE__ */ new Set(),
  "": /* @__PURE__ */ new Set()
};
function assertKnownFlags(command, flags) {
  if (command === "rollout-release") return;
  const allowed = FLAGS_BY_COMMAND[command];
  if (!allowed) return;
  const unknown = Object.keys(flags).filter((flag) => !allowed.has(flag));
  if (unknown.length > 0) {
    throw new Error(`unknown flag for ${command || "help"}: --${unknown[0]}`);
  }
}
function parsePort(raw) {
  const port = Number(raw);
  if (!Number.isInteger(port) || port < 0 || port > 65535) {
    throw new Error(`--port must be an integer from 0 to 65535; received ${JSON.stringify(raw)}`);
  }
  return port;
}
main().then((code) => process.exit(code)).catch((err) => {
  console.error("[agent-eval] cli error:", err);
  process.exit(1);
});
//# sourceMappingURL=cli.js.map