Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(youtube-music): music by voice on the account you already pay for

Harald96aa86f71df8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 11da53d2a6..39204c1c91 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,34 @@ versioning per [SemVer](https://semver.org/).
### Added
+- **YouTube Music as a marketplace plugin — music by voice, on the account you
+ already pay for.** "Play Radiohead", "play my running playlist", "play my
+ liked songs", "pause", "skip", "what song is this", "like this", "add this to
+ my chill playlist", "create a playlist called Late night". Google publishes
+ no YouTube Music API, so the plugin rides the official **YouTube Data API v3**
+ (search, your playlists, likes) through the **same Google OAuth client** as
+ Gmail, Drive and Calendar — one Cloud project, one more API to enable — and
+ never a reverse-engineered private client.
+ - **Playback happens in YouTube Music, not in Jarvis** — the same model as
+ the Spotify plugin. Playing opens a `music.youtube.com` deep link in the
+ browser (a song opens as its own radio, an album or playlist as its list;
+ both verified live), so Premium, recommendations and history stay in the
+ user's own account. Jarvis pauses whatever played before, then watches the
+ system's media session and says whether playback actually started —
+ including the honest "press play once" when the browser withholds autoplay.
+ - **Pause, resume, next, previous and "what is playing" come from the OS media
+ session** — new cross-platform seam `jarvis/platform/media_session.py`, the
+ same channel the keyboard's media keys use. Windows reads and steers through
+ WinRT (`winrt-*` in the `[desktop]` extra; measured live, including the
+ case of two Chrome tabs sharing one app id, where a paused YouTube video used
+ to hijack "pause the music"), Linux through `playerctl`, macOS through
+ `nowplaying-cli`; without the tool the answer names the install command
+ instead of a fake success (`docs/os-parity.md` P-33).
+ - **Honest limits, said out loud.** Google allows 100 searches a day per
+ project (each "play <name>" is one; repeats are cached, own playlists cost
+ none); volume and "queue next" do not exist in YouTube's API and the skill
+ says so instead of guessing. Setup: `docs/marketplace/youtube-music-setup.md`.
+
- **Google Cloud Vertex AI as a provider family of its own, on every tier.**
Vertex serves the same Gemini models as Google AI Studio, but bills a Cloud
project — and until now it was reachable only by accident: an express-mode key
diff --git a/docs/marketplace/google-oauth-setup.md b/docs/marketplace/google-oauth-setup.md
index c20ede22b3..5f69f322d8 100644
--- a/docs/marketplace/google-oauth-setup.md
+++ b/docs/marketplace/google-oauth-setup.md
@@ -1,4 +1,4 @@
-# OAuth app setup for the Asana, Gmail, Drive and Calendar plugins
+# OAuth app setup for the Asana, Gmail, Drive, Calendar and YouTube Music plugins
These marketplace plugins use browser-login OAuth against an app **you** register
once. This is the providers' security model — no one can do it for you, and there
@@ -17,19 +17,22 @@ still set it as an env var / credential-manager secret or edit
| Gmail | one Google Cloud "Desktop" OAuth client | `REPLACE_WITH_JARVIS_GOOGLE_CLIENT_ID` |
| Google Drive | **the same** Google client (shared) | `REPLACE_WITH_JARVIS_GOOGLE_CLIENT_ID` |
| Google Calendar | **the same** Google client (shared) | `REPLACE_WITH_JARVIS_GOOGLE_CLIENT_ID` |
+| YouTube Music | **the same** Google client (shared) — see [`youtube-music-setup.md`](youtube-music-setup.md) | `REPLACE_WITH_JARVIS_GOOGLE_CLIENT_ID` |
| Asana | an Asana OAuth app | `REPLACE_WITH_JARVIS_ASANA_CLIENT_ID` |
---
-## Part A — Google (covers Gmail, Drive AND Calendar with one client)
+## Part A — Google (covers Gmail, Drive, Calendar AND YouTube Music with one client)
1. Go to <https://console.cloud.google.com> and create (or select) a project.
-2. **APIs & Services → Library** → enable **Gmail API**, **Google Drive API**
- and **Google Calendar API** (enable only the ones whose plugins you want).
+2. **APIs & Services → Library** → enable **Gmail API**, **Google Drive API**,
+ **Google Calendar API** and **YouTube Data API v3** (enable only the ones
+ whose plugins you want).
3. **APIs & Services → OAuth consent screen** → User type **External** → Create.
Fill app name, your support email, and developer contact email → Save.
4. **Scopes** → add the ones you need: `.../auth/gmail.readonly`,
- `.../auth/gmail.send`, `.../auth/drive.file`, `.../auth/calendar`.
+ `.../auth/gmail.send`, `.../auth/drive.file`, `.../auth/calendar`,
+ `.../auth/youtube` (YouTube Music).
(Drive's `drive.file` is non-sensitive; the Gmail scopes are
sensitive/restricted; the full `calendar` scope is sensitive — it lets Jarvis
read events across ALL your calendars, not just the primary one, so a lesson
@@ -56,9 +59,9 @@ still set it as an env var / credential-manager secret or edit
Or store it permanently in the credential manager (service
`personal-jarvis`), keys `google_oauth_client_id` /
- `google_oauth_client_secret`. One client covers **Gmail, Drive AND Calendar**
- (the shared Google family). Then restart Jarvis and **connect the plugin** in
- the Plugins view.
+ `google_oauth_client_secret`. One client covers **Gmail, Drive, Calendar AND
+ YouTube Music** (the shared Google family). Then restart Jarvis and
+ **connect the plugin** in the Plugins view.
(Editing `data/plugin_catalog.json` directly still works as a fallback, but
the secret takes precedence and is the durable option.)
diff --git a/docs/marketplace/youtube-music-setup.md b/docs/marketplace/youtube-music-setup.md
new file mode 100644
index 0000000000..654446e505
--- /dev/null
+++ b/docs/marketplace/youtube-music-setup.md
@@ -0,0 +1,108 @@
+# YouTube Music plugin setup
+
+The YouTube Music plugin logs in with the **same Google OAuth client** as
+Gmail, Google Drive and Google Calendar. If you already connected one of those,
+this takes two minutes: enable one more API in that Cloud project and press
+Connect. If you have not, follow Part A of
+[`google-oauth-setup.md`](google-oauth-setup.md) once — every Google plugin
+shares that client — and come back here.
+
+There is no way around the Google Cloud console: Google publishes **no YouTube
+Music API** at all, and the official API that does exist (the YouTube Data API
+v3) is only reachable through a Cloud project you own. The community "YouTube
+Music APIs" are reverse-engineered private clients that break with every
+redesign and sit outside YouTube's terms, so this project does not ship one.
+
+## What you get — and what YouTube does not offer
+
+| You say | What happens |
+|---|---|
+| "play Radiohead" · "play Karma Police" · "play the album OK Computer" · "play my running playlist" · "play my liked songs" | Jarvis finds it and opens it in **YouTube Music in your browser** — your own account, your Premium, your history. A song opens as its own radio, so music keeps coming. |
+| "pause" · "carry on" · "skip this" · "go back" | Sent to the browser through the system's media session — the same channel your keyboard's play/pause key uses. |
+| "what song is this?" | Read from that media session: track, artist, album, and which app it comes out of. |
+| "like this song" · "add this to my running playlist" · "create a playlist called Late night" · "what is in my chill playlist?" | Written to your YouTube library through the official API. |
+| "turn it up" | **Not available.** YouTube exposes no volume control; use the system or app volume. |
+| "queue this next" | **Not available.** There is no queue API; Jarvis offers to play it now or add it to a playlist instead. |
+
+Playback happens **in YouTube Music, not in Jarvis** — exactly like the Spotify
+plugin, where the music comes out of Spotify. That is deliberate: it keeps your
+Premium (no ads), your recommendations and your history in your own account.
+
+## Part A — the Google Cloud project (once)
+
+If you have not set up the shared Google client yet, do
+[Part A of the Google setup](google-oauth-setup.md) first. Then, in the same
+project:
+
+1. **APIs & Services → Library** → search **YouTube Data API v3** → **Enable**.
+2. **APIs & Services → OAuth consent screen → Scopes** → add
+ `https://www.googleapis.com/auth/youtube` (it is a *sensitive* scope; for
+ personal use in Testing mode no verification is needed).
+3. That is all — the OAuth client itself is the one you already have. Nothing
+ to register: the loopback redirect works out of the box for a Google
+ **Desktop app** client.
+
+## Part B — connect it in Jarvis
+
+1. Open **Plugins**, find the YouTube Music card, click **Connect**.
+2. If Jarvis does not have your Google Client ID yet, expand **"Use your own
+ OAuth client (advanced)"** and paste it. It is stored as
+ `google_oauth_client_id` — one client for Gmail, Drive, Calendar and
+ YouTube Music.
+3. Your browser opens Google's approval page. Approve the **YouTube** permission.
+4. The tab reports `Connected.` and can be closed.
+
+## Part C — playback control on your machine
+
+Reading "what is playing" and pause/skip use the OS media session:
+
+| OS | Out of the box | If not |
+|---|---|---|
+| **Windows** | Yes — reads and steers through WinRT (part of the `[desktop]` extras). | Without the extras, pause/skip still work as blind media keys; "what is playing" says it cannot read. `pip install "personal-jarvis[desktop]"` fixes it. |
+| **Linux** | Needs `playerctl` (`sudo apt install playerctl`). | Without it, the answer names that command; playing and the library actions work regardless. |
+| **macOS** | Needs `nowplaying-cli` (`brew install nowplaying-cli`). Apple ships no public now-playing API. | Without it, control YouTube Music directly; playing and the library actions work regardless. |
+| **Headless / VPS** | No player exists there. | "Play" returns the link so you can open it on a device with YouTube Music. |
+
+## Keeping it connected
+
+Google's rules for the shared client apply: while your OAuth app is in
+**Testing** mode a grant expires after seven days, so publish the app to
+**In production** (see the Google doc's "Keeping it connected"). Jarvis renews
+the hourly access token itself and only asks to reconnect when the grant is
+truly gone.
+
+## Limits worth knowing
+
+- **100 searches a day.** Google gives every Cloud project 100 `search.list`
+ calls a day, separate from the 10,000-unit pool the other calls use. Every
+ "play <name>" is one search (repeats within a session are cached; your own
+ playlists and liked songs cost none). Enough for a household, not for a
+ party. When they are gone, Jarvis says so; pausing, skipping and your own
+ playlists keep working. The counter resets at midnight Pacific time.
+- **First autoplay.** A browser blocks autoplay on a site until you have used
+ it there. If Jarvis reports "opened, but playback not confirmed", press play
+ once — after that it starts on its own.
+- **A song is a video.** YouTube's top hit is sometimes the music video or a
+ live version. Jarvis says what it actually started so you notice at once.
+- **Two tabs.** Each "play" opens a new YouTube Music tab; Jarvis pauses the
+ old one first, so only one plays. Close the extras whenever you like.
+
+## When something does not work
+
+| What you see | What it means |
+|---|---|
+| "The YouTube Data API v3 is not enabled" | Part A step 1 was skipped in the Cloud project behind your client. |
+| "The stored Google authorization does not include YouTube" | The scope was not approved — reconnect and tick the YouTube permission. |
+| "100 YouTube searches a day … used up" | Google's daily search bucket. Resets at midnight Pacific. |
+| "opened, but playback not confirmed" | The browser withheld autoplay; press play once. |
+| "Nothing is registered as playing" | No app on this machine has a media session — open YouTube Music (say "open YouTube Music") or play something first. |
+| "This machine cannot control playback" | Linux without `playerctl` / macOS without `nowplaying-cli`; the message names the install command. |
+| The card asks to reconnect after a week | The Testing-mode seven-day rule; publish the app. |
+
+## Why not an off-the-shelf MCP server?
+
+Google publishes no YouTube Music MCP server, and every community one wraps the
+same unofficial private client (browser cookies or a reverse-engineered OAuth
+flow) — a fragile, terms-of-service-grey base this project will not put under
+a store card. The official Data API plus the OS media session covers playing,
+control, "what is playing" and the library, honestly and durably.
diff --git a/docs/os-parity.md b/docs/os-parity.md
index ee4079e7b8..540dc90080 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -248,6 +248,7 @@ experiences today.
| P-32 | Low | Local models | The in-app Ollama runtime install (the plug-and-go path for local models: detect → install → start → pull, no terminal) has one silent path per OS and an honest refusal elsewhere: Windows uses winget or the official per-user OllamaSetup.exe (built, not yet live-run on a machine WITHOUT Ollama); macOS automates only Homebrew — a dmg drag cannot be scripted honestly, so brew-less Macs get the download pointer; Linux runs the official install.sh only when non-interactive sudo exists (the script escalates internally; without it the refusal names the one terminal command instead of hanging on an invisible password prompt). Detection and start are cross-platform | `jarvis/brain/ollama_runtime.py`, `jarvis/ui/web/provider_routes.py` (ollama-runtime routes), `jarvis/realtime/local_server/install.py::_setup_local_brain` | Every OS gets the same three-state truth (not installed / stopped / running) and the same buttons; only the INSTALL leg differs. Refusals are one honest sentence with the exact fixing action. All install legs are unit-tested with fakes; no leg has been live-run on a machine without Ollama yet — the cold-machine drill is the recorded release gate |
| P-31 | Low | Detached views | The "own window" detach (Agentic IDE / Voice into a second pywebview window) creates the window at RUNTIME, after `webview.start()`. pywebview documents runtime multi-window, and the code path is OS-neutral (worker-thread create, distinct title, shared backend), but it has only been RUN against the Windows/WebView2 backend; whether the cocoa and GTK backends accept a runtime `create_window` is unverified from this machine. Browser-lock auth in the second window additionally relies on a shared cookie jar, which is verified for WebView2 only | `jarvis/ui/desktop_app.py::open_detached_window`, `jarvis/platform/probes.py::webview_backend_available`, `jarvis/ui/web/desktop_routes.py` | Every failure is honest and keeps the feature usable: a shell whose backend refuses the runtime create answers `ok: false` with the solo URL and the frontend opens it in the user's real browser tab (via open-external); plain-browser clients open the tab directly; headless answers `no_desktop_shell` the same way. macOS/Linux desktop live check pending: detach, close main, reattach, tray-reopen — on success this row shrinks to the cookie-jar note or disappears |
+| P-33 | Low | Music control (YouTube Music) | Pause / resume / next / previous and "what is playing" for the YouTube Music plugin go through the OS media session — the registry the keyboard's media keys use — because Google publishes no remote-playback API. Windows reads and steers it through WinRT (`winrt-Windows.Media.Control`, in the `[desktop]` extra; measured live 2026-08-18 against YouTube Music in Chrome, including the two-tabs-same-app-id case) and falls back to blind media keys without the extra. Linux has no binding in the base install and needs the `playerctl` CLI (MPRIS); macOS has no public API at all and needs the Homebrew `nowplaying-cli`, whose MediaRemote access Apple has been narrowing on recent releases | `jarvis/platform/media_session.py::make_media_session_controller`, `WindowsMediaSession`, `LinuxMediaSession`, `MacMediaSession`, `jarvis/plugins/tool/youtube_music_rest.py::_control` | Playing (search + open the `music.youtube.com` deep link) works on every desktop OS. Without the CLI, `now_playing` and the transport verbs answer with the exact install command instead of a fake success, and the play deep link plus the library actions (like, playlists) stay fully usable. Headless: no player exists, so the tool returns the link and says so. Linux `playerctl` and macOS `nowplaying-cli` backends are unit-tested with fake CLI output, not live-run from this machine |
| P-34 | Low | Drop-path bridge | The desktop shell reports the REAL path of a file or folder dropped onto the UI (`jarvis-native-drop` DOM event from `jarvis/ui/native_drop.py`, consumed by `src/lib/nativeDrop.ts` in the Agentic IDE folder picker). Built on pywebview's own cross-platform drop handling (`pywebviewFullPath` — WebView2 on Windows, WKWebView on macOS, WebKitGTK on Linux); live-verified for a dropped FOLDER on Windows/WebView2 only | `jarvis/ui/native_drop.py::register_native_drop`, `jarvis/ui/desktop_app.py::_register_native_drop`, `jarvis/ui/web/frontend/src/lib/nativeDrop.ts` | Honest degradation everywhere: without the announcement (plain browser, headless, a shell whose backend does not resolve paths) the picker falls back to searching for the dropped NAME after 2 s, exactly as before. macOS/Linux live check pending: drop a folder onto the folder step and confirm the exact path is used without a candidate list |
## Maintenance
diff --git a/jarvis/brain/evidence_gate.py b/jarvis/brain/evidence_gate.py
index f664d15d16..e3c6cab0e8 100644
--- a/jarvis/brain/evidence_gate.py
+++ b/jarvis/brain/evidence_gate.py
@@ -87,7 +87,11 @@ _SYSTEM_SYNONYMS: tuple[frozenset[str], ...] = (
"repo", "repos", "repository", "repositories", "pull request",
"pull requests", "issue", "issues", "github", "gitlab",
}),
- frozenset({"spotify", "musik", "music"}),
+ # One domain, two systems: "musik" must find a lone Spotify OR a lone
+ # YouTube Music (the tool name carries "music", the brand terms do not).
+ frozenset({
+ "spotify", "musik", "music", "youtube music", "youtube_music", "yt music", "ytmusic",
+ }),
frozenset({"twitter", "x", "tweet", "tweets"}),
frozenset({
"pizza", "lieferando", "doordash", "uber eats", "ubereats", "wolt",
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index 3d60f7fdfe..8d01d74b57 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -201,6 +201,12 @@ ROUTER_TOOLS = frozenset({
# voice, which is the entire point of a music plugin. risk_tier "monitor":
# starting music is audible and instantly undone. Never a spawn (AP-5/AP-14).
"spotify",
+ # YouTube Music Marketplace plugin (2026-08-18): native REST tool over the
+ # official YouTube Data API v3 plus the OS media session — Google publishes
+ # no YouTube Music API and no MCP server, so it must be router-visible
+ # directly; otherwise a connected YouTube Music is not callable by voice.
+ # risk_tier "monitor": audible and instantly undone. Never a spawn (AP-5/AP-14).
+ "youtube_music",
# Computer-Use (Wave 1, 2026-05-29): first-class, clearly-described tool to
# drive the user's LIVE desktop (open apps, click, type, scroll, operate
# any GUI). The router previously had no honest desktop path — spawn-worker
diff --git a/jarvis/brain/local_action_gate.py b/jarvis/brain/local_action_gate.py
index c247180987..d076a007ac 100644
--- a/jarvis/brain/local_action_gate.py
+++ b/jarvis/brain/local_action_gate.py
@@ -653,7 +653,7 @@ _EXTERNAL_INTEGRATION_NOUN_RE = re.compile(
# Calendar
r"kalender|calendar|termine?|appointments?|"
# Music
- r"spotify|"
+ r"spotify|youtube\s*music|yt\s*music|"
# Social
r"tweets?|twitter|instagram|facebook|linkedin|tiktok|"
# Real-world commerce / transport
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 474f50b470..0b5bdb4fbc 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -170,6 +170,12 @@ _SKILL_TURN_STATE: ContextVar[_SkillTurnState | None] = ContextVar(
_CU_CONTEXT_MAX_MESSAGES = 8
_CU_CONTEXT_MAX_MESSAGE_CHARS = 240
+# Plugin-paired skill capture (2026-08-18): whether a catalog plugin holds a
+# usable credential is a keyring read, remembered per plugin for this long so
+# the turn path pays for it once per window, not once per matched turn.
+_PAIRED_CONNECTION_TTL_S = 15.0
+_PAIRED_CONNECTION_CACHE: dict[str, tuple[float, bool]] = {}
+
#: Hard bound on the per-turn vision capture (Wave-3 latency fix). ``vision.
#: current()`` can stall (mss BitBlt hang, paused-state miss, slow disk); without
#: a cap it blocks the whole brain turn on the hot path. On timeout the turn
@@ -5420,6 +5426,22 @@ class BrainManager:
vetoed_by=guards.VETO_BLOCK_TIER, skill=skill,
)
return None
+ if self._paired_plugin_disconnected(skill):
+ # Two connectors can serve one domain (Spotify and YouTube
+ # Music both answer "spiel Musik"). A paired skill whose plugin
+ # holds no usable credential must not capture the turn: it
+ # would steer the model at a tool that can only answer "not
+ # connected" while the connected sibling sits in the surface.
+ log.info(
+ "skill %s matched but its plugin is not connected — turn "
+ "not captured, routing stays with the live tool surface",
+ getattr(skill, "name", "?"),
+ )
+ self._record_skill_decision(
+ user_text, decision, lang=lang,
+ vetoed_by=guards.VETO_PLUGIN_NOT_CONNECTED, skill=skill,
+ )
+ return None
self._skill_match_band = decision.band
self._skill_match_class = classify(skill)
@@ -5612,6 +5634,54 @@ class BrainManager:
except Exception: # noqa: BLE001
return False
+ @staticmethod
+ def _paired_plugin_disconnected(skill: Any, *, store: Any | None = None) -> bool:
+ """True when ``skill`` is paired to a CATALOG plugin whose credential is
+ absent or flagged for re-auth.
+
+ Only catalog plugins are judged — every one of them authenticates, so
+ "no token" really means "not connected". A community skill naming an
+ unknown ``plugin_id`` is left alone: nothing here may veto a skill on
+ a guess. Any store or catalog fault answers False for the same reason
+ (a fault must never decide a turn). ``store`` is injectable for tests
+ (a fake with ``load``); the default is the real TokenStore.
+
+ The keyring read is synchronous and this sits on the turn path, so the
+ answer is remembered per plugin for a short while: one read per
+ plugin per :data:`_PAIRED_CONNECTION_TTL_S`, not one per matched turn.
+ A connect made inside that window merely routes without the skill's
+ guidance for a few seconds — the tool itself is callable at once."""
+ fm = getattr(skill, "frontmatter", None)
+ plugin_id = str(getattr(fm, "plugin_id", "") or "").strip()
+ if not plugin_id:
+ return False
+ now = time.monotonic()
+ if store is None:
+ cached = _PAIRED_CONNECTION_CACHE.get(plugin_id)
+ if cached is not None and cached[0] > now:
+ return cached[1]
+ try:
+ from jarvis.marketplace.catalog_data import load_catalog
+
+ if load_catalog().by_id(plugin_id) is None:
+ return False
+ if store is None:
+ from jarvis.marketplace.token_store import TokenStore
+
+ store = TokenStore()
+ remember = True
+ else:
+ remember = False
+ tokens = store.load(plugin_id)
+ except Exception: # noqa: BLE001 — a store fault must not decide a turn
+ return False
+ disconnected = tokens is None or (
+ not getattr(tokens, "access", None) or bool(getattr(tokens, "needs_reauth", False))
+ )
+ if remember:
+ _PAIRED_CONNECTION_CACHE[plugin_id] = (now + _PAIRED_CONNECTION_TTL_S, disconnected)
+ return disconnected
+
def _render_skill_turn_hint(self) -> str | None:
"""Steering hint appended to the turn context on a skill-matched turn."""
skill = self._skill_turn_match
diff --git a/jarvis/marketplace/seed_catalog.json b/jarvis/marketplace/seed_catalog.json
index cb185dcd09..9ab79a3337 100644
--- a/jarvis/marketplace/seed_catalog.json
+++ b/jarvis/marketplace/seed_catalog.json
@@ -565,6 +565,36 @@
},
"native_tool": "spotify",
"post_install_hint_md": "Setup: see docs/marketplace/spotify-oauth-setup.md. Spotify has no shared client — every install registers its own app, which takes about five minutes and needs no client secret. Register the redirect URI **exactly** as `http://127.0.0.1:3125/callback`; Spotify rejects `localhost`.\n\nControlling playback (play, pause, skip, volume) requires Spotify **Premium** — Spotify's own rule, not ours. Reading what is playing works on a free account. Spotify offers no revoke endpoint, so disconnecting here removes the local credential; remove the app itself under Account → Apps."
+ },
+ {
+ "id": "youtube_music",
+ "display_name": "YouTube Music",
+ "description": "Play songs, albums and your playlists, pause, skip, like — and hear what is playing",
+ "category": "Media & Creativity",
+ "logo_slug": "youtubemusic",
+ "logo_color": "FF0000",
+ "featured": true,
+ "longevity": "provider_limited",
+ "longevity_note": "Google expires the authorization after 7 days while your own OAuth app is in Testing mode. Publish the app to keep the connection indefinitely.",
+ "oauth_client_family": "google",
+ "auth": {
+ "mode": "oauth_pkce_loopback",
+ "authorization_url": "https://accounts.google.com/o/oauth2/v2/auth",
+ "token_url": "https://oauth2.googleapis.com/token",
+ "revocation_url": "https://oauth2.googleapis.com/revoke",
+ "client_id": "REPLACE_WITH_JARVIS_GOOGLE_CLIENT_ID",
+ "callback_port": 3123,
+ "callback_path": "",
+ "scopes": [
+ "https://www.googleapis.com/auth/youtube"
+ ],
+ "scope_separator": "space",
+ "user_scopes_only": false,
+ "refresh_supported": true,
+ "offline_access": true
+ },
+ "native_tool": "youtube_music",
+ "post_install_hint_md": "Setup: see docs/marketplace/youtube-music-setup.md — it shares the Google OAuth client with Gmail, Drive and Calendar; only **enable the YouTube Data API v3** in that Cloud project and add the `youtube` scope. Google publishes no YouTube Music API, so this talks to the official YouTube Data API v3 (search, your playlists, likes) and plays by opening YouTube Music in your browser — your own account and Premium. Pause, skip and \"what is playing\" go through the system's media session (Windows out of the box; Linux needs `playerctl`, macOS `nowplaying-cli`). Google allows **100 searches a day** per project — enough for one household, not for a party. Volume is not controllable here."
}
]
}
diff --git a/jarvis/marketplace/usage_cards/youtube_music.md b/jarvis/marketplace/usage_cards/youtube_music.md
new file mode 100644
index 0000000000..ca58200a9b
--- /dev/null
+++ b/jarvis/marketplace/usage_cards/youtube_music.md
@@ -0,0 +1,13 @@
+---
+plugin_id: youtube_music
+keywords: youtube music, youtube, yt music, ytmusic, musik, music, música, lied, song, canción, track, titel, album, álbum, playlist, wiedergabeliste, lista de reproducción, künstler, artist, artista, band, grupo, radio, spiel, spiele, play, pon, reproduce, pausier, pause, pausa, stopp, stop, überspring, skip, salta, next, siguiente, weiter, zurück, previous, anterior, like, liken, gefällt mir, me gusta, was läuft, what is playing, qué suena # i18n-allow: spoken-input matching vocabulary (de/en/es), not prose
+---
+Use the youtube_music tool to play and control the user's music on YouTube Music.
+
+- To start something, pass what the user said as `query` and set `type`: `song` for a track, `artist` for a band (their top song starts and the radio continues with them), `album`, `playlist` for one of their own lists, `liked` for their liked songs. The tool searches and opens the hit in YouTube Music in one step; a song opens as its own radio, so music keeps coming.
+- `play` without a query resumes what is paused; `pause`, `next` and `previous` steer what is already running. There is no volume action — say the system or app volume does that.
+- `now_playing` answers "what song is this" — it reports track, artist and which app it comes out of. If it names another player (Spotify, a YouTube video), say so; it is not a wrong answer.
+- Report the track the response names, not the words the user used. YouTube's top hit is sometimes not what they meant, and saying it aloud is how they notice.
+- Playing opens YouTube Music in the browser. When the response says playback is not confirmed, tell the user to press play once — the browser blocks autoplay on a site until it has been used there. That is the browser's rule, not a broken connection.
+- `like`, `add_to_playlist` and `create_playlist` change their library; without a `query` they act on the song playing right now.
+- Google allows 100 searches a day for this app. When the response says they are used up, say so plainly — playing their own playlists, pausing and skipping still work.
diff --git a/jarvis/platform/media_session.py b/jarvis/platform/media_session.py
new file mode 100644
index 0000000000..c46927bf2b
--- /dev/null
+++ b/jarvis/platform/media_session.py
@@ -0,0 +1,694 @@
+"""OS media-session seam — read and steer whatever is playing on this machine.
+
+Every desktop OS keeps a "now playing" registry that browsers and music apps
+feed the same way they feed the keyboard's media keys: Windows exposes it as
+``GlobalSystemMediaTransportControlsSessionManager`` (WinRT), Linux as MPRIS
+over D-Bus, macOS through the private MediaRemote framework. YouTube Music in
+a browser tab publishes title, artist and album there, and accepts play, pause,
+next and previous from it. That registry is the only supported way to control
+YouTube Music — Google publishes no remote-playback API — so this module is what
+turns "pause the music" into an action instead of a shrug.
+
+Shape (AD-5/AD-6): one :func:`make_media_session_controller` factory picks the
+per-OS backend from :func:`detect_platform`; each backend degrades to an honest
+:class:`MediaSessionCapability` instead of raising, and nothing here imports a
+platform-only package at module scope (HN-7) — the WinRT import lives inside
+the Windows backend and is guarded, so a headless ``python:3.11-slim`` boots
+unaffected.
+
+Per-OS reality, recorded in ``docs/os-parity.md``:
+
+* **Windows** — full read + control via WinRT when the ``winrt-*`` desktop
+ extras are installed; without them, control still works through the OS media
+ keys (which cannot tell "pause" from "play", so it is a toggle) and reading
+ is honestly unavailable.
+* **Linux** — read + control through ``playerctl`` (MPRIS) when it is on PATH
+ and a session bus exists; a headless box has neither and says so.
+* **macOS** — read + control through ``nowplaying-cli`` (Homebrew) when
+ installed. Apple ships no public API for this, so without that tool the
+ answer is "control it in YouTube Music" rather than a fake success.
+
+Backends take an injectable runner/manager so the unit tests use fakes, never
+mocks and never a real media session.
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+import shutil
+import subprocess
+from collections.abc import Callable, Sequence
+from dataclasses import dataclass
+from typing import Any, Literal, Protocol
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+from jarvis.platform import detect_platform
+
+log = logging.getLogger(__name__)
+
+PlaybackStatus = Literal["playing", "paused", "stopped", "unknown"]
+
+# The Chrome/Edge PWA of YouTube Music registers a per-app model id that ends in
+# the extension id below; a plain tab is just "Chrome"/"MSEdge". Knowing the
+# PWA lets the picker prefer the app the user actually installed for music.
+_YTM_PWA_MARKERS: tuple[str, ...] = ("cinhimbnkkaeohfgghhklpknlkffjgod", "youtube")
+
+# Substrings that identify a web browser's media session on any OS. Order does
+# not matter; matching is case-insensitive.
+_BROWSER_MARKERS: tuple[str, ...] = (
+ "chrome",
+ "chromium",
+ "msedge",
+ "edge",
+ "firefox",
+ "brave",
+ "opera",
+ "vivaldi",
+ "arc",
+ "zen",
+ "safari",
+)
+
+# Friendly names for the raw per-OS session identifiers, so a spoken answer
+# says "in Google Chrome" instead of "in Chrome._crx_cinhi…".
+_APP_LABELS: tuple[tuple[str, str], ...] = (
+ ("cinhimbnkkaeohfgghhklpknlkffjgod", "YouTube Music app"),
+ ("msedge", "Microsoft Edge"),
+ ("chromium", "Chromium"),
+ ("chrome", "Google Chrome"),
+ ("firefox", "Firefox"),
+ ("brave", "Brave"),
+ ("vivaldi", "Vivaldi"),
+ ("opera", "Opera"),
+ ("safari", "Safari"),
+ ("spotify", "Spotify"),
+ ("apple.music", "Apple Music"),
+ ("music", "Music"),
+ ("vlc", "VLC"),
+)
+
+# WinRT GlobalSystemMediaTransportControlsSessionPlaybackStatus values:
+# 0 CLOSED, 1 OPENED, 2 CHANGING, 3 STOPPED, 4 PLAYING, 5 PAUSED.
+_WINRT_STATUS: dict[int, PlaybackStatus] = {4: "playing", 5: "paused", 3: "stopped"}
+
+# Windows media-key virtual-key codes (used only by the no-WinRT fallback).
+_VK_MEDIA_NEXT_TRACK = 0xB0
+_VK_MEDIA_PREV_TRACK = 0xB1
+_VK_MEDIA_PLAY_PAUSE = 0xB3
+_KEYEVENTF_KEYUP = 0x0002
+
+_CLI_TIMEOUT_S = 3.0
+
+
+@dataclass(frozen=True, slots=True)
+class NowPlaying:
+ """What the OS says is playing — the fields a spoken answer needs."""
+
+ title: str
+ artist: str
+ album: str
+ app: str
+ status: PlaybackStatus
+ position_s: float | None = None
+ duration_s: float | None = None
+ is_browser: bool = False
+ is_youtube_music_app: bool = False
+
+ @property
+ def is_playing(self) -> bool:
+ return self.status == "playing"
+
+ def as_dict(self) -> dict[str, Any]:
+ out: dict[str, Any] = {
+ "is_playing": self.is_playing,
+ "status": self.status,
+ "track": self.title,
+ "artist": self.artist,
+ "app": self.app,
+ }
+ if self.album:
+ out["album"] = self.album
+ if self.position_s is not None:
+ out["position_s"] = round(self.position_s)
+ if self.duration_s is not None and self.duration_s > 0:
+ out["duration_s"] = round(self.duration_s)
+ return out
+
+
+@dataclass(frozen=True, slots=True)
+class MediaSessionCapability:
+ """What this machine can do, and — when it cannot — what would fix it."""
+
+ can_read: bool
+ can_control: bool
+ backend: str
+ note: str = ""
+
+
+class MediaSessionController(Protocol):
+ """Async per-OS backend. Every method is exception-free by contract."""
+
+ async def capability(self) -> MediaSessionCapability: ...
+
+ async def now_playing(self) -> NowPlaying | None: ...
+
+ async def play(self) -> bool: ...
+
+ async def pause(self) -> bool: ...
+
+ async def toggle(self) -> bool: ...
+
+ async def next(self) -> bool: ...
+
+ async def previous(self) -> bool: ...
+
+
+# -- shared helpers -----------------------------------------------------------
+
+
+def app_label(identifier: str) -> str:
+ """Friendly app name for a raw OS session identifier (never empty)."""
+ low = (identifier or "").lower()
+ for marker, label in _APP_LABELS:
+ if marker in low:
+ return label
+ return identifier or "unknown app"
+
+
+def is_browser_identifier(identifier: str) -> bool:
+ low = (identifier or "").lower()
+ return any(marker in low for marker in _BROWSER_MARKERS) or is_ytm_app_identifier(
+ identifier
+ )
+
+
+def is_ytm_app_identifier(identifier: str) -> bool:
+ low = (identifier or "").lower()
+ return any(marker in low for marker in _YTM_PWA_MARKERS)
+
+
+def _rank(entry: NowPlaying, is_current: bool) -> tuple[int, ...]:
+ """Higher sorts first. The YouTube Music app beats a browser tab, a browser
+ beats another player, playing beats paused, and the OS's own "current"
+ session (the one media keys would hit) breaks ties — that is the session
+ the user is most likely talking about."""
+ return (
+ int(entry.is_youtube_music_app),
+ int(entry.is_browser),
+ int(entry.is_playing),
+ int(is_current),
+ )
+
+
+def pick_session(entries: Sequence[tuple[NowPlaying, bool]]) -> NowPlaying | None:
+ """Choose the session a music request most plausibly means.
+
+ ``entries`` are ``(now_playing, is_current)`` pairs. Deterministic and pure,
+ so the choice is unit-testable without any OS."""
+ if not entries:
+ return None
+ best = max(entries, key=lambda pair: _rank(pair[0], pair[1]))
+ return best[0]
+
+
+def _same_session(a: NowPlaying, b: NowPlaying) -> bool:
+ """Two enumerations of one session: same app, same track."""
+ return (a.app, a.title, a.artist, a.album) == (b.app, b.title, b.artist, b.album)
+
+
+def _norm_status(raw: str) -> PlaybackStatus:
+ low = (raw or "").strip().lower()
+ if low.startswith("play"):
+ return "playing"
+ if low.startswith("paus"):
+ return "paused"
+ if low.startswith("stop"):
+ return "stopped"
+ return "unknown"
+
+
+CliRunner = Callable[[Sequence[str]], tuple[int, str]]
+
+
+def _default_cli_runner(argv: Sequence[str]) -> tuple[int, str]:
+ """Bounded, windowless, UTF-8 subprocess. Returns (returncode, stdout)."""
+ try:
+ proc = subprocess.run( # noqa: S603 — fixed argv, no shell
+ list(argv),
+ capture_output=True,
+ timeout=_CLI_TIMEOUT_S,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ log.debug("media_session: %s failed: %s", argv[0], exc)
+ return 127, ""
+ return proc.returncode, proc.stdout.decode("utf-8", errors="replace")
+
+
+# -- Null backend (headless / unknown) ----------------------------------------
+
+
+class NullMediaSession:
+ """Honest no-op: nothing here can see or steer a player."""
+
+ def __init__(self, note: str) -> None:
+ self._note = note
+
+ async def capability(self) -> MediaSessionCapability:
+ return MediaSessionCapability(False, False, "none", self._note)
+
+ async def now_playing(self) -> NowPlaying | None:
+ return None
+
+ async def play(self) -> bool:
+ return False
+
+ async def pause(self) -> bool:
+ return False
+
+ async def toggle(self) -> bool:
+ return False
+
+ async def next(self) -> bool:
+ return False
+
+ async def previous(self) -> bool:
+ return False
+
+
+# -- Windows ------------------------------------------------------------------
+
+
+def _load_winrt_manager() -> Any | None:
+ """Return the WinRT session-manager class, or None when the desktop extras
+ are absent. Guarded lazy import (HN-7)."""
+ try:
+ from winrt.windows.media.control import ( # type: ignore[import-not-found]
+ GlobalSystemMediaTransportControlsSessionManager,
+ )
+ except Exception: # noqa: BLE001 — ImportError, or a broken WinRT runtime
+ return None
+ return GlobalSystemMediaTransportControlsSessionManager
+
+
+class WindowsMediaSession:
+ """WinRT ``GlobalSystemMediaTransportControlsSessionManager`` backend.
+
+ ``manager_factory`` is an awaitable returning an object with
+ ``get_current_session()`` and ``get_sessions()``; the tests inject a fake.
+ ``key_sender`` is the media-key fallback used when WinRT is unavailable.
+ """
+
+ def __init__(
+ self,
+ manager_factory: Callable[[], Any] | None = None,
+ key_sender: Callable[[int], bool] | None = None,
+ ) -> None:
+ self._manager_factory = manager_factory
+ self._key_sender = key_sender or _send_media_key
+ self._winrt_checked = False
+ self._winrt_cls: Any | None = None
+
+ def _resolve_factory(self) -> Callable[[], Any] | None:
+ if self._manager_factory is not None:
+ return self._manager_factory
+ if not self._winrt_checked:
+ self._winrt_checked = True
+ self._winrt_cls = _load_winrt_manager()
+ if self._winrt_cls is None:
+ return None
+ cls = self._winrt_cls
+ return lambda: cls.request_async()
+
+ async def capability(self) -> MediaSessionCapability:
+ if self._resolve_factory() is not None:
+ return MediaSessionCapability(True, True, "winrt")
+ return MediaSessionCapability(
+ False,
+ True,
+ "media-keys",
+ "Reading what plays needs the desktop extras "
+ "(`pip install \"personal-jarvis[desktop]\"` adds the winrt "
+ "packages); until then play/pause is a blind toggle via the media keys.",
+ )
+
+ async def _sessions(self) -> list[tuple[NowPlaying, bool, Any]]:
+ """Every registered session as ``(entry, is_current, session)``.
+
+ The OS's "current" session (the one the keyboard's media keys reach)
+ is listed first and flagged. Chrome registers one session PER TAB, all
+ under the same app id, so "current" is matched by what it plays, never
+ by app id — otherwise every Chrome tab would look current at once and
+ a paused YouTube video could hijack a "pause the music" aimed at
+ YouTube Music (seen live 2026-08-18)."""
+ factory = self._resolve_factory()
+ if factory is None:
+ return []
+ for attempt in (0, 1):
+ try:
+ manager = await factory()
+ out: list[tuple[NowPlaying, bool, Any]] = []
+ current = manager.get_current_session()
+ current_entry = await self._describe(current) if current else None
+ if current_entry is not None:
+ out.append((current_entry, True, current))
+ for session in list(manager.get_sessions()):
+ entry = await self._describe(session)
+ if entry is None or (
+ current_entry is not None and _same_session(entry, current_entry)
+ ):
+ continue
+ out.append((entry, False, session))
+ if out or attempt:
+ return out
+ except Exception as exc: # noqa: BLE001 — a WinRT hiccup is a "nothing playing", never a crash
+ log.debug("media_session: WinRT enumeration failed: %s", exc)
+ if attempt:
+ return []
+ # A track change briefly closes and re-opens the session; one short
+ # retry turns that blink into an answer instead of "nothing playing".
+ await asyncio.sleep(0.25)
+ return []
+
+ @staticmethod
+ async def _describe(session: Any) -> NowPlaying | None:
+ try:
+ ident = getattr(session, "source_app_user_model_id", "") or ""
+ props = await session.try_get_media_properties_async()
+ playback = session.get_playback_info()
+ status_val = int(getattr(playback, "playback_status", 0) or 0)
+ # WinRT enum: 0 CLOSED, 1 OPENED, 2 CHANGING, 3 STOPPED, 4 PLAYING, 5 PAUSED
+ status = _WINRT_STATUS.get(status_val, "unknown")
+ position = duration = None
+ try:
+ timeline = session.get_timeline_properties()
+ pos = getattr(timeline, "position", None)
+ end = getattr(timeline, "end_time", None)
+ if pos is not None and hasattr(pos, "total_seconds"):
+ position = float(pos.total_seconds())
+ if end is not None and hasattr(end, "total_seconds"):
+ duration = float(end.total_seconds())
+ except Exception as exc: # noqa: BLE001 — timeline is optional detail
+ log.debug("media_session: timeline unavailable: %s", exc)
+ return NowPlaying(
+ title=str(getattr(props, "title", "") or ""),
+ artist=str(getattr(props, "artist", "") or ""),
+ album=str(getattr(props, "album_title", "") or ""),
+ app=app_label(ident),
+ status=status,
+ position_s=position,
+ duration_s=duration,
+ is_browser=is_browser_identifier(ident),
+ is_youtube_music_app=is_ytm_app_identifier(ident),
+ )
+ except Exception as exc: # noqa: BLE001 — one bad session must not hide the others
+ log.debug("media_session: session describe failed: %s", exc)
+ return None
+
+ async def _target(self) -> Any | None:
+ rows = await self._sessions()
+ if not rows:
+ return None
+ chosen = pick_session([(entry, is_current) for entry, is_current, _ in rows])
+ for entry, _, session in rows:
+ if entry is chosen:
+ return session
+ return None
+
+ async def now_playing(self) -> NowPlaying | None:
+ rows = await self._sessions()
+ return pick_session([(entry, is_current) for entry, is_current, _ in rows])
+
+ async def _command(self, method: str, key: int) -> bool:
+ session = await self._target()
+ if session is None:
+ # No WinRT (or nothing registered): the media key still reaches
+ # whatever the OS considers current, so try that before giving up.
+ if self._resolve_factory() is None:
+ return self._key_sender(key)
+ return False
+ try:
+ return bool(await getattr(session, method)())
+ except Exception as exc: # noqa: BLE001
+ log.debug("media_session: %s failed: %s", method, exc)
+ return False
+
+ async def play(self) -> bool:
+ return await self._command("try_play_async", _VK_MEDIA_PLAY_PAUSE)
+
+ async def pause(self) -> bool:
+ return await self._command("try_pause_async", _VK_MEDIA_PLAY_PAUSE)
+
+ async def toggle(self) -> bool:
+ return await self._command("try_toggle_play_pause_async", _VK_MEDIA_PLAY_PAUSE)
+
+ async def next(self) -> bool:
+ return await self._command("try_skip_next_async", _VK_MEDIA_NEXT_TRACK)
+
+ async def previous(self) -> bool:
+ return await self._command("try_skip_previous_async", _VK_MEDIA_PREV_TRACK)
+
+
+def _send_media_key(vk: int) -> bool:
+ """Press-and-release one media key through user32 (Windows only)."""
+ try:
+ import ctypes
+
+ user32 = ctypes.windll.user32 # type: ignore[attr-defined]
+ user32.keybd_event(vk, 0, 0, 0)
+ user32.keybd_event(vk, 0, _KEYEVENTF_KEYUP, 0)
+ return True
+ except Exception as exc: # noqa: BLE001
+ log.debug("media_session: media key %#x failed: %s", vk, exc)
+ return False
+
+
+# -- Linux (MPRIS via playerctl) ---------------------------------------------
+
+_PLAYERCTL_FORMAT = "{{title}}\x1f{{artist}}\x1f{{album}}\x1f{{position}}\x1f{{mpris:length}}"
+
+
+class LinuxMediaSession:
+ """MPRIS backend through the ``playerctl`` CLI (no D-Bus binding needed)."""
+
+ def __init__(
+ self,
+ runner: CliRunner | None = None,
+ which: Callable[[str], str | None] | None = None,
+ ) -> None:
+ self._run = runner or _default_cli_runner
+ self._which = which or shutil.which
+
+ def _available(self) -> bool:
+ return self._which("playerctl") is not None
+
+ async def capability(self) -> MediaSessionCapability:
+ if self._available():
+ return MediaSessionCapability(True, True, "playerctl")
+ return MediaSessionCapability(
+ False,
+ False,
+ "none",
+ "Install playerctl (e.g. `sudo apt install playerctl`) so this "
+ "machine can read and steer the browser's music session.",
+ )
+
+ async def _players(self) -> list[str]:
+ rc, out = await asyncio.to_thread(self._run, ["playerctl", "-l"])
+ if rc != 0:
+ return []
+ return [line.strip() for line in out.splitlines() if line.strip()]
+
+ async def _describe(self, player: str) -> NowPlaying | None:
+ rc, status_out = await asyncio.to_thread(
+ self._run, ["playerctl", "-p", player, "status"]
+ )
+ status = _norm_status(status_out) if rc == 0 else "unknown"
+ rc, meta = await asyncio.to_thread(
+ self._run,
+ ["playerctl", "-p", player, "metadata", "--format", _PLAYERCTL_FORMAT],
+ )
+ if rc != 0:
+ return None
+ parts = (meta.strip("\n") + "\x1f" * 4).split("\x1f")
+ title, artist, album, position, length = (p.strip() for p in parts[:5])
+ position_s = _to_float(position)
+ length_us = _to_float(length)
+ return NowPlaying(
+ title=title,
+ artist=artist,
+ album=album,
+ app=app_label(player),
+ status=status,
+ position_s=position_s,
+ duration_s=(length_us / 1_000_000) if length_us else None,
+ is_browser=is_browser_identifier(player),
+ is_youtube_music_app=is_ytm_app_identifier(player),
+ )
+
+ async def _rows(self) -> list[tuple[NowPlaying, str]]:
+ if not self._available():
+ return []
+ rows: list[tuple[NowPlaying, str]] = []
+ for player in await self._players():
+ entry = await self._describe(player)
+ if entry is not None:
+ rows.append((entry, player))
+ return rows
+
+ async def _target(self) -> str | None:
+ rows = await self._rows()
+ if not rows:
+ return None
+ chosen = pick_session([(entry, index == 0) for index, (entry, _) in enumerate(rows)])
+ for entry, player in rows:
+ if entry is chosen:
+ return player
+ return None
+
+ async def now_playing(self) -> NowPlaying | None:
+ rows = await self._rows()
+ return pick_session([(entry, index == 0) for index, (entry, _) in enumerate(rows)])
+
+ async def _command(self, verb: str) -> bool:
+ player = await self._target()
+ if player is None:
+ return False
+ rc, _ = await asyncio.to_thread(self._run, ["playerctl", "-p", player, verb])
+ return rc == 0
+
+ async def play(self) -> bool:
+ return await self._command("play")
+
+ async def pause(self) -> bool:
+ return await self._command("pause")
+
+ async def toggle(self) -> bool:
+ return await self._command("play-pause")
+
+ async def next(self) -> bool:
+ return await self._command("next")
+
+ async def previous(self) -> bool:
+ return await self._command("previous")
+
+
+# -- macOS (nowplaying-cli) ---------------------------------------------------
+
+
+class MacMediaSession:
+ """MediaRemote backend through the ``nowplaying-cli`` Homebrew tool."""
+
+ def __init__(
+ self,
+ runner: CliRunner | None = None,
+ which: Callable[[str], str | None] | None = None,
+ ) -> None:
+ self._run = runner or _default_cli_runner
+ self._which = which or shutil.which
+
+ def _available(self) -> bool:
+ return self._which("nowplaying-cli") is not None
+
+ async def capability(self) -> MediaSessionCapability:
+ if self._available():
+ return MediaSessionCapability(True, True, "nowplaying-cli")
+ return MediaSessionCapability(
+ False,
+ False,
+ "none",
+ "macOS has no public now-playing API. Install nowplaying-cli "
+ "(`brew install nowplaying-cli`) so this machine can read and steer "
+ "the browser's music session; otherwise control it in YouTube Music.",
+ )
+
+ async def now_playing(self) -> NowPlaying | None:
+ if not self._available():
+ return None
+ fields = ["title", "artist", "album", "playbackRate", "elapsedTime", "duration"]
+ rc, out = await asyncio.to_thread(self._run, ["nowplaying-cli", "get", *fields])
+ if rc != 0:
+ return None
+ lines = [line.strip() for line in out.splitlines()]
+ lines += [""] * (6 - len(lines))
+ title, artist, album, rate, elapsed, duration = (
+ "" if value == "null" else value for value in lines[:6]
+ )
+ if not title and not artist:
+ return None
+ rate_f = _to_float(rate)
+ status: PlaybackStatus = "playing" if rate_f and rate_f > 0 else "paused"
+ return NowPlaying(
+ title=title,
+ artist=artist,
+ album=album,
+ app="the active player",
+ status=status,
+ position_s=_to_float(elapsed),
+ duration_s=_to_float(duration),
+ is_browser=False,
+ )
+
+ async def _command(self, verb: str) -> bool:
+ if not self._available():
+ return False
+ rc, _ = await asyncio.to_thread(self._run, ["nowplaying-cli", verb])
+ return rc == 0
+
+ async def play(self) -> bool:
+ return await self._command("play")
+
+ async def pause(self) -> bool:
+ return await self._command("pause")
+
+ async def toggle(self) -> bool:
+ return await self._command("togglePlayPause")
+
+ async def next(self) -> bool:
+ return await self._command("next")
+
+ async def previous(self) -> bool:
+ return await self._command("previous")
+
+
+def _to_float(raw: str | None) -> float | None:
+ try:
+ return float(raw) if raw not in (None, "") else None
+ except (TypeError, ValueError): # a CLI printed "null"/garbage: no number, not an error
+ return None
+
+
+# -- factory ------------------------------------------------------------------
+
+
+def make_media_session_controller() -> MediaSessionController:
+ """Per-OS backend, honest null object where nothing can be done."""
+ from jarvis.platform.capabilities import detect_capabilities
+
+ plat = detect_platform()
+ if plat == "win32":
+ return WindowsMediaSession()
+ if not detect_capabilities().display_present:
+ return NullMediaSession(
+ "This machine has no desktop session, so there is no player to read or steer."
+ )
+ if plat == "darwin":
+ return MacMediaSession()
+ return LinuxMediaSession()
+
+
+__all__ = [
+ "LinuxMediaSession",
+ "MacMediaSession",
+ "MediaSessionCapability",
+ "MediaSessionController",
+ "NowPlaying",
+ "NullMediaSession",
+ "WindowsMediaSession",
+ "app_label",
+ "is_browser_identifier",
+ "is_ytm_app_identifier",
+ "make_media_session_controller",
+ "pick_session",
+]
diff --git a/jarvis/plugins/tool/youtube_music_rest.py b/jarvis/plugins/tool/youtube_music_rest.py
new file mode 100644
index 0000000000..ad49484920
--- /dev/null
+++ b/jarvis/plugins/tool/youtube_music_rest.py
@@ -0,0 +1,914 @@
+"""youtube_music tool — play, steer and read the user's YouTube Music by voice.
+
+Google publishes NO YouTube Music API. What it does publish, and what this
+tool is built on, is the **YouTube Data API v3** — the catalog behind YouTube
+Music is YouTube's catalog (a song is a video in category 10, an album is an
+``OLAK5uy_…`` playlist, the user's playlists and likes are ordinary YouTube
+playlists and ratings). Everything the community "YouTube Music APIs" add on top
+is a reverse-engineered private client that breaks with each redesign and sits
+outside YouTube's terms, so it stays out (AP-2 spirit: an official key-backed
+path over a fragile scrape).
+
+Three facts of that API shape everything below:
+
+* **It produces no audio and offers no remote control.** There is no YouTube
+ equivalent of Spotify Connect. Playing means opening a ``music.youtube.com``
+ watch link in the user's browser — their own account, Premium and history —
+ and steering means the OS media session (``jarvis.platform.media_session``),
+ the same channel the keyboard's play/pause keys use. Reading "what is playing"
+ comes from that session too, so it works for the browser tab, the installed
+ YouTube Music app, and honestly names any other player that happens to be
+ current.
+* **Search is rationed.** Google gives every Cloud project 100 ``search.list``
+ calls a day (its own bucket, separate from the 10,000-unit pool the other
+ calls draw from), so each "play X" is one of them; results are cached per
+ process and the day's exhaustion is reported as Google's limit, not a fault.
+* **A "song" search hits videos.** The user's own playlists are matched by name
+ first (a cheap ``playlists.list``), likes are read with ``videos.list
+ myRating=like``, and every deep link is built so YouTube Music keeps going
+ after the first track (a song opens as its own radio, ``list=RDAMVM<id>``).
+
+Risk tier ``monitor``: starting music is audible and instantly reversible, and
+the writes (like, add to playlist, create playlist) are all undoable in the app.
+A direct gated action, never a spawn (AP-5/AP-14).
+"""
+from __future__ import annotations
+
+import asyncio
+import difflib
+import html
+import logging
+import re
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+from jarvis.core.protocols import ExecutionContext, ToolResult
+
+log = logging.getLogger(__name__)
+
+_API = "https://www.googleapis.com/youtube/v3"
+_MUSIC = "https://music.youtube.com"
+
+HOME_URL = f"{_MUSIC}/"
+LIKED_PAGE_URL = f"{_MUSIC}/playlist?list=LM"
+
+_NOT_CONNECTED = "YouTube Music is not connected — connect it in the Plugins view."
+_NEEDS_RECONNECT = (
+ "Google rejected the stored YouTube authorization. Reconnect YouTube Music "
+ "in the Plugins view."
+)
+_QUOTA = (
+ "Google's daily YouTube API allowance for this app is used up — it resets "
+ "at midnight Pacific time. Playback control and reading what plays still work."
+)
+_SEARCH_QUOTA = (
+ "Google allows this app 100 YouTube searches a day and they are used up — "
+ "the counter resets at midnight Pacific time. Playing one of your own "
+ "playlists, pausing, skipping and reading what plays still work."
+)
+_API_DISABLED = (
+ "The YouTube Data API v3 is not enabled in the Google Cloud project behind "
+ "your OAuth client. Enable it (APIs & Services → Library → YouTube Data API "
+ "v3) and try again."
+)
+_NO_SCOPE = (
+ "The stored Google authorization does not include YouTube. Reconnect "
+ "YouTube Music in the Plugins view and approve the YouTube permission."
+)
+_NO_BROWSER = (
+ "This machine cannot open a browser, so nothing can play here — open the "
+ "link on a device with YouTube Music."
+)
+_NO_SESSION_READ = (
+ "Nothing is registered as playing on this machine, so there is nothing to "
+ "report or control here."
+)
+
+# Music category on YouTube. Songs on YouTube Music are videos in it.
+_MUSIC_CATEGORY_ID = "10"
+_SEARCH_MAX = 25
+_ART_TRACK_SUFFIX = " - Topic"
+
+# Names people use for the liked-songs list; matched after normalisation.
+_LIKED_NAMES: frozenset[str] = frozenset({
+ "liked", "likes", "liked songs", "liked music", "my likes", "favorites", "favourites",
+ # i18n-allow: spoken-input vocabulary (de/es), not prose
+ "gelikte songs", "gelikte lieder", "geliked", "meine likes", "favoriten",
+ "lieblingslieder", "lieblingssongs",
+ "canciones que me gustan", "me gusta", "favoritos", "mis me gusta",
+})
+# Filler around a playlist name ("my running playlist" → "running").
+_PLAYLIST_NOISE_RE = re.compile(
+ r"\b(my|the|playlist"
+ r"|mein|meine|meiner|meinen|wiedergabeliste|die|der|das" # i18n-allow: spoken-input vocabulary
+ r"|mi|mis|lista|el|la)\b", # i18n-allow: spoken-input vocabulary
+ re.IGNORECASE,
+)
+
+# How long `play` watches the media session for the new track before it stops
+# claiming to know. A warm browser registers the session within a second; a
+# cold start needs four to five (measured live 2026-08-18: Edge from closed took
+# ~4 s). Bounded so a voice turn never hangs on a browser that never starts,
+# and the wait ends the moment playback is seen.
+_CONFIRM_TIMEOUT_S = 6.0
+_CONFIRM_STEP_S = 0.5
+
+
+def song_url(video_id: str) -> str:
+ """The song plus its own radio, so playback continues like in the app."""
+ return f"{_MUSIC}/watch?v={video_id}&list=RDAMVM{video_id}"
+
+
+def playlist_url(playlist_id: str, first_video_id: str | None = None) -> str:
+ """Autoplays the list (verified live 2026-08-18 for an album playlist)."""
+ if first_video_id:
+ return f"{_MUSIC}/watch?v={first_video_id}&list={playlist_id}"
+ return f"{_MUSIC}/watch?list={playlist_id}"
+
+
+def _default_token_provider() -> str | None:
+ from jarvis.marketplace.token_store import TokenStore
+
+ tokens = TokenStore().load("youtube_music")
+ return tokens.access if tokens is not None else None
+
+
+async def _default_refresher(observed_access_token: str | None = None) -> bool:
+ """Refresh the stored token in place; flags ``needs_reauth`` on a dead grant
+ so the Plugins view stops showing a green "connected" that lies."""
+ from jarvis.marketplace.connect_helpers import build_handler_from_catalog
+ from jarvis.marketplace.refresh_scheduler import refresh_plugin_token
+ from jarvis.marketplace.token_store import TokenStore
+
+ attempt = await refresh_plugin_token(
+ "youtube_music",
+ TokenStore(),
+ build_handler_from_catalog,
+ force=True,
+ observed_access_token=observed_access_token,
+ )
+ return attempt.usable
+
+
+def _default_opener(url: str) -> bool:
+ from jarvis.platform.open_path import open_url
+
+ return open_url(url)
+
+
+def _clean(text: Any) -> str:
+ return html.unescape(str(text or "")).strip()
+
+
+def _artist_from_channel(channel_title: str) -> str:
+ """Auto-generated music channels are named "<Artist> - Topic"."""
+ name = _clean(channel_title)
+ if name.endswith(_ART_TRACK_SUFFIX):
+ return name[: -len(_ART_TRACK_SUFFIX)].strip()
+ return name
+
+
+def _slim_search_item(item: dict[str, Any]) -> dict[str, Any] | None:
+ ident = item.get("id") or {}
+ snippet = item.get("snippet") or {}
+ kind = str(ident.get("kind") or "")
+ out: dict[str, Any] = {"title": _clean(snippet.get("title"))}
+ if kind.endswith("#video") and ident.get("videoId"):
+ video_id = str(ident["videoId"])
+ out.update(
+ type="song",
+ artist=_artist_from_channel(snippet.get("channelTitle", "")),
+ video_id=video_id,
+ url=song_url(video_id),
+ )
+ elif kind.endswith("#playlist") and ident.get("playlistId"):
+ playlist_id = str(ident["playlistId"])
+ out.update(
+ type="album" if playlist_id.startswith("OLAK5uy_") else "playlist",
+ owner=_artist_from_channel(snippet.get("channelTitle", "")),
+ playlist_id=playlist_id,
+ url=playlist_url(playlist_id),
+ )
+ elif kind.endswith("#channel") and ident.get("channelId"):
+ out.update(
+ type="artist",
+ channel_id=str(ident["channelId"]),
+ url=f"{_MUSIC}/channel/{ident['channelId']}",
+ )
+ else:
+ return None
+ return out
+
+
+def _slim_playlist(item: dict[str, Any]) -> dict[str, Any]:
+ snippet = item.get("snippet") or {}
+ details = item.get("contentDetails") or {}
+ playlist_id = str(item.get("id") or "")
+ out: dict[str, Any] = {
+ "title": _clean(snippet.get("title")),
+ "playlist_id": playlist_id,
+ "url": playlist_url(playlist_id),
+ }
+ if isinstance(details.get("itemCount"), int):
+ out["track_count"] = details["itemCount"]
+ return out
+
+
+def _slim_playlist_item(item: dict[str, Any]) -> dict[str, Any] | None:
+ snippet = item.get("snippet") or {}
+ video_id = ((snippet.get("resourceId") or {}).get("videoId")) or (
+ (item.get("contentDetails") or {}).get("videoId")
+ )
+ if not video_id:
+ return None
+ return {
+ "title": _clean(snippet.get("title")),
+ "artist": _artist_from_channel(snippet.get("videoOwnerChannelTitle", "")),
+ "video_id": str(video_id),
+ "url": song_url(str(video_id)),
+ }
+
+
+def _slim_video(item: dict[str, Any]) -> dict[str, Any]:
+ snippet = item.get("snippet") or {}
+ video_id = str(item.get("id") or "")
+ return {
+ "title": _clean(snippet.get("title")),
+ "artist": _artist_from_channel(snippet.get("channelTitle", "")),
+ "video_id": video_id,
+ "url": song_url(video_id),
+ }
+
+
+def _normalize_name(name: str) -> str:
+ cleaned = _PLAYLIST_NOISE_RE.sub(" ", name.lower())
+ return re.sub(r"\s+", " ", cleaned).strip()
+
+
+def is_liked_name(name: str) -> bool:
+ return _normalize_name(name) in {_normalize_name(n) for n in _LIKED_NAMES} or (
+ name.strip().lower() in _LIKED_NAMES
+ )
+
+
+def match_playlist(name: str, playlists: list[dict[str, Any]]) -> dict[str, Any] | None:
+ """The user's playlist a spoken name most plausibly means: exact, then
+ contains, then a fuzzy ratio — never a wild guess below the floor."""
+ wanted = _normalize_name(name)
+ if not wanted or not playlists:
+ return None
+ titled = [(p, _normalize_name(str(p.get("title") or ""))) for p in playlists]
+ for playlist, title in titled:
+ if title == wanted:
+ return playlist
+ for playlist, title in titled:
+ if wanted in title or (title and title in wanted):
+ return playlist
+ scored = sorted(
+ ((difflib.SequenceMatcher(None, wanted, title).ratio(), p) for p, title in titled),
+ key=lambda pair: pair[0],
+ reverse=True,
+ )
+ if scored and scored[0][0] >= 0.6:
+ return scored[0][1]
+ return None
+
+
+class YouTubeMusicRestTool:
+ name: str = "youtube_music"
+ risk_tier: str = "monitor"
+ description: str = (
+ "Play and control the user's YouTube Music: start a song, artist, album, "
+ "one of their playlists or their liked songs (opens in YouTube Music in the "
+ "browser and keeps playing like a radio), pause, resume, skip, go back, say "
+ "what is playing right now, like a song, add a song to a playlist, create a "
+ "playlist, list playlists. Use for 'play Radiohead on YouTube Music', "
+ "'skip this', 'what song is this', 'pause the music', 'like this song', "
+ "'add this to my running playlist'. Actions: now_playing, play, pause, "
+ "next, previous, search, list_playlists, playlist_tracks, liked_songs, "
+ "like, add_to_playlist, create_playlist, open. Requires the YouTube Music "
+ "plugin to be connected in the Plugins view. Volume is not controllable "
+ "here — use the system or app volume."
+ )
+ schema: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": [
+ "now_playing",
+ "play",
+ "pause",
+ "next",
+ "previous",
+ "search",
+ "list_playlists",
+ "playlist_tracks",
+ "liked_songs",
+ "like",
+ "add_to_playlist",
+ "create_playlist",
+ "open",
+ ],
+ "default": "now_playing",
+ },
+ "query": {
+ "type": "string",
+ "description": (
+ "what to play, search for, like or add: 'Radiohead', 'Karma "
+ "Police', 'OK Computer', 'my running playlist'. Leave out on "
+ "play to resume what is paused; leave out on like/add_to_playlist "
+ "to use the song playing right now."
+ ),
+ },
+ "type": {
+ "type": "string",
+ "enum": ["song", "album", "artist", "playlist", "liked"],
+ "default": "song",
+ "description": "what the query names ('liked' = the user's liked songs)",
+ },
+ "playlist": {
+ "type": "string",
+ "description": (
+ "target playlist name for add_to_playlist / playlist_tracks, or "
+ "the new playlist's name for create_playlist"
+ ),
+ },
+ "rating": {
+ "type": "string",
+ "enum": ["like", "dislike", "none"],
+ "default": "like",
+ "description": "for like: 'none' removes an earlier like or dislike",
+ },
+ "limit": {"type": "integer", "default": 5, "description": "results, max 25"},
+ },
+ "required": ["action"],
+ }
+
+ def __init__(
+ self,
+ access_token_provider: Callable[[], str | None] | None = None,
+ transport: Any | None = None,
+ token_refresher: Callable[[], Awaitable[bool]] | None = None,
+ media: Any | None = None,
+ opener: Callable[[str], bool] | None = None,
+ confirm_timeout_s: float = _CONFIRM_TIMEOUT_S,
+ ) -> None:
+ from ._http_pool import HttpClientPool
+
+ self._token_provider = access_token_provider or _default_token_provider
+ self._refresher = token_refresher
+ self._media = media
+ self._opener = opener or _default_opener
+ self._confirm_timeout_s = confirm_timeout_s
+ self._pool = HttpClientPool(transport=transport)
+ # search.list is the rationed call (100/day). Same words → same answer
+ # within a session, so a repeat costs nothing.
+ self._search_cache: dict[tuple[str, str, int], list[dict[str, Any]]] = {}
+
+ # -- media session (OS) --------------------------------------------------
+
+ def _media_controller(self) -> Any:
+ if self._media is None:
+ from jarvis.platform.media_session import make_media_session_controller
+
+ self._media = make_media_session_controller()
+ return self._media
+
+ async def _capability(self) -> Any:
+ return await self._media_controller().capability()
+
+ # -- HTTP -----------------------------------------------------------------
+
+ def _bearer(self) -> dict[str, str] | None:
+ token = self._token_provider()
+ if not token:
+ return None
+ return {"Authorization": f"Bearer {token}", "User-Agent": "Personal-Jarvis/1.0"}
+
+ async def _with_auth_retry(
+ self, do_call: Callable[[dict[str, str]], Awaitable[Any]]
+ ) -> Any:
+ """Run an authenticated call; on a 401 refresh once and retry (Google
+ access tokens live one hour, so this is the ordinary path)."""
+ import httpx
+
+ headers = self._bearer()
+ if headers is None:
+ return {"error": _NOT_CONNECTED}
+ try:
+ return await do_call(headers)
+ except httpx.HTTPStatusError as exc:
+ if exc.response.status_code != 401:
+ raise
+ observed = headers["Authorization"].removeprefix("Bearer ")
+ try:
+ if self._refresher is None:
+ refreshed = bool(await _default_refresher(observed))
+ else:
+ refreshed = bool(await self._refresher())
+ except Exception: # noqa: BLE001 — refresher must never crash the tool
+ refreshed = False
+ if not refreshed:
+ return {"error": _NEEDS_RECONNECT}
+ headers = self._bearer()
+ if headers is None:
+ return {"error": _NEEDS_RECONNECT}
+ return await do_call(headers)
+
+ async def _request(
+ self,
+ method: str,
+ path: str,
+ headers: dict[str, str],
+ *,
+ params: dict[str, Any] | None = None,
+ json_body: dict[str, Any] | None = None,
+ ) -> Any:
+ client = self._pool.client()
+ resp = await client.request(
+ method, f"{_API}{path}", params=params, json=json_body, headers=headers
+ )
+ resp.raise_for_status()
+ if resp.status_code == 204 or not resp.content:
+ return None
+ return resp.json()
+
+ @staticmethod
+ def _reason(exc: Any) -> str:
+ """Google's machine-readable failure reason (``quotaExceeded``,
+ ``accessNotConfigured``, ``insufficientPermissions`` …)."""
+ try:
+ payload = exc.response.json()
+ except Exception: # noqa: BLE001 — a non-JSON error body is still an error
+ return ""
+ error = payload.get("error") if isinstance(payload, dict) else None
+ if not isinstance(error, dict):
+ return ""
+ errors = error.get("errors")
+ if isinstance(errors, list) and errors and isinstance(errors[0], dict):
+ reason = str(errors[0].get("reason") or "")
+ if reason:
+ return reason
+ return str(error.get("status") or "")
+
+ # -- Data API reads ------------------------------------------------------
+
+ async def _search_raw(
+ self, headers: dict[str, str], *, query: str, kind: str, limit: int
+ ) -> list[dict[str, Any]]:
+ key = (kind, query.lower().strip(), limit)
+ cached = self._search_cache.get(key)
+ if cached is not None:
+ return cached
+ params: dict[str, Any] = {"part": "snippet", "q": query, "maxResults": limit}
+ if kind in ("song", "artist"):
+ params.update(type="video", videoCategoryId=_MUSIC_CATEGORY_ID)
+ elif kind == "album":
+ params["type"] = "playlist"
+ if "album" not in query.lower():
+ params["q"] = f"{query} album"
+ else: # playlist (public)
+ params["type"] = "playlist"
+ payload = await self._request("GET", "/search", headers, params=params)
+ raw = [i for i in ((payload or {}).get("items") or []) if isinstance(i, dict)]
+ slim = [s for s in (_slim_search_item(i) for i in raw) if s]
+ self._search_cache[key] = slim
+ if len(self._search_cache) > 128:
+ self._search_cache.pop(next(iter(self._search_cache)))
+ return slim
+
+ async def _my_playlists(self, headers: dict[str, str]) -> list[dict[str, Any]]:
+ payload = await self._request(
+ "GET",
+ "/playlists",
+ headers,
+ params={"part": "snippet,contentDetails", "mine": "true", "maxResults": 50},
+ )
+ items = [i for i in ((payload or {}).get("items") or []) if isinstance(i, dict)]
+ return [_slim_playlist(i) for i in items]
+
+ async def _liked(self, headers: dict[str, str], limit: int) -> list[dict[str, Any]]:
+ payload = await self._request(
+ "GET",
+ "/videos",
+ headers,
+ params={"part": "snippet", "myRating": "like", "maxResults": limit},
+ )
+ items = [i for i in ((payload or {}).get("items") or []) if isinstance(i, dict)]
+ return [_slim_video(i) for i in items]
+
+ async def _resolve_song(
+ self, headers: dict[str, str], query: str
+ ) -> dict[str, Any] | None:
+ hits = await self._search_raw(headers, query=query, kind="song", limit=1)
+ return hits[0] if hits else None
+
+ async def _resolve_playlist(
+ self, headers: dict[str, str], name: str
+ ) -> dict[str, Any] | None:
+ mine = await self._my_playlists(headers)
+ return match_playlist(name, mine)
+
+ # -- public actions ------------------------------------------------------
+
+ async def now_playing(self) -> dict[str, Any]:
+ media = self._media_controller()
+ cap = await media.capability()
+ entry = await media.now_playing() if cap.can_read else None
+ if entry is None:
+ out: dict[str, Any] = {"is_playing": False}
+ if cap.can_read:
+ out["message"] = _NO_SESSION_READ
+ else:
+ out["message"] = "This machine cannot read what is playing."
+ if cap.note:
+ out["note"] = cap.note
+ return out
+ out = entry.as_dict()
+ out["source"] = "youtube_music_app" if entry.is_youtube_music_app else (
+ "browser" if entry.is_browser else "other_player"
+ )
+ return out
+
+ async def _control(self, verb: str) -> dict[str, Any]:
+ media = self._media_controller()
+ cap = await media.capability()
+ if not cap.can_control:
+ return {"error": "This machine cannot control playback. " + (cap.note or "")}
+ before = await media.now_playing() if cap.can_read else None
+ if cap.can_read and before is None:
+ return {"error": _NO_SESSION_READ}
+ ok = bool(await getattr(media, verb)())
+ if not ok:
+ return {"error": f"The player did not accept '{verb}'."}
+ out: dict[str, Any] = {"ok": True, "action": verb}
+ if before is not None:
+ out["app"] = before.app
+ if verb in ("next", "previous"):
+ await asyncio.sleep(0.8)
+ after = await media.now_playing()
+ if after is not None:
+ out["now"] = after.as_dict()
+ else:
+ out["track"] = before.title
+ out["artist"] = before.artist
+ elif cap.backend == "media-keys":
+ out["note"] = "Sent as a media key: this toggles play/pause blindly."
+ return out
+
+ async def pause(self) -> dict[str, Any]:
+ return await self._control("pause")
+
+ async def resume(self) -> dict[str, Any]:
+ return await self._control("play")
+
+ async def next_track(self) -> dict[str, Any]:
+ return await self._control("next")
+
+ async def previous_track(self) -> dict[str, Any]:
+ return await self._control("previous")
+
+ async def search(
+ self, *, query: str, item_type: str = "song", limit: int = 5
+ ) -> dict[str, Any]:
+ capped = max(1, min(int(limit), _SEARCH_MAX))
+ kind = item_type if item_type in ("song", "album", "artist", "playlist") else "song"
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ if kind == "playlist":
+ mine = match_playlist(query, await self._my_playlists(headers))
+ if mine is not None:
+ return {"query": query, "type": kind, "results": [mine], "own": True}
+ hits = await self._search_raw(headers, query=query, kind=kind, limit=capped)
+ return {"query": query, "type": kind, "results": hits}
+
+ return await self._with_auth_retry(_do)
+
+ async def _open_and_confirm(
+ self, url: str, started: dict[str, Any] | None
+ ) -> dict[str, Any]:
+ """Open the deep link, then watch the OS media session so the answer
+ says what actually happened — including a browser that opened the page
+ but withheld autoplay."""
+ media = self._media_controller()
+ cap = await media.capability()
+ paused_app: str | None = None
+ if cap.can_read and cap.can_control:
+ before = await media.now_playing()
+ # A second tab would play on top of the first; silence the old one.
+ if before is not None and before.is_playing:
+ if await media.pause():
+ paused_app = before.app
+ opened = self._opener(url)
+ out: dict[str, Any] = {"ok": opened, "url": url}
+ if started:
+ out["started"] = started
+ if paused_app:
+ out["paused_previous"] = paused_app
+ if not opened:
+ out["error"] = _NO_BROWSER
+ return out
+ if cap.can_read:
+ wanted = (started or {}).get("title", "").lower()
+ deadline = self._confirm_timeout_s
+ elapsed = 0.0
+ confirmed = False
+ while elapsed < deadline:
+ await asyncio.sleep(_CONFIRM_STEP_S)
+ elapsed += _CONFIRM_STEP_S
+ now = await media.now_playing()
+ if now is not None and now.is_playing and now.is_browser:
+ if not wanted or wanted[:12] in now.title.lower() or (
+ started and started.get("type") != "song"
+ ):
+ out["now"] = now.as_dict()
+ confirmed = True
+ break
+ out["playback_confirmed"] = confirmed
+ if not confirmed:
+ out["note"] = (
+ "YouTube Music opened, but the browser has not reported playback "
+ "yet — if it stays silent, press play once (browsers block "
+ "autoplay on a site until it has been used there)."
+ )
+ return out
+
+ async def play(
+ self, *, query: str = "", item_type: str = "song"
+ ) -> dict[str, Any]:
+ if not query and item_type != "liked":
+ # Resume what is paused; opening the home page would start nothing.
+ resumed = await self.resume()
+ if not resumed.get("error"):
+ resumed["resumed"] = True
+ return resumed
+ return {
+ "error": (
+ "Nothing is paused that could be resumed — say what to play, "
+ "for example a song, an artist or one of your playlists."
+ )
+ }
+ kinds = ("song", "album", "artist", "playlist", "liked")
+ kind = item_type if item_type in kinds else "song"
+ if kind == "playlist" and is_liked_name(query):
+ kind = "liked"
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ if kind == "liked":
+ liked = await self._liked(headers, 1)
+ if not liked:
+ return await self._open_and_confirm(
+ LIKED_PAGE_URL, {"type": "liked", "title": "Liked songs"}
+ )
+ first = liked[0]
+ return await self._open_and_confirm(
+ playlist_url("LM", first["video_id"]),
+ {"type": "liked", "title": "Liked songs", "first": first},
+ )
+ if kind == "playlist":
+ mine = await self._resolve_playlist(headers, query)
+ if mine is not None:
+ return await self._open_and_confirm(
+ mine["url"], {"type": "playlist", "own": True, **mine}
+ )
+ hits = await self._search_raw(headers, query=query, kind="playlist", limit=1)
+ if not hits:
+ return {
+ "error": f"No playlist called {query!r} — neither yours nor a public one."
+ }
+ return await self._open_and_confirm(hits[0]["url"], hits[0])
+ if kind == "album":
+ hits = await self._search_raw(headers, query=query, kind="album", limit=3)
+ albums = [h for h in hits if h.get("type") == "album"] or hits
+ if not albums:
+ return {"error": f"YouTube Music has no album called {query!r}."}
+ return await self._open_and_confirm(albums[0]["url"], albums[0])
+ # song or artist: top song, then its radio keeps the artist's world going
+ hits = await self._search_raw(headers, query=query, kind="song", limit=1)
+ if not hits:
+ return {"error": f"YouTube Music has nothing called {query!r}."}
+ started = dict(hits[0])
+ if kind == "artist":
+ started["note"] = "Started the artist's top song; the radio continues with them."
+ return await self._open_and_confirm(started["url"], started)
+
+ return await self._with_auth_retry(_do)
+
+ async def open_home(self) -> dict[str, Any]:
+ opened = self._opener(HOME_URL)
+ if not opened:
+ return {"error": _NO_BROWSER, "url": HOME_URL}
+ return {"ok": True, "url": HOME_URL}
+
+ async def list_playlists(self) -> dict[str, Any]:
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ return {"playlists": await self._my_playlists(headers)}
+
+ return await self._with_auth_retry(_do)
+
+ async def playlist_tracks(self, *, name: str, limit: int = 10) -> dict[str, Any]:
+ capped = max(1, min(int(limit), 50))
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ if is_liked_name(name):
+ return {"playlist": "Liked songs", "tracks": await self._liked(headers, capped)}
+ mine = await self._resolve_playlist(headers, name)
+ if mine is None:
+ return {"error": f"You have no playlist called {name!r}."}
+ payload = await self._request(
+ "GET",
+ "/playlistItems",
+ headers,
+ params={
+ "part": "snippet,contentDetails",
+ "playlistId": mine["playlist_id"],
+ "maxResults": capped,
+ },
+ )
+ items = [i for i in ((payload or {}).get("items") or []) if isinstance(i, dict)]
+ tracks = [t for t in (_slim_playlist_item(i) for i in items) if t]
+ return {"playlist": mine["title"], "url": mine["url"], "tracks": tracks}
+
+ return await self._with_auth_retry(_do)
+
+ async def liked_songs(self, *, limit: int = 10) -> dict[str, Any]:
+ capped = max(1, min(int(limit), 50))
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ return {"tracks": await self._liked(headers, capped)}
+
+ return await self._with_auth_retry(_do)
+
+ async def _current_or_query_song(
+ self, headers: dict[str, str], query: str
+ ) -> dict[str, Any] | str:
+ """The song a like/add refers to: the named one, else what plays now
+ (looked up by title + artist, since the OS session carries no id)."""
+ if query:
+ found = await self._resolve_song(headers, query)
+ return found or f"YouTube Music has nothing called {query!r}."
+ media = self._media_controller()
+ cap = await media.capability()
+ now = await media.now_playing() if cap.can_read else None
+ if now is None or not now.title:
+ return "Nothing is playing that could be meant — name the song."
+ found = await self._resolve_song(headers, f"{now.title} {now.artist}".strip())
+ return found or f"Could not find {now.title!r} by {now.artist!r} on YouTube Music."
+
+ async def like(self, *, query: str = "", rating: str = "like") -> dict[str, Any]:
+ value = rating if rating in ("like", "dislike", "none") else "like"
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ song = await self._current_or_query_song(headers, query)
+ if isinstance(song, str):
+ return {"error": song}
+ await self._request(
+ "POST",
+ "/videos/rate",
+ headers,
+ params={"id": song["video_id"], "rating": value},
+ )
+ return {"ok": True, "rating": value, "song": song}
+
+ return await self._with_auth_retry(_do)
+
+ async def add_to_playlist(self, *, query: str = "", playlist: str = "") -> dict[str, Any]:
+ if not playlist:
+ return {"error": "add_to_playlist needs the playlist name."}
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ target = await self._resolve_playlist(headers, playlist)
+ if target is None:
+ return {"error": f"You have no playlist called {playlist!r} — create it first."}
+ song = await self._current_or_query_song(headers, query)
+ if isinstance(song, str):
+ return {"error": song}
+ await self._request(
+ "POST",
+ "/playlistItems",
+ headers,
+ params={"part": "snippet"},
+ json_body={
+ "snippet": {
+ "playlistId": target["playlist_id"],
+ "resourceId": {"kind": "youtube#video", "videoId": song["video_id"]},
+ }
+ },
+ )
+ return {"ok": True, "song": song, "playlist": target}
+
+ return await self._with_auth_retry(_do)
+
+ async def create_playlist(self, *, name: str) -> dict[str, Any]:
+ if not name.strip():
+ return {"error": "create_playlist needs a name."}
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ payload = await self._request(
+ "POST",
+ "/playlists",
+ headers,
+ params={"part": "snippet,status"},
+ json_body={
+ "snippet": {"title": name.strip()},
+ "status": {"privacyStatus": "private"},
+ },
+ )
+ created = _slim_playlist(payload or {})
+ created["privacy"] = "private"
+ return {"ok": True, "playlist": created}
+
+ return await self._with_auth_retry(_do)
+
+ # -- Tool protocol ------------------------------------------------------
+
+ def risk_tier_for_args(self, args: dict[str, Any]) -> str:
+ """Reads are ``safe``; everything that makes sound or writes to the
+ account is ``monitor`` (audited, no prompt) — every write is undoable
+ in the app. An unknown action stays conservative."""
+ action = (args.get("action") or "now_playing").strip()
+ if action in ("now_playing", "search", "list_playlists", "playlist_tracks", "liked_songs"):
+ return "safe"
+ if action in (
+ "play", "pause", "next", "previous", "open", "like",
+ "add_to_playlist", "create_playlist",
+ ):
+ return "monitor"
+ return "ask"
+
+ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
+ action = (args.get("action") or "now_playing").strip()
+ query = (args.get("query") or "").strip()
+ item_type = (args.get("type") or "song").strip() or "song"
+ playlist = (args.get("playlist") or "").strip()
+ limit = int(args.get("limit") or 5)
+ try:
+ if action == "now_playing":
+ out = await self.now_playing()
+ elif action == "play":
+ out = await self.play(query=query, item_type=item_type)
+ elif action == "pause":
+ out = await self.pause()
+ elif action == "next":
+ out = await self.next_track()
+ elif action == "previous":
+ out = await self.previous_track()
+ elif action == "search":
+ if not query:
+ return ToolResult(success=False, output=None, error="search needs a query")
+ out = await self.search(query=query, item_type=item_type, limit=limit)
+ elif action == "list_playlists":
+ out = await self.list_playlists()
+ elif action == "playlist_tracks":
+ name = playlist or query
+ if not name:
+ return ToolResult(
+ success=False, output=None, error="playlist_tracks needs a playlist name"
+ )
+ out = await self.playlist_tracks(name=name, limit=limit)
+ elif action == "liked_songs":
+ out = await self.liked_songs(limit=limit)
+ elif action == "like":
+ out = await self.like(query=query, rating=(args.get("rating") or "like"))
+ elif action == "add_to_playlist":
+ out = await self.add_to_playlist(query=query, playlist=playlist)
+ elif action == "create_playlist":
+ out = await self.create_playlist(name=playlist or query)
+ elif action == "open":
+ out = await self.open_home()
+ else:
+ return ToolResult(success=False, output=None, error=f"unknown action {action!r}")
+ except Exception as exc: # noqa: BLE001 — every failure becomes a spoken, actionable error
+ return ToolResult(success=False, output=None, error=self._explain(exc))
+
+ if isinstance(out, dict) and out.get("error"):
+ return ToolResult(success=False, output=None, error=out["error"])
+ return ToolResult(success=True, output=out)
+
+ @classmethod
+ def _explain(cls, exc: Exception) -> str:
+ """Turn a transport or API failure into something a person can act on."""
+ import httpx
+
+ if isinstance(exc, httpx.HTTPStatusError):
+ status = exc.response.status_code
+ reason = cls._reason(exc)
+ if status == 403:
+ if reason == "quotaExceeded":
+ if "search" in str(exc.request.url):
+ return _SEARCH_QUOTA
+ return _QUOTA
+ if reason in ("accessNotConfigured", "SERVICE_DISABLED"):
+ return _API_DISABLED
+ if reason in ("insufficientPermissions", "forbidden", "PERMISSION_DENIED"):
+ return _NO_SCOPE
+ return f"Google refused the request ({reason or 'forbidden'})."
+ if status == 404:
+ return "YouTube has no such item any more (it may have been removed)."
+ if status == 429:
+ retry = exc.response.headers.get("Retry-After", "a moment")
+ return f"Google is rate-limiting this app — try again in {retry}s."
+ if isinstance(exc, httpx.ConnectError | httpx.ConnectTimeout):
+ return "Could not reach Google. Check this machine's internet connection."
+ return str(exc)
diff --git a/jarvis/skills/builtin/__init__.py b/jarvis/skills/builtin/__init__.py
index 0589a92e17..15d9fa2893 100644
--- a/jarvis/skills/builtin/__init__.py
+++ b/jarvis/skills/builtin/__init__.py
@@ -48,6 +48,7 @@ _PLUGIN_PAIRED_SKILLS: tuple[str, ...] = (
"plugin-cal_com",
"plugin-home_assistant",
"plugin-spotify",
+ "plugin-youtube_music",
)
BUILTIN_SKILL_NAMES: tuple[str, ...] = (
diff --git a/jarvis/skills/builtin/plugin-spotify/SKILL.md b/jarvis/skills/builtin/plugin-spotify/SKILL.md
index f8ce12c725..8f50d8cb52 100644
--- a/jarvis/skills/builtin/plugin-spotify/SKILL.md
+++ b/jarvis/skills/builtin/plugin-spotify/SKILL.md
@@ -5,7 +5,7 @@ description: Play and control the user's music on Spotify.
when_to_use: Use when the user wants music — start a song, artist, album or playlist, pause, skip, go back, change the volume, queue something up, or ask what is playing right now.
category: media
plugin_id: spotify
-intent_verbs: [spiel, spiele, abspielen, pausier, pausiere, stopp, stoppe, überspring, überspringe, skip, weiter, zurück, lauter, leiser, play, pause, resume, next, previous, queue, turn, pon, reproduce, pausa, salta, siguiente, sube, baja] # i18n-allow: spoken-input vocabulary, de/en/es
+intent_verbs: [spiel, spiele, abspielen, pausier, pausiere, stopp, stoppe, überspring, überspringe, skip, weiter, zurück, play, pause, resume, next, previous, queue, turn, pon, reproduce, pausa, salta, siguiente] # i18n-allow: spoken-input vocabulary, de/en/es — bare volume verbs (lauter/leiser/sube/baja) stay out: a volume word alone is the system's volume (local-action gate); "Musik leiser" still fires via the trigger
intent_objects: [spotify, musik, music, música, lied, song, canción, track, titel, album, álbum, playlist, wiedergabeliste, lista, künstler, artist, artista, band, radio, lautstärke, volume, volumen] # i18n-allow: spoken-input vocabulary, de/en/es
triggers:
- type: voice
diff --git a/jarvis/skills/builtin/plugin-youtube_music/SKILL.md b/jarvis/skills/builtin/plugin-youtube_music/SKILL.md
new file mode 100644
index 0000000000..14e922b579
--- /dev/null
+++ b/jarvis/skills/builtin/plugin-youtube_music/SKILL.md
@@ -0,0 +1,27 @@
+---
+schema_version: "1"
+name: plugin-youtube_music
+description: Play and control the user's music on YouTube Music.
+when_to_use: Use when the user wants music on YouTube Music — start a song, artist, album, one of their playlists or their liked songs, pause, resume, skip, go back, like a song, add a song to a playlist, or ask what is playing right now.
+category: media
+plugin_id: youtube_music
+intent_verbs: [spiel, spiele, abspielen, pausier, pausiere, stopp, stoppe, überspring, überspringe, skip, weiter, zurück, like, liken, play, pause, resume, next, previous, add, pon, reproduce, pausa, salta, siguiente] # i18n-allow: spoken-input vocabulary, de/en/es
+intent_objects: [youtube music, youtube, yt music, musik, music, música, lied, song, canción, track, titel, album, álbum, playlist, wiedergabeliste, lista, künstler, artist, artista, band, radio, likes] # i18n-allow: spoken-input vocabulary, de/en/es
+triggers:
+ - type: voice
+ pattern: '(youtube ?music|yt ?music|ytmusic)' # brand-only: generic "musik"/"music" is shared with Spotify and routes by relevance + connection state
+requires_tools: [youtube_music]
+risk_policy:
+ default_tier: monitor
+---
+
+Use the connected YouTube Music to play and steer the user's music.
+
+- Play by name, not by id: pass what the user said as `query` and set `type` to what they meant — `song`, `artist`, `album`, `playlist` for "my running playlist", `liked` for "my liked songs". The tool searches and opens the top hit in YouTube Music in one step; a song opens as its own radio so playback continues.
+- "Play" with no name resumes what is paused. Do not search for something to fill the gap.
+- Say what actually started. The result carries the track and artist YouTube matched, which is often not literally what the user said — reporting it is how they catch a wrong hit immediately.
+- YouTube Music plays in the browser, not in this app. When the result says playback is not confirmed, ask the user to press play once — browsers block autoplay on a site until it has been used there. It is not an error and not a broken connection.
+- Pause, next, previous and "what is playing" go through the system's media session. If the result names another app (Spotify, a YouTube video), report that honestly. If the machine cannot control playback, say what the result says would fix it (playerctl on Linux, nowplaying-cli on macOS).
+- Volume cannot be changed here. Say so and point to the system or app volume.
+- "Like this", "add this to my X playlist": call without a `query` to act on the song playing now; the result names the song that was actually liked or added.
+- Google allows 100 searches a day for this app. When they are used up, say so plainly and offer what still works: their own playlists, pause, skip, what is playing.
diff --git a/jarvis/skills/guards.py b/jarvis/skills/guards.py
index 51172e1656..40438c0a99 100644
--- a/jarvis/skills/guards.py
+++ b/jarvis/skills/guards.py
@@ -51,6 +51,10 @@ VETO_AUTO_FIRE_NEVER = "auto_fire_never"
VETO_BAND_BELOW_FLOOR = "band_below_floor"
VETO_KILL_SWITCH = "kill_switch"
VETO_SHADOW_MODE = "shadow_mode"
+# A plugin-paired skill whose marketplace plugin holds no usable credential.
+# Applied by the brain's capture path (it needs the token store), never by the
+# pure guard ladder, so the offline routing eval stays credential-free.
+VETO_PLUGIN_NOT_CONNECTED = "plugin_not_connected"
VETO_REASONS: frozenset[str] = frozenset({
VETO_DEFINITIONAL,
@@ -65,6 +69,7 @@ VETO_REASONS: frozenset[str] = frozenset({
VETO_BAND_BELOW_FLOOR,
VETO_KILL_SWITCH,
VETO_SHADOW_MODE,
+ VETO_PLUGIN_NOT_CONNECTED,
})
#: Guard identifiers, in the order the ladder evaluates them. Exposed so the
diff --git a/jarvis/ui/web/frontend/src/assets/brands/LOGOS.md b/jarvis/ui/web/frontend/src/assets/brands/LOGOS.md
index c6fe0dd1f9..b5833ee1a5 100644
--- a/jarvis/ui/web/frontend/src/assets/brands/LOGOS.md
+++ b/jarvis/ui/web/frontend/src/assets/brands/LOGOS.md
@@ -90,6 +90,7 @@ we could not obtain. Record it below with `own work` as the legal basis.
| telegram | gilbarbara/logos `telegram.svg` | CC0 | 2026-07-25 |
| todoist | gilbarbara/logos `todoist-icon.svg` | CC0 | 2026-07-25 |
| vercel | svgl `vercel_dark.svg` (the light variant, for dark backgrounds) | MIT | 2026-07-25 |
+| youtube_music | svgl `youtube_music.svg` | MIT | 2026-08-18 |
### Deliberately not bundled
diff --git a/jarvis/ui/web/frontend/src/assets/brands/youtube_music.svg b/jarvis/ui/web/frontend/src/assets/brands/youtube_music.svg
new file mode 100644
index 0000000000..20ee6a92b6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/assets/brands/youtube_music.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" viewBox="0 0 192 192"><path fill="none" d="M0 0h192v192H0z"/><circle cx="96" cy="96" r="88" fill="red"/><path fill="#FFF" d="M96 50.32c25.19 0 45.68 20.49 45.68 45.68S121.19 141.68 96 141.68 50.32 121.19 50.32 96 70.81 50.32 96 50.32m0-6.4c-28.76 0-52.08 23.32-52.08 52.08 0 28.76 23.32 52.08 52.08 52.08s52.08-23.32 52.08-52.08c0-28.76-23.32-52.08-52.08-52.08z"/><path fill="#FFF" d="m79 122 45-26-45-26z"/></svg>
\ No newline at end of file
diff --git a/jarvis/ui/web/frontend/src/views/PluginsView.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.tsx
index 7ec1e96dbc..d63c9188fc 100644
--- a/jarvis/ui/web/frontend/src/views/PluginsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/PluginsView.tsx
@@ -2500,7 +2500,7 @@ export function PkceConnectDialog({
)}
.{" "}
{fam.family === "google" &&
- "One client covers Gmail, Drive and Calendar."}
+ "One client covers Gmail, Drive, Calendar and YouTube Music."}
</p>
{redirectUri && (
<div className="rounded-md border border-border bg-background/40 px-2.5 py-2">
diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/tool-icons.ts b/jarvis/ui/web/frontend/src/views/sub-agents/tool-icons.ts
index c4d1057e9f..3235491171 100644
--- a/jarvis/ui/web/frontend/src/views/sub-agents/tool-icons.ts
+++ b/jarvis/ui/web/frontend/src/views/sub-agents/tool-icons.ts
@@ -159,6 +159,15 @@ export function getToolAppearance(
iconColor: "text-blue-300",
};
}
+ if (matches(args, "youtube_music") || matches(args, "youtube music")) {
+ return {
+ Icon: Music,
+ label: "YouTube Music",
+ bg: "bg-red-950",
+ ring: "ring-red-500",
+ iconColor: "text-red-400",
+ };
+ }
if (matches(args, "youtube")) {
return {
Icon: Youtube,
diff --git a/pyproject.toml b/pyproject.toml
index 79df5a1da6..ebea930e2d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -328,6 +328,15 @@ desktop = [
# Windows Core Audio session control. comtypes is pycaw's COM backend.
"pycaw>=20240210; sys_platform == 'win32'",
"comtypes>=1.2; sys_platform == 'win32'",
+ # OS media session (jarvis/platform/media_session.py): read "now playing"
+ # and steer play/pause/next of the browser or the YouTube Music app through
+ # WinRT GlobalSystemMediaTransportControlsSessionManager. PyWinRT ships one
+ # wheel per namespace; the four below are exactly what the module touches.
+ # Absent, the module degrades to media keys (control only, no reading).
+ "winrt-runtime>=3.2; sys_platform == 'win32'",
+ "winrt-Windows.Foundation>=3.2; sys_platform == 'win32'",
+ "winrt-Windows.Foundation.Collections>=3.2; sys_platform == 'win32'",
+ "winrt-Windows.Media.Control>=3.2; sys_platform == 'win32'",
"pystray>=0.19",
"pywebview>=5.3",
# macOS uses pynput for global hotkeys. Linux keeps pyautogui/no-op fallbacks:
@@ -646,6 +655,17 @@ google_drive = "jarvis.plugins.tool.drive_rest:DriveRestTool"
# so it is audited without prompting. Never a spawn (AP-5/AP-14). Entry-point
# name matches the catalog native_tool + token-store key "spotify".
spotify = "jarvis.plugins.tool.spotify_rest:SpotifyRestTool"
+# YouTube Music (marketplace plugin, 2026-08-18) — search/play/like/playlists
+# over the official YouTube Data API v3 (Google publishes NO YouTube Music API;
+# the community "APIs" are reverse-engineered private clients outside YouTube's
+# terms, so they stay out) plus the OS media session for pause/skip/now-playing
+# (jarvis/platform/media_session.py). Playing opens a music.youtube.com deep
+# link in the user's browser — their own account and Premium — because YouTube
+# has no remote-playback API. Router-tier, risk_tier "monitor" (audible,
+# instantly reversible; every write is undoable in the app). Never a spawn
+# (AP-5/AP-14). Entry-point name matches the catalog native_tool + token-store
+# key "youtube_music".
+youtube_music = "jarvis.plugins.tool.youtube_music_rest:YouTubeMusicRestTool"
screen-snapshot = "jarvis.plugins.tool.screen_snapshot:ScreenSnapshotTool"
move-mouse = "jarvis.plugins.tool.move_mouse:MoveMouseTool"
switch-window = "jarvis.plugins.tool.switch_window:SwitchWindowTool"
diff --git a/tests/fixtures/skill_routing/BASELINE.json b/tests/fixtures/skill_routing/BASELINE.json
index 48d7109698..5fb0ac8747 100644
--- a/tests/fixtures/skill_routing/BASELINE.json
+++ b/tests/fixtures/skill_routing/BASELINE.json
@@ -4,8 +4,8 @@
"relevance_recall": 1.0,
"false_fires": 0,
"known_gaps": 2,
- "positives_scored": 69,
- "negatives": 24,
+ "positives_scored": 79,
+ "negatives": 26,
"per_skill": {
"cli-gcloud": 1.0,
"control-api": 0.0,
@@ -27,10 +27,12 @@
"plugin-linear": 1.0,
"plugin-notion": 1.0,
"plugin-slack": 1.0,
+ "plugin-spotify": 1.0,
"plugin-stripe": 1.0,
"plugin-supabase": 1.0,
"plugin-todoist": 1.0,
"plugin-vercel": 1.0,
+ "plugin-youtube_music": 1.0,
"skill-creator": 1.0
}
}
diff --git a/tests/fixtures/skill_routing/golden.yaml b/tests/fixtures/skill_routing/golden.yaml
index 0f123ae8df..38fc5a6ed8 100644
--- a/tests/fixtures/skill_routing/golden.yaml
+++ b/tests/fixtures/skill_routing/golden.yaml
@@ -462,6 +462,63 @@ skills:
min_band: narrow
source: authored
+ # Two connectors, one domain (2026-08-18). Spotify keeps the generic
+ # "musik"/"music" trigger; YouTube Music triggers on its brand only and
+ # otherwise routes by relevance + the brain's connection-state veto. The
+ # positives below are the DISCRIMINATIVE phrasings each side owns; anything
+ # both could mean is deliberately not scored (it would be arbitrary).
+ plugin-spotify:
+ positives:
+ - text: "spiel mir was von radiohead"
+ channel: relevance
+ lang: de
+ min_band: narrow
+ source: authored
+ - text: "pausier mal kurz"
+ channel: relevance
+ lang: de
+ min_band: narrow
+ source: authored
+ - text: "what song is this"
+ channel: relevance
+ lang: en
+ min_band: narrow
+ source: authored
+ - text: "mach den naechsten song"
+ channel: relevance
+ lang: de
+ min_band: narrow
+ source: authored
+ hard_negatives:
+ - text: "was ist spotify eigentlich fuer ein dienst"
+ reason: definitional question about the product, not a request to act
+
+ plugin-youtube_music:
+ positives:
+ - text: "play my liked songs"
+ channel: relevance
+ lang: en
+ min_band: fire
+ source: authored
+ - text: "zeig mir meine likes"
+ channel: relevance
+ lang: de
+ min_band: fire
+ source: authored
+ - text: "add this to my chill playlist"
+ channel: relevance
+ lang: en
+ min_band: fire
+ source: authored
+ - text: "like diesen song"
+ channel: relevance
+ lang: de
+ min_band: narrow
+ source: authored
+ hard_negatives:
+ - text: "was ist youtube music eigentlich"
+ reason: definitional question about the product, not a request to act
+
skill-creator:
positives:
# Upgraded relevance→trigger 2026-08-12: the new authoring trigger
diff --git a/tests/unit/brain/test_evidence_gate.py b/tests/unit/brain/test_evidence_gate.py
index b4944e6b20..28d8d71e8e 100644
--- a/tests/unit/brain/test_evidence_gate.py
+++ b/tests/unit/brain/test_evidence_gate.py
@@ -320,3 +320,14 @@ def test_live_surface_covers_matching_rule():
# Nothing attached, or nothing related, is not coverage.
assert not live_surface_covers(["calendar"], [])
assert not live_surface_covers(["calendar"], ["spawn_worker", "search_web"])
+
+
+def test_live_surface_music_terms_cover_a_lone_youtube_music_tool():
+ # 2026-08-18: two music systems, one domain. "Musik" / the brand terms must
+ # find whichever of Spotify and YouTube Music is connected, so a request
+ # is never refused with the tool sitting in the surface.
+ assert live_surface_covers(["musik"], ["youtube_music"])
+ assert live_surface_covers(["yt music"], ["youtube_music"])
+ assert live_surface_covers(["youtube music"], ["youtube_music"])
+ assert live_surface_covers(["musik"], ["spotify"])
+ assert not live_surface_covers(["musik"], ["spawn_worker", "search_web"])
diff --git a/tests/unit/brain/test_local_action_gate.py b/tests/unit/brain/test_local_action_gate.py
index 49c53d1c50..35fe7e86ba 100644
--- a/tests/unit/brain/test_local_action_gate.py
+++ b/tests/unit/brain/test_local_action_gate.py
@@ -1003,6 +1003,9 @@ class TestBrowserSearchFastPath:
"reserviere einen Tisch im Restaurant heute Abend",
"book a table at a restaurant tonight",
"bestell mir ein Ticket für den Zug nach München",
+ # 2026-08-18: YouTube Music is a connector, not generic worker work.
+ "spiel Radiohead auf YouTube Music ab",
+ "play my running playlist on yt music",
],
)
def test_booking_transactions_require_external_integration(text: str) -> None:
diff --git a/tests/unit/brain/test_paired_plugin_capture_veto.py b/tests/unit/brain/test_paired_plugin_capture_veto.py
new file mode 100644
index 0000000000..44a1b2fd3c
--- /dev/null
+++ b/tests/unit/brain/test_paired_plugin_capture_veto.py
@@ -0,0 +1,87 @@
+"""A plugin-paired skill must not capture a turn while its plugin is not
+connected (2026-08-18).
+
+Two connectors now serve the music domain — Spotify and YouTube Music both
+answer "spiel Musik" — and the trigger channel captures unconditionally, so
+without this veto the FIRST music skill would steer the model at a tool that
+can only answer "not connected" while the connected sibling sits in the tool
+surface. Judged only for catalog plugins (every one of them authenticates), on
+a real store read, and never on a fault.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+from jarvis.brain.manager import BrainManager
+from jarvis.skills import guards
+
+
+class _Store:
+ def __init__(self, tokens: dict[str, Any], *, raise_on: str | None = None) -> None:
+ self._tokens = tokens
+ self._raise_on = raise_on
+
+ def load(self, plugin_id: str) -> Any:
+ if plugin_id == self._raise_on:
+ raise RuntimeError("corrupted token blob")
+ return self._tokens.get(plugin_id)
+
+
+def _skill(plugin_id: str | None) -> Any:
+ frontmatter = SimpleNamespace(plugin_id=plugin_id)
+ return SimpleNamespace(name=f"plugin-{plugin_id}", frontmatter=frontmatter)
+
+
+def _tokens(access: str | None = "tok", needs_reauth: bool = False) -> Any:
+ return SimpleNamespace(access=access, needs_reauth=needs_reauth)
+
+
+def test_veto_reason_is_in_the_closed_vocabulary() -> None:
+ assert guards.VETO_PLUGIN_NOT_CONNECTED in guards.VETO_REASONS
+
+
+def test_disconnected_catalog_plugin_is_vetoed() -> None:
+ store = _Store({})
+ assert BrainManager._paired_plugin_disconnected(_skill("spotify"), store=store) is True
+ assert BrainManager._paired_plugin_disconnected(_skill("youtube_music"), store=store) is True
+
+
+def test_connected_plugin_is_not_vetoed() -> None:
+ store = _Store({"youtube_music": _tokens()})
+ assert BrainManager._paired_plugin_disconnected(_skill("youtube_music"), store=store) is False
+
+
+def test_reauth_flag_and_empty_access_count_as_disconnected() -> None:
+ store = _Store({"spotify": _tokens(needs_reauth=True), "gmail": _tokens(access="")})
+ assert BrainManager._paired_plugin_disconnected(_skill("spotify"), store=store) is True
+ assert BrainManager._paired_plugin_disconnected(_skill("gmail"), store=store) is True
+
+
+def test_unpaired_or_unknown_plugin_and_store_faults_never_veto() -> None:
+ store = _Store({}, raise_on="spotify")
+ assert BrainManager._paired_plugin_disconnected(_skill(None), store=store) is False
+ community = _skill("some-community-thing")
+ assert BrainManager._paired_plugin_disconnected(community, store=store) is False
+ assert BrainManager._paired_plugin_disconnected(_skill("spotify"), store=store) is False
+
+
+def test_production_path_remembers_the_answer_per_plugin(monkeypatch) -> None:
+ """The keyring read sits on the turn path, so it happens once per window,
+ not once per matched turn."""
+ import jarvis.brain.manager as manager_mod
+ from jarvis.marketplace import token_store as token_store_mod
+
+ loads: list[str] = []
+
+ class _CountingStore:
+ def load(self, plugin_id: str) -> Any:
+ loads.append(plugin_id)
+ return None
+
+ monkeypatch.setattr(token_store_mod, "TokenStore", _CountingStore)
+ monkeypatch.setattr(manager_mod, "_PAIRED_CONNECTION_CACHE", {})
+ assert BrainManager._paired_plugin_disconnected(_skill("youtube_music")) is True
+ assert BrainManager._paired_plugin_disconnected(_skill("youtube_music")) is True
+ assert BrainManager._paired_plugin_disconnected(_skill("spotify")) is True
+ assert loads == ["youtube_music", "spotify"]
diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.py
index 6fc85de46d..fe614f3268 100644
--- a/tests/unit/brain/test_routing.py
+++ b/tests/unit/brain/test_routing.py
@@ -1925,6 +1925,12 @@ def test_router_tools_is_pure_dispatcher_set() -> None:
# plugin. risk_tier "monitor" (starting music is audible and
# instantly undone). Never a spawn (AP-5/AP-14).
"spotify",
+ # YouTube Music Marketplace plugin (2026-08-18): native REST tool
+ # over the official YouTube Data API v3 plus the OS media session.
+ # Google publishes no YouTube Music API and no MCP server, so it
+ # must be router-visible directly. risk_tier "monitor". Never a
+ # spawn (AP-5/AP-14).
+ "youtube_music",
# Computer-Use (Wave 1, 2026-05-29): first-class tool to drive the
# live desktop. Router-tier only — a direct safe-gated action (the
# loop gates each action via ToolExecutor, ADR-0008), never a spawn,
diff --git a/tests/unit/marketplace/test_catalog_seed.py b/tests/unit/marketplace/test_catalog_seed.py
index 243d243dfa..51983e6260 100644
--- a/tests/unit/marketplace/test_catalog_seed.py
+++ b/tests/unit/marketplace/test_catalog_seed.py
@@ -315,3 +315,28 @@ def test_gmail_pkce_loopback_full_mail_scope() -> None:
assert spec.auth.callback_path == ""
assert spec.auth.offline_access is True
assert spec.native_tool == "gmail"
+
+
+def test_youtube_music_joins_the_google_client_family_as_native_tool() -> None:
+ # 2026-08-18: Google publishes no YouTube Music API, so the plugin rides the
+ # official YouTube Data API v3 through the SHARED Google OAuth client (one
+ # Cloud project covers Gmail, Drive, Calendar and YouTube Music) — a native
+ # tool, no MCP server, and its own loopback port so a connect never collides
+ # with a sibling Google plugin's listener.
+ spec = _seed().by_id("youtube_music")
+ assert spec is not None
+ assert spec.display_name == "YouTube Music"
+ assert spec.oauth_client_family == "google"
+ assert spec.auth.mode == "oauth_pkce_loopback"
+ assert spec.auth.scopes == ["https://www.googleapis.com/auth/youtube"]
+ assert spec.auth.client_id == "REPLACE_WITH_JARVIS_GOOGLE_CLIENT_ID"
+ assert spec.auth.offline_access is True
+ assert spec.native_tool == "youtube_music"
+ assert spec.mcp_server is None
+ assert spec.longevity == "provider_limited"
+ ports = [
+ p.auth.callback_port
+ for p in _seed().plugins
+ if getattr(p.auth, "callback_port", 0)
+ ]
+ assert ports.count(spec.auth.callback_port) == 1
diff --git a/tests/unit/platform/test_media_session.py b/tests/unit/platform/test_media_session.py
new file mode 100644
index 0000000000..e79750c927
--- /dev/null
+++ b/tests/unit/platform/test_media_session.py
@@ -0,0 +1,330 @@
+"""Unit tests for the OS media-session seam (``jarvis/platform/media_session``).
+
+Every backend is driven through its injectable fake (a WinRT-shaped manager,
+a CLI runner) — no real player, no mocks. The picker is the part that decides
+whether "pause the music" hits YouTube Music or a paused YouTube tab, so it
+gets the most attention.
+"""
+from __future__ import annotations
+
+from datetime import timedelta
+
+from jarvis.platform.media_session import (
+ LinuxMediaSession,
+ MacMediaSession,
+ NowPlaying,
+ NullMediaSession,
+ WindowsMediaSession,
+ app_label,
+ is_browser_identifier,
+ pick_session,
+)
+
+# -- shared helpers -----------------------------------------------------------
+
+
+def _np(title: str, app: str, status: str, browser: bool, ytm: bool = False) -> NowPlaying:
+ return NowPlaying(
+ title=title,
+ artist="a",
+ album="",
+ app=app,
+ status=status, # type: ignore[arg-type]
+ is_browser=browser,
+ is_youtube_music_app=ytm,
+ )
+
+
+def test_app_label_maps_raw_identifiers_to_names():
+ assert app_label("Chrome") == "Google Chrome"
+ assert app_label("MSEdge") == "Microsoft Edge"
+ assert app_label("Chrome._crx_cinhimbnkkaeohfgghhklpknlkffjgod") == "YouTube Music app"
+ assert app_label("SpotifyAB.SpotifyMusic_zpdnekdrzrea0!Spotify") == "Spotify"
+ assert app_label("") == "unknown app"
+ assert app_label("SomeUnknownPlayer") == "SomeUnknownPlayer"
+
+
+def test_browser_identifier_detection():
+ assert is_browser_identifier("Chrome")
+ assert is_browser_identifier("firefox.instance1234")
+ assert is_browser_identifier("Chrome._crx_cinhimbnkkaeohfgghhklpknlkffjgod")
+ assert not is_browser_identifier("Spotify.exe")
+
+
+def test_pick_session_prefers_playing_browser_over_current_paused_tab():
+ """Two Chrome tabs: a paused YouTube video is the OS's "current" session,
+ YouTube Music plays in the other. The music wins."""
+ paused_video = _np("Some video", "Google Chrome", "paused", browser=True)
+ music = _np("Karma Police", "Google Chrome", "playing", browser=True)
+ assert pick_session([(paused_video, True), (music, False)]) is music
+
+
+def test_pick_session_prefers_browser_over_other_player():
+ spotify = _np("x", "Spotify", "playing", browser=False)
+ tab = _np("y", "Google Chrome", "paused", browser=True)
+ assert pick_session([(spotify, True), (tab, False)]) is tab
+
+
+def test_pick_session_prefers_the_youtube_music_app_over_a_tab():
+ tab = _np("y", "Google Chrome", "playing", browser=True)
+ app = _np("z", "YouTube Music app", "paused", browser=True, ytm=True)
+ assert pick_session([(tab, True), (app, False)]) is app
+
+
+def test_pick_session_uses_current_as_tiebreak_and_handles_empty():
+ a = _np("a", "Google Chrome", "paused", browser=True)
+ b = _np("b", "Google Chrome", "paused", browser=True)
+ assert pick_session([(a, False), (b, True)]) is b
+ assert pick_session([]) is None
+
+
+def test_now_playing_as_dict_is_speech_sized():
+ entry = NowPlaying("T", "A", "Al", "Google Chrome", "playing", 12.4, 200.6)
+ out = entry.as_dict()
+ assert out == {
+ "is_playing": True,
+ "status": "playing",
+ "track": "T",
+ "artist": "A",
+ "app": "Google Chrome",
+ "album": "Al",
+ "position_s": 12,
+ "duration_s": 201,
+ }
+
+
+# -- Windows (WinRT-shaped fakes) --------------------------------------------
+
+
+class _Props:
+ def __init__(self, title: str, artist: str, album: str = "") -> None:
+ self.title, self.artist, self.album_title = title, artist, album
+
+
+class _Playback:
+ def __init__(self, status: int) -> None:
+ self.playback_status = status
+
+
+class _Timeline:
+ def __init__(self) -> None:
+ self.position = timedelta(seconds=30)
+ self.end_time = timedelta(seconds=180)
+
+
+class _FakeSession:
+ def __init__(self, aumid: str, title: str, artist: str, status: int) -> None:
+ self.source_app_user_model_id = aumid
+ self._props = _Props(title, artist)
+ self._status = status
+ self.calls: list[str] = []
+
+ async def try_get_media_properties_async(self):
+ return self._props
+
+ def get_playback_info(self):
+ return _Playback(self._status)
+
+ def get_timeline_properties(self):
+ return _Timeline()
+
+ async def try_pause_async(self):
+ self.calls.append("pause")
+ self._status = 5
+ return True
+
+ async def try_play_async(self):
+ self.calls.append("play")
+ self._status = 4
+ return True
+
+ async def try_toggle_play_pause_async(self):
+ self.calls.append("toggle")
+ return True
+
+ async def try_skip_next_async(self):
+ self.calls.append("next")
+ return True
+
+ async def try_skip_previous_async(self):
+ self.calls.append("previous")
+ return True
+
+
+class _FakeManager:
+ def __init__(self, sessions: list[_FakeSession], current: _FakeSession | None) -> None:
+ self._sessions = sessions
+ self._current = current
+
+ def get_current_session(self):
+ return self._current
+
+ def get_sessions(self):
+ return list(self._sessions)
+
+
+def _windows(sessions, current):
+ async def factory():
+ return _FakeManager(sessions, current)
+
+ return WindowsMediaSession(manager_factory=factory, key_sender=lambda vk: True)
+
+
+async def test_windows_reads_the_current_session_once_despite_shared_app_id():
+ """Chrome registers every tab under the same app id — the current one must
+ not be double-counted or confused with a sibling tab."""
+ video = _FakeSession("Chrome", "Some video", "Channel", 5)
+ music = _FakeSession("Chrome", "Karma Police", "Radiohead", 4)
+ backend = _windows([video, music], current=video)
+ rows = await backend._sessions()
+ assert [(e.title, is_current) for e, is_current, _ in rows] == [
+ ("Some video", True),
+ ("Karma Police", False),
+ ]
+ now = await backend.now_playing()
+ assert now is not None and now.title == "Karma Police" and now.is_playing
+ assert now.app == "Google Chrome" and now.position_s == 30.0
+
+
+async def test_windows_pause_targets_the_picked_session_not_the_current_one():
+ video = _FakeSession("Chrome", "Some video", "Channel", 5)
+ music = _FakeSession("Chrome", "Karma Police", "Radiohead", 4)
+ backend = _windows([video, music], current=video)
+ assert await backend.pause() is True
+ assert music.calls == ["pause"] and video.calls == []
+
+
+async def test_windows_next_and_previous_reach_the_session():
+ music = _FakeSession("Chrome", "Karma Police", "Radiohead", 4)
+ backend = _windows([music], current=music)
+ assert await backend.next() is True
+ assert await backend.previous() is True
+ assert music.calls == ["next", "previous"]
+
+
+async def test_windows_capability_and_no_sessions():
+ backend = _windows([], current=None)
+ cap = await backend.capability()
+ assert cap.can_read and cap.can_control and cap.backend == "winrt"
+ assert await backend.now_playing() is None
+ assert await backend.pause() is False # WinRT present, nothing registered: no blind key
+
+
+async def test_windows_without_winrt_falls_back_to_media_keys():
+ sent: list[int] = []
+
+ def sender(vk: int) -> bool:
+ sent.append(vk)
+ return True
+
+ backend = WindowsMediaSession(manager_factory=None, key_sender=sender)
+ backend._winrt_checked = True # pretend the import already failed
+ backend._winrt_cls = None
+ cap = await backend.capability()
+ assert cap.can_read is False and cap.can_control is True and cap.backend == "media-keys"
+ assert "desktop" in cap.note
+ assert await backend.now_playing() is None
+ assert await backend.pause() is True and sent == [0xB3]
+ assert await backend.next() is True and sent[-1] == 0xB0
+
+
+async def test_windows_survives_a_broken_manager():
+ async def factory():
+ raise RuntimeError("winrt exploded")
+
+ backend = WindowsMediaSession(manager_factory=factory, key_sender=lambda vk: True)
+ assert await backend.now_playing() is None
+ assert await backend.pause() is False
+
+
+# -- Linux (playerctl fakes) --------------------------------------------------
+
+
+def _linux(outputs: dict[tuple[str, ...], tuple[int, str]], have_playerctl: bool = True):
+ calls: list[list[str]] = []
+
+ def runner(argv):
+ calls.append(list(argv))
+ return outputs.get(tuple(argv), (1, ""))
+
+ backend = LinuxMediaSession(
+ runner=runner, which=lambda name: "/usr/bin/playerctl" if have_playerctl else None
+ )
+ return backend, calls
+
+
+async def test_linux_reads_and_controls_the_browser_player():
+ fmt = "{{title}}\x1f{{artist}}\x1f{{album}}\x1f{{position}}\x1f{{mpris:length}}"
+ outputs = {
+ ("playerctl", "-l"): (0, "spotify\nchromium.instance42\n"),
+ ("playerctl", "-p", "spotify", "status"): (0, "Playing\n"),
+ ("playerctl", "-p", "spotify", "metadata", "--format", fmt): (
+ 0,
+ "Song\x1fBand\x1f\x1f10\x1f200000000\n",
+ ),
+ ("playerctl", "-p", "chromium.instance42", "status"): (0, "Paused\n"),
+ ("playerctl", "-p", "chromium.instance42", "metadata", "--format", fmt): (
+ 0,
+ "Karma Police\x1fRadiohead\x1fOK Computer\x1f31\x1f265000000\n",
+ ),
+ ("playerctl", "-p", "chromium.instance42", "pause"): (0, ""),
+ }
+ backend, calls = _linux(outputs)
+ cap = await backend.capability()
+ assert cap.can_read and cap.can_control and cap.backend == "playerctl"
+ now = await backend.now_playing()
+ assert now is not None
+ assert now.title == "Karma Police" and now.app == "Chromium" and now.status == "paused"
+ assert now.duration_s == 265.0 and now.position_s == 31.0
+ assert await backend.pause() is True
+ assert ["playerctl", "-p", "chromium.instance42", "pause"] in calls
+
+
+async def test_linux_without_playerctl_degrades_honestly():
+ backend, calls = _linux({}, have_playerctl=False)
+ cap = await backend.capability()
+ assert cap.can_read is False and cap.can_control is False
+ assert "playerctl" in cap.note
+ assert await backend.now_playing() is None
+ assert await backend.next() is False
+ assert calls == []
+
+
+# -- macOS (nowplaying-cli fakes) --------------------------------------------
+
+
+async def test_mac_reads_and_controls_via_nowplaying_cli():
+ calls: list[list[str]] = []
+
+ def runner(argv):
+ calls.append(list(argv))
+ if argv[:2] == ["nowplaying-cli", "get"]:
+ return 0, "Karma Police\nRadiohead\nOK Computer\n1\n42.5\n265\n"
+ return 0, ""
+
+ backend = MacMediaSession(runner=runner, which=lambda name: "/opt/homebrew/bin/nowplaying-cli")
+ now = await backend.now_playing()
+ assert now is not None and now.title == "Karma Police" and now.is_playing
+ assert now.position_s == 42.5 and now.duration_s == 265.0
+ assert await backend.pause() is True
+ assert calls[-1] == ["nowplaying-cli", "pause"]
+
+
+async def test_mac_null_fields_and_missing_tool():
+ def runner(argv):
+ return 0, "null\nnull\nnull\n0\nnull\nnull\n"
+
+ present = MacMediaSession(runner=runner, which=lambda name: "/x/nowplaying-cli")
+ assert await present.now_playing() is None
+ absent = MacMediaSession(runner=runner, which=lambda name: None)
+ cap = await absent.capability()
+ assert not cap.can_read and not cap.can_control and "brew install" in cap.note
+ assert await absent.play() is False
+
+
+async def test_null_backend_is_honest():
+ backend = NullMediaSession("no desktop here")
+ cap = await backend.capability()
+ assert cap.backend == "none" and cap.note == "no desktop here"
+ assert await backend.now_playing() is None
+ assert await backend.toggle() is False
diff --git a/tests/unit/plugins/tool/test_youtube_music_rest.py b/tests/unit/plugins/tool/test_youtube_music_rest.py
new file mode 100644
index 0000000000..6541560ff2
--- /dev/null
+++ b/tests/unit/plugins/tool/test_youtube_music_rest.py
@@ -0,0 +1,526 @@
+"""Unit tests for the YouTube Music tool.
+
+Weighted towards what decides whether the plugin is usable: the deep links it
+opens (a song must open as its own radio, an album as its playlist), the OS
+media session it steers, the rationed search, and Google's three real
+refusals — quota, API not enabled, missing scope.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import httpx
+
+from jarvis.platform.media_session import MediaSessionCapability, NowPlaying
+from jarvis.plugins.tool.youtube_music_rest import (
+ HOME_URL,
+ YouTubeMusicRestTool,
+ match_playlist,
+ playlist_url,
+ song_url,
+)
+
+_FAKE_TOKEN = "tok123" # noqa: S105 — a literal for MockTransport, not a credential
+
+_SONG_HIT = {
+ "id": {"kind": "youtube#video", "videoId": "vid123"},
+ "snippet": {"title": "Karma Police", "channelTitle": "Radiohead - Topic"},
+}
+_ALBUM_HIT = {
+ "id": {"kind": "youtube#playlist", "playlistId": "OLAK5uy_abc"},
+ "snippet": {"title": "OK Computer", "channelTitle": "Radiohead - Topic"},
+}
+_MY_PLAYLISTS = {
+ "items": [
+ {
+ "id": "PLrun",
+ "snippet": {"title": "Running 2026"},
+ "contentDetails": {"itemCount": 12},
+ },
+ {"id": "PLchill", "snippet": {"title": "Chill evenings"}, "contentDetails": {}},
+ ]
+}
+
+
+class FakeMedia:
+ """A media session that remembers what it was told to do."""
+
+ def __init__(
+ self,
+ now: NowPlaying | None = None,
+ can_read: bool = True,
+ can_control: bool = True,
+ backend: str = "fake",
+ note: str = "",
+ after_open: NowPlaying | None = None,
+ ) -> None:
+ self.now = now
+ self.after_open = after_open
+ self.cap = MediaSessionCapability(can_read, can_control, backend, note)
+ self.calls: list[str] = []
+ self.opened = False
+
+ async def capability(self):
+ return self.cap
+
+ async def now_playing(self):
+ if self.opened and self.after_open is not None:
+ return self.after_open
+ return self.now
+
+ async def play(self):
+ self.calls.append("play")
+ return True
+
+ async def pause(self):
+ self.calls.append("pause")
+ return True
+
+ async def toggle(self):
+ self.calls.append("toggle")
+ return True
+
+ async def next(self):
+ self.calls.append("next")
+ return True
+
+ async def previous(self):
+ self.calls.append("previous")
+ return True
+
+
+def _playing(title="Karma Police", artist="Radiohead", app="Google Chrome", browser=True):
+ return NowPlaying(title, artist, "OK Computer", app, "playing", 10.0, 260.0, browser)
+
+
+def _paused(title="Karma Police", artist="Radiohead"):
+ return NowPlaying(title, artist, "", "Google Chrome", "paused", 10.0, 260.0, True)
+
+
+class Opener:
+ def __init__(self, ok: bool = True, media: FakeMedia | None = None) -> None:
+ self.ok = ok
+ self.urls: list[str] = []
+ self.media = media
+
+ def __call__(self, url: str) -> bool:
+ self.urls.append(url)
+ if self.media is not None:
+ self.media.opened = True
+ return self.ok
+
+
+def _tool(handler, media=None, opener=None, token=_FAKE_TOKEN, refresher=None):
+ return YouTubeMusicRestTool(
+ access_token_provider=lambda: token,
+ transport=httpx.MockTransport(handler),
+ token_refresher=refresher,
+ media=media or FakeMedia(),
+ opener=opener or Opener(),
+ confirm_timeout_s=0.6,
+ )
+
+
+def _google_error(status: int, reason: str, message: str = "nope") -> httpx.Response:
+ return httpx.Response(
+ status,
+ json={
+ "error": {
+ "code": status,
+ "message": message,
+ "errors": [{"reason": reason, "domain": "youtube.quota"}],
+ }
+ },
+ )
+
+
+def _search_handler(request: httpx.Request) -> httpx.Response:
+ if request.url.path.endswith("/search"):
+ kind = request.url.params.get("type")
+ if kind == "video":
+ assert request.url.params.get("videoCategoryId") == "10"
+ return httpx.Response(200, json={"items": [_SONG_HIT]})
+ return httpx.Response(200, json={"items": [_ALBUM_HIT]})
+ if request.url.path.endswith("/playlists"):
+ return httpx.Response(200, json=_MY_PLAYLISTS)
+ return httpx.Response(404, json={"error": {"code": 404, "message": "?"}})
+
+
+# -- deep links ---------------------------------------------------------------
+
+
+def test_song_url_opens_the_song_as_its_own_radio():
+ assert song_url("abc") == "https://music.youtube.com/watch?v=abc&list=RDAMVMabc"
+
+
+def test_playlist_url_shapes():
+ assert playlist_url("PL1") == "https://music.youtube.com/watch?list=PL1"
+ assert playlist_url("LM", "v1") == "https://music.youtube.com/watch?v=v1&list=LM"
+
+
+def test_match_playlist_exact_contains_fuzzy_and_floor():
+ lists = [{"title": "Running 2026"}, {"title": "Chill evenings"}, {"title": "Workout"}]
+ assert match_playlist("running 2026", lists)["title"] == "Running 2026"
+ assert match_playlist("my running playlist", lists)["title"] == "Running 2026"
+ assert match_playlist("chill evening", lists)["title"] == "Chill evenings"
+ assert match_playlist("wrkout", lists)["title"] == "Workout"
+ assert match_playlist("jazz classics", lists) is None
+ assert match_playlist("", lists) is None
+
+
+# -- search -------------------------------------------------------------------
+
+
+async def test_search_song_slims_and_strips_topic_suffix():
+ out = await _tool(_search_handler).search(query="karma police", item_type="song")
+ assert out["results"] == [
+ {
+ "title": "Karma Police",
+ "type": "song",
+ "artist": "Radiohead",
+ "video_id": "vid123",
+ "url": song_url("vid123"),
+ }
+ ]
+
+
+async def test_search_is_cached_per_process_because_google_rations_it():
+ calls = {"n": 0}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls["n"] += 1
+ return _search_handler(request)
+
+ tool = _tool(handler)
+ await tool.search(query="Karma Police", item_type="song")
+ await tool.search(query="karma police", item_type="song")
+ assert calls["n"] == 1
+
+
+async def test_search_album_asks_for_playlists_and_labels_olak_as_album():
+ out = await _tool(_search_handler).search(query="OK Computer", item_type="album")
+ assert out["results"][0]["type"] == "album"
+ assert out["results"][0]["url"] == playlist_url("OLAK5uy_abc")
+
+
+async def test_search_playlist_prefers_the_users_own_lists():
+ out = await _tool(_search_handler).search(query="my running playlist", item_type="playlist")
+ assert out["own"] is True
+ assert out["results"][0]["playlist_id"] == "PLrun"
+
+
+async def test_not_connected_without_token():
+ tool = YouTubeMusicRestTool(access_token_provider=lambda: None, media=FakeMedia())
+ out = await tool.search(query="x")
+ assert "not connected" in out["error"].lower()
+
+
+# -- play ---------------------------------------------------------------------
+
+
+async def test_play_song_pauses_the_old_player_opens_the_radio_link_and_confirms():
+ media = FakeMedia(now=_playing("Old song", "Someone"), after_open=_playing())
+ opener = Opener(media=media)
+ out = await _tool(_search_handler, media=media, opener=opener).play(query="karma police")
+ assert opener.urls == [song_url("vid123")]
+ assert media.calls == ["pause"]
+ assert out["paused_previous"] == "Google Chrome"
+ assert out["started"]["title"] == "Karma Police"
+ assert out["playback_confirmed"] is True
+ assert out["now"]["track"] == "Karma Police"
+
+
+async def test_play_reports_when_the_browser_withholds_autoplay():
+ media = FakeMedia(now=None, after_open=_paused())
+ opener = Opener(media=media)
+ out = await _tool(_search_handler, media=media, opener=opener).play(query="karma police")
+ assert out["ok"] is True and out["playback_confirmed"] is False
+ assert "press play" in out["note"]
+
+
+async def test_play_without_browser_returns_the_link_honestly():
+ opener = Opener(ok=False)
+ out = await _tool(_search_handler, opener=opener).play(query="karma police")
+ assert out["url"] == song_url("vid123")
+ assert "cannot open a browser" in out["error"]
+
+
+async def test_play_artist_opens_top_song_radio_with_a_note():
+ opener = Opener()
+ out = await _tool(_search_handler, opener=opener).play(query="Radiohead", item_type="artist")
+ assert opener.urls == [song_url("vid123")]
+ assert "radio" in out["started"]["note"]
+
+
+async def test_play_album_opens_the_album_playlist():
+ opener = Opener()
+ out = await _tool(_search_handler, opener=opener).play(query="OK Computer", item_type="album")
+ assert opener.urls == [playlist_url("OLAK5uy_abc")]
+ assert out["started"]["type"] == "album"
+
+
+async def test_play_own_playlist_by_fuzzy_name_costs_no_search():
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert not request.url.path.endswith("/search"), "own playlist must not burn a search"
+ return _search_handler(request)
+
+ opener = Opener()
+ tool = _tool(handler, opener=opener)
+ out = await tool.play(query="my running playlist", item_type="playlist")
+ assert opener.urls == [playlist_url("PLrun")]
+ assert out["started"]["own"] is True
+
+
+async def test_play_liked_songs_uses_the_first_like_and_the_lm_list():
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.url.path.endswith("/videos"):
+ assert request.url.params.get("myRating") == "like"
+ return httpx.Response(
+ 200,
+ json={
+ "items": [
+ {"id": "likedvid", "snippet": {"title": "Angels", "channelTitle": "Robbie"}}
+ ]
+ },
+ )
+ return _search_handler(request)
+
+ opener = Opener()
+ out = await _tool(handler, opener=opener).play(query="liked songs", item_type="playlist")
+ assert opener.urls == [playlist_url("LM", "likedvid")]
+ assert out["started"]["type"] == "liked"
+
+
+async def test_play_without_query_resumes_the_paused_session():
+ media = FakeMedia(now=_paused())
+ out = await _tool(_search_handler, media=media).play(query="")
+ assert media.calls == ["play"] and out["resumed"] is True and out["track"] == "Karma Police"
+
+
+async def test_play_without_query_and_nothing_paused_asks_for_a_name():
+ media = FakeMedia(now=None)
+ out = await _tool(_search_handler, media=media).play(query="")
+ assert "say what to play" in out["error"]
+
+
+async def test_play_unknown_song_says_so():
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"items": []})
+
+ out = await _tool(handler).play(query="zzz")
+ assert "nothing called" in out["error"]
+
+
+# -- media session actions ---------------------------------------------------
+
+
+async def test_now_playing_reports_the_session_and_its_source():
+ media = FakeMedia(now=_playing())
+ out = await _tool(_search_handler, media=media).now_playing()
+ assert out["track"] == "Karma Police" and out["is_playing"] and out["source"] == "browser"
+
+
+async def test_now_playing_without_read_capability_carries_the_fix():
+ media = FakeMedia(now=None, can_read=False, backend="media-keys", note="install X")
+ out = await _tool(_search_handler, media=media).now_playing()
+ assert out["is_playing"] is False and out["note"] == "install X"
+
+
+async def test_pause_and_next_report_the_app_and_new_track():
+ media = FakeMedia(now=_playing())
+ tool = _tool(_search_handler, media=media)
+ out = await tool.pause()
+ assert out["ok"] and out["app"] == "Google Chrome" and out["track"] == "Karma Police"
+ out = await tool.next_track()
+ assert out["ok"] and out["now"]["track"] == "Karma Police"
+ assert media.calls == ["pause", "next"]
+
+
+async def test_control_without_capability_is_an_honest_error():
+ media = FakeMedia(now=None, can_read=False, can_control=False, note="brew install it")
+ out = await _tool(_search_handler, media=media).pause()
+ assert "cannot control" in out["error"] and "brew install it" in out["error"]
+
+
+async def test_control_with_nothing_registered_is_an_error():
+ out = await _tool(_search_handler, media=FakeMedia(now=None)).next_track()
+ assert "Nothing is registered" in out["error"]
+
+
+# -- library writes -----------------------------------------------------------
+
+
+async def test_like_current_song_looks_it_up_by_title_and_artist():
+ seen: dict[str, Any] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.url.path.endswith("/search"):
+ seen["q"] = request.url.params.get("q")
+ return httpx.Response(200, json={"items": [_SONG_HIT]})
+ if request.url.path.endswith("/videos/rate"):
+ seen["rate"] = dict(request.url.params)
+ return httpx.Response(204)
+ return httpx.Response(404)
+
+ media = FakeMedia(now=_playing())
+ out = await _tool(handler, media=media).like()
+ assert seen["q"] == "Karma Police Radiohead"
+ assert seen["rate"] == {"id": "vid123", "rating": "like"}
+ assert out["ok"] and out["song"]["title"] == "Karma Police"
+
+
+async def test_like_with_nothing_playing_asks_for_the_song():
+ out = await _tool(_search_handler, media=FakeMedia(now=None)).like()
+ assert "name the song" in out["error"]
+
+
+async def test_add_to_playlist_inserts_into_the_matched_list():
+ seen: dict[str, Any] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.method == "POST" and request.url.path.endswith("/playlistItems"):
+ import json
+
+ seen["body"] = json.loads(request.content)
+ return httpx.Response(200, json={"id": "item1"})
+ return _search_handler(request)
+
+ out = await _tool(handler).add_to_playlist(query="karma police", playlist="running")
+ assert seen["body"]["snippet"]["playlistId"] == "PLrun"
+ assert seen["body"]["snippet"]["resourceId"]["videoId"] == "vid123"
+ assert out["playlist"]["title"] == "Running 2026"
+
+
+async def test_add_to_playlist_unknown_list_says_create_it():
+ out = await _tool(_search_handler).add_to_playlist(query="x", playlist="jazz classics")
+ assert "create it first" in out["error"]
+
+
+async def test_create_playlist_is_private_by_default():
+ seen: dict[str, Any] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ import json
+
+ seen["body"] = json.loads(request.content)
+ return httpx.Response(
+ 200, json={"id": "PLnew", "snippet": {"title": "Late night"}, "contentDetails": {}}
+ )
+
+ out = await _tool(handler).create_playlist(name="Late night")
+ assert seen["body"]["status"]["privacyStatus"] == "private"
+ assert out["playlist"]["playlist_id"] == "PLnew" and out["playlist"]["privacy"] == "private"
+
+
+async def test_playlist_tracks_lists_a_named_playlist():
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.url.path.endswith("/playlistItems"):
+ assert request.url.params.get("playlistId") == "PLchill"
+ return httpx.Response(
+ 200,
+ json={
+ "items": [
+ {
+ "snippet": {
+ "title": "Angels",
+ "videoOwnerChannelTitle": "Robbie Williams - Topic",
+ "resourceId": {"videoId": "v9"},
+ }
+ }
+ ]
+ },
+ )
+ return _search_handler(request)
+
+ out = await _tool(handler).playlist_tracks(name="chill evenings")
+ assert out["playlist"] == "Chill evenings"
+ assert out["tracks"] == [
+ {"title": "Angels", "artist": "Robbie Williams", "video_id": "v9", "url": song_url("v9")}
+ ]
+
+
+# -- auth + Google's refusals -------------------------------------------------
+
+
+async def test_401_triggers_one_refresh_and_retry():
+ current = {"value": "old"}
+ calls: list[str] = []
+
+ async def refresher() -> bool:
+ current["value"] = "new"
+ return True
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls.append(request.headers["Authorization"])
+ if request.headers["Authorization"] == "Bearer old":
+ return httpx.Response(401, json={"error": {"code": 401, "message": "expired"}})
+ return httpx.Response(200, json=_MY_PLAYLISTS)
+
+ tool = YouTubeMusicRestTool(
+ access_token_provider=lambda: current["value"],
+ transport=httpx.MockTransport(handler),
+ token_refresher=refresher,
+ media=FakeMedia(),
+ opener=Opener(),
+ )
+ out = await tool.list_playlists()
+ assert calls == ["Bearer old", "Bearer new"]
+ assert len(out["playlists"]) == 2
+
+
+async def test_failed_refresh_asks_to_reconnect():
+ async def refresher() -> bool:
+ return False
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(401, json={"error": {"code": 401}})
+
+ out = await _tool(handler, refresher=refresher).list_playlists()
+ assert "Reconnect" in out["error"]
+
+
+async def test_execute_explains_search_quota_api_disabled_and_scope():
+ def quota(request: httpx.Request) -> httpx.Response:
+ return _google_error(403, "quotaExceeded")
+
+ res = await _tool(quota).execute({"action": "search", "query": "x"}, ctx=None) # type: ignore[arg-type]
+ assert not res.success and "100 YouTube searches" in res.error
+
+ def disabled(request: httpx.Request) -> httpx.Response:
+ return _google_error(403, "accessNotConfigured", "YouTube Data API v3 has not been used")
+
+ res = await _tool(disabled).execute({"action": "list_playlists"}, ctx=None) # type: ignore[arg-type]
+ assert "not enabled" in res.error
+
+ def scope(request: httpx.Request) -> httpx.Response:
+ return _google_error(403, "insufficientPermissions")
+
+ res = await _tool(scope).execute({"action": "liked_songs"}, ctx=None) # type: ignore[arg-type]
+ assert "approve the YouTube permission" in res.error
+
+
+# -- tool protocol ------------------------------------------------------------
+
+
+def test_risk_tiers_reads_safe_everything_else_monitor():
+ tool = YouTubeMusicRestTool(access_token_provider=lambda: None, media=FakeMedia())
+ for action in ("now_playing", "search", "list_playlists", "playlist_tracks", "liked_songs"):
+ assert tool.risk_tier_for_args({"action": action}) == "safe"
+ for action in ("play", "pause", "next", "previous", "open", "like", "add_to_playlist"):
+ assert tool.risk_tier_for_args({"action": action}) == "monitor"
+ assert tool.risk_tier_for_args({"action": "nuke"}) == "ask"
+
+
+async def test_execute_routes_and_validates():
+ opener = Opener()
+ tool = _tool(_search_handler, media=FakeMedia(now=_playing()), opener=opener)
+ res = await tool.execute({"action": "open"}, ctx=None) # type: ignore[arg-type]
+ assert res.success and opener.urls == [HOME_URL]
+ res = await tool.execute({"action": "search"}, ctx=None) # type: ignore[arg-type]
+ assert not res.success and "needs a query" in res.error
+ res = await tool.execute({"action": "playlist_tracks"}, ctx=None) # type: ignore[arg-type]
+ assert not res.success and "playlist name" in res.error
+ res = await tool.execute({"action": "teleport"}, ctx=None) # type: ignore[arg-type]
+ assert not res.success and "unknown action" in res.error
+ res = await tool.execute({"action": "now_playing"}, ctx=None) # type: ignore[arg-type]
+ assert res.success and res.output["track"] == "Karma Police"