import {
  cosineSimilarity
} from "./chunk-KVE7R4CG.js";

// src/buffer-surprise.ts
var DEFAULT_SURPRISE_K = 5;
async function computeSurprise(turn, recentMemories, options) {
  if (typeof turn !== "string") {
    throw new TypeError("computeSurprise: `turn` must be a string");
  }
  if (!options || typeof options.embedFn !== "function") {
    throw new TypeError(
      "computeSurprise: `options.embedFn` is required and must be a function"
    );
  }
  const candidates = Array.isArray(recentMemories) ? recentMemories : [];
  if (candidates.length === 0) return 1;
  const kRaw = typeof options.k === "number" ? options.k : DEFAULT_SURPRISE_K;
  const kClamped = clampK(kRaw, candidates.length);
  const turnEmbedding = await options.embedFn(turn);
  const candidateEmbeddings = await Promise.all(
    candidates.map((c) => options.embedFn(c.content))
  );
  const sims = [];
  for (let i = 0; i < candidates.length; i += 1) {
    const candEmbedding = candidateEmbeddings[i] ?? [];
    sims.push(safeCosine(turnEmbedding, candEmbedding));
  }
  sims.sort((a, b) => b - a);
  const top = sims.slice(0, kClamped);
  if (top.length === 0) {
    return 1;
  }
  let sum = 0;
  for (const s of top) sum += s;
  const nearestSim = sum / top.length;
  const surprise = 1 - nearestSim;
  if (!Number.isFinite(surprise)) return 1;
  if (surprise < 0) return 0;
  if (surprise > 1) return 1;
  return surprise;
}
function clampK(k, ceiling) {
  if (!Number.isFinite(k)) {
    return Math.min(DEFAULT_SURPRISE_K, Math.max(1, ceiling));
  }
  const floored = Math.floor(k);
  if (floored < 1) return 1;
  if (floored > ceiling) return ceiling;
  return floored;
}
function safeCosine(a, b) {
  if (!Array.isArray(a) || !Array.isArray(b)) return 0;
  if (a.length === 0 || b.length === 0) return 0;
  if (a.length !== b.length) return 0;
  const raw = cosineSimilarity(a, b);
  if (!Number.isFinite(raw)) return 0;
  if (raw < 0) return 0;
  if (raw > 1) return 1;
  return raw;
}

export {
  DEFAULT_SURPRISE_K,
  computeSurprise
};
//# sourceMappingURL=chunk-5JRF2PZA.js.map