Live football in Claude Code for the competition you follow: the score or the countdown above the prompt (the same line on demand with /claudinho), a toast…

<img src="https://raw.githubusercontent.com/arturogarrido/claudinho/main/.github/assets/logo.png" alt="The Claudinho logo: a yellow C around a football, above the word claudinho" width="120">
Live football in Claude Code, for the competition you follow:
toasts: all it also plays on any goal in a match that is not your team's. The mascot is Anthropic's: it is the one exception to this project's rule against logos and marks, and it is removed if Anthropic asks./claudinho match opens the match with its goals and cards beside the transcript./claudinho: the band's line on demand.<img src="https://raw.githubusercontent.com/arturogarrido/claudinho/main/.github/assets/plugin.gif" alt="Claude Code with the plugin during Real Betis v Barcelona on Oct 17, 2026: beside a coding answer, a toast and the mascot say GOAL! Barcelona, Rodri 41', the band shows the score in bold, and the match pane lists the goals and cards" width="800"> <img src="https://raw.githubusercontent.com/arturogarrido/claudinho/main/.github/assets/pane.png" alt="The match pane in Claude Code: Brentford 1–2 Liverpool, its goals and cards with each player" width="640">
The plugin reads everything from the claudinho CLI installed on your machine and never fetches anything itself.
You need the CLI (Node.js 22 or later) and a competition to follow. Node.js 22 is the oldest line it runs on, not a security level: run a patched release of the Node 22 or 24 line. Everything on this page needs @claudinho/cli 0.12.0 or later; With CLI 0.11.2 says what an older CLI gives.
npm i -g @claudinho/cli
claudinho follow premier-league --team Arsenal # the toasts and the celebration are for your pinned team by default
claudinho init plugin # only if Claudinho's statusline or hook is in Claude Code's settings (see below)
Then, at the prompt of Claude Code in a terminal:
/plugin install claudinho --marketplace arturogarrido/claudinho
Answer y to add the marketplace, then choose a scope (the user scope is the first, press Enter). The plugin is active in that session from then on. Installed at the user scope from a terminal, it also loads in the desktop app's Code tab, which cannot run /plugin install itself.
claudinho init plugin removes, from ~/.claude/settings.json, the statusline whose command is claudinho prompt and the prompt hook whose command is claudinho hook (the commands init claude, init-statusline and init-hook write by default), so the score does not show twice. It keeps every other setting. Any other command stays (a wrapper, an npx form, a --command one), and init plugin names it when it mentions claudinho.
To get new versions on their own: Claude Code leaves auto-update off by default for this marketplace. Turn it on once: run /plugin in a terminal, open the Marketplaces tab, select claudinho and choose Enable auto-update. A new version then installs in the background after a session starts; the session you are in keeps the version it loaded until you run /reload-plugins, and the next session you start loads the new one.
To remove the plugin: claude plugin uninstall claudinho@claudinho.
Change them in /config.
| Option | Values | Default |
|---|---|---|
toasts | pinned: your pinned team's match; all: every live match of the competition you follow; off: none | pinned (with no team pinned, no toasts) |
celebrate | on: the celebration plays on your team's goal and on its win or draw, and under toasts: all on any goal in a match that is not your team's; off: it never plays. The toasts are the same either way | on |
context | on: while a match is live, the score goes beside each prompt you send, for Claude; off: nothing goes with your prompts | on |
language | auto: the language your environment asks for (below); en, es, pt or fr: that language, whatever the environment says | auto |
Changing an option reloads the plugin. The band and every later toast follow the new value at once. An open match pane stays as it was drawn and stops reading: run /claudinho match again to update it.
The band shows the line claudinho prompt prints, in the plugin's language: the live score (⚽ ARS 2–1 CHE 50', the score in bold), or the countdown to the next match (⚽ ARS vs LEE in 7h13m). From kickoff until the data provider marks the match live, for up to 30 minutes, the countdown reads the language's word for now (⚽ BET vs BAR now; ahora, agora, maintenant) and keeps that match. With several matches live it shows them side by side (up to eight, and a count of the rest), or, while your pinned team is playing, its match and a count of the others (+2). It shows nothing when no competition is followed or nothing is known. At the end of the World Cup it shows its sign-off line.
A toast is one line: what happened, then the score. Examples with Liverpool pinned, away at LASK Linz:
| What happened | The toast |
|---|---|
| Your team scores | ⚽ GOAL! Liverpool · Ronald Araújo 22' · LASK Linz 0–1 Liverpool |
| ... and the scorer is not yet known | ⚽ GOAL! Liverpool 60' · LASK Linz 0–1 Liverpool |
| An own goal for your team | ⚽ Own goal · Liverpool 63' · LASK Linz 1–2 Liverpool |
| A goal against your team | Goal for LASK Linz · Robert Ljubicic 63' · LASK Linz 1–1 Liverpool |
| More than one goal since the last reading | Goals · LASK Linz 1–2 Liverpool |
| A score corrected down | Score updated · LASK Linz 0–0 Liverpool |
| A penalty shootout goes on | Penalties · LASK Linz 1(3)–1(4) Liverpool |
| Full time | Full time · LASK Linz 3–6 Liverpool · Liverpool win (or · Draw) |
The scorer is named only when the CLI proves it: its listed goals add up to the score, and the newest one is on the side that scored. Toasts are best effort, not a promise of every goal: a goal the plugin could not confirm when it happened is said late, at the first reliable reading after it.
The celebration plays on your team's goal (under toasts: all, on any goal in a match that is not your team's): the mascot on the left in your theme's Claude colour, its legs stepping, the ball crossing the top row, GOAL! Liverpool with GOAL! bold and in your theme's success colour, and the scorer's row under it. After about three seconds the band is one line again. At full time, on your team's win or draw (your team's match only), the mascot plays once more for five seconds beside Full time · Liverpool win. A goal against, a correction, penalties and a loss play nothing. While Claude is working the celebration waits, and plays when the turn ends (within a minute; after that the toast has already said it).
The match pane opens with /claudinho match and shows the match you follow now: the score in bold, your team in the success colour, the competition, stage and venue dimmed, the status and the kickoff, and the goals and cards, each marked (⚽, 🟨, 🟥) with the scorer in bold. In a narrow pane the player of each goal or card goes on the next line, under the event. It updates when the band sees the score change, and every two minutes while the match is in play. Close it with its close mark (or ctrl+x x). The command answers in one line, claudinho: ⚽ LAS 0–4 LIV 62' · match pane open, when the pane opened.
The context: while a match is live, each prompt you send carries the live score for Claude, from the plugin's last reading, when that reading is current and less than 30 seconds old. Off-match it adds nothing. The context option turns it off.
/claudinho prints the band's line now, with the data provider's name and the non-affiliation sentence under it, or one plain sentence when there is nothing to show.
claude -p, the SDK, a phone, an editor alone) the band runs nothing. /claudinho still answers when you type it.Everything on this page needs @claudinho/cli 0.12.0 or later. With 0.11.2 the plugin works in part: a toast is ⚽ and the hook's own English line for any score change (⚽ Arsenal 2–1 Chelsea (67')), the celebration is a ball and a growing "GOAL!", the band's line is plain and English, the match pane says Nothing to show: the CLI's answer is not one this plugin reads., and no full time is said. The language option changes none of it. With a CLI older than 0.11.2 the band shows nothing and nothing toasts. Update the CLI to see the rest.
The plugin runs claudinho from the PATH Claude Code started with. When that PATH does not hold it (an app can start Claude Code with a minimal PATH), the plugin also looks where the usual installers put global commands: nvm's recent Node versions, ~/.volta/bin, ~/.local/share/pnpm, ~/Library/pnpm, ~/.bun/bin, ~/.npm-global/bin, ~/.local/bin, /opt/homebrew/bin, /usr/local/bin, /usr/bin and /bin. A CLI installed anywhere else leaves the band empty, and /claudinho answers The CLI gave no answer. On Windows the plugin uses Claude Code's own PATH only.
auto speaks the language your environment asks for, as the CLI reads it: CLAUDINHO_LANG, then the language part of LANG (es_MX.UTF-8 is Spanish), each only when it is en, es, pt or fr, else English. The band, the toasts, the celebration and the match pane follow the option. A Spanish session reads ⚽ ¡GOL! Liverpool · Ronald Araújo 22' · LASK Linz 0–1 Liverpool and ⚽ BOU vs BRE en 17m. The words come from the CLI: the plugin passes --lang with the chosen code to the CLI runs of the band and of /claudinho, and to the match pane's runs once the CLI has said it speaks that language. Names, scores and minutes are never translated.
Some things stay English in every language: the terminal statusline (claudinho prompt), the hook, the live score beside your prompt for Claude, the band's +more, the World Cup's sign-off line and ⚽ —. The countdown's units (2d4h, 17m) are the same in every language. An open match pane keeps its rows in the language it read them in until /claudinho match opens it again.
The band runs claudinho ambient --json every 15 seconds (every five minutes on the World Cup's sign-off line and while no competition is followed), which also keeps the CLI's local cache fresh. That command answers from the cache and never waits on the network; when the cache is due for a refresh it starts the CLI's background refresh, as the statusline does. While no competition is followed it reads no cache and starts nothing: its line is ⚽ claudinho follow. The CLI fits the line to the band's width and marks each score in it; the band draws the marks only when they spell the line exactly. A band another plugin draws beneath ours stays, under our line.
A toast compares two readings the CLI vouches for: not stale, not degraded, and from a complete read. The first reading of a match says nothing, and neither does a change of competition. When one change could read two ways, the first that holds is said: Score updated, then Penalties, then the goal, then Goals. Every toast follows the toasts option.
Full time is said only by a current reading. The CLI lists a finished match for ten minutes after the reading that saw it end, and stops polling once the day's last match is over, so a session with no current reading in the minutes after the whistle (closed, idle or offline then) hears nothing about it.
The celebration takes up to three rows above the line and leaves room for a band beneath ours. With two rows it shows GOAL! Liverpool and the scorer's row, with one GOAL! Liverpool 22', and with none it waits. A later score change in that match, a change of the competition you follow, the last window closing, a reload of the plugin (changing an option reloads it) or, while it waits, the minute running out drops it. A full-time celebration lasts only while each later reading still lists the match as finished with the same result: another result at the same score, the match listed live again, or not listed at all drops it (a goal celebration queued before it keeps its own rules).
/claudinho repliesWhen there is nothing to show, /claudinho answers one of these sentences, chosen from what the CLI answered:
The CLI gave no answer. The CLI could not be found or run, took longer than two seconds, failed, or printed something that is not its answer.No competition followed yet. Run claudinho follow <alias>.Nothing to show: the CLI's answer is not one this plugin reads. Usually a CLI older than the plugin.Nothing to show right now: no live match and no next fixture known.The edition you follow is over.A reply made from a reading ends with the provider's name and the non-affiliation sentence, each when the reading carries it. /claudinho match answers in one line only when its pane opened on a terminal or desktop window and holds both of those sentences; otherwise it gives the same reply as /claudinho. Each /claudinho runs the CLI once and changes nothing the band shows. A /claudinho typed while Claude is working runs when the turn ends.
--competition, so its row then says "from the command line"./claudinho match.Goal, Yellow card), so the timeline reads as one column. Any other row too wide for the pane continues under its own first character (an indented row keeps its indent). The pane measures widths as the CLI does.The CLI gave no answer. Later: the last rows stay, under Could not refresh: showing the last reading.claudinho match <id>, which asks the data provider about five times. In play that is about two and a half requests a minute, plus one read per goal. Before kickoff and after full time, none. When the provider asks the CLI to slow down, the pane's reads wait too.Everything the plugin's code (hooks/register.tsx) does beyond drawing the band, the toasts and the pane is listed here.
The plugin runs one program, claudinho: the CLI you installed. It runs it in these forms and no other:
| When | The command |
|---|---|
| The band, every 15 seconds while a terminal or desktop window is attached (less often on an idle line, see How the band reads) | claudinho ambient --json --columns <N> --lang <xx> |
/claudinho and /claudinho match, when you type them | claudinho ambient --json --lang <xx> |
The match pane, after /claudinho match | claudinho match <id> --json, then --competition <slug> and --lang <xx> when they apply |
Four arguments are not fixed text. Each comes from one place:
<N>: the band's width in columns, as Claude Code reports it (80 until it does).<xx>: en, es, pt or fr. The language option decides it; under auto, CLAUDINHO_LANG or LANG does (see The language). The pane's runs add it once the CLI has said it speaks that language.<id>: the id of the match the CLI's own last answer listed (the live match or the next fixture).<slug>: the competition the CLI's own answer named when the pane opened. The pane adds it once a run made without it answers for another competition or for none (you followed another one after opening the pane).None of them comes from your prompts, your files or the conversation. The plugin passes the arguments as a list, with no shell, and writes nothing to the program's input. A band or /claudinho run may take 2 seconds, a pane run 5; Claude Code stops a run that takes longer. Off Windows, the plugin hands the run one variable, PATH, made of the folders in Claude Code's own PATH and folders from Finding the CLI. Every other variable of Claude Code's environment reaches the run as it is. On Windows the plugin hands nothing, and the run gets Claude Code's environment as it is.
Why a program: the CLI owns the football data. It reads ESPN, keeps the local cache and respects the provider's limits. The plugin itself makes no network request. What leaves your machine is the CLI's own requests to ESPN (and to Polymarket for a World Cup match's market signal in the pane), as PRIVACY.md describes. Those requests carry football parameters, such as a competition and dates, never anything from your session.
OS. Off Windows, also PATH and HOME. Under language: auto, also CLAUDINHO_LANG and LANG.HOME set to an absolute path, it lists ~/.nvm/versions/node (its first 256 entries) and checks up to eight of the newest version folders for bin/claudinho, once per plugin load. That finds a CLI nvm installed when Claude Code started with a bare PATH. It reads no file's contents and writes no file./claudinho still runs the CLI when you type it.prompt.submit hook): with context: on, when the plugin's last reading is current, still inside the CLI's own deadline for it, less than 30 seconds old and shows a live match, the hook adds the CLI's short note beside your prompt, as the CLI wrote it: the line [Claudinho — live football scores right now] and one line per live match, the team you picked first (at most 12, then a line when more are not shown; the CLI cuts a longer note at about 4,096 characters and says so). Claude Code sends that note to the model with your prompt. The hook does not read your prompt's text, change it, keep it or send it anywhere, and it starts no program. With context: off it adds nothing./claudinho (the command.run hook): the hook answers the command the plugin registers, /claudinho, and no other. It reads the text you typed after /claudinho for the word match alone. It runs the CLI as listed above, answers with text (the band's line, or a sentence when there is nothing to show), and opens the pane for match.Live data: ESPN, read by the CLI, which keeps it in a local cache. The plugin's football data is the CLI's answer alone. The plugin itself makes no network request and writes no file. Full policy: PRIVACY.md.
Independent fan project. Not affiliated with FIFA, any confederation, league or club, or Anthropic.
hooks/register.tsx 2193 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, FsEntry, ProcessRunResult, Register, RenderChildren, Timer } from 'claude-code'
3
4import type {
5 ClaudinhoBand,
6 ClaudinhoBaseline,
7 ClaudinhoCelebration,
8 ClaudinhoContext,
9 ClaudinhoGoal,
10 ClaudinhoOutcome,
11 ClaudinhoPace,
12 ClaudinhoPane,
13 ClaudinhoPanePart,
14 ClaudinhoPaneRow,
15 ClaudinhoPlay,
16 ClaudinhoTally,
17} from '../types'
18
19/**
20 * The claudinho plugin: the live score or the countdown above the prompt (the band), a toast when a score changes,
21 * the live score beside the prompt for the model (none under `context: off`), `/claudinho`, the band's line on demand,
22 * and the match pane (`/claudinho match`).
23 *
24 * The CLI owns the data (its cache, its refresher, the network, the backoff) and the words: the plugin itself makes no
25 * network request.
26 * This module runs the one binary, `claudinho ambient --json` (the band's runs add `--columns <the band's columns>`;
27 * the pane runs `claudinho match <id> --json`, whose read of the provider is the CLI's; every ambient run ends with
28 * `--lang <code>`, the `language` option's, `auto` resolved from the host's environment as the CLI resolves it, and the
29 * match runs too once any view said the CLI localizes, `cliLocalizes`), with an argument array,
30 * bounded, and reads the fields of the one JSON object it prints, never its text: what the line IS (`idle`, `empty`,
31 * the first run's `noCompetition`), whether its list is `current`, and the hook's own line on each record, said
32 * verbatim. No binary, a timeout, a cut or an answer that is not the object: the band shows nothing (the command says
33 * so in one fixed sentence), never a blocked turn. Every run is also what triggers the CLI's refresher, so the band
34 * runs at the live pace on every line but the idle ones. Best effort throughout: a toast says a score change this
35 * module observed between two current views, never every goal. The band draws the CLI's `lineParts` (CLI 0.12.0), each
36 * `strong` part bold, only when their texts join to the line; else the plain line.
37 *
38 * The toasts (`momentsFor`), per match between two current views, under `toasts`: a record that carries `names` (CLI
39 * 0.12.0) says what happened, from the CLI's fields alone, in the view's `words` (read whole, else today's English
40 * words for every moment together; the English ones are written here): `⚽ GOAL! <team>` for one side up by exactly 1
41 * (the scorer and the goal's minute only when `lastGoal` is a new identity on that side, a proven own goal
42 * `⚽ Own goal · <team>`, else the record's clock minute), `Goal for <team>` for the side opposite `pinnedSide`, `Goals`
43 * for more than one, `Score updated` for a tally that fell, `Penalties` for a shootout tally that rose (in that order
44 * of precedence), each with the scoreline from `names`; and full time, a record of the last current view's live list
45 * now in `finished` (the goal toast first when its tally rose in the same read, then `Full time ·` the scoreline and
46 * the result). A record without `names` (CLI 0.11.2) toasts today's `⚽` and its own `line`, and no full time is said
47 * for it.
48 *
49 * The band runs while a surface that draws it is attached: the terminal or the desktop app, the two that raise
50 * `AbovePrompt`, asked of the session's roster at every run, first and again as the last step before the spawn (the
51 * desktop app's session starts with no surface and attaches after; a plugin loaded into an open desktop session hears
52 * a start with no surface while the roster holds the desktop). A run that finds none attached (`claude -p`, the SDK, a
53 * phone or an editor alone), or cannot read the roster, starts no process and clears the band. A roster read refused at
54 * the start is unknown, so the pace starts and each run asks again: a read denied for good costs one read per 15
55 * seconds and no process. Each run is handed a PATH: the host's own, then the folders npm, Homebrew, nvm, Volta, pnpm
56 * and Bun put global commands in, so a session started with a bare PATH still finds the CLI and its `node` (on
57 * Windows nothing is handed). nvm's part is looked up once per load; while that lookup has not answered, each run waits
58 * at most a second for it and uses the PATH without nvm's folders, and the first run that finds it answered keeps the
59 * PATH with them. A band drawn beneath ours in the hook chain (a plugin registered after ours, or the engine's own)
60 * stays, under our line: we never drop it.
61 * A run's answer is drawn only if no clear (a window leaving, or a run finding none) happened since the run began its spawn.
62 *
63 * `/claudinho` is registered at every start, headless included, and answers by itself: one `claudinho ambient --json`
64 * run on the band's PATH, read by the band's own reading of the answer (`readAnswer`), replied as the view's line or
65 * one fixed sentence chosen by what the answer says. With no `--columns` the CLI fits the line to its own ceiling,
66 * 200 display columns, never to the window: past it the CLI keeps its `+N` count of the other matches, or ends an
67 * over-wide segment with `…`; the transcript row wraps what it draws. A reply made from a view (its line, or the idle
68 * or empty sentence) ends with the view's own provider attribution and then its disclaimer, each after a blank line,
69 * relayed from its `attribution` and `disclaimer` fields (each only when usable), never spelled here; a reply made
70 * from no view is its sentence alone. Its run is its own: whatever the roster says,
71 * it takes no part in the band's guard or pace, reads and writes no `$.state` value, raises no toast and clears
72 * nothing; it shares only the kept PATH and nvm's lookup (`/claudinho match` writes the pane's two values alone, below).
73 * The text typed after the command is read for one word alone: `match` (surrounding spaces aside) opens the match pane;
74 * any other text is ignored.
75 *
76 * The match pane: `/claudinho match` binds, from the command's own reading, a view's competition (its slug) and the
77 * first record of its live list (the CLI lists the pick first), else its `next`; nothing to bind, no read and no pane.
78 * It writes the pane's value under a new generation (`paneGen`), first a provisional one (the view's line and footer),
79 * and opens the pane `match` at once inside the hook (an open is the person's only within about 15 s of the command,
80 * measured); then it runs `claudinho match <id> --json` once (5 s, the whole stdout ONE JSON value), whose answer
81 * replaces the provisional value; the reply is the view's line and ` · match pane open` when the pane opened with the
82 * CLI's rows and both its attribution and its disclaimer on a surface that draws it (the pane carries them), else the
83 * bare one
84 * (headless, nothing to bind, a first read that failed). A match run names no competition, so the CLI resolves the
85 * person's own choice (its mode row says where it came from); an answer of another competition, or the first-run object
86 * (nothing chosen now), is never used: the binding is pinned for good and the read is made once more with
87 * `--competition <slug>`. The pane draws the CLI's `rows` by their parts' styles when they join to its `lines` (CLI
88 * 0.12.0: strong bold, dim dimmed, accent and flair the theme's `success`, quote dimmed italic), laid out at the
89 * pane's width (`bodyColumns`, a positive integer; plugin 0.5.1) by each row's role: when any named event row (role
90 * `event`, its last part `strong`: the player) is wider than the pane, every named event row is drawn as two rows,
91 * the event, then the player, bold, under the event label's column; any other row wider than the pane continues
92 * under its own first non-space character (display widths by core's `displayWidth`, copied: an emoji cluster, a
93 * keycap and an East Asian wide character 2, a combining mark, a format or a control character 0, else 1); with no
94 * usable width, or a value written before the roles, the rows as before; else its `lines` verbatim (at most 150, each
95 * cut at 600 characters, each wrapped), a blank row, then the `attribution` and the `disclaimer` dimmed (each at 1,000), or one fixed sentence: a
96 * first read that failed, or an answer with no `lines` (a CLI before them). While open it re-reads the bound match: on
97 * a band run's CURRENT view of the bound competition that shows its score or shootout tally changed from the band's
98 * previous observation (seeded by the open's reading; consumed once), or lists it newly (kickoff) or no more (full
99 * time); at its kickoff alone while the last answer is not in play and its kickoff is ahead (degraded or not); every 2
100 * minutes otherwise: in play (`LIVE`, `HT`), failed, no match, a kickoff passed or unreadable. One read in flight at
101 * most, the open's included (it waits for the read in flight, whose answer its new binding fences off; a trigger during
102 * either is kept once); a read writes only under its generation; a failed re-read keeps the rows under a fixed row;
103 * none after a final answer (`FT`, `POSTPONED`, `CANCELLED`) or once closed. The close (`ui.close` for `match`) moves
104 * the generation on and drops the value, the binding and the timers. The binding and the timers are this module load's:
105 * after a reload the pane stays drawn from its value and is re-read again from the next `/claudinho match`.
106 *
107 * The goal celebration: when a run's toasts include a goal, the band plays it above its line in at most
108 * min(3, maxRows - 2) rows, then goes back to its one line. For a record without `names` (CLI 0.11.2), any goal (a
109 * regulation or shootout tally that rose, none that fell): 6 frames over 3 seconds, a ball crossing a row, a "GOAL"
110 * banner growing, then the toast's own line. For a record with `names`, a single-goal toast for the pinned side (with
111 * no `pinnedSide`, any): 3 seconds of Anthropic's Claude mascot as three rows of text art (the theme's `claude` colour,
112 * its legs alternating) beside the ball crossing the top row, `GOAL!` (the goal word the toast was built with, whole on
113 * every frame; bold, the theme's `success`) and the team on the middle row, the scorer and minute (or the minute) on
114 * the bottom row; two rows: the words alone; one: `GOAL! <team> <minute>`; none: it waits. `Goal for`, `Goals`,
115 * `Penalties` and `Score updated` play nothing. Full time for the pinned side's win or draw: the mascot beside
116 * `Full time · <result>` (in the words it was built with) for 5 seconds, queued behind the goal of the same read (the
117 * record's `queue`, played as one stretch). Its record (`celebration`: the first play, its queue, when the run decided
118 * it, its competition, its match's id and that match's tallies it was decided on) is written by the run and the clear
119 * alone: in a run, any answer naming another competition, or none, current or not (a view, or the first-run object),
120 * nulls it, then its match's score changing from the record's own in any later current view, live or finished (a
121 * correction, or a later goal the plugin did not see as one; by the record's id, whatever the `toasts` filter) nulls
122 * it, both plays with it; a full-time play (its own, or queued) is kept only while each later current view lists its
123 * match in `finished` with the same result, its evidence (`outcome`), never its words (listed live again, listed
124 * nowhere, or another result drops that play: the record when it is its own, the queue when it follows a goal); then
125 * the run's last match with a play replaces it under the band's clear generation; the existing clear nulls it. Every
126 * null also stops the redraws. A record another module load wrote is never played (its `at` is not this load's), so a
127 * reload drops a waiting or playing celebration (the toast already said it); it stays in state until a goal or a clear
128 * replaces it. A played or expired record stays until the next goal replaces it: the draw ignores it. The draw only
129 * reads it, and computes the play and its frame from module values (how much of its plays has been on screen), redrawn
130 * by a 500 ms ticker that runs only while there is something to play and no hold: a main-loop turn (`turn.start` to a
131 * `turn.complete` with no `agentId`) or the drawn `isWorking` holds it, and it plays when the hold ends within 60
132 * seconds of the goal. A paused celebration never resumes after 60 seconds; a stretch on screen finishes its plays.
133 * `celebrate: off` plays nothing.
134 */
135
136const band = atom({ plugin: 'claudinho', key: 'band' } as const, null as ClaudinhoBand)
137const pace = atom({ plugin: 'claudinho', key: 'pace' } as const, { ranAt: 0, idle: false } as ClaudinhoPace)
138const baseline = atom({ plugin: 'claudinho', key: 'baseline' } as const, null as ClaudinhoBaseline)
139const lastContext = atom({ plugin: 'claudinho', key: 'context' } as const, null as ClaudinhoContext)
140const celebration = atom({ plugin: 'claudinho', key: 'celebration' } as const, null as ClaudinhoCelebration)
141const paneGen = atom({ plugin: 'claudinho', key: 'paneGen' } as const, 0 as number)
142const pane = atom({ plugin: 'claudinho', key: 'pane' } as const, null as ClaudinhoPane)
143
144const LIVE_MS = 15_000
145const IDLE_MS = 300_000
146const RUN_TIMEOUT_MS = 2_000
147/** The command's one line in the typeahead and `/help`: facts only. */
148const COMMAND_DESCRIPTION = 'The live score or the next fixture of the competition you follow, now'
149/** The command's replies where the band would show nothing, by what the CLI's answer says (never by a cause). */
150const REPLY_FAILED = 'The CLI gave no answer.'
151const REPLY_FIRST_RUN = 'No competition followed yet.'
152const REPLY_NO_VIEW = "Nothing to show: the CLI's answer is not one this plugin reads."
153const REPLY_EMPTY = 'Nothing to show right now: no live match and no next fixture known.'
154const REPLY_IDLE = 'The edition you follow is over.'
155/** The prompt context is attached only from a run younger than two periods. */
156const CONTEXT_MAX_AGE_MS = 2 * LIVE_MS
157/** The band's width before any draw. */
158const DEFAULT_COLUMNS = 80
159/** A celebration frame's length; six frames are its whole length, after which it is spent. */
160const FRAME_MS = 500
161const FRAMES = 6
162const PLAY_MS = FRAMES * FRAME_MS
163/** A celebration not on screen this long after its goal is dropped (the toast already said it). */
164const CELEBRATION_MAX_AGE_MS = 60_000
165/** The legacy banner (CLI 0.11.2), English: `G`, `GO`, `GOA`, `GOAL`, `GOAL!`, `GOAL!` frame by frame. */
166const BANNER = 'GOAL!'
167/** The ball's display width (an emoji takes two columns). */
168const BALL_COLUMNS = 2
169/** Full time's play, for the pinned side's win or draw: 5 s on screen. */
170const FULLTIME_MS = 5_000
171/**
172 * Anthropic's Claude mascot, as three rows of text art (its head, its body, its legs in two steps), drawn in the
173 * theme's `claude` colour in the goal and full-time celebrations only. It stands left of the celebration's three rows.
174 */
175const MASCOT_HEAD = ' ▐▛███▜▌'
176const MASCOT_BODY = '▝▜█████▛▘'
177const MASCOT_LEGS = [' ▘▘ ▝▝', ' ▝▝ ▘▘'] as const
178/** The mascot's widest row, and the column between it and the celebration's text. */
179const MASCOT_COLUMNS = 9
180const MASCOT_GAP = 1
181/** The theme keys the moments are drawn in: the mascot's, and the goal word's (the pane's accent and flair too). */
182const MASCOT_COLOR = 'claude'
183const GOAL_COLOR = 'success'
184/** The band's `lineParts` read, at most. */
185const LINE_PARTS_MAX = 64
186/** A pane row's parts kept, at most. */
187const PANE_ROW_PARTS_MAX = 64
188/** The kinds of goal a `lastGoal` names, and the minutes it is believed for. */
189const GOAL_TYPES: readonly string[] = ['GOAL', 'OWN_GOAL', 'PEN']
190const MINUTE_MAX = 200
191/** The reply's note when `/claudinho match` opened the pane on a surface that draws it. */
192const PANE_OPEN_NOTE = ' · match pane open'
193/** The pane's part styles the plugin draws; another is a plain part. */
194const PANE_STYLES: readonly string[] = ['strong', 'dim', 'accent', 'quote', 'flair']
195/** The match pane: its one id, its title, the word typed after the command that opens it. */
196const PANE_ID = 'match'
197const PANE_TITLE = 'claudinho'
198const PANE_WORD = 'match'
199/** A `match` run's bound: one match read is several provider requests, measured at about half a second. */
200const MATCH_TIMEOUT_MS = 5_000
201/** The pane's bounds: rows of `lines`, each row's characters, and the attribution's and the disclaimer's. */
202const PANE_LINES_MAX = 150
203const PANE_LINE_CHARS = 600
204const PANE_FOOTER_CHARS = 1_000
205/** The re-read while the last answer is in play, failed, or had no match. */
206const PANE_EVERY_MS = 120_000
207/** The longest delay a timer is armed for (a platform timer's limit); a kickoff further out re-reads then. */
208const TIMER_MAX_MS = 2_147_483_647
209/** The pane's fixed rows: a re-read that failed (above the last rows), a first read that failed, an answer it does not read. */
210const PANE_REFRESH_FAILED = 'Could not refresh: showing the last reading.'
211const PANE_FAILED = REPLY_FAILED
212const PANE_NO_VIEW = REPLY_NO_VIEW
213/** The statuses `match --json` states; a final one ends the re-reads. */
214const STATUSES = ['SCHEDULED', 'LIVE', 'HT', 'FT', 'POSTPONED', 'CANCELLED'] as const
215const FINAL_STATUSES: readonly string[] = ['FT', 'POSTPONED', 'CANCELLED']
216
217type ToastsOption = 'pinned' | 'all' | 'off'
218const TOASTS_OPTIONS: readonly ToastsOption[] = ['pinned', 'all', 'off']
219
220/** The four languages the CLI speaks; the option's `auto` (or any other value) resolves to one of them. */
221type Lang = 'en' | 'es' | 'pt' | 'fr'
222const LANGS: readonly Lang[] = ['en', 'es', 'pt', 'fr']
223
224/**
225 * The moment words (CLI 0.12.0: the view's `words`), in this order; `goalFor` and `win` hold `{team}` once, the
226 * others none. `ENGLISH_WORDS` are today's words, used for every moment together when a view's cannot be read whole.
227 */
228type Words = {
229 goal: string
230 ownGoal: string
231 ownGoalDetail: string
232 goalFor: string
233 goals: string
234 scoreUpdated: string
235 penalties: string
236 fullTime: string
237 win: string
238 draw: string
239}
240const WORD_KEYS = ['goal', 'ownGoal', 'ownGoalDetail', 'goalFor', 'goals', 'scoreUpdated', 'penalties', 'fullTime', 'win', 'draw'] as const
241const TEAM_WORDS: readonly string[] = ['goalFor', 'win']
242const TEAM_SLOT = '{team}'
243/** A word's length, at most (UTF-16 units). */
244const WORD_MAX = 40
245/**
246 * What no word may hold: a control (newline, carriage return, escape), a format character (zero-width, joiners,
247 * direction marks), a line or paragraph separator, a private-use or an unassigned code point.
248 */
249const REFUSED_IN_WORD = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Co}\p{Cn}]/u
250const ENGLISH_WORDS: Words = {
251 goal: 'GOAL!',
252 ownGoal: 'Own goal',
253 ownGoalDetail: 'own goal',
254 goalFor: 'Goal for {team}',
255 goals: 'Goals',
256 scoreUpdated: 'Score updated',
257 penalties: 'Penalties',
258 fullTime: 'Full time',
259 win: '{team} win',
260 draw: 'Draw',
261}
262
263/**
264 * The band's width as last drawn (`bodyColumns`), which the next run asks the CLI to fit the line to. Kept in the
265 * module, not `$.state`: the draw that learns it may not write state. A reload starts again from the default.
266 */
267let columns = DEFAULT_COLUMNS
268let clears = 0
269/** At most one run in flight: the guard is taken before the first await. */
270let busy = false
271/** A forced run asked while a run was in flight: made as soon as that run ends (cleared when it starts). */
272let forcedPending = false
273/**
274 * The pace (the forced first run, then every 15 seconds) is started once per module load, by whichever comes first of
275 * a start or an attach of a band surface. A reload makes a fresh module and drops the previous one's timers.
276 */
277let paced = false
278/**
279 * The `env` every run is handed, kept for the rest of the module load once it is whole (nvm's lookup answered, or not
280 * needed); `env` undefined: none, on Windows.
281 */
282let runEnvKept: { env: { PATH: string } | undefined } | null = null
283/** nvm's lookup, started once per module load by the first run that needs it. */
284let nvmOnce: Promise<string[]> | null = null
285/** nvm's lookup's answer once it has settled. */
286let nvmAnswer: string[] | null = null
287/** The `language` option as set (`auto` for anything but the four codes), at load. */
288let languageOption: Lang | 'auto' = 'auto'
289/** The language a run is handed, kept for the rest of the module load once both reads answered (or not needed). */
290let langKept: Lang | null = null
291/**
292 * Whether the CLI localizes (0.12.0): set for the rest of the module load by any view that states a `lang` among the
293 * four codes, current or not, read by the band's run or by `/claudinho`'s own run (`markLocalizes`); a view stating no
294 * such value marks nothing. Only once it is set do the match runs carry `--lang`, so a CLI that does not localize
295 * (0.11.2) keeps its pane English like its toasts. Every ambient run (the band's and `/claudinho`'s) carries `--lang`
296 * always.
297 */
298let cliLocalizes = false
299/** Whether the goal celebration plays (`celebrate` is anything but `off`), set at load. */
300let celebrateOn = true
301/** Whether a prompt carries the live score (`context` is anything but `off`), set at load. */
302let contextOn = true
303/** A main-loop turn is running: set by `turn.start`, cleared by a `turn.complete` with no `agentId`. */
304let holdTurn = false
305/**
306 * The celebration's playback, kept in the module (a draw may not write state): the record's `at` these values belong
307 * to, how much of its 3 s was on screen before the current stretch, when the current stretch began (null while
308 * paused), and the last draw that played it. A new record resets them; a pause folds the stretch into `playedMs`.
309 */
310let playingAt: number | null = null
311let playedMs = 0
312let playFrom: number | null = null
313let lastPlayedAt = 0
314/** The redraw ticker, running only while a celebration is playable and not held. */
315let ticker: Timer | null = null
316/**
317 * The match pane's binding in this module load: the generation it was opened under (the `paneGen` the open wrote),
318 * its competition and match id, whether its last answer was final, and whether its reads name the competition
319 * (`pinned`: set for good by the first answer of another competition, or of none). Replaced by every open, nulled by
320 * the close: a read whose binding is no longer this object writes nothing.
321 */
322type Binding = { gen: number; slug: string; id: string; final: boolean; pinned: boolean }
323let bound: Binding | null = null
324/** The band's previous observation of the bound id, under its generation: whether it was listed, and its tallies. */
325type Observation = { gen: number; listed: boolean; score?: Tally; shootout?: Tally }
326let observed: Observation | null = null
327/**
328 * The pane's `match` reads in flight or waiting their turn (the open counts from before it waits), and a re-read asked
329 * during one (kept once). `readTail` settles when the last read queued has settled: the open waits for it, so no two
330 * `match` runs are ever in flight at once.
331 */
332let paneReads = 0
333let rereadPending = false
334let readTail: Promise<void> = Promise.resolve()
335/** The 2-minute re-read and the kickoff re-read. */
336let everyTimer: Timer | null = null
337let kickoffTimer: Timer | null = null
338
339/** The two surfaces that raise `AbovePrompt`. */
340const drawsBand = (surface: unknown): boolean => surface === 'terminal' || surface === 'desktop'
341
342/** Whether a surface that draws the band is attached to the session now (a read that rejects is the caller's to read). */
343async function drawable($: EngineInterface): Promise<boolean> {
344 const surfaces = await $.session.surfaces()
345 return surfaces.some(drawsBand)
346}
347
348/**
349 * The band cleared and the pace back to its initial value (no clock read), so the next run the roster allows is never
350 * held by an idle gap.
351 */
352async function clear($: EngineInterface): Promise<void> {
353 clears += 1
354 stopTicker()
355 await update($, band, () => null)
356 await update($, pace, () => ({ ranAt: 0, idle: false }))
357 await update($, celebration, () => null)
358}
359
360/** How much of the record's 3 s has been on screen at `now` (the stretch in progress included). */
361const playedAt = (now: number): number => playedMs + (playFrom === null ? 0 : Math.max(0, now - playFrom))
362
363/** A play's length on screen: full time's 5 s, a goal's 3 s. */
364const playLength = (p: ClaudinhoPlay): number => (p.kind === 'fulltime' ? FULLTIME_MS : PLAY_MS)
365
366/** A record's plays in order: its own, then its queue (at most one more). */
367const playsOf = (rec: NonNullable<ClaudinhoCelebration>): ClaudinhoPlay[] => [
368 rec,
369 ...(Array.isArray(rec.queue) ? rec.queue.slice(0, 1) : []),
370]
371
372/** A record's whole length on screen: its plays one after the other. */
373const recordLength = (rec: NonNullable<ClaudinhoCelebration>): number =>
374 playsOf(rec).reduce((sum, p) => sum + playLength(p), 0)
375
376/**
377 * Whether a record has anything left to play at `now`: set, its plays not all on screen, and either within 60 s of its
378 * goal or in a stretch on screen (which finishes its plays). A paused one never resumes after 60 s.
379 */
380const playable = (rec: ClaudinhoCelebration, now: number): boolean =>
381 rec !== null &&
382 rec.at === playingAt &&
383 playedAt(now) < recordLength(rec) &&
384 (now - rec.at <= CELEBRATION_MAX_AGE_MS || playFrom !== null)
385
386/** The playback paused at `at`: the stretch on screen folded into `playedMs`. */
387function pausePlayback(at: number): void {
388 if (playFrom === null) return
389 playedMs += Math.max(0, at - playFrom)
390 playFrom = null
391}
392
393function stopTicker(): void {
394 ticker?.cancel()
395 ticker = null
396}
397
398/**
399 * The redraw ticker: every 500 ms a redraw, then stopped once the record has nothing left to play (spent, expired or
400 * gone). No state write per frame.
401 */
402function startTicker($: EngineInterface): void {
403 if (ticker) return
404 ticker = $.clock.every(FRAME_MS, () => {
405 $.ui.invalidate('ui.render')
406 void frameCheck($)
407 })
408}
409
410/** A frame's check: the ticker stopped once the record has nothing left to play. Never rejects. */
411async function frameCheck($: EngineInterface): Promise<void> {
412 try {
413 const rec = await read($, celebration)
414 const now = await $.clock.now()
415 if (!playable(rec, now)) stopTicker()
416 } catch {
417 // The engine's calls failed: the ticker runs on to its next period.
418 }
419}
420
421/** After a hold ends: the ticker again when the record is still playable. Never rejects. */
422async function resumeTicker($: EngineInterface): Promise<void> {
423 if (holdTurn) return
424 try {
425 const rec = await read($, celebration)
426 if (holdTurn) return
427 const now = await $.clock.now()
428 if (playable(rec, now)) startTicker($)
429 } catch {
430 // The engine's calls failed: no redraws are asked until the next goal or the next turn's end.
431 }
432}
433
434/** The ball row of a frame: the ball stepping right across `cols` columns, never past them. */
435function ballRow(frame: number, cols: number): string {
436 const room = Math.max(0, cols - BALL_COLUMNS)
437 return `${' '.repeat(Math.floor((frame * room) / (FRAMES - 1)))}⚽`
438}
439
440/** The celebration's rows for a frame in `rows` rows (1 to 3): the frame table. */
441function celebrationRows(frame: number, rows: number, text: string, cols: number): string[] {
442 const last = frame === FRAMES - 1
443 const banner = BANNER.slice(0, Math.min(frame + 1, BANNER.length))
444 if (rows >= 3) return last ? [ballRow(frame, cols), banner, text] : [ballRow(frame, cols), banner]
445 if (rows === 2) return [ballRow(frame, cols), last ? text : banner]
446 return [last ? text : banner]
447}
448
449/** Whether a run may go on: a band surface is attached; a roster read that rejects is no. */
450async function mayRun($: EngineInterface): Promise<boolean> {
451 try {
452 return await drawable($)
453 } catch {
454 return false
455 }
456}
457
458/** An environment variable's value, or undefined when it is unset or its read rejected (an empty PATH or HOME adds nothing where it is used). */
459async function orUnset(get: () => Promise<string | undefined>): Promise<string | undefined> {
460 try {
461 const value = await get()
462 return typeof value === 'string' ? value : undefined
463 } catch {
464 return undefined
465 }
466}
467
468const NVM_VERSION = /^v(\d+)\.(\d+)\.(\d+)$/
469/** How long a run waits for nvm's lookup (the listing, the sort and the probes) before it goes on without it. */
470const NVM_WAIT_MS = 1_000
471/** The listing's entries read, before any per-entry work. */
472const NVM_ENTRIES_MAX = 256
473/** The version folders kept, the newest by number. */
474const NVM_VERSIONS_MAX = 8
475
476/**
477 * nvm's version folders' `bin`, of the first 256 entries the listing gives, at most the 8 newest by number: those whose
478 * `bin/claudinho` exists first, then the rest, each newest first; none when the folder cannot be listed (an error or a
479 * refusal is an answer). Never rejects.
480 */
481async function nvmLookup($: EngineInterface, home: string): Promise<string[]> {
482 const root = `${home}/.nvm/versions/node`
483 let entries: FsEntry[]
484 try {
485 entries = await $.fs.list(root)
486 } catch {
487 return []
488 }
489 const versions: Array<{ name: string; parts: [number, number, number] }> = []
490 for (const entry of entries.slice(0, NVM_ENTRIES_MAX)) {
491 const m = entry.kind === 'dir' ? entry.name.match(NVM_VERSION) : null
492 if (m) versions.push({ name: entry.name, parts: [Number(m[1]), Number(m[2]), Number(m[3])] })
493 }
494 versions.sort((a, b) => b.parts[0] - a.parts[0] || b.parts[1] - a.parts[1] || b.parts[2] - a.parts[2])
495 const bins = versions.slice(0, NVM_VERSIONS_MAX).map((v) => `${root}/${v.name}/bin`)
496 // Of nvm's folders, those that hold the CLI come first, so the node beside the CLI leads nvm's part of the PATH (a
497 // node in an earlier folder of the host's PATH still comes before it). A probe that rejects is "not there"; the
498 // probes run together.
499 const holds = await Promise.all(bins.map((bin) => holdsCli($, bin)))
500 return [...bins.filter((_, i) => holds[i]), ...bins.filter((_, i) => !holds[i])]
501}
502
503/** Whether `<bin>/claudinho` exists; a probe that rejects is "not there". Never rejects. */
504async function holdsCli($: EngineInterface, bin: string): Promise<boolean> {
505 try {
506 const found = await $.fs.exists(`${bin}/claudinho`)
507 return found === true
508 } catch {
509 return false
510 }
511}
512
513/** nvm's lookup, its answer kept for the module load once it has settled. Never rejects. */
514async function nvmLookupKept($: EngineInterface, home: string): Promise<string[]> {
515 const bins = await nvmLookup($, home)
516 nvmAnswer = bins
517 return bins
518}
519
520/** Null once the wait for nvm's lookup is over, or at once when the wait cannot be kept. Never rejects. */
521async function nvmWait($: EngineInterface, signal: AbortSignal): Promise<null> {
522 try {
523 await $.clock.sleep(NVM_WAIT_MS, { signal })
524 } catch {
525 // The wait was cut or refused: no wait.
526 }
527 return null
528}
529
530/**
531 * nvm's part of the PATH: the lookup's answer once it has settled, else null after this run has waited a second for it
532 * (or at once when the wait cannot be kept). The lookup is started once per module load and never again.
533 */
534async function nvmBins($: EngineInterface, home: string): Promise<string[] | null> {
535 if (nvmAnswer) return nvmAnswer
536 nvmOnce ??= nvmLookupKept($, home)
537 const stop = new AbortController()
538 const waited = nvmWait($, stop.signal)
539 const bins = await Promise.race([nvmOnce, waited])
540 if (bins) stop.abort()
541 return bins
542}
543
544/**
545 * The `env` a run is handed: none on Windows; else `PATH` = the host's PATH, then (under a HOME) nvm's version folders
546 * and the user-level global-bin folders, then the system ones; each folder once, its first place kept, so the host's
547 * order wins. `whole` is false while nvm's lookup has not answered (the PATH then has none of its folders). Never
548 * rejects.
549 */
550async function computeRunEnv($: EngineInterface): Promise<{ env: { PATH: string } | undefined; whole: boolean }> {
551 if ((await orUnset(() => $.env.get('OS'))) === 'Windows_NT') return { env: undefined, whole: true }
552 let whole = true
553 const folders: string[] = []
554 const host = await orUnset(() => $.env.get('PATH'))
555 if (host) folders.push(...host.split(':').filter((s) => s !== ''))
556 // A folder under HOME only when HOME is an absolute path that holds no PATH separator.
557 const home = await orUnset(() => $.env.get('HOME'))
558 if (home?.startsWith('/') && !home.includes(':')) {
559 const nvm = await nvmBins($, home)
560 if (nvm) folders.push(...nvm)
561 else whole = false
562 folders.push(
563 `${home}/.volta/bin`,
564 `${home}/.local/share/pnpm`,
565 `${home}/Library/pnpm`,
566 `${home}/.bun/bin`,
567 `${home}/.npm-global/bin`,
568 `${home}/.local/bin`,
569 )
570 }
571 folders.push('/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin')
572 return { env: { PATH: [...new Set(folders)].join(':') }, whole }
573}
574
575/** The `env` for this run: the kept one, else computed now and kept when it is whole. */
576async function runEnv($: EngineInterface): Promise<{ PATH: string } | undefined> {
577 if (runEnvKept) return runEnvKept.env
578 const { env, whole } = await computeRunEnv($)
579 if (whole) runEnvKept = { env }
580 return env
581}
582
583const isLang = (v: unknown): v is Lang => typeof v === 'string' && LANGS.includes(v as Lang)
584
585/**
586 * The language a CLI run is handed (`--lang <code>`; see `cliLocalizes` for which runs): the option when it is one
587 * of the four codes; under `auto`, the CLI's own rule (`pickLang`) on the host's environment: `CLAUDINHO_LANG`, then `LANG`'s language part
588 * (`es_MX.UTF-8` gives `es`), each only when it is one of the four (case-sensitive; an empty value skipped), else
589 * `en`. The host's environment is read here so every run names its language (`--lang`). Kept for the module load once both
590 * reads answered; a read that rejected is unset for this run and asked again on the next. Never rejects.
591 */
592async function runLang($: EngineInterface): Promise<Lang> {
593 if (languageOption !== 'auto') return languageOption
594 if (langKept) return langKept
595 let whole = true
596 // Each name spelled at its call (the engine lists the variables a module reads).
597 const got = async (read: () => Promise<string | undefined>): Promise<string | undefined> => {
598 try {
599 const value = await read()
600 return typeof value === 'string' ? value : undefined
601 } catch {
602 whole = false
603 return undefined
604 }
605 }
606 const own = await got(() => $.env.get('CLAUDINHO_LANG'))
607 const locale = await got(() => $.env.get('LANG'))
608 const lang = [own, locale?.split('.')[0]?.split('_')[0]].find(isLang) ?? 'en'
609 if (whole) langKept = lang
610 return lang
611}
612
613/** The argument a CLI run ends with: the language, one of the four codes. */
614const langArgs = (lang: Lang): string[] => ['--lang', lang]
615
616/** The argument the match runs end with: the language once a view said the CLI localizes, else none. */
617async function matchLangArgs($: EngineInterface): Promise<string[]> {
618 if (!cliLocalizes) return []
619 const lang = await runLang($)
620 return langArgs(lang)
621}
622
623/** A reading that is a view stating a `lang` among the four codes marks the CLI as localizing; anything else marks nothing. */
624function markLocalizes(reading: Reading): void {
625 if (reading.answered && reading.isView && isLang(reading.view.lang)) cliLocalizes = true
626}
627
628/**
629 * What `claudinho ambient --json` prints, as far as this module reads it: a selected competition's VIEW (an object
630 * with a `live` object holding an `items` array that says what its line is, `idle` and `empty` as two booleans), or
631 * a shape that is no view: the first-run object (no competition chosen: `noCompetition`, the one line), the fallback
632 * object (a refused value or a failure: the line and `empty`; an older CLI's `{ line }` has the same shape), and a
633 * view from a CLI older than `idle` and `empty` (a live list and neither).
634 */
635type View = {
636 line: string
637 noCompetition?: unknown
638 idle?: unknown
639 empty?: unknown
640 context?: unknown
641 live?: { items?: unknown }
642 next?: unknown
643 current?: unknown
644 competition?: { slug?: unknown } | null
645 staleAfter?: unknown
646 disclaimer?: unknown
647 attribution?: unknown
648 /** CLI 0.12.0: the line's parts, the score tokens `strong`. */
649 lineParts?: unknown
650 /** CLI 0.12.0: the records that finished in the last ten minutes. */
651 finished?: unknown
652 /** CLI 0.12.0: the moment words in the view's language (read whole, else the English ones). */
653 words?: unknown
654 /** CLI 0.12.0: the CLI's resolved language; a view stating one of the four codes says the CLI localizes. */
655 lang?: unknown
656}
657
658type Item = {
659 id: string
660 line?: unknown
661 score?: unknown
662 shootout?: unknown
663 pinned?: unknown
664 minute?: unknown
665 home?: unknown
666 away?: unknown
667 winnerCode?: unknown
668 /** CLI 0.12.0: the names the hook's line uses, the saved pin's side, the last goal it proved. */
669 names?: unknown
670 pinnedSide?: unknown
671 lastGoal?: unknown
672}
673
674const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
675
676/** The first line of the CLI's stdout as the view (or the first-run object), or null for anything else (a run that failed). */
677function parseView(stdout: string): View | null {
678 const first = (stdout.split('\n')[0] ?? '').trim()
679 if (!first) return null
680 let parsed: unknown
681 try {
682 parsed = JSON.parse(first)
683 } catch {
684 return null
685 }
686 if (!isObject(parsed) || typeof parsed.line !== 'string') return null
687 return parsed as View
688}
689
690type RunResult = ProcessRunResult
691
692/**
693 * What one run of the CLI said, read once for the band and the command alike: no answer (a run that rejected, a
694 * non-zero exit, a cut stdout, a first line that is not the object), or the object and what its line IS. That comes
695 * from the fields, never the text (which `--columns` may have cut): the first-run object (nothing chosen) is hidden and
696 * idle; an object that is no view the plugin reads is hidden and not idle; a view that says `empty`, or whose line is
697 * blank, is hidden; one that says `idle` is idle. A view the plugin reads has its `live` list AND says what its line
698 * is, `idle` and `empty` as two booleans: the fallback object, an older CLI's `{ line }`, and a view from a CLI older
699 * than those two fields (a live list and neither) are no view.
700 */
701type Reading =
702 | { answered: false }
703 | { answered: true; view: View; firstRun: boolean; isView: boolean; idle: boolean; hidden: boolean }
704
705/** The one reading of a run's result (undefined: the run rejected). */
706function readAnswer(r: RunResult | undefined): Reading {
707 // A cut stdout is no answer: its first line may be part of an object.
708 const view = r && r.exitCode === 0 && r.isStdoutTruncated !== true ? parseView(r.stdout) : null
709 if (!view) return { answered: false }
710 const firstRun = view.noCompetition === true
711 const isView =
712 !firstRun &&
713 isObject(view.live) &&
714 Array.isArray(view.live.items) &&
715 typeof view.idle === 'boolean' &&
716 typeof view.empty === 'boolean'
717 const idle = firstRun || (isView && view.idle === true)
718 const hidden = !isView || view.empty === true || view.line.trim() === ''
719 return { answered: true, view, firstRun, isView, idle, hidden }
720}
721
722/** The reply's body for a view: nothing known, the edition over, else its line. */
723const viewReply = (view: View, r: { hidden: boolean; idle: boolean }): string =>
724 r.hidden ? REPLY_EMPTY : r.idle ? REPLY_IDLE : view.line
725
726/** A sentence the CLI states for the plugin to relay, when it is usable: a string with something besides spaces. */
727const relayed = (v: unknown): string | null => (typeof v === 'string' && v.trim() !== '' ? v : null)
728
729/**
730 * The command's reply to a reading: the first that holds of a failed run, the first run, no view (each its sentence
731 * alone), nothing known, the edition over; else the line. A reply made from a view ends with the view's attribution,
732 * then its disclaimer (the CLI's own footer order), each after a blank line and each only when usable.
733 */
734function replyTo(reading: Reading): string {
735 if (!reading.answered) return REPLY_FAILED
736 if (reading.firstRun) return REPLY_FIRST_RUN
737 if (!reading.isView) return REPLY_NO_VIEW
738 const text = viewReply(reading.view, reading)
739 // The CLI's own sentences, relayed (core's copy and core's one constant), never spelled here.
740 const footer = [relayed(reading.view.attribution), relayed(reading.view.disclaimer)].filter((s) => s !== null)
741 return [text, ...footer].join('\n\n')
742}
743
744/** A tally `{ home, away }` of two numbers, or undefined. */
745function tally(v: unknown): { home: number; away: number } | undefined {
746 if (!isObject(v) || typeof v.home !== 'number' || typeof v.away !== 'number') return undefined
747 return { home: v.home, away: v.away }
748}
749
750/** The view's live matches that carry an id. */
751function itemsOf(view: View): Item[] {
752 const items = isObject(view.live) && Array.isArray(view.live.items) ? view.live.items : []
753 return items.filter((m): m is Item => isObject(m) && typeof m.id === 'string')
754}
755
756/** The view's competition, by its slug ('' when it states none). */
757const slugOf = (view: View): string =>
758 isObject(view.competition) && typeof view.competition.slug === 'string' ? view.competition.slug : ''
759
760type Tally = { home: number; away: number }
761
762/**
763 * How a match's tallies moved against its baseline entry: whether a side of a compared tally rose or fell (a tally
764 * compared only when both carry one).
765 */
766function movement(m: Item, was: ClaudinhoTally): { rose: boolean; fell: boolean } {
767 const pairs: Array<[Tally, Tally]> = []
768 const score = tally(m.score)
769 const shootout = tally(m.shootout)
770 if (score && was.score) pairs.push([score, was.score])
771 if (shootout && was.shootout) pairs.push([shootout, was.shootout])
772 return {
773 rose: pairs.some(([a, b]) => a.home > b.home || a.away > b.away),
774 fell: pairs.some(([a, b]) => a.home < b.home || a.away < b.away),
775 }
776}
777
778type Side = 'home' | 'away'
779type Names = { home: string; away: string }
780
781/**
782 * A record's `names` (CLI 0.12.0: the names the hook's line uses), or null: a record without them is an older CLI's,
783 * whose toast is its own `line` and for which neither `names` nor `lastGoal` is read.
784 */
785function namesOf(m: Item): Names | null {
786 const n = m.names
787 if (!isObject(n) || typeof n.home !== 'string' || typeof n.away !== 'string') return null
788 if (n.home.trim() === '' || n.away.trim() === '') return null
789 return { home: n.home, away: n.away }
790}
791
792/** The side the CLI says the saved pin is on, or null (no pin, or not a side). */
793const pinnedSideOf = (m: Item): Side | null => (m.pinnedSide === 'home' || m.pinnedSide === 'away' ? m.pinnedSide : null)
794
795const isMinute = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= MINUTE_MAX
796
797/** A record's `lastGoal` as the CLI proved it, or null for anything else (a player that is no name is left out). */
798function lastGoalOf(v: unknown): ClaudinhoGoal | null {
799 if (!isObject(v) || typeof v.type !== 'string' || !GOAL_TYPES.includes(v.type)) return null
800 if ((v.side !== 'home' && v.side !== 'away') || !isMinute(v.minute)) return null
801 if (v.added !== undefined && !(isMinute(v.added) && v.added > 0)) return null
802 const player = typeof v.player === 'string' && v.player.trim() !== '' ? v.player : undefined
803 return {
804 type: v.type as ClaudinhoGoal['type'],
805 minute: v.minute,
806 ...(v.added !== undefined ? { added: v.added as number } : {}),
807 side: v.side,
808 ...(player !== undefined ? { player } : {}),
809 }
810}
811
812/** Whether two `lastGoal` identities are the same goal: every field equal. */
813const sameGoal = (a: ClaudinhoGoal, b: ClaudinhoGoal): boolean =>
814 a.type === b.type && a.minute === b.minute && a.added === b.added && a.side === b.side && a.player === b.player
815
816/** A goal's minute as a toast writes it: `22'`, `90+3'`. */
817const goalMinute = (g: ClaudinhoGoal): string => (g.added ? `${g.minute}+${g.added}'` : `${g.minute}'`)
818
819/** The record's clock minute, `60'`, or '' when it states none. */
820const clockMinute = (m: Item): string => (isMinute(m.minute) ? `${m.minute}'` : '')
821
822/** Words joined by one space, the empty ones left out. */
823const words = (...ws: string[]): string => ws.filter((w) => w !== '').join(' ')
824
825/** The scoreline a moment's toast writes: the names, the tally (a shootout tally after each side), or `vs`. */
826function scoreline(names: Names, score: Tally | undefined, shootout: Tally | undefined): string {
827 if (!score) return `${names.home} vs ${names.away}`
828 const homeTally = shootout ? `${score.home}(${shootout.home})` : `${score.home}`
829 const awayTally = shootout ? `${score.away}(${shootout.away})` : `${score.away}`
830 return `${names.home} ${homeTally}–${awayTally} ${names.away}`
831}
832
833/** One moment of one record: its toast text, and the celebration's play when it has one. */
834type Moment = { text: string; play: ClaudinhoPlay | null }
835
836/** How many times `{team}` is in a word. */
837const teamSlots = (w: string): number => w.split(TEAM_SLOT).length - 1
838
839/**
840 * The view's moment words (CLI 0.12.0), read whole: an object holding the ten, each a string of at most 40 characters
841 * with something besides spaces and none of the refused classes (`REFUSED_IN_WORD`), `goalFor` and `win` holding
842 * `{team}` exactly once and the others none. Anything else (no `words`, an older CLI's view, one field missing, of
843 * another type, empty or spaces alone, too long, holding a control, a format character, a separator, a private-use or
844 * an unassigned code point, or a `{team}` out of place): today's English words, for every moment together.
845 */
846function wordsOf(view: View): Words {
847 const raw = view.words
848 if (!isObject(raw)) return ENGLISH_WORDS
849 const out: Partial<Words> = {}
850 for (const key of WORD_KEYS) {
851 const w = raw[key]
852 if (typeof w !== 'string' || w.trim() === '' || w.length > WORD_MAX || REFUSED_IN_WORD.test(w)) return ENGLISH_WORDS
853 if (teamSlots(w) !== (TEAM_WORDS.includes(key) ? 1 : 0)) return ENGLISH_WORDS
854 out[key] = w
855 }
856 return out as Words
857}
858
859/**
860 * A word's `{team}` replaced by the name, literally: no replacement pattern is read in the name (`$&` stays `$&`). The
861 * words read (`wordsOf`) hold it exactly once, so it is replaced once.
862 */
863const fillTeam = (template: string, team: string): string => template.split(TEAM_SLOT).join(team)
864
865/**
866 * The moment of a record that carries `names`, against its baseline entry, in the view's words (`w`; English: the
867 * words below), the first that holds: a compared tally that fell (`Score updated`), a shootout tally that rose
868 * (`Penalties`; one that appears where the baseline had none counts from 0), one regulation side up by exactly 1 (the
869 * goal), any other rise (`Goals`); none: null. A regulation tally is compared only when both carry one. The goal names
870 * the side that rose; its scorer, the goal's minute and the own-goal detail only when `goal` (the record's `lastGoal`)
871 * is a new identity against the baseline's and on that side; otherwise the record's clock minute. Against the pinned
872 * side it reads `Goal for <team>` and plays nothing; else `⚽ GOAL!` (`⚽ Own goal ·` for a proven own goal) and its
873 * play, which keeps the goal word and the detail it was built with.
874 */
875function scoreMoment(m: Item, names: Names, was: ClaudinhoTally, goal: ClaudinhoGoal | null, w: Words): Moment | null {
876 const score = tally(m.score)
877 const shootout = tally(m.shootout)
878 const line = scoreline(names, score, shootout)
879 const regulation: [Tally, Tally] | null = score && was.score ? [score, was.score] : null
880 const shootWas = was.shootout ?? (shootout ? { home: 0, away: 0 } : undefined)
881 const shoot: [Tally, Tally] | null = shootout && shootWas ? [shootout, shootWas] : null
882 const pairs = [regulation, shoot].filter((p): p is [Tally, Tally] => p !== null)
883 if (pairs.some(([a, b]) => a.home < b.home || a.away < b.away)) return { text: `${w.scoreUpdated} · ${line}`, play: null }
884 if (shoot && (shoot[0].home > shoot[1].home || shoot[0].away > shoot[1].away)) {
885 return { text: `${w.penalties} · ${line}`, play: null }
886 }
887 if (!regulation) return null
888 const dh = regulation[0].home - regulation[1].home
889 const da = regulation[0].away - regulation[1].away
890 if (dh + da === 0) return null
891 if (dh + da > 1) return { text: `${w.goals} · ${line}`, play: null }
892 const side: Side = dh === 1 ? 'home' : 'away'
893 const team = names[side]
894 const proven = goal !== null && goal.side === side && !(was.lastGoal && sameGoal(goal, was.lastGoal))
895 const own = proven && goal.type === 'OWN_GOAL'
896 const player = proven && !own ? (goal.player ?? '') : ''
897 const minute = proven ? goalMinute(goal) : clockMinute(m)
898 const pinned = pinnedSideOf(m)
899 if (pinned !== null && pinned !== side) {
900 const tail = own ? ` · ${words(w.ownGoalDetail, minute)}` : player ? ` · ${words(player, minute)}` : minute ? ` ${minute}` : ''
901 return { text: `${fillTeam(w.goalFor, team)}${tail} · ${line}`, play: null }
902 }
903 const head = own
904 ? `⚽ ${w.ownGoal} · ${words(team, minute)}`
905 : player
906 ? `⚽ ${w.goal} ${team} · ${words(player, minute)}`
907 : `⚽ ${w.goal} ${words(team, minute)}`
908 const detail = own ? words(w.ownGoalDetail, minute) : player ? words(player, minute) : minute
909 return { text: `${head} · ${line}`, play: { kind: 'goal', word: w.goal, team, minute, detail } }
910}
911
912/** A side's code, when the record states one. */
913const codeOf = (t: unknown): string | null => (isObject(t) && typeof t.code === 'string' && t.code !== '' ? t.code : null)
914
915/**
916 * The result of a finished record: a `winnerCode` first (the side whose code it is; a code that names neither side, or
917 * both, establishes nothing), else the shootout (level: nothing), else the score (level: a draw); no score: nothing.
918 * `winner` null is a draw.
919 */
920function resultOf(f: Item): { winner: Side | null } | null {
921 if (typeof f.winnerCode === 'string' && f.winnerCode !== '') {
922 const home = codeOf(f.home) === f.winnerCode
923 const away = codeOf(f.away) === f.winnerCode
924 return home !== away ? { winner: home ? 'home' : 'away' } : null
925 }
926 const shootout = tally(f.shootout)
927 if (shootout) return shootout.home === shootout.away ? null : { winner: shootout.home > shootout.away ? 'home' : 'away' }
928 const score = tally(f.score)
929 if (!score) return null
930 return { winner: score.home === score.away ? null : score.home > score.away ? 'home' : 'away' }
931}
932
933
934/**
935 * Whether a finished record is the pin's: the CLI names its side (`pinnedSide`, the shape it prints on a finished
936 * record, which carries no `pinned` key), or marks it `pinned`.
937 */
938const finishedPinned = (f: Item): boolean => f.pinned === true || pinnedSideOf(f) !== null
939
940/** The full-time evidence's team identity: a side's `id` when it carries one, else its code and name. */
941type TeamIdentity = ClaudinhoOutcome['team']
942
943/**
944 * The identity of a record's side as the record states it: its `id` when it carries one, else its code and name (each
945 * `null` when the record states none; a side with no team object states neither).
946 */
947function identityOf(t: unknown): NonNullable<TeamIdentity> {
948 if (isObject(t) && typeof t.id === 'string' && t.id !== '') return { id: t.id }
949 return { code: codeOf(t), name: isObject(t) && typeof t.name === 'string' && t.name !== '' ? t.name : null }
950}
951
952/** Whether an identity states nothing: no id, and neither a code nor a name (a side with no team object). */
953const missingIdentity = (t: Record<string, unknown>): boolean =>
954 t.id === undefined && (t.code === null || t.code === undefined) && (t.name === null || t.name === undefined)
955
956/**
957 * Whether two identities are one team: both a draw's none, the same id when both carry one, or (neither with an id)
958 * the same code AND the same name. A missing identity (`missingIdentity`) on either side is no evidence: never the
959 * same team, so a held full-time play whose winning side states none is dropped (fail closed), even against another
960 * missing one.
961 */
962function sameIdentity(a: unknown, b: TeamIdentity): boolean {
963 if (a === null || b === null) return a === b
964 if (!isObject(a) || missingIdentity(a) || missingIdentity(b)) return false
965 if ('id' in b) return a.id === b.id
966 return a.id === undefined && a.code === b.code && a.name === b.name
967}
968
969/**
970 * The full-time moment of a finished record that carries `names`, in the view's words (`w`): `Full time ·` the
971 * scoreline, then the result (`<team> win`, `Draw`) when it can be established (`resultOf`); the play for the pinned
972 * side's win or draw, which keeps the result as evidence (`outcome`: the winning side, and the winning team's identity
973 * as the record states it, none for a draw) apart from the words it draws (`heading`, `result`).
974 */
975function fullTimeMoment(f: Item, names: Names, w: Words): Moment {
976 const line = scoreline(names, tally(f.score), tally(f.shootout))
977 const outcome = resultOf(f)
978 if (outcome === null) return { text: `${w.fullTime} · ${line}`, play: null }
979 const said = outcome.winner === null ? w.draw : fillTeam(w.win, names[outcome.winner])
980 const pinned = pinnedSideOf(f)
981 const plays = pinned !== null && (outcome.winner === null || outcome.winner === pinned)
982 return {
983 text: `${w.fullTime} · ${line} · ${said}`,
984 play: plays
985 ? {
986 kind: 'fulltime',
987 outcome: { winner: outcome.winner, team: outcome.winner === null ? null : identityOf(f[outcome.winner]) },
988 heading: w.fullTime,
989 result: said,
990 }
991 : null,
992 }
993}
994
995/**
996 * One match's moments in a run: its id, its toasts in order, the plays its celebration would hold in order, and its
997 * tallies in this view (each when present), the evidence a celebration keeps.
998 */
999type MatchMoments = { id: string; texts: string[]; plays: ClaudinhoPlay[]; score?: Tally; shootout?: Tally }
1000
1001/** The view's finished records (CLI 0.12.0) that carry an id; none from an older CLI. */
1002function finishedOf(view: View): Item[] {
1003 const items = Array.isArray(view.finished) ? view.finished : []
1004 return items.filter((m): m is Item => isObject(m) && typeof m.id === 'string')
1005}
1006
1007const evidence = (m: Item): { score?: Tally; shootout?: Tally } => {
1008 const score = tally(m.score)
1009 const shootout = tally(m.shootout)
1010 return { ...(score ? { score } : {}), ...(shootout ? { shootout } : {}) }
1011}
1012
1013/**
1014 * The moments of a CURRENT view against the last current view's baseline, under the option (off: none; pinned: a record
1015 * with `pinned: true`; all: every match), one entry per match whose id the baseline holds, live records first, in the
1016 * view's order; a new id is the first observation (silent); a competition change rebases with nothing to compare.
1017 * - A live record without `names` (CLI 0.11.2): today's toast, `⚽` and its own `line`, when a compared tally changed
1018 * (both carrying it); the banner play when one rose and none fell.
1019 * - A live record with `names`: its one moment (`scoreMoment`).
1020 * - A finished record with `names` whose id the baseline holds as live (it left `live` for `finished` between the two
1021 * views): the goal moment when its tally rose in the same read (no `lastGoal` read: the clock minute), then full
1022 * time. A finished record without `names`, or one also listed live, says nothing.
1023 */
1024function momentsFor(view: View, prev: ClaudinhoBaseline, option: ToastsOption): MatchMoments[] {
1025 if (option === 'off' || !prev || prev.slug !== slugOf(view)) return []
1026 const w = wordsOf(view)
1027 const before = new Map(prev.items.map((t) => [t.id, t]))
1028 const out: MatchMoments[] = []
1029 const live = itemsOf(view)
1030 for (const m of live) {
1031 if (option === 'pinned' && m.pinned !== true) continue
1032 const was = before.get(m.id)
1033 if (!was) continue
1034 const names = namesOf(m)
1035 if (names === null) {
1036 if (typeof m.line !== 'string' || m.line === '') continue
1037 const { rose, fell } = movement(m, was)
1038 if (!rose && !fell) continue
1039 const text = `⚽ ${m.line}`
1040 out.push({ id: m.id, texts: [text], plays: rose && !fell ? [{ kind: 'banner', text }] : [], ...evidence(m) })
1041 continue
1042 }
1043 const moment = scoreMoment(m, names, was, lastGoalOf(m.lastGoal), w)
1044 if (moment === null) continue
1045 out.push({ id: m.id, texts: [moment.text], plays: moment.play ? [moment.play] : [], ...evidence(m) })
1046 }
1047 const liveIds = new Set(live.map((m) => m.id))
1048 for (const f of finishedOf(view)) {
1049 if (option === 'pinned' && !finishedPinned(f)) continue
1050 const was = before.get(f.id)
1051 if (!was || liveIds.has(f.id)) continue
1052 const names = namesOf(f)
1053 if (names === null) continue
1054 const goal = scoreMoment(f, names, was, null, w)
1055 const ft = fullTimeMoment(f, names, w)
1056 const moments = [goal, ft].filter((x): x is Moment => x !== null)
1057 out.push({
1058 id: f.id,
1059 texts: moments.map((x) => x.text),
1060 plays: moments.map((x) => x.play).filter((p): p is ClaudinhoPlay => p !== null),
1061 ...evidence(f),
1062 })
1063 }
1064 return out
1065}
1066
1067/**
1068 * Whether this view says the celebrated goal's score is no longer the one it was decided on: the record's match
1069 * present (by its id, in the live list or else the finished list, before any `toasts` filter: a pin change never
1070 * hides it) with a tally DIFFERENT from the record's own (lower: a correction; higher: a later goal), a tally compared
1071 * only when both carry it. The baseline is not read, so a view in between without the match, or without its tally,
1072 * hides nothing. Absent or equal: no news.
1073 */
1074function differsFromRecord(view: View, rec: NonNullable<ClaudinhoCelebration>): boolean {
1075 const live = itemsOf(view).find((x) => x.id === rec.id)
1076 const finished = live ? undefined : finishedOf(view).find((x) => x.id === rec.id)
1077 const m = live ?? finished
1078 if (!m) return false
1079 const score = tally(m.score)
1080 const shootout = tally(m.shootout)
1081 const differs = (a: Tally | undefined, b: Tally | undefined) => !!(a && b && (a.home !== b.home || a.away !== b.away))
1082 return differs(score, rec.score) || differs(shootout, rec.shootout)
1083}
1084
1085/**
1086 * Whether a record's full-time play (its own, or queued) still stands in this CURRENT view: the view lists the match
1087 * in `finished` with names, with the same result the play was decided on (its evidence, `outcome`: the winning side and
1088 * the winning team's identity, or a draw, compared alone, never the words: a later view in another language, or with
1089 * the English fallback, says the same result). A view that lists it live again (the CLI then lists no finished record
1090 * for it), or nowhere, or finished with another result or none (a `winnerCode` changed, a shootout appearing), or with
1091 * another team on the winning side at the same score (another id; with no id, another code or name), or with a
1092 * winning side that states no identity in either reading (no id, code or name: no evidence), does not. A record with
1093 * no full-time play: true.
1094 */
1095function fullTimeStands(view: View, rec: NonNullable<ClaudinhoCelebration>): boolean {
1096 const fulltime = playsOf(rec).find((p): p is Extract<ClaudinhoPlay, { kind: 'fulltime' }> => p.kind === 'fulltime')
1097 if (fulltime === undefined) return true
1098 const finished = finishedOf(view).find((x) => x.id === rec.id)
1099 if (finished === undefined || namesOf(finished) === null) return false
1100 const outcome = resultOf(finished)
1101 // A record another module load wrote (plugin 0.5.0's carried no `outcome`) is never played; it stands for nothing.
1102 if (outcome === null || !isObject(fulltime.outcome) || outcome.winner !== fulltime.outcome.winner) return false
1103 const team = outcome.winner === null ? null : identityOf(finished[outcome.winner])
1104 return sameIdentity(fulltime.outcome.team, team)
1105}
1106
1107/**
1108 * The baseline a CURRENT view leaves for the next one: its competition and each live match's tallies, with its
1109 * `lastGoal` identity when the record carries `names` and a `lastGoal`.
1110 */
1111function baselineOf(view: View): ClaudinhoBaseline {
1112 const items: ClaudinhoTally[] = itemsOf(view).map((m) => {
1113 const goal = namesOf(m) === null ? null : lastGoalOf(m.lastGoal)
1114 return { id: m.id, ...evidence(m), ...(goal ? { lastGoal: goal } : {}) }
1115 })
1116 return { slug: slugOf(view), items }
1117}
1118
1119/**
1120 * The band's `lineParts` (CLI 0.12.0) when their texts join to the line exactly: each a text and, kept, the style
1121 * `strong` (another style is a plain part); at most 64. Anything else: none, and the band draws the plain line.
1122 */
1123function linePartsOf(view: View): Array<{ text: string; style?: 'strong' }> | null {
1124 const raw = view.lineParts
1125 if (!Array.isArray(raw) || raw.length === 0 || raw.length > LINE_PARTS_MAX) return null
1126 const parts: Array<{ text: string; style?: 'strong' }> = []
1127 for (const p of raw) {
1128 if (!isObject(p) || typeof p.text !== 'string') return null
1129 parts.push(p.style === 'strong' ? { text: p.text, style: 'strong' } : { text: p.text })
1130 }
1131 return parts.map((p) => p.text).join('') === view.line ? parts : null
1132}
1133
1134/**
1135 * The match a `/claudinho match` binds, from the command's own reading: a view whose competition names a slug, its live
1136 * list's first record (the CLI lists the pick first), else its `next`; with the band's observation of that id in this
1137 * reading (whether it is listed, and its tallies). Nothing to bind: null.
1138 */
1139function bindingOf(reading: Reading): { slug: string; id: string; listed: boolean; score?: Tally; shootout?: Tally } | null {
1140 if (!reading.answered || !reading.isView) return null
1141 const { view } = reading
1142 const slug = slugOf(view)
1143 if (slug === '') return null
1144 const items = isObject(view.live) && Array.isArray(view.live.items) ? view.live.items : []
1145 const first: unknown = items[0]
1146 let id: string | null = null
1147 if (isObject(first) && typeof first.id === 'string' && first.id !== '') id = first.id
1148 else if (isObject(view.next) && typeof view.next.id === 'string' && view.next.id !== '') id = view.next.id
1149 if (id === null) return null
1150 return { slug, id, ...observe(view, id) }
1151}
1152
1153/** What a view says of a match id: whether its live list holds it, and its tallies there (each when present). */
1154function observe(view: View, id: string): { listed: boolean; score?: Tally; shootout?: Tally } {
1155 const m = itemsOf(view).find((x) => x.id === id)
1156 if (!m) return { listed: false }
1157 const score = tally(m.score)
1158 const shootout = tally(m.shootout)
1159 return { listed: true, ...(score ? { score } : {}), ...(shootout ? { shootout } : {}) }
1160}
1161
1162/**
1163 * Whether a CURRENT view of the bound competition is news about the bound match against the band's previous observation
1164 * of it: listed now and not before (kickoff), listed before and not now (full time), or a tally different (one that
1165 * appears is news; one that disappears is not). The observation is replaced either way: a change is consumed once.
1166 */
1167function paneNews(view: View): boolean {
1168 const b = bound
1169 if (b === null || b.final || observed === null || observed.gen !== b.gen || slugOf(view) !== b.slug) return false
1170 const was = observed
1171 const now = observe(view, b.id)
1172 observed = { gen: b.gen, ...now }
1173 if (now.listed !== was.listed) return true
1174 const differs = (a: Tally | undefined, prev: Tally | undefined) =>
1175 a !== undefined && (prev === undefined || a.home !== prev.home || a.away !== prev.away)
1176 return now.listed && (differs(now.score, was.score) || differs(now.shootout, was.shootout))
1177}
1178
1179/** A string cut at `max` UTF-16 units, never ending in half a surrogate pair. */
1180function cut(s: string, max: number): string {
1181 if (s.length <= max) return s
1182 const c = s.slice(0, max)
1183 const last = c.charCodeAt(c.length - 1)
1184 return last >= 0xd800 && last <= 0xdbff ? c.slice(0, -1) : c
1185}
1186
1187/** The Text props a pane part's style draws: strong bold, dim dimmed, accent and flair the goal colour, quote dimmed italic. */
1188function partStyle(style: ClaudinhoPanePart['style']): { bold?: true; dimColor?: true; italic?: true; color?: string } {
1189 if (style === 'strong') return { bold: true }
1190 if (style === 'dim') return { dimColor: true }
1191 if (style === 'accent' || style === 'flair') return { color: GOAL_COLOR }
1192 if (style === 'quote') return { dimColor: true, italic: true }
1193 return {}
1194}
1195
1196/** A named event row's first part through its marker emoji and the one space after it. */
1197const THROUGH_MARKER = /^[\s\S]*?\p{Extended_Pictographic}[\p{M}\u200D]* /u
1198
1199/*
1200 * The pane's display width is core's `displayWidth` (packages/core/src/text.ts, with its `clusterWidth`,types/index.d.ts 184 lines1/**
2 * The contract of the claudinho plugin: what it keeps in the session (`$.state`), each value under
3 * `PluginState.claudinho`. Everything is read from `claudinho ambient --json`, the installed CLI's view of its
4 * local cache, and the match pane's rows from `claudinho match <id> --json`; the plugin never fetches (the CLI does). A view is readable when it carries its `live` list and says what its line
5 * is, `idle` and `empty` as two booleans (`@claudinho/cli` 0.11.2 or later); anything else (the first-run object, the
6 * fallback object, a view from an older CLI) is no view: hidden, never current, the baseline kept.
7 */
8
9/**
10 * The band's line as the CLI fitted it, or null when there is nothing to show, the last run failed, or a run found no
11 * surface that draws the band (none attached, or the roster could not be read). `parts`: the CLI's `lineParts` (at most
12 * 64, each a text and, for a score token the fit kept whole, the style `strong`), kept only when their texts joined
13 * equal `text` exactly; the band then draws each `strong` part bold. Absent (an older CLI, or parts that do not join to
14 * the line): the plain line.
15 */
16export type ClaudinhoBand = { text: string; parts?: Array<{ text: string; style?: 'strong' }> } | null
17
18/**
19 * The band's pace: when the last run started (the clock's milliseconds) and whether the CLI said its answer was idle
20 * (the first-run object, nothing chosen; or a view whose `idle` is true, the edition over), which is read once per
21 * five minutes instead of every fire. `ranAt` is read only while `idle` is true; `{ ranAt: 0, idle: false }` is what a
22 * clear leaves (a run that found no surface that draws the band, or the last such surface detached).
23 */
24export type ClaudinhoPace = { ranAt: number; idle: boolean }
25
26/**
27 * The identity of a live record's `lastGoal` (CLI 0.12.0): the goal's kind, its minute and added time, the side it
28 * counted for, and the player when named. Two `lastGoal` objects are the same goal when every field is equal; a
29 * `lastGoal` the previous current view already carried is not the goal that made a new score.
30 */
31export type ClaudinhoGoal = {
32 type: 'GOAL' | 'OWN_GOAL' | 'PEN'
33 minute: number
34 added?: number
35 side: 'home' | 'away'
36 player?: string
37}
38
39/**
40 * One live match as the toasts remember it: its id, its two tallies, and (a record that carries `names`, CLI 0.12.0)
41 * its `lastGoal` identity when it had one. A record without `names` (CLI 0.11.2) keeps no `lastGoal`: its toast is
42 * the CLI's record's own `line`, and the plugin reads neither field for it.
43 */
44export type ClaudinhoTally = {
45 id: string
46 score?: { home: number; away: number }
47 shootout?: { home: number; away: number }
48 lastGoal?: ClaudinhoGoal
49}
50
51/**
52 * The toasts' baseline: the last CURRENT view's live matches, under its competition. Replaced by every current view,
53 * kept through a view that is not current and through a failed run (a change across the gap is said at the next
54 * current view); null before the first current view.
55 */
56export type ClaudinhoBaseline = { slug: string; items: ClaudinhoTally[] } | null
57
58/**
59 * The prompt context's record: the last CURRENT view's context block (null when it had none), its own display
60 * deadline (`staleAfter`, ISO 8601, or null) and when its run started. Cleared by a view that is not current, kept
61 * through a failed run.
62 */
63export type ClaudinhoContext = { context: string | null; staleAfter: string | null; ranAt: number } | null
64
65/**
66 * One play of the goal celebration, by its kind, each with its own length on screen:
67 * - `banner` (3 s): a view whose record carries no `names` (CLI 0.11.2), today's frames: a ball crossing a row, an
68 * English "GOAL" banner growing, then `text`, the goal's toast line (`⚽` and the CLI's record line);
69 * - `goal` (3 s): a goal toast for the pinned side (with no `pinnedSide`, any goal toast): the mascot, the ball crossing
70 * the top row, `word` (the view's goal word the toast was built with: `GOAL!`, `¡GOL!`; whole on every frame) and
71 * `team` on the middle row, `detail` on the bottom row (the scorer and the goal's minute, the own-goal detail and the
72 * minute, or the record's clock minute alone, as built); `minute` is the one-row form's minute;
73 * - `fulltime` (5 s): full time for the pinned side on a win or a draw: the mascot beside `<heading> · <result>`, the
74 * words it was built with (`Full time`, and `<team> win` or `Draw`, filled); `outcome` is the result as evidence (the
75 * winning side and team, each `null` for a draw: `ClaudinhoOutcome`), the one thing a later view is compared with.
76 */
77export type ClaudinhoPlay =
78 | { kind: 'banner'; text: string }
79 | { kind: 'goal'; word: string; team: string; minute: string; detail: string }
80 | { kind: 'fulltime'; outcome: ClaudinhoOutcome; heading: string; result: string }
81
82/**
83 * A full-time play's evidence: the winning side (`null` for a draw) and the winning team's identity as the finished
84 * record states it, its `id` when it carries one, else its `code` and `name` (each `null` when the record states
85 * none); `null` for a draw. A later current view keeps the play only with the same side and the same identity.
86 */
87export type ClaudinhoOutcome = {
88 winner: 'home' | 'away' | null
89 team: { id: string } | { code: string | null; name: string | null } | null
90}
91
92/**
93 * The goal celebration's record: its first play (its `kind` and that kind's fields) and `queue`, the plays after it
94 * (at most one: full time's, behind a goal decided in the same read, its own 5 s), played one after the other as one
95 * stretch; when the run that saw it decided it (the clock's milliseconds), the competition of the view it was decided
96 * in (its `competition.slug`, `''` when it states none), the match's id, and that match's regulation and shootout
97 * tallies in the view it was decided on (each when present: its own evidence; a finished record's at full time). Both
98 * plays are under one hold while Claude works and one 60-second drop counted from `at`. Its four writers, in a run's
99 * order: any answer naming another competition, or none, current or not (a view, or the first-run object; the fallback
100 * object names none and leaves it), nulls it; its match's score changing in any later current view (by `id`, in the
101 * live list or the finished list, whatever the `toasts` filter: a tally both carry differing from the record's, a
102 * correction or a later goal the plugin did not see as one; an absent match or tally is no news) nulls it, both
103 * plays with it; a full-time play is kept only while each later current view lists its match in `finished` with the
104 * same result (its `outcome`, never its words): a current view listing it live again, listing it nowhere, or giving
105 * another result (or none)
106 * drops that play (the record when the play is its own, its `queue` when it follows a goal, the goal play then kept
107 * under the rules above); the run's last match with a play writes it (a run a clear superseded writes nothing; never under `celebrate:
108 * off`); and the band's clear nulls it. The draw's guard: a record another module load wrote (its `at` not this
109 * load's) is never played; it stays in state until a goal or a clear replaces it. A played or expired record also
110 * stays until the next one replaces it (the draw ignores it). The draw reads it; its frames are not state.
111 */
112export type ClaudinhoCelebration =
113 | (ClaudinhoPlay & {
114 at: number
115 slug: string
116 id: string
117 score?: { home: number; away: number }
118 shootout?: { home: number; away: number }
119 queue?: ClaudinhoPlay[]
120 })
121 | null
122
123/** One part of a pane row: its text and its style (`strong` bold, `dim` dimmed, `accent` and `flair` the theme's
124 * `success` colour, `quote` dimmed italic; none: plain). */
125export type ClaudinhoPanePart = { text: string; style?: 'strong' | 'dim' | 'accent' | 'quote' | 'flair' }
126/** One pane row: its parts, in order. */
127export type ClaudinhoPaneRow = ClaudinhoPanePart[]
128
129/**
130 * The match pane's generation: a number that only grows, never null, which a new binding takes its own value from
131 * (a reload starts the module's values over; this number does not). Its two writers: `/claudinho match` binding a
132 * match (+1) and the `ui.close` hook for the pane `match` (+1). What fences an answer from before a close or a reopen
133 * is the module's binding and the pane value's own `gen`, both checked inside the write.
134 */
135export type ClaudinhoPaneGen = number
136
137/**
138 * The match pane's value (`/claudinho match`), read by the pane's draw alone: the generation it was written under, the
139 * competition (`slug`) and match `id` it is bound to, what the last `claudinho match <id> --json` read said (`rows`:
140 * one JSON value whose `lines` is an array of strings; `noView`: one JSON value without such `lines`; `failed`: no
141 * answer), the CLI's `lines` (at most 150, each cut at 600 characters), its styled `rows` when it printed them (CLI
142 * 0.12.0: each row the parts of the line at its index, kept only when every row's parts join to that line; at most 150
143 * rows of at most 64 parts, each row cut at 600 characters; a style the plugin does not draw is a plain part), beside
144 * them each row's `roles` (the one fact of the CLI's `rows[i].role` the drawing uses: `'event'` when that role is
145 * exactly `'event'`, else null; written with `rows` alone, as long as `rows`, so a value from a plugin load before
146 * them has none and the pane draws it as before) and its `attribution` and `disclaimer` (each a
147 * non-empty string cut at 1,000 characters, else absent), whether the last re-read failed (the rows kept from the read
148 * before it), and the fields the re-reads decide by: the answered match's `status` and `kickoff` (null with no match),
149 * and whether that status is final (`FT`, `POSTPONED`, `CANCELLED`). Its writers: the open, twice under its new
150 * generation (first a provisional value before its read, `rows` holding the view's line and its footer, with no status
151 * or kickoff; then its read's answer, while its binding is still the module's), a re-read only while its generation is
152 * the binding's (a failed one keeps the rows and sets `refreshFailed`), and the
153 * `ui.close` hook, which nulls it. Null before the first open and after a close.
154 */
155export type ClaudinhoPane = {
156 gen: number
157 slug: string
158 id: string
159 kind: 'rows' | 'noView' | 'failed'
160 lines: string[]
161 rows?: ClaudinhoPaneRow[]
162 roles?: Array<'event' | null>
163 attribution?: string
164 disclaimer?: string
165 refreshFailed: boolean
166 status: string | null
167 kickoff: string | null
168 final: boolean
169} | null
170
171declare module 'claude-code' {
172 interface PluginState {
173 claudinho: {
174 band: ClaudinhoBand
175 pace: ClaudinhoPace
176 baseline: ClaudinhoBaseline
177 context: ClaudinhoContext
178 celebration: ClaudinhoCelebration
179 paneGen: ClaudinhoPaneGen
180 pane: ClaudinhoPane
181 }
182 }
183}
184