AI Tone Rewriter — Zig 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 Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! tone-rewriter — tone registry, prompt building, and reply cleanup.
//!
//! Language: Zig (0.13, standard library only — the fence stripper is
//! hand-rolled like rust.rs, and no field is ever named `error`,
//! which the language reserves)
//! 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 tone rewriter is an AI tool, but its contract is
//! pure — which registers exist, how the system prompt is assembled, and how
//! a raw model reply is cleaned for display. The allocator makes every buffer
//! size explicit: prompt building is two allocations, cleanup is one.
//!
//! Test: zig test zig.zig
const std = @import("std");
/// The five supported registers (the TS `Tone` string-literal union).
/// `@tagName` supplies the wire id, so the registry below needs no copy.
pub const Tone = enum { professional, friendly, concise, formal, playful };
/// A registry entry — the TS `ToneOption` (wire id + human label).
pub const ToneOption = struct { id: []const u8, label: []const u8 };
/// The five-register registry — the SSOT for the picker, in order.
pub const tones = [_]ToneOption{
.{ .id = "professional", .label = "Professional" },
.{ .id = "friendly", .label = "Friendly" },
.{ .id = "concise", .label = "Concise" },
.{ .id = "formal", .label = "Formal" },
.{ .id = "playful", .label = "Playful" },
};
/// Payload cap for the user text (the TS `MAX_INPUT_CHARS`).
pub const max_input_chars: usize = 12000;
/// Per-tone register sentence embedded in the system prompt.
pub fn toneContract(tone: Tone) []const u8 {
return switch (tone) {
.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",
};
}
/// One chat message (`role` is "system" or "user").
pub const Message = struct { role: []const u8, content: []const u8 };
/// Build the [system, user] chat messages for the provider layer.
///
/// Slices are byte sequences, so the truncation slice counts bytes where the
/// TS lib counts UTF-16 units — they agree outside the astral planes. Input
/// over the cap is sliced and tagged with a visible "… (text truncated)"
/// marker. The caller owns the returned slice and both content strings.
pub fn buildPromptMessages(allocator: std.mem.Allocator, text: []const u8, tone: Tone) ![]Message {
const msgs = try allocator.alloc(Message, 2);
errdefer allocator.free(msgs);
msgs[0] = .{ .role = "system", .content = try std.fmt.allocPrint(
allocator,
"You rewrite text in a target tone. Rewrite the user's text in a {s} tone: {s}. Keep the same meaning and the same facts — only the register changes. Output ONLY the rewritten text, no preamble, no notes.",
.{ @tagName(tone), toneContract(tone) },
) };
msgs[1] = if (text.len > max_input_chars)
.{ .role = "user", .content = try std.fmt.allocPrint(
allocator,
"{s}\n… (text truncated)",
.{text[0..max_input_chars]},
) }
else
.{ .role = "user", .content = try allocator.dupe(u8, text) };
return msgs;
}
/// Clean the model's reply into displayable rewritten text.
///
/// Strips every ```lang fence marker (the TS /```[a-z]*\n?/g regex) plus
/// surrounding whitespace. No strict format contract — any non-empty cleaned
/// text is the rewrite; null only when nothing survives. The caller owns the
/// returned slice.
pub fn parseRewrite(allocator: std.mem.Allocator, text: []const u8) !?[]u8 {
// Scratch buffer: fences only ever shrink the text.
const scratch = try allocator.alloc(u8, text.len);
defer allocator.free(scratch);
var o: usize = 0;
var i: usize = 0;
while (i < text.len) {
if (std.mem.startsWith(u8, text[i..], "```")) {
i += 3;
while (i < text.len and text[i] >= 'a' and text[i] <= 'z') i += 1;
if (i < text.len and text[i] == '\n') i += 1;
continue;
}
scratch[o] = text[i];
o += 1;
i += 1;
}
const cleaned = std.mem.trim(u8, scratch[0..o], " \t\n\x0b\x0c\r");
if (cleaned.len == 0) return null;
return try allocator.dupe(u8, cleaned);
}
test "buildPromptMessages assembles the system contract and user body" {
const t = std.testing;
const msgs = try buildPromptMessages(t.allocator, "The Q3 numbers are in.", .friendly);
defer {
t.allocator.free(msgs[0].content);
t.allocator.free(msgs[1].content);
t.allocator.free(msgs);
}
try t.expectEqual(@as(usize, 2), msgs.len);
try t.expectEqualStrings("system", msgs[0].role);
try t.expect(std.mem.startsWith(u8, msgs[0].content, "You rewrite text in a target tone. Rewrite the user's text in a friendly tone: warm and approachable"));
try t.expect(std.mem.endsWith(u8, msgs[0].content, "no preamble, no notes."));
try t.expectEqualStrings("The Q3 numbers are in.", msgs[1].content);
}
test "input over the cap is truncated with the visible marker" {
const t = std.testing;
const long_buf = [_]u8{'a'} * 13000;
const long: []const u8 = &long_buf;
const msgs = try buildPromptMessages(t.allocator, long, .concise);
defer {
t.allocator.free(msgs[0].content);
t.allocator.free(msgs[1].content);
t.allocator.free(msgs);
}
try t.expectEqual(max_input_chars + "\n… (text truncated)".len, msgs[1].content.len);
try t.expect(std.mem.endsWith(u8, msgs[1].content, "\n… (text truncated)"));
}
test "parseRewrite strips fences and trims, null when nothing survives" {
const t = std.testing;
const a = t.allocator;
const rewrite = try parseRewrite(a, "```text\nHere you go!\n```\n");
defer a.free(rewrite.?);
try t.expectEqualStrings("Here you go!", rewrite.?);
const plain = try parseRewrite(a, "no fences at all\n");
defer a.free(plain.?);
try t.expectEqualStrings("no fences at all", plain.?);
try t.expectEqual(@as(?[]u8, null), try parseRewrite(a, "``` \n"));
}
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 →