Skip to content

Clone your own voice on your own computer: speak any text in 60+ languages and dub videos into another language in your voice. Fully local. Early version.

116 KB
Raw Blame
//! The MCP tools and resources.

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use futures_util::StreamExt;
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
    CallToolResult, ContentBlock, Icon, Implementation, ListResourceTemplatesResult, ListResourcesResult,
    PaginatedRequestParams, ProgressNotificationParam, ProgressToken, ReadResourceRequestParams, ReadResourceResponse,
    ReadResourceResult, RequestMetaObject, Resource, ResourceContents, ResourceTemplate, ServerCapabilities,
    ServerConfig,
};
use rmcp::service::RequestContext;
use rmcp::{ErrorData, Peer, RoleServer, ServerHandler, tool, tool_handler, tool_router};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use tokio::io::AsyncWriteExt;
use tokio::sync::broadcast::error::RecvError;
use tokio_util::sync::CancellationToken;

use crate::api::{Api, ApiError};
use crate::events::{Event, JobState, State, Tracker, end_state, progress_of};

/// Audio larger than this is returned as a link only.
pub const AUDIO_INLINE_MAX: u64 = 4 << 20;
/// `resources/read` refuses larger files (download_file streams them instead).
pub const RESOURCE_MAX: u64 = 32 << 20;
const EVENTS_CONNECT: Duration = Duration::from_secs(10);
const SPEAK_TIMEOUT_S: u64 = 600;
const VIDEO_TIMEOUT_S: u64 = 1800;
const WAIT_TIMEOUT_S: u64 = 300;
const MAX_TIMEOUT_S: u64 = 3600;
const RESOURCE_LIST_LIMIT: u64 = 100;
pub const FILE_URI: &str = "mimvox://file/";
const ICONS: [(&[u8], &str); 2] = [
    (include_bytes!("../../../tools/release/icons/mcp_64x64.png"), "64x64"),
    (include_bytes!("../../../tools/release/icons/mcp_256x256.png"), "256x256"),
];

const INSTRUCTIONS: &str = "Mimvox clones a voice and speaks text with it, on the user's machine. create_voice makes a \
voice from recordings of the speaker (voice_recordings adds more, train_voice trains it for a closer likeness, \
manage_voice renames, deletes or exports it); design_voice makes a new voice from a description instead. \
export_video turns results into a video (one result, or book chapters joined into one episode with a picture and \
subtitles per chapter), transcribe turns speech into timed lines, subtitle_video burns subtitles into a video, \
export_subtitles saves them as a subtitle file (SRT, WebVTT, SBV), dub_video translates a video and dubs it in a voice, respeak speaks a file's (edited) lines again in a voice and \
convert_voice turns its speech into a trained voice. list_results, export_audio and delete_result handle the saved \
results. This server is a client of the Mimvox local HTTP API (on in Mimvox Settings, API, or `mimvox serve`). \
Paths in requests and answers are on the API's machine: with a remote API, upload_file a local file first and \
download_file results. Only clone the user's own voice or one whose owner gave explicit permission; the speech model \
weights are CC BY-NC 4.0, so generated speech is for non-commercial use only.";

const ENGINE_CALL: &str = "Call any Mimvox engine method through the API's /rpc and return its result as is. Covers \
everything the app can do. Method families: hello, components.set; voices.* (list, create, rename, delete, import, \
export, warm, reference_candidates, set_reference, add_reference, remove_reference, reference_from_media, \
media_cancel, clear_media, design, design_cancel, design_takes, design_delete); media.combine; video.export, \
video.cancel, subtitles.export; presets.list; text.analyze, text.import, text.stress; recording.check; dataset.add, dataset.remove, \
dataset.summary; train.start, train.pause, train.resume, train.cancel; tts.generate, tts.cancel, tts.languages; \
outputs.list, outputs.play, outputs.delete; formats.list, audio.export; book.start, book.resume, book.pause, \
book.cancel, book.list, book.get, book.delete, book.reread, book.play; redub.probe, redub.prepare, redub.transcribe, \
redub.dub, redub.render (modes convert, respeak, subtitles), redub.cancel; shutdown. Parameters and results are \
documented in contract/engine-protocol.md of the Mimvox repository. Methods that answer {job} run in the background: \
follow them with wait_job or job_status. Errors carry the engine's code (bad_request, not_found, busy, not_ready, \
paused, cancelled, no_memory, internal).";

#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum AudioFormat {
    Wav,
    Mp3,
    Flac,
    Ogg,
    Opus,
    M4a,
    Aiff,
}

impl AudioFormat {
    fn as_str(self) -> &'static str {
        match self {
            Self::Wav => "wav",
            Self::Mp3 => "mp3",
            Self::Flac => "flac",
            Self::Ogg => "ogg",
            Self::Opus => "opus",
            Self::M4a => "m4a",
            Self::Aiff => "aiff",
        }
    }
}

#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Quality {
    Best,
    Fast,
}

#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Cast {
    Fast,
    Careful,
}

impl Cast {
    fn as_str(self) -> &'static str {
        match self {
            Cast::Fast => "fast",
            Cast::Careful => "careful",
        }
    }
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct EngineCallArgs {
    /// Engine method, e.g. "voices.list" or "audio.export".
    pub method: String,
    /// The method's parameters (an object); omit for none.
    #[serde(default)]
    pub params: Option<Map<String, Value>>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SpeakArgs {
    /// The text to speak.
    pub text: String,
    /// Voice id or name (case-insensitive); default: the first voice of list_voices.
    #[serde(default)]
    pub voice: Option<String>,
    /// ISO 639-1 code of the text (en, uk, de, ...); default: the voice's language.
    #[serde(default)]
    pub language: Option<String>,
    /// Voice-cloning model: omnivoice, voxcpm or chatterbox when installed; default: the engine's choice.
    #[serde(default)]
    pub model: Option<String>,
    /// Format of the saved file; default wav.
    #[serde(default)]
    pub format: Option<AudioFormat>,
    /// Speaking speed, 0.8 to 1.3; default 1.0.
    #[serde(default)]
    pub speed: Option<f64>,
    /// Return the audio itself when it is at most 4 MB (default true); the file path is always returned.
    #[serde(default)]
    pub include_audio: Option<bool>,
    /// Seconds to wait for the result (default 600); after that the job goes on and wait_job follows it.
    #[serde(default)]
    pub timeout_s: Option<u64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DesignArgs {
    /// What the new voice says.
    pub text: String,
    /// ISO 639-1 code of the text (en, uk, de, ...).
    pub language: String,
    /// omnivoice or voxcpm; default: the first installed that speaks the language (OmniVoice before VoxCPM2).
    #[serde(default)]
    pub model: Option<String>,
    /// The voice. VoxCPM2: any words ("a deep, calm male voice"). OmniVoice: comma-separated terms from gender (male,
    /// female), age (child, teenager, young adult, middle-aged, elderly), pitch (very low pitch ... very high pitch),
    /// whisper and, for English, american accent or british accent. Empty: the model chooses.
    #[serde(default)]
    pub description: Option<String>,
    /// Ukrainian only: HolosTTS reads the text in the new voice with exact word stress (default true when installed).
    #[serde(default)]
    pub exact_stress: Option<bool>,
    /// Loudness of the take in LUFS, -40 to -10 (default -23).
    #[serde(default)]
    pub loudness: Option<f64>,
    /// Return the audio itself when it is at most 4 MB (default true); the file path is always returned.
    #[serde(default)]
    pub include_audio: Option<bool>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct KeepTakeArgs {
    /// The take's id (from design_voice or list_design_takes).
    pub take: String,
    /// Name of the new voice.
    pub name: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeleteTakesArgs {
    /// The take's id; leave it out and set all to delete every take.
    #[serde(default)]
    pub take: Option<String>,
    /// Delete every take (voices kept from them stay).
    #[serde(default)]
    pub all: Option<bool>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ImportTextArgs {
    /// Absolute path of a document on the API's machine (txt, md, html, epub, docx, odt, rtf, fb2, pdf, srt, vtt).
    pub path: String,
    /// Language code of the text, or "auto" (default).
    #[serde(default)]
    pub language: Option<String>,
    /// Include each chapter's full text (default false: titles and word counts only).
    #[serde(default)]
    pub include_text: Option<bool>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct Chapter {
    pub title: String,
    pub text: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct StartBookArgs {
    /// A document on the API's machine to read (imported as import_text does). Give this or chapters.
    #[serde(default)]
    pub path: Option<String>,
    /// The chapters to read, instead of a document.
    #[serde(default)]
    pub chapters: Option<Vec<Chapter>>,
    /// Only these chapters of the document (0-based indexes, as import_text lists them).
    #[serde(default)]
    pub chapter_indexes: Option<Vec<usize>>,
    /// Book title; default: the document's title.
    #[serde(default)]
    pub title: Option<String>,
    /// Voice id or name; default: the first voice.
    #[serde(default)]
    pub voice: Option<String>,
    /// Language code of the text; default: the document's detected language, else the voice's.
    #[serde(default)]
    pub language: Option<String>,
    /// Format of each chapter file; default wav.
    #[serde(default)]
    pub format: Option<AudioFormat>,
    /// Also make one .m4b audiobook with chapter marks (default false).
    #[serde(default)]
    pub m4b: Option<bool>,
    /// Read each chapter's title first (default true).
    #[serde(default)]
    pub read_titles: Option<bool>,
    /// Speaking speed, 0.8 to 1.3 (default 1.0).
    #[serde(default)]
    pub speed: Option<f64>,
    /// 0.1 to 1.5 (default 0.6 for books): lower is steadier.
    #[serde(default)]
    pub expressiveness: Option<f64>,
    /// "best" (default) or "fast".
    #[serde(default)]
    pub quality: Option<Quality>,
    /// Voice-cloning model: omnivoice, voxcpm or chatterbox when installed; default: the engine's choice.
    #[serde(default)]
    pub model: Option<String>,
    /// Voice id or name that reads every male character's lines; voice then reads the narration. Needs the
    /// Character voices component.
    #[serde(default)]
    pub men_voice: Option<String>,
    /// Voice id or name that reads every female character's lines, as men_voice.
    #[serde(default)]
    pub women_voice: Option<String>,
    /// How the speakers are found with men_voice or women_voice: "fast" (default) or "careful" (reads the book
    /// twice and leaves the lines the two readings disagree on to the narrator).
    #[serde(default)]
    pub cast: Option<Cast>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct FindSpeakersArgs {
    /// A document on the API's machine (imported as import_text does). Give this or chapters.
    #[serde(default)]
    pub path: Option<String>,
    /// The chapters, instead of a document.
    #[serde(default)]
    pub chapters: Option<Vec<Chapter>>,
    /// Only these chapters of the document (0-based indexes, as import_text lists them).
    #[serde(default)]
    pub chapter_indexes: Option<Vec<usize>>,
    /// Language code of the text; default: the document's detected language. Use the same as start_book.
    #[serde(default)]
    pub language: Option<String>,
    /// "fast" (default) or "careful", as start_book's cast.
    #[serde(default)]
    pub cast: Option<Cast>,
    /// Search every chapter again, even one searched before (default false).
    #[serde(default)]
    pub again: Option<bool>,
    /// Seconds to wait for the result (default 1800); after that the job goes on and wait_job follows it.
    #[serde(default)]
    pub timeout_s: Option<u64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct BookStatusArgs {
    /// Book id; omit to list every book.
    #[serde(default)]
    pub id: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct BookIdArgs {
    /// Book id (from start_book or book_status).
    pub id: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct JobArgs {
    /// Job id, e.g. "job-3".
    pub job: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct WaitJobArgs {
    /// Job id, e.g. "job-3".
    pub job: String,
    /// Seconds to wait (default 300, at most 3600).
    #[serde(default)]
    pub timeout_s: Option<u64>,
}

#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum VideoFormat {
    Mp4,
    Mkv,
    Webm,
    Mov,
}

impl VideoFormat {
    fn as_str(self) -> &'static str {
        match self {
            Self::Mp4 => "mp4",
            Self::Mkv => "mkv",
            Self::Webm => "webm",
            Self::Mov => "mov",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum SubtitleFormat {
    #[default]
    Srt,
    Vtt,
    Sbv,
}

impl SubtitleFormat {
    fn as_str(self) -> &'static str {
        match self {
            Self::Srt => "srt",
            Self::Vtt => "vtt",
            Self::Sbv => "sbv",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Position {
    #[default]
    Bottom,
    Top,
}

impl Position {
    fn as_str(self) -> &'static str {
        match self {
            Self::Bottom => "bottom",
            Self::Top => "top",
        }
    }
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct Line {
    /// Seconds.
    pub start: f64,
    /// Seconds.
    pub end: f64,
    pub text: String,
    /// Whisper's words of a transcript line, [start, end, word]: subtitles then follow each word, also after the text
    /// was edited.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub words: Option<Vec<(f64, f64, String)>>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct VideoPart {
    /// An audio file on the API's machine: a book chapter, a speech result, an upload.
    pub path: String,
    /// This part's subtitle lines, in seconds of the part.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub segments: Option<Vec<Line>>,
    /// A file with this part's lines instead: a book chapter's segments_path, or a result's .result.json.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub segments_path: Option<String>,
    /// A picture on the API's machine, shown from this part's start until the next picture starts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub image: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct VideoImage {
    /// A picture on the API's machine (jpg, png, webp, ...).
    pub path: String,
    /// Seconds into the video where it starts (the first 0); leave it out on every picture to space them evenly.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start: Option<f64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ExportVideoArgs {
    /// One file on the API's machine: a result's audio (Speak, Design, a book chapter) or a Redub result's video.
    /// Give this or parts.
    #[serde(default)]
    pub path: Option<String>,
    /// Audio files joined in order into one video (an episode of book chapters), each with its own lines and picture.
    #[serde(default)]
    pub parts: Option<Vec<VideoPart>>,
    /// Subtitle lines of path, instead of its result's own text.
    #[serde(default)]
    pub segments: Option<Vec<Line>>,
    /// A file with the lines of path (a book chapter's segments_path or a .result.json), instead of its own.
    #[serde(default)]
    pub segments_path: Option<String>,
    /// Container; default mp4.
    #[serde(default)]
    pub format: Option<VideoFormat>,
    /// Draw subtitles into the picture; default true when segments or segments_path are given (here or in a part).
    #[serde(default)]
    pub subtitles: Option<bool>,
    /// Where the subtitles go; default bottom.
    #[serde(default)]
    pub subtitle_position: Option<Position>,
    /// Pictures over the sound besides the parts' own, each also blurred behind itself; none at all: black.
    #[serde(default)]
    pub images: Option<Vec<VideoImage>>,
    /// The pictures fade in from black and into each other (0.6 s each); default false.
    #[serde(default)]
    pub transitions: Option<bool>,
    /// Absolute path of the video on the API's machine. Default: next to path when it is in the outputs, else in
    /// <data>/outputs/videos/ (parts: named after their folder, a book's title); an existing file is never replaced.
    #[serde(default)]
    pub dest: Option<String>,
    /// Seconds to wait (default 1800); after that the export goes on and wait_job follows it.
    #[serde(default)]
    pub timeout_s: Option<u64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SubtitleVideoArgs {
    /// A video (or an audio file: a black video) on the API's machine.
    pub path: String,
    /// ISO 639-1 code of the speech, or "auto" (default) to detect it.
    #[serde(default)]
    pub language: Option<String>,
    /// Where the subtitles go; default bottom.
    #[serde(default)]
    pub subtitle_position: Option<Position>,
    /// The lines (seconds in the file); given, nothing is transcribed.
    #[serde(default)]
    pub segments: Option<Vec<Line>>,
    /// Pictures over the sound, each also blurred behind itself: instead of black for an audio file, instead of its
    /// own picture for a video.
    #[serde(default)]
    pub images: Option<Vec<VideoImage>>,
    /// Without images, a video's picture: "own" (default) or "black".
    #[serde(default)]
    pub picture: Option<String>,
    /// The pictures fade in from black and into each other (0.6 s each); default false.
    #[serde(default)]
    pub transitions: Option<bool>,
    /// Seconds to wait for both steps (default 1800); after that the job goes on and wait_job follows it.
    #[serde(default)]
    pub timeout_s: Option<u64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ExportSubtitlesArgs {
    /// The lines to save (seconds), such as transcribe's segments; given, nothing is transcribed.
    #[serde(default)]
    pub segments: Option<Vec<Line>>,
    /// An audio or video file on the API's machine: transcribed when no segments are given, and where the
    /// subtitle file goes by default.
    #[serde(default)]
    pub path: Option<String>,
    /// srt (default), vtt (WebVTT) or sbv (YouTube's SubViewer).
    #[serde(default)]
    pub format: Option<SubtitleFormat>,
    /// ISO 639-1 code of the speech to transcribe, or "auto" (default) to detect it.
    #[serde(default)]
    pub language: Option<String>,
    /// Absolute path of the subtitle file on the API's machine (replaced when it exists); default: named after path,
    /// placed as export_video places a video.
    #[serde(default)]
    pub dest: Option<String>,
    /// Seconds to wait for the transcription (default 1800); after that it goes on and wait_job follows it.
    #[serde(default)]
    pub timeout_s: Option<u64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DubVideoArgs {
    /// A video on the API's machine.
    pub path: String,
    /// Voice id or name (case-insensitive); default: the first voice of list_voices.
    #[serde(default)]
    pub voice: Option<String>,
    /// ISO 639-1 code to dub into; default en.
    #[serde(default)]
    pub target_language: Option<String>,
    /// ISO 639-1 code of the speech, or "auto" (default).
    #[serde(default)]
    pub source_language: Option<String>,
    /// Draw the dubbed text into the picture (default false).
    #[serde(default)]
    pub subtitles: Option<bool>,
    /// Where the subtitles go; default bottom.
    #[serde(default)]
    pub subtitle_position: Option<Position>,
    /// Seconds to wait (default 1800); after that the dub goes on and wait_job follows it.
    #[serde(default)]
    pub timeout_s: Option<u64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct UploadArgs {
    /// Path of a file on this machine (where mimvox-mcp runs).
    pub local_path: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DownloadArgs {
    /// Absolute path on the API's machine, under <data>/outputs, <data>/tmp, <data>/api/uploads or <data>/design, or a
    /// book's segments_path.
    pub path: String,
    /// Where to save it on this machine (a file or an existing folder); default: the Downloads folder.
    #[serde(default)]
    pub dest: Option<String>,
    /// Replace an existing file (default false).
    #[serde(default)]
    pub overwrite: Option<bool>,
}

#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum VoiceAction {
    Rename,
    Delete,
    Export,
}

#[derive(Clone, Copy, Debug, Default, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum RecordingsAction {
    #[default]
    List,
    Add,
    Remove,
}

#[derive(Clone, Copy, Debug, Default, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum TrainAction {
    #[default]
    Start,
    Status,
    Pause,
    Resume,
    Cancel,
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Output {
    Audio,
    Video,
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Timing {
    Keep,
    Natural,
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ExportQuality {
    High,
    Standard,
    Small,
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ResultKind {
    Speak,
    Redub,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct CreateVoiceArgs {
    /// Name of the new voice; default: the first file's name (with bundle: the bundle's own).
    #[serde(default)]
    pub name: Option<String>,
    /// Recordings of one speaker on the API's machine: audio or video files, any number (up to 20 minutes are used).
    /// Give this or bundle.
    #[serde(default)]
    pub paths: Option<Vec<String>>,
    /// ISO 639-1 code of the language spoken in them; default: heard in the files.
    #[serde(default)]
    pub language: Option<String>,
    /// Remove background music first: true for every file, false for none; default: only videos with sound under
    /// the voice, and only with a GPU.
    #[serde(default)]
    pub remove_music: Option<bool>,
    /// A voice bundle (.mimvoice, from manage_voice export) on the API's machine, instead of paths.
    #[serde(default)]
    pub bundle: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ManageVoiceArgs {
    /// Voice id or name (case-insensitive).
    pub voice: String,
    /// rename (name, language or both), delete, or export as a bundle.
    pub action: VoiceAction,
    /// rename: the new name.
    #[serde(default)]
    pub name: Option<String>,
    /// rename: ISO 639-1 code of the language the voice was recorded in.
    #[serde(default)]
    pub language: Option<String>,
    /// export: absolute path of the bundle on the API's machine (replaced when it exists); default:
    /// <data>/tmp/export/, which download_file serves until the engine restarts.
    #[serde(default)]
    pub dest: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct VoiceRecordingsArgs {
    /// Voice id or name (case-insensitive).
    pub voice: String,
    /// list (default), add (paths) or remove (part).
    #[serde(default)]
    pub action: Option<RecordingsAction>,
    /// add: more recordings of the speaker on the API's machine (audio or video), joined into one new part.
    #[serde(default)]
    pub paths: Option<Vec<String>>,
    /// add: remove background music first, as in create_voice.
    #[serde(default)]
    pub remove_music: Option<bool>,
    /// remove: the part's index, as list shows it.
    #[serde(default)]
    pub part: Option<u32>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct TrainVoiceArgs {
    /// Voice id or name (case-insensitive).
    pub voice: String,
    /// start (default), status, pause, resume or cancel.
    #[serde(default)]
    pub action: Option<TrainAction>,
    /// start: epochs, 1 to 2000; default: the number recommended for the recordings (status shows it).
    #[serde(default)]
    pub epochs: Option<u32>,
    /// start: discard a paused training of this voice and start over (default false).
    #[serde(default)]
    pub restart: Option<bool>,
    /// pause, cancel: the training's job; default: the training that runs.
    #[serde(default)]
    pub job: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct TranscribeArgs {
    /// An audio or video file on the API's machine.
    pub path: String,
    /// ISO 639-1 code of the speech, or "auto" (default) to detect it.
    #[serde(default)]
    pub language: Option<String>,
    /// Also translate every line into this language (ISO 639-1).
    #[serde(default)]
    pub translate_to: Option<String>,
    /// Keep Whisper's word times in each line ([start, end, word]; long), for subtitle_video (default false).
    #[serde(default)]
    pub include_words: Option<bool>,
    /// Seconds to wait (default 1800); after that the job goes on and wait_job follows it.
    #[serde(default)]
    pub timeout_s: Option<u64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct RespeakArgs {
    /// An audio or video file on the API's machine.
    pub path: String,
    /// Voice id or name (case-insensitive); default: the first voice of list_voices.
    #[serde(default)]
    pub voice: Option<String>,
    /// The lines to speak, each at its time in the file (transcribe's, edited); without them the file is transcribed.
    #[serde(default)]
    pub segments: Option<Vec<Line>>,
    /// ISO 639-1 code of the speech ("auto", the default, detects it) or, with segments, of their text (default:
    /// guessed from the script).
    #[serde(default)]
    pub language: Option<String>,
    /// Without segments: translate the transcript into this language (ISO 639-1) and speak the translation.
    #[serde(default)]
    pub translate_to: Option<String>,
    /// Speaking speed, 0.8 to 1.3; default 1.0.
    #[serde(default)]
    pub speed: Option<f64>,
    /// keep (default): each line fits its original time; natural: at the voice's pace, the result can be longer.
    /// A video result always keeps the timing.
    #[serde(default)]
    pub timing: Option<Timing>,
    /// audio or video; default: video for a video file (by its extension).
    #[serde(default)]
    pub output: Option<Output>,
    /// Keep the original music and sounds under the new voice; default true for a video result.
    #[serde(default)]
    pub keep_background: Option<bool>,
    /// Video result: draw the spoken text into the picture (default false).
    #[serde(default)]
    pub subtitles: Option<bool>,
    /// Where the subtitles go; default bottom.
    #[serde(default)]
    pub subtitle_position: Option<Position>,
    /// Format of the saved audio; default wav.
    #[serde(default)]
    pub format: Option<AudioFormat>,
    /// Voice-cloning model: omnivoice, voxcpm or chatterbox when installed; default: the engine's choice.
    #[serde(default)]
    pub model: Option<String>,
    /// Seconds to wait for both steps (default 1800); after that the job goes on and wait_job follows it.
    #[serde(default)]
    pub timeout_s: Option<u64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ConvertVoiceArgs {
    /// An audio or video file on the API's machine.
    pub path: String,
    /// A trained voice's id or name (case-insensitive); default: the first voice of list_voices.
    #[serde(default)]
    pub voice: Option<String>,
    /// How closely the timbre follows the voice's recordings, 0 to 1 (RVC index rate); default 1.
    #[serde(default)]
    pub voice_match: Option<f64>,
    /// audio or video; default: video for a video file (by its extension).
    #[serde(default)]
    pub output: Option<Output>,
    /// Keep the original music and sounds under the new voice; default true for a video result.
    #[serde(default)]
    pub keep_background: Option<bool>,
    /// Format of the saved audio; default wav.
    #[serde(default)]
    pub format: Option<AudioFormat>,
    /// Seconds to wait (default 1800); after that the job goes on and wait_job follows it.
    #[serde(default)]
    pub timeout_s: Option<u64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ExportAudioArgs {
    /// An audio file on the API's machine: a result, a book chapter, a design take.
    pub path: String,
    /// The format to write.
    pub format: AudioFormat,
    /// Lossy formats only: high, standard (default) or small.
    #[serde(default)]
    pub quality: Option<ExportQuality>,
    /// Absolute path of the new file on the API's machine (replaced when it exists); default: next to path with the
    /// format's extension.
    #[serde(default)]
    pub dest: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ListResultsArgs {
    /// Only Speak or only Redub results; default both.
    #[serde(default)]
    pub kind: Option<ResultKind>,
    /// At most this many, 1 to 500 (default 20).
    #[serde(default)]
    pub limit: Option<u32>,
    /// Only results made before this time (unix seconds): the created of the last entry, for the next page.
    #[serde(default)]
    pub before: Option<f64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeleteResultArgs {
    /// The result's path, as list_results shows it.
    pub path: String,
}

#[derive(Clone)]
pub struct Mimvox {
    api: Arc<Api>,
    events: Tracker,
    tool_router: ToolRouter<Self>,
}

fn ok(value: Value) -> CallToolResult {
    CallToolResult::structured(value)
}

fn fail(e: &ApiError) -> CallToolResult {
    let mut res = CallToolResult::error(vec![ContentBlock::text(e.to_string())]);
    res.structured_content = Some(json!({ "error": e.to_json() }));
    res
}

fn reply(r: Result<Value, ApiError>) -> CallToolResult {
    match r {
        Ok(v) => ok(v),
        Err(e) => fail(&e),
    }
}

fn timeout_of(given: Option<u64>, default: u64) -> Duration {
    Duration::from_secs(given.unwrap_or(default).clamp(1, MAX_TIMEOUT_S))
}

pub fn mime_for(path: &str) -> &'static str {
    let ext = path.rsplit('.').next().unwrap_or_default().to_ascii_lowercase();
    match ext.as_str() {
        "wav" | "wave" => "audio/wav",
        "mp3" => "audio/mpeg",
        "flac" => "audio/flac",
        "ogg" | "oga" | "opus" => "audio/ogg",
        "m4a" | "aac" => "audio/mp4",
        "m4b" => "audio/mp4",
        "aif" | "aiff" => "audio/aiff",
        "mp4" | "m4v" => "video/mp4",
        "mov" => "video/quicktime",
        "mkv" => "video/x-matroska",
        "webm" => "video/webm",
        "avi" => "video/x-msvideo",
        "json" => "application/json",
        "mimvoice" | "zip" => "application/zip",
        "txt" | "srt" | "vtt" | "sbv" => "text/plain",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        _ => "application/octet-stream",
    }
}

fn file_name(path: &str) -> &str {
    path.rsplit(['/', '\\']).next().unwrap_or(path)
}

/// `mimvox://file/<the absolute path, percent-encoded>`: a file the API serves.
pub fn file_uri(path: &str) -> String {
    let mut uri = String::from(FILE_URI);
    for b in path.bytes() {
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
            uri.push(b as char);
        } else {
            uri.push_str(&format!("%{b:02X}"));
        }
    }
    uri
}

pub fn path_of_uri(uri: &str) -> Option<String> {
    let enc = uri.strip_prefix(FILE_URI)?.as_bytes();
    let mut out = Vec::with_capacity(enc.len());
    let mut i = 0;
    while i < enc.len() {
        if enc[i] == b'%' {
            let hex = std::str::from_utf8(enc.get(i + 1..i + 3)?).ok()?;
            out.push(u8::from_str_radix(hex, 16).ok()?);
            i += 3;
        } else {
            out.push(enc[i]);
            i += 1;
        }
    }
    String::from_utf8(out).ok().filter(|p| !p.is_empty())
}

fn file_link(path: &str, size: Option<u64>) -> ContentBlock {
    let mut res = Resource::new(file_uri(path), file_name(path)).with_mime_type(mime_for(path));
    if let Some(size) = size {
        res = res.with_size(size);
    }
    ContentBlock::resource_link(res)
}

/// The text of every chapter left out (a book's text can be megabytes).
fn without_texts(mut import: Value) -> Value {
    let strip = |chapters: &mut Value| {
        if let Some(list) = chapters.as_array_mut() {
            for (i, ch) in list.iter_mut().enumerate() {
                if let Some(obj) = ch.as_object_mut() {
                    obj.remove("text");
                    obj.insert("index".into(), json!(i));
                }
            }
        }
    };
    strip(&mut import["chapters"]);
    if import["parts"].is_object() {
        strip(&mut import["parts"]["chapters"]);
    }
    import
}

struct Progress {
    peer: Peer<RoleServer>,
    token: ProgressToken,
    last: f64,
    /// The share of 0-100 the current job's percent maps to, for a call that runs jobs one after another.
    span: (f64, f64),
}

impl Progress {
    fn new(meta: &RequestMetaObject, peer: Peer<RoleServer>) -> Option<Self> {
        meta.get_progress_token().map(|token| Self { peer, token, last: f64::NEG_INFINITY, span: (0.0, 100.0) })
    }

    async fn send(&mut self, ev: &Event, total_hint: Option<f64>) {
        let Some((mut value, total, message)) = progress_of(ev, total_hint) else { return };
        if total == Some(100.0) {
            let (lo, hi) = self.span;
            value = lo + value * (hi - lo) / 100.0;
        }
        // Progress must increase with each notification.
        if value <= self.last {
            return;
        }
        self.last = value;
        let mut p = ProgressNotificationParam::new(self.token.clone(), value).with_message(message);
        if let Some(total) = total {
            p = p.with_total(total);
        }
        let _ = self.peer.notify_progress(p).await;
    }
}

#[derive(Default)]
struct BookText {
    chapters: Vec<Value>,
    title: Option<String>,
    language: Option<String>,
    /// The document's path and format.
    source: Option<(Value, Value)>,
}

enum Ran {
    Done(Value),
    Running,
}

fn still_running(job: &str, message: &str) -> CallToolResult {
    ok(json!({ "job": job, "state": "running", "message": message }))
}

/// The summary as text and structured content, with a link to each file (videos are never inlined).
fn with_links(summary: Value, paths: &[&str]) -> CallToolResult {
    let mut content = vec![ContentBlock::text(summary.to_string())];
    content.extend(paths.iter().filter(|p| !p.is_empty()).map(|p| file_link(p, None)));
    let mut res = CallToolResult::success(content);
    res.structured_content = Some(summary);
    res
}

/// Recordings added from files are parts from 1000 on, as the app numbers them: apart from the reading parts.
const FILES_PART: u64 = 1000;
const VIDEO_EXTENSIONS: [&str; 6] = ["mp4", "m4v", "mov", "mkv", "webm", "avi"];

fn put<const N: usize>(params: &mut Value, pairs: [(&str, Option<Value>); N]) {
    for (key, value) in pairs {
        if let Some(v) = value {
            params[key] = v;
        }
    }
}

fn is_video(path: &str) -> bool {
    let ext = path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
    VIDEO_EXTENSIONS.contains(&ext.as_str())
}

/// The app's default name for a voice made from files: the first file's name in words.
fn stem_name(path: &str) -> String {
    let name = file_name(path);
    let stem = name.rsplit_once('.').map_or(name, |(s, _)| s).replace(['_', '-'], " ");
    let words: String = stem.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(60).collect();
    if words.is_empty() { "My voice".into() } else { words }
}

/// A `redub.done` as the Redub tools answer it, with links to its video (when made) and its audio.
fn redub_answer(job: &str, voice: Option<&Value>, r: Value, extra: Value) -> CallToolResult {
    let video = r["video_path"].as_str().unwrap_or_default().to_string();
    let audio = r["path"].as_str().unwrap_or_default().to_string();
    let mut summary = json!({
        "job": job,
        "state": "done",
        "mode": r["mode"],
        "video_path": r["video_path"],
        "uri": file_uri(if video.is_empty() { &audio } else { &video }),
        "path": audio,
        "path_play": r["path_play"],
        "format": r["format"],
        "duration_s": r["duration_s"],
        "language": r["language"],
        "target_language": r["target_language"],
        "keep_background": r["keep_background"],
    });
    if let Some(v) = voice {
        summary["voice"] = v["name"].clone();
        summary["voice_id"] = v["id"].clone();
    }
    for key in ["subtitles_burned", "subtitle_lines", "subtitle_note", "background_note", "timing", "drift_s"] {
        if let Some(v) = r.get(key) {
            summary[key] = v.clone();
        }
    }
    if let Some(extra) = extra.as_object() {
        for (k, v) in extra {
            summary[k] = v.clone();
        }
    }
    summary["result"] = r;
    with_links(summary, &[&video, &audio])
}

/// The default folder and name (no extension) of a video of `sources` (paths on the API's machine): next to a single
/// source in the outputs, else `<data>/outputs/videos`, the data folder found from the first source's path.
fn video_place(sources: &[&str], single: bool) -> Option<(String, String)> {
    let first = *sources.first()?;
    let sep = if first.rfind('\\') > first.rfind('/') { '\\' } else { '/' };
    let parts: Vec<&str> = first.split(['/', '\\']).collect();
    let (file, dirs) = parts.split_last()?;
    let stem = |f: &str| f.rsplit_once('.').map_or(f, |(s, _)| s).to_string();
    let sep_s = sep.to_string();
    let join = |c: &[&str]| c.join(sep_s.as_str());
    let outputs = dirs.iter().rposition(|c| *c == "outputs");
    if single && outputs.is_some() {
        return Some((join(dirs), stem(file)));
    }
    let data = match outputs {
        Some(i) => i,
        None => {
            let uploads = dirs.windows(2).rposition(|w| w == ["api", "uploads"]);
            let design = (dirs.len() >= 2 && dirs[dirs.len() - 2] == "design").then(|| dirs.len() - 2);
            uploads.or(design)?
        }
    };
    let folder = format!("{}{sep}outputs{sep}videos", join(&dirs[..data]));
    let parent = |p: &str| p.rsplit_once(['/', '\\']).map(|(d, _)| d.to_string());
    let shared = sources.iter().all(|s| parent(s) == parent(first));
    let name = match dirs.last() {
        Some(dir) if !single && sources.len() > 1 && shared && !dir.is_empty() => dir.to_string(),
        _ => stem(file),
    };
    Some((folder, name))
}

enum Waited {
    Ended(JobState),
    TimedOut(Option<JobState>),
    Cancelled,
}

impl Mimvox {
    pub fn new(api: Arc<Api>, events: Tracker) -> Self {
        Self { api, events, tool_router: Self::tool_router() }
    }

    async fn events_ready(&self) -> Result<(), ApiError> {
        self.events.ready(EVENTS_CONNECT).await.map_err(|reason| {
            ApiError::new(
                "unreachable",
                format!(
                    "cannot follow the Mimvox API's events at {} ({reason}). Turn on the API in Mimvox Settings, or \
                     run `mimvox serve` (mimvox-server).",
                    self.api.base()
                ),
            )
        })
    }

    async fn wait(
        &self,
        job: &str,
        timeout: Duration,
        mut progress: Option<&mut Progress>,
        total_hint: Option<f64>,
        cancel: &CancellationToken,
    ) -> Waited {
        let (mut rx, known) = self.events.watch(job);
        if let Some(st) = known.filter(JobState::ended) {
            return Waited::Ended(st);
        }
        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let ev = tokio::select! {
                _ = tokio::time::sleep_until(deadline) => return Waited::TimedOut(self.events.job(job)),
                _ = cancel.cancelled() => return Waited::Cancelled,
                ev = rx.recv() => ev,
            };
            match ev {
                Ok(ev) if ev.job.as_deref() == Some(job) => {
                    if end_state(&ev.event).is_some() {
                        if let Some(st) = self.events.job(job) {
                            return Waited::Ended(st);
                        }
                    } else if let Some(p) = progress.as_deref_mut() {
                        p.send(&ev, total_hint).await;
                    }
                }
                Ok(ev) if ev.event == "engine.exited" => {
                    let lost = self.events.job(job).filter(JobState::ended);
                    return Waited::Ended(lost.unwrap_or_else(|| JobState::lost(job, &ev.event)));
                }
                Ok(_) => {}
                Err(RecvError::Lagged(_)) => {
                    if let Some(st) = self.events.job(job).filter(JobState::ended) {
                        return Waited::Ended(st);
                    }
                }
                Err(RecvError::Closed) => return Waited::TimedOut(self.events.job(job)),
            }
        }
    }

    async fn voices(&self) -> Result<Vec<Value>, ApiError> {
        let list = self.api.rpc("voices.list", json!({})).await?;
        Ok(list["voices"].as_array().cloned().unwrap_or_default())
    }

    /// A voice by id or name (case-insensitive), else the first one.
    async fn voice(&self, wanted: Option<&str>) -> Result<Value, ApiError> {
        let voices = self.voices().await?;
        let names = || voices.iter().filter_map(|v| v["name"].as_str()).collect::<Vec<_>>().join(", ");
        match wanted.map(str::trim).filter(|w| !w.is_empty()) {
            Some(w) => voices
                .iter()
                .find(|v| v["id"].as_str() == Some(w))
                .or_else(|| voices.iter().find(|v| v["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(w))))
                .cloned()
                .ok_or_else(|| ApiError::new("not_found", format!("no voice {w:?}; the voices are: {}", names()))),
            None => voices
                .first()
                .cloned()
                .ok_or_else(|| ApiError::new("not_found", "there are no voices yet: make one in the Mimvox app first")),
        }
    }

    async fn speak_inner(
        &self,
        args: SpeakArgs,
        progress: Option<&mut Progress>,
        cancel: &CancellationToken,
    ) -> Result<CallToolResult, ApiError> {
        let voice = self.voice(args.voice.as_deref()).await?;
        let mut params = json!({ "voice_id": voice["id"], "text": args.text });
        if let Some(lang) = args.language.or_else(|| voice["language"].as_str().map(str::to_string)) {
            params["language"] = json!(lang);
        }
        if let Some(format) = args.format {
            params["output_format"] = json!(format.as_str());
        }
        if let Some(model) = args.model {
            params["model"] = json!(model);
        }
        if let Some(speed) = args.speed {
            params["speed"] = json!(speed);
        }
        self.events_ready().await?;
        let started = self.api.rpc("tts.generate", params).await?;
        let job = started["job"].as_str().unwrap_or_default().to_string();
        let segments = started["segments"].as_f64();
        let timeout = timeout_of(args.timeout_s, SPEAK_TIMEOUT_S);
        let st = match self.wait(&job, timeout, progress, segments, cancel).await {
            Waited::Ended(st) => st,
            Waited::TimedOut(_) => {
                return Ok(ok(json!({
                    "job": job,
                    "state": "running",
                    "voice": voice["name"],
                    "message": "still speaking: follow it with wait_job",
                })));
            }
            Waited::Cancelled => {
                let _ = self.api.rpc("tts.cancel", json!({ "job": job })).await;
                return Err(ApiError::new("cancelled", "the request was cancelled, and so was the job"));
            }
        };
        let result = st.result.clone().unwrap_or(Value::Null);
        if st.state != State::Done {
            let code = result["code"].as_str().unwrap_or("internal");
            let message = result["message"].as_str().unwrap_or("the job failed");
            return Err(ApiError::new(code, message));
        }
        let path = result["path"].as_str().unwrap_or_default().to_string();
        let summary = json!({
            "job": job,
            "state": "done",
            "voice": voice["name"],
            "voice_id": voice["id"],
            "path": path,
            "uri": file_uri(&path),
            "format": result["format"],
            "duration_s": result["duration_s"],
            "elapsed_s": result["elapsed_s"],
            "result": result,
        });
        let mut content = vec![ContentBlock::text(summary.to_string())];
        let mut size = None;
        if args.include_audio.unwrap_or(true) {
            match self.fetch(&path, AUDIO_INLINE_MAX).await {
                Ok(Fetched::Bytes(bytes)) => {
                    size = Some(bytes.len() as u64);
                    content.push(ContentBlock::audio(BASE64.encode(&bytes), mime_for(&path)));
                }
                Ok(Fetched::TooLarge(n)) => size = n,
                Err(e) => eprintln!("mimvox-mcp: cannot fetch {path}: {e}"),
            }
        }
        content.push(file_link(&path, size));
        let mut res = CallToolResult::success(content);
        res.structured_content = Some(summary);
        Ok(res)
    }

    async fn design_inner(&self, args: DesignArgs, cancel: &CancellationToken) -> Result<CallToolResult, ApiError> {
        let mut params = json!({ "language": args.language, "text": args.text });
        if let Some(model) = args.model {
            params["model"] = json!(model);
        }
        if let Some(description) = args.description {
            params["description"] = json!(description);
        }
        if let Some(exact) = args.exact_stress {
            params["exact_stress"] = json!(exact);
        }
        if let Some(loudness) = args.loudness {
            params["loudness"] = json!(loudness);
        }
        let take = tokio::select! {
            take = self.api.rpc("voices.design", params) => take?,
            _ = cancel.cancelled() => {
                let _ = self.api.rpc("voices.design_cancel", json!({})).await;
                return Err(ApiError::new("cancelled", "the request was cancelled, and so was the take"));
            }
        };
        let path = take["path"].as_str().unwrap_or_default().to_string();
        let summary = json!({
            "take": take["id"],
            "path": path,
            "uri": file_uri(&path),
            "model": take["model"],
            "language": take["language"],
            "duration_s": take["duration_s"],
            "clear": take["clear"],
            "result": take,
        });
        let mut content = vec![ContentBlock::text(summary.to_string())];
        let mut size = None;
        if args.include_audio.unwrap_or(true) {
            match self.fetch(&path, AUDIO_INLINE_MAX).await {
                Ok(Fetched::Bytes(bytes)) => {
                    size = Some(bytes.len() as u64);
                    content.push(ContentBlock::audio(BASE64.encode(&bytes), mime_for(&path)));
                }
                Ok(Fetched::TooLarge(n)) => size = n,
                Err(e) => eprintln!("mimvox-mcp: cannot fetch {path}: {e}"),
            }
        }
        content.push(file_link(&path, size));
        let mut res = CallToolResult::success(content);
        res.structured_content = Some(summary);
        Ok(res)
    }

    /// Starts a job and waits for its end; a cancelled call cancels the job with `cancel_method`.
    async fn run_job(
        &self,
        method: &str,
        params: Value,
        cancel_method: &str,
        timeout: Duration,
        progress: Option<&mut Progress>,
        cancel: &CancellationToken,
    ) -> Result<(String, Ran), ApiError> {
        self.events_ready().await?;
        let started = self.api.rpc(method, params).await?;
        let job = started["job"].as_str().unwrap_or_default().to_string();
        let ran = self.follow(&job, cancel_method, timeout, progress, cancel).await?;
        Ok((job, ran))
    }

    /// Waits for a started job's end; a cancelled call cancels the job with `cancel_method`.
    async fn follow(
        &self,
        job: &str,
        cancel_method: &str,
        timeout: Duration,
        progress: Option<&mut Progress>,
        cancel: &CancellationToken,
    ) -> Result<Ran, ApiError> {
        Ok(match self.wait(job, timeout, progress, None, cancel).await {
            Waited::Ended(st) => {
                let result = st.result.unwrap_or(Value::Null);
                if st.state != State::Done {
                    let code = result["code"].as_str().unwrap_or("internal");
                    return Err(ApiError::new(code, result["message"].as_str().unwrap_or("the job failed")));
                }
                Ran::Done(result)
            }
            Waited::TimedOut(_) => Ran::Running,
            Waited::Cancelled => {
                let _ = self.api.rpc(cancel_method, json!({ "job": job })).await;
                return Err(ApiError::new("cancelled", "the request was cancelled, and so was the job"));
            }
        })
    }

    /// A video path that no file has yet, as `video_place` picks it (`_2`, `_3`, ... on a clash).
    async fn video_dest(&self, sources: &[&str], single: bool, ext: &str) -> Result<String, ApiError> {
        let no_place = || {
            ApiError::new(
                "bad_request",
                format!("cannot tell where the video goes from {:?}: give dest", sources.first().unwrap_or(&"")),
            )
        };
        let (folder, name) = video_place(sources, single).ok_or_else(no_place)?;
        let sep = if folder.rfind('\\') > folder.rfind('/') { '\\' } else { '/' };
        for n in 1..1000 {
            let suffix = if n == 1 { String::new() } else { format!("_{n}") };
            let candidate = format!("{folder}{sep}{name}{suffix}.{ext}");
            match self.api.download(&candidate).await {
                Ok(_) => {}
                Err(e) if e.code == "not_found" => return Ok(candidate),
                Err(e) if e.code == "forbidden" => return Err(no_place()),
                Err(e) => return Err(e),
            }
        }
        Err(no_place())
    }

    async fn export_inner(
        &self,
        args: ExportVideoArgs,
        progress: Option<&mut Progress>,
        cancel: &CancellationToken,
    ) -> Result<CallToolResult, ApiError> {
        let format = args.format.unwrap_or(VideoFormat::Mp4).as_str();
        let parts = args.parts.unwrap_or_default();
        let sources: Vec<&str> = match &args.path {
            Some(path) if parts.is_empty() => vec![path.as_str()],
            None if !parts.is_empty() => parts.iter().map(|p| p.path.as_str()).collect(),
            _ => return Err(ApiError::new("bad_request", "give either path or parts")),
        };
        let lines = args.segments.is_some()
            || args.segments_path.is_some()
            || parts.iter().any(|p| p.segments.is_some() || p.segments_path.is_some());
        let dest = match args.dest {
            Some(dest) => dest,
            None => self.video_dest(&sources, args.path.is_some(), format).await?,
        };
        let mut params = json!({ "dest": dest, "format": format, "subtitles": null });
        match args.path {
            Some(path) => params["path"] = json!(path),
            None => params["parts"] = json!(parts),
        }
        if args.subtitles.unwrap_or(lines) {
            params["subtitles"] = json!({ "position": args.subtitle_position.unwrap_or_default().as_str() });
        }
        let optional = [
            ("segments", args.segments.map(|s| json!(s))),
            ("segments_path", args.segments_path.map(Value::from)),
            ("images", args.images.map(|i| json!(i))),
            ("transitions", args.transitions.filter(|on| *on).map(Value::from)),
        ];
        for (key, value) in optional {
            if let Some(v) = value {
                params[key] = v;
            }
        }
        let timeout = timeout_of(args.timeout_s, VIDEO_TIMEOUT_S);
        let (job, ran) = self.run_job("video.export", params, "video.cancel", timeout, progress, cancel).await?;
        let Ran::Done(r) = ran else {
            return Ok(still_running(&job, "still exporting: follow it with wait_job"));
        };
        let dest = r["dest"].as_str().unwrap_or(&dest).to_string();
        let mut summary = json!({
            "job": job,
            "state": "done",
            "dest": dest,
            "uri": file_uri(&dest),
            "format": format,
            "duration_s": r["duration_s"],
            "parts": r["parts"],
            "subtitles": r["subtitles"],
            "copied": r["copied"],
        });
        if let Some(note) = r.get("subtitle_note") {
            summary["subtitle_note"] = note.clone();
        }
        Ok(with_links(summary, &[&dest]))
    }

    /// The file's lines as redub.transcribe hears them, `{start, end, text, words?}`, and their language; Err: the
    /// transcription still runs, with `then` the tool to give its segments to.
    async fn heard(
        &self,
        path: &str,
        language: &str,
        timeout: Duration,
        progress: Option<&mut Progress>,
        cancel: &CancellationToken,
        then: &str,
    ) -> Result<Result<(Vec<Value>, Option<String>), CallToolResult>, ApiError> {
        let params = json!({ "path": path, "language": language });
        let (job, ran) = self.run_job("redub.transcribe", params, "redub.cancel", timeout, progress, cancel).await?;
        let Ran::Done(t) = ran else {
            let hint = format!("still transcribing: follow it with wait_job, then give its segments to {then}");
            return Ok(Err(still_running(&job, &hint)));
        };
        let lines = t["segments"].as_array().cloned().unwrap_or_default();
        let lines = lines
            .iter()
            .map(|s| {
                let mut line = json!({ "start": s["start"], "end": s["end"], "text": s["text"] });
                if s["words"].is_array() {
                    line["words"] = s["words"].clone();
                }
                line
            })
            .collect();
        Ok(Ok((lines, t["language"].as_str().map(str::to_string))))
    }

    async fn export_subtitles_inner(
        &self,
        args: ExportSubtitlesArgs,
        progress: Option<&mut Progress>,
        cancel: &CancellationToken,
    ) -> Result<CallToolResult, ApiError> {
        let format = args.format.unwrap_or_default().as_str();
        let dest = match (args.dest, &args.path) {
            (Some(dest), _) => dest,
            (None, Some(path)) => self.video_dest(&[path.as_str()], true, format).await?,
            (None, None) => return Err(ApiError::new("bad_request", "give path, or segments and dest")),
        };
        let mut summary = json!({ "transcribed": args.segments.is_none() });
        let segments: Vec<Value> = match (args.segments, &args.path) {
            (Some(given), _) => given.iter().map(|s| json!(s)).collect(),
            (None, Some(path)) => {
                let language = args.language.unwrap_or_else(|| "auto".into());
                let timeout = timeout_of(args.timeout_s, VIDEO_TIMEOUT_S);
                match self.heard(path, &language, timeout, progress, cancel, "export_subtitles").await? {
                    Ok((lines, lang)) => {
                        summary["language"] = json!(lang.unwrap_or(language));
                        summary["segments"] = json!(lines);
                        lines
                    }
                    Err(running) => return Ok(running),
                }
            }
            (None, None) => return Err(ApiError::new("bad_request", "give segments or path")),
        };
        if segments.is_empty() {
            return Err(ApiError::new("bad_request", "no speech was found in this file: no subtitles to save"));
        }
        let params = json!({ "format": format, "dest": dest, "segments": segments });
        let r = self.api.rpc("subtitles.export", params).await?;
        let path = r["path"].as_str().unwrap_or(&dest).to_string();
        for (key, value) in [
            ("path", json!(path)),
            ("uri", json!(file_uri(&path))),
            ("format", json!(format)),
            ("cues", r["cues"].clone()),
            ("size_bytes", r["size_bytes"].clone()),
        ] {
            summary[key] = value;
        }
        Ok(with_links(summary, &[&path]))
    }

    async fn subtitle_inner(
        &self,
        args: SubtitleVideoArgs,
        mut progress: Option<&mut Progress>,
        cancel: &CancellationToken,
    ) -> Result<CallToolResult, ApiError> {
        let deadline = tokio::time::Instant::now() + timeout_of(args.timeout_s, VIDEO_TIMEOUT_S);
        let left = || deadline.saturating_duration_since(tokio::time::Instant::now()).max(Duration::from_secs(1));
        let mut language = args.language.unwrap_or_else(|| "auto".into());
        let transcribed = args.segments.is_none();
        let segments: Vec<Value> = match args.segments {
            Some(given) => given.iter().map(|s| json!(s)).collect(),
            None => {
                if let Some(p) = progress.as_deref_mut() {
                    p.span = (0.0, 50.0);
                }
                let then = "subtitle_video";
                match self.heard(&args.path, &language, left(), progress.as_deref_mut(), cancel, then).await? {
                    Ok((lines, lang)) => {
                        language = lang.unwrap_or(language);
                        lines
                    }
                    Err(running) => return Ok(running),
                }
            }
        };
        if segments.is_empty() {
            return Err(ApiError::new("bad_request", "no speech was found in this file: nothing to subtitle"));
        }
        if let Some(p) = progress.as_deref_mut() {
            p.span = if transcribed { (50.0, 100.0) } else { (0.0, 100.0) };
        }
        let position = args.subtitle_position.unwrap_or_default().as_str();
        let mut params = json!({
            "path": args.path,
            "mode": "subtitles",
            "segments": segments,
            "language": language,
            "subtitle_position": position,
        });
        if let Some(images) = args.images {
            params["images"] = json!(images);
        }
        if args.transitions == Some(true) {
            params["transitions"] = json!(true);
        }
        if let Some(picture) = args.picture {
            params["picture"] = json!(picture);
        }
        let (job, ran) = self.run_job("redub.render", params, "redub.cancel", left(), progress, cancel).await?;
        let Ran::Done(r) = ran else {
            return Ok(still_running(&job, "still burning the subtitles in: follow it with wait_job"));
        };
        let video = r["video_path"].as_str().unwrap_or_default().to_string();
        let mut summary = json!({
            "job": job,
            "state": "done",
            "video_path": video,
            "uri": file_uri(&video),
            "path": r["path"],
            "language": r["language"],
            "duration_s": r["duration_s"],
            "subtitles_burned": r["subtitles_burned"],
            "subtitle_lines": r["subtitle_lines"],
            "transcribed": transcribed,
            "segments": segments,
        });
        if let Some(note) = r.get("subtitle_note") {
            summary["subtitle_note"] = note.clone();
        }
        Ok(with_links(summary, &[&video]))
    }

    async fn dub_inner(
        &self,
        args: DubVideoArgs,
        progress: Option<&mut Progress>,
        cancel: &CancellationToken,
    ) -> Result<CallToolResult, ApiError> {
        let voice = self.voice(args.voice.as_deref()).await?;
        let mut params = json!({
            "path": args.path,
            "voice_id": voice["id"],
            "output": "video",
            "subtitles": args.subtitles.unwrap_or(false),
            "subtitle_position": args.subtitle_position.unwrap_or_default().as_str(),
        });
        if let Some(lang) = args.target_language {
            params["target_language"] = json!(lang);
        }
        if let Some(lang) = args.source_language {
            params["source_language"] = json!(lang);
        }
        let timeout = timeout_of(args.timeout_s, VIDEO_TIMEOUT_S);
        let (job, ran) = self.run_job("redub.dub", params, "redub.cancel", timeout, progress, cancel).await?;
        let Ran::Done(r) = ran else {
            return Ok(still_running(&job, "still dubbing: follow it with wait_job"));
        };
        Ok(redub_answer(&job, Some(&voice), r, json!({})))
    }

    async fn keep_inner(&self, args: KeepTakeArgs) -> Result<Value, ApiError> {
        let listed = self.api.rpc("voices.design_takes", json!({})).await?;
        let takes = listed["takes"].as_array().cloned().unwrap_or_default();
        let take = takes.iter().find(|t| t["id"] == args.take.as_str()).ok_or_else(|| {
            ApiError::new("not_found", format!("no design take {:?}: see list_design_takes", args.take))
        })?;
        let params = json!({ "name": args.name, "reference_path": take["reference"], "language": take["language"] });
        self.api.rpc("voices.import", params).await
    }

    async fn delete_takes_inner(&self, args: DeleteTakesArgs) -> Result<Value, ApiError> {
        let params = match (args.take, args.all.unwrap_or(false)) {
            (_, true) => json!({ "all": true }),
            (Some(take), false) => json!({ "id": take }),
            (None, false) => return Err(ApiError::new("bad_request", "give a take id, or all: true")),
        };
        self.api.rpc("voices.design_delete", params).await
    }

    /// A voice by id or name, never a default: for the tools that change a voice.
    async fn named_voice(&self, wanted: &str) -> Result<Value, ApiError> {
        if wanted.trim().is_empty() {
            return Err(ApiError::new("bad_request", "give the voice's id or name (see list_voices)"));
        }
        self.voice(Some(wanted)).await
    }

    /// Record's "Use recordings you already have": `media.combine` of the files, then `dataset.add` as one new part.
    async fn add_recordings(
        &self,
        voice_id: &str,
        paths: &[String],
        remove_music: Option<bool>,
        detect: bool,
    ) -> Result<Value, ApiError> {
        let mut params = json!({ "paths": paths, "voice_id": voice_id });
        put(
            &mut params,
            [("language", detect.then(|| json!("auto"))), ("remove_music", remove_music.map(Value::from))],
        );
        let combined = self.api.rpc("media.combine", params).await?;
        let summary = self.api.rpc("dataset.summary", json!({ "voice_id": voice_id })).await?;
        let last = summary["parts"].as_array().into_iter().flatten().filter_map(|p| p["index"].as_u64()).max();
        let part = last.map_or(FILES_PART, |i| (i + 1).max(FILES_PART));
        let params = json!({ "voice_id": voice_id, "part_index": part, "path": combined["path"] });
        let added = self.api.rpc("dataset.add", params).await?;
        let mut out = json!({
            "part": added["part"],
            "recordings": added["summary"],
            "files": combined["files"],
            "skipped": combined["skipped"],
            "unused": combined["unused"],
            "music_removed": combined["music_removed"],
            "music_files": combined["music_files"],
        });
        put(
            &mut out,
            [
                ("music_reason", combined.get("music_reason").filter(|r| !r.is_null()).cloned()),
                ("language_heard", (combined["language_set"] == true).then(|| combined["language"].clone())),
            ],
        );
        Ok(out)
    }

    async fn create_voice_inner(&self, args: CreateVoiceArgs) -> Result<Value, ApiError> {
        let paths = args.paths.unwrap_or_default();
        match (args.bundle, paths.is_empty()) {
            (Some(bundle), true) => {
                let mut params = json!({ "bundle": bundle });
                put(&mut params, [("name", args.name.filter(|n| !n.trim().is_empty()).map(Value::from))]);
                let made = self.api.rpc("voices.import", params).await?;
                return Ok(json!({ "voice": made["voice"], "from": "bundle" }));
            }
            (None, false) => {}
            _ => return Err(ApiError::new("bad_request", "give either paths (recordings) or bundle")),
        }
        let name = args.name.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| stem_name(&paths[0]));
        let language = args.language.filter(|l| !l.trim().is_empty() && !l.eq_ignore_ascii_case("auto"));
        let params = json!({ "name": name, "language": language.as_deref().unwrap_or("en") });
        let created = self.api.rpc("voices.create", params).await?;
        let id = created["voice"]["id"].as_str().unwrap_or_default().to_string();
        let mut out = match self.add_recordings(&id, &paths, args.remove_music, language.is_none()).await {
            Ok(out) => out,
            Err(e) => {
                let _ = self.api.rpc("voices.delete", json!({ "id": id })).await;
                return Err(e);
            }
        };
        let voices = self.voices().await?;
        out["voice"] = voices.into_iter().find(|v| v["id"] == id.as_str()).unwrap_or_else(|| created["voice"].clone());
        Ok(out)
    }

    async fn manage_voice_inner(&self, args: ManageVoiceArgs) -> Result<CallToolResult, ApiError> {
        let voice = self.named_voice(&args.voice).await?;
        let id = voice["id"].clone();
        match args.action {
            VoiceAction::Rename => {
                if args.name.is_none() && args.language.is_none() {
                    return Err(ApiError::new("bad_request", "rename needs a name, a language or both"));
                }
                let mut params = json!({ "id": id });
                put(&mut params, [("name", args.name.map(Value::from)), ("language", args.language.map(Value::from))]);
                Ok(ok(self.api.rpc("voices.rename", params).await?))
            }
            VoiceAction::Delete => {
                self.api.rpc("voices.delete", json!({ "id": id })).await?;
                Ok(ok(json!({ "deleted": id, "name": voice["name"] })))
            }
            VoiceAction::Export => {
                let mut params = json!({ "id": id });
                put(&mut params, [("dest", args.dest.map(Value::from))]);
                let mut bundle = self.api.rpc("voices.export", params).await?;
                let path = bundle["path"].as_str().unwrap_or_default().to_string();
                bundle["uri"] = json!(file_uri(&path));
                Ok(with_links(bundle, &[&path]))
            }
        }
    }

    async fn recordings_inner(&self, args: VoiceRecordingsArgs) -> Result<Value, ApiError> {
        let voice = self.named_voice(&args.voice).await?;
        let id = voice["id"].as_str().unwrap_or_default();
        let mut out = match args.action.unwrap_or_default() {
            RecordingsAction::List => self.api.rpc("dataset.summary", json!({ "voice_id": id })).await?,
            RecordingsAction::Add => {
                let paths = args.paths.filter(|p| !p.is_empty());
                let paths = paths.ok_or_else(|| ApiError::new("bad_request", "add needs paths: the recordings"))?;
                self.add_recordings(id, &paths, args.remove_music, true).await?
            }
            RecordingsAction::Remove => {
                let part = args.part.ok_or_else(|| ApiError::new("bad_request", "remove needs part: its index"))?;
                let params = json!({ "voice_id": id, "part_index": part });
                self.api.rpc("dataset.remove", params).await?
            }
        };
        out["voice"] = voice["name"].clone();
        out["voice_id"] = voice["id"].clone();
        Ok(out)
    }

    /// The given job, else the training that runs (the engine trains one voice at a time).
    async fn training_job(&self, given: Option<String>) -> Result<String, ApiError> {
        if let Some(job) = given.filter(|j| !j.trim().is_empty()) {
            return Ok(job);
        }
        let _ = self.events.ready(Duration::from_secs(2)).await;
        self.events.running("train.").map(|s| s.job).ok_or_else(|| ApiError::new("not_found", "no training is running"))
    }

    async fn train_inner(&self, args: TrainVoiceArgs) -> Result<Value, ApiError> {
        let voice = self.named_voice(&args.voice).await?;
        let id = voice["id"].clone();
        let action = args.action.unwrap_or_default();
        match action {
            TrainAction::Start | TrainAction::Resume => {
                self.events_ready().await?;
                let (method, params) = match action {
                    TrainAction::Resume => ("train.resume", json!({ "voice_id": id })),
                    _ => {
                        let mut params = json!({ "voice_id": id, "epochs": args.epochs });
                        put(&mut params, [("restart", args.restart.map(Value::from))]);
                        ("train.start", params)
                    }
                };
                let started = self.api.rpc(method, params).await?;
                let job = started["job"].as_str().unwrap_or_default().to_string();
                self.events.started(&job, method);
                Ok(json!({
                    "job": job,
                    "state": "running",
                    "voice": voice["name"],
                    "voice_id": id,
                    "message": "training in the background (minutes to hours): follow it with wait_job (progress per \
                                epoch) or status; Speak, Design and Redub answer not_ready until it ends",
                }))
            }
            TrainAction::Pause => {
                let job = self.training_job(args.job).await?;
                let paused = self.api.rpc("train.pause", json!({ "job": job })).await?;
                Ok(json!({
                    "job": job,
                    "pausing": paused["pausing"],
                    "message": "it stops at the next checkpoint (at most 5 epochs): wait_job then answers paused, and \
                                resume goes on from there",
                }))
            }
            TrainAction::Cancel => match self.training_job(args.job).await {
                Ok(job) => {
                    self.api.rpc("train.cancel", json!({ "job": job })).await?;
                    Ok(json!({ "job": job, "cancelled": true }))
                }
                Err(_) if !voice["training_paused"].is_null() => {
                    self.api.rpc("train.cancel", json!({ "voice_id": id })).await?;
                    Ok(json!({ "voice": voice["name"], "voice_id": id, "discarded": true }))
                }
                Err(_) => Err(ApiError::new(
                    "not_found",
                    format!(
                        "no training is running, and {} has no paused one",
                        voice["name"].as_str().unwrap_or("the voice")
                    ),
                )),
            },
            TrainAction::Status => {
                let summary = self.api.rpc("dataset.summary", json!({ "voice_id": id })).await?;
                let running = self.events.running("train.");
                Ok(json!({
                    "voice": voice["name"],
                    "voice_id": id,
                    "trained": voice["trained"],
                    "trained_epochs": voice["trained_epochs"],
                    "trained_at": voice["trained_at"],
                    "training_paused": voice["training_paused"],
                    "usable_minutes": summary["usable_minutes"],
                    "level": summary["level"],
                    "recommended_epochs": summary["recommended_epochs"],
                    "message": summary["message"],
                    "running": running.map(|s| json!({ "job": s.job, "progress": s.progress })),
                }))
            }
        }
    }

    async fn transcribe_inner(
        &self,
        args: TranscribeArgs,
        progress: Option<&mut Progress>,
        cancel: &CancellationToken,
    ) -> Result<CallToolResult, ApiError> {
        let mut params = json!({ "path": args.path, "language": args.language.unwrap_or_else(|| "auto".into()) });
        put(&mut params, [("translate_to", args.translate_to.map(Value::from))]);
        let timeout = timeout_of(args.timeout_s, VIDEO_TIMEOUT_S);
        let (job, ran) = self.run_job("redub.transcribe", params, "redub.cancel", timeout, progress, cancel).await?;
        let Ran::Done(mut t) = ran else {
            return Ok(still_running(&job, "still transcribing: follow it with wait_job"));
        };
        if !args.include_words.unwrap_or(false) {
            for s in t["segments"].as_array_mut().into_iter().flatten() {
                if let Some(obj) = s.as_object_mut() {
                    obj.remove("words");
                }
            }
        }
        t["job"] = json!(job);
        t["state"] = json!("done");
        Ok(ok(t))
    }

    async fn respeak_inner(
        &self,
        args: RespeakArgs,
        mut progress: Option<&mut Progress>,
        cancel: &CancellationToken,
    ) -> Result<CallToolResult, ApiError> {
        let voice = self.voice(args.voice.as_deref()).await?;
        let deadline = tokio::time::Instant::now() + timeout_of(args.timeout_s, VIDEO_TIMEOUT_S);
        let left = || deadline.saturating_duration_since(tokio::time::Instant::now()).max(Duration::from_secs(1));
        let output = args.output.unwrap_or(if is_video(&args.path) { Output::Video } else { Output::Audio });
        let mut params = json!({ "voice_id": voice["id"], "path": args.path, "mode": "respeak", "output": output });
        let transcribed = args.segments.is_none();
        let segments: Vec<Value> = match args.segments {
            Some(given) => {
                let language = args.language.filter(|l| !l.eq_ignore_ascii_case("auto"));
                put(&mut params, [("language", language.map(Value::from))]);
                given.iter().map(|s| json!(s)).collect()
            }
            None => {
                if let Some(p) = progress.as_deref_mut() {
                    p.span = (0.0, 30.0);
                }
                let language = args.language.unwrap_or_else(|| "auto".into());
                let mut asked = json!({ "path": args.path, "language": language });
                put(&mut asked, [("translate_to", args.translate_to.map(Value::from))]);
                let (job, ran) = self
                    .run_job("redub.transcribe", asked, "redub.cancel", left(), progress.as_deref_mut(), cancel)
                    .await?;
                let Ran::Done(t) = ran else {
                    return Ok(still_running(
                        &job,
                        "still transcribing: follow it with wait_job, then give its segments to respeak",
                    ));
                };
                let translated = t["translated"] == true;
                if translated {
                    params["language"] = t["target_language"].clone();
                    params["translated"] = json!(true);
                    params["target_language"] = t["target_language"].clone();
                } else {
                    params["language"] = t["language"].clone();
                }
                let lines = t["segments"].as_array().cloned().unwrap_or_default();
                lines
                    .iter()
                    .map(|s| {
                        let mut line = json!({ "start": s["start"], "end": s["end"], "text": s["text"] });
                        if !translated && s["words"].is_array() {
                            line["words"] = s["words"].clone();
                        }
                        line
                    })
                    .collect()
            }
        };
        if segments.is_empty() {
            return Err(ApiError::new("bad_request", "no speech was found in this file: nothing to re-speak"));
        }
        if let Some(p) = progress.as_deref_mut() {
            p.span = if transcribed { (30.0, 100.0) } else { (0.0, 100.0) };
        }
        params["segments"] = json!(segments);
        put(
            &mut params,
            [
                ("speed", args.speed.map(Value::from)),
                ("timing", args.timing.map(|t| json!(t))),
                ("keep_background", args.keep_background.map(Value::from)),
                ("subtitles", args.subtitles.map(Value::from)),
                ("subtitle_position", args.subtitle_position.map(|p| json!(p.as_str()))),
                ("output_format", args.format.map(|f| json!(f.as_str()))),
                ("model", args.model.map(Value::from)),
            ],
        );
        let (job, ran) = self.run_job("redub.render", params, "redub.cancel", left(), progress, cancel).await?;
        let Ran::Done(r) = ran else {
            return Ok(still_running(&job, "still speaking: follow it with wait_job"));
        };
        let extra = if transcribed {
            json!({ "transcribed": true, "segments": segments })
        } else {
            json!({ "transcribed": false })
        };
        Ok(redub_answer(&job, Some(&voice), r, extra))
    }

    async fn convert_inner(
        &self,
        args: ConvertVoiceArgs,
        progress: Option<&mut Progress>,
        cancel: &CancellationToken,
    ) -> Result<CallToolResult, ApiError> {
        let voice = self.voice(args.voice.as_deref()).await?;
        let output = args.output.unwrap_or(if is_video(&args.path) { Output::Video } else { Output::Audio });
        let mut params = json!({ "voice_id": voice["id"], "path": args.path, "mode": "convert", "output": output });
        put(
            &mut params,
            [
                ("voice_match", args.voice_match.map(Value::from)),
                ("keep_background", args.keep_background.map(Value::from)),
                ("output_format", args.format.map(|f| json!(f.as_str()))),
            ],
        );
        let timeout = timeout_of(args.timeout_s, VIDEO_TIMEOUT_S);
        let (job, ran) = self.run_job("redub.render", params, "redub.cancel", timeout, progress, cancel).await?;
        let Ran::Done(r) = ran else {
            return Ok(still_running(&job, "still converting: follow it with wait_job"));
        };
        Ok(redub_answer(&job, Some(&voice), r, json!({})))
    }

    async fn export_audio_inner(&self, args: ExportAudioArgs) -> Result<CallToolResult, ApiError> {
        let mut params = json!({ "path": args.path, "format": args.format.as_str() });
        put(&mut params, [("quality", args.quality.map(|q| json!(q))), ("dest", args.dest.map(Value::from))]);
        let r = self.api.rpc("audio.export", params).await?;
        let path = r["path"].as_str().unwrap_or_default().to_string();
        let summary = json!({
            "path": path,
            "uri": file_uri(&path),
            "format": args.format.as_str(),
            "size_bytes": r["size_bytes"],
        });
        Ok(with_links(summary, &[&path]))
    }

    async fn list_results_inner(&self, args: ListResultsArgs) -> Result<Value, ApiError> {
        let mut params = json!({ "limit": args.limit.unwrap_or(20).clamp(1, 500) });
        put(&mut params, [("kind", args.kind.map(|k| json!(k))), ("before", args.before.map(Value::from))]);
        let mut list = self.api.rpc("outputs.list", params).await?;
        for entry in list["results"].as_array_mut().into_iter().flatten() {
            for (key, uri) in [("path", "uri"), ("video_path", "video_uri")] {
                if let Some(path) = entry[key].as_str().map(file_uri) {
                    entry[uri] = json!(path);
                }
            }
        }
        Ok(list)
    }

    /// A file of the API, unless it is larger than `max`.
    async fn fetch(&self, path: &str, max: u64) -> Result<Fetched, ApiError> {
        let res = self.api.download(path).await?;
        if let Some(len) = res.content_length().filter(|n| *n > max) {
            return Ok(Fetched::TooLarge(Some(len)));
        }
        let mut bytes = Vec::new();
        let mut stream = res.bytes_stream();
        while let Some(chunk) = stream.next().await {
            let chunk = chunk.map_err(|e| ApiError::new("http_error", format!("reading {path}: {e}")))?;
            if (bytes.len() + chunk.len()) as u64 > max {
                return Ok(Fetched::TooLarge(None));
            }
            bytes.extend_from_slice(&chunk);
        }
        Ok(Fetched::Bytes(bytes))
    }

    async fn book_text(
        &self,
        path: Option<String>,
        chapters: Option<Vec<Chapter>>,
        indexes: Option<&[usize]>,
    ) -> Result<BookText, ApiError> {
        let mut text = BookText::default();
        text.chapters = match (path, chapters) {
            (Some(path), None) => {
                let doc = self.api.rpc("text.import", json!({ "path": path, "language": "auto" })).await?;
                text.language = doc["language"].as_str().map(str::to_string);
                text.title = doc["title"].as_str().filter(|t| !t.is_empty()).map(str::to_string);
                text.title = text.title.or_else(|| doc["name"].as_str().map(str::to_string));
                text.source = Some((doc["path"].clone(), doc["format"].clone()));
                let all = doc["chapters"].as_array().cloned().unwrap_or_default();
                let picked = match indexes {
                    Some(idx) => idx.iter().filter_map(|i| all.get(*i).cloned()).collect(),
                    None => all,
                };
                picked.into_iter().map(|c| json!({ "title": c["title"], "text": c["text"] })).collect()
            }
            (None, Some(chapters)) => {
                chapters.into_iter().map(|c| json!({ "title": c.title, "text": c.text })).collect()
            }
            _ => return Err(ApiError::new("bad_request", "give either path or chapters")),
        };
        if text.chapters.is_empty() {
            return Err(ApiError::new("bad_request", "no chapters to read"));
        }
        Ok(text)
    }

    async fn start_book_inner(&self, args: StartBookArgs) -> Result<Value, ApiError> {
        let mut params = Map::new();
        let text = self.book_text(args.path, args.chapters, args.chapter_indexes.as_deref()).await?;
        if let Some((source, format)) = text.source {
            params.insert("source".into(), source);
            params.insert("format".into(), format);
        }
        let voice = self.voice(args.voice.as_deref()).await?;
        let mut voices = Map::new();
        for (role, wanted) in [("men", args.men_voice), ("women", args.women_voice)] {
            if let Some(w) = wanted.filter(|w| !w.trim().is_empty()) {
                voices.insert(role.into(), self.voice(Some(&w)).await?["id"].clone());
            }
        }
        params.insert("title".into(), json!(args.title.or(text.title).unwrap_or_else(|| "Untitled".into())));
        params.insert("chapters".into(), json!(text.chapters));
        params.insert("voice_id".into(), voice["id"].clone());
        if let Some(lang) = args.language.or(text.language).or_else(|| voice["language"].as_str().map(str::to_string)) {
            params.insert("language".into(), json!(lang));
        }
        let optional = [
            ("output_format", args.format.map(|f| json!(f.as_str()))),
            ("m4b", args.m4b.map(Value::from)),
            ("read_titles", args.read_titles.map(Value::from)),
            ("speed", args.speed.map(Value::from)),
            ("expressiveness", args.expressiveness.map(Value::from)),
            ("quality", args.quality.map(|q| json!(if matches!(q, Quality::Fast) { "fast" } else { "best" }))),
            ("model", args.model.map(Value::from)),
            ("voices", Some(Value::Object(voices)).filter(|v| v.as_object().is_some_and(|m| !m.is_empty()))),
            ("cast", args.cast.map(|c| json!(c.as_str()))),
        ];
        for (key, value) in optional {
            if let Some(v) = value {
                params.insert(key.into(), v);
            }
        }
        let mut started = self.api.rpc("book.start", Value::Object(params)).await?;
        started["voice"] = voice["name"].clone();
        Ok(started)
    }

    async fn find_speakers_inner(
        &self,
        args: FindSpeakersArgs,
        progress: Option<&mut Progress>,
        cancel: &CancellationToken,
    ) -> Result<CallToolResult, ApiError> {
        let text = self.book_text(args.path, args.chapters, args.chapter_indexes.as_deref()).await?;
        let mut params = json!({ "chapters": text.chapters });
        put(
            &mut params,
            [
                ("language", args.language.or(text.language).map(Value::from)),
                ("cast", args.cast.map(|c| json!(c.as_str()))),
                ("again", args.again.map(Value::from)),
            ],
        );
        self.events_ready().await?;
        let mut found = self.api.rpc("book.cast", params).await?;
        let Some(job) = found["job"].as_str().map(str::to_string) else {
            found["state"] = json!("done");
            return Ok(ok(found));
        };
        let timeout = timeout_of(args.timeout_s, VIDEO_TIMEOUT_S);
        let Ran::Done(mut found) = self.follow(&job, "book.cast_cancel", timeout, progress, cancel).await? else {
            return Ok(still_running(&job, "still finding the speakers: follow it with wait_job"));
        };
        found["job"] = json!(job);
        found["state"] = json!("done");
        Ok(ok(found))
    }

    async fn download_inner(&self, args: DownloadArgs) -> Result<Value, ApiError> {
        let name = file_name(&args.path);
        if name.is_empty() {
            return Err(ApiError::new("bad_request", "path names no file"));
        }
        let dest = match args.dest.map(PathBuf::from) {
            Some(d) if d.is_dir() => d.join(name),
            Some(d) => d,
            None => dirs::download_dir().unwrap_or_else(std::env::temp_dir).join(name),
        };
        if dest.exists() && !args.overwrite.unwrap_or(false) {
            return Err(ApiError::new(
                "exists",
                format!("{} already exists: pass overwrite or another dest", dest.display()),
            ));
        }
        let res = self.api.download(&args.path).await?;
        let size = write_stream(res, &dest).await?;
        Ok(json!({ "path": dest.display().to_string(), "size_bytes": size }))
    }

    async fn upload_inner(&self, args: UploadArgs) -> Result<Value, ApiError> {
        let local = Path::new(&args.local_path);
        if !local.is_file() {
            return Err(ApiError::new("not_found", format!("no file {}", local.display())));
        }
        self.api.upload(local).await
    }

    async fn resources(&self) -> Result<Vec<Resource>, ApiError> {
        let list = self.api.rpc("outputs.list", json!({ "limit": RESOURCE_LIST_LIMIT })).await?;
        let mut out = Vec::new();
        for entry in list["results"].as_array().into_iter().flatten() {
            let what = match entry["kind"].as_str() {
                Some("redub") => "Redub result",
                _ => "Speech",
            };
            let mut about = vec![what.to_string()];
            if let Some(v) = entry["voice_name"].as_str() {
                about.push(format!("voice {v}"));
            }
            if let Some(d) = entry["duration_s"].as_f64() {
                about.push(format!("{d:.1} s"));
            }
            if let Some(t) = entry["text"].as_str() {
                let short: String = t.chars().take(120).collect();
                about.push(format!("\"{short}{}\"", if short.len() < t.len() { "..." } else { "" }));
            }
            for key in ["path", "video_path"] {
                if let Some(path) = entry[key].as_str() {
                    out.push(
                        Resource::new(file_uri(path), file_name(path))
                            .with_mime_type(mime_for(path))
                            .with_description(about.join(", ")),
                    );
                }
            }
        }
        Ok(out)
    }
}

enum Fetched {
    Bytes(Vec<u8>),
    TooLarge(Option<u64>),
}

async fn write_stream(res: reqwest::Response, dest: &Path) -> Result<u64, ApiError> {
    let io = |e: std::io::Error| ApiError::new("io_error", format!("{}: {e}", dest.display()));
    let part = dest.with_file_name(format!("{}.part", dest.file_name().unwrap_or_default().to_string_lossy()));
    let mut file = tokio::fs::File::create(&part).await.map_err(io)?;
    let mut size = 0u64;
    let mut stream = res.bytes_stream();
    while let Some(chunk) = stream.next().await {
        let chunk = match chunk {
            Ok(c) => c,
            Err(e) => {
                drop(file);
                let _ = tokio::fs::remove_file(&part).await;
                return Err(ApiError::new("http_error", format!("download interrupted: {e}")));
            }
        };
        file.write_all(&chunk).await.map_err(io)?;
        size += chunk.len() as u64;
    }
    file.sync_all().await.map_err(io)?;
    drop(file);
    tokio::fs::rename(&part, dest).await.map_err(io)?;
    Ok(size)
}

#[tool_router]
impl Mimvox {
    #[tool(description = ENGINE_CALL)]
    async fn engine_call(&self, Parameters(args): Parameters<EngineCallArgs>) -> Result<CallToolResult, ErrorData> {
        let params = args.params.map(Value::Object).unwrap_or_else(|| json!({}));
        Ok(reply(self.api.rpc(&args.method, params).await))
    }

    #[tool(
        description = "List the cloned voices: id, name, language (the one it was recorded in), dataset minutes, \
                       whether it is trained, per-language reference clips.",
        annotations(read_only_hint = true)
    )]
    async fn list_voices(&self) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.api.rpc("voices.list", json!({})).await))
    }

    #[tool(description = "Speak text in a cloned voice and wait for the result. Saves the audio in Mimvox's outputs \
                          (it shows in the app's Results) and returns its path and a mimvox://file/ link, plus the \
                          audio itself when it is at most 4 MB. Long texts can take minutes; progress is reported \
                          per segment. Use only the user's own voice or one they have permission to use.")]
    async fn speak(
        &self,
        Parameters(args): Parameters<SpeakArgs>,
        meta: RequestMetaObject,
        peer: Peer<RoleServer>,
        cancel: CancellationToken,
    ) -> Result<CallToolResult, ErrorData> {
        let mut progress = Progress::new(&meta, peer);
        Ok(self.speak_inner(args, progress.as_mut(), &cancel).await.unwrap_or_else(|e| fail(&e)))
    }

    #[tool(
        description = "Read a document (txt, md, html, epub, docx, odt, rtf, fb2, pdf, srt, vtt) on the API's \
                       machine into chapters: title, detected language, words, estimated reading time per chapter, \
                       metadata and a suggested split of long chapters. Use it before start_book to pick chapters.",
        annotations(read_only_hint = true)
    )]
    async fn import_text(&self, Parameters(args): Parameters<ImportTextArgs>) -> Result<CallToolResult, ErrorData> {
        let mut params = json!({ "path": args.path });
        if let Some(lang) = args.language {
            params["language"] = json!(lang);
        }
        let res = self.api.rpc("text.import", params).await;
        Ok(reply(if args.include_text.unwrap_or(false) { res } else { res.map(without_texts) }))
    }

    #[tool(description = "Start reading an audiobook: a document (path) or given chapters, one audio file per \
                          chapter in <data>/outputs/books/<title>/, in one voice or with men_voice and women_voice \
                          reading the characters' lines. Returns the book id and its job; follow it with \
                          wait_job (progress in percent) or book_status. Only one generation runs at a time: while \
                          a book is read, speak answers busy until it is paused.")]
    async fn start_book(&self, Parameters(args): Parameters<StartBookArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.start_book_inner(args).await))
    }

    #[tool(description = "Find who speaks each line of a book before it is read (Character voices component, a \
                          local model): the narrator, the speaking characters with gender and lines, how many lines \
                          the men's, the women's voice and the narrator read, and a design_voice description for a \
                          voice of each role. Waits with progress; the result is kept, so start_book of the same \
                          chapters, language and cast uses it at once. Cancelling the call stops the search.")]
    async fn find_speakers(
        &self,
        Parameters(args): Parameters<FindSpeakersArgs>,
        meta: RequestMetaObject,
        peer: Peer<RoleServer>,
        cancel: CancellationToken,
    ) -> Result<CallToolResult, ErrorData> {
        let mut progress = Progress::new(&meta, peer);
        Ok(self.find_speakers_inner(args, progress.as_mut(), &cancel).await.unwrap_or_else(|e| fail(&e)))
    }

    #[tool(
        description = "One book's status (percent, chapters done, time left, chapter files) or, without id, every \
                       book.",
        annotations(read_only_hint = true)
    )]
    async fn book_status(&self, Parameters(args): Parameters<BookStatusArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(reply(match args.id {
            Some(id) => self.api.rpc("book.get", json!({ "id": id })).await,
            None => self.api.rpc("book.list", json!({})).await,
        }))
    }

    #[tool(description = "Pause a book that is being read (it can be resumed later, also after a restart).")]
    async fn pause_book(&self, Parameters(args): Parameters<BookIdArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.api.rpc("book.pause", json!({ "id": args.id })).await))
    }

    #[tool(description = "Resume a paused, failed or cancelled book from where it stopped. Returns its new job.")]
    async fn resume_book(&self, Parameters(args): Parameters<BookIdArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.api.rpc("book.resume", json!({ "id": args.id })).await))
    }

    #[tool(
        description = "The latest known state of a background job (speech, book, training, Redub, reference from \
                       media) as seen by this server since it started: running, done, paused or error, with its \
                       latest progress and its result.",
        annotations(read_only_hint = true)
    )]
    async fn job_status(&self, Parameters(args): Parameters<JobArgs>) -> Result<CallToolResult, ErrorData> {
        let _ = self.events.ready(Duration::from_secs(2)).await;
        Ok(match self.events.job(&args.job) {
            Some(st) => ok(json!(st)),
            None => ok(json!({
                "job": args.job,
                "state": "unknown",
                "connected": self.events.is_connected(),
                "message": "no event of this job since this server started; it may not have reported yet, or it \
                            ended earlier (for a book use book_status)",
            })),
        })
    }

    #[tool(
        description = "Wait until a background job ends (done, paused or error) and return its result, sending \
                       progress notifications meanwhile. On timeout the job keeps running and the answer says so.",
        annotations(read_only_hint = true)
    )]
    async fn wait_job(
        &self,
        Parameters(args): Parameters<WaitJobArgs>,
        meta: RequestMetaObject,
        peer: Peer<RoleServer>,
        cancel: CancellationToken,
    ) -> Result<CallToolResult, ErrorData> {
        if let Err(e) = self.events_ready().await {
            return Ok(fail(&e));
        }
        let mut progress = Progress::new(&meta, peer);
        let timeout = timeout_of(args.timeout_s, WAIT_TIMEOUT_S);
        Ok(match self.wait(&args.job, timeout, progress.as_mut(), None, &cancel).await {
            Waited::Ended(st) if st.state == State::Error => {
                let r = st.result.clone().unwrap_or(Value::Null);
                let e = ApiError::new(
                    r["code"].as_str().unwrap_or("internal"),
                    r["message"].as_str().unwrap_or("the job failed"),
                );
                let mut res = fail(&e);
                res.structured_content = Some(json!({ "error": e.to_json(), "job": st }));
                res
            }
            Waited::Ended(st) => ok(json!(st)),
            Waited::TimedOut(st) => ok(json!({
                "job": args.job,
                "state": "running",
                "timed_out": true,
                "progress": st.and_then(|s| s.progress),
            })),
            Waited::Cancelled => fail(&ApiError::new("cancelled", "the wait was cancelled (the job goes on)")),
        })
    }

    #[tool(description = "Make a new voice with no recording, from a description, and hear it say the text. Waits \
                          for the take (seconds; VoxCPM2's first load adds about 15 s) and returns its id, path, a \
                          mimvox://file/ link and, up to 4 MB, the audio. Every take is kept (the last 40); \
                          keep_design_take saves one as a voice for speak. Each call makes a different person. \
                          Cancelling the call stops the take.")]
    async fn design_voice(
        &self,
        Parameters(args): Parameters<DesignArgs>,
        cancel: CancellationToken,
    ) -> Result<CallToolResult, ErrorData> {
        Ok(self.design_inner(args, &cancel).await.unwrap_or_else(|e| fail(&e)))
    }

    #[tool(
        description = "List the takes design_voice made, newest first: id, when, model, language, description, \
                       text, duration, whether Whisper heard the text clearly, and the paths of the clip and the \
                       designed voice.",
        annotations(read_only_hint = true)
    )]
    async fn list_design_takes(&self) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.api.rpc("voices.design_takes", json!({})).await))
    }

    #[tool(description = "Keep a design take as a voice under the given name (voices.import of its designed voice, \
                          in its language); the voice is then used like any other in speak and Redub.")]
    async fn keep_design_take(&self, Parameters(args): Parameters<KeepTakeArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.keep_inner(args).await))
    }

    #[tool(description = "Delete one design take, or every take with all: true; voices kept from them stay. \
                          Returns the takes left.")]
    async fn delete_design_take(
        &self,
        Parameters(args): Parameters<DeleteTakesArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.delete_takes_inner(args).await))
    }

    #[tool(description = "Make a video on the API's machine of one result (path) or of several audio files joined \
                          into one (parts: an episode of book chapters, each part's picture shown from its start and \
                          its subtitles from segments or segments_path, a book chapter's segment file). Waits for \
                          video.done (an hour of audio takes well under a minute) and returns the path, a \
                          mimvox://file/ link, the length, where each part starts (seconds; for chapter marks) and \
                          the subtitles made. Cancelling the call stops the export.")]
    async fn export_video(
        &self,
        Parameters(args): Parameters<ExportVideoArgs>,
        meta: RequestMetaObject,
        peer: Peer<RoleServer>,
        cancel: CancellationToken,
    ) -> Result<CallToolResult, ErrorData> {
        let mut progress = Progress::new(&meta, peer);
        Ok(self.export_inner(args, progress.as_mut(), &cancel).await.unwrap_or_else(|e| fail(&e)))
    }

    #[tool(description = "Burn subtitles into a video with its own sound (Redub's Subtitle video): \
                          transcribes it (redub.transcribe) unless segments are given, then redub.render mode \
                          subtitles; images put pictures over the sound (fading with transitions). Returns the video's path, a \
                          mimvox://file/ link and the lines used; the video and its sound are saved as a Redub \
                          result. Cancelling the call stops the job.")]
    async fn subtitle_video(
        &self,
        Parameters(args): Parameters<SubtitleVideoArgs>,
        meta: RequestMetaObject,
        peer: Peer<RoleServer>,
        cancel: CancellationToken,
    ) -> Result<CallToolResult, ErrorData> {
        let mut progress = Progress::new(&meta, peer);
        Ok(self.subtitle_inner(args, progress.as_mut(), &cancel).await.unwrap_or_else(|e| fail(&e)))
    }

    #[tool(description = "Save timed lines as a subtitle file to upload to YouTube or open in a player, instead of \
                          burning them in: SRT (default), WebVTT or SBV, cut into cues as subtitle_video draws them. \
                          The lines are the given segments (such as transcribe's, with their words), or path \
                          transcribed first (redub.transcribe); then subtitles.export. Returns the file's path, a \
                          mimvox://file/ link, the number of cues and, when transcribed, the segments. Cancelling \
                          the call stops the transcription.")]
    async fn export_subtitles(
        &self,
        Parameters(args): Parameters<ExportSubtitlesArgs>,
        meta: RequestMetaObject,
        peer: Peer<RoleServer>,
        cancel: CancellationToken,
    ) -> Result<CallToolResult, ErrorData> {
        let mut progress = Progress::new(&meta, peer);
        Ok(self.export_subtitles_inner(args, progress.as_mut(), &cancel).await.unwrap_or_else(|e| fail(&e)))
    }

    #[tool(description = "Translate a video's speech and dub it in a voice (Redub's Translate & dub, redub.dub with \
                          output video): the new voice over the original music and sounds, optionally with the \
                          translated text drawn in. Waits for redub.done (minutes) and returns the paths of the \
                          video and its audio with mimvox://file/ links. Use only the user's own voice or one they \
                          have permission to use. Cancelling the call stops the job.")]
    async fn dub_video(
        &self,
        Parameters(args): Parameters<DubVideoArgs>,
        meta: RequestMetaObject,
        peer: Peer<RoleServer>,
        cancel: CancellationToken,
    ) -> Result<CallToolResult, ErrorData> {
        let mut progress = Progress::new(&meta, peer);
        Ok(self.dub_inner(args, progress.as_mut(), &cancel).await.unwrap_or_else(|e| fail(&e)))
    }

    #[tool(description = "Make a new voice from recordings of one speaker (Record's \"Use recordings you already \
                          have\"): audio or video files on the API's machine are cleaned (background music removed \
                          from videos when a GPU is there), joined (up to 20 minutes) and kept as the voice's \
                          recordings; the best clip becomes its reference and, unless language is given, the \
                          language spoken is heard in them. Answers the voice, which speaks at once (speak), and its \
                          recordings; more of them (voice_recordings add) make it closer, and from about 3 minutes \
                          train_voice trains it. With bundle instead, imports a voice bundle (.mimvoice). Only the \
                          user's own voice or one whose owner gave explicit permission.")]
    async fn create_voice(&self, Parameters(args): Parameters<CreateVoiceArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.create_voice_inner(args).await))
    }

    #[tool(
        description = "Rename a voice (a new name, or the language it was recorded in), delete it with its \
                       recordings, reference and training, or export it as a voice bundle (.mimvoice: what it needs \
                       to speak on another computer, which create_voice with bundle imports). export answers the \
                       bundle's path with a mimvox://file/ link for download_file.",
        annotations(destructive_hint = true)
    )]
    async fn manage_voice(&self, Parameters(args): Parameters<ManageVoiceArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(self.manage_voice_inner(args).await.unwrap_or_else(|e| fail(&e)))
    }

    #[tool(description = "A voice's recordings, its training data. list (default): each part's length and verdict, \
                          the usable minutes, the level (too_short, zero_shot, trainable from 3 minutes, great from \
                          10), the recommended training epochs and the reference clip. add: more recordings of the \
                          speaker (audio or video files, cleaned and joined into one new part; the reference is \
                          picked again). remove: one part, by its index.")]
    async fn voice_recordings(
        &self,
        Parameters(args): Parameters<VoiceRecordingsArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.recordings_inner(args).await))
    }

    #[tool(description = "Train a voice's own voice-conversion model (RVC) from its recordings, for a closer \
                          likeness; it needs about 3 usable minutes (voice_recordings list). start answers at once \
                          with the job: training takes minutes to hours, and Speak, Design and Redub answer not_ready \
                          until it ends; follow it with wait_job (progress per epoch) or status. pause stops at the \
                          next checkpoint and resume goes on from there, also after a restart. cancel stops the \
                          training that runs (one runs at a time) or, when none does, discards this voice's paused \
                          one. status: whether the voice is trained, a paused run, the usable minutes, the \
                          recommended epochs and the progress of the training that runs.")]
    async fn train_voice(&self, Parameters(args): Parameters<TrainVoiceArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.train_inner(args).await))
    }

    #[tool(description = "Transcribe the speech of an audio or video file on the API's machine (Whisper), \
                          optionally translated: the language and the lines, each with start and end in seconds (and \
                          its original text when translated). Waits for the transcript, with progress. Edit the lines \
                          and give them to respeak or subtitle_video. Cancelling the call stops the job.")]
    async fn transcribe(
        &self,
        Parameters(args): Parameters<TranscribeArgs>,
        meta: RequestMetaObject,
        peer: Peer<RoleServer>,
        cancel: CancellationToken,
    ) -> Result<CallToolResult, ErrorData> {
        let mut progress = Progress::new(&meta, peer);
        Ok(self.transcribe_inner(args, progress.as_mut(), &cancel).await.unwrap_or_else(|e| fail(&e)))
    }

    #[tool(description = "Speak a file's speech again in a voice, each line at its original time (Redub's \
                          Re-speak): the given segments (transcribe's lines, edited), else the file is transcribed \
                          first and, with translate_to, translated. A video source gives a video with the new voice \
                          over its original music and sounds (output audio: the sound alone). Waits for redub.done \
                          (minutes) and returns the paths with mimvox://file/ links. Use only the user's own voice or \
                          one they have permission to use. Cancelling the call stops the job.")]
    async fn respeak(
        &self,
        Parameters(args): Parameters<RespeakArgs>,
        meta: RequestMetaObject,
        peer: Peer<RoleServer>,
        cancel: CancellationToken,
    ) -> Result<CallToolResult, ErrorData> {
        let mut progress = Progress::new(&meta, peer);
        Ok(self.respeak_inner(args, progress.as_mut(), &cancel).await.unwrap_or_else(|e| fail(&e)))
    }

    #[tool(description = "Turn the speech of an audio or video file into a trained voice (Redub's Convert voice): \
                          the same delivery and timing in the voice's timbre; only a voice train_voice trained can do \
                          it. A video source gives a video with the converted voice over its original music and \
                          sounds. Waits for redub.done and returns the paths with mimvox://file/ links. Use only the \
                          user's own voice or one they have permission to use. Cancelling the call stops the job.")]
    async fn convert_voice(
        &self,
        Parameters(args): Parameters<ConvertVoiceArgs>,
        meta: RequestMetaObject,
        peer: Peer<RoleServer>,
        cancel: CancellationToken,
    ) -> Result<CallToolResult, ErrorData> {
        let mut progress = Progress::new(&meta, peer);
        Ok(self.convert_inner(args, progress.as_mut(), &cancel).await.unwrap_or_else(|e| fail(&e)))
    }

    #[tool(description = "Save an audio file of the API's machine (a result, a book chapter, a design take) in \
                          another format (the app's Export as...): wav, mp3, flac, ogg, opus, m4a or aiff, by default \
                          next to it under the same name. Returns the new file's path and a mimvox://file/ link.")]
    async fn export_audio(&self, Parameters(args): Parameters<ExportAudioArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(self.export_audio_inner(args).await.unwrap_or_else(|e| fail(&e)))
    }

    #[tool(
        description = "The saved results (Speak's and Redub's Results), newest first: kind, path, video_path, \
                       voice, text or mode, length, created, with mimvox://file/ links (uri, video_uri). For older \
                       ones pass before: the created of the last entry.",
        annotations(read_only_hint = true)
    )]
    async fn list_results(&self, Parameters(args): Parameters<ListResultsArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.list_results_inner(args).await))
    }

    #[tool(
        description = "Delete a saved result (its trash button in the app): the file at path in <data>/outputs \
                       and the files of the same result beside it (a Redub result's video and audio, its record). \
                       Returns the paths deleted.",
        annotations(destructive_hint = true)
    )]
    async fn delete_result(&self, Parameters(args): Parameters<DeleteResultArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.api.rpc("outputs.delete", json!({ "path": args.path })).await))
    }

    #[tool(description = "Upload a local file to the API's machine (needed when the API runs on another computer) \
                          and return its path there, to pass to methods that take files. Uploads are deleted after \
                          24 hours.")]
    async fn upload_file(&self, Parameters(args): Parameters<UploadArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.upload_inner(args).await))
    }

    #[tool(description = "Download a file the API serves (a result in <data>/outputs, a file in <data>/tmp, an \
                          upload, a design take or a book chapter's segments_path) to this machine.")]
    async fn download_file(&self, Parameters(args): Parameters<DownloadArgs>) -> Result<CallToolResult, ErrorData> {
        Ok(reply(self.download_inner(args).await))
    }
}

