Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: add cap-demo skill assets

Richie McIlroydccd0af16818
diff --git a/apps/cli/skill/cap-demo/SKILL.md b/apps/cli/skill/cap-demo/SKILL.md
new file mode 100644
index 000000000..a0b9b92dc
--- /dev/null
+++ b/apps/cli/skill/cap-demo/SKILL.md
@@ -0,0 +1,200 @@
+---
+name: cap-demo
+description: Generate a cinematic 3D product-demo video from any URL — scouts the page, records it with virtual input, and treats it with Cap's 3D camera, brand background, and music.
+---
+
+# cap-demo
+
+Give it a URL, get back a short, cinematic product-demo video. The pipeline
+scouts the page headlessly, shoots a headed browser with **virtual input only**
+(CDP mouse/keyboard — the user's real cursor is never touched), records with
+Cap's CLI, then treats the recording with Cap's 3D camera, a brand-matched
+background gradient, a synthetic cursor, and music, and exports an mp4.
+
+> **macOS only (for now).** This skill records via Cap's window capture and
+> resolves a cached Playwright Chromium under
+> `~/Library/Caches/ms-playwright`, both of which are macOS-specific today.
+> Apple Silicon is assumed (the bundled Chromium path is `chrome-mac-arm64`).
+
+## The skill directory
+
+`<skilldir>` below is the directory this `SKILL.md` was installed into. `cap
+agents install` writes it next to the main `cap` skill, so it is one of:
+
+- Claude: `~/.claude/skills/cap-demo`
+- Cursor: `~/.cursor/skills/cap-demo`
+- Codex: `<CODEX_HOME>/skills/cap-demo` (default `~/.codex/skills/cap-demo`)
+
+There is no `cap-demo` binary on PATH — the `cap-demo` command is just
+`node <skilldir>/cap-demo.mjs`. Alias it if you like:
+
+```
+alias cap-demo='node <skilldir>/cap-demo.mjs'
+```
+
+## Requirements
+
+- **macOS on Apple Silicon.** Windows/Linux are not supported yet.
+- **Node 18+**, with `playwright-core` vendored into the skill. Run `npm
+ install` once inside `<skilldir>` on first use. It **reuses an already-cached
+ Chromium** under `~/Library/Caches/ms-playwright`; if none is cached, run
+ `npx playwright install chromium` once.
+- **`python3`** and **`ffmpeg`/`ffprobe`** on PATH.
+- The **`cap` CLI** on PATH (Cap Desktop, https://cap.so) with macOS
+ **screen-recording permission** granted to it. Both stages otherwise resolve
+ the binary from `CAP_BIN`; if neither is set they error clearly.
+
+## One-liner
+
+```
+cap-demo https://website.com
+```
+
+Output lands at `<outDir>/<slug>-demo.mp4` (default `<tmp>/cap-demo/<slug>/<slug>-demo.mp4`).
+
+## Two modes
+
+- **Deterministic** (`cap-demo <url>`): fixed heuristics, no agent in the loop.
+ Scores the best CTA, picks click-through vs scroll, paints a brand gradient
+ from the page colors, picks music by brand darkness. Good, ~70% quality. Use
+ it for batch runs or when you cannot watch the frames.
+- **Agent-driven recipe** (recommended, ~95% quality): the agent runs the
+ same steps but frame-QAs each stage and applies judgment — sets the brand
+ color by eye, matches export fps to the real capture rate, reshoots on a
+ dead-end CTA, regrades until the beats read. This is the path that produced
+ the shipped demos. Follow the recipe below.
+
+## The agent recipe
+
+Run the two stages by hand so you can inspect between them. Both scripts live in
+this skill; the orchestrator just chains them.
+
+### 1. Scout + shoot
+
+```
+node <skilldir>/lib/scout-shoot.mjs <url> <outDir> <slug> [--story click|scroll]
+```
+
+- Writes the recording to `<outDir>/<slug>.cap` and the beat log to
+ `<outDir>/<slug>.timeline.json`.
+- Prints a final JSON line: `{"slug","story","scout":{title,hero,accent,pageBg,ctaText}}`.
+ Read it to see what it decided (story, chosen CTA, brand colors).
+- It already: kills stale test-chrome, closes Finder windows, dismisses cookie
+ banners, injects the shimmer div, matches the capture window by exact page
+ title (asserts a single match), and logs the virtual cursor path.
+
+**Story choice.** Leave it to auto for most sites (a strong content CTA →
+`click`, otherwise `scroll`). Force `--story scroll` for product one-pagers that
+showcase best as a scroll of their own sections, or when the top CTA dead-ends
+at a booking/login page.
+
+### 2. Frame-QA the raw recording (before treating)
+
+Extract a few beat frames and **look at them**:
+
+```
+ffmpeg -y -ss <t> -i <outDir>/<slug>.cap/content/segments/segment-0/display.mp4 -frames:v 1 /tmp/raw-<t>.png
+```
+
+Check: the right window/content is captured (no leftover footage from a prior
+shoot), no cookie banner leaked in, the CTA click did **not** dead-end at a
+booking calendar or login form, and the **end** of the clip is clean (no desktop
+or Finder window bleeding into the bottom of the capture). If any of that is
+wrong, reshoot with `--story scroll` or a better landmark before spending an
+export.
+
+### 3. Treat + export
+
+```
+python3 <skilldir>/lib/treat.py <outDir> <slug> [--music ID] [--quality 4k|hd] [--bg-gradient FROM_HEX,TO_HEX]
+```
+
+- Aligns beats to video (tail-anchored: the video can be **shorter** than the
+ event log — never trust event times blindly), trims dead time, aims three 3D
+ shots at the logged landmarks, paints the brand gradient, synthesizes the
+ cursor track from the bundled cursor assets, copies music, exports the mp4.
+- **Set the brand background by eye** when the site is gradient-heavy or
+ light/pastel: `getComputedStyle` lies on those (e.g. a site that looks white
+ with lavender accents can sample as black). Look at the raw frames and pass
+ `--bg-gradient FROM_HEX,TO_HEX` (light sites → a soft light gradient; dark
+ sites → a deep tint of the brand hue).
+- **Match export fps to the real capture rate.** `cap record --detach` can
+ engage late and the window capture stalls timestamps on static pixels, so the
+ true rate is often ~58, not 60. Check it and avoid the 58-vs-60 judder:
+ `ffprobe -v error -select_streams v:0 -show_entries stream=nb_frames,duration -of csv=p=0 <cap>/content/segments/segment-0/display.mp4`,
+ then pass `--quality hd` (60) only if the capture is really ~60, otherwise
+ leave fps at the source rate (omit `--quality`).
+
+### 4. Frame-QA the export, then regrade if needed
+
+Extract 4 beat frames from `<outDir>/<slug>-demo.mp4` and look: each beat
+readable, a typing shot aimed at the **text-entry point** (not the field
+center), no window/desktop bleed, clean fps, music fades feel right. If a shot
+reads too tight or the aim is off, adjust and re-export. The reference 3D poses
+were tuned on full-desktop captures; a browser-window capture fills the card
+more, so distances can read ~30% too tight — back the zoom off if so.
+
+### 5. Deliver
+
+Ship `<outDir>/<slug>-demo.mp4`.
+
+## Hard editorial rules (encode these every time)
+
+- **12s max** total. The tail is shaved evenly if the cut runs long.
+- **A camera cut MUST be a content cut.** Every 3D perspective change lands on a
+ different section/page — the shot boundary sits exactly on the clip cut or the
+ scroll into new content. Never cut the camera mid-idle.
+- **Cut on action, trim dead time.** Cut on the click; resume on the loaded
+ page. Trim page-loads and loading-state frames — never let a blur-up or
+ spinner leak into a shot tail (frame-check the cut points).
+- **Aim at content, not the container.** Shots are aimed at landmarks (hero, the
+ clicked CTA, the destination header), not copied pans. Blur focus rides the
+ aim.
+- **One motion system.** All emphasis lives in the 3D shot (a dolly-in is the
+ click punch). Never stack 2D zoom segments on 3D shots — the two systems fight
+ and read as jarring.
+- **Hands off.** Virtual input only; the user's real cursor/mouse is never
+ moved. The on-screen cursor is synthesized post-hoc from the logged glide path.
+
+## Options reference
+
+Orchestrator (`cap-demo <url> [flags]`):
+
+- `--out DIR` — output directory (default `<tmp>/cap-demo/<slug>`).
+- `--slug NAME` — project slug (default: the URL host, dashed).
+- `--music ID` — music track id (see below). Default: chosen by brand darkness
+ (dark → `lofi-cinematic-pulsebox`, light → `sunday-mood-lofi-cafe-upbeat-bluelike`).
+- `--quality 4k|hd` — `4k` = 3840x2160 / 60fps / maximum / filesize-optimized;
+ `hd` = 60fps / maximum. Omit for the source-rate default.
+- `--story click|scroll` — force the storyboard (default: auto).
+
+`lib/treat.py` extra flags (when running the stages by hand):
+
+- `--bg-gradient FROM_HEX,TO_HEX` — override the brand gradient by eye
+ (e.g. `--bg-gradient E4DCF8,C6BAEA` for a light lavender, or `261A40,0C0914`
+ for a deep purple).
+
+**Bundled music** (a premium/dark/light/moody spread):
+`lofi-cinematic-pulsebox` (moody/premium), `lofi-hip-hop-leberch` (dark),
+`sunday-mood-lofi-cafe-upbeat-bluelike` (light/upbeat), `lofi-smooth-pulsebox`
+(light/smooth). Music resolves only from the skill's bundled
+`assets/music/<id>.mp3`; an unknown id errors.
+
+**Binary resolution** (both scripts): Cap binary = env `CAP_BIN`, else `cap` on
+PATH, else a clear error. Chromium = newest cached
+`~/Library/Caches/ms-playwright/chromium-*` (macOS), else the pinned
+`chromium-1228` build.
+
+## For dev tools / typing showcases (closeup variant)
+
+For dev tools with a live terminal or code on screen, a bespoke storyboard beats
+the generic click-through. Scout for `[class*=terminal]` / `pre` / `code`,
+scroll each to center, dwell ~2.7s (live terminals animate = free motion). The
+**closeup shot recipe**: a gentle tilt (tiltX 10-13, tiltY 9-13, rotateX -4) so
+text stays legible, a tight slow push-in zoom (0.72-0.82), and blur focus locked
+ON the element (focusX = the element's fraction, small focusSize ~0.55). Keep it
+a single continuous clip (no editorial cut) so scrolls stay smooth — cuts are
+3D-only. Aim typing shots at the **text-entry region**, not the field center.
+Rebuild a bespoke shoot from `lib/scout-shoot.mjs` as the base when a site
+deserves it (edit a fresh copy — do not sed/splice shot arrays, overlapping
+offsets corrupt the file).
diff --git a/apps/cli/skill/cap-demo/assets/cursor_0.png b/apps/cli/skill/cap-demo/assets/cursor_0.png
new file mode 100644
index 000000000..379db242e
Binary files /dev/null and b/apps/cli/skill/cap-demo/assets/cursor_0.png differ
diff --git a/apps/cli/skill/cap-demo/assets/cursor_2.png b/apps/cli/skill/cap-demo/assets/cursor_2.png
new file mode 100644
index 000000000..1d9a4a989
Binary files /dev/null and b/apps/cli/skill/cap-demo/assets/cursor_2.png differ
diff --git a/apps/cli/skill/cap-demo/assets/cursors.json b/apps/cli/skill/cap-demo/assets/cursors.json
new file mode 100644
index 000000000..4bcfef47e
--- /dev/null
+++ b/apps/cli/skill/cap-demo/assets/cursors.json
@@ -0,0 +1,12 @@
+{
+ "0": {
+ "imagePath": "content/cursors/cursor_0.png",
+ "hotspot": { "x": 0.17857142857142858, "y": 0.125 },
+ "shape": "MacOS|TahoeArrow"
+ },
+ "2": {
+ "imagePath": "content/cursors/cursor_2.png",
+ "hotspot": { "x": 0.40625, "y": 0.25 },
+ "shape": "MacOS|TahoePointingHand"
+ }
+}
diff --git a/apps/cli/skill/cap-demo/assets/music/lofi-cinematic-pulsebox.mp3 b/apps/cli/skill/cap-demo/assets/music/lofi-cinematic-pulsebox.mp3
new file mode 100644
index 000000000..8a178d61c
Binary files /dev/null and b/apps/cli/skill/cap-demo/assets/music/lofi-cinematic-pulsebox.mp3 differ
diff --git a/apps/cli/skill/cap-demo/assets/music/lofi-hip-hop-leberch.mp3 b/apps/cli/skill/cap-demo/assets/music/lofi-hip-hop-leberch.mp3
new file mode 100644
index 000000000..28baaa633
Binary files /dev/null and b/apps/cli/skill/cap-demo/assets/music/lofi-hip-hop-leberch.mp3 differ
diff --git a/apps/cli/skill/cap-demo/assets/music/lofi-smooth-pulsebox.mp3 b/apps/cli/skill/cap-demo/assets/music/lofi-smooth-pulsebox.mp3
new file mode 100644
index 000000000..0614d1573
Binary files /dev/null and b/apps/cli/skill/cap-demo/assets/music/lofi-smooth-pulsebox.mp3 differ
diff --git a/apps/cli/skill/cap-demo/assets/music/sunday-mood-lofi-cafe-upbeat-bluelike.mp3 b/apps/cli/skill/cap-demo/assets/music/sunday-mood-lofi-cafe-upbeat-bluelike.mp3
new file mode 100644
index 000000000..8cbf35c1d
Binary files /dev/null and b/apps/cli/skill/cap-demo/assets/music/sunday-mood-lofi-cafe-upbeat-bluelike.mp3 differ
diff --git a/apps/cli/skill/cap-demo/cap-demo.mjs b/apps/cli/skill/cap-demo/cap-demo.mjs
new file mode 100644
index 000000000..5f98c066f
--- /dev/null
+++ b/apps/cli/skill/cap-demo/cap-demo.mjs
@@ -0,0 +1,148 @@
+#!/usr/bin/env node
+// cap-demo orchestrator: URL in, cinematic 3D product-demo video out.
+// Chains SCOUT + SHOOT (lib/scout-shoot.mjs) -> TREAT + EXPORT (lib/treat.py).
+//
+// Usage: cap-demo <url> [--out DIR] [--slug NAME] [--music ID] [--quality 4k|hd] [--story click|scroll]
+import { spawn } from "node:child_process";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+import { existsSync, mkdirSync } from "node:fs";
+import os from "node:os";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const LIB = join(__dirname, "lib");
+
+// --- CLI ----------------------------------------------------------------------
+const argv = process.argv.slice(2);
+const opts = { out: null, slug: null, music: null, quality: null, story: null };
+const positionals = [];
+for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ const take = () => argv[++i];
+ if (a === "--out" || a === "-o") opts.out = take();
+ else if (a.startsWith("--out=")) opts.out = a.slice(6);
+ else if (a === "--slug") opts.slug = take();
+ else if (a.startsWith("--slug=")) opts.slug = a.slice(7);
+ else if (a === "--music") opts.music = take();
+ else if (a.startsWith("--music=")) opts.music = a.slice(8);
+ else if (a === "--quality") opts.quality = take();
+ else if (a.startsWith("--quality=")) opts.quality = a.slice(10);
+ else if (a === "--story") opts.story = take();
+ else if (a.startsWith("--story=")) opts.story = a.slice(8);
+ else if (a === "-h" || a === "--help") { usage(); process.exit(0); }
+ else positionals.push(a);
+}
+
+function usage() {
+ console.log(
+ "Usage: cap-demo <url> [--out DIR] [--slug NAME] [--music ID] [--quality 4k|hd] [--story click|scroll]",
+ );
+}
+
+const url = positionals[0];
+if (!url) { usage(); fail("missing <url>"); }
+if (opts.quality && opts.quality !== "4k" && opts.quality !== "hd") fail("--quality must be 4k or hd");
+if (opts.story && opts.story !== "click" && opts.story !== "scroll") fail("--story must be click or scroll");
+
+function fail(msg) {
+ console.error(`cap-demo: ${msg}`);
+ process.exit(1);
+}
+
+function slugFromUrl(u) {
+ let host;
+ try {
+ host = new URL(/^https?:\/\//i.test(u) ? u : `https://${u}`).host;
+ } catch {
+ host = u;
+ }
+ return (
+ host
+ .replace(/^www\./i, "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "") || "demo"
+ );
+}
+
+const slug = opts.slug || slugFromUrl(url);
+const outDir = opts.out || join(os.tmpdir(), "cap-demo", slug);
+mkdirSync(outDir, { recursive: true });
+
+// playwright-core is vendored into the skill; give a clear hint if missing.
+if (!existsSync(join(__dirname, "node_modules", "playwright-core"))) {
+ fail(`playwright-core not installed. Run: (cd "${__dirname}" && npm install)`);
+}
+
+// --- run a child, streaming stdout to the user and optionally capturing it -----
+function run(cmd, cmdArgs, { capture = false } = {}) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(cmd, cmdArgs, { stdio: ["ignore", "pipe", "inherit"] });
+ let buf = "";
+ child.stdout.on("data", (chunk) => {
+ process.stdout.write(chunk);
+ if (capture) buf += chunk.toString();
+ });
+ child.on("error", reject);
+ child.on("close", (code) =>
+ code === 0 ? resolve(buf) : reject(new Error(`${cmd} exited with code ${code}`)),
+ );
+ });
+}
+
+// Parse the scout's final machine-readable JSON line (last line with a `scout` key).
+function parseScoutResult(out) {
+ const lines = out.split("\n").map((l) => l.trim()).filter(Boolean);
+ for (let i = lines.length - 1; i >= 0; i--) {
+ if (!lines[i].startsWith("{")) continue;
+ try {
+ const o = JSON.parse(lines[i]);
+ if (o && o.scout) return o;
+ } catch {}
+ }
+ return null;
+}
+
+// Dark brand -> moody cinematic; light brand -> upbeat lofi.
+function defaultMusic(scoutResult) {
+ const bg = scoutResult?.scout?.pageBg;
+ const light = Array.isArray(bg) && bg.reduce((a, b) => a + b, 0) / bg.length > 150;
+ return light ? "sunday-mood-lofi-cafe-upbeat-bluelike" : "lofi-cinematic-pulsebox";
+}
+
+// --- pipeline -----------------------------------------------------------------
+(async () => {
+ console.log(`cap-demo: ${url} -> ${outDir}`);
+ console.log(`[1/2] scout + shoot (slug=${slug}${opts.story ? `, story=${opts.story}` : ""})`);
+
+ const shootArgs = [join(LIB, "scout-shoot.mjs"), url, outDir, slug];
+ if (opts.story) shootArgs.push("--story", opts.story);
+
+ let scoutOut;
+ try {
+ scoutOut = await run(process.execPath, shootArgs, { capture: true });
+ } catch (e) {
+ fail(`scout/shoot failed: ${e.message}`);
+ }
+
+ const scoutResult = parseScoutResult(scoutOut);
+ const music = opts.music || defaultMusic(scoutResult);
+ const decided = scoutResult
+ ? `story=${scoutResult.story} cta=${scoutResult.scout.ctaText ?? "none"}`
+ : "story=?";
+
+ console.log(`[2/2] treat + export (music=${music}${opts.quality ? `, quality=${opts.quality}` : ""})`);
+ const treatArgs = [join(LIB, "treat.py"), outDir, slug, "--music", music];
+ if (opts.quality) treatArgs.push("--quality", opts.quality);
+
+ try {
+ await run("python3", treatArgs, { capture: false });
+ } catch (e) {
+ fail(`treat/export failed: ${e.message}`);
+ }
+
+ const mp4 = join(outDir, `${slug}-demo.mp4`);
+ console.log("");
+ console.log(`Done: ${mp4}`);
+ console.log(` ${decided}, music=${music}${opts.quality ? `, ${opts.quality}` : ""}`);
+})();
diff --git a/apps/cli/skill/cap-demo/lib/scout-shoot.mjs b/apps/cli/skill/cap-demo/lib/scout-shoot.mjs
new file mode 100644
index 000000000..1e6aa4483
--- /dev/null
+++ b/apps/cli/skill/cap-demo/lib/scout-shoot.mjs
@@ -0,0 +1,350 @@
+// cap-demo SCOUT + SHOOT (adapted from director2.mjs; logic preserved verbatim,
+// only I/O, path/binary resolution, CLI args and a final result line changed).
+//
+// Fully virtual input: CDP mouse/keyboard only (the user's real cursor is never
+// touched); the cursor you see in the final video is synthesized from the logged
+// glide path by treat.py. A near-invisible shimmer dot keeps the window capture
+// emitting frames so the video clock never freezes on static content.
+//
+// Usage: node scout-shoot.mjs <url> <outDir> <slug> [--story click|scroll]
+import { chromium } from "playwright-core";
+import { execFileSync, execSync } from "node:child_process";
+import { writeFileSync, mkdirSync, existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+// --- CLI ----------------------------------------------------------------------
+const argv = process.argv.slice(2);
+const positionals = [];
+let forceStory;
+for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === "--story") {
+ forceStory = argv[++i];
+ } else if (a.startsWith("--story=")) {
+ forceStory = a.slice("--story=".length);
+ } else {
+ positionals.push(a);
+ }
+}
+const [url, outDir, slug] = positionals;
+if (!url || !outDir || !slug) {
+ throw new Error("usage: node scout-shoot.mjs <url> <outDir> <slug> [--story click|scroll]");
+}
+if (forceStory && forceStory !== "click" && forceStory !== "scroll") {
+ throw new Error(`--story must be 'click' or 'scroll' (got '${forceStory}')`);
+}
+mkdirSync(outDir, { recursive: true });
+
+// --- binary resolution --------------------------------------------------------
+// Cap binary: env CAP_BIN, else `cap` on PATH, else a clear error.
+function resolveCap() {
+ if (process.env.CAP_BIN) return process.env.CAP_BIN;
+ try {
+ const p = execSync("command -v cap", { encoding: "utf8" }).trim();
+ if (p) return p;
+ } catch {}
+ throw new Error(
+ "cap CLI not found on PATH. Install Cap Desktop (https://cap.so) or set CAP_BIN.",
+ );
+}
+const CAP = resolveCap();
+
+// Chromium: newest cached ms-playwright chromium-*; fall back to the pinned build.
+function resolveChromium() {
+ const HOME = process.env.HOME;
+ const suffix =
+ "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing";
+ const fallback = `${HOME}/Library/Caches/ms-playwright/chromium-1228/${suffix}`;
+ try {
+ const base = `${HOME}/Library/Caches/ms-playwright`;
+ const dirs = readdirSync(base)
+ .filter((d) => /^chromium-\d+$/.test(d))
+ .map((d) => ({ d, n: parseInt(d.split("-")[1], 10) }))
+ .sort((a, b) => b.n - a.n);
+ for (const { d } of dirs) {
+ const exe = join(base, d, suffix);
+ if (existsSync(exe)) return exe;
+ }
+ } catch {}
+ return fallback;
+}
+const EXE = resolveChromium();
+
+const PROJECT = join(outDir, `${slug}.cap`);
+const TIMELINE = join(outDir, `${slug}.timeline.json`);
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const jitter = (b, s) => b + (Math.random() - 0.5) * s;
+
+// Stale/closing test-chrome windows stay enumerable in `cap record windows` and
+// the first-match can grab the WRONG one. Also close Finder/preview windows so
+// they never composite into the bottom of the window capture.
+try { execSync(`pkill -f "Google Chrome for Testing" || true`); } catch {}
+try { execSync(`osascript -e 'tell application "Finder" to close every window' || true`); } catch {}
+await sleep(800);
+
+const browser = await chromium.launch({
+ executablePath: EXE,
+ headless: false,
+ ignoreDefaultArgs: ["--enable-automation"],
+ args: [
+ "--window-size=1560,1000",
+ "--window-position=120,60",
+ "--disable-blink-features=AutomationControlled",
+ ],
+});
+const page = await browser.newPage({ viewport: null });
+await page.goto(url, { waitUntil: "load", timeout: 60000 });
+await sleep(2600);
+
+// Dismiss cookie / consent banners so they never leak into a shot.
+await page.evaluate(() => {
+ const re = /^(accept|accept all|allow all|agree|i agree|got it|ok|reject all|decline|dismiss|close)$/i;
+ for (const el of document.querySelectorAll("button, a, [role=button]")) {
+ const t = (el.textContent || "").trim();
+ if (re.test(t)) { try { el.click(); } catch {} }
+ }
+}).catch(() => {});
+await sleep(400);
+
+const geo = await page.evaluate(() => ({
+ chromeTop: window.outerHeight - window.innerHeight,
+ iw: window.innerWidth,
+ ih: window.innerHeight,
+}));
+// Window-fraction mapping for aim targets and the synthetic cursor track.
+const toFrac = (b) => ({
+ x: (b.x + b.width / 2) / geo.iw,
+ y: (geo.chromeTop + b.y + b.height / 2) / (geo.ih + geo.chromeTop),
+});
+const pointFrac = (p) => ({
+ x: p.x / geo.iw,
+ y: (geo.chromeTop + p.y) / (geo.ih + geo.chromeTop),
+});
+
+// Shimmer dot: 3px, 2% opacity, orbits 2px in a corner. Invisible to the eye,
+// visible to the encoder. Re-injected after navigations.
+const injectShimmer = () =>
+ page
+ .evaluate(() => {
+ if (document.getElementById("__cap_shimmer")) return;
+ const d = document.createElement("div");
+ d.id = "__cap_shimmer";
+ d.style.cssText =
+ "position:fixed;right:6px;bottom:6px;width:3px;height:3px;background:rgba(127,127,127,0.02);z-index:2147483647;pointer-events:none;";
+ document.documentElement.appendChild(d);
+ let t = 0;
+ const tick = () => {
+ t += 0.25;
+ d.style.transform = `translate(${Math.sin(t) * 2}px, ${Math.cos(t) * 2}px)`;
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ })
+ .catch(() => {});
+await injectShimmer();
+
+// --- Scout --------------------------------------------------------------------
+const scout = await page.evaluate(() => {
+ const vis = (el) => {
+ const r = el.getBoundingClientRect();
+ const s = getComputedStyle(el);
+ return r.width > 8 && r.height > 8 && s.visibility !== "hidden" && s.display !== "none" && r.y < innerHeight * 1.1;
+ };
+ const hero =
+ [...document.querySelectorAll("h1")].find(vis) ?? [...document.querySelectorAll("h2")].find(vis);
+ const heroBox = hero ? hero.getBoundingClientRect() : null;
+ const sameHost = (href) => {
+ try {
+ return new URL(href, location.href).host === location.host;
+ } catch {
+ return false;
+ }
+ };
+ // Content destinations tell the story; conversion CTAs dead-end at forms.
+ const ctaWords =
+ /how it works|features|product|explore|browse|see|watch|demo|learn|courses|membership|events|about|pricing|showcase|gallery|tools|docs/i;
+ const ctaBad = /try|free|sign ?up|register|get started|start now|join|book|download|log ?in|subscribe|get a demo|book a demo|request a demo|contact|talk to/i;
+ const candidates = [...document.querySelectorAll("a, button")]
+ .filter(vis)
+ .map((el) => {
+ const r = el.getBoundingClientRect();
+ const s = getComputedStyle(el);
+ const text = (el.textContent || "").trim();
+ const href = el.tagName === "A" ? el.href : null;
+ const bg = s.backgroundColor;
+ const filled = bg && bg !== "rgba(0, 0, 0, 0)" && bg !== "transparent";
+ let score = 0;
+ if (ctaWords.test(text)) score += 3;
+ if (filled) score += 2;
+ if (r.width > 110) score += 1;
+ if (r.y > 120 && r.y < innerHeight * 0.85) score += 2;
+ if (href && sameHost(href) && !href.includes("#")) score += 2;
+ if (href && new URL(href).pathname === location.pathname) score -= 3;
+ if (/login|log in|sign in/i.test(text)) score -= 4;
+ if (ctaBad.test(text)) score -= 5;
+ if (href && /\/(blog|changelog|careers|jobs|news|press)(\/|$)/i.test(new URL(href).pathname)) score -= 5;
+ if (/↗|↗️|external/i.test(text)) score -= 3;
+ return {
+ text: text.slice(0, 48),
+ href,
+ score,
+ box: { x: r.x, y: r.y, width: r.width, height: r.height },
+ filled,
+ bg,
+ };
+ })
+ .filter((c) => c.text && c.score >= 5)
+ .sort((a, b) => b.score - a.score);
+ const parse = (c) => {
+ const m = c?.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
+ return m ? [+m[1], +m[2], +m[3]] : null;
+ };
+ let pageBg = null;
+ for (const el of [document.body, document.documentElement, ...document.querySelectorAll("main, header, section")]) {
+ const c = parse(getComputedStyle(el).backgroundColor);
+ if (c) {
+ pageBg = c;
+ break;
+ }
+ }
+ const filledCta = candidates.find((c) => c.filled);
+ return {
+ title: document.title,
+ heroBox,
+ candidates: candidates.slice(0, 5),
+ pageBg,
+ accent: filledCta ? parse(filledCta.bg) : null,
+ };
+});
+const cta = scout.candidates[0] ?? null;
+const story = forceStory ?? (cta?.href ? "click" : "scroll");
+console.log(`STORY=${story} cta=${cta?.text ?? "none"} accent=${scout.accent} bg=${scout.pageBg}`);
+
+// --- Virtual cursor -----------------------------------------------------------
+const events = [];
+const cursorLog = { moves: [], clicks: [] };
+let t0 = 0;
+const now = () => (Date.now() - t0) / 1000;
+let vpos = { x: geo.iw * 0.55, y: geo.ih * 0.45 };
+
+const logMove = () => {
+ const f = pointFrac(vpos);
+ cursorLog.moves.push({ t: now(), x: f.x, y: f.y });
+};
+const vmove = async (p) => {
+ vpos = p;
+ await page.mouse.move(p.x, p.y).catch(() => {});
+ logMove();
+};
+async function glide(to, ms) {
+ const from = { ...vpos };
+ const steps = Math.max(8, Math.round(ms / 16));
+ for (let i = 1; i <= steps; i++) {
+ const t = i / steps,
+ e = t * t * (3 - 2 * t);
+ await vmove({ x: from.x + (to.x - from.x) * e, y: from.y + (to.y - from.y) * e });
+ await sleep(ms / steps);
+ }
+}
+const vclick = async () => {
+ cursorLog.clicks.push({ t: now(), down: true });
+ await page.mouse.down().catch(() => {});
+ await sleep(70);
+ await page.mouse.up().catch(() => {});
+ cursorLog.clicks.push({ t: now() - 0.001, down: false });
+};
+const center = (b) => ({ x: b.x + b.width / 2, y: b.y + b.height / 2 });
+
+const pageTitle = await page.title();
+const windows = JSON.parse(execFileSync(CAP, ["record", "windows", "--json"], { encoding: "utf8" }));
+const chromeWins = windows.filter(
+ (w) => /Chrome for Testing/i.test(w.ownerName ?? "") || /Chrome for Testing/i.test(w.name ?? ""),
+);
+let win = chromeWins.find((w) => (w.name ?? "").trim() === pageTitle.trim());
+if (!win && chromeWins.length === 1) win = chromeWins[0];
+if (!win) throw new Error(`window not found (title="${pageTitle}", ${chromeWins.length} chrome windows: ${chromeWins.map((w) => w.name).join(" | ")})`);
+
+execFileSync(CAP, ["record", "start", "--detach", "--window", String(win.id), "--fps", "60", "--path", PROJECT], {
+ encoding: "utf8",
+});
+t0 = Date.now();
+const mark = (n, extra = {}) => {
+ events.push({ name: n, t: now(), ...extra });
+ console.log(`[${now().toFixed(2)}s] ${n}`);
+};
+
+try {
+ logMove();
+ if (scout.heroBox) mark("hero_frac", toFrac(scout.heroBox));
+ await sleep(1300);
+
+ if (story === "click" && cta) {
+ const c = center(cta.box);
+ mark("cta_frac", toFrac(cta.box));
+ mark("drift_to_cta");
+ await glide({ x: c.x + 16, y: c.y + 24 }, 700);
+ await glide(c, 380);
+ await sleep(420);
+ mark("click_cta");
+ await vclick();
+ await page.waitForLoadState("load", { timeout: 25000 }).catch(() => {});
+ await injectShimmer();
+ await sleep(1100);
+ mark("page_ready");
+ const head2 = await page
+ .locator("h1, h2")
+ .first()
+ .boundingBox()
+ .catch(() => null);
+ if (head2 && head2.y < geo.ih) mark("page2_frac", toFrac(head2));
+ await glide({ x: geo.iw * 0.55, y: geo.ih * 0.5 }, 800);
+ await sleep(1100);
+ } else {
+ mark("drift_hero");
+ await glide({ x: geo.iw * 0.5, y: geo.ih * 0.45 }, 900);
+ await sleep(500);
+ mark("scroll1_start");
+ await page.evaluate((d) => window.scrollBy({ top: d, behavior: "smooth" }), Math.round(geo.ih * 0.95));
+ await glide({ x: vpos.x + 90, y: vpos.y + 120 }, 900);
+ await sleep(800);
+ mark("scroll1_settled");
+ await sleep(1500);
+ }
+
+ mark("scroll_start");
+ await page.evaluate(() => window.scrollBy({ top: 700, behavior: "smooth" }));
+ await glide({ x: vpos.x + 110, y: vpos.y + 130 }, 900);
+ await sleep(800);
+ mark("scroll_settled");
+ // Gentle idle drift for the settle; shimmer keeps the clock honest anyway.
+ const until = Date.now() + 2300;
+ while (Date.now() < until) {
+ await vmove({ x: vpos.x + jitter(0, 2.4), y: vpos.y + jitter(0, 2.4) });
+ await sleep(150);
+ }
+ mark("end");
+} finally {
+ execFileSync(CAP, ["record", "stop"], { encoding: "utf8" });
+ writeFileSync(
+ TIMELINE,
+ JSON.stringify({ story, scout: { ...scout, candidates: undefined }, events, cursorLog }, null, 1),
+ );
+ await browser.close();
+}
+
+// Final machine-readable line: what the scout decided (orchestrator/agent reads this).
+console.log(
+ JSON.stringify({
+ slug,
+ story,
+ scout: {
+ title: scout.title,
+ hero: scout.heroBox,
+ accent: scout.accent,
+ pageBg: scout.pageBg,
+ ctaText: cta?.text ?? null,
+ },
+ }),
+);
+console.log("DONE");
diff --git a/apps/cli/skill/cap-demo/lib/treat.py b/apps/cli/skill/cap-demo/lib/treat.py
new file mode 100644
index 000000000..6b6ecbc0d
--- /dev/null
+++ b/apps/cli/skill/cap-demo/lib/treat.py
@@ -0,0 +1,333 @@
+#!/usr/bin/env python3
+"""cap-demo TREAT + EXPORT (adapted from treat.py; all shot math, brand-gradient
+and editorial logic preserved verbatim, only I/O, binary/asset/music resolution
+and CLI args changed).
+
+Aligns beats to video, trims, aims 3D shots at landmarks, paints a brand
+background, synthesizes the cursor track from the bundled cursor assets, copies
+music, writes project-config.json, and exports via the Cap CLI.
+
+Usage: python3 treat.py <outDir> <slug> [--music ID] [--quality 4k|hd] [--bg-gradient FROM_HEX,TO_HEX]
+"""
+import argparse
+import colorsys
+import json
+import math
+import os
+import shutil
+import subprocess
+import sys
+
+SKILL_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ASSETS = os.path.join(SKILL_DIR, "assets")
+
+
+def resolve_cap():
+ """Cap binary: env CAP_BIN, else `cap` on PATH, else a clear error."""
+ if os.environ.get("CAP_BIN"):
+ return os.environ["CAP_BIN"]
+ p = shutil.which("cap")
+ if p:
+ return p
+ raise SystemExit(
+ "cap CLI not found on PATH. Install Cap Desktop (https://cap.so) or set CAP_BIN."
+ )
+
+
+def resolve_music(music_id):
+ bundled = os.path.join(ASSETS, "music", f"{music_id}.mp3")
+ if os.path.exists(bundled):
+ return bundled
+ raise SystemExit(
+ f"music not found: {music_id} (looked in {os.path.join(ASSETS, 'music')})"
+ )
+
+
+def parse_bg_override(spec):
+ parts = [p.strip() for p in spec.split(",")]
+ if len(parts) != 2:
+ raise SystemExit("--bg-gradient must be FROM_HEX,TO_HEX (e.g. 261A40,0C0914)")
+
+ def hexrgb(h):
+ h = h.lstrip("#")
+ if len(h) != 6:
+ raise SystemExit(f"invalid hex color: {h}")
+ return [int(h[i:i + 2], 16) for i in (0, 2, 4)]
+
+ return {"type": "gradient", "from": hexrgb(parts[0]), "to": hexrgb(parts[1]), "angle": 135}
+
+
+ap = argparse.ArgumentParser()
+ap.add_argument("outDir")
+ap.add_argument("slug")
+ap.add_argument("--music", default="lofi-cinematic-pulsebox")
+ap.add_argument("--quality", choices=["4k", "hd"], default=None)
+ap.add_argument("--bg-gradient", dest="bg_gradient", default=None)
+args = ap.parse_args()
+
+outDir = args.outDir
+slug = args.slug
+music = args.music
+CAP = resolve_cap()
+
+proj = os.path.join(outDir, f"{slug}.cap")
+
+with open(os.path.join(outDir, f"{slug}.timeline.json")) as f:
+ tl = json.load(f)
+events = {e["name"]: e for e in tl["events"]}
+story = tl["story"]
+scout = tl["scout"]
+
+video = f"{proj}/content/segments/segment-0/display.mp4"
+probe = subprocess.run(
+ ["ffprobe", "-v", "quiet", "-show_entries", "format=duration", "-of", "csv=p=0", video],
+ capture_output=True, text=True).stdout.strip()
+vdur = float(probe)
+dims = subprocess.run(
+ ["ffprobe", "-v", "quiet", "-show_entries", "stream=width,height", "-of", "csv=p=0", video],
+ capture_output=True, text=True).stdout.strip()
+W, H = [int(x) for x in dims.split(",")[:2]]
+aspect = W / H
+hx, hy = (1.0, 1.0 / aspect) if aspect >= 1 else (aspect, 1.0)
+
+# Tail-anchored alignment: micro-drift keeps frames flowing to the end.
+offset = events["end"]["t"] - vdur
+def v(name):
+ return max(0.0, events[name]["t"] - offset)
+
+# --- camera math ---------------------------------------------------------------
+def rot(axis, deg):
+ t = math.radians(deg); c, s = math.cos(t), math.sin(t)
+ if axis == "x": return [[1, 0, 0], [0, c, -s], [0, s, c]]
+ if axis == "y": return [[c, 0, s], [0, 1, 0], [-s, 0, c]]
+ return [[c, -s, 0], [s, c, 0], [0, 0, 1]]
+
+def mul(a, b):
+ return [[sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)] for i in range(3)]
+
+def aim_pan(p, frac):
+ R = mul(mul(rot("y", p["tiltY"]), mul(rot("x", p["tiltX"]), rot("z", p["roll"]))),
+ mul(rot("y", p["rotateY"]), rot("x", p["rotateX"])))
+ u = 0.5 + (frac[0] - 0.5) * 0.9
+ vv = 0.5 + (frac[1] - 0.5) * 0.9
+ X, Y = (2 * u - 1) * hx, (1 - 2 * vv) * hy
+ return (-(R[0][0] * X + R[0][1] * Y), -(R[1][0] * X + R[1][1] * Y))
+
+def props(**kw):
+ base = {"tiltX": 0.0, "tiltY": 0.0, "roll": 0.0, "rotateX": 0.0, "rotateY": 0.0,
+ "fov": 45.0, "zoom": 2.0, "panX": 0.0, "panY": 0.0}
+ base.update(kw); return base
+
+def kf(t, val, first):
+ k = {"time": t, "value": val}
+ k["outEasing" if first else "inEasing"] = [0.0, 0.0] if first else [1.0, 1.0]
+ return k
+
+def tracks_between(p0, p1, length):
+ return {key: [kf(0.0, p0[key], True), kf(length, p1[key], False)]
+ for key in p0 if abs(p0[key] - p1[key]) > 1e-6}
+
+def blur(st, fo, sz):
+ return {"mode": "radial", "strength": st, "falloff": fo, "focusX": 0.5, "focusY": 0.46,
+ "focusSize": sz, "angle": 0.0, "dirPosition": 0.5, "bokeh": True}
+
+def shot(a, b, p0, p1, bl):
+ return {"start": a, "end": b, "enabled": True, "properties": p0, "blur": bl,
+ "tracks": tracks_between(p0, p1, b - a), "transitionIn": 0.0, "transitionOut": 0.0}
+
+def frac_of(name, default):
+ e = events.get(name)
+ return (e["x"], e["y"]) if e and "x" in e else default
+
+# --- brand background ----------------------------------------------------------
+def brand_gradient():
+ accent = scout.get("accent")
+ bg = scout.get("pageBg")
+ def tune(rgb, lo, hi, sat_cap=0.75):
+ r, g, b = [c / 255 for c in rgb]
+ h, l, s = colorsys.rgb_to_hls(r, g, b)
+ l = min(max(l, lo), hi)
+ s = min(s, sat_cap)
+ r, g, b = colorsys.hls_to_rgb(h, l, s)
+ return [int(r * 255), int(g * 255), int(b * 255)]
+ if accent and bg:
+ return {"type": "gradient", "from": tune(accent, 0.18, 0.42), "to": tune(bg, 0.10, 0.30), "angle": 135}
+ if accent:
+ base = tune(accent, 0.18, 0.42)
+ return {"type": "gradient", "from": base, "to": tune(accent, 0.08, 0.2), "angle": 135}
+ if bg and (sum(bg) / 3) > 150: # light brand -> soft light gradient
+ return {"type": "gradient", "from": tune(bg, 0.86, 0.94, 0.25), "to": tune(bg, 0.72, 0.82, 0.35), "angle": 135}
+ return {"type": "gradient", "from": [38, 40, 58], "to": [16, 17, 26], "angle": 135}
+
+bg_source = parse_bg_override(args.bg_gradient) if args.bg_gradient else brand_gradient()
+
+# --- editorial cut -------------------------------------------------------------
+HERO = frac_of("hero_frac", (0.5, 0.4))
+
+if story == "click":
+ CTA = frac_of("cta_frac", (0.5, 0.6))
+ PAGE2 = frac_of("page2_frac", (0.42, 0.45))
+ click = v("click_cta")
+ ready = v("page_ready")
+ scroll = v("scroll_start")
+ cutA = (0.25, min(click + 0.4, ready - 0.1))
+ cutB = (ready + 0.5, vdur - 0.05)
+else:
+ CTA = HERO
+ PAGE2 = (0.5, 0.45)
+ s1 = v("scroll1_start")
+ scroll = v("scroll_start")
+ cutA = (0.25, s1 + 0.9) # hero through the first scroll's start
+ cutB = (s1 + 1.1, vdur - 0.05) # arrive in section 2 mid-scroll
+
+clip_cut = cutA[1] - cutA[0]
+DUR = clip_cut + (cutB[1] - cutB[0])
+# 12s cap: shave the tail evenly if long.
+if DUR > 12.0:
+ trim = DUR - 12.0
+ cutB = (cutB[0], cutB[1] - trim)
+ DUR = 12.0
+
+scroll_out = clip_cut + (scroll - cutB[0])
+b2 = min(max(scroll_out + 0.45, clip_cut + 1.2), DUR - 2.2)
+
+s1a = props(tiltX=26.0, tiltY=-22.0, roll=1.0, zoom=1.05)
+s1a["panX"], s1a["panY"] = aim_pan(s1a, HERO)
+s1b = props(tiltX=26.0, tiltY=-26.0, roll=1.0, zoom=0.86)
+s1b["panX"], s1b["panY"] = aim_pan(s1b, CTA)
+s2a = props(tiltX=24.8, tiltY=17.04, rotateX=-40.0, rotateY=18.0, fov=60.0, zoom=0.8)
+s2a["panX"], s2a["panY"] = aim_pan(s2a, PAGE2)
+s2b = props(tiltX=34.19, tiltY=15.28, rotateX=-40.0, rotateY=9.0, fov=60.0, zoom=0.74)
+s2b["panX"], s2b["panY"] = aim_pan(s2b, PAGE2)
+s3a = props(rotateX=-14.0, zoom=0.95)
+s3a["panX"], s3a["panY"] = aim_pan(s3a, (0.5, 0.45))
+s3b = props(rotateX=-14.0, zoom=1.6)
+
+
+# --- synthetic cursor track ----------------------------------------------------
+# The shoot used CDP input only; the on-screen cursor in the final render is
+# drawn from this data. Overwrites any stray real-cursor data Cap recorded.
+# Cursor assets are bundled with the skill (assets/cursor_0.png, cursor_2.png,
+# assets/cursors.json).
+if "cursorLog" in tl:
+ with open(os.path.join(ASSETS, "cursors.json")) as f:
+ cursors_meta = json.load(f)
+ with open(f"{proj}/recording-meta.json") as f:
+ meta = json.load(f)
+ start_time = meta["segments"][0].get("display", {}).get("start_time", 0.0) or 0.0
+
+ os.makedirs(f"{proj}/content/cursors", exist_ok=True)
+ for cid in ("0", "2"):
+ src = os.path.join(ASSETS, f"cursor_{cid}.png")
+ shutil.copy(src, f"{proj}/content/cursors/cursor_{cid}.png")
+ meta["cursors"] = {cid: cursors_meta[cid] for cid in ("0", "2")}
+ meta["segments"][0]["cursor"] = "content/segments/segment-0/cursor.json"
+ with open(f"{proj}/recording-meta.json", "w") as f:
+ json.dump(meta, f, indent=2)
+
+ def ms(t):
+ return max(0.0, (t - offset + start_time)) * 1000.0
+
+ moves = [
+ {"active_modifiers": [], "cursor_id": "0", "time_ms": ms(m["t"]), "x": m["x"], "y": m["y"]}
+ for m in tl["cursorLog"]["moves"]
+ ]
+ clicks = [
+ {"active_modifiers": [], "cursor_num": 1, "cursor_id": "0", "time_ms": ms(c["t"]), "down": c["down"]}
+ for c in tl["cursorLog"]["clicks"]
+ ]
+ with open(f"{proj}/content/segments/segment-0/cursor.json", "w") as f:
+ json.dump({"moves": moves, "clicks": clicks}, f)
+ print(f"cursor track synthesized: {len(moves)} moves, {len(clicks)} clicks")
+
+os.makedirs(f"{proj}/assets/audio", exist_ok=True)
+music_src = resolve_music(music)
+dest = f"{proj}/assets/audio/library-{music}.mp3"
+shutil.copy(music_src, dest)
+mdur = float(subprocess.run(
+ ["ffprobe", "-v", "quiet", "-show_entries", "format=duration", "-of", "csv=p=0", dest],
+ capture_output=True, text=True).stdout.strip())
+
+config = {
+ "aspectRatio": None,
+ "background": {
+ "source": bg_source,
+ "blur": 0.0, "padding": 10.0, "rounding": 7.5, "roundingType": "squircle", "inset": 0,
+ "crop": None, "displayPosition": None, "shadow": 73.6,
+ "advancedShadow": {"size": 14.4, "opacity": 68.1, "blur": 3.8}, "border": None, "frame": None,
+ },
+ "timeline": {
+ "segments": [
+ {"recordingSegment": 0, "timescale": 1.0, "start": cutA[0], "end": cutA[1], "name": None},
+ {"recordingSegment": 0, "timescale": 1.0, "start": cutB[0], "end": cutB[1], "name": None},
+ ],
+ "zoomSegments": [],
+ "camera3dSegments": [
+ shot(0.0, clip_cut, s1a, s1b, blur(20.0, 0.7, 0.32)),
+ shot(clip_cut, b2, s2a, s2b, blur(18.0, 0.72, 0.5)),
+ shot(b2, DUR, s3a, s3b, blur(19.0, 0.67, 0.42)),
+ ],
+ "audioSegments": [{
+ "start": 0.0, "end": DUR, "track": 0,
+ "path": f"assets/audio/library-{music}.mp3",
+ "name": music, "enabled": True, "trimStart": 0.0,
+ "volumeDb": 0.0, "fadeIn": 0.5, "fadeOut": 1.5, "duration": mdur,
+ }],
+ },
+}
+with open(f"{proj}/project-config.json", "w") as f:
+ json.dump(config, f, indent=1)
+print(f"{slug}: story={story} dur={DUR:.2f} cut={clip_cut:.2f} b2={b2:.2f} offset={offset:.2f} grad={config['background']['source']}")
+
+out_mp4 = os.path.join(outDir, f"{slug}-demo.mp4")
+
+
+def source_fps(path):
+ """Dominant capture rate (mode of instantaneous fps). Window capture is VFR:
+ a few long stall gaps (page nav, heavy animation) drag the mean down, so the
+ mean is the wrong number to export at. The mode is the real rate the smooth
+ sections were captured at; matching it avoids resample judder."""
+ try:
+ import re as _re
+ from collections import Counter
+ pts = subprocess.run(
+ ["ffprobe", "-v", "quiet", "-select_streams", "v",
+ "-show_entries", "frame=pts_time", "-of", "csv=p=0", path],
+ capture_output=True, text=True).stdout.replace(",", " ").split()
+ times = [float(x) for x in pts if x.strip()]
+ rates = Counter()
+ for a, b in zip(times, times[1:]):
+ d = b - a
+ if d > 1e-6:
+ rates[round(1.0 / d)] += 1
+ if rates:
+ return max(2, min(60, rates.most_common(1)[0][0]))
+ except Exception:
+ pass
+ try:
+ import re as _re
+ meta = subprocess.run(
+ ["ffprobe", "-v", "quiet", "-count_frames", "-select_streams", "v",
+ "-show_entries", "stream=nb_read_frames", "-show_entries", "format=duration",
+ "-of", "csv=p=0", path], capture_output=True, text=True).stdout
+ nums = [x for x in _re.split(r"[,\n]", meta) if x.strip()]
+ return max(2, min(60, round(int(nums[0]) / float(nums[1]))))
+ except Exception:
+ return 60
+
+
+fps = str(source_fps(video))
+cmd = [CAP, "export", proj, "-o", out_mp4, "--fps", fps]
+if args.quality == "4k":
+ cmd += ["--resolution", "3840x2160", "--quality", "maximum", "--optimize-filesize"]
+elif args.quality == "hd":
+ cmd += ["--quality", "maximum"]
+else:
+ cmd += ["--quality", "maximum", "--optimize-filesize"]
+res = subprocess.run(cmd, capture_output=True, text=True)
+if res.returncode != 0:
+ sys.stderr.write(res.stdout or "")
+ sys.stderr.write(res.stderr or "")
+ raise SystemExit(f"cap export failed (exit {res.returncode})")
+print(f"exported {slug}-demo.mp4")
+print(out_mp4)
diff --git a/apps/cli/skill/cap-demo/package-lock.json b/apps/cli/skill/cap-demo/package-lock.json
new file mode 100644
index 000000000..d7c425d89
--- /dev/null
+++ b/apps/cli/skill/cap-demo/package-lock.json
@@ -0,0 +1,30 @@
+{
+ "name": "cap-demo",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "cap-demo",
+ "version": "1.0.0",
+ "dependencies": {
+ "playwright-core": "^1.62.1"
+ },
+ "bin": {
+ "cap-demo": "cap-demo.mjs"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.62.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz",
+ "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==",
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ }
+ }
+}
diff --git a/apps/cli/skill/cap-demo/package.json b/apps/cli/skill/cap-demo/package.json
new file mode 100644
index 000000000..b581adbad
--- /dev/null
+++ b/apps/cli/skill/cap-demo/package.json
@@ -0,0 +1,10 @@
+{
+ "name": "cap-demo",
+ "version": "1.0.0",
+ "type": "module",
+ "description": "Generate a cinematic 3D product-demo video from any URL with Cap.",
+ "bin": { "cap-demo": "./cap-demo.mjs" },
+ "dependencies": {
+ "playwright-core": "^1.62.1"
+ }
+}