---
name: key-wrapped
description: >
  Build the user's "Agent Wrapped": a Spotify-Wrapped-style animated story of a year working with
  coding agents (hours, tokens, favourite agent, model and language, most-edited file, how they talk to
  agents, weekly rhythm, git year, terminal habits, close calls with pasted keys), with LLM-found fun facts,
  an export-and-share finale (X, HTML, MP4) and a fun made-up demo. Use when the user says "wrapped",
  "agent wrapped", "key wrapped", "my year with agents", "how many times did I paste a key", or invokes /key-wrapped.
---

# Agent Wrapped (single-file skill)

Produces a 9:16 animated, Remotion-styled "Wrapped" page from the local Prismor store, optionally a 1080x1920 MP4.
Everything needed is in this one file: instructions first, then the full source of three files at the bottom.
Logos come from thesvg.org (see "Logos"). No other assets.

Requirements: Python 3.9+, the `prismor` CLI (data comes from `prismor query`; installed automatically if missing; `--demo` needs no store),
Chrome (to view, and for MP4), ffmpeg + Node 18+ (MP4 only), network access to thesvg.org (first run only).

## 1. Setup (once per machine)

Create `~/agent-wrapped/src/` and write the three files from "Source files" at the bottom of this document,
byte for byte, to these paths (skip any that already exist and match):

| Block | Path |
|---|---|
| wrapped.py | `~/agent-wrapped/src/wrapped.py` |
| template.html | `~/agent-wrapped/src/template.html` |
| video/record.mjs | `~/agent-wrapped/src/video/record.mjs` |

Each block sits in a four-backtick fence; the file is everything between the fences. Run all later commands from
`~/agent-wrapped/src/`. Outputs: `~/agent-wrapped/stats.json`, `~/agent-wrapped/index.html`,
`~/agent-wrapped/agent-wrapped.mp4`, demo files in `~/agent-wrapped/demo/`.

For MP4 export only, inside `~/agent-wrapped/src/video/` run `prismor supplychain npm install playwright-core`
(never plain npm; Prismor checks the package). It drives the installed Chrome (`channel: 'chrome'`).

**First run, no questions.** If the `prismor` CLI is missing, `wrapped.py` installs it straight away (pipx, else a venv in
`~/agent-wrapped/venv`) without asking, and imports past Claude Code, Codex and Hermes transcripts with
`prismor analyze-history --since all`. **Never run `prismor setup` or `prismor install-hooks`, and never `login` or
`enroll`:** making a Wrapped must not put anyone's agents under governance. Tell the user in one line what was installed
and that no hooks were added. The import is skipped when hooks already recorded sessions (it would double count).
Imported history has no token or model data, so those slides are hidden; other agents (Cursor, etc.) are not imported.

If you query the store yourself before running the script, run the script first so the history exists.

## 2. The workflow

1. **Collect + render the base page** (a few minutes; it scans every shell event; run it in the background):
   `python3 wrapped.py --no-open`
   Flags: `--since YYYY-MM-DD` narrows the period, `--reuse` skips the queries and re-renders from `stats.json`,
   `--insights FILE` (default `~/agent-wrapped/insights.json`), `--out FILE`, `--no-open`.
2. **Reason over the stats. This step makes it good.** Read `~/agent-wrapped/stats.json`, then run your own
   `prismor query --limit 0 "<sql>"` calls (`prismor query --schema` lists tables) to find 4 to 6 facts this person
   would find funny, surprising or relatable: habits (the word typed most, politeness, longest chat, late nights),
   obsession (one file or project eating the year), rhythm (a streak, weekend habit, one wild day), and ratios
   ("that is 38 work weeks"). Write `~/agent-wrapped/insights.json` (max 6 slides are used):
   ```json
   {"slides":[{"kicker":"Your most-typed word","big":695,"unit":"prompts with the word \"still\"",
               "caption":"One short sentence, plain words.","palette":["#a855f7","#2e1065","#f3e8ff"],"logo":"claude"}],
    "persona":{"name":"Dusk Builder","define":"Peaks after dinner"}}
   ```
   `big` is a number (counts up) or short text. `logo` is optional: a slug from the Logos list. `persona` is optional:
   a 2 to 3 word name and a 2 to 3 word plain definition. If omitted, the script computes the persona from the hour
   distribution (dark share 5pm to 5am above 50%: Midnight Operator when the peak hour is 22 to 4, otherwise Dusk
   Builder; else Early Bird or Daylight Delegator).
3. **Sanity-check every number** before it goes on a slide (rules in section 4). Drop what you cannot explain.
4. **Render and open**: `python3 wrapped.py --reuse`.
5. **Export and share** (offer it at the end). The last slide has three buttons: **Share on X** (opens a pre-filled
   post, the user presses Post; never post for them; every share post ends with the line
   "Generate your wrapped @ prismor.dev/agent-wrapped", and any post text you draft for the user must end with it too), **Download HTML** (self-contained copy) and **Download as video**
   (in-page Chrome tab capture, needs permission). For a clean MP4 from the command line:
   `python3 wrapped.py --reuse --video --no-open` writes `~/agent-wrapped/agent-wrapped.mp4`
   (1080x1920, H.264, 30 fps, about 2 min, real-time render; `--ms 4200` sets time per slide). X allows 2:20 max;
   the MP4 must be attached by hand.
6. **Report** the 3 or 4 best facts in two lines and say which numbers were corrected or dropped.

## 3. Demo mode

`python3 wrapped.py --demo [--video] [--no-open]` builds a fun made-up developer, "Model Hopper": ten agents (Claude,
Cursor, Codex, Copilot, Windsurf, Cline, Gemini CLI, OpenCode, Kiro, Continue), nine models (Claude, GPT, DeepSeek,
Gemini, Qwen, Kimi, Mistral, Grok, Llama) and six jokes. It never touches the user's store and writes to
`~/agent-wrapped/demo/`. The page carries no "sample data" label, so tell the user that its numbers are invented
before they post it.

## 4. Data-quality rules (learned the hard way)

- **Hook-doubled events.** Hooks installed at both project and global scope log every event twice, back to back (ids
  n and n+1, same type and text, milliseconds apart). `wrapped.py` dedupes with a `NOT EXISTS` on the previous id.
  Do the same in your own queries. Also exclude agents `mcp-gateway`, `prismor-proxy`, `immunity-cli` and sessions
  with the placeholder `started_at='2026-01-01T00:00:00Z'`.
- **Meaningless stats, never use:** `sessions.updated_at - started_at` as work time (sessions stay open for days);
  `token_usage.latency_ms` (empty); first-word shell counts like `cd` (inflated by compound commands); "active hours"
  is distinct 15-minute buckets with any event, so background agents inflate it.
- **`LIKE '%git commit%'` matches mentions, not runs.** Anchor to the start of a command, after `&& `, after a
  semicolon, after `| `, or after a newline. A bad regex undercounted pytest and overcounted force-push; both were dropped.
- **`prismor query` gotchas:** default `--limit` is 200, pass `--limit 0`; some prompt events have `ts = null`, skip them;
  one statement per query, and a semicolon anywhere in the SQL (even inside a LIKE string) fails, so use `char(59)`
  for a semicolon and `char(10)` for a newline; `rowid` does not exist; slow queries can exceed a 120 s tool timeout, so
  run them in the background.
- **Key pastes** have no findings category. Count `events` rows with `type='prompt'` whose `content_text` contains
  `[REDACTED]` or `[REDACTED:secret]` (`:email`, `:phone`, `:card` are PII, not keys), counting markers per prompt.
  Secret placeholders (the cloak placeholder form from CLAUDE.md) are the safe route and are reported as "cloaked".
  Counts only include pastes made while Prismor prompt redaction was on.
- **If a number looks too big, find out why** (one day with 935 prompts was doubled events). Cut facts you cannot explain.
- **Privacy.** Counts and file or project names only. Never quote prompt text. Never put real secret values anywhere.
- Plain, warm, specific language. No security jargon in the facts.

## 5. Logos

Source: `https://thesvg.org/icons/<slug>/default.svg` (public, no key). `wrapped.py` downloads every slug it needs on the
first run into `~/agent-wrapped/src/logos/<slug>.svg`, then embeds them as base64 data URIs, so the final page is
self-contained and works offline. A failed download just drops that logo.

- Slugs that exist: claude, anthropic, openai, cursor, github-copilot, langchain, windsurf, gemini, github, git, python,
  npm, pypi, rust, docker, bash, openclaw, hermes, kiro, opencode, qwen, cline, continue, typescript, javascript,
  markdown, json, html5, css3, swift, go, yaml, deepseek, mistral-ai, meta, grok, xai, kimi, moonshot, perplexity,
  zhipu, cohere, groq, openrouter, zed, jetbrains, visual-studio-code, replit, cody, amazon-q, devin, lovable, bolt,
  v0, trae, cloudflare, vercel, reddit.
- 404 (do not use): antigravity, goose, react, llama (use `meta`), together, aider.
- Some logos are white-only (bash, markdown, cursor, qwen, windsurf, github-copilot, grok). `light_only()` detects
  white fills, including the named color `white` (grok), and the template gives them a dark tile. Gradient `url(#...)`
  fills count as colored.
- Model name to logo mapping lives in `model_logo()`: deepseek, kimi or moonshot, mistral, llama to meta, grok,
  gemini, qwen, glm to zhipu, command to cohere, sonar to perplexity, gpt, o-series and codex to openai.

## 6. Design (Remotion "Spotify Wrapped" style)

Flat saturated colour fields (hot pink, mint, lime, electric violet, near-black), round-ended ranked bars that grow out
of a circle, a mirrored kaleidoscope intro opening into an expanding scrolling-gradient circle with a square card,
critically damped springs (no bounce). Slides: intro, time, tokens (rain), top agent, model podium, roster belts,
roulette wheel, language, most-edited file, how you talk, patience gauge, weekly rhythm, radial clock and persona on a
sunset sheet, monthly trend, biggest day, git, terminal, sites, LLM insights, close calls (key pastes), finale.
Real data renders about 23 slides, the demo 26. Rules: keep the palette varied, never one colour; night personas use
indigo, violet and magenta, never green; no pills, no monospace, no tinted callout boxes; persona names always come
with a 2 to 3 word definition. URL params `?rec=1&t=<ms>` put the page in record mode; it sets `window.__done` at the end.

## 7. Troubleshooting

- Black slide in a throttled or backgrounded tab: the clip-path wipe has a 1.1 s fallback; keep the tab in front.
- A logo missing: its slug may 404 or the network was down; delete `logos/<slug>.svg` and re-run, or pick another slug.
- White logo invisible on a white tile: add its slug to the dark list in `wrapped.py` (`D["dark"]`).
- MP4 fails with "no frames": Chrome is not installed or `playwright-core` is missing in `video/`.
- A cloak or hook block on writing a file means it contains a vaulted value; remove that text, never retry the same write.
- Big numbers that look wrong: re-check the dedupe and infrastructure filters first.

## 8. What the user asked for (do not regress these)

The skill exists because the user wanted a Spotify-Wrapped-style recap of their agent usage. Requirements in the order
they came up, all of which must keep holding:

1. The count of times a key was pasted is ONE slide, not the whole thing. It is a full Wrapped with everything else.
2. Real logos from thesvg.org for agents, models, languages and sites.
3. Relatable, fun facts, not only security. Remove stats that do not make sense. The LLM running the skill reasons over
   the data and finds the facts itself (step 2 of the workflow, `insights.json`).
4. Plain language everywhere. Every persona has a 2 to 3 word definition, for example Midnight Operator: "Ships after dark".
5. Dark or midnight look is fine but must not be monochromatic and must not be green. Keep the palette varied.
6. Style: the Arxsher spotify-wrapped repo and the JonnyBurger remotion-wrapped scenes (flat saturated fields,
   round-ended ranked bars, kaleidoscope intro, expanding gradient circle, spring easing without bounce).
7. Many motion graphics, not static cards.
8. An end-of-story way to export: MP4, HTML, and Share on X.
9. A fun made-up demo video with many different models (DeepSeek and others) and many different agents.
10. UI taste: no pills, no monospace type, no tinted callout boxes; status as dot plus text.

## 9. Anatomy and how to extend it

`wrapped.py` has two stages and a demo:
- `collect(since)` runs about 25 SQL queries in parallel threads (`ThreadPoolExecutor`) and returns raw rows `R`.
- `stats(R)` turns rows into one dict `D`: year, sessions, workspaces, prompts, shell, writes, reads, subagents,
  activeHours, workWeeks, activeDays, outTokens, novels, cachePct, agents (name, count, logo), projects, models
  (name, tokens, logo), langs, topFiles, talk, sites, months, hours[24], dow[7], weekendPct, peakHour, afterMidnight,
  bestDay, bestDayN, streak, longestChat, multiAgentDays, persona, personaDef, personaKind, habits, keysRaw, keysSafe,
  cloakPct, pkgBlocked, pkgWarned, pkgAllowed. `persona(hours, weekend_pct)` is recomputed on every render, so `--reuse`
  stays correct.
- `main()` adds `D["insights"]` (cap 6), `D["logos"]` (base64 data URIs from `logos_for`), `D["dark"]` (slugs needing a
  dark tile), then replaces `__DATA__` in `template.html` with the JSON. Real data goes to `~/agent-wrapped/`, the
  demo to `~/agent-wrapped/demo/`.
- `demo_stats()` plus `DEMO_INSIGHTS` is the made-up dataset ("Model Hopper"); it sets `D["demo"]`.
- `make_video(html, mp4, ms)` shells out to `video/record.mjs`.

`template.html` is vanilla JS with no dependencies. Slides are template strings pushed into the `S` array
(options: `dur` in ms, `mq` marquee text, `confetti`, `last`). Building blocks: flat brand palette `FL` as
`[bg, ink, accent]` feeding CSS variables `--bg --ink --acc`; circular clip-path wipe between slides; per-word
letter-stagger reveal; `data-count` count-ups; `.rbar` round-ended ranked bars (`data-w` is the width %, minimum 64 so
labels fit); SVG draw-on lines (`pathLength=1`); radial clock; podium; belts; roulette wheel (`data-spin`); needle gauge
(`data-needle`); token-rain canvas; confetti canvas; sunset gradient (`SUN_NIGHT` indigo, violet, magenta for night
owls, `SUN_FULL` otherwise); kaleidoscope intro (`.ql`); expanding gradient circle (`.gc`); `.sheet` card.
To add a slide, push a new entry to `S` and read only fields that exist in `D`. Real data renders 23 slides, the demo 26.

Rendering gotchas already solved (keep them): words split into letters must be wrapped per word in
`inline-block; white-space:nowrap` or they break mid-word; a clip-path transition can show a black slide in a
throttled tab, hence the 1.1 s fallback that sets `clipPath='none'`; "Download HTML" uses a copy of
`document.documentElement.outerHTML` captured at the top of the script, so the download is the clean page and not the
animated DOM; "Download as video" uses `getDisplayMedia` with `preferCurrentTab` and `MediaRecorder` (mp4 if supported,
else webm).

Share on X opens `https://x.com/intent/post?text=<encoded>` with a pre-filled text of about 215 characters containing
hours, tokens, commits, persona and its definition and `#AgentWrapped`, ending with
"Generate your wrapped @ prismor.dev/agent-wrapped" on its own line. The user presses Post themselves and attaches
the MP4 by hand. Never post on their behalf and never open X unasked.

## 10. Video export internals

`video/record.mjs` uses `playwright-core` with `channel: 'chrome'`, headless, viewport 540x960 at
`deviceScaleFactor` 2, and a CDP `Page.startScreencast` (jpeg quality 92, max 1080x1920). Each frame is written to a temp
folder with its timestamp; an ffmpeg concat-demuxer list is built from the timestamp deltas, then encoded to
1080x1920 H.264 (`crf 18`, 30 fps, `yuv420p`, `+faststart`). It loads the page with `?rec=1&t=<ms>` and waits for
`window.__done`. It renders in real time: about 2 minutes for the 26-slide demo (real data has not been timed). The result has no audio. The demo MP4 is about 2:01 and 20 MB, inside X's 2:20 limit; if real data runs longer,
lower `--ms`.

## 11. Working rules for the agent running this skill

- Run long steps (collect, video) in the background and wait for the completion notice; do not poll.
- Write scratch files and probe output to a scratchpad or temp folder with absolute paths, never into the user's
  project folder.
- Install packages only through `prismor supplychain <pm> install <pkg>`. The one exception is the Prismor CLI itself on a
  machine that does not have it yet, which `wrapped.py` installs directly.
- The placeholder form for secrets must never be written with a real value, and writing a file that contains a vaulted
  value is blocked by the cloak hook; do not retry that write, remove the text.
- Never publish, post or share without the user's go-ahead; report file paths and let them send it.
- After a task, append an entry to the project's `TASK_NOTES.md` if the project has that convention (newest first: goal,
  how, corner cases still missing) and give the same summary in chat.
