# Agent avatar

The agent's face in four looks, 3D plush, glass orb, flat shape or pixel, in any color, acting out its work: it searches with a magnifier, reads, scribbles, asks and hops when it's done.

Tier: free. Type: component. Category: ai. Tags: agent, run, motion.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/agent-avatar.json
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/agent-avatar.tsx`.

## Preview

Live preview: https://pixilui.com/components/agent-avatar

Knobs:

- `family`: `3d`, `2d`, `flat`, `pixel`
- `shape3d`: `orb`, `drop`, `block`, `bean`, `cloud`, `dome`, `clover`, `star`
- `shape2d`: `waves`, `tide`, `ripple`, `bloom`, `star`, `heart`
- `shapeFlat`: `circle`, `squircle`, `pill`, `cloud`, `blob`, `flower`, `egg`, `tri`
- `shapePixel`: `orb`, `drop`, `block`, `bean`, `cloud`, `dome`, `clover`, `star`
- `state`: `live run`, `idle`, `thinking`, `searching`, `reading`, `writing`, `browsing`, `running`, `waiting`, `done`, `failed`, `stopped`
- `color`: `violet`, `pink`, `blue`, `lime`, `tangerine`, `yellow`, `cyan`, `red`

Signature: Turn the run Done and the plush blinks, swaps to happy closed eyes at the blink's midpoint, then hops with a squash, a stretch in the air and a squash to land.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/agent-avatar.tsx, quiet https://pixilui.com/r/standalone/agent-avatar.quiet.tsx.

## Code

`components/pixilui/agent-avatar.tsx`

```tsx
"use client";

import { forwardRef, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type ComponentPropsWithoutRef, type CSSProperties } from "react";
import { cn } from "./lib/utils";

/*
  The agent avatar (H5, locked 30 Nov 2026): the agent's face in four families (3D plush, 2D glass, flat, pixel) that acts
  out its work in eleven states. A port of the locked agent-avatar.js. Looks, motion, face positions, the fur ramp and the
  gaze reach are CSS in foundation.css section 8 (.pixilui-agent-avatar); the drawings (shape outlines, faces, props, pixel
  sprites, the 2D glass filters) are geometry, kept here as markup in the locked templates, word for word: one pass at the
  end (libraryClasses) gives their classes the library's names.

  3D draws a white plush render (an image, 512px webp) under a gradient-map filter computed from the color, so any color
  works: the tables are computed in the browser (they need the color parsed), right after the first render, and updated in
  place when the color changes. The renders and the felt props are served from pixilui.com by default; pass `assets` to
  serve your own copies.
*/

/** The four looks. 3d is the default. */
export type AgentAvatarFamily = "3d" | "2d" | "flat" | "pixel";
/** Each family's shapes (pure shapes: no limbs, antennas or ears). */
export type AgentAvatarShape =
  | "orb" | "drop" | "block" | "bean" | "cloud" | "dome" | "clover" | "star"
  | "waves" | "tide" | "ripple" | "bloom" | "heart"
  | "circle" | "squircle" | "pill" | "blob" | "flower" | "egg" | "tri";
/** The eleven states the avatar acts out. */
export type AgentAvatarState = "idle" | "thinking" | "searching" | "reading" | "writing" | "browsing" | "running" | "waiting" | "done" | "failed" | "stopped";
/** The named colors (saturated toy colors); any CSS color works too. */
export type AgentAvatarColor = "pink" | "blue" | "lime" | "tangerine" | "violet" | "yellow" | "cyan" | "red";
type Cell = [number, number] | [number, number, string];

export const agentAvatarShapes: Record<AgentAvatarFamily, readonly AgentAvatarShape[]> = {
  "3d": ["orb", "drop", "block", "bean", "cloud", "dome", "clover", "star"],
  "2d": ["waves", "tide", "ripple", "bloom", "star", "heart"],
  flat: ["circle", "squircle", "pill", "cloud", "blob", "flower", "egg", "tri"],
  pixel: ["orb", "drop", "block", "bean", "cloud", "dome", "clover", "star"],
};
export const agentAvatarFamilies = Object.keys(agentAvatarShapes) as AgentAvatarFamily[];
export const agentAvatarColors: readonly AgentAvatarColor[] = ["pink", "blue", "lime", "tangerine", "violet", "yellow", "cyan", "red"];
export const agentAvatarStates: readonly AgentAvatarState[] = ["idle", "thinking", "searching", "reading", "writing", "browsing", "running", "waiting", "done", "failed", "stopped"];
const PROP_OF: Partial<Record<AgentAvatarState, string>> = { searching: "magnifier", reading: "book", writing: "pencil" };
/** Where the plush renders and felt props are served by default (shape-<shape>.webp, prop-<prop>.webp). */
export const agentAvatarAssets = "https://pixilui.com/assets/agent-avatar/";

/* ------------------------------------------------------------------ the gradient map (3D) */

const isNamed = (color: string): color is AgentAvatarColor => (agentAvatarColors as readonly string[]).includes(color);
/** The color as the avatar's custom property sets it: a named option reads its token. */
export const agentAvatarColorValue = (color: string) => (isNamed(color) ? `var(--pixilui-agent-avatar-${color})` : color);
const root = () => getComputedStyle(document.documentElement);
let parser: CanvasRenderingContext2D | null | undefined;
// any CSS color (or a named option) to [r, g, b]
function rgbOf(color: string): [number, number, number] {
  const named = isNamed(color) ? root().getPropertyValue(`--pixilui-agent-avatar-${color}`).trim() : color;
  if (parser === undefined) parser = document.createElement("canvas").getContext("2d");
  if (!parser) return [0, 0, 0];
  parser.fillStyle = "#000"; // check-registry-ignore: the locked color parser resets to black first
  parser.fillStyle = named;
  const h = String(parser.fillStyle).replace("#", "");
  return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)) as [number, number, number];
}
// the fur ramp and hue turn, read once from CSS
let FUR: { ramp: [number, string, number][]; turn: number[][]; shadeSat: number; baseSat: number } | undefined;
function fur() {
  if (FUR) return FUR;
  const cs = root(), str = (n: string) => cs.getPropertyValue(n).trim().replace(/^"|"$/g, "");
  // without the foundation's tokens (yet) there is nothing to read; read again next time
  if (!str("--pixilui-agent-avatar-fur-ramp")) return undefined;
  FUR = {
    ramp: str("--pixilui-agent-avatar-fur-ramp").split(",").map((s) => { const [L, k, t] = s.trim().split(/\s+/); return [+L!, k!, +t!] as [number, string, number]; }),
    turn: str("--pixilui-agent-avatar-fur-turn").split(",").map((s) => s.trim().split(/\s+/).map(Number)),
    shadeSat: +cs.getPropertyValue("--pixilui-agent-avatar-fur-shade-sat"), baseSat: +cs.getPropertyValue("--pixilui-agent-avatar-fur-base-sat"),
  };
  return FUR;
}
type V3 = number[];
const mix = (a: V3, b: V3, t: number) => a.map((v, i) => v + (b[i]! - v) * t);
const sat = (v: V3, amt: number) => { const g = (v[0]! + v[1]! + v[2]!) / 3; return v.map((x) => Math.min(255, Math.max(0, g + (x - g) * amt))); };
const toHSL = (c: V3): V3 => { const r = c[0]! / 255, g = c[1]! / 255, b = c[2]! / 255; const mx = Math.max(r, g, b), mn = Math.min(r, g, b), l = (mx + mn) / 2; if (mx === mn) return [0, 0, l];
  const d = mx - mn, s2 = l > .5 ? d / (2 - mx - mn) : d / (mx + mn); const h = mx === r ? (g - b) / d + (g < b ? 6 : 0) : mx === g ? (b - r) / d + 2 : (r - g) / d + 4; return [h * 60, s2, l]; };
