Skip to content

AI Tone Rewriter — Rust source

Rewrite any message in a new tone — professional, friendly, concise, formal, or playful — with your own free Groq key, called straight from your browser.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! tone-rewriter — tone registry, prompt building, and reply cleanup.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `tone-rewriter` tool, ported from
//! src/lib/tone-rewriter.ts (the canonical TypeScript implementation).
//!
//! Why this file exists: the tool is AI-backed but its contract is pure —
//! which registers exist, how the system prompt is assembled, and how a raw
//! reply is cleaned for display. No regex crate is needed: the fence stripper
//! is a plain substring scan, and the `Tone` enum replaces the TS
//! string-literal union at zero runtime cost.
//!
//! display source — part of CosmoDev's polyglot tool pages.

/// The five supported registers (the TS `Tone` string-literal union).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Tone {
    Professional,
    Friendly,
    Concise,
    Formal,
    Playful,
}

impl Tone {
    /// All five registers in registry order (the picker's data source).
    pub const ALL: [Tone; 5] = [
        Tone::Professional, Tone::Friendly, Tone::Concise, Tone::Formal, Tone::Playful,
    ];

    /// (wire id, human label, register contract) — the TS `ToneOption` fields
    /// plus the system-prompt sentence, in one exhaustive table.
    fn parts(self) -> (&'static str, &'static str, &'static str) {
        match self {
            Tone::Professional => ("professional", "Professional", "polished and businesslike, no slang, clear and direct — the register of a status update to stakeholders"),
            Tone::Friendly => ("friendly", "Friendly", "warm and approachable, contractions welcome, like a teammate chatting — never stiff"),
            Tone::Concise => ("concise", "Concise", "as short as possible while keeping every fact; prefer one sentence; cut filler words without exception"),
            Tone::Formal => ("formal", "Formal", "ceremonial register, no contractions, complete sentences — the register of official correspondence"),
            Tone::Playful => ("playful", "Playful", "light and witty, a touch of humor, emojis allowed (at most two) — but the facts stay exact"),
        }
    }

    /// Wire id — the TS `Tone` string literal used inside the system prompt.
    pub fn id(self) -> &'static str { self.parts().0 }

    /// Human label — the TS `ToneOption.label`.
    pub fn label(self) -> &'static str { self.parts().1 }

    /// Per-tone register sentence embedded in the system prompt.
    fn contract(self) -> &'static str { self.parts().2 }
}

/// Payload cap for the user text (the TS `MAX_INPUT_CHARS`).
pub const MAX_INPUT_CHARS: usize = 12000;

/// One chat message (`role` is `"system"` or `"user"`).
pub struct Message {
    pub role: &'static str,
    pub content: String,
}

/// Build the [system, user] chat messages for the provider layer.
///
/// Input longer than `MAX_INPUT_CHARS` is sliced and tagged with a visible
/// "… (text truncated)" marker so the model knows the payload was capped.
/// The slice counts `char`s (code points) where the TS lib counts UTF-16
/// units — they agree for everything outside the astral planes.
pub fn build_prompt_messages(text: &str, tone: Tone) -> [Message; 2] {
    let body = if text.chars().count() > MAX_INPUT_CHARS {
        let head: String = text.chars().take(MAX_INPUT_CHARS).collect();
        format!("{head}\n\u{2026} (text truncated)")
    } else {
        text.to_string()
    };
    [
        Message {
            role: "system",
            content: format!(
                "You rewrite text in a target tone. Rewrite the user's text in a {} tone: {}. Keep the same meaning and the same facts — only the register changes. Output ONLY the rewritten text, no preamble, no notes.",
                tone.id(),
                tone.contract()
            ),
        },
        Message { role: "user", content: body },
    ]
}

/// Clean the model's reply into displayable rewritten text.
///
/// Strips every ```lang fence marker plus surrounding whitespace. No strict
/// format contract — any non-empty cleaned text is the rewrite; `None` only
/// when nothing survives.
pub fn parse_rewrite(text: &str) -> Option<String> {
    let cleaned = strip_fences(text).trim().to_string();
    (!cleaned.is_empty()).then_some(cleaned)
}

/// Hand-rolled equivalent of the TS `/```[a-z]*\n?/g` regex: drop every
/// "```" marker, any lowercase language tag right after it, and one optional
/// following newline. Lone backtick runs shorter than three are kept as-is.
fn strip_fences(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut rest = input;
    while let Some(pos) = rest.find("```") {
        out.push_str(&rest[..pos]);
        let after = &rest[pos + 3..];
        let tag_len = after.chars().take_while(|c| c.is_ascii_lowercase()).count();
        let after = &after[tag_len..];
        rest = after.strip_prefix('\n').unwrap_or(after);
    }
    out.push_str(rest);
    out
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →