Skip to content

akunzai/agent-skills / skills/record-walkthrough

record-walkthrough

Flagged

Record a website walkthrough video with auto-zoom on clicks. Use when the user asks for a walkthrough, when a PR, MR, or issue needs a recording of a web flow, or on /record-walkthrough.

FileKindSize
SKILL.mdskill md7.6 KB
references/auth.mdmarkdown8.4 KB
references/effects.mdmarkdown9.1 KB
scripts/record.mjsexecutablescript65.7 KB
scripts/render-auto-zoom.mjsexecutablescript11.4 KB
scripts/suggest-zooms.mjsexecutablescript8.4 KB
skill.oms.sigother13.0 KB

scripts/render-auto-zoom.mjs

View on GitHub
#!/usr/bin/env node
import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { parseSamples, suggestZooms, ZOOM_IN_MS, ZOOM_OUT_MS, ZOOM_SCALE } from "./suggest-zooms.mjs";

export { ZOOM_IN_MS, ZOOM_OUT_MS };

function printUsage(stream) {
  stream.write(`Usage: render-auto-zoom.mjs --video FILE --out FILE [--zooms FILE | --clicks FILE]

Apply auto-zoom regions to a recorded viewport video. Needs ffmpeg on PATH.
Pass --zooms from suggest-zooms.mjs, or --clicks plus optional --duration-ms.
`);
}

function parseArgs(argv) {
  const args = {
    video: null,
    out: null,
    zooms: null,
    clicks: null,
    durationMs: null,
  };
  for (let i = 0; i < argv.length; i += 1) {
    const arg = argv[i];
    if (arg === "--help" || arg === "-h") {
      args.help = true;
    } else if (arg === "--video" || arg === "--out" || arg === "--zooms" || arg === "--clicks") {
      args[arg.slice(2)] = argv[i + 1];
      i += 1;
    } else if (arg === "--duration-ms" || arg === "--trim-start-ms") {
      args[arg === "--duration-ms" ? "durationMs" : "trimStartMs"] = Number(argv[i + 1]);
      i += 1;
    } else {
      throw new Error(`unknown option: ${arg}`);
    }
  }
  return args;
}

function run(command, argv, options = {}) {
  return new Promise((resolve, reject) => {
    const child = spawn(command, argv, {
      stdio: ["ignore", options.stdout ?? "pipe", options.stderr ?? "pipe"],
    });
    let stdout = "";
    let stderr = "";
    if (child.stdout) {
      child.stdout.on("data", (chunk) => {
        stdout += chunk;
      });
    }
    if (child.stderr) {
      child.stderr.on("data", (chunk) => {
        stderr += chunk;
      });
    }
    child.on("error", reject);
    child.on("close", (code) => {
      if (code === 0) {
        resolve({ stdout, stderr });
        return;
      }
      const error = new Error(`${command} exited ${code}${stderr ? `: ${stderr.trim()}` : ""}`);
      error.stdout = stdout;
      error.stderr = stderr;
      reject(error);
    });
  });
}

function parseFrameRate(rate) {
  if (!rate || typeof rate !== "string") {
    return 30;
  }
  if (rate.includes("/")) {
    const [num, den] = rate.split("/").map(Number);
    if (Number.isFinite(num) && Number.isFinite(den) && den !== 0) {
      return num / den;
    }
  }
  const value = Number(rate);
  return Number.isFinite(value) && value > 0 ? value : 30;
}

export async function probeVideo(videoPath) {
  const { stdout } = await run("ffprobe", [
    "-v",
    "error",
    "-print_format",
    "json",
    "-show_format",
    "-show_streams",
    videoPath,
  ]);
  const info = JSON.parse(stdout);
  const video = (info.streams ?? []).find((stream) => stream.codec_type === "video");
  if (!video) {
    throw new Error(`no video stream in ${videoPath}`);
  }
  const duration = Number(info.format?.duration ?? video.duration);
  const fps = parseFrameRate(video.avg_frame_rate) || parseFrameRate(video.r_frame_rate);
  return {
    durationMs: Math.round(duration * 1000),
    width: Number(video.width),
    height: Number(video.height),
    fps,
  };
}

function even(value) {
  const rounded = Math.round(value);
  return rounded % 2 === 0 ? rounded : rounded + 1;
}

function loadZooms(args, durationMs) {
  if (args.zooms) {
    const parsed = JSON.parse(fs.readFileSync(path.resolve(args.zooms), "utf8"));
    if (Array.isArray(parsed)) {
      return { status: parsed.length ? "ok" : "no-interactions", suggestions: parsed };
    }
    return parsed;
  }
  if (args.clicks) {
    const samples = parseSamples(fs.readFileSync(path.resolve(args.clicks), "utf8"));
    return suggestZooms(samples, durationMs);
  }
  throw new Error("need --zooms or --clicks");
}

