AI Tone Rewriter — TypeScript 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 TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// src/lib/tone-rewriter.ts — the pure core of the AI tone rewriter
// (AI Studio tool #5, FEAT-077; class rollout per the FEAT-049 verdict).
// Tone registry + prompt building + reply cleanup are pure so the island is
// a thin shell over the shared provider layer (src/lib/ai-studio), and this
// file is a future Go-twin candidate once the class proves out.
export type Tone = 'professional' | 'friendly' | 'concise' | 'formal' | 'playful';
export interface ToneOption {
id: Tone;
label: string;
}
/** The five supported registers — the SSOT for the island's SegmentedControl. */
export const TONES: ToneOption[] = [
{ id: 'professional', label: 'Professional' },
{ id: 'friendly', label: 'Friendly' },
{ id: 'concise', label: 'Concise' },
{ id: 'formal', label: 'Formal' },
{ id: 'playful', label: 'Playful' },
];
const MAX_INPUT_CHARS = 12000;
const TONE_CONTRACT: Record<Tone, string> = {
professional:
'polished and businesslike, no slang, clear and direct — the register of a status update to stakeholders',
friendly:
'warm and approachable, contractions welcome, like a teammate chatting — never stiff',
concise:
'as short as possible while keeping every fact; prefer one sentence; cut filler words without exception',
formal:
'ceremonial register, no contractions, complete sentences — the register of official correspondence',
playful:
'light and witty, a touch of humor, emojis allowed (at most two) — but the facts stay exact',
};
/** Build the [system, user] chat messages for the provider layer. */
export function buildPromptMessages(
text: string,
opts: { tone: Tone },
): Array<{ role: 'system' | 'user'; content: string }> {
const truncated = text.length > MAX_INPUT_CHARS;
const body = truncated ? `${text.slice(0, MAX_INPUT_CHARS)}\n… (text truncated)` : text;
return [
{
role: 'system',
content: `You rewrite text in a target tone. Rewrite the user's text in a ${opts.tone} tone: ${TONE_CONTRACT[opts.tone]}. Keep the same meaning and the same facts — only the register changes. Output ONLY the rewritten text, no preamble, no notes.`,
},
{ role: 'user', content: body },
];
}
/**
* Clean the model's reply into displayable rewritten text. No strict format
* contract — any non-empty cleaned text is the rewrite; null only when
* nothing survives.
*/
export function parseRewrite(text: string): string | null {
const cleaned = text.replace(/```[a-z]*\n?/g, '').trim();
return cleaned.length > 0 ? cleaned : null;
}
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 →