{
  "schemaVersion": 1,
  "target": "react",
  "name": "context",
  "version": "0.1.1",
  "category": "ai-elements",
  "title": "Context",
  "description": "How much of the model's context window is used: a compact ring and percentage that opens a card with the input, output, and cached token breakdown and the cost.",
  "tags": [
    "ai",
    "agent",
    "context",
    "tokens",
    "usage",
    "cost",
    "meter"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "@base-ui/react": "^1.9.0"
  },
  "registryDependencies": [
    {
      "name": "popover",
      "version": "0.2.2"
    }
  ],
  "docsPath": "/components/context",
  "props": [
    {
      "name": "max",
      "type": "number",
      "description": "Context window size in tokens."
    },
    {
      "name": "used",
      "type": "number",
      "default": "sum of usage",
      "description": "Tokens in the window now."
    },
    {
      "name": "usage",
      "type": "{ input?, output?, cacheRead?, reasoning? }",
      "description": "The token breakdown rows."
    },
    {
      "name": "pricing",
      "type": "{ input, output, cacheRead?, reasoning? }",
      "description": "Prices per million tokens. Adds a cost column and a total."
    },
    {
      "name": "currency",
      "type": "string",
      "default": "\"USD\"",
      "description": "ISO 4217 code for costs."
    },
    {
      "name": "model",
      "type": "ReactNode",
      "description": "Model name at the foot of the card."
    },
    {
      "name": "warnAt / dangerAt",
      "type": "number",
      "default": "0.8 / 0.95",
      "description": "Shares of the window where the meter turns amber and red."
    },
    {
      "name": "side",
      "type": "\"top\" | \"bottom\" | \"left\" | \"right\"",
      "default": "\"top\"",
      "description": "Card side."
    },
    {
      "name": "formatTokens",
      "type": "(value) => string",
      "description": "The compact token format on its own: 950, 84.2K, 1.2M."
    }
  ],
  "accessibility": [
    "The trigger is a button whose label states the share, the token counts, and nearing the limit when it applies; the ring is decorative.",
    "The card opens on hover, keyboard focus, or press (Base UI Popover with openOnHover), so it works without a pointer, and closes with Escape.",
    "Usage is a Base UI Meter (role=\"meter\") with a value text in exact tokens. The breakdown is a description list.",
    "Nearing the limit is said in text as well as color."
  ],
  "states": [
    "normal",
    "warning",
    "danger"
  ],
  "files": [
    {
      "path": "agent/context.tsx",
      "content": "\"use client\";\n\nimport { Meter } from \"@base-ui/react/meter\";\nimport type { ReactNode } from \"react\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"../ui/popover\";\n\nfunction cx(...classes: Array<string | false | null | undefined>) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nexport interface ContextUsage {\n  /** Fresh prompt tokens. */\n  input?: number;\n  /** Tokens the model wrote. */\n  output?: number;\n  /** Prompt tokens read from the cache. */\n  cacheRead?: number;\n  /** Reasoning tokens, when the provider reports them apart from output. */\n  reasoning?: number;\n}\n\n/** Prices per million tokens, in `currency`. */\nexport interface ContextPricing {\n  input: number;\n  output: number;\n  cacheRead?: number;\n  /** Defaults to the output price. */\n  reasoning?: number;\n}\n\nexport interface ContextProps {\n  /** Size of the model's context window, in tokens. */\n  max: number;\n  /** Tokens in the window now. Defaults to the sum of `usage`. */\n  used?: number;\n  /** The breakdown shown in the card. */\n  usage?: ContextUsage;\n  /** Adds a cost column and a total. */\n  pricing?: ContextPricing;\n  /** ISO 4217 code for the cost figures. @default \"USD\" */\n  currency?: string;\n  /** Model name shown at the foot of the card. */\n  model?: ReactNode;\n  /** Share of the window (0 to 1) at which the meter turns amber. @default 0.8 */\n  warnAt?: number;\n  /** Share of the window at which it turns red. @default 0.95 */\n  dangerAt?: number;\n  /** Card side relative to the trigger. @default \"top\" */\n  side?: \"top\" | \"bottom\" | \"left\" | \"right\";\n  /** Classes for the trigger button. */\n  className?: string;\n}\n\nconst compact = new Intl.NumberFormat(\"en\", { notation: \"compact\", maximumFractionDigits: 1 });\nconst exact = new Intl.NumberFormat(\"en\");\n\n/** 950, 84.2K, 1.2M. */\nexport function formatTokens(value: number): string {\n  return compact.format(Math.max(0, Math.round(value)));\n}\n\nfunction formatCost(value: number, currency: string) {\n  const options: Intl.NumberFormatOptions = { style: \"currency\", currency };\n  if (value > 0 && value < 0.01) {\n    options.maximumSignificantDigits = 2;\n  } else {\n    options.minimumFractionDigits = 2;\n    options.maximumFractionDigits = 2;\n  }\n  return new Intl.NumberFormat(\"en\", options).format(value);\n}\n\ntype Level = \"normal\" | \"warn\" | \"danger\";\n\nconst levelText: Record<Level, string> = {\n  normal: \"text-zinc-950 dark:text-white\",\n  warn: \"text-amber-600 dark:text-amber-400\",\n  danger: \"text-red-600 dark:text-red-400\",\n};\n\nconst levelFill: Record<Level, string> = {\n  normal: \"bg-zinc-950 dark:bg-white\",\n  warn: \"bg-amber-500\",\n  danger: \"bg-red-500\",\n};\n\n/**\n * How much of the model's context window is in use: a compact ring and percentage that opens\n * a card on hover, focus, or press with the input, output, and cached token breakdown and\n * what it cost. The ring turns amber near the limit and red when the window is almost full.\n */\nexport function Context({\n  max,\n  used: usedProp,\n  usage = {},\n  pricing,\n  currency = \"USD\",\n  model,\n  warnAt = 0.8,\n  dangerAt = 0.95,\n  side = \"top\",\n  className,\n}: ContextProps) {\n  const used = usedProp ?? (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.reasoning ?? 0);\n  const ratio = max > 0 ? Math.min(1, used / max) : 0;\n  const percent = Math.round(ratio * 100);\n  const level: Level = ratio >= dangerAt ? \"danger\" : ratio >= warnAt ? \"warn\" : \"normal\";\n  const levelWord = level === \"danger\" ? \", nearly full\" : level === \"warn\" ? \", nearing the limit\" : \"\";\n\n  const rows: { label: string; tokens: number; price?: number }[] = [];\n  if (usage.input != null) rows.push({ label: \"Input\", tokens: usage.input, price: pricing?.input });\n  if (usage.cacheRead != null) rows.push({ label: \"Cached\", tokens: usage.cacheRead, price: pricing?.cacheRead ?? pricing?.input });\n  if (usage.output != null) rows.push({ label: \"Output\", tokens: usage.output, price: pricing?.output });\n  if (usage.reasoning != null) rows.push({ label: \"Reasoning\", tokens: usage.reasoning, price: pricing?.reasoning ?? pricing?.output });\n  const costs = rows.map((row) => (row.price != null ? (row.tokens / 1_000_000) * row.price : undefined));\n  const total = pricing ? costs.reduce<number>((sum, cost) => sum + (cost ?? 0), 0) : undefined;\n\n  return (\n    <Popover>\n      <PopoverTrigger\n        openOnHover\n        delay={200}\n        closeDelay={120}\n        aria-label={`Context window: ${percent}% used, ${formatTokens(used)} of ${formatTokens(max)} tokens${levelWord}`}\n        className={cx(\n          \"inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-lg px-2 font-mono text-xs tabular-nums select-none\",\n          \"text-zinc-600 transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none\",\n          \"hover:bg-zinc-950/[0.04] hover:text-zinc-950 data-[popup-open]:bg-zinc-950/[0.06] data-[popup-open]:text-zinc-950\",\n          \"dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white dark:data-[popup-open]:bg-white/[0.09] dark:data-[popup-open]:text-white\",\n          \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n          className,\n        )}\n      >\n        <Ring ratio={ratio} level={level} />\n        <span aria-hidden=\"true\">{percent}%</span>\n      </PopoverTrigger>\n      <PopoverContent side={side} align=\"end\" sideOffset={8} className=\"w-72 p-0\">\n        <div className=\"p-4\">\n          <Meter.Root\n            value={used}\n            min={0}\n            max={max}\n            getAriaValueText={() => `${exact.format(Math.round(used))} of ${exact.format(max)} tokens${levelWord}`}\n          >\n            <div className=\"flex items-baseline justify-between gap-3\">\n              <Meter.Label className=\"text-xs font-medium text-zinc-500\">Context window</Meter.Label>\n              <span className={cx(\"font-mono text-xs tabular-nums\", level === \"normal\" ? \"text-zinc-950 dark:text-white\" : levelText[level])}>\n                {percent}%\n              </span>\n            </div>\n            <p className=\"mt-1 font-mono text-sm text-zinc-950 tabular-nums dark:text-white\">\n              {formatTokens(used)} <span className=\"text-zinc-500\">/ {formatTokens(max)} tokens</span>\n            </p>\n            <Meter.Track className=\"mt-3 h-1 overflow-hidden rounded-full bg-zinc-950/[0.07] dark:bg-white/10\">\n              <Meter.Indicator className={cx(\"h-full rounded-full\", levelFill[level])} />\n            </Meter.Track>\n          </Meter.Root>\n          {level !== \"normal\" ? (\n            <p className={cx(\"mt-2 text-xs\", levelText[level])}>\n              {level === \"danger\" ? \"Almost full. Older messages will be summarized soon.\" : \"Getting close to the limit.\"}\n            </p>\n          ) : null}\n        </div>\n\n        {rows.length ? (\n          <dl className=\"grid grid-cols-[minmax(0,1fr)_auto_auto] gap-x-4 gap-y-1.5 border-t border-zinc-950/[0.07] px-4 py-3 text-xs dark:border-white/[0.08]\">\n            {rows.map((row, index) => (\n              <div key={row.label} className=\"col-span-3 grid grid-cols-subgrid items-baseline\">\n                <dt className=\"text-zinc-600 dark:text-zinc-400\">{row.label}</dt>\n                <dd className=\"text-right font-mono text-zinc-950 tabular-nums dark:text-white\">{formatTokens(row.tokens)}</dd>\n                <dd className=\"min-w-12 text-right font-mono text-zinc-500 tabular-nums\">\n                  {costs[index] != null ? formatCost(costs[index], currency) : pricing ? \"\" : null}\n                </dd>\n              </div>\n            ))}\n          </dl>\n        ) : null}\n\n        {total != null || model != null ? (\n          <div className=\"flex items-baseline justify-between gap-3 border-t border-zinc-950/[0.07] px-4 py-3 text-xs dark:border-white/[0.08]\">\n            <span className=\"min-w-0 truncate text-zinc-500\">{model ?? \"Total\"}</span>\n            {total != null ? (\n              <span className=\"shrink-0 text-zinc-600 dark:text-zinc-400\">\n                {model != null ? \"Total \" : \"\"}\n                <span className=\"font-mono font-medium text-zinc-950 tabular-nums dark:text-white\">{formatCost(total, currency)}</span>\n              </span>\n            ) : null}\n          </div>\n        ) : null}\n      </PopoverContent>\n    </Popover>\n  );\n}\n\n/** A 16px ring: a faint full circle with the used share drawn over it from twelve o'clock. */\nfunction Ring({ ratio, level }: { ratio: number; level: Level }) {\n  const r = 6;\n  const length = 2 * Math.PI * r;\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" className={cx(\"size-4 shrink-0 -rotate-90\", levelText[level])}>\n      <circle cx=\"8\" cy=\"8\" r={r} stroke=\"currentColor\" strokeOpacity=\"0.18\" strokeWidth=\"2\" />\n      <circle\n        cx=\"8\"\n        cy=\"8\"\n        r={r}\n        stroke=\"currentColor\"\n        strokeWidth=\"2\"\n        strokeLinecap={ratio > 0 ? \"round\" : \"butt\"}\n        strokeDasharray={length}\n        strokeDashoffset={length * (1 - ratio)}\n        className=\"transition-[stroke-dashoffset,color] duration-500 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none\"\n      />\n    </svg>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "import { Context } from \"@/components/shaken/agent/context\";\n\nexport default function ContextExample() {\n  return (\n    <div className=\"flex items-center gap-2 rounded-xl border border-zinc-950/10 px-2 py-1.5 dark:border-white/10\">\n      <span className=\"px-1.5 text-sm text-zinc-500\">Ask a follow-up</span>\n      <Context\n        max={200_000}\n        usage={{ input: 61_400, cacheRead: 18_200, output: 4_600 }}\n        pricing={{ input: 3, cacheRead: 0.3, output: 15 }}\n        model=\"Claude Sonnet 5.5\"\n      />\n    </div>\n  );\n}\n"
  }
}