const fromHSL = ([h, s2, l]: V3): V3 => { h = ((h! % 360) + 360) % 360; const c = (1 - Math.abs(2 * l! - 1)) * s2!, x = c * (1 - Math.abs((h / 60) % 2 - 1)), m = l! - c / 2;
  const [r, g, b] = h < 60 ? [c, x, 0] : h < 120 ? [x, c, 0] : h < 180 ? [0, c, x] : h < 240 ? [0, x, c] : h < 300 ? [x, 0, c] : [c, 0, x]; return [(r + m) * 255, (g + m) * 255, (b + m) * 255]; };
/** The gradient map for one color: three feFuncR/G/B tables over the white render's luminance (needs the browser). */
export function agentAvatarTables(color: string): [string, string, string] {
  const F = fur();
  if (!F) return ["", "", ""];
  const c = rgbOf(color), K = [0, 0, 0], W = [255, 255, 255], [h, s2, l] = toHSL(c), turn = F.turn.find(([lim]) => h! < lim!)![1]!;
  const stops = F.ramp.map(([L, kind, t]): [number, V3] => [L, kind === "k" ? sat(mix(fromHSL([h! + turn * t, Math.min(1, s2! * F.baseSat), l!]), K, t), F.shadeSat) : kind === "c" ? c : mix(c, W, t)]);
  const N = 40, ch: string[][] = [[], [], []];
  for (let i = 0; i <= N; i++) { const L = i / N; let j = 0; while (j < stops.length - 2 && L > stops[j + 1]![0]) j++;
    const [l0, c0] = stops[j]!, [l1, c1] = stops[j + 1]!, t = Math.min(1, Math.max(0, (L - l0) / (l1 - l0))), v = mix(c0, c1, t);
    for (let k = 0; k < 3; k++) ch[k]!.push((v[k]! / 255).toFixed(3)); }
  return ch.map((a) => a.join(" ")) as [string, string, string];
}

/* ------------------------------------------------------------------ the drawings (locked markup) */

const eye = (side: "l" | "r", n: string) => `<g class="agent-avatar-eye ${side}" transform="translate(${side === 'l' ? -11.5 : 11.5} 0)"><g class="agent-avatar-wink"><g class="agent-avatar-blink"><g class="agent-avatar-eye-open">
    <ellipse class="agent-avatar-bead-ball" rx="4.5" ry="5.2" fill="url(#agent-avatar-b${n})"/><circle class="agent-avatar-glint" cx="-1.5" cy="-2" r="1.45"/><circle class="agent-avatar-glint-2" cx="1.4" cy="1.8" r=".65"/></g>
    <path class="agent-avatar-eye-happy" d="M-4.6 1.8 Q0 -4 4.6 1.8"/><path class="agent-avatar-eye-shut" d="M-4.6 0 Q0 3 4.6 0"/></g></g>
    <path class="agent-avatar-brow ${side}"/></g>`;

function markup3d(shape: AgentAvatarShape, n: string, assets: string, [r, g, b]: [string, string, string]) {
  return `<span class="agent-avatar-shadow"></span><span class="agent-avatar-jump"><span class="agent-avatar-body">
      <svg class="agent-avatar-art" viewBox="0 0 100 100" aria-hidden="true" overflow="visible">
        <defs><radialGradient id="agent-avatar-b${n}" class="agent-avatar-bead" cx="38%" cy="32%" r="75%"><stop offset="0" class="s1"/><stop offset=".55" class="s2"/><stop offset="1" class="s3"/></radialGradient>
          <filter id="agent-avatar-f${n}" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="2"/></filter>
          <filter id="agent-avatar-t${n}" color-interpolation-filters="sRGB" x="0" y="0" width="100%" height="100%">
            <feColorMatrix type="matrix" values=".2126 .7152 .0722 0 0  .2126 .7152 .0722 0 0  .2126 .7152 .0722 0 0  0 0 0 1 0"/>
            <feComponentTransfer><feFuncR type="table" tableValues="${r}"/><feFuncG type="table" tableValues="${g}"/><feFuncB type="table" tableValues="${b}"/></feComponentTransfer></filter></defs>
        <image href="${assets}shape-${shape}.webp" x="0" y="0" width="100" height="100" filter="url(#agent-avatar-t${n})" preserveAspectRatio="xMidYMid meet"/>
        <g class="agent-avatar-face"><g class="agent-avatar-look">
          <g class="agent-avatar-blush" filter="url(#agent-avatar-f${n})"><ellipse cx="-18.5" cy="7.4" rx="5.4" ry="3"/><ellipse cx="18.5" cy="7.4" rx="5.4" ry="3"/></g>
          ${eye('l', n)}${eye('r', n)}<path class="agent-avatar-mouth"/></g></g>
      </svg></span></span>
      ${['magnifier', 'book', 'pencil'].map(k => `<img class="agent-avatar-prop" data-prop="${k}" src="${assets}prop-${k}.webp" alt="" draggable="false">`).join('')}
      <svg class="agent-avatar-fx" viewBox="0 0 100 100" aria-hidden="true" overflow="visible">
        <g class="agent-avatar-think"><circle cx="77" cy="24" r="3"/><circle cx="85" cy="15" r="4.2"/><circle cx="94" cy="4" r="5.8"/></g>
        <g class="agent-avatar-spark"><path d="M81 12 l1.8 4.4 4.4 1.8 -4.4 1.8 -1.8 4.4 -1.8 -4.4 -4.4 -1.8 4.4 -1.8z"/><path d="M17 22 l1.2 3 3 1.2 -3 1.2 -1.2 3 -1.2 -3 -3 -1.2 3 -1.2z"/><path d="M90 40 l.9 2.2 2.2 .9 -2.2 .9 -.9 2.2 -.9 -2.2 -2.2 -.9 2.2 -.9z"/></g>
        <path class="agent-avatar-drop" d="M78 26 C78 26 73 33 73 36 a5 5 0 0 0 10 0 C83 33 78 26 78 26z"/>
        <g class="agent-avatar-ask"><circle cx="83" cy="17" r="9"/><path d="M80.2 14.6 a3 3 0 1 1 4.2 2.7 c-1.1.6-1.4 1.2-1.4 2.4 M83 22.4 v.1"/></g>
        <g class="agent-avatar-doze"><path d="M76 22 h5 l-5 6 h5 M85 11 h4 l-4 5 h4"/></g></svg>`;
}

