# YouTube
<!--
ref: @integrations/youtube
tags: [YouTube, transcripts, yt-dlp]
aliases: [youtube, yt, transcript, yt-transcript]
triggers: [youtube url, youtube link, youtu.be, pull the transcript, get the transcript, what does this video say, list channel videos]
trigger_prompt: You are handed a YouTube link or id, or need what a video says. Run the block below.
category: integration
last_reviewed: 2026-09-28
complements: [@integrations/youtube-reference, @integrations/agent-browser]
audience: [agent-author, terminal-only]
version: 14
updated_at: 2026-11-24T04:03:40.246Z
appendixes: [@integrations/youtube_/reference]
-->

YouTube link → transcript file. Operational: run it. Why, failures, delegation, editing the script: `@integrations/youtube-reference`.

## Run

```bash
P="${TMPDIR:-/tmp}/yt-transcript.ts"
curly protocol "@integrations/youtube?section=script" | sed '1,/^```ts$/d;/^```$/,$d' > "$P"
bun "$P" "<url-or-id>" --dir <dest> [--corpus <dedupe-root>]
```

Stdout is one line: the transcript path — the existing copy if `--corpus` already holds the video id, else a new `YYYY-MM-DD-<slug>.md` in `--dir` with a `# Title / # Source / # URL / # Date` header.

**Trap — the corpus match is any file that mentions the id.** A staging note or queue that cites the video id (say `memory/knowledge/_staging/...`) makes it print "already in corpus" and return that note, not a transcript. If the printed path is not under a transcripts dir, rerun with `--corpus ~/workspace/memory/transcripts`. (Hit 2026-11-15, knowledge-seeking.)

**Reading it is cheap-model work.** Summarize or scrape the transcript in a Haiku subagent (Sonnet when the summary needs judgment) that writes the summary to a file; the conductor reads the summary, never the raw transcript. Rule: `@protocol/model-selection-anthropic` §Spending a big model well.

| Exit | Do |
|---|---|
| 0 | Read the printed path |
| 2 | Test-Chrome is down and a cookie is needed: run the `@integrations/agent-browser` bootstrap, rerun |
| 1 | No captions on any rung → `@integrations/youtube_/reference` §When it fails |

Needs `bun` and `yt-dlp`.

## List a channel or playlist

```bash
yt-dlp --flat-playlist -J "<channel-videos-or-playlist-url>" | jq -r '.entries[] | "\(.id)\t\(.duration)\t\(.title)"'
```

## Script

```ts
#!/usr/bin/env bun
// yt-transcript — YouTube link in, headered transcript path out.
//
//   bun yt-transcript.ts <url-or-id> [--dir DIR] [--corpus ROOT] [--force]
//
// Stdout: ONE line, the transcript path (existing or new). Progress on stderr.
// Exit 0 = path printed · 1 = no captions on any rung · 2 = cookie rung needs Test-Chrome.
// Source of truth: @integrations/youtube — materialized per run, never edited locally.
//
// Ladder: dedupe (grep id under --corpus) → plain yt-dlp → yt-dlp --cookies <file>.
// The cookie file is ours: exported once from Test-Chrome over raw CDP, reused until
// it stops working, then re-exported once.
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, chmodSync, mkdirSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";

const args = process.argv.slice(2);
const flag = (k: string) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : undefined; };
const input = args.find((a, i) => !a.startsWith("--") && !args[i - 1]?.startsWith("--"));
const dir = flag("--dir") ?? process.env.YT_TRANSCRIPT_DIR ?? ".";
const corpus = flag("--corpus") ?? dir;
const force = args.includes("--force");
const CDP = process.env.CDP_URL ?? "http://127.0.0.1:10020";
const COOKIES = process.env.YT_COOKIES ?? join(tmpdir(), "yt-cookies.txt");
const log = (m: string) => console.error(`yt-transcript: ${m}`);

if (!input) { log("usage: bun yt-transcript.ts <url-or-id> [--dir DIR] [--corpus ROOT] [--force]"); process.exit(1); }
const id = input.match(/(?:v=|youtu\.be\/|shorts\/|embed\/|live\/)([\w-]{11})/)?.[1] ?? (/^[\w-]{11}$/.test(input) ? input : null);
if (!id) { log(`not a YouTube url or id: ${input}`); process.exit(1); }

// 1. dedupe
if (!force && existsSync(corpus)) {
  const hit = Bun.spawnSync(["grep", "-rl", "--include=*.md", "--include=*.txt", "-e", id, corpus]).stdout.toString().split("\n")[0];
  if (hit) { log("already in corpus"); console.log(hit); process.exit(0); }
}

// Export youtube/google cookies from Test-Chrome as a Netscape cookies.txt. Reads the
// cookie jar only — no page, no tab, no navigation.
async function exportCookies(): Promise<boolean> {
  const ver = await fetch(`${CDP}/json/version`).then(r => r.json()).catch(() => null) as any;
  if (!ver?.webSocketDebuggerUrl) return false;
  const cookies: any[] = await new Promise((resolve, reject) => {
    const ws = new WebSocket(ver.webSocketDebuggerUrl);
    ws.onopen = () => ws.send(JSON.stringify({ id: 1, method: "Storage.getCookies" }));
    ws.onmessage = e => { const m = JSON.parse(String(e.data)); if (m.id === 1) { ws.close(); m.error ? reject(m.error) : resolve(m.result.cookies); } };
    ws.onerror = reject;
  });
  const rows = cookies
    .filter(c => /(^|\.)(youtube|google)\.com$/.test(c.domain))
    .map(c => [c.domain, c.domain.startsWith(".") ? "TRUE" : "FALSE", c.path, c.secure ? "TRUE" : "FALSE",
               c.expires > 0 ? Math.floor(c.expires) : 0, c.name, c.value].join("\t"));
  writeFileSync(COOKIES, "# Netscape HTTP Cookie File\n" + rows.join("\n") + "\n");
  chmodSync(COOKIES, 0o600);
  log(`exported ${rows.length} cookies from Test-Chrome${cookies.some(c => c.name === "SAPISID") ? "" : " (not signed in to YouTube)"}`);
  return true;
}

function ytdlp(tmp: string, cookies?: string) {
  const cmd = ["yt-dlp", "--ignore-no-formats-error", "--skip-download", "--write-auto-subs", "--write-subs", "--sub-langs", "en.*,en",
    "--sub-format", "vtt", "--no-simulate", "--print", "%(.{title,channel,duration_string,upload_date})j",
    "-o", join(tmp, "yt.%(ext)s"), `https://www.youtube.com/watch?v=${id}`];
  if (cookies) cmd.splice(1, 0, "--cookies", cookies);
  const r = Bun.spawnSync(cmd);
  let meta: any = {};
  for (const l of r.stdout.toString().split("\n")) if (l.startsWith("{")) try { meta = JSON.parse(l); } catch {}
  const vtt = readdirSync(tmp).filter(f => f.endsWith(".vtt")).sort((a, b) => Number(a !== "yt.en.vtt") - Number(b !== "yt.en.vtt"))[0];
  const err = r.stderr.toString().trim().split("\n").pop() ?? "";
  return { meta, vtt: vtt && join(tmp, vtt), err };
}

