SLOPSHOPPER

jukebox7

Plays music from YouTube when asked in plain words, audio only through a hidden VLC, with a small control pane

panecommandtoaststatuspromptmodel
★ 1v0.2.0MITupdated 2026-10-15KTCrisis/flux7-mods/jukebox7
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · jukebox7
│ ┃ jukebox7 ✕ › fix the failing auth test and add an audit log call │ ┃ ╭─────────────────────────────────────────── │ ┃ │ ■ Nothing plays. ⏺ Read(src/auth.ts) │ ┃ │ 1: ambient 2: alt 90s 3: metal 4: synth ⎿ Read 6 lines │ ┃ ╰─────────────────────────────────────────── ⏺ Update(src/auth.ts) │ ┃ 3 ミ ケ ク ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ ュ キ シ ⎿ 3 pass, 1 fail │ ┃ マ │ ┃ 9 ッ イ ヤ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ウ │ ┃ ワ チ ョ マ ✻ Worked for 42s · done 4:20 PM │ ┃ キ │ ┃ ォ ヨ ネ シ › /music │ ┃ ハ ⎿ jukebox7: Nothing played from here yet: pick a genre in the pane │ ┃ ニ ヤ ウ ユ │ ┃ ン │ ┃ フ 6 メ ョ │ ┃ ゥ │ ┃ シ カ ハ ム │ ┃ 9 │ ┃ 4 レ ョ カ │ ┃ │ ┃ ヲ オ │ ┃ ヒ │ ┃ シ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · jukebox7
╭─────────────────────────────────────────────────────────── │ ■ Nothing plays. │ 1: ambient 2: alt 90s 3: metal 4: synth & electro 5: i ╰─────────────────────────────────────────────────────────── 3 ミ ケ ク ュ キ シ マ 9 ッ イ ヤ ウ ワ チ ョ マ キ ォ ヨ ネ シ ハ ニ ヤ ウ ユ ン フ 6 メ ョ ゥ シ カ ハ ム 9 4 レ ョ カ ヲ オ ヒ シ リ エ 7 7 ン 7 シ リ ン ァ ヘ ン ハ ル ゥ コ ソ ア テ ネ コ ヒ ヒ キ ナ ユ マ ヌ ョ チ ヲ ネ タ ホ コ テ ミ 8 マ セ ハ コ ン ハ ヨ ケ レ ス ム シ ノ サ ラ ソ 4 シ ェ キ 5 ワ ワ ッ サ シ サ ヘ 7 7 ト ス キ ィ ソ ツ オ ュ ユ 0 ワ サ 3 カ マ チ
README

jukebox7

Music on demand inside a Claude Code session, asked in plain words, played without a browser.

What it does

A prompt that names music (put on some ambient, coupe la musique, next) goes to Haiku first, which answers one intent: play, toggle, next, similar, volume, stop, or none. Anything else, including requests aimed at play7, keys7, Renoise or a melody, reaches the session untouched; a prompt without a music word skips the model call altogether.

  • play: yt-dlp searches YouTube, keeps songs of two to twenty minutes (a mood asked in words prefers five and more), and streams the audio into Windows' VLC with its dummy interface: no window, no focus taken. The track asked for plays whatever its length; next walks the songs alone, and past the last one the list ends.
  • toggle / next / stop: the WSL side runs in a process group of its own (setsid); pause is VLC's own pl_forcepause over its HTTP interface, at once, stop is CONT then TERM, and the vlc.exe it started is terminated by its --meta-title=jukebox7 tag, so a VLC opened by hand is never touched. A pause VLC does not answer changes nothing and says so. One change of song runs at a time (a search takes up to 40 s): a press meanwhile is refused. A session that never played leaves the VLC alone when it ends.

The pane (/music, or opened on the first song) shows the title, its state and volume, p pause, n next, r similar, s stop, d and u the volume by 10 %, and the genre buttons 1 to 9 and 0: ambient, alt 90s, metal, synth & electro, idm, indie rock, video games, film & modern classical, hip-hop & abstract, post-rock. A genre is a radio: a random artist from its list, a random song of theirs; next and the end of a song roll again.

A pick searches YouTube Music's songs tab, which holds tracks only: no interview, gameplay or full OST. Its listing gives no length: yt-dlp is asked for it once the song plays, the bar shows the elapsed time until then; plain YouTube, kept to two to twenty minutes, is the fallback when it finds nothing.

Discoveries. Each genre also holds a few artists beyond the listener's own, drawn from the lists' neighbors (Grouper and Tim Hecker by Loscil and Brian Eno, Deathspell Omega and Panopticon by Blut Aus Nord and Agalloch, Sewerslvt and Machine Girl by Venetian Snares, Car Seat Headrest and Alex G by Modest Mouse and Elliott Smith). One pick in three comes from there and its title wears a ✦; strike a name from discover to drop it.

similar (r, /music similar, or in words, plus comme ça) plays the YouTube Music radio of the song on: other artists first (the radio lingers on the same one), covers, tributes and hour-long loops dropped; next walks that list.

On the terminal the pane is black down to its last row, framed in the avatar's color, and the room left under the player fills with a green code rain in the manner of Ghost in the Shell: half-width katakana and digits, falling five frames a second while a song plays, frozen on pause.

With avatar7 loaded, a plays the pick of the avatar on duty: the station of its persona.json, which avatar7 publishes in its station state. Each song that starts, asked, from a genre or chained when the last one ends, is written to this mod's say state: avatar7, if loaded, introduces it in the persona's manner, like a radio host over the intro. While the avatar speaks (its isVoicing state) the music drops to 70 % of its level, then returns.

/music <search> plays one named track; /music pause|next|stop; /music vol 60, /music vol +20. In words, monte le son works too.

/music album pixies doolittle (or in words, "joue l'album Doolittle des Pixies") plays the first album YouTube Music finds for it, track by track in order: next and ⏮ walk the album, its end ends the list. The search does not give the album's name, so the first track's title (Doolittle - Debaser) shows which one it found.

back (b, /music back) starts the song again; within its first five seconds it goes to the song before, through the last fifty that played, and next then walks forward again before rolling a new one. keep (k, /music fav) keeps the song playing in the favorites, or takes it out; they are kept across sessions ($.store, at most 500) and play shuffled as the favorites station (v, /music favorites). The phone gets the same three: back, ★ (full when the song is kept) and the station.

A station goes round its artists: those of its last songs are set aside, up to half its list (eight at most), and no song of the last fifty plays again; each pick looks through an artist's first fifteen songs on YouTube Music. One pick in three is a discovery (✦): first from the YouTube Music radio of the station's last song, an artist the station does not have yet (only from YouTube Music's own artist channels, never a label's or a VEVO one); else from the genre's written list. A discovery kept with ★ teaches the station: its artist joins the station it played on, across sessions ($.store, fifty per station); taking the ★ back takes it out. Station lists name artists, not albums, except where the album is the style (Ulver Perdition City in ambient, Aphex Twin Selected Ambient Works Volume II) or a soundtrack names its work.

Only a short prompt (eight words at most) with a music word or phrase goes to Haiku; a longer one is talk to the assistant and passes untouched, even when it mentions music.

The volume goes through VLC's HTTP interface on Windows' loopback (port 18797), reached with Windows' own curl.exe. The level is kept apart from the player, survives a stop, and is set again on each new song: a fresh VLC starts at whatever level Windows kept for it.

Requirements

WSL with Windows interop, yt-dlp on the path, VLC at C:\Program Files\VideoLAN\VLC. VLC rather than ffplay on WSLg's PulseAudio: that server stalls after a sleep (it takes audio at a tenth of real time and nothing comes out) until wsl --shutdown.

Limits

  • The genre lists are one listener's; edit GENRES in hooks/register.tsx. A station belongs to its persona, in avatar7's personas/<id>/persona.json.
  • A very long pause may let YouTube drop the stream behind VLC, which then ends the song early on resume.
  • A song that ends moves on within five seconds (the liveness poll).

Tests

claude plugin test ~/flux7-mods/jukebox7

