import { d as bind_props, b as attr_class, g as clsx, s as stringify, a as attr, c as attr_style } from './index2-BuOY2QE4.js';
import { I as Icon } from './Icon-BgknHaZs.js';
import { X as escape_html } from './context-zH5kvtGY.js';
import './utils-KcIDVAAe.js';
import './state.svelte-DtOGaiYC.js';
import './trpc-client-Bucti7HD.js';

function Popper($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let {
      referenceEl = null,
      placement = "bottom-start",
      offset = [0, 2],
      flip = true,
      preventOverflow = true,
      children
    } = $$props;
    function update() {
    }
    $$renderer2.push(`<div class="popper svelte-1dn0eza">`);
    children($$renderer2);
    $$renderer2.push(`<!----></div>`);
    bind_props($$props, { update });
  });
}
function Dropdown($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let {
      open = false,
      anchorEl = null,
      id = "",
      placement = "bottom-start",
      offset = [0, 2],
      flip = true,
      preventOverflow = true,
      onClose = () => {
      },
      children
    } = $$props;
    if (open && anchorEl) {
      $$renderer2.push("<!--[-->");
      {
        let children2 = function($$renderer3) {
          $$renderer3.push(`<div${attr("id", id)} class="popover svelte-1fd3ybn" role="dialog" aria-modal="true"><div${attr("id", id)} class="popover svelte-1fd3ybn" role="dialog" aria-modal="true"${attr_style(`min-width:${anchorEl?.offsetWidth ?? 0}px`)}>`);
          children2($$renderer3);
          $$renderer3.push(`<!----></div></div>`);
        };
        Popper($$renderer2, {
          referenceEl: anchorEl,
          placement,
          offset,
          flip,
          preventOverflow,
          children: children2,
          $$slots: { default: true }
        });
      }
    } else {
      $$renderer2.push("<!--[!-->");
    }
    $$renderer2.push(`<!--]-->`);
  });
}
function ChatApiCallTrace($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let { trace } = $$props;
    function safeJson(value) {
      try {
        if (typeof value === "string") {
          const trimmed = value.trim();
          if (!trimmed) return "";
          const maybe = JSON.parse(trimmed);
          return JSON.stringify(maybe, null, 2);
        }
      } catch {
      }
      try {
        return JSON.stringify(value ?? null, null, 2);
      } catch {
        return String(value);
      }
    }
    function fmtDate(ms) {
      return new Date(ms).toISOString();
    }
    function formatHHmmss(ms) {
      if (typeof ms !== "number" || !Number.isFinite(ms)) return null;
      const d = new Date(ms);
      if (Number.isNaN(d.getTime())) return null;
      const hh = String(d.getHours()).padStart(2, "0");
      const mm = String(d.getMinutes()).padStart(2, "0");
      const ss = String(d.getSeconds()).padStart(2, "0");
      return `${hh}:${mm}:${ss}`;
    }
    const time = (() => formatHHmmss(trace.createdAt))();
    const derivedError = (() => {
      if (trace.error != null) return trace.error;
      const isFailed = trace.ok === false || typeof trace.status === "number" && trace.status >= 400;
      if (!isFailed) return void 0;
      const resp = trace.response;
      if (resp && typeof resp === "object") {
        if ("error" in resp && resp.error != null) return resp.error;
      }
      return { status: trace.status, ok: trace.ok };
    })();
    const hasError = derivedError != null;
    `API: ${trace.operationName}`;
    const oneLine = trace.operationName;
    (() => {
      if (typeof trace.createdAt !== "number") return "—";
      return fmtDate(trace.createdAt);
    })();
    safeJson({
      method: trace.method,
      path: trace.path,
      baseUrl: trace.baseUrl,
      request: trace.request
    });
    safeJson({
      status: trace.status,
      ok: trace.ok,
      response: trace.response,
      error: derivedError
    });
    derivedError != null ? safeJson(derivedError) : "";
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      $$renderer3.push(`<button type="button" class="flex w-full items-baseline gap-2 truncate rounded-md bg-transparent px-2 py-1 text-left text-sm text-rc-gray-200 hover:bg-rc-gray-800/40">`);
      Icon($$renderer3, {
        name: hasError ? "close" : "checkmark",
        width: 18,
        height: 18,
        class: hasError ? "self-center text-red-400" : "self-center text-rc-green-200"
      });
      $$renderer3.push(`<!----> `);
      if (time) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<span class="text-[13px] leading-none text-rc-gray-400">${escape_html(time)}</span>`);
      } else {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]--> <span${attr_class(clsx(hasError ? "text-red-200" : ""))}>${escape_html(oneLine)}</span></button> `);
      {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]-->`);
    }
    do {
      $$settled = true;
      $$inner_renderer = $$renderer2.copy();
      $$render_inner($$inner_renderer);
    } while (!$$settled);
    $$renderer2.subsume($$inner_renderer);
  });
}
function ChatConversationalTrace($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let { trace, context, agentId, analyzeDisabled = false, onAnalyze } = $$props;
    function agentName(id) {
      if (!id) return "";
      return id.split("/").at(-1) ?? id;
    }
    function getInitial(id) {
      const first = agentName(id).trim().charAt(0);
      return first ? first.toUpperCase() : "?";
    }
    const sender = (() => {
      if (trace.role === "system") return "system";
      if (trace.eventName === "finished-main-streaming-step" || trace.eventName === "sent-message") {
        return "agent";
      }
      return trace.role === "user" ? "user" : "user";
    })();
    const hasError = (() => trace.error != null)();
    function formatHHmmss(ms) {
      if (typeof ms !== "number" || !Number.isFinite(ms)) return null;
      const d = new Date(ms);
      if (Number.isNaN(d.getTime())) return null;
      const hh = String(d.getHours()).padStart(2, "0");
      const mm = String(d.getMinutes()).padStart(2, "0");
      const ss = String(d.getSeconds()).padStart(2, "0");
      return `${hh}:${mm}:${ss}`;
    }
    const time = (() => formatHHmmss(trace?.createdAt))();
    function isAddTestEligible() {
      return sender === "agent" && trace.eventName !== "transfer-requested" && !!(agentId && agentId.trim()) && (trace.eventName === "finished-main-streaming-step" || trace.eventName === "sent-message");
    }
    function isAnalyzeEligible() {
      return sender === "agent" && trace.eventName !== "transfer-requested" && !!(agentId && agentId.trim()) && (trace.eventName === "finished-main-streaming-step" || trace.eventName === "sent-message");
    }
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      $$renderer3.push(`<div${attr_class("group mb-2 flex w-full items-center", void 0, { "justify-end": sender === "user" || sender === "system" })}>`);
      if (trace.eventName === "transfer-requested") {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<div class="flex w-full justify-center"><div${attr_class(`rounded-full border border-rc-gray-650 bg-rc-gray-800/40 px-4 py-2 text-sm text-rc-gray-100 ${stringify(hasError ? "border-red-500 bg-red-950/30 text-red-200" : "")}`)} role="button" tabindex="0"><div class="flex flex-wrap items-baseline gap-x-2 gap-y-0">`);
        if (time) {
          $$renderer3.push("<!--[-->");
          $$renderer3.push(`<span class="text-[13px] leading-none text-rc-gray-400">${escape_html(time)}</span>`);
        } else {
          $$renderer3.push("<!--[!-->");
        }
        $$renderer3.push(`<!--]--> <div class="min-w-0 break-words">Transfer requested: ${escape_html(trace.content)}</div></div></div></div>`);
      } else {
        $$renderer3.push("<!--[!-->");
        if (sender === "agent" && agentId) {
          $$renderer3.push("<!--[-->");
          $$renderer3.push(`<div class="mr-2 mt-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-sm bg-rc-green-700 text-sm uppercase text-rc-gray-100 backdrop-blur-md"${attr("title", agentName(agentId))}>${escape_html(getInitial(agentId))}</div>`);
        } else {
          $$renderer3.push("<!--[!-->");
        }
        $$renderer3.push(`<!--]--> <div${attr_class(`min-w-0 ${stringify(sender === "agent" ? "max-w-[83%]" : "")}`)} role="button" tabindex="0"><div${attr_class(`rounded-lg ${stringify(sender === "system" ? "justify-between whitespace-pre-line break-words border border-emerald-500 text-emerald-500" : sender !== "user" ? "w-full whitespace-pre-line break-words bg-rc-green-700 backdrop-blur-md" : "max-w5/6 justify-self-end bg-rc-gray-700")} border-thin border-rc-gray-110 p-2 pt-1 text-rc-gray-100 ${stringify(hasError ? "border-red-500 bg-red-950/30 text-red-200" : "")}`)}><div>${escape_html(trace.content)}</div> `);
        if (time) {
          $$renderer3.push("<!--[-->");
          $$renderer3.push(`<div class="mt-1 text-right text-xs text-rc-gray-200/70">${escape_html(time)}</div>`);
        } else {
          $$renderer3.push("<!--[!-->");
        }
        $$renderer3.push(`<!--]--></div></div> `);
        if (isAnalyzeEligible() || isAddTestEligible()) {
          $$renderer3.push("<!--[-->");
          $$renderer3.push(`<div class="ml-0 flex flex-col items-start">`);
          if (isAddTestEligible()) {
            $$renderer3.push("<!--[-->");
            $$renderer3.push(`<button type="button"${attr_class(`cursor-pointer text-nowrap border-0 bg-transparent pb-1 pl-3 pr-1 transition-colors focus:outline-none focus-visible:outline-none ${stringify("text-rc-gray-300 hover:text-rc-green-200")}`)}>`);
            {
              $$renderer3.push("<!--[!-->");
              {
                $$renderer3.push("<!--[!-->");
                $$renderer3.push(`Add test`);
              }
              $$renderer3.push(`<!--]-->`);
            }
            $$renderer3.push(`<!--]--></button>`);
          } else {
            $$renderer3.push("<!--[!-->");
          }
          $$renderer3.push(`<!--]--> `);
          if (isAnalyzeEligible() && onAnalyze) {
            $$renderer3.push("<!--[-->");
            $$renderer3.push(`<button type="button"${attr("disabled", analyzeDisabled, true)} class="cursor-pointer text-nowrap border-0 bg-transparent pb-1 pl-3 pr-1 text-rc-gray-300 transition-colors hover:text-rc-green-200 focus:outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:text-rc-gray-400 disabled:hover:text-rc-gray-400">Analyze</button>`);
          } else {
            $$renderer3.push("<!--[!-->");
          }
          $$renderer3.push(`<!--]--></div>`);
        } else {
          $$renderer3.push("<!--[!-->");
        }
        $$renderer3.push(`<!--]-->`);
      }
      $$renderer3.push(`<!--]--></div> `);
      {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]-->`);
    }
    do {
      $$settled = true;
      $$inner_renderer = $$renderer2.copy();
      $$render_inner($$inner_renderer);
    } while (!$$settled);
    $$renderer2.subsume($$inner_renderer);
  });
}
function ChatStepTrace($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let { trace, compareTrace } = $$props;
    function getPromptForDiff(t) {
      if (!t) return null;
      if (typeof t.renderedPrompt === "string") return t.renderedPrompt;
      return null;
    }
    function commonPrefixLength(a, b) {
      if (a === b) return a.length;
      const max = Math.min(a.length, b.length);
      for (let i = 0; i < max; i++) {
        if (a.charCodeAt(i) !== b.charCodeAt(i)) return i;
      }
      return max;
    }
    function similarityPercent(current, baseline) {
      const denom = Math.max(current.length, baseline.length);
      if (denom === 0) return 100;
      const prefixLen = commonPrefixLength(current, baseline);
      return Math.floor(prefixLen / denom * 100);
    }
    function safeJsonStringify(value) {
      const seen = /* @__PURE__ */ new WeakSet();
      try {
        return JSON.stringify(
          value,
          (_, v) => {
            if (typeof v === "bigint") return v.toString();
            if (v instanceof Error) {
              return { name: v.name, message: v.message, stack: v.stack };
            }
            if (typeof v === "object" && v !== null) {
              if (seen.has(v)) return "[Circular]";
              seen.add(v);
            }
            return v;
          },
          2
        ) ?? "";
      } catch {
        return String(value);
      }
    }
    function formatMaybeJson(value) {
      if (value == null) return "";
      if (typeof value === "string") {
        const trimmed = value.trim();
        if (!trimmed) return "";
        try {
          return JSON.stringify(JSON.parse(trimmed), null, 2);
        } catch {
          return value;
        }
      }
      return safeJsonStringify(value);
    }
    function formatHHmmss(ms) {
      if (typeof ms !== "number" || !Number.isFinite(ms)) return null;
      const d = new Date(ms);
      if (Number.isNaN(d.getTime())) return null;
      const hh = String(d.getHours()).padStart(2, "0");
      const mm = String(d.getMinutes()).padStart(2, "0");
      const ss = String(d.getSeconds()).padStart(2, "0");
      return `${hh}:${mm}:${ss}`;
    }
    const time = (() => formatHHmmss(trace.createdAt))();
    const hasError = trace.error != null;
    `AI: ${trace.name}`;
    const oneLine = trace.name;
    const mainPromptSimilarityPct = (() => {
      if (trace.name !== "main") return null;
      const current = getPromptForDiff(trace);
      const baseline = getPromptForDiff(compareTrace);
      if (current == null || baseline == null) return null;
      return similarityPercent(current, baseline);
    })();
    formatMaybeJson(trace.response);
    (() => {
      const raw = trace.response;
      if (typeof raw !== "string") return "json";
      try {
        JSON.parse(raw);
        return "json";
      } catch {
        return "text";
      }
    })();
    trace.stringifiedConversation ?? "";
    formatMaybeJson(trace.renderedPrompt);
    formatMaybeJson(trace.receivedPrompt);
    formatMaybeJson(trace.receivedContext);
    formatMaybeJson(trace.schema);
    trace.error ? safeJsonStringify(trace.error) : "";
    function toCopyablePrompt(value) {
      if (value == null) return "";
      if (typeof value === "string") return value;
      return safeJsonStringify(value);
    }
    toCopyablePrompt(trace.receivedPrompt);
    toCopyablePrompt(trace.renderedPrompt);
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      $$renderer3.push(`<button type="button" class="flex w-full items-baseline gap-2 truncate rounded-md bg-transparent px-2 py-1 text-left text-sm text-rc-gray-200 hover:bg-rc-gray-800/40">`);
      Icon($$renderer3, {
        name: hasError ? "close" : "checkmark",
        width: 18,
        height: 18,
        class: hasError ? "self-center text-red-400" : "self-center text-rc-green-200"
      });
      $$renderer3.push(`<!----> `);
      if (time) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<span class="text-[13px] leading-none text-rc-gray-400">${escape_html(time)}</span>`);
      } else {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]--> <span${attr_class(clsx(hasError ? "text-red-200" : ""))}>AI: ${escape_html(oneLine)}</span> `);
      if (mainPromptSimilarityPct != null) {
        $$renderer3.push("<!--[-->");
        $$renderer3.push(`<span${attr_class(`shrink-0 text-xs ${mainPromptSimilarityPct < 80 ? "text-red-200" : "text-rc-gray-400"}`)}>`);
        if (mainPromptSimilarityPct < 80) {
          $$renderer3.push("<!--[-->");
          $$renderer3.push(`${escape_html(mainPromptSimilarityPct)}% cached - move dynamic parts of prompt to the bottom`);
        } else {
          $$renderer3.push("<!--[!-->");
          $$renderer3.push(`${escape_html(mainPromptSimilarityPct)}%`);
        }
        $$renderer3.push(`<!--]--></span>`);
      } else {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]--></button> `);
      {
        $$renderer3.push("<!--[!-->");
      }
      $$renderer3.push(`<!--]-->`);
    }
    do {
      $$settled = true;
      $$inner_renderer = $$renderer2.copy();
      $$render_inner($$inner_renderer);
    } while (!$$settled);
    $$renderer2.subsume($$inner_renderer);
  });
}

export { ChatApiCallTrace as C, Dropdown as D, ChatConversationalTrace as a, ChatStepTrace as b };
//# sourceMappingURL=ChatStepTrace-B5HQ8Zv3.js.map
