Spaces:
Sleeping
Sleeping
File size: 20,352 Bytes
7c87115 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | """Main CLI application for NotebookLM Tools."""
from typing import Optional
import typer
from rich.console import Console
from notebooklm_tools import __version__
from notebooklm_tools.cli.commands.chat import app as chat_app
from notebooklm_tools.cli.commands.notebook import app as notebook_app
from notebooklm_tools.cli.commands.note import app as note_app
from notebooklm_tools.cli.commands.research import app as research_app
from notebooklm_tools.cli.commands.source import app as source_app
from notebooklm_tools.cli.commands.alias import app as alias_app
from notebooklm_tools.cli.commands.config import app as config_app
from notebooklm_tools.cli.commands.skill import app as skill_app
from notebooklm_tools.cli.commands.setup import app as setup_app
from notebooklm_tools.cli.commands.doctor import app as doctor_app
from notebooklm_tools.cli.commands.studio import (
app as studio_app,
audio_app,
data_table_app,
flashcards_app,
infographic_app,
mindmap_app,
quiz_app,
report_app,
slides_app,
video_app,
)
from notebooklm_tools.cli.commands.download import app as download_app
from notebooklm_tools.cli.commands.share import app as share_app
from notebooklm_tools.cli.commands.export import app as export_app
from notebooklm_tools.cli.commands.verbs import (
create_app,
list_app,
get_app,
delete_app,
add_app,
rename_app,
status_app,
describe_app,
query_app,
sync_app,
content_app,
stale_app,
configure_app,
set_app,
show_app,
install_app,
uninstall_app,
update_app,
)
console = Console()
# Main application
app = typer.Typer(
name="nlm",
help="NotebookLM Tools - Unified CLI for Google NotebookLM",
no_args_is_help=True,
rich_markup_mode="rich",
)
# =============================================================================
# LOGIN app with nested profile commands
# =============================================================================
login_app = typer.Typer(
help="Authentication and profile management",
rich_markup_mode="rich",
)
# Profile management subcommands
profile_app = typer.Typer(
help="Manage authentication profiles",
rich_markup_mode="rich",
no_args_is_help=True,
)
@login_app.callback(invoke_without_command=True)
def login_callback(
ctx: typer.Context,
manual: bool = typer.Option(
False, "--manual", "-m",
help="Manually provide cookies from a file",
),
check: bool = typer.Option(
False, "--check",
help="Only check if current auth is valid",
),
profile: Optional[str] = typer.Option(
None, "--profile", "-p",
help="Profile name (uses config default if not specified)",
),
cookie_file: Optional[str] = typer.Option(
None, "--file", "-f",
help="Path to file containing cookies (for manual mode)",
),
provider: str = typer.Option(
"builtin", "--provider",
help="Auth provider: builtin (default) or openclaw",
),
cdp_url: str = typer.Option(
"http://127.0.0.1:18800", "--cdp-url",
help="CDP endpoint URL for external provider mode",
),
) -> None:
"""
Authenticate with NotebookLM.
Default: Uses Chrome DevTools Protocol to extract cookies automatically.
Use --manual to import cookies from a file.
Use --check to validate existing credentials.
Use --provider openclaw --cdp-url <url> to read auth from an existing
OpenClaw-managed browser CDP endpoint.
"""
from notebooklm_tools.core.auth import AuthManager
from notebooklm_tools.core.exceptions import NLMError
from notebooklm_tools.utils.config import get_config
# If a subcommand is invoked, don't run login logic
if ctx.invoked_subcommand is not None:
return
# Use config default if no profile specified
if profile is None:
profile = get_config().auth.default_profile
auth = AuthManager(profile)
if check:
# Check existing auth by making a real API call
try:
from notebooklm_tools.core.client import NotebookLMClient
p = auth.load_profile()
console.print(f"[dim]Checking credentials for profile: {p.name}...[/dim]")
# Actually test the API using profile's credentials
with NotebookLMClient(
cookies=p.cookies,
csrf_token=p.csrf_token or "",
session_id=p.session_id or "",
) as client:
notebooks = client.list_notebooks()
# Success! Update last validated
auth.save_profile(
cookies=p.cookies,
csrf_token=p.csrf_token,
session_id=p.session_id,
email=p.email,
)
console.print(f"[green]β[/green] Authentication valid!")
console.print(f" Profile: {p.name}")
console.print(f" Notebooks found: {len(notebooks)}")
if p.email:
console.print(f" Account: {p.email}")
except NLMError as e:
console.print(f"[red]β[/red] Authentication failed: {e.message}")
if e.hint:
console.print(f"[dim]{e.hint}[/dim]")
raise typer.Exit(2)
return
if manual:
# Manual mode - read from file
if not cookie_file:
cookie_file = typer.prompt(
"Enter path to file containing cookies",
default="~/.nlm/cookies.txt",
)
try:
profile_obj = auth.login_with_file(cookie_file)
console.print(f"[green]β[/green] Successfully authenticated!")
console.print(f" Profile saved: {profile}")
console.print(f" Credentials saved to: {auth.profile_dir}")
except NLMError as e:
console.print(f"[red]Error:[/red] {e.message}")
if e.hint:
console.print(f"\n[dim]Hint: {e.hint}[/dim]")
raise typer.Exit(1)
return
provider = (provider or "builtin").strip().lower()
if provider not in {"builtin", "openclaw"}:
console.print(f"[red]Error:[/red] Unsupported provider '{provider}'")
console.print("[dim]Supported values: builtin, openclaw[/dim]")
raise typer.Exit(1)
try:
from notebooklm_tools.utils.cdp import (
extract_cookies_via_cdp,
extract_cookies_via_existing_cdp,
terminate_chrome,
)
launched_local_chrome = False
if provider == "openclaw":
console.print("[bold]Using external CDP authentication provider[/bold]")
console.print(f"[dim]Provider: openclaw | CDP: {cdp_url}[/dim]\n")
result = extract_cookies_via_existing_cdp(
cdp_url=cdp_url,
wait_for_login=True,
login_timeout=300,
)
else:
# Default: builtin CDP mode - managed Chrome profile
console.print("[bold]Launching Chrome for authentication...[/bold]")
console.print("[dim]Using Chrome DevTools Protocol[/dim]\n")
from notebooklm_tools.utils.config import check_migration_sources, run_migration, get_storage_dir
# Check if we need to migrate from legacy packages
# IMPORTANT: Don't use get_chrome_profile_dir() here as it creates the directory,
# which would prevent migration from running
chrome_profile = get_storage_dir() / "chrome-profile"
profile_exists = chrome_profile.exists() and (
(chrome_profile / "Default").exists() or (chrome_profile / "Local State").exists()
)
if not profile_exists:
sources = check_migration_sources()
if sources["chrome_profiles"]:
console.print("[yellow]Found Chrome profile from legacy installation![/yellow]")
for src in sources["chrome_profiles"]:
console.print(f" [dim]{src}[/dim]")
console.print("[dim]Migrating to new location...[/dim]")
actions = run_migration(dry_run=False)
for action in actions:
console.print(f" [green]β[/green] {action}")
console.print()
console.print("Starting Chrome...")
result = extract_cookies_via_cdp(
auto_launch=True,
wait_for_login=True,
login_timeout=300,
profile_name=profile,
)
launched_local_chrome = True
cookies = result["cookies"]
csrf_token = result.get("csrf_token", "")
session_id = result.get("session_id", "")
email = result.get("email", "")
# Save to profile
auth.save_profile(
cookies=cookies,
csrf_token=csrf_token,
session_id=session_id,
email=email,
)
# Close builtin auth Chrome to release profile lock (enables headless auth later)
if launched_local_chrome:
console.print("[dim]Closing Chrome...[/dim]")
terminate_chrome()
console.print(f"\n[green]β[/green] Successfully authenticated!")
console.print(f" Profile: {profile}")
console.print(f" Provider: {provider}")
console.print(f" Cookies: {len(cookies)} extracted")
console.print(f" CSRF Token: {'Yes' if csrf_token else 'No (will be auto-extracted)'}")
if email:
console.print(f" Account: {email}")
console.print(f" Credentials saved to: {auth.profile_dir}")
except NLMError as e:
console.print(f"\n[red]Error:[/red] {e.message}")
if e.hint:
console.print(f"\n[dim]Hint: {e.hint}[/dim]")
raise typer.Exit(1)
@profile_app.command("list")
def profile_list() -> None:
"""List all authentication profiles."""
from notebooklm_tools.core.auth import AuthManager
profiles = AuthManager.list_profiles()
if not profiles:
console.print("[dim]No profiles found.[/dim]")
console.print("\nRun 'nlm login' to create a profile.")
return
console.print("[bold]Available profiles:[/bold]")
for name in profiles:
try:
auth = AuthManager(name)
p = auth.load_profile()
email = p.email or "Unknown"
console.print(f" [cyan]{name}[/cyan]: {email}")
except Exception:
console.print(f" [cyan]{name}[/cyan]: [dim](invalid)[/dim]")
@profile_app.command("delete")
def profile_delete(
profile: str = typer.Argument(..., help="Profile name to delete"),
confirm: bool = typer.Option(
False, "--confirm", "-y",
help="Skip confirmation prompt",
),
) -> None:
"""Delete a profile and its credentials."""
from notebooklm_tools.core.auth import AuthManager
auth = AuthManager(profile)
if not auth.profile_exists():
console.print(f"[red]Error:[/red] Profile '{profile}' not found")
raise typer.Exit(1)
if not confirm:
typer.confirm(
f"Are you sure you want to delete profile '{profile}'?",
abort=True,
)
auth.delete_profile()
console.print(f"[green]β[/green] Deleted profile: {profile}")
@profile_app.command("rename")
def profile_rename(
old_name: str = typer.Argument(..., help="Current profile name"),
new_name: str = typer.Argument(..., help="New profile name"),
) -> None:
"""Rename an authentication profile."""
from notebooklm_tools.core.auth import AuthManager
from notebooklm_tools.core.exceptions import NLMError
# Check if old profile exists
old_auth = AuthManager(old_name)
if not old_auth.profile_exists():
console.print(f"[red]Error:[/red] Profile '{old_name}' not found")
raise typer.Exit(1)
# Check if new profile name already exists
new_auth = AuthManager(new_name)
if new_auth.profile_exists():
console.print(f"[red]Error:[/red] Profile '{new_name}' already exists")
raise typer.Exit(1)
try:
# Load old profile data
profile_data = old_auth.load_profile()
# Save with new name
new_auth.save_profile(
cookies=profile_data.cookies,
csrf_token=profile_data.csrf_token,
session_id=profile_data.session_id,
email=profile_data.email,
)
# Delete old profile
old_auth.delete_profile()
console.print(f"[green]β[/green] Renamed profile from '{old_name}' to '{new_name}'")
except NLMError as e:
console.print(f"[red]Error:[/red] {e.message}")
if e.hint:
console.print(f"\n[dim]Hint: {e.hint}[/dim]")
raise typer.Exit(1)
@login_app.command("switch")
def login_switch(
profile: str = typer.Argument(..., help="Profile name to switch to"),
) -> None:
"""Switch the default profile for all commands."""
from notebooklm_tools.core.auth import AuthManager
from notebooklm_tools.utils.config import get_config, save_config
# Check if profile exists
auth = AuthManager(profile)
if not auth.profile_exists():
console.print(f"[red]Error:[/red] Profile '{profile}' not found")
console.print("\nAvailable profiles:")
for name in AuthManager.list_profiles():
console.print(f" [cyan]{name}[/cyan]")
raise typer.Exit(1)
# Update config
config = get_config()
old_profile = config.auth.default_profile
config.auth.default_profile = profile
save_config(config)
# Show confirmation with account info
try:
p = auth.load_profile()
email = p.email or "Unknown"
console.print(f"[green]β[/green] Switched default profile to [cyan]{profile}[/cyan]")
console.print(f" Account: {email}")
if old_profile != profile:
console.print(f" [dim]Previous: {old_profile}[/dim]")
except Exception:
console.print(f"[green]β[/green] Switched default profile to [cyan]{profile}[/cyan]")
# Register profile commands under login
login_app.add_typer(profile_app, name="profile")
# Register login app with nested profile commands
app.add_typer(login_app, name="login")
# Register noun-first subcommands (existing structure)
app.add_typer(notebook_app, name="notebook", help="Manage notebooks")
app.add_typer(note_app, name="note", help="Manage notes")
app.add_typer(source_app, name="source", help="Manage sources")
app.add_typer(chat_app, name="chat", help="Configure chat settings")
app.add_typer(studio_app, name="studio", help="Manage studio artifacts")
app.add_typer(research_app, name="research", help="Research and discover sources")
app.add_typer(alias_app, name="alias", help="Manage ID aliases")
app.add_typer(config_app, name="config", help="Manage configuration")
app.add_typer(download_app, name="download", help="Download artifacts (audio, video, etc)")
app.add_typer(share_app, name="share", help="Manage notebook sharing")
app.add_typer(export_app, name="export", help="Export artifacts to Google Docs/Sheets")
app.add_typer(skill_app, name="skill", help="Install skills for AI tools")
app.add_typer(setup_app, name="setup", help="Configure MCP server for AI tools")
app.add_typer(doctor_app, name="doctor", help="Diagnose installation and configuration")
# Generation commands as top-level
app.add_typer(audio_app, name="audio", help="Create audio overviews")
app.add_typer(report_app, name="report", help="Create reports")
app.add_typer(quiz_app, name="quiz", help="Create quizzes")
app.add_typer(flashcards_app, name="flashcards", help="Create flashcards")
app.add_typer(mindmap_app, name="mindmap", help="Create and manage mind maps")
app.add_typer(slides_app, name="slides", help="Create slide decks")
app.add_typer(infographic_app, name="infographic", help="Create infographics")
app.add_typer(video_app, name="video", help="Create video overviews")
app.add_typer(data_table_app, name="data-table", help="Create data tables")
# Auth is now under login (removed auth_app registration)
# Register verb-first subcommands (alternative structure)
app.add_typer(create_app, name="create", help="Create resources (notebooks, audio, video, etc)")
app.add_typer(list_app, name="list", help="List resources (notebooks, sources, artifacts)")
app.add_typer(get_app, name="get", help="Get details about resources")
app.add_typer(delete_app, name="delete", help="Delete resources (notebooks, sources, artifacts)")
app.add_typer(add_app, name="add", help="Add resources (sources to notebooks)")
app.add_typer(rename_app, name="rename", help="Rename resources")
app.add_typer(status_app, name="status", help="Check status of resources")
app.add_typer(describe_app, name="describe", help="Get AI-generated descriptions and summaries")
app.add_typer(query_app, name="query", help="Chat with notebook sources")
app.add_typer(sync_app, name="sync", help="Sync resources (Drive sources)")
app.add_typer(content_app, name="content", help="Get raw content from sources")
app.add_typer(stale_app, name="stale", help="List stale resources that need syncing")
app.add_typer(configure_app, name="configure", help="Configure settings")
app.add_typer(set_app, name="set", help="Set values (aliases, config)")
app.add_typer(show_app, name="show", help="Show information")
app.add_typer(install_app, name="install", help="Install resources (skills)")
app.add_typer(uninstall_app, name="uninstall", help="Uninstall resources (skills)")
app.add_typer(update_app, name="update", help="Update resources (skills)")
@app.callback(invoke_without_command=True)
def main(
ctx: typer.Context,
version: bool = typer.Option(
False, "--version", "-v",
help="Show version and exit",
),
ai: bool = typer.Option(
False, "--ai",
help="Output AI-friendly documentation for this CLI",
),
) -> None:
"""
NLM - Command-line interface for Google NotebookLM.
Use 'nlm <command> --help' for help on specific commands.
"""
if version:
from notebooklm_tools.cli.utils import check_for_updates
console.print(f"nlm version {__version__}")
# Check for updates when showing version
update_available, latest = check_for_updates()
if update_available and latest:
console.print(
f"\n[dim]π Update available:[/dim] [green]{latest}[/green]. "
f"[dim]Run[/dim] [bold]uv tool upgrade notebooklm-mcp-cli[/bold] [dim]to update.[/dim]"
)
else:
console.print(f"[dim]You are on the latest version.[/dim]")
raise typer.Exit()
if ai:
from notebooklm_tools.cli.ai_docs import print_ai_docs
print_ai_docs()
raise typer.Exit()
# Show help if no command provided
if ctx.invoked_subcommand is None:
console.print(ctx.get_help())
def cli_main():
"""Main CLI entry point with error handling."""
try:
app()
except Exception as e:
# Import here to avoid circular dependencies
from notebooklm_tools.core.exceptions import (
AuthenticationError,
NLMError,
)
from notebooklm_tools.core.errors import ClientAuthenticationError
# Handle authentication errors cleanly
if isinstance(e, (AuthenticationError, ClientAuthenticationError)):
console.print(f"\n[red]β Authentication Error[/red]")
console.print(f" {str(e)}")
console.print(f"\n[yellow]β[/yellow] Run [cyan]nlm login[/cyan] to re-authenticate\n")
raise typer.Exit(1)
# Handle other NLM errors cleanly
elif isinstance(e, NLMError):
console.print(f"\n[red]β Error:[/red] {e.message}")
if e.hint:
console.print(f"[dim]{e.hint}[/dim]\n")
raise typer.Exit(1)
# For unexpected errors, show the traceback
else:
raise
finally:
# Check for updates after command execution (runs even on typer.Exit)
from notebooklm_tools.cli.utils import print_update_notification
print_update_notification()
if __name__ == "__main__":
cli_main()
|