import "../chunk-PZ5AY32C.js";

// src/storyboard/code-edit.ts
var EDIT_TOOLS = /(edit|write|patch|apply|str_replace|create.*file|save|insert|update.*file|multi_edit)/i;
function languageOf(path) {
  const ext = path.includes(".") ? path.split(".").pop()?.toLowerCase() : void 0;
  if (!ext) return void 0;
  const map = {
    ts: "ts",
    tsx: "tsx",
    js: "js",
    jsx: "jsx",
    mjs: "js",
    cjs: "js",
    py: "python",
    rs: "rust",
    go: "go",
    sol: "solidity",
    java: "java",
    rb: "ruby",
    php: "php",
    c: "c",
    cpp: "cpp",
    cs: "csharp",
    css: "css",
    scss: "scss",
    html: "html",
    json: "json",
    yaml: "yaml",
    yml: "yaml",
    toml: "toml",
    md: "markdown",
    sh: "bash",
    sql: "sql"
  };
  return map[ext] ?? ext;
}
function pick(obj, keys) {
  if (!obj || typeof obj !== "object") return void 0;
  const rec = obj;
  for (const k of Object.keys(rec)) {
    if (keys.includes(k.toLowerCase())) {
      const v = rec[k];
      if (typeof v === "string") return v;
    }
  }
  return void 0;
}
function countDiff(diff) {
  if (!diff) return { additions: 0, deletions: 0 };
  let additions = 0;
  let deletions = 0;
  for (const line of diff.split("\n")) {
    if (line.startsWith("+") && !line.startsWith("+++")) additions++;
    else if (line.startsWith("-") && !line.startsWith("---")) deletions++;
  }
  return { additions, deletions };
}
function codeEditFromSpan(span) {
  if (span.kind !== "tool") return void 0;
  const tool = span;
  if (!EDIT_TOOLS.test(tool.toolName)) return void 0;
  const path = pick(tool.args, ["path", "file_path", "filepath", "filename", "file"]);
  if (!path) return void 0;
  const diff = pick(tool.args, ["diff", "patch"]);
  const after = pick(tool.args, ["content", "new_str", "new_string", "newtext", "text", "body"]);
  const before = pick(tool.args, ["old_str", "old_string", "oldtext", "original"]);
  const counts = countDiff(diff);
  return {
    spanId: span.spanId,
    path,
    language: languageOf(path),
    diff,
    before,
    after,
    additions: diff ? counts.additions : after ? after.split("\n").length : 0,
    deletions: diff ? counts.deletions : 0,
    startedAt: span.startedAt
  };
}
function extractCodeEdits(spans) {
  return spans.map(codeEditFromSpan).filter((e) => e != null).sort((a, b) => a.startedAt - b.startedAt);
}
function codeEditsForStoryboard(storyboard, spans) {
  const bySpan = new Map(extractCodeEdits(spans).map((e) => [e.spanId, e]));
  const out = [];
  for (const scene of storyboard.scenes) {
    if (scene.sceneType !== "diff") continue;
    const edit = scene.evidenceSpanIds.map((id) => bySpan.get(id)).find((e) => e != null);
    if (edit) out.push({ scene, edit });
  }
  return out;
}
function editAnimationText(edit) {
  if (edit.after && edit.after.trim()) return edit.after;
  if (edit.diff) {
    const added = edit.diff.split("\n").filter((l) => l.startsWith("+") && !l.startsWith("+++")).map((l) => l.slice(1)).join("\n");
    if (added.trim()) return added;
  }
  return `// ${edit.path}
// (${edit.additions} line${edit.additions === 1 ? "" : "s"} written)`;
}
function esc(s) {
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
function renderCodeAnimationHtml(source, opts = {}) {
  const edits = source.length > 0 && "path" in source[0] ? source : extractCodeEdits(source);
  const files = edits.map((e) => ({
    path: e.path,
    language: e.language ?? "",
    additions: e.additions,
    deletions: e.deletions,
    code: editAnimationText(e)
  }));
  const title = opts.title ?? "Agent writing code";
  const charsPerTick = opts.charsPerTick ?? 4;
  const pauseBetweenMs = opts.pauseBetweenMs ?? 900;
  const filesJson = JSON.stringify(files);
  return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${esc(title)}</title>
<style>
  :root { color-scheme: dark; }
  * { box-sizing: border-box; }
  body { margin: 0; background: #0b0f17; color: #e6edf3;
    font: 14px/1.55 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
    display: flex; flex-direction: column; min-height: 100vh; align-items: center; justify-content: center; gap: 14px; }
  h1 { font-family: ui-sans-serif, system-ui, sans-serif; font-size: 1rem; font-weight: 600; color: #9aa7b5; margin: 0; }
  .editor { width: min(900px, 94vw); background: #0d1320; border: 1px solid #1e2a3a; border-radius: 12px;
    overflow: hidden; box-shadow: 0 16px 50px rgba(0,0,0,.5); }
  .tabbar { display: flex; align-items: center; gap: 8px; background: #111a29; padding: 9px 14px; border-bottom: 1px solid #1e2a3a; }
  .dot { width: 11px; height: 11px; border-radius: 50%; }
  .dot.r { background: #ff5f56; } .dot.y { background: #ffbd2e; } .dot.g { background: #27c93f; }
  .tab { margin-left: 10px; background: #0d1320; padding: 5px 12px; border-radius: 7px 7px 0 0;
    color: #cdd9e5; font-family: ui-sans-serif, system-ui, sans-serif; font-size: .85rem; }
  .lang { color: #5b6b7d; font-size: .75rem; margin-left: 6px; }
  .adds { margin-left: auto; color: #3fb950; font-size: .78rem; font-family: ui-sans-serif, system-ui, sans-serif; }
  .dels { color: #f85149; margin-left: 8px; }
  .codewrap { display: flex; max-height: 60vh; overflow: auto; }
  .gutter { padding: 14px 10px 14px 14px; text-align: right; color: #3a4757; user-select: none; white-space: pre; }
  pre { margin: 0; padding: 14px 18px 14px 6px; white-space: pre; tab-size: 2; flex: 1; }
  .cursor { display: inline-block; width: 8px; margin-left: 1px; background: #58a6ff; animation: blink .9s steps(1) infinite; }
  @keyframes blink { 50% { opacity: 0; } }
  .controls { display: flex; gap: 10px; align-items: center; font-family: ui-sans-serif, system-ui, sans-serif; font-size: .85rem; color: #8b98a6; }
  button { background: #1b2636; color: #e6edf3; border: 1px solid #2a3a4f; border-radius: 8px; padding: 6px 12px; cursor: pointer; font: inherit; }
  button:hover { background: #243349; }
  .empty { padding: 40px; color: #5b6b7d; }
</style>
</head>
<body>
  <h1>\u270F\uFE0F ${esc(title)}</h1>
  <div class="editor">
    <div class="tabbar">
      <span class="dot r"></span><span class="dot y"></span><span class="dot g"></span>
      <span class="tab" id="tab">\u2014</span><span class="lang" id="lang"></span>
      <span class="adds" id="adds"></span>
    </div>
    <div class="codewrap"><div class="gutter" id="gutter">1</div><pre id="code"></pre></div>
  </div>
  <div class="controls">
    <button id="pp">\u23F8 Pause</button><button id="restart">\u21BB Restart</button>
    <span id="counter"></span>
  </div>
<script>
  const FILES = ${filesJson};
  const CPT = ${charsPerTick}, PAUSE = ${pauseBetweenMs};
  const codeEl = document.getElementById('code'), gutterEl = document.getElementById('gutter');
  const tabEl = document.getElementById('tab'), langEl = document.getElementById('lang');
  const addsEl = document.getElementById('adds'), counterEl = document.getElementById('counter');
  let fi = 0, ci = 0, playing = true, raf = 0, paused = false;
  if (!FILES.length) { codeEl.innerHTML = '<span class="empty">No code edits in this run.</span>'; }
  function esc(s){return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}
  function setHeader(){ const f = FILES[fi]; tabEl.textContent = f.path; langEl.textContent = f.language || '';
    addsEl.innerHTML = '+' + f.additions + (f.deletions ? ' <span class="dels">-' + f.deletions + '</span>' : '');
    counterEl.textContent = (fi+1) + ' / ' + FILES.length + ' files'; }
  function paint(){ const f = FILES[fi]; const shown = f.code.slice(0, ci);
    const lines = (shown.match(/\\n/g) || []).length + 1;
    gutterEl.textContent = Array.from({length: lines}, (_, k) => k+1).join('\\n');
    codeEl.innerHTML = esc(shown) + '<span class="cursor">&nbsp;</span>';
    const wrap = codeEl.parentElement; wrap.scrollTop = wrap.scrollHeight; }
  function tick(){ if (paused || !FILES.length) return;
    const f = FILES[fi];
    if (ci < f.code.length){ ci = Math.min(f.code.length, ci + CPT); paint(); raf = requestAnimationFrame(tick); }
    else if (fi < FILES.length - 1){ setTimeout(() => { fi++; ci = 0; setHeader(); paint(); raf = requestAnimationFrame(tick); }, PAUSE); }
    else { playing = false; document.getElementById('pp').textContent = '\u25B6 Play'; } }
  document.getElementById('pp').onclick = () => { if (!playing){ playing = true; paused = false; tick(); } else { paused = !paused; if (!paused) tick(); } document.getElementById('pp').textContent = paused ? '\u25B6 Play' : '\u23F8 Pause'; };
  document.getElementById('restart').onclick = () => { fi = 0; ci = 0; playing = true; paused = false; document.getElementById('pp').textContent = '\u23F8 Pause'; setHeader(); paint(); cancelAnimationFrame(raf); tick(); };
  if (FILES.length){ setHeader(); paint(); tick(); }
</script>
</body>
</html>
`;
}

// src/storyboard/index.ts
function str(v) {
  return typeof v === "string" && v.length > 0 ? v : void 0;
}
function num(v) {
  return typeof v === "number" ? v : void 0;
}
function attr(span, ...keys) {
  const a = span.attributes;
  if (!a) return void 0;
  for (const k of keys) if (a[k] != null) return a[k];
  return void 0;
}
function asObj(v) {
  return v && typeof v === "object" && !Array.isArray(v) ? v : void 0;
}
function safeJson(v) {
  if (v == null) return void 0;
  if (typeof v === "string") return v;
  try {
    return JSON.stringify(v, null, 2);
  } catch {
    return String(v);
  }
}
function isImageSrc(s) {
  return !!s && (s.startsWith("data:image") || /^https?:\/\//.test(s));
}
function extractVisual(span) {
  const shot = str(attr(span, "screenshot", "screenshotUrl", "image", "frame", "videoFrame")) ?? (span.kind === "tool" ? str(asObj(span.result)?.screenshot) ?? str(asObj(span.result)?.image) : void 0);
  if (span.kind === "tool") {
    const tn = span.toolName.toLowerCase();
    const a = asObj(span.args);
    if (/computer|cua|desktop|\bgui\b|xdotool|mouse|keyboard|screen_|pyautogui/.test(tn)) {
      return {
        type: "browser",
        action: str(a?.action) ?? span.toolName,
        url: str(a?.target),
        screenshot: shot
      };
    }
    if (/browser|playwright|puppeteer|\bpage\b|navigate|goto|\bclick\b|\btype\b|screenshot|dom/.test(
      tn
    )) {
      return {
        type: "browser",
        url: str(a?.url) ?? str(attr(span, "url")),
        action: str(a?.action) ?? str(a?.selector) ?? span.toolName,
        screenshot: shot
      };
    }
    const diff = str(attr(span, "diff", "patch")) ?? str(a?.diff) ?? str(a?.patch);
    if (diff && /edit|write|patch|apply|str_replace|create|save|file/.test(tn)) {
      return {
        type: "diff",
        path: str(a?.path) ?? str(a?.file) ?? str(attr(span, "path")) ?? "",
        patch: truncate(diff, 2e3)
      };
    }
    if (/edit|write|patch|apply|str_replace/.test(tn)) {
      const newText = str(a?.new_str) ?? str(a?.content) ?? str(a?.text);
      return {
        type: "diff",
        path: str(a?.path) ?? str(a?.file) ?? "",
        patch: newText ? `+ ${truncate(newText, 1600)}` : "(no diff captured)"
      };
    }
    if (/read|\bcat\b|open|view|get_file|load|fetch_file/.test(tn)) {
      const content = str(asObj(span.result)?.content) ?? (typeof span.result === "string" ? span.result : void 0) ?? str(attr(span, "content"));
      return {
        type: "code",
        path: str(a?.path) ?? str(a?.file) ?? "",
        content: truncate(content ?? "", 1400)
      };
    }
    if (/search|grep|find|glob|query/.test(tn)) {
      return {
        type: "terminal",
        command: `search ${str(a?.query) ?? str(a?.pattern) ?? ""}`.trim(),
        output: truncate(safeJson(span.result) ?? "", 1e3)
      };
    }
    const url = str(a?.url) ?? str(attr(span, "url"));
    if (url || /http|\bapi\b|fetch|request|webhook|rest|graphql|endpoint/.test(tn)) {
      return {
        type: "api",
        method: str(a?.method) ?? str(attr(span, "method")),
        url: url ?? span.toolName,
        status: num(attr(span, "status", "statusCode")) ?? num(asObj(span.result)?.status),
        request: truncate(str(a?.body) ?? safeJson(span.args) ?? "", 900),
        response: truncate(str(attr(span, "response")) ?? safeJson(span.result) ?? "", 900)
      };
    }
    if (/shell|exec|bash|\brun\b|terminal|command|sandbox|process/.test(tn)) {
      const command = typeof span.args === "string" ? span.args : str(a?.command) ?? str(a?.cmd) ?? span.toolName;
      const output = str(attr(span, "output", "stdout")) ?? (typeof span.result === "string" ? span.result : safeJson(span.result));
      return {
        type: "terminal",
        command: truncate(command, 240),
        output: truncate(output ?? "", 1400)
      };
    }
    return {
      type: "api",
      url: span.toolName,
      request: truncate(safeJson(span.args) ?? "", 900),
      response: truncate(safeJson(span.result) ?? "", 900)
    };
  }
  if (isImageSrc(shot)) return { type: "screenshot", src: shot };
  if (span.kind === "llm") {
    const text = str(span.output) ?? str(span.messages?.[span.messages.length - 1]?.content);
    return text ? { type: "prose", text: truncate(text, 900) } : { type: "none" };
  }
  if (span.kind === "sandbox")
    return { type: "terminal", command: span.name, output: str(attr(span, "output")) };
  return { type: "none" };
}
function toolLabel(span) {
  if (span.kind === "tool") {
    const a = asObj(span.args);
    const arg = typeof span.args === "string" ? span.args : a ? str(a.path) ?? str(a.url) ?? str(a.command) ?? str(a.query) ?? Object.values(a).find((v) => typeof v === "string") : void 0;
    return typeof arg === "string" && arg.length > 0 ? `${span.toolName}: ${truncate(arg, 60)}` : span.toolName;
  }
  return span.name;
}
function classify(span) {
  if (span.status === "error" || span.error) {
    return { kind: "observed_failure", importance: 5, label: span.error ?? span.name };
  }
  if (span.kind === "llm" || span.kind === "agent")
    return { kind: "reasoned", importance: 2, label: span.name };
  if (span.kind === "judge") return { kind: "evaluated", importance: 2, label: span.name };
  if (span.kind === "retrieval") return { kind: "searched", importance: 2, label: span.name };
  if (span.kind === "sandbox") return { kind: "ran_command", importance: 3, label: span.name };
  if (span.kind === "tool") {
    const tn = span.toolName.toLowerCase();
    const label = toolLabel(span);
    if (/computer|cua|desktop|\bgui\b|xdotool|pyautogui/.test(tn))
      return { kind: "used_computer", importance: 3, label };
    if (/browser|playwright|puppeteer|\bpage\b|navigate|goto|\bclick\b|screenshot|dom/.test(tn))
      return { kind: "used_browser", importance: 3, label };
    if (/edit|write|patch|apply|str_replace|create.*file|save/.test(tn))
      return { kind: "edited_code", importance: 4, label };
    if (/read|\bcat\b|open|view|get.*file|load/.test(tn))
      return { kind: "read_file", importance: 2, label };
    if (/search|grep|find|glob|query/.test(tn)) return { kind: "searched", importance: 2, label };
    if (/http|\bapi\b|fetch|request|webhook|rest|graphql|endpoint/.test(tn) || str(asObj(span.args)?.url)) {
      return { kind: "called_api", importance: 3, label };
    }
    if (/shell|exec|bash|\brun\b|terminal|command|process/.test(tn))
      return { kind: "ran_command", importance: 3, label };
    return { kind: "called_tool", importance: 3, label };
  }
  return { kind: "called_tool", importance: 2, label: span.name };
}
var KIND_VERB = {
  understood_task: "Understood the task",
  user_message: "User said",
  agent_reply: "Agent replied",
  reasoned: "Reasoned",
  ran_command: "Ran a command",
  read_file: "Read files",
  edited_code: "Edited code",
  searched: "Searched",
  used_browser: "Used the browser",
  used_computer: "Controlled the computer",
  called_api: "Called an API",
  called_tool: "Used a tool",
  evaluated: "Evaluated the result",
  observed_failure: "Hit a failure",
  completed: "Finished"
};
var STANDALONE_KINDS = /* @__PURE__ */ new Set([
  "observed_failure",
  "understood_task",
  "user_message",
  "agent_reply"
]);
function conversationEvents(span, seen, state) {
  if (span.kind !== "llm") return [];
  const out = [];
  const emit = (kind, text, importance) => {
    const t = text.trim();
    if (!t) return;
    const who = kind === "agent_reply" ? "a" : "u";
    const key = `${who}
${t}`;
    if (seen.has(key)) return;
    seen.add(key);
    const speaker = kind === "understood_task" ? "Task" : kind === "user_message" ? "User" : "Agent";
    out.push({
      kind,
      title: `${speaker}: ${truncate(t, 64)}`,
      summary: truncate(t, 280),
      visual: { type: "prose", text: truncate(t, 1200) },
      evidenceSpanIds: [span.spanId],
      importance,
      startTs: span.startedAt,
      endTs: span.endedAt ?? span.startedAt
    });
  };
  for (const m of span.messages ?? []) {
    const content = str(m.content);
    if (!content) continue;
    if (m.role === "user") {
      emit(state.sawUser ? "user_message" : "understood_task", content, state.sawUser ? 4 : 5);
      state.sawUser = true;
    } else if (m.role === "assistant") {
      emit("agent_reply", content, 3);
    }
  }
  const reply = str(span.output);
  if (reply) emit("agent_reply", reply, 3);
  return out;
}
function reduceToSemanticEvents(spans, opts = {}) {
  const collapse = opts.collapseAdjacent ?? true;
  const ordered = [...spans].sort((a, b) => a.startedAt - b.startedAt);
  const seen = /* @__PURE__ */ new Set();
  const convState = { sawUser: false };
  const raw = [];
  for (const s of ordered) {
    const conv = conversationEvents(s, seen, convState);
    if (conv.length > 0) {
      raw.push(...conv);
      continue;
    }
    const c = classify(s);
    raw.push({
      kind: c.kind,
      title: c.label,
      summary: `${KIND_VERB[c.kind]} \u2014 ${c.label}`,
      visual: extractVisual(s),
      evidenceSpanIds: [s.spanId],
      importance: c.importance,
      startTs: s.startedAt,
      endTs: s.endedAt ?? s.startedAt
    });
  }
  if (!collapse) return raw;
  const merged = [];
  for (const ev of raw) {
    const prev = merged[merged.length - 1];
    if (prev && prev.kind === ev.kind && !STANDALONE_KINDS.has(ev.kind)) {
      prev.evidenceSpanIds.push(...ev.evidenceSpanIds);
      prev.endTs = Math.max(prev.endTs, ev.endTs);
      if (ev.visual.type !== "none") prev.visual = ev.visual;
      const n = prev.evidenceSpanIds.length;
      prev.title = `${KIND_VERB[ev.kind]} (${n}\xD7)`;
      prev.summary = `${KIND_VERB[ev.kind]} ${n} time${n === 1 ? "" : "s"} \u2014 latest: ${ev.title}`;
    } else {
      merged.push({ ...ev, evidenceSpanIds: [...ev.evidenceSpanIds] });
    }
  }
  return merged;
}
var KIND_TO_SCENE = {
  understood_task: "title_card",
  user_message: "prompt",
  agent_reply: "reply",
  reasoned: "reasoning",
  ran_command: "terminal",
  read_file: "file",
  edited_code: "diff",
  searched: "search",
  used_browser: "browser",
  used_computer: "computer",
  called_api: "api",
  called_tool: "tool",
  evaluated: "eval",
  observed_failure: "error",
  completed: "summary"
};
var DURATION_BY_IMPORTANCE = {
  1: 2500,
  2: 3e3,
  3: 4e3,
  4: 5e3,
  5: 6e3
};
function compileStoryboard(events, opts = {}) {
  const title = opts.title ?? "Agent run";
  const maxScenes = opts.maxScenes ?? 16;
  const taskEvent = events.find((e) => e.kind === "understood_task");
  const indexed = events.filter((ev) => ev.kind !== "understood_task").map((ev, i) => ({ ev, i }));
  const mustKeep = indexed.filter(({ ev }) => ev.importance >= 4);
  const rest = indexed.filter(({ ev }) => ev.importance < 4).sort((a, b) => b.ev.importance - a.ev.importance || a.i - b.i);
  const budget = Math.max(0, maxScenes - mustKeep.length);
  const selected = [...mustKeep, ...rest.slice(0, budget)].sort((a, b) => a.i - b.i);
  const actionScenes = selected.map(({ ev }) => ({
    sceneType: KIND_TO_SCENE[ev.kind],
    title: ev.title,
    narration: ev.summary,
    visual: ev.visual,
    durationMs: DURATION_BY_IMPORTANCE[ev.importance],
    evidenceSpanIds: ev.evidenceSpanIds
  }));
  const failures = events.filter((e) => e.kind === "observed_failure").length;
  const edits = events.filter((e) => e.kind === "edited_code").length;
  const commands = events.filter((e) => e.kind === "ran_command").length;
  const summaryNarration = `${events.length} moments \xB7 ${commands} command${commands === 1 ? "" : "s"} \xB7 ${edits} edit${edits === 1 ? "" : "s"} \xB7 ${failures} failure${failures === 1 ? "" : "s"}`;
  const scenes = [
    {
      sceneType: "title_card",
      title,
      narration: taskEvent ? taskEvent.summary : "The agent receives its task.",
      visual: taskEvent ? taskEvent.visual : { type: "none" },
      durationMs: 3e3,
      evidenceSpanIds: taskEvent ? taskEvent.evidenceSpanIds : []
    },
    ...actionScenes,
    {
      sceneType: "summary",
      title: failures > 0 ? "Finished \u2014 with failures" : "Finished",
      narration: summaryNarration,
      visual: { type: "none" },
      durationMs: 4e3,
      evidenceSpanIds: []
    }
  ];
  return { title, totalMs: scenes.reduce((s, sc) => s + sc.durationMs, 0), scenes };
}
var SCENE_ICON = {
  title_card: "\u{1F3AC}",
  prompt: "\u{1F4AC}",
  reply: "\u{1F916}",
  reasoning: "\u{1F9E0}",
  terminal: "\u2328\uFE0F",
  file: "\u{1F4C4}",
  diff: "\u270F\uFE0F",
  search: "\u{1F50E}",
  browser: "\u{1F310}",
  computer: "\u{1F5A5}\uFE0F",
  api: "\u{1F50C}",
  tool: "\u{1F527}",
  eval: "\u2696\uFE0F",
  error: "\u274C",
  summary: "\u{1F3C1}"
};
function mmss(ms) {
  const s = Math.round(ms / 1e3);
  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
}
function truncate(s, max) {
  return s.length <= max ? s : `${s.slice(0, Math.max(0, max - 1))}\u2026`;
}
function escapeHtml(s) {
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
function visualMarkdown(v) {
  switch (v.type) {
    case "screenshot":
      return `\u{1F5BC} screenshot (${truncate(v.src, 60)})`;
    case "browser":
      return `\u{1F310} ${v.action ?? "browser"}${v.url ? ` \u2192 ${v.url}` : ""}${v.screenshot ? " [screenshot]" : ""}`;
    case "diff":
      return `

\`\`\`diff
${truncate(v.patch, 600)}
\`\`\`${v.path ? `
_${v.path}_` : ""}`;
    case "code":
      return `

\`\`\`
${truncate(v.content, 500)}
\`\`\`${v.path ? `
_${v.path}_` : ""}`;
    case "terminal":
      return `

\`\`\`sh
$ ${v.command}${v.output ? `
${truncate(v.output, 500)}` : ""}
\`\`\``;
    case "api":
      return `\u{1F50C} ${v.method ?? "CALL"} ${v.url}${v.status != null ? ` \u2192 ${v.status}` : ""}`;
    case "prose":
      return `

> ${truncate(v.text, 400).replace(/\n/g, "\n> ")}`;
    default:
      return "";
  }
}
function visualHtml(v) {
  switch (v.type) {
    case "screenshot":
      return `<img class="shot" src="${escapeHtml(v.src)}" alt="screenshot" loading="lazy"/>`;
    case "browser": {
      const bar = `<div class="urlbar">${escapeHtml(v.url ?? v.action ?? "browser")}</div>`;
      const body = isImageSrc(v.screenshot) ? `<img class="shot" src="${escapeHtml(v.screenshot)}" alt="page" loading="lazy"/>` : `<div class="browser-action">${escapeHtml(v.action ?? "navigated")}</div>`;
      return `<div class="browser">${bar}${body}</div>`;
    }
    case "diff": {
      const lines = v.patch.split("\n").map((l) => {
        const cls = l.startsWith("+") ? "add" : l.startsWith("-") ? "del" : "";
        return `<span class="${cls}">${escapeHtml(l)}</span>`;
      });
      return `${v.path ? `<div class="pathhdr">${escapeHtml(v.path)}</div>` : ""}<pre class="diff">${lines.join("\n")}</pre>`;
    }
    case "code":
      return `${v.path ? `<div class="pathhdr">${escapeHtml(v.path)}</div>` : ""}<pre class="code">${escapeHtml(v.content)}</pre>`;
    case "terminal":
      return `<pre class="term"><span class="cmd">$ ${escapeHtml(v.command)}</span>${v.output ? `
${escapeHtml(v.output)}` : ""}</pre>`;
    case "api": {
      const badge = `<span class="method">${escapeHtml(v.method ?? "CALL")}</span> <span class="url">${escapeHtml(v.url)}</span>${v.status != null ? ` <span class="status s${Math.floor(v.status / 100)}">${v.status}</span>` : ""}`;
      const req = v.request ? `<div class="kv"><b>req</b><pre>${escapeHtml(v.request)}</pre></div>` : "";
      const res = v.response ? `<div class="kv"><b>res</b><pre>${escapeHtml(v.response)}</pre></div>` : "";
      return `<div class="api"><div class="apihdr">${badge}</div>${req}${res}</div>`;
    }
    case "prose":
      return `<div class="prose">${escapeHtml(v.text)}</div>`;
    default:
      return "";
  }
}
function renderStoryboardMarkdown(storyboard) {
  const out = [
    `# \u{1F3AC} ${storyboard.title}`,
    "",
    `_${storyboard.scenes.length} scenes \xB7 ${mmss(storyboard.totalMs)} replay_`,
    ""
  ];
  let elapsed = 0;
  for (const sc of storyboard.scenes) {
    out.push(`### [${mmss(elapsed)}] ${SCENE_ICON[sc.sceneType]} ${sc.title}`);
    out.push("");
    out.push(sc.narration);
    const vm = visualMarkdown(sc.visual);
    if (vm) out.push(vm);
    if (sc.evidenceSpanIds.length > 0) {
      out.push("");
      out.push(`_evidence: ${sc.evidenceSpanIds.length} span(s)_`);
    }
    out.push("");
    elapsed += sc.durationMs;
  }
  return out.join("\n");
}
function renderStoryboardHtml(storyboard, opts = {}) {
  const docTitle = opts.title ?? storyboard.title;
  const scenesJson = JSON.stringify(
    storyboard.scenes.map((s) => ({
      icon: SCENE_ICON[s.sceneType],
      type: s.sceneType,
      title: s.title,
      narration: s.narration,
      durationMs: s.durationMs,
      evidence: s.evidenceSpanIds.length,
      visual: visualHtml(s.visual)
    }))
  ).replace(/</g, "\\u003c");
  return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${escapeHtml(docTitle)}</title>
<style>
  :root { color-scheme: dark; }
  * { box-sizing: border-box; }
  body { margin: 0; font: 16px/1.5 ui-sans-serif, system-ui, -apple-system, sans-serif;
    background: #0b0f17; color: #e6edf3; display: flex; min-height: 100vh; align-items: center; justify-content: center; }
  .stage { width: min(900px, 95vw); }
  h1 { font-size: 1.1rem; font-weight: 600; color: #9aa7b5; margin: 0 0 14px; letter-spacing: .02em; }
  .card { background: #111824; border: 1px solid #1e2a3a; border-radius: 14px; padding: 24px 28px;
    min-height: 300px; box-shadow: 0 12px 40px rgba(0,0,0,.45); position: relative; overflow: hidden; }
  .card::before { content: ""; position: absolute; inset: 0 0 auto 0; height: 3px; background: var(--accent, #3b82f6); }
  .head { display: flex; align-items: center; gap: 12px; margin-bottom: 6px; }
  .icon { font-size: 2rem; line-height: 1; }
  .title { font-size: 1.3rem; font-weight: 650; }
  .narration { color: #9fb0c0; font-size: .95rem; margin-bottom: 14px; }
  .visual { margin-top: 6px; }
  .visual img.shot { max-width: 100%; max-height: 360px; border-radius: 8px; border: 1px solid #1e2a3a; display: block; }
  .visual pre { background: #0a0e15; border: 1px solid #1e2a3a; border-radius: 8px; padding: 12px 14px;
    overflow: auto; max-height: 340px; font: 13px/1.5 ui-monospace, "SF Mono", Menlo, monospace; white-space: pre-wrap; word-break: break-word; }
  .pathhdr { font: 12px ui-monospace, monospace; color: #7d8da0; margin-bottom: 4px; }
  .diff .add { color: #56d364; } .diff .del { color: #f85149; }
  .term .cmd { color: #eab308; }
  .browser { border: 1px solid #1e2a3a; border-radius: 8px; overflow: hidden; }
  .urlbar { background: #0a0e15; padding: 7px 12px; font: 12px ui-monospace, monospace; color: #8b98a6; border-bottom: 1px solid #1e2a3a; }
  .browser-action { padding: 28px; color: #9fb0c0; text-align: center; }
  .api .apihdr { font: 13px ui-monospace, monospace; margin-bottom: 8px; }
  .method { background: #1b2636; padding: 2px 8px; border-radius: 5px; color: #79c0ff; }
  .status.s2 { color: #56d364; } .status.s4, .status.s5 { color: #f85149; }
  .kv { margin-top: 6px; } .kv b { color: #7d8da0; font-weight: 600; font-size: 12px; }
  .prose { color: #c9d4e0; font-size: 1rem; white-space: pre-wrap; max-height: 340px; overflow: auto; }
  .type-error { --accent: #ef4444; } .type-diff { --accent: #22c55e; } .type-terminal { --accent: #eab308; }
  .type-browser { --accent: #06b6d4; } .type-computer { --accent: #14b8a6; } .type-api { --accent: #79c0ff; }
  .type-summary { --accent: #a855f7; } .type-title_card { --accent: #3b82f6; }
  .type-prompt { --accent: #f59e0b; } .type-reply { --accent: #10b981; }
  .scene-enter { animation: pop .45s cubic-bezier(.2,.7,.3,1.2); }
  @keyframes pop { from { opacity: 0; transform: translateY(10px) scale(.985); } to { opacity: 1; transform: none; } }
  .bar { height: 4px; background: #1e2a3a; border-radius: 4px; margin-top: 14px; overflow: hidden; }
  .bar > i { display: block; height: 100%; width: 0; background: var(--accent, #3b82f6); transition: width .1s linear; }
  .controls { display: flex; gap: 10px; align-items: center; margin-top: 14px; color: #8b98a6; font-size: .85rem; }
  button { background: #1b2636; color: #e6edf3; border: 1px solid #2a3a4f; border-radius: 8px; padding: 6px 12px; cursor: pointer; font: inherit; }
  button:hover { background: #243349; }
  .dots { display: flex; gap: 5px; margin-left: auto; flex-wrap: wrap; }
  .dot { width: 7px; height: 7px; border-radius: 50%; background: #2a3a4f; cursor: pointer; }
  .dot.on { background: var(--accent, #3b82f6); }
</style>
</head>
<body>
<div class="stage">
  <h1>\u{1F3AC} ${escapeHtml(docTitle)}</h1>
  <div class="card" id="card">
    <div class="head"><span class="icon" id="icon"></span><span class="title" id="title"></span></div>
    <div class="narration" id="narration"></div>
    <div class="visual" id="visual"></div>
    <div class="bar"><i id="fill"></i></div>
  </div>
  <div class="controls">
    <button id="playPause">\u23F8 Pause</button>
    <button id="prev">\u25C0 Prev</button>
    <button id="next">Next \u25B6</button>
    <span id="counter"></span>
    <span class="dots" id="dots"></span>
  </div>
</div>
<script>
  const SCENES = ${scenesJson};
  let i = 0, playing = true, raf = 0, start = 0;
  const card = document.getElementById('card'), counter = document.getElementById('counter'), dotsEl = document.getElementById('dots');
  SCENES.forEach((_, k) => { const d = document.createElement('span'); d.className = 'dot'; d.onclick = () => go(k); dotsEl.appendChild(d); });
  function paint() {
    const s = SCENES[i];
    card.className = 'card scene-enter type-' + s.type;
    document.getElementById('icon').textContent = s.icon;
    document.getElementById('title').textContent = s.title;
    document.getElementById('narration').textContent = s.narration;
    document.getElementById('visual').innerHTML = s.visual || '';
    counter.textContent = (i + 1) + ' / ' + SCENES.length;
    [...dotsEl.children].forEach((d, k) => d.className = 'dot' + (k === i ? ' on' : ''));
    void card.offsetWidth;
  }
  function tick(t) {
    if (!start) start = t;
    const s = SCENES[i], p = Math.min(1, (t - start) / s.durationMs);
    document.getElementById('fill').style.width = (p * 100) + '%';
    if (p >= 1) { if (i < SCENES.length - 1) { go(i + 1); } else { playing = false; updateBtn(); return; } }
    if (playing) raf = requestAnimationFrame(tick);
  }
  function go(n) { i = Math.max(0, Math.min(SCENES.length - 1, n)); start = 0; cancelAnimationFrame(raf); paint(); if (playing) raf = requestAnimationFrame(tick); }
  function updateBtn() { document.getElementById('playPause').textContent = playing ? '\u23F8 Pause' : '\u25B6 Play'; }
  document.getElementById('playPause').onclick = () => { playing = !playing; updateBtn(); start = 0; if (playing) raf = requestAnimationFrame(tick); else cancelAnimationFrame(raf); };
  document.getElementById('next').onclick = () => go(i + 1);
  document.getElementById('prev').onclick = () => go(i - 1);
  paint(); raf = requestAnimationFrame(tick);
</script>
</body>
</html>
`;
}
export {
  codeEditFromSpan,
  codeEditsForStoryboard,
  compileStoryboard,
  editAnimationText,
  extractCodeEdits,
  reduceToSemanticEvents,
  renderCodeAnimationHtml,
  renderStoryboardHtml,
  renderStoryboardMarkdown
};
//# sourceMappingURL=index.js.map