fn icons() -> Vec<Icon> {
    ICONS
        .iter()
        .map(|(png, size)| {
            Icon::new(format!("data:image/png;base64,{}", BASE64.encode(png)))
                .with_mime_type("image/png")
                .with_sizes(vec![size.to_string()])
        })
        .collect()
}

#[tool_handler(router = self.tool_router)]
impl ServerHandler for Mimvox {
    fn get_info(&self) -> ServerConfig {
        ServerConfig::new(ServerCapabilities::builder().enable_tools().enable_resources().build())
            .with_server_info(
                Implementation::new("mimvox-mcp", env!("CARGO_PKG_VERSION"))
                    .with_title("Mimvox")
                    .with_icons(icons())
                    .with_website_url("https://github.com/tarpetos/mimvox"),
            )
            .with_instructions(INSTRUCTIONS)
    }

    async fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListResourcesResult, ErrorData> {
        self.resources()
            .await
            .map(ListResourcesResult::with_all_items)
            .map_err(|e| ErrorData::internal_error(e.to_string(), Some(e.to_json())))
    }

    async fn list_resource_templates(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListResourceTemplatesResult, ErrorData> {
        let file = ResourceTemplate::new(format!("{FILE_URI}{{path}}"), "file").with_description(
            "A file the Mimvox API serves (under <data>/outputs, <data>/tmp, <data>/api/uploads or <data>/design, or a \
             book's segments_path); {path} is its absolute path, percent-encoded.",
        );
        Ok(ListResourceTemplatesResult::with_all_items(vec![file]))
    }

    async fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<ReadResourceResponse, ErrorData> {
        let uri = request.uri;
        let Some(path) = path_of_uri(&uri) else {
            return Err(ErrorData::invalid_params(format!("not a {FILE_URI} URI: {uri}"), None));
        };
        let fetched = self.fetch(&path, RESOURCE_MAX).await.map_err(|e| match e.code.as_str() {
            "not_found" => ErrorData::resource_not_found(e.to_string(), Some(json!({ "uri": uri }))),
            _ => ErrorData::internal_error(e.to_string(), Some(e.to_json())),
        })?;
        let bytes = match fetched {
            Fetched::Bytes(b) => b,
            Fetched::TooLarge(_) => {
                return Err(ErrorData::invalid_params(
                    format!("{path} is larger than {} MB: use the download_file tool", RESOURCE_MAX >> 20),
                    None,
                ));
            }
        };
        let mime = mime_for(&path);
        let contents = match String::from_utf8(bytes) {
            Ok(text) if mime.starts_with("text/") || mime == "application/json" => ResourceContents::text(text, &uri),
            Ok(text) => ResourceContents::blob(BASE64.encode(text.as_bytes()), &uri),
            Err(e) => ResourceContents::blob(BASE64.encode(e.as_bytes()), &uri),
        }
        .with_mime_type(mime);
        Ok(ReadResourceResult::new(vec![contents]).into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn uris_round_trip() {
        for p in ["/home/u/.local/share/mimvox/outputs/20261111_101112.wav", r"C:\Users\Ана\outputs\a b%.mp3"] {
            let uri = file_uri(p);
            assert!(uri.starts_with(FILE_URI) && !uri[FILE_URI.len()..].contains('/'), "{uri}");
            assert_eq!(path_of_uri(&uri).as_deref(), Some(p));
        }
        assert_eq!(path_of_uri("mimvox://file/%zz"), None);
        assert_eq!(path_of_uri("file:///x"), None);
    }

    #[test]
    fn video_places() {
        let place = |s: &[&str], single| video_place(s, single).map(|(d, n)| format!("{d}|{n}"));
        assert_eq!(place(&["/d/outputs/20261111_101112.wav"], true).unwrap(), "/d/outputs|20261111_101112");
        let book = ["/d/outputs/books/My Book/01 - One.wav", "/d/outputs/books/My Book/02 - Two.wav"];
        assert_eq!(place(&book, false).unwrap(), "/d/outputs/videos|My Book");
        assert_eq!(place(&book[..1], false).unwrap(), "/d/outputs/videos|01 - One");
        let win = r"C:\Users\me\AppData\mimvox\api\uploads\a1-take.wav";
        assert_eq!(place(&[win], true).unwrap(), r"C:\Users\me\AppData\mimvox\outputs\videos|a1-take");
        assert_eq!(place(&["/d/design/20261111-1/voice.wav"], true).unwrap(), "/d/outputs/videos|voice");
        assert_eq!(place(&["/home/me/clip.wav"], true), None);
    }

    #[test]
    fn import_without_texts() {
        let doc = json!({ "chapters": [{ "title": "One", "text": "...", "words": 1 }], "parts": null });
        assert_eq!(without_texts(doc)["chapters"][0], json!({ "title": "One", "words": 1, "index": 0 }));
    }
}