{
  "schemaVersion": 1,
  "target": "react",
  "name": "stack-trace",
  "version": "0.1.0",
  "category": "ai-elements",
  "title": "Stack Trace",
  "description": "A failed tool call's error with a collapsible list of stack frames that marks app frames, folds library frames, and copies the whole trace.",
  "tags": [
    "ai",
    "agent",
    "error",
    "stack trace",
    "debug",
    "tool call"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "@base-ui/react": "^1.9.0"
  },
  "registryDependencies": [
    {
      "name": "step-list",
      "version": "0.3.0"
    }
  ],
  "docsPath": "/components/stack-trace",
  "props": [
    {
      "name": "stack",
      "type": "string",
      "description": "A raw V8 stack string; parsed into a name, message, and frames."
    },
    {
      "name": "name / message / frames",
      "type": "string / string / { fn?, file, line?, column?, library? }[]",
      "description": "Pass these instead of, or to override, the parsed stack."
    },
    {
      "name": "tool",
      "type": "string",
      "description": "The tool call that failed, shown in the header."
    },
    {
      "name": "durationMs",
      "type": "number",
      "description": "How long the call ran before failing."
    },
    {
      "name": "defaultOpen",
      "type": "boolean",
      "default": "false",
      "description": "Opens the frame list initially."
    },
    {
      "name": "parseStack / isLibraryFrame",
      "type": "functions",
      "description": "The parser and the node_modules and runtime detection, exported for reuse."
    }
  ],
  "accessibility": [
    "The error message is a role alert in a red tinted box; the header pairs the failed glyph with the word failed.",
    "The frame list is a Base UI Collapsible; its trigger states the frame count and how many are in your code.",
    "App frames carry a solid dot and stronger text plus an sr-only your code; library runs fold into a labelled button that reveals them, and a Hide button folds them again.",
    "The copy button is labelled and announces Copied. The list height animates in 220ms; instant with reduced motion."
  ],
  "states": [
    "collapsed",
    "expanded",
    "library frames shown"
  ],
  "files": [
    {
      "path": "agent/stack-trace.tsx",
      "content": "\"use client\";\n\nimport { Collapsible } from \"@base-ui/react/collapsible\";\nimport { type ComponentProps, Fragment, useEffect, useMemo, useRef, useState } from \"react\";\nimport { StatusGlyph } from \"./step-list\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nconst ease = \"ease-[cubic-bezier(0.23,1,0.32,1)]\";\n\nexport interface StackFrame {\n  /** Function name. Anonymous frames leave it unset. */\n  fn?: string;\n  /** File path or URL. */\n  file: string;\n  line?: number;\n  column?: number;\n  /** Library or runtime code rather than the app's own. Detected from the path when unset. */\n  library?: boolean;\n}\n\nexport interface ParsedStack {\n  name: string;\n  message: string;\n  frames: StackFrame[];\n}\n\nconst libraryPattern = /(node_modules|^node:|^internal\\/|\\(native\\)|webpack-internal:\\/\\/\\/\\(?\\.?\\/?node_modules)/;\n\n/** Whether a frame belongs to a dependency or the runtime. */\nexport function isLibraryFrame(frame: StackFrame): boolean {\n  // Frames without a real path, such as `Promise.all (index 2)`, come from the runtime.\n  return frame.library ?? (libraryPattern.test(frame.file) || !/[/\\\\.]/.test(frame.file));\n}\n\n/**\n * Parses a V8 style stack (`Error: message` followed by `    at fn (file:line:col)` lines)\n * into a name, a message, and frames. Lines it does not recognize are skipped.\n */\nexport function parseStack(stack: string): ParsedStack {\n  const lines = stack.split(\"\\n\");\n  const head: string[] = [];\n  const frames: StackFrame[] = [];\n  for (const raw of lines) {\n    const line = raw.trim();\n    const match = /^at (?:(?:async )?(.+?) \\()?(.+?)(?::(\\d+))?(?::(\\d+))?\\)?$/.exec(line);\n    if (match && line.startsWith(\"at \")) {\n      frames.push({ fn: match[1], file: match[2] ?? \"\", line: match[3] ? Number(match[3]) : undefined, column: match[4] ? Number(match[4]) : undefined });\n    } else if (!frames.length && line) {\n      head.push(line);\n    }\n  }\n  const first = head.join(\"\\n\");\n  const colon = first.indexOf(\": \");\n  const name = colon > 0 && /^[\\w$.]+$/.test(first.slice(0, colon)) ? first.slice(0, colon) : \"Error\";\n  const message = name === \"Error\" && colon <= 0 ? first : first.slice(colon + 2);\n  return { name, message, frames };\n}\n\nfunction formatFrame(frame: StackFrame): string {\n  const location = [frame.file, frame.line, frame.column].filter((part) => part !== undefined).join(\":\");\n  return frame.fn ? `    at ${frame.fn} (${location})` : `    at ${location}`;\n}\n\nexport interface StackTraceProps extends Omit<ComponentProps<\"section\">, \"children\"> {\n  /** Error class, for example `TypeError`. */\n  name?: string;\n  message?: string;\n  /** Frames, innermost first. Or pass `stack` and let it parse. */\n  frames?: StackFrame[];\n  /** A raw V8 stack string. Used for the name, message, and frames that are not passed. */\n  stack?: string;\n  /** The tool call that failed, shown in the header. */\n  tool?: string;\n  /** How long the call ran before failing. */\n  durationMs?: number;\n  /** Opens the frame list initially. */\n  defaultOpen?: boolean;\n}\n\n/**\n * A failed tool call's error: the error name and message, then a collapsible list of stack\n * frames. Frames from the app's own code are emphasized and marked; runs of library frames fold\n * into one row until the reader asks for them. Copy puts the whole trace on the clipboard.\n */\nexport function StackTrace({\n  name: nameProp,\n  message: messageProp,\n  frames: framesProp,\n  stack,\n  tool,\n  durationMs,\n  defaultOpen = false,\n  className,\n  ...props\n}: StackTraceProps) {\n  const parsed = useMemo(() => (stack ? parseStack(stack) : undefined), [stack]);\n  const name = nameProp ?? parsed?.name ?? \"Error\";\n  const message = messageProp ?? parsed?.message ?? \"\";\n  const frames = framesProp ?? parsed?.frames ?? [];\n  const [showLibrary, setShowLibrary] = useState(false);\n  const appCount = frames.filter((frame) => !isLibraryFrame(frame)).length;\n  const libraryCount = frames.length - appCount;\n  const copyText = `${name}: ${message}\\n${frames.map(formatFrame).join(\"\\n\")}`;\n\n  // Consecutive library frames fold into one group while they are hidden.\n  const groups = useMemo(() => {\n    const result: { library: boolean; frames: { frame: StackFrame; index: number }[] }[] = [];\n    frames.forEach((frame, index) => {\n      const library = isLibraryFrame(frame);\n      const last = result[result.length - 1];\n      if (last && last.library === library) last.frames.push({ frame, index });\n      else result.push({ library, frames: [{ frame, index }] });\n    });\n    return result;\n  }, [frames]);\n\n  return (\n    <section\n      aria-label={tool ? `${tool} failed` : `${name}: ${message}`}\n      className={cx(\n        \"overflow-hidden rounded-xl border border-red-500/35 bg-white text-left text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]\",\n        \"dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]\",\n        className,\n      )}\n      {...props}\n    >\n      <header className=\"flex items-center gap-2.5 py-2.5 pr-2.5 pl-4\">\n        <StatusGlyph kind=\"failed\" />\n        <p className=\"min-w-0 flex-1 truncate text-sm\">\n          {tool ? (\n            <>\n              <span className=\"font-mono text-[13px] font-medium\">{tool}</span>\n              <span className=\"text-zinc-600 dark:text-zinc-400\"> failed</span>\n            </>\n          ) : (\n            <span className=\"font-medium\">Failed</span>\n          )}\n        </p>\n        {durationMs != null ? <span className=\"font-mono text-xs text-zinc-500 tabular-nums\">{formatDuration(durationMs)}</span> : null}\n        <CopyButton text={copyText} label=\"Copy error and stack trace\" />\n      </header>\n\n      <div className=\"px-4 pb-4\">\n        <p role=\"alert\" className=\"rounded-lg border border-red-500/35 bg-red-500/[0.08] px-3 py-2.5 font-mono text-xs leading-relaxed break-words text-red-700 dark:text-red-300\">\n          <span className=\"font-semibold\">{name}</span>\n          {message ? `: ${message}` : null}\n        </p>\n      </div>\n\n      {frames.length ? (\n        <Collapsible.Root defaultOpen={defaultOpen} className=\"border-t border-zinc-950/[0.07] dark:border-white/[0.08]\">\n          <Collapsible.Trigger\n            className={cx(\n              \"group flex w-full cursor-pointer items-center justify-between gap-3 px-4 py-2.5 text-left text-xs font-medium select-none\",\n              \"text-zinc-600 transition-colors duration-150 hover:bg-zinc-950/[0.03] hover:text-zinc-950 motion-reduce:transition-none\",\n              \"dark:text-zinc-400 dark:hover:bg-white/[0.04] dark:hover:text-white\",\n              \"focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500\",\n            )}\n          >\n            <span>\n              Stack trace\n              <span className=\"ml-2 font-normal text-zinc-500 tabular-nums\">\n                {frames.length} {frames.length === 1 ? \"frame\" : \"frames\"}, {appCount} in your code\n              </span>\n            </span>\n            <svg\n              aria-hidden=\"true\"\n              viewBox=\"0 0 16 16\"\n              className={`size-4 shrink-0 text-zinc-500 transition-transform duration-200 ${ease} group-data-panel-open:rotate-180 motion-reduce:transition-none`}\n            >\n              <path d=\"m4.5 6.25 3.5 3.5 3.5-3.5\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n            </svg>\n          </Collapsible.Trigger>\n          <Collapsible.Panel\n            className={cx(\n              \"h-(--collapsible-panel-height) overflow-hidden\",\n              `transition-[height,opacity] duration-220 ${ease} motion-reduce:transition-none`,\n              \"data-starting-style:h-0 data-starting-style:opacity-0\",\n              \"data-ending-style:h-0 data-ending-style:opacity-0 data-ending-style:duration-180\",\n            )}\n          >\n            <ol className=\"pb-2\" aria-label=\"Stack frames\">\n              {groups.map((group) =>\n                group.library && !showLibrary ? (\n                  <li key={`fold-${group.frames[0]?.index}`}>\n                    <button\n                      type=\"button\"\n                      onClick={() => setShowLibrary(true)}\n                      className={cx(\n                        \"flex w-full cursor-pointer items-center gap-2.5 px-4 py-1 text-left font-mono text-[11px] text-zinc-500\",\n                        \"transition-colors duration-150 hover:bg-zinc-950/[0.03] hover:text-zinc-700 motion-reduce:transition-none dark:hover:bg-white/[0.04] dark:hover:text-zinc-300\",\n                        \"focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500\",\n                      )}\n                    >\n                      <span aria-hidden=\"true\" className=\"flex w-1.5 justify-center\">\n                        <span className=\"h-3 border-l border-dashed border-zinc-400 dark:border-zinc-600\" />\n                      </span>\n                      {group.frames.length} library {group.frames.length === 1 ? \"frame\" : \"frames\"}\n                    </button>\n                  </li>\n                ) : (\n                  <Fragment key={`group-${group.frames[0]?.index}`}>\n                    {group.frames.map(({ frame, index }) => (\n                      <FrameRow key={index} frame={frame} library={group.library} />\n                    ))}\n                  </Fragment>\n                ),\n              )}\n            </ol>\n            {libraryCount > 0 && showLibrary ? (\n              <div className=\"px-4 pb-3\">\n                <button\n                  type=\"button\"\n                  onClick={() => setShowLibrary(false)}\n                  className={cx(\n                    \"-ml-1.5 inline-flex h-7 cursor-pointer items-center rounded-md px-1.5 text-xs font-medium text-zinc-600\",\n                    \"transition-colors duration-150 hover:bg-zinc-950/[0.04] hover:text-zinc-950 motion-reduce:transition-none\",\n                    \"dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white\",\n                    \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n                  )}\n                >\n                  Hide {libraryCount} library {libraryCount === 1 ? \"frame\" : \"frames\"}\n                </button>\n              </div>\n            ) : null}\n          </Collapsible.Panel>\n        </Collapsible.Root>\n      ) : null}\n    </section>\n  );\n}\n\nfunction FrameRow({ frame, library }: { frame: StackFrame; library: boolean }) {\n  const location = [frame.file, frame.line, frame.column].filter((part) => part !== undefined).join(\":\");\n  return (\n    <li className=\"grid grid-cols-[0.375rem_minmax(0,1fr)] items-start gap-x-2.5 px-4 py-1\">\n      <span aria-hidden=\"true\" className=\"flex h-4 items-center\">\n        {library ? null : <span className=\"size-1.5 rounded-full bg-zinc-950 dark:bg-white\" />}\n      </span>\n      <span className=\"min-w-0 font-mono text-xs leading-4 break-words\">\n        <span className={library ? \"text-zinc-500\" : \"font-medium text-zinc-950 dark:text-white\"}>{frame.fn ?? \"<anonymous>\"}</span>{\" \"}\n        <span className={library ? \"text-zinc-400 dark:text-zinc-600\" : \"text-zinc-600 dark:text-zinc-400\"}>{location}</span>\n        <span className=\"sr-only\">{library ? \", library\" : \", your code\"}</span>\n      </span>\n    </li>\n  );\n}\n\n/** An icon button that copies text and confirms with a check for 1.5s; the confirmation is announced. */\nfunction CopyButton({ text, label }: { text: string; label: string }) {\n  const [copied, setCopied] = useState(false);\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  useEffect(() => () => clearTimeout(timer.current), []);\n\n  async function copy() {\n    try {\n      await navigator.clipboard.writeText(text);\n      setCopied(true);\n      clearTimeout(timer.current);\n      timer.current = setTimeout(() => setCopied(false), 1500);\n    } catch {\n      setCopied(false);\n    }\n  }\n\n  return (\n    <button\n      type=\"button\"\n      onClick={copy}\n      aria-label={label}\n      className={cx(\n        \"inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-zinc-500\",\n        \"transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none\",\n        \"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white\",\n        \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n      )}\n    >\n      <svg\n        key={copied ? \"copied\" : \"copy\"}\n        aria-hidden=\"true\"\n        viewBox=\"0 0 16 16\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        className={cx(\n          \"size-4 transition-[opacity,scale] duration-200 starting:scale-90 starting:opacity-0 motion-reduce:transition-none\",\n          ease,\n          copied && \"text-emerald-600 dark:text-emerald-400\",\n        )}\n      >\n        {copied ? (\n          <path d=\"m3.75 8.5 2.75 2.75 5.75-6.5\" />\n        ) : (\n          <>\n            <rect x=\"5.25\" y=\"5.25\" width=\"8\" height=\"8\" rx=\"1.75\" />\n            <path d=\"M10.75 5.25V3.5c0-.97-.78-1.75-1.75-1.75H3.5c-.97 0-1.75.78-1.75 1.75V9c0 .97.78 1.75 1.75 1.75h1.75\" />\n          </>\n        )}\n      </svg>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {copied ? \"Copied\" : \"\"}\n      </span>\n    </button>\n  );\n}\n\nfunction formatDuration(ms: number): string {\n  return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;\n}\n"
    }
  ],
  "example": {
    "content": "import { StackTrace } from \"@/components/shaken/agent/stack-trace\";\n\nconst stack = `TypeError: Cannot read properties of undefined (reading 'tenantId')\n    at resolveTenant (/app/src/db/tenants.ts:41:27)\n    at applyMigration (/app/src/db/migrate.ts:88:19)\n    at async Promise.all (index 2)\n    at async runPending (/app/src/db/migrate.ts:52:5)\n    at async Command.<anonymous> (/app/node_modules/commander/lib/command.js:1092:14)\n    at async Command.parseAsync (/app/node_modules/commander/lib/command.js:1078:5)\n    at async main (/app/scripts/migrate.ts:12:3)\n    at processTicksAndRejections (node:internal/process/task_queues:105:5)`;\n\nexport default function StackTraceExample() {\n  return <StackTrace tool=\"run_migration\" stack={stack} durationMs={1240} defaultOpen className=\"w-full max-w-xl\" />;\n}\n"
  }
}
