Skip to content

Free, open source blog writer for Claude Code. Researches current sources, writes answer-first posts for Google and AI answers, has an independent reviewer score each one out of 100 and ships only after five delivery gates. 32 skills, 30 /blog commands, 5 agents. Active development at AI-Marketing-Hub/claude-blog; public releases ship here.

feat: v1.6.0 - add blog-notebooklm and blog-audio skills (2 new skills, 21 total)

Daniel1a69074e7f0a
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index f9e4965..526d7f7 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "claude-blog",
- "description": "AI-powered blog skill with 17 commands, persona-driven writing, fact-checking, cannibalization detection, CMS taxonomy sync, 5-category scoring, 4 agents, and Gemini image generation. Optimized for Google rankings and AI citations (GEO/AEO).",
- "version": "1.5.0",
+ "description": "AI-powered blog skill with 20 commands, persona-driven writing, fact-checking, cannibalization detection, CMS taxonomy sync, NotebookLM research, Gemini TTS audio narration, 5-category scoring, 4 agents, and Gemini image generation. Optimized for Google rankings and AI citations (GEO/AEO).",
+ "version": "1.6.0",
"author": {
"name": "AgriciDaniel"
},
@@ -26,6 +26,8 @@
{"name": "blog-factcheck", "path": "skills/blog-factcheck"},
{"name": "blog-image", "path": "skills/blog-image"},
{"name": "blog-persona", "path": "skills/blog-persona"},
- {"name": "blog-taxonomy", "path": "skills/blog-taxonomy"}
+ {"name": "blog-taxonomy", "path": "skills/blog-taxonomy"},
+ {"name": "blog-notebooklm", "path": "skills/blog-notebooklm"},
+ {"name": "blog-audio", "path": "skills/blog-audio"}
]
}
diff --git a/.gitignore b/.gitignore
index 505a14e..2775efe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -48,6 +48,10 @@ credentials.json
# Firebase
firebase-debug.log
+# NotebookLM skill data (auth, browser state, library)
+**/browser_state/
+**/auth_info.json
+
# Generated output
output/
diff --git a/CLAUDE.md b/CLAUDE.md
index 25296df..75c1c43 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4,7 +4,7 @@
This repository contains **Claude Blog**, a Tier 4 Claude Code skill for blog content
creation, optimization, and management. It follows the Agent Skills open standard and the
-3-layer architecture (directive, orchestration, execution). 19 sub-skills, 4 specialized
+3-layer architecture (directive, orchestration, execution). 21 sub-skills, 4 specialized
subagents, and 12 content templates are dual-optimized for Google rankings (December 2025
Core Update, E-E-A-T) and AI citations (GEO/AEO).
@@ -13,10 +13,10 @@ Core Update, E-E-A-T) and AI citations (GEO/AEO).
```
claude-blog/
CLAUDE.md # Project instructions (this file)
- .claude-plugin/plugin.json # Plugin manifest (v1.5.0)
+ .claude-plugin/plugin.json # Plugin manifest (v1.6.0)
.mcp.json # MCP server configuration (nanobanana-mcp)
pyproject.toml # Python packaging (3.11+)
- skills/ # 19 sub-skills (blog/ is the orchestrator)
+ skills/ # 21 sub-skills (blog/ is the orchestrator)
blog/SKILL.md # Main orchestrator, routing, scoring
references/ # 12 on-demand knowledge files
templates/ # 12 content templates
@@ -42,6 +42,14 @@ claude-blog/
blog-factcheck/SKILL.md # Statistics verification
blog-persona/SKILL.md # Writing persona management
blog-taxonomy/SKILL.md # CMS taxonomy management
+ blog-notebooklm/ # NotebookLM source-grounded research
+ SKILL.md # NotebookLM query sub-skill
+ references/ # 2 reference docs (commands, troubleshooting)
+ scripts/ # 10 Python scripts + requirements.txt
+ blog-audio/ # Audio narration via Gemini TTS
+ SKILL.md # Audio generation sub-skill
+ references/ # 1 reference doc (30 voice catalog)
+ scripts/ # 5 Python scripts + requirements.txt
agents/ # 4 specialized subagents
blog-researcher.md # Statistics and source research
blog-writer.md # Content generation
@@ -72,6 +80,8 @@ claude-blog/
| `/blog factcheck` | Verify statistics against cited sources |
| `/blog persona` | Manage writing personas and voice profiles |
| `/blog taxonomy` | Tag/category CMS management |
+| `/blog notebooklm` | Query NotebookLM for source-grounded research |
+| `/blog audio` | Generate audio narration via Gemini TTS |
## Development Rules
diff --git a/agents/blog-researcher.md b/agents/blog-researcher.md
index 9d76a53..d5671bf 100644
--- a/agents/blog-researcher.md
+++ b/agents/blog-researcher.md
@@ -77,6 +77,30 @@ If fewer than 3 suitable stock images are found, or the topic is too niche/abstr
- "Section 3: Infographic mode - [description of data illustration]"
3. Do NOT call MCP tools directly. The `blog-image` sub-skill handles generation
+### When Querying NotebookLM
+
+If the user has NotebookLM notebooks relevant to the blog topic, use them for
+Tier 1 research data (user-uploaded primary sources). This is optional and
+should never block the research workflow.
+
+1. Check if `blog-notebooklm` is configured:
+ ```bash
+ python3 skills/blog-notebooklm/scripts/run.py auth_manager.py status
+ ```
+2. If authenticated, check for relevant notebooks:
+ ```bash
+ python3 skills/blog-notebooklm/scripts/run.py notebook_manager.py search --query "[topic]"
+ ```
+3. If a matching notebook exists, query it:
+ ```bash
+ python3 skills/blog-notebooklm/scripts/run.py ask_question.py --question "[research question]" --notebook-id [id] --json
+ ```
+4. Parse the JSON response and include findings as Tier 1 sources
+5. If auth is missing or no notebooks match, skip silently and continue with WebSearch
+
+**Source classification:** NotebookLM answers are Tier 1 because they come
+exclusively from the user's own uploaded documents -- zero hallucination risk.
+
### When Analyzing Competition
1. Search for the target keyword
diff --git a/skills/blog-audio/SKILL.md b/skills/blog-audio/SKILL.md
new file mode 100644
index 0000000..f9df29a
--- /dev/null
+++ b/skills/blog-audio/SKILL.md
@@ -0,0 +1,255 @@
+---
+name: blog-audio
+description: >
+ Generate audio narration of blog posts using Google Gemini TTS.
+ Supports summary narration, full article read-aloud, and two-speaker
+ podcast/dialogue mode with 30 voice options. Outputs MP3 with HTML5
+ audio embed code. Works standalone via /blog audio or internally from
+ blog-write. Falls back gracefully when API key is not configured.
+ Use when user says "blog audio", "narrate blog", "audio version",
+ "text to speech", "tts", "podcast mode", "read aloud", "audio narration",
+ "voice", "narration", "generate audio".
+user-invokable: true
+argument-hint: "[generate|voices|setup] [file-or-text] [--mode summary|full|dialogue] [--voice name]"
+allowed-tools:
+ - Read
+ - Write
+ - Bash
+ - Glob
+ - Grep
+license: MIT
+metadata:
+ author: AgriciDaniel
+ version: "1.0.0"
+---
+
+# Blog Audio -- Gemini TTS Narration for Blog Posts
+
+Generate professional audio narration of blog content using Google's Gemini TTS.
+Three modes: summary (200-300 word spoken overview), full article read-aloud,
+or two-speaker podcast dialogue. 30 voices, 80+ languages, HTML5 embed output.
+
+## Quick Reference
+
+| Command | What it does |
+|---------|-------------|
+| `/blog audio generate <file>` | Generate audio narration of a blog post |
+| `/blog audio voices` | Show available voices with characteristics |
+| `/blog audio setup` | Check/configure API key for Gemini TTS |
+
+## Prerequisites
+
+- Python 3.11+ (venv managed automatically by `run.py`)
+- `GOOGLE_AI_API_KEY` environment variable (same key used by blog-image)
+- FFmpeg (for WAV-to-MP3 conversion; falls back to WAV if missing)
+
+## Always Use run.py Wrapper
+
+```bash
+# CORRECT:
+python3 scripts/run.py generate_audio.py --text "..." --voice Charon --json
+
+# WRONG:
+python3 scripts/generate_audio.py --text "..." # Fails without venv
+```
+
+## API Key Check (Gate Pattern)
+
+Before generating audio, check for the API key:
+
+```bash
+echo $GOOGLE_AI_API_KEY
+```
+
+- If set: proceed with generation
+- If not set: guide the user:
+ "Audio generation requires a Google AI API key. Get one free at https://aistudio.google.com/apikey
+ Then set it: `export GOOGLE_AI_API_KEY=your-key`
+ This is the same key used by `/blog image` -- if image generation works, audio works too."
+- **When called internally** (from blog-write): return silently if key is missing.
+ Never block the writing workflow.
+
+## Setup
+
+For `/blog audio setup`:
+
+1. Check if `GOOGLE_AI_API_KEY` is set in environment
+2. If blog-image is configured (check `.mcp.json`), the key is already available
+3. If not, guide user to https://aistudio.google.com/apikey
+4. Verify with a dry run: `python3 scripts/run.py generate_audio.py --text "Test" --dry-run --json`
+
+## Voice Selection
+
+For `/blog audio voices`:
+
+Load `references/voices.md` and present the voice catalog to the user.
+
+Ask the user which voice they prefer, or recommend based on content type:
+- **Article narration**: Charon (Informative) or Sadaltager (Knowledgeable)
+- **Tutorial/how-to**: Achird (Friendly) or Sulafat (Warm)
+- **News/analysis**: Rasalgethi (Informative) or Schedar (Even)
+- **Lifestyle/wellness**: Aoede (Breezy) or Vindemiatrix (Gentle)
+- **Dialogue host**: Puck (Upbeat) or Laomedeia (Upbeat)
+- **Dialogue expert**: Kore (Firm) or Charon (Informative)
+
+## Generation Workflow
+
+For `/blog audio generate <file>`:
+
+### Step 1: Read the Blog Post
+
+Read the file and extract:
+- Title (from H1 or frontmatter)
+- Full content (markdown body)
+- Approximate word count
+
+### Step 2: Choose Mode
+
+Ask the user (or auto-select if they specified `--mode`):
+
+| Mode | When to use | Output |
+|------|-------------|--------|
+| **Summary** | Quick audio overview (1-2 min) | 200-300 word spoken summary |
+| **Full** | Complete read-aloud (5-15 min) | Full article as natural speech |
+| **Dialogue** | Podcast-style (3-8 min) | Two-person conversation about the article |
+
+### Step 3: Prepare Text
+
+**CRITICAL:** Claude prepares the text. The script does TTS only.
+
+**Summary mode:**
+Write a 200-300 word spoken summary of the article. Rules:
+- Write as natural speech, not written text
+- Open with the article's key finding or answer
+- Cover 3-5 main takeaways
+- Close with actionable advice
+- No markdown, no "In this article...", no meta-commentary
+- Use conversational transitions ("Here's what matters...", "The key finding is...")
+
+**Full mode:**
+Strip the markdown content to clean spoken text:
+- Headings become natural transitions ("Next, let's look at...")
+- Links become plain text (remove URLs, keep anchor text)
+- Images and charts: omit or briefly describe ("As the data shows...")
+- Code blocks: describe verbally ("The code uses a for-loop to...")
+- Lists: convert to natural sentences
+- Remove frontmatter, schema markup, HTML tags
+- Add brief intro: "This is [title], published on [date]."
+
+**Dialogue mode:**
+Write a 2-person conversation script about the article:
+- Speaker1 = Host (curious, asks good questions)
+- Speaker2 = Expert (knowledgeable, gives clear answers)
+- Format each line as: `[Speaker1] What's the key takeaway here?`
+- Cover the article's main points conversationally
+- 15-25 exchanges (produces ~3-8 minutes)
+- Natural, not stilted ("That's a great point" over "Indeed, as the research indicates")
+
+### Step 4: Select Voice
+
+If the user chose a voice, use it. Otherwise, recommend based on mode:
+- Summary/Full: default to Charon (Informative)
+- Dialogue: default to Puck (Host) + Kore (Expert)
+
+### Step 5: Generate Audio
+
+Write the prepared text to a temp file, then call:
+
+```bash
+# Single voice (summary or full mode)
+python3 scripts/run.py generate_audio.py \
+ --text-file /tmp/blog_audio_prepared.txt \
+ --voice Charon \
+ --model flash \
+ --output /path/to/audio/post-slug.mp3 \
+ --json
+
+# Two voices (dialogue mode)
+python3 scripts/run.py generate_audio.py \
+ --text-file /tmp/blog_audio_dialogue.txt \
+ --voice Puck \
+ --voice2 Kore \
+ --model pro \
+ --output /path/to/audio/post-slug-dialogue.mp3 \
+ --json
+```
+
+**Model selection:**
+- `flash` (default): Fast, cheap. Good for summaries and standard narration.
+- `pro`: Higher quality. Use for dialogue mode or premium content.
+
+### Step 6: Deliver
+
+Present the result to the user:
+1. **File path** -- where the audio was saved
+2. **Duration** -- human-readable (e.g., "3:42")
+3. **Embed code** -- ready-to-paste HTML5 audio tag
+4. **Cost** -- estimated API cost
+5. **Placement suggestion** -- where to insert the embed in the blog post
+
+## Embedding Guide
+
+### Standard HTML (Hugo, Jekyll, static sites)
+```html
+<audio controls preload="metadata">
+ <source src="audio/post-slug.mp3" type="audio/mpeg">
+ Your browser does not support the audio element.
+</audio>
+```
+
+### MDX (Next.js, Gatsby)
+```jsx
+<audio controls preload="metadata">
+ <source src="/audio/post-slug.mp3" type="audio/mpeg" />
+</audio>
+```
+
+### WordPress
+```
+[audio src="audio/post-slug.mp3"]
+```
+
+### Placement
+Insert the audio player after the introduction (below the first H2) or at the
+very top of the article with a label: "Listen to this article" or "Audio version".
+
+## Internal API (for blog-write)
+
+When invoked internally from blog-write:
+
+**Input:**
+- `text`: Prepared text (already cleaned by Claude)
+- `voice`: Voice name (default: Charon)
+- `voice2`: Second voice for dialogue (optional)
+- `model`: flash or pro
+- `output_path`: Where to save the file
+
+**Output:**
+```markdown
+### Audio Narration
+- **Path:** /path/to/audio/post-slug.mp3
+- **Duration:** 3:42
+- **Voice:** Charon
+- **Embed:** `<audio controls preload="metadata"><source src="audio/post-slug.mp3" type="audio/mpeg"></audio>`
+```
+
+**Graceful fallback:** If `GOOGLE_AI_API_KEY` is not set, return immediately
+with no error. The writing workflow continues without audio. Never block
+blog-write because audio generation is unavailable.
+
+## Error Handling
+
+| Error | Resolution |
+|-------|-----------|
+| GOOGLE_AI_API_KEY not set | Get key at https://aistudio.google.com/apikey |
+| FFmpeg not found | Install: `sudo apt install ffmpeg`. Falls back to WAV output. |
+| Rate limited | Wait and retry. Check limits at https://aistudio.google.com/rate-limit |
+| Text too long (>32k tokens) | Split into sections, generate separately |
+| Unknown voice name | Run `/blog audio voices` to see valid options |
+| API error | Check key validity, model availability (preview models) |
+| API key missing (internal call) | Return silently -- writing workflow continues |
+
+## Reference Documentation
+
+Load on-demand -- do NOT load all at startup:
+- `references/voices.md` -- Full 30-voice catalog, recommendations by content type, dialogue pairings
diff --git a/skills/blog-audio/references/voices.md b/skills/blog-audio/references/voices.md
new file mode 100644
index 0000000..28aca78
--- /dev/null
+++ b/skills/blog-audio/references/voices.md
@@ -0,0 +1,98 @@
+# Gemini TTS Voice Catalog
+
+30 prebuilt voices for Google Gemini TTS. All voices support 80+ languages
+with automatic language detection.
+
+## Full Voice Table
+
+| Voice | Tone | Best For |
+|-------|------|----------|
+| Zephyr | Bright | Energetic intros, lifestyle content |
+| Puck | Upbeat | Podcast host, casual blogs |
+| Charon | Informative | Article narration (default), technical content |
+| Kore | Firm | Expert/authority voice, dialogue guest |
+| Fenrir | Excitable | Product launches, news highlights |
+| Leda | Youthful | Youth-oriented content, tutorials |
+| Orus | Firm | Business, formal content |
+| Aoede | Breezy | Lifestyle, wellness, travel |
+| Callirrhoe | Easy-going | Casual blogs, personal essays |
+| Autonoe | Bright | Marketing, upbeat summaries |
+| Enceladus | Breathy | Intimate storytelling, ASMR-adjacent |
+| Iapetus | Clear | Technical documentation, clarity-first |
+| Umbriel | Easy-going | Relaxed tutorials, guides |
+| Algieba | Smooth | Professional narration, case studies |
+| Despina | Smooth | Polished delivery, executive summaries |
+| Erinome | Clear | Educational content, explainers |
+| Algenib | Gravelly | Character voice, dramatic reading |
+| Rasalgethi | Informative | News analysis, data-driven content |
+| Laomedeia | Upbeat | Co-host voice, interview-style |
+| Achernar | Soft | Gentle delivery, mindfulness content |
+| Alnilam | Firm | Authoritative statements, conclusions |
+| Schedar | Even | Neutral delivery, balanced reporting |
+| Gacrux | Mature | Thought leadership, industry analysis |
+| Pulcherrima | Forward | Direct, opinion pieces |
+| Achird | Friendly | How-to guides, tutorials (recommended) |
+| Zubenelgenubi | Casual | Conversational blogs, Reddit-style |
+| Vindemiatrix | Gentle | Health, wellness, sensitive topics |
+| Sadachbia | Lively | Listicles, roundups, energetic content |
+| Sadaltager | Knowledgeable | Deep dives, pillar pages |
+| Sulafat | Warm | Welcome messages, community content |
+
+## Recommended by Blog Type
+
+| Blog Type | Single Voice | Why |
+|-----------|-------------|-----|
+| How-to guide | Achird (Friendly) | Approachable, clear instruction delivery |
+| Technical tutorial | Iapetus (Clear) | Precision and clarity for code/data |
+| News analysis | Rasalgethi (Informative) | Authoritative without being dry |
+| Thought leadership | Gacrux (Mature) | Gravitas for opinion and prediction |
+| Listicle | Sadachbia (Lively) | Keeps energy up across list items |
+| Case study | Algieba (Smooth) | Professional, results-focused delivery |
+| Product review | Charon (Informative) | Balanced, trustworthy assessment |
+| Pillar page | Sadaltager (Knowledgeable) | Sustained depth over long content |
+| Lifestyle/wellness | Aoede (Breezy) | Light, inviting, relaxed pace |
+| FAQ/knowledge base | Erinome (Clear) | Direct answers, no filler |
+
+## Dialogue Mode Pairings
+
+Recommended voice combinations for two-speaker podcast/dialogue format:
+
+| Pair | Host | Guest/Expert | Style |
+|------|------|-------------|-------|
+| **Default** | Puck (Upbeat) | Kore (Firm) | Energetic host + authoritative expert |
+| Professional | Achird (Friendly) | Charon (Informative) | Warm interviewer + knowledgeable guest |
+| Casual | Zubenelgenubi (Casual) | Callirrhoe (Easy-going) | Relaxed conversation, both laid-back |
+| Technical | Laomedeia (Upbeat) | Iapetus (Clear) | Curious host + precise technical expert |
+| News | Schedar (Even) | Rasalgethi (Informative) | Neutral anchor + informed analyst |
+
+## Model Comparison
+
+| Model | ID | Best For | Cost (output) |
+|-------|----|---------|----|
+| **Flash** | `gemini-2.5-flash-preview-tts` | Summaries, standard narration, cost-sensitive | $10/1M tokens |
+| **Pro** | `gemini-2.5-pro-preview-tts` | Dialogue mode, premium podcasts, audiobooks | $20/1M tokens |
+
+**Default:** Flash for summary/full modes, Pro for dialogue mode.
+
+Flash is 2x cheaper and faster. Pro has higher fidelity and better handling of
+multi-speaker turn-taking. Use Pro when audio quality is the priority.
+
+## Language Notes
+
+- All 30 voices support 80+ languages via automatic detection
+- Pass text in any supported language -- no language parameter needed
+- Voice characteristics (Bright, Firm, etc.) carry across languages
+- For best results with non-English text, test voice-language combinations
+- BCP-47 language codes are auto-detected from input text
+
+## Style Control
+
+Gemini TTS does not support SSML. Control style via natural language in the text:
+
+Instead of markup, write the text in the desired style:
+- For emphasis: use naturally emphatic phrasing
+- For pauses: use punctuation (periods, ellipses, commas)
+- For pace: shorter sentences = faster pace, longer = slower
+- For tone: word choice drives delivery (urgent words = urgent delivery)
+
+The TTS model interprets natural language prosody cues automatically.
diff --git a/skills/blog-audio/scripts/__init__.py b/skills/blog-audio/scripts/__init__.py
new file mode 100644
index 0000000..4cc5b67
--- /dev/null
+++ b/skills/blog-audio/scripts/__init__.py
@@ -0,0 +1,2 @@
+#!/usr/bin/env python3
+"""Blog Audio Skill Scripts Package"""
diff --git a/skills/blog-audio/scripts/generate_audio.py b/skills/blog-audio/scripts/generate_audio.py
new file mode 100644
index 0000000..a9b27ef
--- /dev/null
+++ b/skills/blog-audio/scripts/generate_audio.py
@@ -0,0 +1,359 @@
+#!/usr/bin/env python3
+"""
+Blog Audio Generator -- Gemini TTS
+Converts prepared text to speech using Google's Gemini TTS models.
+
+Usage:
+ python scripts/run.py generate_audio.py --text "Hello world" --voice Charon --json
+ python scripts/run.py generate_audio.py --text-file article.txt --voice Puck --voice2 Kore --json
+ python scripts/run.py generate_audio.py --text "Test" --dry-run --json
+"""
+
+import argparse
+import base64
+import json
+import os
+import shutil
+import subprocess
+import sys
+import struct
+import tempfile
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+
+# All 30 Gemini TTS prebuilt voices
+VOICES = {
+ "Zephyr": "Bright", "Puck": "Upbeat", "Charon": "Informative",
+ "Kore": "Firm", "Fenrir": "Excitable", "Leda": "Youthful",
+ "Orus": "Firm", "Aoede": "Breezy", "Callirrhoe": "Easy-going",
+ "Autonoe": "Bright", "Enceladus": "Breathy", "Iapetus": "Clear",
+ "Umbriel": "Easy-going", "Algieba": "Smooth", "Despina": "Smooth",
+ "Erinome": "Clear", "Algenib": "Gravelly", "Rasalgethi": "Informative",
+ "Laomedeia": "Upbeat", "Achernar": "Soft", "Alnilam": "Firm",
+ "Schedar": "Even", "Gacrux": "Mature", "Pulcherrima": "Forward",
+ "Achird": "Friendly", "Zubenelgenubi": "Casual", "Vindemiatrix": "Gentle",
+ "Sadachbia": "Lively", "Sadaltager": "Knowledgeable", "Sulafat": "Warm",
+}
+
+MODELS = {
+ "flash": "gemini-2.5-flash-preview-tts",
+ "pro": "gemini-2.5-pro-preview-tts",
+}
+
+# Audio constants (Gemini TTS output format)
+SAMPLE_RATE = 24000 # 24kHz
+SAMPLE_WIDTH = 2 # 16-bit (2 bytes per sample)
+CHANNELS = 1 # Mono
+
+# Cost per 1M tokens (output)
+COST_PER_1M_OUTPUT = {"flash": 10.0, "pro": 20.0}
+COST_PER_1M_INPUT = {"flash": 0.50, "pro": 1.0}
+
+
+def estimate_cost(text: str, model: str) -> dict:
+ """Estimate generation cost from text length."""
+ char_count = len(text)
+ input_tokens = char_count / 4 # rough: 1 token ~ 4 chars
+ # Output tokens scale with audio duration; ~150 words/min speech
+ word_count = len(text.split())
+ duration_minutes = word_count / 150
+ duration_seconds = duration_minutes * 60
+ # Rough output token estimate based on audio duration
+ output_tokens = duration_seconds * 200 # ~200 tokens per second of audio
+
+ input_cost = (input_tokens / 1_000_000) * COST_PER_1M_INPUT[model]
+ output_cost = (output_tokens / 1_000_000) * COST_PER_1M_OUTPUT[model]
+ total_cost = input_cost + output_cost
+
+ return {
+ "input_tokens_est": int(input_tokens),
+ "output_tokens_est": int(output_tokens),
+ "duration_seconds_est": int(duration_seconds),
+ "duration_human_est": f"{int(duration_minutes)}:{int(duration_seconds % 60):02d}",
+ "cost_estimate": f"${total_cost:.3f}",
+ }
+
+
+def pcm_to_wav(pcm_data: bytes, output_path: str):
+ """Write raw PCM data as a WAV file."""
+ num_samples = len(pcm_data) // SAMPLE_WIDTH
+ data_size = num_samples * SAMPLE_WIDTH * CHANNELS
+ byte_rate = SAMPLE_RATE * CHANNELS * SAMPLE_WIDTH
+ block_align = CHANNELS * SAMPLE_WIDTH
+
+ with open(output_path, "wb") as f:
+ # RIFF header
+ f.write(b"RIFF")
+ f.write(struct.pack("<I", 36 + data_size))
+ f.write(b"WAVE")
+ # fmt chunk
+ f.write(b"fmt ")
+ f.write(struct.pack("<I", 16)) # chunk size
+ f.write(struct.pack("<H", 1)) # PCM format
+ f.write(struct.pack("<H", CHANNELS))
+ f.write(struct.pack("<I", SAMPLE_RATE))
+ f.write(struct.pack("<I", byte_rate))
+ f.write(struct.pack("<H", block_align))
+ f.write(struct.pack("<H", SAMPLE_WIDTH * 8))
+ # data chunk
+ f.write(b"data")
+ f.write(struct.pack("<I", data_size))
+ f.write(pcm_data)
+
+
+def wav_to_mp3(wav_path: str, mp3_path: str) -> bool:
+ """Convert WAV to MP3 using FFmpeg. Returns True on success."""
+ if not shutil.which("ffmpeg"):
+ return False
+ try:
+ subprocess.run(
+ ["ffmpeg", "-y", "-i", wav_path, "-codec:a", "libmp3lame",
+ "-b:a", "192k", "-ar", "24000", "-ac", "1", mp3_path],
+ check=True, capture_output=True,
+ )
+ return True
+ except subprocess.CalledProcessError:
+ return False
+
+
+def extract_audio_data(response) -> bytes:
+ """Extract raw PCM audio bytes from Gemini TTS response.
+ The SDK returns inline_data.data as bytes (raw PCM), not base64."""
+ data = response.candidates[0].content.parts[0].inline_data.data
+ if isinstance(data, bytes):
+ return data
+ # Fallback: if it's a base64 string (older SDK versions)
+ return base64.b64decode(data)
+
+
+def generate_single_speaker(client, text: str, voice: str, model: str) -> bytes:
+ """Generate audio with a single voice."""
+ from google.genai import types
+
+ response = client.models.generate_content(
+ model=MODELS[model],
+ contents=text,
+ config=types.GenerateContentConfig(
+ response_modalities=["AUDIO"],
+ speech_config=types.SpeechConfig(
+ voice_config=types.VoiceConfig(
+ prebuilt_voice_config=types.PrebuiltVoiceConfig(
+ voice_name=voice
+ )
+ )
+ ),
+ ),
+ )
+ return extract_audio_data(response)
+
+
+def generate_multi_speaker(client, text: str, voice1: str, voice2: str, model: str) -> bytes:
+ """Generate audio with two speakers (dialogue mode)."""
+ from google.genai import types
+
+ response = client.models.generate_content(
+ model=MODELS[model],
+ contents=text,
+ config=types.GenerateContentConfig(
+ response_modalities=["AUDIO"],
+ speech_config=types.SpeechConfig(
+ multi_speaker_voice_config=types.MultiSpeakerVoiceConfig(
+ speaker_voice_configs=[
+ types.SpeakerVoiceConfig(
+ speaker="Speaker1",
+ voice_config=types.VoiceConfig(
+ prebuilt_voice_config=types.PrebuiltVoiceConfig(
+ voice_name=voice1
+ )
+ ),
+ ),
+ types.SpeakerVoiceConfig(
+ speaker="Speaker2",
+ voice_config=types.VoiceConfig(
+ prebuilt_voice_config=types.PrebuiltVoiceConfig(
+ voice_name=voice2
+ )
+ ),
+ ),
+ ]
+ )
+ ),
+ ),
+ )
+ return extract_audio_data(response)
+
+
+def output_result(data: dict, as_json: bool):
+ """Print result in JSON or human-readable format."""
+ if as_json:
+ print(json.dumps(data, indent=2))
+ else:
+ if data["status"] == "success":
+ print(f"\n{'=' * 50}")
+ print(f" Audio generated successfully!")
+ print(f"{'=' * 50}")
+ print(f" File: {data['path']}")
+ print(f" Format: {data['format']}")
+ print(f" Duration: {data['duration_human']}")
+ print(f" Voice: {data['voice']}")
+ print(f" Model: {data['model']}")
+ print(f" Cost: ~{data['cost_estimate']}")
+ print(f"\n Embed HTML:")
+ print(f" {data['embed_html']}")
+ print(f"{'=' * 50}\n")
+ elif data["status"] == "dry_run":
+ print(f"\n Dry run estimate:")
+ print(f" Duration: ~{data['duration_human_est']}")
+ print(f" Cost: ~{data['cost_estimate']}")
+ print(f" Model: {data['model']}")
+ print(f" Voice: {data['voice']}")
+ else:
+ print(f"\n Error: {data.get('error', 'Unknown error')}")
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Generate audio from text using Gemini TTS")
+ group = parser.add_mutually_exclusive_group(required=True)
+ group.add_argument("--text", help="Text to convert to speech")
+ group.add_argument("--text-file", help="Path to text file")
+
+ parser.add_argument("--voice", default="Charon", help="Primary voice (default: Charon)")
+ parser.add_argument("--voice2", help="Second voice for dialogue mode")
+ parser.add_argument("--model", choices=["flash", "pro"], default="flash", help="TTS model")
+ parser.add_argument("--output", help="Output file path (default: auto-generated)")
+ parser.add_argument("--json", action="store_true", help="Output structured JSON")
+ parser.add_argument("--dry-run", action="store_true", help="Estimate cost without generating")
+
+ args = parser.parse_args()
+
+ # Validate voice names
+ for voice_arg in [args.voice, args.voice2]:
+ if voice_arg and voice_arg not in VOICES:
+ result = {"status": "error", "error": f"Unknown voice: {voice_arg}. Valid voices: {', '.join(sorted(VOICES.keys()))}"}
+ output_result(result, args.json)
+ return 1
+
+ # Read text
+ if args.text_file:
+ text_path = Path(args.text_file)
+ if not text_path.exists():
+ result = {"status": "error", "error": f"Text file not found: {args.text_file}"}
+ output_result(result, args.json)
+ return 1
+ text = text_path.read_text(encoding="utf-8").strip()
+ else:
+ text = args.text.strip()
+
+ if not text:
+ result = {"status": "error", "error": "Empty text provided"}
+ output_result(result, args.json)
+ return 1
+
+ # Dry run -- estimate only
+ if args.dry_run:
+ est = estimate_cost(text, args.model)
+ result = {
+ "status": "dry_run",
+ "model": args.model,
+ "voice": args.voice,
+ "voice2": args.voice2,
+ "text_length": len(text),
+ "word_count": len(text.split()),
+ **est,
+ }
+ output_result(result, args.json)
+ return 0
+
+ # Check API key
+ api_key = os.environ.get("GOOGLE_AI_API_KEY") or os.environ.get("GEMINI_API_KEY")
+ if not api_key:
+ result = {"status": "error", "error": "GOOGLE_AI_API_KEY not set. Get one at https://aistudio.google.com/apikey"}
+ output_result(result, args.json)
+ return 1
+
+ # Generate audio
+ try:
+ from google import genai
+ client = genai.Client(api_key=api_key)
+
+ if not args.json:
+ print(f"Generating audio ({args.model} model, voice: {args.voice})...")
+
+ if args.voice2:
+ pcm_data = generate_multi_speaker(client, text, args.voice, args.voice2, args.model)
+ else:
+ pcm_data = generate_single_speaker(client, text, args.voice, args.model)
+
+ except Exception as e:
+ result = {"status": "error", "error": f"Gemini TTS API error: {str(e)}"}
+ output_result(result, args.json)
+ return 1
+
+ # Calculate duration
+ num_samples = len(pcm_data) // SAMPLE_WIDTH
+ duration_seconds = num_samples / SAMPLE_RATE
+ duration_min = int(duration_seconds // 60)
+ duration_sec = int(duration_seconds % 60)
+ duration_human = f"{duration_min}:{duration_sec:02d}"
+
+ # Determine output path
+ if args.output:
+ output_path = Path(args.output)
+ else:
+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")
+ output_path = Path.cwd() / f"audio_{ts}.mp3"
+
+ # Write WAV, then convert to MP3
+ wav_path = str(output_path.with_suffix(".wav"))
+ pcm_to_wav(pcm_data, wav_path)
+
+ final_format = "wav"
+ final_path = wav_path
+
+ if output_path.suffix.lower() in (".mp3", ""):
+ mp3_path = str(output_path.with_suffix(".mp3"))
+ if wav_to_mp3(wav_path, mp3_path):
+ os.unlink(wav_path) # Remove temp WAV
+ final_path = mp3_path
+ final_format = "mp3"
+ else:
+ if not args.json:
+ print(" Warning: FFmpeg not found. Output is WAV (install ffmpeg for MP3).")
+ final_path = wav_path
+ final_format = "wav"
+ elif output_path.suffix.lower() == ".wav":
+ final_path = wav_path
+ final_format = "wav"
+
+ # Build embed HTML
+ rel_path = Path(final_path).name
+ mime = "audio/mpeg" if final_format == "mp3" else "audio/wav"
+ embed_html = (
+ f'<audio controls preload="metadata">'
+ f'<source src="{rel_path}" type="{mime}">'
+ f'Your browser does not support the audio element.</audio>'
+ )
+
+ # Cost estimate
+ est = estimate_cost(text, args.model)
+
+ result = {
+ "status": "success",
+ "path": str(Path(final_path).resolve()),
+ "format": final_format,
+ "duration_seconds": int(duration_seconds),
+ "duration_human": duration_human,
+ "voice": args.voice,
+ "voice2": args.voice2,
+ "model": args.model,
+ "embed_html": embed_html,
+ "cost_estimate": est["cost_estimate"],
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+ output_result(result, args.json)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/blog-audio/scripts/requirements.txt b/skills/blog-audio/scripts/requirements.txt
new file mode 100644
index 0000000..19d2962
--- /dev/null
+++ b/skills/blog-audio/scripts/requirements.txt
@@ -0,0 +1,5 @@
+# Blog Audio Skill Dependencies
+# Installed in the skill's local .venv via run.py
+
+# Google Gemini SDK for TTS generation
+google-genai>=1.0.0
diff --git a/skills/blog-audio/scripts/run.py b/skills/blog-audio/scripts/run.py
new file mode 100644
index 0000000..a846b8c
--- /dev/null
+++ b/skills/blog-audio/scripts/run.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env python3
+"""
+Universal runner for Blog Audio skill scripts
+Ensures all scripts run with the correct virtual environment
+"""
+
+import os
+import sys
+import subprocess
+from pathlib import Path
+
+
+def get_venv_python():
+ """Get the virtual environment Python executable"""
+ skill_dir = Path(__file__).parent.parent
+ venv_dir = skill_dir / ".venv"
+
+ if os.name == 'nt': # Windows
+ venv_python = venv_dir / "Scripts" / "python.exe"
+ else: # Unix/Linux/Mac
+ venv_python = venv_dir / "bin" / "python"
+
+ return venv_python
+
+
+def ensure_venv():
+ """Ensure virtual environment exists"""
+ skill_dir = Path(__file__).parent.parent
+ venv_dir = skill_dir / ".venv"
+ setup_script = skill_dir / "scripts" / "setup_environment.py"
+
+ # Check if venv exists
+ if not venv_dir.exists():
+ print("First-time setup: Creating virtual environment...")
+ print(" This may take a minute...")
+
+ # Run setup with system Python
+ result = subprocess.run([sys.executable, str(setup_script)])
+ if result.returncode != 0:
+ print("Failed to set up environment")
+ sys.exit(1)
+
+ print("Environment ready!")
+
+ return get_venv_python()
+
+
+def main():
+ """Main runner"""
+ if len(sys.argv) < 2:
+ print("Usage: python run.py <script_name> [args...]")
+ print("\nAvailable scripts:")
+ print(" generate_audio.py - Generate audio from text via Gemini TTS")
+ sys.exit(1)
+
+ script_name = sys.argv[1]
+ script_args = sys.argv[2:]
+
+ # Handle both "scripts/script.py" and "script.py" formats
+ if script_name.startswith('scripts/'):
+ script_name = script_name[8:] # len('scripts/') = 8
+
+ # Ensure .py extension
+ if not script_name.endswith('.py'):
+ script_name += '.py'
+
+ # Get script path
+ skill_dir = Path(__file__).parent.parent
+ script_path = skill_dir / "scripts" / script_name
+
+ if not script_path.exists():
+ print(f"Script not found: {script_name}")
+ print(f" Skill directory: {skill_dir}")
+ print(f" Looked for: {script_path}")
+ sys.exit(1)
+
+ # Ensure venv exists and get Python executable
+ venv_python = ensure_venv()
+
+ # Build command
+ cmd = [str(venv_python), str(script_path)] + script_args
+
+ # Run the script
+ try:
+ result = subprocess.run(cmd)
+ sys.exit(result.returncode)
+ except KeyboardInterrupt:
+ print("\nInterrupted by user")
+ sys.exit(130)
+ except Exception as e:
+ print(f"Error: {e}")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/blog-audio/scripts/setup_environment.py b/skills/blog-audio/scripts/setup_environment.py
new file mode 100644
index 0000000..594dcb9
--- /dev/null
+++ b/skills/blog-audio/scripts/setup_environment.py
@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+"""
+Environment Setup for Blog Audio Skill
+Manages virtual environment and dependencies automatically
+"""
+
+import os
+import sys
+import subprocess
+import venv
+from pathlib import Path
+
+
+class SkillEnvironment:
+ """Manages skill-specific virtual environment"""
+
+ def __init__(self):
+ self.skill_dir = Path(__file__).parent.parent
+ self.venv_dir = self.skill_dir / ".venv"
+ self.requirements_file = self.skill_dir / "scripts" / "requirements.txt"
+
+ if os.name == 'nt':
+ self.venv_python = self.venv_dir / "Scripts" / "python.exe"
+ self.venv_pip = self.venv_dir / "Scripts" / "pip.exe"
+ else:
+ self.venv_python = self.venv_dir / "bin" / "python"
+ self.venv_pip = self.venv_dir / "bin" / "pip"
+
+ def ensure_venv(self) -> bool:
+ """Ensure virtual environment exists and is set up"""
+ if self.is_in_skill_venv():
+ return True
+
+ if not self.venv_dir.exists():
+ print(f"Creating virtual environment in {self.venv_dir.name}/")
+ try:
+ venv.create(self.venv_dir, with_pip=True)
+ except Exception as e:
+ print(f"Failed to create venv: {e}")
+ return False
+
+ if self.requirements_file.exists():
+ print("Installing dependencies...")
+ try:
+ subprocess.run(
+ [str(self.venv_pip), "install", "--upgrade", "pip"],
+ check=True, capture_output=True, text=True,
+ )
+ subprocess.run(
+ [str(self.venv_pip), "install", "-r", str(self.requirements_file)],
+ check=True, capture_output=True, text=True,
+ )
+ print("Dependencies installed")
+ return True
+ except subprocess.CalledProcessError as e:
+ print(f"Failed to install dependencies: {e}")
+ return False
+ else:
+ print("No requirements.txt found, skipping dependency installation")
+ return True
+
+ def is_in_skill_venv(self) -> bool:
+ """Check if running in the skill's venv"""
+ if hasattr(sys, 'real_prefix') or (
+ hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
+ ):
+ return Path(sys.prefix) == self.venv_dir
+ return False
+
+ def get_python_executable(self) -> str:
+ """Get the correct Python executable"""
+ if self.venv_python.exists():
+ return str(self.venv_python)
+ return sys.executable
+
+
+def main():
+ """Main entry point for environment setup"""
+ import argparse
+
+ parser = argparse.ArgumentParser(description='Setup Blog Audio skill environment')
+ parser.add_argument('--check', action='store_true', help='Check if environment is set up')
+ args = parser.parse_args()
+
+ env = SkillEnvironment()
+
+ if args.check:
+ if env.venv_dir.exists():
+ print(f"Virtual environment exists: {env.venv_dir}")
+ print(f" Python: {env.get_python_executable()}")
+ else:
+ print("No virtual environment found")
+ return
+
+ if env.ensure_venv():
+ print(f"\nEnvironment ready!")
+ print(f" Virtual env: {env.venv_dir}")
+ print(f" Python: {env.get_python_executable()}")
+ else:
+ print("\nEnvironment setup failed")
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main() or 0)
diff --git a/skills/blog-notebooklm/SKILL.md b/skills/blog-notebooklm/SKILL.md
new file mode 100644
index 0000000..98e5cf3
--- /dev/null
+++ b/skills/blog-notebooklm/SKILL.md
@@ -0,0 +1,252 @@
+---
+name: blog-notebooklm
+description: >
+ Query Google NotebookLM notebooks for source-grounded, citation-backed
+ answers from user-uploaded documents. Manages notebook library, handles
+ Google authentication, and supports smart discovery. Works standalone
+ via /blog notebooklm or internally from blog-write and blog-researcher
+ for Tier 1 research data. Falls back gracefully when not configured.
+ Use when user says "notebooklm", "notebook", "query notebook",
+ "ask notebook", "notebook research", "source grounded research",
+ "document query", "notebook library".
+user-invokable: true
+argument-hint: "[ask|discover|library|setup|status|cleanup] [question-or-url]"
+allowed-tools:
+ - Read
+ - Bash
+ - Glob
+ - Grep
+license: MIT
+metadata:
+ author: AgriciDaniel
+ version: "1.0.0"
+ source: "https://github.com/PleasePrompto/notebooklm-skill"
+---
+
+# Blog NotebookLM -- Source-Grounded Research from Your Documents
+
+Query Google NotebookLM notebooks directly from Claude Code for citation-backed
+answers from Gemini. Each question opens a headless browser session, retrieves
+the answer exclusively from your uploaded documents, and closes. Responses are
+Tier 1 quality (user's own primary sources) -- zero hallucination risk.
+
+## Quick Reference
+
+| Command | What it does |
+|---------|-------------|
+| `/blog notebooklm ask <question>` | Query a notebook for source-grounded answers |
+| `/blog notebooklm discover <url>` | Smart-discover notebook content before cataloging |
+| `/blog notebooklm library list` | List all notebooks in library |
+| `/blog notebooklm library add <url>` | Add a notebook to library |
+| `/blog notebooklm library search <query>` | Search notebooks by keyword |
+| `/blog notebooklm library remove <id>` | Remove a notebook from library |
+| `/blog notebooklm setup` | One-time Google authentication (browser visible) |
+| `/blog notebooklm status` | Check authentication status |
+| `/blog notebooklm cleanup` | Clean browser state (preserves library) |
+
+## Prerequisites
+
+- Google account with NotebookLM access
+- Python 3.11+ (venv managed automatically by `run.py`)
+- Google Chrome (installed automatically on first run via Patchright)
+- One-time authentication setup (interactive Google login in visible browser)
+
+## Always Use run.py Wrapper
+
+**NEVER call scripts directly. ALWAYS use `python3 scripts/run.py [script]`:**
+
+```bash
+# CORRECT:
+python3 scripts/run.py auth_manager.py status
+python3 scripts/run.py ask_question.py --question "..."
+
+# WRONG -- fails without venv:
+python3 scripts/auth_manager.py status
+```
+
+The `run.py` wrapper automatically creates `.venv`, installs dependencies,
+sets up Chrome, and executes the target script.
+
+## Auth Check (Gate Pattern)
+
+Before any query operation, check authentication:
+
+```bash
+python3 scripts/run.py auth_manager.py status
+```
+
+- If authenticated: proceed with the query
+- If not authenticated: inform user and guide to setup:
+ "NotebookLM requires Google login. Run `/blog notebooklm setup` to authenticate."
+- **When called internally** (from blog-write or blog-researcher): return silently
+ with no error if not authenticated. Never block the writing workflow.
+
+## Setup Workflow
+
+For `/blog notebooklm setup`:
+
+```bash
+# Opens a visible browser for manual Google login (one-time)
+python3 scripts/run.py auth_manager.py setup
+```
+
+Tell the user: "A browser window will open. Please log in to your Google account."
+Authentication persists via browser profile + cookie injection (hybrid approach).
+
+Other auth commands:
+```bash
+python3 scripts/run.py auth_manager.py status # Check auth
+python3 scripts/run.py auth_manager.py reauth # Re-authenticate
+python3 scripts/run.py auth_manager.py clear # Clear all auth data
+```
+
+## Query Workflow
+
+For `/blog notebooklm ask <question>`:
+
+### Step 1: Check Auth
+Run auth check (see gate pattern above). If not authenticated, guide to setup.
+
+### Step 2: Resolve Notebook
+Determine which notebook to query:
+- If `--notebook-url` provided: use directly
+- If `--notebook-id` provided: look up in library
+- If neither: use active notebook from library
+- If no active notebook: show library and ask user to select
+
+### Step 3: Ask the Question
+```bash
+# Basic query (uses active notebook)
+python3 scripts/run.py ask_question.py --question "Your question here"
+
+# Query specific notebook by ID
+python3 scripts/run.py ask_question.py --question "..." --notebook-id notebook-id
+
+# Query by URL directly
+python3 scripts/run.py ask_question.py --question "..." --notebook-url "https://..."
+
+# JSON output (for internal/programmatic use)
+python3 scripts/run.py ask_question.py --question "..." --json
+
+# Show browser for debugging
+python3 scripts/run.py ask_question.py --question "..." --show-browser
+```
+
+### Step 4: Analyze and Follow Up
+Every response ends with a follow-up prompt. **Required behavior:**
+1. **STOP** -- do not immediately respond to the user
+2. **ANALYZE** -- compare the answer to the user's original request
+3. **IDENTIFY GAPS** -- determine if more information is needed
+4. **ASK FOLLOW-UP** -- if gaps exist, immediately ask a follow-up question
+5. **REPEAT** -- continue until information is complete
+6. **SYNTHESIZE** -- combine all answers before responding to the user
+
+## Smart Discovery Workflow
+
+For `/blog notebooklm discover <url>`:
+
+When adding a notebook without knowing its content, query it first:
+
+```bash
+# Step 1: Discover content
+python3 scripts/run.py ask_question.py \
+ --question "What is the content of this notebook? What topics are covered? Provide a complete overview briefly and concisely" \
+ --notebook-url "<URL>"
+
+# Step 2: Add with discovered metadata
+python3 scripts/run.py notebook_manager.py add \
+ --url "<URL>" \
+ --name "<Based on content>" \
+ --description "<Based on content>" \
+ --topics "<Extracted topics>"
+```
+
+**NEVER guess or use generic descriptions.** Always discover or ask the user.
+
+## Library Management
+
+```bash
+# List all notebooks
+python3 scripts/run.py notebook_manager.py list
+
+# Add notebook (all params required -- discover or ask user!)
+python3 scripts/run.py notebook_manager.py add \
+ --url "https://notebooklm.google.com/notebook/..." \
+ --name "Descriptive Name" \
+ --description "What this notebook contains" \
+ --topics "topic1,topic2,topic3"
+
+# Search by keyword
+python3 scripts/run.py notebook_manager.py search --query "keyword"
+
+# Set active notebook
+python3 scripts/run.py notebook_manager.py activate --id notebook-id
+
+# Remove notebook
+python3 scripts/run.py notebook_manager.py remove --id notebook-id
+
+# Library statistics
+python3 scripts/run.py notebook_manager.py stats
+```
+
+## Internal API (for blog-write / blog-researcher)
+
+When invoked as a Task subagent from blog-write or blog-researcher:
+
+**Input** (provided by calling skill):
+- `question`: Research question relevant to the blog topic
+- `notebook_id` or `notebook_url`: Which notebook to query
+- `context`: "internal" (signals graceful fallback mode)
+
+**Process:**
+1. Check auth status -- if not authenticated, return empty result silently
+2. Query the notebook with the research question
+3. Parse and return structured response
+
+**Output** (returned to calling skill):
+```markdown
+### NotebookLM Research
+- **Source:** [Notebook name]
+- **Question:** [What was asked]
+- **Answer:** [Source-grounded response from user's documents]
+- **Source Quality:** Tier 1 (user-uploaded primary documents)
+```
+
+**Graceful fallback:** If auth is missing or query fails, return immediately
+with no error. The calling workflow continues with WebSearch-based research.
+Never block blog-write or blog-rewrite because NotebookLM is unavailable.
+
+## Data Storage
+
+All data stored inside the skill directory:
+- `scripts/data/library.json` -- Notebook metadata and library
+- `scripts/data/auth_info.json` -- Authentication status
+- `scripts/data/browser_state/` -- Chrome profile with cookies
+
+**Security:** All data directories are gitignored. Never commit auth or browser state.
+
+## Error Handling
+
+| Error | Resolution |
+|-------|-----------|
+| Not authenticated | Run `/blog notebooklm setup` |
+| ModuleNotFoundError | Always use `run.py` wrapper |
+| Browser crash | `cleanup_manager.py --confirm --preserve-library`, then re-auth |
+| Rate limit (50/day) | Wait until midnight PST or switch Google account |
+| Notebook not found | Check with `notebook_manager.py list` |
+| Query timeout (120s) | Retry with simpler question or `--show-browser` to debug |
+| MCP unavailable (internal) | Return silently -- writing workflow uses WebSearch |
+
+## Limitations
+
+- No session persistence (each question = new browser session)
+- Rate limits on free Google accounts (50 queries/day)
+- Manual upload required (user must add docs to NotebookLM web UI)
+- Browser overhead (few seconds per question for launch + teardown)
+- Local Claude Code only (not available in web UI)
+
+## Reference Documentation
+
+Load on-demand -- do NOT load all at startup:
+- `references/commands.md` -- Full CLI commands, parameters, and workflow patterns
+- `references/troubleshooting.md` -- Error solutions, recovery procedures, debugging
diff --git a/skills/blog-notebooklm/references/commands.md b/skills/blog-notebooklm/references/commands.md
new file mode 100644
index 0000000..d1a796a
--- /dev/null
+++ b/skills/blog-notebooklm/references/commands.md
@@ -0,0 +1,197 @@
+# NotebookLM Commands Reference
+
+Complete CLI documentation for all NotebookLM skill scripts.
+
+## run.py -- Universal Script Runner
+
+Always use `run.py` to execute any script. It handles venv creation,
+dependency installation, Chrome setup, and proper execution.
+
+```bash
+python3 scripts/run.py <script_name>.py [arguments]
+```
+
+## ask_question.py -- Query Interface
+
+Ask questions to NotebookLM notebooks with automated browser interaction.
+
+```bash
+# Basic query (uses active notebook)
+python3 scripts/run.py ask_question.py --question "Your question"
+
+# Query specific notebook by ID
+python3 scripts/run.py ask_question.py --question "..." --notebook-id notebook-id
+
+# Query by URL directly
+python3 scripts/run.py ask_question.py --question "..." --notebook-url "https://..."
+
+# JSON output for structured responses
+python3 scripts/run.py ask_question.py --question "..." --json
+
+# Show browser for debugging
+python3 scripts/run.py ask_question.py --question "..." --show-browser
+```
+
+**Parameters:**
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `--question` | Yes | Question to ask |
+| `--notebook-id` | No | Use notebook from library |
+| `--notebook-url` | No | Use URL directly |
+| `--json` | No | Output structured JSON |
+| `--show-browser` | No | Make browser visible |
+
+**JSON output format** (with `--json`):
+```json
+{
+ "status": "success",
+ "question": "What are the key findings?",
+ "answer": "The source-grounded response text...",
+ "notebook_id": "my-notebook",
+ "notebook_url": "https://notebooklm.google.com/notebook/...",
+ "timestamp": "2026-03-25T14:30:00Z"
+}
+```
+
+**Returns:** Answer text with follow-up prompt. Timeout: 120 seconds.
+
+## notebook_manager.py -- Library Management
+
+CRUD operations for the notebook library.
+
+```bash
+# Add notebook (all metadata required)
+python3 scripts/run.py notebook_manager.py add \
+ --url "https://notebooklm.google.com/notebook/..." \
+ --name "Descriptive Name" \
+ --description "What this notebook contains" \
+ --topics "topic1,topic2,topic3"
+
+# List all notebooks
+python3 scripts/run.py notebook_manager.py list
+
+# Search by keyword (searches name, description, topics)
+python3 scripts/run.py notebook_manager.py search --query "keyword"
+
+# Set active notebook (default for queries without --notebook-id)
+python3 scripts/run.py notebook_manager.py activate --id notebook-id
+
+# Remove notebook from library
+python3 scripts/run.py notebook_manager.py remove --id notebook-id
+
+# Show library statistics
+python3 scripts/run.py notebook_manager.py stats
+```
+
+**Commands:**
+| Command | Description |
+|---------|-------------|
+| `add` | Add notebook (requires --url, --name, --description, --topics) |
+| `list` | Show all notebooks with metadata |
+| `search` | Find notebooks by keyword |
+| `activate` | Set default notebook for queries |
+| `remove` | Delete from library |
+| `stats` | Display library statistics |
+
+**Smart discovery** (recommended before `add`):
+```bash
+# Query the notebook to learn its content first
+python3 scripts/run.py ask_question.py \
+ --question "What is the content of this notebook? What topics are covered?" \
+ --notebook-url "<URL>"
+# Then use discovered info for the add command
+```
+
+## auth_manager.py -- Authentication
+
+Handle Google authentication and browser state.
+
+```bash
+python3 scripts/run.py auth_manager.py setup # Initial setup (browser visible)
+python3 scripts/run.py auth_manager.py status # Check authentication
+python3 scripts/run.py auth_manager.py reauth # Re-authenticate
+python3 scripts/run.py auth_manager.py clear # Clear all auth data
+```
+
+**Commands:**
+| Command | Description |
+|---------|-------------|
+| `setup` | Interactive Google login in visible browser (one-time) |
+| `status` | Check if authenticated (lightweight, no side effects) |
+| `reauth` | Clear and re-setup authentication |
+| `clear` | Remove all authentication data |
+
+**Auth architecture:** Hybrid approach -- persistent browser profile for
+fingerprint consistency + manual cookie injection from state.json
+(Playwright bug #36139 workaround).
+
+## cleanup_manager.py -- Data Cleanup
+
+Clean skill data with preservation options.
+
+```bash
+python3 scripts/run.py cleanup_manager.py # Preview (dry run)
+python3 scripts/run.py cleanup_manager.py --confirm # Execute cleanup
+python3 scripts/run.py cleanup_manager.py --confirm --preserve-library # Keep notebooks
+python3 scripts/run.py cleanup_manager.py --confirm --force # Skip confirmation
+```
+
+**Options:**
+| Option | Description |
+|--------|-------------|
+| `--confirm` | Actually perform cleanup (without this, preview only) |
+| `--preserve-library` | Keep notebook library, clean everything else |
+| `--force` | Skip confirmation prompt |
+
+## Workflow Patterns
+
+### Pattern: Research for Blog Writing
+```bash
+# 1. Check if relevant notebook exists
+python3 scripts/run.py notebook_manager.py search --query "marketing"
+
+# 2. Query for source-grounded data
+python3 scripts/run.py ask_question.py \
+ --question "What are the latest conversion rate benchmarks?" \
+ --notebook-id marketing-research --json
+
+# 3. Follow up for completeness
+python3 scripts/run.py ask_question.py \
+ --question "Break down conversion rates by industry and channel" \
+ --notebook-id marketing-research --json
+```
+
+### Pattern: Multi-Notebook Research
+```bash
+# Query different notebooks for a comprehensive view
+python3 scripts/run.py ask_question.py --question "..." --notebook-id source-a
+python3 scripts/run.py ask_question.py --question "..." --notebook-id source-b
+# Synthesize answers from both sources
+```
+
+### Pattern: Batch Questions
+```bash
+# Ask multiple focused questions (respect 50/day rate limit)
+for question in "Q1" "Q2" "Q3"; do
+ python3 scripts/run.py ask_question.py --question "$question" --json
+ sleep 2 # Avoid rate limits
+done
+```
+
+## Environment Variables (Optional)
+
+Create `.env` in skill root directory:
+```env
+HEADLESS=false # Browser visibility (default: true)
+SHOW_BROWSER=false # Default browser display
+STEALTH_ENABLED=true # Human-like behavior simulation
+TYPING_WPM_MIN=160 # Typing speed range
+TYPING_WPM_MAX=240
+DEFAULT_NOTEBOOK_ID= # Default notebook for queries
+```
+
+## Rate Limits
+
+- Free Google accounts: ~50 queries/day
+- Reset: midnight PST
+- Mitigation: switch accounts with `auth_manager.py reauth`
diff --git a/skills/blog-notebooklm/references/troubleshooting.md b/skills/blog-notebooklm/references/troubleshooting.md
new file mode 100644
index 0000000..37a1b08
--- /dev/null
+++ b/skills/blog-notebooklm/references/troubleshooting.md
@@ -0,0 +1,148 @@
+# NotebookLM Troubleshooting Guide
+
+## Quick Fix Table
+
+| Error | Solution |
+|-------|----------|
+| ModuleNotFoundError | Always use `python3 scripts/run.py [script].py` |
+| Not authenticated | `python3 scripts/run.py auth_manager.py setup` (browser visible) |
+| Browser crash | Kill Chrome, cleanup with `--preserve-library`, re-auth |
+| Rate limit (50/day) | Wait until midnight PST or switch Google account |
+| Notebook not found | Check with `notebook_manager.py list` |
+| Query timeout | Retry with simpler question or `--show-browser` to debug |
+
+## Authentication Issues
+
+### Not authenticated error
+```bash
+python3 scripts/run.py auth_manager.py status # Confirm status
+python3 scripts/run.py auth_manager.py setup # Browser visible for login
+```
+User must manually log in to Google in the browser window.
+
+### Authentication expires frequently
+```bash
+python3 scripts/run.py cleanup_manager.py --confirm --preserve-library
+python3 scripts/run.py auth_manager.py setup # Fresh login
+```
+Uses hybrid auth: persistent browser profile + cookie injection
+(workaround for Playwright bug #36139).
+
+### Google blocks automated login
+1. Use a dedicated Google account for automation
+2. Browser is ALWAYS visible during setup (no headless auth)
+3. Complete any 2FA challenges in the browser window
+
+## Browser Issues
+
+### Browser crashes or hangs
+```bash
+pkill -f chromium && pkill -f chrome # Kill hanging processes
+python3 scripts/run.py cleanup_manager.py --confirm --preserve-library
+python3 scripts/run.py auth_manager.py reauth # Re-authenticate
+```
+
+### Browser not found
+```bash
+# run.py installs Chrome automatically on first run
+python3 scripts/run.py auth_manager.py status
+# If still failing, manual install:
+source .venv/bin/activate
+python -m patchright install chromium
+```
+
+### Timeout waiting for selector
+NotebookLM UI may have changed CSS selectors. Check `config.py` for
+current selectors (`QUERY_INPUT_SELECTORS`, `RESPONSE_SELECTORS`).
+Use `--show-browser` to visually debug.
+
+## Rate Limiting
+
+### Rate limit exceeded (50 queries/day)
+
+**Option 1: Wait** -- resets at midnight PST
+
+**Option 2: Switch accounts**
+```bash
+python3 scripts/run.py auth_manager.py clear
+python3 scripts/run.py auth_manager.py setup # Login with different account
+```
+
+## Notebook Access Issues
+
+### Notebook not found in library
+```bash
+python3 scripts/run.py notebook_manager.py list
+python3 scripts/run.py notebook_manager.py search --query "keyword"
+```
+
+### Wrong notebook being queried
+```bash
+python3 scripts/run.py notebook_manager.py list # Check active
+python3 scripts/run.py notebook_manager.py activate --id correct-id
+```
+
+## Virtual Environment Issues
+
+### ModuleNotFoundError
+**Always use `run.py`** -- it handles venv automatically:
+```bash
+python3 scripts/run.py [any_script].py # Creates .venv if needed
+```
+
+### Corrupted venv
+```bash
+rm -rf .venv # Remove broken venv
+python3 scripts/run.py auth_manager.py status # Auto-recreates
+```
+
+## Data Issues
+
+### Corrupted notebook library
+```bash
+cp data/library.json library.backup.json # Backup first
+rm data/library.json # Reset
+python3 scripts/run.py notebook_manager.py add --url ... --name ... # Re-add
+```
+
+## Recovery Procedures
+
+### Complete reset (keep library)
+```bash
+pkill -f chromium
+python3 scripts/run.py cleanup_manager.py --confirm --preserve-library
+rm -rf .venv
+python3 scripts/run.py auth_manager.py setup # Rebuilds everything
+```
+
+### Complete reset (fresh start)
+```bash
+pkill -f chromium
+python3 scripts/run.py cleanup_manager.py --confirm --force
+rm -rf .venv
+python3 scripts/run.py auth_manager.py setup
+```
+
+## Debugging
+
+```bash
+# Enable visible browser for debugging
+python3 scripts/run.py ask_question.py --question "test" --show-browser
+
+# Check individual components
+python3 scripts/run.py auth_manager.py status
+python3 scripts/run.py notebook_manager.py list
+```
+
+## Common Questions
+
+**Q: Why doesn't this work in Claude web UI?**
+A: Requires local file system and browser access. Use Claude Code CLI only.
+
+**Q: Can I use multiple Google accounts?**
+A: Yes, use `auth_manager.py reauth` to switch between accounts.
+
+**Q: Is Patchright safe?**
+A: It's an anti-detection fork of Playwright. Uses Chrome, not Chromium,
+for better fingerprint consistency. Required because Google actively blocks
+standard Playwright automation.
diff --git a/skills/blog-notebooklm/scripts/__init__.py b/skills/blog-notebooklm/scripts/__init__.py
new file mode 100644
index 0000000..e77fffc
--- /dev/null
+++ b/skills/blog-notebooklm/scripts/__init__.py
@@ -0,0 +1,81 @@
+#!/usr/bin/env python3
+"""
+NotebookLM Skill Scripts Package
+Provides automatic environment management for all scripts
+"""
+
+import os
+import sys
+import subprocess
+from pathlib import Path
+
+
+def ensure_venv_and_run():
+ """
+ Ensure virtual environment exists and run the requested script.
+ This is called when any script is imported or run directly.
+ """
+ # Only do this if we're not already in the skill's venv
+ skill_dir = Path(__file__).parent.parent
+ venv_dir = skill_dir / ".venv"
+
+ # Check if we're in a venv
+ in_venv = hasattr(sys, 'real_prefix') or (
+ hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
+ )
+
+ # Check if it's OUR venv
+ if in_venv:
+ venv_path = Path(sys.prefix)
+ if venv_path == venv_dir:
+ # We're already in the correct venv
+ return
+
+ # We need to set up or switch to our venv
+ if not venv_dir.exists():
+ print("🔧 First-time setup detected...")
+ print(" Creating isolated environment for NotebookLM skill...")
+ print(" This ensures clean dependency management...")
+
+ # Create venv
+ import venv
+ venv.create(venv_dir, with_pip=True)
+
+ # Install requirements
+ requirements_file = skill_dir / "requirements.txt"
+ if requirements_file.exists():
+ if os.name == 'nt': # Windows
+ pip_exe = venv_dir / "Scripts" / "pip.exe"
+ else:
+ pip_exe = venv_dir / "bin" / "pip"
+
+ print(" Installing dependencies in isolated environment...")
+ subprocess.run(
+ [str(pip_exe), "install", "-q", "-r", str(requirements_file)],
+ check=True
+ )
+
+ # Also install patchright's chromium
+ print(" Setting up browser automation...")
+ if os.name == 'nt':
+ python_exe = venv_dir / "Scripts" / "python.exe"
+ else:
+ python_exe = venv_dir / "bin" / "python"
+
+ subprocess.run(
+ [str(python_exe), "-m", "patchright", "install", "chromium"],
+ check=True,
+ capture_output=True
+ )
+
+ print("✅ Environment ready! All dependencies isolated in .venv/")
+
+ # If we're here and not in the venv, we should recommend using the venv
+ if not in_venv:
+ print("\n⚠️ Running outside virtual environment")
+ print(" Recommended: Use scripts/run.py to ensure clean execution")
+ print(" Or activate: source .venv/bin/activate")
+
+
+# Check environment when module is imported
+ensure_venv_and_run()
\ No newline at end of file
diff --git a/skills/blog-notebooklm/scripts/ask_question.py b/skills/blog-notebooklm/scripts/ask_question.py
new file mode 100644
index 0000000..2ba9bfb
--- /dev/null
+++ b/skills/blog-notebooklm/scripts/ask_question.py
@@ -0,0 +1,281 @@
+#!/usr/bin/env python3
+"""
+Simple NotebookLM Question Interface
+Based on MCP server implementation - simplified without sessions
+
+Implements hybrid auth approach:
+- Persistent browser profile (user_data_dir) for fingerprint consistency
+- Manual cookie injection from state.json for session cookies (Playwright bug workaround)
+See: https://github.com/microsoft/playwright/issues/36139
+"""
+
+import argparse
+import json
+import sys
+import time
+import re
+from datetime import datetime, timezone
+from pathlib import Path
+
+from patchright.sync_api import sync_playwright
+
+# Add parent directory to path
+sys.path.insert(0, str(Path(__file__).parent))
+
+from auth_manager import AuthManager
+from notebook_manager import NotebookLibrary
+from config import QUERY_INPUT_SELECTORS, RESPONSE_SELECTORS
+from browser_utils import BrowserFactory, StealthUtils
+
+
+# Follow-up reminder (adapted from MCP server for stateless operation)
+# Since we don't have persistent sessions, we encourage comprehensive questions
+FOLLOW_UP_REMINDER = (
+ "\n\nEXTREMELY IMPORTANT: Is that ALL you need to know? "
+ "You can always ask another question! Think about it carefully: "
+ "before you reply to the user, review their original request and this answer. "
+ "If anything is still unclear or missing, ask me another comprehensive question "
+ "that includes all necessary context (since each question opens a new browser session)."
+)
+
+
+def ask_notebooklm(question: str, notebook_url: str, headless: bool = True) -> str:
+ """
+ Ask a question to NotebookLM
+
+ Args:
+ question: Question to ask
+ notebook_url: NotebookLM notebook URL
+ headless: Run browser in headless mode
+
+ Returns:
+ Answer text from NotebookLM
+ """
+ auth = AuthManager()
+
+ if not auth.is_authenticated():
+ print("⚠️ Not authenticated. Run: python auth_manager.py setup")
+ return None
+
+ print(f"💬 Asking: {question}")
+ print(f"📚 Notebook: {notebook_url}")
+
+ playwright = None
+ context = None
+
+ try:
+ # Start playwright
+ playwright = sync_playwright().start()
+
+ # Launch persistent browser context using factory
+ context = BrowserFactory.launch_persistent_context(
+ playwright,
+ headless=headless
+ )
+
+ # Navigate to notebook
+ page = context.new_page()
+ print(" 🌐 Opening notebook...")
+ page.goto(notebook_url, wait_until="domcontentloaded")
+
+ # Wait for NotebookLM
+ page.wait_for_url(re.compile(r"^https://notebooklm\.google\.com/"), timeout=10000)
+
+ # Wait for query input (MCP approach)
+ print(" ⏳ Waiting for query input...")
+ query_element = None
+
+ for selector in QUERY_INPUT_SELECTORS:
+ try:
+ query_element = page.wait_for_selector(
+ selector,
+ timeout=10000,
+ state="visible" # Only check visibility, not disabled!
+ )
+ if query_element:
+ print(f" ✓ Found input: {selector}")
+ break
+ except:
+ continue
+
+ if not query_element:
+ print(" ❌ Could not find query input")
+ return None
+
+ # Type question (human-like, fast)
+ print(" ⏳ Typing question...")
+
+ # Use primary selector for typing
+ input_selector = QUERY_INPUT_SELECTORS[0]
+ StealthUtils.human_type(page, input_selector, question)
+
+ # Submit
+ print(" 📤 Submitting...")
+ page.keyboard.press("Enter")
+
+ # Small pause
+ StealthUtils.random_delay(500, 1500)
+
+ # Wait for response (MCP approach: poll for stable text)
+ print(" ⏳ Waiting for answer...")
+
+ answer = None
+ stable_count = 0
+ last_text = None
+ deadline = time.time() + 120 # 2 minutes timeout
+
+ while time.time() < deadline:
+ # Check if NotebookLM is still thinking (most reliable indicator)
+ try:
+ thinking_element = page.query_selector('div.thinking-message')
+ if thinking_element and thinking_element.is_visible():
+ time.sleep(1)
+ continue
+ except:
+ pass
+
+ # Try to find response with MCP selectors
+ for selector in RESPONSE_SELECTORS:
+ try:
+ elements = page.query_selector_all(selector)
+ if elements:
+ # Get last (newest) response
+ latest = elements[-1]
+ text = latest.inner_text().strip()
+
+ if text:
+ if text == last_text:
+ stable_count += 1
+ if stable_count >= 3: # Stable for 3 polls
+ answer = text
+ break
+ else:
+ stable_count = 0
+ last_text = text
+ except:
+ continue
+
+ if answer:
+ break
+
+ time.sleep(1)
+
+ if not answer:
+ print(" ❌ Timeout waiting for answer")
+ return None
+
+ print(" ✅ Got answer!")
+ # Add follow-up reminder to encourage Claude to ask more questions
+ return answer + FOLLOW_UP_REMINDER
+
+ except Exception as e:
+ print(f" ❌ Error: {e}")
+ import traceback
+ traceback.print_exc()
+ return None
+
+ finally:
+ # Always clean up
+ if context:
+ try:
+ context.close()
+ except:
+ pass
+
+ if playwright:
+ try:
+ playwright.stop()
+ except:
+ pass
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Ask NotebookLM a question')
+
+ parser.add_argument('--question', required=True, help='Question to ask')
+ parser.add_argument('--notebook-url', help='NotebookLM notebook URL')
+ parser.add_argument('--notebook-id', help='Notebook ID from library')
+ parser.add_argument('--show-browser', action='store_true', help='Show browser')
+ parser.add_argument('--json', action='store_true', help='Output structured JSON')
+
+ args = parser.parse_args()
+
+ # Resolve notebook URL
+ notebook_url = args.notebook_url
+
+ if not notebook_url and args.notebook_id:
+ library = NotebookLibrary()
+ notebook = library.get_notebook(args.notebook_id)
+ if notebook:
+ notebook_url = notebook['url']
+ else:
+ print(f"❌ Notebook '{args.notebook_id}' not found")
+ return 1
+
+ if not notebook_url:
+ # Check for active notebook first
+ library = NotebookLibrary()
+ active = library.get_active_notebook()
+ if active:
+ notebook_url = active['url']
+ print(f"📚 Using active notebook: {active['name']}")
+ else:
+ # Show available notebooks
+ notebooks = library.list_notebooks()
+ if notebooks:
+ print("\n📚 Available notebooks:")
+ for nb in notebooks:
+ mark = " [ACTIVE]" if nb.get('id') == library.active_notebook_id else ""
+ print(f" {nb['id']}: {nb['name']}{mark}")
+ print("\nSpecify with --notebook-id or set active:")
+ print("python scripts/run.py notebook_manager.py activate --id ID")
+ else:
+ print("❌ No notebooks in library. Add one first:")
+ print("python scripts/run.py notebook_manager.py add --url URL --name NAME --description DESC --topics TOPICS")
+ return 1
+
+ # Ask the question
+ answer = ask_notebooklm(
+ question=args.question,
+ notebook_url=notebook_url,
+ headless=not args.show_browser
+ )
+
+ if answer:
+ if args.json:
+ output = {
+ "status": "success",
+ "question": args.question,
+ "answer": answer,
+ "notebook_id": args.notebook_id or "",
+ "notebook_url": notebook_url,
+ "timestamp": datetime.now(timezone.utc).isoformat()
+ }
+ print(json.dumps(output, indent=2))
+ else:
+ print("\n" + "=" * 60)
+ print(f"Question: {args.question}")
+ print("=" * 60)
+ print()
+ print(answer)
+ print()
+ print("=" * 60)
+ return 0
+ else:
+ if args.json:
+ output = {
+ "status": "error",
+ "question": args.question,
+ "answer": None,
+ "notebook_id": args.notebook_id or "",
+ "notebook_url": notebook_url or "",
+ "timestamp": datetime.now(timezone.utc).isoformat()
+ }
+ print(json.dumps(output, indent=2))
+ else:
+ print("\n❌ Failed to get answer")
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/blog-notebooklm/scripts/auth_manager.py b/skills/blog-notebooklm/scripts/auth_manager.py
new file mode 100644
index 0000000..54c8b3b
--- /dev/null
+++ b/skills/blog-notebooklm/scripts/auth_manager.py
@@ -0,0 +1,358 @@
+#!/usr/bin/env python3
+"""
+Authentication Manager for NotebookLM
+Handles Google login and browser state persistence
+Based on the MCP server implementation
+
+Implements hybrid auth approach:
+- Persistent browser profile (user_data_dir) for fingerprint consistency
+- Manual cookie injection from state.json for session cookies (Playwright bug workaround)
+See: https://github.com/microsoft/playwright/issues/36139
+"""
+
+import json
+import time
+import argparse
+import shutil
+import re
+import sys
+from pathlib import Path
+from typing import Optional, Dict, Any
+
+from patchright.sync_api import sync_playwright, BrowserContext
+
+# Add parent directory to path
+sys.path.insert(0, str(Path(__file__).parent))
+
+from config import BROWSER_STATE_DIR, STATE_FILE, AUTH_INFO_FILE, DATA_DIR
+from browser_utils import BrowserFactory
+
+
+class AuthManager:
+ """
+ Manages authentication and browser state for NotebookLM
+
+ Features:
+ - Interactive Google login
+ - Browser state persistence
+ - Session restoration
+ - Account switching
+ """
+
+ def __init__(self):
+ """Initialize the authentication manager"""
+ # Ensure directories exist
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
+ BROWSER_STATE_DIR.mkdir(parents=True, exist_ok=True)
+
+ self.state_file = STATE_FILE
+ self.auth_info_file = AUTH_INFO_FILE
+ self.browser_state_dir = BROWSER_STATE_DIR
+
+ def is_authenticated(self) -> bool:
+ """Check if valid authentication exists"""
+ if not self.state_file.exists():
+ return False
+
+ # Check if state file is not too old (7 days)
+ age_days = (time.time() - self.state_file.stat().st_mtime) / 86400
+ if age_days > 7:
+ print(f"⚠️ Browser state is {age_days:.1f} days old, may need re-authentication")
+
+ return True
+
+ def get_auth_info(self) -> Dict[str, Any]:
+ """Get authentication information"""
+ info = {
+ 'authenticated': self.is_authenticated(),
+ 'state_file': str(self.state_file),
+ 'state_exists': self.state_file.exists()
+ }
+
+ if self.auth_info_file.exists():
+ try:
+ with open(self.auth_info_file, 'r') as f:
+ saved_info = json.load(f)
+ info.update(saved_info)
+ except Exception:
+ pass
+
+ if info['state_exists']:
+ age_hours = (time.time() - self.state_file.stat().st_mtime) / 3600
+ info['state_age_hours'] = age_hours
+
+ return info
+
+ def setup_auth(self, headless: bool = False, timeout_minutes: int = 10) -> bool:
+ """
+ Perform interactive authentication setup
+
+ Args:
+ headless: Run browser in headless mode (False for login)
+ timeout_minutes: Maximum time to wait for login
+
+ Returns:
+ True if authentication successful
+ """
+ print("🔐 Starting authentication setup...")
+ print(f" Timeout: {timeout_minutes} minutes")
+
+ playwright = None
+ context = None
+
+ try:
+ playwright = sync_playwright().start()
+
+ # Launch using factory
+ context = BrowserFactory.launch_persistent_context(
+ playwright,
+ headless=headless
+ )
+
+ # Navigate to NotebookLM
+ page = context.new_page()
+ page.goto("https://notebooklm.google.com", wait_until="domcontentloaded")
+
+ # Check if already authenticated
+ if "notebooklm.google.com" in page.url and "accounts.google.com" not in page.url:
+ print(" ✅ Already authenticated!")
+ self._save_browser_state(context)
+ return True
+
+ # Wait for manual login
+ print("\n ⏳ Please log in to your Google account...")
+ print(f" ⏱️ Waiting up to {timeout_minutes} minutes for login...")
+
+ try:
+ # Wait for URL to change to NotebookLM (regex ensures it's the actual domain, not a parameter)
+ timeout_ms = int(timeout_minutes * 60 * 1000)
+ page.wait_for_url(re.compile(r"^https://notebooklm\.google\.com/"), timeout=timeout_ms)
+
+ print(f" ✅ Login successful!")
+
+ # Save authentication state
+ self._save_browser_state(context)
+ self._save_auth_info()
+ return True
+
+ except Exception as e:
+ print(f" ❌ Authentication timeout: {e}")
+ return False
+
+ except Exception as e:
+ print(f" ❌ Error: {e}")
+ return False
+
+ finally:
+ # Clean up browser resources
+ if context:
+ try:
+ context.close()
+ except Exception:
+ pass
+
+ if playwright:
+ try:
+ playwright.stop()
+ except Exception:
+ pass
+
+ def _save_browser_state(self, context: BrowserContext):
+ """Save browser state to disk"""
+ try:
+ # Save storage state (cookies, localStorage)
+ context.storage_state(path=str(self.state_file))
+ print(f" 💾 Saved browser state to: {self.state_file}")
+ except Exception as e:
+ print(f" ❌ Failed to save browser state: {e}")
+ raise
+
+ def _save_auth_info(self):
+ """Save authentication metadata"""
+ try:
+ info = {
+ 'authenticated_at': time.time(),
+ 'authenticated_at_iso': time.strftime('%Y-%m-%d %H:%M:%S')
+ }
+ with open(self.auth_info_file, 'w') as f:
+ json.dump(info, f, indent=2)
+ except Exception:
+ pass # Non-critical
+
+ def clear_auth(self) -> bool:
+ """
+ Clear all authentication data
+
+ Returns:
+ True if cleared successfully
+ """
+ print("🗑️ Clearing authentication data...")
+
+ try:
+ # Remove browser state
+ if self.state_file.exists():
+ self.state_file.unlink()
+ print(" ✅ Removed browser state")
+
+ # Remove auth info
+ if self.auth_info_file.exists():
+ self.auth_info_file.unlink()
+ print(" ✅ Removed auth info")
+
+ # Clear entire browser state directory
+ if self.browser_state_dir.exists():
+ shutil.rmtree(self.browser_state_dir)
+ self.browser_state_dir.mkdir(parents=True, exist_ok=True)
+ print(" ✅ Cleared browser data")
+
+ return True
+
+ except Exception as e:
+ print(f" ❌ Error clearing auth: {e}")
+ return False
+
+ def re_auth(self, headless: bool = False, timeout_minutes: int = 10) -> bool:
+ """
+ Perform re-authentication (clear and setup)
+
+ Args:
+ headless: Run browser in headless mode
+ timeout_minutes: Login timeout in minutes
+
+ Returns:
+ True if successful
+ """
+ print("🔄 Starting re-authentication...")
+
+ # Clear existing auth
+ self.clear_auth()
+
+ # Setup new auth
+ return self.setup_auth(headless, timeout_minutes)
+
+ def validate_auth(self) -> bool:
+ """
+ Validate that stored authentication works
+ Uses persistent context to match actual usage pattern
+
+ Returns:
+ True if authentication is valid
+ """
+ if not self.is_authenticated():
+ return False
+
+ print("🔍 Validating authentication...")
+
+ playwright = None
+ context = None
+
+ try:
+ playwright = sync_playwright().start()
+
+ # Launch using factory
+ context = BrowserFactory.launch_persistent_context(
+ playwright,
+ headless=True
+ )
+
+ # Try to access NotebookLM
+ page = context.new_page()
+ page.goto("https://notebooklm.google.com", wait_until="domcontentloaded", timeout=30000)
+
+ # Check if we can access NotebookLM
+ if "notebooklm.google.com" in page.url and "accounts.google.com" not in page.url:
+ print(" ✅ Authentication is valid")
+ return True
+ else:
+ print(" ❌ Authentication is invalid (redirected to login)")
+ return False
+
+ except Exception as e:
+ print(f" ❌ Validation failed: {e}")
+ return False
+
+ finally:
+ if context:
+ try:
+ context.close()
+ except Exception:
+ pass
+ if playwright:
+ try:
+ playwright.stop()
+ except Exception:
+ pass
+
+
+def main():
+ """Command-line interface for authentication management"""
+ parser = argparse.ArgumentParser(description='Manage NotebookLM authentication')
+
+ subparsers = parser.add_subparsers(dest='command', help='Commands')
+
+ # Setup command
+ setup_parser = subparsers.add_parser('setup', help='Setup authentication')
+ setup_parser.add_argument('--headless', action='store_true', help='Run in headless mode')
+ setup_parser.add_argument('--timeout', type=float, default=10, help='Login timeout in minutes (default: 10)')
+
+ # Status command
+ subparsers.add_parser('status', help='Check authentication status')
+
+ # Validate command
+ subparsers.add_parser('validate', help='Validate authentication')
+
+ # Clear command
+ subparsers.add_parser('clear', help='Clear authentication')
+
+ # Re-auth command
+ reauth_parser = subparsers.add_parser('reauth', help='Re-authenticate (clear + setup)')
+ reauth_parser.add_argument('--timeout', type=float, default=10, help='Login timeout in minutes (default: 10)')
+
+ args = parser.parse_args()
+
+ # Initialize manager
+ auth = AuthManager()
+
+ # Execute command
+ if args.command == 'setup':
+ if auth.setup_auth(headless=args.headless, timeout_minutes=args.timeout):
+ print("\n✅ Authentication setup complete!")
+ print("You can now use ask_question.py to query NotebookLM")
+ else:
+ print("\n❌ Authentication setup failed")
+ exit(1)
+
+ elif args.command == 'status':
+ info = auth.get_auth_info()
+ print("\n🔐 Authentication Status:")
+ print(f" Authenticated: {'Yes' if info['authenticated'] else 'No'}")
+ if info.get('state_age_hours'):
+ print(f" State age: {info['state_age_hours']:.1f} hours")
+ if info.get('authenticated_at_iso'):
+ print(f" Last auth: {info['authenticated_at_iso']}")
+ print(f" State file: {info['state_file']}")
+
+ elif args.command == 'validate':
+ if auth.validate_auth():
+ print("Authentication is valid and working")
+ else:
+ print("Authentication is invalid or expired")
+ print("Run: auth_manager.py setup")
+
+ elif args.command == 'clear':
+ if auth.clear_auth():
+ print("Authentication cleared")
+
+ elif args.command == 'reauth':
+ if auth.re_auth(timeout_minutes=args.timeout):
+ print("\n✅ Re-authentication complete!")
+ else:
+ print("\n❌ Re-authentication failed")
+ exit(1)
+
+ else:
+ parser.print_help()
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/skills/blog-notebooklm/scripts/browser_session.py b/skills/blog-notebooklm/scripts/browser_session.py
new file mode 100644
index 0000000..b121af8
--- /dev/null
+++ b/skills/blog-notebooklm/scripts/browser_session.py
@@ -0,0 +1,255 @@
+#!/usr/bin/env python3
+"""
+Browser Session Management for NotebookLM
+Individual browser session for persistent NotebookLM conversations
+Based on the original NotebookLM API implementation
+"""
+
+import time
+import sys
+from typing import Any, Dict, Optional
+from pathlib import Path
+
+from patchright.sync_api import BrowserContext, Page
+
+# Add parent directory to path
+sys.path.insert(0, str(Path(__file__).parent))
+
+from browser_utils import StealthUtils
+
+
+class BrowserSession:
+ """
+ Represents a single persistent browser session for NotebookLM
+
+ Each session gets its own Page (tab) within a shared BrowserContext,
+ allowing for contextual conversations where NotebookLM remembers
+ previous messages.
+ """
+
+ def __init__(self, session_id: str, context: BrowserContext, notebook_url: str):
+ """
+ Initialize a new browser session
+
+ Args:
+ session_id: Unique identifier for this session
+ context: Browser context (shared or dedicated)
+ notebook_url: Target NotebookLM URL for this session
+ """
+ self.id = session_id
+ self.created_at = time.time()
+ self.last_activity = time.time()
+ self.message_count = 0
+ self.notebook_url = notebook_url
+ self.context = context
+ self.page = None
+ self.stealth = StealthUtils()
+
+ # Initialize the session
+ self._initialize()
+
+ def _initialize(self):
+ """Initialize the browser session and navigate to NotebookLM"""
+ print(f"🚀 Creating session {self.id}...")
+
+ # Create new page (tab) in context
+ self.page = self.context.new_page()
+ print(f" 🌐 Navigating to NotebookLM...")
+
+ try:
+ # Navigate to notebook
+ self.page.goto(self.notebook_url, wait_until="domcontentloaded", timeout=30000)
+
+ # Check if login is needed
+ if "accounts.google.com" in self.page.url:
+ raise RuntimeError("Authentication required. Please run auth_manager.py setup first.")
+
+ # Wait for page to be ready
+ self._wait_for_ready()
+
+ # Simulate human inspection
+ self.stealth.random_mouse_movement(self.page)
+ self.stealth.random_delay(300, 600)
+
+ print(f"✅ Session {self.id} ready!")
+
+ except Exception as e:
+ print(f"❌ Failed to initialize session: {e}")
+ if self.page:
+ self.page.close()
+ raise
+
+ def _wait_for_ready(self):
+ """Wait for NotebookLM page to be ready"""
+ try:
+ # Wait for chat input
+ self.page.wait_for_selector("textarea.query-box-input", timeout=10000, state="visible")
+ except Exception:
+ # Try alternative selector
+ self.page.wait_for_selector('textarea[aria-label="Feld für Anfragen"]', timeout=5000, state="visible")
+
+ def ask(self, question: str) -> Dict[str, Any]:
+ """
+ Ask a question in this session
+
+ Args:
+ question: The question to ask
+
+ Returns:
+ Dict with status, question, answer, session_id
+ """
+ try:
+ self.last_activity = time.time()
+ self.message_count += 1
+
+ print(f"💬 [{self.id}] Asking: {question}")
+
+ # Snapshot current answer to detect new response
+ previous_answer = self._snapshot_latest_response()
+
+ # Find chat input
+ chat_input_selector = "textarea.query-box-input"
+ try:
+ self.page.wait_for_selector(chat_input_selector, timeout=5000, state="visible")
+ except Exception:
+ chat_input_selector = 'textarea[aria-label="Feld für Anfragen"]'
+ self.page.wait_for_selector(chat_input_selector, timeout=5000, state="visible")
+
+ # Click and type with human-like behavior
+ self.stealth.realistic_click(self.page, chat_input_selector)
+ self.stealth.human_type(self.page, chat_input_selector, question)
+
+ # Small pause before submit
+ self.stealth.random_delay(300, 800)
+
+ # Submit
+ self.page.keyboard.press("Enter")
+
+ # Wait for response
+ print(" ⏳ Waiting for response...")
+ self.stealth.random_delay(1500, 3000)
+
+ # Get new answer
+ answer = self._wait_for_latest_answer(previous_answer)
+
+ if not answer:
+ raise Exception("Empty response from NotebookLM")
+
+ print(f" ✅ Got response ({len(answer)} chars)")
+
+ return {
+ "status": "success",
+ "question": question,
+ "answer": answer,
+ "session_id": self.id,
+ "notebook_url": self.notebook_url
+ }
+
+ except Exception as e:
+ print(f" ❌ Error: {e}")
+ return {
+ "status": "error",
+ "question": question,
+ "error": str(e),
+ "session_id": self.id
+ }
+
+ def _snapshot_latest_response(self) -> Optional[str]:
+ """Get the current latest response text"""
+ try:
+ # Use correct NotebookLM selector
+ responses = self.page.query_selector_all(".to-user-container .message-text-content")
+ if responses:
+ return responses[-1].inner_text()
+ except Exception:
+ pass
+ return None
+
+ def _wait_for_latest_answer(self, previous_answer: Optional[str], timeout: int = 120) -> str:
+ """Wait for and extract the new answer"""
+ start_time = time.time()
+ last_candidate = None
+ stable_count = 0
+
+ while time.time() - start_time < timeout:
+ # Check if NotebookLM is still thinking (most reliable indicator)
+ try:
+ thinking_element = self.page.query_selector('div.thinking-message')
+ if thinking_element and thinking_element.is_visible():
+ time.sleep(0.5)
+ continue
+ except Exception:
+ pass
+
+ try:
+ # Use correct NotebookLM selector
+ responses = self.page.query_selector_all(".to-user-container .message-text-content")
+
+ if responses:
+ latest_text = responses[-1].inner_text().strip()
+
+ # Check if it's a new response
+ if latest_text and latest_text != previous_answer:
+ # Check if text is stable (3 consecutive polls)
+ if latest_text == last_candidate:
+ stable_count += 1
+ if stable_count >= 3:
+ return latest_text
+ else:
+ stable_count = 1
+ last_candidate = latest_text
+
+ except Exception:
+ pass
+
+ time.sleep(0.5)
+
+ raise TimeoutError(f"No response received within {timeout} seconds")
+
+ def reset(self):
+ """Reset the chat by reloading the page"""
+ print(f"🔄 Resetting session {self.id}...")
+
+ self.page.reload(wait_until="domcontentloaded")
+ self._wait_for_ready()
+
+ previous_count = self.message_count
+ self.message_count = 0
+ self.last_activity = time.time()
+
+ print(f"✅ Session reset (cleared {previous_count} messages)")
+ return previous_count
+
+ def close(self):
+ """Close this session and clean up resources"""
+ print(f"🛑 Closing session {self.id}...")
+
+ if self.page:
+ try:
+ self.page.close()
+ except Exception as e:
+ print(f" ⚠️ Error closing page: {e}")
+
+ print(f"✅ Session {self.id} closed")
+
+ def get_info(self) -> Dict[str, Any]:
+ """Get information about this session"""
+ return {
+ "id": self.id,
+ "created_at": self.created_at,
+ "last_activity": self.last_activity,
+ "age_seconds": time.time() - self.created_at,
+ "inactive_seconds": time.time() - self.last_activity,
+ "message_count": self.message_count,
+ "notebook_url": self.notebook_url
+ }
+
+ def is_expired(self, timeout_seconds: int = 900) -> bool:
+ """Check if session has expired (default: 15 minutes)"""
+ return (time.time() - self.last_activity) > timeout_seconds
+
+
+if __name__ == "__main__":
+ # Example usage
+ print("Browser Session Module - Use ask_question.py for main interface")
+ print("This module provides low-level browser session management.")
\ No newline at end of file
diff --git a/skills/blog-notebooklm/scripts/browser_utils.py b/skills/blog-notebooklm/scripts/browser_utils.py
new file mode 100644
index 0000000..60a1210
--- /dev/null
+++ b/skills/blog-notebooklm/scripts/browser_utils.py
@@ -0,0 +1,107 @@
+"""
+Browser Utilities for NotebookLM Skill
+Handles browser launching, stealth features, and common interactions
+"""
+
+import json
+import time
+import random
+from typing import Optional, List
+
+from patchright.sync_api import Playwright, BrowserContext, Page
+from config import BROWSER_PROFILE_DIR, STATE_FILE, BROWSER_ARGS, USER_AGENT
+
+
+class BrowserFactory:
+ """Factory for creating configured browser contexts"""
+
+ @staticmethod
+ def launch_persistent_context(
+ playwright: Playwright,
+ headless: bool = True,
+ user_data_dir: str = str(BROWSER_PROFILE_DIR)
+ ) -> BrowserContext:
+ """
+ Launch a persistent browser context with anti-detection features
+ and cookie workaround.
+ """
+ # Launch persistent context
+ context = playwright.chromium.launch_persistent_context(
+ user_data_dir=user_data_dir,
+ channel="chrome", # Use real Chrome
+ headless=headless,
+ no_viewport=True,
+ ignore_default_args=["--enable-automation"],
+ user_agent=USER_AGENT,
+ args=BROWSER_ARGS
+ )
+
+ # Cookie Workaround for Playwright bug #36139
+ # Session cookies (expires=-1) don't persist in user_data_dir automatically
+ BrowserFactory._inject_cookies(context)
+
+ return context
+
+ @staticmethod
+ def _inject_cookies(context: BrowserContext):
+ """Inject cookies from state.json if available"""
+ if STATE_FILE.exists():
+ try:
+ with open(STATE_FILE, 'r') as f:
+ state = json.load(f)
+ if 'cookies' in state and len(state['cookies']) > 0:
+ context.add_cookies(state['cookies'])
+ # print(f" 🔧 Injected {len(state['cookies'])} cookies from state.json")
+ except Exception as e:
+ print(f" ⚠️ Could not load state.json: {e}")
+
+
+class StealthUtils:
+ """Human-like interaction utilities"""
+
+ @staticmethod
+ def random_delay(min_ms: int = 100, max_ms: int = 500):
+ """Add random delay"""
+ time.sleep(random.uniform(min_ms / 1000, max_ms / 1000))
+
+ @staticmethod
+ def human_type(page: Page, selector: str, text: str, wpm_min: int = 320, wpm_max: int = 480):
+ """Type with human-like speed"""
+ element = page.query_selector(selector)
+ if not element:
+ # Try waiting if not immediately found
+ try:
+ element = page.wait_for_selector(selector, timeout=2000)
+ except:
+ pass
+
+ if not element:
+ print(f"⚠️ Element not found for typing: {selector}")
+ return
+
+ # Click to focus
+ element.click()
+
+ # Type
+ for char in text:
+ element.type(char, delay=random.uniform(25, 75))
+ if random.random() < 0.05:
+ time.sleep(random.uniform(0.15, 0.4))
+
+ @staticmethod
+ def realistic_click(page: Page, selector: str):
+ """Click with realistic movement"""
+ element = page.query_selector(selector)
+ if not element:
+ return
+
+ # Optional: Move mouse to element (simplified)
+ box = element.bounding_box()
+ if box:
+ x = box['x'] + box['width'] / 2
+ y = box['y'] + box['height'] / 2
+ page.mouse.move(x, y, steps=5)
+
+ StealthUtils.random_delay(100, 300)
+ element.click()
+ StealthUtils.random_delay(100, 300)
diff --git a/skills/blog-notebooklm/scripts/cleanup_manager.py b/skills/blog-notebooklm/scripts/cleanup_manager.py
new file mode 100644
index 0000000..c4a8fc2
--- /dev/null
+++ b/skills/blog-notebooklm/scripts/cleanup_manager.py
@@ -0,0 +1,302 @@
+#!/usr/bin/env python3
+"""
+Cleanup Manager for NotebookLM Skill
+Manages cleanup of skill data and browser state
+"""
+
+import shutil
+import argparse
+from pathlib import Path
+from typing import Dict, List, Any
+
+
+class CleanupManager:
+ """
+ Manages cleanup of NotebookLM skill data
+
+ Features:
+ - Preview what will be deleted
+ - Selective cleanup options
+ - Library preservation
+ - Safe deletion with confirmation
+ """
+
+ def __init__(self):
+ """Initialize the cleanup manager"""
+ # Skill directory paths
+ self.skill_dir = Path(__file__).parent.parent
+ self.data_dir = self.skill_dir / "data"
+
+ def get_cleanup_paths(self, preserve_library: bool = False) -> Dict[str, Any]:
+ """
+ Get paths that would be cleaned up
+
+ Args:
+ preserve_library: Keep library.json if True
+
+ Returns:
+ Dict with paths and sizes
+
+ Note: .venv is NEVER deleted - it's part of the skill infrastructure
+ """
+ paths = {
+ 'browser_state': [],
+ 'sessions': [],
+ 'library': [],
+ 'auth': [],
+ 'other': []
+ }
+
+ total_size = 0
+
+ if self.data_dir.exists():
+ # Browser state
+ browser_state_dir = self.data_dir / "browser_state"
+ if browser_state_dir.exists():
+ for item in browser_state_dir.iterdir():
+ size = self._get_size(item)
+ paths['browser_state'].append({
+ 'path': str(item),
+ 'size': size,
+ 'type': 'dir' if item.is_dir() else 'file'
+ })
+ total_size += size
+
+ # Sessions
+ sessions_file = self.data_dir / "sessions.json"
+ if sessions_file.exists():
+ size = sessions_file.stat().st_size
+ paths['sessions'].append({
+ 'path': str(sessions_file),
+ 'size': size,
+ 'type': 'file'
+ })
+ total_size += size
+
+ # Library (unless preserved)
+ if not preserve_library:
+ library_file = self.data_dir / "library.json"
+ if library_file.exists():
+ size = library_file.stat().st_size
+ paths['library'].append({
+ 'path': str(library_file),
+ 'size': size,
+ 'type': 'file'
+ })
+ total_size += size
+
+ # Auth info
+ auth_info = self.data_dir / "auth_info.json"
+ if auth_info.exists():
+ size = auth_info.stat().st_size
+ paths['auth'].append({
+ 'path': str(auth_info),
+ 'size': size,
+ 'type': 'file'
+ })
+ total_size += size
+
+ # Other files in data dir (but NEVER .venv!)
+ for item in self.data_dir.iterdir():
+ if item.name not in ['browser_state', 'sessions.json', 'library.json', 'auth_info.json']:
+ size = self._get_size(item)
+ paths['other'].append({
+ 'path': str(item),
+ 'size': size,
+ 'type': 'dir' if item.is_dir() else 'file'
+ })
+ total_size += size
+
+ return {
+ 'categories': paths,
+ 'total_size': total_size,
+ 'total_items': sum(len(items) for items in paths.values())
+ }
+
+ def _get_size(self, path: Path) -> int:
+ """Get size of file or directory in bytes"""
+ if path.is_file():
+ return path.stat().st_size
+ elif path.is_dir():
+ total = 0
+ try:
+ for item in path.rglob('*'):
+ if item.is_file():
+ total += item.stat().st_size
+ except Exception:
+ pass
+ return total
+ return 0
+
+ def _format_size(self, size: int) -> str:
+ """Format size in human-readable form"""
+ for unit in ['B', 'KB', 'MB', 'GB']:
+ if size < 1024:
+ return f"{size:.1f} {unit}"
+ size /= 1024
+ return f"{size:.1f} TB"
+
+ def perform_cleanup(
+ self,
+ preserve_library: bool = False,
+ dry_run: bool = False
+ ) -> Dict[str, Any]:
+ """
+ Perform the actual cleanup
+
+ Args:
+ preserve_library: Keep library.json if True
+ dry_run: Preview only, don't delete
+
+ Returns:
+ Dict with cleanup results
+ """
+ cleanup_data = self.get_cleanup_paths(preserve_library)
+ deleted_items = []
+ failed_items = []
+ deleted_size = 0
+
+ if dry_run:
+ return {
+ 'dry_run': True,
+ 'would_delete': cleanup_data['total_items'],
+ 'would_free': cleanup_data['total_size']
+ }
+
+ # Perform deletion
+ for category, items in cleanup_data['categories'].items():
+ for item_info in items:
+ path = Path(item_info['path'])
+ try:
+ if path.exists():
+ if path.is_dir():
+ shutil.rmtree(path)
+ else:
+ path.unlink()
+ deleted_items.append(str(path))
+ deleted_size += item_info['size']
+ print(f" ✅ Deleted: {path.name}")
+ except Exception as e:
+ failed_items.append({
+ 'path': str(path),
+ 'error': str(e)
+ })
+ print(f" ❌ Failed: {path.name} ({e})")
+
+ # Recreate browser_state dir if everything was deleted
+ if not preserve_library and not failed_items:
+ browser_state_dir = self.data_dir / "browser_state"
+ browser_state_dir.mkdir(parents=True, exist_ok=True)
+
+ return {
+ 'deleted_items': deleted_items,
+ 'failed_items': failed_items,
+ 'deleted_size': deleted_size,
+ 'deleted_count': len(deleted_items),
+ 'failed_count': len(failed_items)
+ }
+
+ def print_cleanup_preview(self, preserve_library: bool = False):
+ """Print a preview of what will be cleaned"""
+ data = self.get_cleanup_paths(preserve_library)
+
+ print("\n🔍 Cleanup Preview")
+ print("=" * 60)
+
+ for category, items in data['categories'].items():
+ if items:
+ print(f"\n📁 {category.replace('_', ' ').title()}:")
+ for item in items:
+ path = Path(item['path'])
+ size_str = self._format_size(item['size'])
+ type_icon = "📂" if item['type'] == 'dir' else "📄"
+ print(f" {type_icon} {path.name:<30} {size_str:>10}")
+
+ print("\n" + "=" * 60)
+ print(f"Total items: {data['total_items']}")
+ print(f"Total size: {self._format_size(data['total_size'])}")
+
+ if preserve_library:
+ print("\n📚 Library will be preserved")
+
+ print("\nThis preview shows what would be deleted.")
+ print("Use --confirm to actually perform the cleanup.")
+
+
+def main():
+ """Command-line interface for cleanup management"""
+ parser = argparse.ArgumentParser(
+ description='Clean up NotebookLM skill data',
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ # Preview what will be deleted
+ python cleanup_manager.py
+
+ # Perform cleanup (delete everything)
+ python cleanup_manager.py --confirm
+
+ # Cleanup but keep library
+ python cleanup_manager.py --confirm --preserve-library
+
+ # Force cleanup without preview
+ python cleanup_manager.py --confirm --force
+ """
+ )
+
+ parser.add_argument(
+ '--confirm',
+ action='store_true',
+ help='Actually perform the cleanup (without this, only preview)'
+ )
+
+ parser.add_argument(
+ '--preserve-library',
+ action='store_true',
+ help='Keep the notebook library (library.json)'
+ )
+
+ parser.add_argument(
+ '--force',
+ action='store_true',
+ help='Skip confirmation prompt'
+ )
+
+ args = parser.parse_args()
+
+ # Initialize manager
+ manager = CleanupManager()
+
+ if args.confirm:
+ # Show preview first unless forced
+ if not args.force:
+ manager.print_cleanup_preview(args.preserve_library)
+
+ print("\n⚠️ WARNING: This will delete the files shown above!")
+ print(" Note: .venv is preserved (part of skill infrastructure)")
+ response = input("Are you sure? (yes/no): ")
+
+ if response.lower() != 'yes':
+ print("Cleanup cancelled.")
+ return
+
+ # Perform cleanup
+ print("\n🗑️ Performing cleanup...")
+ result = manager.perform_cleanup(args.preserve_library, dry_run=False)
+
+ print(f"\n✅ Cleanup complete!")
+ print(f" Deleted: {result['deleted_count']} items")
+ print(f" Freed: {manager._format_size(result['deleted_size'])}")
+
+ if result['failed_count'] > 0:
+ print(f" ⚠️ Failed: {result['failed_count']} items")
+
+ else:
+ # Just show preview
+ manager.print_cleanup_preview(args.preserve_library)
+ print("\n💡 Note: Virtual environment (.venv) is never deleted")
+ print(" It's part of the skill infrastructure, not user data")
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/skills/blog-notebooklm/scripts/config.py b/skills/blog-notebooklm/scripts/config.py
new file mode 100644
index 0000000..4486b55
--- /dev/null
+++ b/skills/blog-notebooklm/scripts/config.py
@@ -0,0 +1,44 @@
+"""
+Configuration for NotebookLM Skill
+Centralizes constants, selectors, and paths
+"""
+
+from pathlib import Path
+
+# Paths
+SKILL_DIR = Path(__file__).parent.parent
+DATA_DIR = SKILL_DIR / "data"
+BROWSER_STATE_DIR = DATA_DIR / "browser_state"
+BROWSER_PROFILE_DIR = BROWSER_STATE_DIR / "browser_profile"
+STATE_FILE = BROWSER_STATE_DIR / "state.json"
+AUTH_INFO_FILE = DATA_DIR / "auth_info.json"
+LIBRARY_FILE = DATA_DIR / "library.json"
+
+# NotebookLM Selectors
+QUERY_INPUT_SELECTORS = [
+ "textarea.query-box-input", # Primary
+ 'textarea[aria-label="Feld für Anfragen"]', # Fallback German
+ 'textarea[aria-label="Input for queries"]', # Fallback English
+]
+
+RESPONSE_SELECTORS = [
+ ".to-user-container .message-text-content", # Primary
+ "[data-message-author='bot']",
+ "[data-message-author='assistant']",
+]
+
+# Browser Configuration
+BROWSER_ARGS = [
+ '--disable-blink-features=AutomationControlled', # Patches navigator.webdriver
+ '--disable-dev-shm-usage',
+ '--no-sandbox',
+ '--no-first-run',
+ '--no-default-browser-check'
+]
+
+USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
+
+# Timeouts
+LOGIN_TIMEOUT_MINUTES = 10
+QUERY_TIMEOUT_SECONDS = 120
+PAGE_LOAD_TIMEOUT = 30000
diff --git a/skills/blog-notebooklm/scripts/notebook_manager.py b/skills/blog-notebooklm/scripts/notebook_manager.py
new file mode 100644
index 0000000..e10e156
--- /dev/null
+++ b/skills/blog-notebooklm/scripts/notebook_manager.py
@@ -0,0 +1,410 @@
+#!/usr/bin/env python3
+"""
+Notebook Library Management for NotebookLM
+Manages a library of NotebookLM notebooks with metadata
+Based on the MCP server implementation
+"""
+
+import json
+import argparse
+import uuid
+import os
+from pathlib import Path
+from typing import Dict, List, Optional, Any
+from datetime import datetime
+
+
+class NotebookLibrary:
+ """Manages a collection of NotebookLM notebooks with metadata"""
+
+ def __init__(self):
+ """Initialize the notebook library"""
+ # Store data within the skill directory
+ skill_dir = Path(__file__).parent.parent
+ self.data_dir = skill_dir / "data"
+ self.data_dir.mkdir(parents=True, exist_ok=True)
+
+ self.library_file = self.data_dir / "library.json"
+ self.notebooks: Dict[str, Dict[str, Any]] = {}
+ self.active_notebook_id: Optional[str] = None
+
+ # Load existing library
+ self._load_library()
+
+ def _load_library(self):
+ """Load library from disk"""
+ if self.library_file.exists():
+ try:
+ with open(self.library_file, 'r') as f:
+ data = json.load(f)
+ self.notebooks = data.get('notebooks', {})
+ self.active_notebook_id = data.get('active_notebook_id')
+ print(f"📚 Loaded library with {len(self.notebooks)} notebooks")
+ except Exception as e:
+ print(f"⚠️ Error loading library: {e}")
+ self.notebooks = {}
+ self.active_notebook_id = None
+ else:
+ self._save_library()
+
+ def _save_library(self):
+ """Save library to disk"""
+ try:
+ data = {
+ 'notebooks': self.notebooks,
+ 'active_notebook_id': self.active_notebook_id,
+ 'updated_at': datetime.now().isoformat()
+ }
+ with open(self.library_file, 'w') as f:
+ json.dump(data, f, indent=2)
+ except Exception as e:
+ print(f"❌ Error saving library: {e}")
+
+ def add_notebook(
+ self,
+ url: str,
+ name: str,
+ description: str,
+ topics: List[str],
+ content_types: Optional[List[str]] = None,
+ use_cases: Optional[List[str]] = None,
+ tags: Optional[List[str]] = None
+ ) -> Dict[str, Any]:
+ """
+ Add a new notebook to the library
+
+ Args:
+ url: NotebookLM notebook URL
+ name: Display name for the notebook
+ description: What's in this notebook
+ topics: Topics covered
+ content_types: Types of content (optional)
+ use_cases: When to use this notebook (optional)
+ tags: Additional tags for organization (optional)
+
+ Returns:
+ The created notebook object
+ """
+ # Generate ID from name
+ notebook_id = name.lower().replace(' ', '-').replace('_', '-')
+
+ # Check for duplicates
+ if notebook_id in self.notebooks:
+ raise ValueError(f"Notebook with ID '{notebook_id}' already exists")
+
+ # Create notebook object
+ notebook = {
+ 'id': notebook_id,
+ 'url': url,
+ 'name': name,
+ 'description': description,
+ 'topics': topics,
+ 'content_types': content_types or [],
+ 'use_cases': use_cases or [],
+ 'tags': tags or [],
+ 'created_at': datetime.now().isoformat(),
+ 'updated_at': datetime.now().isoformat(),
+ 'use_count': 0,
+ 'last_used': None
+ }
+
+ # Add to library
+ self.notebooks[notebook_id] = notebook
+
+ # Set as active if it's the first notebook
+ if len(self.notebooks) == 1:
+ self.active_notebook_id = notebook_id
+
+ self._save_library()
+
+ print(f"✅ Added notebook: {name} ({notebook_id})")
+ return notebook
+
+ def remove_notebook(self, notebook_id: str) -> bool:
+ """
+ Remove a notebook from the library
+
+ Args:
+ notebook_id: ID of notebook to remove
+
+ Returns:
+ True if removed, False if not found
+ """
+ if notebook_id in self.notebooks:
+ del self.notebooks[notebook_id]
+
+ # Clear active if it was removed
+ if self.active_notebook_id == notebook_id:
+ self.active_notebook_id = None
+ # Set new active if there are other notebooks
+ if self.notebooks:
+ self.active_notebook_id = list(self.notebooks.keys())[0]
+
+ self._save_library()
+ print(f"✅ Removed notebook: {notebook_id}")
+ return True
+
+ print(f"⚠️ Notebook not found: {notebook_id}")
+ return False
+
+ def update_notebook(
+ self,
+ notebook_id: str,
+ name: Optional[str] = None,
+ description: Optional[str] = None,
+ topics: Optional[List[str]] = None,
+ content_types: Optional[List[str]] = None,
+ use_cases: Optional[List[str]] = None,
+ tags: Optional[List[str]] = None,
+ url: Optional[str] = None
+ ) -> Dict[str, Any]:
+ """
+ Update notebook metadata
+
+ Args:
+ notebook_id: ID of notebook to update
+ Other args: Fields to update (None = keep existing)
+
+ Returns:
+ Updated notebook object
+ """
+ if notebook_id not in self.notebooks:
+ raise ValueError(f"Notebook not found: {notebook_id}")
+
+ notebook = self.notebooks[notebook_id]
+
+ # Update fields if provided
+ if name is not None:
+ notebook['name'] = name
+ if description is not None:
+ notebook['description'] = description
+ if topics is not None:
+ notebook['topics'] = topics
+ if content_types is not None:
+ notebook['content_types'] = content_types
+ if use_cases is not None:
+ notebook['use_cases'] = use_cases
+ if tags is not None:
+ notebook['tags'] = tags
+ if url is not None:
+ notebook['url'] = url
+
+ notebook['updated_at'] = datetime.now().isoformat()
+
+ self._save_library()
+ print(f"✅ Updated notebook: {notebook['name']}")
+ return notebook
+
+ def get_notebook(self, notebook_id: str) -> Optional[Dict[str, Any]]:
+ """Get a specific notebook by ID"""
+ return self.notebooks.get(notebook_id)
+
+ def list_notebooks(self) -> List[Dict[str, Any]]:
+ """List all notebooks in the library"""
+ return list(self.notebooks.values())
+
+ def search_notebooks(self, query: str) -> List[Dict[str, Any]]:
+ """
+ Search notebooks by query
+
+ Args:
+ query: Search query (searches name, description, topics, tags)
+
+ Returns:
+ List of matching notebooks
+ """
+ query_lower = query.lower()
+ results = []
+
+ for notebook in self.notebooks.values():
+ # Search in various fields
+ searchable = [
+ notebook['name'].lower(),
+ notebook['description'].lower(),
+ ' '.join(notebook['topics']).lower(),
+ ' '.join(notebook['tags']).lower(),
+ ' '.join(notebook.get('use_cases', [])).lower()
+ ]
+
+ if any(query_lower in field for field in searchable):
+ results.append(notebook)
+
+ return results
+
+ def select_notebook(self, notebook_id: str) -> Dict[str, Any]:
+ """
+ Set a notebook as active
+
+ Args:
+ notebook_id: ID of notebook to activate
+
+ Returns:
+ The activated notebook
+ """
+ if notebook_id not in self.notebooks:
+ raise ValueError(f"Notebook not found: {notebook_id}")
+
+ self.active_notebook_id = notebook_id
+ self._save_library()
+
+ notebook = self.notebooks[notebook_id]
+ print(f"✅ Activated notebook: {notebook['name']}")
+ return notebook
+
+ def get_active_notebook(self) -> Optional[Dict[str, Any]]:
+ """Get the currently active notebook"""
+ if self.active_notebook_id:
+ return self.notebooks.get(self.active_notebook_id)
+ return None
+
+ def increment_use_count(self, notebook_id: str) -> Dict[str, Any]:
+ """
+ Increment usage counter for a notebook
+
+ Args:
+ notebook_id: ID of notebook that was used
+
+ Returns:
+ Updated notebook
+ """
+ if notebook_id not in self.notebooks:
+ raise ValueError(f"Notebook not found: {notebook_id}")
+
+ notebook = self.notebooks[notebook_id]
+ notebook['use_count'] += 1
+ notebook['last_used'] = datetime.now().isoformat()
+
+ self._save_library()
+ return notebook
+
+ def get_stats(self) -> Dict[str, Any]:
+ """Get library statistics"""
+ total_notebooks = len(self.notebooks)
+ total_topics = set()
+ total_use_count = 0
+
+ for notebook in self.notebooks.values():
+ total_topics.update(notebook['topics'])
+ total_use_count += notebook['use_count']
+
+ # Find most used
+ most_used = None
+ if self.notebooks:
+ most_used = max(
+ self.notebooks.values(),
+ key=lambda n: n['use_count']
+ )
+
+ return {
+ 'total_notebooks': total_notebooks,
+ 'total_topics': len(total_topics),
+ 'total_use_count': total_use_count,
+ 'active_notebook': self.get_active_notebook(),
+ 'most_used_notebook': most_used,
+ 'library_path': str(self.library_file)
+ }
+
+
+def main():
+ """Command-line interface for notebook management"""
+ parser = argparse.ArgumentParser(description='Manage NotebookLM library')
+
+ subparsers = parser.add_subparsers(dest='command', help='Commands')
+
+ # Add command
+ add_parser = subparsers.add_parser('add', help='Add a notebook')
+ add_parser.add_argument('--url', required=True, help='NotebookLM URL')
+ add_parser.add_argument('--name', required=True, help='Display name')
+ add_parser.add_argument('--description', required=True, help='Description')
+ add_parser.add_argument('--topics', required=True, help='Comma-separated topics')
+ add_parser.add_argument('--use-cases', help='Comma-separated use cases')
+ add_parser.add_argument('--tags', help='Comma-separated tags')
+
+ # List command
+ subparsers.add_parser('list', help='List all notebooks')
+
+ # Search command
+ search_parser = subparsers.add_parser('search', help='Search notebooks')
+ search_parser.add_argument('--query', required=True, help='Search query')
+
+ # Activate command
+ activate_parser = subparsers.add_parser('activate', help='Set active notebook')
+ activate_parser.add_argument('--id', required=True, help='Notebook ID')
+
+ # Remove command
+ remove_parser = subparsers.add_parser('remove', help='Remove a notebook')
+ remove_parser.add_argument('--id', required=True, help='Notebook ID')
+
+ # Stats command
+ subparsers.add_parser('stats', help='Show library statistics')
+
+ args = parser.parse_args()
+
+ # Initialize library
+ library = NotebookLibrary()
+
+ # Execute command
+ if args.command == 'add':
+ topics = [t.strip() for t in args.topics.split(',')]
+ use_cases = [u.strip() for u in args.use_cases.split(',')] if args.use_cases else None
+ tags = [t.strip() for t in args.tags.split(',')] if args.tags else None
+
+ notebook = library.add_notebook(
+ url=args.url,
+ name=args.name,
+ description=args.description,
+ topics=topics,
+ use_cases=use_cases,
+ tags=tags
+ )
+ print(json.dumps(notebook, indent=2))
+
+ elif args.command == 'list':
+ notebooks = library.list_notebooks()
+ if notebooks:
+ print("\n📚 Notebook Library:")
+ for notebook in notebooks:
+ active = " [ACTIVE]" if notebook['id'] == library.active_notebook_id else ""
+ print(f"\n 📓 {notebook['name']}{active}")
+ print(f" ID: {notebook['id']}")
+ print(f" Topics: {', '.join(notebook['topics'])}")
+ print(f" Uses: {notebook['use_count']}")
+ else:
+ print("📚 Library is empty. Add notebooks with: notebook_manager.py add")
+
+ elif args.command == 'search':
+ results = library.search_notebooks(args.query)
+ if results:
+ print(f"\n🔍 Found {len(results)} notebooks:")
+ for notebook in results:
+ print(f"\n 📓 {notebook['name']} ({notebook['id']})")
+ print(f" {notebook['description']}")
+ else:
+ print(f"🔍 No notebooks found for: {args.query}")
+
+ elif args.command == 'activate':
+ notebook = library.select_notebook(args.id)
+ print(f"Now using: {notebook['name']}")
+
+ elif args.command == 'remove':
+ if library.remove_notebook(args.id):
+ print("Notebook removed from library")
+
+ elif args.command == 'stats':
+ stats = library.get_stats()
+ print("\n📊 Library Statistics:")
+ print(f" Total notebooks: {stats['total_notebooks']}")
+ print(f" Total topics: {stats['total_topics']}")
+ print(f" Total uses: {stats['total_use_count']}")
+ if stats['active_notebook']:
+ print(f" Active: {stats['active_notebook']['name']}")
+ if stats['most_used_notebook']:
+ print(f" Most used: {stats['most_used_notebook']['name']} ({stats['most_used_notebook']['use_count']} uses)")
+ print(f" Library path: {stats['library_path']}")
+
+ else:
+ parser.print_help()
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/skills/blog-notebooklm/scripts/requirements.txt b/skills/blog-notebooklm/scripts/requirements.txt
new file mode 100644
index 0000000..6e38008
--- /dev/null
+++ b/skills/blog-notebooklm/scripts/requirements.txt
@@ -0,0 +1,10 @@
+# NotebookLM Skill Dependencies
+# These will be installed in the skill's local .venv
+
+# Core browser automation with anti-detection
+# Note: After installation, run: patchright install chrome
+# (Chrome is required, not Chromium, for cross-platform reliability)
+patchright==1.55.2
+
+# Environment management
+python-dotenv==1.0.0
\ No newline at end of file
diff --git a/skills/blog-notebooklm/scripts/run.py b/skills/blog-notebooklm/scripts/run.py
new file mode 100644
index 0000000..7c47a92
--- /dev/null
+++ b/skills/blog-notebooklm/scripts/run.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python3
+"""
+Universal runner for NotebookLM skill scripts
+Ensures all scripts run with the correct virtual environment
+"""
+
+import os
+import sys
+import subprocess
+from pathlib import Path
+
+
+def get_venv_python():
+ """Get the virtual environment Python executable"""
+ skill_dir = Path(__file__).parent.parent
+ venv_dir = skill_dir / ".venv"
+
+ if os.name == 'nt': # Windows
+ venv_python = venv_dir / "Scripts" / "python.exe"
+ else: # Unix/Linux/Mac
+ venv_python = venv_dir / "bin" / "python"
+
+ return venv_python
+
+
+def ensure_venv():
+ """Ensure virtual environment exists"""
+ skill_dir = Path(__file__).parent.parent
+ venv_dir = skill_dir / ".venv"
+ setup_script = skill_dir / "scripts" / "setup_environment.py"
+
+ # Check if venv exists
+ if not venv_dir.exists():
+ print("🔧 First-time setup: Creating virtual environment...")
+ print(" This may take a minute...")
+
+ # Run setup with system Python
+ result = subprocess.run([sys.executable, str(setup_script)])
+ if result.returncode != 0:
+ print("❌ Failed to set up environment")
+ sys.exit(1)
+
+ print("✅ Environment ready!")
+
+ return get_venv_python()
+
+
+def main():
+ """Main runner"""
+ if len(sys.argv) < 2:
+ print("Usage: python run.py <script_name> [args...]")
+ print("\nAvailable scripts:")
+ print(" ask_question.py - Query NotebookLM")
+ print(" notebook_manager.py - Manage notebook library")
+ print(" session_manager.py - Manage sessions")
+ print(" auth_manager.py - Handle authentication")
+ print(" cleanup_manager.py - Clean up skill data")
+ sys.exit(1)
+
+ script_name = sys.argv[1]
+ script_args = sys.argv[2:]
+
+ # Handle both "scripts/script.py" and "script.py" formats
+ if script_name.startswith('scripts/'):
+ # Remove the scripts/ prefix if provided
+ script_name = script_name[8:] # len('scripts/') = 8
+
+ # Ensure .py extension
+ if not script_name.endswith('.py'):
+ script_name += '.py'
+
+ # Get script path
+ skill_dir = Path(__file__).parent.parent
+ script_path = skill_dir / "scripts" / script_name
+
+ if not script_path.exists():
+ print(f"❌ Script not found: {script_name}")
+ print(f" Working directory: {Path.cwd()}")
+ print(f" Skill directory: {skill_dir}")
+ print(f" Looked for: {script_path}")
+ sys.exit(1)
+
+ # Ensure venv exists and get Python executable
+ venv_python = ensure_venv()
+
+ # Build command
+ cmd = [str(venv_python), str(script_path)] + script_args
+
+ # Run the script
+ try:
+ result = subprocess.run(cmd)
+ sys.exit(result.returncode)
+ except KeyboardInterrupt:
+ print("\n⚠️ Interrupted by user")
+ sys.exit(130)
+ except Exception as e:
+ print(f"❌ Error: {e}")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/skills/blog-notebooklm/scripts/setup_environment.py b/skills/blog-notebooklm/scripts/setup_environment.py
new file mode 100644
index 0000000..a4167d0
--- /dev/null
+++ b/skills/blog-notebooklm/scripts/setup_environment.py
@@ -0,0 +1,204 @@
+#!/usr/bin/env python3
+"""
+Environment Setup for NotebookLM Skill
+Manages virtual environment and dependencies automatically
+"""
+
+import os
+import sys
+import subprocess
+import venv
+from pathlib import Path
+
+
+class SkillEnvironment:
+ """Manages skill-specific virtual environment"""
+
+ def __init__(self):
+ # Skill directory paths
+ self.skill_dir = Path(__file__).parent.parent
+ self.venv_dir = self.skill_dir / ".venv"
+ self.requirements_file = self.skill_dir / "requirements.txt"
+
+ # Python executable in venv
+ if os.name == 'nt': # Windows
+ self.venv_python = self.venv_dir / "Scripts" / "python.exe"
+ self.venv_pip = self.venv_dir / "Scripts" / "pip.exe"
+ else: # Unix/Linux/Mac
+ self.venv_python = self.venv_dir / "bin" / "python"
+ self.venv_pip = self.venv_dir / "bin" / "pip"
+
+ def ensure_venv(self) -> bool:
+ """Ensure virtual environment exists and is set up"""
+
+ # Check if we're already in the correct venv
+ if self.is_in_skill_venv():
+ print("✅ Already running in skill virtual environment")
+ return True
+
+ # Create venv if it doesn't exist
+ if not self.venv_dir.exists():
+ print(f"🔧 Creating virtual environment in {self.venv_dir.name}/")
+ try:
+ venv.create(self.venv_dir, with_pip=True)
+ print("✅ Virtual environment created")
+ except Exception as e:
+ print(f"❌ Failed to create venv: {e}")
+ return False
+
+ # Install/update dependencies
+ if self.requirements_file.exists():
+ print("📦 Installing dependencies...")
+ try:
+ # Upgrade pip first
+ subprocess.run(
+ [str(self.venv_pip), "install", "--upgrade", "pip"],
+ check=True,
+ capture_output=True,
+ text=True
+ )
+
+ # Install requirements
+ result = subprocess.run(
+ [str(self.venv_pip), "install", "-r", str(self.requirements_file)],
+ check=True,
+ capture_output=True,
+ text=True
+ )
+ print("✅ Dependencies installed")
+
+ # Install Chrome for Patchright (not Chromium!)
+ # Using real Chrome ensures cross-platform reliability and consistent browser fingerprinting
+ # See: https://github.com/Kaliiiiiiiiii-Vinyzu/patchright-python#anti-detection
+ print("🌐 Installing Google Chrome for Patchright...")
+ try:
+ subprocess.run(
+ [str(self.venv_python), "-m", "patchright", "install", "chrome"],
+ check=True,
+ capture_output=True,
+ text=True
+ )
+ print("✅ Chrome installed")
+ except subprocess.CalledProcessError as e:
+ print(f"⚠️ Warning: Failed to install Chrome: {e}")
+ print(" You may need to run manually: python -m patchright install chrome")
+ print(" Chrome is required (not Chromium) for reliability!")
+
+ return True
+ except subprocess.CalledProcessError as e:
+ print(f"❌ Failed to install dependencies: {e}")
+ print(f" Output: {e.output if hasattr(e, 'output') else 'No output'}")
+ return False
+ else:
+ print("⚠️ No requirements.txt found, skipping dependency installation")
+ return True
+
+ def is_in_skill_venv(self) -> bool:
+ """Check if we're already running in the skill's venv"""
+ if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
+ # We're in a venv, check if it's ours
+ venv_path = Path(sys.prefix)
+ return venv_path == self.venv_dir
+ return False
+
+ def get_python_executable(self) -> str:
+ """Get the correct Python executable to use"""
+ if self.venv_python.exists():
+ return str(self.venv_python)
+ return sys.executable
+
+ def run_script(self, script_name: str, args: list = None) -> int:
+ """Run a script with the virtual environment"""
+ script_path = self.skill_dir / "scripts" / script_name
+
+ if not script_path.exists():
+ print(f"❌ Script not found: {script_path}")
+ return 1
+
+ # Ensure venv is set up
+ if not self.ensure_venv():
+ print("❌ Failed to set up environment")
+ return 1
+
+ # Build command
+ cmd = [str(self.venv_python), str(script_path)]
+ if args:
+ cmd.extend(args)
+
+ print(f"🚀 Running: {script_name} with venv Python")
+
+ try:
+ # Run the script with venv Python
+ result = subprocess.run(cmd)
+ return result.returncode
+ except Exception as e:
+ print(f"❌ Failed to run script: {e}")
+ return 1
+
+ def activate_instructions(self) -> str:
+ """Get instructions for manual activation"""
+ if os.name == 'nt':
+ activate = self.venv_dir / "Scripts" / "activate.bat"
+ return f"Run: {activate}"
+ else:
+ activate = self.venv_dir / "bin" / "activate"
+ return f"Run: source {activate}"
+
+
+def main():
+ """Main entry point for environment setup"""
+ import argparse
+
+ parser = argparse.ArgumentParser(
+ description='Setup NotebookLM skill environment'
+ )
+
+ parser.add_argument(
+ '--check',
+ action='store_true',
+ help='Check if environment is set up'
+ )
+
+ parser.add_argument(
+ '--run',
+ help='Run a script with the venv (e.g., --run ask_question.py)'
+ )
+
+ parser.add_argument(
+ 'args',
+ nargs='*',
+ help='Arguments to pass to the script'
+ )
+
+ args = parser.parse_args()
+
+ env = SkillEnvironment()
+
+ if args.check:
+ if env.venv_dir.exists():
+ print(f"✅ Virtual environment exists: {env.venv_dir}")
+ print(f" Python: {env.get_python_executable()}")
+ print(f" To activate manually: {env.activate_instructions()}")
+ else:
+ print(f"❌ No virtual environment found")
+ print(f" Run setup_environment.py to create it")
+ return
+
+ if args.run:
+ # Run a script with venv
+ return env.run_script(args.run, args.args)
+
+ # Default: ensure environment is set up
+ if env.ensure_venv():
+ print("\n✅ Environment ready!")
+ print(f" Virtual env: {env.venv_dir}")
+ print(f" Python: {env.get_python_executable()}")
+ print(f"\nTo activate manually: {env.activate_instructions()}")
+ print(f"Or run scripts directly: python setup_environment.py --run script_name.py")
+ else:
+ print("\n❌ Environment setup failed")
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main() or 0)
\ No newline at end of file
diff --git a/skills/blog-write/SKILL.md b/skills/blog-write/SKILL.md
index bf4d1d9..1d40d55 100644
--- a/skills/blog-write/SKILL.md
+++ b/skills/blog-write/SKILL.md
@@ -103,6 +103,11 @@ Spawn a `blog-researcher` agent (or do inline research with WebSearch):
- If stock photo results are insufficient (< 3 good matches) or topic is too niche
- Generate custom hero image and/or inline illustrations via `blog-image` sub-skill
- Stock photos remain default - AI generation supplements, never replaces
+6. **NotebookLM research** (optional, if user has relevant notebooks):
+ - If the user mentions a NotebookLM notebook or the topic aligns with a configured notebook
+ - Query via `blog-notebooklm` for source-grounded data from user-uploaded documents
+ - Treat NotebookLM responses as Tier 1 sources (user's own primary documents)
+ - Falls back silently if not configured or not authenticated
### Phase 3: Outline Generation
@@ -471,4 +476,5 @@ Present the completed article with a summary:
- Resolve [INTERNAL-LINK] placeholders with actual URLs
- Add internal links to your existing content
- Run `/blog analyze <file>` to verify quality score
+- Generate audio narration: `/blog audio generate <file>` (optional)
```
diff --git a/skills/blog/SKILL.md b/skills/blog/SKILL.md
index a934c8c..7d952c6 100644
--- a/skills/blog/SKILL.md
+++ b/skills/blog/SKILL.md
@@ -1,7 +1,7 @@
---
name: blog
description: >
- Full-lifecycle blog engine with 17 commands, 12 content templates, 5-category
+ Full-lifecycle blog engine with 20 commands, 12 content templates, 5-category
100-point scoring, and 4 specialized agents. Optimized for Google rankings
(December 2025 Core Update, E-E-A-T) and AI citations (GEO/AEO). Writes,
rewrites, analyzes, outlines, audits, and repurposes blog content with
@@ -18,9 +18,9 @@ license: MIT
compatibility: Requires Claude Code and Python 3.11+ for quality scoring
metadata:
author: AgriciDaniel
- version: "1.5.0"
+ version: "1.6.0"
user-invokable: true
-argument-hint: "[write|rewrite|analyze|brief|calendar|cannibalization|strategy|outline|seo-check|schema|repurpose|geo|image|audit|factcheck|persona|taxonomy] [topic-or-file]"
+argument-hint: "[write|rewrite|analyze|brief|calendar|cannibalization|strategy|outline|seo-check|schema|repurpose|geo|image|audit|factcheck|persona|taxonomy|notebooklm|audio] [topic-or-file]"
allowed-tools:
- Read
- Write
@@ -61,6 +61,8 @@ Perplexity, Google AI Overviews, Gemini).
| `/blog image [generate\|edit\|setup]` | AI image generation and editing via Gemini |
| `/blog persona [create\|list\|use\|show]` | Manage writing personas and voice profiles |
| `/blog taxonomy [suggest\|sync\|audit]` | Tag/category management across CMS platforms |
+| `/blog notebooklm <question>` | Query NotebookLM for source-grounded research |
+| `/blog audio [generate\|voices\|setup]` | Generate audio narration of blog posts |
| `/blog update <file>` | Update existing post with fresh stats (routes to rewrite) |
## Orchestration Logic
@@ -87,6 +89,8 @@ Perplexity, Google AI Overviews, Gemini).
- `geo` / `aeo` / `citation` → `blog-geo` (AI citation audit)
- `audit` / `health` → `blog-audit` (site-wide assessment)
- `image` → `blog-image` (AI image generation and editing)
+ - `notebooklm` / `notebook` / `query-notebook` → `blog-notebooklm` (source-grounded notebook queries)
+ - `audio` / `narrate` / `tts` → `blog-audio` (audio narration generation)
- `update` → `blog-rewrite` (with freshness-update mode)
### Platform Detection
@@ -216,6 +220,8 @@ Templates are in `templates/` and contain section structure, markers, and checkl
| `blog-image` | AI image generation and editing for blog content via Gemini MCP |
| `blog-persona` | Writing persona management with NNGroup framework |
| `blog-taxonomy` | CMS taxonomy management (WordPress, Shopify, Ghost, Strapi, Sanity) |
+| `blog-notebooklm` | Query Google NotebookLM for source-grounded research from user documents |
+| `blog-audio` | Generate audio narration with Gemini TTS (summary/full/dialogue modes, 30 voices) |
## Agents
@@ -271,6 +277,15 @@ callable internally by `blog-write` and `blog-rewrite` when AI-generated images
are needed (requires nanobanana-mcp configured). Falls back gracefully when MCP
is not available.
+The `blog-notebooklm` sub-skill is both user-invocable (`/blog notebooklm ask`)
+and callable internally by `blog-write` and `blog-researcher` for Tier 1 research
+data from user-uploaded documents. Falls back gracefully when not authenticated.
+
+The `blog-audio` sub-skill is user-invocable (`/blog audio generate`) and can be
+offered as an optional final step after blog-write completes. Generates summary,
+full-article, or two-speaker dialogue narration via Gemini TTS. Falls back
+gracefully when `GOOGLE_AI_API_KEY` is not configured.
+
## Integration
Chart generation is built-in - no external dependencies required for full functionality.