Exported functions in state/lib/youtube.ts. .md file to compare - side-by-side diff against youtube
youtube
description: "Triggers on prompt mention of 'youtube'."
What it does for you
Connects your assistant to your YouTube channel.
What it produces
A recent result, so you can see the kind of work it returns.
loading…
How to get it
These run inside the Snappy workspace. Want this working in your business? I set skills like this up with you, in one focused week.
For developers how this skill is built, graded, and how it runs
at a glance- the short version
what's inside - the parts that make up a skill 3/4 present
A skill is just a few plain-text files. Only the main one is required. The rest are optional, added as the work needs them. This is what the skill is made of; how it runs is just below.
state/skills/youtube/SKILL.md
present
state/lib/youtube.ts
present
state/bin/youtube/
not present
state/skills/youtube/AGENTS.md
present
how it's graded - what counts as a good run 5 criteria · 3 deterministic · 2 judge
Each row is one thing a good run has to get right. deterministic means a quick check decides, pass or fail. judge means the AI reads the result and rates it. Grading each piece on its own (instead of one overall score) shows exactly where a run fell short, so the fix is obvious.
how it runs - the shared frame every skill uses 5/5 present
Every skill runs the same way. One part does the work, a separate part checks it, and a short loader hands the AI exactly what it needs for the job. Anything this skill doesn't use shows a one-line note saying why, on purpose, not by accident.
state/log/pending-eval.ndjson - ALWAYS run voice.checkTone() over comment replies BEFORE posting — em-dashes / hype / engagement-bait HARD-BLOCK on a public channel
- Default to apply: false on replyToComment() and uploadVideo() — preview first, require explicit apply to publish
- Round-trip verify after replyToComment() — fetch the comment thread separately and confirm the reply is visible (actor ≠ auditor)
- NEVER include author-scoreboard numbers in video descriptions or comments (memory: numbers_decoy_rule)
- NEVER frame uploads with scarcity hooks (memory: no_scarcity_offers)
- Eval is manual (Robert review) — every run files to state/log/pending-eval.ndjson
what it has learned - fixes written back in over time sample
When a run hits something this skill didn't handle, the fix gets written back into the skill so it doesn't happen again. FIXED means it was corrected on the spot. LOGGED means it's queued for a bigger rewrite. Either way, the skill gets a little better and never makes the same mistake twice.
- Loading feedback rows…
how the work flows- who makes it, who checks it
SKILL.md- the skill, written out in plain English
youtube
YouTube operations via direct YouTube Data API v3.
Ported from kernel snappy-youtube in Phase 0.5. See state/lib/youtube.ts for the full API surface.
Steps
getComments()- seestate/lib/youtube.tsreplyToComment()- seestate/lib/youtube.tsuploadVideo()- seestate/lib/youtube.tsgetVideo()- seestate/lib/youtube.tssearchVideos()- seestate/lib/youtube.ts
Eval
Actor: the exported functions in state/lib/youtube.ts. Auditor: none wired yet - eval is manual (Robert review). File a state/log/pending-eval.ndjson row on each run.
Score convention:
| Outcome | Score |
|---|---|
| Pass on first try | 1.0 |
| Failed first, auto-fix applied, re-check passed | 0.5 |
| Still failing or unrecoverable | 0.0 |
Gotchas
via the Phase 0.5 driver. Only these rewrites were applied: already in state/lib/)
realpathSync(process.argv[1])CLI guard wrapped in try/catch
- See the kernel SKILL.md for the original long-form guidance if you need it
(read-only reference at the kernel path above).
Graduation
This skill is prose. Graduate by defining a deterministic auditor and flipping eval: auto.
Rubric
criteria:
- name: youtube_api_calls_logged
kind: deterministic
check: "Verify all calls to the YouTube Data API v3 are logged in 'state/log/pending-eval.ndjson' with appropriate input parameters."
- name: required_inputs_present
kind: deterministic
check: "Check that the 'getComments_input', 'replyToComment_input', and 'uploadVideo_input' fields are present and not null when the corresponding function is invoked."
- name: youtube_function_completeness
kind: judge
check: "Assess if the executed YouTube function (e.g., getComments, uploadVideo) produced the expected and complete output as defined by the YouTube Data API v3 specifications."
- name: no_unhandled_exceptions
kind: deterministic
check: "Ensure the execution completes without any unhandled exceptions or errors logged in the system, indicating stable operation."
- name: correct_api_endpoint_used
kind: judge
check: "Confirm that the skill utilized the correct YouTube Data API v3 endpoints for the requested operation, adhering to the API documentation."AGENTS.md- what the AI loads when this skill comes up
youtube - loader
Per-turn rules for the youtube skill. Full reference: state/skills/youtube/SKILL.md. Do not skip these.
Critical Rules
- ALWAYS run
voice.checkTone()over comment replies BEFORE posting - em-dashes / hype / engagement-bait HARD-BLOCK on a public channel - Default to
apply: falseonreplyToComment()anduploadVideo()- preview first, require explicit apply to publish - Round-trip verify after
replyToComment()- fetch the comment thread separately and confirm the reply is visible (actor ≠ auditor) - NEVER include author-scoreboard numbers in video descriptions or comments (memory: numbers_decoy_rule)
- NEVER frame uploads with scarcity hooks (memory: no_scarcity_offers)
- Eval is manual (Robert review) - every run files to
state/log/pending-eval.ndjson
Commands
| ui dashboard | state/skills/youtube/resources/ui.openui | |library: state/lib/youtube.ts - getComments(), replyToComment(), uploadVideo(), getVideo(), searchVideos() |voice gate: state/lib/voice.ts - checkTone() |eval log: state/log/pending-eval.ndjson (manual)
OpenUI Resource
- Skill-owned OpenUI Lang resource:
state/skills/youtube/resources/ui.openui. Read it before rendering or editing this skill's generated component surface. - Treat this resource as a first-class artifact of the skill, not a generic chat response. Improve it when the skill's user-facing output needs to become richer.
- System resources compose OpenUI primitives and inherit SnappyChat tokens. Use
ui_contract: brandedin SKILL.md only for deliberate platform or client visuals.
Known Pitfalls
- Trusting the YouTube write API response as proof a comment posted; the round-trip fetch is the real auditor
- Engagement-bait closers ("Drop a like!", "Subscribe!") feel native to YouTube but still trip the voice gate
Self-Test
An agent reading this should correctly:
- [ ] Voice-gate every comment reply before publishing?
- [ ] Default to scope-only and require explicit apply for any public-facing write?
- [ ] Round-trip verify the post via an independent fetch?
Self-report
If this loader fell short, append a line:
echo "[$(date -u +%FT%TZ)] youtube: <what was missing>" >> state/log/loader-feedback.log
<!-- kernel-ok: historical attribution for the PID-loader pattern. -->
Self-correcting loader (PID feedback)
This is the rule that makes loaders learn. Ported from snappy-kernel, where it demonstrably worked: the snappy-dom-cartographer skill mapped Skool admin UI once, every later ship-agent inherited the full map for free.
Before you finish, do two things:
1. Fix gaps (P - proportional). MANDATORY. If this loader didn't cover your case - if you had to read another file, run an undocumented command, work around a wrong selector, or discover a quirk - you MUST attempt an Edit to this AGENTS.md before you log.
- Default action: edit this file. Surgical. Add the missing line, table
row, or code example where it belongs. No restructuring.
- Only
LOGGEDis allowed when: the fix needs >10 lines, spans multiple
files, or requires a structural rewrite. In that case the state/regen/drain.sh queue picks it up asynchronously.
- "I didn't have time" / "it's minor" / "the next agent will figure it out"
are NOT valid reasons. Minor gaps compound - that's the whole point of this loop.
- Concrete example of a valid P-fix: discover
agent-browser screenshot
takes path positionally not as --output <path>. One line in a table. Edit it in. Do not just log it.
- The goal: the next agent never has to leave the loader.
2. Log the result.
echo "[$(date -u +%FT%TZ)] youtube: <what was missing or fixed> [FIXED|LOGGED]" >> state/log/loader-feedback.log
FIXED= you patched this loader inline (P-fix).LOGGED= too large for inline; the PostToolUse enqueue + Stop-hook drain
will rewrite the loader from scratch on next session-end.
Do not skip this. Every agent run must leave the system better than it found it. The loader is the setpoint; you are the sensor; the gap is the error signal; closing the gap is the correction.
api.ts- the code it can call
#!/usr/bin/env npx tsx
/**
* snappy-youtube/api.ts -- YouTube operations via direct YouTube Data API v3.
*
* Read operations (comments, video info, search) use API key auth (GEMINI_API_KEY).
* Write operations (reply, upload) require YOUTUBE_ACCESS_TOKEN (OAuth2).
*
* Obtain YOUTUBE_ACCESS_TOKEN via OAuth2 flow using YOUTUBE_CLIENT_ID +
* YOUTUBE_CLIENT_SECRET. Analytics requires agent-browser (no API).
*
* Usage:
* npx tsx api.ts comments <videoId> # pull comments
* npx tsx api.ts reply <commentId> "response" # reply to a comment
* npx tsx api.ts upload <filePath> <title> <description> # upload video
* npx tsx api.ts video <videoId> # get video details
* npx tsx api.ts search <query> # search channel videos
*
* Or import as module:
* import { getComments, replyToComment, uploadVideo } from "./youtube.ts";
*/
import { env } from "./env.ts";
import { existsSync, readFileSync, realpathSync, writeFileSync } from "fs";
const YT_API = "https://www.googleapis.com/youtube/v3";
const YT_UPLOAD_API = "https://www.googleapis.com/upload/youtube/v3/videos";
const TOKEN_CACHE = `${process.env.HOME}/.claude/skills/snappy-settings/.youtube-token-cache.json`;
interface TokenCache {
access_token: string;
refresh_token: string;
expires_at: number;
}
function loadTokenCache(): TokenCache | null {
if (!existsSync(TOKEN_CACHE)) return null;
try { return JSON.parse(readFileSync(TOKEN_CACHE, "utf8")); } catch { return null; }
}
function saveTokenCache(data: TokenCache) {
writeFileSync(TOKEN_CACHE, JSON.stringify(data, null, 2), { mode: 0o600 });
}
let _accessToken: string | null = null;
let _tokenExpiry = 0;
async function refreshOAuthToken(): Promise<string> {
if (_accessToken && Date.now() / 1000 < _tokenExpiry - 60) return _accessToken;
const cached = loadTokenCache();
if (cached && Date.now() / 1000 < cached.expires_at - 60) {
_accessToken = cached.access_token;
_tokenExpiry = cached.expires_at;
return _accessToken;
}
const refreshToken = cached?.refresh_token || env("YOUTUBE_REFRESH_TOKEN", false);
if (refreshToken) {
const res = await fetch("https://oauth2.googleapis.com/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refreshToken,
client_id: env("YOUTUBE_CLIENT_ID"),
client_secret: env("YOUTUBE_CLIENT_SECRET"),
}).toString(),
});
const data = await res.json() as any;
if (res.ok && data.access_token) {
_accessToken = data.access_token;
_tokenExpiry = Math.floor(Date.now() / 1000) + (data.expires_in || 3600);
saveTokenCache({
access_token: data.access_token,
refresh_token: data.refresh_token || refreshToken,
expires_at: _tokenExpiry,
});
return _accessToken!;
}
}
const staticToken = env("YOUTUBE_ACCESS_TOKEN", false);
if (staticToken) {
_accessToken = staticToken;
_tokenExpiry = Math.floor(Date.now() / 1000) + 3600;
return _accessToken;
}
throw new Error("No YouTube auth. Run: npx tsx api.ts auth");
}
/** API key for read-only operations. */
function apiKey(): string {
return env("YOUTUBE_API_KEY", false) || env("GEMINI_API_KEY");
}
/** OAuth access token for write operations. */
async function oauthToken(): Promise<string> {
return refreshOAuthToken();
}
/** GET request with API key auth (read-only). */
async function ytGet(path: string, params: Record<string, string> = {}) {
const url = new URL(`${YT_API}${path}`);
url.searchParams.set("key", apiKey());
for (const [k, v] of Object.entries(params)) {
url.searchParams.set(k, v);
}
const res = await fetch(url.toString());
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`YouTube GET ${path} failed (${res.status}): ${text}`);
}
return res.json();
}
/** POST request with OAuth token (write operations). */
async function ytPost(path: string, body: Record<string, unknown>) {
const token = await oauthToken();
const res = await fetch(`${YT_API}${path}`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`YouTube POST ${path} failed (${res.status}): ${text}`);
}
return res.json();
}
// --- Public API ---
/**
* Pull comment threads for a video.
* Read-only -- uses API key auth.
*/
export async function getComments(videoId: string, maxResults = 50) {
return ytGet("/commentThreads", {
part: "snippet,replies",
videoId,
maxResults: String(maxResults),
order: "time",
});
}
/**
* Reply to a YouTube comment.
* Write operation -- requires YOUTUBE_ACCESS_TOKEN.
*/
export async function replyToComment(commentId: string, text: string) {
return ytPost("/comments?part=snippet", {
snippet: {
parentId: commentId,
textOriginal: text,
},
});
}
/**
* Upload a video to YouTube.
* Write operation -- requires YOUTUBE_ACCESS_TOKEN.
*
* Uses resumable upload protocol. Reads the file from disk.
*/
export async function uploadVideo(
filePath: string,
title: string,
description: string,
tags?: string[]
) {
const token = await oauthToken();
// Step 1: Initiate resumable upload
const metadata = {
snippet: {
title,
description,
tags: tags || [],
categoryId: "28", // Science & Technology
},
status: {
privacyStatus: "private", // Always upload as private first
selfDeclaredMadeForKids: false,
},
};
const initRes = await fetch(
`${YT_UPLOAD_API}?uploadType=resumable&part=snippet,status`,
{
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json; charset=UTF-8",
"X-Upload-Content-Type": "video/*",
},
body: JSON.stringify(metadata),
}
);
if (!initRes.ok) {
const text = await initRes.text().catch(() => "");
throw new Error(`YouTube upload init failed (${initRes.status}): ${text}`);
}
const uploadUrl = initRes.headers.get("location");
if (!uploadUrl) {
throw new Error("YouTube upload init did not return a Location header");
}
// Step 2: Upload the file
const fileData = readFileSync(filePath);
const uploadRes = await fetch(uploadUrl, {
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "video/*",
"Content-Length": String(fileData.byteLength),
},
body: fileData,
});
if (!uploadRes.ok) {
const text = await uploadRes.text().catch(() => "");
throw new Error(`YouTube upload failed (${uploadRes.status}): ${text}`);
}
return uploadRes.json();
}
/**
* Get video details (snippet, statistics).
* Read-only -- uses API key auth.
*/
export async function getVideo(videoId: string) {
return ytGet("/videos", {
part: "snippet,statistics,contentDetails",
id: videoId,
});
}
/**
* Search videos on a channel.
* Read-only -- uses API key auth.
*
* @param query - Search query
* @param channelId - Channel to search (defaults to Snappy channel)
*/
export async function searchVideos(query: string, channelId?: string, maxResults = 10) {
const params: Record<string, string> = {
part: "snippet",
q: query,
type: "video",
maxResults: String(maxResults),
order: "date",
};
if (channelId) params.channelId = channelId;
return ytGet("/search", params);
}
// --- CLI ---
if ((() => { try { return import.meta.url === `file://${realpathSync(process.argv[1])}`; } catch { return false; } })()) {
(async () => {
const [, , cmd, ...args] = process.argv;
switch (cmd) {
case "comments": {
const [videoId] = args;
if (!videoId) { console.error("Usage: api.ts comments <videoId>"); process.exit(1); }
const data = await getComments(videoId);
console.log(JSON.stringify(data, null, 2));
break;
}
case "reply": {
const [commentId, ...textParts] = args;
if (!commentId || !textParts.length) {
console.error("Usage: api.ts reply <commentId> <text>"); process.exit(1);
}
const data = await replyToComment(commentId, textParts.join(" "));
console.log(JSON.stringify(data, null, 2));
break;
}
case "upload": {
const [filePath, title, ...descParts] = args;
if (!filePath || !title) {
console.error("Usage: api.ts upload <filePath> <title> <description>"); process.exit(1);
}
const data = await uploadVideo(filePath, title, descParts.join(" "));
console.log(JSON.stringify(data, null, 2));
break;
}
case "video": {
const [videoId] = args;
if (!videoId) { console.error("Usage: api.ts video <videoId>"); process.exit(1); }
const data = await getVideo(videoId);
console.log(JSON.stringify(data, null, 2));
break;
}
case "search": {
const query = args.join(" ");
if (!query) { console.error("Usage: api.ts search <query>"); process.exit(1); }
const data = await searchVideos(query);
console.log(JSON.stringify(data, null, 2));
break;
}
case "auth": {
const { createServer } = await import("http");
const clientId = env("YOUTUBE_CLIENT_ID");
const redirectUri = "http://localhost:3142/callback";
const scopes = "https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/yt-analytics.readonly";
const state = Math.random().toString(36).slice(2);
const authUrl =
`https://accounts.google.com/o/oauth2/v2/auth?` +
`response_type=code&client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}` +
`&state=${state}&scope=${encodeURIComponent(scopes)}&access_type=offline&prompt=consent`;
console.log("\n=== YouTube OAuth Setup ===");
console.log("1. Open this URL in your browser:\n");
console.log(authUrl);
console.log("\n2. Log in and authorize the app.");
console.log("3. You'll be redirected back here automatically.\n");
console.log("Waiting for callback...");
const { exec } = await import("child_process");
exec(`open "${authUrl}"`);
await new Promise<void>((resolve, reject) => {
const server = createServer(async (req, res) => {
if (!req.url?.startsWith("/callback")) { res.end(); return; }
const url = new URL(req.url, `http://localhost:3142`);
const code = url.searchParams.get("code");
if (!code) {
res.writeHead(400); res.end("No code received");
reject(new Error("No code")); return;
}
try {
const tokenRes = await fetch("https://oauth2.googleapis.com/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: redirectUri,
client_id: env("YOUTUBE_CLIENT_ID"),
client_secret: env("YOUTUBE_CLIENT_SECRET"),
}).toString(),
});
const tokenData = await tokenRes.json() as any;
if (!tokenRes.ok) throw new Error(JSON.stringify(tokenData));
const expiresAt = Math.floor(Date.now() / 1000) + (tokenData.expires_in || 3600);
saveTokenCache({
access_token: tokenData.access_token,
refresh_token: tokenData.refresh_token || "",
expires_at: expiresAt,
});
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>YouTube auth complete! You can close this tab.</h1>");
console.log("\nTokens saved! Refresh token:", tokenData.refresh_token ? "YES" : "NO");
console.log("Token cache:", TOKEN_CACHE);
server.close();
resolve();
} catch (err) {
res.writeHead(500); res.end("Token exchange failed");
reject(err);
}
});
server.listen(3142);
});
break;
}
case "token-status": {
const cached = loadTokenCache();
if (!cached) { console.log("No token cache. Run: npx tsx api.ts auth"); break; }
const now = Date.now() / 1000;
const remaining = cached.expires_at - now;
console.log(`Access token: ${cached.access_token.slice(0, 10)}...`);
console.log(`Refresh token: ${cached.refresh_token ? "present" : "none"}`);
console.log(`Expires: ${new Date(cached.expires_at * 1000).toISOString()}`);
console.log(`Remaining: ${remaining > 0 ? Math.floor(remaining / 3600) + " hours" : "EXPIRED"}`);
console.log(`Status: ${remaining > 0 ? "VALID" : "EXPIRED -- will auto-refresh if refresh token exists"}`);
break;
}
default:
console.log("Usage: npx tsx api.ts [comments|reply|upload|video|search|auth|token-status] ...");
console.log("\nRead ops (comments, video, search) use API key -- no OAuth needed.");
console.log("Write ops (reply, upload) use OAuth -- auto-refreshes from token cache.");
console.log("First time: run 'auth' to bootstrap OAuth tokens.");
}
})();
}
scripts- helper scripts it can run
prose-only skill - 1 inline code block live in SKILL.md above (no state/bin/ sidecar yet).
how we check it- the checks, plus the last 10 runs
| timestamp | verb | score | primary_issue | artifact |
|---|---|---|---|---|
| 2026-04-25 04:11Z | - | 1.00 | - | - |
| 2026-04-21 15:58Z | - | 1.00 | - | - |
| 2026-04-21 15:57Z | - | 1.00 | - | - |
| 2026-04-21 03:53Z | - | 1.00 | - | - |
| 2026-04-25 04:11Z | - | 1.00 | - | - |
| 2026-04-21 15:58Z | - | 1.00 | - | - |
| 2026-04-21 15:57Z | - | 1.00 | - | - |
| 2026-04-21 03:53Z | - | 1.00 | - | - |
| 2026-04-25 04:11Z | - | 1.00 | - | - |
| 2026-04-21 15:58Z | - | 1.00 | - | - |