- Verify before claiming: open the page, check the console is clean, check the slide count, and look at several frames.
  Say plainly what was not verified (in-page "Download as video" needs Chrome's tab-capture permission).

## 12. Final checklist

1. Source files written to `~/agent-wrapped/src/`; logos downloaded (`logos/` has about 25 to 30 SVGs).
2. `stats.json` has no absurd numbers (no 935-prompt days, no 20,000-hour sessions).
3. `insights.json` has 4 to 6 facts, each explained and checked, no prompt text.
4. Persona name plus a 2 to 3 word definition; night palette has no green.
5. Page opens with no console errors; last slide shows the three buttons.
6. Optional MP4 under 2:20 for X; the user told whether the data is real or invented.

## Source files

Write each block to the path in section 1.

### wrapped.py

````python
#!/usr/bin/env python3
"""Agent Wrapped: a Spotify-Wrapped-style animated recap of a year of working with coding agents.

Two stages, so an LLM can sit in the middle:
  1. collect: queries the local Prismor store (`prismor query`) and writes ~/agent-wrapped/stats.json
  2. render : turns stats.json (+ optional LLM-written insights.json) into ~/agent-wrapped/index.html

Only counts and file/project names go into the page. No prompt text. Logos: thesvg.org, vendored in ./logos.

usage: wrapped.py [--since YYYY-MM-DD] [--reuse] [--insights FILE] [--out FILE] [--no-open]
  --reuse   skip the (slow) queries and re-render from the saved stats.json
"""
import argparse, base64, collections, json, os, re, subprocess, sys, webbrowser
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import shutil

HERE = os.path.dirname(os.path.abspath(__file__))
WORK = os.path.expanduser("~/agent-wrapped")
PRISMOR = shutil.which("prismor") or shutil.which("prismor", path=os.pathsep.join(
    [os.path.expanduser("~/.local/bin"), os.path.join(WORK, "venv", "bin")])) or "prismor"
RAW = re.compile(r"\[REDACTED(?::secret)?\]")   # typed non-secret kinds (email, phone, card) are not keys
SAFE = re.compile(r"@@SECRET:[\w.-]+@@")
INFRA = "('mcp-gateway','prismor-proxy','immunity-cli')"   # plumbing, not agents the user chose
REAL = "started_at!='2026-01-01T00:00:00Z'"               # placeholder start date on some sessions

AGENT_LOGO = {"claude": "claude", "claude-code": "claude", "codex": "openai", "openai-agents": "openai",
              "langchain": "langchain", "cursor": "cursor", "copilot": "github-copilot", "windsurf": "windsurf",
              "gemini": "gemini", "openclaw": "openclaw", "hermes": "hermes", "kiro": "kiro",
              "opencode": "opencode", "qwen": "qwen", "cline": "cline", "continue": "continue", "gemini-cli": "gemini", "trae": "trae",
              "devin": "devin", "zed": "zed", "cody": "cody", "amazon-q": "amazon-q", "replit": "replit", "grok": "grok"}
LANG = {"py": ("Python", "python"), "ts": ("TypeScript", "typescript"), "tsx": ("TypeScript", "typescript"),
        "js": ("JavaScript", "javascript"), "jsx": ("JavaScript", "javascript"), "rs": ("Rust", "rust"),
        "md": ("Markdown", "markdown"), "swift": ("Swift", "swift"), "sh": ("Shell", "bash"),
        "html": ("HTML", "html5"), "css": ("CSS", "css3"), "json": ("JSON", "json"), "yaml": ("YAML", "yaml"),
        "yml": ("YAML", "yaml"), "go": ("Go", "go")}
SITE_LOGO = [("github", "github"), ("cloudflare", "cloudflare"), ("openai", "openai"), ("claude", "claude"),
             ("anthropic", "claude"), ("google", "google"), ("reddit", "reddit"), ("vercel", "vercel"),
             ("npmjs", "npm"), ("pypi", "pypi")]
OWN = ("prismor", "localhost", "127.0.0.1")


def model_logo(m):
    m = m.lower()
    for key, slug in (("claude", "claude"), ("deepseek", "deepseek"), ("kimi", "kimi"), ("moonshot", "kimi"),
                      ("mistral", "mistral-ai"), ("mixtral", "mistral-ai"), ("llama", "meta"), ("grok", "grok"),
                      ("gemini", "gemini"), ("qwen", "qwen"), ("glm", "zhipu"), ("command", "cohere"),
                      ("sonar", "perplexity")):
        if key in m: return slug
    return "openai" if re.match(r"(gpt|o\d|codex)", m) else None


def q(sql):
    r = subprocess.run([PRISMOR, "query", "--limit", "0", sql], capture_output=True, text=True, timeout=900)
    if r.returncode:
        sys.exit(r.stderr or "prismor query failed")
    return json.loads(r.stdout or "[]")


def ensure_history():
    """First run: install the Prismor CLI if missing and import past agent transcripts.
    Never runs `setup` or `install-hooks`, so nothing on this machine gets governed."""
    global PRISMOR
    if not shutil.which(PRISMOR):
        venv = os.path.join(WORK, "venv")
        print("Prismor CLI not found: installing it (no hooks are added)")
        if shutil.which("pipx"):
            subprocess.run(["pipx", "install", "prismor"], check=True)
            PRISMOR = shutil.which("prismor") or os.path.expanduser("~/.local/bin/prismor")
        else:
            subprocess.run([sys.executable, "-m", "venv", venv], check=True)
            subprocess.run([os.path.join(venv, "bin", "pip"), "install", "-q", "prismor"], check=True)
            PRISMOR = os.path.join(venv, "bin", "prismor")
    live = subprocess.run([PRISMOR, "query", "SELECT count(*) n FROM sessions WHERE coalesce(source,'')!='transcript'"],
                          capture_output=True, text=True)
    if live.returncode == 0 and json.loads(live.stdout or "[]")[0]["n"]:
        return  # hooks already captured history; importing too would count it twice
    print("importing past agent transcripts (read-only, no hooks)")
    subprocess.run([PRISMOR, "analyze-history", "--since", "all", "--max-events", "2000000", "--agent", "claude,codex,hermes"],
                   check=True, stdout=subprocess.DEVNULL)
    if not q("SELECT count(*) n FROM sessions")[0]["n"]:
        sys.exit("No agent history found. Import supports Claude Code, Codex and Hermes transcripts.")


def cmd(c):  # a real command, not a mention: at line start or after && ; |
    pre = ["''", "'%&& '", "'%'||char(59)||' '", "'%| '", "'%'||char(10)"]   # char(59) is ';', which the query gate rejects
    return "(" + " OR ".join(f"command_text LIKE {p}||'{c}%'" for p in pre) + ")"


DEDUP = ("NOT EXISTS (SELECT 1 FROM events p WHERE p.id=e.id-1 AND p.session_id=e.session_id AND p.type=e.type "
         "AND p.command_text IS e.command_text AND p.path_text IS e.path_text AND p.content_text IS e.content_text "
         "AND p.url_text IS e.url_text)")   # hooks at project + global scope log every event twice, back to back
EV = f"FROM events e LEFT JOIN sessions s ON s.session_id=e.session_id WHERE (s.agent IS NULL OR s.agent NOT IN {INFRA}) AND {DEDUP}"


def collect(since):
    w = lambda col: f" AND {col}>='{since}'" if since else ""
    sess = f"FROM sessions WHERE {REAL} AND agent NOT IN {INFRA}{w('started_at')}"
    sql = {
        "types": f"SELECT type, count(*) n {EV} AND 1=1{w('ts')} GROUP BY type",
        "prompts": f"SELECT ts {EV} AND type='prompt' AND ts IS NOT NULL{w('ts')}",
        "active": f"SELECT count(DISTINCT cast(strftime('%s',ts) as int)/900) b {EV} AND ts IS NOT NULL{w('ts')}",
        "agents": f"SELECT CASE agent WHEN 'claude-code' THEN 'claude' ELSE agent END a, count(*) n {sess} GROUP BY a ORDER BY n DESC LIMIT 10",
        "sessions": f"SELECT count(*) n, count(DISTINCT workspace_path) ws {sess}",
        "projects": f"SELECT workspace_path p, count(*) n {sess} GROUP BY p ORDER BY n DESC LIMIT 5",
        "models": f"SELECT model, sum(output_tokens) o FROM token_usage WHERE model!='' AND model NOT LIKE '<%'{w('ts')} GROUP BY model ORDER BY o DESC LIMIT 9",
        "tokens": f"SELECT sum(output_tokens) o, sum(cache_read_tokens) c, sum(input_tokens+cache_creation_tokens) f FROM token_usage WHERE 1=1{w('ts')}",
        "supply": f"SELECT verdict, count(*) n FROM supply_chain_events WHERE 1=1{w('ts')} GROUP BY 1",
        "ext": f"SELECT lower(replace(path_text, rtrim(path_text, replace(path_text,'.','')), '')) x, count(*) n {EV} AND type='file_write' AND path_text LIKE '%.%'{w('ts')} GROUP BY x ORDER BY n DESC LIMIT 30",
        "files": f"SELECT path_text p, count(*) n {EV} AND type='file_write' AND path_text!=''{w('ts')} GROUP BY p ORDER BY n DESC LIMIT 5",
        "hosts": ("SELECT substr(h,1,instr(h||'/','/')-1) h, count(*) n FROM (SELECT replace(replace(url_text,'https://',''),'http://','') h "
                  f"{EV} AND type='network' AND url_text!=''{w('ts')}) GROUP BY 1 ORDER BY n DESC LIMIT 15"),
        "talk": ("SELECT count(*) n, round(avg(length(content_text))) avg_len, max(length(content_text)) max_len, "
                 "sum(lower(content_text) LIKE '%please%') please, sum(lower(content_text) LIKE '%thank%') thanks, "
                 "sum(lower(content_text) LIKE '%fuck%' OR lower(content_text) LIKE '%wtf%' OR lower(content_text) LIKE '%shit%') swear, "
                 "sum(lower(content_text) LIKE '%why%') why, sum(content_text LIKE '%?%') qmark, sum(lower(content_text) LIKE '%still%') still, "
                 "sum(lower(content_text) LIKE '%fix%') fix, sum(lower(content_text) LIKE '%continue%') cont, "
                 "sum(lower(trim(content_text)) IN ('yes','y','ok','do it','go','yep','sure','proceed')) yes "
                 f"{EV} AND type='prompt' AND content_text!=''{w('ts')}"),
        "turns": f"SELECT max(n) m FROM (SELECT count(*) n {EV} AND type='prompt'{w('ts')} GROUP BY e.session_id)",
        "multi": f"SELECT count(*) n FROM (SELECT date(started_at) d FROM sessions WHERE {REAL} AND agent NOT IN {INFRA}{w('started_at')} GROUP BY d HAVING count(DISTINCT agent)>=3)",
        "habits": ("SELECT sum(" + cmd("git commit") + ") commits, sum(" + cmd("git push") + ") pushes, sum(" + cmd("gh pr create") + ") prs, "
                   "sum(" + cmd("gh pr merge") + ") merges, "
                   "sum(" + cmd("git stash") + ") stash, sum(" + cmd("rm -rf") + ") rmrf, sum(" + cmd("curl") + ") curl, "
                   "sum(" + cmd("ssh") + ") ssh, sum(" + cmd("ls") + ") ls "
                   f"{EV} AND type='shell'{w('ts')}"),
        "keys": (f"SELECT content_text {EV} AND type='prompt' AND "
                 f"(content_text LIKE '%[REDACTED%' OR content_text LIKE '%@@SECRET:%'){w('ts')}"),
    }
    with ThreadPoolExecutor(len(sql)) as ex:
        futs = {k: ex.submit(q, v) for k, v in sql.items()}
        return {k: f.result() for k, f in futs.items()}


def local(ts):
    return datetime.fromisoformat(ts.replace("Z", "+00:00")).astimezone()  # 3.9 rejects "Z"


def persona(hours, weekend_pct):
    t = max(1, sum(hours))
    dark = sum(hours[h] for h in list(range(17, 24)) + list(range(0, 5))) / t   # share of prompts between 5pm and 5am
    morn = sum(hours[h] for h in range(5, 10)) / t
    peak = hours.index(max(hours))
    if dark > .5 and (peak >= 22 or peak < 5): return ("Midnight Operator", "Ships after dark", "night")
    if dark > .5: return ("Dusk Builder", "Peaks after dinner", "night")
    if morn > .3: return ("Early Bird", "Delegates before coffee", "early")
    return ("Daylight Delegator", "Nine-to-five, tidy", "day")


def stats(R):
    types = {r["type"]: r["n"] for r in R["types"]}
    P = [local(r["ts"]) for r in R["prompts"] if r["ts"]]
    hours, dow = [0] * 24, [0] * 7
    for t in P:
        hours[t.hour] += 1
        dow[(t.weekday() + 1) % 7] += 1   # 0 = Sunday
    days = collections.Counter(t.date().isoformat() for t in P)
    months = sorted(collections.Counter(t.strftime("%Y-%m") for t in P).items())
    bd, bn = days.most_common(1)[0] if days else ("", 0)
    ds = sorted(datetime.fromisoformat(d).toordinal() for d in days)
    streak = cur = 1 if ds else 0
    for a, b in zip(ds, ds[1:]):
        cur = cur + 1 if b == a + 1 else 1
        streak = max(streak, cur)
    weekend = round(100 * (dow[0] + dow[6]) / max(1, sum(dow)))
    pers = persona(hours, weekend)
    keys_raw = sum(len(RAW.findall(r["content_text"])) for r in R["keys"])
    keys_safe = sum(len(SAFE.findall(r["content_text"])) for r in R["keys"])
    langs = collections.Counter()
    logo_of = {}
    for r in R["ext"]:
        if r["x"] in LANG:
            langs[LANG[r["x"]][0]] += r["n"]
            logo_of[LANG[r["x"]][0]] = LANG[r["x"]][1]
    sup = {r["verdict"]: r["n"] for r in R["supply"]}
    sites = []
    for r in R["hosts"]:
        if any(o in r["h"] for o in OWN) or not r["h"]: continue
        sites.append((r["h"], r["n"], next((l for k, l in SITE_LOGO if k in r["h"]), None)))
    tk = R["tokens"][0]
    out_tok = tk["o"] or 0
    cache_pct = round(100 * (tk["c"] or 0) / max(1, (tk["c"] or 0) + (tk["f"] or 0)), 2)
    tf = (R["files"] or [{"p": "", "n": 0}])
    top_file = tf[0]["p"]
    active_h = round((R["active"][0]["b"] or 0) * 0.25)
    d = {
        "year": P[0].year if P else datetime.now().year,
        "sessions": R["sessions"][0]["n"], "workspaces": R["sessions"][0]["ws"],
        "prompts": types.get("prompt", 0), "shell": types.get("shell", 0), "writes": types.get("file_write", 0),
        "reads": types.get("file_read", 0), "subagents": types.get("subagent_spawn", 0),
        "activeHours": active_h, "workWeeks": round(active_h / 40, 1), "activeDays": len(days),
        "outTokens": out_tok, "novels": round(out_tok / 120000), "cachePct": cache_pct, "cachedTokens": tk["c"] or 0,
        "agents": [(a["a"] or "unknown", a["n"], AGENT_LOGO.get(a["a"])) for a in R["agents"]],
        "projects": [(os.path.basename((p["p"] or "").rstrip("/")) or "unknown", p["n"]) for p in R["projects"]],
        "models": [(m["model"], m["o"], model_logo(m["model"])) for m in R["models"]],
        "langs": [(n, c, logo_of[n]) for n, c in langs.most_common(6)],
        "topFiles": [(os.path.basename(f["p"]), f["n"], os.path.basename(os.path.dirname(f["p"]))) for f in tf],
        "talk": R["talk"][0], "sites": sites[:5],
        "months": months, "hours": hours, "dow": dow, "weekendPct": weekend, "peakHour": hours.index(max(hours)),
        "afterMidnight": sum(hours[h] for h in range(0, 5)),
        "bestDay": bd, "bestDayN": bn, "streak": streak, "longestChat": R["turns"][0]["m"],
        "multiAgentDays": R["multi"][0]["n"],
        "persona": pers[0], "personaDef": pers[1], "personaKind": pers[2],
        "habits": {k: (v or 0) for k, v in R["habits"][0].items()},
        "keysRaw": keys_raw, "keysSafe": keys_safe, "cloakPct": round(100 * keys_safe / max(1, keys_safe + keys_raw)),
        "pkgBlocked": sup.get("block", 0), "pkgWarned": sup.get("warn", 0), "pkgAllowed": sup.get("allow", 0),
    }
    return d


def light_only(svg):
    """True when every explicit fill is white-ish, so the logo vanishes on a white tile."""
    cols = re.findall(r'fill(?:="|:)\s*(#[0-9a-fA-F]{3,8}|white)', svg)
    return "url(#" not in svg and bool(cols) and all(re.fullmatch(r"white|#(f{3,8}|fefffe|f3f3f3|edecec)", c, re.I) for c in cols)


def logos_for(d, extra):
    slugs = {x[2] for k in ("agents", "models", "langs", "sites") for x in d[k] if x[2]} | {"claude", "git", "github", "bash", "npm", "pypi", "python"} | set(extra)
    out = {}
    for s in slugs:
        p = os.path.join(HERE, "logos", s + ".svg")
        if not os.path.exists(p):  # single-file install: fetch from thesvg.org once, then cache
            try:
                import urllib.request
                os.makedirs(os.path.dirname(p), exist_ok=True)
                open(p, "wb").write(urllib.request.urlopen(f"https://thesvg.org/icons/{s}/default.svg", timeout=8).read())
            except Exception:
                if os.path.exists(p): os.remove(p)
        if os.path.exists(p):
            out[s] = "data:image/svg+xml;base64," + base64.b64encode(open(p, "rb").read()).decode()
    return out



def demo_stats():
    """A made-up, fun developer: ten agents, nine models, zero loyalty. Clearly marked as sample data."""
    base = [160, 185, 140, 90, 45, 10, 6, 8, 14, 22, 30, 34, 38, 40, 42, 48, 55, 70, 90, 110, 125, 140, 150, 155]
    hours = [h * 17 for h in base]
    dow = [3100, 4200, 5200, 4800, 4300, 3900, 2900]
    months = [("2026-%02d" % (i + 1), v) for i, v in enumerate([820, 1100, 1500, 1900, 2300, 2100, 2600, 3100, 3600, 3900, 4300, 2200])]
    agents = [("claude", 3120), ("cursor", 2210), ("codex", 1480), ("copilot", 980), ("windsurf", 610), ("cline", 402),
              ("gemini-cli", 355), ("opencode", 140), ("kiro", 72), ("continue", 30)]
    models = [("claude-opus-5-5", 61e6), ("gpt-5.5", 38e6), ("deepseek-v4", 27e6), ("gemini-3-pro", 21e6), ("qwen3-coder", 14e6),
              ("kimi-k2", 9e6), ("mistral-large", 6e6), ("grok-4", 4.5e6), ("llama-4", 2e6)]
    pers = persona(hours, 21)
    out = sum(m[1] for m in models) + 3e6
    return {
        "demo": True, "year": 2026, "sessions": sum(a[1] for a in agents), "workspaces": 211,
        "prompts": sum(hours), "shell": 301842, "writes": 41210, "reads": 38100, "subagents": 2210,
        "activeHours": 2210, "workWeeks": 55.3, "activeDays": 288, "outTokens": out, "novels": round(out / 120000),
        "cachePct": 96.4, "cachedTokens": 41e9,
        "agents": [(n, c, AGENT_LOGO.get(n)) for n, c in agents],
        "projects": [("moonshot-app", 3100), ("side-quest", 2210), ("work-thing", 1800), ("dotfiles", 900), ("mystery-repo", 400)],
        "models": [(n, t, model_logo(n)) for n, t in models],
        "langs": [("TypeScript", 9120, "typescript"), ("Python", 7440, "python"), ("Rust", 3010, "rust"),
                  ("Markdown", 2800, "markdown"), ("Go", 1900, "go"), ("Swift", 1400, "swift")],
        "topFiles": [("README.md", 412, "root"), ("schema.sql", 301, "db"), ("App.tsx", 288, "src"), ("main.rs", 190, "src"), ("TODO.md", 150, "root")],
        "talk": {"n": 30100, "avg_len": 410, "max_len": 4100, "please": 612, "thanks": 301, "swear": 188, "why": 1420,
                 "qmark": 6200, "still": 1650, "fix": 3900, "cont": 800, "yes": 300},
        "sites": [("github.com", 1820, "github"), ("reddit.com", 940, "reddit"), ("developers.openai.com", 610, "openai"),
                  ("docs.anthropic.com", 480, "claude"), ("vercel.com", 260, "vercel")],
        "months": months, "hours": hours, "dow": dow, "weekendPct": round(100 * (dow[0] + dow[6]) / sum(dow)),
        "peakHour": hours.index(max(hours)), "afterMidnight": sum(hours[:5]),
        "bestDay": "2026-10-14", "bestDayN": 612, "streak": 211, "longestChat": 307, "multiAgentDays": 94,
        "persona": pers[0], "personaDef": pers[1], "personaKind": pers[2],
        "habits": {"commits": 7210, "pushes": 6980, "prs": 1920, "merges": 1740, "stash": 2210, "rmrf": 5120, "curl": 8400, "ssh": 4100, "ls": 21000},
        "keysRaw": 12, "keysSafe": 904, "cloakPct": 99, "pkgBlocked": 41, "pkgWarned": 17, "pkgAllowed": 640,
    }


DEMO_INSIGHTS = [
    {"kicker": "Most apologetic", "big": 1204, "unit": "times an agent said \"You're absolutely right!\"", "caption": "Right about what? Nobody knows. Everybody apologised.", "flat": "lime"},
    {"kicker": "The 3am specialist", "big": "DeepSeek", "unit": "wrote 41% of your after-midnight commits", "caption": "Cheap, fast and awake when nobody else is.", "logo": "deepseek", "flat": "violet"},
    {"kicker": "Model hopper", "big": 37, "unit": "times you swapped models mid-bug", "caption": "Whoever fixed it got the credit. Nobody was loyal.", "flat": "pink"},
    {"kicker": "The staring contest", "big": "11m 42s", "unit": "longest wait for one answer", "caption": "You made tea. It was a good tea.", "flat": "mint"},
    {"kicker": "The wildcard", "big": "Grok", "unit": "was asked exactly 12 questions", "caption": "Nobody knows why. Everybody respects it.", "logo": "grok", "flat": "ink"},
    {"kicker": "Kimi read the whole repo", "big": "1.2M", "unit": "tokens of context in one go", "caption": "Then it asked which file you meant.", "logo": "kimi", "flat": "white"},
]


def make_video(html, mp4, ms):
    node = os.path.join(HERE, "video")
    if not os.path.isdir(os.path.join(node, "node_modules", "playwright-core")):
        sys.exit("video needs playwright-core: run `prismor supplychain npm install playwright-core` inside the skill's video folder")
    r = subprocess.run(["node", os.path.join(node, "record.mjs"), "file://" + html, mp4, str(ms)])
    if r.returncode: sys.exit("video render failed")
    print("video ->", mp4)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--since")
    ap.add_argument("--reuse", action="store_true")
    ap.add_argument("--insights", default=os.path.join(WORK, "insights.json"))
    ap.add_argument("--out", default=os.path.join(WORK, "index.html"))
    ap.add_argument("--no-open", action="store_true")
    ap.add_argument("--demo", action="store_true", help="fun made-up data: ten agents, nine models")
    ap.add_argument("--video", action="store_true", help="also render a 1080x1920 MP4 (headless Chrome + ffmpeg)")
    ap.add_argument("--ms", type=int, default=4200, help="milliseconds per slide in the video")
    a = ap.parse_args()
    if a.since and not re.fullmatch(r"\d{4}-\d{2}-\d{2}", a.since):
        sys.exit("--since must be YYYY-MM-DD")
    work = os.path.join(WORK, "demo") if a.demo else WORK
    if a.demo and a.out == os.path.join(WORK, "index.html"): a.out = os.path.join(work, "index.html")
    os.makedirs(work, exist_ok=True)
    sp = os.path.join(work, "stats.json")
    if a.demo:
        D = demo_stats()
    elif a.reuse and os.path.exists(sp):
        D = json.load(open(sp))
    else:
        ensure_history()
        D = stats(collect(a.since))
        json.dump(D, open(sp, "w"), indent=1)
        print("stats ->", sp)
    D["persona"], D["personaDef"], D["personaKind"] = persona(D["hours"], D["weekendPct"])
    ins = json.load(open(a.insights)) if (os.path.exists(a.insights) and not a.demo) else {}
    D["insights"] = (DEMO_INSIGHTS if a.demo else ins.get("slides", []))[:6]
    if ins.get("persona"): D["persona"], D["personaDef"] = ins["persona"]["name"], ins["persona"]["define"]
    D["logos"] = logos_for(D, [i.get("logo") for i in D["insights"] if i.get("logo")])
    D["dark"] = [k for k in D["logos"] if k in ("bash", "markdown", "cursor") or light_only(base64.b64decode(D["logos"][k].split(",", 1)[1]).decode("utf8", "ignore"))]
    open(a.out, "w").write(TEMPLATE.replace("__DATA__", json.dumps(D).replace("</", "<\\/")))
    print(f"{D['sessions']} sessions, {D['activeHours']} active hours, {len(D['insights'])} insights -> {a.out}")
    if a.video: make_video(a.out, os.path.join(os.path.dirname(a.out), "agent-wrapped.mp4"), a.ms)
    if not a.no_open: webbrowser.open("file://" + a.out)


TEMPLATE = open(os.path.join(HERE, "template.html")).read() if os.path.exists(os.path.join(HERE, "template.html")) else ""

if __name__ == "__main__":
    main()
````

### template.html

````html
<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Agent Wrapped</title>
<link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;600;700;800;900&display=swap" rel="stylesheet" media="print" onload="this.media='all'">
<style>
*{box-sizing:border-box;margin:0;padding:0}
:root{--ease:cubic-bezier(.16,1,.3,1)}
html,body{height:100%;background:#000;color:#fff;font-family:Poppins,-apple-system,"Helvetica Neue",Arial,sans-serif;overflow:hidden;-webkit-font-smoothing:antialiased}
#app{position:relative;height:100%;max-width:480px;margin:0 auto;overflow:hidden;background:#000;user-select:none;cursor:pointer}
.bars{position:absolute;top:14px;left:14px;right:14px;display:flex;gap:3px;z-index:9}
.bars i{flex:1;height:3px;background:#fff4;border-radius:2px;overflow:hidden}.bars b{display:block;height:100%;width:0;background:#fff}
.hint{position:absolute;bottom:10px;left:0;right:0;text-align:center;font-size:11px;opacity:.5;z-index:9;pointer-events:none}
.badge{position:absolute;left:16px;bottom:26px;z-index:9;font-size:11px;font-weight:700;letter-spacing:.12em;text-transform:uppercase;pointer-events:none;display:flex;align-items:center;gap:7px;color:#fff;text-shadow:0 1px 6px #0008}
.badge i{width:8px;height:8px;border-radius:50%;background:#d5f772;animation:tw 1.4s ease-in-out infinite alternate}
@keyframes tw{from{opacity:.3}to{opacity:1}}
body.rec .hint{display:none}
.slide{position:absolute;inset:0;padding:78px 28px 52px;display:flex;flex-direction:column;justify-content:center;visibility:hidden;clip-path:circle(0% at 50% 60%);overflow:hidden;background:var(--bg);color:var(--ink)}
.slide.on{visibility:visible;clip-path:circle(150% at 50% 60%);transition:clip-path .9s var(--ease);z-index:2}
.slide.prev{visibility:visible;z-index:1}
.slide>*{position:relative;z-index:2}
.dot{position:absolute!important;z-index:1!important;border-radius:50%;background:var(--acc);opacity:.22;animation:float 9s ease-in-out infinite alternate}
@keyframes float{to{transform:translate(40px,-60px) scale(1.2)}}
.spin{position:absolute!important;z-index:1!important;border:2px solid currentColor;opacity:.2;border-radius:50%;animation:rot 30s linear infinite}
@keyframes rot{to{transform:rotate(360deg)}}
.mq{position:absolute!important;left:0;white-space:nowrap;font-weight:900;font-size:74px;letter-spacing:-.03em;opacity:.08;z-index:1!important;animation:mq 22s linear infinite}
@keyframes mq{to{transform:translateX(-50%)}}
.k{font-size:13px;letter-spacing:.18em;text-transform:uppercase;font-weight:700;opacity:.85;margin-bottom:14px}
.h{font-size:42px;line-height:1.05;font-weight:900;letter-spacing:-.03em;text-shadow:0 0 6px #0003}
.big{font-size:104px;line-height:.95;font-weight:900;letter-spacing:-.05em;font-variant-numeric:tabular-nums;text-shadow:0 0 6px #0003}
.p{font-size:17px;line-height:1.35;font-weight:600;opacity:.92;margin-top:16px}
.acc{color:var(--acc)}
.ch{display:inline-block;opacity:0;transform:translateY(60px) rotate(8deg)}
.on .ch{animation:ch .8s var(--ease) forwards;animation-delay:calc(var(--i)*38ms + var(--d,0ms))}
@keyframes ch{to{opacity:1;transform:none}}
.in{opacity:0;transform:translateY(34px) scale(.96)}
.on .in{animation:inn .9s var(--ease) forwards;animation-delay:var(--d,.5s)}
@keyframes inn{to{opacity:1;transform:none}}
.logo{width:56px;height:56px;border-radius:16px;background:#fff;padding:10px;box-shadow:0 8px 24px #0004;display:grid;place-items:center;flex:none}
.logo img{width:100%;height:100%;object-fit:contain}
.logo.f{font-weight:900;color:#111;font-size:22px}
.pop{transform:scale(0) rotate(-30deg)}
.on .pop{animation:pop .9s var(--ease) forwards;animation-delay:var(--d,.6s)}
@keyframes pop{to{transform:none}}
/* ranked bars, after the Remotion wrapped bars: round ends, grow out of a circle */
.rb{margin:9px 0;display:flex;align-items:center}
.rbar{height:60px;width:60px;border-radius:30px;display:flex;align-items:center;gap:10px;padding:8px;overflow:hidden;box-shadow:0 0 4px #0004;transition:width 1.3s var(--ease);white-space:nowrap}
.rbar .logo{width:44px;height:44px;border-radius:50%;padding:9px;box-shadow:none}
.rbar b{font-size:16px;font-weight:800;overflow:hidden;text-overflow:ellipsis;opacity:0;transition:opacity .6s .9s;flex:1;min-width:0}
.rbar .v{font-weight:800;font-size:15px;padding-right:12px;opacity:0;transition:opacity .6s 1s;font-variant-numeric:tabular-nums}
.rbar .n{width:44px;height:44px;border-radius:50%;display:grid;place-items:center;font-weight:900;font-size:20px;background:#0002;flex:none}
.rb.go .rbar b,.rb.go .rbar .v{opacity:1}
.card{background:color-mix(in srgb,var(--ink) 11%,transparent);border:1px solid color-mix(in srgb,var(--ink) 24%,transparent);border-radius:18px;padding:16px;transition:transform .15s}
.grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.grid .card .big{font-size:38px;letter-spacing:-.04em}.grid .card .k{font-size:10px;margin:0 0 6px}
.grid .card small{display:block;font-size:12px;opacity:.75;margin-top:4px;font-weight:600}
svg text{font-family:inherit}
.draw{stroke-dasharray:1;stroke-dashoffset:1;transition:stroke-dashoffset 2.2s cubic-bezier(.4,0,.2,1)}
.on .draw.go{stroke-dashoffset:0}
.col{transform:scaleY(0);transform-origin:bottom;transition:transform 1.2s var(--ease)}
.on .col{transform:scaleY(1);transition-delay:var(--d,.6s)}
.pulse{animation:pulse 1.6s ease-out infinite}@keyframes pulse{0%{r:5;opacity:1}100%{r:22;opacity:0}}
/* intro: kaleidoscope, expanding gradient circle, wrapped card */
.ql{position:absolute!important;inset:0;z-index:1!important;clip-path:inset(33% 33% 33% 33%);opacity:0}
.on .ql{animation:qin 1.1s var(--ease) forwards;animation-delay:calc(var(--k)*.85s)}
@keyframes qin{to{clip-path:inset(0);opacity:1}}
.ql div{position:absolute;width:50%;height:50%;display:grid;place-items:center;overflow:hidden}
.ql img{width:56%;height:56%;object-fit:contain;animation:zoom 9s linear forwards}
@keyframes zoom{from{transform:scale(1)}to{transform:scale(1.35) translateX(12px)}}
.gc{position:absolute!important;left:50%;top:50%;width:150vh;height:150vh;margin:-75vh 0 0 -75vh;border-radius:50%;overflow:hidden;z-index:2!important;transform:scale(0);opacity:0}
.on .gc{animation:gcin 1.6s cubic-bezier(.3,.7,.2,1) forwards;animation-delay:var(--gd,3.6s)}
@keyframes gcin{to{transform:scale(1);opacity:1}}
.sunset{position:absolute;inset:0;height:200%;background:var(--sun);animation:sun 9s linear infinite}
@keyframes sun{to{transform:translateY(-50%)}}
.sheet{position:relative;background:var(--sheet);color:var(--sheetink);border-radius:6px;box-shadow:0 0 14px #0006;padding:26px 22px;transform:scale(.7);opacity:0}
.on .sheet{animation:sheet 1.1s var(--ease) forwards;animation-delay:var(--sd,4.6s)}
@keyframes sheet{to{transform:scale(1);opacity:1}}
.sheet .card{background:#0000000d;border-color:#0002}
/* belts */
.belt{overflow:hidden;margin:12px -28px;position:relative}
.trk{display:flex;gap:12px;width:max-content;animation:belt 26s linear infinite}
.belt.r .trk{animation-direction:reverse}
@keyframes belt{to{transform:translateX(-50%)}}
.bi{display:flex;align-items:center;gap:10px;background:color-mix(in srgb,var(--ink) 12%,transparent);border-radius:16px;padding:8px 14px 8px 8px;font-weight:800;font-size:14px;white-space:nowrap}
.bi .logo{width:40px;height:40px;border-radius:12px;padding:8px}
/* podium */
.pod{display:flex;align-items:flex-end;gap:10px;height:290px;margin-top:40px}
.pod>div{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;text-align:center;min-width:0}
.pod .step{width:100%;border-radius:14px 14px 0 0;display:flex;align-items:flex-start;justify-content:center;padding-top:10px;font-weight:900;font-size:40px;transform:scaleY(0);transform-origin:bottom;transition:transform 1.3s var(--ease)}
.on .pod .step{transform:scaleY(1);transition-delay:var(--d)}
.pod small{font-size:12px;font-weight:700;margin:6px 0;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.pod .top{opacity:0;transform:translateY(-60px)}
.on .pod .top{animation:drop .9s var(--ease) forwards;animation-delay:calc(var(--d) + .9s)}
@keyframes drop{to{opacity:1;transform:none}}
/* wheel + gauge */
.wheel{transition:transform 4.2s cubic-bezier(.1,.75,.15,1);transform:rotate(-1500deg)}
.needle{transition:transform 2.2s cubic-bezier(.3,1.5,.5,1);transform:rotate(-90deg);transform-origin:150px 150px}
.exp{display:flex;gap:8px;margin-top:16px}
.exp button{flex:1;font:inherit;font-weight:800;font-size:12px;border:0;border-radius:12px;padding:12px 6px;background:var(--sheetink);color:var(--sheet);cursor:pointer;transition:transform .15s}
.exp button:hover{transform:translateY(-2px) scale(1.03)}
body.rec .exp{display:none}
.slide.i0{justify-content:flex-end;padding-bottom:70px}
canvas{position:absolute;inset:0;z-index:3;pointer-events:none}
.rain{z-index:1!important}
@media(prefers-reduced-motion:reduce){*{animation-duration:.01s!important;transition-duration:.01s!important}}
</style>
<div id="app"><div class="bars" id="bars"></div><div class="hint">tap · ← → · space</div></div>
<script>
const SRC='<!doctype html>\n'+document.documentElement.outerHTML;
const D=__DATA__,app=document.getElementById('app'),bars=document.getElementById('bars'),Q=new URLSearchParams(location.search);
const SLIDE_MS=+Q.get('t')||6000;if(Q.has('rec'))document.body.classList.add('rec');
const DARK=new Set(D.dark||['bash','markdown','cursor']);
const nf=n=>Math.round(n).toLocaleString(),cmp=n=>n>=1e9?(n/1e9).toFixed(1)+'B':n>=1e6?(n/1e6).toFixed(1)+'M':n>=1e3?(n/1e3).toFixed(1)+'K':n;
const H=h=>(h%12||12)+(h<12?'am':'pm'),MON=m=>new Date(m+'-15').toLocaleDateString(undefined,{month:'short'});
const split=(s,d=0)=>{let i=0;return String(s).split(' ').map(w=>`<span style="display:inline-block;white-space:nowrap">${[...w].map(c=>`<span class="ch" style="--i:${i++};--d:${d}ms">${c}</span>`).join('')}</span>`).join(' ')};
const logo=(s,x='')=>D.logos[s]?`<div class="logo ${x}" style="${DARK.has(s)?'background:#111':''}"><img src="${D.logos[s]}"></div>`:`<div class="logo f ${x}">?</div>`;
const lg=(s,n,x='')=>D.logos[s]?logo(s,x):`<div class="logo f ${x}">${(n||'?')[0].toUpperCase()}</div>`;
// flat brand colours, after the Remotion wrapped scenes: [background, ink, accent]
const FL={pink:['#d4148e','#ffffff','#b2fef5'],mint:['#b2fef5','#d4148e','#4e00f9'],lime:['#d5f772','#1e1416','#4e00f9'],violet:['#4e00f9','#ffffff','#d5f772'],ink:['#1e1416','#ffffff','#b2fef5'],white:['#fefefe','#d4148e','#4e00f9']};
const RANK=['#b2fef5','#d5f772','#4e00f9','#d4148e','#fefefe'],rinkOf=c=>c=='#4e00f9'||c=='#d4148e'?'#fff':'#1e1416';
let curBg='#000';
const rows=(r,fmt=v=>nf(v),d=.5,ranked=false)=>{const m=Math.max(...r.map(x=>x[1]),1),cols=RANK.filter(c=>c!=curBg);return r.map((x,i)=>{const c=cols[i%cols.length];return `<div class="rb in" style="--d:${d+i*.12}s"><div class="rbar" data-w="${Math.max(64,100*x[1]/m)}" style="background:${c};color:${rinkOf(c)}">${ranked?`<span class="n">${i+1}</span>`:lg(x[2],x[0])}<b>${x[0]}${x[3]?` <span style="opacity:.6;font-weight:600">${x[3]}</span>`:''}</b><span class="v">${fmt(x[1])}</span></div></div>`}).join('')};
const cnt=(v,s='',st='')=>`<div class="big" style="${st}"><span data-count="${v}">0</span>${s}</div>`;
const card=(k,v,sub,d)=>`<div class="card tilt in" style="--d:${d}s"><div class="k">${k}</div>${v}${sub?`<small>${sub}</small>`:''}</div>`;
const SUN_NIGHT='linear-gradient(#090416,#2f0199 22%,#c026d3 38%,#470905 52%,#090416 64%,#2f0199 80%,#736bdb 92%,#090416)',SUN_FULL='linear-gradient(#92a77d,#ccd56a 9%,#e6b417 18%,#e37e10 27%,#dc2407 36%,#470905 45%,#090416 54%,#2f0199 64%,#736bdb 73%,#adc1d3 82%,#aecdbf 91%,#92a77d)';
const sunOf=()=>D.personaKind=='night'?SUN_NIGHT:SUN_FULL;
const T=D.talk||{},hb=D.habits||{},S=[];
const tpl=(f,h,o={})=>S.push(Object.assign({f,h},o));
const logoTiles=Object.keys(D.logos);
// 0 intro: kaleidoscope -> gradient circle -> wrapped card
{const ks=['pink','lime','violet','mint'],lk=logoTiles.filter(s=>!DARK.has(s)).slice(0,4);while(lk.length<4)lk.push(lk[lk.length-1]||'claude');
tpl('pink',`${lk.map((s,k)=>{const c=FL[ks[k]][0],q=(m)=>`<div style="background:${c};${m}"><img src="${D.logos[s]||''}"></div>`;return `<div class="ql" style="--k:${k}">${q('left:0;top:0;transform:scaleX(-1)')}${q('left:50%;top:0')}${q('left:0;top:50%;transform:scale(-1)')}${q('left:50%;top:50%;transform:scaleY(-1)')}</div>`}).join('')}
 <div class="gc" style="--gd:3.6s"><div class="sunset" style="--sun:${sunOf()}"></div></div>
 <div style="position:relative;z-index:3"><div class="sheet" style="--sheet:#b2fef5;--sheetink:#d4148e;--sd:4.9s"><div class="k">${D.year}</div><div class="h" style="font-size:66px;line-height:.98">Agent<br>Wrapped</div><div class="p" style="margin-top:14px;font-size:15px">${D.demo?'A made-up developer, ten agents and nine models. Pure chaos.':'A year of you and your coding agents.'}</div></div></div>`,{dur:9500,mq:'AGENT WRAPPED '});}
// time
if(D.activeHours)tpl('pink',`<div class="k in">Time with your agents</div>${cnt(D.activeHours,'','font-size:112px')}<div class="h in" style="--d:.9s;font-size:32px">hours of agents at work</div><div class="p in" style="--d:1.3s">Counted in 15-minute slots with any activity. That is ${D.workWeeks} full 40-hour work weeks, across ${D.activeDays} days and ${nf(D.workspaces)} projects.</div>`,{mq:'TIME '});
// tokens with rain
if(D.outTokens)tpl('ink',`<canvas class="rain" data-rain="1"></canvas><div class="k in">Your agents wrote</div>${cnt(D.outTokens/1e6,'M','font-size:92px')}<div class="h in" style="--d:.9s;font-size:30px">tokens of text</div>
 <div style="display:flex;align-items:flex-end;gap:5px;height:100px;margin:20px 0 4px">${Array.from({length:Math.min(14,Math.max(3,Math.round(D.novels/50)))},(_,i)=>`<i class="in" style="--d:${1.2+i*.09}s;flex:1;height:${55+((i*37)%60)}%;background:${RANK[i%5]};border-radius:3px 3px 0 0;display:block"></i>`).join('')}</div>
 <div class="p in" style="--d:2.6s">About ${nf(D.novels)} novels. You read a small slice, and that is fine.</div>`,{mq:'OUTPUT '});
// top agent
if(D.agents.length){curBg=FL.violet[0];const tot=D.agents.reduce((a,b)=>a+b[1],0);tpl('violet',`<div class="k in">Your most-used agent</div><div style="display:flex;align-items:center;gap:16px"><div style="transform:scale(1.7);transform-origin:left;margin-right:30px">${lg(D.agents[0][2],D.agents[0][0],'pop')}</div></div><div class="h" style="margin-top:36px">${split(D.agents[0][0],500)}</div><div class="p in" style="--d:1s">${nf(D.agents[0][1])} sessions. ${Math.round(100*D.agents[0][1]/tot)}% of the total.</div><div style="margin-top:12px">${rows(D.agents.slice(1,4),nf,1.2)}</div>${D.multiAgentDays?`<div class="p in" style="--d:2s;font-size:14px">On ${D.multiAgentDays} days you ran three or more agents at once.</div>`:''}`,{mq:'TOP AGENT '})}
// models podium
if(D.models.length>=3){const m=D.models,ord=[1,0,2],hs=[150,205,105],cs=['#d4148e','#4e00f9','#1e1416'];
tpl('lime',`<div class="k in">Who did the thinking</div><div class="h">${split('The model podium',100)}</div>
 <div class="pod">${ord.map((r,i)=>`<div><div class="top" style="--d:${.6+i*.2}s">${lg(m[r][2],m[r][0])}</div><small class="top" style="--d:${.6+i*.2}s">${m[r][0]}</small><small class="top" style="--d:${.6+i*.2}s">${cmp(m[r][1])} tokens</small><div class="step" style="height:${hs[i]}px;background:${cs[i]};color:#fff;--d:${.4+i*.25}s">${r+1}</div></div>`).join('')}</div>`,{mq:'PODIUM '})}
// roster belts
{const ag=D.agents.map(a=>[a[0],a[2]]),md=D.models.map(a=>[a[0],a[2]]);if(ag.length>=3&&md.length>=3){const belt=(it,c)=>`<div class="belt ${c}"><div class="trk">${[...it,...it,...it,...it].map(i=>`<div class="bi">${lg(i[1],i[0])}<b>${i[0]}</b></div>`).join('')}</div></div>`;
const labs=new Set(D.models.map(x=>x[2]||x[0])).size;
tpl('violet',`<div class="k in">Your AI roster</div><div class="h">${split(ag.length+' agents. '+md.length+' models.',100)}</div>${belt(ag,'')}${belt(md,'r')}${belt(ag.slice().reverse(),'')}<div class="p in" style="--d:1.6s">${labs} different labs wrote the brains. You played the field.</div>`,{mq:'ROSTER '})}}
// roulette
if(D.models.length>=3){const m=D.models.slice(0,8),n=m.length,a=360/n,R=140,cols=['#d4148e','#4e00f9','#1e1416','#d5f772','#b2fef5','#d4148e','#4e00f9','#1e1416'],pt=(ang,r)=>[Math.sin(ang*Math.PI/180)*r,-Math.cos(ang*Math.PI/180)*r];
tpl('mint',`<div class="k in">Model of the year</div>
 <svg viewBox="-160 -170 320 330" style="width:100%;max-width:340px;margin:0 auto;display:block"><g class="wheel" data-spin="1">${m.map((x,i)=>{const [x1,y1]=pt(i*a-a/2,R),[x2,y2]=pt(i*a+a/2,R),[lx,ly]=pt(i*a,R*.68);return `<path d="M0 0L${x1} ${y1}A${R} ${R} 0 0 1 ${x2} ${y2}Z" fill="${cols[i%8]}" stroke="#fff" stroke-width="3"/><g transform="translate(${lx} ${ly}) rotate(${i*a})"><rect x="-19" y="-19" width="38" height="38" rx="10" fill="${DARK.has(x[2])?'#111':'#fff'}"/>${D.logos[x[2]]?`<image href="${D.logos[x[2]]}" x="-13" y="-13" width="26" height="26"/>`:`<text y="6" text-anchor="middle" font-weight="900" font-size="18" fill="#111">${x[0][0].toUpperCase()}</text>`}</g>`}).join('')}<circle r="16" fill="#fff"/></g><path d="M-14 -166L14 -166L0 -138Z" fill="#1e1416"/></svg>
 <div class="h in" style="--d:4.4s;font-size:34px;text-align:center;margin-top:6px">${m[0][0]}</div><div class="p in" style="--d:4.8s;text-align:center;margin-top:6px">${cmp(m[0][1])} tokens. The wheel only lands on winners.</div>`,{mq:'ROULETTE ',dur:Math.max(SLIDE_MS,7500)})}
// language
if(D.langs.length){curBg=FL.white[0];const md=D.langs.find(x=>x[0]=='Markdown'),ts=D.langs.find(x=>x[0]=='TypeScript');
tpl('white',`<div class="k in">The language you wrote most</div><div style="transform:scale(1.7);transform-origin:left;margin-right:30px">${lg(D.langs[0][2],D.langs[0][0],'pop')}</div><div class="h" style="margin-top:36px">${split(D.langs[0][0],500)}</div><div class="p in" style="--d:1s">${nf(D.langs[0][1])} files written by your agents.</div><div style="margin-top:10px">${rows(D.langs.slice(1,5),nf,1.2)}</div>${md&&ts&&md[1]>ts[1]?`<div class="p in" style="--d:2s;font-size:14px">You write more docs than TypeScript. Respect.</div>`:''}`,{mq:'CODE '})}
// file
if(D.topFiles.length&&D.topFiles[0][1]){const f=D.topFiles[0],ext=(f[0].split('.').pop()||''),line={css:'The styling is never quite done.',md:'Writing it down, again and again.',py:'One file, many opinions.',tsx:'One component, many revisions.',swift:'One view, many revisions.'}[ext]||'Some files are never finished.';
tpl('lime',`<div class="k in">The file you could not leave alone</div><div class="h" style="font-size:34px;word-break:break-all">${split(f[0],100)}</div>${cnt(f[1],'','font-size:104px;margin-top:14px')}<div class="h in" style="--d:1s;font-size:26px">edits in ${f[2]||'one folder'}</div><div class="p in" style="--d:1.5s">${line}</div>`,{mq:'EDITS '})}
// talk
if(T.n)tpl('violet',`<div class="k in">How you talk to your agents</div><div class="h">${split('Mostly polite. Mostly.',100)}</div><div class="grid" style="margin-top:20px">
 ${card('Said please',cnt(T.please),'and thanks '+nf(T.thanks)+' times',.9)}${card('Lost patience',cnt(T.swear),'prompts with a swear word',1.05)}
 ${card('The word "still"',cnt(T.still),'as in "still broken"',1.2)}${card('Asked "why"',cnt(T.why),nf(T.qmark)+' had a question mark',1.35)}</div>
 <div class="p in" style="--d:2s">"Fix" is in ${Math.round(100*T.fix/T.n)}% of your prompts. The average prompt is ${Math.round(T.avg_len/5.5)} words.</div>`,{mq:'PROMPTS '});
// patience gauge
if(T.n&&(T.please+T.thanks+T.swear)>0){const pol=Math.round(100*(T.please+T.thanks)/(T.please+T.thanks+T.swear)),ang=-90+180*pol/100,arc=(a0,a1,c)=>{const p=(a,r)=>[150+Math.cos((a-180)*Math.PI/180)*r,150+Math.sin((a-180)*Math.PI/180)*r],[x0,y0]=p(a0,120),[x1,y1]=p(a1,120);return `<path d="M${x0} ${y0}A120 120 0 0 1 ${x1} ${y1}" stroke="${c}" stroke-width="26" fill="none"/>`};
tpl('pink',`<div class="k in">Patience meter</div><div class="h">${split('How polite are you',100)}</div>
 <svg viewBox="0 0 300 175" style="width:100%;margin-top:14px">${arc(0,60,'#1e1416')}${arc(60,120,'#d5f772')}${arc(120,180,'#b2fef5')}<g class="needle" data-needle="${ang}"><line x1="150" y1="150" x2="150" y2="48" stroke="#fff" stroke-width="7" stroke-linecap="round"/></g><circle cx="150" cy="150" r="14" fill="#fff"/></svg>
 ${cnt(pol,'%','font-size:72px;text-align:center')}<div class="p in" style="--d:1.4s;text-align:center">${nf(T.please+T.thanks)} pleases and thanks against ${nf(T.swear)} swears. The agents noticed.</div>`,{mq:'PATIENCE '})}
// rhythm
{const dn=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],full=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],mx=Math.max(...D.dow),pk=D.dow.indexOf(mx);
tpl('ink',`<div class="k in">Your week</div><div class="h">${split(full[pk]+' is your day',100)}</div>
 <svg viewBox="0 0 400 220" style="width:100%;margin-top:22px">${D.dow.map((n,i)=>{const h=170*n/mx;return `<rect class="col" x="${12+i*55}" y="${190-h}" width="38" height="${h}" rx="19" fill="${i==pk?'#d5f772':RANK[i%5]}" fill-opacity="${i==pk?1:.8}" style="--d:${.5+i*.1}s"/><text x="${31+i*55}" y="212" text-anchor="middle" fill="currentColor" font-size="13" opacity=".8">${dn[i]}</text>`}).join('')}</svg>
 <div class="p in" style="--d:1.8s">${D.weekendPct}% of your prompts happened on a weekend.</div>`,{mq:'WEEK '})}
// clock + persona on the sunset sheet
{const R0=62,mx=Math.max(...D.hours),L=h=>8+88*D.hours[h]/mx;
tpl('ink',`<div class="gc" style="--gd:.1s;opacity:1;transform:scale(1);animation:none"><div class="sunset" style="--sun:${sunOf()}"></div></div>
 <div class="sheet" style="--sheet:#b2fef5;--sheetink:#d4148e;--sd:.5s"><div class="k">Your peak hour</div><div class="h" style="font-size:52px">${H(D.peakHour)}</div>
 <svg viewBox="-130 -130 260 260" style="width:100%;max-width:280px;margin:0 auto;display:block"><circle r="${R0-8}" fill="#d4148e" fill-opacity=".12"/>
 ${D.hours.map((n,h)=>{const a=(h/24)*2*Math.PI-Math.PI/2,l=L(h);return `<line x1="${Math.cos(a)*R0}" y1="${Math.sin(a)*R0}" x2="${Math.cos(a)*(R0+l)}" y2="${Math.sin(a)*(R0+l)}" pathLength="1" class="draw go" style="transition-delay:${.9+h*.05}s" stroke="#d4148e" stroke-width="7" stroke-linecap="round" stroke-opacity="${h==D.peakHour?1:.5}"/>`}).join('')}
 <text y="6" text-anchor="middle" fill="#d4148e" font-weight="900" font-size="22">24h</text></svg>
 <div class="h" style="font-size:26px;margin-top:10px">${D.persona}</div><div class="p" style="margin-top:4px;font-size:15px"><b>${D.personaDef}.</b> ${nf(D.afterMidnight)} prompts landed between midnight and 5am.</div></div>`,{mq:'AFTER HOURS '})}
// trend
if(D.months.length>1){curBg=FL.mint[0];const W=400,Hh=190,m=D.months,mx=Math.max(...m.map(x=>x[1])),pt=m.map((x,i)=>[20+i*(W-40)/(m.length-1),Hh-14-(Hh-40)*x[1]/mx]),pi=m.findIndex(x=>x[1]==mx),pk=pt[pi];
 const d=pt.map((p,i)=>(i?'L':'M')+p[0].toFixed(1)+' '+p[1].toFixed(1)).join(' ');
 tpl('mint',`<div class="k in">Prompts per month</div><div class="h">${split('Your busiest era',100)}</div>
 <svg viewBox="0 0 ${W} ${Hh+22}" style="width:100%;margin-top:26px;overflow:visible"><defs><linearGradient id="g" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#4e00f9" stop-opacity=".35"/><stop offset="1" stop-color="#4e00f9" stop-opacity="0"/></linearGradient></defs>
 ${pt.map(p=>`<line x1="${p[0]}" x2="${p[0]}" y1="10" y2="${Hh-10}" stroke="currentColor" stroke-opacity=".2" stroke-dasharray="4 4"/>`).join('')}
 <path d="${d} L${pt.at(-1)[0]} ${Hh-10} L${pt[0][0]} ${Hh-10}Z" fill="url(#g)" class="in" style="--d:1.6s"/>
 <path d="${d}" pathLength="1" class="draw go" fill="none" stroke="#4e00f9" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>
 <circle cx="${pk[0]}" cy="${pk[1]}" r="7" fill="#4e00f9" class="in" style="--d:2s"/><circle cx="${pk[0]}" cy="${pk[1]}" r="6" fill="none" stroke="#4e00f9" stroke-width="2" class="pulse"/>
 ${pt.map((p,i)=>`<text x="${p[0]}" y="${Hh+14}" fill="currentColor" font-size="11" text-anchor="middle" opacity=".7">${MON(m[i][0])}</text>`).join('')}</svg>
 <div class="p in" style="--d:2.2s">Peak: ${MON(m[pi][0])}, with ${nf(mx)} prompts.</div>`,{mq:'MOMENTUM '})}
// biggest day
if(D.bestDay)tpl('lime',`<div class="k in">Your biggest day</div><div class="h" style="font-size:50px">${split(new Date(D.bestDay+'T12:00').toLocaleDateString(undefined,{month:'long',day:'numeric'}),100)}</div>${cnt(D.bestDayN,'','font-size:92px;margin-top:8px')}<div class="h in" style="--d:1s;font-size:26px">prompts in one day</div>
 <div class="grid" style="margin-top:18px">${card('Longest streak',cnt(D.streak),'days in a row',1.3)}${card('Longest chat',cnt(D.longestChat),'prompts, one session',1.45)}</div>`,{mq:'BIG DAY '});
// git
if(hb.commits){curBg=FL.violet[0];tpl('violet',`<div class="k in">Your git year</div><div class="h">${split('You shipped a lot',100)}</div><div style="margin-top:16px">${rows([['Commits',hb.commits,'git'],['Pushes',hb.pushes,'github'],['PRs opened',hb.prs,'github'],['PRs merged',hb.merges,'github']],nf,.9)}</div><div class="p in" style="--d:2s;font-size:15px">${nf(hb.stash)} stashes too: plenty of work you were not ready to commit yet.</div>`,{mq:'SHIPPED '})}
// terminal
if(hb.ssh){curBg=FL.ink[0];tpl('ink',`<div class="k in">Terminal habits</div><div class="h">${split('Look. Connect. Delete.',100)}</div><div style="margin-top:16px">${rows([['Looked around (ls)',hb.ls,'bash'],['Logged in remotely (ssh)',hb.ssh,'bash'],['Fetched a URL (curl)',hb.curl,'bash'],['Deleted for good (rm -rf)',hb.rmrf,'bash']].sort((a,b)=>b[1]-a[1]),nf,.9)}</div><div class="p in" style="--d:2s;font-size:15px">You (or your agents) ran rm -rf ${nf(hb.rmrf)} times. Brave.</div>`,{mq:'TERMINAL '})}
// sites
if(D.sites.length){curBg=FL.white[0];tpl('white',`<div class="k in">Where your agents looked things up</div><div class="h">${split('Top sites',100)}</div><div style="margin-top:18px">${rows(D.sites,nf,.9)}</div><div class="p in" style="--d:2s;font-size:15px">Pages fetched on your behalf, so you did not have to.</div>`,{mq:'READING '})}
// LLM insights
const CYC=['pink','lime','violet','mint','ink','white'];
(D.insights||[]).forEach((x,i)=>tpl(x.flat||CYC[i%6],`<div class="k in">${x.kicker||''}</div>${typeof x.big=='number'?cnt(x.big,'','font-size:96px'):`<div class="h" style="font-size:46px">${split(x.big,100)}</div>`}${x.unit?`<div class="h in" style="--d:.9s;font-size:26px;margin-top:8px">${x.unit}</div>`:''}${x.logo?`<div style="margin-top:18px">${lg(x.logo,'','pop')}</div>`:''}<div class="p in" style="--d:1.4s">${x.caption||''}</div>`,{mq:(x.kicker||'FACT')+' '}));
// close calls
tpl('ink',`<div class="k in">Close calls</div><div class="h">${split('Keys you pasted',100)}</div>${cnt(D.keysRaw,'','font-size:110px;margin-top:6px')}<div class="h in" style="--d:.9s;font-size:26px">raw key pastes</div>
 <div class="grid" style="margin-top:16px">${card('Went through safely',cnt(D.keysSafe),D.cloakPct+'% of key uses',1.3)}${card('Risky packages stopped',cnt(D.pkgBlocked),'before install',1.45)}</div>`,{mq:'CLOSE CALLS '});
// finale: sheet on gradient + export
const shareTxt=`My ${D.year} Agent Wrapped: ${nf(D.activeHours)} hours of agents at work, ${D.outTokens?cmp(D.outTokens)+' tokens written, ':''}${nf(hb.commits||0)} commits. I'm a ${D.persona}: ${D.personaDef}. #AgentWrapped\n\nGenerate your wrapped @ prismor.dev/agent-wrapped`;
tpl('ink',`<div class="gc" style="--gd:.1s;opacity:1;transform:scale(1);animation:none"><div class="sunset" style="--sun:${sunOf()}"></div></div>
 <div class="sheet" style="--sheet:#fefefe;--sheetink:#d4148e;--sd:.6s"><div class="k">You are</div><div class="h" style="font-size:44px">${split('The '+D.persona,400)}</div><div class="h in" style="--d:1.4s;font-size:22px;margin-top:8px;color:#1e1416">${D.personaDef}</div>
 <div class="grid" style="margin-top:18px">${card('Hours',`<div class="big">${nf(D.activeHours)}</div>`,'with agents',1.6)}${D.outTokens?card('Tokens',`<div class="big">${cmp(D.outTokens)}</div>`,'written',1.7):card('Sessions',`<div class="big">${cmp(D.sessions)}</div>`,'started',1.7)}${card('Top agent',`<div class="big" style="font-size:22px">${D.agents[0]?D.agents[0][0]:'-'}</div>`,D.langs[0]?D.langs[0][0]+' is your language':'',1.8)}${card('Commits',`<div class="big">${cmp(hb.commits||0)}</div>`,nf(hb.prs||0)+' PRs opened',1.9)}</div>
 <div class="exp in" style="--d:2.4s"><button data-x="share">Share on X</button><button data-x="html">Download HTML</button><button data-x="video">Download as video</button></div></div><canvas></canvas>`,{mq:'SEE YOU NEXT YEAR ',confetti:1,last:1});
S.forEach((s,i)=>{const [bg,ink,acc]=FL[s.f]||FL.ink,el=document.createElement('section');el.className='slide i'+i;el.style.cssText=`--bg:${bg};--ink:${ink};--acc:${acc}`;
 el.innerHTML=`<div class="dot" style="width:340px;height:340px;right:-140px;top:-90px"></div><div class="dot" style="width:200px;height:200px;left:-80px;bottom:90px;animation-delay:-4s"></div>
 <div class="spin" style="width:380px;height:380px;right:-170px;top:-120px"></div><div class="spin" style="width:220px;height:220px;left:-90px;bottom:60px;animation-direction:reverse"></div>
 <div class="mq" style="bottom:46px">${(s.mq||'').repeat(8)}</div>${s.h}`;
 app.appendChild(el);bars.insertAdjacentHTML('beforeend','<i><b></b></i>')});
const sl=[...document.querySelectorAll('.slide')],fill=[...bars.querySelectorAll('b')];let cur=-1,raf;
function count(el){const n=+el.dataset.count,s=performance.now(),dec=n<100&&n%1?1:0;(function f(now){const p=Math.min(1,(now-s-400)/1600);if(p>=0)el.textContent=(n*(1-Math.pow(1-p,4))).toLocaleString(undefined,{maximumFractionDigits:dec,minimumFractionDigits:dec});if(p<1)requestAnimationFrame(f)})(s)}
function confetti(cv){const x=cv.getContext('2d');cv.width=cv.offsetWidth;cv.height=cv.offsetHeight;const C=['#d4148e','#b2fef5','#d5f772','#4e00f9','#fff'],P=Array.from({length:170},()=>({x:cv.width/2,y:cv.height*.55,vx:(Math.random()-.5)*15,vy:-Math.random()*17-4,s:Math.random()*8+4,c:C[Math.random()*5|0],r:Math.random()*6}));(function f(){x.clearRect(0,0,cv.width,cv.height);P.forEach(p=>{p.vy+=.28;p.x+=p.vx;p.y+=p.vy;p.r+=.2;x.fillStyle=p.c;x.save();x.translate(p.x,p.y);x.rotate(p.r);x.fillRect(-p.s/2,-p.s/4,p.s,p.s/2);x.restore()});if(P.some(p=>p.y<cv.height+20))requestAnimationFrame(f)})()}
function rain(cv,i){const x=cv.getContext('2d');cv.width=cv.offsetWidth;cv.height=cv.offsetHeight;const G=['0','1','{','}','</>','=>','()','tok','"','#'],c=getComputedStyle(cv.parentNode).getPropertyValue('--acc'),P=Array.from({length:46},()=>({x:Math.random()*cv.width,y:Math.random()*-cv.height,v:1.2+Math.random()*3,g:G[Math.random()*G.length|0],s:12+Math.random()*16}));(function f(){if(cur!=i)return;x.clearRect(0,0,cv.width,cv.height);x.fillStyle=c;P.forEach(p=>{p.y+=p.v;if(p.y>cv.height){p.y=-20;p.x=Math.random()*cv.width}x.globalAlpha=.22;x.font=`800 ${p.s}px Poppins,sans-serif`;x.fillText(p.g,p.x,p.y)});requestAnimationFrame(f)})()}
function go(i){i=Math.max(0,Math.min(sl.length-1,i));if(i==cur&&i<sl.length-1)return;cancelAnimationFrame(raf);
 sl.forEach((s,k)=>{s.classList.remove('prev');if(k==cur&&k!=i)s.classList.add('prev');if(k!=i)s.classList.remove('on')});
 const s=sl[i];sl.forEach(x=>x.style.clipPath='');s.querySelectorAll('.rbar').forEach(b=>{b.style.width='';b.parentNode.classList.remove('go')});
 s.querySelectorAll('[data-spin]').forEach(w=>{w.style.transition='none';w.style.transform='rotate(-1500deg)';void w.getBoundingClientRect();w.style.transition='';});
 s.querySelectorAll('[data-needle]').forEach(w=>{w.style.transition='none';w.style.transform='rotate(-90deg)';void w.getBoundingClientRect();w.style.transition='';});
 void s.offsetWidth;s.classList.add('on');setTimeout(()=>{if(cur==i)s.style.clipPath='none'},1100);
 fill.forEach((f,k)=>f.style.width=k<i?'100%':'0');cur=i;
 s.querySelectorAll('[data-count]').forEach(count);
 setTimeout(()=>{if(cur!=i)return;s.querySelectorAll('.rbar').forEach(b=>{b.style.width=b.dataset.w+'%';b.parentNode.classList.add('go')});s.querySelectorAll('[data-spin]').forEach(w=>w.style.transform='rotate(0deg)');s.querySelectorAll('[data-needle]').forEach(w=>w.style.transform=`rotate(${w.dataset.needle}deg)`)},900);
 const cv=s.querySelector('canvas:not(.rain)');if(cv)setTimeout(()=>confetti(cv),1300);const rv=s.querySelector('canvas.rain');if(rv)rain(rv,i);
 const sp=S[i],dur=sp.last?1e9:(sp.dur||SLIDE_MS),t0=performance.now();(function tick(now){const p=Math.min(1,(now-t0)/dur);fill[i].style.width=p*100+'%';if(p<1)raf=requestAnimationFrame(tick);else go(i+1)})(t0);
 if(sp.last)setTimeout(()=>{window.__done=true;window.__onDone&&window.__onDone()},4200)}
// export
async function recVideo(){try{const st=await navigator.mediaDevices.getDisplayMedia({video:{displaySurface:'browser'},preferCurrentTab:true,audio:false}),mt=['video/mp4;codecs=avc1','video/webm;codecs=vp9','video/webm'].find(t=>MediaRecorder.isTypeSupported(t)),mr=new MediaRecorder(st,{mimeType:mt,videoBitsPerSecond:8e6}),ch=[];mr.ondataavailable=e=>ch.push(e.data);mr.onstop=()=>{document.body.classList.remove('rec');const b=new Blob(ch,{type:mt}),a=document.createElement('a');a.href=URL.createObjectURL(b);a.download='agent-wrapped.'+(mt.includes('mp4')?'mp4':'webm');a.click()};document.body.classList.add('rec');window.__done=false;window.__onDone=()=>setTimeout(()=>{mr.stop();st.getTracks().forEach(t=>t.stop())},800);mr.start();cur=-1;go(0)}catch(e){alert('Recording needs Chrome and permission to capture this tab. Or run the skill with --video for an MP4.')}}
app.addEventListener('click',e=>{const b=e.target.closest('button');if(b){e.stopPropagation();const x=b.dataset.x;if(x=='share')window.open('https://x.com/intent/post?text='+encodeURIComponent(shareTxt),'_blank','noopener');if(x=='html'){const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([SRC],{type:'text/html'}));a.download='agent-wrapped.html';a.click()}if(x=='video')recVideo();return}
 const r=app.getBoundingClientRect();go(cur+(e.clientX<r.left+r.width/3?-1:1))});
addEventListener('keydown',e=>{if(e.key=='ArrowLeft')go(cur-1);if(e.key=='ArrowRight'||e.key==' ')go(cur+1)});
app.addEventListener('mousemove',e=>document.querySelectorAll('.on .tilt').forEach(c=>{const r=c.getBoundingClientRect(),x=(e.clientX-r.left)/r.width-.5,y=(e.clientY-r.top)/r.height-.5;c.style.transform=`perspective(500px) rotateY(${x*18}deg) rotateX(${-y*18}deg)`}));
window.__slides=S.length;go(0);window.__ready=true;
</script></html>
````

### video/record.mjs

````js
// Records the Agent Wrapped page to a 1080x1920 MP4: headless Chrome screencast frames + ffmpeg.
// usage: node record.mjs <file-url> <out.mp4> [msPerSlide]
import { chromium } from 'playwright-core';
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';

const [, , url, out, ms = '4200'] = process.argv;
if (!url || !out) { console.error('usage: node record.mjs <file-url> <out.mp4> [ms]'); process.exit(2); }

const tmp = fs.mkdtempSync(path.join(path.dirname(path.resolve(out)), '.frames-'));
const browser = await chromium.launch({ channel: 'chrome', headless: true });
const ctx = await browser.newContext({ viewport: { width: 540, height: 960 }, deviceScaleFactor: 2 });
const page = await ctx.newPage();
const cdp = await ctx.newCDPSession(page);

const frames = [];
cdp.on('Page.screencastFrame', ({ data, metadata, sessionId }) => {
  const f = path.join(tmp, `f${String(frames.length).padStart(6, '0')}.jpg`);
  fs.writeFileSync(f, Buffer.from(data, 'base64'));
  frames.push({ f, t: metadata.timestamp });
  cdp.send('Page.screencastFrameAck', { sessionId }).catch(() => {});
});

await cdp.send('Page.startScreencast', { format: 'jpeg', quality: 92, maxWidth: 1080, maxHeight: 1920, everyNthFrame: 1 });
await page.goto(`${url}?rec=1&t=${ms}`);
await page.waitForFunction(() => window.__done === true, null, { timeout: 15 * 60 * 1000 });
await page.waitForTimeout(1500);
await cdp.send('Page.stopScreencast');
await browser.close();

if (!frames.length) { console.error('no frames captured'); process.exit(1); }
let list = '';
frames.forEach((fr, i) => {
  const d = i < frames.length - 1 ? Math.max(0.001, frames[i + 1].t - fr.t) : 1.0;
  list += `file '${fr.f}'\nduration ${d.toFixed(4)}\n`;
});
list += `file '${frames.at(-1).f}'\n`;
const listFile = path.join(tmp, 'list.txt');
fs.writeFileSync(listFile, list);

const r = spawnSync('ffmpeg', ['-y', '-loglevel', 'error', '-f', 'concat', '-safe', '0', '-i', listFile,
  '-vf', 'fps=30,scale=1080:1920,format=yuv420p', '-c:v', 'libx264', '-crf', '18', '-preset', 'medium',
  '-movflags', '+faststart', path.resolve(out)], { stdio: 'inherit' });
fs.rmSync(tmp, { recursive: true, force: true });
process.exit(r.status ?? 1);
````
