Saltar a contenido

Referencia

Dos archivos describen el contrato de los plugins para máquinas. Están copiados del repositorio de Kino, donde una prueba amarra sus valores al código de la app (algunos comentarios se reescriben para esta copia pública), y las tablas de esta guía salen de contract.json.

Archivo Qué es Descarga
contract.json Cada número y regla que hace cumplir la app: las capacidades y el apiVersion que necesita cada una, los patrones y tamaños del manifiesto, los tipos de ajuste, los límites de tiempo, los límites y códigos de error de kino.fetch, los algoritmos de crypto, los topes de resultados, los límites de canales en vivo. sdk/contract.mjs lo lee, así que validate.mjs y run.mjs revisan exactamente estos valores. contract.json
kino.d.ts Declaraciones de TypeScript de todo el global kino y de cada forma que tus funciones reciben y devuelven. Ponlo al lado de plugin.js y agrega /// <reference path="./kino.d.ts" /> al comienzo del archivo: tu editor completa y revisa kino.* y tus valores de retorno. kino.d.ts

Los dos archivos también vienen dentro de cada repositorio de plugin de ejemplo, al lado de sdk/, y al final de llms-full.txt.

contract.json

Ver contract.json
{
  "$comment": "Kino plugin contract, apiVersion 1 to 27. The single source of truth for every number and rule a plugin meets. The app checks each value against its own code, and a test in the app pins this file to it; sdk/validate.mjs, sdk/run.mjs and the guide's tables read this file. apiVersion 12 (sync providers), 13 and 14 (plugin screens: screen, library, playerPanelTab, playerControl, room, schedule, ai, shared, enhancements) all arrive in Kino 0.9.74, the next release (not published yet); a Kino before 0.9.74 refuses all three. apiVersion 16 (coins) arrives in Kino 0.9.78; apiVersion 17 (kino.library.stats, Tu mes en Kino) arrives in Kino 0.9.81. apiVersion 18 (appThemes, a plugin's whole-app looks) arrives in Kino 0.9.81. apiVersion 19 (lyrics, the screen additions) and apiVersion 20 (visualBrowser, a web window the person drives; the plugin protocol: provides, consumes, kino.plugins.call) also arrive in Kino 0.9.81. apiVersion 21 (files) arrives in Kino 0.9.82; apiVersion 22 (progress, how far along the person is in something in a plugin, read back with list) in Kino 0.9.83 (provisional, like 23); apiVersion 23 (playerSlot) in Kino 0.9.83 (provisional: the number moves if the release does). apiVersion 24 (a Stream's drm as a list of options, and ClearKey blocks) in Kino 0.9.85 (provisional). apiVersion 27 (the clockLive stream field: a clock-enumerated live HLS window Kino synthesizes itself on its local proxy, for live from an open CDN) arrives in Kino 0.9.88.",
  "apiVersion": 28,
  "maxApiVersion": 28,
  "apiVersionFromApp": { "6": "0.9.50", "7": "0.9.51", "8": "0.9.54", "9": "0.9.55", "10": "0.9.65", "11": "0.9.66", "12": "0.9.74", "13": "0.9.74", "14": "0.9.74", "15": "0.9.77", "16": "0.9.78", "17": "0.9.81", "18": "0.9.81", "19": "0.9.81", "20": "0.9.81", "21": "0.9.82", "22": "0.9.83", "23": "0.9.83", "24": "0.9.85", "25": "0.9.86", "26": "0.9.87", "27": "0.9.88", "28": "0.9.90" },
  "additiveFromApp": { "kino.meta": "0.9.53", "kino.tmdb": "0.9.53", "catalogOnly": "0.9.54", "kino.browser.captureAll": "0.9.54", "fetch.errorHost": "0.9.55", "kino.fetchAnyHost": "0.9.55",
    "kino.meta.byTitle": "0.9.55", "kino.device": "0.9.55", "kino.seed": "0.9.55", "panel.loading": "0.9.64", "kino.nuvio": "0.9.71", "kino.sync.remoteChanged": "0.9.74", "action.link": "0.9.74", "action.setSettings": "0.9.74",
    "kino.library.episode": "0.9.77", "kino.sync.setActive": "0.9.78", "recommends": "0.9.81", "screen.installed": "0.9.81", "scaffold.onBack": "0.9.81", "appBar.mergeWithKinoBar": "0.9.81", "visualBrowser": "0.9.81", "kino.visualBrowser.available": "0.9.81", "protocol.ctx": "0.9.84", "openFrom": "0.9.84", "go.plugin": "0.9.84", "kino.image.thumbnail": "0.9.84",
    "kino.screen.httpImages": "0.9.88",
    "kino.pluginApiVersion": "0.9.88",
    "manifest.resolveAhead": "0.9.88",
    "export.prepare": "0.9.88" },
  "capabilities": {
    "$comment": "standaloneSupplements (apiVersion 13; room, schedule, ai and shared from apiVersion 14): a capabilities set with at least one standalone capability and nothing else but these runtime capabilities (all declarative but schedule, which exports job) is still standalone (needs neither required nor atLeastOneOf). Alone, with no standalone capability, they get the usual rule. playerSlot (apiVersion 23) is itself a standalone capability: a plugin with only it and its slot block needs neither resolve nor search. playerControl (Task 8t) is a supplement only beside a panel object (its own player panel, or panel.contributes with playerPanelTab): a standalone set with playerControl and no panel is refused with playerControlNeedsPanelMessage.",
    "names": ["search", "home", "browse", "episodes", "resolve", "download", "drm", "channels", "migrate", "scopedSearch", "meta", "subtitles", "tracking", "segments", "lyrics", "playlists", "externalResolve", "nuvio", "syncProvider", "socket", "byteSource", "storageLarge", "catalog", "qrScan", "imageSource", "screen", "library", "playerPanelTab", "playerControl", "playerSlot", "room", "schedule", "ai", "shared", "identity", "vault", "notifications", "coins", "pluginStore", "files", "progress"],
    "required": ["resolve"],
    "atLeastOneOf": ["search", "home"],
    "standalone": ["subtitles", "tracking", "segments", "lyrics", "syncProvider", "screen", "library", "playerPanelTab", "pluginStore", "playerSlot"],
    "standaloneSupplements": ["socket", "storageLarge", "catalog", "qrScan", "room", "schedule", "ai", "shared", "playerControl", "identity", "vault", "notifications", "coins", "files", "progress"],
    "playerControlNeedsPanelMessage": "The \"playerControl\" capability needs a \"panel\" (its own player panel, or \"panel\": { \"contributes\": true }) in a plugin that plays nothing",
    "anyPluginExports": ["subtitles"],
    "declarative": ["download", "drm", "scopedSearch", "externalResolve", "nuvio", "socket", "storageLarge", "catalog", "qrScan", "library", "playerControl", "room", "ai", "shared", "identity", "vault", "notifications", "coins", "files", "progress"],
    "apiVersions": { "download": 2, "drm": 2, "channels": 3, "migrate": 6, "scopedSearch": 6, "meta": 6, "tracking": 7, "segments": 7, "lyrics": 19, "playlists": 10, "externalResolve": 11, "nuvio": 11, "syncProvider": 12, "socket": 13, "byteSource": 13, "storageLarge": 13, "catalog": 13, "qrScan": 13, "imageSource": 13, "screen": 14, "library": 14, "playerPanelTab": 14, "playerControl": 14, "playerSlot": 23, "room": 14, "schedule": 14, "ai": 14, "shared": 14, "identity": 15, "vault": 28, "notifications": 15, "coins": 16, "pluginStore": 15, "files": 21, "progress": 22 },
    "requires": { "scopedSearch": "search", "vault": "identity" },
    "requiresMessage": "The \"{capability}\" capability also needs \"{requires}\"",
    "needsApproval": ["download", "drm", "channels", "migrate", "tracking", "nuvio", "syncProvider", "library", "playerPanelTab", "playerControl", "room", "schedule", "ai", "identity", "notifications", "coins", "pluginStore"],
    "exports": { "channels": ["liveCategories", "liveChannels"], "tracking": ["track"], "playlists": [], "syncProvider": ["syncPull", "syncPush"], "byteSource": ["read"], "imageSource": ["image"], "screen": ["screen", "screenEvent"], "playerPanelTab": ["panel"], "playerSlot": ["playerSlot", "playerSlotAction"], "schedule": ["job"], "pluginStore": ["storeSync"] },
    "optionalExports": { "channels": ["guide", "liveSearch"], "resolve": ["sign", "prepare"], "playlists": ["playlists", "playlistItems", "playlistCreate", "playlistAddItem", "playlistRemoveItem", "playlistReorder"], "syncProvider": ["syncStatus"] }
  },
  "manifest": {
    "maxBytes": 16384,
    "idPattern": "^[a-z0-9][a-z0-9-]{1,39}$",
    "reservedIds": ["live", "local", "unknown", "plugin", "own", "subtitle-keys", "subtitle-prefs", "kino"],
    "nameMaxChars": 40,
    "descriptionMaxChars": 300,
    "authorMaxChars": 60,
    "homepageMaxChars": 200,
    "minHosts": 1,
    "legacyMaxHosts": { "value": 20, "refusedUpToApp": "0.9.44", "noLimitFromApp": "0.9.45" },
    "noHostsApiVersion": 2,
    "insecureHostApiVersion": 2,
    "colorPattern": "^#[0-9A-Fa-f]{6}$",
    "entryMaxBytes": 1048576,
    "iconMaxBytes": 131072,
    "versionPattern": "^(0|[1-9]\\d{0,5})\\.(0|[1-9]\\d{0,5})\\.(0|[1-9]\\d{0,5})$",
    "pathSegmentPattern": "^[A-Za-z0-9._-]+$",
    "maxPathChars": 200,
    "liveStreamHosts": { "value": "any", "apiVersion": 3, "requires": "channels" },
    "streamHosts": { "value": "any", "apiVersion": 4 },
    "fetchHosts": { "value": "any", "apiVersion": 4, "handWrittenApiVersion": 9, "consentLine": "Puede conectarse a cualquier servidor público de internet (solo https, nunca tu red local)" },
    "discoverable": { "default": true },
    "categories": { "values": ["movies", "series", "anime", "live", "radio", "subtitles", "utilities", "themes", "adult"], "pattern": "^[a-z][a-z0-9-]{1,23}$", "message": "The \"categories\" field must be a list without repeats of: movies, series, anime, live, radio, subtitles, utilities, themes, adult, or a new type (2 to 24 lowercase letters, digits and hyphens, starting with a letter)" },
    "catalogOnly": {
      "$comment": "\"catalogOnly\": true (Kino 0.9.54, additive: no apiVersion, valid at every one, an older Kino ignores the field). The plugin lists and describes titles and plays none: resolve is not required, one of atLeastOneOf is, forbiddenCapabilities and forbiddenFields (streamHosts, and browser only as true: \"pages\" reads pages for the catalog) are refused. Kino never calls its resolve, never lists it as a source of a title (search, Ver en otros plugins, Buscar dónde verlo, the player's Servidor) and sends its titles to the person's other sources. For Kino 0.9.53 and older also declare and export resolve (throwing not_found) and search or home.",
      "notBooleanMessage": "The \"catalogOnly\" field must be true or false",
      "atLeastOneOf": ["home", "browse", "search", "meta"],
      "atLeastOneOfMessage": "A \"catalogOnly\" plugin must declare \"home\", \"browse\", \"search\" or \"meta\"",
      "forbiddenCapabilities": ["download", "drm", "channels"],
      "forbiddenFields": ["streamHosts", "browser"],
      "forbidsMessage": "A \"catalogOnly\" plugin can't declare \"{name}\": it doesn't play videos",
      "consentLine": { "es": "Solo catálogo: no reproduce videos", "en": "Catalog only: doesn't play videos" },
      "playerMessage": { "es": "{name} solo muestra el catálogo: no reproduce videos. Busca este título en tus otros plugins.", "en": "{name} only shows the catalog: it doesn't play videos. Look for this title in your other plugins." },
      "resolveNote": "catalogOnly: Kino {fromApp} y posteriores nunca llaman resolve ni sign; solo un Kino anterior, que no conoce el campo",
      "olderApps": {
        "compatibleNote": "catalogOnly existe desde Kino {fromApp}: un Kino anterior ignora el campo y lo instala como un plugin normal, así que tu resolve debe fallar con kino.error(\"not_found\", …) y un mensaje para la persona",
        "refusedNote": "catalogOnly existe desde Kino {fromApp}: un Kino anterior ignora el campo y rechaza este plugin porque le falta \"{missing}\". Para que también se instale ahí, declara y exporta resolve (que falle con not_found) y search o home"
      }
    },
    "recommends": {
      "$comment": "\"recommends\": [\"owner/name\", ...] (Kino 0.9.81, additive: no apiVersion, valid at every one, an older Kino ignores the field). The plugins this one works better with, each a plain GitHub owner/name as written (case kept; PluginAddress.bareRepoOf: at most maxRepoChars, no ://, no URL, no sub-path, no @ref), at most max of them; a repeat (case-insensitive) collapses, keeping the first. Anything else (not an array, more than max, a bad entry) makes the manifest invalid on field recommends. The plugin's screen and screenEvent receive installed, { \"<repo as written>\": true | false }, one key per entry (so {} when it declares none): whether that plugin is installed now on this device, never anything else. Kino calls screen again whenever it changes.",
      "max": 8,
      "maxRepoChars": 100,
      "badMessage": "The \"recommends\" field must be a list of at most 8 plain GitHub owner/name repositories",
      "screenArgument": "installed"
    },
    "resolveAhead": {
      "$comment": "\"resolveAhead\": true (owner 2026-11-18; additive: no apiVersion, valid at every one, an older Kino ignores the field; additiveFromApp[\"manifest.resolveAhead\"]). The plugin says its resolve(ref) may be called before the person presses play, because a resolve nobody plays has no effect they would notice (no play counted, no quota spent, no hidden page). Kino then resolves a movie or an episode ahead, as a background call, once the person has stayed about 0.3 s on its title page (a Continue watching card opens that page too), checks its stream's hosts exactly as the player's own resolve does (the broad video permission included; an answer that would need the person's approval of a host is not kept, and the press asks as always), keeps the answer for that title until min(maxKeepMs, expiresInSeconds x 1000 - expiryMarginMs) after it came, and the player takes it on its plain first open (a retry or a reopen resolves again; so does a press after that deadline, or after a failed answer). Leaving the page before then starts nothing; a resolve already running is never cancelled. A plugin whose resolve must not run for titles nobody plays leaves the field out and may export prepare instead (the prepare section); with the field true, prepare is never called. A hint, never a refusal: a value that is not a boolean is dropped (notBooleanMessage; null reads as left out), and true is ignored beside ignoredBeside, the first one found named in ignoredMessage: catalogOnly (Kino never calls that plugin's resolve) and browser, true or \"pages\" (a resolve called ahead is a background call, where kino.browser.capture and kino.browser.page are refused). The app logs each drop once per manifest version; the kit's validate warns with the same words. It needs no enhancements block (an enhancement carrying it is dropped as any unknown field is).",
      "default": false,
      "notBooleanMessage": "The \"resolveAhead\" field must be true or false; Kino ignores any other value",
      "ignoredMessage": "The \"resolveAhead\" field is ignored beside \"{name}\": Kino never calls this plugin's resolve ahead",
      "ignoredBeside": ["catalogOnly", "browser"],
      "maxKeepMs": 1200000,
      "expiryMarginMs": 60000
    },
    "debug": { "apiVersion": 6, "default": false, "switchLabel": "Modo debug", "switchHint": "Muestra los errores de este plugin en pantalla y guarda un registro que puedes compartir con su autor.", "defaultOnNote": "Modo debug encendido de entrada (\"debug\": true): quien instale el plugin verá sus errores en pantalla y se guardará su registro hasta que apague el interruptor en Ajustes. Sin el campo, cada persona puede encenderlo cuando quiera enviarte un registro" },
    "browser": { "apiVersion": 6, "consentLine": "Puede abrir páginas web ocultas para encontrar el video", "notBooleanMessage": "The \"browser\" field must be true, false or \"pages\"", "pageApiVersion": 6, "pagesValue": "pages", "pageConsentLine": "Puede abrir páginas web ocultas para mostrar contenido y encontrar el video" },
    "telemetry": { "apiVersion": 6, "consentLine": "Comparte con Kino registros de errores y datos técnicos de algunas reproducciones para corregir fallas", "notBooleanMessage": "The \"telemetry\" field must be true, false or \"verbose\"", "switchLabel": "Enviar registros de errores y de reproducción", "report": { "windowSeconds": 3600, "areaMaxChars": 24, "areaPattern": "^(?=[a-z0-9_:]*[_:])[a-z0-9_:]{1,24}$", "otherArea": "other", "perPluginPerSession": 3, "sessionShare": 10 }, "verbose": { "value": "verbose", "consentLine": "Comparte registros detallados de reproducción y errores con Kino para corregir fallas", "successSample": 0.25, "perPluginPerSession": 60, "areaWindowSeconds": 60 }, "logcat": { "playTag": "KinoPlay", "pluginTagPrefix": "KinoPlugin/" } },
    "section": { "apiVersion": 6, "labelMaxChars": 20, "export": "section" },
    "openFrom": {
      "$comment": "apiVersion 20, additive from Kino 0.9.84: \"openFrom\": { \"routes\": [...] } lists the names of this plugin's own screen routes that other plugins' cards may open (a plugin decides later how its own content is reached; a card whose route is not listed falls back to a search). 1 to maxRoutes different names, each read like a go.screen route (screen.limits.maxGoRouteChars characters of letters, digits and . _ ~ -); needs the screen capability (effective, enhancements included). Also valid in enhancements[\"20\"], so an older Kino ignores it without refusing the plugin; below apiVersion 20 a plain top-level block is refused.",
      "apiVersion": 20,
      "field": "openFrom",
      "routesField": "routes",
      "maxRoutes": 16,
      "routePattern": "^[A-Za-z0-9._~-]{1,64}$",
      "needsApiMessage": "The \"openFrom\" block needs apiVersion 20",
      "notObjectMessage": "The \"openFrom\" field must be an object with a \"routes\" list",
      "needsScreenMessage": "The \"openFrom\" field needs the \"screen\" capability",
      "badRoutesMessage": "The \"openFrom.routes\" field must list 1 to 16 different screen route names (1 to 64 letters, digits or . _ ~ -)",
      "fromApp": "0.9.84"
    },
    "enhancements": {
      "$comment": "\"enhancements\": { \"<apiVersion>\": { \"capabilities\"?, \"screen\"?, \"settings\"?, \"panel\"? } } (Task 8c; panel, Task 8k). A plugin keeps its own apiVersion, so a Kino older than fromApiVersion (which ignores the unknown key) installs and runs it as before, and lists under the apiVersion that brought them the features only a newer Kino reads. A Kino merges each key it supports (key <= maxApiVersion), in numeric order, over the manifest: capabilities are added, screen, settings and panel replaced, then the whole manifest is validated at that key's apiVersion. A block that fails is dropped and logged (dropped messages, after \"enhancements.<key>: \"), and an enhancement never refuses the plugin: a key at or below the plugin's apiVersion (notAboveApi), a setting whose type differs from the one the manifest declares (settingRetyped: keep the list a superset of the base one), a screen.replaces the plugin's own apiVersion has no Categorías for (replacesNeedsCategories), and, once the script is probed, exports the block newly needs and the script lacks (missingExports) all drop the block. A key above the Kino's maxApiVersion is ignored silently. The kit's validate reports every drop as a problem. The plugin's apiVersion never moves (its old behaviour stays); only the capabilities listed here gate on the enhancement's apiVersion. A block that adds playerPanelTab must carry the panel with contributes: true, and the other way round (panelTabNeedsPanel). Consent lines of added capabilities (library, playerPanelTab) are asked at install and update like any other; until approved, kino.library calls are refused with permission_denied. Task 18 (G1, apiVersion stays 14): a block may also add schedule (with its jobs, the jobs field: each needs the other, so a block with one and not the other is dropped; a top-level jobs of a manifest whose own apiVersion is below kinoJobs.apiVersion is never read), shared and ai, under exactly the consent of a plain manifest: schedule and ai are red lines asked at install and on the update that adds them, never approved by Kino on its own, unticked in a kit import, revocable in Ajustes; shared is a plain line. Their features gate on the manifest's featureApiVersion, so an older apiVersion plugin runs its jobs, kino.shared and kino.ai on a Kino that read the block, and nowhere else. Task 18 (G13): a block's settings list may not change the sync of a key the manifest (or an earlier block) declares, each list's sync as its own apiVersion reads it (below settings.sync.apiVersion every setting syncs), else the block is dropped (settingResynced): a value would sync on one Kino and stay on the device on another; a new key may say sync false.",
      "fromApiVersion": 14,
      "fields": ["capabilities", "screen", "settings", "panel", "jobs", "provides", "consumes", "openFrom", "visualBrowser", "slot"],
      "capabilities": ["screen", "library", "playerPanelTab", "playerControl", "room", "schedule", "shared", "ai", "files", "progress", "playerSlot"],
      "keyPattern": "^[1-9][0-9]{0,3}$",
      "dropped": {
        "notObject": "enhancements: must be an object keyed by apiVersion",
        "badKey": "the key must be an apiVersion (a whole number)",
        "notAboveApi": "the key must be above the plugin's apiVersion ({api})",
        "settingRetyped": "\"settings\" changes the type of the setting \"{key}\"",
        "settingResynced": "\"settings\" changes \"sync\" of the setting \"{key}\"",
        "replacesNeedsCategories": "\"screen.replaces\" needs the plugin's categories, which need its own apiVersion to be {min} or more",
        "missingExports": "needs the exports {exports}",
        "blockNotObject": "must be an object",
        "badField": "\"{field}\" can't be enhanced (only capabilities, screen, settings, panel, jobs, visualBrowser and slot)",
        "capabilitiesNotList": "\"capabilities\" must be a list",
        "badCapability": "the \"{capability}\" capability can't be added by an enhancement (only screen, library, playerPanelTab, playerControl, room, schedule, shared, ai, files, progress and playerSlot)",
        "panelTabNeedsPanel": "\"playerPanelTab\" and \"panel.contributes\" must come together in the same enhancement",
        "sectionChanges": "\"section\" is read at apiVersion {key} but not at the plugin's apiVersion"
      }
    },
    "screen": {
      "apiVersion": 14, "labelMaxChars": 20, "exports": { "screen": "screen", "event": "screenEvent" },
      "menuOpens": ["section", "screen", "both"],
      "settingsIn": ["settings", "screen", "both"],
      "opensFrom": ["menu", "settings"], "opensFromDefault": ["menu"], "settingsButtonLabelMaxChars": 40,
      "replaces": ["categories"], "replacesCatalogCapability": "browse", "categoriesRoute": "categories", "categoriesFrom": ["categories", "screen", "panel"],
      "goTitleFields": ["ref", "kind", "id", "title", "adult"],
      "goTitleByIds": { "fields": ["tmdb", "imdb", "kind", "season", "episode", "title", "year"], "kinds": ["movie", "series"], "maxTmdb": 2147483647, "imdbPattern": "^tt[0-9]{7,10}$", "maxSeason": 999, "maxEpisode": 9999, "minYear": 1870, "maxYear": 2100, "maxTitleChars": 120, "scrubPattern": "[\\u0000-\\u001F\\u007F-\\u009F\\u200B-\\u200F\\u202A-\\u202E\\u2066-\\u2069\\uFEFF]" },
      "textStyleHero": { "$comment": "apiVersion 17 (Tu mes en Kino): Text.style \"hero\", one step above h1, for a big number: 72 sp with a 72 sp line on the phone, x1.25 (90 sp) on the TV, bold; 56 sp in a TV panel. display stays an alias of h1. An older Kino does not know it and reads it as p (an unknown style is p, logged), so a plugin that needs the size on an older one checks apiVersion first." },
      "pagesNode": { "$comment": "apiVersion 17 (Tu mes en Kino): { type: \"pages\", key, children, onPageChanged? }, full-screen pages, Kino's own node (no Flutter name: PageView stays the carousel, with dots). minChildren to maxChildren children (else the whole node is dropped, logged) and a key of its own (required). Swiped on a phone and a desktop; on a TV Left and Right move a page once nothing more is focusable that way inside it, Up and Down stay in it, focus goes into the new page, a page with nothing focusable still turns; on the first page Left is left alone (the plugin's area never hands it on: Back and Kino's close leave). Kino draws the progress bar above the pages, one segment a page; the plugin neither draws nor hides it. No autoplay: notTaken are ignored, logged. The page reached lives in state.inputs.<key> as a number from 0, though pages is no input (no label, no form rules): the state, an answer's state or a ui set move it (out of range: clamped); onPageChanged's event carries the settled index as value. Never inside a sideways scroll, a table cell or another pages (dropped, logged). Additive, no new apiVersion: reverse (true: right to left, page 0 at the right, for manga) and progress (segments, the default, up to maxChildren pages; bar, a single thin bar, or none, up to longMaxChildren pages: a chapter, not a story). An older Kino ignores both and keeps the 8-page limit. An older Kino drops the node: read kino.screen.widgets.", "minChildren": 2, "maxChildren": 8, "notTaken": ["autoPlayMs", "initialPage", "viewportFraction", "padEnds"], "longMaxChildren": 250, "progress": ["segments", "bar", "none"], "fromApiVersion": 17 },
      "goSearch": { "$comment": "apiVersion 17 (Tu mes en Kino): { search: { q, scope? } }. Without scope, Kino's search opens with q and ONLY this plugin as the source (the plugin must be searchable). scope \"all\" opens Kino's normal search on every source the person has (no source, so no plugin is narrowed to), needs no search ability of the plugin, and the 18+ gate works as in Kino's search. The plugin learns nothing: no results and no list of sources come back. Honoured only from the person's own tap or submit (dropped, logged, from open, a timer, a load-more or a change), and only for a plugin of apiVersion 17 or later (a lower one is refused, logged). Any other scope value drops the go, logged.", "fields": ["q", "scope"], "scopes": ["all"], "scopeAllApiVersion": 17, "needsApiLog": "needs_api_17" },
      "goUrl": { "fields": ["href", "title"], "schemes": ["https"], "ports": [443], "maxHrefChars": 2048, "maxTitleChars": 60, "hrefChars": "^[A-Za-z0-9._~:/?#@!$&'()*+,;=%-]+$", "blockedSuffixes": ["localhost", "local", "localdomain", "internal", "intranet", "lan", "home", "corp", "home.arpa", "nip.io", "sslip.io", "xip.io", "localtest.me", "lvh.me"], "titleScrubPattern": "[\\u0000-\\u001F\\u007F-\\u009F\\u061C\\u200B-\\u200F\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u2069\\uFEFF]", "maxCombiningMarks": 2, "maxAnswerAgeMs": 5000, "openArmMs": 600, "maxQrChars": 1000, "minIntervalMs": 1000, "perMinutePerPlugin": 10, "fromTriggers": ["press", "submit"] },
      "goCopy": { "fields": ["text", "label", "sensitive"], "maxTextChars": 500, "maxLines": 6, "maxLabelChars": 40, "textScrubPattern": "[\\u0000-\\u0009\\u000B-\\u001F\\u007F-\\u009F\\u061C\\u200B-\\u200F\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u2069\\uFEFF]", "labelScrubPattern": "[\\u0000-\\u001F\\u007F-\\u009F\\u061C\\u200B-\\u200F\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u2069\\uFEFF]", "minIntervalMs": 500, "perMinutePerPlugin": 20, "fromTriggers": ["press", "submit"] },
      "goSyncProvider": { "$comment": "{ syncProvider: true } opens Kino's sync-provider settings (Ajustes > Conectar > Proveedor), where the person picks THIS plugin as the provider. It carries nothing and changes no choice by itself. Honoured only for a plugin that declares the syncProvider capability (else dropped, logged notSyncProviderLog) and only after the person's own press or submit (fromTriggers, as url and copy).", "value": true, "needsCapability": "syncProvider", "notSyncProviderLog": "not_sync_provider", "fromTriggers": ["press", "submit"] },
      "goSearchScreen": { "$comment": "{ searchScreen: true } opens Kino's native search screen, empty: nothing typed, no source narrowed to, so the person searches from there. Unlike { search: { q } } it carries no query (it is the \"send me to search\" button). Additive, no apiVersion of its own: an older Kino that does not know the key drops the whole go (the screen stays as it is). No capability is needed, since it is only navigation to a Kino page.", "value": true },
      "goSetExperience": { "$comment": "apiVersion 18: { setExperience: \"light\" | \"full\" } asks for the light experience (no shadows, no effects, square corners) or the full one of the whole app: the same two presets as Ajustes > Experiencia visual. Only from the person's own press or submit on the plugin's own screen, never a panel or a notice. Kino asks the person first, in its own words, naming the plugin, and changes nothing without their yes; when the app already has that experience nothing is asked. A theme may also suggest one with its `experience` field, asked the same way when the theme is turned on.", "words": ["light", "full"], "apiVersion": 18 },
      "goInstallPlugin": { "$comment": "apiVersion 19: { installPlugin: { repo: \"owner/name\" } } opens Kino's own install sheet for that repo (the same preview and consent sheet as Agregar un plugin: what it connects to, Instalar or Cancelar). Nothing installs without the person's own Instalar there. The sheet opens over the plugin's own screen (no navigation to Plugins). When that plugin is already installed Kino opens nothing and shows its own toast (Ese plugin ya está instalado / That plugin is already installed); read installed (the screen argument, from the manifest's recommends) to offer a tile only for what is missing. repo is a plain GitHub owner/name, kept as written (case untouched): a URL (anything with ://), a sub-path or an @ref is dropped. Only from the person's own press or submit on the plugin's own screen (fromTriggers, as url and copy), never a panel, a notice, open, a timer or a change.", "fields": ["repo"], "maxRepoChars": 100, "apiVersion": 19 },
      "goPlugin": { "$comment": "apiVersion 20: { plugin: { repo, route?, args?, query? } } opens another plugin's screen (route, with args) or its search (query). repo is a GitHub owner/name with an optional sub-path (owner/name/plugins/x), kept in its canonical form: a URL (anything with ://) or an @ref is dropped, at most 200 characters. route is a go.screen route; args is a JSON object within the go.screen args cap; query is at most 200 characters. Only from the person's own press or submit on the plugin's own screen (fromTriggers, as url and copy), never a panel, a notice, open, a timer or a change.", "fields": ["repo", "route", "args", "query"], "maxRepoChars": 200, "maxQueryChars": 200, "fromTriggers": ["press", "submit"], "apiVersion": 20 },
      "goUseTheme": { "$comment": "apiVersion 18: { useTheme: { theme } } turns on one of the plugin's own appThemes ids, exactly as Apariencia's button, or with theme null goes back to Kino's theme while one of the plugin's own is active. Only from the person's own press or submit on the plugin's own screen, never a panel or a notice; refused, logged, when Apariencia does not list that theme as this plugin's. Kino shows its own toast and calls screen again with the new activeTheme, the id of this plugin's active theme or null, which screen and screenEvent receive.", "fields": ["theme"], "apiVersion": 18 },
      "goLiveChannel": { "$comment": "Task 11, apiVersion 14: { liveChannel: { provider, code } } tunes to the channel code of the En vivo provider plugin provider. Honoured only for a plugin whose approved contributing panel declares \"live\" in manifest.panel.contributes.kinds (else dropped, logged needsLiveTabLog), only after the person's own press or submit (fromTriggers, as url and copy), for an installed, usable provider with live channels (never a reservedProviders id; an 18+ provider only while the 18+ code is unlocked). An 18+ channel fails closed through the module's own open (locked: not found). From the player panel while a module channel plays the channel changes in place (the panel and its pin stay); from anywhere else the panel or screen closes and the player opens the channel, as go.play does.", "fields": ["provider", "code"], "providerPattern": "^[a-z0-9][a-z0-9-]{1,39}$", "codePattern": "^[A-Za-z0-9._~-]{1,128}$", "reservedProviders": ["live", "local", "unknown", "plugin", "own", "subtitle-keys", "subtitle-prefs", "kino"], "fromTriggers": ["press", "submit"], "needsKind": "live", "needsLiveTabLog": "needs_live_tab" },
      "limits": { "maxConfigKeys": 32, "maxDepth": 10, "maxNodes": 600, "maxListItems": 500, "maxStateBytes": 65536, "maxTextChars": 2000, "minEventIntervalMs": 100, "callTimeoutMs": 20000, "maxPopups": 1, "maxRefChars": 4096, "maxSearchQueryChars": 200, "eventQueue": 8, "maxUiOps": 8, "maxDialogButtons": 3, "maxWeight": 12, "maxGridColumns": 8, "maxTestKeyChars": 64, "maxTrailingLabelChars": 40, "maxHeroButtons": 2, "maxMenuItems": 8, "maxTitles": 1000, "maxFlatTitles": 60, "maxPatternChars": 200, "maxPatternRepeat": 1000, "maxPatternStates": 500, "maxPatternFields": 16, "maxPatternCompileWork": 20000, "maxPatternMatchWork": 4000000, "minTimerMs": 1000, "maxTimerMs": 86400000, "maxTimers": 3, "timerMaxFailures": 3, "toastMinMs": 2000, "toastMaxMs": 8000, "toastDefaultMs": 3500, "timerConfigWriteIntervalMs": 60000, "maxQrChars": 1000, "maxStepperDecimals": 6, "maxStepperAbs": 1000000000000000, "maxSkeletonLines": 6, "maxTableColumns": 20, "maxTableRows": 200, "maxColSpan": 8, "gridColumns": 12, "maxGoRouteChars": 64, "maxGoArgsBytes": 4096 },
      "spacingScale": [0, 4, 8, 12, 16, 24, 32, 48],
      "radiusTokens": ["none", "small", "medium", "large", "full"],
      "colorRoles": ["primary", "secondary", "surface", "muted", "warning", "error", "onPrimary", "primaryContainer", "surfaceVariant"],
      "sharedProps": { "$comment": "Task 15 (apiVersion stays 14): properties a whole family of nodes shares, with one meaning everywhere (no component per need). autofocus: on a focusable node (focusableWidgets, or any node with an onTap or onLongPress; never a QR), true; on a render (a tick or an answer) that left focus nowhere or on a node now gone, focus goes to the first such node in tree order; an answer's own focus wins; a node that still holds focus keeps it; on a phone a text field is never autofocused (no keyboard). selected: true or false on a button or a card with an onTap (pressableWidgets): Kino's selected look (filled-tonal; a card: an outline in the primary colour), read as selected; chips and tabs say theirs through value (selected on them is ignored, logged); ui set { key, value: true | false } on such a node sets it and ui toggle { toggle: key, prop: \"selected\" } flips it, kept until the plugin's next tree. badge: the Badge node's shape, \"dot\" or { text, textEn?, color? } (text 1 to maxChars, cut beyond; color a colour role, else the default), on a button, a card with an onTap, a tabs node's tab entry and a panel result's tabs entry: a count or a dot on the top end corner (beside a tab's label), read after the node's name. None of the three takes a per-size map. A value on a node that does not take it, or not of its shape, is ignored, logged.", "focusableWidgets": ["button", "textInput", "textArea", "dropdown", "toggle", "checkbox", "radioGroup", "slider", "chips", "stepper", "tabs", "titleCard", "fab"], "pressableWidgets": ["button", "card", "fab", "listTile"], "loadingWidgets": ["button", "card", "fab", "listTile"], "badge": { "dot": "dot", "fields": ["text", "textEn", "color"], "maxChars": 12 }, "toggleProps": ["hidden", "selected"] },
      "maxWidthFraction": { "$comment": "Task 15: a style property of every node: at most that share of the width its parent offers (the node still wraps its content); with fill it takes exactly that share; placement is the parent's crossAxisAlignment. Off the scale: dropped, logged.", "min": 0.25, "max": 1, "step": 0.05 },
      "corners": { "$comment": "Task 15: borderRadius also takes a per-corner map of radius tokens; an omitted corner takes the default; start and end follow the reading direction; a key that is no corner is ignored, a value that is no token drops the whole radius, both logged. Fills, clips, outlines and the TV's focus ring follow it.", "keys": ["topStart", "topEnd", "bottomStart", "bottomEnd"], "default": "medium" },
      "textTime": { "$comment": "Task 15: a Text's time (epoch ms, a whole number 0 to maxMs) is written by Kino in the app's language: relative (refreshed every refreshMs while shown, no plugin call) or clock (the device's 12/24 h); with a time the text is optional and is a prefix. A bad time is dropped (and the text is then required), logged; a timeFormat without a time is ignored, logged.", "field": "time", "formatField": "timeFormat", "formats": ["relative", "clock", "countdown"], "maxMs": 253402300799999, "refreshMs": 60000, "countdownRefreshMs": 1000, "maxCountdownMs": 86400000 },
      "enabledAt": { "$comment": "Task 18 (G10, apiVersion stays 14): enabledAt (epoch ms, a whole number 0 to textTime.maxMs; not per size) on a pressable (sharedProps.pressableWidgets: a button, a FloatingActionButton, a card or a ListTile with an onTap; elsewhere ignored, logged): drawn off (no press, no TV focus stop) until that time on the device's clock, then on by itself, with no plugin call (Kino keeps one timer for it while it is drawn). A Text's timeFormat countdown (with a time) writes the wait left until its time, «0:42», «1:02:03» (whole seconds rounded up, at most textTime.maxCountdownMs), rewritten every textTime.countdownRefreshMs while it runs and «0:00» once reached: the «Reenviar en 0:42» beside a button with the same enabledAt. A bad time is ignored, logged.", "field": "enabledAt" },
      "swipe": { "$comment": "Additive, no new apiVersion (Kino 0.9.82; an older Kino ignores both): onSwipeLeft and onSwipeRight on any node, one action each (the same shapes as onTap). A drag sideways of at least minDp sends the action for the direction the finger went (left: the next page). On the TV they answer Right (onSwipeLeft) and Left (onSwipeRight) once focus has nowhere further to go that way. Not per size.", "leftField": "onSwipeLeft", "rightField": "onSwipeRight", "minDp": 64 },
      "imageHeaders": { "$comment": "Additive, no new apiVersion (Kino 0.9.83; an older Kino ignores the field and asks for the picture without it): an image's headers, { Referer?, User-Agent? }, the request headers its picture is asked with, for a site that answers only to its own Referer. Only these names (any case), each a text of 1 to maxChars characters with no control character, a Referer an https address; the rest is dropped, logged. They need an https url (a data: picture takes none, and so does an http one: httpImages) and are sent only when the picture's host is one the plugin declared in its manifest hosts and, for the Referer, that address is on a declared host too (else the Referer alone is left out). Not per size. Without a User-Agent Kino sends Kino/<version>.", "field": "headers", "names": ["Referer", "User-Agent"], "maxChars": 512, "compositeNodes": ["titleCard", "titleRail", "titleGrid", "heroCard"], "compositeNote": "Also additive (Kino 0.9.83): the same headers field on titleCard, titleRail, titleGrid and heroCard, applied to every picture of the node (each item's poster and backdrop, the hero's image and logo) with the same rules, so never to one of them asked over http (httpImages); the node's headers are not per item. Not on the classic rows (a PluginItem's poster in Home or search)." },
      "dataImage": { "$comment": "Additive, no new apiVersion (Kino 0.9.82; an older Kino draws the fallback): an image's url may be data:image/<format>;base64,<bytes> (a picture the plugin holds, such as a book's cover read from its file), at most maxChars characters in all; svg is never taken.", "formats": ["png", "jpeg", "webp", "gif"], "maxChars": 200000 },
      "httpImages": { "$comment": "Additive, no new apiVersion (Kino 0.9.88; an older Kino keeps a screen's pictures https-only and drops an http one, logged, so an image draws its fallback, a hero its plain banner and a CircleAvatar its initials, a title its placeholder): every picture of a screen may be http as well as https, on a public host, by exactly the rule of a poster in Home (at most output.maxImageUrlChars characters; never the home network, a private, local or reserved IP address, localhost, a local name nor, over http, a name without a dot), so the channel logos IPTV panels hand out over http show. Nothing else loosens: a picture's headers (imageHeaders) go only with an https one, a link (goUrl) stays https-only, a data: picture keeps its own rule (dataImage). Feature-detect with featureDetect (kino.screen is on every runtime; the flag is absent on an older Kino). nodes names each picture field, by Kino's own node name (an item's poster and backdrop for the title nodes); a player panel built with the screen kit follows the same rule.", "flag": "httpImages", "featureDetect": "kino.screen.httpImages === true", "schemes": ["https", "http"], "nodes": { "image": ["url"], "heroCard": ["image", "logo"], "avatar": ["image"], "titleCard": ["item.poster", "item.backdrop"], "titleRail": ["items.poster", "items.backdrop"], "titleGrid": ["items.poster", "items.backdrop"] } },
      "canRequestFocus": { "$comment": "Task 22 (apiVersion stays 14): canRequestFocus (Flutter's name; true or false, default false; not per size) on any node. On the TV a node that takes no focus of its own (a status Card, a Text, a Row, a Column, a DataTable, a MaterialBanner without an action...) becomes a D-pad stop: Kino's row look while focused (a tonal tint and a 3 dp accent underline, never the white ring), no press (OK does nothing), its content read by a screen reader, in the normal Up/Down/Left/Right traversal and the Scaffold rules. Ignored on a node that already takes focus (an input, a button, a node with an onTap or onLongPress) and on the phone. A non-boolean is ignored, logged. Without it a non-focusable block is read by paging: the TV scrolls a body by 80% of its height before focus moves past what has not shown yet.", "field": "canRequestFocus" },
      "listHints": { "$comment": "Task 15: a ListView's newItemsHint: while items are appended (the old last item still in the list) and the person is not at the end, Kino's own chip (its text, never the plugin's) shows over the list's bottom; a tap goes to the end; it hides once the end shows. Only on a list that scrolls itself (one column).", "field": "newItemsHint" },
      "boxProps": { "$comment": "Task 17 (apiVersion stays 14): style properties, every one per size. alignSelf (start, center, end, stretch) places a child of a Row or a Column (or a Card, a Form, a scroll: alignSelfParents) across it, over the parent's crossAxisAlignment; stretch in a row draws as start; elsewhere (a wrapping row's cell too) ignored, logged. textAlign (textAligns) aligns the paragraph of a node that draws text (textAlignWidgets). border { width?, color? } (width 0 to border.maxWidth dp, default border.defaultWidth; color a colour role, else Kino's outline) and background (a colour role: the box's fill, its content in the role's readable on-colour; over color) on a node that draws a box (boxWidgets); elevation 0 to maxElevation, a whole number (Kino's shadow, a card's tonal lift too) on elevationWidgets. minWidth, maxWidth, maxHeight take the size scale beside minHeight; a min above its max drops the max. A value off its scale or shape is dropped, a number out of range clamped, a property on a node that does not take it ignored; all logged.", "boxWidgets": ["col", "row", "box", "card", "scroll", "grid", "form", "listTile", "pageView"], "elevationWidgets": ["card", "box", "appBar"], "textAlignWidgets": ["text", "button", "chips", "textInput", "textArea", "listTile"], "alignSelfParents": ["col", "row", "card", "form", "scroll"], "textAligns": ["start", "center", "end", "justify"], "maxElevation": 24, "border": { "fields": ["width", "color"], "maxWidth": 8, "defaultWidth": 1 } },
      "positioned": { "$comment": "Task 17: a style property (per size) of a child of a Stack (box) only, Flutter's Positioned: any of keys, each a number of dp (0 to maxDp, clamped) or a share of the stack written \"25%\" (percentPattern, 0 to 100, clamped); a value that is neither drops that key, an unknown key is ignored, both sides and a size on one axis ignore the size; all logged. Unpositioned children keep the stack's alignment and size it; a stack whose children are all positioned takes its own width (the width offered) and its height/minHeight (else 0). Children are drawn and focused in their order, clipped to the stack, sized and placed inside it (never pressed outside).", "parent": "box", "keys": ["top", "left", "right", "bottom", "width", "height"], "maxDp": 1280, "percentPattern": "^([0-9]{1,3}(?:\\.[0-9]{1,4})?)%$" },
      "motion": { "$comment": "Task 17: opacity (a style property, per size, every node): 0 to 1, clamped; below minInteractiveOpacity the node takes no press and no focus (Kino treats it as off). visible: false (not per size) hides a node as hidden: true does. animate (a style property, per size) on a box (boxProps.boxWidgets) or a positioned child, elsewhere ignored: { duration?, curve? }, duration whole ms minMs to maxMs (clamped; default defaultMs), curve one of curves (else the first): changes of its size, opacity, fill, place (positioned) and visibility between renders glide (AnimatedContainer, AnimatedOpacity and AnimatedSwitcher in one property). The device's animations off (animator duration scale 0) turns them off; an animation never delays a press or focus (a node gliding out takes neither); at most maxAnimated animating nodes per screen, the rest drop their animate (logged once). All other problems logged.", "fields": ["duration", "curve"], "minMs": 100, "maxMs": 600, "defaultMs": 250, "curves": ["standard", "ease", "decelerate"], "maxAnimated": 24, "minInteractiveOpacity": 0.38 },
      "tooltip": { "$comment": "Task 17: tooltip (and tooltipEn; not per size) on a node that does something (sharedProps.focusableWidgets, or any node with an onTap or onLongPress; never a QR), elsewhere ignored, logged: at most maxChars characters (cut beyond, logged). Kino draws it: on a phone on a long press (a node with its own onLongPress shows none: its action wins), on a TV after tvDelayMs of focus (hidden when focus leaves), shown showMs; a screen reader gets it as the long-press action's label. Never essential information: a person who never sees it misses nothing. A disabled node shows the plugin's own tooltip too (Kino adds none of its own).", "field": "tooltip", "maxChars": 80, "tvDelayMs": 800, "showMs": 2500 },
      "flutterNodes": { "$comment": "Task 17: Flutter's own nodes under their Flutter names (the older names are fab, listTile, avatar, pageView). FloatingActionButton { icon (required), labelText? (the extended form; else what a screen reader says: the tooltip, else Kino's own word), onPressed (required), fabPosition end | center (per size) }: Kino draws it over the bottom of the plugin's area (a player panel's body), never in place, never under the system bars or the keyboard; at most maxFabs per screen, never inside a list, a table, a pop-up, a ListTile or an image's fallback (dropped, logged); it takes selected, badge, autofocus and tooltip; on a TV a focus stop with the ring. ListTile { title (required), subtitle?, leading?, trailing? (one node each of tileSlotWidgets, else dropped; never pressed themselves), dense (per size) }: Material's heights, the whole tile one press and one TV stop (ring only with an onTap); selected (with an onTap) fills it with primaryContainer. CircleAvatar { image? (https, or http on a public host: httpImages; Kino's image pipeline; a failed one shows the initials), text? (initials, at most avatarMaxTextChars, cut), icon?, radius (dp, avatarMinRadius to avatarMaxRadius, clamped; default avatarDefaultRadius; per size), backgroundColor? (a colour role, default primaryContainer), labelText? (what a screen reader says) }: always a circle (no borderRadius). PageView { children (the pages, at most maxPages), initialPage (the first look only, clamped to the last page, logged), onPageChanged (its event's value: the settled page's index), autoPlayMs? (autoPlayMinMs to autoPlayMaxMs, raised or lowered, logged; paused while touched or focused and with animations off), viewportFraction (viewportFractionMin to 1, clamped; below 1 Kino's carousel: the neighbours peek), padEnds (default true) }: swiped on a phone, Left and Right at a page's edge on a TV (a page with nothing focusable leaves the pager itself as the stop), Kino's page dots under it, its place read by a screen reader; never inside a sideways scroll or a table cell (dropped, logged).", "maxFabs": 1, "fabPositions": ["end", "center"], "tileSlots": ["leading", "trailing"], "tileSlotWidgets": ["icon", "avatar", "image", "badge", "text", "loading"], "avatarMinRadius": 12, "avatarMaxRadius": 64, "avatarDefaultRadius": 20, "avatarMaxTextChars": 3, "maxPages": 24, "autoPlayMinMs": 3000, "autoPlayMaxMs": 60000, "viewportFractionMin": 0.3 },
      "scaffold": { "$comment": "Task 17 item G: Scaffold { appBar?, body (required), floatingActionButton?, bottomNavigationBar? } only as the root of a screen result (a screen's or a player panel's root; anywhere else, or in an answer's pop-up, dropped, logged), read slot by slot (slotTypes: the node each holds; body any node); a result whose root is a Scaffold is drawn in layout fill (a layout given other than fill is ignored, logged). Its AppBar is pinned at the top of the plugin's area, BELOW Kino's own title bar (the plugin's name and Close, drawn by Kino and never covered; the one exception is AppBar.mergeWithKinoBar, below); its body takes the bounded height left (a ListView or a scroll in it scrolls itself, the bars stay; the keyboard shrinks the body); its FloatingActionButton (or one in the body) sits above its NavigationBar. AppBar { title? (a string, read as a heading for a screen reader, with its titleEn twin; or, Flutter's way, any node: a TabBar, a Row of buttons, an Image..., read as any child, at most maxAppBarTitleNodes nodes, else dropped, logged; it takes the room left of the actions, a TabBar there scrolls sideways, a Text node is the heading; on the TV its focusables are part of the row, Left/Right across them then to the actions), leading? (an IconButton), actions? (at most maxAppBarActions IconButtons, the rest dropped, logged; each needs a labelText), bottom? (a TabBar), centerTitle, backgroundColor? (a colour role), elevation }: only a Scaffold's appBar; appBarDp tall, appBarPanelDp in a player panel. Scaffold.onBack (apiVersion 19, Flutter's PopScope with canPop false; below 19 dropped, logged): an action, same shapes as onPressed ('event', { event, arg } or { ui: [...], event }), never a go (a go in it is dropped, logged; one alone drops the whole onBack); only on a Scaffold root. While the root on screen declares it, the system Back (the phone's, the TV remote's) does NOT close the screen or pop a route: Kino sends that action as the person's press and the plugin answers as usual (its next tree simply no longer declares onBack when the next Back should leave). A pop-up open at the time closes first, Back never reaching the plugin; a pushed route whose root declares onBack gets it instead of popping. Never a trap: when the onBack call fails, times out or is refused the screen closes by itself, and a second Back while the first onBack call is still in flight closes the screen; Kino's own Close, a failed screen and the reserved open event are unaffected. A player panel has no Back to hold: ignored there, logged. AppBar.mergeWithKinoBar (apiVersion 19, boolean true, opt-in; below 19 dropped, logged): with a leading IconButton, Kino draws ONE bar over the screen: the leading takes Kino's Close button's place (its press is the plugin's action; its labelText is what a screen reader says), the AppBar's title (string, titleEn) takes the plugin's name's place, the AppBar's actions stay at the end followed by Kino's own buttons (the bell); the plugin's name stays the bar's accessibility label. Without a leading the flag is ignored, logged, and both bars show as before; without the flag nothing changes. The person's ways out are then the plugin's leading and the system Back (which closes the screen when onBack is absent or fails). On the TV the same, the leading first in D-pad order. Only on the root Scaffold's appBar; ignored in a player panel, logged. NavigationBar { items: [{ key, icon, label, labelEn?, badge? }] (minNavItems to maxNavItems, the rest dropped; fewer drops the bar; logged), value (an item's key) or selectedIndex, onChanged (its event's value: the item's key; not in state.inputs) }: only a Scaffold's bottomNavigationBar; Material's bar on a phone, a bottom row of focusable items with Kino's ring on a TV. TV D-pad: the AppBar's leading and actions, the body, the bottom bar, the button (Compose's geometry; Up from the body's first stop reaches the bar); Back closes or pops as everywhere.", "slots": ["appBar", "body", "floatingActionButton", "bottomNavigationBar"], "onBackField": "onBack", "mergeField": "mergeWithKinoBar", "backApiVersion": 19, "slotTypes": { "appBar": "appBar", "floatingActionButton": "fab", "bottomNavigationBar": "navigationBar" }, "maxAppBarActions": 4, "maxAppBarTitleNodes": 40, "minNavItems": 2, "maxNavItems": 5, "appBarDp": 56, "appBarPanelDp": 48 },
      "sizeScale": [16, 24, 32, 40, 48, 64, 80, 96, 120, 160, 200, 240, 320, 400, 480, 560, 640],
      "uiOps": ["show", "hide", "toggle", "enable", "disable", "focus", "set", "clear", "open", "close", "fullscreen"],
      "goKinds": ["movie", "series", "episode", "live", "music", "podcast"],
      "goShapes": ["title", "play", "search", "searchScreen", "browse", "section", "categories", "close", "screen", "titleByIds", "url", "copy", "liveChannel", "syncProvider", "useTheme", "setExperience", "installPlugin", "plugin"],
      "widgets": ["col", "row", "box", "card", "spacer", "divider", "scroll", "grid", "text", "image", "icon", "badge", "progress", "loading", "list", "button", "textInput", "textArea", "dropdown", "toggle", "checkbox", "radioGroup", "slider", "chips", "tabs", "emptyState", "errorState", "titleCard", "titleRail", "titleGrid", "heroCard", "popup", "form", "settings", "banner", "accordion", "skeleton", "qr", "stepper", "table", "fab", "listTile", "avatar", "pageView", "scaffold", "appBar", "navigationBar", "steps", "pages"],
      "tableParts": ["tr", "td"],
      "notInTableCell": ["list", "scroll", "table"],
      "fallbackWidgets": { "$comment": "Task 7i-1, apiVersion 14: an image's fallback is one node drawn in the image's box when the picture fails or there is no url (with a fallback an image whose url is missing or not one Kino may load is kept); at any depth in it only these widgets, and no onTap or onLongPress (ignored, logged). A card's flush (a layout prop) drops its own padding and clips its children to its shape. A wrapping row's cells stretch to their line's height unless the row's align is start, center or end.", "widgets": ["col", "row", "box", "card", "spacer", "divider", "text", "icon", "badge", "skeleton", "image"] },
      "skeletonShapes": ["line", "block", "circle", "card"],
      "roles": ["info", "warning", "error", "success"],
      "timerAnswerFields": ["state", "toast", "close", "config"],
      "answerFields": ["state", "dialog", "sheet", "menu", "toast", "toastEn", "go", "route", "close", "focus", "config", "ui", "share", "enableJob"],
      "shareAnswer": { "$comment": "apiVersion 17 (Tu mes en Kino): an answer's share: { key } draws the node with that key the person can see now, in the current tree or an open pop-up's body (when the answer also asks for a new tree, on that tree; a hidden node, one under a closed pop-up or accordion item, one on another page of pages, or a key naming a pop-up is dropped, logged), with every 18+ title taken out even while unlocked (nothing left: dropped, logged), to a PNG of widthPx by heightPx at widthDp, font scale 1, in the screen's theme, with Kino's own line naming the plugin under it, and opens the system share sheet (read-only content Uri, only a title naming the plugin, no text added to the person's message). Only the answer to the person's own tap or submit, at most maxAnswerAgeMs after it: dropped, logged, from open, a tick, a load-more, a change and an onClose; dropped inside a panel. Images wait imageWaitMs at most, then Kino's placeholder. One at a time. A TV refuses it, logged, with no toast (hide the button by device); so does a plugin below fromApiVersion. No permission line: the person taps and picks the target in the system sheet.", "fromApiVersion": 17, "fields": ["key"], "widthPx": 1080, "heightPx": 1350, "widthDp": 360, "imageWaitMs": 3000, "maxAnswerAgeMs": 5000 },
      "declaredPopups": { "$comment": "Task 7i-2, apiVersion 14: an answer's ui is a list of the same ui operations as a node's action (at most maxUiOps), run as the answer is applied; the deferredOps among them wait for the tree the answer's state change asks for (when it asks for one) and run on it, so a declared pop-up opens with its new body, never the last one's; a timer's answer drops ui, logged; Back before that tree arrives cancels them. A popup node's onClose (an event name with the node's arg, or { ui?, event?, arg? }) runs after the person dismissed that open pop-up (Back, Kino's close, a tap outside): its ui operations, then its event; never when a pop-up button, a menu item, an answer's ui or a new pop-up closed it; a go and any dismissDroppedOps in it are dropped, logged. Back always closes: the onClose event is no press (no kino.qr.scan, no go.titleByIds) and its answer drops dismissDroppedFields and the dismissDroppedOps of its ui, logged. The deferredOps also wait for a route the answer moves; only the newest held one is kept; a newer pop-up, a failed or invalid render, Try again and the error state drop them. A blank title is no title: no empty row is drawn, Kino's close (an X alone, Task 7k) starts the bottom row and the pop-up's own buttons sit together at its end; with a title the X ends the title's row.", "answerField": "ui", "deferredOps": ["open"], "dismissAction": "onClose", "dismissActionKeys": ["ui", "event", "arg"], "dismissDroppedOps": ["open", "focus"], "dismissDroppedFields": ["dialog", "sheet", "menu", "focus", "go", "route", "share", "enableJob"], "anchor": { "$comment": "Task 15: a popup node's anchor (a node's key): drawn next to that node (above it when there is more room above, else below), sized to its content and at most the area's width, over the content with no scrim, taking no layout space; ui open and close, Back and a tap outside work as for any pop-up; it has no close button of its own; TV focus goes into it and stays there, and Back gives it back to the anchor. Without an anchor, or when the anchor is not on screen or there is no room above or below it, the kind's own placement (logged once). A screen-format player panel draws a popup only with an anchor.", "field": "anchor", "notOnScreenLog": "screen: popup anchor \"<key>\" is not on screen, the pop-up drawn in its own place", "misfitLog": "screen: popup anchor has too little room above and below it for the pop-up, drawn in its own place" } },
      "popupKinds": ["dialog", "sheet", "menu"],
      "cardSizes": ["small", "medium", "large"],
      "pressBudget": { "$comment": "Task 18 (G6, G7, apiVersion stays 14): an action object may carry timeoutMs, its event's own call budget: a whole number of ms from minActionTimeoutMs to maxActionTimeoutMs (clamped, logged; not a number, ignored, logged), only on a press (pressFields: a button's onPressed is its onTap; elsewhere, or without an event, ignored, logged) and honoured only when the person's own press or submit sends it (a change, a tick, open or a load-more keep limits.callTimeoutMs). Kino's pending cue: while the call of a press runs past pendingCueMs, the node pressed (a button, a FloatingActionButton, a card or a ListTile with an onTap) is drawn in Kino's busy look until its answer (or its failure). loadingField (loading: true or false, not per size) on such a pressable draws the same look from your tree: Kino's spinner in place of a button's icon (a ListTile's trailing), no press (a TV keeps its focus there), read as busy (busyWord); elsewhere ignored, logged.", "field": "timeoutMs", "pressFields": ["onTap", "onLongPress", "onSubmit", "onTrailingTap"], "minActionTimeoutMs": 1000, "maxActionTimeoutMs": 30000, "pendingCueMs": 400, "loadingField": "loading", "busyWord": { "es": "Cargando", "en": "Loading" } },
      "forceError": { "$comment": "Task 18 (G8, apiVersion stays 14): Flutter's forceErrorText (and forceErrorTextEn; not per size) on any input: the plugin's own verdict (a server's code refused, an address already taken), drawn under the field exactly as a failed form check's error (the error role, read with the field by a screen reader), a failed submit's own error winning while it shows. The person's edit of that field (a change, ui set or clear) hides it until the plugin's next verdict: the answer to the person's next press or submit, or a different text, shows it again. At most maxChars characters (cut, logged); not a text, ignored, logged. It never blocks a submit (only Kino's own rules do).", "field": "forceErrorText", "maxChars": 200 },
      "settingsAutoSave": { "$comment": "Task 18 (G11, G12, apiVersion stays 14): a settings node's autoSave: true (else false; not a boolean, ignored, logged) saves its toggle and select settings (types) as the person changes them, through the screen's own write (the same store and sync; your validateSettings is not asked, as for bind; toggles and selects keep your web session); a refused write puts the stored value back with Kino's generic line. A setting with unlockWith changes (and so saves) only after its code in the form's own prompt. When every valued setting the node shows saves this way the form draws no Guardar nor Descartar; a text, url, password or list it shows keeps them. Without autoSave every change waits for Guardar, as in Ajustes. G12: a settings node whose keys hold no valued setting (only action, status, section, link, help or qr items, e.g. keys: [\"logout\"]) draws those items and no Guardar nor Descartar: an action runs from its own button (its confirm first), as in Ajustes.", "field": "autoSave", "types": ["toggle", "select"] },
      "inputKinds": ["text", "number", "email", "url", "search"],
      "inputs": ["textInput", "textArea", "dropdown", "toggle", "checkbox", "radioGroup", "slider", "chips", "stepper"],
      "fieldProps": { "textInput": ["required", "minLength", "maxLength", "pattern", "errorText"], "textArea": ["required", "minLength", "maxLength", "pattern", "errorText"], "dropdown": ["required", "errorText"], "toggle": ["required", "errorText"], "checkbox": ["required", "errorText"], "radioGroup": ["required", "errorText"], "chips": ["required", "minLength", "maxLength", "errorText"], "slider": [], "stepper": ["required", "errorText"] },
      "formChecks": ["required", "minLength", "maxLength", "pattern"],
      "colorHints": { "$comment": "Screen asks (#8): a colour that is no role logs its closest role: a role in another case, or one of these words (success and info are banner and toast roles, never a node's color).", "success": "primary", "info": "secondary", "danger": "error", "warn": "warning", "alert": "warning", "critical": "error", "ok": "primary", "accent": "primary", "subtle": "muted", "disabled": "muted", "gray": "muted", "grey": "muted", "background": "surface", "text": "onPrimary" },
      "configTypes": ["text", "toggle", "select", "list", "password"],
      "secretField": "secret", "secretBindHolds": ["password"],
      "screenAsks": { "$comment": "Screen asks (apiVersion 14, not shipped yet: additive inside 14). (1) An answer's config may write or empty a password setting: kept exactly as given (never trimmed; blank empties it; required ones are never emptied; at most the type's maxChars), saved through the same store, sync namespace and sync record as Ajustes' save (a synced password reaches the person's other devices, an emptied one is cleared there too; a device-only one, \"sync\": false, stays on the device), never read back by a screen, never in a log line (only its key). (2) A textInput with secret: true (Flutter's obscureText) is drawn masked on phone and TV; its text lives only in Kino's memory, never in the state, a render, a change or a tick: it goes only with the person's own tap or submit (state.inputs.<key>, and a form's or the field's own submit value), and is cleared once that call ends unless the answer gives one back in state.inputs.<key>. Its value from the tree and its onChange are ignored, logged; secret on a multi-line field, or a secret that is not true or false, drops the field. Bound (bind) only to a password setting (secretBindHolds), written on commit when not empty; a password is bound only by a secret field. (3) A settings node's onSaved (event name or { event, arg }) is sent after Kino's form in it saved (its Guardar, or with autoSave a toggle or select that saved on change and changed something: kind save with that key) or an action button in it finished, with value { kind: save | action, ok, keys, action?, reason? } (setting keys only, never values), as a change: not a press, never coalesced with ticks, which wait behind it; a save or action that ends after the screen closed sends nothing.", "onSavedField": "onSaved", "onSavedKinds": ["save", "action"], "onSavedReasons": ["rejected", "checkFailed", "refused", "failed"],
        "qr": { "$comment": "(4) A QrImage's countdown: expiresInMs (minExpiryMs..maxExpiryMs, counted from when Kino first draws that value) or expiresAt (epoch ms, read against the device's clock once, at most maxExpiryMs away; both given: expiresAt ignored). Kino draws a bar and the seconds left under the code, ticked by itself every tickMs between your calls, and once it reaches zero the code dims under its own 'expired' text. A countdown keeps its deadline while the value stays the same (re-sending expiresInMs never restarts it; a different expiresAt does); a new value starts a new one. onExpire (an event name or { event, arg }) is sent ONCE per value, value { phase, remainingMs }: phase renew renewBeforeMs before the end when given (bounded like expiresInMs; not below the lifetime: half of it used, logged), else expired at zero; never while the screen is hidden (one that came due goes once it shows again, expired if the end passed too), never for a withheld code (it holds one of your secrets), never twice (a slow or missing answer leaves the old code counting down to its expired look; your every timer is the fallback). It is nobody's press: its answer keeps what a timer's keeps (state, toast, close, config). onExpire and renewBeforeMs need an expiry; renewBeforeMs needs onExpire; else ignored, logged.", "fields": ["expiresInMs", "expiresAt", "renewBeforeMs", "onExpire"], "onExpireField": "onExpire", "minExpiryMs": 1000, "maxExpiryMs": 3600000, "phases": ["renew", "expired"], "tickMs": 250 },
        "steps": { "$comment": "(5) steps: a setup flow in Kino's own look, for any plugin (never Flutter's Stepper name, which reads as the number stepper). items [{ key, title, titleEn?, subtitle?, subtitleEn?, state, children? }], 1 to maxSteps (key valid and distinct, title required): done (collapsed to its subtitle, else Kino's Done), current (open: its children drawn under it) or pending (collapsed, dimmed). Exactly one current: none while a step is still to do makes the first one not done current; several keep the first, the others pending; an unknown state reads as pending; all logged. Only the current step's children are read (one level below the node, each header one node of the budget). onStepTapField (an event name or { event }): a done step is pressable (touch, or OK with the TV's focus ring) and sends it with the step's key as arg; without it nothing is pressable and focus goes from above straight into the current step. A screen reader reads each header as Step i of n: title, state.", "onStepTapField": "onStepTap", "maxSteps": 12, "states": ["done", "current", "pending"] } },
      "bindHolds": { "textInput": ["text"], "textArea": ["text"], "dropdown": ["select", "text"], "toggle": ["toggle"], "checkbox": ["toggle"], "radioGroup": ["select", "text"], "slider": ["text"], "chips": ["select", "text"], "stepper": [] },
      "devices": ["phone", "tv", "desktop"],
      "sizeClasses": ["compact", "medium", "expanded"],
      "styleProps": ["padding", "margin", "gap", "radius", "w", "h", "minH", "fill", "weight", "align", "justify", "color", "span", "offset", "maxWidthFraction", "alignSelf", "textAlign", "border", "elevation", "background", "minWidth", "maxWidth", "maxHeight", "positioned", "opacity", "animate"],
      "layoutProps": { "row": ["stackOnNarrow", "wrap"], "card": ["variant", "flush"], "scroll": ["direction", "zoom"], "grid": ["columns"], "list": ["columns", "stickToBottom"], "text": ["style", "maxLines", "bold"], "image": ["aspect", "fit", "focus"], "button": ["variant"], "titleCard": ["size"], "titleRail": ["size"], "titleGrid": ["columns"], "skeleton": ["shape", "lines"], "qr": ["size"], "table": ["header", "wrap", "zebra", "columns"], "textInput": ["trailingIcon"], "fab": ["fabPosition"], "listTile": ["dense"], "avatar": ["radius"], "pageView": ["viewportFraction", "padEnds"] },
      "layout": { "$comment": "Task 14 (apiVersion 14, no new apiVersion): a screen result's layout, chosen per result: on a screen() answer's root object (beside every; a deeper node's is not read), on a screen-format panel() result beside root (a panel root's own layout is ignored, logged). scroll (the default; absent or null): a player panel's body scrolls and the tree has no height limit (a list draws flat, flex does nothing), exactly as before. fill: the root is drawn at the panel body's bounded size, with no body scroll; flex shares the height left and a list with it is lazy and scrolls itself (TV: Up/Down pages it, the Task 7k rule). A render whose fixed (non-flex) children of the root alone reach the body's bottom is drawn in the scroll layout instead, logged once per screen (fallbackLog); it tries fill again with a new size, layout or set of root children. The dock and the drawer end above the keyboard, so a bottom row stays above it. A full screen's root is always the screen's bounded area (what fill does), whatever layout says. Any other value is logged and read as scroll. ListView stickToBottom (layoutProps.list, responsive): a lazy single-column list opens at its last item, follows new items while the person is at its end or one item from it, stays put once they scroll up and sticks again when they come back to the end; Kino keeps that per list key while the list is drawn (a re-render keeps it; a new key or a closed screen starts over). In a flat list (scroll layout, inside a scroll) it does nothing, logged once per screen (stickFlatLog).", "field": "layout", "values": ["scroll", "fill"], "fallbackLog": "screen: layout fill does not fit, using scroll", "stickFlatLog": "screen: list stickToBottom works only in a list that scrolls itself (layout fill, or a full screen), ignored in a flat list" },
      "tableCellProps": ["align", "colSpan"],
      "tableColumnProps": ["weight"],
      "aliases": {
        "$comment": "Task 8e: the Flutter-style names are the documented spelling of a node's type and properties; the older names above (widgets, styleProps, ...) are what Kino reads internally and stay accepted as aliases. Kino (PluginScreenOutput via ScreenNames) and the kit rewrite every node object at the one point it is read, before validation: a type of types becomes its older name (a TextField with multiline true or a maxLines above 1 in any size class becomes textArea, its multiline and maxLines dropped); a type of implied also sets that property (a different value given is logged and replaced); each props pair moves the canonical value under the older name (when both are given the canonical one wins and the clash is logged; a canonical null counts as absent); buttonProps only on a button (elsewhere logged and ignored); a table's columns take columnProps and its rows and cells are rewritten too. Anything else (an unknown name such as Stepper) is read as before: an unknown type is dropped and logged. Log lines name the older spelling. names: every type name the docs list (kino.screen.names).",
        "types": { "Column": "col", "Row": "row", "Stack": "box", "Card": "card", "Spacer": "spacer", "SizedBox": "spacer", "Divider": "divider", "SingleChildScrollView": "scroll", "GridView": "grid", "Text": "text", "Image": "image", "Icon": "icon", "Badge": "badge", "LinearProgressIndicator": "progress", "CircularProgressIndicator": "loading", "ListView": "list", "Button": "button", "ElevatedButton": "button", "TextButton": "button", "IconButton": "button", "TextField": "textInput", "DropdownButton": "dropdown", "Switch": "toggle", "Checkbox": "checkbox", "RadioGroup": "radioGroup", "Slider": "slider", "Chips": "chips", "TabBar": "tabs", "AlertDialog": "popup", "BottomSheet": "popup", "PopupMenuButton": "popup", "Form": "form", "MaterialBanner": "banner", "ExpansionTile": "accordion", "Skeleton": "skeleton", "QrImage": "qr", "NumberStepper": "stepper", "DataTable": "table", "TableRow": "tr", "TableCell": "td", "FloatingActionButton": "fab", "ListTile": "listTile", "CircleAvatar": "avatar", "PageView": "pageView", "Scaffold": "scaffold", "AppBar": "appBar", "NavigationBar": "navigationBar" },
        "implied": { "ElevatedButton": { "variant": "primary" }, "TextButton": { "variant": "text" }, "IconButton": { "variant": "icon" }, "AlertDialog": { "kind": "dialog" }, "BottomSheet": { "kind": "sheet" }, "PopupMenuButton": { "kind": "menu" } },
        "textFieldMultiline": "textArea",
        "props": { "width": "w", "height": "h", "minHeight": "minH", "mainAxisAlignment": "justify", "crossAxisAlignment": "align", "flex": "weight", "borderRadius": "radius", "onChanged": "onChange", "onSubmitted": "onSubmit", "hintText": "hint", "hintTextEn": "hintEn", "labelText": "label", "labelTextEn": "labelEn", "obscureText": "secret" },
        "buttonProps": { "onPressed": "onTap" }, "buttonPropTypes": ["button", "fab"],
        "columnProps": { "flex": "weight" },
        "names": ["Column", "Row", "Stack", "Card", "Spacer", "SizedBox", "Divider", "SingleChildScrollView", "GridView", "Text", "Image", "Icon", "Badge", "LinearProgressIndicator", "CircularProgressIndicator", "ListView", "Button", "ElevatedButton", "TextButton", "IconButton", "TextField", "DropdownButton", "Switch", "Checkbox", "RadioGroup", "Slider", "Chips", "TabBar", "emptyState", "errorState", "titleCard", "titleRail", "titleGrid", "heroCard", "popup", "AlertDialog", "BottomSheet", "PopupMenuButton", "Form", "settings", "MaterialBanner", "ExpansionTile", "Skeleton", "QrImage", "NumberStepper", "DataTable", "FloatingActionButton", "ListTile", "CircleAvatar", "PageView", "Scaffold", "AppBar", "NavigationBar", "steps", "pages"]
      }
    },
    "panel": {
      "apiVersion": 9, "labelMaxChars": 24, "exports": { "panel": "panel", "action": "panelAction", "event": "playerEvent" },
      "icons": ["info", "tune", "settings", "star", "bolt", "language", "subtitles", "list", "magic", "heart", "movie", "tv", "sports", "music", "bookmark", "help", "refresh", "sync", "add", "remove", "delete", "edit", "search", "close", "check", "share", "play", "pause", "download", "upload", "link", "open_in_new", "home", "person", "lock", "notifications", "warning", "error", "visibility", "copy", "arrow_back", "arrow_forward", "expand_more", "expand_less", "more_vert", "filter_list", "calendar", "schedule", "send", "mood"],
      "extraIcons": { "$comment": "Task 8v: the larger icon set (Material Symbols, outlined, as Kino already ships them). icons is every name; these names are read from apiVersion on; below it such a name is an unknown one (panel.icon draws defaultIcon). The screen surface (screen.icon, a tree's Icon, button, menu item and empty and error states, a panel in screen mode) exists only from apiVersion 14, so there every name of icons is known.", "apiVersion": 14, "names": ["refresh", "sync", "add", "remove", "delete", "edit", "search", "close", "check", "share", "play", "pause", "download", "upload", "link", "open_in_new", "home", "person", "lock", "notifications", "warning", "error", "visibility", "copy", "arrow_back", "arrow_forward", "expand_more", "expand_less", "more_vert", "filter_list", "calendar", "schedule", "send", "mood"] },
      "defaultIcon": "tune",
      "iconFile": { "sizePx": 96, "maxBytes": 24576, "storedName": "panel-icon.png", "refusal": "The panel icon must be a 96×96 px PNG with a transparent background, at most 24 KB" },
      "contributes": {
        "$comment": "Task 8k, apiVersion 14: \"panel\": { \"contributes\": true, \"label\"?, \"labelEn\"?, \"icon\"? | \"iconFile\"? } with the capability playerPanelTab (each needs the other; a missing label is the plugin's name, cut to labelMaxChars). The player panel is a tab host: one outer tab per source. With a contributed tab the bar is drawn and Kino's own information panel is first (fixed), then the panel of the plugin that provides the stream (its own tabs kept inside it), then the contributed ones in the person's order (Ajustes, Paneles del reproductor; default install order), at most maxTabs; with no contribution the drawer is as before (a plugin's own panel replaces Kino's, no bar). Each outer tab is labelled with the plugin's name (a name that reads like Kino is shown qualified, as \"Plugin «<name>»\") and its icon (never Kino's info icon), never the panel's own title; the id kino is reserved. A contributed panel(context) / panelAction / playerEvent is the same contract (legacy or screen format) for a plugin's title (never an 18+ one, never a title of an 18+ plugin; an 18+ plugin's tab only while the 18+ code is unlocked; not for M3U lists, own channels or other non-plugin content), with a context built from an allow-list (contextFields, player.playerFields): context.ref is an opaque id (foreignRefPrefix + foreignRefHexChars hex characters of foreignRefMac keyed by the install's own random salt over foreignRefInput: the same title gives this plugin the same id on that install, another plugin or install another one; opaque, not secret), contextAdds (foreign: true and source: { pluginId, name } of the plugin that provides the stream), notSent never sent (the owner's copy and its autoNext, which names a ref of the owner). It is called only while its tab is the selected one and the drawer is open (refreshMs only then), and playerEvent reaches it only then too (from the moment its tab opens until it closes, the drawer closes or the title ends), while approved and switched on (copyChanged without its label). Its player actions are honoured only in the answer to a panelAction whose trigger is in playerActionsFrom, and only playerActionKept (a seek of the title playing); with the playerControl capability (kinoPlayerControl, Task 8j) from any origin, and playerActionKeptWithControl; every other player field belongs to the playing plugin and is dropped. Its go never opens a plugin's title (goDropped). Consent: playerPanelTab is approved by the person with consentLine (red), never auto-approved, revocable with the per-plugin switch switchLabel (the person's, synced).",
        "apiVersion": 14, "capability": "playerPanelTab", "field": "contributes",
        "badMessage": "The \"panel.contributes\" field must be true or false",
        "needsCapabilityMessage": "The \"panel.contributes\" field needs the \"playerPanelTab\" capability",
        "capabilityNeedsMessage": "The \"playerPanelTab\" capability needs \"panel\": { \"contributes\": true }",
        "maxTabs": 6, "kinoTabId": "kino",
        "kinds": { "$comment": "Task 11, apiVersion 14: which content the contributed tab joins: \"title\" (a plugin's title, the 8k rule) and \"live\" (an En vivo module channel, kinoLivePanel). Optional; a non-empty list of values (duplicates kept once); an unknown value, an empty list or a non-list is an invalid manifest (badMessage); only beside contributes: true (needsContributesMessage).", "field": "kinds", "values": ["title", "live"], "default": ["title"], "badMessage": "The \"panel.kinds\" field must be a non-empty list of \"title\" and \"live\"", "needsContributesMessage": "The \"panel.kinds\" field needs \"panel\": { \"contributes\": true }" },
        "foreignRefPrefix": "foreign:", "foreignRefHexChars": 32, "foreignRefMac": "HmacSHA256", "foreignRefInput": "kino-panel-foreign:v2\n{contributor}\n{owner}\n{ref}",
        "contextFields": ["kind", "title", "year", "season", "episode", "episodeTitle", "ids", "positionMs", "durationMs", "paused", "seekStepMs", "stats", "device", "lang", "tab", "values", "features", "state", "size"],
        "playerFields": ["seekStepMs", "speed", "resize"],
        "contextAdds": ["foreign", "source"], "sourceFields": ["pluginId", "name"], "notSent": ["playing", "player.autoNext"],
        "playerActionsFrom": ["press"], "playerActionKept": ["seekToMs"], "playerActionKeptWithControl": ["seekToMs", "pause", "speed"], "goDropped": ["title", "play"],
        "consentLine": {
          "es": "Su pestaña en el reproductor verá lo que estás viendo (título, año, identificadores y posición, o el canal en vivo) mientras la tengas abierta, y podrá enviarlo a sus servicios",
          "en": "Its tab in the player will see what you are watching (title, year, ids and position, or the live channel) while you have it open, and can send it to its services"
        },
        "switchLabel": { "es": "Mostrar en el reproductor", "en": "Show in the player" }
      }
    },
    "settingsLayout": { "apiVersion": 9 },
    "theme": {
      "apiVersion": 6,
      "tokens": ["accent", "onAccent", "background", "surface", "highlight"],
      "defaults": { "accent": "#E50914", "onAccent": "#FFFFFF", "background": "#0E0E0E", "surface": "#181818", "highlight": "#F5F5F5" },
      "brandRed": "#E50914",
      "minTextContrast": 4.5,
      "minUiContrast": 3,
      "maxBackgroundLuminance": 0.05,
      "maxSurfaceLuminance": 0.12,
      "minSurfaceContrast": 1.05,
      "minBrandDeltaE": 25
    },
    "appThemes": {
      "$comment": "apiVersion 18, plugin app themes (phase 1): a plugin offers whole-app looks, declared as data. Below apiVersion 18 the field is ignored. Format is checked at parse (id, names, known token paths, types; a wrong type or unknown token refuses the manifest); a value outside its range does not refuse it: the resolver drops it with a warning, so a theme stays usable. A manifest with appThemes may declare no capabilities (it plays nothing). background.image is refused until a later version (imageArrivesLater); background.dim is an unknown token until then. tv and phone take the same groups as the theme itself. Resolution order (low to high): Kino's defaults, the theme, its tv/phone block, the person's adjustments clamped to adjustable and to ranges. The legibility pairs (text on the background, surface and surfaceHigh; accent and focus on the background; onAccent and onFocus on theirs) reuse manifest.theme's minTextContrast and minUiContrast and read the effective values, Kino's where the theme changed only one side: a pair that fails falls back on the side the theme set; the dark-background limit (manifest.theme.maxBackgroundLuminance) stays until light themes arrive, and the near-Kino-red rule does not apply to appThemes.",
      "apiVersion": 18,
      "maxThemes": 8, "maxAdjustable": 48, "idPattern": "^[a-z0-9][a-z0-9-]{1,39}$", "nameMaxChars": 40,
      "groups": ["colors", "shape", "typography", "elevation", "motion", "player"],
      "backgroundTypes": ["solid", "gradient"], "backgroundMaxColors": 8, "backgroundDefaultAngle": 180,
      "pluginColors": ["respect", "override"], "pluginColorsDefault": "respect",
      "experience": ["light", "full"],
      "price": { "$comment": "A theme with no price is free. A price is `{ kinos, payTo }`: Kino asks the person to buy the theme before turning it on, shows the price and their balance, enables Comprar only when the balance covers it, and pays `kinos` to the coins account `payTo` (the author's). One purchase per theme and account, valid on every device of the person. The price and the account come from this public manifest, so they are what Kino enforces for the person and pays the author, not a lock on the files.", "fields": ["kinos", "payTo"], "minKinos": 1, "maxKinos": 1000, "accountPattern": "^[0-9a-f]{64}$" },
      "logo": { "$comment": "A theme may draw its own logo in the side menu, the TV rail and the header, in place of Kino's. Vector only (no image file, no network): `{ wordmark?, mark? }`, each `{ size: [w, h], paths: [{ d, fill }] }`. The wordmark is the long logo (phone menu and header, the TV's open rail); the mark is the square one (the TV's collapsed rail). `decor` is `{ paths }` drawn OVER Kino's own logo (wordmark and mark) in the space of its \"o\": origin at its centre, y down, ring outer radius 100 (decorUnits); a hat on the \"o\" is y < -100, the dot of the \"i\" is near (-353, -132). What a theme leaves out stays Kino's. Kino's decision screens, the splash and the gate always show Kino's own logo.", "shapes": ["wordmark", "mark"], "decorUnits": 100, "maxPaths": 8, "maxPathChars": 2000, "maxCanvas": 1000, "maxAspect": 8, "fillTokens": ["accent", "onAccent", "textPrimary", "textSecondary"], "pathPattern": "^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\\s+-]+$" },
    "surfaces": {
      "$comment": "apiVersion 26 (Kino number to be set): themes may paint surfaces (a fill, a stroke and a glow per element), a gloss, a layout, shipped files (assets), a background image and a font. Every key is ignored below apiVersion 26 (a new Kino skips it, an old one never reads it). Format is checked at parse like the rest; a value outside its range is clamped or dropped by the resolver with a warning, never a refusal of the manifest. A device can switch each effect off in Ajustes > Rendimiento (the device wins over a theme).",
      "apiVersion": 26,
      "elements": ["button", "buttonGhost", "navItem", "navActive", "rail", "iconButton", "card", "cardFocus", "focus", "hero", "progress"],
      "surfaceFields": ["fill", "stroke", "glow"],
      "fillTypes": ["solid", "gradient"],
      "gradientColors": [2, 8],
      "strokeWidth": [0, 4],
      "glowRadius": [0, 24],
      "glowAlpha": [0, 1],
      "gloss": [0, 1],
      "layoutHero": ["fullBleed", "framed"],
      "layoutRail": ["strip", "floating"],
      "maxAssets": 16,
      "assetIdPattern": "^[a-z0-9][a-z0-9-]{1,39}$",
      "assetFields": ["id", "path", "sha256", "bytes"],
      "assetCaps": { "imageBytes": 2000000, "fontBytes": 1000000, "totalBytes": 6000000, "imageMaxPixels": [3840, 2160] },
      "imageFit": ["cover", "top"],
      "imageDim": [0.3, 1],
      "blockKeys": ["surfaces", "layout"]
    },
      "imageArrivesLater": "background.image arrives in a later version of Kino; remove it from this theme",
      "tokens": {
        "colors.accent": "color", "colors.onAccent": "color", "colors.background": "color", "colors.surface": "color", "colors.surfaceHigh": "color", "colors.textPrimary": "color", "colors.textSecondary": "color", "colors.outline": "color", "colors.focus": "color", "colors.onFocus": "color", "colors.railPanel": "color", "colors.placeholderTop": "color", "colors.placeholderBottom": "color", "colors.success": "color", "colors.warning": "color", "colors.error": "color", "colors.favorite": "color", "colors.scrim": "color", "colors.border": "color",
        "background": "background",
        "shape.cardRadius": "number", "shape.channelRadius": "number", "shape.buttonRadius": "number", "shape.chipRadius": "number", "shape.dialogRadius": "number", "shape.inputRadius": "number",
        "shape.dialogBorder": "number", "shape.menuBorder": "number", "shape.headerBorder": "number", "shape.cardBorder": "number", "shape.panelBorder": "number", "shape.heroRadius": "number", "shape.railItemRadius": "number",
        "typography.scale": "number", "typography.titleScale": "number", "typography.bodyScale": "number",
        "elevation.cardShadow": "number", "elevation.heroScrim": "number", "elevation.dialogShadow": "number",
        "motion.focusZoom": "number", "motion.crossfadeMs": "number", "motion.heroDrift": "word",
        "player.buttonScale": "number", "player.playButtonScale": "number", "player.seekBarScale": "number", "player.labelScale": "number", "player.buttonShape": "word"
      },
      "ranges": {
        "shape.cardRadius": [0, 32], "shape.channelRadius": [0, 32], "shape.buttonRadius": [0, 32], "shape.chipRadius": [0, 32], "shape.dialogRadius": [0, 32], "shape.inputRadius": [0, 32],
        "shape.dialogBorder": [0, 4], "shape.menuBorder": [0, 4], "shape.headerBorder": [0, 4], "shape.cardBorder": [0, 4], "shape.panelBorder": [0, 4], "shape.heroRadius": [0, 32], "shape.railItemRadius": [0, 24],
        "typography.scale": [0.85, 1.3], "typography.titleScale": [0.85, 1.3], "typography.bodyScale": [0.85, 1.3],
        "elevation.cardShadow": [0, 1], "elevation.heroScrim": [0.3, 1], "elevation.dialogShadow": [0, 1],
        "motion.focusZoom": [1, 1.15], "motion.crossfadeMs": [0, 800],
        "player.buttonScale": [0.8, 1.4], "player.playButtonScale": [0.8, 1.6], "player.seekBarScale": [0.8, 2], "player.labelScale": [0.85, 1.3]
      },
      "words": { "motion.heroDrift": ["on", "off"], "player.buttonShape": ["circle", "rounded", "square"] },
      "defaults": {
        "colors.accent": "#E50914", "colors.onAccent": "#FFFFFF", "colors.surface": "#181818", "colors.surfaceHigh": "#242424", "colors.textPrimary": "#F5F5F5", "colors.textSecondary": "#B3B3B3", "colors.focus": "#FFFFFF", "colors.onFocus": "#000000",
        "background": "#0E0E0E", "accentText": "#FF6B6B"
      }
    },
    "secrets": { "apiVersion": 4, "namePattern": "^[A-Za-z][A-Za-z0-9_]{0,31}$", "maxSecrets": 16, "maxValueBytes": 4096, "prefix": "kino-sealed:v1:", "largeApiVersion": 6, "largeMaxValueBytes": 8192, "typed": { "apiVersion": 6, "uses": ["cipher-key"], "keyEncodings": ["hex", "base64"], "keyBytes": [16, 24, 32] } },
    "signature": { "apiVersion": 5, "fromApp": "0.9.45", "domain": "kino-signed-entry:v1", "authorKeyHexChars": 64, "valueHexChars": 128, "consentLine": "Firmado por su autor", "authorKeyLabel": "Clave del autor", "badFieldMessage": "The \"signature\" field must be { \"authorKey\": 64 hex characters, \"value\": 128 hex characters } (node sdk/seal.mjs --sign)", "badSignatureMessage": "La firma del autor no es válida: el código no es el que firmó, o no es para este repositorio, este plugin o esta versión" },
    "sync": { "$comment": "apiVersion 12, only with the syncProvider capability, which requires it: a syncProvider plugin without a sync block or without keySecret is refused (keySecret.missingMessage). keySecret names one of the plugin's own password settings: Kino, host side, derives the sync key from that setting's value as the plugin's runtime reads it (the profile in use) (HKDF-SHA256, salt = saltPrefix + pluginId + \":\" + accountId, where accountId is the pluginId too), so the key never travels and a second device needs only the provider's own settings. The derivation is public and the plugin reads that setting, so the plugin and its service CAN read the synced data (the consent line consentLine, always in red); it must be a high-entropy token, never a password a person picks (offline guessing from any blob). There is no random-key mode: such a key could never reach a second device.", "apiVersion": 12, "requires": "syncProvider", "modes": ["poll", "realtime"], "defaults": { "mode": "poll", "pullEveryMs": 600000, "pushDebounceMs": 300000, "maxBlobBytes": 4194304 }, "maxBlobBytes": 4194304, "needsCapabilityMessage": "The \"sync\" field needs the \"syncProvider\" capability", "badMessage": "The \"sync\" field must be an object with an optional \"mode\" of \"poll\" or \"realtime\" and optional positive whole numbers \"pullEveryMs\", \"pushDebounceMs\" and \"maxBlobBytes\" (at most 4194304)", "consentLine": "Sincronizará tus datos a través de su servicio: el plugin y su servicio podrán leerlos", "keySecret": { "required": true, "missingMessage": "The \"syncProvider\" capability needs a \"sync\" field whose \"keySecret\" is the key of one of the plugin's own \"password\" settings", "settingType": "password", "badMessage": "The \"keySecret\" of the \"sync\" field must be the key of one of the plugin's own \"password\" settings", "noDefaultMessage": "The setting the \"keySecret\" of the \"sync\" field names must not have a \"default\"", "deviceOnlyMessage": "The \"keySecret\" of the \"sync\" field can't name a setting with \"sync\": false", "kdf": "HKDF-SHA256", "saltPrefix": "kino-sync-key:v1", "info": "aes-256-gcm", "keyBytes": 32 }, "generateKey": { "$comment": "apiVersion 13, optional, default false (below 13 the key is ignored): Kino makes the keySecret value itself, keyBytes random bytes from a SecureRandom as lower-case hex (64 characters), only while that setting is empty, at two moments: when the person switches the provider on and when they press Enviar configuración (before the values are read, so an empty key never hides that button). Saved through the settings form's own save, sealed exactly like a typed password, never logged and never drawn in the form on any device (its value is kept and saved back). Never replaces a value that exists; a value received from another device always replaces a generated one.", "apiVersion": 13, "keyBytes": 32, "encoding": "hex", "badMessage": "The \"generateKey\" of the \"sync\" field must be true or false" }, "provision": { "$comment": "The keys of the plugin's own settings (secret or not) a pairing hands to another device so it can run the same provider; it must include keySecret, so it is always there. The receiving device saves them like typed values but does not run the plugin's validateSettings on them (as for action.setSettings). From apiVersion 13 it may name a device-only password (settings.sync false) for a one-shot secret such as a 2FA password: the sender sends it only while it holds a value (blank, it is left out and never blocks the send) and adds a plain line naming its label; the receiver lists its label only and stores it sealed and device-only exactly as a typed one (never synced, never in a backup); the plugin clears it itself (an action's clearSettings) once used. keySecret is never a device-only password (keySecret.deviceOnlyMessage).", "maxNames": 8, "badMessage": "The \"provision\" of the \"sync\" field must be a list of at most 8 different keys of the plugin's own settings that hold a value", "needsKeySecretMessage": "The \"provision\" of the \"sync\" field must include its \"keySecret\"", "deviceOnlyTextMessage": "The \"provision\" of the \"sync\" field can't name a text setting with \"sync\": false" } }
  },
  "hostRules": {
    "labelPattern": "^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$",
    "privateSuffixes": [".local", ".lan", ".internal", ".localhost", ".home.arpa"],
    "maxHostChars": 253
  },
  "permissions": [],
  "settings": {
    "max": 12,
    "keyPattern": "^[a-z][a-zA-Z0-9_]{0,31}$",
    "labelMaxChars": 40,
    "hintMaxChars": 80,
    "sectionHintMaxChars": 300,
    "english": {
      "$comment": "Kino 0.9.55, apiVersion 9 (below it, and on an older Kino, the keys are unknown and ignored, never checked): the English variant of a setting's label, hint and confirm, of an option's and a list field's texts, and of section.label. Same limits as the base field (confirmEn only where confirm is, and only with it). The base text is the Spanish default and the fallback; Kino shows the variant when it speaks English. Other languages: unknown keys, ignored.",
      "fromApp": "0.9.55", "apiVersion": 9, "suffix": "En",
      "settingKeys": ["labelEn", "hintEn", "confirmEn"], "optionKeys": ["labelEn"], "fieldKeys": ["labelEn", "hintEn"], "sectionKeys": ["labelEn"]
    },
    "maxOptions": 20,
    "optionValueMaxChars": 40,
    "optionLabelMaxChars": 40,
    "types": {
      "text": { "maxChars": 500, "canBeRequired": true, "canHaveDefault": true },
      "url": { "maxChars": 2048, "canBeRequired": true, "canHaveDefault": false },
      "password": { "maxChars": 500, "canBeRequired": true, "canHaveDefault": true },
      "toggle": { "canBeRequired": false, "canHaveDefault": true },
      "select": { "canBeRequired": false, "canHaveDefault": true },
      "list": { "canBeRequired": true, "canHaveDefault": false },
      "section": { "canBeRequired": false, "canHaveDefault": false, "hasValue": false, "apiVersion": 6 },
      "status": { "canBeRequired": false, "canHaveDefault": false, "hasValue": false, "apiVersion": 6 },
      "action": { "canBeRequired": false, "canHaveDefault": false, "hasValue": false, "apiVersion": 6 },
      "qr": { "canBeRequired": false, "canHaveDefault": false, "hasValue": false, "apiVersion": 13, "maxChars": 512 },
      "link": { "canBeRequired": false, "canHaveDefault": false, "hasValue": false, "apiVersion": 12 },
      "help": { "canBeRequired": false, "canHaveDefault": false, "hasValue": false, "apiVersion": 12 }
    },
    "sync": { "$comment": "apiVersion 13, a password or a text setting only: \"sync\": false keeps its value on the device where it was typed (a 2FA password the plugin clears once used; a phone number shown as typed). Never sealed to a paired device, never set or cleared by a value another device sends, never in a backup or a kit; the plugin reads it and may clear it. A password one may still be named in a sync provision (a one-shot secret, stored device-only on the receiver too); a text one never (manifest.sync.provision.deviceOnlyTextMessage). A text keeps drawing as a text field: nothing is masked. Default true: the value syncs as always. Below apiVersion 13 the key is unknown, so ignored.", "apiVersion": 13, "default": true, "types": ["password", "text"], "onlyPasswordOrTextMessage": "Only a setting of type password or text has \"sync\" (\"{key}\")", "notBooleanMessage": "\"sync\" of the setting \"{key}\" must be true or false" },
    "unlockWith": { "$comment": "apiVersion 14, a toggle or a select setting only: \"unlockWith\": \"adultCode\" makes Kino ask the device's 18+ code (its own prompt, phone and TV; the default code is announced while it rules) before the person moves the setting AWAY from its default (a toggle off its default, a select to any other option) in Kino's settings form: Ajustes ▸ the plugin's tab and a screen's or a panel's settings node. Back toward the default never asks. The change applies only once the code is accepted; a wrong code or Cancelar leaves the old value; the plugin never sees the code and nothing else is unlocked. The value syncs as any other setting; the code is asked per device at the moment of the change. A plugin's own writes may only move it toward its default: an answer's config away from it is refused (screen.lockedWhy), an action's setSettings is refused whole, and a field may never be bound to it (screen.lockedBind): show it in a settings node. One value for now (values); others may come. Below apiVersion 14 the key is unknown, so ignored.", "apiVersion": 14, "values": ["adultCode"], "types": ["toggle", "select"], "onlyToggleOrSelectMessage": "Only a setting of type toggle or select has \"unlockWith\" (\"{key}\")", "badValueMessage": "\"unlockWith\" of the setting \"{key}\" must be one of: {values}", "lockedWhy": "is locked (unlockWith {value}): only the person moves it away from its default, in Kino's settings form", "lockedBind": "bind \"{key}\" is locked (unlockWith {value}): show it in a settings node" },
    "linkOnly": { "$comment": "apiVersion 12 (additive): an action with \"linkOnly\": true is never drawn on any device; it runs only as the confirm target of another action's link (action.link), after Kino's own question. For a two-step link (find, then confirm) the person then sees one button.", "apiVersion": 12, "onlyActionMessage": "Only a setting of type action has \"linkOnly\" (\"{key}\")", "notBooleanMessage": "\"linkOnly\" of the setting \"{key}\" must be true or false" },
    "devices": { "$comment": "apiVersion 12 (additive): any settings item may say which devices draw it, \"devices\": [\"phone\"] / [\"tv\"] / both; absent = every device. Host side only: on a device it leaves out, the item is not drawn nor checked by the form, but its value is still stored, saved back unchanged, synced, provisioned and read by the plugin (kino.config). Below apiVersion 12 the key is ignored. The Node kit renders no form, so it only validates the field.", "apiVersion": 12, "values": ["phone", "tv"], "badMessage": "\"devices\" of the setting \"{key}\" must be a list of different devices: \"phone\", \"tv\"" },
    "configAids": {
      "$comment": "apiVersion 12 configuration aids in the settings form. link: { key, type: \"link\", label (+labelEn), url, hint? }: a button that opens url through the system only when the person taps it (https only, no user info, at most linkUrlMaxChars), with Kino's \"Abrir enlace\" and the host under it; on TV the address as text plus a QR. Kino makes no request to that host and it is no network access of the plugin's; an address holding one of the plugin's secrets is not shown. help: { key, type: \"help\", label? (+labelEn; default Kino's \"Ayuda\"), title? (+titleEn, at most helpTitleMaxChars), body (+bodyEn, at most helpBodyMaxChars; one of them required) }: a button that opens a modal titled with the plugin's name, plain text only (newlines kept, no markup, nothing clickable), scrubbed of the plugin's secrets; a missing base or English text falls back to the other. Their label, title and body may hold no control character (a body keeps its line breaks), invisible formatting or direction override. Kino opens a link's canonical address, the one whose host it shows. At most maxLinks links and maxHelps helps; they count among the sections, statuses and actions.",
      "apiVersion": 12, "maxLinks": 4, "maxHelps": 4, "linkUrlMaxChars": 2048, "linkSchemes": ["https"], "helpTitleMaxChars": 60, "helpBodyMaxChars": 2000
    },
    "list": { "apiVersion": 4, "defaultMaxEntries": 20, "maxEntries": 50, "maxFields": 4, "fieldTypes": ["text", "url"] },
    "ui": {
      "apiVersion": 6,
      "maxItems": 16,
      "confirmMaxChars": 120,
      "statusMaxChars": 200,
      "messageMaxChars": 300,
      "fieldErrorMaxChars": 200,
      "clearSettings": { "maxEntries": 12 },
      "statusHide": { "$comment": "apiVersion 13 (of the settings list in effect: an enhancements block's key when the block replaced settings, else the plugin's own, G5), additive: a settingsStatus() answer may carry hide: [setting keys]; the settings form (phone and TV) does not draw those items while that answer is current (a failed answer hides nothing). Their stored values stay, nothing is deleted, and they still count for the form's own rules; unknown keys and non-strings are ignored, entries past maxEntries are never read. A qr setting with no text draws nothing at all.", "apiVersion": 13, "maxEntries": 32 },
      "setSettings": { "$comment": "Additive action.setSettings (no apiVersion): an action may answer setSettings: { <key>: <string> } to fill the plugin's own text or select settings and, from passwordApiVersion (13, of the settings list in effect: an enhancements block's key when the block replaced settings, else the plugin's own, G5), its password settings (never a url: its value would become a server the plugin may reach, and only the person types one; never a toggle, list or valueless one). A password filled this way (a \"Create key\" action writing random bytes) is saved and sealed exactly like a typed one (a \"sync\": false one stays on the device), is never logged, and every password value the answer names is scrubbed from the action's own message and link, so it is never shown back. Only an action the person ran fills anything: a settingsStatus answer's setSettings is ignored. Kino does not run the plugin's validateSettings on them. Each value is trimmed and checked like a typed one; a required setting is never emptied; a key also in clearSettings, a value holding one of the plugin's secrets, a non-string, an unknown key or more than maxEntries keys refuse the whole field (nothing applied, Kino's generic error, the message still shows). Kino saves the values through the settings form's own save, so they reach the person's other devices and the profile in use like typed ones. Only from the plugin's own settings form.", "fromApp": "0.9.74", "maxEntries": 8, "types": ["text", "select", "password"], "passwordApiVersion": 13 },
      "link": { "$comment": "Additive action.link (no apiVersion): an action may answer link: { candidate, confirm }. Kino shows its own question (\"Is this you, <candidate>?\") with Confirm and Cancel; Cancel runs nothing, Confirm runs the confirm action once. candidate: a string, 1 to candidateMaxChars after trimming, no control or invisible formatting characters, scrubbed like any plugin text, shown as plain text. Runs of spaces collapse to one; any space but the ASCII one and the fillers that draw nothing (U+115F, U+1160, U+3164, U+FFA0, U+2800) refuse it. The question names the asking plugin by its manifest name. confirm: the key of ANOTHER action setting of the same plugin that declares no confirm/confirmEn question of its own. Anything else refuses the link: the action's own message is still shown, with Kino's generic error. A link in the confirm action's own answer is ignored (no chains); one pending link at a time, a newer one replaces it, leaving the form drops it.", "fromApp": "0.9.74", "candidateMaxChars": 64, "confirmMustBeAnotherAction": true, "confirmWithOwnQuestionRefused": true, "nestedIgnored": true, "onlyAsciiSpace": true, "blankFillers": ["U+115F", "U+1160", "U+3164", "U+FFA0", "U+2800"] },
      "exports": { "status": "settingsStatus", "action": "action", "validate": "validateSettings" }
    }
  },
  "output": {
    "section": { "apiVersion": 6, "maxTabs": 8, "maxTabLabelChars": 24, "maxHeroTextChars": 300 },
    "categories": { "apiVersion": 6, "export": "categories", "maxCategories": 24, "maxTitleChars": 40 },
    "panel": { "maxTopElements": 40, "maxTitleChars": 60, "maxMessageChars": 160, "maxTabs": 6, "maxTabLabelChars": 24, "maxQrUrlChars": 512, "minRefreshMs": 2000, "maxRefreshMs": 60000, "maxStatusChars": 200, "maxLabelChars": 40, "maxConfirmChars": 160, "maxHintChars": 80, "maxPlaceholderChars": 40, "maxAltChars": 200, "maxValueChars": 500, "maxSaveKeys": 50, "maxOptions": 20, "maxOptionChars": 40, "storedValueMaxChars": 500, "storedMaxKeysPerScope": 50,
      "loadingElement": { "$comment": "Kino 0.9.64, additive (no apiVersion): { type: \"loading\", text?, textEn? } draws a spinner with the text (else Kino's «Cargando…»). Answer at once with the tab's shell plus a loading element and a refreshMs, and the next call fills it in. From Kino 0.9.64 the panel context carries features: [\"loading\"]; an older Kino sends no features and drops the element as an unknown type, so check context.features and answer a status line there instead.", "type": "loading", "fromApp": "0.9.64", "maxTextChars": 200, "contextFeature": "loading" },
      "formats": ["legacy", "screen"],
      "screen": { "$comment": "Task 8i, opt-in per result: panel(context) may return { format: \"screen\", root, title?, titleEn?, tabs?, tab?, refreshMs?, accent?, layout? } (apiVersion 14; below it, or an unknown format, the result is read as the legacy panel, logged). root is a tree of the screen nodes, read like screen() with these limits; the drawer keeps its title, tabs, refreshMs (THE periodic call; no every in a panel) and accent. In screen mode the context gains state (Kino's, kept for the title's playback) and size (the drawer's size classes); panelAction gets { event: { key?, trigger, name, arg?, value?, values }, context } and its answer honours answerFields; droppedAnswerFields and legacyAnswerFields are dropped, logged. With plugin screens switched off a screen-format result shows no panel; legacy panels keep working: context.features carries contextFeature only while they are on, so the plugin can answer a legacy panel then. A playerEvent answer's panel (either format) shows in the open panel only for apiVersion 14 plugins (below it, ignored as before); its state is never applied.", "format": "screen", "apiVersion": 14, "maxDepth": 6, "maxNodes": 200, "notDrawn": ["popup"], "drawnWhenAnchored": ["popup"], "resultFields": ["title", "titleEn", "accent", "refreshMs", "tabs", "tab", "player", "layout"], "contextAdds": ["state", "size"], "contextFeature": "screen", "triggers": ["press", "change", "submit"], "answerFields": ["state", "toast", "toastEn", "ui", "config", "go", "close", "focus", "player", "message", "pause", "panel"], "droppedAnswerFields": ["dialog", "sheet", "menu", "route", "share", "enableJob"], "legacyAnswerFields": ["patch", "values", "save"] } },
    "layout": { "maxDepth": 4, "maxRowChildren": 6, "maxNodes": 120, "maxCardTitleChars": 60, "maxTextChars": 1000, "maxLogLines": 10 },
    "player": { "speeds": [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2], "minSeekStepMs": 5000, "maxSeekStepMs": 120000, "maxMarkers": 30, "maxMarkerLabelChars": 24, "maxCountdownS": 30, "resizes": ["fit", "fill", "zoom", "4:3", "16:9", "21:9"] },
    "details": { "apiVersion": 8, "fromApp": "0.9.54", "export": "details", "capability": null, "askedFor": "movie", "fields": ["title", "poster", "backdrop", "overview", "ids", "genres", "year", "rating", "runtimeMinutes"], "seriesFields": ["rating", "runtimeMinutes", "ids.mal", "ids.anilist", "ids.kitsu"], "ids": ["tmdb", "imdb", "mal", "anilist", "kitsu"], "reservedExportFromApiVersion": 8 },
    "meta": { "apiVersion": 6, "fromApp": "0.9.51", "fields": ["logo", "ratings", "cast"], "ratingSources": ["imdb", "tmdb", "rottentomatoes", "metacritic", "letterboxd", "mal", "anilist", "trakt"], "maxRatings": 6, "ratingValuePattern": "^\\d{1,3}([.,]\\d{1,2})?(%|/\\d{1,3})?$", "maxCast": 20, "maxCastNameChars": 60, "maxEpisodes": 5000, "maxRatingSourceChars": 20, "yearReadChars": 9, "yearPattern": "\\d{4}", "minEpisodeSeason": 0, "answerFields": ["title", "overview", "poster", "backdrop", "episodes", "genres", "logo", "ratings", "cast"], "ratingLabels": { "imdb": "IMDb", "tmdb": "TMDB", "rottentomatoes": "Rotten Tomatoes", "metacritic": "Metacritic", "letterboxd": "Letterboxd", "mal": "MAL", "anilist": "AniList", "trakt": "Trakt" }, "pageCastNames": 5, "cacheTtlMs": 1800000, "maxCachedTitles": 200 },
    "retry": { "apiVersion": 6, "reasons": ["conflict", "expired"], "maxAttempts": 3, "statuses": [401, 403, 409] },
    "signing": {
      "value": "request",
      "apiVersion": 6,
      "maxContextChars": 4096,
      "hlsMimes": ["application/x-mpegurl", "application/vnd.apple.mpegurl", "audio/mpegurl"],
      "alternateHosts": { "apiVersion": 6, "maxEntries": 6, "pattern": "^[A-Za-z0-9.-]{1,253}(:[0-9]{1,5})?$" }
    },
    "clockLive": {
      "$comment": "apiVersion 27, a Stream field, LIVE CHANNELS ONLY. A clock-enumerated live HLS window Kino synthesizes ITSELF, segment by segment, on its own loopback proxy and plays through its hardened live stack, so the plugin's server does only the ciphered channel discovery and every viewer pulls the open-CDN segments straight from its own IP (deviceless). The stream then carries no playable `url` (set to \"\") and its `mime` is `mime` below; it never combines with `drm`, per-request `signing` or an `external` hand-off. `template` is the per-segment URL with the required `{seg}` token (the media clock in ms) and the optional `{mc}` token (replaced by `mediaCode`, which is then required); its host is checked exactly like a channel's own URL (so a cleartext or undeclared CDN refuses). `grid` is the repeating per-segment durations in ms (e.g. [4004, 6006]); `rate` is media-ms advanced per 1000 ms of wall clock (1000 = realtime). `anchor` pins one real segment: `t` epoch ms, `s` that segment's media-clock ms, `firstStep` its 0-based index into `grid` (default 0). `window` is the sliding window (`count` segments ending `behind` the live edge); `reanchor` steers the server's drift correction (`everySec` cadence, `probeSpan` ± segments probed around the estimated edge); `segWidth` zero-pads `{seg}`. STRUCTURE (template, grid, anchor) is refused when invalid; every TUNING knob (rate, window, reanchor, segWidth) is clamped into range, never refused. Engine and server: com.arkiv.player.playback.ClockLiveEngine / ClockLiveServer; design: docs/clockLive-design.md.",
      "apiVersion": 27,
      "field": "clockLive",
      "liveOnly": true,
      "mime": "application/vnd.apple.mpegurl",
      "segToken": "{seg}",
      "mediaCodeToken": "{mc}",
      "mediaCodePattern": "^[A-Za-z0-9._~-]{1,128}$",
      "maxTemplateChars": 2048,
      "maxMediaCodeChars": 128,
      "maxSegWidth": 12,
      "grid": { "maxSteps": 16, "minStepMs": 200, "maxStepMs": 60000 },
      "rate": { "default": 1000, "min": 500, "max": 2000 },
      "window": { "countDefault": 6, "countMin": 2, "countMax": 20, "behindDefault": 3, "behindMin": 0, "behindMax": 20 },
      "reanchor": { "everySecDefault": 1200, "everySecMin": 60, "everySecMax": 21600, "probeSpanDefault": 4, "probeSpanMin": 0, "probeSpanMax": 12 }
    },
    "itemIdPattern": "^[A-Za-z0-9._~-]{1,128}$",
    "maxSearchItems": 100,
    "maxHomeRows": 20,
    "maxRowItems": 60,
    "maxBrowseItems": 100,
    "maxEpisodes": 5000,
    "maxSeasons": 50,
    "maxRefChars": 4096,
    "maxCursorChars": 2048,
    "maxResultChars": 2000000,
    "maxImageUrlChars": 2048,
    "maxGenres": 5,
    "maxGenreChars": 30,
    "maxBadges": 3,
    "maxBadgeChars": 20,
    "imdbPattern": "^tt\\d{5,10}$",
    "minRating": 0,
    "maxRating": 10,
    "minRuntimeMinutes": 1,
    "maxRuntimeMinutes": 1000,
    "minExpiresInSeconds": 30,
    "maxExpiresInSeconds": 86400,
    "airDatePattern": "^\\d{4}-\\d{2}-\\d{2}$",
    "maxTitleChars": 200,
    "maxTextChars": 2000,
    "maxSeasonNumber": 999,
    "maxEpisodeNumber": 99999,
    "maxSubtitles": 30,
    "maxSubtitleLabelChars": 60,
    "maxSubtitleTextBytes": 2000000,
    "maxAudioTracks": 8,
    "maxAlternatives": 8,
    "streamLabels": { "apiVersion": 6, "maxChars": 48, "maxRefChars": 512 },
    "skip": { "field": "skip", "fields": ["openingStartMs", "openingEndMs", "endingStartMs"], "maxMs": 86400000 },
    "maxHeaders": 20,
    "drmKeys": ["drm", "license", "licenseUrl", "drmLicenseUrl", "keySystem", "widevine"],
    "drm": { "field": "drm", "types": ["widevine", "clearkey"], "listApiVersion": 24, "maxOptions": 4, "clearKey": { "maxPairs": 8, "hexDigits": 32 } },
    "itemKinds": ["movie", "series", "live", "music", "podcast"],
    "migrateKinds": ["movie", "series", "episode", "live", "music", "podcast"],
    "liveKindApiVersion": 2,
    "audioKindApiVersion": 8,
    "audioKinds": ["music", "podcast"],
    "maxArtistChars": 200,
    "audioIdsApiVersion": 19,
    "audioIdKeys": ["isrc", "musicbrainz", "youtube"],
    "maxAudioIdChars": 64,
    "adultApiVersion": 6,
    "homeLiveApiVersion": 6
  },
  "live": {
    "apiVersion": 3,
    "maxCategories": 200,
    "maxChannelsPerPage": 500,
    "maxPagesPerCategory": 10,
    "pagesPerStep": 5,
    "maxChannelsPerCategory": 10000,
    "maxTotalPagesPerCategory": 200,
    "maxSearchChannels": 100,
    "minSearchChars": 2,
    "maxGuideChannels": 50,
    "maxGuideWindowMs": 86400000,
    "maxGuideEntriesPerChannel": 100,
    "maxChannelNumber": 9999,
    "maxPlaylists": 10,
    "adultApiVersion": 6,
    "defaultRefreshHours": 12,
    "minRefreshHours": 1,
    "maxRefreshHours": 168,
    "maxHideGroups": 50,
    "maxPlaylistBytes": 20971520,
    "maxEpgBytes": 52428800,
    "maxChannelsPerProvider": 5000,
    "maxCategoriesPerProvider": 500,
    "playlistParseBudgetMs": 20000,
    "epgParseBudgetMs": 30000,
    "reservedIdPrefix": "~",
    "playlistFormats": ["m3u"],
    "epgFormats": ["xmltv"]
  },
  "genres": ["peliculas", "series", "anime", "infantil", "documentales", "deportes", "noticias", "musica", "entretenimiento", "otros"],
  "discovery": { "topic": "kino-plugin", "maxResults": 100 },
  "search": {
    "types": ["movie", "series", "music", "podcast", "any"],
    "maxAltTitles": 5,
    "maxAltTitleChars": 200,
    "scoped": { "capability": "scopedSearch", "apiVersion": 6, "field": "within", "debounceMs": 400, "softTimeoutMs": 6000, "local": { "minMatches": 24, "maxExtraPages": 10, "maxExtraItems": 300 } }
  },
  "timeoutsMs": {
    "load": 10000,
    "search": 15000,
    "home": 20000,
    "browse": 20000,
    "episodes": 20000,
    "details": 20000,
    "resolve": 20000,
    "nuvioResolve": 75000,
    "browserResolve": 75000,
    "cloudstreamList": 45000,
    "liveCategories": 20000,
    "liveChannels": 20000,
    "guide": 20000,
    "liveSearch": 15000,
    "settingsStatus": 10000,
    "action": 30000,
    "section": 20000,
    "panel": 20000,
    "panelAction": 20000,
    "playerEvent": 5000,
    "playerSlot": 5000,
    "playerSlotAction": 5000,
    "categories": 20000,
    "validateSettings": 20000,
    "migrate": 10000,
    "sign": 1500,
    "signTotal": 3000,
    "subtitles": 10000,
    "track": 10000,
    "segments": 8000,
    "lyrics": 10000,
    "meta": 6000,
    "prepare": 15000
  },
  "prepare": {
    "$comment": "The optional export prepare(ref) (owner 2026-11-18; additive: no apiVersion, at every one, an older Kino never calls it; additiveFromApp[\"export.prepare\"]). For a plugin whose resolve must not run for titles nobody plays (a backend quota per account, plays counted or trials spent on resolve): once the person has stayed dwellMs on the title page of one of its titles, Kino calls prepare(ref) for what the page's play button would start, ref being the very string resolve(ref) gets for it (a movie, an episode or a lone track; never a series or a live channel), so the plugin can warm what that resolve will need (a session, an authorization). Its answer is ignored and nothing is kept: pressing play calls resolve as always. A background call within timeoutsMs.prepare: nobody is asked anything (a kino.fetch that would need the person to approve a host fails instead), its failures and timeouts never count toward \"No responde\", and the person's own calls go first in the plugin's queue. At most once per ref in perRefEveryMs (a failed call counts), and at most perMinute calls a minute per plugin, shared with resolveAhead's. Never called beside notCalledBeside: a manifest whose \"resolveAhead\": true stands (Kino resolves ahead instead), catalogOnly (Kino never calls that resolve) and browser, true or \"pages\" (a hidden page needs a play the person started). Never for an 18+ plugin while the person's 18+ code is locked, a title with a finished download, or a plugin that is off or waiting for its settings. It must not start a play, count one, or spend anything of the person's (a quota, a trial, a free play). sdk/validate.mjs warns when the export is never called and notes what it means otherwise; sdk/run.mjs <folder> prepare <ref> runs it.",
    "export": "prepare",
    "capability": "resolve",
    "dwellMs": 300,
    "perRefEveryMs": 300000,
    "perMinute": 6,
    "notCalledBeside": ["resolveAhead", "catalogOnly", "browser"]
  },
  "runtime": {
    "memoryBytes": 67108864,
    "stackBytes": 1048576,
    "idleCloseMs": 300000,
    "timeoutsBeforeUnresponsive": 3,
    "maxLogChars": 2000,
    "reportLogLines": 30,
    "reportLogLineChars": 300,
    "reportLogChars": 2048,
    "maxErrorChars": 2000,
    "maxThrownNameChars": 100
  },
  "fetch": {
    "methods": ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"],
    "bodyKinds": ["text", "json", "form", "base64"],
    "redirectModes": ["follow", "manual"],
    "defaultTimeoutMs": 15000,
    "maxTimeoutMs": 30000,
    "maxBodyBytes": 5242880,
    "maxBytes": { "$comment": "Task 7i-1: kino.fetch option maxBytes, from apiVersion 14 (below it the option is unknown and ignored): the body is read up to that many bytes and the read stops there (decoded bytes, after the transport's decompression; a cut text may end inside a character), except in a runtime holding sealed values (secrets, Kino's TMDB key), where the body is read whole up to maxBodyBytes (over it too_large), redacted whole and only then cut; the answer then has truncated: true (false when the whole body fit). Out of range or not a whole number: invalid_request. Never past the call's own response cap.", "apiVersion": 14, "min": 1, "max": 2000000, "field": "truncated" },
    "stopAt": { "$comment": "Task 8u: kino.fetch option stopAt, from apiVersion 14 (below it ignored like any unknown option): a marker of 1 to maxChars printable ASCII characters (0x20-0x7E); the read ends as soon as the decoded text holds it, ASCII case-insensitive, keeping everything up to and including it, with truncated: true when more followed. Text responses only: a byte answer fails with invalid_request (notText). With maxBytes, whichever comes first; never past the call's response cap. In a charset whose ASCII bytes are not those characters (UTF-16, UTF-32, a stateful one) the body is read as without stopAt and the decoded text is cut. In a runtime holding sealed values the body is read whole, redacted, then cut at the marker (searched in the redacted text) and at maxBytes.", "apiVersion": 14, "minChars": 1, "maxChars": 32, "charRange": [32, 126], "caseInsensitive": "ascii", "inclusive": true, "notText": "invalid_request" },
    "maxRequestChars": 1048576,
    "syncCall": { "$comment": "A syncProvider's syncPull and syncPush calls (only those, only while Kino runs them) may move the blob the manifest declares: each kino.fetch request (its JSON, the base64 body included) and each response body may reach ceil(sync.maxBlobBytes * 4/3) + envelopeChars, and so may the call's answer, instead of maxRequestChars, maxBodyBytes and runtime.maxResultChars. Hosts, quotas, redirects and timeouts are unchanged. Kino 0.9.74.", "functions": ["syncPull", "syncPush"], "envelopeChars": 65536 },
    "maxRequestsPerCall": 60,
    "nuvioMaxRequestsPerCall": 250,
    "maxInFlight": 6,
    "maxHostQuestionsPerCall": 3,
    "maxRedirects": 10,
    "errorCodes": ["host_not_allowed", "timeout", "network", "too_large", "invalid_request", "rate_limited"],
    "errorHostField": "host",
    "maxErrorHostChars": 253,
    "anyHost": {
      "$comment": "A host reached ONLY through an approved fetchHosts \"any\" (not declared, not a typed server): https on port 443, a public IPv4 literal or a dotted public name (a single-label name such as router is refused), on every redirect hop and for the hidden page's start address too. Each such request spends a budget on top of maxRequestsPerCall: perSite in perSiteWindowMs (a site is the registrable domain, so its subdomains count together) and perPlugin in perPluginWindowMs, refilled continuously and kept per plugin for the whole app (a runtime that closes and reopens keeps it). nuvioPerSite/nuvioPerPlugin: a converted Nuvio scraper's, scaled with its larger per-call cap. Over budget the request fails with errorCode, never queued. Declared hosts (insecureHttp ones included) and typed servers keep their own rules and never spend it. The hidden page (kino.browser) under the grant: its start address and every later top-level navigation of a capture (always for a CloudStream page) follow one rule: a declared or typed host by its own rules, any other host https on port 443 at a dotted public name (not limited to the plugin's hosts); on the proxy path a main-frame server redirect target may be contacted once before the capture ends blocked (detection, not prevention); subresources stay any public host (never the LAN) and spend no budget. From Kino 0.9.55.",
      "schemes": ["https"],
      "port": 443,
      "singleLabelNames": false,
      "perSite": 60,
      "perSiteWindowMs": 60000,
      "perPlugin": 600,
      "perPluginWindowMs": 600000,
      "nuvioPerSite": 250,
      "nuvioPerPlugin": 2500,
      "errorCode": "rate_limited"
    }
  },
  "browser": {
    "apiVersion": 6,
    "onlyFrom": "resolve",
    "onlyWhen": "the person pressed play, or a download the person started (never a background resolve such as the live zap's resolve ahead, which Kino skips for a browser plugin); a download's capture never waits for another page: busy at once",
    "defaultTimeoutMs": 18000,
    "minTimeoutMs": 1000,
    "maxTimeoutMs": 25000,
    "maxMatchChars": 500,
    "maxMedia": 8,
    "maxSubtitles": 10,
    "graceMs": 1000,
    "errorCodes": ["browser_unavailable", "timeout", "blocked", "busy", "not_allowed", "invalid_request"],
    "captureAll": {
      "feature": "kino.browser.captureAll",
      "options": "captureAll (every matching request until the page settles), alsoMatch (more patterns, only with captureAll), waitForCookie (a cookie the page must also hold; alone: a cookie-only page with no match), returnCookiesOnTimeout (a timeout answers what the page had, with timedOut, instead of the timeout error)",
      "maxAlsoMatch": 10,
      "maxRequests": 20,
      "settleMs": 1000,
      "waitForCookiePattern": "^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$",
      "maxCookies": 64,
      "maxCookiesTotalChars": 16384,
      "maxRequestHeaders": 64,
      "methods": ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
      "answerAdds": ["requests", "cookies", "userAgent", "timedOut"],
      "rules": "match and alsoMatch are searched anywhere in each URL, case-insensitively unless the pattern starts with (?-i); requests are deduplicated by URL, the primary match (the first request matching match) first; with waitForCookie the page never autoplays and the settle starts once both the match and the cookie hold; captureAll with waitForCookie needs a match; the answer adds its keys only when one of these options was used"
    },
    "page": {
      "apiVersion": 6,
      "manifest": "\"browser\": \"pages\" (\"browser\": true stays capture-only)",
      "onlyFrom": ["search", "home", "browse", "episodes", "details", "section", "resolve", "lyrics"],
      "onlyWhen": "the person is using the app: their own search, Home, list, title or play (a resolve also for a download they started); never a background call (prewarm, the live zap's resolve ahead, sync, update checks), and a list's read only with the app in front. Never clicks, taps, types or scrolls: only a check that completes with no input passes",
      "defaultTimeoutMs": 15000,
      "minTimeoutMs": 1000,
      "maxTimeoutMs": 25000,
      "maxWaitForChars": 500,
      "maxHtmlChars": 2000000,
      "perMinute": 20,
      "pollMs": 500,
      "lockWaitMs": 8000,
      "callMarginMs": 1500,
      "topLevel": "every top-level navigation and the document read stay on the plugin's kino.fetch hosts (https); else blocked, no HTML",
      "waitForFlags": ["m", "s"],
      "errorCodes": ["browser_unavailable", "timeout", "blocked", "busy", "not_allowed", "invalid_request", "rate_limited"]
    }
  },
  "tracking": {
    "apiVersion": 7,
    "capability": "tracking",
    "export": "track",
    "consentLine": "Le contará a {hosts} qué ves y cuándo lo terminas",
    "consentLineNoHosts": "Le contará al servidor que escribas en su configuración qué ves y cuándo lo terminas",
    "consentMaxHosts": 3,
    "switchLabel": "Enviar lo que veo",
    "types": ["start", "progress", "stop", "watched"],
    "kinds": ["movie", "episode"],
    "idKeys": ["imdb", "tmdb", "tvdb", "anilist", "mal"],
    "progressIntervalMs": 300000,
    "watched": { "remainingMs": 180000, "minFraction": 0.9 },
    "outbox": { "maxPerPlugin": 200, "maxAgeMs": 604800000, "maxAttempts": 12, "backoffBaseMs": 30000, "backoffMaxMs": 21600000, "failuresBeforeShown": 3, "ledgerMaxPerPlugin": 5000 },
    "idResolveTimeoutMs": 8000,
    "retryCodes": ["timeout", "network", "unavailable", "rate_limited"],
    "dropCodes": ["auth_required", "invalid_request", "not_found", "geo_blocked", "host_not_allowed", "too_large"]
  },
  "segments": {
    "apiVersion": 7,
    "capability": "segments",
    "export": "segments",
    "consentLine": "Agrega el botón para saltar la intro y los créditos",
    "kinds": ["movie", "episode"],
    "idKeys": ["imdb", "tmdb", "tvdb", "anilist", "mal"],
    "types": ["intro", "outro", "recap", "credits", "preview"],
    "openingTypes": ["intro"],
    "endingTypes": ["outro", "credits"],
    "minLengthMs": 1000,
    "maxSegments": 10,
    "maxEntriesRead": 100,
    "endSlackMs": 5000,
    "waitMs": 12000,
    "durationBucketMs": 10000,
    "failureRetryMs": 120000
  },
  "files": {
    "$comment": "apiVersion 21: the files capability. A plugin that declares it works with files on the person's device: kino.files.pick / pickFolder open the system picker from a press (settings action, panelAction or a screenEvent that follows a tap or submit: the same rule as qr.fromFunctions) and answer opaque handles, never an address; list, folders, info, read, readText, forget and url need no press, because a handle exists only for what the person picked. `copy: true` imports the bytes into the plugin's own store; the default keeps a reference (a persisted grant). A stream or an audio track may be `kino-file:<id>` (the id of one of the plugin's own handles); the host rules do not apply to it. Nothing is uploaded or sent. Additive pieces and new errors never move SUPPORTED_API by themselves; this block did, once, to 21.",
    "apiVersion": 21,
    "capability": "files",
    "consentLine": "Podrá guardar y leer los archivos que tú elijas de este aparato, o una carpeta entera si la eliges",
    "consentLineEn": "Can keep and read the files you pick from this device, or a whole folder if you pick one",
    "kinds": ["video", "audio", "book", "image", "subtitle", "other"],
    "operations": ["pick", "pickFolder", "list", "info", "read", "forget"],
    "fromFunctions": ["action", "panelAction", "screenEvent"],
    "maxReadBytes": 2000000,
    "maxHandles": 500,
    "maxFolders": 20,
    "maxFolderFiles": 5000,
    "maxPickAtOnce": 50,
    "defaultImportBytes": 64000000,
    "maxCopiesBytes": 1000000000,
    "pickTimeoutMs": 180000,
    "urlScheme": "kino-file:",
    "errorCodes": ["unavailable", "not_allowed", "busy", "timeout", "invalid_request", "gone", "too_large", "denied", "quota"]
  },
  "lyrics": {
    "$comment": "apiVersion 19: the lyrics provider capability. A plugin that declares it (alone is enough) exports lyrics({ title, artist, album?, durationMs?, ids? }) and answers { synced?: [{ ms, text }], plain?, label?, instrumental?, matchDurationMs? }; Kino asks it only while the person has the lyrics overlay on, never for 18+ items, and shows synced lines only when they plausibly fit the track (plausibleSlackMs, endSlackMs).",
    "apiVersion": 19,
    "capability": "lyrics",
    "export": "lyrics",
    "consentLine": "Recibirá el título y el artista de lo que escuchas para buscar la letra",
    "idKeys": ["isrc", "musicbrainz", "youtube"],
    "maxPlainChars": 20000,
    "maxSyncedLines": 800,
    "maxLineChars": 300,
    "maxAnswerChars": 102400,
    "plausibleSlackMs": 3000,
    "endSlackMs": 5000,
    "negativeCacheMs": 600000,
    "positiveCacheMs": 604800000
  },
  "kinoProgress": {
    "$comment": "apiVersion 22: the progress capability, declarative (no export), may sit beside a standalone set, and also valid in enhancements[\"22\"]. kino.progress.set({ id, fraction, title?, label?, labelEn?, poster?, resume?, done?, doneAt? }) tells Kino how far along the person is in something that is not a video (a chapter of a manga, a book, an episode of a podcast outside the player); get(id) answers the full entry, the same shape as a list entry, { id, title?, poster?, label?, labelEn?, resume?, fraction, done, updatedAtMs }, or null; clear(id) forgets it. Kino draws nothing from it (no Home row, no card): the plugin builds its own shelf from list(options?), which answers { id, fraction, title?, poster?, label?, labelEn?, resume?, done, updatedAtMs }[] most recently set first (limit 1..100 default 50, sinceMs a finite number >= 0); resume is the plugin's own opaque data (up to 1 KB) that Kino never reads. The elements are the plugin's own data about the person's own reading, kept apart from the library and the viewing statistics, so there is NO approval line (consentLine is null). Kino keeps the latest set per element in memory and writes to disk at most every writeEveryMs, and always when the screen closes or the app goes to the background; set calls past setsPerSecond are coalesced, never an error. A finished element (done: true, or fraction >= doneAt) stays in list with done: true; a later set with a lower fraction reopens it.",
    "apiVersion": 22,
    "capability": "progress",
    "consentLine": null,
    "functions": ["set", "get", "clear", "list"],
    "idPattern": "^[A-Za-z0-9._~-]{1,128}$",
    "maxLabelChars": 80,
    "maxResumeBytes": 1024,
    "doneAtDefault": 0.9,
    "maxElements": 500,
    "setsPerSecond": 20,
    "writeEveryMs": 2000,
    "listLimitMax": 100,
    "listLimitDefault": 50,
    "errorCodes": ["not_allowed", "bad_request", "too_large"]
  },
  "kinoDevice": {
    "$comment": "kino.device (Kino 0.9.55, every apiVersion): the UI Kino shows on this device, \"tv\" or \"phone\" (a tablet gets whatever Kino shows it, usually \"phone\"). Undefined on an older Kino. The Node kit says \"phone\" unless run.mjs gets --device tv or the environment has KINO_DEVICE=tv.",
    "values": ["phone", "tv"],
    "default": "phone",
    "kitEnv": "KINO_DEVICE",
    "kitFlag": "--device"
  },
  "kinoSyncSwitch": {
    "$comment": "kino.sync.active() and kino.sync.setActive(on) (Kino 0.9.78, additive, capability syncProvider): a sync provider reads and changes whether it is THIS device's provider (Kino keeps one at a time: on turns the current one off, off returns to Kino's local sync). Both resolve with a boolean, whether the plugin is the provider now. setActive(true) asks the person first in Kino's own dialog (the installed plugin's name, Kino's words): a decline resolves false and nothing changes; setActive(false) asks nothing and only acts when this plugin is the one on. Both changes only run from a call the person started with a tap (fromFunctions, and a screen's call only after their own press): the same rule as kino.qr.scan; active() may be read in any call. Never from a job. Not an apiVersion: feature-detect with typeof kino.sync.setActive === \"function\".",
    "fromApp": "0.9.78",
    "capability": "syncProvider",
    "errorCodes": ["busy", "timeout", "unavailable", "invalid_request", "not_allowed"],
    "timeoutMs": 120000,
    "fromFunctions": ["action", "panelAction", "screenEvent"]
  },
  "kinoSeed": {
    "$comment": "kino.seed(session) (Kino 0.9.55, every apiVersion): a plugin shares ONE anonymous, free guest session of its source so people in regions that cannot log in have live sessions to seed from. Best-effort and synchronous: it answers nothing and never throws into the plugin. Kino keeps only the allowed keys (each a short string or a finite number), drops the whole thing unless the three required ones are present and non-blank, and sends it to Kino's error board only when the plugin's telemetry consent is on. Absent on an older Kino: feature-detect with typeof kino.seed === \"function\". The Node kit has it, sends nothing and logs which keys Kino would keep.",
    "feature": "typeof kino.seed === \"function\"",
    "required": ["sn", "userId", "userToken"],
    "allowed": ["sn", "userId", "userToken", "jwtToken", "mintedAt", "customer", "activeTime", "availableTime"],
    "maxInputChars": 16384,
    "maxValueChars": 2048,
    "maxTotalChars": 8192,
    "needsTelemetryConsent": true
  },
  "kinoMeta": {
    "fromApp": "0.9.53",
    "featureDetect": "typeof kino.meta === \"function\"",
    "types": ["movie", "series"],
    "idKeys": ["imdb", "tmdb", "tvdb", "kitsu", "mal", "anilist"],
    "maxNumericId": 2147483647,
    "langPattern": "^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})?$",
    "maxRequestChars": 4096,
    "perMinute": 30,
    "timeoutMs": 8000,
    "providerTimeoutMs": 6000,
    "cacheTtlMs": 1800000,
    "maxCachedTitles": 200,
    "maxTmdbSeasons": 30,
    "maxAnswerChars": 1000000,
    "sources": ["tmdb", "anilist", "plugin"],
    "answerFields": ["title", "overview", "year", "poster", "backdrop", "logo", "genres", "runtimeMinutes", "tagline", "certification", "directors", "episodes", "ids", "ratings", "cast", "sources"],
    "notFrom": ["sign"],
    "noPluginsFrom": ["meta"],
    "errorCodes": ["invalid_request", "rate_limited", "not_allowed"],
    "byTitle": {
      "$comment": "Kino 0.9.55, apiVersion 9 (below it the prelude drops title and year, so the query needs ids; kino.meta.byTitle is absent): kino.meta({ type, title, year? }) instead of ids (ids win when both come). Kino searches TMDB (type's endpoint, es-MX, first page) and keeps a hit whose es-MX or original title equals the asked one once both are normalised (lowercase, no accents, punctuation as spaces); with a year, that exact year wins, else one within yearSlack. A tie (same title and year, or same title and no year) or no match answers null, never a guess. Then the answer is the ids lookup's, same shape, cache (keyed by type, normalised title and year), budget and timeout. year without title, a bad title or a bad year: invalid_request.",
      "fromApp": "0.9.55",
      "apiVersion": 9,
      "featureDetect": "kino.meta.byTitle === true",
      "titleMaxChars": 200, "minYear": 1870, "maxYear": 2100, "yearSlack": 1, "searchLanguage": "es-MX"
    }
  },
  "kinoNuvio": {
    "fromApp": "0.9.71",
    "comment": "Experiment (spec docs/superpowers/specs/2026-10-22-kino-nuvio-design.md): the plugin names its Nuvio repos (nuvioRepos); the app installs the scrapers it asks for exactly as the importer does (no screen) and the plugin asks them for streams. Nothing new runs: every scraper keeps the importer's hosts, torrent filter, request budget and 75 s resolve.",
    "capability": "nuvio",
    "manifestField": "nuvioRepos",
    "maxRepos": 4,
    "featureDetect": "typeof kino.nuvio === \"object\"",
    "consentLine": { "es": "Instala y usa scrapers de Nuvio del repositorio que indica para buscar enlaces", "en": "Installs and uses Nuvio scrapers from the repository it names to look for links" },
    "maxRequestChars": 4096,
    "maxScraperFilter": 64,
    "perMinute": 20,
    "scraperTimeoutMs": 60000,
    "maxScrapers": 12,
    "minScraperTimeoutMs": 2000,
    "maxOffered": 200,
    "maxUse": 12,
    "installTimeoutMs": 45000,
    "parallel": 4,
    "resolveTimeoutMs": 75000
  },
  "kinoTmdb": {
    "fromApp": "0.9.53",
    "featureDetect": "typeof kino.tmdb === \"function\"",
    "base": "https://api.themoviedb.org/3",
    "pathPrefixes": ["/discover", "/trending", "/search", "/movie", "/tv", "/find", "/genre", "/configuration", "/person", "/collection"],
    "pathPattern": "^/[A-Za-z0-9._/-]{1,255}$",
    "maxParams": 20,
    "paramKeyPattern": "^[A-Za-z0-9_.]{1,40}$",
    "maxParamValueChars": 500,
    "forbiddenParams": ["api_key", "session_id", "guest_session_id", "request_token", "access_token"],
    "perWindow": 40,
    "windowMs": 10000,
    "timeoutMs": 15000,
    "maxBodyBytes": 2097152,
    "cacheTtlMs": 600000,
    "cacheTtlByRouteMs": { "$comment": "KinoTmdbTtl.forPath: tv = a series by id, its seasons and episodes; stable = a movie, person or collection by id, any title's credits, images and the like, /find, /genre, /configuration; search = /search; lists = /trending, /discover and the lists; anything else, an empty answer or a 404: cacheTtlMs.", "tv": 43200000, "stable": 2592000000, "search": 86400000, "lists": 10800000 },
    "maxCachedEntries": 300,
    "maxCachedBodyChars": 524288,
    "$keyOrder": "Kino's own key first, behind its cache, in-flight dedup and the two kinoKey limits; the person's key (their Ajustes setting, else a Stremio addon's they agreed to) only when Kino's key gets one of personKeyOn; with neither, a cached copy up to staleMaxDays old, else rate_limited (unavailable when TMDB refused Kino's key). no_tmdb_key only on a build without a key of Kino's and a person without one. A key a plugin keeps in its own settings is never read.",
    "keyOrder": ["kino", "setting", "stremioAddon"],
    "kinoKeyPerWindow": 20,
    "kinoKeyGlobalPerWindow": 60,
    "personKeyOn": [401, 403, 429, "kinoKeyLimit"],
    "staleMaxDays": 7,
    "keyPatterns": { "v3": "^[0-9a-fA-F]{32}$", "v4": "^eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$" },
    "notFrom": ["sign"],
    "errorCodes": ["invalid_request", "rate_limited", "no_tmdb_key", "not_found", "too_large", "timeout", "network", "unavailable", "not_allowed"],
    "noKeyCode": "no_tmdb_key",
    "noKeyUserMessage": {
      "es": "Agrega tu llave de TMDB en Ajustes de todos los perfiles ▸ Llaves",
      "en": "Add your TMDB key in Settings for all profiles ▸ Keys"
    }
  },
  "kinoImage": {
    "$comment": "kino.image.thumbnail(url, { maxWidth?, maxBytes? }) (Kino 0.9.84, no new apiVersion): Kino downloads the picture under the CALLING plugin's own kino.fetch rules (its hosts, fetchHosts any, https only, never the home network, its request budget) and answers a JPEG as a data: address, so a sender passes only an address and the receiving plugin asks Kino for the small image. Kino decodes and re-encodes natively (a plugin's QuickJS cannot, and a library for it runs a 1 GB TV box out of memory). The decode is sampled (the whole picture is never held), a transparent PNG goes over white, quality steps 85, 75, 65, 55, 45 until it fits maxBytes. Allowed in every export that may use Kino's services (as kino.tmdb), a provider's proto_* call and a job included; not from sign.",
    "fromApp": "0.9.84",
    "featureDetect": "typeof kino.image === \"object\"",
    "defaultMaxWidth": 200,
    "minMaxWidth": 32,
    "maxMaxWidth": 400,
    "defaultMaxBytes": 16384,
    "minMaxBytes": 2048,
    "maxMaxBytes": 32768,
    "maxDownloadBytes": 5242880,
    "perMinute": 20,
    "maxUrlChars": 2048,
    "maxRequestChars": 4096,
    "output": "data:image/jpeg;base64,",
    "jpegQualities": [85, 75, 65, 55, 45],
    "inputFormats": ["jpeg", "png", "webp", "gif"],
    "notFrom": ["sign"],
    "errorCodes": ["bad_request", "not_found", "network", "timeout", "too_large", "not_image", "host_not_allowed", "rate_limited", "not_allowed"]
  },
  "kinoLibrary": {
    "$comment": "apiVersion 14, capability \"library\" (Task 8b): kino.library.watched({ limit?, kind?, sinceMs? }) and kino.library.saved({ limit?, kind? }) read what the ACTIVE profile watched and saved in Kino, newest first, one entry per title: { title, year?, kind, ids: { tmdb?, imdb? }, progress (0..1, watched only), watchedAtMs (rounded down to the day, UTC, watched only) }. Never a stream URL, a plugin ref, a library id, a play position in seconds, a profile name, anything of another profile, nor an 18+ title (always left out, even with the 18+ code unlocked). Declarative (no export); needs the person's approval at install and again on the update that adds it, always with the red consent line, the plugin's declared hosts listed beside it; revocable from the plugin's tab in Ajustes (switchLabel), after which every call rejects with permission_denied. Only inside a call the person started from fromFunctions; never in background, prewarm or sync calls. kino.library is an object on every apiVersion 14 runtime: feature-detect with featureDetect. sinceMs is rounded down to the day and compared with each title's rounded time, and progress is rounded to progressStep, so no finer time or position can be probed. 18+ fails closed: a title whose source plugin this device cannot place (uninstalled, only on another device, absent from the catalog) or that has no plugin source is left out. The revoke switch applies to the whole device, every profile, and the person's synced devices. Screen timer ticks (screen.every) count as the person's use while the screen is in front. The consent line, the host list and the switch are the safeguards, not a technical block: a plugin that can fetch can send what it read. Nothing is kept for the plugin: each answer is built per call.",
    "capability": "library",
    "apiVersion": 14,
    "featureDetect": "typeof kino.library === \"object\"",
    "functions": ["watched", "saved", "stats"],
    "kinds": ["movie", "series"],
    "idKeys": ["tmdb", "imdb"],
    "answerFields": ["title", "year", "kind", "ids", "progress", "watchedAtMs", "season", "episode"],
    "defaultLimit": 50,
    "maxLimit": 100,
    "perMinute": 30,
    "dayMs": 86400000,
    "maxRequestChars": 512,
    "maxTitleChars": 200,
    "progressStep": 0.01,
    "fromFunctions": ["screen", "screenEvent", "home", "section", "search"],
    "errorCodes": ["permission_denied", "rate_limited", "bad_request"],
    "consentLine": {
      "es": "Podrá leer lo que has visto y guardado en Kino, cuánto lo ves y a qué hora, y enviarlo a sus servicios",
      "en": "Can read what you have watched and saved in Kino, how much and at what time of day, and send it to its services"
    },
    "switchLabel": {
      "es": "Dejar que lea lo que he visto y guardado",
      "en": "Let it read what I watched and saved"
    },
    "stats": {
      "$comment": "apiVersion 17 (Tu mes en Kino), same capability and the same switch: kino.library.stats({ month? }) answers one month's aggregates of the ACTIVE profile with every device of the person summed: { month, estimated, seconds, secondsByKind: { movie, series, live }, secondsByBand: { morning, afternoon, night, lateNight } | null, titles, episodes, activeDays, longestStreakDays, top: [{ title, year?, kind, ids: { tmdb?, imdb? }, poster?, genres?, seconds }] }. Nothing finer than the month: no per-day series and no timestamps. month is 'yyyy-mm' (a real month; the current one when left out); no other option exists. A plugin that declares a lower apiVersion never gets kino.library.stats (the function is not there), and an update that raises a library plugin to this apiVersion asks the person again because the consent line grew. Never 18+: a title KNOWN to be 18+ at read time leaves the totals and the list; a title Kino merely cannot place now (its plugin is gone) stays in the totals but not in top (sourceIsAdult stays fail-closed for the names). Live channels are in the totals and never named. top holds at most topMax titles by seconds; poster and genres are only what Kino already holds for the item (no network call), each left out when Kino has none. A month before the counter existed is estimated from the play history (estimated: true, secondsByBand: null); the month of release mixes both (secondsByBand covers the counted part only). Shares the rate limit of watched and saved, answers from the same exports, jobs included.",
      "apiVersion": 17,
      "featureDetect": "typeof kino.library.stats === \"function\"",
      "monthPattern": "^\\d{4}-(0[1-9]|1[0-2])$",
      "defaultMonth": "current",
      "topMax": 20,
      "kinds": ["movie", "series", "live"],
      "bands": ["morning", "afternoon", "night", "lateNight"],
      "answerFields": ["month", "estimated", "seconds", "secondsByKind", "secondsByBand", "titles", "episodes", "activeDays", "longestStreakDays", "top"],
      "topFields": ["title", "year", "kind", "ids", "poster", "genres", "seconds"],
      "badRequestMessage": "kino.library.stats: month is \"yyyy-mm\" (the current month when left out); nothing else is an option"
    }
  },
  "kinoLivePanel": {
    "$comment": "Task 11, apiVersion 14: the player panel on an En vivo module channel. Kino's own General tab first (generalTabId; the favourite and the channel's brightness, answered by Kino, nothing stored), then the tabs of contributors whose manifest.panel.contributes.kinds holds kind, by the 8k rules (approved, usable, switched on, an 18+ contributor only while unlocked). Contributed tabs show only while the channel on screen was confirmed by its provider's own listing as not 18+, its provider is an installed plugin that is not 18+ and not a reserved provider (own: the person's M3U lists and channels; legacy). The context is exactly contextFields (screen mode adds screenContextAdds); channel is { provider, code, name }; no ref, title, ids, playing, position, duration, paused, seekStepMs, stats or player (notSent). Every player action of a tab on a live channel is dropped whole, logged playerDroppedLog; no playerEvent is sent on live. On a zap every open contributed tab is asked panel(context) again with the new channel (a render, never a press); the panel stays open across zaps. A plugin reads the channel only from the context: there is no kino.player.state().",
    "apiVersion": 14, "kind": "live", "generalTabId": "kino",
    "contextFields": ["kind", "live", "channel", "foreign", "source", "device", "lang", "tab", "values", "features"],
    "screenContextAdds": ["state", "size"],
    "channelFields": ["provider", "code", "name"],
    "notSent": ["ref", "title", "year", "ids", "playing", "positionMs", "durationMs", "paused", "seekStepMs", "stats", "player"],
    "reservedProviders": ["own", "legacy"],
    "playerDroppedLog": "panel: player actions do nothing on a live channel, dropped (live_channel)",
    "playerEvent": false, "rerenderOnZap": true
  },
  "playerSlot": {
    "$comment": "apiVersion 23, capability \"playerSlot\": a plugin draws up to maxElements small elements in the player (manifest \"slot\": { \"elements\": [ { \"id\", \"kind\", \"mode\" } ] }; the block and the capability need each other, below 23 both are unknown). Exports playerSlot (fills the elements) and playerSlotAction (answers a press). An element is text (at most textMaxLines lines), icon, image or button; mode overlay floats over the video, fixed holds a reserved place in the player and needs the person's approval (hasFixed; the capability is not in capabilities.needsApproval because an overlay-only slot needs none). A refreshMs below refreshMsFloor is raised to it. Ids are unique lowercase names.",
    "apiVersion": 23, "capability": "playerSlot", "field": "slot",
    "exports": { "slot": "playerSlot", "action": "playerSlotAction" },
    "maxElements": 3, "idPattern": "^[a-z][a-z0-9_-]{0,23}$",
    "kinds": ["text", "icon", "image", "button"], "modes": ["overlay", "fixed"],
    "textMaxLines": 2, "textMaxChars": 2000, "textSizes": ["small", "normal", "large", "xlarge"], "textWeights": ["extralight", "light", "normal", "medium", "semibold", "bold"], "textColorPattern": "^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$", "textMinAlpha": 128, "textMinContrast": 2,
    "placeLimits": { "left": [-400, 200], "top": [-40, 300] }, "labelMaxChars": 40, "refreshMsFloor": 2000, "refreshMsCeiling": 60000,
    "firstFrameRetryMs": 5000, "firstFrameRetries": 4,
    "openPanelKey": "openPanel", "actionAnswerKeys": ["openPanel", "player"],
    "liveDropped": ["seekToMs", "seekStepMs", "speed", "skip", "markers", "autoNext"],
    "bareContextFields": ["live", "foreign", "device", "lang", "features"],
    "fixedConsentLine": { "es": "Mostrará algo suyo de forma permanente en el reproductor mientras ves un video", "en": "Will keep something of its own on screen in the player while you watch a video" },
    "switchLabel": { "es": "Dejar que muestre algo en el reproductor", "en": "Let it show something in the player" },
    "notObjectMessage": "The \"slot\" field must be an object with an \"elements\" list",
    "needsCapabilityMessage": "The \"slot\" field needs the \"playerSlot\" capability",
    "capabilityNeedsMessage": "The \"playerSlot\" capability needs a \"slot\" block",
    "badElementsMessage": "The \"slot.elements\" field must list 1 to 3 elements",
    "badElementMessage": "Each \"slot\" element needs an \"id\" (lowercase letters, digits, - or _, up to 24), a \"kind\" (text, icon, image or button) and a \"mode\" (overlay or fixed)",
    "duplicateIdMessage": "The \"slot\" element ids must be unique"
  },
  "kinoPlayerControl": {
    "$comment": "apiVersion 14, capability \"playerControl\" (Task 8j), declarative (no export), never on its own. A player action may carry pause (true pauses, false resumes; anything else is dropped); it is a one-shot command, never stored. Each player action has an origin: press, change, submit (the person's, in the panel), refresh (a panel result's own player: its open, a tab, a refreshMs tick, a playerEvent answer's new panel; panel and screen-format results may carry player) and event (a playerEvent answer). Without the capability the plugin whose title plays (the owner) keeps the old rules: every field after a press, change or submit and in a playerEvent answer, except pause, which needs a press; a result's own player never counts. A panel contributed to another plugin's title (manifest.panel.contributes) keeps only seekToMs, only after a press in it. With the capability, approved by the person (consentLine, red, never auto-approved, a kit import starts it unticked) and not switched off (switchLabel, in the plugin's tab in Ajustes, device-wide and synced), every origin counts: the owner keeps every field, a contributed panel keeps contributedWithControl (the stored player properties stay the owner's; its speed is never stored and ends with the title; the person's own speed still wins). An action kept only thanks to the capability is controlled: never while Kino is not in front (the player screen stopped: the background, a Kino page over it), one of Kino's dialogs is up or the person is seeking (heldBy), only pause on a live stream (liveKeeps), at most perMinute in windowMs and one action of any field per minIntervalMs per plugin; and when its origin is not the person's (announcedOrigins) Kino shows a short notice naming the plugin (notice + noticeParts; a name that reads like Kino is qualified), which the plugin cannot word or suppress. Every action, controlled or not, shares one guard: one seek or pause per minIntervalMs per plugin (the panel and its playerEvent calls together). A pause of any origin, the person's press included, is dropped while the phone's player is held for a cast (castingDropsPause: Chromecast or DLNA; never routed to the TV) and when it asks for the state the video is already in (noopPauseDropped: no notice, no budget). A panel nested in an answer (an answer's or a playerEvent answer's panel) carries no player of its own (nestedPanelPlayer false). Without the capability the owner's change, submit and playerEvent actions keep the rules shipped at apiVersion 9 (every field but pause, unheld, unannounced); with it, an owner action that mixes those fields with pause from such an origin becomes wholly controlled. The rules are the same for every plugin and feature: Kino never knows why a plugin asks. Shared cases: plugins/sdk/test/player-control-cases.json.",
    "capability": "playerControl",
    "apiVersion": 14,
    "field": "pause",
    "origins": ["press", "change", "submit", "refresh", "event"],
    "personOrigins": ["press", "change", "submit"],
    "announcedOrigins": ["refresh", "event"],
    "ownerPauseFrom": ["press"],
    "ownerWithoutControlFrom": ["press", "change", "submit", "event"],
    "contributedWithoutControl": ["seekToMs"],
    "contributedWithControl": ["seekToMs", "pause", "speed"],
    "minIntervalMs": 1000,
    "perMinute": 30,
    "windowMs": 60000,
    "liveKeeps": ["pause"],
    "heldBy": ["background", "kinoDialog", "seeking"],
    "castingDropsPause": true,
    "noopPauseDropped": true,
    "nestedPanelPlayer": false,
    "notice": { "es": "{who}: {what}", "en": "{who}: {what}" },
    "noticeParts": {
      "es": { "paused": "pausado", "resumed": "reanudado", "movedTo": "movido a {time}", "speed": "velocidad {speed}" },
      "en": { "paused": "paused", "resumed": "resumed", "movedTo": "moved to {time}", "speed": "speed {speed}" }
    },
    "consentLine": {
      "es": "Podrá pausar, reanudar y mover tu video por sí solo",
      "en": "Can pause, resume and move your video by itself"
    },
    "switchLabel": {
      "es": "Dejar que pause y mueva mi video",
      "en": "Let it pause and move my video"
    }
  },
  "kinoRoom": {
    "$comment": "apiVersion 14, capability \"room\" (Task 8l), declarative (no export), never on its own. kino.room is a short-lived mailbox hosted on the person's own device and reached from the Internet through the same Cloudflare quick tunnel Kino opens for \"Recibir configuración\": no external service, no Kino server. open({ ttlMin?, max?, name?, code?, codeDigits? }) -> { code, words, expiresAtMs } opens the tunnel and the mailbox; the code is codeDigits.default digits unless the plugin asks for codeDigits.min to codeDigits.max (the room's only secret; words are public; see codeDigits for what a short code costs), shown by the plugin, typed or carried by the person; spaces and hyphens are ignored. join({ words, code, name? }) -> { handle, memberId, host: { name }, expiresAtMs }. send(payload, { to?, session? }): payload is a JSON object of at most maxPayloadBytes UTF-8 bytes as the plugin's JSON text and maxPayloadDepth levels deep (the object itself is 1); at most perSecond messages a second, perMinute and bytesPerMinute a minute per member (checked by the sender's Kino and again by the host). The host may send to everyone (to absent or \"all\") or one memberId; a guest writes to the host (to absent or hostId) or to \"all\" through the host, never to another member directly. inbox({ since?, limit?, session? }) -> { events: [{ seq, from, kind, payload?, name? }], last, more, reachable }: a bounded mailbox per member (mailboxEvents, mailboxMs), seq only grows, last is the seq to pass as since next time; a guest's inbox asks the host at most every pollIntervalMs and reachable says whether it answered. members({ session? }) -> [{ memberId, name, host }], never an address. close({ session? }); state() -> { role: host|guest|none, joined: [{ handle, memberId, host, expiresAtMs, reachable }], hosted: { code, words, expiresAtMs, members } | null }. Sessions: at most maxJoined joined and maxHosted hosted per device, and at most maxSlotsPerPlugin of them for one plugin (room_busy); session is hostedSession or a joined handle, default the first joined, else the hosted one; a join with the code of a joined session replaces it. open({ code }) is refused unless the plugin is in a room with that code now or opened it itself (a backup endpoint with its own words; the plugin decides who opens one and publishes its words in ordinary messages; failover is the plugin's). Calls: open and join only from openFrom (the person's own action: a screen timer tick or a panel refresh never), send/inbox/members from trafficFrom (ticks included), all with Kino in front; close and state from any live call; never a background call. Every request is sealed (scrypt N=8192 r=8 of the code salted with the words, AES-256-GCM plus HMAC-SHA256, per-member keys, growing sequence, answers bound to their request): a stranger can only guess online, but the code protects against casual access, not against the TLS-terminating tunnel provider targeting a room (it could crack a captured join offline in hundreds of GPU-days (about 400 on average on one high-end GPU) and then read it; no forward secrecy). Requests no member key vouches for share one small budget (429 past it) and never touch a member's; a payload nested past maxPayloadDepth is refused before parsing. A wrong code is refused with nothing keyed; after joinFailuresBeforeLock wrong codes an endpoint refuses joins for lockMs, doubling up to maxLockMs (rate_limited), and after maxFailedJoins wrong codes in its whole life (lockouts included, whoever sends them) it closes itself; Kino tells the person, and the plugin's next calls get room_closed with Kino's userMessage. Members a host has not heard from for idleMs are dropped (leave). The tunnel and the endpoint exist only while a room is open: closed by close(), the TTL, the plugin removed, disabled or switched off (switchLabel, device-wide, synced), the owner's screens switch, Kino in the background for backgroundCloseMinutes (while a room is hosted Android keeps it alive with a foreground service and a visible notification \u00abSala abierta \u00b7 N personas\u00bb with \u00abCerrar sala\u00bb; Android only), or the app ending. A failure opening the route or reaching a room is room_unreachable with Kino's own userMessage (no internet, a network that blocks it, Cloudflare's rate limit). Payloads are opaque JSON, re-serialised by Kino, never executed, never written to disk. Shared cases: plugins/sdk/test/room-cases.json.",
    "capability": "room",
    "apiVersion": 14,
    "featureDetect": "typeof kino.room === \"object\"",
    "functions": ["open", "join", "send", "inbox", "members", "close", "state"],
    "eventKinds": ["msg", "join", "leave", "closed"],
    "hostId": "host",
    "hostedSession": "hosted",
    "codeDigits": { "$comment": "Task 8w: open({ codeDigits }) asks for a shorter numeric code; join takes any length in range (the host chose it). A short code keeps strangers out only because the words cannot be guessed and the room closes itself after limits.maxFailedJoins wrong codes; whoever captures the traffic and knows the words (the tunnel provider) recovers a 4-digit code offline in milliseconds, so such a room is not private from the provider. The default 12 makes that attack expensive, not impossible.", "min": 4, "max": 12, "default": 12 },
    "openFrom": ["screenEvent", "panelAction"],
    "trafficFrom": ["screen", "screenEvent", "panel", "panelAction", "playerEvent"],
    "limits": {
      "minTtlMin": 10, "maxTtlMin": 240, "defaultTtlMin": 120,
      "minMembers": 2, "maxMembers": 8, "defaultMembers": 6,
      "maxHostNameChars": 40, "maxMemberNameChars": 24, "maxFailedJoins": 30,
      "maxPayloadBytes": 8192, "maxPayloadDepth": 4,
      "perSecond": 5, "perMinute": 100, "bytesPerMinute": 262144,
      "mailboxEvents": 200, "mailboxMs": 900000, "defaultInboxLimit": 50, "maxInboxLimit": 50,
      "maxJoined": 2, "maxHosted": 1, "maxSlotsPerPlugin": 2,
      "joinFailuresBeforeLock": 5, "lockMs": 60000, "maxLockMs": 1800000,
      "idleMs": 120000, "backgroundCloseMinutes": 30, "pollIntervalMs": 1000,
      "maxRequestChars": 65536
    },
    "errorCodes": ["room_denied", "room_closed", "room_full", "room_unreachable", "room_busy", "rate_limited", "permission_denied", "bad_request"],
    "consentLine": {
      "es": "Podrá abrir una sala a la que se entra por internet a través de este aparato, y enviar los mensajes de la sala a quienes entren",
      "en": "Can open a room that people reach over the Internet through this device, and send the room's messages to whoever joins"
    },
    "switchLabel": {
      "es": "Dejar que abra salas por internet",
      "en": "Let it open rooms over the Internet"
    }
  },
  "kinoJobs": {
    "$comment": "apiVersion 14, capability \"schedule\" (Task 8q): Kino's job scheduler, the kernel of a plugin's background work (owner 2026-10-26: \"planificador en la app, tipo cron de Laravel\"). The manifest lists jobs (manifest): 1 to maxJobs, each { id (idPattern), label: { es, en? } (1 to labelMaxChars each once control and bidirectional characters are scrubbed), everyMin (one of everyOptions), everyOptions (1 to maxOptions different whole minutes from minEveryMin, WorkManager's floor, to maxEveryMin), runOn? (runOnValues, default runOnDefault; badRunOn otherwise) }; other keys of a job are ignored. The capability and the jobs need each other; the plugin exports job(ctx) with ctx = { id, reason: scheduled|manual, lastRunMs (null before the first run), attempt (1 + the failures in a row) }. The answer is never read (outputIgnored): what the plugin wants kept goes to kino.storage, which its screens read when they open (stale-while-revalidate). Kino shows nothing of a job by itself. A job may use availableApis and read readOnly only: an allow-list, every other API (forbiddenApis and any added later) answers not_allowed (logged), and no UI, screen, panel, go, toast, player control or room can come out of a job (nothing it returns is read). kino.library answers a job only with the plugin's own library approval (the same 18+ rule, rounding and rate); kino.ai.ask (Task 8r) only with its own ai approval, each ask one of the run's maxFetches requests. One run: at most runTimeoutMs; maxFetches requests (the next answers rate_limited), made one at a time; maxResponseBytes of answer bodies, each body read with a cap of what is left (an answer that would cross it is refused with too_large, never handed over); maxStorageWriteBytes written to kino.storage (UTF-8 bytes of keys and values; the next set throws too_large); a cap crossed cuts the run and counts as a failure. A failure is worded by Kino only: network only when kino.fetch itself failed to reach a site in that run. Per plugin at most maxRunsPerDay runs a day (UTC), all its jobs together. A failure waits backoffBaseMin, doubling up to backoffMaxMin, before the next scheduled run; failuresToPause in a row pause the job until the person switches it off and on, or a manual run succeeds. A run never starts while the plugin's own screen, panel or catalog call is in progress (it waits up to foregroundWaitMs, then gives way). Approval: consentLine in red at install and on the update that adds it, never auto-approved, unticked in a kit import; revocable from the plugin's tab in Ajustes (switchLabel, device-wide and synced): off cancels its work at once and refuses even a manual run. Each job starts OFF (opt-in) at everyMin, and OFF again after any gap in its approval on the device (uninstalled, an update without schedule or without that job, a reinstall); an update never makes a switched-on job run more often than before: the person's choice while it is an option, else the nearest option at least as slow as both the new everyMin and the period it ran at; when no option is that slow the job is switched OFF (stamped, so it syncs) and its row asks the person to choose again. Once a run is over (it answered or was cut), every API refuses whatever its evaluation still tries; Kino's own rows in the plugin's tab: the job's switch, its frequency (only everyOptions), \"Solo con Wi-Fi\" (per plugin, on by default: an unmetered network), the last run and \"Ejecutar ahora\" (reason manual, the same caps). Works also need a network and the battery not low, and stop with the plugin disabled, removed or updated (a new work then), the job switched off or paused, and the owner's screens kill switch (screensEnabled is the one shared switch for plugin screens, rooms and jobs). fetch keeps the plugin's declared hosts and every fetch rule and quota; sealed values keep their rules. The person's choices (on, frequency, Wi-Fi only) sync between their devices. runOn \"any\" (the default): each device that has the plugin runs its own job, for its own kino.storage. runOn \"preferPhone\" (Task 8q-2, owner: the phone does the work and what syncs is the result): ONE of the person's linked devices runs it, and the plugin shares the result with kino.shared (kinoShared). Each device decides by itself from a synced record of the person's devices (election): a device is a candidate when the job is approved, on, not paused and not switched off there, and its last SUCCESSFUL run of the job is within freshPeriods times the job's period (being seen is not enough: a phone whose work never fires, on mobile data with \"Solo con Wi-Fi\" or force-stopped, loses the job; a time more than maxSkewMs ahead of the reader's clock is not believed); the person's choice whereLabel (\"Este aparato\" names one device; default: the phone if linked) first, then a candidate phone (the smallest device id), else the smallest id of the others (in practice: the TV that has the plugin runs it itself). A TV never runs it while a fresh phone can. A firing on a device that is not the runner skips at once (no runtime, no network, never a failure) and keeps its work, so the TV takes over when the phone stops (no linked phone, no successful run on the phone for freshPeriods periods, its job paused or switched off there); a rare overlap runs it twice, harmless with last-writer-wins results. \"Ejecutar ahora\" runs on the device where it is pressed. A plugin may read kino.device (\"tv\" or \"phone\", readOnly) to pick a lighter batch on a TV (Kino enforces nothing extra; the job caps apply). Kino's rows for such a job add whereLabel with its two choices and the device that ran it last (lastRunLabel). Task 18 (G2, apiVersion stays 14): kino.seed is among availableApis, under exactly its gate everywhere (sent only while the plugin's telemetry consent is on, cleaned to the anonymous-seed allow-list, capped per process; contract.kinoSeed). A job may say enabledBy (enabledByField): the key of one of the plugin's own toggle settings (else badEnabledBy refuses the manifest, or drops an enhancement's block). That setting, in the profile in use with its default, is the person's on/off for the job: on while the setting is on and the job's row in Ajustes holds no OFF of the person's (the row may still switch it off, and its OFF wins until the person switches the row on again); the setting off is always off. Kino's row says which setting drives it (followsSettingLabel). Everything else is unchanged: the consent line, the schedule switch, the frequency, Solo con Wi-Fi, the caps, the pause after failures, the kill switch. apiVersion 17 (Tu mes en Kino): kino.tmdb is among availableApis, each call one of the run's requests. A run of a plugin at apiVersion 17 or later whose ai capability is approved and switched on gets aiRunTimeoutMs and aiMaxRequests instead of runTimeoutMs and maxFetches; every other cap, the runs a day and WorkManager's limits stand. A job may say perProfile: true (perProfileField, apiVersion 17, always with runOn any; else perProfileNeedsAny, perProfileApi or badPerProfile refuses the manifest): Kino then runs job(ctx) once for each profile of the device with the plugin enabled, each as its own run: its own caps, its own lastRunMs, attempt, backoff and pause, one of maxRunsPerDay, oldest result first, one profile at a time, a person using the plugin first (each turn has the usual wait, then gives way). What does not fit the worker's window (perProfileWindowMs) continues next period. A failure pauses that profile's turn, not the others'. Such a job may not declare enabledBy (perProfileEnabledBy): consent is Kino's own device-wide job row, off by default and synced, which covers every profile of the device and linked devices. A screen turns it on with the answer enableJob: \"<jobId>\" (enableJobField, enableJobApiVersion), only after a person's tap (dropped from open, ticks, onClose, a load-more, a change and panels, and more than 5 s after the tap), only for a job of that plugin without enabledBy with its approvals in place; no answer turns it off, and a row the person switched off themselves stays off (dropped, logged, Kino's own toast points to the plugin's tab). kino.jobOn(\"<jobId>\") answers a boolean in a screen or screenEvent call, so the plugin knows whether to ask; it is in forbiddenApis for a job. Each profile has Kino's own row includeProfileLabel, on by default, kept per profile and synced on its own clock: a left-out profile gets no turn and its database is not opened; each key has its own clock, a tie stays left out; a restore may add to the left-out set, never remove from it. Ejecutar ahora runs the profile in use even when it is left out. ctx is unchanged: the plugin gets no profile id or name. The active profile never changes. In a turn of a profile that is not the one in use, the runtime is opened for that turn alone and closed after it (nothing in memory crosses): kino.library, kino.shared, kino.storage, kino.config and kino.cookies, kino.fetch's cookie jar included, are that profile's; kino.secret is the plugin's sealed values, nobody's; kino.ai and kino.tmdb hold no person's data; perProfileRefusedApis have no per-profile home and answer not_allowed; kino.log stays in logcat, out of the plugin's Registro, reports and telemetry; kino.tmdb uses Kino's key only; kino.lang and typed servers are that profile's; outside its call such a runtime only reads. A profile deleted during a turn refuses every API and leaves no record. Ejecutar ahora runs the profile in use only. Approval: consentLinePerProfile replaces consentLine, and an update that adds perProfile asks again.",
    "capability": "schedule",
    "apiVersion": 14,
    "export": "job",
    "manifest": {
      "field": "jobs",
      "maxJobs": 3,
      "idPattern": "^[a-z0-9-]{1,24}$",
      "labelMaxChars": 40,
      "maxOptions": 6,
      "minEveryMin": 15,
      "maxEveryMin": 1440,
      "jobsNeedsCapability": "The \"jobs\" field needs the \"schedule\" capability",
      "scheduleNeedsJobs": "The \"schedule\" capability needs a \"jobs\" list with 1 to 3 jobs",
      "jobsBad": "The \"jobs\" field must be a list of 1 to 3 jobs",
      "badId": "Each job needs an \"id\" of 1 to 24 characters: a-z, 0-9 and -",
      "duplicateId": "Two jobs have the same \"id\"",
      "badLabel": "Each job needs a \"label\" object whose \"es\" is 1 to 40 characters (\"en\" optional, the same limit)",
      "badOptions": "Each job's \"everyOptions\" must list 1 to 6 different whole numbers of minutes from 15 to 1440",
      "badEvery": "Each job's \"everyMin\" must be one of its \"everyOptions\"",
      "runOnValues": ["any", "preferPhone"],
      "runOnDefault": "any",
      "badRunOn": "Each job's \"runOn\" must be \"any\" or \"preferPhone\"",
      "enabledByField": "enabledBy",
      "badEnabledBy": "Each job's \"enabledBy\" must name one of the plugin's toggle settings",
      "perProfileField": "perProfile",
      "perProfileApiVersion": 17,
      "perProfileNeedsAny": "A \"perProfile\" job must use \"runOn\": \"any\"",
      "perProfileApi": "A job's \"perProfile\" needs apiVersion 17",
      "badPerProfile": "Each job's \"perProfile\" must be true or false",
      "perProfileEnabledBy": "A \"perProfile\" job can't use \"enabledBy\": Kino's own row is its consent",
      "enableJobField": "enableJob",
      "enableJobApiVersion": 17
    },
    "election": {
      "freshPeriods": 2,
      "heartbeatMs": 600000,
      "maxSkewMs": 300000,
      "whereLabel": { "es": "Hacer el trabajo en", "en": "Do the work on" },
      "whereChoices": { "es": ["Este aparato", "El celular si está vinculado"], "en": ["This device", "The phone, if linked"] },
      "lastRunLabel": { "es": "Última ejecución en: {device}", "en": "Last run on: {device}" }
    },
    "followsSettingLabel": { "es": "Lo enciende y lo apaga el ajuste «{label}» del plugin; aquí también puedes apagarlo.", "en": "The plugin's “{label}” setting turns it on and off; you can also switch it off here." },
    "contextFields": ["id", "reason", "lastRunMs", "attempt"],
    "reasons": ["scheduled", "manual"],
    "outputIgnored": true,
    "availableApis": ["kino.fetch", "kino.storage", "kino.log", "kino.library", "kino.config", "kino.cookies", "kino.crypto", "kino.sleep", "kino.html", "kino.secret", "kino.error", "kino.rank", "kino.ai", "kino.shared", "kino.seed", "kino.notifications", "kino.coins", "kino.tmdb", "kino.progress"],
    "perProfileRefusedApis": ["kino.notifications", "kino.coins", "kino.seed", "kino.progress"],
    "readOnly": ["kino.apiVersion", "kino.appVersion", "kino.lang", "kino.device", "kino.fetchAnyHost", "kino.screen"],
    "forbiddenApis": ["kino.room", "kino.qr", "kino.browser", "kino.ws", "kino.meta", "kino.nuvio", "kino.catalog", "kino.sync", "kino.cloudstream", "kino.identity", "kino.vault", "kino.jobOn", "kino.plugins", "kino.visualBrowser"],
    "limits": {
      "runTimeoutMs": 20000, "maxFetches": 10, "maxResponseBytes": 2097152, "maxStorageWriteBytes": 262144,
      "maxRunsPerDay": 96, "failuresToPause": 3, "backoffBaseMin": 15, "backoffMaxMin": 360, "foregroundWaitMs": 30000,
      "aiRunTimeoutMs": 60000, "aiMaxRequests": 20, "aiApiVersion": 17, "perProfileWindowMs": 540000
    },
    "failureCodes": ["timeout", "cap_fetches", "cap_bytes", "cap_storage", "network", "plugin_error"],
    "defaults": { "jobOn": false, "wifiOnly": true },
    "consentLine": {
      "es": "Podrá ejecutarse en segundo plano cada cierto tiempo para actualizar sus datos, usando internet y batería",
      "en": "Can run in the background every so often to refresh its data, using your internet and battery"
    },
    "includeProfileLabel": { "es": "Incluir este perfil", "en": "Include this profile" },
    "consentLinePerProfile": {
      "es": "Podrá ejecutarse en segundo plano cada cierto tiempo, para cada perfil de este aparato y de tus aparatos vinculados que tenga el plugin activado, usando internet y batería",
      "en": "Can run in the background every so often, for every profile on this device and your linked devices with the plugin turned on, using your internet and battery"
    },
    "switchLabel": {
      "es": "Dejar que trabaje en segundo plano",
      "en": "Let it work in the background"
    }
  },
  "kinoAi": {
    "$comment": "apiVersion 14, capability \"ai\" (Task 8r), declarative (no export), never on its own. kino.ai.ask({ prompt, system?, json?, maxChars? }) sends one short text to Kino's text AI (Kilo's free models, the same fixed destination as Kino's own assistant; no key, no server of Kino's) and answers { ok: true, text, model } or { ok: false, error, message }: it never throws (errorCodes; message is Kino's English detail for the author). One-shot: no conversation memory, no streaming, no tools, no images, no files; Kino adds no persona and keeps nothing (logs carry sizes and codes only, never the prompt, the system text or the reply). prompt is a non-empty string of at most maxPromptBytes UTF-8 bytes, system at most maxSystemBytes (too_large past either); maxChars is a whole number from 1 to maxChars (default defaultMaxChars): the reply is cut there. json: true only ASKS the model for JSON (Kino adds jsonInstruction to the system text); the reply comes back as the model wrote it, parseable or not: the plugin parses and validates it (Kino never trusts model output). The model and endpoint are Kino's: the plugin sees only the name of the model that answered (model), never an address, a key or a header. Calls: from fromFunctions only after the person's own action (the same rule as kino.qr.scan: a settings action, a panelAction, or a screenEvent that follows the person's tap or submit; never a screen's open, a timer tick, a load-more, a change, a playerEvent, Home, search or play), and from the plugin's scheduled job (fromJob, Task 8q), where each ask is one of the run's maxFetches requests and is refused once the run is over. Device-wide, over every plugin together: devicePerDay asks a day and deviceMaxInFlight waiting at once (rate_limited past either; the stricter of these and the plugin's own limits applies), so plugins never starve Kino's own assistant, which shares Kilo's anonymous quota. Limits per plugin: perMinute asks in any 60 s (a strict sliding window), perDay a day (UTC; counted on the device), maxInFlight at a time (the next is rate_limited, never queued), timeoutMs to answer, the model list included (timeout; the call's own clock stops meanwhile, a job's does not). A plugin screen's event is still bounded by the session's own 60 s wall clock: ask once per event and batch items into one prompt. unavailable: no model could answer (no internet, every free model busy). refused: anything else (not approved, switched off, the plugin disabled, the owner's switch, the wrong origin, a malformed request). Approval: consentLine in red at install and on the update that adds it, never auto-approved, unticked in a kit import; revocable from the plugin's tab in Ajustes (switchLabel, device-wide and synced): every ask is then refused. What the plugin sends leaves the device: its own UI must tell the person what it sends. The reply is untrusted data written by a model that read text the plugin chose (titles from the web, the person's words): a prompt can be injected into it, so never execute it, never follow instructions found in it, never treat it as markup or as a URL to open without checking it, and validate every field (an id, a category) against what you sent. Kino never shows a reply by itself; the plugin's own screen shows what it decides. Shared cases: plugins/sdk/test/ai-cases.json.",
    "capability": "ai",
    "apiVersion": 14,
    "featureDetect": "typeof kino.ai === \"object\"",
    "functions": ["ask"],
    "answerFields": ["text", "model"],
    "fromFunctions": ["action", "panelAction", "screenEvent"],
    "fromJob": "job",
    "limits": {
      "maxPromptBytes": 8192, "maxSystemBytes": 2048, "maxChars": 4096, "defaultMaxChars": 2048,
      "perMinute": 10, "perDay": 100, "maxInFlight": 1, "timeoutMs": 20000, "maxRequestChars": 65536,
      "devicePerDay": 300, "deviceMaxInFlight": 2
    },
    "jsonInstruction": "Reply with valid JSON only: nothing before or after it, without explanations or code fences.",
    "errorCodes": ["unavailable", "rate_limited", "too_large", "timeout", "refused"],
    "consentLine": {
      "es": "Podrá enviar texto a un servicio de IA de terceros (Kilo) para que lo resuma o clasifique; lo que envíe sale de tu aparato",
      "en": "Can send text to a third-party AI service (Kilo) to have it summarized or classified; what it sends leaves your device"
    },
    "switchLabel": {
      "es": "Dejar que use la IA de texto",
      "en": "Let it use the text AI"
    }
  },
  "kinoIdentity": {
    "$comment": "apiVersion 15, capability \"identity\" (Kino Social), declarative (no export), never on its own, not enhanceable (the plugin declares apiVersion 15 itself). kino.identity.telegram({ challenge? }) answers { id } (plus token only for a plugin by one of tokenAuthors, see token) and, with a challenge, also { deviceKey, signature, author, codeHash }; it rejects with errorCodes. id is a pseudonym of the person for THIS plugin: the first pseudonymHexChars lowercase hex characters of SHA-256 over UTF-8 pseudonymPrefix + pluginId + \"\\n\" + the Telegram account id (decimal); stable for the plugin on every install of every device of the person, different between plugins; never the Telegram id nor the username, which never reach the plugin. token is the gate token Kino's bot signed for this device (base64url(payload).base64url(Ed25519 signature)): it still names the Telegram account, so the plugin's server can verify it with the bot's public key (a per-audience token from the bot is the future fix); treat it as a credential, never log or show it. Only a plugin whose pinned author key's fingerprint (see author) is one of tokenAuthors receives the token: 07DA-B67F-2ACF-B4D3 is Kino's own, E04E-EA25-1A34-290E the xuper-plugin author's (owner decision 2026-11-17, from Kino 0.9.88; an older Kino gives the token to 07DA-B67F-2ACF-B4D3 only); every key listed is trusted like Kino's own, since the token names the account. Any other author (a community plugin) is approved and gets the id and, with a challenge, the attestation, but never the token; a debug build of Kino gives the token to any author, for development. challenge (challengePattern) is the plugin server's nonce: Kino then signs, with a P-256 key of its own for this plugin on this install (non-exportable, Android Keystore, created on first use, never synced nor backed up; a reinstall makes a new one), the UTF-8 bytes signaturePrefix + pluginId + \"\\n\" + challenge + \"\\n\" + author + \"\\n\" + codeHash (SHA256withECDSA, DER): deviceKey is the public key (X.509 SubjectPublicKeyInfo DER) and signature the signature, both base64url without padding. author is the fingerprint of the author key Kino verified and pinned at install for a signed plugin (manifest.signature: the first 8 bytes of SHA-256 of the Ed25519 public key, upper-case hex in four groups of four joined by \"-\", e.g. 07DA-B67F-2ACF-B4D3), \"\" for an unsigned plugin; codeHash the lowercase hex SHA-256 of the installed entry file Kino runs (the runtime refuses a script whose bytes differ). Both come from Kino's own record of the installed plugin, never from the plugin: a server can require its own author fingerprint, so a modified copy cannot log in. Keys are per plugin, so two plugins cannot correlate the person by key. Calls: only inside a call the person started from fromFunctions (a screen's open and events, a panel's action), never a screen timer's tick, a job (forbidden there), Home, search, play or sync; perMinute per plugin (rate_limited). permission_denied: not approved, switched off, the plugin disabled, the owner's switch, the wrong origin. not_available: this device holds no token, or one issued before the bot signed the account (it must validate again), or the key could not sign. bad_request: options not an object, an unknown key, a challenge that is not challengePattern. Approval: consentLine in red at install and on the update that adds it, never auto-approved, unticked in a kit import; revocable from the plugin's tab in Ajustes (switchLabel, device-wide and synced).",
    "capability": "identity",
    "apiVersion": 15,
    "featureDetect": "typeof kino.identity === \"object\"",
    "functions": ["telegram"],
    "answerFields": ["id", "token"],
    "challengeFields": ["deviceKey", "signature", "author", "codeHash"],
    "fromFunctions": ["screen", "screenEvent", "panelAction"],
    "perMinute": 10,
    "maxRequestChars": 512,
    "challengePattern": "^[A-Za-z0-9_-]{16,128}$",
    "pseudonymPrefix": "kino-identity-v1\n",
    "pseudonymHexChars": 32,
    "signaturePrefix": "kino-identity-v2\n",
    "signatureAlgorithm": "SHA256withECDSA",
    "keyCurve": "P-256",
    "authorPattern": "^([0-9A-F]{4}(-[0-9A-F]{4}){3})?$",
    "tokenAuthors": ["07DA-B67F-2ACF-B4D3", "E04E-EA25-1A34-290E"],
    "badRequestMessage": "kino.identity.telegram takes { challenge?: 16 to 128 letters, digits, _ or - }",
    "errorCodes": ["permission_denied", "not_available", "rate_limited", "bad_request"],
    "consentLine": {
      "es": "Podrá saber tu usuario de Telegram y enviarlo a sus servicios",
      "en": "Can know your Telegram user and send it to its services"
    },
    "switchLabel": {
      "es": "Dejar que sepa mi usuario de Telegram",
      "en": "Let it know my Telegram user"
    }
  },
  "kinoVault": {
    "$comment": "apiVersion 28 (Kino 0.9.90), capability \"vault\", declarative (no export), REQUIRES \"identity\" (see capabilities.requires), not enhanceable (the plugin declares apiVersion 28 itself). kino.vault.get() returns the plugin's OWN sealed secret from the Kino secrets vault: whatever JSON its author registered for it (an API base, request-signing params, keys), resolved by (pluginId, author). It rejects with errorCodes. Kino runs the WHOLE exchange from inside with the same machinery as kinoIdentity: it mints a challenge at its own secrets service, attests THIS plugin (the per-plugin pseudonym id, the device-key signature over signaturePrefix + pluginId + challenge + author + codeHash, the author fingerprint and codeHash, and — for a tokenAuthors author — the gate token, which lets the vault verify group membership live), and reads the secret the vault resolves for that (pluginId, author). The plugin never sees the vault's address, the challenge, nor the pluginId/author the vault resolves by: Kino fills both from its own install record, so a plugin can only ever read ITS OWN secret, and a copy re-signed with a different key resolves a different (missing) scope. Because the secret read is gated by who the person is on Telegram exactly as identity is, vault rides on identity's red consentLine and switch and adds no approval line of its own. Calls: only inside a call the person started from fromFunctions (a screen's open and events, a panel's action), never a screen timer's tick, a job (forbidden there), Home, search, play or sync; perMinute per plugin (rate_limited). permission_denied: not approved, identity switched off, the plugin disabled, the wrong origin. not_member: the person is not in the Kino group, or the plugin's scope does not match. not_found: no secret is registered for this plugin. not_available: this device holds no Telegram token yet, the key could not sign, or the secrets service could not be reached. unavailable: the service answered an unexpected status or an unreadable body. bad_request: an argument was passed (get takes none).",
    "capability": "vault",
    "apiVersion": 28,
    "requires": "identity",
    "featureDetect": "typeof kino.vault === \"object\"",
    "functions": ["get"],
    "fromFunctions": ["screen", "screenEvent", "panelAction"],
    "perMinute": 6,
    "maxRequestChars": 64,
    "badRequestMessage": "kino.vault.get takes no arguments",
    "errorCodes": ["permission_denied", "not_member", "not_found", "rate_limited", "unavailable", "not_available", "bad_request"]
  },
  "kinoNotifications": {
    "$comment": "apiVersion 15, capability \"notifications\" (Kino Social), declarative (no export), never on its own, not enhanceable. kino.notifications.post({ id, title, titleEn?, text?, textEn?, go? }) leaves a short notice in the Home bell and kino.notifications.clear(id?) removes one (or every notice of the plugin); both resolve undefined or reject with errorCodes. id (idPattern) replaces an earlier notice with the same id, unread again. title (1 to maxTitleChars) and text (at most maxTextChars) are plain: one line, control and direction characters removed (go.copy's scrub); titleEn/textEn are shown in English. go is only { screen: { route?, args? } } (this plugin's own screen, read like a screen's go.screen), { title: { ref, kind, id?, title? } } or { titleByIds: {...} } (the screen's rules); anything else drops go (never the notice, logged) and a tap opens the plugin's screen root; a title or titleByIds go also opens the root today (the bell has no screen of the plugin's to follow it from). Calls: from fromFunctions (the screen, its events, the plugin's scheduled job, where it is on the job allow-list and counts against nothing else). Limits per plugin: perHour posts in any hour (rate_limited), maxKept notices kept (the oldest dropped), keepDays days. The bell's badge counts the unread notices plus the plugin updates waiting for approval; the bell lists them newest first with the plugin's icon and name, the title, the text and how long ago; a tap follows go and marks it read; opening the list marks all read. An 18+ plugin's notices show only while 18+ is unlocked. Not synced: each device keeps its own notices (each device's job fetches its own; the plugin's server holds what was read). Approval: consentLine as a plain line (not red) at install and on the update that adds it; revocable from the plugin's tab in Ajustes (switchLabel, device-wide and synced): its notices leave the bell and every call rejects with permission_denied. The kit keeps what was posted in <folder>/.kino-notices.json: node sdk/run.mjs <folder> notifications.",
    "capability": "notifications",
    "apiVersion": 15,
    "featureDetect": "typeof kino.notifications === \"object\"",
    "functions": ["post", "clear"],
    "fields": ["id", "title", "titleEn", "text", "textEn", "go"],
    "goKeys": ["screen", "title", "titleByIds"],
    "fromFunctions": ["screen", "screenEvent", "job"],
    "idPattern": "^[A-Za-z0-9._-]{1,64}$",
    "limits": { "maxTitleChars": 80, "maxTextChars": 160, "perHour": 20, "maxKept": 30, "keepDays": 30, "maxRequestChars": 8192 },
    "errorCodes": ["permission_denied", "rate_limited", "bad_request"],
    "consentLine": {
      "es": "Podrá mostrarte avisos en la campanita",
      "en": "Can show you notices in the bell"
    },
    "switchLabel": {
      "es": "Mostrar sus avisos en la campanita",
      "en": "Show its notices in the bell"
    }
  },
  "kinoCoins": {
    "$comment": "apiVersion 16, capability \"coins\" (Kino coins, Kino 0.9.78), declarative (no export), never on its own, not enhanceable (the plugin declares apiVersion 16 itself). Kino coins are a free currency shared by all of Kino: the person earns them by watching (1 coin every 10 minutes, at most 20 a UTC day) and gives them one at a time. kino.coins.balance() answers { balance, earnedToday, capToday } (balanceFields); kino.coins.give({ to, postId }) gives ONE coin to the account to (1 to maxToChars characters: the coins service's id of the recipient, which a plugin learns from its own server, e.g. Kino Social's coinsAccount) for the post postId (1 to maxPostIdChars characters) and answers { balance, postTotal } (giveFields: the balance left and the coins the post holds now). Both reject with errorCodes: permission_denied (not approved, the plugin disabled, the wrong origin), not_available (the coins service is unreachable or slow, or this device was never validated with a Telegram account), rate_limited (perMinute calls a minute per plugin, both functions together, or the service's own limit), bad_request (not an object, an unknown key, a field out of range), disabled (the person switched Kinos off in Kino's Ajustes, the profile's switch, on by default; message disabledMessage; the service is never asked: show nothing of coins, no button, no balance, no notice), and the service's own refusals of a gift passed on as they are (serviceCodes): no_balance (no coin to give), self_gift (to yourself), unknown_account (no such recipient). Kino's own client talks to the coins service (signed in with the device's gate token and a device key of Kino's own): the plugin never learns the service's address nor its session. Calls: give only inside a call the person started from giveFromFunctions (a screen's open and events, a panel's action), never a screen timer's tick nor a job; balance from balanceFromFunctions, a screen timer's tick included, and the plugin's scheduled job (where kino.coins is on the job allow-list: a daily balance notice). Approval: consentLine in red at install and on the update that adds it, never auto-approved, unticked in a kit import; no switch of its own: the person revokes it by disabling or removing the plugin. Feature-detect with typeof kino.coins === \"object\" (an older Kino has no kino.coins: hide the coin button).",
    "capability": "coins",
    "apiVersion": 16,
    "featureDetect": "typeof kino.coins === \"object\"",
    "functions": ["balance", "give"],
    "balanceFields": ["balance", "earnedToday", "capToday"],
    "giveFields": ["balance", "postTotal"],
    "giveFromFunctions": ["screen", "screenEvent", "panelAction"],
    "balanceFromFunctions": ["screen", "screenEvent", "panelAction", "job"],
    "perMinute": 30,
    "maxRequestChars": 512,
    "maxToChars": 128,
    "maxPostIdChars": 64,
    "badRequestMessage": "kino.coins.give takes { to: 1 to 128 characters, postId: 1 to 64 characters }",
    "errorCodes": ["permission_denied", "not_available", "rate_limited", "bad_request", "disabled", "no_balance", "self_gift", "unknown_account"],
    "disabledMessage": "kino.coins is switched off in Kino's settings",
    "serviceCodes": ["no_balance", "self_gift", "unknown_account"],
    "consentLine": {
      "es": "Podrá ver tu saldo de kinos y regalar tus kinos",
      "en": "Can see your Kinos balance and give your Kinos away"
    }
  },
  "kinoStore": {
    "$comment": "apiVersion 15, capability \"pluginStore\" (plugin stores), not declarative (it exports storeSync), may be declared alone (standalone), not enhanceable, needsApproval. The plugin is a SOURCE of plugins for Kino's store: Kino paints the store from one local index (cards, search, categories, pagination, the owner's blocklist, install) and the plugin only hands over entries; it is never asked anything while the person browses unless it is a live store. The manifest block \"pluginStore\": { \"mode\"?: \"local\" | \"live\", \"name\"?: 1 to maxNameChars characters } is optional (the capability alone is a local store, mode local); the block without the capability is refused. Every store exports storeSync({ reason: \"schedule\" | \"reload\", since?: number (ms, when this store last synced), state?: object }) -> { full: boolean, entries: StoreEntry[], removed?: address[], state?: object }: full true means entries is the whole list (Kino replaces the store's rows), false means upserts plus removed (the addresses that left); state (at most maxStateBytes of JSON) is handed back on the next call. A live store (mode \"live\") also exports storeList({ category?, sort: \"popular\" | \"recent\", cursor? }) -> { entries, next?: cursor } and storeSearch({ q, category?, cursor? }) -> { entries, next?: cursor }, answered while the person browses, at most liveTimeoutMs per call and livePerMinute calls a minute (past either the call adds nothing), cached by Kino for liveCacheTtlMs; a live page keeps its first maxEntriesPerLivePage valid entries (the rest are dropped). storeSync runs in the background at the person's interval and on reload, at most syncTimeoutMs and syncMaxRequests kino.fetch requests (not the scheduled job's budget). An answer over maxSyncBytes of JSON is refused; entries beyond maxEntriesPerSync are dropped; an entry with no address and no stremio, no id (idPattern) or no name is dropped; texts are cut to the limits. StoreEntry fields (entryFields): address (owner/repo[/path][@ref] or url:https://.../kino-plugin.json), id, name, description, longDescription, categories (MarketCategory ids), tags, icon (https URL on a public host: never an IP literal, localhost, a single-label name or a hostRules.privateSuffixes name; Kino's image loader fetches it), screenshots (https URLs, the same host rule), version, author, popularity (number), updatedAt (ms), recommended (honoured only from Kino Plugins), stremio (a Stremio manifest URL; then address may be absent), requires (capabilities), needsSetup, signed (a hint that its author signs it: the card says Firmado), authorKey (a hint of that author key, 64 lowercase hex, authorKeyPattern: an installed plugin of the same id pinned to it reads as installed). Hints only: Kino re-checks everything at install. Approval: consentLine as a plain line at install and on the update that adds it, and consentLineLive in red for a live store. The kit checks the answers like this and prints them: node sdk/run.mjs <folder> storeSync [--since n] / storeList [popular|recent] [category] / storeSearch \"q\".",
    "capability": "pluginStore",
    "apiVersion": 15,
    "field": "pluginStore",
    "modes": ["local", "live"],
    "defaultMode": "local",
    "exports": ["storeSync"],
    "liveExports": ["storeList", "storeSearch"],
    "syncReasons": ["schedule", "reload"],
    "sorts": ["popular", "recent"],
    "answerFields": { "storeSync": ["full", "entries", "removed", "state"], "live": ["entries", "next"] },
    "entryFields": ["address", "id", "name", "description", "longDescription", "categories", "tags", "icon", "screenshots", "version", "author", "popularity", "updatedAt", "recommended", "stremio", "requires", "needsSetup", "signed", "authorKey"],
    "authorKeyPattern": "^[0-9a-f]{64}$",
    "idPattern": "^[a-z0-9][a-z0-9-]{1,39}$",
    "addressPattern": "^(?:url:https://[^\\s/]+/\\S*kino-plugin\\.json|[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}(?:/(?!\\.{1,2}(?:/|@|$))[A-Za-z0-9._-]+)*(?:@[A-Za-z0-9._/-]+)?)$",
    "categories": ["movies", "series", "anime", "live", "radio", "subtitles", "utilities", "themes", "adult"],
    "categoryPattern": "^[a-z][a-z0-9-]{1,23}$",
    "keepRule": "At most maxEntriesPerSync entries are kept, counting only the valid ones: an invalid entry never uses a slot, and the first maxEntriesPerSync valid ones (a repeat of an address already kept is skipped, not counted) win.",
    "needsCapabilityMessage": "The \"pluginStore\" field needs the \"pluginStore\" capability",
    "badMessage": "The \"pluginStore\" field must be an object: { \"mode\": \"local\" or \"live\", \"name\": 1 to 60 characters }",
    "limits": {
      "maxEntriesPerSync": 5000, "maxSyncBytes": 4194304, "maxStateBytes": 16384,
      "liveTimeoutMs": 5000, "livePerMinute": 20, "liveCacheTtlMs": 1800000, "maxEntriesPerLivePage": 50,
      "syncTimeoutMs": 60000, "syncMaxRequests": 40, "syncMaxDownloadBytes": 8388608,
      "maxNameChars": 60, "maxDescriptionChars": 300, "maxLongDescriptionChars": 4000,
      "maxTags": 10, "maxTagChars": 30, "maxScreenshots": 8, "maxVersionChars": 40, "maxAuthorChars": 60,
      "maxRequires": 20, "maxRequireChars": 40
    },
    "consentLine": {
      "es": "Agrega plugins de sus servidores a tu tienda",
      "en": "Adds plugins from its servers to your store"
    },
    "consentLineLive": {
      "es": "Lo que busques en la tienda llegará a sus servidores",
      "en": "What you search in the store will reach its servers"
    }
  },
  "kinoShared": {
    "$comment": "apiVersion 14, capability \"shared\" (Task 8q-2), declarative (no export), never on its own, NOT an approval capability: the consent sheet shows consentLine as a plain line (not red), marked new on the update that adds it (it is the person's own data on the person's own devices, bounded); an update that adds only \"shared\" applies without a sheet, by design. Per profile: each profile's values sync only as that profile's row, so a TV that carries several people's profiles never hands one person's values to another person's phone; a scheduled job (device-wide) writes to the profile in use. kino.shared.get(key) -> the value or null (never throws for a stored value: one this engine cannot read answers null), and kino.shared.set(key, value) -> true when stored, false when the value was already that one (nothing written, nothing sent); set(key, null) removes the key. Synchronous, like kino.storage; usable from screens, panels, settings and scheduled jobs (on the job allow-list; not bounded by the job's storage budget but by these limits). Values are JSON only: the plugin's JSON.stringify text of any JSON value, at most maxValueBytes UTF-8 bytes, strict JSON (RFC 8259: no leading zeros, no lone . or sign, no empty or trailing elements; checked on write, on arrival and on read) at most maxDepth levels deep, one value; a plugin keeps at most maxKeys keys and maxPluginBytes bytes of values; a key matches keyPattern. Secrets never go here (a value is copied to every linked device): a key is split into words (wordPattern, after splitting at _ . -; lowercased) and refused when a word is one of secretKeyTokens or its plural, or two words in a row make apikey (authToken, api_key, sessions refused; author kept), and so is a value that holds one of the plugin's sealed values or markers; never put tokens, passwords, cookies or sessions in it (keep those in kino.storage or your settings). The values sync between the person's own linked devices, both ways, over the existing sync channel (sealed with each peer's pairing key), last writer wins per key by a clock Kino assigns when the value is written; a key's new value travels at most once per syncEveryMs, and at most tripsPerMinute of a plugin's keys travel in any syncEveryMs (renaming keys gains nothing; the newest value written meanwhile goes; reads on this device see it at once). A plugin keeps at most maxRemovals removals (its own oldest go); a removal is forgotten after tombstoneMs, so a device offline longer may bring an old value back. Never sent anywhere else, never shown, logged or parsed by Kino beyond these checks; removed (on every linked device) when the plugin is removed. Each plugin reaches only its own keys. What a peer sends is checked again on arrival (key, size, depth, strict JSON, caps); past a cap the oldest values are dropped. Treat what get answers as untrusted input: another device wrote it (maybe an older or newer version of your plugin), so validate its shape, sizes and every field before you use it. At most writesPerMinute writes a minute per plugin (rate_limited). Errors (thrown as kino errors): not_allowed (no \"shared\" capability, the plugin off, a sealed value), bad_request (a key, a value that is not JSON, a secret-like key), too_large (a value, the plugin's keys or bytes), rate_limited. On the wire the store holds at most maxRowEntries keys of all plugins and maxRowBytes of values. A device not linked to any other keeps them as an ordinary local store. Shared cases: plugins/sdk/test/shared-cases.json.",
    "capability": "shared",
    "apiVersion": 14,
    "featureDetect": "typeof kino.shared === \"object\"",
    "functions": ["get", "set"],
    "keyPattern": "^[A-Za-z0-9_.-]{1,40}$",
    "secretKeyTokens": ["token", "secret", "password", "passwd", "pwd", "apikey", "cookie", "session", "credential", "auth"],
    "wordPattern": "[A-Z]+(?![a-z])|[A-Z]?[a-z]+|[0-9]+",
    "limits": {
      "maxKeys": 4, "maxValueBytes": 65536, "maxPluginBytes": 131072, "maxDepth": 16, "maxKeyChars": 40,
      "syncEveryMs": 60000, "tripsPerMinute": 4, "maxRemovals": 8, "writesPerMinute": 30, "maxRowEntries": 512, "maxRowBytes": 1048576,
      "tombstoneMs": 2592000000
    },
    "errorCodes": ["not_allowed", "bad_request", "too_large", "rate_limited"],
    "consentLine": {
      "es": "Guarda unos pocos resultados que se sincronizan entre tus aparatos vinculados",
      "en": "Keeps a few small results that sync between your linked devices"
    }
  },
  "protocol": {
    "$comment": "apiVersion 20 (Kino 0.9.81), the plugin protocol: a provider plugin opens named doors (\"provides\") and a consumer uses them through Kino (\"consumes\" and kino.plugins.call); no plugin ever calls another directly. Neither block is a capability: a plugin keeps the capabilities of the kind it is (a provider is an ordinary plugin with exports named proto_<door>_<name>). Both blocks are also valid in enhancements[\"20\"], so an older Kino ignores them without refusing the plugin; below apiVersion 20 a plain top-level block is refused (\"The \\\"provides\\\" block needs apiVersion 20\"). A consumer names its provider by repository (owner/name, normalised like recommends: a fork does not stand in) and the door; the key of the entry is a local alias. Types are a closed language scoped to the door: string, number, boolean, T? (optional), T[] (array), a named object type declared by the door (capitalised), or an inline object of field to type. A request is validated strictly (an extra field is bad_input, a missing required one too; a call with no argument to an input whose fields are all optional reads as {}, at the top level only: a null nested in the argument is never {}); a response is validated loosely (extra fields dropped, a wrong or missing type is bad_output, no coercion). Request and response are JSON, at most maxPayloadBytes UTF-8 bytes. A provider can only expose what it declared; Kino re-checks the consumer's list at every call (a call the provider no longer declares answers not_declared) and never when the provider updates. The consent sheet of a consumer carries one plain line per door (consentLine, with the provider's name and the door's summary), at install and on an update that adds it (also in the notice of an update applied without asking); no per-call prompt, and removing a provider just makes its doors answer provider_missing. The line does not say that the consumer's arguments reach the provider, which may send them to its own hosts (or to any host with fetchHosts \"any\"): a consumer must not pass in an argument what it would not hand to the provider's author. An 18+ provider is provider_missing to a consumer that is not 18+; a plugin never reaches its own door (not_declared); an answer holding one of the provider's sealed values or a marker is bad_output. The rate limit (maxCalls per windowMs, and streams.maxPollsPerWindow) is per consumer and provider's door, whatever alias reaches it. Nothing is persisted, so nothing new is synced. kino.plugins is not available in background jobs (not_allowed) nor to sign(); it is available wherever the other kino services are (screen, screenEvent, panel exports...).",
    "apiVersion": 20,
    "provides": {
      "maxDoors": 4,
      "maxCallsPerDoor": 16,
      "maxStreamsPerDoor": 8,
      "summaryMaxChars": 120,
      "namePattern": "^[A-Za-z][A-Za-z0-9]{0,31}$",
      "typeNamePattern": "^[A-Z][A-Za-z0-9]{0,31}$",
      "primitives": [
        "string",
        "number",
        "boolean"
      ],
      "callExport": "proto_<door>_<call>",
      "streamExport": "proto_<door>_<stream>",
      "streamArgument": "the cursor of the last answer (null the first time)",
      "streamAnswer": "{ items, cursor }",
      "streamEverySeconds": {
        "min": 30,
        "default": 60,
        "max": 86400
      }
    },
    "consumes": {
      "maxEntries": 8,
      "maxCallsPerEntry": 16,
      "maxStreamsPerEntry": 8,
      "fields": [
        "repo",
        "door",
        "calls",
        "streams"
      ]
    },
    "call": {
      "function": "kino.plugins.call",
      "timeoutMs": 10000,
      "maxCalls": 30,
      "windowMs": 10000,
      "maxPayloadBytes": 65536
    },
    "errorCodes": [
      "provider_missing",
      "not_declared",
      "bad_input",
      "bad_output",
      "rate_limited",
      "timeout",
      "provider_failed"
    ],
    "streams": {
      "event": "protocol",
      "stateKey": "protocol",
      "maxSubscriptionsPerConsumer": 4,
      "maxStateFlags": 16,
      "maxPollsPerWindow": 8,
      "pollWindowMs": 10000,
      "argFields": [
        "alias",
        "stream",
        "items"
      ],
      "availableIn": "a plugin screen (not a player-panel session)"
    },
    "providesOnly": {
      "apiVersion": 20,
      "$comment": "A plugin whose only purpose is a non-empty \"provides\" and which declares no capability (the field may be left out) is valid with \"hosts\": [] and without search/home/resolve: it plays nothing, is no source, its consent sheet claims no network or role, and with no host its installed card says it does not connect to the internet. Any capability, setting, or a provides below apiVersion 20 brings back the ordinary rules."
    },
    "screenOnlyConsumer": {
      "apiVersion": 20,
      "capabilities": [
        "screen"
      ],
      "$comment": "Owner decision: a manifest of apiVersion 20 or later with a non-empty \"consumes\" and capabilities exactly [\"screen\"] (no source capability, nothing else) is valid with \"hosts\": []. With no host its own kino.fetch calls are refused unless it declares fetchHosts \"any\" or has a url setting (alone or as a field of a list), it is no source, and the pictures its screen shows from public addresses (https, and http where httpImages says so) need no host declared, so it declares none rather than a placeholder. With no host and no setting at all its installed card says it does not connect to the internet. Another capability, an empty or missing consumes, or apiVersion 19 (consumes only through enhancements[\"20\"]) bring back the ordinary rules; a screen-only consumer that does declare hosts stays valid."
    },
    "ctx": {
      "$comment": "Every proto_<door>_<name> export is called as (arg, ctx), arg being the call's validated input (or a stream's cursor) and ctx what Kino knows about the caller. Kino sets ctx; a consumer never sends or shapes it, and a provider that declares only (arg) keeps working. ctx.caller is the consuming plugin: its id, the canonical address it was installed from on GitHub, owner/name[/path][@ref] (null for a plugin installed from a manifest URL or a file; drop any @ref before using it as go.plugin's repo), its display name and whether it is 18+ (the same test as the 18+ lock). The kit passes the same shape (run.mjs proto takes --repo for it).",
      "caller": ["id", "repo", "name", "adult"]
    },
    "consentLine": "Uses data from <provider> (<door summary>)"
  },
  "cookies": {
    "maxPerHost": 50,
    "maxTotalBytes": 65536
  },
  "storage": {
    "maxTotalBytes": 262144,
    "maxTtlMs": 2592000000,
    "largeApiVersion": 13,
    "largeMaxTotalBytes": 16777216,
    "largeMaxValueBytes": 2097152,
    "largeMaxKeys": 1000,
    "largeMaxKeyChars": 256
  },
  "crypto": {
    "hashes": ["md5", "sha1", "sha256", "sha512"],
    "ciphers": ["aes-128-cbc", "aes-192-cbc", "aes-256-cbc", "aes-128-ecb", "aes-192-ecb", "aes-256-ecb", "aes-128-ctr", "aes-192-ctr", "aes-256-ctr", "aes-128-gcm", "aes-192-gcm", "aes-256-gcm", "des-ede3-cbc", "des-ede3-ecb"],
    "encodings": ["utf8", "hex", "base64"],
    "pbkdf2Hashes": ["sha1", "sha256", "sha512"],
    "pbkdf2MaxIterations": 100000,
    "pbkdf2MaxKeyBytes": 64,
    "randomMaxBytes": 1024,
    "bytesOps": {
      "apiVersion": 13,
      "ops": ["aesIge", "modPow", "gunzip", "convert", "aesIgeVerify"],
      "modPowMaxBits": 4096
    },
    "maxDataBytes": 5242880,
    "errorCode": "crypto_error",
    "keyPairs": {
      "apiVersion": 6,
      "types": ["ec", "ed25519", "x25519"],
      "curves": ["P-256", "P-384"],
      "signHashes": ["SHA-256", "SHA-384"],
      "signatureFormats": ["der", "ieee-p1363"],
      "importFormats": ["jwk", "spki", "raw"],
      "maxKeysPerRuntime": 64,
      "maxSignatureBytes": 512
    }
  },
  "socket": {
    "apiVersion": 13,
    "maxSockets": 4,
    "maxQueuedBytes": 8388608,
    "maxRecvMs": 60000,
    "maxSendBytes": 786000,
    "encodings": ["hex", "base64"],
    "errorCodes": ["host_not_allowed", "not_https", "limit", "closed", "network", "timeout", "invalid_request", "too_large"]
  },
  "byteSource": {
    "apiVersion": 13,
    "source": "plugin",
    "export": "read",
    "readTimeoutMs": 20000,
    "mimePattern": "^[a-z]+/[A-Za-z0-9.+-]{1,100}$",
    "maxSessions": 2,
    "maxLanSessions": 2,
    "chunkBytes": 1048576,
    "alignmentBytes": 4096,
    "readAheadChunks": 3,
    "cacheChunks": 8,
    "maxHandleChars": 512
  },
  "catalog": {
    "apiVersion": 13,
    "fileName": "catalog.db",
    "maxItems": 100000,
    "maxIdChars": 128,
    "maxTitleChars": 300,
    "maxDataBytes": 4096,
    "maxUpsertBatch": 500,
    "defaultSearchLimit": 50,
    "maxSearchLimit": 100,
    "maxOffset": 1000000,
    "maxQueryChars": 256,
    "maxDbBytes": 67108864,
    "maxRequestChars": 6291456,
    "orders": ["newest", "oldest", "title"],
    "errorCodes": ["invalid_request", "too_large", "limit", "unavailable"]
  },
  "visualBrowser": {
    "$comment": "apiVersion 20, manifest \"visualBrowser\": true (additive key, boolean only, ignored below apiVersion 20; not a capability: nothing is approved at install, Kino asks in its own sheet at every open). kino.visualBrowser.open({ url, title?, doneWhen?, collect?, userAgent?, timeoutMs? }) opens a full-screen web window the PERSON drives (to sign in, solve a challenge, accept terms) on the plugin's declared hosts only (https, default port, never the local network; a blocked navigation is stopped and Kino says so). Android phone, tablet and TV (experimental on a TV: the remote's D-pad drives the page and Kino's bar, and a page with pointer-only controls may be hard to reach): kino.visualBrowser.available is false on the desktop and on a device without a WebView, and kino.visualBrowser is undefined on a Kino without it. It answers { status: done | closed | timeout, finalUrl?, cookies?, html?, stored?, storedNames?, userAgent? }; closed also covers the person saying No to the sheet; cookies and html only with done. Only from the person's own press, the very gate of qr (fromFunctions, screenTriggers); anything else is forbidden. The window starts with the declared hosts' cookies expired and expires them again at the end (the Android cookie jar is the app's one: a cookie scoped to another path survives). No script of the plugin in the page, no pop-up, download, file chooser, camera, microphone, location or prompt. collect.storeAs { setting, format: header | json } makes Kino write the collected cookies into the plugin's own password setting (after its call ends: saving restarts the runtime); the script then only gets stored and storedNames, never a value; a text longer than that setting allows is store_failed. collect.storeAs.spill (optional, apiVersion 20, additive): an array of 1 to 3 DISTINCT names of MORE declared password settings of the same plugin, none equal to setting (else bad_args); Kino cuts the formatted text into pieces of at most the password limit (settings.types.password.maxChars) and fills setting, then each spill setting in order (a surrogate pair is never split; a header text may be cut inside a cookie), so the plugin joins the settings' values in that order with NO separator; settings the text does not reach are written as empty strings, but only when they hold a value now; every piece goes in ONE settings save (sync records one change), all or nothing, and when (1 + spill) x the limit cannot hold the text the answer is store_failed and nothing is stored. The script still never sees a value and stored/storedNames are unchanged. collect.storeAs.thenEvent (optional, a screenEvent name: 1 to 128 of A-Z a-z 0-9 . _ ~ -, never the reserved open; anything else is bad_args) asks Kino to send that event to the plugin's OPEN screen once the setting was written successfully: its arg is { stored: [cookie names] } (names only, never a value) and it has no value. Only when the call came from a screen's screenEvent (from a settings action or a panelAction the option is accepted and nothing is sent); never after a failed write or a window that was not done; dropped silently when that plugin has no screen open then or its event queue is full; at most one per call. It is a follow-up, not a press: a change-like event (its answer's go.url, go.copy, go.titleByIds, go.installPlugin, share and enableJob are dropped) with the normal event time budget. The call's time bound does not run while the window is up: the call's own clock and the screen session's guard against a call that never ends both stop for as long as the window is on screen (from a settings action, a panelAction and a screenEvent alike), the window's own timeoutMs (at most maxTimeoutMs) is the only limit, and once it closes the call has at least afterWindowGraceMs left to run the code after open resolves. doneWhen.urlMatches is a pattern where * matches any run of characters, against the whole address. userAgent \"browser\" is the Chrome-for-Android string below; either way the WebView marker (; wv) is removed and X-Requested-With dropped where the WebView supports it.",
    "apiVersion": 20,
    "manifestKey": "visualBrowser",
    "notBooleanMessage": "The \"visualBrowser\" field must be true or false",
    "consentLine": "Puede abrir una ventana web donde inicias sesión o terminas un paso en sus sitios",
    "fromFunctions": ["action", "panelAction", "screenEvent"],
    "screenTriggers": ["press", "submit"],
    "thenEvent": { "maxChars": 128, "reservedNames": ["open"], "argKey": "stored", "fromFunctions": ["screenEvent"] },
    "maxTimeoutMs": 600000,
    "minTimeoutMs": 5000,
    "backgroundCloseMs": 60000,
    "maxUrlChars": 2048,
    "maxTitleChars": 60,
    "maxCookieNames": 32,
    "maxCookieNameChars": 256,
    "maxCookies": 64,
    "maxCookieChars": 16384,
    "maxLocalStorageKeys": 32,
    "maxLocalStorageKeyChars": 256,
    "maxLocalStorageChars": 65536,
    "maxHtmlChars": 2000000,
    "maxUrlMatchChars": 200,
    "maxUserAgentChars": 300,
    "userAgentBrowser": "browser",
    "browserUserAgent": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Mobile Safari/537.36",
    "statuses": ["done", "closed", "timeout"],
    "storeFormats": ["header", "json"],
    "maxSpill": 3,
    "afterWindowGraceMs": 10000,
    "errorCodes": ["bad_args", "forbidden", "unavailable", "busy", "store_failed"]
  },
  "qr": {
    "$comment": "apiVersion 13. kino.qr.scan({ title?, titleEn? }) (capability qrScan, declarative, no approval): Kino's camera scanner full screen on the phone, under the installed plugin's name, the plugin's title (titleEn in English) and Kino's instruction. Resolves with the decoded text (1 to maxScanChars characters) or null when the person closes it (the close button, Back, leaving the screen, or the call ending). A scan runs only from a settings action, a panelAction or a screenEvent that follows the person's press (fromFunctions: the person pressed one of the plugin's buttons; anything else is not_allowed). Task 8p: a plugin screen's call (a root screen, a screen-mode panel, a contributed tab in screen mode) counts only after the person's own tap or submit (screenTriggers), never its open event, a timer tick (every), a load-more, a change, a panel's refreshMs or a playerEvent. The scanning call's clock is paused while the scanner is up; one scan on screen at a time for the whole app (a second one, from any plugin, is busy). unavailable: this device cannot scan (no camera, or Kino's TV interface). title and titleEn hold no control, bidi or format character (invalid_request); a code over maxScanChars is ignored and the scanner says it is not valid for the plugin. Showing a QR needs no capability: the settings form's qr setting (settingsQr), whose text is settingsStatus()'s answer under its key, asked again when the form opens, after every action and every refreshMs while the form is on screen.",
    "apiVersion": 13,
    "capability": "qrScan",
    "fromFunctions": ["action", "panelAction", "screenEvent"],
    "screenTriggers": ["press", "submit"],
    "maxScanChars": 4096,
    "timeoutMs": 120000,
    "maxTitleChars": 80,
    "errorCodes": ["busy", "timeout", "unavailable", "permission_denied", "invalid_request", "not_allowed"],
    "settingsQr": { "type": "qr", "maxChars": 512, "minRefreshMs": 2000, "maxRefreshMs": 60000 }
  },
  "images": {
    "$comment": "imageSource (apiVersion 13): a poster, backdrop, still or section hero image may be { source: \"plugin\", handle } instead of a URL; Kino loads it from the plugin's required image({ handle }) export, which answers { bytes: <base64>, mime }. One call in flight per plugin, never while that plugin has an open byte stream or a read queued, running or ended under readQuietMs ago (a timed-out call discards the plugin's runtime: QuickJS cannot be interrupted), kept in the image disk cache per plugin, installed version and handle; a failed handle is left alone for failureTtlMs; pauseAfterTimeouts timeouts in a row pause the plugin's images for pauseMs.",
    "apiVersion": 13,
    "capability": "imageSource",
    "export": "image",
    "source": "plugin",
    "fields": ["poster", "backdrop", "still", "hero.image"],
    "maxHandleChars": 512,
    "maxBytes": 262144,
    "mimes": ["image/jpeg", "image/png", "image/webp"],
    "timeoutMs": 10000,
    "maxInFlightPerPlugin": 1,
    "readQuietMs": 2000,
    "maxWaitMs": 20000,
    "failureTtlMs": 300000,
    "pauseAfterTimeouts": 2,
    "pauseMs": 300000
  },
  "sleep": {
    "maxMs": 5000
  },
  "errors": {
    "codes": ["auth_required", "not_found", "geo_blocked", "rate_limited", "unavailable"],
    "maxMessageChars": 200,
    "maxUserMessageChars": 160
  }
}

kino.d.ts

Ver kino.d.ts
// TypeScript declarations for Kino plugins (apiVersion 1 to 27; 27 adds the clockLive stream field (KinoStream.clockLive: a clock-enumerated sliding-window live HLS feed Kino synthesizes itself on its local proxy, for live from an open CDN whose segment URLs are enumerable by a media clock; capability-free, live only); 26 adds to appThemes the painted surfaces, gloss, layout, assets, background image and font; 25 lets a stream's `subtitles` entry carry its own decrypted `text` (with `format`) instead of a `url` (Kino 0.9.86, provisional); 24 lets a stream's `drm` be a list of options and adds the `clearkey` type (Kino 0.9.85, provisional); 23 adds the playerSlot capability (up to three small elements in the top-right corner of the TV player: the playerSlot and playerSlotAction exports and the manifest's slot block); 22 adds the progress capability (kino.progress: how far along the person is in something that is not a video, kept by Kino and read back with `kino.progress.list`; Kino draws nothing from it, the plugin builds its own shelf); 21 adds the files capability (kino.files: files on the person's device, picked by the person, read by ranges and played through a kino-file: address); 20 adds the visualBrowser manifest key (kino.visualBrowser.open: a web window the person sees and drives, on the plugin's own hosts, to sign in or finish a step) and the plugin protocol (the manifest's provides and consumes blocks and kino.plugins.call: one plugin uses the doors another opens, through Kino); 19 adds the lyrics capability (the lyrics(query) export: a song's time-synced or plain lyrics for the music player's overlay); 18 adds the app themes (go.useTheme, go.setExperience, appThemes with price, experience and logo); 17 adds the stats operation of the library capability (kino.library.stats, a month's totals and top titles); 16 adds the coins capability (kino.coins: the person's Kino coins balance, and giving one coin for a post); 15 adds the identity capability (kino.identity.telegram: a per-plugin pseudonym of the person and the signed token that proves it), the notifications capability (kino.notifications: notices in the Home bell), library episodes (the latest season and episode of a watched series) and the pluginStore capability (the plugin is a source of plugins for Kino's store: storeSync, and storeList and storeSearch for a live store); 14 adds the screen capability (screen, screenEvent and the manifest's screen block: a full-screen canvas the plugin builds), library, playerPanelTab, playerControl, room (kino.room, a mailbox hosted on the person's device over the Internet), schedule (background jobs: the manifest's jobs and the job export) and the manifest's enhancements; 13 adds the socket capability (kino.ws, outbound WebSockets) and the byteSource capability (a stream whose bytes the plugin serves through its read export) and the storageLarge capability (a 16 MiB kino.storage for a plugin that keeps a catalog) and the catalog capability (kino.catalog, a searchable SQLite catalog of up to 100,000 items per plugin in a 64 MiB file) and the qrScan capability (kino.qr.scan, the phone's camera scanner for a QR code) and the settings form's qr setting (a QR whose text settingsStatus gives, refreshed every refreshMs) and the kino.crypto operations aesIge, modPow, gunzip, convert and aesIgeVerify and the imageSource capability (a poster, backdrop, still or hero image the plugin serves through its image export, KinoImageRef); 12 adds the syncProvider capability (syncPull, syncPush, syncStatus and the manifest's sync block); 11 adds the externalResolve capability (a stream's `external` hand-off to a resolver app, the manifest's externalResolver) and, from Kino 0.9.66, a stream's advisory `media` and its `portable` universal copy; 10 adds the playlists capability; 9 adds the player panel (panel, panelAction, playerEvent, the manifest's panel and settingsLayout), fetchHosts "any" for hand-written plugins, English setting texts and kino.meta by title; 8 adds the audio item kinds music and podcast; 7 adds tracking and segments; apiVersion 5 only adds the manifest's signature, 6 the plain-plugin SDK: typed and larger secrets, migrate, signed streams, the settings form, debug, telemetry, section, categories, theme and scopedSearch). Reference them from plugin.js
// with `/// <reference path="./kino.d.ts" />` for editor help; Kino itself runs plain JavaScript.
// The numbers in the comments come from contract.json, which is authoritative. The app checks that
// every `kino` member declared here exists in its runtime and nothing else does (KinoDtsTest).

// ---------- what your functions receive and return ----------

/**
 * `search(query)`: `type` is a hint, never a filter. `cursor` is null on the first page. `"music"` and `"podcast"`
 * (apiVersion 8) when Kino leans towards audio; `"any"` includes them.
 */
interface KinoSearchQuery {
  q: string;
  type: "movie" | "series" | "music" | "podcast" | "any";
  year: number;
  season: number;
  episode: number;
  tmdbId: number;
  /** TMDB's original title when it differs from `q`, else "". */
  originalTitle: string;
  /** Other known titles, at most 5, each at most 200 characters. */
  altTitles: string[];
  cursor: string | null;
  /**
   * apiVersion 6, capability "scopedSearch": the browse `ref` of the "Ver más" page the person searches inside (a Home
   * row, a section row, a category), exactly as you gave it; absent on a plain search. Return null when you cannot
   * search there: Kino then filters the page's loaded titles itself.
   */
  within?: string;
}

interface KinoItem {
  /** ^[A-Za-z0-9._~-]{1,128}$, stable: the library keys the title by it. */
  id: string;
  /** Your own opaque reference, at most 4096 characters. */
  ref: string;
  title: string;
  /**
   * `"live"` needs `"apiVersion": 2` (a v1 plugin's live item is dropped): a live channel, whose
   * `ref` goes to `resolve` and plays as live straight from its card, with an "EN VIVO" badge; it
   * has no `runtimeMinutes` (ignored) and no episodes, is never saved to the library, never resumed
   * and never downloaded.
   *
   * `"music"` (an album, playlist or single track) and `"podcast"` (a show or an audiobook) need `"apiVersion": 8`
   * (below it they are dropped, with a log line, and the rest of the answer stays) and NOT the `episodes` capability.
   * With `episodes` declared, Kino calls `episodes(ref)` with an audio item's `ref` for its tracks or episodes (a single
   * track answers one entry: `number` = track number, `still` = cover, `runtimeMinutes`), each entry's `ref` going to
   * `resolve`; without it, the item's own `ref` goes straight to `resolve` and plays as one track, like a movie's.
   * `runtimeMinutes` is kept.
   */
  kind: "movie" | "series" | "live" | "music" | "podcast";
  /**
   * apiVersion 8, `music` and `podcast` only: the artist (music) or the host/author (podcast). Trimmed, at most 200
   * characters; ignored on any other kind. The album or podcast page shows it as the line under the title; without it
   * there is no such line (Kino never guesses one from `overview` or `genres`).
   */
  artist?: string;
  year?: string | number;
  /**
   * http or https, at most 2048 characters; a public name or a public IPv4 address, never the home network or a local name
   * (over http not even a name without a dot), except the person's own server. apiVersion 13 with "imageSource": or an
   * image reference ({@link KinoImageRef}) whose bytes your `image` export serves.
   */
  poster?: string | KinoImageRef;
  /** Like `poster`: a URL, or with "imageSource" (apiVersion 13) a {@link KinoImageRef}. */
  backdrop?: string | KinoImageRef;
  overview?: string;
  originalTitle?: string;
  /** At most 5, each at most 30 characters. */
  genres?: string[];
  /** 0..10 */
  rating?: number;
  /** 1..1000; ignored on a `live` item. */
  runtimeMinutes?: number;
  /**
   * `tmdb` and `imdb` name the title for Kino's metadata. On a `music` or `podcast` item (apiVersion 19) `isrc`, `musicbrainz` and
   * `youtube` are the ids a lyrics plugin may match the song by: each a text of 1 to 64 characters (others are skipped). Kino keeps them with
   * the artist on the device and sends them in the `ids` of the `lyrics` query while that item plays.
   */
  ids?: { tmdb?: number; /** ^tt\d{5,10}$ */ imdb?: string; isrc?: string; musicbrainz?: string; youtube?: string };
  lang?: string;
  quality?: string;
  /** At most 3, each at most 20 characters; shown as chips. */
  badges?: string[];
  /** apiVersion 6: true = an 18+ entry, shown only while the person's 18+ code is unlocked on that device (Ajustes ▸ Control parental). Below apiVersion 6 it is dropped. */
  adult?: boolean;
  /**
   * Task 7g (with the `screen` capability): a tap on the card opens this plugin's own screen at that route instead of the
   * title's page, while the screen can open; otherwise (screens off, the screen hidden or failing) the tap does what it always
   * did. Anything but `{ screen }` is ignored and logged, the item kept.
   */
  open?: { screen: KinoScreenOpen };
}

/** A Home row. `ref` needs the `browse` capability: the row gets "Ver más", which calls browse(ref, null). */
type KinoGenre =
  | "peliculas" | "series" | "anime" | "infantil" | "documentales"
  | "deportes" | "noticias" | "musica" | "entretenimiento" | "otros";

interface KinoRow {
  id: string;
  title: string;
  /**
   * Items of kind "live" (channels) stay in a Home row from apiVersion 6, as channel cards with the "En vivo" badge
   * that open like a channel from En vivo (a 18+ one only while the person's code is unlocked); below 6 they are
   * dropped from Home. A row left with nothing to show is not shown.
   */
  items: KinoItem[];
  ref?: string;
  /** Task 7g: the row's "Ver mas" opens this plugin's own screen while it can, else follows `ref` as before (none: no "Ver mas"). */
  open?: { screen: KinoScreenOpen };
  /**
   * What the row (or category, or list) is about, from Kino's closed vocabulary: "peliculas", "series", "anime",
   * "infantil", "documentales", "deportes", "noticias", "musica", "entretenimiento" or "otros". Kino groups Categorías
   * by it and filters En vivo by it across plugins. Optional: without it Kino guesses from the title; a value outside
   * the list is ignored. Kino versions before this field ignore it.
   */
  genre?: KinoGenre;
}

/** `next` (at most 2048 characters, opaque) needs the `browse` capability; the app passes it back as the cursor. */
interface KinoPage {
  items: KinoItem[];
  next?: string;
}

interface KinoEpisode {
  /** 1..999, default 1. */
  season?: number;
  /** 1..99999 */
  number: number;
  ref: string;
  title?: string;
  /** Like an item's `poster`: a URL, or with "imageSource" (apiVersion 13) a {@link KinoImageRef}. */
  still?: string | KinoImageRef;
  overview?: string;
  /** YYYY-MM-DD. Since Kino 0.9.55 shown under the episode in the list (phone and TV), worded in the app's language. */
  airDate?: string;
  /** 1..1000. Since Kino 0.9.55 shown under the episode in the list, next to `airDate` ("12 mar 2024 · 48 min"). */
  runtimeMinutes?: number;
}

interface KinoSeriesInfo {
  title?: string;
  /** Like an item's: a URL, or with "imageSource" (apiVersion 13) a {@link KinoImageRef}. */
  poster?: string | KinoImageRef;
  backdrop?: string | KinoImageRef;
  overview?: string;
  genres?: string[];
  year?: string | number;
  /** Kino 0.9.54: 0 to 10, like an item's. */
  rating?: number;
  /** `tmdb`, `imdb`; Kino 0.9.54: also an anime's `mal`, `anilist`, `kitsu` (whole numbers), for AniList and meta plugins. */
  ids?: { tmdb?: number; imdb?: string; mal?: number; anilist?: number; kitsu?: number };
  /** Kino 0.9.54: a movie's length (in a `details` answer); a series' is per episode and ignored. */
  runtimeMinutes?: number;
}

/**
 * One season of a series, for a source that keeps each season as its own `series` item: that item's
 * `id` and `ref` (`episodes(ref)` lists it). `title` is what the season selector shows ("Temporada 2");
 * `current` marks the season whose episodes came in the same answer (Kino also recognizes it by `id`).
 */
interface KinoSeason {
  /** The season's own item id, same pattern as an item id. */
  id: string;
  /** The season's own series ref, at most 4096 characters. */
  ref: string;
  title: string;
  /** 1..999; leave it out when the source has no numbering. */
  number?: number;
  current?: boolean;
}

interface KinoEpisodes {
  series?: KinoSeriesInfo;
  episodes: KinoEpisode[];
  /**
   * Only when each season is a separate item: every season of the show, this one included, at most
   * 50. Leave it out when `episodes` already holds every season (Kino reads the seasons from them).
   */
  seasons?: KinoSeason[];
}

/**
 * One DRM option of a stream's `drm`. Widevine fetches its license from `licenseUrl` (apiVersion 2).
 * ClearKey (apiVersion 24) has no license server: `keys` maps a key id to its key, each exactly 32 hex
 * digits (a key id may be a dashed UUID), at most 8 pairs; a pair that is not valid is dropped.
 */
type KinoDrm =
  | { type: "widevine"; licenseUrl: string; licenseHeaders?: Record<string, string> }
  | { type: "clearkey"; keys: Record<string, string> };

interface KinoStream {
  /**
   * https on a declared host (http only on one declared `insecureHttp`), or the person's own server exactly as typed.
   * A live channel's stream of a plugin approved for `"liveStreamHosts": "any"` may be on any public host, http or https.
   * Ignored when `external` is given instead (apiVersion 11): then `url` may be omitted or left empty.
   */
  url: string;
  mime?: string;
  /**
   * Sent with every request the player makes for this stream (and, for a plugin that declares the
   * `download` capability, with the request that saves it to the device). At most 20.
   */
  headers?: Record<string, string>;
  /**
   * Side subtitle tracks, at most 30. Each is a `url` (checked like the video's) or, apiVersion 25, your own decrypted `text`
   * with a `format` of "vtt" or "srt" and no `url`: at most 2,000,000 bytes (UTF-8); with no `format`, or over the limit, the
   * entry is dropped. An entry with both keeps only the `text`.
   */
  subtitles?: KinoStreamSubtitle[];
  /**
   * Separately-hosted audio tracks (a dub, an alternate mix), at most 8: Kino plays your video with
   * each merged in as its own track, offered and auto-picked by the person's audio-language
   * preference exactly like the container's own. `lang` is a short code like `subtitles`' (up to 16
   * characters; blank becomes `"und"`); `label`, if given (up to 40 characters), is shown verbatim
   * instead of a name guessed from `lang`. Checked the same way as `subtitles`: https on a declared
   * host, or the person's own server exactly as typed; a bad entry is dropped and the rest survive,
   * and so is a `url` already listed (the first entry wins). Ignored for a `live` item's stream: a
   * channel's other languages go inside its manifest.
   */
  audioTracks?: { lang: string; url: string; label?: string }[];
  /** Ignored for a `live` item's stream: a channel has no length. */
  durationMs?: number;
  /** 30..86400: after that long, a failed playback calls resolve() once more. */
  expiresInSeconds?: number;
  /**
   * apiVersion 2, and only with the `drm` capability declared: the stream is Widevine-protected and
   * Kino fetches its license from `licenseUrl` (checked exactly like `url`: https on a declared host, http only on one declared `insecureHttp`)
   * sending `licenseHeaders` (filtered like `headers`, at most 20) with the license request only.
   * Without the capability any DRM-shaped key refuses the stream. A protected title never downloads.
   * Kino negotiates Widevine at security level L3 (software), and only when the device confirms L3:
   * the license server must allow it. `audioTracks` next to `drm` are played clear (no license for
   * them): plain, unencrypted files only.
   *
   * apiVersion 24: `drm` may also be a list of options, best first (at most 4; a wrong entry is dropped,
   * a list with none usable refuses the stream), and a block may be ClearKey (no license server). Kino
   * uses the first option the device supports. On a phone that really has Widevine L1 (never a TV, never
   * a live channel), and only when the license is refused because it demands output protection L3 cannot
   * give, Kino plays the title again at L1 on a surface without zoom or forced ratio; the plugin does
   * nothing. Any other DRM failure moves to the next option.
   */
  drm?: KinoDrm | KinoDrm[];
  /**
   * apiVersion 6: `"request"` makes Kino sign every playlist and segment request of this stream with your
   * `sign()` export, right before sending it, through a local proxy. HLS only (an HLS `mime` or a `.m3u8`
   * path); never with `drm` or `audioTracks`; not on an inline `liveChannels` stream (use `resolve()`).
   */
  signing?: "request";
  /**
   * apiVersion 6, with `signing`: up to 4096 characters `sign()` gets back as `context` (it can't read kino.storage).
   * Never a `kino.secret()` marker (refused): a marker only works in the runtime that made it, so call
   * `kino.secret()` inside `sign()` itself.
   */
  signContext?: string;
  /**
   * apiVersion 6, with `signing`: other hosts serving this same stream at the same path and scheme, up
   * to 6, each `"host"` or `"host:port"` (no scheme, no path, no IPv6). Kino tries the playlist on each
   * (3 rounds, the one that served last first) and moves a segment, key or map to another one when its
   * own fails 3 times. `sign()` always gets the URL of the host being asked, so pick that host's token
   * from `context`. Each entry meets the same host rule as `url` (declared hosts, or any public host
   * under `liveStreamHosts: "any"`); one that fails it, repeats `url`'s host or another entry, or comes
   * after the sixth is dropped. Not an array of strings: the stream is refused. Ignored without `signing`.
   */
  alternateHosts?: string[];
  /**
   * apiVersion 6: this copy's short name, e.g. "Latino · Streamwish", shown in the player's "Servidor" menu (phone and
   * TV) and in logs. Trimmed; at most 48 characters, no control characters, or it is dropped (the copy still plays).
   * Ignored below apiVersion 6.
   */
  label?: string;
  /**
   * Other copies of the same video, best first, at most 8: when `url` cannot play on the device (a codec it lacks, a broken
   * file) or is gone, Kino moves on to the next one by itself, at the same spot, before showing any error. Each is checked
   * exactly like `url`, `mime` and `headers`; a bad entry is dropped. They share this stream's subtitles and audio tracks.
   * Ignored next to `drm`, with `signing` (use `alternateHosts`) and for a live channel.
   *
   * apiVersion 6: each may carry a `label` (same rules as the Stream's), and may be `{ label, ref }` instead of a URL: a
   * lazy copy. `ref` (a non-blank string of at most 512 characters) goes to your `resolve(ref)` ONLY when that copy is
   * needed -- the person picks it in the "Servidor" menu, the automatic fallback reaches it, or a download's copy choice
   * probes it within its 30 s budget. That call is a normal `resolve` (same time limit, same checks,
   * `kino.browser.capture` allowed); only its `url`, `headers`, `mime`, `subtitles`, `expiresInSeconds` and `skip` are
   * used, never its own `alternatives`. Its `skip` applies while that copy plays and is never saved (the Stream's `skip`
   * stays the episode's). A failure moves on to the next copy. Below apiVersion 6 a ref-only entry has no `url` and is
   * dropped.
   */
  alternatives?: KinoStreamAlternative[];
  /**
   * Where THIS file's opening and ending are, in ms from its start: Kino's "Saltar intro" shows from
   * `openingStartMs` (0 when left out or null) to `openingEndMs`, "Saltar outro" from `endingStartMs`. Each a
   * finite number in 0..`durationMs` (0..86 400 000 without `durationMs`); the opening needs its end,
   * after its start; the ending not before the opening's end. A bad part is dropped, never the stream.
   * A person's hand correction wins over it; it wins over AniSkip. Ignored for a live channel.
   */
  skip?: { openingStartMs?: number; openingEndMs?: number; endingStartMs?: number };
  /**
   * apiVersion 11: instead of a playable `url`, hand this stream to an independently-installed app that declares it
   * can resolve `protocol` (Kino never interprets `protocol` or `ref` itself). `ref` is opaque, 1..2048 characters,
   * never logged in full. When `external` is present, `url` is ignored. See the External Source Resolver guide.
   */
  external?: {
    protocol: string;
    ref: string;
    /**
     * Android package of the one resolver app this stream wants. Overrides the manifest's `externalResolver.package`.
     * Kino asks only that app (the person still has to allow it) and never another one in its place; if it isn't
     * installed and the manifest doesn't name a download for it, the stream fails.
     */
    resolver?: string;
  };
  /**
   * Kino 0.9.66, optional and ADVISORY: what you know about the file itself. Kino shows and logs it and may use it as a
   * hint (for a cast), never for anything that could harm the person. Every field is optional; text is one line cut at 120
   * characters (`codec`/`container` 40, `language` 20), numbers are clamped, at most 16 tracks and 4 `notes`; an object with
   * nothing usable left is dropped, and a bad `media` never refuses the stream. Older Kino ignores it.
   */
  media?: KinoStreamMedia;
  /**
   * Kino 0.9.66, optional: a universal copy of THIS video, for a source that can make one on demand (an external resolver app
   * that converts): HLS, H.264 8-bit up to 1080p, stereo AAC, playable by any TV receiver. Checked exactly like `url`
   * (anything else, a non-HLS `mime` included, drops it and the rest still counts); ignored next to `drm`, request signing or
   * `external`. The phone's own player never uses it; Kino casts it when the title's own cast route needs a conversion or the
   * stream is likely not playable as it is. See the External Source Resolver guide.
   */
  portable?: { url: string; mime?: "application/x-mpegURL" | "application/vnd.apple.mpegurl" };
  /**
   * apiVersion 27, `live` streams only, capability-free: a sliding-window live HLS feed whose MPEG-TS/fMP4 segment URLs
   * are enumerable from a media clock, so Kino SYNTHESIZES the `.m3u8` itself on its own local proxy and recomputes the
   * window on every player playlist-refresh -- WITHOUT any plugin call while it plays and without ever fetching a
   * playlist from the CDN. Every specific (CDN template, channel code, duration lattice, clock, anchor, window) is
   * plugin-supplied data, so ANY plugin uses it with ITS own CDN; nothing is hardcoded. The player then downloads the
   * segments the synthesized playlist lists straight from the CDN (deviceless, each viewer from its own IP).
   *
   * When `clockLive` is present `url` is IGNORED (as with `external`), and `drm`, `signing`/`signContext`/
   * `alternateHosts`, `external`, `alternatives`, `audioTracks`, `durationMs`, `skip` and `expiresInSeconds` are ignored
   * next to it (a clock window has no single URL, fixed length or expiry). Valid ONLY on a `live` stream (resolve() of a
   * `live` item, or an inline liveChannels[].stream); on a non-live stream it refuses. `headers` and `subtitles` still
   * apply to every synthesized request. Each concrete segment URL (after substitution) is checked exactly like `url`
   * against the plugin's live host grant (`liveStreamHosts: "any"` -- which needs `channels` -- or `streamHosts: "any"`,
   * or a declared host; http is allowed for a live channel, never the LAN). An older Kino ignores `clockLive` and, finding
   * `url` empty, refuses the stream: a plugin targeting older apps must also give a real `url` or gate on `kino.apiVersion`.
   */
  clockLive?: KinoClockLive;
}

/**
 * apiVersion 27: the parameters Kino needs to synthesize a clock-enumerated live HLS playlist (see `KinoStream.clockLive`).
 * Kino computes, for wall-clock `now`: `D(k) = Σ grid[(firstStep+i) mod grid.length]` (media-ms from segment `s` to `s+k`,
 * `k<0` walks the lattice backward); segment `s+k` begins at wall time `anchor.t + D(k)·(1000/rate)`; the live index is
 * `anchor.s + max{k : that time ≤ now}`; the emitted window is the indices `[live−behind−count+1 … live−behind]`, each line
 * `#EXTINF:grid[phase]/1000`, `#EXT-X-MEDIA-SEQUENCE` a monotonic per-segment ordinal, `#EXT-X-TARGETDURATION =
 * ceil(max(grid)/1000)`, no `#EXT-X-ENDLIST`. With `reanchor`, Kino replaces the predicted edge with the one it probes.
 * Parts that could mislocate the window or fetch an unintended URL REFUSE the stream (bad `grid`, `template` without `{seg}`,
 * an unknown placeholder, a bad `anchor`, a host-rule failure); tuning knobs (`rate`, `reanchor`, `window`, `segWidth`,
 * `firstStep`) are clamped/defaulted and logged, never refusing.
 */
interface KinoClockLive {
  /**
   * The segment-URL template. `{seg}` (the integer segment number) is REQUIRED and may repeat; `{mc}` (the `mediaCode`)
   * is optional and may repeat. e.g. `"http://cdn/live/{mc}/{mc}_cyx_cj_{seg}.ts"`. At most 2048 characters. No `{seg}`,
   * or any other `{…}` placeholder, REFUSES the stream (a typo must never be fetched literally).
   */
  template: string;
  /**
   * Substituted for every `{mc}`. Required when the template uses `{mc}`, ignored otherwise. Pattern
   * `^[A-Za-z0-9._~-]{1,128}$` (the live-channel code shape: a safe token, never a slash, path segment or host, so it
   * cannot inject a new host or traverse the path).
   */
  mediaCode?: string;
  /**
   * The repeating lattice of per-segment durations in ms, e.g. `[4004, 6006]`: a segment at lattice-phase `p` lasts
   * `grid[p]` ms and the phase advances `p → (p+1) mod grid.length` each segment. 1 to 16 entries, each a finite integer
   * in 200..60000, with a positive sum. A missing, empty or bad grid REFUSES the stream (the `#EXTINF` durations and the
   * valid segment numbers would be unknowable).
   */
  grid: number[];
  /**
   * Media-clock speed: ms of media advanced per 1000 ms of wall clock. Default 1000 (realtime); clamped to 500..2000.
   * Lets the window track real time when `Σ grid` is not an exact multiple of a second (e.g. the NTSC 1001/1000 drift that
   * makes `[4004, 6006]` sum to 10010). A non-number is dropped to the default and logged.
   */
  rate?: number;
  /**
   * Pins the clock to the segment lattice: at wall-clock epoch `t` (ms, UTC) the segment numbered `s` begins, sitting at
   * lattice-phase `firstStep` (0-based index into `grid`, default 0). `t` and `s` are REQUIRED; a missing or bad anchor
   * REFUSES the stream (the live edge cannot be located). `firstStep` out of range is dropped to 0 and logged.
   */
  anchor: { t: number; s: number; firstStep?: number };
  /**
   * Robustness: instead of trusting the clock blindly, Kino re-pins the live edge by probing real segment URLs around its
   * predicted edge every `everySec` seconds, scanning up to `probeSpan` segments each way, to absorb device↔CDN clock skew
   * and keep latency honest. Omit the whole object to trust the clock exactly. Both are clamped, never refusing:
   * `everySec` 60..21600 (default 1200 — the reference backend re-pins every ~20 min), `probeSpan` 0..12 (default 4; 0
   * keeps the periodic re-pin but probes only the estimated edge).
   */
  reanchor?: { everySec?: number; probeSpan?: number };
  /**
   * The sliding window Kino emits: `count` segments ending `behind` segments before the computed live edge (a latency
   * cushion against half-written newest segments). `count` default 6 (clamped 2..20), `behind` default 3 (clamped 0..20).
   * Clamped and logged, never refusing.
   */
  window?: { count?: number; behind?: number };
  /**
   * Optional zero-pad width for `{seg}` (0..12, default 0 = no padding) so `{seg}` renders e.g. `"000042"` when the CDN
   * names segments with fixed-width indices. A bad value is dropped to 0 and logged.
   */
  segWidth?: number;
}

/**
 * apiVersion 13, capability "byteSource": a stream whose bytes the plugin itself serves, instead of a URL. Kino pulls them
 * by calling the plugin's `read` export (see `KinoPlugin.read`). `handle` is opaque to Kino (1..512 characters, the plugin
 * decides what it means); `size` is the total byte length; `mime` the media type (e.g. "video/mp4"). It casts to a
 * Chromecast or a DLNA TV (served from the phone over the LAN, every byte still from `read`) when `mime` is a video or audio
 * file type other than MPEG-TS; it is never downloaded (declaring "download" is pointless for such streams).
 */
interface KinoPluginByteStream {
  source: "plugin";
  handle: string;
  size: number;
  mime: string;
}

/**
 * apiVersion 13, capability "imageSource": a picture whose bytes your plugin serves, instead of a URL. Accepted wherever
 * an item's `poster` or `backdrop`, an episode's `still`, a series' (or `details`') `poster`/`backdrop` or a section hero's
 * `image` is read; anywhere else (a channel logo, a category's art, a `meta` answer, a layout image), and from a plugin
 * that does not declare "imageSource", it is ignored like a bad URL. `handle` is yours and opaque to Kino: 1 to 512
 * characters, no control characters (a malformed reference is simply no image, the item stays).
 *
 * When a card with such an image comes on screen, Kino calls your `image({ handle })` export ({@link KinoPlugin.image}),
 * at most one call at a time for your plugin, never while one of your byte streams is open or your `read` runs (it waits
 * for that to end, at most 20 s), and keeps the picture in its image cache: the same handle of the same installed version is asked once.
 * Make handles stable (the same picture, the same handle) and never put a secret in one: Kino stores it like a poster URL
 * wherever the title is saved (library, history), which sync to the person's other devices and go into backups. There it
 * shows the placeholder, and a saved row keeps it (Kino never rewrites it): a reference only loads on the device whose Kino
 * read it from your answer.
 *
 * @example
 * export async function home() {
 *   return [{ id: "new", title: "New", items: [
 *     { id: "v1", ref: "video:1", title: "Holiday", kind: "movie", poster: { source: "plugin", handle: "thumb:1" } },
 *   ] }];
 * }
 * export async function image({ handle }) {
 *   const bytes = kino.storage.get(handle);              // a base64 JPEG you saved when you indexed the video
 *   if (!bytes) throw kino.error("not_found", "no thumbnail");
 *   return { bytes, mime: "image/jpeg" };
 * }
 */
interface KinoImageRef {
  source: "plugin";
  handle: string;
}

/**
 * What `image({ handle })` answers (apiVersion 13, "imageSource"): the picture, base64-encoded (canonical: the standard
 * alphabet, padded, no whitespace), at most 262,144 bytes (256 KB) once decoded, and its type, one of "image/jpeg",
 * "image/png" or "image/webp", which the bytes must really be (their first bytes are checked). Anything else, a throw or
 * no answer within 10 s shows the card's placeholder, and Kino does not ask for that handle again for 5 minutes; two
 * timeouts in a row pause all your images for 5 minutes.
 */
interface KinoImageAnswer {
  bytes: string;
  mime: "image/jpeg" | "image/png" | "image/webp";
}

/** What a stream's source says about the media itself (`KinoStream.media`). */
interface KinoStreamMedia {
  /** The file's own name or a title for it. */
  title?: string;
  /** Bytes of the file being served (0..2^50). */
  sizeBytes?: number;
  /** The container as the source names it ("matroska,webm", "mp4"…). Display only: never given to the player. */
  container?: string;
  video?: {
    codec?: string;
    profile?: string;
    width?: number;
    height?: number;
    fps?: number;
    /** 0..16 */
    bitDepth?: number;
    hdr?: boolean;
  };
  /** The FILE's audio tracks, converted or not. */
  audio?: { codec?: string; channels?: number; language?: string; title?: string; default?: boolean }[];
  /** The FILE's subtitle tracks; `text` is true for the text formats (SubRip, ASS, WebVTT…) as opposed to bitmaps (PGS…). */
  subtitles?: { codec?: string; language?: string; title?: string; text?: boolean }[];
  /** The source re-encoded the file to make it playable: what it serves is not what the file holds. */
  converted?: boolean;
  /** Short plain remarks in the source's own words, at most 4. */
  notes?: string[];
}

/**
 * One of a Stream's `alternatives`: a URL (labelled from apiVersion 6), (apiVersion 6) a lazy `{ label, ref }`, or
 * (apiVersion 11) an external hand-off.
 */
type KinoStreamAlternative =
  | { url: string; mime?: string; headers?: Record<string, string>; label?: string }
  | { ref: string; label?: string }
  | { external: { protocol: string; ref: string; resolver?: string }; label?: string };

/** apiVersion 3, capability "channels": a section of the En vivo tab. */
interface KinoLiveCategory {
  id: string;
  title: string;
  /** ISO 3166 alpha-2, e.g. "CO". Informational. */
  country?: string;
  /**
   * What the row (or category, or list) is about, from Kino's closed vocabulary: "peliculas", "series", "anime",
   * "infantil", "documentales", "deportes", "noticias", "musica", "entretenimiento" or "otros". Kino groups Categorías
   * by it and filters En vivo by it across plugins. Optional: without it Kino guesses from the title; a value outside
   * the list is ignored. Kino versions before this field ignore it.
   */
  genre?: KinoGenre;
  /** apiVersion 6: true = an 18+ entry, shown only while the person's 18+ code is unlocked on that device (Ajustes ▸ Control parental). Below apiVersion 6 it is dropped. Every channel listed in it is 18+ too. */
  adult?: boolean;
}

/**
 * apiVersion 3: an M3U playlist Kino downloads itself (from a declared host only, never under
 * `liveStreamHosts: "any"`), with an optional XMLTV guide. Put it next to your categories in the
 * `liveCategories()` answer, or return it alone. At most 10 per answer. `refreshHours` is 1..168,
 * default 12. `hideGroups` are group titles not to show (case-insensitive), at most 50. With
 * `resolve: true` each entry plays through your `resolve(<entry url>)` instead of directly.
 */
interface KinoPlaylist {
  playlist: {
    url: string;
    format: "m3u";
    headers?: Record<string, string>;
    /**
     * Headers the PLAYER sends for every channel of the list: a `User-Agent` some channels only answer to, a
     * `Referer`. Filtered like a Stream's `headers` (at most 20). Kept apart from `headers` on purpose: those carry
     * the list's own credentials and go only to the list's host, never to the hosts the channels are on. A header an
     * M3U entry names itself (`#EXTVLCOPT:http-user-agent=...`) wins. Kino versions before this field ignore it.
     */
    streamHeaders?: Record<string, string>;
    /** The [genre](KinoLiveCategory) of every group this list produces; without it Kino guesses from each group's title. */
    genre?: KinoGenre;
    epg?: { url: string; format: "xmltv" };
    refreshHours?: number;
    hideGroups?: string[];
    resolve?: boolean;
  };
}

/**
 * apiVersion 10, capability "playlists": one of the person's own playlists on that plugin's service
 * (not an M3U/IPTV channel list — see {@link KinoPlaylist} for that, an unrelated, older concept).
 */
interface KinoHostedPlaylist {
  id: string;
  title: string;
  itemCount: number;
}

/**
 * One channel: give `ref` (resolved on play, exactly like a `live` item's) or `stream` (played as
 * is, checked like `resolve()`'s answer). With both, the stream plays and `ref` is the fallback.
 * An `id` starting with `~` is reserved for Kino and dropped.
 */
interface KinoLiveChannel {
  id: string;
  title: string;
  ref?: string;
  stream?: KinoStream;
  /**
   * In liveChannels, informational: the channel is listed under the category it was asked for. Not a valid id = empty.
   * In a liveSearch hit (apiVersion 6), the category it belongs to: one of your 18+ categories makes it 18+, a plain one
   * makes it plain. A hit with neither `categoryId` nor `adult` counts as 18+ when you have any 18+ category.
   */
  categoryId?: string;
  /** https image, like a poster. */
  logo?: string;
  /** 1..9999. */
  number?: number;
  /**
   * apiVersion 6: true = an 18+ entry, shown only while the person's 18+ code is unlocked on that device (Ajustes ▸ Control parental).
   * Below apiVersion 6 it is dropped. On a liveSearch hit, `false` says it is plain (needed when your categories can't be
   * read and it carries no `categoryId`): mark every hit with `adult` or `categoryId`.
   */
  adult?: boolean;
}

interface KinoLiveChannelPage {
  items: KinoLiveChannel[];
  /** Opaque cursor for the next page; omit or null at the end. */
  next?: string | null;
}

/** One programme. `start`/`end` are epoch milliseconds. */
interface KinoGuideEntry {
  channelId: string;
  title: string;
  start: number;
  end: number;
  description?: string;
}

/** apiVersion 6, capability "migrate": one value Kino stored and can no longer open. */
type KinoMigrateInput =
  | { kind: "title"; ref: string }
  | { kind: "chapter"; ref: string; season: number | null; episode: number | null }
  | { kind: "live"; provider: string; code: string };

/**
 * Your answer: the same id/ref you would return from search() today. `ref` never starts with "plg1:".
 * "music" and "podcast" need apiVersion 8 (below it such an answer is no claim). They move in the shape your
 * plugin saves them in: with the "episodes" capability as an album or show, chapter by chapter like a series;
 * without it as a lone track, like a movie, and only when one row is saved.
 */
type KinoMigrateAnswer =
  | { kind: "movie" | "series" | "music" | "podcast"; id: string; ref: string }
  | { kind: "episode"; ref: string; season?: number; number: number }
  | { kind: "live"; code: string };

/** apiVersion 6, with `"section": { "label" }` in the manifest: your own section (TV sidebar, chip atop Inicio on the phone). Kino 0.9.55: an optional `"labelEn"` (same 20-character limit) is the entry's text when the app is in English; `label` stays the Spanish default and the fallback. */
interface KinoSectionAnswer {
  /** At most 8; each `id` matches the item id pattern, each `label` at most 24 characters. */
  tabs?: { id: string; label: string }[];
  /** The tab this answer is for; an unknown or missing one reads as the first tab. */
  tab?: string;
  /** A banner above the rows: `title` as an item title, `text` at most 300 characters, `image` http or https (the Images rule), or with "imageSource" (apiVersion 13) a {@link KinoImageRef}. */
  hero?: { title: string; image?: string | KinoImageRef; text?: string };
  /** The same shape and limits as `home`. */
  rows: KinoRow[];
}

/** apiVersion 6, optional, needs the `browse` capability: a tile of your Categorías group; it opens `browse(ref, null)`. */
interface KinoCategory {
  /** The item id pattern. */
  id: string;
  /** At most 40 characters. */
  title: string;
  /** http or https image (the Images rule), same rules as a poster. */
  art?: string;
  /** At most 4096 characters. */
  ref: string;
  /** apiVersion 6: true = an 18+ entry, shown only while the person's 18+ code is unlocked on that device (Ajustes ▸ Control parental). Below apiVersion 6 it is dropped. */
  adult?: boolean;
}

// ---------- apiVersion 9 (Kino 0.9.55): the player panel ----------
// A button in the player, shown only while YOUR content plays, opens a panel you describe with `panel(context)`. Kino
// validates every answer; an invalid element is dropped (and logged), a panel that is not an object shows nothing. The
// kit runs the same validation: node sdk/run.mjs <plugin dir> panel|panelAction|playerEvent. Layout limits: at most 40
// top-level elements, 120 nodes in all, 4 levels deep, 6 children per row.

/** What the player knows about the title playing when `panel`, `panelAction` or `playerEvent` is called (exactly these keys; an absent optional is left out). */
interface KinoPanelContext {
  kind: "movie" | "episode" | "live";
  /** The ref of the title that plays, exactly as you gave it. */
  ref: string;
  title: string;
  year?: string;
  season?: number;
  episode?: number;
  episodeTitle?: string;
  ids: { tmdb?: number; imdb?: string; tvdb?: number; mal?: number; anilist?: number; kitsu?: number };
  /** The copy playing now. */
  playing: { label?: string; lang?: string; quality?: string; server?: string };
  positionMs: number;
  /** Absent for live or while the player does not know it. */
  durationMs?: number;
  paused: boolean;
  /** The back/forward step in effect, ms. */
  seekStepMs: number;
  /** Read-only playback stats; only what the player knows. */
  stats: {
    width?: number; height?: number; videoCodec?: string; audioCodec?: string; bitrateKbps?: number; bufferedMs?: number;
    droppedFrames?: number; network?: "wifi" | "ethernet" | "cellular" | "other"; stallsThisSession?: number;
  };
  device: "tv" | "phone";
  /** The app's language, "es-CO" or "en-US" style. */
  lang: string;
  /** The tab the person asked for (a tab press calls `panel` again with it). */
  tab?: string;
  /** What you saved with `values`/`save`: per title (`video`) and for the whole plugin (`plugin`). */
  values: { video: Record<string, KinoPanelValue>; plugin: Record<string, KinoPanelValue> };
  /** The player's own properties in effect: the step, the speed, the resize mode and your `autoNext` when you set one. */
  player: { seekStepMs: number; speed?: number; resize?: KinoPlayerResize; autoNext?: { enabled: boolean; countdownS: number; nextRef?: string } };
  /**
   * Kino 0.9.64 (additive): what this Kino draws beyond apiVersion 9's panel; `"loading"`: the `loading` element. Absent on
   * an older Kino, which drops that element: check it before you answer with one.
   */
  features?: ("loading" | "screen")[];
  /**
   * apiVersion 14 (Task 8k), only in a tab YOUR plugin contributes to another plugin's title (`"panel": { "contributes": true }`
   * and the `playerPanelTab` capability): `true`. Then `ref` is an opaque id (`"foreign:"` and 32 hex characters, keyed by the
   * install: the same title gives you the same id on that device, never the other plugin's ref; opaque, not secret), `playing`
   * is empty, `player.autoNext` is left out, and `values` are your own. `title`, `year`, `ids`, `season`, `episode` and the
   * position are given. Only a plugin's title (never an 18+ one, nor M3U lists or the person's own channels).
   */
  foreign?: true;
  /**
   * apiVersion 14 (Task 8k), with `foreign`: the plugin that provides the stream playing, its public id and name (so a tab can
   * tell whether two people watch through the SAME source). Never its ref.
   */
  source?: { pluginId: string; name: string };
}

type KinoPanelValue = string | boolean | number | null;
type KinoPlayerResize = "fit" | "fill" | "zoom" | "4:3" | "16:9" | "21:9";
/** `scope` of an input: `plugin` (default) is one value for all your titles, `video` one per title. */
type KinoPanelScope = "video" | "plugin";

/**
 * Rows, columns and cards around leaves (the one layout model of the player panel and of `settingsLayout`). `hidden: true`
 * keeps a node out of sight, `enabled: false` greys it out and takes it out of focus (a settings layout ignores both).
 * Limits: depth 4, a row keeps 6 children, `col.weight` 1 to 12 (else 1), 120 nodes in all, card `title` 60 characters.
 */
type KinoLayoutNode<Leaf> =
  | { type: "row"; children: KinoLayoutNode<Leaf>[]; gap?: "none" | "small" | "medium" | "large"; align?: "start" | "center" | "end" | "stretch"; stackOnNarrow?: boolean; enabled?: boolean; hidden?: boolean }
  | { type: "col"; children: KinoLayoutNode<Leaf>[]; weight?: number; gap?: "none" | "small" | "medium" | "large"; align?: "start" | "center" | "end" | "stretch"; enabled?: boolean; hidden?: boolean }
  | { type: "card"; title?: string; titleEn?: string; children: KinoLayoutNode<Leaf>[]; style?: "plain" | "outlined" | "filled"; enabled?: boolean; hidden?: boolean }
  | (Leaf & { enabled?: boolean; hidden?: boolean });

/**
 * A leaf of a panel. `key` (1 to 128 of A-Z a-z 0-9 . _ ~ -) names what holds a value or can be pressed and is unique
 * across the whole panel; a label is 1 to 40 characters. Every text has an optional `...En` twin shown when the app is in English.
 */
type KinoPanelElement =
  | { type: "section"; title: string; titleEn?: string; text?: string; textEn?: string }
  | { type: "text"; text: string; textEn?: string }
  /** At most 200 characters. */
  | { type: "status"; text: string; textEn?: string }
  /** https only, on a public host; `alt` up to 200 characters. */
  | { type: "image"; url: string; aspect?: "16:9" | "2:3" | "1:1" | "banner"; alt?: string; altEn?: string }
  /** `confirm` (up to 160 characters) asks first. Pressing calls `panelAction` with trigger "press". */
  | { type: "button"; key: string; label: string; labelEn?: string; confirm?: string; confirmEn?: string;
      /** Task 7g: the press opens this plugin's own screen over the player, no panelAction call; `pause` pauses the video. */
      go?: { screen: KinoScreenOpen }; pause?: boolean }
  /** `autoSave: true` saves each change by itself (trigger "change"). `hint` up to 80 characters. */
  | { type: "toggle"; key: string; label: string; labelEn?: string; scope?: KinoPanelScope; hint?: string; hintEn?: string; autoSave?: boolean }
  /** 1 to 20 options, `value` and `label` 1 to 40 characters, values distinct. */
  | { type: "select"; key: string; label: string; labelEn?: string; scope?: KinoPanelScope; options: { value: string; label: string; labelEn?: string }[]; hint?: string; hintEn?: string; autoSave?: boolean }
  /** `placeholder` up to 40 characters; Enter calls `panelAction` with trigger "submit". */
  | { type: "text-input"; key: string; label: string; labelEn?: string; scope?: KinoPanelScope; hint?: string; hintEn?: string; placeholder?: string; placeholderEn?: string }
  /** https, up to 512 characters, on a public host with a dot, or a public IPv4 address (never the device or the home network: no single-label or local name, private address or IPv6 literal). */
  | { type: "qr"; url: string; label?: string; labelEn?: string }
  /**
   * Kino 0.9.64 (additive, any apiVersion): a spinner, with `text` beside it (else Kino's «Cargando…»). Answer at once
   * with the tab's shell and this element, and set `refreshMs` so Kino asks again for the finished tab. Send it only when
   * `context.features` includes "loading": an older Kino drops it as an unknown element (answer a `status` line there).
   */
  | { type: "loading"; text?: string; textEn?: string }
  /** The series' episodes, the current one highlighted; choosing one plays it. */
  | { type: "episodes"; ref: string }
  /** Not in this Kino: dropped ("needs a newer Kino"). Reserved for a later version. */
  | { type: "ai"; [field: string]: unknown }
  /** Not in this Kino: dropped ("needs a newer Kino"). Reserved for a later version. */
  | { type: "chat"; [field: string]: unknown };

/** What `panel(context)` returns. A tab press calls it again with `context.tab`; `refreshMs` calls it again by itself. */
interface KinoPanel {
  /** Up to 60 characters. */
  title?: string;
  titleEn?: string;
  /**
   * Accepted for compatibility; both values look the same: the panel is a drawer over the whole player
   * (from the right on TV and a phone held sideways, from the bottom on a phone held upright). The video keeps playing.
   */
  presentation?: "modal" | "panel";
  /** `#RRGGBB`; kept only when it passes the same rules as the manifest theme's `accent`. */
  accent?: string;
  /** Asks Kino to call `panel` again every so often: 2000 to 60000 ms (clamped). */
  refreshMs?: number;
  /** At most 6: `id` as a key, `label` up to 24 characters. */
  tabs?: { id: string; label: string; labelEn?: string; badge?: KinoScreenBadge }[];
  /** The tab shown; the first one when absent or unknown. */
  tab?: string;
  elements: KinoLayoutNode<KinoPanelElement>[];
  /**
   * Task 8j (apiVersion 14): a player action of the result itself, e.g. a `refreshMs` tick that keeps the video in step with
   * something. It is not the person's press, so it counts only with the `playerControl` capability (see `KinoPlayerAction`).
   */
  player?: KinoPlayerAction;
}

/** Why `panelAction` is called: a button pressed, an input changed or submitted. "tab" and "open" are reserved: this Kino never sends them. */
interface KinoPanelEvent {
  /** The element's key. */
  key: string;
  trigger: "press" | "change" | "submit" | "tab" | "open";
  /** Every input's value on screen now (saved or not yet). */
  values: Record<string, KinoPanelValue>;
  /** The new value, for "change" and "submit". */
  value?: KinoPanelValue;
}

/**
 * What the plugin asks the player to do (every field optional). Bounds below are applied by Kino, which clamps or drops what is
 * outside them.
 *
 * A plugin that plays nothing (a player-panel tab, say) may declare `playerControl` only beside a `panel` (its own, or
 * `"contributes": true` with `playerPanelTab`); without one it is refused (contract.json `capabilities.playerControlNeedsPanelMessage`).
 *
 * Who may ask what (contract.json `kinoPlayerControl`, Task 8j): the plugin whose title plays may use every field after the
 * person's press, change or submit in its panel and in a `playerEvent` answer, except `pause`, which needs a press; a panel
 * result's own `player` (`KinoPanel.player`, a `refreshMs` tick) never counts. A tab contributed to another plugin's title may
 * only `seekToMs`, after a press in it. With the `playerControl` capability (approved by the person on a red line, revocable in
 * Ajustes: never assume it) every origin counts, and a contributed tab may also `pause` and set the `speed` (never stored: it
 * ends with the title, and the person's own speed wins). Such an action is announced to the person with a short notice naming
 * your plugin ("Party Chat: pausado"), which you cannot word or hide; it is dropped while Kino is not in front (the app in the
 * background, a Kino page over the player), one of Kino's dialogs is up or the person is seeking, on live only `pause` counts,
 * at most 30 a minute and one a second. One seek or pause a second, always. A `pause` is dropped while the video is cast
 * (Chromecast or DLNA) and when the video is already in that state (check `context.paused`). A `panel` inside an answer carries
 * no `player` of its own.
 */
interface KinoPlayerAction {
  /** Ms from the start, clamped to 0..duration; ignored on live. At most one seek or pause per second. */
  seekToMs?: number;
  /** Task 8j: `true` pauses the video, `false` resumes it (anything else is dropped). Never stored; at most one seek or pause per second. */
  pause?: boolean;
  /** The back/forward step: 5000 to 120000, whole seconds. */
  seekStepMs?: number;
  /** One of 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2. */
  speed?: number;
  resize?: KinoPlayerResize;
  /** The same block as a Stream's `skip`: the skip-intro/outro button. */
  skip?: { openingStartMs?: number; openingEndMs?: number; endingStartMs?: number };
  /** At most 30 dots on the progress bar; `label` up to 24 characters; selecting one seeks there. */
  markers?: { atMs: number; label: string }[];
  /** The end-of-episode countdown: `countdownS` 0 to 30, required when `enabled` (left out it is 0 when disabled). */
  autoNext?: { enabled: boolean; countdownS?: number; nextRef?: string };
}

/** What `panelAction` (and, for `player`, `message` and `panel`, `playerEvent`) may return. `null` is "nothing to do". */
interface KinoPanelAnswer {
  /** A whole new panel (Task 8i: either format, `KinoPanelScreenResult` too; in a `playerEvent` answer it shows in the open panel). */
  panel?: KinoPanel | KinoPanelScreenResult;
  /** Replaces single elements in place, by key (at most 40 entries); each is one node, validated like any element. */
  patch?: Record<string, KinoLayoutNode<KinoPanelElement>>;
  /** Values to show now (at most 120 keys; strings up to 500 characters). */
  values?: Record<string, KinoPanelValue>;
  /** Keys of `values` (or on-screen inputs) to keep: at most 50. */
  save?: string[];
  /** The key to move focus to. */
  focus?: string;
  /** A short toast for the person (up to 160 characters); shown only when it passes the rules a `userMessage` does. */
  message?: string;
  player?: KinoPlayerAction;
  /**
   * Task 7g: opens this plugin's own screen over the player (the panel closes). Task 8m: or `titleByIds`, Kino's own title page
   * by ids ([KinoScreenTitleByIds]), honoured only in the answer to the person's press or submit (a change's and a
   * `playerEvent`'s are dropped, logged). Task 8s: or `url`, a link Kino asks the person about first ([KinoScreenUrl]), under
   * the same press-only rule. Task 8x: or `copy` ([KinoScreenCopy]), the same rule, the panel stays open. No other shape.
   */
  go?: { screen: KinoScreenOpen } | { titleByIds: KinoScreenTitleByIds } | { url: KinoScreenUrl } | { copy: KinoScreenCopy };
  /** With `go`: pause the video under the screen. Default false: it keeps playing. */
  pause?: boolean;
}

/** What `playerEvent` is told. `failed` carries `kind`; `copyChanged` carries `automatic`, `label` and, after an automatic change, the last copy's failure `kind`. */
interface KinoPlayerEvent {
  type: "started" | "paused" | "resumed" | "ended" | "failed" | "copyChanged";
  kind?: string;
  label?: string;
  automatic?: boolean;
}

/**
 * One of Kino's icons by name (Material Symbols, outlined; tinted by the colour role around it). The first sixteen since
 * apiVersion 9; the rest (Task 8v, `refresh` the circular arrow among them) from apiVersion 14: below it such a name is an
 * unknown one (a panel button draws `tune`). The screen surface (apiVersion 14) knows every name. The User interface guide
 * lists what each one means.
 */
type KinoIconName =
  | "info" | "tune" | "settings" | "star" | "bolt" | "language" | "subtitles" | "list" | "magic" | "heart" | "movie"
  | "tv" | "sports" | "music" | "bookmark" | "help"
  // apiVersion 14:
  | "refresh" | "sync" | "add" | "remove" | "delete" | "edit" | "search" | "close" | "check" | "share" | "play"
  | "pause" | "download" | "upload" | "link" | "open_in_new" | "home" | "person" | "lock" | "notifications"
  | "warning" | "error" | "visibility" | "copy" | "arrow_back" | "arrow_forward" | "expand_more" | "expand_less"
  | "more_vert" | "filter_list" | "calendar" | "schedule" | "send" | "mood";

/**
 * The manifest's `panel` (apiVersion 9): the player's button. `label` 1 to 24 characters (`labelEn` the English one),
 * and `icon` (a [KinoIconName]; another name, or a name of the larger set below apiVersion 14, draws tune) or
 * `iconFile`, a relative .png of exactly 96x96 px with an alpha channel, at most 24 KB (only its alpha is drawn), never both. Declaring it makes `panel` required.
 */
interface KinoManifestPanel {
  label: string; labelEn?: string; icon?: KinoIconName; iconFile?: string;
  /**
   * apiVersion 14 (Task 8k): `true` adds a TAB to the player panel of ANY plugin's title (never an 18+ one), after Kino's own
   * and the playing plugin's, in the person's order (Ajustes, «Paneles del reproductor»), at most 6 tabs in all. Needs the
   * `playerPanelTab` capability (and it needs this), which the person approves with a red line (your tab SEES what they watch
   * while it is open) and can hide again («Mostrar en el reproductor»). `label` may then be left out (your plugin's name stands
   * in); the tab is always labelled with your plugin's name and icon. Your `panel(context)` is the same contract, with
   * `context.foreign` and `context.source`; it is called only while your tab is the selected one and the drawer is open, and
   * `playerEvent` reaches you only then too (it stops when your tab or the drawer closes). Your tab reads your plugin's name
   * and icon (never Kino's `info` icon; a name like "Kino" is shown as "Plugin «<name>»"). Your `player` actions count only in
   * the answer to a `panelAction` after a press in your tab, and only `seekToMs` (with the `playerControl` capability, Task 8j:
   * from any origin, and `pause` and `speed` too); `go.title` / `go.play` are dropped.
   */
  contributes?: boolean;
  /**
   * apiVersion 14 (Task 11), only with `contributes: true`: which content your tab joins. "title": a plugin's title (the rule
   * above); "live": an En vivo channel, after Kino's own «General» tab, with `context.kind === "live"` (`KinoLivePanelContext`:
   * the channel, never a position) and `go.liveChannel` to tune. Default `["title"]`; a non-empty list of these two (an
   * unknown value or an empty list refuses the install).
   */
  kinds?: ("title" | "live")[];
}

/**
 * The manifest's `settingsLayout` (apiVersion 9): where the settings of the form go. A list of rows, columns and cards
 * around `{ setting: "<key>" }`, `{ type: "text", text }` and `{ type: "image", url }` leaves. Settings left out are
 * added at the end in manifest order; an unknown or repeated key is ignored by Kino (and refused by the kit's validate).
 */
type KinoSettingsLayoutLeaf = { setting: string } | { type: "text"; text: string; textEn?: string } | { type: "image"; url: string; aspect?: "16:9" | "2:3" | "1:1" | "banner" };
type KinoSettingsLayout = KinoLayoutNode<KinoSettingsLayoutLeaf>[];

/**
 * The manifest's `screen` (apiVersion 14, capability `"screen"`): the menu entry of the plugin's full-screen canvas.
 * `label` 1 to 20 characters (`labelEn` the English one), `icon` (a [KinoIconName]) or `iconFile` (a 96x96 .png, never both).
 * `menuOpens` says what the entry opens: `"section"` (the rows of cards, needs the `section` field), `"screen"` (the canvas) or
 * `"both"` (two entries, needs `section`); default `"section"` when `section` is declared, else `"screen"`. `adult: true` shows
 * the entry only while the 18+ code is unlocked. The capability may stand alone and needs the exports `screen` and `screenEvent`.
 * `settingsIn` says where the plugin's settings show: `"settings"` (Kino's settings list), `"screen"` (only the plugin's own
 * screen: Kino hides the settings form in its settings list while the screen can be opened; refused with `menuOpens: "section"`)
 * or `"both"` (the default). Either way they are the same, real settings (`kino.config`). `every`: timers that run whenever
 * the screen is open, as a tree root's `every` (KinoScreenTimer); a bad one is dropped and logged, never refused.
 * `opensFrom` (Task 7g) says where the screen opens from: `"menu"` (the icon: TV sidebar, phone Inicio strip) and/or
 * `"settings"` (a button at the top of the plugin's own settings page); default `["menu"]`, never empty. Without `"menu"` there
 * is no icon and no entry: `icon`, `iconFile` and `menuOpens` are not needed and are ignored (a `section` keeps its entry as
 * today). `settingsIn: "screen"` needs some way in: `menuOpens` `"screen"`/`"both"` or `"settings"` in `opensFrom`; its settings
 * page then shows only the button (and Kino's own switches) while the screen can open, and the form whenever it cannot.
 * `settingsButton` names that button (`label`, `labelEn`, each 1 to 40 characters once control characters are removed);
 * default Kino's «Abrir pantalla» / "Open screen".
 */
interface KinoManifestScreen {
  label: string; labelEn?: string; icon?: KinoIconName; iconFile?: string; menuOpens?: "section" | "screen" | "both"; adult?: boolean;
  settingsIn?: "settings" | "screen" | "both"; every?: KinoScreenTimer | KinoScreenTimer[];
  opensFrom?: ("menu" | "settings")[]; settingsButton?: { label?: string; labelEn?: string };
  /**
   * Task 8: what the screen takes the place of. `["categories"]`: while the screen can open, every place Kino opens THIS plugin's
   * categories (a tile of its group in Kino's Categorías, a `go: { categories: true }` from its other routes or from the player
   * panel's screen) opens the screen at the route `categories` with `args: { from: "categories" | "screen" | "panel", category? }`
   * (`category`: the tile's `ref`, when a tile was pressed; `from: "panel"` when its screen over the player asks, which then
   * starts again in place there). With screens switched off or the screen hidden (18+ locked, plugin off), Kino's own
   * Categorías shows instead. When its FIRST opening fails (`screen()` throws, times out, an invalid tree), Kino shows the
   * pressed tile's own "Ver más" list instead (no tile: Kino's Categorías), logs it, and the plugin's tiles skip the screen
   * until the app restarts; a failure later, while it is in use, keeps the screen's error state and its «Reintentar». A
   * `go: { categories: true }` sent FROM that `categories` route
   * opens Kino's own screen (never itself again). Needs a catalog to fall back on: the `browse` capability and the
   * `categories` export (refused at install otherwise). Build it from `titleRail`, `titleGrid`, `heroCard`, `TabBar`, `Chips` and
   * `go` (`browse` a category, `title`, `search`).
   */
  replaces?: "categories"[];
}

/**
 * The manifest's `slot` block (apiVersion 23, contract.json `playerSlot`): the elements the `playerSlot` capability draws in the
 * top-right corner of the TV player (never on a phone). It and the capability need each other. 1 to 3 elements; at most 3 are on
 * screen in all, across every plugin (`fixed` first, then the `overlay` ones, in the person's plugin order). The count, kinds and
 * modes are fixed here: `playerSlot` answers may change content only. A plugin with a `fixed` element shows a red consent line
 * ("Mostrará algo suyo de forma permanente en el reproductor mientras ves un video"), asked again by an update that adds one.
 * It may be a plugin's only capability: it plays nothing, so it needs neither `resolve` nor `search`.
 */
interface KinoManifestSlot {
  elements: KinoSlotElement[];
}

/** One declared element: `id` is lowercase letters, digits, `-` or `_`, starting with a letter, 1 to 24 characters, unique in the block. */
interface KinoSlotElement {
  id: string;
  /** What it shows; the answer for this id must be of this kind or it is dropped. */
  kind: "text" | "icon" | "image" | "button";
  /** `overlay` shows with the controls (VOD) or the channel card (live); `fixed` holds its place all the time and asks the person's approval. */
  mode: "overlay" | "fixed";
}

/**
 * The context of `playerSlot(context)` and of `playerSlotAction({ id, context })`: the player panel's context for the title playing
 * plus `live`. The title's own plugin gets the panel's whole context (`kind`, `ref`, `title`, ids, position, its saved values...) with
 * `live: false`; another plugin gets the contributed-panel one (`foreign: true`, an opaque `ref`, `source`); on an En vivo channel the
 * provider confirmed, the live panel's (`kind: "live"`, `channel`...) with `live: true`. For a title that reaches no other plugin (18+,
 * something no plugin owns, a title Kino cannot confirm) and a live channel Kino cannot confirm, the **bare** context:
 * only `live`, `foreign: true`, `device`, `lang` and `features` -- **no `kind`**, not even movie or series. Read `live` and `lang`
 * (such as "es-CO"); treat everything else as possibly missing.
 */
interface KinoSlotContext {
  live: boolean;
  foreign?: boolean;
  device: string;
  lang: string;
  features?: string[];
  /** Absent in the bare context. */
  kind?: string;
  [field: string]: unknown;
}

/**
 * One filled element in a `playerSlot` answer. `id` is a declared element; the other field(s) must match its `kind` -- `text` for a text
 * (a string; newlines split lines; at most 2 lines are kept, 2000 characters), `icon` (one of Kino's icon names) for an icon, `image`
 * (an https address on a public host) for an image, `label` (at most 40 characters) and/or `icon` for a button. Anything else is
 * dropped, not repaired; a repeated id keeps the first valid item.
 */
type KinoSlotItem = KinoSlotNudge & (
  | { id: string; text: string; size?: KinoSlotTextSize; weight?: KinoSlotTextWeight; color?: string; background?: string }
  | { id: string; icon: string }
  | { id: string; image: string }
  | { id: string; label?: string; icon?: string });

/** A text's weight: Inter 200, 300, 400, 500, 600 or 700 for every line (absent: Kino's own, the first line Medium and the next Regular). */
type KinoSlotTextWeight = "extralight" | "light" | "normal" | "medium" | "semibold" | "bold";

/** A text's size: 12, 14 (the default), 18 or 24 sp. */
type KinoSlotTextSize = "small" | "normal" | "large" | "xlarge";

/**
 * Any slot item may carry a nudge from its place in the row, in whole dp: `left` moves it right (negative: left), `top` moves it
 * down (negative: up). Clamped to -400..200 and -40..300; anything that is not a number counts as 0.
 *
 * A `text` may also set `color` (the letters) and `background` (the pill), each "#RRGGBB" or "#RRGGBBAA". An invalid field is
 * ignored on its own. The letters never get less than half opacity, a `color` under 2:1 contrast against an opaque pill (or Kino's
 * dark one when there is no `background`) is dropped, and Kino's white letters turn black on a light opaque pill. A `background`
 * with alpha 0 draws no pill.
 */
interface KinoSlotNudge { left?: number; top?: number }

/**
 * What `playerSlot(context)` returns. Kino keeps the items in declared order. If the answer is not an object with an `items` list the
 * last good frame stays (none the first time). Until the first good answer a failed call is retried every 5 s, at most 4 times.
 * Calls run unattended and never count toward "No responde".
 * With no "No responde" breaker for refreshes, a plugin that keeps timing out after its first frame is called again every `refreshMs` plus up to about 5 s.
 * Kino makes no call while it is in the background. A `fixed` slot's approval never carries over from a peer device or a backup: it is asked on each device.
 */
interface KinoSlotAnswer {
  items: KinoSlotItem[];
  /**
   * Call `playerSlot` again this many ms after the last call ended: raised to 2000 and lowered to 60000. Absent (or not a number):
   * never again.
   */
  refreshMs?: number;
}

/** What `playerSlotAction` receives when the person presses a declared button on screen (OK on the remote). */
interface KinoSlotActionEvent {
  /** The pressed element's id. */
  id: string;
  context: KinoSlotContext;
}

/**
 * What `playerSlotAction` returns; `null` or `{}` does nothing. `player` is an ordinary `KinoPlayerAction`, read by the panel's own
 * reader and sifted as a press (the plugin of the title playing keeps its fields; any other plugin only `seekToMs`, or with the approved
 * `playerControl` capability `seekToMs`, `pause` and `speed`), then through Kino's gate. On a live channel a plugin always counts as
 * another one and `seekToMs`, `seekStepMs`, `speed`, `skip`, `markers` and `autoNext` are dropped, so only `pause` can survive, and only
 * with the approved `playerControl` capability (which a plugin with only `playerSlot` cannot declare: it needs a `panel`).
 */
interface KinoSlotActionAnswer {
  /**
   * `true` opens this plugin's player panel (it needs a `panel` block or a contributed tab). If the panel is already open it is
   * not switched to your tab. On an En vivo channel it only has an effect when the channel's player offers plugin panel tabs;
   * otherwise (for example an own M3U channel) it is ignored and logged.
   */
  openPanel?: boolean;
  player?: KinoPlayerAction;
}

/**
 * The manifest's `enhancements` (read from the Kino of apiVersion 14; contract.json `manifest.enhancements`): features of a
 * newer apiVersion offered WITHOUT raising the plugin's own `apiVersion`, so a Kino that does not know them (it ignores this
 * key) still installs and runs the plugin as before. Keyed by the apiVersion that brought the feature, e.g.
 * `"enhancements": { "14": { "capabilities": ["screen", "library"], "screen": { "label": "Inicio" } } }` in a plugin that keeps
 * `"apiVersion": 8`. A Kino that knows a key merges its block over the manifest, keys in numeric order: `capabilities` are
 * ADDED (only `"screen"`, `"library"`, `"playerPanelTab"`, `"playerControl"`, `"room"`, `"schedule"`, `"shared"`, `"ai"` and `"playerSlot"`), `screen`,
 * `settings` (the whole list), `panel`, `jobs` and `slot` REPLACE the manifest's (`"playerPanelTab"` and a `panel` with `"contributes": true`
 * come together in one block, and so do `"schedule"` and its `jobs`; Task 18: a top-level `jobs` below apiVersion 14 is never
 * read); then everything is
 * checked at that apiVersion with the very same rules as the plain fields. A plugin is NEVER refused because of an
 * enhancement: a block is dropped and logged, and the plugin runs as its own manifest says, when it fails those rules (a bad
 * screen, a capability that can't be added, any other field), when its key is at or below the plugin's own `apiVersion`
 * (declare a feature once), when its `settings` change the type of a setting the manifest declares (keep the list a superset
 * of the manifest's: values sync by key with devices on an older Kino), when its `screen.replaces` names Categorías the
 * plugin's own apiVersion lacks (below 6), and when the script lacks an export the block newly needs (`screen` and
 * `screenEvent`, `settingsStatus` or `action` for such settings; checked at install and at every start). A key above the
 * Kino's apiVersion is ignored. The plugin's `apiVersion` never moves, so everything else keeps its old behaviour; the JS
 * stays one file and its `screen`/`screenEvent` exports are simply never called by an older Kino. The added capabilities'
 * consent lines (the red ones of library, playerPanelTab, playerControl, room, schedule and ai; shared's plain one) are asked at
 * install and at the update that adds them, like any other, never approved by Kino on its own; their features follow the block
 * (featureApiVersion): jobs run, `kino.shared` and `kino.ai` exist, only on a Kino that read it. `kino.library`
 * exists on every Kino of apiVersion 14, but until the person approves the line its calls reject with `permission_denied`:
 * a plugin installed on an older Kino, whose person then updates Kino, is asked only with its NEXT version. So
 * `typeof kino.library === "object"` is not enough: catch the refusal and work without it. `node sdk/validate.mjs` reports
 * every block the app would drop as a problem.
 */
interface KinoManifestEnhancements {
  [apiVersion: string]: { provides?: KinoManifestProvides; consumes?: KinoManifestConsumes; capabilities?: ("screen" | "library" | "playerPanelTab" | "playerControl" | "room" | "schedule" | "shared" | "ai" | "playerSlot")[]; screen?: KinoManifestScreen; settings?: unknown[]; panel?: KinoManifestPanel; jobs?: unknown[]; slot?: KinoManifestSlot };
}

// ---------- the plugin protocol (apiVersion 20, contract.json `protocol`) ----------

/**
 * A type of the plugin protocol's closed language: `"string"`, `"number"`, `"boolean"`, `"T?"` (optional: absent or null),
 * `"T[]"` (an array), the name of a type declared by the same door (capitalised, e.g. `"Movie"`), or an inline object of field
 * to type. A request is checked strictly (an extra or missing field, or a wrong type, is `bad_input`; nothing is coerced), an
 * answer loosely (undeclared fields are dropped; a missing or wrong one is `bad_output`). JSON only, at most 64 KB.
 */
type KinoProtocolType = string | { [field: string]: KinoProtocolType };

/** One call of a door: your export `proto_<door>_<call>(arg)` answers it. `in` may be left out (no arguments). */
interface KinoProtocolCall { in?: KinoProtocolType; out: KinoProtocolType }

/** One stream of a door: your export `proto_<door>_<stream>(cursor)` answers `{ items, cursor }`. `everySeconds` 30 to 86400 (60 when omitted). */
interface KinoProtocolStream { out: KinoProtocolType; everySeconds?: number }

/** A door a provider opens. `summary` (at most 120 characters) is the person's "Uses data from <provider> (<summary>)" line. */
interface KinoProtocolDoor {
  summary?: string;
  /** At most 16. */
  calls?: Record<string, KinoProtocolCall>;
  /** At most 8. */
  streams?: Record<string, KinoProtocolStream>;
  /** Named object types of this door only; names start with a capital letter. */
  types?: Record<string, Record<string, KinoProtocolType>>;
}

/** The manifest's `provides` (apiVersion 20, or `enhancements["20"]`): at most 4 doors; names are letters and digits starting with a letter, at most 32. */
type KinoManifestProvides = Record<string, KinoProtocolDoor>;

/** One entry of the manifest's `consumes`: `repo` is the provider's plain GitHub `owner/name` (a fork does not stand in), `door` its door, `calls` (at most 16) and `streams` (at most 8) the names you use. */
interface KinoManifestConsumesEntry { repo: string; door: string; calls?: string[]; streams?: string[] }

/** The manifest's `consumes` (apiVersion 20, or `enhancements["20"]`): at most 8 entries keyed by the alias `kino.plugins.call` takes. */
type KinoManifestConsumes = Record<string, KinoManifestConsumesEntry>;

/** Why `kino.plugins.call` rejected (the Error's `code`). */
type KinoProtocolErrorCode = "provider_missing" | "not_declared" | "bad_input" | "bad_output" | "rate_limited" | "timeout" | "provider_failed";

/**
 * The `arg` of the screenEvent named `protocol` (apiVersion 20): the new items of a stream your screen switched on with
 * `state.protocol.<alias>.<stream> = true`, each validated against the stream's `out`. An object here, not the string `arg` of
 * other events.
 */
interface KinoProtocolEventArg { alias: string; stream: string; items: unknown[] }

/**
 * A screen's timer: Kino sends `screenEvent { name: event }` every `ms` milliseconds (at least 1000: a shorter one is raised,
 * at most a day) while the screen is open, shown and the app in front (a pop-up does not stop it; the background does). At
 * most 3 timers per screen (the manifest's and the root's together). The next wait starts once a tick and the render it
 * asked for are done (twice what that took when longer); a tick never runs beside or ahead of the person's events. A timer
 * whose ticks fail or time out 3 times in a row is switched off for that opening (logged). Timer calls never count toward
 * the plugin's "No responde". A tick's answer keeps only `state`, `toast`, `close` and `config` (its pop-ups, `focus`, `go`
 * and `route` are dropped), and its `config` writes each setting at most once a minute.
 */
interface KinoScreenTimer { ms: number; event: string }

/** What a banner or a toast is about: Kino paints it with its own colour and icon for that role. */
type KinoScreenRole = "info" | "warning" | "error" | "success";

/**
 * Load more on a `ListView`, `titleRail` or `titleGrid`: `onEndReached` is sent once when the person reaches the last item, and
 * again only after the plugin answered and the tree it asked for is drawn, and then only once the list grew or its
 * `loadingMore` went from true to false (a load that finished with nothing new; turning it on never asks again). Never more
 * than once a second per list (an end reached within that second asks by itself once it is over), never while the screen
 * is hidden or the app in the background (it asks once the screen shows again), never for an empty list, never at 500
 * items (the cap stays, and 60 for a rail or grid drawn inside a scroll). A load-more's answer never changes the route:
 * its `route` is dropped (logged). Set `loadingMore: true` to show Kino's spinner after the items and `done: true` to stop
 * asking.
 */
/** Screen asks: the `value` of a `QrImage`'s `onExpire` event. */
interface KinoScreenQrExpire {
  /** `renew`: `renewBeforeMs` before the end; `expired`: the end came (no lead time, or the screen was hidden past it). */
  phase: "renew" | "expired";
  /** What was left when Kino sent it (0 once expired). */
  remainingMs: number;
}

/** Screen asks: the `value` of a `settings` node's `onSaved` event. Keys only: a value, a password's least of all, never. */
interface KinoScreenSettingsOutcome {
  kind: "save" | "action";
  ok: boolean;
  /** The settings that changed (sorted): edited and saved, or cleared or set by the action. */
  keys: string[];
  /** The action button's key, for `kind: "action"`. */
  action?: string;
  /** Why not `ok`: your validateSettings refused, it could not check, Kino's store refused, or the action failed. */
  reason?: "rejected" | "checkFailed" | "refused" | "failed";
}

interface KinoScreenPaging { onEndReached?: { event: string; arg?: string }; loadingMore?: boolean; done?: boolean }

/** A device Kino draws a screen on (`ctx.device`, a node's `devices`). */
type KinoScreenDevice = "phone" | "tv" | "desktop";
/** A width class (Material window size classes: compact < 600 dp, medium 600-839, expanded >= 840); a node's `sizes`. */
type KinoScreenSizeClass = "compact" | "medium" | "expanded";
/**
 * A style or layout property: a plain value or a per-size map. A class missing from the map takes the next smaller one
 * present, else Kino's default; each class's value is checked like a plain one. Kino resolves them before drawing.
 */
type KinoScreenResponsive<T> = T | { compact?: T; medium?: T; expanded?: T };
/** The spacing scale (`padding`, `margin`, `gap`); a value off it is dropped and logged. */
type KinoScreenSpacing = 0 | 4 | 8 | 12 | 16 | 24 | 32 | 48;
/** The size scale (`width`, `height`, `minHeight`), in the same units as the spacing. */
type KinoScreenSize = 16 | 24 | 32 | 40 | 48 | 64 | 80 | 96 | 120 | 160 | 200 | 240 | 320 | 400 | 480 | 560 | 640;
/** Every side, or some of them (`x` = start and end, `y` = top and bottom; `start`/`end` follow the reading direction). */
type KinoScreenEdges = KinoScreenSpacing | { x?: KinoScreenSpacing; y?: KinoScreenSpacing; top?: KinoScreenSpacing; end?: KinoScreenSpacing; bottom?: KinoScreenSpacing; start?: KinoScreenSpacing };
/**
 * Colors only by role, painted with Kino's palette (never a hex value). Task 15: `primaryContainer` (the surface tinted with the
 * primary; a manifest `theme` tints it as it tints `primary`) and `surfaceVariant` (Kino's raised surface): on a box they are
 * its fill and its text and icons take the matching on-colour; on a `Text` or an `Icon` the colour, nudged to read.
 */
type KinoScreenColorRole = "primary" | "secondary" | "surface" | "muted" | "warning" | "error" | "onPrimary" | "primaryContainer" | "surfaceVariant";
/** A radius token. */
type KinoScreenRadius = "none" | "small" | "medium" | "large" | "full";
/**
 * Task 15: `borderRadius` per corner: each a token, an omitted corner `medium`; `start` and `end` follow the reading direction.
 * Fills, clips, outlines and the TV's focus ring follow it.
 */
type KinoScreenCorners = { topStart?: KinoScreenRadius; topEnd?: KinoScreenRadius; bottomStart?: KinoScreenRadius; bottomEnd?: KinoScreenRadius };
/**
 * Task 15: the shared `badge` (the `Badge` node's value): `"dot"`, or a short count or word (at most 12 characters, cut beyond)
 * with an optional colour role (Kino's primary by default). Drawn on the node's top end corner (beside a tab's label); a screen
 * reader reads it after the node's name. Set it again on each render.
 */
type KinoScreenBadge = "dot" | { text: string; textEn?: string; color?: KinoScreenColorRole };
/** The style every node takes; each property may be a per-size map. */
interface KinoScreenStyle {
  padding?: KinoScreenResponsive<KinoScreenEdges>; margin?: KinoScreenResponsive<KinoScreenEdges>; gap?: KinoScreenResponsive<KinoScreenSpacing>;
  borderRadius?: KinoScreenResponsive<KinoScreenRadius | KinoScreenCorners>;
  width?: KinoScreenResponsive<KinoScreenSize>; height?: KinoScreenResponsive<KinoScreenSize>; minHeight?: KinoScreenResponsive<KinoScreenSize>;
  /** Take the parent's whole width. */
  fill?: KinoScreenResponsive<boolean>;
  /** Share of a `Row` or `Column`, 1..12 (Flutter's `Expanded(flex:)`). */
  flex?: KinoScreenResponsive<number>;
  /** Across the main axis (a `Row`'s height, a `Column`'s width). */
  crossAxisAlignment?: KinoScreenResponsive<"start" | "center" | "end" | "stretch">;
  /** Along the main axis. */
  mainAxisAlignment?: KinoScreenResponsive<"start" | "center" | "end" | "spaceBetween" | "spaceAround">;
  color?: KinoScreenResponsive<KinoScreenColorRole>;
  /**
   * In a `Row` with `wrap: true` (the twelve-column layout, Bootstrap's grid), how many of the line's 12 columns this child
   * takes: 1..12, or `"auto"` (the autos of a line share what the fixed spans leave, equally). A child without one is `auto`.
   * Above 12 it is 12 (logged); anything else is dropped (logged). Only on a child of a row that wraps (in some size class):
   * anywhere else it is ignored and logged. Per size, like `col-md-6`:
   * `span: { compact: 12, medium: 6, expanded: 4 }`.
   */
  span?: KinoScreenResponsive<number | "auto">;
  /**
   * In a wrapping row, the empty columns before this child (0..11; above 11 it is 11, logged), never past what its span
   * leaves (lowered, logged). Per size as `span`.
   */
  offset?: KinoScreenResponsive<number>;
  /**
   * Task 15: at most this share of the width the parent offers, 0.25 to 1 in steps of 0.05 (off the scale: dropped, logged);
   * the node still wraps its content, so it is a maximum. With `fill: true` it takes exactly that share. Where it sits is the
   * parent's `crossAxisAlignment` (a chat's bubbles: `0.75`, their column aligned `end` or `start`).
   */
  maxWidthFraction?: KinoScreenResponsive<number>;
  /**
   * Task 17: where this child of a `Row` or `Column` (a `Card`, a `Form`, a scroll) sits across it, over the parent's
   * `crossAxisAlignment`; `stretch` in a row draws as `start`. Elsewhere ignored, logged.
   */
  alignSelf?: KinoScreenResponsive<"start" | "center" | "end" | "stretch">;
  /** Task 17: the paragraph of a `Text`, a button's label, `Chips`, a `TextField` or a `ListTile`; elsewhere ignored, logged. */
  textAlign?: KinoScreenResponsive<"start" | "center" | "end" | "justify">;
  /**
   * Task 17: an outline on a box (`Column`, `Row`, `Stack`, `Card`, a scroll, `GridView`, `Form`, `ListTile`, `PageView`): `width`
   * 0 to 8 dp (default 1, clamped), `color` a role (default Kino's outline); it follows `borderRadius`.
   */
  border?: KinoScreenResponsive<{ width?: number; color?: KinoScreenColorRole }>;
  /** Task 17: Kino's shadow (a card's tonal lift too) on a `Card` or a `Stack`, 0 to 24 (clamped). */
  elevation?: KinoScreenResponsive<number>;
  /** Task 17: a box's fill (over `color`); its text and icons read in the role's on-colour. */
  background?: KinoScreenResponsive<KinoScreenColorRole>;
  /** Task 17: size limits beside `minHeight`; a minimum above its maximum drops the maximum, logged. */
  minWidth?: KinoScreenResponsive<KinoScreenSize>; maxWidth?: KinoScreenResponsive<KinoScreenSize>; maxHeight?: KinoScreenResponsive<KinoScreenSize>;
  /**
   * Task 17: Flutter's `Positioned`, on a child of a `Stack` only: each side or size in dp (0 to 1280, clamped) or a share of
   * the stack written `"25%"`. With `left` and `right` (or `top` and `bottom`) the size between them; a `width` given too is
   * ignored, logged. Kept inside the stack (clipped, never pressed outside it); drawn and focused in child order.
   */
  positioned?: KinoScreenResponsive<{ top?: number | string; left?: number | string; right?: number | string; bottom?: number | string; width?: number | string; height?: number | string }>;
  /** Task 17: 0 to 1 (clamped); below 0.38 the node takes no press and no focus. */
  opacity?: KinoScreenResponsive<number>;
  /**
   * Task 17: on a box or a positioned child, changes of size, opacity, fill, place and visibility between renders glide:
   * `duration` 100 to 600 ms (default 250, clamped), `curve` `standard` (default), `ease` or `decelerate`. Off when the device
   * turns animations off; never delays a press or focus; at most 24 animating nodes a screen (the rest drop it, logged).
   */
  animate?: KinoScreenResponsive<{ duration?: number; curve?: "standard" | "ease" | "decelerate" }>;
}

/** The kind of a `go.title` / `go.play` ref: what this plugin's `home`/`search`/`browse` said it was. */
type KinoScreenKind = "movie" | "series" | "episode" | "live" | "music" | "podcast";
/**
 * The title a `go.title` / `go.play` opens (Task 8), only ever this plugin's own: `ref` and `kind` as its lists gave them. A
 * title on the canvas (a `titleCard`, `titleRail`, `titleGrid` item) is opened with that very item, so the page, "Continuar
 * viendo", the saved lists and the progress know it as Home does: pass its `id` when two items share a `ref`. A title that is
 * NOT on the canvas needs its `id` (an item id) and `title` (at most 200 characters), and `adult: true` when it is 18+ (hidden
 * while the 18+ code is locked, as on Home); without them Kino cannot know which title it is and shows its usual error. A
 * `go.play` of a live channel plays it, of a series opens its page (an episode needs its series: `kind: "episode"` alone
 * shows the error, and so does a `series` from a plugin without `episodes`, which Home never lists); a movie, a track or a
 * podcast episode plays at once. A bad `id`, `title` or `adult` drops the go (logged). A card whose item has `open: { screen }`
 * starts the screen again at that route instead (in place, like a `go.screen`).
 */
type KinoScreenTitleRef = { ref: string; kind: KinoScreenKind; id?: string; title?: string; adult?: boolean };
/**
 * Where a node or an answer sends the person, always into this plugin's own content or one of Kino's own pages: exactly one
 * of these ten shapes (anything else, a bare URL string or an intent, is dropped; a link goes only through `url`, behind
 * Kino's own sheet). `ref` at most 4096 characters, `q` at most 200.
 * Task 8: `search` opens Kino's search with `q` filled in and ONLY this plugin as the source (the person sees its chip and
 * may clear it; a plugin without `search` gets it refused). apiVersion 17: `scope: "all"` opens Kino's normal search on EVERY
 * source instead (no source is named, the plugin needs no `search`, the 18+ gate works as in Kino's search); you get nothing
 * back, no results and no list of sources, and it opens only from the person's own tap or submit (dropped and logged from `open`,
 * a timer, a load-more or a change). A plugin below apiVersion 17 gets it refused and logged; any other `scope` drops the go; `browse` its "Ver más" list for that ref; `section` its section;
 * `categories` Kino's Categorías showing this plugin's group first (its own screen when `screen.replaces` names them;
 * refused and logged when the plugin has no Categorías tiles: the `categories` export, `browse`, usable). Kino's page opens
 * over the screen: Back returns to the screen with its state. At most one such page every 500 ms: a second go sent meanwhile
 * is dropped and logged. From the screen opened over the player, the screen closes first and the video then does what it
 * does whenever a Kino page covers the player (the TV pauses, a live stream stops); `play` plays the new title in the player.
 * The answer to the reserved `open` event never leaves the screen: its `go` (other than `screen`) is dropped and logged,
 * as a timer's is, so opening a screen never plays or pushes anything by itself. A tap's go is never affected.
 */
type KinoScreenGo =
  | { title: KinoScreenTitleRef }
  | { play: KinoScreenTitleRef }
  | { search: { q: string; scope?: "all" } }
  | { browse: { ref: string; title?: string; titleEn?: string } }
  | { section: true }
  | { categories: true }
  | { close: true }
  | { screen: KinoScreenOpen }
  | { titleByIds: KinoScreenTitleByIds }
  | { url: KinoScreenUrl }
  | { copy: KinoScreenCopy }
  | { useTheme: KinoScreenUseTheme }
  | { setExperience: "light" | "full" }
  | { installPlugin: KinoScreenInstallPlugin }
  | { liveChannel: KinoScreenLiveChannel }
  | { syncProvider: true };

/**
 * `go: { syncProvider: true }` (the thirteenth shape): Kino opens its own sync-provider settings (Ajustes ▸ Conectar ▸ Proveedor),
 * where the person taps «Usar <your plugin>» to make it the provider that carries their data. It carries nothing and changes no
 * choice by itself, so it is the right last step of a sync provider's connect flow.
 *
 * - Only for a plugin that declares the `syncProvider` capability (else dropped, logged `not_sync_provider`), and only after the
 *   person's own tap or press (as `go.url` and `go.copy`).
 * - A Kino from before this shape drops the whole `go`, logged, so keep your own written instruction beside the button.
 */

/**
 * `go: { useTheme: { theme } }` (apiVersion 18, the fourteenth shape): a button on your own screen activates one of your manifest's
 * `appThemes` ids exactly as Apariencia does; `theme: null` goes back to Kino's theme, only while your own theme is active. Only
 * from the person's own press or submit on your screen; dropped, logged, from `open`, timers, changes, a pop-up's `onClose`, panels
 * and notices, and below apiVersion 18. Refused, logged, for a theme Apariencia does not list as yours. Kino shows its own toast
 * and calls `screen` again with the new `activeTheme`.
 *
 * `go: { setExperience: "light" | "full" }` (apiVersion 18, the fifteenth shape): asks for the light experience (no shadows, no
 * effects, square corners) or the full one of the whole app, the two presets of Ajustes. Kino asks the person first, in its own
 * words naming your plugin, and changes nothing without their yes; nothing is asked when the app already has it. Only from the
 * person's own press or submit on your screen, as `useTheme`. A theme may also suggest one with its `experience` field.
 */
interface KinoScreenUseTheme {
  theme: string | null;
}

/**
 * Kino 0.9.81, `"recommends": ["owner/name", ...]` in kino-plugin.json (additive: valid at every apiVersion, an older Kino ignores
 * it): at most 8 plain GitHub `owner/name` strings (no URL, no sub-path, no `@ref`, at most 100 characters; case kept, repeats
 * ignoring case collapse), else the manifest is refused: `The "recommends" field must be a list of at most 8 plain GitHub
 * owner/name repositories`. `screen` and `screenEvent` then receive `installed`: `true` or `false` for exactly those entries
 * (the repo as you wrote it), never for any other plugin the person has. Kino calls `screen` again when it changes.
 */
type KinoScreenInstalled = Record<string, boolean>;

/**
 * `go: { installPlugin: { repo } }` (apiVersion 19, the sixteenth shape): Kino opens its own install sheet for `repo` (the same one
 * as Agregar un plugin), over your screen (no navigation to Plugins), so the person can install another plugin (a dependency of
 * yours, a sibling) in one tap and one confirmation. Nothing installs without the person's own Instalar on that sheet. When that
 * plugin is already installed Kino opens nothing and shows its own toast ("Ese plugin ya está instalado" / "That plugin is
 * already installed"); declare it in the manifest's `recommends` and read `installed` to show "Instalado" instead of a button.
 *
 * - `repo` is a plain GitHub `owner/name` (at most 100 characters), kept as you wrote it. A URL, a sub-path (`owner/name/dir`) or a
 *   `@ref` drops the whole `go`, logged; so does any other field.
 * - Only from the person's own press or submit on your screen (as `go.url` and `go.copy`): dropped, logged, from `open`, a timer, a
 *   change, a pop-up's `onClose`, a panel and a notice, and below apiVersion 19.
 */
interface KinoScreenInstallPlugin {
  repo: string;
}

/**
 * `go: { liveChannel: { provider, code } }` (Task 11, apiVersion 14, the twelfth shape): Kino tunes the player to the channel
 * `code` (an item id, 1 to 128 of `A-Z a-z 0-9 . _ ~ -`) of the En vivo provider plugin `provider` (a plugin id, never `own`).
 *
 * - Only for a plugin whose approved contributed tab declares `"kinds": ["live"]` (else dropped, logged `needs_live_tab`), and
 *   only after the person's own tap or press (as `go.url` and `go.copy`).
 * - The provider must be installed, usable and list live channels; an 18+ provider only while the 18+ code is unlocked; an
 *   18+ channel is not found while it is locked (Kino's usual message).
 * - From the player panel on a live channel the channel changes in place (the panel and its pin stay); from anywhere else the
 *   panel or screen closes and the player opens the channel. Nothing comes back: the next context says the channel.
 */
type KinoScreenLiveChannel = { provider: string; code: string };

/**
 * `go: { copy: { text, label?, sensitive? } }` (Task 8x, the eleventh shape): a «Copiar» button. Kino puts `text` on the
 * clipboard itself (clip label «Kino») and ALWAYS shows its own toast, «Copiado» / «Copied», or «Copiado: <label>», so nothing
 * is copied unseen; Kino never reads the clipboard and nothing comes back to you. No capability.
 *
 * - `text`: 1 to 500 characters in at most 6 lines, once control (a newline stays), direction, zero-width and line-separator
 *   characters are removed and it is trimmed. `label`: what was copied, at most 40 characters, named in the toast.
 *   `sensitive: true` hides it from the clipboard's preview on Android 13+ (a room code). Anything else drops the go, logged
 *   (never the text).
 * - Only after the person's own tap or press (a node's tap, a form's submit, the answer to either, a pop-up's button, a player
 *   panel press, a contributed tab's press); from `open`, a timer, a load-more, a change, a `refreshMs`, a pop-up's `onClose`
 *   or a `playerEvent` it is dropped, logged. A panel stays open.
 * - One copy every 500 ms (all plugins) and 20 a minute per plugin.
 * - On a TV nothing is copied: Kino's toast says «No se puede copiar en este aparato». Hide the button there (`kino.device`).
 */
type KinoScreenCopy = { text: string; label?: string; sensitive?: boolean };

/**
 * `go: { url: { href, title? } }` (Task 8s, the tenth shape): asks Kino to open a link in the phone's browser (a "Ver noticia"
 * button). Nothing opens by itself and it needs no capability: Kino first shows ITS OWN sheet: its heading "Abrir un enlace",
 * "Lo pide: <your plugin's name>" (cut at 24 characters; a tab you contribute to another plugin's panel shows YOUR name, never
 * the title's plugin), the link's host (wrapping, its end always drawn; an international one as its punycode with a warning to
 * check it, never decoded), your `title` under Kino's "Texto del plugin:" label, and Cancelar (focused first) and Abrir (which
 * does nothing for its first 600 ms). Only Abrir opens it, and only in a browser (never another app's link filter). On a TV, or
 * a phone with no browser, the sheet shows the link as a QR code to scan with a phone instead (a link over 1000 characters: a
 * line saying it is too long for one), and a Close button.
 *
 * - `href`: `https://` only, at most 2048 characters of printable ASCII (an international host written as punycode
 *   `xn--...`, everything else percent-encoded); a public DNS name with a dot (never an IP address, `localhost`, `.local`,
 *   `.internal`, `.lan`, `.home.arpa`, the loopback wildcard names `nip.io`, `sslip.io`, `xip.io`, `localtest.me`, `lvh.me`
 *   or a single label), no `user:password@`, no port but 443. Kino keeps
 *   `https://<host lower-cased><the rest as written>` (`/` added when the rest is empty). A bad href drops the go, logged
 *   with its host at most, never the address.
 * - `title`: optional, at most 60 characters once control, direction and line-separator characters are removed and runs of
 *   combining marks cut to 2.
 * - Only after the person's own tap or press (a node's tap, a form's submit, the answer to a tap or a submit, a pop-up's
 *   button, a player panel press, a contributed tab's press). From the reserved `open`, a timer, a load-more, a change, a
 *   `refreshMs`, a pop-up's `onClose` or a `playerEvent` it is dropped, logged.
 * - At most one link a second (all plugins) and 10 a minute per plugin; one sheet at a time (a link while one is asked about
 *   is dropped). An answer that comes more than 5 s after the tap drops the link (logged); the same answer's own pop-ups
 *   (`dialog`, `sheet`, `menu`, `ui` `open`) are dropped so nothing covers Kino's sheet. Nothing comes back to you: not whether
 *   the person opened it.
 * - Desktop opens it with its own opener (same sheet and rules).
 */
type KinoScreenUrl = { href: string; title?: string };

/**
 * `go: { titleByIds: {...} }` (Task 8m, the ninth shape): opens KINO'S OWN title page for the title these ids name (the page a
 * Home TMDB card opens), where the person picks any of THEIR sources. It never opens your content or another plugin's by ref,
 * never plays, carries no URL, needs no capability, and nothing comes back to you (not even which plugins the person has).
 * Use it when people with different plugins should reach the same title (a shared room, a list of recommendations).
 *
 * - At least one of `tmdb` (a whole number from 1 to 2147483647) and `imdb` (`tt` and 7 to 10 digits); with only `imdb`,
 *   Kino asks TMDB for the title (an unknown one shows Kino's usual "No se pudo abrir"; never a title search).
 * - `season` (0 to 999) and `episode` (1 to 9999, needs `season`) only with `kind: "series"`; today the page opens the series
 *   whole. `year` 1870 to 2100. `title` at most 120 characters once control, direction and zero-width characters and U+FEFF are removed (for your
 *   own logs: the page shows TMDB's). Any other field (a `ref`, a `source`, a URL) drops the whole go, logged.
 * - Only after the person's own tap or press: a node's tap, a form's submit, the answer to a tap or a submit, a player panel
 *   press. From the reserved `open`, a timer, a load-more, a change, a `refreshMs` or a `playerEvent` it is dropped, logged.
 * - 18+: while the person's parental control is on, Kino opens it only when TMDB says the title is not adult; adult or
 *   unknown shows Kino's locked message.
 * - While Kino asks TMDB it shows "Buscando el título…"; one lookup at a time (a tap meanwhile is dropped), and if the person
 *   has moved on when it answers, nothing opens.
 * - At most one page-opening go every 500 ms. From the player panel (yours or a tab you contribute to another plugin's title)
 *   the panel closes first, then the page covers the player as any Kino page does.
 */
type KinoScreenTitleByIds = {
  tmdb?: number; imdb?: string; kind: "movie" | "series"; season?: number; episode?: number; title?: string; year?: number;
};

/**
 * `go: { screen: {...} }` (Task 7g): opens THIS plugin's own screen, never another plugin's, a URL or an intent. `route` (a name,
 * 1 to 64 of `A-Z a-z 0-9 . _ ~ -`) and `args` (an object, at most 4096 bytes of JSON) reach `screen()` and the reserved `open`
 * event as `route: { name, params: {}, args }` (`name` `"main"` when no `route`), so a deep link lands on the right tab. From
 * inside the screen it starts again at that route (the state stays): `screen()` runs, then the reserved `open` event comes
 * again with the new route, so load what the args name there, exactly as when another surface opened it. At most one such
 * restart a second (a sooner one is dropped and logged), so an `open` that answers `go.screen` cannot loop. Accepted in a screen, in the player panel's answers and
 * buttons (`pause: true` beside it pauses the video; default it keeps playing under the screen) and as an item's or a row's
 * `open` in `home`, `section` and `browse` answers. With screens switched off, or the screen hidden or failing, a card or row
 * does what it did before; a plugin without a screen gets it refused and logged.
 * With no `route` the screen opens as `{ name: "main", params: {}, args }`: put what the screen must load in `args` (for a row item
 * in Kino's Home, `{ screen: { args: { open: url } } }`) and answer the reserved `open` with `route: { push: "detail" }`, so your
 * front page stays under the detail and Back returns to it. An item that names `route: "detail"` directly opens the screen with
 * nothing under it: Back then has nowhere to go.
 */
type KinoScreenOpen = { route?: string; args?: Record<string, unknown> };

/**
 * A local operation Kino runs at once, with no plugin call, on another node of the same screen by its `key` (kept in the
 * state under `ui`). `set` gives an input a value: a string (at most 2000 characters), a boolean, a number, or a list of
 * at most 500 strings (chips).
 */
type KinoScreenUiOp =
  | { show: string } | { hide: string } | { enable: string } | { disable: string } | { focus: string }
  /**
   * Shows or hides a node; Task 15: `prop: "selected"` flips the `selected` state of a button or a card with `onTap` instead
   * (`"hidden"`, the default, is the same as none). Any other `prop` drops the operation, logged.
   */
  | { toggle: string; prop?: "hidden" | "selected" }
  /** Task 15: on a button or a card with `onTap`, `value: true | false` sets its `selected` state (anything else is ignored, logged). */
  | { set: { key: string; value: string | boolean | number | string[] } }
  | { clear: string }
  /** Opens the `popup` node of that key (replacing any open pop-up); `close` closes it when it is the one open. */
  | { open: string } | { close: string };
/**
 * What a tap, long press, change or submit does: an event name for `screenEvent` (the shorthand string, its `arg` from the
 * node's `arg`), or ui operations (at most 8, run first) followed by an event or a go, or a bare go object. The event name
 * `open` is reserved; `arg` at most 4096 characters.
 */
type KinoScreenAction = string | {
  ui?: KinoScreenUiOp[]; event?: string; arg?: string;
  /**
   * Task 18: on a press (`onPressed`, `onTap`, `onLongPress`, `onSubmitted`, `onTrailingTap`) with an event, its call's own
   * budget, 1000 to 30000 ms (clamped; the default stays 20000), honoured only when the person's own press or submit sends it.
   */
  timeoutMs?: number;
} | { ui?: KinoScreenUiOp[]; go: KinoScreenGo } | KinoScreenGo;
/**
 * A declared `popup`'s `onClose` (apiVersion 14, Task 7i-2): what runs after the person dismissed it (Back, Kino's close, a
 * tap outside), never after one of its buttons, a menu item, an answer's `close` or another pop-up replaced it. An event name
 * (its `arg` from the popup's `arg`) or `{ ui?, event?, arg? }`; a `go`, an `open` and a `focus` are dropped (closing a
 * pop-up never navigates, opens one nor moves focus). Back always closes: the event is not the person's press (no
 * `kino.qr.scan`), and its answer's `dialog`, `sheet`, `menu`, `focus`, `go`, `route` and `ui` open and focus operations
 * are dropped, logged; its `state`, `toast`, `config`,
 * `close` and other `ui` operations apply. A popup's `title` is optional: without one (or a blank one) no empty row is drawn
 * and Kino's close (an X alone) starts the bottom row, the pop-up's own buttons together at its end (Task 7k); with a title
 * the X ends the title's row.
 */
type KinoScreenPopupClose = string | { ui?: KinoScreenUiOp[]; event?: string; arg?: string };

/** What every node takes. `key` is required (and unique) on inputs; other nodes get a generated one. */
interface KinoScreenBase extends KinoScreenStyle {
  key?: string;
  /** For tests and tooling, never drawn: 1..64 characters. */
  testKey?: string;
  enabled?: boolean; hidden?: boolean;
  /** A tap on the node (a button's is `onPressed`). */
  onTap?: KinoScreenAction; onLongPress?: KinoScreenAction;
  /**
   * What a sideways swipe sends, by the direction the finger goes: `onSwipeLeft` turns to the next page, `onSwipeRight` to the previous
   * one. Any node, not per size; a drag of at least 64 dp. On the TV they answer Right and Left once focus has nowhere further to go.
   * Additive (Kino 0.9.82): an older Kino ignores them, so keep your buttons.
   */
  onSwipeLeft?: KinoScreenAction; onSwipeRight?: KinoScreenAction;
  /** The event arg of a shorthand-string action. */
  arg?: string;
  /** Drawn only on these devices / width classes; an unknown name drops the node. */
  devices?: KinoScreenDevice[]; sizes?: KinoScreenSizeClass[];
  /**
   * Task 15, on a node that takes focus (a button, an input, a `TabBar`, a `titleCard`, or any node with `onTap` or
   * `onLongPress`): on a render (a tick or an answer) that left focus nowhere or on a node that is gone, focus goes to the first
   * `autofocus` node in tree order (the remote lands on the one way forward). An answer's own `focus` wins; a node that still
   * holds focus keeps it; on a phone a text field is never autofocused (no keyboard opens). Elsewhere ignored, logged.
   */
  autofocus?: boolean;
  /**
   * Task 15, on a button or a card with `onTap`: Kino's selected look (filled-tonal; a card: an outline in the primary colour),
   * read as selected. State, not an action: `ui` `set` (true or false) and `toggle` with `prop: "selected"` change it without a
   * round trip until your next render says it again. `Chips` and `TabBar` say theirs with `value`.
   */
  selected?: boolean;
  /** Task 15, on a button or a card with `onTap`: a count or a dot on the top end corner ([KinoScreenBadge]). */
  badge?: KinoScreenBadge;
  /** Task 17: `false` hides the node as `hidden: true` does (with `animate`, it fades and folds out). */
  visible?: boolean;
  /**
   * Task 17, on a node that does something (a button, an input, a `FloatingActionButton`, any node with `onTap` or
   * `onLongPress`): Kino's hint, at most 80 characters (`tooltipEn` the English one): a phone shows it on a long press (none on a
   * node with its own `onLongPress`), a TV after about 800 ms of focus, a screen reader as the long press's label. Never put
   * essential information in it. Elsewhere ignored, logged.
   */
  tooltip?: string; tooltipEn?: string;
  /**
   * Task 18, on a button, a `FloatingActionButton`, a card or a `ListTile` with `onTap`: Kino's busy look (a spinner in the icon's
   * place, no press, read as busy; a TV keeps its focus there). Kino draws the same look by itself on the node the person pressed
   * while its call runs past 400 ms, until your answer.
   */
  loading?: boolean;
  /**
   * Task 18, on a button, a `FloatingActionButton`, a card or a `ListTile` with `onTap`: epoch ms; drawn off until that time on the
   * device's clock, then on by itself (no call to you). Pair it with a `Text` of the same `time` and `timeFormat: "countdown"`.
   */
  enabledAt?: number;
  /**
   * Task 22 (Flutter's name), on any node: `true` makes a node with no focus of its own (a status `Card`, a `Text`, a `Row`, a
   * `DataTable`) a D-pad stop on the TV, so the remote can rest on it to read it: Kino's row look (a tint and an underline), no
   * press, read by a screen reader. Ignored on a node that already takes focus and on the phone. Without it the TV pages a
   * scrolling body (80% of its height) before focus moves past a block that has not shown yet.
   */
  canRequestFocus?: boolean;
}
/** One choice of a `DropdownButton`, `RadioGroup`, `Chips` or `TabBar` (values distinct, at most 500); a tab also takes a `badge` (Task 15). */
interface KinoScreenOption { value: string; label: string; labelEn?: string; badge?: KinoScreenBadge }
/**
 * What every input takes; its value lives in the state under `inputs.<key>`. `bind`: the key of one of the plugin's own
 * settings: the field shows its stored value when the screen opens and writes the person's change back to it through Kino's
 * settings (the same store and sync as Kino's settings screen) -- a choice on change, a text on commit (keyboard action, focus
 * leaving it, the TV dialog's accept), never per keystroke, and only when the value differs from the stored one; the plugin still
 * gets the field's events. A `Switch` or `Checkbox` holds a `toggle` setting, a `TextField` a `text` one, a `DropdownButton`,
 * `RadioGroup` or single `Chips` a `select` or `text` one, a `Slider` a `text` one (its number as text). Never a `url` (only the person types an
 * address: the `settings` node), a `password`, an `action` or a `help` setting; any other bind, or one inside an answer's pop-up,
 * is dropped, logged. Each setting is written at most once every 500 ms (the newest value wins, the last one always lands).
 */
interface KinoScreenInput extends KinoScreenBase {
  key: string; labelText?: string; labelTextEn?: string; hintText?: string; hintTextEn?: string; onChanged?: KinoScreenAction; bind?: string;
  /**
   * Task 18: Flutter's `forceErrorText` (`forceErrorTextEn`): your own verdict, drawn under the field as Kino's errors are, until the
   * person edits it (your answer to their next press, or a new text, shows it again). At most 200 characters; never blocks a submit.
   */
  forceErrorText?: string; forceErrorTextEn?: string;
}
/** The kinds of a `TextField` (no password kind). */
type KinoScreenInputKind = "text" | "number" | "email" | "url" | "search";
/**
 * A field's rules inside a `Form`, checked by Kino before anything reaches the plugin. `required`: a text not blank, a
 * choice made, a toggle or checkbox on, a chip picked. An empty field that is not required passes every check.
 * `errorText` (and `errorTextEn`) is what the person reads under the field when it fails, else Kino's own text.
 */
interface KinoScreenFieldRules { required?: boolean; errorText?: string; errorTextEn?: string }
/**
 * A `TextField`'s rules: `minLength` characters (1..its `maxLength`); `pattern` (at most 200 characters) must match the
 * WHOLE value, in a safe subset: literals, `.`, `^`, `$`, `|`, `( )`, `(?: )`, `[...]`, the escapes \d \D \w \W
 * \s \S \b \B \n \r \t and escaped punctuation, the quantifiers `* + ? {n} {n,} {n,m}` (at most 1000, optionally lazy).
 * Quantifiers nest freely (`^\w+(\.\w+)?$`). No backreferences, no lookarounds; at most 500 steps once counts are
 * expanded. A pattern outside the subset is dropped and logged. Kino matches it with its own linear-time matcher (\d is
 * [0-9], \w [A-Za-z0-9_], \s ASCII whitespace), never with the platform's regex; one submit runs at most 16 patterns and 4,000,000 matcher steps (past either, the rest pass).
 */
interface KinoScreenTextRules extends KinoScreenFieldRules { minLength?: number; pattern?: string }

/**
 * Kino 0.9.83, additive (no new apiVersion; an older Kino asks for the picture without them): the request headers of an `Image`'s
 * `url`, for a site that serves its pictures only to requests that carry its own page as `Referer` (and a browser `User-Agent`).
 * Only these two names, each a text of 1 to 512 characters. They need an https `url` (an http picture, which a Kino with
 * `kino.screen.httpImages` draws, never takes them), and are sent only when the picture's host
 * is one of your manifest's `hosts` (a `*.` pattern counts); a `Referer` on a host you did not declare is left out. Without a
 * `User-Agent` Kino sends `Kino/<version>`. A header that is not valid is dropped and logged (Registro).
 *
 * @example
 * { type: "Image", url: page.imageUrl, aspect: "2:3", headers: { Referer: "https://mangasite.example/", "User-Agent": "Mozilla/5.0" } }
 */
interface KinoScreenImageHeaders {
  Referer?: string;
  "User-Agent"?: string;
}

/**
 * One node of a screen tree: depth at most 10, at most 600 nodes, lists of at most 500 items, plain text of at most 2000
 * characters (`...En` the English twin). An invalid node is dropped and logged; the rest is drawn.
 */
type KinoScreenNode =
  | (KinoScreenBase & { type: "Column" | "Stack"; children?: KinoScreenNode[] })
  /**
   * `wrap: true`: the twelve-column layout. Each child takes its `span` columns after its `offset`; one that does not fit
   * what is left of a line starts the next; `gap` (the spacing scale) between cells and between lines, the columns lined
   * up from line to line. A line is as tall as its tallest child, and by default (or with `crossAxisAlignment: "stretch"`)
   * every Card or container child (Column, Row, Stack, GridView, Form) with no fixed `width` or `height` is drawn that tall,
   * so a grid of cards is even; any other child (a button, a badge, an Image with a size...) keeps its own height at the top
   * of the line. `start`, `center` or `end` keep every child at its own height, at the top, middle or bottom of its line. A hidden child leaves no gap. A child takes its natural width at
   * the start of its columns unless it has `fill: true` (then the cell's whole width). `flex`, `mainAxisAlignment` and
   * `stackOnNarrow` mean nothing there; without `wrap` a row is as before (`flex` shares it). On the TV focus follows the
   * tree, the D-pad moving by what is drawn.
   */
  | (KinoScreenBase & { type: "Row"; children?: KinoScreenNode[]; stackOnNarrow?: KinoScreenResponsive<boolean>; wrap?: KinoScreenResponsive<boolean> })
  /**
   * `flush: true` (apiVersion 14): no padding of the card's own (its `padding` is not used either) and its children clipped
   * to its rounded shape, so an `Image` at its top runs to its edges; pad the text children with their own `padding`.
   */
  | (KinoScreenBase & { type: "Card"; children?: KinoScreenNode[]; variant?: KinoScreenResponsive<"plain" | "outlined" | "filled">; flush?: KinoScreenResponsive<boolean> })
  | (KinoScreenBase & { type: "SingleChildScrollView"; children?: KinoScreenNode[]; direction?: KinoScreenResponsive<"vertical" | "horizontal">; zoom?: true | { max?: number }; onScroll?: KinoScreenAction })
  | (KinoScreenBase & { type: "GridView"; children?: KinoScreenNode[]; columns?: KinoScreenResponsive<number> })
  /** `SizedBox` is an empty box of its `width`/`height`; `Spacer` an empty one that takes its `flex` share. */
  | (KinoScreenBase & { type: "Spacer" | "SizedBox" | "Divider" })
  /**
   * Task 15: `time` (epoch ms) is written by Kino in the app's language: `timeFormat: "relative"` (the default: «ahora»,
   * «hace 2 min», «ayer», rewritten every minute while shown, never a call to you) or `"clock"` («18:42», the device's 12/24 h).
   * With a `time`, `text` is optional and is its prefix («Actualizado hace 5 min»).
   */
  | (KinoScreenBase & { type: "Text"; text: string; textEn?: string; style?: KinoScreenResponsive<"hero" | "h1" | "h2" | "h3" | "h4" | "h5" | "p" | "caption" | "label">; maxLines?: KinoScreenResponsive<number>; bold?: KinoScreenResponsive<boolean>; time?: number; timeFormat?: "relative" | "clock" | "countdown" })
  | (KinoScreenBase & { type: "Text"; text?: string; textEn?: string; style?: KinoScreenResponsive<"hero" | "h1" | "h2" | "h3" | "h4" | "h5" | "p" | "caption" | "label">; maxLines?: KinoScreenResponsive<number>; bold?: KinoScreenResponsive<boolean>; time: number; timeFormat?: "relative" | "clock" | "countdown" })
  /**
   * `fallback` (apiVersion 14): one node drawn in the image's box, at its size, when the picture fails to load or there is
   * no `url` (with a fallback, an image whose `url` is missing or not an address Kino may load is kept and draws it). It may
   * hold only Column, Row, Stack, Card, Spacer, SizedBox, Divider, Text, Icon, Badge, Skeleton and Image, at any depth, and
   * nothing in it is pressed (`onTap`/`onLongPress` there are ignored). Without one a failed picture shows Kino's mark.
   * `url`: https on a public host, a `data:image/...;base64,` picture, or (Kino 0.9.88, additive: check
   * `kino.screen.httpImages === true`) http on a public host by a poster's rule, never the home network; an older Kino drops
   * an http one (the fallback draws).
   */
  | (KinoScreenBase & { type: "Image"; url?: string; aspect?: KinoScreenResponsive<"16:9" | "2:3" | "1:1" | "banner" | `${number}:${number}`>; alt?: string; altEn?: string; fallback?: KinoScreenNode; fit?: KinoScreenResponsive<"cover" | "contain" | "width">; focus?: KinoScreenResponsive<"top" | "center" | "bottom">; headers?: KinoScreenImageHeaders })
  | (KinoScreenBase & { type: "Icon"; name: KinoIconName })
  | (KinoScreenBase & { type: "Badge"; text: string; textEn?: string })
  | (KinoScreenBase & { type: "LinearProgressIndicator"; value?: number; labelText?: string; labelTextEn?: string })
  | (KinoScreenBase & { type: "CircularProgressIndicator"; text?: string; textEn?: string })
  | (KinoScreenBase & KinoScreenPaging & { type: "ListView"; items?: KinoScreenNode[]; empty?: KinoScreenNode; columns?: KinoScreenResponsive<number>;
      /**
       * Task 14: opens at the last item; while the person is at the end (or one item from it) a new last item scrolls into view;
       * scrolled up it stays put until they come back. One column, in a list that scrolls itself (a full screen, or a panel with
       * `layout: "fill"`); drawn flat it does nothing (logged once).
       */
      stickToBottom?: KinoScreenResponsive<boolean>;
      /**
       * Task 15: items appended while the person is not at the end show Kino's own chip («↓ Nuevos» / «↓ New», never your text)
       * over the list's bottom; a tap goes to the end and it hides once the end shows. One column, a list that scrolls itself.
       * On the TV it is a focus stop: Down from the list region reaches it before your controls under the list.
       */
      newItemsHint?: boolean })
  /**
   * A button: `ElevatedButton` (Kino's primary), `TextButton`, `IconButton` (needs `icon`), or `Button` with its `variant`
   * (`secondary` has no other name). `submit: true` inside a `Form`: Kino checks the form, then runs the form's `onSubmitted`
   * (the button's own `onPressed` is ignored).
   */
  | (KinoScreenButton & { type: "ElevatedButton" | "TextButton" | "IconButton" })
  | (KinoScreenButton & { type: "Button"; variant?: KinoScreenResponsive<"primary" | "secondary" | "text" | "icon"> })
  /** A `TextField` with `maxLines` above 1 (in any size class) or `multiline: true` takes several lines. */
  | (KinoScreenInput & KinoScreenTextRules & { type: "TextField"; kind?: KinoScreenInputKind; maxLength?: number; value?: string; maxLines?: KinoScreenResponsive<number>; multiline?: boolean; onSubmitted?: KinoScreenAction;
      /**
       * Task 8y: an icon inside the field's box at its end (one-line fields only), all three or none: `trailingIcon`,
       * `trailingLabel` (what a screen reader says, at most 40 characters; `trailingLabelEn` in English) and `onTrailingTap`
       * (sent like `onSubmitted`, the field's current text as the event's `value`). Never shown on a disabled field.
       */
      trailingIcon?: KinoScreenResponsive<KinoIconName>; trailingLabel?: string; trailingLabelEn?: string; onTrailingTap?: KinoScreenAction;
      /**
       * Screen asks: a masked one-line field (a password, a token), drawn with dots on the phone and the TV. What is typed never
       * enters the state or a render: it goes only with the person's own tap or submit (`state.inputs.<key>` and, for the
       * form's or the field's own submit, `value`), and is cleared once that call ends unless the answer gives one back in
       * `state.inputs.<key>`. `value` and `onChanged` are ignored on it; with several lines (or not a boolean) the field is
       * dropped. `bind` takes only a `password` setting, and writes it on commit (an empty field never clears it).
       */
      obscureText?: boolean })
  | (KinoScreenInput & KinoScreenFieldRules & { type: "DropdownButton" | "RadioGroup"; options: KinoScreenOption[]; value?: string })
  /** `minLength` / `maxLength` count the chips picked. */
  | (KinoScreenInput & KinoScreenFieldRules & { type: "Chips"; options: KinoScreenOption[]; multiple?: boolean; value?: string | string[]; minLength?: number; maxLength?: number })
  | (KinoScreenInput & KinoScreenFieldRules & { type: "Switch" | "Checkbox"; value?: boolean })
  | (KinoScreenInput & { type: "Slider"; min?: number; max?: number; step?: number; value?: number })
  | (KinoScreenBase & { type: "TabBar"; tabs: KinoScreenOption[]; value?: string; onChanged?: KinoScreenAction; /** additive, no new apiVersion: `false` takes away the line under the tabs (default `true`) */ divider?: boolean })
  | (KinoScreenBase & { type: "emptyState" | "errorState"; title: string; titleEn?: string; text?: string; textEn?: string; icon?: KinoIconName })
  // Kino's own components: data only, drawn with Home's cards and rows. Items are what `home` rows return (KinoItem),
  // read by the same rules (a series needs the episodes capability; posters and backdrops https, or http on a public host
  // where `kino.screen.httpImages` is true, else Kino's placeholder); 18+ items show only while the 18+ code is unlocked. At most 1000 titles per tree, and at most 60 in a
  // grid inside a scroll, list or pop-up, or a rail inside a horizontal scroll (drawn all at once there).
  /** One Home poster card; without `onTap` it opens the title's page (`go: { title: { ref, kind } }`). */
  | (KinoScreenBase & { type: "titleCard"; item: KinoItem; size?: KinoScreenResponsive<KinoScreenCardSize>; headers?: KinoScreenImageHeaders })
  /** A Home row: a title, 1..500 items, and "Ver más" (`go: { browse: { ref } }`) when `ref` is set. */
  | (KinoScreenBase & KinoScreenPaging & { type: "titleRail"; title: string; titleEn?: string; items: KinoItem[]; ref?: string; size?: KinoScreenResponsive<KinoScreenCardSize>; headers?: KinoScreenImageHeaders })
  /** Home cards in a grid (default 3 columns), 1..500 items. */
  | (KinoScreenBase & KinoScreenPaging & { type: "titleGrid"; items: KinoItem[]; columns?: KinoScreenResponsive<number>; headers?: KinoScreenImageHeaders })
  /**
   * A section's banner: title, text, an image and a title `logo` (each https on a public host, or http on one where
   * `kino.screen.httpImages` is true: an older Kino drops an http one) and at most 2 buttons.
   */
  | (KinoScreenBase & { type: "heroCard"; title: string; titleEn?: string; text?: string; textEn?: string; image?: string; logo?: string; headers?: KinoScreenImageHeaders; buttons?: ((KinoScreenButton & { type: "ElevatedButton" | "TextButton" | "IconButton" }) | (KinoScreenButton & { type: "Button"; variant?: KinoScreenResponsive<"primary" | "secondary" | "text" | "icon"> }))[] })
  /**
   * A pop-up declared in the tree (`key` required), drawn only once a `{ open: key }` ui operation opens it. One pop-up at
   * a time; Back closes it first. An `AlertDialog` or `BottomSheet` takes `children` (an `AlertDialog` also `buttons`); a
   * `PopupMenuButton` takes 1..8 `items`. `popup` with its `kind` is the same thing.
   * Task 15 `anchor` (a node's key): drawn next to that node (above it when there is more room above, else below), sized to
   * its content, over the content and taking no layout space, with no close of its own (Back and a tap outside close it; on
   * the TV focus goes in, stays there and Back gives it back to the anchor). With no room above or below, or the anchor not on
   * screen, it falls back to its kind's own place (logged once). A screen-format panel draws a pop-up only with an `anchor`.
   */
  | (KinoScreenBase & { type: "AlertDialog"; key: string; title?: string; titleEn?: string; children?: KinoScreenNode[]; buttons?: KinoScreenDialog["buttons"]; anchor?: string })
  | (KinoScreenBase & { type: "BottomSheet"; key: string; title?: string; titleEn?: string; children?: KinoScreenNode[]; anchor?: string })
  | (KinoScreenBase & { type: "PopupMenuButton"; key: string; title?: string; titleEn?: string; items: KinoScreenMenuItem[]; anchor?: string })
  | (KinoScreenBase & { type: "popup"; key: string; kind: "dialog" | "sheet"; title?: string; titleEn?: string; children?: KinoScreenNode[]; buttons?: KinoScreenDialog["buttons"]; onClose?: KinoScreenPopupClose; anchor?: string })
  | (KinoScreenBase & { type: "popup"; key: string; kind: "menu"; title?: string; titleEn?: string; items: KinoScreenMenuItem[]; onClose?: KinoScreenPopupClose; anchor?: string })
  /**
   * A form: its `children` drawn as a column; its fields (every input in it, a pop-up's body excepted) take the rules of
   * KinoScreenFieldRules. A `submit: true` button submits it: Kino checks every field first, and an invalid form never
   * calls the plugin (the error shows under each failing field, focus goes to the first). While a required field is
   * empty the submit button is off. A valid form runs `onSubmitted`: its event's `value` is every field's value by key.
   * Forms do not nest and an answer's pop-up takes none.
   */
  | (KinoScreenBase & { type: "Form"; children?: KinoScreenNode[]; onSubmitted: KinoScreenAction })
  /**
   * Kino's own settings form for this plugin, the same one Kino's settings screen shows: every setting type, `devices`,
   * both languages, validation, Kino's own fields for secrets and its buttons for actions, with its own save. `keys`
   * shows only those settings, in that order (none: all of them); each setting shows at most once per screen, so a custom
   * form can drop one in for a secret (`keys: ["password"]`). Its JavaScript never sees what is typed in it. Never inside a
   * `Form` or an answer's pop-up. `onSaved` (screen asks): sent after this form saved or one of its action buttons finished,
   * its event's `value` a KinoScreenSettingsOutcome (setting keys only, never a value); a nobody's-press event that waits in
   * the queue like the person's (a timer's tick never runs before it); a save merged with a still-waiting earlier one.
   */
  /**
   * Task 18: `autoSave: true` saves its toggles and selects as the person changes them (no `validateSettings`; a locked one only
   * after its code); with only those shown, no Guardar. A node whose keys hold no valued setting (`keys: ["logout"]`) draws its
   * buttons and no Guardar. Screen asks: each autosave that changed something sends `onSaved` too (`kind: "save"`, the key),
   * as a Guardar does; one that changed nothing sends none.
   */
  | (KinoScreenBase & { type: "settings"; keys?: string[]; autoSave?: boolean; onSaved?: string | { event: string; arg?: string } })
  /**
   * A line of news across the screen in Kino's colour for its `role` (default info), with an optional title, a button
   * (`action`) and, when `dismissible` (it needs a `key` of its own), Kino's close: it hides the banner at once (in
   * `state.ui.hidden`) and sends the event `dismiss` with the banner's key as `arg`.
   */
  | (KinoScreenBase & { type: "MaterialBanner"; role?: KinoScreenRole; title?: string; titleEn?: string; text: string; textEn?: string; action?: { label: string; labelEn?: string; onTap: KinoScreenAction; arg?: string }; dismissible?: boolean })
  /**
   * Sections that open and close: each item's header (its `title`) shows or hides its `children`; one open at a time
   * unless `multiple`. `key` is required: which items are open lives in `state.ui.open.<key>` (the open item keys), so it
   * survives a re-render, and the plugin may set it there too; `open` is only the first look. 1..500 items, item keys
   * valid and distinct. Each item's header and its children count toward the depth and node limits. A required field in a
   * closed item does not keep a form's submit button off; the submit still checks it and, when it fails, opens its item and
   * focuses it. Never in an answer's pop-up. On the TV each
   * header takes focus and OK toggles it.
   */
  | (KinoScreenBase & { type: "ExpansionTile"; key: string; items: { key: string; title: string; titleEn?: string; children?: KinoScreenNode[]; open?: boolean }[]; multiple?: boolean })
  /**
   * A placeholder while something loads, in Kino's muted colour: a `line` (`lines` bars, 1..6), a `block`, a `circle` or a
   * `card` (a poster and its lines); size it with `width`/`height`. It pulses gently, and stands still when the system's
   * animations are off; a screen reader says Kino's "Loading".
   */
  | (KinoScreenBase & { type: "Skeleton"; shape?: KinoScreenResponsive<"line" | "block" | "circle" | "card">; lines?: KinoScreenResponsive<number> })
  /**
   * A QR code drawn by Kino itself (on the device, no network), black on white with its quiet zone, at one of Kino's three
   * sizes. `value`: 1..1000 characters, drawn as written; an empty or longer one is dropped (logged). A value holding one
   * of your plugin's secrets is never drawn: Kino shows its empty state instead (logged). `labelText` is what a screen
   * reader says. Never pressable (its `onTap` and `onLongPress` are ignored) and never focused; it may sit in an answer's
   * `dialog` or `sheet` body or a declared pop-up.
   *
   * Screen asks: a code that expires. `expiresInMs` (1000..3600000, from when Kino first draws this value) or `expiresAt` (epoch
   * ms, read against the device's clock once, at most an hour away): Kino draws a bar and the seconds left under the code,
   * ticked by itself between your calls, and dims the code under «Código caducado» at zero. The same value sent again never
   * restarts it; a new value starts a new countdown. `onExpire` is sent ONCE per value, `value` a KinoScreenQrExpire:
   * `renewBeforeMs` before the end (phase `renew`, below the lifetime, else half of it), else at zero (`expired`); never while
   * the screen is hidden (it goes once it shows again), never for a withheld code. Its answer keeps what a timer's keeps.
   */
  | (KinoScreenBase & { type: "QrImage"; value: string; labelText?: string; labelTextEn?: string; size?: KinoScreenResponsive<KinoScreenCardSize>;
      expiresInMs?: number; expiresAt?: number; onExpire?: string | { event: string; arg?: string }; renewBeforeMs?: number })
  /**
   * Screen asks: a setup flow in Kino's own look, for any plugin. One `current` step is open (its `children` drawn under it), a
   * `done` one collapses to its `subtitle` (else Kino's «Listo»), a `pending` one is dimmed. 1..12 items with valid, distinct
   * keys and a title. None current while one is to do: the first not done is; several: the first; an unknown state reads as
   * pending (all logged). `onStepTap` makes a done step pressable (touch, or OK on the TV): its event goes with the step's
   * key as `arg`. A screen reader reads each header as «Paso 2 de 3: Código, actual».
   */
  | (KinoScreenBase & { type: "steps"; items: { key: string; title: string; titleEn?: string; subtitle?: string; subtitleEn?: string; state?: "done" | "current" | "pending"; children?: KinoScreenNode[] }[]; onStepTap?: string | { event: string } })
  /**
   * A number drawn `[ − ] value [ + ]` (not Flutter's `Stepper`, a wizard: that name is unknown here): each press moves it
   * by `step` (default 1), kept within `min`..`max` (min below max) and rounded to `decimals` places (0..6); a button at its
   * limit is off; holding it repeats, slowly faster. Its value is in `state.inputs.<key>` as text: a `.` for decimals, no
   * grouping, exactly `decimals` places ("2.50"). `onChanged` goes with each press (the newest of a quick run, like any
   * change). `editable: true` also lets the person type it, with Kino's digits-only entry (the TV's number pad, the phone's
   * number keyboard): only with `decimals` 0 and a `min` of 0 or more, otherwise ignored (logged). Inside a `Form` it is a
   * field (`required`, `errorText`). No `bind` in this version (ignored, logged). Its numbers are at most 1e15 either way
   * (larger ones are clamped, logged). On the TV Left and Right move between −, the value and +.
   */
  | (Omit<KinoScreenInput, "bind"> & KinoScreenFieldRules & { type: "NumberStepper"; value?: number; min?: number; max?: number; step?: number; decimals?: number; editable?: boolean })
  /**
   * A table in Kino's own look: `children` are `TableRow`s (1..200), each with `TableCell`s. `columns` (at most 20) gives
   * each column its share of the width (`flex` 1..12, default 1); without it the table has as many columns as its widest row
   * spans. `header: true` makes the first row the header (bold, read as headings, a stronger rule under it); a rule under
   * every row; `zebra: true` paints every other row with Kino's surface. On a compact width the table scrolls sideways
   * (the table at least 96 dp per column, shared by flex) unless `wrap: true`. A row with fewer cells is padded; cells past the last column are
   * dropped and a span past it is cut (logged), for each size class with its own columns. Each row and each cell counts
   * toward the 600 nodes. Every property takes a per-size map: the flags, `columns`, a column's `flex`, a cell's `colSpan`
   * and `crossAxisAlignment`. It takes no focus: on the TV the D-pad walks only what is focusable inside its cells.
   */
  | (KinoScreenBase & { type: "DataTable"; columns?: KinoScreenResponsive<{ key?: string; flex?: KinoScreenResponsive<number> }[]>; header?: KinoScreenResponsive<boolean>; wrap?: KinoScreenResponsive<boolean>; zebra?: KinoScreenResponsive<boolean>; children: KinoScreenTableRow[] })
  /**
   * Task 17: Kino's floating button, one per screen, drawn over the bottom end (or centre) of your area (above a Scaffold's
   * bottom bar), never in place, never under the system bars or the keyboard; never inside a list, a table, a pop-up, a
   * `ListTile` or an image's fallback. `labelText` makes it the extended form. Takes `selected`, `badge`, `autofocus`, `tooltip`.
   */
  | (Omit<KinoScreenBase, "onTap"> & { type: "FloatingActionButton"; icon: KinoIconName; labelText?: string; labelTextEn?: string; onPressed: KinoScreenAction; fabPosition?: KinoScreenResponsive<"end" | "center"> })
  /**
   * Task 17: one row of a list (56 dp, 72 with a subtitle, 48 `dense`); `leading` and `trailing` one small node each (an `Icon`,
   * a `CircleAvatar`, an `Image`, a `Badge`, a `Text` or a `CircularProgressIndicator`), never pressed themselves; the whole tile
   * is one press and one TV stop; `selected` (with an `onTap`) fills it with primaryContainer.
   */
  | (KinoScreenBase & { type: "ListTile"; title: string; titleEn?: string; subtitle?: string; subtitleEn?: string; leading?: KinoScreenNode; trailing?: KinoScreenNode; dense?: KinoScreenResponsive<boolean> })
  /**
   * Task 17: a circle with a picture (`image`: https on a public host, or http on one where `kino.screen.httpImages` is true),
   * else initials (at most 3), else an icon; `radius` 12..64 dp (default 20). No `borderRadius`.
   */
  | (KinoScreenBase & { type: "CircleAvatar"; image?: string; text?: string; textEn?: string; icon?: KinoIconName; radius?: KinoScreenResponsive<number>; backgroundColor?: KinoScreenColorRole; labelText?: string; labelTextEn?: string })
  /**
   * Task 17: pages (at most 24) swiped across on a phone, Left and Right on a TV, Kino's dots under them; `onPageChanged`'s
   * `value` is the settled page's index; `initialPage` the first look only; `autoPlayMs` 3000..60000 (paused while touched or
   * focused, and with animations off); `viewportFraction` 0.3..1 (below 1: Kino's carousel), `padEnds` (default true). Never
   * inside a sideways scroll or a table cell.
   */
  | (KinoScreenBase & { type: "PageView"; children: KinoScreenNode[]; initialPage?: number; onPageChanged?: KinoScreenAction; autoPlayMs?: number; viewportFraction?: KinoScreenResponsive<number>; padEnds?: KinoScreenResponsive<boolean> })
  /**
   * apiVersion 17: full-screen pages, 2 to 8 `children` and a `key` (else dropped), under Kino's own progress bar, swiped on a
   * phone, Left and Right on a TV, never by themselves. The page reached is in `state.inputs.<key>` (a number from 0);
   * `onPageChanged`'s `value` is the settled index. Never inside a sideways scroll, a table cell or another `pages`.
   */
  | (KinoScreenBase & { type: "pages"; key: string; children: KinoScreenNode[]; onPageChanged?: KinoScreenAction; reverse?: boolean; progress?: "segments" | "bar" | "none" })
  /**
   * Task 17 item G: only a result's root. The `appBar` sits under Kino's own title bar (never replacing or covering it), the
   * `body` takes the bounded height left (drawn in `layout: "fill"`), the button sits above the `bottomNavigationBar`.
   *
   * `onBack` (apiVersion 19, Flutter's PopScope with `canPop: false`): while the screen on show declares it, Back (the phone's,
   * the TV remote's) does not close the screen or pop a route: Kino sends this action to you as the person's press and you
   * answer as usual; your next tree no longer declares `onBack` when the next Back should leave. An open pop-up still closes
   * first. No `go` in it. A failed or timed-out call closes the screen, and so does a second Back while the first is still
   * running. A player panel ignores it.
   */
  | (KinoScreenBase & { type: "Scaffold"; appBar?: KinoScreenAppBar; body: KinoScreenNode; floatingActionButton?: KinoScreenNode; bottomNavigationBar?: KinoScreenNavigationBar; onBack?: KinoScreenAction });

/**
 * Task 17 item G: a Scaffold's top bar: `leading` and up to four `actions` are `IconButton`s with a `labelText`; `bottom` a `TabBar`.
 * `title` is a string (with its `titleEn` twin) or, Flutter's way, any node (a `TabBar`, a `Row` of buttons, an `Image`...; at
 * most 40 nodes) drawn in the room left of the actions: a `TabBar` there shares one row with the actions.
 * `mergeWithKinoBar` (apiVersion 19, opt-in, needs a `leading`): Kino draws ONE bar, your `leading` in the place of its Close
 * button and your `title` in the place of your plugin's name; your `actions` stay at the end, followed by Kino's own buttons.
 * Without a `leading` the flag is ignored and both bars show. The person then leaves by your `leading` or by Back.
 * `dense` (additive, no new apiVersion): on a phone the bar has 4 dp above and below its row instead of 16 (56 dp in all); a TV
 * and a player panel ignore it. **Recommended for every screen of a plugin: `mergeWithKinoBar: true` + `dense: true`**, one compact
 * bar instead of two; both are plain booleans, so choose by window with `ctx.device` / `ctx.size` when you need to.
 * `divider` (additive, no new apiVersion): `false` takes away the hairline at the bar's lower edge (default `true`). A logo instead
 * of the name: with `mergeWithKinoBar`, an `Image` as the `title` (a `data:image/png;base64,…` address, `fit: "contain"`, `h: 32`
 * or 40, and a `Text` as its `fallback`), painted on the bar's own colour.
 */
type KinoScreenAppBar = KinoScreenBase & { type: "AppBar"; title?: string | KinoScreenNode; titleEn?: string; leading?: KinoScreenNode; actions?: KinoScreenNode[]; bottom?: KinoScreenNode; centerTitle?: boolean; dense?: boolean; divider?: boolean; backgroundColor?: KinoScreenColorRole; mergeWithKinoBar?: boolean };
/** Task 17 item G: a Scaffold's bottom bar of 2..5 items; `onChanged`'s `value` is the item's key (keep it in your state). */
type KinoScreenNavigationBar = KinoScreenBase & { type: "NavigationBar"; items: { key: string; icon: KinoIconName; label: string; labelEn?: string; badge?: KinoScreenBadge }[]; value?: string; selectedIndex?: number; onChanged?: KinoScreenAction };

/** What every button takes: `labelText` (not for an `IconButton`), `icon` (a Kino icon name), `onPressed`. */
type KinoScreenButton = Omit<KinoScreenBase, "onTap"> & { labelText?: string; labelTextEn?: string; icon?: KinoIconName; confirm?: string; confirmEn?: string; submit?: boolean; onPressed?: KinoScreenAction };

/**
 * A table row: its cells (at most 20), whose `colSpan`s fill the table's columns. `key` (unique among the screen's keys) lets a
 * `ui` show, hide or toggle operation name the row; `hidden` starts it hidden.
 */
interface KinoScreenTableRow { type: "TableRow"; key?: string; hidden?: boolean; children?: KinoScreenTableCell[] }
/**
 * A table cell: a plain `text` (`textEn` its English twin) or `children` (nodes, one level below the table: no `ListView`,
 * `SingleChildScrollView` or `DataTable` at any depth, those are dropped and logged; an `ExpansionTile` may sit there and
 * grows its row; with a `text` the children are ignored). `crossAxisAlignment` places its content across its width (start);
 * `colSpan` 1..8 (default 1; above 8 it is 8). Both may be per-size maps.
 */
interface KinoScreenTableCell { type: "TableCell"; text?: string; textEn?: string; children?: KinoScreenNode[]; crossAxisAlignment?: KinoScreenResponsive<"start" | "center" | "end">; colSpan?: KinoScreenResponsive<number> }

/*
 * The older spellings, still accepted (Kino reads them as the names above; nothing changes in what is drawn): the types
 * `col` (Column), `row`, `box` (Stack), `card`, `spacer` (Spacer and SizedBox), `divider`, `scroll` (SingleChildScrollView),
 * `grid` (GridView), `text`, `image`, `icon`, `badge`, `progress` (LinearProgressIndicator), `loading`
 * (CircularProgressIndicator), `list` (ListView), `button` (Button), `textInput` and `textArea` (TextField), `dropdown`
 * (DropdownButton), `toggle` (Switch), `checkbox`, `radioGroup`, `slider`, `chips`, `tabs` (TabBar), `popup` with `kind`
 * (AlertDialog, BottomSheet, PopupMenuButton), `form`, `banner` (MaterialBanner), `accordion` (ExpansionTile), `skeleton`,
 * `qr` (QrImage), `stepper` (NumberStepper), `table`, `tr`, `td` (DataTable, TableRow, TableCell); the properties `w`, `h`,
 * `minH`, `justify`, `align`, `weight`, `radius`, `onChange`, `onSubmit`, `hint`, `label` (and their `...En`), and a button's
 * `onTap`. Give one spelling: when a node has both, the Flutter-style one wins and Kino logs the clash. Log lines name the
 * older spelling. A name Kino does not know (Flutter's `Stepper` too) drops the node, logged.
 */

/**
 * How a player panel's body holds the tree (Task 14, apiVersion 14). "scroll" (the default): the body scrolls, the tree has no
 * height limit (a `ListView` draws flat, `flex` does nothing). "fill": the root is drawn at the body's size with no body scroll;
 * `flex` shares the height left and a `ListView` with `flex` is lazy and scrolls itself (a chat: messages over an input row at
 * the bottom). When the parts without `flex` alone are taller, that render is drawn as "scroll" (logged once). A full screen's
 * root is always drawn at the screen's size. Any other value is logged and read as "scroll".
 */
type KinoScreenLayout = "scroll" | "fill";

/** `screen` may return its tree with `every` on the root (the screen's timers, KinoScreenTimer) and its `layout` (Task 14). */
type KinoScreenRoot = KinoScreenNode & { every?: KinoScreenTimer | KinoScreenTimer[]; layout?: KinoScreenLayout };

/** A title card's or rail's size. */
type KinoScreenCardSize = "small" | "medium" | "large";
/** One action of a menu pop-up: a label, an optional Kino icon, and what a press does (the menu closes first). */
interface KinoScreenMenuItem { label: string; labelEn?: string; icon?: KinoIconName; onTap: KinoScreenAction; arg?: string }

/** A pop-up drawn by Kino over the canvas: `body` is text or nodes; at most 3 buttons, one without `event` closes it. */
interface KinoScreenDialog {
  title?: string; titleEn?: string; body?: string | KinoScreenNode[]; bodyEn?: string;
  buttons?: { label: string; labelEn?: string; event?: string; arg?: string; variant?: "primary" | "secondary" | "text" }[];
}

/**
 * What `screenEvent` answers; every field optional, `null` means nothing to do. `state` is a patch merged key by key
 * (`null` removes a key; at most 64 KB) after which Kino calls `screen` again; `route` goes to another screen of this plugin.
 */
interface KinoScreenAnswer {
  state?: Record<string, unknown> | null;
  /** One pop-up at a time: with more than one of dialog, sheet and menu, the dialog wins, then the sheet. */
  dialog?: KinoScreenDialog | null;
  /** A bottom sheet on the phone, a side drawer on the TV. */
  sheet?: { title?: string; titleEn?: string; body?: string | KinoScreenNode[]; bodyEn?: string } | null;
  /** A short list of actions (1..8). */
  menu?: { title?: string; titleEn?: string; items: KinoScreenMenuItem[] } | null;
  /**
   * A short message at the bottom (one at a time: a newer one replaces it). A string, or `{ text, role, action, ms }`: `ms`
   * 2000..8000 (default 3500), `action` a button whose event (with its `arg`) Kino sends once. On the TV the toast never takes
   * focus by itself: Down from the bottom of the screen reaches its action, and the remote's Menu (or Play/Pause) runs it.
   */
  toast?: string | { text: string; textEn?: string; role?: KinoScreenRole; action?: { label: string; labelEn?: string; event: string; arg?: string }; ms?: number } | null; toastEn?: string;
  go?: KinoScreenGo | null;
  route?: { push: string; params?: Record<string, unknown> } | { pop: true } | null;
  close?: boolean;
  focus?: string | null;
  /**
   * apiVersion 17: Kino draws the node with this `key` the person can see now (with a `state` change in the same answer, on the
   * new tree; a hidden node, a closed pop-up's, another page's or a pop-up's own key is dropped; 18+ titles always go) as a 1080x1350 PNG, at 360 dp wide and font scale 1, in the screen's theme, with Kino's own line
   * naming your plugin under it, and opens the system share sheet. Only the answer to the person's own tap or submit, within
   * 5 s; dropped, logged, from `open`, a tick, a load-more, a change, an `onClose` and inside a panel. Images wait 3 s at most,
   * then Kino's placeholder; buttons draw but do nothing. One at a time. A TV refuses it, logged, no toast: hide the button when
   * `kino.device` is "tv". A plugin below apiVersion 17 is refused and logged. No capability and no permission line.
   */
  share?: { key: string } | null;
  /**
   * apiVersion 17: the id of one of the plugin's jobs: turns on Kino's own row of that job, with its approvals in place. Only the
   * answer to the person's own tap or submit, within 5 s; dropped, logged, from `open`, a tick, a load-more, a change, an `onClose`
   * and inside a panel. Only for a job without `enabledBy`. No answer turns it off, and a row the person switched off stays off: Kino
   * tells them where to turn it on. Ask first with a line that says what runs; read `kino.jobOn` to know whether to ask.
   */
  enableJob?: string | null;
  /**
   * The plugin's own settings to write, by key, through Kino's settings (the same store and sync as its settings screen;
   * written before the `screen` call the answer asks for, so `kino.config` reads the new value). Only keys the manifest
   * declares in `settings`, at most 32 (sorted), with a value that fits: a `text` a string (trimmed; blank or `null` empties
   * it, unless required), a `toggle` a boolean, a `select` one of its option values, a `list` an array of records of its
   * fields that adds no address to its `url` fields (entries may be removed, reordered or retitled). Never a `url` (only the
   * person types an address, in the `settings` node), a `password`, an `action` or a `help` setting, and never a value holding
   * one of the plugin's secrets. Anything else is dropped and logged. Toggles and selects keep the plugin's web session; any
   * other write restarts it as Kino's Guardar does. Each setting is written at most once every 500 ms.
   */
  /**
   * Your settings to write (at most 32 keys). Screen asks: a `password` setting takes a string, kept exactly as given
   * (null or blanks empty it, never a required one), saved and synced as Ajustes saves a typed one, never read back.
   */
  config?: Record<string, string | boolean | Record<string, string>[] | null> | null;
  /**
   * Local operations the answer runs (apiVersion 14, Task 7i-2), the same as an action's `ui` (at most 8). `{ open: key }`
   * opens a declared `popup`; when the answer also changes `state`, it opens once the new tree is drawn, so the pop-up shows
   * its new body from its first frame (Back before then cancels it). `{ close: key }` closes it at once, for example after
   * the pop-up's Save. A timer's answer drops `ui`.
   */
  ui?: KinoScreenUiOp[];
}

/** The screen the person is on: `{ name: "main", params: {} }` at the root, else the last `route.push` and its params. */
/** `args` only on the route the screen opened at, when a `go.screen` gave it some (Task 7g). */
type KinoScreenRoute = { name: string; params: Record<string, unknown>; args?: Record<string, unknown> };

/**
 * `screen` -- required with the capability "screen": a pure view, the tree for this state (called on open and after every state patch).
 * `state.ui` holds what Kino did locally: `hidden` and `enabled` (by node key) and `open` (each accordion's open item keys).
 * `state.inputs` holds every input on screen by key: what the person or the plugin set, else the value the last tree shows
 * (toggle/checkbox a boolean, slider a number, dropdown/radioGroup the option value or null, chips an array when multiple,
 * stepper its value as text).
 * Events arrive one at a time, spaced 100 ms apart, never dropped for coming fast. Inside `screen` and `screenEvent`,
 * `kino.config.get/all` read the settings as stored now (a bound field's write or a `config` answer included).
 */
type KinoScreenFn = (arg: {
  state: Record<string, unknown>; route: KinoScreenRoute; device: KinoScreenDevice;
  size: { widthClass: KinoScreenSizeClass; heightClass: KinoScreenSizeClass; orientation: "portrait" | "landscape" };
  lang: "es" | "en";
  /** apiVersion 18: the id of your `appThemes` theme active now, else null. A change calls `screen` again. */
  activeTheme: string | null;
  /** Kino 0.9.81: one key per entry of your manifest's `recommends`, written as you wrote it (`{}` when none): whether that plugin is installed now. A change calls `screen` again. */
  installed: KinoScreenInstalled;
}) => Promise<KinoScreenRoot>;

/**
 * apiVersion 14, capability "schedule" (Task 8q): what `job(ctx)` receives. `id` is the manifest job's id; `reason` is
 * "scheduled" (its periodic work fired) or "manual" (the person pressed "Ejecutar ahora"); `lastRunMs` is when this job last ran
 * on this device (null before its first run); `attempt` is 1 plus its failures in a row.
 */
interface JobContext {
  id: string;
  reason: "scheduled" | "manual";
  lastRunMs: number | null;
  attempt: number;
}

/**
 * One entry of the manifest's `jobs` (apiVersion 14, Task 8q; `runOn`, Task 8q-2). `runOn: "any"` (the default): every device
 * that has the plugin runs it, for its own `kino.storage`. `runOn: "preferPhone"`: ONE of the person's linked devices runs it, a
 * linked phone first (a TV never runs it while a fresh phone can; it takes over when the phone stops for two periods), and the
 * job writes its result with `kino.shared` so the other devices read it. Read `kino.device` in the job to pick a lighter batch on
 * a TV (Kino enforces nothing extra; the job's caps apply). `enabledBy` (Task 18): the key of one of the plugin's own `toggle`
 * settings that is the person's on/off for this job, instead of its own opt-in switch: on while that setting is on (its default
 * counts) and the job's row in Ajustes holds no OFF of the person's (that OFF wins until they switch the row on again); the
 * setting off is always off. Anything else refuses the manifest.
 */
interface KinoJobDecl {
  id: string;
  label: { es: string; en?: string };
  everyMin: number;
  everyOptions: number[];
  runOn?: "any" | "preferPhone";
  enabledBy?: string;
  /**
   * apiVersion 17, with `runOn: "any"` only, never with `enabledBy`: one run per profile of the device with the plugin on that did not
   * leave itself out, one at a time. Consent is Kino's own row (a screen's `enableJob` turns it on, `kino.jobOn` reads it), and each
   * profile has Kino's «Incluir este perfil». Each run has that
   * profile's `kino.library`, `kino.shared`, `kino.storage`, `kino.config`, cookies, typed servers and `kino.lang`, in a fresh runtime
   * (keep nothing in module variables). `ctx` never says which profile. For a profile not in use `kino.notifications`, `kino.coins` and
   * `kino.seed` reject with `not_allowed`, `kino.log` stays out of the plugin's Registro, `kino.tmdb` uses Kino's key only, and outside `job` the runtime only reads.
   */
  perProfile?: boolean;
}

/**
 * `job` -- required with the capability "schedule": one background run, headless (no screen, nothing shown; its answer is never
 * read). Keep what you fetched in `kino.storage`; your screens read it when they open. At most 20 s, 10 requests (one at a
 * time; from apiVersion 17, with `ai` approved, 60 s and 20 requests; a `kino.fetch`, a `kino.ai.ask` and a `kino.tmdb` count), 2 MB of answer bodies (an answer that would cross it is refused with `too_large`) and 256 KB (UTF-8) written to
 * `kino.storage` per run (a cap crossed cuts the run: a failure). An allow-list: only `kino.fetch`, `kino.storage`, `kino.log`,
 * `kino.config` (read), `kino.cookies`, `kino.crypto`, `kino.sleep`, `kino.html`, `kino.secret`, `kino.error`, `kino.rank` and
 * `kino.library` (with its own approval), `kino.ai` (with its own approval), `kino.shared` (Task 8q-2), `kino.tmdb` (apiVersion 17), `kino.notifications` (with its own approval), `kino.coins`
 * (with its own approval, the balance only) and `kino.seed` (Task 18: under its usual telemetry-consent gate) work, plus the plain values (`kino.apiVersion`, `kino.device`...); everything else
 * (`kino.room`, `kino.qr`, `kino.browser`, `kino.ws`, `kino.meta`, `kino.nuvio`, `kino.catalog`, `kino.sync` and
 * any later API) rejects with `not_allowed`.
 */
type KinoJobFn = (ctx: JobContext) => Promise<unknown>;

/** `screenEvent` -- required with the capability "screen": a node's event (the first one is the reserved `open`). */
type KinoScreenEventFn = (arg: {
  /** apiVersion 18: the id of your `appThemes` theme active now, else null. */
  activeTheme: string | null;
  /** Kino 0.9.81: as in `screen`, `{ "<repo in recommends>": true | false }`. */
  installed: KinoScreenInstalled;
  name: string;
  /** The press's text; for the event `protocol` (apiVersion 20) the object `{ alias, stream, items }` instead. */
  arg?: string | KinoProtocolEventArg;
  value?: unknown; state: Record<string, unknown>; route: KinoScreenRoute; device: KinoScreenDevice; lang: "es" | "en";
}) => Promise<KinoScreenAnswer | null>;

// ---------- the player panel built with the screen kit (Task 8i, opt-in per result, apiVersion 14) ----------

/**
 * What `panel(context)` may return instead of a `KinoPanel`: the same drawer (its title, tabs and `refreshMs`) with a body built
 * from the screen nodes (`root`: Flutter-style names or aliases, forms, tabs, lists, tables, the settings node, qr, banner...).
 * A result without `format` is the legacy panel, unchanged; the format may change from one call to the next. Needs apiVersion
 * 14 (below it Kino reads the result as a legacy panel, logged). Answer it only when `context.features` includes "screen":
 * Kino puts it there only while plugin screens are on (with them switched off a screen-format result shows no panel, so
 * answer a legacy one then); an older Kino never sends it.
 * Limits: depth 6, 200 nodes (the legacy panel keeps its own); a `popup` node is dropped (pop-ups belong to the screen, not
 * to the drawer). `refreshMs` (2000..60000) is THE periodic call, as in the legacy panel: `every` is dropped here, logged. With
 * plugin screens switched off a screen-format result shows no panel (a legacy one still does).
 */
interface KinoPanelScreenResult {
  format: "screen";
  root: KinoScreenNode;
  /** Up to 60 characters. */
  title?: string; titleEn?: string;
  /** `#RRGGBB`, the legacy panel's rule. */
  accent?: string;
  /** Kino calls `panel` again every so often (2000..60000 ms), only while the panel is open: e.g. live scores. */
  refreshMs?: number;
  /** At most 6, as the legacy panel's; a tab press calls `panel` again with `context.tab`. */
  tabs?: { id: string; label: string; labelEn?: string; badge?: KinoScreenBadge }[];
  tab?: string;
  /** Task 8j: as `KinoPanel.player`: counts only with the `playerControl` capability. */
  player?: KinoPlayerAction;
  /** Task 14: how the body holds `root` (KinoScreenLayout); "fill" for a chat tab. Here, never on `root`. */
  layout?: KinoScreenLayout;
}

/**
 * The context of an apiVersion 14 plugin's panel calls: exactly `KinoPanelContext` (`device` "tv" | "phone", `lang` "es-CO"
 * style) plus the screen part, in every call, the first one included (Kino cannot know the format before the answer):
 * `state` (Kino's, kept for this title's playback: `inputs`, `ui` and your keys, as a screen's) and `size` (the drawer's size
 * classes; before the drawer measured itself, Kino's estimate). `playerEvent`'s context stays the legacy one.
 */
interface KinoPanelScreenContext extends KinoPanelContext {
  state: Record<string, unknown>;
  size: { widthClass: KinoScreenSizeClass; heightClass: KinoScreenSizeClass; orientation: "portrait" | "landscape" };
}

/**
 * Task 11 (apiVersion 14): the context of a tab you contribute (`"kinds": ["live"]`) on an En vivo channel. Exactly these keys:
 * live has no ref, title, ids, position, duration, pause, stats or player block. `channel.provider` is the id of the plugin
 * that lists the channel, `channel.code` its id there, `channel.name` its listed name: pass the first two to
 * `go.liveChannel` to tune another device to it. Sent only for a channel its provider's listing confirmed as not 18+, never
 * for «Mis canales» (the person's own lists). On a zap Kino calls `panel` again with the new channel (a render, never a
 * press); the panel stays open. Your `player` actions are dropped whole (live_channel); no `playerEvent` on live.
 * `values.video` is one set for every live channel (the session stays open across zaps). In screen mode `state` and `size` come too, as in `KinoPanelScreenContext`.
 */
interface KinoLivePanelContext {
  kind: "live";
  live: true;
  channel: { provider: string; code: string; name: string };
  foreign: true;
  source: { pluginId: string; name: string };
  device: "tv" | "phone";
  lang: string;
  tab?: string;
  values: { video: Record<string, KinoPanelValue>; plugin: Record<string, KinoPanelValue> };
  features?: ("loading" | "screen")[];
  state?: Record<string, unknown>;
  size?: { widthClass: KinoScreenSizeClass; heightClass: KinoScreenSizeClass; orientation: "portrait" | "landscape" };
}

/**
 * A screen-format panel's event to `panelAction(event, context)`: a node's action. `trigger` is "press" (a tap or a long
 * press), "change" or "submit"; `name` and `arg` are the node's event; `key` the input that fired (absent for a tap); `values`
 * the inputs' values (`context.state.inputs`). "tab" and "open" stay reserved.
 */
interface KinoPanelScreenEvent {
  key?: string;
  trigger: "press" | "change" | "submit";
  name: string;
  arg?: string;
  value?: unknown;
  values: Record<string, unknown>;
}

/**
 * What `panelAction` answers while the panel is in screen mode (`null` is nothing to do): the screen answer's fields that make
 * sense in a drawer, and the legacy panel's `player`, `message`, `pause` and `panel`. `state` is merged and `panel` asked again
 * with it; `ui` runs Kino's local operations; `config` writes your settings (the screen's rules); `go` takes every shape
 * (title, play, search, browse, section, categories: the panel closes and Kino goes there; `screen`: your screen over the
 * player, `pause` pauses the video; `close`, like `close: true`, closes the panel). `panel` is a whole new result, either format.
 * `dialog`, `sheet`, `menu` and `route` are not honoured inside the panel; `patch`, `values` and `save` are legacy-only: all
 * dropped, logged. A `playerEvent` answer's `panel` (either format) shows in the open panel of that title too (apiVersion 14
 * and later; logged when no panel of that title is open), but a `playerEvent` answer's `state` is never applied: keep it in
 * your own variables (or `kino.storage`) or answer a `panel` built from it. A toast's action on the TV runs from the remote's
 * Menu or Play/Pause key, wherever focus is in the drawer (it never takes focus).
 */
interface KinoPanelScreenAnswer {
  state?: Record<string, unknown> | null;
  toast?: KinoScreenAnswer["toast"]; toastEn?: string;
  ui?: KinoScreenUiOp[];
  config?: KinoScreenAnswer["config"];
  go?: KinoScreenGo | null;
  close?: boolean;
  focus?: string | null;
  player?: KinoPlayerAction;
  message?: string;
  pause?: boolean;
  panel?: KinoPanel | KinoPanelScreenResult;
}

/**
 * Configuration aids in the manifest's `settings` (apiVersion 12; no value, never in kino.config, never required).
 * `link`: a button that opens `url` through the system ONLY when the person taps it (https only, no user info, at most 2048
 * characters; https://t.me/... opens Telegram when installed), with Kino's "Abrir enlace" and the host under it; on TV the
 * address as text plus a QR to open on a phone. Kino makes no request to that host. An address holding one of your secrets is
 * not shown. `help`: a button (your `label`, else Kino's "Ayuda" / "Help") that opens a modal titled with your plugin's name with
 * `title` (at most 60) and `body` (at most 2000; `body` or `bodyEn` required), plain text only: newlines are kept, markup is
 * shown literally, nothing is clickable (use a `link` for an address); scrubbed of your secrets; a missing Spanish or English
 * text falls back to the other. At most 4 of each per plugin; they count among the sections, statuses and actions.
 */
type KinoLinkSetting = { key: string; type: "link"; label: string; labelEn?: string; url: string; hint?: string; hintEn?: string; devices?: KinoSettingDevice[] };
type KinoHelpSetting = { key: string; type: "help"; label?: string; labelEn?: string; title?: string; titleEn?: string; body?: string; bodyEn?: string; devices?: KinoSettingDevice[] };

/**
 * apiVersion 12 (additive): `devices` on any settings item, the devices whose Kino draws it: `["phone"]`, `["tv"]` or both
 * (absent = every device; an unknown device, an empty list or a repeat refuses the manifest). Host side only: on a device it
 * leaves out the item is neither drawn nor checked, but its value is still stored, saved back unchanged, synced, provisioned
 * and read through `kino.config`. Use it for setup a TV cannot do (a token pasted on the phone, sent with "Enviar
 * configuración"). Ignored below apiVersion 12.
 */
type KinoSettingDevice = "phone" | "tv";

/** One entry of the manifest's `settings` (the manifest is JSON: this documents its shape, a `settings` array holds these). */
type KinoManifestSetting =
  | {
      key: string; label: string; labelEn?: string;
      type: "text" | "url" | "password" | "toggle" | "select" | "list" | "section" | "status" | "action";
      hint?: string; hintEn?: string; required?: boolean; default?: string | boolean;
      options?: { value: string; label: string; labelEn?: string }[];
      fields?: { key: string; label: string; labelEn?: string; type: "text" | "url"; hint?: string; hintEn?: string; required?: boolean }[];
      max?: number; confirm?: string; confirmEn?: string;
      devices?: KinoSettingDevice[];
      /**
       * apiVersion 12, on an `action` only: never drawn on any device; it runs only as the `confirm` of another action's `link`,
       * after Kino's own "¿Eres tú?" (a find-then-confirm pair shows the person one button).
       */
      linkOnly?: boolean;
      /**
       * apiVersion 13, on a `password` or a `text` only: `false` keeps the value on the device where it was typed (never sent to a
       * paired device, never set or cleared by one, in no backup or kit). A password one may still be named in a sync `provision`
       * for a one-shot secret (stored device-only on the receiver too), never as the `keySecret`; a text one never in a provision.
       * A text one is still drawn as a plain text field (nothing masked). Default `true`.
       */
      sync?: boolean;
      /**
       * apiVersion 14, on a `toggle` or a `select` only: `"adultCode"` makes Kino ask the device's 18+ code (its own prompt, phone
       * and TV) before the person moves this setting AWAY from its `default` in Kino's settings form (Ajustes, or a screen's or
       * panel's `settings` node); back toward the default never asks. A wrong code or Cancelar keeps the old value; you never see
       * the code. Your own writes may only move it toward the default (an answer's `config` or an action's `setSettings` away
       * from it is refused), and no field may `bind` it: show it with `{ type: "settings", keys: ["<key>"] }`. The value syncs
       * like any setting; the code is asked on each device at the moment of the change.
       */
      unlockWith?: "adultCode";
    }
  | KinoLinkSetting
  | KinoHelpSetting;
type KinoManifestSettings = KinoManifestSetting[];

/** Your module's exports. `resolve` is required, and at least one of `search`/`home` (a catalog-only plugin: see [KinoCatalogOnlyPlugin]). */
interface KinoPlugin {
  /** apiVersion 6, capability "migrate". Return null for anything that is not yours. 10 s per call. */
  migrate?(input: KinoMigrateInput): Promise<KinoMigrateAnswer | null>;
  /** apiVersion 6, required when the manifest declares `section`. `tab` is null the first time. 20 s per call. */
  section?(arg: { tab: string | null }): Promise<KinoSectionAnswer>;
  /**
   * apiVersion 9, required when the manifest declares `panel`: the panel the button opens. Called with the context when it
   * opens, on a tab press and every `refreshMs`. 20 s per call; a panel that is not an object shows nothing.
   */
  panel?(context: KinoPanelContext | KinoPanelScreenContext | KinoLivePanelContext): Promise<KinoPanel | KinoPanelScreenResult>;
  /**
   * apiVersion 9, optional: a button pressed, an input changed or submitted. Called with TWO arguments, `(event, context)`. 20 s
   * per call. While the panel is in screen mode (Task 8i) the event is a `KinoPanelScreenEvent` and the answer a `KinoPanelScreenAnswer`.
   */
  panelAction?(event: KinoPanelEvent | KinoPanelScreenEvent, context: KinoPanelContext | KinoPanelScreenContext | KinoLivePanelContext): Promise<KinoPanelAnswer | KinoPanelScreenAnswer | null | void>;
  /**
   * apiVersion 9, optional, needs no `panel`: told about the playing title's player events (fire and forget: 5 s, at most one
   * in flight, events coalesce). May answer a `player` action, a `message` or (Task 8i, apiVersion 14 and later) a new
   * `panel` for the open panel; anything else is ignored (a `state` is never applied; below apiVersion 14 a `panel` too).
   * `(event, context)`.
   */
  playerEvent?(event: KinoPlayerEvent, context: KinoPanelContext): Promise<KinoPanelAnswer | null | void>;
  /**
   * apiVersion 14, required with "schedule" (Task 8q): one run of one of the manifest's `jobs`, in the background (see
   * `KinoJobFn` and `JobContext`). 20 s per run (from apiVersion 17, with `ai` approved, 60 s); the answer is ignored.
   */
  job?(ctx: JobContext): Promise<unknown>;
  /** apiVersion 6, optional, needs `browse`: up to 24 tiles in Categorías, in your order. 20 s per call. */
  categories?(arg: null): Promise<KinoCategory[]>;
  /** With `query.within` (capability "scopedSearch", apiVersion 6): null = "can't search inside this page". 15 s per call. */
  search?(query: KinoSearchQuery): Promise<KinoItem[] | KinoPage | null>;
  home?(): Promise<KinoRow[]>;
  browse?(ref: string, cursor: string | null): Promise<KinoPage>;
  episodes?(ref: string): Promise<KinoEpisodes>;
  /** Kino 0.9.54, optional, no capability, asked only from apiVersion 8 (a RESERVED export name from apiVersion 8): a movie item's details for its title page. 20 s. */
  details?(ref: string): Promise<KinoSeriesInfo | null>;
  /** `options.retry` (apiVersion 6) only when Kino resolves again after the origin refused your stream. `attempt` is 1 to 3; `status` is the origin's HTTP status when Kino heard one. */
  resolve(ref: string, options?: { retry?: { reason: "conflict" | "expired"; attempt: number; status?: 401 | 403 | 409 } }): Promise<KinoStream | KinoPluginByteStream>;
  /**
   * Optional, any apiVersion (additive: Kino 0.9.88 is the first to call it; an older one never does).
   * Called after the person stayed about 0.3 s on one of your title pages, with the very `ref` your `resolve` gets for
   * what its play button would start (a movie, an episode or a lone track; never a series or a live channel), so you can
   * warm what that `resolve` will need (a session, an authorization). The answer is ignored, and so is a failure: pressing
   * play calls `resolve` as always. A background call of 15 s (never "No responde"; a `kino.fetch` that would need the
   * person to approve a host fails instead of asking), at most once every 5 minutes per `ref` and 6 a minute per plugin. Never called beside
   * `"resolveAhead": true` (Kino resolves ahead instead), `catalogOnly` or `browser`. Must not start or count a play, nor
   * spend anything of the person's (a quota, a trial, a free play).
   */
  prepare?(ref: string): Promise<unknown>;
  /**
   * apiVersion 13, required with "byteSource". Kino calls it to play a `{ source: "plugin" }` stream: `handle` is the one
   * you returned, `offset` is a multiple of 4096, `length` is at most 1048576 (1 MiB). Answer with the bytes of that range,
   * base64-encoded; fewer than `length` only at the end of the data.
   */
  read?(arg: { handle: string; offset: number; length: number }): Promise<{ bytes: string }>;
  /**
   * apiVersion 13, required with "imageSource". Kino calls it to draw a {@link KinoImageRef} you returned: `handle` is
   * yours. Answer the picture as {@link KinoImageAnswer} within 10 s. It runs in the background (nobody is asked
   * anything, a slow answer never marks your plugin "No responde"), one call at a time for your plugin and never while
   * one of your byte streams is open; a call that started always runs to its end, so a connection you keep stays open. A
   * timeout discards your sandbox (QuickJS cannot be interrupted), and with it that connection.
   */
  image?(arg: { handle: string }): Promise<KinoImageAnswer>;
  /**
   * apiVersion 6, needed when a stream says `signing: "request"`: headers for one request, computed with
   * kino.crypto / kino.secret only. kino.fetch answers host_not_allowed; kino.storage, kino.cookies and
   * kino.sleep fail with not_allowed. 1.5 s limit.
   */
  sign?(request: { url: string; kind: "playlist" | "segment"; ref: string; context: string }): Promise<{ headers: Record<string, string> }>;
  /** apiVersion 3, capability "channels" (required with it). At most 200 categories. */
  liveCategories?(): Promise<Array<KinoLiveCategory | KinoPlaylist> | KinoPlaylist>;
  /**
   * apiVersion 3, capability "channels" (required with it). At most 500 per page. Kino asks 10
   * pages at first and 5 more each time the person scrolls near the end, up to 10,000 channels.
   */
  liveChannels?(arg: { categoryId: string; cursor: string | null }): Promise<KinoLiveChannelPage | KinoLiveChannel[]>;
  /**
   * apiVersion 3, optional with "channels": channels whose name matches `query`, listed or not (the
   * En vivo search, while some of your channels were never listed). At most 100 kept; `next` ignored.
   * apiVersion 6 with an 18+ category: give every hit `adult` or `categoryId`; an unmarked hit counts as 18+.
   */
  liveSearch?(arg: { query: string }): Promise<KinoLiveChannelPage | KinoLiveChannel[]>;
  /** apiVersion 3, optional with "channels". At most 50 channels and a 24 h window per call. */
  guide?(arg: { channelIds: string[]; from: number; to: number }): Promise<KinoGuideEntry[]>;
  /**
   * apiVersion 10, capability "playlists" (optional with it, like every function below). The
   * playlists already in the person's account on this service.
   */
  playlists?(): Promise<KinoHostedPlaylist[]>;
  /**
   * apiVersion 10, optional with "playlists". A page of one playlist's items, the same shape as
   * {@link KinoPlugin.browse}.
   */
  playlistItems?(arg: { playlistId: string; cursor: string | null }): Promise<KinoPage | KinoItem[]>;
  /**
   * apiVersion 10, optional with "playlists". Absent means Kino never offers "crear lista nueva" for
   * this plugin.
   */
  playlistCreate?(arg: { title: string }): Promise<{ id: string }>;
  /** apiVersion 10, optional with "playlists", independently of playlistRemoveItem. */
  playlistAddItem?(arg: { playlistId: string; ref: string }): Promise<void>;
  /** apiVersion 10, optional with "playlists", independently of playlistAddItem. */
  playlistRemoveItem?(arg: { playlistId: string; ref: string }): Promise<void>;
  /** apiVersion 10, optional with "playlists". The new full order, as a list of every item's `ref`. */
  playlistReorder?(arg: { playlistId: string; refs: string[] }): Promise<void>;
  /**
   * The settings form's texts (manifest, not code): since Kino 0.9.55 a setting may add `labelEn`, `hintEn` and (an action,
   * next to `confirm`) `confirmEn`, an option and a list field `labelEn` (a field also `hintEn`), each with the base field's
   * limits. Kino shows them when the app is in English; the base texts stay the Spanish default and the fallback. apiVersion 9
   * (Kino 0.9.55): below it the keys are unknown and ignored. Your code never sees them: keys and values are the same in both languages.
   */
  /**
   * apiVersion 6: required when a setting has `type: "status"` (or, apiVersion 13, `type: "qr"`). One text per status setting
   * key, shown as-is (at most 200 characters; a missing key or a non-text reads "Sin información"). 10 s. A `qr` setting's
   * key holds the text its QR encodes: 1 to 512 characters, no control character, an http(s) address only https on a public
   * host; anything else (or a text holding a sealed secret) draws no QR. Asked when the form opens, after every action and,
   * with a `qr` setting's `refreshMs`, every that many ms while the form is on screen (never while the previous call runs).
   * apiVersion 13 `hide`: keys of your own settings the form does not draw while this answer is current (values kept, at most
   * 32 read, unknown keys ignored). A `qr` setting with no text draws nothing.
   */
  settingsStatus?(): Promise<{ [key: string]: string | string[] | undefined; hide?: string[] }>;
  /** apiVersion 6: required when a setting has `type: "action"`. Runs when the person presses that button (30 s); the `message` (at most 300 characters, default "Listo") is shown; settingsStatus() is asked again after every action (and when the form opens); `refresh: true` is still accepted and changes nothing. `clearSettings` (up to 12 keys of your own optional, valued settings: not a `required` one, not a section/status/action) is emptied by Kino right after a successful action, as if the person had emptied the field and saved (a password leaves the Keystore; your sandbox closes as for any saved change; `kino.storage` survives); anything else in it is dropped. A throwing action clears nothing. `link` (Kino 0.9.74, additive `action.link`): Kino asks the person with its OWN question ("¿Eres tú, <candidate>?" / "Is this you, <candidate>?", naming your plugin by its manifest `name`) and runs the `confirm` action exactly once only if they confirm; Cancel runs nothing and your plugin hears nothing. `candidate`: 1 to 64 characters after trimming, runs of spaces collapsed; no control or invisible formatting characters, no space but the ASCII one, no blank fillers (U+115F, U+1160, U+3164, U+FFA0, U+2800); scrubbed of your secrets and shown as plain text. `confirm`: the key of ANOTHER `action` setting of this plugin that declares no `confirm`/`confirmEn` question of its own. Anything else refuses the link: your `message` still shows, with Kino's generic error. A `link` in the confirm action's own answer is ignored. `setSettings` (Kino 0.9.74, additive `action.setSettings`): up to 8 of your own `text` or `select` settings and, from apiVersion 13, `password` settings (never a `url`: only the person types a server; never a toggle or list) with string values, checked like typed values (a required one is never emptied; your `validateSettings` is not run); Kino saves them through the form's own save, so they reach the person's other devices like typed values. An unknown or secret key, a non-string, a bad value, a key also in `clearSettings`, a value holding one of your secrets or more than 8 keys refuse the whole field: nothing is applied and the form shows Kino's generic error under your message. A password filled this way (apiVersion 13, a "Create key" action) is stored sealed exactly like a typed one, never logged, and scrubbed from this answer's `message` and `link`, so it is never shown back. */
  action?(key: string): Promise<{ message?: string; refresh?: boolean; clearSettings?: string[]; setSettings?: Record<string, string>; link?: { candidate: string; confirm: string } } | null | void>;
  /**
   * apiVersion 6, optional: checks the values BEFORE Kino saves them (20 s). `null` accepts; `{ key: "mensaje" }`
   * refuses with the message under that field (a key that is not one of your valued settings refuses too, as a
   * general message); a text refuses with that text. If it throws, times out or answers anything else, nothing is
   * saved and the person may "Guardar sin comprobar".
   */
  validateSettings?(values: Record<string, string | boolean | Array<Record<string, string>>>): Promise<Record<string, string> | string | null>;
}

/** A Stream's `subtitles` entry: a track at a `url`, or (apiVersion 25) inline `text` in `format` "vtt" or "srt" with no `url`. */
type KinoStreamSubtitle =
  | { lang: string; url: string; format?: "vtt" | "srt" }
  | { lang: string; format: "vtt" | "srt"; text: string };

/** A subtitles() track: a Stream's `subtitles` entry plus an optional `label` and `translated` (a machine translation). */
interface KinoSubtitleTrack { lang: string; url: string; format?: "vtt" | "srt"; label?: string; translated?: boolean }

/**
 * `subtitles` -- optional for any plugin (Kino asks every plugin that exports it), required with the capability
 * "subtitles". Tracks for a title Kino knows by IMDb or TMDB id (an episode's ids are the series'); `languages` are ISO
 * 639-1, best first. Checked like a Stream's `subtitles`: 30 kept, then only the person's languages are listed. 10 s, a
 * background call.
 */
type KinoSubtitlesFn = (arg: {
  imdbId?: string; tmdbId?: number; kind: "movie" | "series"; season?: number; episode?: number;
  title?: string; year?: number; languages: string[];
  /**
   * The file playing (Kino 0.9.51+), only what is known, absent when nothing is; never its URL. `hash`: the 16-hex
   * OpenSubtitles hash and `size` the bytes it was computed with; `name`: the file name with its extension.
   */
  file?: { hash?: string; size?: number; name?: string };
}) => Promise<KinoSubtitleTrack[]>;

/** Ids a tracking event carries, each only when known. */
interface KinoTrackingIds { imdb?: string; tmdb?: number; tvdb?: number; anilist?: number; mal?: number }

/**
 * `track(event)`'s argument (apiVersion 7, the "tracking" capability): what the person plays on this device. For a movie
 * `ids` are the movie's; for an episode `ids` are the EPISODE's own (may be `{}`) and the show's are in `show.ids` -- never
 * use the show's ids as the episode's. `watched` fires once, with 3 minutes or less left and at least 90% played.
 */
interface KinoTrackingEvent {
  /** Stable across retries of this event: the idempotency key. */
  id: string;
  type: "start" | "progress" | "stop" | "watched";
  /** When it happened on the device, epoch ms. */
  at: number;
  kind: "movie" | "episode";
  ids: KinoTrackingIds;
  /** A movie's name, or an episode's own name when TMDB has one. */
  title?: string;
  year?: number;
  show?: { title: string; year?: number; ids: KinoTrackingIds };
  season?: number;
  episode?: number;
  positionMs?: number;
  durationMs?: number;
  /** positionMs / durationMs, 0..1. */
  progress?: number;
  /** A `progress` sent because the person paused. */
  paused?: true;
}

/**
 * `track` -- required with the capability "tracking" (apiVersion 7). Return anything (`{ ok: true }`) when delivered; throw
 * `kino.error(code)` otherwise: `timeout`/`network`/`unavailable`/`rate_limited` retry later (in order, with backoff),
 * `auth_required`/`invalid_request`/`not_found`/`geo_blocked`/`host_not_allowed`/`too_large` drop the event. 10 s, a
 * background call.
 */
type KinoTrackFn = (event: KinoTrackingEvent) => Promise<unknown>;

/**
 * `segments(query)`'s argument (apiVersion 7, the "segments" capability): the title that started playing. For a movie `ids`
 * are the movie's; for an episode `ids` are the EPISODE's own (maybe `{}`) and the show's are in `show.ids`.
 */
interface KinoSegmentsQuery {
  kind: "movie" | "episode";
  ids: KinoTrackingIds;
  show?: { ids: KinoTrackingIds };
  season?: number;
  episode?: number;
  /** The playing file's length: answer for that cut. */
  durationMs?: number;
}

/** One segment of the file, in whole ms. Kino uses `intro` and the first `outro`/`credits`; `recap` and `preview` have no button yet. */
interface KinoSegment { type: "intro" | "outro" | "recap" | "credits" | "preview"; startMs: number; endMs: number }

/**
 * `segments` -- required with the capability "segments" (apiVersion 7). Each bad entry is dropped on its own (unknown type,
 * not whole ms, under 1 s, past the file's end, overlapping one of its type); 10 kept. 8 s, a background call.
 */
type KinoSegmentsFn = (query: KinoSegmentsQuery) => Promise<KinoSegment[] | null>;

/**
 * `lyrics(query)`'s argument (apiVersion 19, the "lyrics" capability): the song that is playing in the music player. `artist` may be
 * "" and `album`, `durationMs` and `ids` absent. The audio's address is never sent.
 */
interface KinoLyricsQuery {
  title: string;
  artist: string;
  album?: string;
  /** The song's length: answer for that cut. */
  durationMs?: number;
  /** Only the ids Kino knows: `isrc`, `musicbrainz`, `youtube`. */
  ids?: { isrc?: string; musicbrainz?: string; youtube?: string };
}

/** One synchronized line: it starts at `ms` (a whole number of ms, at least 0, never below the previous line's) and has text. */
interface KinoLyricsLine { ms: number; text: string }

/**
 * What Kino shows. Give `synced` and/or `plain`; `instrumental: true` alone says the song has no lyrics. `label` (60 characters) names
 * the source in the picker; `matchDurationMs` is the length of the entry you matched, so Kino can tell whether the timing fits.
 */
interface KinoLyricsAnswer {
  synced?: KinoLyricsLine[];
  plain?: string;
  label?: string;
  instrumental?: boolean;
  matchDurationMs?: number;
}

/**
 * `lyrics` -- required with the capability "lyrics" (apiVersion 19). `null`, `[]` or `{}` means "nothing for this song". Each bad
 * synced line is dropped on its own; 800 lines of 300 characters, a plain text of 20,000, the whole answer under 102,400 characters.
 * 10 s, a background call.
 */
type KinoLyricsFn = (query: KinoLyricsQuery) => Promise<KinoLyricsAnswer | null>;

/** A lyrics source: capabilities only "lyrics" (and maybe "subtitles", "tracking" or "segments"). */
interface KinoLyricsSource { lyrics: KinoLyricsFn; subtitles?: KinoSubtitlesFn; track?: KinoTrackFn; segments?: KinoSegmentsFn }

/** A plugin that plays (`resolve` required, as above), optionally finding subtitles, tracking or segments too. */
interface KinoPlayingPlugin extends KinoPlugin { subtitles?: KinoSubtitlesFn; track?: KinoTrackFn; segments?: KinoSegmentsFn; lyrics?: KinoLyricsFn; meta?: KinoMetaFn }

/** A subtitle provider: capabilities only "subtitles" (and maybe "tracking" or "segments"), so `subtitles` is its export. */
interface KinoSubtitleProvider { subtitles: KinoSubtitlesFn; track?: KinoTrackFn; segments?: KinoSegmentsFn }

/** A tracker: capabilities only "tracking" (and maybe "subtitles" or "segments"). */
interface KinoTracker { track: KinoTrackFn; subtitles?: KinoSubtitlesFn; segments?: KinoSegmentsFn }

/** A segment source: capabilities only "segments" (and maybe "subtitles" or "tracking"). */
interface KinoSegmentSource { segments: KinoSegmentsFn; subtitles?: KinoSubtitlesFn; track?: KinoTrackFn }

/**
 * Kino 0.9.54, `"catalogOnly": true` in kino-plugin.json (additive: no new apiVersion, an older Kino ignores the field): a
 * catalog that lists and describes titles and plays none. Kino sends its titles to the person's other sources ("Buscar
 * dónde verlo"), never lists it as a source of a title and never calls its `resolve`. Needs one of `home`, `browse`,
 * `search`, `meta`; refuses `download`, `drm`, `channels`, `streamHosts` and `"browser": true` (`"pages"` is fine). To install
 * on Kino 0.9.53 and older too, keep declaring and exporting `resolve` (throw `kino.error("not_found", …, { userMessage })`)
 * and declare `search` or `home`: those apps ignore the field and require both.
 */
interface KinoCatalogOnlyPlugin extends Omit<KinoPlugin, "resolve" | "sign" | "prepare" | "liveCategories" | "liveChannels" | "liveSearch" | "guide"> {
  /** Only for Kino 0.9.53 and older (which require it): never called from Kino 0.9.54 on. */
  resolve?: KinoPlugin["resolve"];
  subtitles?: KinoSubtitlesFn;
  track?: KinoTrackFn;
  segments?: KinoSegmentsFn;
  meta?: KinoMetaFn;
}

/** Your module's exports: one of these. */
type KinoPluginModule = KinoPlayingPlugin | KinoCatalogOnlyPlugin | KinoSubtitleProvider | KinoTracker | KinoSegmentSource | KinoLyricsSource;

// ---------- the kino API ----------

type KinoErrorCode = "auth_required" | "not_found" | "geo_blocked" | "rate_limited" | "unavailable";
type KinoFetchErrorCode = "host_not_allowed" | "timeout" | "network" | "too_large" | "invalid_request" | "rate_limited";
/** Kino 0.9.53: what `kino.meta` and `kino.tmdb` throw besides the fetch codes (see contract.json `kinoMeta`/`kinoTmdb`). */
type KinoServiceErrorCode = "rate_limited" | "not_allowed" | "no_tmdb_key" | "not_found" | "unavailable";

/** Kino 0.9.71, `kino.nuvio.scrapers(query)`: `repo` is a GitHub `owner/repo` or the https address of a Nuvio `manifest.json`, as the person added it. */
interface KinoNuvioScrapersRequest {
  repo: string;
  /** Only these scraper ids (at most 64). */
  scrapers?: string[];
}

/** Kino 0.9.71, `kino.nuvio.streams(query)`: the title by its TMDB id; a series needs `season` and `episode`. */
interface KinoNuvioStreamsRequest extends KinoNuvioScrapersRequest {
  type: "movie" | "series" | "tv";
  tmdbId: number;
  season?: number;
  episode?: number;
  /** How long each scraper may take, 2000 to 60000 ms (default 60000): a scraper that hangs answers `timeout` and hides nothing. */
  timeoutMs?: number;
}

interface KinoNuvioScraper { id: string; name: string }

/** One scraper a repository offers (`kino.nuvio.available`). */
interface KinoNuvioOffered extends KinoNuvioScraper { description: string; types: string[]; languages: string[]; compatible: boolean; installed: boolean }

/** One copy a scraper found: a `Stream`'s fields, copies included; a lazy copy (no address yet) is left out. */
interface KinoNuvioStream {
  url: string;
  mime?: string;
  headers?: Record<string, string>;
  label?: string;
  expiresInSeconds?: number;
  subtitles?: { lang: string; url: string; format?: "vtt" | "srt" }[];
  alternatives?: { url: string; mime?: string; headers?: Record<string, string>; label?: string }[];
}

type KinoNuvioResult =
  | { scraper: KinoNuvioScraper; ok: true; stream: KinoNuvioStream }
  | { scraper: KinoNuvioScraper; ok: false; code: string; message: string };

interface KinoNuvioStreamsAnswer { results: KinoNuvioResult[]; truncated: boolean }

/**
 * Kino 0.9.53, `kino.meta(query)`: the title to ask about. `type` and at least one id; ids are positive integers up to
 * 2147483647 (a number or a digit string) except `imdb` ("tt0133093"). `lang` ("es", "es-MX") goes to the person's meta
 * plugins. Anything else is `invalid_request`; the whole query as JSON is at most 4096 characters.
 */
interface KinoMetaRequest {
  type: "movie" | "series";
  ids: { imdb?: string; tmdb?: number | string; tvdb?: number | string; kitsu?: number | string; mal?: number | string; anilist?: number | string };
  lang?: string;
}

/**
 * Kino 0.9.55, apiVersion 9 (check `kino.meta.byTitle === true` first; below apiVersion 9 or on an older Kino the title is dropped and the query answers `invalid_request`): the title to ask about by
 * name when you have no id. `title` 1..200 characters, `year` 1870..2100 (a number or a 4-digit string; only with `title`).
 * Kino searches TMDB (the type's own search, es-MX, first page) and keeps the hit whose es-MX or original title equals
 * yours once both are normalised (lowercase, no accents, punctuation as spaces); with `year`, that exact year wins, else
 * one a year off. Two hits that tie (same title and year, or same title and no year) or no match: the answer is null,
 * never a guess. Then it answers exactly as for ids (same shape, `ids` filled in, same cache, budget and timeout). With
 * `ids` too, the ids win.
 */
interface KinoMetaTitleRequest {
  type: "movie" | "series";
  title: string;
  year?: number | string;
  lang?: string;
}

/**
 * Kino 0.9.53, what `kino.meta` answers (or null: nobody knew the title). Merged the way Kino's info page merges: Kino's
 * own TMDB lookup first (Spanish, es-MX), AniList for an anime, then the person's other `meta` plugins, each only filling
 * what the earlier ones left empty (ratings add up). Every field but `ids` and `sources` appears only when known.
 */
interface KinoMetaAnswer {
  title?: string;
  /** Up to 2000 characters, HTML stripped. */
  overview?: string;
  /** "1999". */
  year?: string;
  poster?: string;
  backdrop?: string;
  /** A clear-logo of the title (its name drawn as art). */
  logo?: string;
  /** At most 5. */
  genres?: string[];
  /** A movie's runtime, 1..1000 (never a series'). */
  runtimeMinutes?: number;
  tagline?: string;
  /** Age rating ("12+", "PG-13"). */
  certification?: string;
  /** A movie's directors, or a series' creators. */
  directors?: string[];
  /** A series' episodes, at most 5000 (trimmed from the end to keep the answer under 1,000,000 characters); `id` is the Stremio-style video id ("tt0944947:1:1"). */
  episodes?: { season: number; number: number; title?: string; overview?: string; still?: string; airDate?: string; id?: string }[];
  /** Every id Kino knows for the title, the ones you asked with included. */
  ids: { imdb?: string; tmdb?: number; tvdb?: number; kitsu?: number; mal?: number; anilist?: number };
  /** At most 6, one per source; TMDB's own vote is `{ source: "tmdb" }`. */
  ratings?: { source: "imdb" | "tmdb" | "rottentomatoes" | "metacritic" | "letterboxd" | "mal" | "anilist" | "trakt"; value: string }[];
  /** At most 20. */
  cast?: { name: string; character?: string; photo?: string }[];
  /** Who contributed to this answer. */
  sources: ("tmdb" | "anilist" | "plugin")[];
}
type KinoEncoding = "utf8" | "hex" | "base64";
type KinoKeyType = "ec" | "ed25519" | "x25519";
/** A public key as a JWK, in WebCrypto's key order: EC `{ crv, kty: "EC", x, y }`, OKP `{ crv: "Ed25519" | "X25519", kty: "OKP", x }` (base64url, no padding). */
interface KinoJwk { readonly crv: string; readonly kty: "EC" | "OKP"; readonly x: string; readonly y?: string }
/** apiVersion 6: a handle to a private key that lives only inside Kino, in this runtime. */
interface KinoPrivateKey { readonly type: KinoKeyType; readonly namedCurve?: "P-256" | "P-384"; readonly handle: string }
/** apiVersion 6: `spki` is DER as base64; `raw` is base64 (an uncompressed point 04||x||y for ec, 32 bytes otherwise). */
interface KinoPublicKey { readonly type: KinoKeyType; readonly namedCurve?: "P-256" | "P-384"; readonly jwk: KinoJwk; readonly spki: string; readonly raw: string }

interface KinoError extends Error {
  /** `KinoError_<code>` (e.g. `KinoError_not_found`). */
  readonly name: string;
  readonly code: KinoErrorCode | KinoFetchErrorCode | KinoServiceErrorCode | "crypto_error" | "unknown";
  /**
   * The sentence you passed as `{ userMessage }`, cut at 161 characters; absent when you passed none. On a `no_tmdb_key`
   * from `kino.tmdb` (Kino 0.9.53) it is Kino's own sentence for the person, in their language: show it as is.
   */
  readonly userMessage?: string;
  /**
   * Kino 0.9.55: on a `host_not_allowed` from `kino.fetch`, the host Kino refused (at most 253 characters), so you never
   * have to read it out of the message. Absent on older Kino and when no one host was refused (the signing lane).
   */
  readonly host?: string;
}

interface KinoErrorOptions {
  /**
   * Your own sentence for the person, shown INSTEAD of Kino's line for the code as "Mensaje de <plugin>: <sentence>",
   * only when: your plugin's name has no ":", no digit glued to a letter, spells no Kino and uses only the characters
   * below; the code is one of
   * the five `KinoErrorCode`s; it is 1..160 characters once trimmed, made only of Basic Latin and Latin-1 letters
   * (á é í ó ú ü ñ ç ã õ…, not ø æ ð þ ß), digits 0-9, the plain space and . , : ; ¿ ? ¡ ! ' ’ ‘ “ ” « » ( ) % - – — ▸
   * (; only before a space); it reads as
   * plain words (two or more, no URL, no "TypeError:" prefix, no undefined/null/NaN, not ending in : , ; -); fewer than
   * 6 digits in all and none glued to a letter; no domain (site.app, site .app, site. app, www, punto/dot + com, app…);
   * no "kino" once 1 l ! ¡ read as
   * i, 0 as o and non-letters dropped; no credential, money or contact stem (pag…, abon…, recarg…, transfer…,
   * contraseñ…, passw…, clave…, token…, tarjeta, PIN, Nequi, Daviplata, WhatsApp, Telegram, SMS/verification code);
   * and none of the person's passwords or a sealed value. Otherwise Kino's line stays. A host the person refused still
   * wins, whatever the code. It counts only for the call that built the error. Older Kino builds ignore it. Plugins
   * that use it to ask for money, credentials or contact outside Kino are removed from the catalog.
   */
  userMessage?: string;
}

interface KinoFetchOptions {
  method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
  headers?: Record<string, string>;
  /** A string, or JSON, a form, or raw bytes as base64. URL + headers + body at most 1,048,576 characters. */
  body?: string | { json: unknown } | { form: Record<string, string | number | boolean> } | { base64: string };
  /** "follow" (default, at most 10 hops, each host-checked) or "manual" (returns the 3xx). */
  redirect?: "follow" | "manual";
  /** true (default): send and store cookies from the plugin's jar. */
  cookies?: boolean;
  /** Default 15000, at most 30000. */
  timeoutMs?: number;
  /**
   * apiVersion 14: read at most this many bytes of the body (1 to 2,000,000), then stop: the rest is never downloaded and
   * the answer's `truncated` is true (a plugin with sealed `secrets` gets the same answer, but the body is read whole, up to
   * 5 MB, and redacted before the cut). Bytes after decompression; a cut text may end inside a character. Out of range:
   * `invalid_request`. Below apiVersion 14 the option is ignored.
   */
  maxBytes?: number;
  /**
   * apiVersion 14: end the read as soon as the text holds this marker (1 to 32 printable ASCII characters, ASCII
   * case-insensitive), keeping everything up to and including it; `truncated` is true when more followed. Text responses
   * only (a byte answer fails with `invalid_request`). With `maxBytes`, whichever comes first. Below apiVersion 14 ignored.
   * Example: `{ stopAt: "</head>", maxBytes: 65536 }` reads a page's head and nothing more.
   */
  stopAt?: string;
}

interface KinoResponse {
  readonly ok: boolean;
  readonly status: number;
  readonly url: string;
  /** Lower-cased names; repeated headers joined with ", "; never set-cookie. */
  readonly headers: Readonly<Record<string, string>>;
  text(): string;
  json(): any;
  /** The body bytes (at most 5 MB) as base64. */
  base64(): string;
  /** apiVersion 14: true when the body was cut at the request's `maxBytes` (false otherwise; absent below 14). */
  readonly truncated?: boolean;
}

interface KinoHtmlMatch {
  text: string;
  html: string;
  attrs: Record<string, string>;
}

interface KinoCipherOptions {
  key: string;
  iv?: string;
  data: string;
  /** CBC/ECB only. Default "pkcs7". */
  padding?: "pkcs7" | "none";
  /** GCM only: additional authenticated data. */
  aad?: string;
  /** Default utf8 to encrypt, base64 to decrypt. */
  inputEncoding?: KinoEncoding;
  /** Default base64 from encrypt, utf8 from decrypt. */
  outputEncoding?: KinoEncoding;
  keyEncoding?: KinoEncoding;
  ivEncoding?: KinoEncoding;
  aadEncoding?: KinoEncoding;
}

type KinoCipher =
  | "aes-128-cbc" | "aes-192-cbc" | "aes-256-cbc"
  | "aes-128-ecb" | "aes-192-ecb" | "aes-256-ecb"
  | "aes-128-ctr" | "aes-192-ctr" | "aes-256-ctr"
  | "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"
  | "des-ede3-cbc" | "des-ede3-ecb";

/** apiVersion 20: `kino.visualBrowser.open` options. */
interface KinoVisualBrowserOptions {
  /** Where the window starts: https, the default port, on a host of the manifest's `hosts` (at most 2,048 characters). */
  url: string;
  /** A short line after your plugin's name in Kino's bar (at most 60 characters, no control character). */
  title?: string;
  /**
   * When to close by itself. With it Kino draws no Listo button. `cookies`: every named cookie exists for the hosts the window
   * was on (at most 32 names; checked about every 0.7 s, HttpOnly ones included). `urlMatches`: the window's address matches
   * this pattern, where `*` is any run of characters (also none) and the rest is literal, against the whole address (at most
   * 200 characters). Either one is enough.
   */
  doneWhen?: {
    cookies?: string[];
    urlMatches?: string;
    /** The page's localStorage holds every one of these KEYS (at most 32, checked about every 0.7 s), for the page the window is on. Needs a Kino that reads localStorage (see `collect.localStorage`). */
    localStorage?: string[];
  };
  /** What to hand back when the status is `"done"` (a closed or timed-out window returns nothing but `finalUrl`). */
  collect?: {
    /** Cookie NAMES (at most 32), read from the hosts the window was on and that your manifest declares; at most 64 cookies and 16,384 characters of names and values together. */
    cookies?: string[];
    /**
     * localStorage KEYS (at most 32, each 1 to 256 characters without control characters) read from the page the window ends on, which
     * must be on a host of your manifest. Only the keys you name are read, never the whole store, and only with `"done"`; the answer's
     * `localStorage` holds the ones that exist (key to value), at most 65,536 characters of keys and values together (what does not fit
     * is left out, never cut). `storeAs` keeps to the cookies: these values come back to your script. Kino's sheet lists the keys.
     * A Kino that does not read localStorage ignores this option and answers no `localStorage`: check for it before relying on it.
     */
    localStorage?: string[];
    /** The page's HTML as it stands, at most 2,000,000 characters (as `kino.browser.page`). */
    html?: boolean;
    finalUrl?: boolean;
    /**
     * Kino writes the collected cookies itself into YOUR `password` setting named `setting` (declared in the manifest), as
     * `name=value; name2=value2` (`"header"`) or a JSON object (`"json"`), once your call has ended; you only get `stored` and
     * `storedNames`, never a value. Needs `cookies`. The text must fit the setting (500 characters for a `password`): else `"store_failed"`.
     *
     * `spill`: a longer cookie list (YouTube Music's needs about 850 characters) goes into up to 3 MORE of your declared `password`
     * settings (distinct, none equal to `setting`, else `"bad_args"`). Kino cuts the text at 500 characters and fills `setting`, then
     * each `spill` setting in order (a header text may be cut inside a cookie); settings the text does not reach are emptied, but only
     * if they hold a value. All of them are saved in ONE save, all or nothing; if `(1 + spill.length) x 500` cannot hold the text:
     * `"store_failed"` and nothing is stored. To read it back, concatenate the settings' values in that order WITHOUT a separator:
     * `[kino.config.cookieA, kino.config.cookieB, ...].join("")`.
     *
     * `thenEvent`: the name of a `screenEvent` Kino sends to THIS plugin's open screen once the setting was written (your call has
     * ended by then, so a screen cannot read the new account from the call itself). Its `arg` is `{ stored: ["SID", ...] }` (cookie
     * names, never a value) and it has no `value`. Same name rules as any event (1 to 128 of `A-Z a-z 0-9 . _ ~ -`, never `"open"`,
     * else `"bad_args"`). Sent only when the call came from a screen's `screenEvent` (from a settings action or a panelAction the
     * option is accepted and nothing is sent), only after a successful write (never if it failed or the window was not `"done"`),
     * dropped silently when your screen is no longer open or its event queue is full, at most once per call. It is a follow-up of
     * the person's press, not a press: like a change, its answer's `go.url`, `go.copy`, `go.titleByIds` and `go.installPlugin`,
     * `share` and `enableJob` are dropped; it may change `state`, `config` and show a toast.
     */
    storeAs?: { setting: string; format: "header" | "json"; spill?: string[]; thenEvent?: string };
  };
  /**
   * `"browser"`: the window identifies itself as the phone's Chrome (one string Kino keeps up to date). Or your own string, 1 to
   * 300 printable ASCII characters (a site that changes what it accepts is fixed by a plugin update, not a Kino release). Either
   * way the WebView marker (`; wv`) is removed and `X-Requested-With` is not sent (on a WebView that lets Kino remove it). Absent:
   * the WebView's own. The sheet tells the person which one.
   */
  userAgent?: "browser" | (string & {});
  /**
   * At most 600,000 (10 minutes, the default); a larger value is brought down to it, a smaller one up to 5,000. This is the only
   * time limit of the window: the call's own time bound (a settings action's, a panelAction's, a screenEvent's) does not run while
   * the window is up, so a sign-in with 2-step verification can take its time. Once it closes the call has at least 10 seconds
   * to run the code that follows `open`.
   */
  timeoutMs?: number;
}

/** apiVersion 20: what `kino.visualBrowser.open` answers. */
interface KinoVisualBrowserResult {
  /** `"done"`: the person pressed Listo or your `doneWhen` was met. `"closed"`: they closed the window (or said No to the sheet). `"timeout"`: `timeoutMs` passed. */
  status: "done" | "closed" | "timeout";
  /** The window's last address, when `collect.finalUrl` was true and it is still on your hosts. */
  finalUrl?: string;
  /** The cookies asked for in `collect.cookies` (name to value), only with `"done"` and without `storeAs`. */
  cookies?: Record<string, string>;
  /** The localStorage values asked for in `collect.localStorage` (key to value; a key the page did not have is absent), only with `"done"`. */
  localStorage?: Record<string, string>;
  html?: string;
  /** With `storeAs`: true when Kino keeps the cookies for you (false when none of the named ones existed: nothing was stored). */
  stored?: boolean;
  /** With `storeAs`: the NAMES of the cookies Kino keeps, never their values. */
  storedNames?: string[];
  /** The user agent the window used, when you chose one (`userAgent`). */
  userAgent?: string;
}

/** apiVersion 6: `kino.browser.capture` options. */
interface KinoBrowserCaptureOptions {
  /** 1..25000 ms; default 18000. */
  timeoutMs?: number;
  /** Extra headers for the first page load only (a `Referer` an embed insists on). */
  headers?: Record<string, string>;
  /** A regular expression (case-insensitive, up to 500 characters) for what counts as the video request; default: m3u8, mpd, mp4, `master.txt`, `videoplayback`, `/hls/`. */
  match?: string;
  /** Default true: mute and start the page's player, click common play buttons, tap the middle. Off with `waitForCookie`. */
  autoplay?: boolean;
  /**
   * Kino 0.9.54 (check `kino.browser.captureAll` first; older Kino ignores it): collect EVERY request matching `match`
   * (or the default media pattern) or one of `alsoMatch`, deduplicated by URL, at most 20, until the page settles (the
   * first match was seen and nothing new matched for 1 s) or `timeoutMs`. The answer then has `requests`.
   */
  captureAll?: boolean;
  /** Kino 0.9.54, only with `captureAll`: 1..10 more patterns (up to 500 characters each, case-insensitive) whose requests are collected too, never held back from the page. */
  alsoMatch?: (string | RegExp)[];
  /**
   * Kino 0.9.54: a cookie name (an HTTP token, e.g. `"cf_clearance"`) the page must also hold for its current host.
   * Without `match` no request is needed: the page ends as soon as the cookie is there (a cookie-only page). Kino never
   * autoplays or taps a page that waits for a cookie. With `captureAll` it needs a `match`. A capture with
   * `waitForCookie` WAITS THROUGH an auto-clearing challenge (Cloudflare's managed check) instead of ending at once on
   * its human-check widget: it keeps polling for the cookie (and any matching media) until the cookie is there or the
   * timeout runs out, so a challenge that clears by itself lets the stream through. A real captcha that needs a person
   * never clears on its own, so the capture simply times out (a plain `kino.browser.capture` without `waitForCookie`
   * still ends at once with `blocked` on a human check).
   */
  waitForCookie?: string;
  /** Kino 0.9.54: a page that runs out of time answers what it had, with `timedOut: true`, instead of throwing `timeout`. */
  returnCookiesOnTimeout?: boolean;
}

/** apiVersion 6: what `kino.browser.capture` saw. */
interface KinoBrowserCapture {
  /** At most 8, manifests first. `headers` carries Referer, User-Agent and, when the request had them, Origin and Cookie. */
  media: { url: string; mime?: string; headers: Record<string, string> }[];
  /** `.vtt`/`.srt` requests the page made, at most 10. */
  subtitles: { url: string; lang?: string }[];
  /** The top page's last address. */
  finalUrl: string;
  /**
   * Kino 0.9.54, only when the call used `captureAll`, `waitForCookie` or `returnCookiesOnTimeout`: the matching requests
   * (at most 20) with the method and headers the page sent, the first match first. On a timeout answer without a match,
   * only `alsoMatch` hits (or none): check each URL against your own patterns.
   */
  requests?: { url: string; method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"; headers: Record<string, string> }[];
  /** Kino 0.9.54, same condition: the final page's cookies (at most 64, 16,384 characters in all, Cloudflare's `cf_*`/`__cf*` kept first). */
  cookies?: Record<string, string>;
  /** Kino 0.9.54, same condition: the hidden page's user agent (the one Cloudflare ties `cf_clearance` to). */
  userAgent?: string;
  /** Kino 0.9.54, same condition: true only for a `returnCookiesOnTimeout` page that ran out of time. */
  timedOut?: boolean;
}

/** apiVersion 6, `"browser": "pages"`: `kino.browser.page` options. */
interface KinoBrowserPageOptions {
  /**
   * 1..25000 ms; default 15000. Counts inside your call's own time limit; Kino cuts it to what is left of that limit
   * minus 1.5 s. Pass about 12000 in `search` (15 s for the whole call).
   */
  timeoutMs?: number;
  /**
   * A JavaScript regular expression (source string or RegExp, whose `m` and `s` flags are kept; matched
   * case-insensitively against the page's HTML, up to 500 characters): the page is returned only once it matches. Without it, as soon as the page is loaded and is no
   * longer the site's browser check page. Use it for pages that fill in their list with scripts.
   */
  waitFor?: string | RegExp;
}

/** apiVersion 6, `"browser": "pages"`: what `kino.browser.page` read. */
interface KinoBrowserPage {
  /** The doctype and the DOM's outerHTML (after the page's scripts ran), at most 2,000,000 characters. Feed it to `kino.html.select`. */
  html: string;
  /** The top page's last address (after redirects and the browser check). */
  finalUrl: string;
  /** The HTTP status of the top page's last load: 200 unless that load answered an error. */
  status: number;
  /** True when `html` was cut at 2,000,000 characters. */
  truncated: boolean;
}

/** `kino.cloudstream` (converted plugins only): one result of a CloudStream provider's search or main page. */
interface CsItem {
  name: string;
  url: string;
  type?: string;
  poster?: string;
  posterHeaders?: Record<string, string>;
  year?: number;
  quality?: string;
  provider?: string;
}

/** `kino.cloudstream` (converted plugins only): what a CloudStream provider's `load` says about a title. */
interface CsTitle {
  name: string;
  url: string;
  type?: string;
  plot?: string;
  poster?: string;
  background?: string;
  year?: number;
  tags?: string[];
  rating?: number;
  durationMin?: number;
  kind?: string;
}

/** `kino.cloudstream` (converted plugins only): one episode of a title; `data` is what `loadLinks` takes. */
interface CsEpisode {
  data: string;
  season?: number;
  episode?: number;
  name?: string;
  poster?: string;
  description?: string;
  date?: number;
  dubStatus?: string;
}

/** `kino.cloudstream` (converted plugins only): a playable link, already filtered (public https only) and ranked by Kino. */
interface CsLink {
  url: string;
  name: string;
  quality: number;
  linkType: "VIDEO" | "M3U8" | "DASH";
  headers: Record<string, string>;
}

/** apiVersion 14, capability `"ai"` (Task 8r): what `kino.ai.ask` takes (contract.json `kinoAi`). */
interface KinoAiAskOptions {
  /** The text to send: a non-empty string of at most 8192 UTF-8 bytes. It leaves the device: say so in your own UI. */
  prompt: string;
  /** Your instructions to the model, at most 2048 UTF-8 bytes. Kino adds no persona of its own. */
  system?: string;
  /** true ASKS the model for JSON only; the reply still comes back as the model wrote it, parseable or not. */
  json?: boolean;
  /** The reply is cut at this many characters: a whole number from 1 to 4096 (default 2048). */
  maxChars?: number;
}

/**
 * apiVersion 14, capability `"ai"`: what `kino.ai.ask` answers. Never thrown: a failure is `ok: false` with one of the codes;
 * `message` is Kino's English detail for you, never for the person. `model` is only the name of the model that answered.
 */
type KinoAiAnswer =
  | { ok: true; text: string; model: string }
  | { ok: false; error: "unavailable" | "rate_limited" | "too_large" | "timeout" | "refused"; message: string };

/** A notice for the Home bell (`kino.notifications.post`, apiVersion 15). */
interface KinoNotice {
  /** 1 to 64 of `A-Z a-z 0-9 . _ -`; the same id replaces an earlier notice of yours, unread again. */
  id: string;
  /** 1 to 80 characters, plain text, one line. */
  title: string;
  titleEn?: string;
  /** At most 160 characters, plain text, one line. */
  text?: string;
  textEn?: string;
  /**
   * Where a tap goes: your own screen at a route (`{ screen: { route?, args? } }`), or a title (`{ title: {...} }`,
   * `{ titleByIds: {...} }`, which open your screen's root for now). Anything else is dropped: the tap opens your screen.
   */
  go?: { screen: { route?: string; args?: Record<string, unknown> } } | { title: { ref: string; kind: string; id?: string; title?: string } } | { titleByIds: KinoScreenTitleByIds };
}

/**
 * One plugin a store offers (apiVersion 15, capability "pluginStore"). Kino keeps what fits the caps (contract.json `kinoStore`),
 * paints it with its own cards and re-checks everything at install. An entry with no `address` and no `stremio`, no valid `id`
 * or no `name` is dropped.
 */
interface StoreEntry {
  /** `owner/repo[/path][@ref]` or `url:https://.../kino-plugin.json`. Absent only for a `stremio` entry. */
  address?: string;
  /** The plugin's id (`^[a-z0-9][a-z0-9-]{1,39}$`). */
  id: string;
  /** 1 to 60 characters. */
  name: string;
  /** At most 300 characters. */
  description?: string;
  /** At most 4000 characters. */
  longDescription?: string;
  /** Any of `movies`, `series`, `anime`, `live`, `radio`, `subtitles`, `utilities`, `adult`. */
  categories?: string[];
  tags?: string[];
  /** An https URL. */
  icon?: string;
  /** Https URLs. */
  screenshots?: string[];
  version?: string;
  author?: string;
  /** Higher is more popular: the "popular" sort. */
  popularity?: number;
  /** When it last changed, in milliseconds since 1970: the "recent" sort. */
  updatedAt?: number;
  /** Honoured only from Kino's own built-in store; ignored from any other. */
  recommended?: boolean;
  /** A Stremio manifest URL, installed through Kino's Stremio flow (then `address` may be absent). */
  stremio?: string;
  /** Capabilities the plugin needs: Kino hides an entry this build cannot run. */
  requires?: string[];
  needsSetup?: boolean;
  /** A hint that the plugin is signed by its author (the card says "Firmado"); Kino re-checks at install. */
  signed?: boolean;
  /** A hint of the author key that signs it (64 lowercase hex); display only. */
  authorKey?: string;
}

/** `storeSync(arg)`: the argument (apiVersion 15, capability "pluginStore"). */
interface StoreSyncArg {
  /** `"schedule"`: the background refresh at the person's interval. `"reload"`: the person pressed reload. */
  reason: "schedule" | "reload";
  /** When this store last synced successfully, in milliseconds since 1970 (absent on the first sync). */
  since?: number;
  /** What you returned as `state` last time. */
  state?: Record<string, unknown>;
}

/** `storeSync(arg)`: the answer. */
interface StoreSyncAnswer {
  /** `true`: `entries` is the store's whole list and anything missing is removed. `false`: upserts, plus `removed`. */
  full: boolean;
  /** At most 5000 kept; the whole answer at most 4 MB of JSON. */
  entries: StoreEntry[];
  /** With `full: false`, the addresses that left the store. */
  removed?: string[];
  /** A small object (at most 16 KB of JSON) Kino keeps for you and hands back next time: a cursor, an etag, a date. */
  state?: Record<string, unknown>;
}

/** `storeList(arg)` of a live store (`"pluginStore": { "mode": "live" }`). */
interface StoreListArg {
  category?: string;
  sort: "popular" | "recent";
  cursor?: string;
}

/** `storeSearch(arg)` of a live store. Both live calls answer `{ entries, next? }` within 5 s, at most 20 a minute. */
interface StoreSearchArg {
  q: string;
  category?: string;
  cursor?: string;
}

/** What a handle of the `files` capability is (apiVersion 21): the kind a file has, from its mime type and then its extension. */
type KinoFileKind = "video" | "audio" | "book" | "image" | "subtitle" | "other";

/** A file the person picked (apiVersion 21). `id` is opaque: Kino keeps where the file is, you never see an address. */
interface KinoFile {
  id: string;
  name: string;
  /** Bytes. */
  size: number;
  mime: string;
  kind: KinoFileKind;
  /** True when the bytes were copied into your plugin's own store (`copy: true`); false: a reference to the original. */
  copied: boolean;
  /** Milliseconds since 1970 when the person picked it. */
  addedAt: number;
  /** The id of the folder it came from, for a file listed inside a picked folder. */
  folder?: string;
}

/** A folder the person picked (apiVersion 21): one grant for everything under it. */
interface KinoFileFolder {
  id: string;
  name: string;
  addedAt: number;
}

/** The error codes of `kino.files`: `unavailable` (no picker on this device, or no press), `not_allowed` (a pick from a call the person did not start), `busy`, `timeout`, `invalid_request`, `gone` (moved, deleted or the grant lost), `too_large`, `denied` (not your handle), `quota`. */
type KinoFilesErrorCode = "unavailable" | "not_allowed" | "busy" | "timeout" | "invalid_request" | "gone" | "too_large" | "denied" | "quota";

/** What you tell Kino about one element the person is part way through (apiVersion 22, capability "progress"). */
interface KinoProgressSet {
  /** The element: 1 to 128 characters of `A-Z a-z 0-9 . _ ~ -`, unique within your plugin (a chapter, a book, an episode). */
  id: string;
  /** How far along the element is as a whole, 0 to 1; you decide what "whole" is. */
  fraction: number;
  /** The element's title, for your own shelf (at most 200 characters). Optional. */
  title?: string;
  /** A short line about where the person is, at most 80 characters: "Cap. 87 · hoja 12 de 40". */
  label?: string;
  /** The same in English, at most 80 characters. */
  labelEn?: string;
  /** An image for your own shelf: an https address (the rule of a screen's Image) or a KinoImageRef of your imageSource capability. */
  poster?: string | KinoImageRef;
  /** Anything you need to come back to the place: any JSON value (a string, number, boolean, object or array), at most 1024 bytes once serialized. It is your own opaque data: Kino never reads it, it only hands it back as you set it (`get`, `list`). A `go.screen` route and args is the usual use. */
  resume?: unknown;
  /** True marks the element finished now. */
  done?: boolean;
  /** 0 to 1, default 0.9: Kino marks the element finished when `fraction` reaches this (unless you give `done`). */
  doneAt?: number;
}

/** What `kino.progress.get` answers for an element you have set. */
interface KinoProgressEntry {
  /** The element's id (set by `list`; `get` answers the same shape). */
  id: string;
  fraction: number;
  title?: string;
  poster?: string;
  label?: string;
  /** The English line you set with `labelEn`. */
  labelEn?: string;
  resume?: unknown;
  done: boolean;
  /** Milliseconds since 1970 of the last `set`. */
  updatedAtMs: number;
}

/** The options of `kino.progress.list`. */
interface KinoProgressListOptions {
  /** 1 to 100, default 50. */
  limit?: number;
  /** Only elements set at or after this time, milliseconds since 1970; a finite number >= 0. */
  sinceMs?: number;
}

/** The error codes of `kino.progress`: `not_allowed` (the plugin does not declare the capability, the call is in a scheduled job that runs for a profile other than the active one, or Kino could not keep it right now), `bad_request` (a bad id, fraction, label, poster or doneAt), `too_large` (the `resume` is over 1024 bytes). */
type KinoProgressErrorCode = "not_allowed" | "bad_request" | "too_large";

/** What `kino.coins.balance()` answers (apiVersion 16). */
interface KinoCoinsBalance {
  /** The person's Kino coins now. */
  balance: number;
  /** Coins earned by watching today (UTC). */
  earnedToday: number;
  /** The most a UTC day may earn (20). */
  capToday: number;
}

/** `kino.coins.give(gift)` (apiVersion 16): ONE coin. */
interface KinoCoinsGift {
  /** The recipient's coins account (1 to 128 characters), as your server names it (Kino Social: `coinsAccount`). */
  to: string;
  /** The post the coin is for (1 to 64 characters). */
  postId: string;
}

/** What `kino.coins.give` answers (apiVersion 16). */
interface KinoCoinsGiven {
  /** The person's balance left. */
  balance: number;
  /** The coins the post holds now. */
  postTotal: number;
}

/** `kino.identity.telegram(options?)` (apiVersion 15). */
interface KinoIdentityOptions {
  /** A nonce your server issued: 16 to 128 of `A-Z a-z 0-9 _ -`. With it, Kino signs and attests (see [KinoIdentity]). */
  challenge?: string;
}

/** What `kino.identity.telegram` answers (apiVersion 15). */
interface KinoIdentity {
  /**
   * A pseudonym of the person for YOUR plugin: the first 32 lowercase hex characters of SHA-256 over UTF-8
   * `"kino-identity-v1\n" + pluginId + "\n" + telegramAccountId`. Stable for your plugin on every install and device of the
   * person (install-independent), different for every plugin. Never the Telegram id nor the username.
   */
  id: string;
  /**
   * The gate token Kino's bot signed for this device (`base64url(payload).base64url(Ed25519 signature)`). It still carries the
   * Telegram account, so your server can verify it with the bot's public key; a per-audience token from the bot is the
   * planned fix. A credential: never log or show it. Present only for a plugin signed with one of contract.json
   * `kinoIdentity.tokenAuthors` (`07DA-B67F-2ACF-B4D3`, Kino's own; `E04E-EA25-1A34-290E`, the xuper-plugin author's, from
   * Kino 0.9.88); any other author gets the `id` and, with a challenge, the attestation, but never the token.
   */
  token?: string;
  /** With a challenge: the public key (X.509 SubjectPublicKeyInfo DER, base64url without padding) of Kino's key for your plugin on this install. */
  deviceKey?: string;
  /**
   * With a challenge: SHA256withECDSA (DER, base64url without padding) over UTF-8
   * `"kino-identity-v2\n" + pluginId + "\n" + challenge + "\n" + author + "\n" + codeHash`.
   */
  signature?: string;
  /**
   * With a challenge: the fingerprint of the author key Kino verified and pinned at install (`XXXX-XXXX-XXXX-XXXX`, upper-case
   * hex), `""` for an unsigned plugin. From Kino's record, never your code: your server can require its own fingerprint so a
   * modified copy cannot log in.
   */
  author?: string;
  /** With a challenge: lowercase hex SHA-256 of the installed entry file Kino runs. */
  codeHash?: string;
}

/**
 * apiVersion 14, capability `"library"`: one title the person watched or saved, as `kino.library` gives it (contract.json
 * `kinoLibrary`). Nothing else ever comes: no stream, no plugin ref, no Kino id, no profile.
 */
interface KinoLibraryEntry {
  /** The title's name as Kino shows it (TMDB's when Kino identified it), at most 200 characters. */
  title: string;
  /** Only when Kino knows it (a saved title's card year); usually absent on a watched one. */
  year?: number;
  kind: "movie" | "series";
  /** Each only when Kino knows it; may be empty. */
  ids: { tmdb?: number; imdb?: string };
  /** `watched` only: how far the most recent playback of this title went, 0..1 in steps of 0.01 (1 when finished). */
  progress?: number;
  /** `watched` only: when it was last played, rounded down to the day (UTC midnight, ms since the epoch). */
  watchedAtMs?: number;
  /**
   * `watched` series only (contract.json `additiveFromApp["kino.library.episode"]`): the season of the latest chapter played,
   * only when its source numbered it. Absent on a movie and on an older Kino: feature-detect by its presence.
   */
  season?: number;
  /** `watched` series only: the number of the latest chapter played (with [season]), only when its source numbered it. */
  episode?: number;
}

/** `kino.library.watched`'s options: `limit` 1..100 (default 50; above 100 gives 100), `kind` filters, `sinceMs` keeps titles played on that day (UTC) or later: it is rounded down to the day, like `watchedAtMs`. A number that is not finite is `bad_request`. */
interface KinoLibraryWatchedOptions { limit?: number; kind?: "movie" | "series"; sinceMs?: number }

/** `kino.library.saved`'s options: `limit` 1..100 (default 50), `kind` filters. */
interface KinoLibrarySavedOptions { limit?: number; kind?: "movie" | "series" }

/** `kino.library.stats`'s only option: `month` as "yyyy-mm" (a real month); the current month when left out. */
interface KinoLibraryStatsOptions { month?: string }

/** One title of [KinoLibraryStats.top]; never a live channel. */
interface KinoLibraryStatsTitle {
  title: string;
  /** Only when Kino holds it. */
  year?: number;
  kind: "movie" | "series";
  /** Each only when Kino knows it; may be empty. */
  ids: { tmdb?: number; imdb?: string };
  /** What Kino already holds for the item (no network call): an https image address, only when it has one. */
  poster?: string;
  /** Only when Kino holds genres for the item. */
  genres?: string[];
  /** Seconds watched in the month, every device summed. */
  seconds: number;
}

/**
 * What `kino.library.stats` answers for a month (contract.json `kinoLibrary.stats`). 18+ is out of every number: a title known to
 * be 18+ at read time leaves the totals and `top`; a title Kino cannot place now (its plugin is gone) stays in the totals but not in
 * `top`. Live channels are in the totals and never named.
 */
interface KinoLibraryStats {
  /** "yyyy-mm". */
  month: string;
  /** True when part of the month comes from the play history, not the counter (a month before it existed, or the month of release). */
  estimated: boolean;
  seconds: number;
  secondsByKind: { movie: number; series: number; live: number };
  /** By the local hour: morning 05-12, afternoon 12-18, night 18-23, lateNight 23-05. Null for a month with no counted time. */
  secondsByBand: { morning: number; afternoon: number; night: number; lateNight: number } | null;
  /** Distinct movies and series (live channels are not titles). */
  titles: number;
  /** Distinct chapters of series played in the month. */
  episodes: number;
  activeDays: number;
  longestStreakDays: number;
  /** At most 20, most seconds first. */
  top: KinoLibraryStatsTitle[];
}

/** What `kino.library` throws (contract.json `kinoLibrary.errorCodes`). */
type KinoLibraryErrorCode = "permission_denied" | "rate_limited" | "bad_request";

/** apiVersion 14, `kino.room.open`'s options. */
interface KinoRoomOpenOptions {
  /** Minutes the room lives, 10..240 (default 120). The endpoint and its internet route close when it is over. */
  ttlMin?: number;
  /** Members including you (the host), 2..8 (default 6). */
  max?: number;
  /** Your name as the guests see it, at most 40 characters (control and direction characters removed). */
  name?: string;
  /**
   * Task 8w: a shorter numeric code, 4..12 digits (default 12; anything else is `bad_request`). A short code (a friends'
   * Watch Party) keeps strangers out only because the words cannot be guessed and the room closes itself after 30 wrong codes;
   * whoever captures the traffic and knows the words (the tunnel provider) recovers a 4-digit code offline in milliseconds,
   * so such a room is NOT private from the provider. The default 12 digits makes that expensive, not impossible.
   */
  codeDigits?: number;
  /**
   * Open ANOTHER door to a room you are in (a backup endpoint with its own words): the room's code. Refused
   * (`permission_denied`) unless this plugin is a member of a room with that code right now, or opened it itself. Its
   * expiry is capped at the room's.
   */
  code?: string;
}

/** What `kino.room.open` answers. Show `words` and `code` to the person (or send `words` to the members in a message). Never a URL. */
interface KinoRoomOpened {
  /** The room's secret: 12 digits, or the `codeDigits` you asked for. Show it grouped (`1234 5678 9012`); spaces and hyphens are ignored on `join`. */
  code: string;
  /** The endpoint's public words (`brave-river-cat-moon`). Anyone may see them; the code is what lets people in. */
  words: string;
  expiresAtMs: number;
}

/** apiVersion 14, `kino.room.join`'s options: the words and code the host's person shared, and the name the others see (at most 24 characters). */
interface KinoRoomJoinOptions { words: string; code: string; name?: string }

/** What `kino.room.join` answers. Keep `handle`: it names this session in `send`, `inbox`, `members` and `close`. */
interface KinoRoomJoined {
  handle: string;
  memberId: string;
  host: { name: string };
  expiresAtMs: number;
}

/** `"hosted"` (the room this device hosts) or a `handle` from `join`. Absent: the first joined session, else the hosted one. */
type KinoRoomSession = string;

/** `kino.room.send`'s options. The host may write to one `memberId` or everyone (absent or `"all"`); a guest to the host (absent or `"host"`) or `"all"`. */
interface KinoRoomSendOptions { to?: string; session?: KinoRoomSession }

/** `kino.room.inbox`'s options: events after `since` (pass the last answer's `last`), at most `limit` (1..50, default 50). */
interface KinoRoomInboxOptions { since?: number; limit?: number; session?: KinoRoomSession }

/** One mailbox event: a message, someone joining or leaving, or the room closing. `seq` only grows. */
interface KinoRoomEvent {
  seq: number;
  /** A `memberId`, or `"host"`. */
  from: string;
  kind: "msg" | "join" | "leave" | "closed";
  /** `msg` only: the object the sender passed to `send`, as Kino re-serialised it. Never executed by Kino; treat it as untrusted data. */
  payload?: object;
  /** `join` only: the member's display name. */
  name?: string;
}

/** What `kino.room.inbox` answers. `reachable` is false when a guest's last poll of its host got no answer (your failover cue). */
interface KinoRoomInbox { events: KinoRoomEvent[]; last: number; more: boolean; reachable: boolean }

/** A room member: never an address, only the id Kino gave it, its chosen name, and whether it is the host. */
interface KinoRoomMember { memberId: string; name: string; host: boolean }

/** What `kino.room.state` answers: this plugin's sessions on this device. */
interface KinoRoomState {
  role: "host" | "guest" | "none";
  joined: { handle: string; memberId: string; host: { name: string }; expiresAtMs: number; reachable: boolean }[];
  hosted: { code: string; words: string; expiresAtMs: number; members: number } | null;
}

/** What `kino.room` throws (contract.json `kinoRoom.errorCodes`); `room_unreachable` and the room refusals carry Kino's own `userMessage`. */
type KinoRoomErrorCode = "room_denied" | "room_closed" | "room_full" | "room_unreachable" | "room_busy" | "rate_limited" | "permission_denied" | "bad_request";

/** apiVersion 13, `kino.ws.open`: a connected WebSocket carrying binary messages. */
interface KinoWebSocket {
  /** Sends one binary message of at most 786000 bytes (`"too_large"` above). `await` it: it rejects with code `"closed"` when the socket is no longer open. */
  send(data: Uint8Array): Promise<void>;
  /**
   * Sends one binary message given as a string in `encoding`: `"hex"` (an even number of digits, either case) or `"base64"`
   * (standard alphabet, padded, no whitespace). Kino decodes it natively, so no JavaScript loop touches the bytes: for a
   * binary protocol whose bytes already live as hex in your code (`kino.crypto` results, a packet you built), this is the
   * fast path. The 786000-byte cap is on the decoded bytes (`"too_large"`); a string that is not exactly that encoding
   * rejects with `"invalid_request"`, as does an `encoding` other than these two.
   * @example
   * await ws.send("efefefef", { encoding: "hex" });
   * await ws.send(kino.crypto.aesIge("encrypt", key, iv, plain, { keyEncoding: "hex", ivEncoding: "hex", inputEncoding: "hex", outputEncoding: "hex" }), { encoding: "hex" });
   */
  send(data: string, options: { encoding: "hex" | "base64" }): Promise<void>;
  /**
   * Waits up to `timeoutMs` (default 30000, at most 60000) for the next message: resolves with it, or with null when none
   * came in time. Rejects with code `"closed"` once the socket is closed and nothing is left queued (`"limit"` when it was
   * closed for holding more than 8 MiB of unread messages).
   */
  recv(timeoutMs?: number): Promise<Uint8Array | null>;
  /**
   * As `recv(timeoutMs)`, but the message comes as a string in `encoding`, `"hex"` (lower case) or `"base64"` (padded),
   * encoded natively by Kino. Building a `Uint8Array` costs a JavaScript pass over every byte (QuickJS interprets each
   * iteration); for anything big prefer an encoded frame and hand it on as it is, e.g. to `kino.crypto` with the same
   * `inputEncoding`. Rejects with `"invalid_request"` for an `encoding` other than these two, before waiting.
   * @example
   * const hex = await ws.recv(10000, { encoding: "hex" });   // "0a1b..." (2 characters per byte), or null
   */
  recv(timeoutMs: number | undefined, options: { encoding: "hex" | "base64" }): Promise<string | null>;
  /** Closes the socket; later calls reject with `"closed"`. Closing twice is harmless. */
  close(): Promise<void>;
}

/**
 * apiVersion 13, `kino.catalog`: one item as you give it to `upsert`. Only these four fields are kept; anything else is
 * dropped before it reaches Kino.
 */
interface KinoCatalogUpsertItem {
  /**
   * Your own key for the item (a message id, a video id, a URL), 1 to 128 characters (longer is `"too_large"`, empty or not a
   * string is `"invalid_request"`). Upserting an id that is already there REPLACES that item whole (title, sort and data).
   */
  id: string;
  /**
   * What `search` matches and what the "title" order sorts by: at most 300 characters (longer is `"too_large"`). Kino keeps
   * a copy lower-cased and without accents for the search ("Película" is found by "pelicula", "PELICULA" or "película").
   */
  title: string;
  /**
   * A whole number for the "newest" (descending) and "oldest" (ascending) orders, for example a date in ms or a message id.
   * Default 0. Must be a safe integer (at most 2^53 - 1 in size); a fraction, `NaN` or `Infinity` is `"invalid_request"`.
   */
  sort?: number;
  /**
   * Small display fields you want back with the item (a poster URL, a duration, a file reference), a plain object whose
   * JSON is at most 4,096 bytes in UTF-8 (`"too_large"` above; an array, a string or a number is `"invalid_request"`).
   * Not searched. Not a place for blobs or credentials.
   */
  data?: Record<string, unknown> | null;
}

/** apiVersion 13, `kino.catalog`: one stored item as `search` and `get` answer it. */
interface KinoCatalogItem {
  id: string;
  title: string;
  /** 0 when you gave none. */
  sort: number;
  /** The object you stored, parsed again; null when you gave none. */
  data: Record<string, unknown> | null;
}

/** apiVersion 13, `kino.catalog.search`'s options. Every field is optional; anything else is dropped. */
interface KinoCatalogSearchOptions {
  /**
   * Words to find, at most 256 characters (`"too_large"` above). Split on whitespace; EVERY word must appear somewhere in
   * the title (AND, any order, as a substring: "gat roj" finds "Gato rojo"), ignoring case, accents and control characters
   * other than whitespace (a NUL, an escape code). `%`, `_` and `\`
   * are plain characters, never wildcards. Empty, blank or absent lists everything.
   */
  q?: string;
  /** Items per page: default 50, at most 100 (`"too_large"` above, `"invalid_request"` below 1, for a fraction, `NaN` or `Infinity`). */
  limit?: number;
  /** Items to skip: default 0, at most 1,000,000 (`"too_large"` above, `"invalid_request"` for a negative, fractional or non-finite number). */
  offset?: number;
  /**
   * "newest" (default): `sort` descending, then `id`; "oldest": `sort` ascending, then `id`; "title": the title without case
   * or accents, then the title as written, then `id`. Ties are always broken by `id`, so paging is stable.
   */
  order?: "newest" | "oldest" | "title";
}

/** apiVersion 13, `kino.catalog.search`'s answer: one page and the count of every match. */
interface KinoCatalogPage {
  /** At most `limit` items, in the order asked. */
  items: KinoCatalogItem[];
  /** How many items match `q` in all (not just this page): compare it with `offset + items.length` to know if there is more. */
  total: number;
}

declare namespace kino {
  const apiVersion: number;
  /** Kino's version name, for example "0.9.56" ("sdk" in the Node kit). */
  const appVersion: string;
  /**
   * The language Kino speaks now, as a tag: "es-CO" or "en-US" (`kino.lang.slice(0, 2)` for the bare "es"/"en"). It follows
   * the person's choice in Ajustes ▸ App ▸ Idioma: on a change Kino closes the plugin's runtime and the next call opens a
   * new one with the new value (a `sign()` lane keeps the old one), so read it per call, not into a long-lived cache.
   */
  const lang: string;
  /**
   * Kino 0.9.55+: the UI Kino shows on this device, `"tv"` (remote control, ten-foot screen) or `"phone"` (touch; a
   * tablet gets whatever Kino shows it, usually `"phone"`). Same value for every apiVersion and every call while Kino
   * runs; no permission, it says nothing about the person. `undefined` on an older Kino. The Node kit says `"phone"`
   * unless `run.mjs --device tv` or `KINO_DEVICE=tv`.
   */
  const device: "tv" | "phone" | undefined;
  /**
   * Kino 0.9.55+: `true` when THIS install's `kino.fetch` may reach any public host -- the manifest declares
   * `"fetchHosts": "any"`, the plugin qualifies (apiVersion 9 or later, or converted from a Nuvio scraper) and the
   * person approved its red consent line. `false` otherwise; `undefined` on an older Kino (keep your own fallback).
   */
  const fetchAnyHost: boolean | undefined;
  /**
   * Your plugin's FEATURE apiVersion on this Kino: your manifest's `apiVersion`, or the highest key of your
   * `enhancements` this Kino applied, whichever is higher. A feature gated on it (such as `clockLive`, apiVersion 27)
   * is on exactly when this is high enough, so you can keep a lower base for older Kino and still use it here.
   * `undefined` on a Kino before this field: such a Kino reads those features from your base apiVersion only.
   */
  const pluginApiVersion: number | undefined;
  /**
   * apiVersion 17: whether Kino's own row of one of the plugin's jobs is on, so a screen knows whether to ask (`enableJob`). Only
   * inside `screen` and `screenEvent`; anywhere else, a job included, it throws `not_allowed`. Undefined below apiVersion 17.
   */
  function jobOn(jobId: string): boolean;

  /**
   * Only to the manifest's hosts over https (http only on a host declared `insecureHttp`), or to the person's own server as typed.
   * With `fetchAnyHost` true, also any PUBLIC host over https on port 443, at a public IPv4 address or a dotted name (never
   * the home network, never a single-label name; a sealed secret still only goes to the manifest's own hosts over https).
   * Those requests spend a budget kept for the whole app: at most 60 a minute per site and 600 every 10 minutes per plugin
   * (250 / 2,500 for a converted Nuvio scraper), then `rate_limited`; declared hosts never spend it (declare your main
   * sites). From Kino 0.9.55; a hidden page's start address and a capture's top-level navigations to a host reachable
   * only through the grant follow the same https / port 443 / dotted-name rule (declared hosts keep theirs); its
   * subresources do not.
   * Never throws for a non-2xx status.
   */
  function fetch(url: string, options?: KinoFetchOptions): Promise<KinoResponse>;

  /**
   * `throw kino.error("not_found", "…")`: the app words the message; yours is a detail of at most 200 characters.
   * `throw kino.error("not_found", "…", { userMessage: "Este capítulo ya no está disponible." })`: your own sentence
   * for the person, shown instead of Kino's line when it is safe (see `KinoErrorOptions`).
   */
  function error(code: KinoErrorCode, message?: string, options?: KinoErrorOptions): KinoError;

  /** 0..5000 ms, counts inside the call's own timeout. */
  function sleep(ms: number): Promise<void>;

  /**
   * Kino 0.9.53 (no new apiVersion: absent on older Kino, so check `typeof kino.meta === "function"` first). Asks Kino about
   * a title and answers what it knows, without your plugin ever touching a TMDB key: Kino's own TMDB lookup (its app
   * feature, the one its info page uses), AniList for an anime, then the person's installed `meta` plugins (never yours,
   * and none at all when called from your own `meta` export). Null when nobody knows the title (never an error).
   * At most 30 calls a minute per plugin (`rate_limited`); 8 s at most, inside your call's own time limit; cached 30 min.
   * Throws `invalid_request` (a bad query), `rate_limited`, `not_allowed` (from `sign()`).
   */
  function meta(query: KinoMetaRequest | KinoMetaTitleRequest): Promise<KinoMetaAnswer | null>;
  namespace meta {
    /** Kino 0.9.55, apiVersion 9: true when `kino.meta` takes `{ type, title, year? }` (KinoMetaTitleRequest); absent before. */
    const byTitle: true | undefined;
  }

  /**
   * Kino 0.9.53 (no new apiVersion: check `typeof kino.tmdb === "function"` first). A GET to TMDB's v3 API
   * (`https://api.themoviedb.org/3` + `path`) with no key in your plugin. Kino's own TMDB key goes first, behind Kino's
   * TMDB cache, a shared in-flight request and its own limits (at most 20 calls per 10 s per plugin and 60 per 10 s for
   * all plugins on Kino's key). Only when Kino's key fails (TMDB answers 401/403/429 for it, or one of those limits is
   * spent) does the same request go again with the PERSON'S key: the one they typed in Ajustes ("Tu llave de TMDB",
   * optional), else the one they configured in an installed Stremio addon (once they agree). With neither, a cached copy
   * up to 7 days old, else `rate_limited`. A key your plugin keeps in its own settings is never used. Your plugin never
   * sees any key and needs no `hosts` entry for TMDB. `path` starts with /discover, /trending, /search, /movie, /tv,
   * /find, /genre, /configuration, /person or /collection, without the version and without a query string; `params` (at
   * most 20; never `api_key` or a session) become the query. Answers the parsed JSON body (a cached copy when TMDB is down
   * or unreachable). At most 40 calls per 10 s per plugin whichever key; bodies up to 2 MiB; cached 10 min in memory by
   * path and params, and on disk with Kino's TMDB cache. Throws `no_tmdb_key` (only on a Kino build without a key of its
   * own and a person without one: `e.userMessage` is Kino's sentence telling the person what to do), `invalid_request`,
   * `rate_limited`, `not_found`, `too_large`, `timeout`, `network`, `unavailable`, `not_allowed` (from `sign()`).
   */
  function tmdb(path: string, params?: Record<string, string | number | boolean>): Promise<any>;

  /**
   * Kino 0.9.84, no new apiVersion (feature-detect with `typeof kino.image === "object"`): `thumbnail(url, { maxWidth?, maxBytes? })`
   * downloads an `https` picture under THIS plugin's own `kino.fetch` rules (its hosts, https only, never the home network, its
   * request budget; capped at 5 MB) and answers a small JPEG as `"data:image/jpeg;base64,…"`. `maxWidth` 32 to 400 (default 200),
   * `maxBytes` 2048 to 32768 (default 16384). At most 20 calls a minute. Throws `bad_request`, `host_not_allowed`, `not_found`,
   * `network`, `timeout`, `too_large`, `not_image`, `rate_limited`, `not_allowed` (from `sign()`). Under the Node kit it only
   * passes a JPEG/PNG that is already small enough through (else `kit_unsupported`); `KINO_THUMBNAIL_FIXTURE=<file>` answers a file.
   */
  namespace image {
    function thumbnail(url: string, options?: { maxWidth?: number; maxBytes?: number }): Promise<string>;
  }

  /**
   * Kino 0.9.71, apiVersion 11, needs `"nuvio"` in the manifest's `capabilities` (a declarative capability; the consent sheet says "Instala y usa
   * scrapers de Nuvio del repositorio que indica para buscar enlaces"; check `typeof kino.nuvio === "object"` first). EXPERIMENT. You name
   * your Nuvio repositories in the manifest's `nuvioRepos` (1 to 4, `owner/repo`; the capability needs it) and `kino.nuvio` refuses any other (`not_allowed`).
   * The scrapers you install are yours: Kino does not list them among the person's plugins, counts them under yours and removes them with it. The app installs the scrapers you ask for exactly as the importer does for a person (same reader, same conversion, same
   * torrent filter: a P2P-only scraper is listed as not compatible and never installed), with nothing for the person to do, then asks each for a
   * title and hands you what it found, to sort, merge and label as you like. Nothing is run or downloaded by your plugin: every scraper keeps
   * the importer's own hosts, request budget and 75 s limit, and a plugin that declares `nuvio` gets the same 75 s for its own `resolve`.
   * Only inside one of your functions. At most 20 calls a minute; up to 12 scrapers per `use` or `streams` call (`streams` asks 4 at a time).
   * Throws `invalid_request` (a bad query), `rate_limited`, `unavailable` (the repository cannot be read), `not_allowed` (the capability is
   * not declared, or from `sign()`).
   */
  namespace nuvio {
    /** What `repo` offers, read by the importer: each scraper's id, name, types (`movie`, `tv`, `anime`) and languages, whether it is `compatible` and whether it is already `installed`. */
    function available(query: { repo: string }): Promise<KinoNuvioOffered[]>;
    /**
     * Makes sure each scraper in `scrapers` (at most 12) is installed, installing the missing ones one after another (up to 45 s each). A scraper that
     * cannot be installed is in `failed` (`refused` for a torrent-based one, `not_found`, `timeout`, `failed`) and the rest go on.
     */
    function use(query: { repo: string; scrapers: string[] }): Promise<{ ready: string[]; failed: { id: string; code: string; message: string }[] }>;
    /** The scrapers of `repo` that are installed and on right now (18+ ones are never listed), in install order. */
    function scrapers(query: KinoNuvioScrapersRequest): Promise<KinoNuvioScraper[]>;
    /**
     * One answer per scraper asked, in install order. A scraper that fails or takes longer than 60 s is an entry with `ok: false`, never a
     * throw, so one slow source hides nothing. `truncated` is true when more than 12 scrapers were installed and only the first 12 were asked.
     */
    function streams(query: KinoNuvioStreamsRequest): Promise<KinoNuvioStreamsAnswer>;
  }

  /**
   * apiVersion 14, needs `"library"` in the manifest's `capabilities` (declarative, no export). What the person watched and saved
   * in Kino, read-only, from the profile in use: never another profile, never an 18+ title (even with the 18+ code unlocked),
   * never a stream URL or another plugin's ref. Newest first, one entry per title (a series' chapters fold into one).
   * The person approves it at install, and again on the update that adds it, on a RED consent line: "Podrá leer lo que has
   * visto y guardado en Kino, cuánto lo ves y a qué hora, y enviarlo a sus servicios" / "Can read what you have watched and saved in
   * Kino, how much and at what time of day, and send it to its services", next to your declared hosts. They can switch it off later in your tab in Ajustes; every call then rejects
   * with `permission_denied` until they switch it back on. Only inside a call the person started (`screen`, `screenEvent`,
   * `home`, `section`, `search`); any other call (background, prewarm, sync, `resolve`) rejects with `permission_denied`.
   * At most 30 calls a minute per plugin (both functions together), then `rate_limited`; a wrong option is `bad_request`. A
   * screen's timer ticks (`screen.every`) count as the person's use while the screen is in front. A call Kino has abandoned
   * (timed out, or its screen closed) gets `permission_denied`. If you build Home rows from these titles, Kino caches that answer
   * like any Home.
   * Kino keeps nothing for you: store only what you need, and only in your own storage. Present on every apiVersion 14 runtime:
   * feature-detect with `typeof kino.library === "object"` (the Node kit answers from `KINO_LIBRARY_FIXTURE`).
   */
  namespace library {
    /** The titles played, most recent first. */
    function watched(options?: KinoLibraryWatchedOptions): Promise<KinoLibraryEntry[]>;
    /** The titles saved (the heart on a title's page), most recently saved first: no `progress` and no `watchedAtMs`. */
    function saved(options?: KinoLibrarySavedOptions): Promise<KinoLibraryEntry[]>;
    /**
     * apiVersion 17 (Tu mes en Kino), same capability and switch: one month's aggregates of the profile in use, every device of the
     * person summed. Only on a plugin that declares apiVersion 17 or later (feature-detect with `typeof kino.library.stats ===
     * "function"`); the same rate limit as `watched` and `saved`; a `month` that is not "yyyy-mm" (or any other option) is
     * `bad_request`. Never 18+; nothing finer than the month (no per-day series, no timestamps).
     */
    function stats(options?: KinoLibraryStatsOptions): Promise<KinoLibraryStats>;
  }

  /**
   * apiVersion 14, capability `room` (Task 8l): a short-lived mailbox hosted on the person's OWN device and reached from the
   * Internet through the same Cloudflare quick tunnel Kino opens for "Recibir configuración". Kino is only the transport: who
   * leads, what a message means and failover are yours. The person approves it at install, and again on the update that adds
   * it, on a RED consent line: "Podrá abrir una sala a la que se entra por internet a través de este aparato, y enviar los
   * mensajes de la sala a quienes entren" / "Can open a room that people reach over the Internet through this device, and send
   * the room's messages to whoever joins". They can switch it off in your tab in Ajustes ("Dejar que abra salas por internet"),
   * which closes your rooms at once; every call then rejects with `permission_denied`.
   *
   * - `open` and `join` only from the person's own action: a `screenEvent` or a `panelAction` (never a screen timer tick or a
   *   panel refresh). `send`, `inbox` and `members` from an open screen or panel (`screen`, `screenEvent`, `panel`,
   *   `panelAction`, `playerEvent`; ticks and `refreshMs` included), with Kino in front. Never a background call.
   * - Poll `inbox` from your panel's `refreshMs` (2000 or more) or a screen's `every`; nothing is pushed into a closed runtime.
   * - A payload is a JSON object of at most 8192 UTF-8 bytes and 4 levels; at most 5 messages a second, 100 and 256 KB a
   *   minute per member. Kino never executes or stores it.
   * - A device holds at most two joined sessions and one hosted room, and one plugin at most two of those three (`room_busy`);
   *   a `join` with the code of a session you
   *   are in replaces it (moving to a backup endpoint). Publish a backup's `words` a few seconds after `open` (a fresh name
   *   takes a moment to resolve; `join` retries for 20 s).
   * - The room closes on `close`, at its TTL, if your plugin is removed, disabled or switched off, or if Kino stays in the
   *   background 30 minutes (while your room is hosted, Android shows Kino's notification «Sala abierta · N personas» with
   *   «Cerrar sala» and keeps it alive meanwhile). Guests silent for 2 minutes are dropped (`leave`).
   * - Five wrong codes lock new joins for 60 s, then 120 s, ... (`rate_limited`, with Kino's `userMessage`); members already in
   *   keep going. After 30 wrong codes in all the room closes itself: Kino tells the person and your next calls get
   *   `room_closed`.
   * - The code keeps out whoever does not have it (guessing is online only); it does not protect against the tunnel provider
   *   (Cloudflare) targeting a room. Keep a room's messages low-sensitivity (a chat, playback positions).
   * - While this device hosts your room, Kino shows it in your tab in Ajustes with a button that closes it.
   *
   * Present on every apiVersion 14 runtime: feature-detect with `typeof kino.room === "object"` (the Node kit runs an
   * in-memory room with two simulated members).
   */
  namespace room {
    function open(options?: KinoRoomOpenOptions): Promise<KinoRoomOpened>;
    function join(options: KinoRoomJoinOptions): Promise<KinoRoomJoined>;
    function send(payload: object, options?: KinoRoomSendOptions): Promise<void>;
    function inbox(options?: KinoRoomInboxOptions): Promise<KinoRoomInbox>;
    function members(options?: { session?: KinoRoomSession }): Promise<KinoRoomMember[]>;
    function close(options?: { session?: KinoRoomSession }): Promise<void>;
    function state(): Promise<KinoRoomState>;
  }

  /**
   * apiVersion 14, capability `ai` (Task 8r, declarative, never on its own): one short, one-shot ask to Kino's text AI (Kilo's
   * free models, the same fixed destination Kino's own assistant uses; no key, no server of yours or Kino's). No conversation
   * memory, no streaming, no tools, no images, no files; Kino keeps nothing and logs only sizes. The person approves it at install,
   * and again on the update that adds it, on a RED consent line: "Podrá enviar texto a un servicio de IA de terceros (Kilo) para
   * que lo resuma o clasifique; lo que envíe sale de tu aparato" / "Can send text to a third-party AI service (Kilo) to have it
   * summarized or classified; what it sends leaves your device". They can switch it off in your tab in Ajustes: every ask is then
   * `refused`. Only from the person's own press (a settings `action`, a `panelAction`, a `screenEvent` tap or submit; never a
   * screen's open, a timer tick, a load-more, a `playerEvent`, Home or search) or from your scheduled `job`, where each ask is one
   * of the run's requests. At most 10 asks in any 60 s and 100 a day per plugin, one at a time, and 300 a day and 2 at once for
   * every plugin of the device together (`rate_limited`), 20 s each
   * (`timeout`). Ask once per screen event and batch items into one prompt: the screen's own 60 s still bounds the event.
   * `unavailable`: no model could answer now; keep a fallback.
   *
   * The reply is UNTRUSTED DATA: the model read whatever you sent (titles from the web, the person's words) and can be steered by
   * it (prompt injection). Validate every field against what you sent, drop what you did not ask for, never execute it, never
   * follow instructions found in it, never open a URL from it unchecked. Present on every apiVersion 14 runtime: feature-detect
   * with `typeof kino.ai === "object"` (the Node kit answers canned text: `KINO_AI_REPLY`, `KINO_AI_ERROR`, `KINO_AI_REVOKED=1`).
   */
  namespace ai {
    function ask(options: KinoAiAskOptions): Promise<KinoAiAnswer>;
  }

  /**
   * apiVersion 15, capability "identity" (a red consent line, approved by the person, revocable in Ajustes): who the person is,
   * for your server, without a login. Only inside a call the person started from `screen`, `screenEvent` or `panelAction`
   * (never a timer tick, a job, Home or search), 10 a minute. Rejects with a KinoError whose `code` is `permission_denied`,
   * `not_available` (this device has no validation with the Telegram account), `rate_limited` or `bad_request`. Present on every
   * apiVersion 15 runtime: feature-detect with `typeof kino.identity === "object"` (the Node kit answers a fake account:
   * `KINO_IDENTITY_TG`, `KINO_IDENTITY_TOKEN`, `KINO_IDENTITY_AUTHOR`, `KINO_IDENTITY_REVOKED=1`).
   */
  namespace identity {
    function telegram(options?: KinoIdentityOptions): Promise<KinoIdentity>;
  }

  /**
   * apiVersion 28, capability "vault" (requires "identity", so it rides on identity's red consent line): read your plugin's OWN
   * sealed secret from the Kino secrets vault with `kino.vault.get()`. Kino runs the whole exchange from inside — it mints a
   * challenge, attests your plugin exactly as `kino.identity` does (a per-plugin pseudonym, a device-key signature, your author
   * fingerprint and code hash, and the gate token for a trusted author so the vault can verify group membership live) and reads
   * the secret the vault resolves for YOUR `(pluginId, author)`. You never see the vault's address, the challenge nor the scope
   * the vault resolves by, so you can only ever read your own secret. The answer is whatever JSON you registered as the secret.
   * Only inside a call the person started from `screen`, `screenEvent` or `panelAction` (never a timer tick, a job, Home or
   * search), 6 a minute. Rejects with a KinoError whose `code` is `permission_denied`, `not_member` (not in the Kino group, or
   * the plugin's scope does not match), `not_found` (no secret registered for this plugin), `rate_limited`, `unavailable` or
   * `not_available` (this device has no Telegram validation, or the secrets service could not be reached). Present on every
   * apiVersion 28 runtime: feature-detect with `typeof kino.vault === "object"`.
   */
  namespace vault {
    function get(): Promise<any>;
  }

  /**
   * apiVersion 15, capability "notifications" (a plain consent line, approved by the person, revocable in Ajustes): short notices
   * in the Home bell, from your `screen`, `screenEvent` or scheduled `job`. 20 posts an hour, 30 kept, 30 days; the same `id`
   * replaces a notice (unread again). Rejects with a KinoError whose `code` is `permission_denied`, `rate_limited` or
   * `bad_request`. Not synced: each device keeps its own. Feature-detect with `typeof kino.notifications === "object"`; the kit
   * keeps them in `<folder>/.kino-notices.json` (`node sdk/run.mjs <folder> notifications`).
   */
  namespace notifications {
    function post(notice: KinoNotice): Promise<void>;
    /** One notice of yours by id, or all of them. */
    function clear(id?: string): Promise<void>;
  }

  /**
   * apiVersion 16, capability "coins" (a red consent line, approved by the person; no switch of its own: disabling or removing
   * the plugin revokes it): the person's Kino coins, earned by watching (1 every 10 minutes, 20 a day). Kino's own client talks
   * to the coins service: you never see its address nor its session. `balance()` from `screen`, `screenEvent`, `panelAction`
   * (a timer tick too) or your scheduled `job`; `give()` only inside a call the person started from `screen`, `screenEvent` or
   * `panelAction`. 30 calls a minute. Rejects with a KinoError whose `code` is `permission_denied`, `not_available` (the
   * service is down, or this device has no Telegram validation), `rate_limited`, `bad_request`, `disabled` (the person
   * switched Kinos off in Kino's Ajustes: show nothing of coins), or the service's own `no_balance`, `self_gift`,
   * `unknown_account`. Present on every apiVersion 16 runtime: feature-detect with
   * `typeof kino.coins === "object"` (an older Kino has none: hide your coin button).
   */
  namespace coins {
    function balance(): Promise<KinoCoinsBalance>;
    function give(gift: KinoCoinsGift): Promise<KinoCoinsGiven>;
  }

  /**
   * apiVersion 21, capability "files" (a plain consent line): files that are on the person's device. `pick` and `pickFolder` open
   * Kino's picker and only run from a press of the person's (a settings action, a `panelAction`, or a `screenEvent` that follows a
   * tap or submit); everything else needs no press, because a handle exists only for what the person picked. You get opaque
   * handles, never an address. By default a handle is a reference (the file stays where it is; a moved or deleted file rejects with
   * `gone`); `pick({ copy: true })` copies the bytes into your plugin's own store instead (up to 64 MB a file, 1 GB in all).
   * `read` and `readText` take a range (`start`, `end` exclusive), at most 2,000,000 bytes a call, like `kino.fetch`'s `maxBytes`:
   * read a big book by its parts. `url(id)` is a `kino-file:<id>` address a stream or an audio track may carry, so the player
   * plays the file; the host rules do not apply to it. Nothing here uploads or sends anything. Rejects with a KinoError whose
   * `code` is a [KinoFilesErrorCode]. Present on every apiVersion 21 runtime that declares the capability: feature-detect with
   * `typeof kino.files === "object"` (an older Kino has none).
   */
  namespace files {
    /** Opens the picker; resolves to the handles the person picked (an empty list when they cancel). */
    function pick(options?: { kinds?: KinoFileKind[]; multiple?: boolean; copy?: boolean }): Promise<KinoFile[]>;
    /** Opens the folder picker; resolves to the folder, or null when the person cancels. */
    function pickFolder(options?: { kinds?: KinoFileKind[] }): Promise<KinoFileFolder | null>;
    /** Your handles, newest first; with `folder`, the files under that picked folder. */
    function list(options?: { folder?: string; kinds?: KinoFileKind[] }): Promise<KinoFile[]>;
    /** The folders the person picked for you. */
    function folders(): Promise<KinoFileFolder[]>;
    function info(id: string): Promise<KinoFile>;
    /** Bytes `start` to `end` (exclusive, clamped to the file), at most 2,000,000. */
    function read(id: string, range?: { start?: number; end?: number }): Promise<Uint8Array>;
    /** The same range as UTF-8 text. */
    function readText(id: string, range?: { start?: number; end?: number }): Promise<string>;
    /** Drops the handle (and the copy of an imported file). */
    function forget(id: string): Promise<void>;
    /** `kino-file:<id>`: for a stream's or an audio track's `url`. */
    function url(id: string): string;
  }

  /**
   * apiVersion 22, capability "progress" (no approval line: it keeps only your plugin's own data about the person's own reading):
   * tell Kino how far along the person is in something that is not a video. Kino draws nothing from it (no Home row, no card):
   * you build your own shelf (a "keep reading" row on your screen) from `list`, and `resume` is your own opaque data (up to 1 KB)
   * that Kino never reads.
   * Call `set` as often as you like, even on every page: Kino keeps the latest per element and writes at most every 2 seconds
   * (and when the screen closes or the app goes to the background); at most 20 calls a second, the rest are coalesced, not
   * errors; 500 elements per plugin, the oldest by last activity dropped. An element is finished with `done: true` or when
   * `fraction` reaches `doneAt` (default 0.9); a later `set` with a lower fraction reopens it. A scheduled job may call it, but
   * not a job that runs for a profile other than the active one (`perProfile` jobs): there it rejects with `not_allowed`. Rejects with a
   * KinoError whose `code` is a [KinoProgressErrorCode]. Feature-detect with `typeof kino.progress === "object"` (an older Kino
   * has none); declare the capability as an enhancement (`enhancements["22"]`) to keep running on a Kino that does not have it.
   *
   * @example
   * // A reader: save the place on each page that is turned.
   * async function onPage(chapter, page, pages) {
   *   await kino.progress.set({
   *     id: "ch-" + chapter.id,
   *     title: chapter.mangaTitle,
   *     fraction: page / pages,
   *     label: "Cap. " + chapter.number + " · hoja " + page + " de " + pages,
   *     labelEn: "Ch. " + chapter.number + " · page " + page + " of " + pages,
   *     poster: chapter.cover,
   *     resume: { screen: "reader", args: { chapter: chapter.id, page } },
   *   });
   * }
   */
  namespace progress {
    /** Saves how far along an element is. Resolves when Kino has taken it (not when it is on disk). */
    function set(entry: KinoProgressSet): Promise<void>;
    /** What you last set for the element, or null when there is none (or the person cleared it). */
    function get(id: string): Promise<KinoProgressEntry | null>;
    /** Forgets the element. */
    function clear(id: string): Promise<void>;
    /**
     * Your elements, the most recently set first. `limit` 1 to 100 (default 50); `sinceMs` a finite number >= 0 keeps only those
     * set at or after that time (milliseconds since 1970). Finished elements are included (see `done`).
     */
    function list(options?: KinoProgressListOptions): Promise<KinoProgressEntry[]>;
  }

  /**
   * apiVersion 20, the plugin protocol (the manifest's `consumes`): asks a door another plugin opens, through Kino. `alias` is a
   * key of your `consumes`, `call` a name it lists, `arg` JSON (up to 64 KB) matching the call's `in`. Resolves to the answer
   * validated against the call's `out`; rejects with an Error whose `code` is a [KinoProtocolErrorCode]: `provider_missing` (not
   * installed, or 18+ while your plugin is not), `not_declared`, `bad_input`, `bad_output`, `rate_limited` (30 calls in any 10 s
   * per provider door), `timeout` (10 s) or `provider_failed`. `arg` reaches the provider, which may send it to its own hosts. Usable wherever the other services are (`screen`, `screenEvent`...); rejects `not_allowed` in a background
   * `job`. Declare the provider in `recommends` and offer `go.installPlugin` while it is missing. A stream is switched on with
   * the state flag `state.protocol.<alias>.<stream> = true` and arrives as the screenEvent `protocol` ([KinoProtocolEventArg]).
   * Feature-detect with `typeof kino.plugins === "object"`.
   */
  namespace plugins {
    function call(alias: string, call: string, arg?: unknown): Promise<unknown>;
  }

  /**
   * apiVersion 14, capability "shared" (Task 8q-2; a plain consent line, not red): a small store of your plugin's, per profile,
   * that syncs between the person's own linked devices, both ways, last writer wins by a clock Kino assigns. Typical use: a `preferPhone`
   * job on the phone writes its result, the TV's screen reads it. Synchronous, like `kino.storage`; usable from screens, panels,
   * settings and jobs.
   *
   * `get(key)`: the value, or null (never throws: a stored value this engine cannot read answers null). `set(key, value)`: JSON values only (stored as their JSON text): at most 64 KB each, 16 levels
   * deep, 4 keys and 128 KB per plugin; true when stored, false when it was already that value (nothing written or sent);
   * `set(key, null)` removes the key. A key's new value reaches the other devices at most once a minute (this device reads it at
   * once), and at most 4 of your keys travel in any minute. Keys are 1 to 40 of `A-Z a-z 0-9 _ . -`. At most 30 writes a minute.
   *
   * NEVER put a secret here (a token, a password, a cookie, a session): it is copied to every linked device. A key with a word
   * like one (token, secret, password, cookie, session, auth, apiKey..., plurals too; `author` is fine) is refused, and so is a value holding a sealed secret. What `get`
   * answers is UNTRUSTED: another device wrote it (maybe another version of your plugin): validate its shape, its sizes and every
   * field before you use it. Errors: `not_allowed`, `bad_request`, `too_large`, `rate_limited`. Feature-detect with
   * `typeof kino.shared === "object"` (the Node kit simulates two devices: `node sdk/run.mjs <folder> shared`).
   */
  namespace shared {
    function get(key: string): unknown;
    function set(key: string, value: unknown): boolean;
  }

  /**
   * Kino 0.9.55: share ONE anonymous, free guest session of your source's portal, so people in regions that can't log in
   * have live sessions to seed from. `session` is a plain object of the session's own fields (its ids and token); Kino keeps
   * only the known seed fields, drops everything else, and sends it to Kino's own error board — but only when the
   * person's plugin-telemetry consent is on (the same consent `kino.log.report` rides on). It is anonymous: it names no
   * account and carries nothing about the person. Best-effort and synchronous; it answers nothing and never throws. Mint a
   * BRAND-NEW guest session for this, never the person's own, and send it only after you confirmed it works. Absent on a
   * Kino older than 0.9.55 (feature-detect with `typeof kino.seed === "function"`).
   */
  function seed(session: Record<string, string | number>): void;

  /**
   * Kino 0.9.74, additive: a `"sync": { "mode": "realtime" }` provider that can learn of a remote change tells Kino, so Kino pulls
   * at once. Synchronous, cheap, answers nothing. Kino accepts at most one signal every 30 seconds and drops one that arrives while
   * a pull is already running (that pull sees the remote), so call it when you notice the change, not in a loop. Throws
   * `{ code: "not_allowed" }` unless the plugin declares the `syncProvider` capability with `mode: "realtime"`. Your code only runs
   * while Kino calls it, so you cannot hold a connection open between calls: the place to notice a change and signal is
   * `syncStatus` (not `syncPull`). Kino also keeps pulling every `pullEveryMs`. Feature-detect with `typeof kino.sync === "object"`.
   */
  namespace sync {
    function remoteChanged(): void;

    /**
     * Kino 0.9.78, additive, only for a plugin with the approved `syncProvider` capability (feature-detect with
     * `typeof kino.sync.active === "function"`; an older Kino, and any other plugin, has neither this nor `setActive`): whether this
     * plugin is the sync provider on THIS device now. Readable in any call.
     */
    function active(): Promise<boolean>;

    /**
     * Kino 0.9.78, additive, `syncProvider` only: turn this plugin on or off as THIS device's sync provider, so the person does it from
     * your own screen instead of going to Ajustes. Resolves with whether the plugin is the provider afterwards.
     * - `true` asks the person first, in Kino's own dialog (your installed name, Kino's words: you cannot change them); the current
     *   provider is turned off. Declined: resolves `false` and nothing changes. Already on: resolves `true` and asks nothing.
     * - `false` asks nothing and returns the person to Kino's local sync, only when this plugin is the one on.
     * Only runs from a call the person started with a tap (a settings action, a panelAction, or a screenEvent after their own press),
     * never from a job, a timer or a screen's `open`. Rejects with `{ code }`: `not_allowed` (not from a tap, or no `syncProvider`),
     * `unavailable` (the plugin cannot be a provider now), `busy` (a question is already open), `timeout` (nobody answered in two
     * minutes), `invalid_request` (not a boolean). Turn it on after the plugin's settings are saved: a provider with no key yet shows "not set up".
     */
    function setActive(on: boolean): Promise<boolean>;
  }

  /**
   * apiVersion 14, additive: what this Kino's screen canvas draws, for feature detection (`typeof kino.screen === "object"`;
   * `undefined` on an older Kino). `names` lists the `type` names it validates and draws, as these docs spell them
   * (`Column`, `TextField`, `titleRail`...); a node of any other type is dropped with a log line, so check it before relying
   * on a widget a newer Kino adds. `widgets` lists the same widgets by their older names. `version` is the screen contract's
   * own number (1 for now), raised only when a widget or an answer field changes meaning. The Node kit reports the
   * contract's lists.
   */
  namespace screen {
    const names: readonly string[];
    const widgets: readonly string[];
    const version: number;
    /**
     * Kino 0.9.88, additive, no new apiVersion: `true` when this Kino draws a screen's
     * pictures over http too (an `Image`'s `url`, a `heroCard`'s `image` and `logo`, a `CircleAvatar`'s `image`, a title's
     * `poster` and `backdrop`), on a public host by a poster's rule (never the home network, a private IP address or a name
     * without a dot), so an IPTV panel's http channel logos show. `undefined` on an older Kino, which keeps them https-only:
     * there, send an https address or nothing. Their `headers` still go only with an https picture. The Node kit says `true`.
     */
    const httpImages: true | undefined;
  }

  /**
   * apiVersion 6, with `"browser": true` (or `"pages"`) in the manifest (the person approves it in red): from `resolve` only, and only
   * a `resolve` the person started (they pressed play, or they started a download; never a background one), opens
   * `url` in a hidden web view, lets the page run its own player (muted; with `autoplay`, the default, it also clicks the
   * usual play buttons and taps the middle of the page), and answers the video requests the page made, HLS/DASH first,
   * each with the headers to play it with (put them in your Stream's `headers`). The start `url` must be a host your
   * `kino.fetch` may reach; the page may then load from any public server, never the home network. One page at a
   * time in the whole app (a download's capture never waits: `busy` at once). Throws a typed error: `browser_unavailable`
   * (no WebView on this device, and always under the Node kit), `timeout` (no video in `timeoutMs`, default 18000, at
   * most 25000), `blocked`, `busy`, `not_allowed` (no approved `"browser": true`, not inside `resolve`, or a `resolve`
   * nobody started), `invalid_request`.
   */
  namespace browser {
    function capture(url: string, options?: KinoBrowserCaptureOptions): Promise<KinoBrowserCapture>;
    /** Kino 0.9.54+: `true` when `capture` takes `captureAll`, `alsoMatch`, `waitForCookie` and `returnCookiesOnTimeout`; absent before. */
    const captureAll: true | undefined;
    /**
     * apiVersion 6, with `"browser": "pages"` in the manifest (`true` is capture-only and answers `not_allowed` here; the
     * person approves "Puede abrir páginas web ocultas para mostrar contenido y
     * encontrar el video", in red): from `search`, `home`, `browse`, `episodes`, `section`, `resolve` or `lyrics` (apiVersion 19: the lyrics the person opened; its 10 s call needs a `timeoutMs` of about 7000), only
     * while the person is using the app (never a background call), loads `url` in the same hidden web view and returns its
     * HTML once the page is past the site's automatic browser check (Cloudflare's "Just a moment…") and matches `waitFor`.
     * Kino never clicks, taps, types or scrolls in it and never solves a captcha: a page that asks for a human answers
     * `blocked` at once, and one still on its check page when the time runs out answers `blocked` too. The top document
     * must stay on your hosts: a redirect or navigation elsewhere answers `blocked`, never that site's HTML. Same start-host
     * rule, same one page at a time, fresh cookies per call; at most 20 page reads per minute per plugin. Throws a typed
     * error: `browser_unavailable` (always under the Node kit: keep a plain `kino.fetch` path), `timeout`, `blocked`,
     * `busy` (another page is open, or the person pressed play and the read was ended), `not_allowed`, `rate_limited`,
     * `invalid_request`.
     */
    function page(url: string, options?: KinoBrowserPageOptions): Promise<KinoBrowserPage>;
  }

  /**
   * Present only in plugins Kino generates from a CloudStream repository. Hand-written plugins never have it.
   * Each call runs the CloudStream provider at index `provider` inside the CloudStream bridge app. Throws a typed
   * error: `not_found` (the provider itself failed), `unavailable` (no bridge, an incompatible plugin, a timeout or a
   * refused request; the message says which), `invalid_request` (the request is over 1 MB).
   */
  namespace cloudstream {
    function search(provider: number, query: string): Promise<{ items: CsItem[] }>;
    function mainPage(provider: number, index: number, page: number): Promise<{ rows: { name: string; items: CsItem[] }[]; hasNext: boolean }>;
    function load(provider: number, url: string): Promise<{ title: CsTitle; episodes: CsEpisode[] }>;
    function loadLinks(provider: number, data: string): Promise<{ links: CsLink[]; subtitles: { lang: string; url: string }[] }>;
  }

  /** apiVersion 4: a marker for a secret the manifest's `secrets` declares (throws for any other name). Kino swaps it for the value in `kino.fetch`, toward the manifest's own hosts only; your code never sees the value. apiVersion 6: a secret declared `{ seal, use: "cipher-key", encoding }` is accepted as the whole `key` of any `kino.crypto.encrypt`/`decrypt` (des-ede3 included), read with the manifest's encoding; it is refused everywhere else, including `kino.fetch`. */
  function secret(name: string): string;

  /** Writes to Kino's log (and console.* does the same); lines are cut at 2000 characters. When a call of a plugin whose manifest says `"telemetry": true` or `"verbose"` (apiVersion 6) fails (a plugin that does not declare it never sends a line; a later Kino build adds a per-device "Enviar registros de errores y de reproducción" switch, on by default, that stops them) (sign and the settings exports included), the last 30 lines it logged (cut at 300 characters, scrubbed of URLs, hosts, ids, secrets and the person's text, 2 KB in all) go with the failure report; never for a call that succeeds. Log what happened, never what the person typed. */
  function log(...args: unknown[]): void;
  namespace log {
    /** apiVersion 6, with `"telemetry": true`: a log line that also tells Kino's error tracker your plugin served a degraded result (a fallback account, a backup source). The line's first word is its area (`[a-z0-9_:]`, with a `_` or `:`, up to 24 characters; anything else is filed as "other"); at most one report per area an hour and 3 per plugin per session, scrubbed like any line. Without telemetry (or, once the per-device switch exists, with it off) it is only a log line. With `"telemetry": "verbose"` a plugin's playback metrics, live/cast problems and edge cases also reach the board (see the README). In a debug build, or while the plugin's "Modo debug" switch is on (every plugin has one in Ajustes; `"debug": true` only makes it on by default), every line is in logcat under `KinoPlugin/<id>` and Kino's playback lines under `KinoPlay`. */
    function report(...args: unknown[]): void;
  }

  namespace html {
    /** Jsoup CSS selectors; at most 500 matches. Only inside Kino. */
    function select(html: string, css: string): KinoHtmlMatch[];
  }

  /**
   * 256 KB in total for this plugin. apiVersion 13, capability "storageLarge" (declarative, nothing to export): 16 MiB in
   * total, 2 MiB per value, at most 1000 keys of at most 256 characters instead, for a plugin that keeps a catalog (shard
   * it into values of about 512 KB); the same API and TTL rules, one file per value on the device. Going over throws
   * code `"too_large"`: "plugin storage full (256 KB)", or with storageLarge "plugin storage full (16 MB)" /
   * "plugin storage full (2 MB per value)" / "plugin storage full (1000 keys)"; a longer key is `"invalid_request"`.
   * The storageLarge store is device-only: never synced and NOT in backups. Declaring storageLarge moves the plugin's
   * existing keys into it, out of the backed-up 256 KB store: keep credentials and sessions in sealed secrets or the
   * person's settings, or in a plugin without the capability.
   */
  namespace storage {
    /** Returns `null` once the entry has expired (see `set`). */
    function get(key: string): string | null;
    /**
     * `options.ttlMs` makes the entry expire: after that many milliseconds, `get` returns `null` and
     * `keys()` leaves it out, even across a restart of the app. A whole number greater than 0,
     * at most 2,592,000,000 ms (30 days); anything else throws before the entry is touched. Leave
     * out `options` (or `ttlMs`) for a permanent entry, exactly as before this option existed. An
     * expired entry never counts against the cap (256 KB, or 16 MiB with storageLarge): it is dropped the next time your plugin
     * reads or writes storage.
     */
    function set(key: string, value: string, options?: { ttlMs?: number }): void;
    function remove(key: string): void;
    /** Expired keys are already gone. */
    function keys(): string[];
  }

  namespace config {
    /** A setting's value (string; boolean for a toggle; an array of `{ [field.key]: string }` for a `list`, apiVersion 4); undefined when unset with no default (a `url` setting never has one). Read-only. */
    function get(key: string): string | boolean | Array<Record<string, string>> | undefined;
    function all(): Record<string, string | boolean | Array<Record<string, string>>>;
  }

  /**
   * apiVersion 13, capability "socket": an outbound WebSocket. `url` must be wss:// (port 443) on a host the manifest declares and the
   * person approved -- never the local network or an IP literal. At most 4 open sockets per plugin and 8 MiB queued unread.
   */
  namespace ws {
    /**
     * Opens the socket and resolves once it is connected. Rejects with an error whose `code` is `"host_not_allowed"` (it
     * also carries the offending `host`), `"not_https"` (not a wss:// address) or `"limit"` (4 sockets already open); also `"network"` and `"timeout"` when the connection cannot be made.
     */
    function open(url: string, options?: { protocol?: string }): Promise<KinoWebSocket>;
  }

  /**
   * apiVersion 13, capability "catalog" (declarative, nothing to export, no consent line): a searchable catalog of your own
   * items, kept by Kino in ONE SQLite database file for your plugin alone, so you can index and search thousands of videos
   * without holding them in your 64 MB of QuickJS memory. Undefined without the capability, and inside `sign()`.
   *
   * Limits (contract.json `catalog`): at most 100,000 items per plugin; `id` 1 to 128 characters; `title` at most 300
   * characters; `data` at most 4,096 bytes of JSON; at most 500 items per `upsert` and 500 ids per `get` or `remove`;
   * `search` `limit` default 50, at most 100, `offset` at most 1,000,000, `q` at most 256 characters; the file at most 64 MiB.
   * Both item limits hold at once: 100,000 items fit only at about 670 bytes of file per item on average (measured with a
   * 50-character title: about 370 bytes with no `data`, about 920 with 500 bytes of `data`, about 4,850 with 4,000 bytes,
   * so only about 13,800 items at that size). Keep `data` small.
   *
   * Every refusal is a KinoError whose `code` says what to do: `"invalid_request"` (a wrong shape or type: fix the call),
   * `"too_large"` (one value or one batch over its limit, named in the message: split it or shorten it), `"limit"` (the
   * catalog is full, 100,000 items or 64 MiB: remove old items first) and `"unavailable"` (Kino could not read or write the
   * file right now: try again later; the message says "damaged and has been reset to empty" when the file was corrupt and
   * Kino started an empty one: rebuild it). A refused `upsert` writes nothing of its batch.
   *
   * Isolation and privacy: no other plugin can read or change your catalog, and your plugin never writes SQL (only these
   * six operations, every value bound). It stays on the device: never synced and NOT in backups, so after a restore or a
   * reinstall it is empty: rebuild it from your source. Credentials and sessions never belong here.
   */
  namespace catalog {
    /**
     * Adds or replaces up to 500 items in one transaction (all or nothing: one bad item refuses its whole batch, so clean
     * them first). Answers how many items were written.
     * @example
     *   const items = videos
     *     .filter((v) => String(v.id).length <= 128)
     *     .map((v) => ({ id: String(v.id), title: String(v.caption || "").slice(0, 300).replace(/[\uD800-\uDBFF]$/, "") || "Video " + v.id, sort: Number.isSafeInteger(v.date) ? v.date : 0, data: { file: String(v.fileRef) } }));
     *   for (let i = 0; i < items.length; i += 500) await kino.catalog.upsert(items.slice(i, i + 500));
     */
    function upsert(items: KinoCatalogUpsertItem[]): Promise<{ count: number }>;
    /**
     * One page of the items whose title holds every word of `q` (case and accents ignored), plus `total`, the count of
     * every match. Reads only the page asked for.
     * @example
     *   const offset = 40;
     *   const page = await kino.catalog.search({ q: "pelicula 2001", limit: 20, offset, order: "newest" });
     *   const more = page.total > offset + page.items.length;
     */
    function search(options?: KinoCatalogSearchOptions): Promise<KinoCatalogPage>;
    /**
     * The items with these ids (at most 500 per call), in the order asked; an id that is not there is skipped and a repeated
     * one comes once.
     * @example
     *   const [item] = await kino.catalog.get([ref]); // ref: the catalog id your resolve(ref) got
     */
    function get(ids: string[]): Promise<KinoCatalogItem[]>;
    /**
     * Deletes the items with these ids (at most 500 per call). Answers how many were there and are now gone.
     * @example
     *   await kino.catalog.remove(staleIds);
     */
    function remove(ids: string[]): Promise<{ count: number }>;
    /**
     * Deletes every item: Kino deletes the file itself, so the space goes back to the device.
     * @example
     *   await kino.catalog.clear(); // then upsert everything again
     */
    function clear(): Promise<void>;
    /**
     * How many items the catalog holds.
     * @example
     *   if ((await kino.catalog.count()) === 0) await rebuild();
     */
    function count(): Promise<number>;
  }

  /**
   * apiVersion 13, capability "qrScan" (declarative, nothing to export, no consent line): ask the person to scan a QR code
   * with the phone's camera. Undefined without the capability, and inside `sign()`.
   *
   * Kino opens its own camera scanner full screen over whatever the person was doing. At the top it shows, from the top:
   * "<your plugin's installed name> wants to read a QR code", your `title` (your `titleEn` when Kino speaks English, else
   * `title`; each at most 80 characters, at most two lines on screen, with no control, bidi or format character), and
   * Kino's instruction; a close button beside them. The first code the camera decodes that holds 1 to 4,096 characters
   * answers the call; a longer one is ignored, the scanner says "This code is not valid for <your plugin>" and keeps looking.
   *
   * Rules: only from a settings `action`, a `panelAction` or a `screenEvent` that follows the person's press (they pressed
   * one of your buttons), never from Home, search, a play, a list, a title page, your section, `settingsStatus` or any
   * background call. In a screen (apiVersion 14: a root screen, a screen-mode panel, a contributed tab in screen mode),
   * only the event of the person's own tap or submit counts: never the open event, a timer tick (`every`), a load-more, a
   * change, a panel's `refreshMs` or a `playerEvent`. The settings node inside a screen runs its `action` as Ajustes does.
   * That call's own time limit stops while the scanner is up. At most one scan on screen at a time, for the whole app.
   * The scanner closes by itself after 120 s. On a device without a camera, and on Kino's TV interface, it never opens.
   *
   * Errors (a KinoError whose `code` says what to do): `"busy"` (a scan is already open, yours or another plugin's: wait
   * for it), `"timeout"` (nothing was scanned in 120 s: offer to try again), `"unavailable"` (this device cannot scan: no
   * camera, or a TV: show the code another way, such as a settings `qr` setting), `"not_allowed"` (called from anything
   * else: "kino.qr.scan only runs from a settings action, panelAction or screenEvent the person pressed"; scan from a
   * button), `"permission_denied"` (the person did not give Kino the camera: say they can allow it in the phone's
   * settings) and `"invalid_request"` (a `title` or `titleEn` that is not a string, is over 80 characters or holds a
   * control or formatting character: fix the call).
   *
   * Privacy: you get only the decoded text of the code the person pointed the camera at, never an image; it is data from
   * the world (check it before you trust it), and only your plugin gets it.
   *
   * To SHOW a QR instead (say, on the new device a login is for), use a settings `qr` setting: `{ "key": "login", "label":
   * "...", "type": "qr", "refreshMs": 5000 }`, whose text is your `settingsStatus()` answer under that key (at most 512
   * characters); Kino asks again when the form opens, after every action and every `refreshMs` (2000 to 60000) while the
   * form is on screen, so a code that expires is replaced in place.
   */
  namespace qr {
    /**
     * Opens the scanner; resolves with the scanned text, or null when the person closed the scanner (the close button,
     * Back, leaving the screen).
     * @example
     *   // In action("link"): the person pressed "Vincular otro aparato" in your settings.
     *   let text;
     *   try {
     *     text = await kino.qr.scan({ title: "Escanea el código del otro aparato", titleEn: "Scan the other device's code" });
     *   } catch (e) {
     *     if (e.code === "unavailable") return { message: "Este aparato no puede escanear: usa tu teléfono" };
     *     if (e.code === "permission_denied") return { message: "Permite la cámara en los ajustes del teléfono" };
     *     throw e;
     *   }
     *   if (text === null) return { message: "Cancelado" };
     *   if (!text.startsWith("exampleapp://login?token=")) return { message: "Ese no es un código de inicio de sesión" };
     *   await acceptLogin(text);
     *   return { message: "Listo: el otro aparato ya entró" };
     */
    function scan(options?: { title?: string; titleEn?: string }): Promise<string | null>;
  }

  /**
   * `kino.visualBrowser` (apiVersion 20, manifest `"visualBrowser": true`): a browser WINDOW THE PERSON SEES AND DRIVES, to sign in,
   * solve a challenge or accept a site's terms. `kino.browser` is hidden and nobody can type in it; this is the same idea with a
   * window. It exists only for a plugin whose manifest declares the key (otherwise `kino.visualBrowser` is undefined, as on a Kino
   * before it: write `kino.visualBrowser?.available`), and `available` is false on the desktop and on a device without a WebView (a TV has one: it works there with the remote, experimental, and a page with pointer-only controls may be hard to reach): keep your other way
   * (pasting the cookies into a `password` setting, say).
   *
   * What the person sees: Kino's own sheet first, EVERY time, naming your plugin, the sites (your manifest `hosts`), the cookie
   * NAMES you asked for, whether the window will identify itself as a regular browser or with your own string, and whether Kino
   * keeps the cookies itself; only after Continuar does the window open. The window has Kino's bar (your plugin's name and your
   * `title`, the site's host with a lock, Cerrar, and Listo when you gave no `doneWhen`). You cannot change the bar.
   *
   * Rules: only from the person's own press -- a settings `action`, a `panelAction` or a `screenEvent` that follows the person's
   * tap or submit (the scanner's gate: `kino.qr.scan` above); from anything else (a search, Home, a timer, a job, a screen's
   * open or load-more, a background call) it throws `"forbidden"`. The first address and every page the window moves to must be
   * https, on the default port, on a host of your manifest `hosts` (wildcards as there; a sign-in that goes through
   * `accounts.google.com` needs it declared); anything else is stopped and Kino says so on the window. Never the local network.
   * One window at a time in the whole app. No script of yours runs in the page, you never see what is typed, and the page cannot
   * open pop-ups, download, pick files or use the camera, microphone or location. The window starts with the cookies of your hosts
   * cleared and clears them again when it closes (Android keeps one cookie jar for the app: a cookie scoped to another path than
   * `/` survives, and your own `kino.fetch` jar is separate). A window the person leaves in the background closes after a
   * minute.
   *
   * Throws a typed error: `"bad_args"` (the options are wrong: fix the call), `"forbidden"`, `"unavailable"` (a TV, or no screen
   * to show it on), `"busy"` (a window is already open: yours or another plugin's) and `"store_failed"` (`storeAs` and the text
   * does not fit the setting). Saying No to the sheet, Cerrar and Back are not errors: you get `{ status: "closed" }`.
   * @example
   *   // In action("link"): the person pressed "Vincular cuenta" in your settings.
   *   if (!kino.visualBrowser?.available) return { message: "Pega tus cookies en los ajustes" };
   *   const r = await kino.visualBrowser.open({
   *     url: "https://accounts.google.com/ServiceLogin?continue=https%3A%2F%2Fmusic.youtube.com",
   *     title: "YouTube Music",
   *     doneWhen: { cookies: ["SAPISID"] },
   *     collect: { cookies: ["SID", "HSID", "SSID", "APISID", "SAPISID"], storeAs: { setting: "cookieHeader", format: "header" } },
   *     userAgent: "browser",
   *   });
   *   if (r.status !== "done" || !r.stored) return { message: "No se vinculó la cuenta" };
   *   return { message: "Cuenta vinculada" }; // r.storedNames lists the cookies Kino kept; you never saw their values
   */
  namespace visualBrowser {
    /** True on a phone or tablet running a Kino with the capability; false on a TV and on the desktop. */
    const available: boolean;
    function open(options: KinoVisualBrowserOptions): Promise<KinoVisualBrowserResult>;
  }

  namespace cookies {
    /** The value of cookie `name` for `url` (a host the plugin may reach), or null. */
    function get(url: string, name: string): string | null;
    /** Forgets every cookie of this plugin (they also go when its settings change). */
    function clear(): void;
  }

  namespace crypto {
    /** Default input utf8, output hex. Data at most 5 MB. Errors carry code "crypto_error". */
    function hash(alg: "md5" | "sha1" | "sha256" | "sha512", data: string, options?: { inputEncoding?: KinoEncoding; outputEncoding?: KinoEncoding }): string;
    function hmac(alg: "md5" | "sha1" | "sha256" | "sha512", key: string, data: string, options?: { keyEncoding?: KinoEncoding; inputEncoding?: KinoEncoding; outputEncoding?: KinoEncoding }): string;
    /** GCM appends the 16-byte tag to the ciphertext. */
    function encrypt(alg: KinoCipher, options: KinoCipherOptions): string;
    /** GCM expects the 16-byte tag appended. */
    function decrypt(alg: KinoCipher, options: KinoCipherOptions): string;
    /** iterations at most 100000, keyLength at most 64 bytes. Password uses keyEncoding, salt inputEncoding. */
    function pbkdf2(hash: "sha1" | "sha256" | "sha512", password: string, salt: string, iterations: number, keyLength: number, options?: { keyEncoding?: KinoEncoding; inputEncoding?: KinoEncoding; outputEncoding?: KinoEncoding }): string;
    /**
     * apiVersion 13: MTProto's AES-256-IGE (`c_i = E(m_i xor c_{i-1}) xor m_{i-1}`). `dir` is "encrypt" or "decrypt"; `key` is
     * 32 bytes, `iv` 32 bytes (two blocks) and `data` a multiple of 16 bytes, each read with its encoding (key and iv with
     * keyEncoding/ivEncoding, data with inputEncoding; default utf8). Output base64 by default. Anything malformed fails
     * with the fixed text "invalid crypto operation". A sealed value is refused in every field.
     */
    function aesIge(dir: "encrypt" | "decrypt", key: string, iv: string, data: string, options?: { keyEncoding?: KinoEncoding; ivEncoding?: KinoEncoding; inputEncoding?: KinoEncoding; outputEncoding?: KinoEncoding }): string;
    /**
     * apiVersion 13: `base ^ exp mod mod` over big-endian hex strings (no 0x prefix; each at most 4096 bits). The answer is hex,
     * left-padded with zeros to the modulus' byte width. A zero modulus or an empty string in any of the three fails with
     * "invalid crypto operation" (write zero as "0").
     */
    function modPow(base: string, exp: string, mod: string): string;
    /** apiVersion 13: inflates a gzip stream (input base64 by default, output utf8 by default); the output is at most 5 MB. */
    function gunzip(data: string, options?: { inputEncoding?: KinoEncoding; outputEncoding?: KinoEncoding }): string;
    /**
     * apiVersion 13 (Kino's own version, not the manifest's: feature-detect with `typeof kino.crypto.convert === "function"`):
     * `data` read in `from` and written in `to` (`"hex"` to `"base64"` and back, `"utf8"` to bytes...), in native
     * code: no JavaScript loop over the bytes. Hex comes out lower case, base64 padded with the standard alphabet; base64 in may
     * be URL-safe or unpadded. At most 5 MB of bytes. A bad input fails with `"data" is not valid hex` / `base64`, an unknown
     * encoding with `unknown encoding: <name>`. A sealed value is refused.
     */
    function convert(data: string, from: KinoEncoding, to: KinoEncoding): string;
    /**
     * apiVersion 13 (Kino's own version, not the manifest's: feature-detect with `typeof kino.crypto.aesIgeVerify === "function"`):
     * AES-256-IGE decryption (as `aesIge("decrypt", ...)`) checked by a MAC in the same call: the SHA-256 digest of
     * `macPrefix` followed by the plaintext, bytes `macOffset` to `macOffset + mac.length` (1 to 32 bytes inside the 32-byte digest),
     * must equal `mac`, compared in constant time. On a match it answers the plaintext (base64 by default); on a mismatch it fails
     * with the fixed text "the mac doesn't match" and answers nothing. `mac` and `macPrefix` are read with `macEncoding` (default
     * hex), `key`/`iv`/`data` as in `aesIge`. MTProto 2.0's msg_key check is `macPrefix` = 32 bytes of the auth key, `macOffset` 8,
     * `mac` = the 16-byte msg_key. Anything malformed (sizes, an offset that is not a whole number or runs past the digest) fails
     * with "invalid crypto operation". A sealed value is refused in every field.
     */
    function aesIgeVerify(key: string, iv: string, data: string, options: { mac: string; macPrefix?: string; macOffset?: number; macEncoding?: KinoEncoding; keyEncoding?: KinoEncoding; ivEncoding?: KinoEncoding; inputEncoding?: KinoEncoding; outputEncoding?: KinoEncoding }): string;
    /** 1..1024 bytes, hex by default. */
    function randomBytes(n: number, outputEncoding?: KinoEncoding): string;
    /** A random (v4) UUID. */
    function uuid(): string;
    /**
     * apiVersion 6: a new key pair. The private key stays inside Kino: you get a handle that works only in this
     * runtime (not in sign()'s signing lane, not after the plugin restarts) and is gone when it closes; at most 64
     * live at once (a new one drops the oldest). Node's generateKeyPairSync / WebCrypto's generateKey map here.
     */
    function generateKeyPair(options: { type: "ec"; namedCurve: "P-256" | "P-384" } | { type: "ed25519" } | { type: "x25519" }): { readonly privateKey: KinoPrivateKey; readonly publicKey: KinoPublicKey };
    /** apiVersion 6: a peer's public key (jwk object, spki base64, or raw base64 with `type` and, for ec, `namedCurve`). Private keys cannot be imported. */
    function importKey(options: { format: "jwk"; key: KinoJwk } | { format: "spki"; key: string } | { format: "raw"; key: string; type: KinoKeyType; namedCurve?: "P-256" | "P-384" }): KinoPublicKey;
    /**
     * apiVersion 6: signs `data` (read with `encoding`, default utf8) with your private key; base64 by default.
     * ec: `hash` "SHA-256" (default) or "SHA-384"; `format` "der" (default, Node's crypto.sign) or "ieee-p1363"
     * (r||s, 64 bytes on P-256, 96 on P-384: WebCrypto's). ed25519: 64 bytes, no `hash`. x25519 does not sign.
     */
    function sign(options: { key: KinoPrivateKey | string; data: string; encoding?: KinoEncoding; hash?: "SHA-256" | "SHA-384"; format?: "der" | "ieee-p1363"; outputEncoding?: "base64" | "hex" }): string;
    /** apiVersion 6: true when `signature` (base64 by default) is valid for `data`; a malformed signature is false. `key`: a public key, a `{ jwk }`, or your own private key. */
    function verify(options: { key: KinoPublicKey | { jwk: KinoJwk } | KinoPrivateKey | string; data: string; encoding?: KinoEncoding; signature: string; signatureEncoding?: KinoEncoding; hash?: "SHA-256" | "SHA-384"; format?: "der" | "ieee-p1363" }): boolean;
    /** apiVersion 6: ECDH (ec, same curve) or X25519: the shared secret, base64 by default (32 bytes; 48 on P-384). */
    function deriveSharedSecret(options: { privateKey: KinoPrivateKey | string; publicKey: KinoPublicKey | { jwk: KinoJwk }; outputEncoding?: "base64" | "hex" }): string;
  }

  namespace rank {
    /**
     * The title's HEAD, up to its first `:`, `,`, `|`, en dash or em dash -- for a search backend
     * that ranks a short query better than a long one. A one- or two-letter head identifies
     * nothing, so the whole (trimmed) text comes back instead; a plain "-" is never a cut point (it
     * would split a hyphenated word like "Spider-Man").
     */
    function shortQuery(query: string): string;
    /**
     * Reorders `items` so the ones sharing the most words with `query` come first; ties keep
     * `items`' own order. `query` is a title, or several forms of one (try `query.q`,
     * `query.originalTitle` and `query.altTitles` together: a backend may only know a title in one
     * language). `getTitle` reads a title off an item, string or array of them; it defaults to
     * `(item) => item.title`. Never throws: `items` not an array answers `[]`; an item with no
     * usable title (missing, not a string, or `getTitle` itself failing) sorts after every item
     * that has one, in `items`' own order among themselves.
     */
    function sortBySimilarity(items: any[], query: string | string[], getTitle?: (item: any) => string | string[]): any[];
    /**
     * Drops items sharing too few words with `query` (under 60% of its distinctive words of 3+
     * letters), and any item with no usable title along with them. Never throws: `items` not an
     * array answers `[]`. Reordering alone (`sortBySimilarity`) still shows a full page of near-misses when
     * the title genuinely is not on the backend, so an absent title comes back with 0 results
     * instead.
     */
    function filterRelevant(items: any[], query: string | string[], getTitle?: (item: any) => string | string[]): any[];
  }
}

// ---------- web globals Kino adds (QuickJS has none of them natively) ----------
// URL, URLSearchParams, atob, btoa, TextEncoder and TextDecoder (UTF-8 only) behave like the
// browser's, without IDN/punycode. Use the lib "dom" typings, or declare them in your editor.

/**
 * The manifest's optional `categories` (every apiVersion; read only by Kino's plugin marketplace for its category chips).
 * A list without repeats; when present it replaces what Kino guesses from the capabilities.
 */
type KinoManifestCategory = "movies" | "series" | "anime" | "live" | "radio" | "subtitles" | "utilities" | "adult";

/**
 * apiVersion 6, capability "meta": what `meta(query)` is asked about a title ANOTHER source listed (never one of your own),
 * as the app's TitleMetaQuery builds it. Keys appear only when known; Kino asks nobody about a title with no id at all.
 */
interface KinoMetaQuery {
  type: "movie" | "series";
  /** Every id Kino knows for the title (from the card, TMDB or its anime mapping); each one only when known, never 0 or "". */
  ids: { imdb?: string; tmdb?: number; kitsu?: number; mal?: number; anilist?: number };
  /** The title's own Stremio-style id in its source ("kitsu:1376", "tt0944947"), only for a Stremio addon's title. */
  id?: string;
  /** The person's language ("es"). */
  lang?: string;
}

/**
 * `meta`'s answer (or null: a title you do not know -- not a failure). Every field optional; Kino only fills what TMDB and
 * AniList left empty, and an answer with only `year` and/or `runtimeMinutes` counts as none. Text fields may also be numbers
 * (read as text); each is trimmed and cut, and anything Kino cannot use is dropped on its own (`node sdk/run.mjs . meta`
 * says which and why). Images follow an item's poster rule: http(s), a public name or IPv4 (http never to a name without
 * a dot), or the person's own server; a URL longer than 2048 characters is dropped, so keep them shorter. Fields not
 * listed here are ignored.
 */
interface KinoTitleMeta {
  /** Read (up to 200 characters) but not shown: the page keeps the source's own title. */
  title?: string | number;
  /** Up to 2000 characters; HTML tags are stripped on the page. */
  overview?: string | number;
  poster?: string;
  backdrop?: string;
  /** Only its first 9 characters are read, and their first four digits are the year: 1999, "1999", "1999-2003". */
  year?: string | number;
  /** Strings only, trimmed, up to 30 characters each; the first 5 non-empty ones. */
  genres?: string[];
  /** 1..1000 (a numeric string or a decimal is read as Android's JSON optInt does). Shown only for a movie. */
  runtimeMinutes?: number | string;
  /**
   * At most 5000 entries read (invalid ones count); `season` 0..999 (0 kept, but never listed on the page), `number`
   * 1..99999, one per season and number (the first wins), sorted. Texts as an item's; `airDate` "YYYY-MM-DD";
   * `id` (up to 4096 characters) the episode's Stremio-style video id.
   */
  episodes?: { season: number | string; number: number | string; title?: string | number; overview?: string | number; still?: string; airDate?: string; id?: string | number }[];
  /** Kino 0.9.51+: a clear-logo of the title, shown instead of its name on the info page. */
  logo?: string;
  /**
   * Kino 0.9.51+: one per source (the first valid one wins; `source` is case-insensitive), at most 6 kept; added to the
   * page's score, never replacing it (a `tmdb` one is left out when the page has a score). `value`: up to 3 digits, up to 2
   * decimals with "." or ",", then optionally "%" or "/N" ("8.8", "94%", "4.1/5", "72/100"); a number >= 0 is written
   * without trailing zeros (8.80 is "8.8").
   */
  ratings?: { source: "imdb" | "tmdb" | "rottentomatoes" | "metacritic" | "letterboxd" | "mal" | "anilist" | "trakt"; value: string | number }[];
  /**
   * Kino 0.9.51+: at most 20 with a name, one per name (the first wins); `name` and `character` up to 60 characters.
   * Shown only when TMDB has no cast, as "Reparto:" with the first 5 names; `character` and `photo` are kept, not shown.
   */
  cast?: { name: string | number; character?: string | number; photo?: string }[];
}

/**
 * `meta` -- required with the capability "meta" (apiVersion 6). Asked with every other meta plugin at once; the first
 * answer in install order wins, within 6 s (a timeout or a throw is just no answer, never shown), remembered 30 minutes.
 */
type KinoMetaFn = (query: KinoMetaQuery) => Promise<KinoTitleMeta | null>;

/**
 * apiVersion 11, manifest field `"externalResolver"` (needs the `externalResolve` capability): the resolver app this
 * plugin wants by default, and optionally where to get it when it isn't installed.
 *
 *     "externalResolver": {
 *       "package": "com.example.resolver",
 *       "apk": { "url": "https://github.com/acme/resolver/releases/download/v1.0/resolver.apk", "sha256": "<64 hex>", "label": "Example Resolver" },
 *       "fdroid": true,
 *       "downloader": { "code": "1234567" }
 *     }
 *
 * `apk.url` must be a GitHub release asset (`https://github.com/<owner>/<repo>/releases/download/<tag>/<file>`) or an archive.org
 * file (`https://archive.org/download/<item>/<file>`); nothing else is
 * ever downloaded. It is offered only for exactly `package`, and only handed to the installer if the file's sha256 matches.
 * Three independent ways to get the app when it is not installed, each optional: `apk` (above); `fdroid: true` (the same
 * `package` is listed in F-Droid: Kino opens F-Droid for exactly that package; the official F-Droid client has no real Android TV
 * support, so on a TV prefer the others); `downloader.code` (3 to 10 digits: a Downloader code for TV sideloading, which Kino only
 * SHOWS, with a button to open the Downloader app when it is installed). Kino offers only what the manifest declares for exactly
 * `package`. With none of them (or if the stream names another package) a missing resolver just fails with "resolver not found".
 * A stream's `external.resolver` overrides `package`; without either, any installed app declaring the protocol may be asked.
 */
interface KinoManifestExternalResolver {
  package: string;
  apk?: { url: string; sha256: string; label?: string };
  /** Only `true` means anything: this `package` is listed in F-Droid. */
  fdroid?: true;
  /** A Downloader app code (3 to 10 digits) that fetches the app, for a TV. Shown, never installed by Kino. */
  downloader?: { code: string };
}

/**
 * apiVersion 12, capability `"syncProvider"`: the plugin is the transport of the person's cross-device sync. Kino keeps the logic
 * (what is synced, merging, when to run) and encrypts the snapshot before handing it over; the plugin only stores and returns an
 * opaque blob, byte for byte. Needs the exports `syncPull` and `syncPush`; `syncStatus` is optional.
 * Who can read the data: the key is derived from one of your own settings (`sync.keySecret`, required), which your code reads, so
 * the plugin and its service CAN read the synced data; the install sheet says so in red ("Sincronizará tus datos a través de su
 * servicio: el plugin y su servicio podrán leerlos"). An update that adds the capability waits for the person's approval again.
 */
interface KinoSyncContext {
  /**
   * The largest blob, in bytes after decoding, Kino will send or accept: the manifest's `maxBlobBytes`, at most 4194304 (4 MiB).
   * Kino 0.9.74: while `syncPull`/`syncPush` run (only then), `kino.fetch` requests and response bodies, and the call's answer,
   * may reach ceil(maxBlobBytes * 4/3) + 65536 characters/bytes instead of 1 MB / 5 MB, so the base64 blob fits in one request.
   */
  maxBlobBytes: number;
}

/**
 * `syncPull` -- required with the capability "syncProvider". The latest stored blob and its version, or null when nothing is stored yet.
 * Every sync export receives ONE argument (an object, or null for `syncStatus`). `blob` is standard base64 (RFC 4648, `+` and `/`,
 * padded) WITHOUT line breaks, in both directions.
 */
type KinoSyncPullFn = (arg: KinoSyncContext) => Promise<{ blob: string /* base64 ciphertext */; version: string } | null>;

/**
 * `syncPush` -- required with the capability "syncProvider". Store `blob` (base64 ciphertext, sealed with the key Kino derives from `sync.keySecret`) and return
 * the new opaque `version`. `arg.expectedVersion` is the version Kino last pulled (null if none): a provider that can detect that the remote
 * changed since throws `{ code: "conflict" }` and Kino pulls, merges and pushes again; one that cannot ignores it.
 */
type KinoSyncPushFn = (arg: KinoSyncContext & { blob: string; expectedVersion: string | null }) => Promise<{ version: string }>;

/** `syncStatus` -- optional with the capability "syncProvider": the status line of the plugin's sync settings. */
type KinoSyncStatusFn = (arg: null) => Promise<{ ready: boolean; message?: string }>;

/**
 * apiVersion 12, manifest field `"sync"` (needs the `syncProvider` capability; refused without it). Required with that capability:
 * a provider without a `sync` block or without `keySecret` is refused. Every key but `keySecret` and `provision` is optional:
 *
 *     "sync": { "mode": "poll", "pullEveryMs": 600000, "pushDebounceMs": 300000, "maxBlobBytes": 4194304,
 *               "keySecret": "botToken", "provision": ["botToken", "chatId"] }
 *
 * `mode` is `"poll"` (default: Kino pulls on foreground and every `pullEveryMs`) or `"realtime"` (the provider signals remote changes).
 * Both times are positive whole milliseconds (defaults 600000 and 300000); Kino clamps them to its own floors. `maxBlobBytes` is the
 * largest blob the provider accepts (default and maximum 4194304).
 *
 * `keySecret` (required) is the `key` of one of the plugin's own `"password"` settings (anything else refuses the manifest). Kino
 * derives the sync key from that setting's value on each device (HKDF-SHA256, host side), so the key never travels: a second device
 * only needs the same settings (for example the same bot token). The derivation is public and your code reads the setting, so the
 * plugin and its service CAN read the synced data (the consent sheet says so in red). It must be a long random token
 * (a bot token, an API key), never a password a person picks: anyone holding a stored blob can try guesses offline. That setting
 * must not declare a `default` (the manifest is refused): the person types it, and until then Kino runs no sync round. There is no
 * key without it: a key one device made up could never reach another. Changing that setting's value changes the key: the copy
 * stored remotely then no longer opens until the person resets sync on one device and gives the new value to the others.
 *
 * `provision` (required) lists the `key`s of your own settings (secret or not, at most 8, no repeats) that pairing hands to another
 * device so it can run the same provider, for example `["botToken", "chatId"]`. It must include `keySecret`. From apiVersion 13 it
 * may name a `"sync": false` password (a one-shot secret such as a 2FA password): sent only while it holds a value, named by its
 * label on both screens, stored sealed and device-only on the receiver (never synced nor backed up); your plugin clears it once
 * used. `keySecret` itself can never be a `"sync": false` password.
 *
 * `generateKey` (apiVersion 13, default false): Kino makes the `keySecret` value itself, 32 random bytes as 64 lower-case hex
 * characters, while that setting is empty: when the person switches the provider on, and when they press "Enviar configuración"
 * (before the values are read, so an empty key never hides that button). It is saved sealed like a typed password, never
 * logged and never drawn in your form; a value that exists is never replaced, and one received from another device replaces it.
 */
interface KinoManifestSync {
  mode?: "poll" | "realtime";
  pullEveryMs?: number;
  pushDebounceMs?: number;
  maxBlobBytes?: number;
  keySecret: string;
  provision: string[];
  generateKey?: boolean;
}