Source 3 files
hooks/register.tsx 1320 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface as Engine, Register } from 'claude-code'
3
4import type { Found, History, ModelUse, Player, Say, Track } from '../types'
5import { chatArgv, drainArgv, heldArgv, parseJukebox, pauseScript, REMOTE, statusArgv } from './remote'
6
7// Cheap sieve before any model call: a prompt that fails it reaches the
8// session untouched, with no added latency. A command to the jukebox is
9// short; a longer message is talk to the assistant, even about music (one
10// about ducking the music was once taken for a volume change). Common words
11// (son, fort, mets, lance) only count inside a music phrase; a prompt that
12// opens on joue or play names what to play.
13const MAX_WORDS = 8
14const MUSIC =
15  /\b(musique|music|morceau|chanson|playlist|youtube|ambient|lofi|radio|volume|pause|stop|coupe|arr[eê]te|reprends|resume|suivant|next|skip|louder|quieter|similar|similaire|pareil)\b|\b(monte|baisse|coupe)[sz]?\s+(le\s+)?son\b|\b(plus|moins)\s+fort\b|\b(joue|jouer|mets|lance|play)\b.*\b(du|des|de\s+la|un\s+peu\s+de|some)\b|^\s*(joue|play)\b/i
16export const isCandidate = (text: string): boolean => text.trim().split(/\s+/).length <= MAX_WORDS && MUSIC.test(text)
17
18const INTENT = [
19  'You read one message typed to a coding assistant and decide whether it asks to control music playback on the computer.',
20  'Answer with one line of JSON and nothing else, one of:',
21  '{"action":"play","query":"...","long":true}',
22  '{"action":"album","query":"..."}',
23  '{"action":"toggle"}',
24  '{"action":"next"}',
25  '{"action":"similar"}',
26  '{"action":"back"}',
27  '{"action":"fav"}',
28  '{"action":"stop"}',
29  '{"action":"volume","delta":10}',
30  '{"action":"none"}',
31  'play: the user wants music played now. query: YouTube search words, in English for a genre or mood, as given for a named artist or title.',
32  'long: true for background or mood music (ambient, lofi, focus, a genre), false for one named track.',
33  'album: the user names an album to hear whole (the word album, or an artist with one of its album titles). query: artist and album title, as given.',
34  'back: the song again, or the one before (précédent, recommence, encore). fav: keep the song playing in the favorites (garde, j aime, favori, celle-là).',
35  'toggle: pause or resume the music. next: skip to another one. similar: more songs like the one playing. stop: stop, cut or turn off the music.',
36  'volume: louder (delta 10, or 20 for much louder) or quieter (delta -10, or -20).',
37  'Only a direct, short command to the music player counts. A question, a remark, a request to change software or code, or a description of how music should behave is none, even when it names volume or music.',
38  'none: anything else, including talk about music, code that plays audio, and requests aimed at Renoise, play7, keys7, a piano, a pattern or a melody.',
39].join('\n')
40
41type Intent =
42  | { action: 'play'; query: string; long: boolean }
43  | { action: 'album'; query: string }
44  | { action: 'toggle' }
45  | { action: 'next' }
46  | { action: 'similar' }
47  | { action: 'back' }
48  | { action: 'fav' }
49  | { action: 'stop' }
50  | { action: 'volume'; delta: number }
51  | { action: 'none' }
52
53// A song lasts two to twenty minutes; above is an album or a mix. A mood
54// asked in words prefers five minutes and more.
55const MIN_SECONDS = 120
56const LONG_SECONDS = 300
57const MAX_SECONDS = 1200
58const SEARCH_SIZE = 8
59// A station looks further into each artist's songs than a search does.
60const STATION_SEARCH_SIZE = 15
61const PANE = 'jukebox7'
62const POLL_MS = 5_000
63// The phone's presses are read this often.
64const REMOTE_MS = 1_000
65
66// One click, a radio: a random artist of the genre, a random song of theirs;
67// next and the end of the song roll again. Seeded from the author's own listening.
68export const GENRES: { key: string; label: string; artists: string[]; discover?: string[] }[] = [
69  {
70    key: '1',
71    label: 'ambient',
72    artists: ['Boards of Canada', 'Loscil', 'Helios', 'Múm', 'Kenji Kawai Ghost in the Shell', 'Rafael Anton Irisarri', 'Ulver Perdition City', 'Brian Eno', 'bxnwxghxrn', 'Deru'], discover: ['Grouper', 'Tim Hecker', 'William Basinski', 'Stars of the Lid', 'Hiroshi Yoshimura', 'Chihei Hatakeyama', 'Biosphere', 'Huerco S.', 'Kali Malone', 'Sarah Davachi', '36 ambient'],
73  },
74  { key: '2', label: 'alt 90s', artists: ['Radiohead', 'The Clash', 'Pulp', 'Smashing Pumpkins', 'Pixies', 'Pavement', 'Supergrass', 'Tool', 'Nine Inch Nails', 'Rage Against the Machine', 'My Bloody Valentine', 'Queens of the Stone Age', 'Slint', 'Beck', 'Sonic Youth'], discover: ['Unwound', 'Polvo', 'Archers of Loaf', 'Sebadoh', 'Hum', 'Failure', 'Swirlies', 'Dinosaur Jr', 'MJ Lenderman', 'Wednesday band', 'Horse Jumper of Love'] },
75  {
76    key: '3',
77    label: 'metal',
78    artists: ['Dissection', 'Cradle of Filth', 'Emperor', 'Dimmu Borgir', 'Agalloch', 'Ulver', 'Arcturus', 'Blut Aus Nord', 'Wolves in the Throne Room', 'Opeth', 'Gojira', 'Children of Bodom', 'In Flames', 'Therion', 'Diabolical Masquerade', 'Anorexia Nervosa', 'Summoning', 'CLANN', 'Drabikowski Batushka', 'Limbonic Art', 'Obtained Enslavement', 'Peste Noire', 'Ghost band', 'The Kovenant'], discover: ['Deathspell Omega', 'Mgła', 'Panopticon', 'Alcest', 'Oranssi Pazuzu', 'Wiegedood', 'Cult of Luna', 'Russian Circles', 'Igorrr', 'Sumac', 'Misþyrming', 'Svartidauði', 'Imperial Triumphant', 'Erang dungeon synth', 'Old Tower'],
79  },
80  { key: '4', label: 'synth & electro', artists: ['Fixions', 'Mega Drive', 'Danger 11h30', 'Perturbator', 'Carpenter Brut', 'Dan Terminus', 'Gost', 'Dance With the Dead', 'Master Boot Record', 'Crystal Castles', 'The Knife', 'Grimes', 'Justice', 'Röyksopp', 'Waveshaper', 'RWD NRTHNDR', 'Lorn', 'SurgeryHead', 'Baldocaster', 'The Toxic Avenger', 'Scattle'], discover: ['Volkor X', 'Daniel Deluxe', 'Magic Sword', 'Irving Force', 'Hollywood Burns', 'Lueur Verte', 'Gunship', 'Lazerhawk', 'Boy Harsher', 'Drab Majesty', 'Kavinsky'] },
81  { key: '5', label: 'idm', artists: ['Aphex Twin', 'Plaid', 'Boards of Canada', 'Squarepusher', 'Venetian Snares', 'Autechre', 'Clark', 'Wisp IDM', 'Arovane', 'Kettel', 'Jega', 'Bogdan Raczynski', 'Ceephax Acid Crew', 'The Future Sound of London', 'Tujiko Noriko', 'Plone', 'Ochre', 'The Tuss', 'Daed', 'EOD Questionmarks', 'Acrnym', 'Koolmorf Widesen', 'exandroid', 'James Shinra', 'Stazma', 'µ-Ziq', 'ID:null', 'Gareth Clarke', 'Hitori Tori'], discover: ['Richard Devine', 'Proem', 'Lusine', 'Funckarma', 'Sewerslvt', 'Machine Girl', 'Rival Consoles', 'Max Cooper', 'Jlin', 'Lanark Artefax', 'Loraine James'] },
82  {
83    key: '6',
84    label: 'indie rock',
85    artists: ['Pixies', 'Modest Mouse', 'Blonde Redhead', 'Eels', 'Sparklehorse', 'Elliott Smith', 'Grandaddy', 'Built to Spill', 'The Unicorns', 'Sufjan Stevens', 'MGMT', 'Ratatat', 'Perfume Genius', 'The Notwist', 'Beach House', 'Weezer', 'Les Savy Fav', 'Wolf Parade', 'The Shins', 'Animal Collective', 'Arcade Fire', 'Joanna Newsom', 'Broadcast', 'Syd Matters', 'The Walkmen', 'The Strokes', 'Metric', 'The Flaming Lips', 'Clues Alden Penner', 'Jason Lytle', 'Ugly Casanova', 'CocoRosie', 'Soap&Skin', 'Xiu Xiu', 'Lykke Li', 'Candy Claws', 'Surfer Blood'], discover: ['Car Seat Headrest', 'Alex G', 'Duster band', 'Pinegrove', 'Big Thief', 'Low Sparhawk slowcore', 'Sun Kil Moon', 'Unknown Mortal Orchestra', 'Black Country New Road', 'Weyes Blood', 'Alvvays', 'Caroline Polachek', 'Zola Jesus', 'Chelsea Wolfe', 'Ethel Cain', 'Fever Ray'],
86  },
87  {
88    key: '7',
89    label: 'video games',
90    artists: [
91      'NieR Automata soundtrack Keiichi Okabe', 'Jeremy Soule Skyrim', 'Jeremy Soule Morrowind', 'Jeremy Soule Oblivion',
92      'Akira Yamaoka Silent Hill', 'Deus Ex soundtrack', 'Christopher Larkin Hollow Knight', 'C418 Minecraft', 'Cyberpunk 2077 soundtrack',
93      'Darren Korb Bastion', 'Darren Korb Transistor', 'Lena Raine Celeste', 'Mark Morgan Fallout', 'Mark Morgan Planescape Torment',
94      'FlybyNo Endless Space', 'FlybyNo Endless Legend', 'Arnaud Roy Humankind', 'Andrew Prahlow Outer Wilds', 'Furi soundtrack', 'Waveshaper Masters of Light',
95      'Hiroyuki Sawano Attack on Titan', 'Hiroyuki Sawano Xenoblade Chronicles X', 'Seiji Yokoyama Saint Seiya', 'League of Legends soundtrack', 'League of Legends login theme',
96    ], discover: ['Disasterpeace Fez', 'Darren Korb Hades', 'Austin Wintory Journey', 'Ben Prunty FTL', 'Toby Fox Undertale', 'Mick Gordon Doom', 'Hideki Naganuma', 'Christopher Larkin Silksong', 'Darren Korb Hades II', 'Disasterpeace Hyper Light Drifter', 'Lena Raine Chicory', 'Toby Fox Deltarune', 'Mick Gordon Atomic Heart'],
97  },
98  {
99    key: '8',
100    label: 'film & modern classical',
101    artists: ['Joe Hisaishi', 'Philip Glass', 'Max Richter', 'Kenji Kawai Ghost in the Shell', 'Ryuichi Sakamoto', 'Jóhann Jóhannsson', 'Hans Zimmer The Thin Red Line', 'Clint Mansell The Fountain', 'Trevor Jones The Last of the Mohicans', 'Elliot Goldenthal Heat', 'Thomas Newman American Beauty', 'John Williams', 'Antonín Dvořák New World Symphony'],
102    discover: ['Ólafur Arnalds', 'Nils Frahm', 'Arvo Pärt', 'Hildur Guðnadóttir', 'Steve Reich', 'Michael Nyman', 'Hania Rani', 'A Winged Victory for the Sullen', 'Hildur Guðnadóttir Chernobyl', 'Kali Malone', 'Caterina Barbieri'],
103  },
104  {
105    key: '9',
106    label: 'hip-hop & abstract',
107    artists: ['Wu-Tang Clan', 'Jedi Mind Tricks', 'Kanye West', 'cLOUDDEAD', 'Sage Francis', 'Danger Mouse', 'Why?', 'Nujabes', 'Prefuse 73', 'DJ Shadow', 'Bonobo', 'Themselves', 'Odd Nosdam', 'Alias Anticon', 'Sole Anticon', 'Son Lux', 'Beastie Boys', 'Cypress Hill', 'Stupeflip', 'Wax Tailor', 'Outkast', 'Eminem', 'Dr. Dre', 'Passage Anticon', 'Death Grips'],
108    discover: ['MF DOOM', 'Cannibal Ox', 'Aesop Rock', 'Company Flow', 'Armand Hammer', 'billy woods', 'clipping.', 'Deltron 3030', 'Madlib', 'J Dilla', 'Flying Lotus', 'Knxwledge', 'JPEGMAFIA', 'Danny Brown', 'ShrapKnel', 'Backxwash'],
109  },
110  {
111    key: '0',
112    label: 'post-rock',
113    artists: ['Godspeed You! Black Emperor', 'Explosions in the Sky', 'Mono', 'Isis', 'Red Sparowes', 'Mogwai', 'Anathema', 'Sigur Rós', 'This Will Destroy You', 'The Mars Volta'],
114    discover: ['Caspian', 'If These Trees Could Talk', 'Pelican', 'Do Make Say Think', 'Tortoise', 'Hammock', 'Lost in Kiev', 'God Is an Astronaut', 'Sumac', 'Year of No Light', 'Bell Witch'],
115  },
116]
117
118// A genre's artists, or else the station of the avatar on duty, which
119// avatar7 publishes from the persona's own persona.json.
120async function poolOf($: Engine, label: string): Promise<{ name: string; artists: string[] }> {
121  const taught = (await learned($))[label] ?? []
122  const genre = GENRES.find(g => g.label === label)
123  if (genre !== undefined) return { name: label, artists: [...genre.artists, ...taught.filter(a => !genre.artists.includes(a))] }
124  const { value } = await $.state.get(onStation)
125  const own = value?.artists ?? []
126  return { name: value?.name || label, artists: own.length === 0 ? [] : [...own, ...taught.filter(a => !own.includes(a))] }
127}
128
129// Artists a station learned: a ✦ discovery kept with ★ joins the station it
130// played on, across sessions ($.store), at most LEARNED_MAX each; taking the
131// ★ back takes the artist out again.
132const LEARNED_MAX = 50
133async function learned($: Engine): Promise<Record<string, string[]>> {
134  const v = await $.store.get('learned')
135  return typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, string[]>) : {}
136}
137async function teach($: Engine, station: string, artist: string, isKept: boolean): Promise<void> {
138  const all = await learned($)
139  const now = all[station] ?? []
140  const next = isKept ? [...now.filter(a => a !== artist), artist].slice(-LEARNED_MAX) : now.filter(a => a !== artist)
141  await $.store.set('learned', { ...all, [station]: next })
142}
143
144// The same name, whatever its case and spacing: "Boards of Canada" and the
145// channel "boards of canada" are one artist; "Ghost band" covers "Ghost".
146const sameArtist = (a: string, b: string): boolean => {
147  const x = a.toLowerCase().replace(/\s+/g, ' ').trim()
148  const y = b.toLowerCase().replace(/\s+/g, ' ').trim()
149  return x !== '' && y !== '' && (x === y || x.startsWith(`${y} `) || y.startsWith(`${x} `))
150}
151// A discovery from the radio of what the station played last: a song by an
152// artist the station does not have yet, not heard lately. Undefined when
153// there is no seed or the radio has nothing new.
154export const radioDiscovery = (rows: RadioRow[], own: string[], heard: Set<string>): RadioRow | undefined =>
155  anyOf(rows.filter(r => r.isArtist && r.artist !== '' && !own.some(a => sameArtist(a, r.artist)) && !heard.has(r.track.id)))
156// Artists picked for a genre beyond the listener's own: one pick in three
157// comes from there, and its title wears a ✦.
158const discoveries = (label: string): string[] => GENRES.find(g => g.label === label)?.discover ?? []
159const DISCOVER_ODDS = 1 / 3
160export const DISCOVERED = '✦ '
161const onDuty = { plugin: 'avatar7', key: 'avatar' } as const
162const tint = { plugin: 'avatar7', key: 'color' } as const
163const onStation = { plugin: 'avatar7', key: 'station' } as const
164// Without an avatar on duty the pane keeps the terminal's phosphor green.
165const PHOSPHOR = '#00ff9c'
166const BLACK = '#000000'
167const BAR = 12
168
169const anyOf = <T,>(xs: T[]): T | undefined => xs[Math.floor(Math.random() * xs.length)]
170export const isSong = (t: Track): boolean => t.seconds !== null && t.seconds >= MIN_SECONDS && t.seconds <= MAX_SECONDS
171
172const IDLE: Player = { tracks: [], index: 0, pgid: null, isPlaying: false, genre: null, startedAt: null, pausedAt: null }
173const player = atom({ plugin: 'jukebox7', key: 'player' } as const, IDLE)
174// The last search asked for a pick (/music find, or the phone): what was
175// asked and what YouTube found, in its order. Nothing plays until a pick.
176const found = atom({ plugin: 'jukebox7', key: 'found' } as const, { query: '', tracks: [] } as Found)
177let isFinding = false
178// The pane's search: its field and the results, shown after `f` until `f`
179// again. Each result answers a letter the pane leaves free (digits are the
180// stations', the rest its controls').
181const searching = atom({ plugin: 'jukebox7', key: 'searching' } as const, false)
182export const PICK_KEYS = ['q', 'w', 'e', 't', 'y', 'i', 'o', 'l']
183const PANE_ROWS = 6
184// The pane grows by the search's rows (the field, a result each, or one
185// line while it searches), so the rain is not all that gives way.
186const paneRows = (isSearching: boolean, results: number): number => PANE_ROWS + (isSearching ? 1 + Math.max(1, results) : 0)
187// Percent of VLC's 100 %, kept apart from the player so a stop keeps it.
188const volume = atom({ plugin: 'jukebox7', key: 'volume' } as const, 70)
189// What played, each song with its list and station, for back (⏮) and for
190// next to walk forward again before rolling a new song. `at` is the one
191// playing.
192const HISTORY_MAX = 50
193const history = atom({ plugin: 'jukebox7', key: 'history' } as const, { items: [], at: -1 } as History)
194// Back within the first seconds of a song goes to the one before; later, it
195// starts the song again.
196export const RESTART_MS = 5_000
197export const elapsedMs = (p: Player, now: number): number => (p.startedAt === null ? 0 : (p.pausedAt ?? now) - p.startedAt)
198// Songs kept with ★, across sessions ($.store), played back shuffled as a
199// station of their own.
200export const FAVORITES = 'favorites'
201const FAVORITES_MAX = 500
202export const unmark = (title: string): string => title.replace(DISCOVERED, '')
203export const shuffled = <T,>(xs: T[]): T[] => {
204  const a = [...xs]
205  for (let i = a.length - 1; i > 0; i--) {
206    const j = Math.floor(Math.random() * (i + 1))
207    ;[a[i], a[j]] = [a[j] as T, a[i] as T]
208  }
209  return a
210}
211// A station goes round its artists before one comes back: the ones of its
212// last songs are set aside, up to half its list (at most RECENT_ARTISTS),
213// and no song of the last HISTORY_MAX plays again. With all set aside, the
214// whole list again rather than silence.
215const RECENT_ARTISTS = 8
216export const freshArtists = (pool: string[], recent: string[]): string[] => {
217  const kept = recent.slice(-Math.min(RECENT_ARTISTS, Math.floor(pool.length / 2)))
218  const fresh = pool.filter(a => !kept.includes(a))
219  return fresh.length > 0 ? fresh : pool
220}
221export const freshSongs = (songs: Track[], heard: Set<string>): Track[] => {
222  const fresh = songs.filter(t => !heard.has(t.id))
223  return fresh.length > 0 ? fresh : songs
224}
225const VOLUME_STEP = 10
226const VOLUME_MAX = 125
227export const clampVolume = (v: number): number => Math.min(VOLUME_MAX, Math.max(0, Math.round(v)))
228
229export const parseIntent = (text: string): Intent => {
230  const json = /\{[^}]*\}/.exec(text)?.[0]
231  if (json === undefined) return { action: 'none' }
232  try {
233    const v = JSON.parse(json) as Record<string, unknown>
234    if (v.action === 'play' && typeof v.query === 'string' && v.query.trim() !== '') {
235      return { action: 'play', query: v.query.trim(), long: v.long === true }
236    }
237    if (v.action === 'album' && typeof v.query === 'string' && v.query.trim() !== '') return { action: 'album', query: v.query.trim() }
238    if (v.action === 'toggle' || v.action === 'next' || v.action === 'similar' || v.action === 'stop' || v.action === 'back' || v.action === 'fav') return { action: v.action }
239    if (v.action === 'volume' && typeof v.delta === 'number' && v.delta !== 0) return { action: 'volume', delta: v.delta }
240  } catch {
241    // Not JSON after all: the prompt goes on to the session.
242  }
243  return { action: 'none' }
244}
245
246// yt-dlp prints one `id<TAB>title<TAB>duration` line per result; a live
247// stream has no duration (NA), which suits a backdrop.
248export const parseTracks = (stdout: string): Track[] =>
249  stdout
250    .split('\n')
251    .map(l => l.split('\t'))
252    .filter(([id]) => id !== undefined && /^[\w-]{11}$/.test(id))
253    .map(([id, title, d]) => ({
254      id: id as string,
255      title: (title ?? '').trim(),
256      seconds: d === undefined || !/^\d+(\.\d+)?$/.test(d.trim()) ? null : Math.round(Number(d)),
257    }))
258
259// The playlist starts on the first fitting result; next walks on from there.
260export const pickTrack = (stdout: string, long: boolean): Track | undefined => {
261  const tracks = parseTracks(stdout)
262  if (!long) return tracks[0]
263  const songs = tracks.filter(isSong)
264  return songs.find(t => (t.seconds ?? 0) >= LONG_SECONDS) ?? songs[0] ?? tracks[0]
265}
266
267// An album: the first one YouTube Music's albums tab finds, then its tracks in
268// order. The search gives the album's page, not its name; the listing does
269// ("Album - Doolittle").
270export const albumSearchArgv = (query: string): string[] => [
271  'yt-dlp',
272  '--flat-playlist',
273  '--no-warnings',
274  '--playlist-end',
275  '1',
276  '--print',
277  '%(url)s',
278  `https://music.youtube.com/search?q=${encodeURIComponent(query)}#albums`,
279]
280export const albumTracksArgv = (url: string): string[] => [
281  'yt-dlp',
282  '--flat-playlist',
283  '--no-warnings',
284  '--print',
285  '%(id)s\t%(title)s\t%(duration)s\t%(playlist_title)s',
286  url,
287]
288export const parseAlbum = (stdout: string): { name: string; tracks: Track[] } => {
289  const lines = stdout.split('\n').filter(l => /^[\w-]{11}\t/.test(l))
290  const name = (lines[0]?.split('\t')[3] ?? '').replace(/^Album - /, '').replace(/^NA$/, '').trim()
291  const tracks = parseTracks(lines.map(l => l.split('\t').slice(0, 3).join('\t')).join('\n'))
292  return { name, tracks: tracks.map(t => ({ ...t, title: name === '' ? t.title : `${name} - ${t.title}` })) }
293}
294
295const search = (query: string): string[] => [
296  'yt-dlp',
297  '--flat-playlist',
298  '--no-warnings',
299  '--print',
300  '%(id)s\t%(title)s\t%(duration)s',
301  `ytsearch${SEARCH_SIZE}:${query}`,
302]
303
304// A station pick searches YouTube Music's songs tab: only tracks, never an
305// interview, a gameplay video or a full OST, at the cost of the durations
306// (the flat listing gives none). Plain YouTube, length-filtered, is the
307// fallback when it finds nothing.
308export const musicSearch = (query: string): string[] => [
309  'yt-dlp',
310  '--flat-playlist',
311  '--no-warnings',
312  '--playlist-end',
313  String(STATION_SEARCH_SIZE),
314  '--print',
315  '%(id)s\t%(title)s\t%(duration)s',
316  `https://music.youtube.com/search?q=${encodeURIComponent(query)}#songs`,
317]
318
319// YouTube Music's search lists no duration (NA): the one playing is asked
320// for its own, so the progress bar has something to fill.
321export const durationArgv = (id: string): string[] => [
322  'yt-dlp',
323  '--no-warnings',
324  '--skip-download',
325  '--print',
326  '%(duration)s',
327  `https://www.youtube.com/watch?v=${id}`,
328]
329
330// YouTube Music's radio from a song: its first entry is the song itself.
331// The radio lingers on the same artist, so other artists come first; covers,
332// tributes and hour-long loops (the drift of a niche radio) are dropped.
333export const radioArgv = (id: string): string[] => [
334  'yt-dlp',
335  '--flat-playlist',
336  '--no-warnings',
337  '--playlist-end',
338  '25',
339  '--print',
340  '%(id)s\t%(title)s\t%(duration)s\t%(channel)s',
341  `https://music.youtube.com/watch?v=${id}&list=RDAMVM${id}`,
342]
343const COVER = /\b(cover|tribute|relaxing|reimagined|orchestral version|piano version|8.?bit|lofi version|1 hour|hours?\b|extended|epic music|fantasy music|sleep|study)\b/i
344// `isArtist`: the channel is YouTube Music's own for an artist ("<name> -
345// Topic"), so its name is the artist's. A label ("Napalm Records") or a
346// "<name>VEVO" channel names no artist a station could search.
347export type RadioRow = { track: Track; artist: string; isArtist: boolean }
348export const parseRadioRows = (stdout: string): RadioRow[] => {
349  const rows = stdout
350    .split('\n')
351    .map(l => l.split('\t'))
352    .filter(([id]) => id !== undefined && /^[\w-]{11}$/.test(id))
353    .map(([id, title, d, channel]) => ({
354      id: id as string,
355      title: (title ?? '').trim(),
356      seconds: d === undefined || !/^\d+(\.\d+)?$/.test(d.trim()) ? null : Math.round(Number(d)),
357      artist: (channel ?? '').replace(/ - Topic$/, '').trim(),
358      isArtist: / - Topic$/.test((channel ?? '').trim()),
359    }))
360  const [self, ...rest] = rows
361  const kept = rest.filter(r => !COVER.test(r.title) && !COVER.test(r.artist) && (r.seconds === null || isSong(r)))
362  const others = kept.filter(r => r.artist !== self?.artist)
363  const same = kept.filter(r => r.artist === self?.artist)
364  return [...others, ...same].map(r => ({ track: { id: r.id, title: r.artist === '' || r.artist === 'NA' ? r.title : `${r.artist} - ${r.title}`, seconds: r.seconds }, artist: r.artist, isArtist: r.isArtist }))
365}
366export const parseRadio = (stdout: string): Track[] => parseRadioRows(stdout).map(r => r.track)
367
368// Audio only, no window: yt-dlp streams the best audio into Windows' VLC
369// with its dummy interface (WSLg's PulseAudio stalls after a sleep, VLC
370// plays on the Windows side and takes no focus). setsid puts the WSL side in
371// a process group of its own, which stop ends (pause asks VLC itself); vlc://quit
372// ends it with the stream; the id arrives as $1, checked against
373// /^[\w-]{11}$/ before.
374const VLC = '/mnt/c/Program Files/VideoLAN/VLC/vlc.exe'
375const TAG = '--meta-title=jukebox7'
376// The volume goes through VLC's HTTP interface, bound to Windows' loopback:
377// curl.exe runs there, where WSL's own localhost does not reach. The
378// password only satisfies VLC, which refuses the interface without one.
379const HTTP_PORT = 18797
380const HTTP_PASSWORD = 'jukebox7'
381const HTTP = `--extraintf http --http-host 127.0.0.1 --http-port ${HTTP_PORT} --http-password ${HTTP_PASSWORD}`
382const PIPE = `${REMOTE}yt-dlp -q --no-warnings -f bestaudio -o - "https://www.youtube.com/watch?v=$1" | "${VLC}" --intf dummy --dummy-quiet --play-and-exit --no-video -q ${TAG} ${HTTP} - vlc://quit`
383export const startArgv = (id: string): string[] => [
384  'bash',
385  '-c',
386  `setsid bash -c '${PIPE}' _ "$1" </dev/null >/dev/null 2>&1 & echo $!`,
387  '_',
388  id,
389]
390// Killing the WSL side leaves vlc.exe running: it goes by its tag, so a VLC
391// the user opened themselves is never touched. A VLC whose WSL side died
392// with its window shows no command line any more, and still holds the port
393// beside the next one (Windows lets both listen, the controls reach one of
394// them). Windows refuses to end that one even to its own user, but it still
395// obeys its interface: pl_stop ends it (--play-and-exit), once per listener,
396// each request reaching one. The port's owner goes last, where allowed.
397const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe'
398const BASIC = btoa(`:${HTTP_PASSWORD}`)
399export const killVlcArgv = [
400  POWERSHELL,
401  '-NoProfile',
402  '-Command',
403  `1..3 | ForEach-Object { try { Invoke-WebRequest -UseBasicParsing -TimeoutSec 1 -Headers @{ Authorization = 'Basic ${BASIC}' } 'http://127.0.0.1:${HTTP_PORT}/requests/status.xml?command=pl_stop' | Out-Null } catch {} }; ` +
404    `Get-CimInstance Win32_Process -Filter "Name='vlc.exe'" | Where-Object { $_.CommandLine -like '*${TAG}*' } | Invoke-CimMethod -MethodName Terminate | Out-Null; ` +
405    `Get-NetTCPConnection -LocalPort ${HTTP_PORT} -State Listen -ErrorAction SilentlyContinue | ForEach-Object { Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue } | Where-Object Name -eq 'vlc' | Stop-Process -Force -ErrorAction SilentlyContinue`,
406]
407// VLC counts 256 for 100 %. A fresh VLC starts at whatever Windows kept for
408// it (--mmdevice-volume is ignored), so each start sets the level again,
409// retrying while the interface is not up yet.
410const CURL = '/mnt/c/Windows/System32/curl.exe'
411export const volumeArgv = (percent: number, retry = false): string[] => [
412  CURL,
413  '-s',
414  '-o',
415  'NUL',
416  '-u',
417  `:${HTTP_PASSWORD}`,
418  ...(retry ? ['--retry', '10', '--retry-connrefused', '--retry-delay', '1'] : ['--max-time', '2']),
419  `http://127.0.0.1:${HTTP_PORT}/requests/status.xml?command=volume&val=${Math.round((clampVolume(percent) * 256) / 100)}`,
420]
421// Pause and resume through the same interface: instant, where stopping the
422// WSL pipeline only starved VLC after its buffer ran out, seconds later or
423// not at all. force* are idempotent, so a missed click cannot invert them.
424// On the phone (music.json holds a song), pause flips its flag; here, VLC's.
425export const pauseArgv = (isPaused: boolean): string[] => [
426  'sh',
427  '-c',
428  pauseScript(isPaused),
429  '_',
430  CURL,
431  '-sf',
432  '-o',
433  'NUL',
434  '-u',
435  `:${HTTP_PASSWORD}`,
436  '--max-time',
437  '2',
438  `http://127.0.0.1:${HTTP_PORT}/requests/status.xml?command=${isPaused ? 'pl_forcepause' : 'pl_forceresume'}`,
439]
440
441// How many rows a wrapped line of plain Buttons takes: each draws as
442// `k: label`, three columns past its label, with `gap` between them.
443export const buttonRows = (labels: string[], columns: number, gap = 2): number => {
444  let rows = 1
445  let used = 0
446  for (const label of labels) {
447    const w = label.length + 3
448    if (used > 0 && used + gap + w > columns) {
449      rows += 1
450      used = w
451    } else {
452      used += (used > 0 ? gap : 0) + w
453    }
454  }
455  return rows
456}
457
458// While the avatar speaks, the music drops to this share of its level.
459export const DUCK = 0.7
460export const duckArgv = (level: number, isVoicing: boolean): string[] => volumeArgv(isVoicing ? level * DUCK : level)
461const detached = (argv: string[]): string[] => ['bash', '-c', 'setsid "$0" "$@" </dev/null >/dev/null 2>&1 &', ...argv]
462export const detachedKillVlcArgv = ['bash', '-c', 'setsid "$0" "$@" </dev/null >/dev/null 2>&1 &', ...killVlcArgv]
463const signal = (sig: 'STOP' | 'CONT' | 'TERM', pgid: number): string[] => ['kill', `-${sig}`, '--', `-${pgid}`]
464
465const show = (p: Player) => {
466  const t = p.tracks[p.index]
467  return t === undefined ? undefined : `music${p.isPlaying ? '' : ' (paused)'}: ${t.title}`
468}
469
470async function halt($: Engine, pgid: number | null) {
471  // A stopped group ignores TERM until it runs again.
472  if (pgid !== null) {
473    await $.process.run(signal('CONT', pgid))
474    await $.process.run(signal('TERM', pgid))
475  }
476  await $.process.run(killVlcArgv)
477}
478
479// Fills in the duration of the track playing, if it still plays when the
480// answer comes; the play never waits on it.
481async function fillDuration($: Engine, id: string): Promise<void> {
482  try {
483    const r = await $.process.run(durationArgv(id), { timeoutMs: 20_000 })
484    const [found] = parseTracks(`${id}\t\t${r.stdout.trim()}`)
485    if (r.exitCode !== 0 || found?.seconds == null) return
486    const seconds = found.seconds
487    await update($, player, p =>
488      p.tracks[p.index]?.id === id ? { ...p, tracks: p.tracks.map((t, i) => (i === p.index ? { ...t, seconds } : t)) } : p,
489    )
490  } catch {
491    // No duration (yt-dlp failed, the session ended): the bar stays a clock.
492  }
493}
494
495// What the persona on duty hears when a song starts: the title, plain, and
496// the cue to introduce it in its own manner.
497export const introEvent = (title: string): string =>
498  `the jukebox starts "${title.replace(DISCOVERED, '')}"; introduce it in your own manner, the way a radio host would`
499
500async function playAt($: Engine, tracks: Track[], index: number, genre: string | null = null, isReplay = false, artist?: string): Promise<Track | undefined> {
501  // Halted even when nothing plays from here: an orphan VLC on the port
502  // would take the controls of the new one. One jukebox per machine.
503  await halt($, (await read($, player)).pgid)
504  const track = tracks[index]
505  if (track === undefined) {
506    await update($, player, () => IDLE)
507    $.ui.status(undefined)
508    return undefined
509  }
510  const started = await $.process.run(startArgv(track.id))
511  const pgid = Number(started.stdout.trim())
512  const p: Player = {
513    tracks,
514    index,
515    pgid: Number.isInteger(pgid) && pgid > 1 ? pgid : null,
516    isPlaying: true,
517    genre,
518    startedAt: await $.clock.now(),
519    pausedAt: null,
520  }
521  await update($, player, () => p)
522  // A new song goes on top of what played (anything ahead of it is
523  // dropped); a song played again from the history leaves it as it is.
524  if (!isReplay) {
525    await update($, history, h => {
526      const items = [...h.items.slice(0, h.at + 1), { tracks, index, genre, ...(artist !== undefined ? { artist } : {}) }].slice(-HISTORY_MAX)
527      return { items, at: items.length - 1 }
528    })
529  }
530  // Every start goes through here: asked, from a genre, or the next one when
531  // a song ends; avatar7, if loaded, speaks over the intro.
532  await $.state.set({ plugin: 'jukebox7', key: 'say' }, { mood: 'watch', event: introEvent(track.title), at: Date.now() } satisfies Say)
533  if (p.pgid !== null) await $.process.run(detached(volumeArgv(await read($, volume), true)))
534  if (track.seconds === null) void fillDuration($, track.id)
535  $.ui.status(show(p))
536  void $.ui.open({ id: PANE, title: 'jukebox7', rows: 6 })
537  return track
538}
539
540// What a short message asks the jukebox, through Haiku: the line it answers
541// with when it did something, undefined when the message was not for it
542// (then the prompt goes on to the session, or a spoken phrase to the avatar).
543async function actOn($: Engine, text: string): Promise<string | undefined> {
544    const r = await $.model.complete({
545    model: 'haiku',
546    system: INTENT,
547    prompt: text.slice(0, 500),
548    maxTokens: 60,
549    effort: 'low',
550    timeoutMs: 8_000,
551  })
552  if (r.usage !== undefined) {
553    await $.state.set({ plugin: 'jukebox7', key: 'modelUse' }, {
554      model: 'haiku', input: r.usage.input_tokens, output: r.usage.output_tokens, cacheRead: r.usage.cache_read_input_tokens ?? 0, at: Date.now(),
555    } satisfies ModelUse)
556  }
557  const intent = r.isAnswered ? parseIntent(r.text) : ({ action: 'none' } as const)
558
559  if (intent.action === 'none') return undefined
560  // A song already on its way: no second search, and no false "nothing found".
561  const changes = intent.action === 'play' || intent.action === 'album' || intent.action === 'next' || intent.action === 'similar' || intent.action === 'back'
562  if (changes && isMoving) return 'jukebox7: a song is already on its way'
563
564  if (intent.action === 'album') {
565    const a = await once($, () => playAlbum($, intent.query).then(x => x?.track))
566    if (a === undefined) return `jukebox7: no album found on YouTube Music for "${intent.query}".`
567    $.ui.toast(`music now playing: ${a.title}`)
568    return `jukebox7: playing the album, from "${a.title}"`
569  }
570  if (intent.action !== 'play') {
571    // Nothing plays: a bare stop, pause or next was meant for the assistant.
572    if ((await read($, player)).pgid === null) return undefined
573    if (intent.action === 'stop') {
574      await stop($)
575      $.ui.toast('music stopped')
576      return 'jukebox7: stopped'
577    }
578    if (intent.action === 'volume') {
579      const v = await louder($, intent.delta)
580      $.ui.toast(`music volume ${v}%`)
581      return `jukebox7: volume ${v}%`
582    }
583    if (intent.action === 'back') {
584      const t = await once($, () => back($))
585      $.ui.toast(t === undefined ? 'music: nothing to go back to' : `music now playing: ${t.title}`)
586      return `jukebox7: ${t === undefined ? 'nothing to go back to' : `back, ${t.title}`}`
587    }
588    if (intent.action === 'fav') {
589      const isIn = await toggleFavorite($)
590      return `jukebox7: ${isIn === true ? 'kept in the favorites' : 'removed from the favorites'}`
591    }
592    if (intent.action === 'similar') {
593      const t = await once($, () => playSimilar($))
594      return `jukebox7: ${t === undefined ? 'no radio for this one' : `like it, ${t.title}`}`
595    }
596    if (intent.action === 'next') {
597      const t = await once($, () => skip($, 1))
598      $.ui.toast(t === undefined ? 'music: end of the list' : `music now playing: ${t.title}`)
599      return `jukebox7: ${t === undefined ? 'end of the list' : `next, ${t.title}`}`
600    }
601    const q = await toggle($)
602    if (q === undefined) return 'jukebox7: VLC did not answer'
603    const said = q.isPlaying ? `resumed: ${q.tracks[q.index]?.title ?? ''}` : 'paused'
604    $.ui.toast(`music ${said}`)
605    return `jukebox7: ${said}`
606  }
607
608  const track = await once($, () => play($, intent.query, intent.long))
609  if (track === undefined) return `jukebox7: nothing found on YouTube for "${intent.query}".`
610  $.ui.toast(`music now playing: ${track.title}`)
611  return `jukebox7: playing "${track.title}" (https://youtu.be/${track.id})`
612}
613
614// One change of song at a time: a search takes up to 40 s, and the poll, a
615// button and a command would each start their own song meanwhile.
616let isMoving = false
617async function once($: Engine, change: () => Promise<Track | undefined>): Promise<Track | undefined> {
618  if (isMoving) {
619    $.ui.toast('music: a song is already on its way')
620    return undefined
621  }
622  isMoving = true
623  try {
624    return await change()
625  } finally {
626    isMoving = false
627  }
628}
629
630// Past the last result the list ends (playAt goes idle): no wrapping back to
631// the first, which would loop for ever over tracks that cannot play.
632async function skip($: Engine, by: number): Promise<Track | undefined> {
633  // After a step back, next walks forward through what already played.
634  const h = await read($, history)
635  const ahead = h.items[h.at + 1]
636  if (by > 0 && ahead !== undefined) {
637    await update($, history, x => ({ ...x, at: x.at + 1 }))
638    return playAt($, ahead.tracks, ahead.index, ahead.genre, true)
639  }
640  const p = await read($, player)
641  if (typeof p.genre === 'string' && p.genre !== FAVORITES) return playGenre($, p.genre)
642  return playAt($, p.tracks, p.index + by, p.genre)
643}
644
645// ⏮: the song again from its start, or, within its first seconds, the one
646// before it. Idle, the last song played starts again.
647async function back($: Engine): Promise<Track | undefined> {
648  const p = await read($, player)
649  const h = await read($, history)
650  const before = h.items[h.at - 1]
651  const isEarly = p.pgid !== null && elapsedMs(p, await $.clock.now()) <= RESTART_MS
652  if (isEarly && before !== undefined) {
653    await update($, history, x => ({ ...x, at: x.at - 1 }))
654    return playAt($, before.tracks, before.index, before.genre, true)
655  }
656  if (p.pgid !== null && p.tracks[p.index] !== undefined) return playAt($, p.tracks, p.index, p.genre, true)
657  const last = h.items[h.at]
658  return last === undefined ? undefined : playAt($, last.tracks, last.index, last.genre, true)
659}
660
661async function favorites($: Engine): Promise<Track[]> {
662  const v = await $.store.get('favorites')
663  return Array.isArray(v) ? (v as Track[]) : []
664}
665
666// ★: the song playing joins the favorites, or leaves them if it was there.
667// Undefined when nothing plays.
668async function toggleFavorite($: Engine): Promise<boolean | undefined> {
669  const p = await read($, player)
670  const now = p.pgid === null ? undefined : p.tracks[p.index]
671  if (now === undefined) return undefined
672  const list = await favorites($)
673  const isIn = list.some(t => t.id === now.id)
674  const next = isIn ? list.filter(t => t.id !== now.id) : [...list, { id: now.id, title: unmark(now.title), seconds: now.seconds }].slice(-FAVORITES_MAX)
675  await $.store.set('favorites', next)
676  $.ui.toast(isIn ? `music: "${unmark(now.title)}" left the favorites` : `music: "${unmark(now.title)}" kept in the favorites`)
677  // A discovery kept: its artist joins the station it played on.
678  const h = await read($, history)
679  const here = h.items[h.at]
680  if (now.title.startsWith(DISCOVERED) && here?.genre && here.genre !== FAVORITES && here.artist) {
681    await teach($, here.genre, here.artist, !isIn)
682    if (!isIn) $.ui.toast(`music: ${here.artist} joins the station`)
683  }
684  $.ui.invalidate('ui.render')
685  return !isIn
686}
687
688async function playFavorites($: Engine): Promise<Track | undefined> {
689  const list = await favorites($)
690  if (list.length === 0) {
691    $.ui.toast('music: no favorites yet, keep adds the song playing')
692    return undefined
693  }
694  return playAt($, shuffled(list), 0, FAVORITES)
695}
696
697async function toggle($: Engine): Promise<Player | undefined> {
698  const p = await read($, player)
699  if (p.pgid === null) return p
700  // VLC not listening (still starting, gone): the state stays as it is, so
701  // the poll keeps watching a song that still plays.
702  const sent = await $.process.run(pauseArgv(p.isPlaying))
703  if (sent.exitCode !== 0) {
704    $.ui.toast('music: VLC did not answer, try again')
705    return undefined
706  }
707  const now = await $.clock.now()
708  const q: Player = p.isPlaying
709    ? { ...p, isPlaying: false, pausedAt: now }
710    : { ...p, isPlaying: true, pausedAt: null, startedAt: (p.startedAt ?? now) + (now - (p.pausedAt ?? now)) }
711  await update($, player, () => q)
712  // A voice that started or ended while paused: the level follows it again.
713  if (q.isPlaying) await $.process.run(detached(duckArgv(await read($, volume), await isAvatarVoicing($))))
714  $.ui.status(show(q))
715  return q
716}
717
718async function isAvatarVoicing($: Engine): Promise<boolean> {
719  return (await $.state.get({ plugin: 'avatar7', key: 'isVoicing' })).value === true
720}
721
722async function louder($: Engine, delta: number): Promise<number> {
723  const v = clampVolume((await read($, volume)) + delta)
724  await update($, volume, () => v)
725  if ((await read($, player)).pgid !== null) await $.process.run(duckArgv(v, await isAvatarVoicing($)))
726  return v
727}
728
729async function stop($: Engine) {
730  const p = await read($, player)
731  await halt($, p.pgid)
732  await update($, player, () => IDLE)
733  $.ui.status(undefined)
734  await $.ui.close({ id: PANE })
735}
736
737async function play($: Engine, query: string, long: boolean): Promise<Track | undefined> {
738  const found = await $.process.run(search(query), { timeoutMs: 20_000 })
739  if (found.exitCode !== 0) return undefined
740  const first = pickTrack(found.stdout, long)
741  if (first === undefined) return undefined
742  // The track asked for plays whatever its length; next walks songs only
743  // (no hour-long mix, no live stream that never ends).
744  const rest = parseTracks(found.stdout).filter(t => t.id !== first.id && isSong(t))
745  return playAt($, [first, ...rest], 0)
746}
747
748// The album asked for, from its first track, in order: next walks it, back
749// goes back in it, and its end ends the list.
750async function playAlbum($: Engine, query: string): Promise<{ name: string; track: Track } | undefined> {
751  $.ui.status(`music: looking for the album ${query}…`)
752  const found = await $.process.run(albumSearchArgv(query), { timeoutMs: 20_000 })
753  const url = found.exitCode === 0 ? found.stdout.split('\n').map(l => l.trim()).find(l => l.startsWith('https://')) : undefined
754  if (url === undefined) {
755    $.ui.status(undefined)
756    return undefined
757  }
758  const listed = await $.process.run(albumTracksArgv(url), { timeoutMs: 30_000 })
759  const album = listed.exitCode === 0 ? parseAlbum(listed.stdout) : { name: '', tracks: [] }
760  if (album.tracks.length === 0) {
761    $.ui.status(undefined)
762    return undefined
763  }
764  const track = await playAt($, album.tracks, 0)
765  return track === undefined ? undefined : { name: album.name, track }
766}
767
768// Lists what YouTube finds for a search, and keeps it for a pick; undefined
769// when yt-dlp failed. One search at a time.
770async function find($: Engine, query: string): Promise<Track[] | undefined> {
771  isFinding = true
772  try {
773    const r = await $.process.run(search(query), { timeoutMs: 20_000 })
774    if (r.exitCode !== 0) return undefined
775    const tracks = parseTracks(r.stdout)
776    await update($, found, () => ({ query, tracks }))
777    return tracks
778  } finally {
779    isFinding = false
780  }
781}
782
783// The result at `index` (from 0) plays whatever its length; next walks on
784// through the rest of the search, as after /music <search>.
785async function pick($: Engine, index: number): Promise<Track | undefined> {
786  const f = await read($, found)
787  if (f.tracks[index] === undefined) return undefined
788  return playAt($, f.tracks, index)
789}
790
791// The results as /music find prints them: numbered from 1, with a length
792// when YouTube gave one.
793export const listing = (tracks: Track[]): string =>
794  tracks.map((t, i) => `${i + 1}. ${t.title}${t.seconds === null ? '' : ` (${clock(t.seconds)})`}`).join('\n')
795
796async function playGenre($: Engine, label: string): Promise<Track | undefined> {
797  const pool = await poolOf($, label)
798  // What played lately: the artists of this station, every song's id.
799  const played = (await read($, history)).items
800  const recent = played.filter(x => x.genre === label).map(x => x.artist ?? '').filter(a => a !== '')
801  const heard = new Set(played.map(x => x.tracks[x.index]?.id ?? ''))
802  const wantsNew = Math.random() < DISCOVER_ODDS
803  // One pick in three is a discovery: first from the radio of the station's
804  // last song, else from the genre's written list.
805  const seed = [...played].reverse().find(x => x.genre === label)?.tracks[0]?.id
806  if (wantsNew && seed !== undefined) {
807    $.ui.status(`music: looking for something new in ${pool.name}…`)
808    const radio = await $.process.run(radioArgv(seed), { timeoutMs: 20_000 })
809    const found = radio.exitCode === 0 ? radioDiscovery(parseRadioRows(radio.stdout), [...pool.artists, ...discoveries(label)], heard) : undefined
810    if (found !== undefined) {
811      const track = { ...found.track, title: `${DISCOVERED}${found.track.title}` }
812      $.ui.toast(`music now playing: ${track.title}`)
813      return playAt($, [track], 0, label, false, found.artist)
814    }
815  }
816  const fresh = discoveries(label)
817  const isNew = wantsNew && fresh.length > 0
818  const artist = anyOf(freshArtists(isNew ? fresh : pool.artists, recent))
819  if (artist === undefined) return undefined
820  $.ui.status(`music: looking for ${pool.name}, ${artist}…`)
821  const music = await $.process.run(musicSearch(artist), { timeoutMs: 20_000 })
822  let songs = music.exitCode === 0 ? parseTracks(music.stdout).filter(t => t.seconds === null || isSong(t)) : []
823  // Its titles carry no artist; the query names it.
824  songs = songs.map(t => ({ ...t, title: `${isNew ? DISCOVERED : ''}${artist} - ${t.title}` }))
825  if (songs.length === 0) {
826    const found = await $.process.run(search(artist), { timeoutMs: 20_000 })
827    songs = found.exitCode === 0 ? parseTracks(found.stdout).filter(isSong) : []
828    if (isNew) songs = songs.map(t => ({ ...t, title: `${DISCOVERED}${t.title}` }))
829  }
830  const track = anyOf(freshSongs(songs, heard))
831  if (track === undefined) {
832    $.ui.status(undefined)
833    $.ui.toast(`music: nothing found for ${artist}`)
834    await $.state.set({ plugin: 'jukebox7', key: 'say' }, { mood: 'error', event: `the jukebox found nothing to play for ${artist}`, at: Date.now() } satisfies Say)
835    return undefined
836  }
837  $.ui.toast(`music now playing: ${track.title}`)
838  return playAt($, [track], 0, label, false, artist)
839}
840
841// More like the song playing: its YouTube Music radio, as a list next walks.
842async function playSimilar($: Engine): Promise<Track | undefined> {
843  const p = await read($, player)
844  const now = p.tracks[p.index]
845  if (now === undefined) return undefined
846  $.ui.status(`music: looking for songs like ${now.title}…`)
847  const found = await $.process.run(radioArgv(now.id), { timeoutMs: 20_000 })
848  const tracks = found.exitCode === 0 ? parseRadio(found.stdout) : []
849  if (tracks.length === 0) {
850    $.ui.status(show(p))
851    $.ui.toast('music: no radio for this one')
852    return undefined
853  }
854  $.ui.toast(`music, like ${now.title}: ${tracks[0]?.title}`)
855  return playAt($, tracks, 0, null)
856}
857
858const clock = (s: number): string => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(Math.floor(s % 60)).padStart(2, '0')}`
859
860// `▰▰▰▱▱▱ 03:12 / 07:00`, or the elapsed time alone when YouTube gave no length.
861export const progress = (p: Player, now: number, seconds: number | null): { done: string; left: string; time: string } => {
862  const elapsed = p.startedAt === null ? 0 : Math.max(0, ((p.pausedAt ?? now) - p.startedAt) / 1000)
863  if (seconds === null || seconds <= 0) return { done: '', left: '', time: clock(elapsed) }
864  const filled = Math.min(BAR, Math.round((elapsed / seconds) * BAR))
865  return { done: '▰'.repeat(filled), left: '▱'.repeat(BAR - filled), time: `${clock(Math.min(elapsed, seconds))} / ${clock(seconds)}` }
866}
867
868// Ghost in the Shell's green code rain under the player: half-width katakana
869// and digits falling per column, moving only while a song plays.
870const GLYPHS = 'ヲァィゥェォャュョッアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン0123456789'
871const TRAIL = 6
872const RAIN_MS = 200
873let frame = 0
874const hash = (n: number): number => {
875  let h = Math.imul(n ^ 0x9e3779b9, 0x85ebca6b)
876  h ^= h >>> 13
877  h = Math.imul(h, 0xc2b2ae35)
878  return (h ^ (h >>> 16)) >>> 0
879}
880
881// One row is a list of runs: 0 blank, 1 trail (dim), 2 head (bright).
882export const rain = (columns: number, rows: number, tick: number): { level: 0 | 1 | 2; text: string }[][] =>
883  Array.from({ length: rows }, (_, r) => {
884    const runs: { level: 0 | 1 | 2; text: string }[] = []
885    for (let c = 0; c < columns; c++) {
886      const span = rows + TRAIL + (hash(c * 7 + 1) % rows || 1)
887      const speed = 1 + (hash(c * 13 + 5) % 2)
888      const head = (Math.floor((tick * speed) / 2) + hash(c * 29 + 3)) % span
889      const behind = head - r
890      const level: 0 | 1 | 2 = c % 2 === 1 || behind < 0 || behind > TRAIL ? 0 : behind === 0 ? 2 : 1
891      const ch = level === 0 ? ' ' : (GLYPHS[hash(c * 131 + r * 17 + Math.floor(tick / 3)) % GLYPHS.length] ?? ' ')
892      const last = runs[runs.length - 1]
893      if (last !== undefined && last.level === level) last.text += ch
894      else runs.push({ level, text: ch })
895    }
896    return runs
897  })
898
899export const register: Register = on => {
900  // A daemon's background session (a spare kept warm, a `claude --bg`)
901  // inherits the plugin dirs but nobody listens to it: no /music, no poll,
902  // no prompt turned into a song.
903  let isBackground = false
904
905  // avatar7 speaking: the music steps back, then returns to its level. The
906  // curl is detached, so the voice never waits on VLC.
907  on('state.set', { plugin: 'avatar7', key: 'isVoicing' }, async ($, e, next) => {
908    const done = await next(e)
909    const p = await read($, player)
910    if (p.pgid !== null && p.isPlaying) await $.process.run(detached(duckArgv(await read($, volume), e.value === true)))
911    return done
912  })
913
914  // ♪ next pressed in avatar7's pane: the next song, as from this pane.
915  on('state.set', { plugin: 'avatar7', key: 'musicNext' }, async ($, e, next) => {
916    const done = await next(e)
917    if ((await read($, player)).pgid !== null) void once($, () => skip($, 1))
918    return done
919  })
920
921  on('session.start', async ($, e, next) => {
922    const kind = await $.process.run(['sh', '-c', 'printf %s "$CLAUDE_CODE_SESSION_KIND"'])
923    isBackground = kind.stdout === 'bg'
924    if (isBackground) return next(e)
925
926    await $.command.register({
927      name: 'music',
928      description: 'Play music from YouTube: /music <search>, /music find <search> then /music pick <n>, /music album <artist album>, /music pause, /music back, /music next, /music fav, /music favorites, /music similar, /music stop, /music vol [+|-]<n>, /music alone for what plays',
929    })
930
931    // A pipeline that ended by itself (the track is over) moves on to the
932    // next result; one that cannot be found any more is forgotten.
933    $.clock.every(POLL_MS, () => {
934      void (async () => {
935        const p = await read($, player)
936        if (p.pgid === null || !p.isPlaying || isMoving) return
937        const alive = await $.process.run(['kill', '-0', '--', `-${p.pgid}`])
938        if (alive.exitCode === 0) {
939          $.ui.invalidate('ui.render')
940          return
941        }
942        // Nothing to follow (the list ended, no network, no station): the
943        // jukebox goes idle rather than retry every tick.
944        if ((await once($, () => skip($, 1))) === undefined) {
945          await update($, player, () => IDLE)
946          $.ui.status(undefined)
947        }
948      })()
949    })
950
951    // The phone, through avatar7's relay: its presses for the jukebox, and
952    // what the jukebox shows it, written again only when it changed.
953    let shown = ''
954    // Where the voice was at the last tick: undefined until first seen.
955    let wasHeld: boolean | undefined
956    $.clock.every(REMOTE_MS, () => {
957      void (async () => {
958        // The relay just taken: a song playing here starts again from its
959        // beginning, and its start takes the remote branch (no seek through
960        // the relay yet). Given back, the phone's song ends by itself and the
961        // next one plays here.
962        const isHeld = (await $.process.run(heldArgv())).stdout.trim() === 'up'
963        const was = wasHeld
964        wasHeld = isHeld
965        if (isHeld && was === false && !isMoving) {
966          const p = await read($, player)
967          if (p.pgid !== null && p.isPlaying) await once($, () => playAt($, p.tracks, p.index, p.genre))
968        }
969        // The avatar on duty's station, offered to the phone under the same
970        // name as on the terminal's button.
971        const { value: avatar } = await $.state.get(onDuty)
972        const { value: onAir } = await $.state.get(onStation)
973        const stationPick = avatar !== undefined && onAir !== undefined && onAir.artists.length > 0 ? `${onAir.name}'s pick` : undefined
974        const labels = [...GENRES.map(g => g.label), ...(stationPick !== undefined ? [stationPick] : []), FAVORITES]
975        const out = (await $.process.run(drainArgv())).stdout
976        for (const line of out.split('\n')) {
977          const press = parseJukebox(line, labels)
978          if (press === undefined) continue
979          if (press.do === 'pause') await toggle($)
980          else if (press.do === 'stop') await stop($)
981          else if (press.do === 'next') await once($, () => skip($, 1))
982          else if (press.do === 'back') await once($, () => back($))
983          else if (press.do === 'fav') await toggleFavorite($)
984          else if (press.do === 'voice') {
985            // A phrase spoken to the phone: the jukebox's if it asks for
986            // music, else a word to the avatar, as the phone's chat.
987            const said = await actOn($, press.text)
988            if (said === undefined) await $.process.run(chatArgv(), { stdin: JSON.stringify({ cmd: 'chat', text: press.text }) })
989            else $.ui.toast(said.replace(/^jukebox7: /, 'music: '))
990          }
991          else if (press.do === 'similar') await once($, () => playSimilar($))
992          else if (press.do === 'find') {
993            if (!isFinding) await find($, press.query)
994          } else if (press.do === 'pick') await once($, () => pick($, press.index))
995          else if (press.do !== 'genre') continue
996          else if (press.genre === FAVORITES) await once($, () => playFavorites($))
997          else {
998            const genre = press.genre === stationPick && avatar !== undefined ? avatar : press.genre
999            await once($, () => playGenre($, genre))
1000          }
1001          $.ui.invalidate('ui.render')
1002        }
1003        const p = await read($, player)
1004        const now = p.pgid === null ? undefined : p.tracks[p.index]
1005        const f = await read($, found)
1006        const status = JSON.stringify({
1007          title: now?.title ?? '', isPlaying: now !== undefined && p.isPlaying,
1008          genre: stationPick !== undefined && p.genre === avatar ? stationPick : p.genre ?? '',
1009          genres: labels, isMoving,
1010          // ★ full or empty on the phone for the song playing.
1011          isFavorite: now !== undefined && (await favorites($)).some(t => t.id === now.id),
1012          // The last search, for the phone to list and pick from.
1013          query: f.query, found: f.tracks.map(t => ({ title: t.title, seconds: t.seconds })), isFinding,
1014        })
1015        if (status !== shown) {
1016          await $.process.run(statusArgv(), { stdin: status })
1017          shown = status
1018        }
1019      })()
1020    })
1021
1022    $.clock.every(RAIN_MS, () => {
1023      void (async () => {
1024        if (!(await read($, player)).isPlaying) return
1025        frame += 1
1026        $.ui.invalidate('ui.render')
1027      })()
1028    })
1029
1030    // Unasked, the pane seats from 144 columns, under the avatar's; /music
1031    // opens it at any width.
1032    void $.ui.open({ id: PANE, title: 'jukebox7', rows: 6 })
1033
1034    return next(e)
1035  })
1036
1037  // Quitting (or /clear, which loses $.state's pgid) must not orphan the
1038  // detached pipeline. The end chain runs under one short bound and
1039  // PowerShell starts slower than that: the group goes at once, the VLC
1040  // kill is detached so it outlives the exit.
1041  // A session that never played (another window, a background spare) leaves
1042  // the VLC alone: it may be another session's song.
1043  on('session.end', async ($, e, next) => {
1044    const p = await read($, player)
1045    if (p.pgid !== null) {
1046      await $.process.run(signal('CONT', p.pgid))
1047      await $.process.run(signal('TERM', p.pgid))
1048      await $.process.run(detachedKillVlcArgv)
1049    }
1050    return next(e)
1051  })
1052
1053  on('prompt.submit', async ($, e, next) => {
1054    if (isBackground || (e.origin.kind !== 'composer' && e.origin.kind !== 'bridge') || !isCandidate(e.text)) return next(e)
1055
1056    const said = await actOn($, e.text)
1057    return said === undefined ? next(e) : { drop: said }
1058  })
1059
1060  on('command.run', { command: 'music' }, async ($, e) => {
1061    const args = e.args.trim()
1062    const isControl = args === '' || args === 'pause' || args === 'stop' || args === 'fav' || /^vol(?:ume)?\b/.test(args) || /^find\b/.test(args)
1063    if (!isControl && isMoving) return { text: 'A song is already on its way.' }
1064    const p = await read($, player)
1065    const now = p.tracks[p.index]
1066    if (args === '') {
1067      void $.ui.open({ id: PANE, title: 'jukebox7', rows: 6 })
1068      if (p.pgid === null || now === undefined) return { text: 'Nothing played from here yet: pick a genre in the pane.' }
1069      return { text: `${p.isPlaying ? 'Playing' : 'Paused'}: ${now.title}` }
1070    }
1071
1072    const vol = /^vol(?:ume)?(?:\s+([+-]?)(\d+))?$/.exec(args)
1073    if (vol !== null) {
1074      const [, sign, n] = vol
1075      if (n === undefined) return { text: `Volume ${await read($, volume)}%.` }
1076      const v = await louder($, sign === '' ? Number(n) - (await read($, volume)) : Number(`${sign}${n}`))
1077      return { text: `Volume ${v}%.` }
1078    }
1079
1080    const asAlbum = /^album\s+(.+)$/.exec(args)
1081    if (asAlbum !== null) {
1082      const query = (asAlbum[1] ?? '').trim()
1083      const t = await once($, () => playAlbum($, query).then(x => x?.track))
1084      return { text: t === undefined ? `No album found on YouTube Music for "${query}".` : `Album: ${t.title}` }
1085    }
1086    if (args === 'back' || args === 'prev') {
1087      const t = await once($, () => back($))
1088      return { text: t === undefined ? 'Nothing played yet.' : `Back to: ${t.title}` }
1089    }
1090    if (args === 'fav') {
1091      const isIn = await toggleFavorite($)
1092      if (isIn === undefined) return { text: 'Nothing is playing from here.' }
1093      return { text: isIn ? 'Kept in the favorites.' : 'Removed from the favorites.' }
1094    }
1095    if (args === 'favorites') {
1096      const t = await once($, () => playFavorites($))
1097      return { text: t === undefined ? 'No favorites yet: /music fav keeps the song playing.' : `Favorites: ${t.title}` }
1098    }
1099
1100    if (args === 'similar' || args === 'like') {
1101      const t = await once($, () => playSimilar($))
1102      return { text: t === undefined ? 'No radio for this one.' : `Like it: ${t.title}` }
1103    }
1104
1105    if (args === 'pause' || args === 'next' || args === 'stop') {
1106      if (p.pgid === null) return { text: 'Nothing is playing from here.' }
1107      if (args === 'stop') {
1108        await stop($)
1109        return { text: 'Stopped.' }
1110      }
1111      if (args === 'next') {
1112        const t = await once($, () => skip($, 1))
1113        return { text: t === undefined ? 'End of the list.' : `Next: ${t.title}` }
1114      }
1115      const q = await toggle($)
1116      if (q === undefined) return { text: 'VLC did not answer; nothing changed.' }
1117      return { text: q.isPlaying ? 'Resumed.' : 'Paused.' }
1118    }
1119
1120    // /music find <search>: the results, numbered, nothing played; /music
1121    // pick <n> plays one of them.
1122    const asked = /^find\s+(.+)$/.exec(args)
1123    if (asked !== null) {
1124      if (isFinding) return { text: 'A search is already running.' }
1125      const query = (asked[1] ?? '').trim()
1126      const tracks = await find($, query)
1127      if (tracks === undefined) return { text: `The search for "${query}" failed.` }
1128      if (tracks.length === 0) return { text: `Nothing found on YouTube for "${query}".` }
1129      return { text: `${listing(tracks)}\n\n/music pick <n> plays one.` }
1130    }
1131    const picked = /^pick\s+(\d+)$/.exec(args)
1132    if (picked !== null) {
1133      const f = await read($, found)
1134      const n = Number(picked[1]) - 1
1135      if (f.tracks.length === 0) return { text: 'Nothing found yet: /music find <search> first.' }
1136      if (f.tracks[n] === undefined) return { text: `Pick 1 to ${f.tracks.length}.` }
1137      const t = await once($, () => pick($, n))
1138      return { text: t === undefined ? 'That one did not start.' : `Playing "${t.title}" (https://youtu.be/${t.id})` }
1139    }
1140
1141    const track = await once($, () => play($, args, false))
1142    if (track === undefined) return { text: `Nothing found on YouTube for "${args}".` }
1143    return { text: `Playing "${track.title}" (https://youtu.be/${track.id})` }
1144  })
1145
1146  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1147    const { Box, Text, Button, Input } = $.ui.resolve(e)
1148    const p = await read($, player)
1149    const level = await read($, volume)
1150    const now = p.tracks[p.index]
1151    const { value: avatar } = await $.state.get(onDuty)
1152    const { value: onAir } = await $.state.get(onStation)
1153    const station = onAir !== undefined && onAir.artists.length > 0 ? onAir : undefined
1154    const isFavorite = now !== undefined && (await favorites($)).some(t => t.id === now.id)
1155    const isTerminal = e.surface === 'terminal'
1156    // The border and the play glyph take three columns on the terminal.
1157    const width = Math.max(10, (e.props.bodyColumns ?? 40) - (isTerminal ? 5 : 2))
1158    const title = now === undefined ? 'Nothing plays.' : now.title.length > width ? `${now.title.slice(0, width - 1)}…` : now.title
1159    const where = p.genre === null || p.genre === undefined ? `${p.index + 1}/${p.tracks.length}` : (GENRES.some(g => g.label === p.genre) || p.genre === FAVORITES ? p.genre : (onAir?.name || p.genre))
1160
1161    // A list, not a fragment: the terminal lays a fragment out as a column of
1162    // its own, which stacked the controls one per row and cut off `u: vol+`.
1163    const controls = [
1164      <Button key="back" label="back" hotkey="b" plain onPress={() => void once($, () => back($))} />,
1165      <Button key="toggle" label={p.isPlaying ? 'pause' : 'play'} hotkey="p" plain onPress={() => void toggle($)} />,
1166      <Button key="next" label="next" hotkey="n" plain onPress={() => void once($, () => skip($, 1))} />,
1167      <Button key="fav" label={isFavorite ? 'kept' : 'keep'} hotkey="k" plain onPress={() => void toggleFavorite($)} />,
1168      <Button key="similar" label="similar" hotkey="r" plain onPress={() => void once($, () => playSimilar($))} />,
1169      <Button key="stop" label="stop" hotkey="s" plain dimColor onPress={() => void stop($)} />,
1170      <Button key="quieter" label="vol−" hotkey="d" plain dimColor onPress={() => void louder($, -VOLUME_STEP)} />,
1171      <Button key="louder" label="vol+" hotkey="u" plain dimColor onPress={() => void louder($, VOLUME_STEP)} />,
1172    ]
1173    const f = await read($, found)
1174    const isSearching = await read($, searching)
1175    const fit = (t: string, room: number): string => (t.length > room ? `${t.slice(0, room - 1)}…` : t)
1176    const reopen = (open: boolean, results: number) => void $.ui.open({ id: PANE, title: 'jukebox7', rows: paneRows(open, results) })
1177    const finder = (
1178      <Button
1179        key="find"
1180        label={isSearching ? 'close search' : 'find'}
1181        hotkey="f"
1182        plain
1183        dimColor={!isSearching}
1184        onPress={() => {
1185          void (async () => {
1186            await update($, searching, () => !isSearching)
1187            reopen(!isSearching, f.tracks.length)
1188          })()
1189        }}
1190      />
1191    )
1192    const search = isSearching ? (
1193      <Box flexDirection="column" backgroundColor={isTerminal ? BLACK : undefined}>
1194        <Input
1195          key="query"
1196          label="find: "
1197          placeholder={f.query === '' ? 'ctrl+x tab, a search, Enter' : f.query}
1198          submitLabel="find"
1199          autoFocus
1200          onSubmit={value => {
hooks/remote.ts 83 lines
1// jukebox7's remote branch: pure strings, run for real by
2// tools/test_remote_shell.ts (the plugin tests mock every process).
3//
4// While avatar7's relay is held (the voice is on the phone), the music goes
5// there too: the song is written for the relay (music.json), the phone streams
6// it through the relay, and this process waits for the phone to say it ended
7// (or skipped it): then it ends, and the poll moves on as when VLC ends a song.
8// Given back meanwhile, it ends too, and the next song plays here. Its exit
9// clears music.json unless a newer song took it already. No single quote: it
10// runs inside one.
11export const RELAY = '"\${XDG_CACHE_HOME:-$HOME/.cache}/avatar7/relay"'
12export const REMOTE =
13  `R=${RELAY}; if [ -f "$R/owner" ]; then rm -f "$R/ended-$1"; ` +
14  `printf "{\\"id\\": \\"%s\\", \\"paused\\": false}" "$1" > "$R/music.part" && mv "$R/music.part" "$R/music.json"; ` +
15  `trap "grep -q $1 $R/music.json 2>/dev/null && printf {} > $R/music.part && mv $R/music.part $R/music.json" EXIT; trap exit TERM; ` +
16  `while [ ! -f "$R/ended-$1" ] && [ -f "$R/owner" ]; do sleep 1; done; rm -f "$R/ended-$1"; exit; fi; `
17
18// Prints `up` while a session holds the relay: the poll watches it change,
19// so a song already playing here moves to the phone when the voice does.
20export const heldArgv = (): string[] => ['sh', '-c', `R=${RELAY}; [ -f "$R/owner" ] && echo up; true`, 'jukebox7-held']
21
22// Pause on the phone flips the flag of the song music.json holds; otherwise
23// the arguments after the script (VLC's curl) run as they are.
24export const pauseScript = (isPaused: boolean): string =>
25  `R=${RELAY}; if [ -f "$R/owner" ] && grep -q '"id"' "$R/music.json" 2>/dev/null; then ` +
26  `sed 's/"paused": [a-z]*/"paused": ${isPaused}/' "$R/music.json" > "$R/music.part" && mv "$R/music.part" "$R/music.json"; else exec "$@"; fi`
27
28// The phone's presses for the jukebox, queued by the relay one JSON file each
29// under jukebox/: read and removed in one go, a line each.
30export const drainArgv = (): string[] => [
31  'sh',
32  '-c',
33  `R=${RELAY}; for f in "$R"/jukebox/*.json; do [ -f "$f" ] && cat "$f" && echo && rm -f "$f"; done; true`,
34]
35
36// What the jukebox shows the phone (title, playing, genre, the genres), from
37// stdin, while a session holds the relay.
38// A phrase for the avatar, written as the relay writes the phone's chat: a
39// file in its command spool, which avatar7 drains.
40export const VOICE_MAX = 300
41export const chatArgv = (): string[] => [
42  'sh',
43  '-c',
44  `R=${RELAY}; [ -f "$R/owner" ] && mkdir -p "$R/cmd" && f="$R/cmd/$(date +%s%N)" && cat > "$f.part" && mv "$f.part" "$f.json"; true`,
45]
46
47export const statusArgv = (): string[] => [
48  'sh',
49  '-c',
50  `R=${RELAY}; [ -f "$R/owner" ] && cat > "$R/jukebox.part" && mv "$R/jukebox.part" "$R/jukebox.json"; true`,
51]
52
53export type JukeboxPress =
54  | { do: 'pause' | 'next' | 'similar' | 'stop' | 'back' | 'fav' }
55  | { do: 'genre'; genre: string }
56  | { do: 'find'; query: string }
57  | { do: 'voice'; text: string }
58  | { do: 'pick'; index: number }
59
60// A search asked from the phone, cut as the relay cuts it.
61export const QUERY_MAX = 120
62
63// A press as the relay queued it, or undefined for anything else: a genre
64// must be one of the given labels.
65export const parseJukebox = (line: string, genres: string[]): JukeboxPress | undefined => {
66  let r: unknown
67  try {
68    r = JSON.parse(line)
69  } catch {
70    return undefined
71  }
72  if (typeof r !== 'object' || r === null) return undefined
73  const o = r as Record<string, unknown>
74  if (o.do === 'pause' || o.do === 'next' || o.do === 'similar' || o.do === 'stop' || o.do === 'back' || o.do === 'fav') return { do: o.do }
75  if (o.do === 'genre' && typeof o.genre === 'string' && genres.includes(o.genre)) return { do: 'genre', genre: o.genre }
76  if (o.do === 'find' && typeof o.query === 'string' && o.query.trim() !== '') return { do: 'find', query: o.query.trim().slice(0, QUERY_MAX) }
77  // A phrase the phone heard (its speech recognizer): Haiku reads it.
78  if (o.do === 'voice' && typeof o.text === 'string' && o.text.trim() !== '') return { do: 'voice', text: o.text.replace(/\s+/g, ' ').trim().slice(0, VOICE_MAX) }
79  // Which result of the last search, from 0; checked against the list when it plays.
80  if (o.do === 'pick' && typeof o.index === 'number' && Number.isInteger(o.index) && o.index >= 0) return { do: 'pick', index: o.index }
81  return undefined
82}
83
types/index.d.ts 42 lines
1export type Track = { id: string; title: string; seconds: number | null }
2
3// What plays: the search results, the one playing, and the process group of
4// its yt-dlp | VLC pipeline. Kept in $.state so a reload still owns it.
5export type Player = {
6  tracks: Track[]
7  index: number
8  pgid: number | null
9  isPlaying: boolean
10  // The genre button behind it: next and the end of a song roll again there.
11  genre: string | null
12  // When the track started, pushed forward by each pause, and when the
13  // current pause began (ms, $.clock.now): what the progress bar reads.
14  startedAt: number | null
15  pausedAt: number | null
16}
17
18// What this mod asks avatar7 to say, if avatar7 is loaded: each song as it
19// starts, for the persona to introduce like a radio host; a search that found
20// nothing. avatar7 hears the write; nothing here depends on it.
21export type Say = { mood: 'watch' | 'error'; event: string; at: number }
22
23// The last search asked for a pick (/music find, the pane's f, the phone):
24// what was asked and the results, in YouTube's order.
25export type Found = { query: string; tracks: Track[] }
26
27// One model call of this mod (the intent of a prompt), for usage-bell's tally.
28export type ModelUse = { model: string; input: number; output: number; cacheRead: number; at: number }
29
30// What played, for back (⏮) and for next to walk forward again: each song
31// with its list and its station; `at` is the one playing.
32export type Played = { tracks: Track[]; index: number; genre: string | null; artist?: string }
33export type History = { items: Played[]; at: number }
34
35declare module 'claude-code' {
36  interface PluginState {
37    jukebox7: { player: Player; volume: number; say: Say; found: Found; searching: boolean; modelUse: ModelUse; history: History }
38    // Read only: avatar7 owns it and says which face is on duty.
39    avatar7: { avatar: string; color: string; isVoicing: boolean; station: { name: string; artists: string[] }; musicNext: number }
40  }
41}
42