// Auto-captions repeat each line as they scroll: keep first sightings, 30-second paragraphs.
function vttToText(path: string): string {
  const out: string[][] = []; const seen = new Set<string>();
  let buf: string[] = [], bucket = -1, cur = 0;
  for (const line of readFileSync(path, "utf8").split("\n")) {
    const m = line.match(/^(\d\d):(\d\d):(\d\d)\.\d+ -->/);
    if (m) { cur = +m[1] * 3600 + +m[2] * 60 + +m[3]; continue; }
    if (!line.trim() || line.includes("-->") || /^(WEBVTT|Kind:|Language:)/.test(line)) continue;
    const t = line.replace(/<[^>]+>/g, "").trim();
    if (!t || seen.has(t)) continue;
    seen.add(t);
    if (Math.floor(cur / 30) !== bucket) {
      if (buf.length) out.push(buf);
      bucket = Math.floor(cur / 30);
      buf = [`${String(Math.floor(cur / 60)).padStart(2, "0")}:${String(cur % 60).padStart(2, "0")}`, t];
    } else buf.push(t);
  }
  if (buf.length) out.push(buf);
  return out.map(p => p[0] + "\n" + p.slice(1).join(" ")).join("\n\n");
}

const tmp = mkdtempSync(join(tmpdir(), "yt-"));
let res = ytdlp(tmp);
if (res.vtt) log("captions via plain");
else {
  log(`plain: ${res.err}`);
  const fresh = existsSync(COOKIES) && Date.now() - statSync(COOKIES).mtimeMs < 12 * 3600e3;
  if (fresh) { res = ytdlp(tmp, COOKIES); if (res.vtt) log("captions via cookie file"); else log(`cookie file: ${res.err}`); }
  if (!res.vtt) {
    if (!(await exportCookies())) { log(`Test-Chrome not reachable at ${CDP} — bootstrap it per @integrations/agent-browser, then rerun`); process.exit(2); }
    res = ytdlp(tmp, COOKIES);
    if (res.vtt) log("captions via fresh Test-Chrome cookies");
  }
}
if (!res.vtt) { log(`no captions (${res.err}) — see @integrations/youtube_/reference`); rmSync(tmp, { recursive: true }); process.exit(1); }

const body = vttToText(res.vtt);
rmSync(tmp, { recursive: true });
const m = res.meta, d: string = m.upload_date ?? new Date().toISOString().slice(0, 10).replace(/-/g, "");
const date = `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}`;
const title: string = m.title ?? id;
const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60).replace(/-$/, "") || "untitled";
const header = [`# ${title}`, "# Source: YouTube", `# URL: https://www.youtube.com/watch?v=${id}`, `# Date: ${date}`,
  ...(m.channel ? [`# Participants: ${m.channel}`] : []), ...(m.duration_string ? [`# Duration: ${m.duration_string}`] : [])];
mkdirSync(dir, { recursive: true });
const path = join(dir, `${date}-${slug}.md`);
writeFileSync(path, header.join("\n") + "\n\n" + body + "\n");
log(`${body.split(/\s+/).length} words`);
console.log(path);
```

---

*Related: `@content/youtube/tiago-forte/i-dont-think-about-meetings-anymore-heres-the-system` · `@content/youtube/wes-mcdowell/new-rules-digital-marketing-ranked-2027` · `@content/youtube/wes-mcdowell/how-everyday-experts-are-getting-famous-on-youtube` · `@content/youtube/lennys-podcast/a-ugc-masterclass-from-the-22-year-old-who-built-wispr-flow-s-growth-machine-hector-serrano` · `@content/youtube/daniel-priestley/why-you-must-build-a-youtube-channel`*

---

*You're reading a protocol on [protocol.supply](https://protocol.supply) — hosted, searchable knowledge for AI agents. Think Agent Skills, as an API: bootstrap once (`curl -sL https://api.protocol.supply/bootstrap`), search (`/search?q=…`), fetch (`/@repo/slug`).*

*Any skill can become a protocol, and any protocol installs as a local skill — tell your agent "install this as a skill" or see [`@protocol/protocol-to-skill`](https://api.protocol.supply/@protocol/protocol-to-skill).*