const FX = `<svg class="agent-avatar-fx" viewBox="0 0 100 100" aria-hidden="true" overflow="visible">
      <g class="agent-avatar-think"><circle cx="77" cy="24" r="3"/><circle cx="85" cy="15" r="4.2"/><circle cx="94" cy="4" r="5.8"/></g>
      <g class="agent-avatar-spark"><path d="M81 12 l1.8 4.4 4.4 1.8 -4.4 1.8 -1.8 4.4 -1.8 -4.4 -4.4 -1.8 4.4 -1.8z"/><path d="M17 22 l1.2 3 3 1.2 -3 1.2 -1.2 3 -1.2 -3 -3 -1.2 3 -1.2z"/><path d="M90 40 l.9 2.2 2.2 .9 -2.2 .9 -.9 2.2 -.9 -2.2 -2.2 -.9 2.2 -.9z"/></g>
      <path class="agent-avatar-drop" d="M78 26 C78 26 73 33 73 36 a5 5 0 0 0 10 0 C83 33 78 26 78 26z"/>
      <g class="agent-avatar-ask"><circle cx="83" cy="17" r="9"/><path d="M80.2 14.6 a3 3 0 1 1 4.2 2.7 c-1.1.6-1.4 1.2-1.4 2.4 M83 22.4 v.1"/></g>
      <g class="agent-avatar-doze"><path d="M76 22 h5 l-5 6 h5 M85 11 h4 l-4 5 h4"/></g></svg>`;
// flat: soft, curvy shapes in a 100 box standing on y 88, with the face centre
const polar = (cx: number, cy: number, rf: (t: number) => number, N = 120) => { const pts: [number, number][] = []; for (let i = 0; i < N; i++) { const t = i / N * Math.PI * 2, r = rf(t); pts.push([cx + r * Math.sin(t), cy - r * Math.cos(t)]); }
  const dy = 88 - Math.max(...pts.map(p => p[1])); return `<path d="M${pts.map(p => `${p[0].toFixed(2)} ${(p[1] + dy).toFixed(2)}`).join(' L')}Z"/>`; };
const squircle = (cx: number, cy: number, a: number, b: number, nn: number) => polar(cx, cy, t => { const c = Math.abs(Math.cos(t)), s2 = Math.abs(Math.sin(t)); return 1 / Math.pow(Math.pow(c / b, nn) + Math.pow(s2 / a, nn), 1 / nn); });
const smooth = (pts: [number, number][]) => { const N = pts.length; let d = `M${pts[0]![0]} ${pts[0]![1]}`;
  for (let i = 0; i < N; i++) { const p0 = pts[(i - 1 + N) % N]!, p1 = pts[i]!, p2 = pts[(i + 1) % N]!, p3 = pts[(i + 2) % N]!;
    d += ` C${(p1[0] + (p2[0] - p0[0]) / 6).toFixed(2)} ${(p1[1] + (p2[1] - p0[1]) / 6).toFixed(2)} ${(p2[0] - (p3[0] - p1[0]) / 6).toFixed(2)} ${(p2[1] - (p3[1] - p1[1]) / 6).toFixed(2)} ${p2[0]} ${p2[1]}`; }
  return `<path d="${d}Z"/>`; };
const FLAT: Record<string, { face: [number, number]; art: string }> = {
  circle: { face: [50, 56], art: `<circle cx="50" cy="58" r="30"/>` },
  squircle: { face: [50, 57], art: squircle(50, 58, 30, 30, 4.2) },
  pill: { face: [50, 66], art: `<rect x="12" y="44" width="76" height="44" rx="22"/>` },
  cloud: { face: [50, 63], art: `<circle cx="33" cy="64" r="17"/><circle cx="51" cy="51" r="20"/><circle cx="68" cy="62" r="17"/><rect x="18" y="62" width="64" height="26" rx="13"/>` },
  blob: { face: [49, 59], art: smooth([[50, 28], [70, 33], [81, 52], [76, 75], [56, 88], [34, 86], [20, 70], [23, 45], [35, 32]]) },
  flower: { face: [50, 58], art: polar(50, 58, t => 26 * (1 + .13 * Math.cos(6 * t))) },
  egg: { face: [50, 62], art: smooth([[50, 25], [65, 30], [74, 48], [74, 68], [65, 83], [50, 88], [35, 83], [26, 68], [26, 48], [35, 30]]) },
  tri: { face: [50, 67], art: `<path d="M40.5 34 Q50 18 59.5 34 L83 71 Q91 87 72 88 L28 88 Q9 87 17 71 Z"/>` },
};
// 2D: bands of the one color inside a glass circle (base, then six bands)
function bands(kind: string) {
  const out: string[] = [], K = 6, P = (d: string, k: number) => `<path class="agent-avatar-band-${k}" d="${d}"/>`, C = (cx: number, cy: number, r: number, k: number) => `<circle class="agent-avatar-band-${k}" cx="${cx}" cy="${cy}" r="${r}"/>`;
  for (let k = 1; k <= K; k++) {
    if (kind === 'waves') { const y = 26 + k * 9.6, a = 4 + (k % 2) * 1.6, ph = k * 7; out.push(P(`M0 ${y} C${18 + ph} ${y - a} ${32 + ph} ${y + a} ${50 + ph / 2} ${y} S${82 - ph / 3} ${y - a} 100 ${y} L100 100 L0 100 Z`, k)); }
    if (kind === 'tide') { const o = k * 10.5 - 6, a = 4.5; out.push(P(`M${o} 100 L${o - 4} ${100 - o * 0} C${o + 6} 70 ${o + 22} ${62 - a} ${o + 34} 40 S${o + 60} 18 ${o + 80} 8 L120 8 L120 100 Z`, k)); }
    if (kind === 'ripple') out.push(C(50, 96, 76 - k * 10.5, k));
    if (kind === 'bloom') { const r = 35 - k * 5.2; const N = 60, pts: string[] = []; for (let i = 0; i < N; i++) { const tt = i / N * Math.PI * 2, rr = r * (1 + .07 * Math.sin(5 * tt + k)); pts.push(`${(50 + rr * Math.cos(tt)).toFixed(2)} ${(60 + rr * Math.sin(tt)).toFixed(2)}`); } out.push(P(`M${pts.join(' L')}Z`, k)); }
    if (kind === 'star') { const z = 46 - k * 7, q = z * .2; out.push(P(`M50 ${57 - z} Q${50 + q} ${57 - q} ${50 + z} 57 Q${50 + q} ${57 + q} 50 ${57 + z} Q${50 - q} ${57 + q} ${50 - z} 57 Q${50 - q} ${57 - q} 50 ${57 - z} Z`, K - k)); }   // the star lightens toward the middle
    if (kind === 'heart') { const z = 1.95 - k * .28; out.push(P(`M50 ${66 + 16 * z} C${50 - 30 * z} ${66 - 2 * z} ${50 - 18 * z} ${66 - 26 * z} 50 ${66 - 12 * z} C${50 + 18 * z} ${66 - 26 * z} ${50 + 30 * z} ${66 - 2 * z} 50 ${66 + 16 * z} Z`, k)); }
  }
  return out.join('');
}
// vector props (2D and flat), beside the body at the right; the outer group places them, the inner one moves
const VPROPS = `
  <g class="agent-avatar-vprop" data-prop="magnifier" transform="translate(88 56) rotate(-16) scale(.9)"><g class="agent-avatar-prop-move">
    <rect x="-2.4" y="7" width="4.8" height="15" rx="2.4" class="agent-avatar-p-handle"/><circle r="9.4" class="agent-avatar-p-ring"/><circle r="6.6" class="agent-avatar-p-lens"/><path d="M-3.6 -2.6 A4.6 4.6 0 0 1 1 -4.4" class="agent-avatar-p-glint"/></g></g>
  <g class="agent-avatar-vprop" data-prop="book" transform="translate(89 74) rotate(-8) scale(.9)"><g class="agent-avatar-prop-move">
    <path d="M-13 -9 Q-6 -11.6 0 -8.6 Q6 -11.6 13 -9 L13 9 Q6 6.6 0 9.4 Q-6 6.6 -13 9 Z" class="agent-avatar-p-cover"/>
    <path d="M-11.4 -7.6 Q-5.6 -9.6 -.8 -7 L-.8 7.8 Q-5.6 5.6 -11.4 7.4 Z M11.4 -7.6 Q5.6 -9.6 .8 -7 L.8 7.8 Q5.6 5.6 11.4 7.4 Z" class="agent-avatar-p-page"/>
    <path d="M-9 -3.6 L-3.4 -3 M-9 0 L-3.4 .6 M3.4 -3 L9 -3.6 M3.4 .6 L9 0" class="agent-avatar-p-line"/></g></g>
  <g class="agent-avatar-vprop" data-prop="pencil" transform="translate(87 80) rotate(-40) scale(.9)"><g class="agent-avatar-prop-move">
    <rect x="-9" y="-3.6" width="17" height="7.2" rx="1" class="agent-avatar-p-wood"/><rect x="8" y="-3.6" width="3.4" height="7.2" class="agent-avatar-p-band"/><rect x="11.4" y="-3.6" width="4.4" height="7.2" rx="2" class="agent-avatar-p-rubber"/>
    <path d="M-9 -3.6 L-16 0 L-9 3.6 Z" class="agent-avatar-p-tip"/><path d="M-13.4 -1.3 L-16 0 L-13.4 1.3 Z" class="agent-avatar-p-lead"/></g></g>`;
// faces: flat = gentle capsule eyes and a small smile; 2D = a tiny drawn face, scaled so the lines stay fine
function familyFace(family: string) {
  if (family === 'flat') {
    const eye = (side: string) => `<g class="agent-avatar-eye ${side}" transform="translate(${side === 'l' ? -9 : 9} 0)"><g class="agent-avatar-wink"><g class="agent-avatar-blink"><g class="agent-avatar-eye-open">
        <rect class="agent-avatar-dot" x="-2.7" y="-4.3" width="5.4" height="8.6" rx="2.7"/><circle class="agent-avatar-glint" cx="-.8" cy="-2.2" r="1"/></g>
        <path class="agent-avatar-eye-happy" d="M-4.4 1.6 Q0 -3.6 4.4 1.6"/><path class="agent-avatar-eye-shut" d="M-4.4 0 Q0 3 4.4 0"/></g></g>
        <path class="agent-avatar-brow ${side}"/></g>`;
    return `<g class="agent-avatar-look"><g transform="scale(1.3)">${eye('l')}${eye('r')}<path class="agent-avatar-mouth"/></g></g>`;
  }
  const eye = (side: string) => `<g class="agent-avatar-eye ${side}" transform="translate(${side === 'l' ? -11 : 11} 0)"><g class="agent-avatar-wink"><g class="agent-avatar-blink"><g class="agent-avatar-eye-open"><circle class="agent-avatar-dot" r="3.4"/></g>
        <path class="agent-avatar-eye-happy" d="M-4.6 1.8 Q0 -4 4.6 1.8"/><path class="agent-avatar-eye-shut" d="M-4.6 0 Q0 3 4.6 0"/></g></g><path class="agent-avatar-brow ${side}"/></g>`;
  return `<g class="agent-avatar-look"><g class="agent-avatar-face-scale" transform="scale(.7)">${eye('l')}${eye('r')}<path class="agent-avatar-mouth"/></g></g>`;
}
// pixel: a 10 by 10 grid in shades of the one color (no outline); e = the eye row; eyes 1 by 2 at columns 3 and 6
const PIX: Record<string, { e: number; g?: [number, number]; rows: string[] }> = {
  orb: { e: 4, rows: ['...xxxx...', '.xxxxxxxx.', '.xxxxxxxx.', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', '.xxxxxxxx.', '.xxxxxxxx.', '...xxxx...'] },
  drop: { e: 5, rows: ['....xx....', '....xx....', '...xxxx...', '..xxxxxx..', '.xxxxxxxx.', '.xxxxxxxx.', 'xxxxxxxxxx', 'xxxxxxxxxx', '.xxxxxxxx.', '..xxxxxx..'] },
  block: { e: 4, rows: ['.xxxxxxxx.', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', '.xxxxxxxx.'] },
  bean: { e: 5, rows: ['..........', '..........', '..........', '..........', '.xxxxxxxx.', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', '.xxxxxxxx.'] },
  cloud: { e: 5, rows: ['..........', '....xxx...', '.xx.xxxx..', 'xxxxxxxxx.', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', '.xxxxxxxx.'] },
  dome: { e: 6, rows: ['..........', '..........', '....xx....', '...xxxx...', '..xxxxxx..', '.xxxxxxxx.', 'xxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxx', '.xxxxxxxx.'] },
  clover: { e: 4, rows: ['.xxx..xxx.', 'xxxxxxxxxx', 'xxxxxxxxxx', '.xxxxxxxx.', '..xxxxxx..', '..xxxxxx..', '.xxxxxxxx.', 'xxxxxxxxxx', 'xxxxxxxxxx', '.xxx..xxx.'] },
  star: { e: 4, g: [2, 4], rows: ['....xx....', '....xx....', '...xxxx...', 'xxxxxxxxxx', '.xxxxxxxx.', '..xxxxxx..', '..xxxxxx..', '.xxxxxxxx.', '.xxx..xxx.', 'xx......xx'] },
};
const sprite = (rows: string[], r0: number, c0: number, cls: string) => rows.flatMap((row, r) => [...row].map((ch, c) => ch === '.' ? '' : `<rect x="${c0 + c}" y="${r0 + r}" width="1" height="1" class="${cls}${ch}"/>`)).join('');
const PXPROPS = { magnifier: ['.yy..', 'yllY.', 'yllY.', '.YY..', '...b.', '....b'], book: ['ll.ll', 'lkgkl', 'llgll', 'gg.gg'], pencil: ['tyyyr', 'dyyyr'] };
const PXFX = { ask: ['ooo', '..o', '.o.', '...', '.o.'], z: ['zzz', '..z', '.z.', 'zzz'] };
function pixelSVG(shape: string) {
  const P = PIX[shape]!;
  // shades: deep along the bottom, a shade down the right, light on the top-left edge, a two-pixel glint
  const on = (r: number, c: number) => P.rows[r]! && P.rows[r][c]! === 'x', rows = P.rows.map((r) => [...r].reduce((m, ch) => m + (ch === 'x' ? 1 : 0), 0));
  const t0 = rows.findIndex(m => m >= 4), [gr, gc] = P.g || [t0 + 1, P.rows[t0 + 1]!.indexOf('x') + 1];
  let body = '';
  P.rows.forEach((row, r) => [...row].forEach((ch, c) => {
    if (ch !== 'x') return;
    const k = (r === gr && (c === gc || c === gc + 1)) ? 'g' : !on(r + 1, c) ? 'd' : (!on(r, c + 1) || (!on(r + 2, c) && c >= 5)) ? 's' : ((!on(r - 1, c) || !on(r, c - 1)) && r < 6) ? 'h' : 'b';
    body += `<rect x="${c}" y="${r}" width="1" height="1" class="agent-avatar-px-${k}"/>`;
  }));
  const er = P.e, eyes = (cls: string, L: Cell[], R: Cell[] = L) => `<g class="agent-avatar-px-eye ${cls}">${([[3, L], [6, R]] as [number, Cell[]][]).map(([c0, cells]) => cells.map(([r, c, k]) => `<rect x="${c0 + c}" y="${er + r}" width="1" height="1" class="agent-avatar-px-${k || 'i'}"/>`).join('')).join('')}</g>`;
  return `<svg class="agent-avatar-art agent-avatar-px" viewBox="0 0 10 10" shape-rendering="crispEdges" aria-hidden="true" overflow="visible">
    <g class="agent-avatar-confetti">${[[-4, -3, 'h'], [4, -4, 'g'], [-5, 1, 'd'], [5, 0, 'h'], [-3, 4, 'g'], [3, 5, 'd'], [0, -5, 'h'], [-1, 5, 'y'], [6, 3, 'y'], [-6, -1, 'y']].map(([dx, dy, k]) => `<rect x="4.5" y="4.5" width="1" height="1" class="agent-avatar-px-${k}" style="--agent-avatar-dx:${dx}px;--agent-avatar-dy:${dy}px"/>`).join('')}</g>
    <g class="agent-avatar-pxbody">${body}</g>
    <g class="agent-avatar-look">
      ${eyes('open', [[0, 0], [1, 0]])}
      ${eyes('wide', [[0, -1], [0, 0], [1, -1], [1, 0]], [[0, 0], [0, 1], [1, 0], [1, 1]])}
      ${eyes('shut', [[1, -1], [1, 0]], [[1, 0], [1, 1]])}
      ${eyes('happy', [[1, -1], [0, 0], [1, 1]])}
      ${eyes('sad', [[0, 0], [1, 0]], [[0, 0], [1, 0], [2, 0, 't']])}
      ${eyes('set', [[0, -1], [1, 0], [2, -1]], [[0, 1], [1, 0], [2, 1]])}
      <g class="agent-avatar-px-eye agent-avatar-px-mouth"><rect x="4" y="${er + 2}" width="2" height="1" class="agent-avatar-px-i"/></g>
    </g>
    <g class="agent-avatar-pxprop" data-prop="magnifier"><g class="agent-avatar-prop-move">${sprite(PXPROPS.magnifier, 3, 8, 'agent-avatar-pp-')}</g></g>
    <g class="agent-avatar-pxprop" data-prop="book"><g class="agent-avatar-prop-move">${sprite(PXPROPS.book, 6, 8, 'agent-avatar-pp-')}</g></g>
    <g class="agent-avatar-pxprop" data-prop="pencil"><g class="agent-avatar-prop-move">${sprite(PXPROPS.pencil, 8, 7, 'agent-avatar-pp-')}</g></g>
    <g class="agent-avatar-pxfx agent-avatar-think"><rect x="8" y="1" width="1" height="1"/><rect x="9" y="-1" width="1" height="1"/><rect x="10" y="-3" width="2" height="2"/></g>
    <g class="agent-avatar-pxfx agent-avatar-spark"><path d="M8 -2h1v1h1v1h-1v1h-1v-1h-1v-1h1z"/><path d="M-1 1h1v1h1v1h-1v1h-1v-1h-1v-1h1z"/></g>
    <g class="agent-avatar-pxfx agent-avatar-ask">${sprite(PXFX.ask, -3, 8, 'agent-avatar-pf-')}</g>
    <g class="agent-avatar-pxfx agent-avatar-drop"><rect x="8" y="1" width="1" height="1"/><rect x="8" y="2" width="1" height="1"/></g>
    <g class="agent-avatar-pxfx agent-avatar-doze">${sprite(PXFX.z, -2, 8, 'agent-avatar-pf-')}</g>
  </svg>`;
}
function familyMarkup(family: string, shape: string, n: string) {
  let art: string;
  if (family === 'pixel') art = pixelSVG(shape);
  else {
    const defs = family === '2d' ? `<defs><clipPath id="agent-avatar-c${n}"><circle cx="50" cy="55" r="33"/></clipPath>
        <filter id="agent-avatar-blur${n}" x="-20%" y="-20%" width="140%" height="140%"><feGaussianBlur stdDeviation="1.7"/></filter>
        <radialGradient id="agent-avatar-sheen${n}" cx="34%" cy="22%" r="72%"><stop offset="0" class="agent-avatar-sheen-a"/><stop offset=".55" class="agent-avatar-sheen-b"/></radialGradient>
        <filter id="agent-avatar-grain${n}" x="0" y="0" width="100%" height="100%"><feTurbulence type="fractalNoise" baseFrequency="1.4" numOctaves="2" seed="7"/><feColorMatrix type="saturate" values="0"/><feComponentTransfer><feFuncA type="table" tableValues="0 .09"/></feComponentTransfer></filter></defs>` : '';
    const fc = family === '2d' ? [50, 48] : FLAT[shape]!.face;
    const body = family === 'flat' ? `<g class="agent-avatar-fill">${FLAT[shape]!.art}</g>`
      : `<g clip-path="url(#agent-avatar-c${n})"><g class="agent-avatar-bands" filter="url(#agent-avatar-blur${n})"><rect class="agent-avatar-band-base agent-avatar-band-${shape === 'star' ? 6 : 0}" x="0" y="0" width="100" height="100"/>${bands(shape)}</g>
          <circle class="agent-avatar-frost" cx="50" cy="55" r="33"/><circle cx="50" cy="55" r="33" fill="url(#agent-avatar-sheen${n})"/><rect x="17" y="22" width="66" height="66" filter="url(#agent-avatar-grain${n})"/>
          <path class="agent-avatar-gloss" d="M28 40 C32 30 42 25 52 25.5 C44 28 37 33 33 42 C31.5 45 27 44 28 40 Z" filter="url(#agent-avatar-blur${n})"/></g>
          <circle class="agent-avatar-rim" cx="50" cy="55" r="32.4"/>`;
    art = `<svg class="agent-avatar-art" viewBox="0 0 100 100" aria-hidden="true" overflow="visible">${defs}${body}
      <g transform="translate(${fc[0]!} ${fc[1]!})">${familyFace(family)}</g>${VPROPS}</svg>`;
  }
  return `<span class="agent-avatar-shadow"></span><span class="agent-avatar-jump"><span class="agent-avatar-body">${art}</span></span>${family !== 'pixel' ? FX : ''}`;
}

/* ------------------------------------------------------------------ the library's class names */

/** The locked templates' short part names, and their library names (scripts/locked-elements/agent-avatar.ts). */
const RENAME: Record<string, string> = {
  s1: "pixilui-agent-avatar-s1", s2: "pixilui-agent-avatar-s2", s3: "pixilui-agent-avatar-s3",
  l: "pixilui-agent-avatar-l", r: "pixilui-agent-avatar-r",
  open: "pixilui-agent-avatar-px-open", wide: "pixilui-agent-avatar-px-wide", shut: "pixilui-agent-avatar-px-shut",
  happy: "pixilui-agent-avatar-px-happy", sad: "pixilui-agent-avatar-px-sad", set: "pixilui-agent-avatar-px-set",
};
/** The locked templates' class names and inline custom properties (the confetti's --agent-avatar-dx), as the library's. */
const libraryClasses = (html: string) =>
  html
    .replace(/class="([^"]*)"/g, (_, list: string) => `class="${list.split(/\s+/).filter(Boolean).map((c) => RENAME[c] ?? (c.startsWith("agent-avatar") ? `pixilui-${c}` : c)).join(" ")}"`) // brand-allow
    .replace(/--agent-avatar-/g, "--pixilui-agent-avatar-");

/**
 * The avatar's inner markup for a family and shape: the locked drawings with the library's class names. `n` makes its
 * ids unique on the page. 3D's gradient-map tables are given, or left empty for the browser to fill (agentAvatarTables).
 */
export function agentAvatarMarkup(family: AgentAvatarFamily, shape: AgentAvatarShape, n: string, { assets = agentAvatarAssets, tables = ["", "", ""] as [string, string, string] } = {}) {
  const list = agentAvatarShapes[family];
  const s = list.includes(shape) ? shape : list[0]!;
  return libraryClasses(family === "3d" ? markup3d(s, n, assets, tables) : familyMarkup(family, s, n));
}

/** The avatar's accessible name: "<name>, <state>" (the name alone when idle). */
export const agentAvatarLabel = (name: string, state: AgentAvatarState, words: Partial<Record<AgentAvatarState, string>> = {}) => (state === "idle" ? name : `${name}, ${words[state] ?? state}`);

/* ------------------------------------------------------------------ gaze (2D, flat, pixel) */

// live avatars look toward the pointer; the CSS applies it only while idle or waiting. How far each family looks
// (--pixilui-agent-avatar-gaze-reach) and how near the pointer must be (--pixilui-agent-avatar-gaze-range) are in CSS.
type Gazer = HTMLElement & { _gaze?: { reach: number; range: number; lift: number } };
let gazing = 0;
let gp: [number, number] | null = null;
let raf = 0;
function gaze() {
  raf = 0;
  if (!gp || matchMedia("(prefers-reduced-motion: reduce)").matches) return;
  document.querySelectorAll<Gazer>('.pixilui-agent-avatar:not([data-frozen]):not([data-family="3d"])').forEach((el) => {
    const r = el.getBoundingClientRect(); if (r.bottom < 0 || r.top > innerHeight) return;
    if (!el._gaze) { const cs = getComputedStyle(el); el._gaze = { reach: +cs.getPropertyValue("--pixilui-agent-avatar-gaze-reach"), range: +cs.getPropertyValue("--pixilui-agent-avatar-gaze-range"), lift: +cs.getPropertyValue("--pixilui-agent-avatar-gaze-lift") }; }
    const G = el._gaze, dx = gp![0] - (r.left + r.width / 2), dy = gp![1] - (r.top + r.height / 2), d = Math.hypot(dx, dy) || 1, k = Math.min(1, d / (r.width * G.range));
    let gx = dx / d * k * G.reach, gy = dy / d * k * G.reach * G.lift; if (el.dataset.family === "pixel") { gx = Math.round(gx); gy = Math.round(gy); }
    el.style.setProperty("--pixilui-agent-avatar-gaze-x", gx.toFixed(2) + "px"); el.style.setProperty("--pixilui-agent-avatar-gaze-y", gy.toFixed(2) + "px"); el.style.setProperty("--pixilui-agent-avatar-gaze-n", (dx / d * k).toFixed(3));
  });
}
const onMove = (e: PointerEvent) => { gp = [e.clientX, e.clientY]; if (!raf) raf = requestAnimationFrame(gaze); };
const onLeave = () => { gp = null; document.querySelectorAll<HTMLElement>(".pixilui-agent-avatar").forEach((el) => ["x", "y", "n"].forEach((a) => el.style.removeProperty(`--pixilui-agent-avatar-gaze-${a}`))); };
/** One pair of listeners for the page, while any live avatar that looks is mounted. */
function watchGaze() {
  if (!gazing++) { addEventListener("pointermove", onMove, { passive: true }); document.addEventListener("pointerleave", onLeave); }
  return () => { if (!--gazing) { removeEventListener("pointermove", onMove); document.removeEventListener("pointerleave", onLeave); } };
}

/* ------------------------------------------------------------------ the component */

export type AgentAvatarProps = Omit<ComponentPropsWithoutRef<"span">, "children" | "color"> & {
  /** The look: 3d plush (default), 2d glass, flat or pixel. */
  family?: AgentAvatarFamily;
  /** One of the family's shapes (agentAvatarShapes[family]); the family's first by default. */
  shape?: AgentAvatarShape;
  /** A named color (pink, blue, lime, tangerine, violet, yellow, cyan, red) or any CSS color. */
  color?: AgentAvatarColor | (string & {});
  /** What the agent is doing. Every change blinks; done hops on arrival, failed shivers once. */
  state?: AgentAvatarState;
  /** CSS pixels. Under 56 the props hide; under 36 the ornaments grow 1.75x so the state still reads. */
  size?: number;
  /** The agent's name, the start of its accessible name ("Ada, searching"). */
  name?: string;
  /** The words for each state in the accessible name, for translation (default: the state's id). */
  stateLabels?: Partial<Record<AgentAvatarState, string>>;
  /** Hold one moment of the state's loops (seconds, negative is into the loop), for stills and sheets. No gaze. */
  at?: number;
  /** Where the 3D renders and props are served (a folder URL ending in /). Defaults to pixilui.com. */
  assets?: string;
};

/**
 * The agent's face that acts out its work: it ponders with thought bubbles, sweeps a magnifier while it searches, reads,
 * scribbles, sweats while it runs, asks with a question bubble, hops when it's done and dozes when it stops.
 */
export const AgentAvatar = forwardRef<HTMLSpanElement, AgentAvatarProps>(function AgentAvatar(
  { family = "3d", shape, color = "blue", state = "idle", size = 64, name = "Agent", stateLabels, at, assets = agentAvatarAssets, className, style, ...rest },
  ref,
) {
  const el = useRef<HTMLSpanElement>(null);
  useImperativeHandle(ref, () => el.current!, []);
  const n = useId().replace(/[^\w-]/g, "");
  const fam = agentAvatarFamilies.includes(family) ? family : "3d";
  const list = agentAvatarShapes[fam];
  const s = shape && list.includes(shape) ? shape : list[0]!;
  const html = useMemo(() => ({ __html: agentAvatarMarkup(fam, s, n, { assets }) }), [fam, s, n, assets]);
  const frozen = at !== undefined;

  // 3D: the gradient-map tables for the color, written in place (no blink, no reset of the loops)
  useLayoutEffect(() => {
    const f = el.current?.querySelector('filter[id^="agent-avatar-t"]');
    if (!f) return;
    const [r, g, b] = agentAvatarTables(color);
    f.querySelector("feFuncR")?.setAttribute("tableValues", r);
    f.querySelector("feFuncG")?.setAttribute("tableValues", g);
    f.querySelector("feFuncB")?.setAttribute("tableValues", b);
  }, [color, html]);

  // a change of state: the eyes blink and the new look swaps in while they are shut; one-shot moments play on arrival.
  // The first render plays nothing.
  const first = useRef(true);
  useLayoutEffect(() => {
    const node = el.current;
    if (first.current || !node) {
      first.current = false;
      return;
    }
    node.removeAttribute("data-changed");
    void node.offsetWidth;
    node.setAttribute("data-changed", "");
    if (fam !== "pixel") return;
    node.setAttribute("data-winking", "");
    const timer = setTimeout(() => node.removeAttribute("data-winking"), parseFloat(getComputedStyle(node).getPropertyValue("--pixilui-agent-avatar-px-wink")) || 180);
    return () => clearTimeout(timer);
  }, [state, fam]);

  // 2D, flat and pixel look toward the pointer while idle or waiting (the CSS applies it)
  useEffect(() => {
    if (fam === "3d" || frozen) return;
    return watchGaze();
  }, [fam, frozen]);

  const vars = {
    "--pixilui-agent-avatar-size": `${size}px`,
    "--pixilui-agent-avatar-color": agentAvatarColorValue(color),
    ...(frozen ? { "--pixilui-agent-avatar-at": `${at}s` } : {}),
    ...style,
  } as CSSProperties;
  return (
    <span
      ref={el}
      className={cn("pixilui-agent-avatar", className)}
      data-frozen={frozen ? "" : undefined}
      data-small={size < 36 ? "" : undefined}
      data-compact={size < 56 ? "" : undefined}
      data-family={fam}
      data-shape={s}
      data-state={state}
      data-prop={PROP_OF[state]}
      role="img"
      aria-label={agentAvatarLabel(name, state, stateLabels)}
      style={vars}
      dangerouslySetInnerHTML={html}
      {...rest}
    />
  );
});

/* ------------------------------------------------------------------ simulation */

/** One step of a simulated run: the state, and how long it lasts (ms). */
export type AgentAvatarStep = { state: AgentAvatarState; ms: number };
const RUN: AgentAvatarStep[] = [
  { state: "idle", ms: 1600 },
  { state: "thinking", ms: 2400 },
  { state: "searching", ms: 2600 },
  { state: "reading", ms: 2600 },
  { state: "writing", ms: 2800 },
  { state: "waiting", ms: 3200 },
  { state: "running", ms: 2400 },
  { state: "done", ms: 3000 },
];

/**
 * Plays a believable run for demos and tests, at human speed: idle, thinking, searching, reading, writing, waiting on you,
 * running, done, then again. Pass your own steps. With autoplay false it holds the first step and runs no timers.
 */
export function useAgentAvatarSimulation({ steps = RUN, autoplay = true, loop = true }: { steps?: AgentAvatarStep[]; autoplay?: boolean; loop?: boolean } = {}) {
  const [at, setAt] = useState(0);
  useEffect(() => {
    if (!autoplay) return;
    const step = steps[at];
    if (!step || (!loop && at === steps.length - 1)) return;
    const timer = setTimeout(() => setAt((i) => (i + 1) % steps.length), step.ms);
    return () => clearTimeout(timer);
  }, [at, autoplay, loop, steps]);
  return { state: steps[at]?.state ?? "idle", index: at };
}
```

## Usage

When to use:

- The agent's face in agent lists, inboxes, run headers, stacks and the working line: who it is (shape and color) and what it is doing (eleven states) at once.
- A product with several agents: give each a family, shape and color of its own and keep them.
- 24 to 240px. Under 56 the props hide; under 36 the ornaments grow so the state still reads.

When not to use:

- A person: use the avatar (initials, figure or photo).
- Beside the activity mark: the mark leads the trail's working line, the avatar is the face; one or the other.
- A run's status in words: pair it with agent status.

```tsx
import { AgentAvatar, useAgentAvatarSimulation, type AgentAvatarFamily, type AgentAvatarShape, type AgentAvatarState } from "@/components/pixilui/agent-avatar";

// The first option of each knob is the demo's default; the docs preview starts there.
// Every family has its own shapes (agentAvatarShapes), so each family has its own Shape row, as on the lock.
export const knobs = {
  family: ["3d", "2d", "flat", "pixel"],
  shape3d: ["orb", "drop", "block", "bean", "cloud", "dome", "clover", "star"],
  shape2d: ["waves", "tide", "ripple", "bloom", "star", "heart"],
  shapeFlat: ["circle", "squircle", "pill", "cloud", "blob", "flower", "egg", "tri"],
  shapePixel: ["orb", "drop", "block", "bean", "cloud", "dome", "clover", "star"],
  state: ["live run", "idle", "thinking", "searching", "reading", "writing", "browsing", "running", "waiting", "done", "failed", "stopped"],
  color: ["violet", "pink", "blue", "lime", "tangerine", "yellow", "cyan", "red"],
} as const;

const words: Record<AgentAvatarState, string> = {
  idle: "Idle",
  thinking: "Thinking",
  searching: "Searching the help center",
  reading: "Reading 3 of 5 sources",
  writing: "Writing the reply",
  browsing: "Browsing stripe.com/docs",
  running: "Running a refund check",
  waiting: "Waiting on you",
  done: "Done in 2:14",
  failed: "Failed: card declined",
  stopped: "Stopped by Maya Rao",
};
const team: { name: string; family: AgentAvatarFamily; shape: "cloud" | "waves" | "blob" | "clover"; color: string }[] = [
  { name: "Support agent", family: "3d", shape: "cloud", color: "violet" },
  { name: "Billing agent", family: "2d", shape: "waves", color: "cyan" },
  { name: "Research agent", family: "flat", shape: "blob", color: "tangerine" },
];

// The docs site serves the plush renders itself; in your app leave assets out (pixilui.com) or point it at your own copy.
const ASSETS = "/assets/agent-avatar/";

/** One agent large, acting out a run, over its team list at 32px. */
export default function AgentAvatarDemo({
  family = "3d",
  shape3d = "orb",
  shape2d = "waves",
  shapeFlat = "circle",
  shapePixel = "orb",
  state = "live run",
  color = "violet",
}: KnobValues<typeof knobs>) {
  const run = useAgentAvatarSimulation({ autoplay: state === "live run" });
  const now: AgentAvatarState = state === "live run" ? run.state : state;
  const shape: AgentAvatarShape = { "3d": shape3d, "2d": shape2d, flat: shapeFlat, pixel: shapePixel }[family];
  return (
    <div className="flex w-full max-w-md flex-col items-center gap-6 rounded-panel bg-surface p-8 elevation-raised">
      <AgentAvatar family={family} shape={shape} color={color} state={now} size={160} name="Support agent" assets={ASSETS} />
      <span className="type-label text-secondary">{words[now]}</span>
      <ul className="flex w-full flex-col divide-y divide-divider">
        {team.map((a, i) => (
          <li key={a.name} className="flex items-center gap-3 py-2">
            <AgentAvatar family={a.family} shape={a.shape} color={a.color} state={i === 0 ? now : i === 1 ? "done" : "idle"} size={32} name={a.name} assets={ASSETS} />
            <span className="type-label text-foreground">{a.name}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `family` | `"3d" \| "2d" \| "flat" \| "pixel"` | `"3d"` | The look: 3d plush (default), 2d glass, flat or pixel. |
| `shape` | `"orb" \| "drop" \| "block" \| "bean" \| "cloud" \| "dome" \| "clover" \| "star" \| "waves" \| "tide" \| "ripple" \| "bloom" \| "heart" \| "circle" \| "squircle" \| "pill" \| "blob" \| "flower" \| "egg" \| "tri"` |  | One of the family's shapes (agentAvatarShapes[family]); the family's first by default. |
| `color` | `AgentAvatarColor \| (string & {})` | `"blue"` | A named color (pink, blue, lime, tangerine, violet, yellow, cyan, red) or any CSS color. |
| `state` | `"idle" \| "thinking" \| "searching" \| "reading" \| "writing" \| "browsing" \| "running" \| "waiting" \| "done" \| "failed" \| "stopped"` | `"idle"` | What the agent is doing. Every change blinks; done hops on arrival, failed shivers once. |
| `size` | `number` | `64` | CSS pixels. Under 56 the props hide; under 36 the ornaments grow 1.75x so the state still reads. |
| `name` | `string` | `"Agent"` | The agent's name, the start of its accessible name ("Ada, searching"). |
| `stateLabels` | `Partial<Record<AgentAvatarState, string>>` |  | The words for each state in the accessible name, for translation (default: the state's id). |
| `at` | `number` |  | Hold one moment of the state's loops (seconds, negative is into the loop), for stills and sheets. No gaze. |
| `assets` | `string` | `agentAvatarAssets` | Where the 3D renders and props are served (a folder URL ending in /). Defaults to pixilui.com. |

Also accepts every native `<span>` attribute except `color`, and a ref to it.

## Keyboard

- `Tab`: Never takes focus: put the avatar inside the row or button that carries the action.

## Accessibility

- role img with the name and the state ("Ada, searching"; the name alone when idle), updated on every change; stateLabels translates the state words.
- The drawing is aria-hidden. State is never color alone: the face, the prop and the ornaments show it.
- Reduced motion: no blink, no loops; the new look shows at once, done shows the happy face without the hop.

## Motion

- Every change of state blinks (240ms) and the new look swaps in while the eyes are shut; done hops (760ms), failed shivers once (440ms); flat wobbles like jelly (640ms), pixel winks and bursts confetti on done.
- Each state loops its own act: thought bubbles rise, the magnifier sweeps, the eyes run along lines, the pencil scribbles, a sweat drop drips, a question bubble asks, z's float up.
- 2D, flat and pixel look toward the pointer while idle or waiting; 2D and flat lean up to 4 degrees.
- Changing the color updates the 3D gradient map in place, with no blink. Nothing plays on first render.

## Responsive

- A square of size pixels. Props hide under 56 and the 2D face grows 1.1 times there; under 36 the ornaments grow 1.75 times into badge-sized marks.

## Performance

- Looks and loops are CSS in the foundation (section 8). 3D computes its gradient-map tables once per color; one pair of pointer listeners serves every avatar that looks.

## Notes for AI

- <AgentAvatar family="3d" shape="cloud" color="violet" state="searching" size={48} name="Ada" />. Families: 3d (orb, drop, block, bean, cloud, dome, clover, star), 2d (waves, tide, ripple, bloom, star, heart), flat (circle, squircle, pill, cloud, blob, flower, egg, tri), pixel (the 3D shapes).
- States: idle, thinking, searching, reading, writing, browsing, running, waiting (on the person), done, failed, stopped. Keep one element and change state: it blinks and plays the arrival. Re-keying skips it.
- color is a named option (pink, blue, lime, tangerine, violet, yellow, cyan, red) or any CSS color.
- 3D loads its plush render (shape-<shape>.webp) and props (prop-<prop>.webp) from https://pixilui.com/assets/agent-avatar/; copy those files and pass assets="/your/folder/" to serve them yourself.
- at (seconds) holds the loops at one moment for stills and sheets; no gaze then.
- useAgentAvatarSimulation() plays a run at human speed; pass steps for your own. thinkingMarkAvatarState (thinking-mark) maps these states to activity marks.
- Per-style rule: none; the avatar is the same in lively and quiet.

## Related

- [Avatar](https://pixilui.com/components/avatar/markdown): A person as a coin of colored glass in their own color: initials, a figure, a photo or an empty seat, with a presence dot, its color picked from the name so a person looks the same everywhere.
- [Agent status](https://pixilui.com/components/agent-status/markdown): A run's live state in a pill, queued, running, waiting on you, done, failed or stopped, that fills as it goes and closes into its result.
- [Activity mark](https://pixilui.com/components/thinking-mark/markdown): What an agent is doing right now, acted out on a 5 by 5 grid at 16px or larger: a radar sweep while it searches, a reading head through text, a question mark when it needs you. 36 activities.
