import {
  isRetrievalSpan,
  isToolSpan
} from "../chunk-5BKGXME7.js";
import "../chunk-PZ5AY32C.js";

// src/groundedness/index.ts
function dedupeKeys(keys) {
  const seen = /* @__PURE__ */ new Set();
  const out = [];
  for (const raw of keys) {
    const k = raw.trim();
    if (!k) continue;
    const lower = k.toLowerCase();
    if (seen.has(lower)) continue;
    seen.add(lower);
    out.push(k);
  }
  return out;
}
function scoreGroundedness(resultText, requiredKnowledge) {
  const keys = dedupeKeys(requiredKnowledge);
  const total = keys.length;
  const text = resultText ?? "";
  const hadResults = text.trim().length > 0;
  const haystack = text.toLowerCase();
  if (total === 0) {
    return { score: 1, found: [], missing: [], total: 0, hadResults };
  }
  const found = [];
  const missing = [];
  for (const key of keys) {
    if (haystack.includes(key.toLowerCase())) found.push(key);
    else missing.push(key);
  }
  return { score: found.length / total, found, missing, total, hadResults };
}
var defaultProviderToolMatcher = (name) => /search|research/i.test(name) && !/fetch/i.test(name);
function resultToText(result) {
  if (result == null) return "";
  if (typeof result === "string") return result;
  try {
    return JSON.stringify(result);
  } catch {
    return String(result);
  }
}
function retrievalSpanText(span) {
  return span.hits.map((h) => h.content ?? "").filter((c) => c.length > 0).join("\n");
}
function extractRetrievedText(spans, opts = {}) {
  const isProviderTool = opts.isProviderTool ?? defaultProviderToolMatcher;
  const parts = [];
  for (const span of spans) {
    if (isRetrievalSpan(span)) {
      const t = retrievalSpanText(span);
      if (t) parts.push(t);
    } else if (isToolSpan(span)) {
      const ts = span;
      if (isProviderTool(ts.toolName)) {
        const t = resultToText(ts.result);
        if (t) parts.push(t);
      }
    }
  }
  return parts.join("\n");
}
function scoreGroundednessForRun(spans, requiredKnowledge, opts = {}) {
  return scoreGroundedness(extractRetrievedText(spans, opts), requiredKnowledge);
}
export {
  defaultProviderToolMatcher,
  extractRetrievedText,
  scoreGroundedness,
  scoreGroundednessForRun
};
//# sourceMappingURL=index.js.map