function buildSegments(suggestions, durationMs) {
  const segments = [];
  let cursor = 0;
  for (const region of suggestions) {
    const start = clampTime(region.start, durationMs);
    const end = clampTime(region.end, durationMs);
    if (end <= start) {
      continue;
    }
    if (start > cursor) {
      segments.push({ kind: "plain", start: cursor, end: start });
    }
    const focus = {
      t: start,
      cx: Number(region.focus?.cx ?? 0.5),
      cy: Number(region.focus?.cy ?? 0.5),
    };
    // A zooms file written before keyframes existed has only focus.
    const keyframes = Array.isArray(region.keyframes) && region.keyframes.length > 0
      ? region.keyframes.map((frame) => ({
          t: Number(frame.t),
          cx: Number(frame.cx ?? focus.cx),
          cy: Number(frame.cy ?? focus.cy),
        }))
      : [focus];
    segments.push({
      kind: "zoom",
      start,
      end,
      keyframes,
      scale: Number(region.scale ?? ZOOM_SCALE),
    });
    cursor = end;
  }
  if (cursor < durationMs) {
    segments.push({ kind: "plain", start: cursor, end: durationMs });
  }
  return segments.filter((segment) => segment.end - segment.start >= 1);
}

function clampTime(value, durationMs) {
  if (!Number.isFinite(value)) {
    return 0;
  }
  return Math.min(durationMs, Math.max(0, value));
}

function sec(ms) {
  return (ms / 1000).toFixed(3);
}

// Focus along one axis as a function of the output frame: it holds at each
// keyframe and eases to the next one over the ZOOM_IN_MS before that click.
function focusExpr(segment, axis, fps) {
  const frames = segment.keyframes;
  const toFrame = (ms) => Math.round(((ms - segment.start) / 1000) * fps);
  let expr = frames[frames.length - 1][axis].toFixed(4);
  for (let i = frames.length - 1; i >= 1; i -= 1) {
    const from = frames[i - 1][axis].toFixed(4);
    const to = frames[i][axis].toFixed(4);
    const panEnd = Math.max(1, toFrame(frames[i].t));
    const panStart = Math.min(panEnd - 1, Math.max(0, toFrame(Math.max(frames[i].t - ZOOM_IN_MS, frames[i - 1].t))));
    const span = panEnd - panStart;
    expr =
      `if(lt(on,${panStart}),${from},` +
      `if(lt(on,${panEnd}),${from}+(${to}-${from})*(0.5-0.5*cos(PI*(on-${panStart})/${span})),` +
      `${expr}))`;
  }
  return expr;
}

function zoomFilter(segment, width, height, fps) {
  const durationMs = segment.end - segment.start;
  // A hand-written region shorter than a full zoom in and out shrinks both.
  const shrink = Math.min(1, durationMs / (ZOOM_IN_MS + ZOOM_OUT_MS));
  const inMs = Math.max(1, ZOOM_IN_MS * shrink);
  const outMs = Math.max(1, ZOOM_OUT_MS * shrink);
  const inFrames = Math.max(1, Math.round((inMs / 1000) * fps));
  const outFrames = Math.max(1, Math.round((outMs / 1000) * fps));
  const totalFrames = Math.max(inFrames + outFrames, Math.round((durationMs / 1000) * fps));
  const holdUntil = Math.max(inFrames, totalFrames - outFrames);
  const scale = segment.scale;
  const delta = (scale - 1).toFixed(4);
  const cx = focusExpr(segment, "cx", fps);
  const cy = focusExpr(segment, "cy", fps);
  const z =
    `if(lt(on,${inFrames}),` +
    `1+${delta}*(0.5-0.5*cos(PI*on/${inFrames})),` +
    `if(lt(on,${holdUntil}),${scale},` +
    `1+${delta}*(0.5-0.5*cos(PI*(${totalFrames}-on)/${outFrames}))))`;
  const x = `max(0,min(iw-iw/zoom,(${cx})*iw-iw/zoom/2))`;
  const y = `max(0,min(ih-ih/zoom,(${cy})*ih-ih/zoom/2))`;
  return (
    `trim=${sec(segment.start)}:${sec(segment.end)},setpts=PTS-STARTPTS,` +
    `setsar=1,format=yuv420p,` +
    `zoompan=z='${z}':x='${x}':y='${y}':d=1:s=${width}x${height}:fps=${fps}`
  );
}

