import {
  exportTrainingData,
  toNdjson
} from "../chunk-KMPRBJK4.js";
import {
  buildTrajectory
} from "../chunk-RZTMDUO7.js";
import "../chunk-5BKGXME7.js";
import {
  TraceEmitter
} from "../chunk-TVVP3ZZQ.js";
import "../chunk-NSBPE2FW.js";

// src/prm/builtin-rubrics.ts
function outputLengthRubric(args = {}) {
  const min = args.minChars ?? 20;
  const max = args.maxChars ?? 8e3;
  return {
    id: "output-length",
    kinds: ["llm"],
    weight: args.weight ?? 0.5,
    async grade({ step }) {
      const llm = step.span;
      const len = (llm.output ?? "").length;
      if (len === 0) return { score: 0, rationale: "empty output" };
      if (len < min)
        return { score: Math.max(0, len / min), rationale: `below min (${len} < ${min})` };
      if (len > max)
        return {
          score: Math.max(0, 1 - (len - max) / max),
          rationale: `above max (${len} > ${max})`
        };
      return { score: 1, rationale: `${len} chars in bounds` };
    }
  };
}
function toolSuccessRubric(args = {}) {
  return {
    id: "tool-success",
    kinds: ["tool"],
    weight: args.weight ?? 1,
    async grade({ step }) {
      const tool = step.span;
      if (tool.status === "error")
        return { score: 0, rationale: `error: ${tool.error ?? "unknown"}` };
      const r = tool.result;
      if (r === null || r === void 0) return { score: 0.3, rationale: "empty result" };
      const asText = typeof r === "string" ? r : JSON.stringify(r);
      if (asText.length < 4) return { score: 0.5, rationale: "tiny result" };
      return { score: 1, rationale: `${tool.toolName} ok` };
    }
  };
}
function toolNonRedundantRubric(args = {}) {
  const weight = args.weight ?? 0.5;
  return {
    id: "tool-non-redundant",
    kinds: ["tool"],
    weight,
    async grade({ step, prior }) {
      const tool = step.span;
      const priorMatches = prior.filter((p) => {
        if (p.span.kind !== "tool") return false;
        const pt = p.span;
        return pt.toolName === tool.toolName && stableStringify(pt.args) === stableStringify(tool.args);
      });
      if (priorMatches.length === 0) return { score: 1, rationale: "novel call" };
      return {
        score: Math.max(0, 1 - priorMatches.length * 0.5),
        rationale: `${priorMatches.length} duplicate(s)`
      };
    }
  };
}
function nonRefusalRubric(args = {}) {
  const weight = args.weight ?? 1;
  const markers = args.markers ?? [
    /\bi\s+(?:can(?:not|'t)|won't|will\s+not)\b/i,
    /\b(?:as\s+an?\s+)?ai\b.*?\b(?:can't|cannot)\b/i
  ];
  return {
    id: "non-refusal",
    kinds: ["llm"],
    weight,
    async grade({ step }) {
      const llm = step.span;
      const out = llm.output ?? "";
      const refused = markers.some((re) => re.test(out));
      return refused ? { score: 0, rationale: "refusal marker present" } : { score: 1, rationale: "no refusal" };
    }
  };
}
function toolIntentAlignmentRubric(args = {}) {
  return {
    id: "tool-intent-alignment",
    kinds: ["llm"],
    weight: args.weight ?? 0.5,
    async grade({ step, next }) {
      const llm = step.span;
      const nextTool = next.find((s) => s.span.kind === "tool");
      if (!nextTool) return null;
      const toolName = nextTool.span.toolName;
      const out = (llm.output ?? "").toLowerCase();
      const mentioned = out.includes(toolName.toLowerCase());
      return mentioned ? { score: 1, rationale: `mentioned "${toolName}" before calling it` } : { score: 0.5, rationale: `called "${toolName}" without announcing it` };
    }
  };
}
function stableStringify(value) {
  if (value === null || typeof value !== "object") return JSON.stringify(value);
  if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
  const keys = Object.keys(value).sort();
  return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
}

// src/prm/inference.ts
async function prmBestOfN(store, grader, runIds) {
  if (runIds.length === 0) throw new Error("prmBestOfN: at least 1 candidate required");
  const graded = await Promise.all(runIds.map((id) => grader.grade(store, id)));
  const ranked = [...graded].sort((a, b) => b.aggregateScore - a.aggregateScore);
  const mean = graded.reduce((a, g) => a + g.aggregateScore, 0) / graded.length;
  const variance = graded.reduce((a, g) => a + (g.aggregateScore - mean) ** 2, 0) / graded.length;
  return { winner: ranked[0], ranked, stdDev: Math.sqrt(variance) };
}
async function prmEnsembleBestOfN(store, graders, runIds) {
  if (graders.length === 0) throw new Error("prmEnsembleBestOfN: at least 1 grader");
  const perGrader = await Promise.all(
    graders.map(async (g) => {
      const graded = await Promise.all(runIds.map((id) => g.grade(store, id)));
      return graded.sort((a, b) => b.aggregateScore - a.aggregateScore);
    })
  );
  const bordaScores = /* @__PURE__ */ new Map();
  for (const ranking of perGrader) {
    ranking.forEach((g, rank) => {
      bordaScores.set(g.runId, (bordaScores.get(g.runId) ?? 0) + (ranking.length - rank));
    });
  }
  const canonical = perGrader[0];
  const byRun = new Map(canonical.map((g) => [g.runId, g]));
  const ranked = [...byRun.values()].sort(
    (a, b) => (bordaScores.get(b.runId) ?? 0) - (bordaScores.get(a.runId) ?? 0)
  );
  const mean = ranked.reduce((a, g) => a + g.aggregateScore, 0) / ranked.length;
  const variance = ranked.reduce((a, g) => a + (g.aggregateScore - mean) ** 2, 0) / ranked.length;
  return { winner: ranked[0], ranked, stdDev: Math.sqrt(variance) };
}

// src/prm/rubric.ts
var PrmGrader = class {
  constructor(rubrics) {
    this.rubrics = rubrics;
    if (rubrics.length === 0) throw new Error("PrmGrader: at least 1 rubric required");
  }
  rubrics;
  /**
   * Grade every eligible span in a run. Emits a JudgeVerdict span for each
   * (rubric × span) verdict so the result is visible to downstream pipelines
   * (judgeAgreementView, etc.) — PRM is just "a judge that runs per span."
   */
  async grade(store, runId) {
    const trajectory = await buildTrajectory(store, runId);
    const emitter = new TraceEmitter(store, { runId });
    const steps = [];
    let ungraded = 0;
    for (let i = 0; i < trajectory.steps.length; i++) {
      const step = trajectory.steps[i];
      const ctx = {
        trajectory,
        step,
        prior: trajectory.steps.slice(0, i),
        next: trajectory.steps.slice(i + 1)
      };
      let gradedThis = false;
      for (const rubric of this.rubrics) {
        if (rubric.kinds && !rubric.kinds.includes(step.span.kind)) continue;
        const verdict = await rubric.grade(ctx);
        if (verdict === null) continue;
        const weight = rubric.weight ?? 1;
        steps.push({
          spanId: step.span.spanId,
          rubricId: rubric.id,
          score: verdict.score,
          weight,
          rationale: verdict.rationale,
          evidence: verdict.evidence
        });
        gradedThis = true;
        await emitter.recordJudge({
          judgeId: `prm:${rubric.id}`,
          targetSpanId: step.span.spanId,
          dimension: "step_quality",
          score: verdict.score,
          rationale: verdict.rationale,
          evidence: verdict.evidence,
          name: `prm:${rubric.id}`
        });
      }
      if (!gradedThis) ungraded++;
    }
    const totalWeight = steps.reduce((a, s) => a + s.weight, 0);
    const aggregateScore = totalWeight === 0 ? 0 : steps.reduce((a, s) => a + s.score * s.weight, 0) / totalWeight;
    return { runId, steps, aggregateScore, gradedCount: steps.length, ungradedCount: ungraded };
  }
};
function isPrmVerdict(verdict) {
  return verdict.judgeId.startsWith("prm:");
}
export {
  PrmGrader,
  exportTrainingData,
  isPrmVerdict,
  nonRefusalRubric,
  outputLengthRubric,
  prmBestOfN,
  prmEnsembleBestOfN,
  toNdjson,
  toolIntentAlignmentRubric,
  toolNonRedundantRubric,
  toolSuccessRubric
};
//# sourceMappingURL=index.js.map