function plainFilter(segment) {
  return `trim=${sec(segment.start)}:${sec(segment.end)},setpts=PTS-STARTPTS,setsar=1,format=yuv420p`;
}

export function buildFilterComplex(suggestions, probe) {
  const width = even(probe.width);
  const height = even(probe.height);
  const fps = Math.round(probe.fps * 1000) / 1000;
  const segments = buildSegments(suggestions, probe.durationMs);
  if (segments.length === 0) {
    return {
      filter: `setsar=1,format=yuv420p,scale=${width}:${height}:flags=lanczos`,
      map: "0:v",
      segments,
    };
  }
  if (segments.length === 1 && segments[0].kind === "plain") {
    return {
      filter: `[0:v]${plainFilter(segments[0])},scale=${width}:${height}:flags=lanczos[out]`,
      map: "[out]",
      segments,
    };
  }

  const parts = [];
  const labels = [];
  segments.forEach((segment, index) => {
    const label = `v${index}`;
    const body = segment.kind === "zoom" ? zoomFilter(segment, width, height, fps) : plainFilter(segment);
    parts.push(`[0:v]${body}[${label}]`);
    labels.push(`[${label}]`);
  });
  parts.push(`${labels.join("")}concat=n=${segments.length}:v=1:a=0[out]`);
  return { filter: parts.join(";"), map: "[out]", segments };
}

// Re-encode without zooming. The caller wants the container, not the effect.
export function transcode(options) {
  return renderAutoZoom({ ...options, suggestions: [] });
}

export async function renderAutoZoom(options) {
  const videoPath = path.resolve(options.video);
  const outPath = path.resolve(options.out);
  fs.mkdirSync(path.dirname(outPath), { recursive: true });

  const probe = await probeVideo(videoPath);
  const trimStartMs = Math.max(0, Number(options.trimStartMs) || 0);
  const durationMs = Math.max(1, (options.durationMs ?? probe.durationMs) - trimStartMs);
  const zoomDoc = options.suggestions
    ? { status: "ok", suggestions: options.suggestions }
    : loadZooms(options, durationMs);
  const suggestions = zoomDoc.suggestions ?? [];
  const { filter, map } = buildFilterComplex(suggestions, { ...probe, durationMs });

  const ffmpegArgs = ["-y"];
  if (trimStartMs > 0) {
    ffmpegArgs.push("-ss", (trimStartMs / 1000).toFixed(3));
  }
  const webm = outPath.toLowerCase().endsWith(".webm");
  ffmpegArgs.push("-i", videoPath, "-filter_complex", filter, "-map", map, "-an");
  if (webm) {
    // Constant quality, not a fixed bitrate: mostly static screen frames need little.
    ffmpegArgs.push(
      "-c:v",
      "libvpx-vp9",
      "-crf",
      "32",
      "-b:v",
      "0",
      "-pix_fmt",
      "yuv420p",
      "-deadline",
      "good",
      "-cpu-used",
      "4",
      "-row-mt",
      "1",
    );
  } else {
    ffmpegArgs.push(
      "-c:v",
      "libx264",
      "-pix_fmt",
      "yuv420p",
      "-preset",
      "veryfast",
      "-crf",
      "20",
      "-movflags",
      "+faststart",
    );
  }
  ffmpegArgs.push(outPath);
  await run("ffmpeg", ffmpegArgs);

  return { outPath, probe, suggestions, status: zoomDoc.status ?? "ok" };
}

export async function main(argv = process.argv.slice(2), io = process) {
  let args;
  try {
    args = parseArgs(argv);
  } catch (error) {
    printUsage(io.stderr);
    io.stderr.write(`${error.message}\n`);
    return 2;
  }

  if (args.help) {
    printUsage(io.stdout);
    return 0;
  }

  if (!args.video || !args.out || (!args.zooms && !args.clicks)) {
    printUsage(io.stderr);
    return 2;
  }

  try {
    const result = await renderAutoZoom(args);
    io.stdout.write(
      `${JSON.stringify({ out: result.outPath, status: result.status, zooms: result.suggestions.length }, null, 2)}\n`,
    );
    return 0;
  } catch (error) {
    io.stderr.write(`${error.message}\n`);
    return 1;
  }
}

// Skills are installed as symlinks, so argv[1] is the link while import.meta.url
// is always the real path. Comparing them unresolved makes main() never run, and
// the command exits 0 having done nothing.
function isMainModule(arg) {
  if (!arg) {
    return false;
  }
  try {
    return import.meta.url === pathToFileURL(fs.realpathSync(path.resolve(arg))).href;
  } catch {
    return false;
  }
}

if (isMainModule(process.argv[1])) {
  main().then((code) => {
    process.exit(code);
  });
}
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall