Inbox Lens — API

Paste the subject and body, get a deliverability audit and an improved email.

API tokens Open the app

Audit email deliverability from your own scripts

Send a subject line and a body — raw HTML or plain text — say what kind of email it is, and optionally paste the From address and the sending domain's SPF, DKIM and DMARC records. Back comes one JSON object: an honest inbox / risky / spam verdict, a health check across five deliverability areas, findings ranked by severity each with a corrected DNS record, header or snippet of copy, a twelve-item checklist scored against the paste, and the same email rewritten to land in the inbox. Everything this app does goes through the SkillSafe App API — plain JSON over HTTPS — so you can wire an audit into a campaign-approval step, a template test suite, or a pre-send gate that refuses a marketing blast with v=spf1 +all and no unsubscribe link. Every code step below is shown in cURL, Python, JavaScript, Go, Java, Ruby, PHP and C#; pick a language once and the whole page follows.

Basics

Base URL: https://api.skillsafe.ai/v1/app-api, app slug inbox-lens. Every request sends Authorization: Bearer <token> and JSON bodies with Content-Type: application/json. Responses are wrapped in an envelope: {"data": …} on success, {"error": {"code", "message"}} on failure. The audit itself is produced by the gpt-terra model. Estimates are free; runs are metered against your credit balance. There is a single run task — one email in, one audit out, no follow-up calls and no session state to carry.

StatusMeaning
401Missing or expired token — create a new session.
402Not enough credits — top up at skillsafe.ai/account/credits.
403The token isn't allowed to do this (e.g. a guest auditing a very large email).
404Unknown job or record id.
5xxTransient platform error — retry with backoff.

Browsers enforce CORS for this API, so run these examples from a server, script or terminal — not from another website's frontend.

Step 0 — A tiny client

Every task below is a single HTTP call, so start with a short helper that adds the auth header, sends JSON and unwraps the data envelope. The later steps reuse it.

export API="https://api.skillsafe.ai/v1/app-api"
export TOKEN="YOUR_TOKEN"      # see step 1

# every call looks like:
#   curl -s "$API/..." -H "Authorization: Bearer $TOKEN" [-d '{json}']
# jq is used below to pull fields out of the {"data": ...} envelope
import json, requests

API = "https://api.skillsafe.ai/v1/app-api"
TOKEN = "YOUR_TOKEN"  # see step 1 — read it from your shell environment in real code

def api(method, path, body=None, **headers):
    res = requests.request(method, API + path, json=body,
                           headers={"Authorization": f"Bearer {TOKEN}", **headers})
    payload = res.json()
    if not res.ok:
        raise RuntimeError(payload.get("error", {}).get("message", res.reason))
    return payload["data"]
// Node 18+ (built-in fetch)
const API = "https://api.skillsafe.ai/v1/app-api";
const TOKEN = "YOUR_TOKEN"; // see step 1 — read it from your shell environment in real code

async function api(method, path, body, extraHeaders = {}) {
  const res = await fetch(API + path, {
    method,
    headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json", ...extraHeaders },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const json = await res.json();
  if (!res.ok) throw new Error(json.error?.message ?? res.statusText);
  return json.data;
}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

const API = "https://api.skillsafe.ai/v1/app-api"

var token = os.Getenv("SKILLSAFE_TOKEN") // see step 1

func call(method, path string, body, out any) error {
	var buf bytes.Buffer
	if body != nil {
		json.NewEncoder(&buf).Encode(body)
	}
	req, _ := http.NewRequest(method, API+path, &buf)
	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json")
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	var env struct {
		Data  json.RawMessage `json:"data"`
		Error *struct{ Message string `json:"message"` } `json:"error"`
	}
	json.NewDecoder(res.Body).Decode(&env)
	if res.StatusCode >= 400 {
		return fmt.Errorf("api %s %s: %s", method, path, env.Error.Message)
	}
	if out == nil {
		return nil
	}
	return json.Unmarshal(env.Data, out)
}
// Java 17+, no dependencies. Pair with your JSON library (Jackson, Gson…)
// to read fields out of the returned envelope.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class SkillSafe {
    static final String API = "https://api.skillsafe.ai/v1/app-api";
    static final String TOKEN = System.getenv("SKILLSAFE_TOKEN"); // see step 1
    static final HttpClient HTTP = HttpClient.newHttpClient();

    static String api(String method, String path, String jsonBody) throws Exception {
        var req = HttpRequest.newBuilder(URI.create(API + path))
            .header("Authorization", "Bearer " + TOKEN)
            .header("Content-Type", "application/json")
            .method(method, jsonBody == null
                ? HttpRequest.BodyPublishers.noBody()
                : HttpRequest.BodyPublishers.ofString(jsonBody))
            .build();
        var res = HTTP.send(req, HttpResponse.BodyHandlers.ofString());
        if (res.statusCode() >= 400) throw new RuntimeException(res.body());
        return res.body(); // envelope: {"data": …}
    }
}
require "net/http"
require "json"

API = "https://api.skillsafe.ai/v1/app-api"
TOKEN = ENV.fetch("SKILLSAFE_TOKEN") # see step 1

def api(method, path, body = nil)
  uri = URI(API + path)
  req = Net::HTTP.const_get(method.capitalize).new(uri)
  req["Authorization"] = "Bearer #{TOKEN}"
  req["Content-Type"] = "application/json"
  req.body = body.to_json if body
  res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }
  payload = JSON.parse(res.body)
  raise (payload.dig("error", "message") || res.message) unless res.is_a?(Net::HTTPSuccess)
  payload["data"]
end
<?php
const API = "https://api.skillsafe.ai/v1/app-api";
$TOKEN = getenv("SKILLSAFE_TOKEN"); // see step 1

function api(string $method, string $path, ?array $body = null): mixed {
    global $TOKEN;
    $ch = curl_init(API . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            "Authorization: Bearer $TOKEN",
            "Content-Type: application/json",
        ],
        CURLOPT_POSTFIELDS     => $body === null ? null : json_encode($body),
    ]);
    $payload = json_decode(curl_exec($ch), true);
    $status  = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    if ($status >= 400) {
        throw new Exception($payload["error"]["message"] ?? "HTTP $status");
    }
    return $payload["data"];
}
// .NET 8+
using System.Net.Http.Json;
using System.Text.Json;

static class SkillSafe
{
    const string Api = "https://api.skillsafe.ai/v1/app-api";
    static readonly HttpClient Http = new();

    static SkillSafe() =>
        Http.DefaultRequestHeaders.Authorization =
            new("Bearer", Environment.GetEnvironmentVariable("SKILLSAFE_TOKEN")); // see step 1

    public static async Task<JsonElement> ApiAsync(HttpMethod method, string path, object? body = null)
    {
        var req = new HttpRequestMessage(method, Api + path);
        if (body != null) req.Content = JsonContent.Create(body);
        var res = await Http.SendAsync(req);
        var json = await res.Content.ReadFromJsonAsync<JsonElement>();
        if (!res.IsSuccessStatusCode)
            throw new Exception(json.GetProperty("error").GetProperty("message").GetString());
        return json.GetProperty("data");
    }
}

Step 1 — Get a token

POST /guest

A guest token lets you check balances and estimate costs for free. For metered audit runs billed to your own account, use your personal token: open the token page, sign in with SkillSafe, and press Copy shell export — it puts export SKILLSAFE_TOKEN="…" on your clipboard, which every example below reads. Treat the token like a password: it can spend your credits. For fully headless scripts, POST /guest mints a guest token with no browser involved.

curl -s -X POST "$API/guest" \
  -H "Content-Type: application/json" \
  -d '{"slug":"inbox-lens"}' | jq -r '.data.token'
token = api("POST", "/guest", {"slug": "inbox-lens"})["token"]
const { token } = await api("POST", "/guest", { slug: "inbox-lens" });
var guest struct{ Token string `json:"token"` }
err := call("POST", "/guest", map[string]string{"slug": "inbox-lens"}, &guest)
String envelope = api("POST", "/guest", """
    {"slug":"inbox-lens"}""");
// token is at data.token in the returned JSON
token = api("POST", "/guest", { slug: "inbox-lens" })["token"]
$token = api("POST", "/guest", ["slug" => "inbox-lens"])["token"];
var guest = await SkillSafe.ApiAsync(HttpMethod.Post, "/guest",
    new { slug = "inbox-lens" });
var token = guest.GetProperty("token").GetString();

The app stores this browser's token under the localStorage key skillsafe_app_token:inbox-lens, on the app's own origin. The token page reads and manages it for you — you never need to open developer tools.

Step 2 — Check who you are and your balance

GET /me

Returns subject_type ("user" or "guest"), subject_id and your credits balance. Check this before auditing a long HTML email.

curl -s "$API/me" -H "Authorization: Bearer $TOKEN" | jq '.data'
me = api("GET", "/me")
print(me["subject_type"], me["credits"])
const me = await api("GET", "/me");
console.log(me.subject_type, me.credits);
var me struct {
	SubjectType string `json:"subject_type"`
	Credits     int64  `json:"credits"`
}
err := call("GET", "/me", nil, &me)
String envelope = api("GET", "/me", null);
// data.subject_type, data.credits
me = api("GET", "/me")
puts "#{me["subject_type"]}: #{me["credits"]} credits"
$me = api("GET", "/me");
echo "{$me['subject_type']}: {$me['credits']} credits\n";
var me = await SkillSafe.ApiAsync(HttpMethod.Get, "/me");
Console.WriteLine($"{me.GetProperty("subject_type")}: {me.GetProperty("credits")} credits");

Step 3 — Estimate the cost

POST /estimate

Send exactly the input you would send to /run; the response's hold_credits is the worst-case cost. Nothing is charged and no job is created, so estimating is free — useful when you are feeding in a long HTML template and want a ceiling before spending credits.

Input fieldTypeNotes
subjectstring, requiredThe subject line exactly as it would be sent, merge tags and all. Send it empty only if the email genuinely has no subject — that is itself a finding.
bodystring, requiredThe email body: raw HTML (the whole template, inline styles, tracking pixels and footer included) or plain text. The audit detects which it is and judges accordingly. Very long bodies may be clipped middle-out, with a [... clipped ...] marker showing where.
email_typestringmarketing | transactional | newsletter | onboarding | cold-outreach | unknown — what kind of mail this is. Consent and unsubscribe rules are judged against it: transactional is exempt from marketing opt-in and unsubscribe requirements, the others are not, and cold-outreach to people who never opted in is itself a compliance finding. On unknown the stricter marketing rules apply.
notesstring, optionalExtra context the body cannot show: the From address and sending domain, the SPF / DKIM / DMARC TXT records as published, which ESP or relay sends it, where the list came from, monthly volume, and whether a plain-text part is generated alongside the HTML. Records pasted here are read literally — nothing is looked up over the network.
prescan_factsobject, optionalWhat a client-side prescan mechanically detected: {"risks": [], "elements": [], "signals": []}. Each entry is {id, label} — keyword-matched spam smells (spam-phrases, no-unsubscribe, spf-plus-all), structure actually present (unsubscribe-present, dmarc-present, plaintext-part) and raw counts (counts). Every id you send comes back in coverage_check. The web UI fills this from its own scan; API callers may omit the field or send the three empty arrays.
retry_notestring, optionalOnly set by the app's automatic reformat retry when a first reply was not valid JSON. Leave it out.
cat > body.txt <<'EMAIL'
Hi Maya,

Your order #58214 shipped today and should arrive by Thursday.

Track it: https://fernway.com/track/58214

Fernway Goods, 410 Mercer St, Portland OR
EMAIL

jq -n --rawfile b body.txt \
  '{subject: "Your order has shipped", body: $b, email_type: "transactional",
    notes: "From: orders@fernway.com. DNS: fernway.com TXT \"v=spf1 +all\". No DKIM selector, no DMARC record.",
    prescan_facts: {risks: [], elements: [], signals: []}}' > input.json

curl -s -X POST "$API/estimate" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d @input.json | jq '.data.hold_credits'
BODY = """Hi Maya,

Your order #58214 shipped today and should arrive by Thursday.

Track it: https://fernway.com/track/58214

Fernway Goods, 410 Mercer St, Portland OR"""

payload = {
    "subject": "Your order has shipped",
    "body": BODY,
    "email_type": "transactional",
    "notes": 'From: orders@fernway.com. DNS: fernway.com TXT "v=spf1 +all". '
             "No DKIM selector, no DMARC record.",
    "prescan_facts": {"risks": [], "elements": [], "signals": []},
}

est = api("POST", "/estimate", payload)
print("worst case:", est.get("hold_credits", est.get("credits")), "credits")
const body = `Hi Maya,

Your order #58214 shipped today and should arrive by Thursday.

Track it: https://fernway.com/track/58214

Fernway Goods, 410 Mercer St, Portland OR`;

const payload = {
  subject: "Your order has shipped",
  body,
  email_type: "transactional",
  notes: 'From: orders@fernway.com. DNS: fernway.com TXT "v=spf1 +all". ' +
         "No DKIM selector, no DMARC record.",
  prescan_facts: { risks: [], elements: [], signals: [] },
};

const est = await api("POST", "/estimate", payload);
console.log("worst case:", est.hold_credits ?? est.credits, "credits");
const body = `Hi Maya,

Your order #58214 shipped today and should arrive by Thursday.

Track it: https://fernway.com/track/58214

Fernway Goods, 410 Mercer St, Portland OR`

payload := map[string]any{
	"subject":    "Your order has shipped",
	"body":       body,
	"email_type": "transactional",
	"notes":      `From: orders@fernway.com. DNS: fernway.com TXT "v=spf1 +all". No DKIM selector, no DMARC record.`,
	"prescan_facts": map[string]any{
		"risks": []any{}, "elements": []any{}, "signals": []any{},
	},
}

var est struct{ HoldCredits int64 `json:"hold_credits"` }
err := call("POST", "/estimate", payload, &est)
String body = """
    Hi Maya,

    Your order #58214 shipped today and should arrive by Thursday.

    Track it: https://fernway.com/track/58214

    Fernway Goods, 410 Mercer St, Portland OR""";

String notes = "From: orders@fernway.com. DNS: fernway.com TXT \"v=spf1 +all\". "
             + "No DKIM selector, no DMARC record.";

String jsonPayload = """
    {"subject": "Your order has shipped", "body": %s,
     "email_type": "transactional", "notes": %s,
     "prescan_facts": {"risks": [], "elements": [], "signals": []}}
    """.formatted(toJsonString(body), toJsonString(notes));

String envelope = api("POST", "/estimate", jsonPayload);
// worst-case cost is at data.hold_credits
BODY_TEXT = <<~'EMAIL'
  Hi Maya,

  Your order #58214 shipped today and should arrive by Thursday.

  Track it: https://fernway.com/track/58214

  Fernway Goods, 410 Mercer St, Portland OR
EMAIL

payload = { subject: "Your order has shipped", body: BODY_TEXT,
            email_type: "transactional",
            notes: 'From: orders@fernway.com. DNS: fernway.com TXT "v=spf1 +all". ' \
                   "No DKIM selector, no DMARC record.",
            prescan_facts: { risks: [], elements: [], signals: [] } }

est = api("POST", "/estimate", payload)
puts "worst case: #{est["hold_credits"] || est["credits"]} credits"
$body = <<<'EMAIL'
Hi Maya,

Your order #58214 shipped today and should arrive by Thursday.

Track it: https://fernway.com/track/58214

Fernway Goods, 410 Mercer St, Portland OR
EMAIL;

$payload = [
    "subject"       => "Your order has shipped",
    "body"          => $body,
    "email_type"    => "transactional",
    "notes"         => 'From: orders@fernway.com. DNS: fernway.com TXT "v=spf1 +all". '
                     . "No DKIM selector, no DMARC record.",
    "prescan_facts" => ["risks" => [], "elements" => [], "signals" => []],
];

$est = api("POST", "/estimate", $payload);
echo "worst case: " . ($est["hold_credits"] ?? $est["credits"]) . " credits\n";
var body = """
    Hi Maya,

    Your order #58214 shipped today and should arrive by Thursday.

    Track it: https://fernway.com/track/58214

    Fernway Goods, 410 Mercer St, Portland OR
    """;

var payload = new {
    subject = "Your order has shipped",
    body,
    email_type = "transactional",
    notes = """From: orders@fernway.com. DNS: fernway.com TXT "v=spf1 +all". No DKIM selector, no DMARC record.""",
    prescan_facts = new {
        risks = Array.Empty<object>(), elements = Array.Empty<object>(),
        signals = Array.Empty<object>(),
    },
};

var est = await SkillSafe.ApiAsync(HttpMethod.Post, "/estimate", payload);
Console.WriteLine($"worst case: {est.GetProperty("hold_credits")} credits");

prescan_facts is how you make the audit answer for things you already know about. Send {"risks": [{"id": "spf-plus-all", "label": "SPF record ends in +all"}, {"id": "no-unsubscribe", "label": "no unsubscribe wording found"}], "elements": [{"id": "plaintext-part", "label": "body is plain text"}], "signals": [{"id": "counts", "label": "38 words · 1 link · 0 images"}]} and every one of those ids comes back in coverage_check — addressed, or explained away as a false positive. Nothing you flag is silently dropped.

Step 4 — Run the audit and wait for the result

POST /run
GET /jobs/{job_id}

/run takes the same input as /estimate, places a credit hold and returns a job_id. Poll /jobs/{job_id} every 1–2 seconds until status is succeeded or failed (a run typically takes 30–90 s, since the improved email is written out in full). Always send an Idempotency-Key header so a network retry can't start a second, double-charged run. The audit is in output — usually nested as output.output, and as a JSON string, so parse defensively. The samples below print the audit name and verdict, the five health areas and the findings, then write rewrite.code to improved-email.txt.

JOB_ID=$(curl -s -X POST "$API/run" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -H "Idempotency-Key: audit-$(date +%s)" \
  -d @input.json | jq -r '.data.job_id')

while :; do
  JOB=$(curl -s "$API/jobs/$JOB_ID" -H "Authorization: Bearer $TOKEN")
  STATUS=$(echo "$JOB" | jq -r '.data.status')
  [ "$STATUS" = "succeeded" ] || [ "$STATUS" = "failed" ] && break
  sleep 2
done

# unwrap the audit once, then read it
echo "$JOB" | jq -r '.data.output.output' > audit.json

jq -r '
  "\(.audit_name) [\(.verdict_level)]: \(.verdict)",
  "",
  "HEALTH",
  (.health[] | "  [\(.status)] \(.area) - \(.note)"),
  "",
  "FINDINGS",
  (.findings[] | "  (\(.severity)) \(.category): \(.title)"),
  "",
  "CHECKLIST",
  (.checklist[] | "  [\(.status)] \(.item) - \(.note)")' audit.json

# and drop the improved email straight into your template folder
jq -r '.rewrite.code' audit.json > "$(jq -r '.rewrite.filename' audit.json)"   # improved-email.txt
import time

job_id = api("POST", "/run", payload,
             **{"Idempotency-Key": "audit-001"})["job_id"]

while True:
    job = api("GET", f"/jobs/{job_id}")
    if job["status"] in ("succeeded", "failed"):
        break
    time.sleep(1.5)

if job["status"] == "failed":
    raise RuntimeError(job.get("error", "run failed"))

raw = job["output"]
if isinstance(raw, dict) and "output" in raw:
    raw = raw["output"]
audit = json.loads(raw) if isinstance(raw, str) else raw

print(f'{audit["audit_name"]} [{audit["verdict_level"]}]: {audit["verdict"]}')
for area in audit["health"]:
    print(f'  [{area["status"]:>4}] {area["area"]:<32} {area["note"]}')
for f in audit["findings"]:
    print(f'  ({f["severity"]}) {f["category"]}: {f["title"]}')
    if f["fix_code"]:
        print(f'      {f["fix_code"]}')
for item in audit["checklist"]:
    print(f'  [{item["status"]:>4}] {item["item"]:<34} {item["note"]}')
for c in audit["coverage_check"]:
    print(f'  {c["id"]}: {"ok" if c["addressed"] else "SET ASIDE"} - {c["note"]}')

with open(audit["rewrite"]["filename"], "w", encoding="utf-8") as fh:   # improved-email.txt
    fh.write(audit["rewrite"]["code"])
import { writeFileSync } from "node:fs";

const { job_id } = await api("POST", "/run", payload,
  { "Idempotency-Key": crypto.randomUUID() });

let job;
do {
  await new Promise((r) => setTimeout(r, 1500));
  job = await api("GET", `/jobs/${job_id}`);
} while (job.status !== "succeeded" && job.status !== "failed");

if (job.status === "failed") throw new Error(job.error ?? "run failed");

const raw = job.output?.output ?? job.output;
const audit = typeof raw === "string" ? JSON.parse(raw) : raw;

console.log(`${audit.audit_name} [${audit.verdict_level}]: ${audit.verdict}`);
for (const area of audit.health) {
  console.log(`  [${area.status}] ${area.area}: ${area.note}`);
}
for (const f of audit.findings) {
  console.log(`  (${f.severity}) ${f.category}: ${f.title}`);
  if (f.fix_code) console.log(`      ${f.fix_code}`);
}
for (const item of audit.checklist) console.log(`  [${item.status}] ${item.item}: ${item.note}`);
for (const c of audit.coverage_check) {
  console.log(`  ${c.id}: ${c.addressed ? "ok" : "SET ASIDE"} - ${c.note}`);
}

writeFileSync(audit.rewrite.filename, audit.rewrite.code);   // improved-email.txt
var started struct{ JobID string `json:"job_id"` }
if err := call("POST", "/run", payload, &started); err != nil {
	log.Fatal(err)
}

var job struct {
	Status string          `json:"status"`
	Error  string          `json:"error"`
	Output json.RawMessage `json:"output"`
}
for {
	if err := call("GET", "/jobs/"+started.JobID, nil, &job); err != nil {
		log.Fatal(err)
	}
	if job.Status == "succeeded" || job.Status == "failed" {
		break
	}
	time.Sleep(1500 * time.Millisecond)
}

// job.Output is {"output": "<json string>"} — unwrap, unquote, then unmarshal:
type Audit struct {
	AuditName    string `json:"audit_name"`
	VerdictLevel string `json:"verdict_level"`
	Verdict      string `json:"verdict"`
	Health       []struct {
		Area, Status, Note string
	} `json:"health"`
	Findings []struct {
		Severity, Category, Title, Detail string
		FixCode                           string `json:"fix_code"`
	} `json:"findings"`
	Checklist []struct {
		Item, Status, Note string
	} `json:"checklist"`
	Rewrite struct {
		Filename, Code string
	} `json:"rewrite"`
}
var wrapper struct{ Output string `json:"output"` }
json.Unmarshal(job.Output, &wrapper)
var audit Audit
json.Unmarshal([]byte(wrapper.Output), &audit)

fmt.Printf("%s [%s]: %s\n", audit.AuditName, audit.VerdictLevel, audit.Verdict)
for _, a := range audit.Health {
	fmt.Printf("  [%s] %s: %s\n", a.Status, a.Area, a.Note)
}
for _, f := range audit.Findings {
	fmt.Printf("  (%s) %s: %s\n", f.Severity, f.Category, f.Title)
}
for _, c := range audit.Checklist {
	fmt.Printf("  [%s] %s: %s\n", c.Status, c.Item, c.Note)
}
os.WriteFile(audit.Rewrite.Filename, []byte(audit.Rewrite.Code), 0o644) // improved-email.txt
String envelope = api("POST", "/run", jsonPayload);
String jobId = /* data.job_id via your JSON library */;

while (true) {
    String job = api("GET", "/jobs/" + jobId, null);
    String status = /* data.status */;
    if (status.equals("succeeded") || status.equals("failed")) break;
    Thread.sleep(1500);
}
// The audit is at data.output.output as a JSON string — parse it again, then read
// audit_name, verdict_level, verdict, overview, health[] (five areas with area/status/note),
// findings[] (severity/category/title/detail/fix_code), checklist[] (item/status/note),
// coverage_check[] (id/addressed/note), rewrite{filename, code}, next_steps[] and summary.
// Finally write the improved email to disk:
//   Files.writeString(Path.of(rewriteFilename), rewriteCode);   // improved-email.txt
started = api("POST", "/run", payload)

job = nil
loop do
  job = api("GET", "/jobs/#{started["job_id"]}")
  break if %w[succeeded failed].include?(job["status"])
  sleep 1.5
end
raise (job["error"] || "run failed") if job["status"] == "failed"

raw = job["output"].is_a?(Hash) ? job["output"].fetch("output", job["output"]) : job["output"]
audit = raw.is_a?(String) ? JSON.parse(raw) : raw

puts "#{audit["audit_name"]} [#{audit["verdict_level"]}]: #{audit["verdict"]}"
audit["health"].each { |a| puts "  [#{a["status"]}] #{a["area"]}: #{a["note"]}" }
audit["findings"].each do |f|
  puts "  (#{f["severity"]}) #{f["category"]}: #{f["title"]}"
  puts "      #{f["fix_code"]}" unless f["fix_code"].to_s.empty?
end
audit["checklist"].each { |c| puts "  [#{c["status"]}] #{c["item"]}: #{c["note"]}" }
audit["coverage_check"].each { |c| puts "  #{c["id"]}: #{c["addressed"] ? "ok" : "SET ASIDE"}" }

File.write(audit["rewrite"]["filename"], audit["rewrite"]["code"])   # improved-email.txt
$started = api("POST", "/run", $payload);

do {
    sleep(2);
    $job = api("GET", "/jobs/" . $started["job_id"]);
} while (!in_array($job["status"], ["succeeded", "failed"]));

if ($job["status"] === "failed") {
    throw new Exception($job["error"] ?? "run failed");
}

$raw = is_array($job["output"]) ? ($job["output"]["output"] ?? $job["output"]) : $job["output"];
$audit = is_string($raw) ? json_decode($raw, true) : $raw;

echo "{$audit['audit_name']} [{$audit['verdict_level']}]: {$audit['verdict']}\n";
foreach ($audit["health"] as $a) {
    echo "  [{$a['status']}] {$a['area']}: {$a['note']}\n";
}
foreach ($audit["findings"] as $f) {
    echo "  ({$f['severity']}) {$f['category']}: {$f['title']}\n";
    if ($f["fix_code"] !== "") { echo "      {$f['fix_code']}\n"; }
}
foreach ($audit["checklist"] as $item) {
    echo "  [{$item['status']}] {$item['item']}: {$item['note']}\n";
}
foreach ($audit["coverage_check"] as $c) {
    echo "  {$c['id']}: " . ($c["addressed"] ? "ok" : "SET ASIDE") . "\n";
}

file_put_contents($audit["rewrite"]["filename"], $audit["rewrite"]["code"]);   // improved-email.txt
var started = await SkillSafe.ApiAsync(HttpMethod.Post, "/run", payload);
var jobId = started.GetProperty("job_id").GetString();

JsonElement job;
while (true)
{
    job = await SkillSafe.ApiAsync(HttpMethod.Get, $"/jobs/{jobId}");
    var status = job.GetProperty("status").GetString();
    if (status is "succeeded" or "failed") break;
    await Task.Delay(1500);
}

var rawText = job.GetProperty("output").GetProperty("output").GetString();
using var doc = JsonDocument.Parse(rawText!);
var audit = doc.RootElement;

Console.WriteLine($"{audit.GetProperty("audit_name")} " +
                  $"[{audit.GetProperty("verdict_level")}]: {audit.GetProperty("verdict")}");
foreach (var a in audit.GetProperty("health").EnumerateArray())
{
    Console.WriteLine($"  [{a.GetProperty("status")}] {a.GetProperty("area")}: {a.GetProperty("note")}");
}
foreach (var f in audit.GetProperty("findings").EnumerateArray())
{
    Console.WriteLine($"  ({f.GetProperty("severity")}) {f.GetProperty("category")}: " +
                      $"{f.GetProperty("title")}");
}
foreach (var c in audit.GetProperty("checklist").EnumerateArray())
{
    Console.WriteLine($"  [{c.GetProperty("status")}] {c.GetProperty("item")}: {c.GetProperty("note")}");
}

var rewrite = audit.GetProperty("rewrite");
await File.WriteAllTextAsync(rewrite.GetProperty("filename").GetString()!,   // improved-email.txt
                             rewrite.GetProperty("code").GetString()!);

The model is asked for one JSON object and nothing else, but a stray code fence or preamble is always possible. Strip a leading ```json fence, take the text between the first { and the last }, and only then parse — that is what the app does before it falls back to a retry_note reformat run.

The audit object — output schema

One JSON object, always the same shape. Every array is present (findings is empty only if genuinely nothing applies); health always has exactly the five areas, checklist always has exactly the twelve items, and rewrite.code is never empty. If the paste was too thin to audit responsibly, you still get this object: what is there gets audited, the verdict says the paste is thin, and what you would need to supply — usually the DNS records — lands in next_steps. If the paste is not an email at all, you still get the object — one high-severity finding explaining what arrived, every health area at risk, every checklist item at na, and a rewrite.code saying what to paste instead.

FieldTypeMeaning
audit_namestringA short name for the audit, taken from the email's own subject or campaign (e.g. Order-shipped confirmation).
verdict_levelstringinbox (nothing high or medium remains — this lands), risky (findings exist that will cost placement or engagement) or spam (a high-severity authentication or compliance finding stands, so filtering is likely).
verdictstringOne or two sentences: where this email is headed and the single most important change.
overviewstringTwo or three short paragraphs: what was submitted, and the overall deliverability picture behind what was found.
healtharray of 5{area, status, note} — the five areas listed below, each exactly once. status is good (nothing material), risk (sends today, with caveats) or bad (a high-severity finding lives here). Each note references something concrete in the paste; an area with no evidence supplied — no DNS records, no plain-text part described — is risk, never good.
findingsarray{severity, category, title, detail, fix_code}. severity is high (will materially hurt placement or is a legal/compliance violation — missing or permissive auth records, no unsubscribe in marketing mail, a bought list, an image-only body) | medium (measurable damage — no plain-text part, no preview text, link-text/href mismatch, spam-trigger phrasing) | low (polish — subject length, CTA count, tone); category is authentication, content, compliance, subject, structure or infrastructure. detail quotes the exact phrase, tag, header or DNS token it concerns; fix_code is the corrected artifact — a DNS TXT record, a header line, an HTML snippet or rewritten copy — as plain text, or an empty string when the finding is a judgement call rather than a mechanical fix.
checklistarray of 12{item, status, note} — the twelve deliverability items listed below, each exactly once and in order. status is pass (the paste shows it handled), fail (the paste shows it mishandled — a finding backs this) or na (the paste gives no evidence either way, e.g. DKIM when no records were supplied). The note says what was seen or what is missing.
coverage_checkarray{id, addressed, note} — one entry per prescan_facts item you sent (spf-plus-all, no-unsubscribe, counts, …), saying where the audit covers it or why it was set aside (a keyword hit can be a false positive; the note says so). Nothing you flagged is silently dropped.
rewriteobject{filename, code}filename is normally improved-email.txt for a plain-text paste and improved-email.html for an HTML one, and code is your own email improved. It starts with a Subject: line and a Preview: line, then a blank line, then the body in the same format you pasted: same product, same offer, same voice, spam triggers rephrased, structure fixed, unsubscribe and postal address present where the type requires them. It is a complete replacement for what you pasted, not a fragment.
next_stepsstring[]Ordered and concrete: publish the DNS records first, then fix the content — tighten SPF to -all, add a DKIM selector, publish DMARC at p=none, split the marketing stream off the transactional one, and so on.
summarystring3–5 sentences an email lead could paste into a campaign review.

The five health areas, in order, spelled exactly like this:

areaWhat its note covers
Authentication & identitySPF, DKIM and DMARC published and actually aligned with the From domain; no permissive +all, no lookalike domain, no free-mailbox From on bulk mail.
Content & structureA body that renders everywhere: a plain-text alternative alongside the HTML, a workable image-to-text ratio, alt text, and links whose visible text matches their href.
Compliance & consentA visible one-click unsubscribe and List-Unsubscribe header, a physical postal address, and a list the recipients actually asked to be on — all judged against the declared email_type.
Subject & preheaderSubject length, spam-trigger phrasing, shouting caps and exclamation abuse, and a preheader that extends the subject instead of repeating it or leaking raw HTML.
Infrastructure & sendingTransactional and marketing streams kept apart, a warmed domain and IP, a reputable ESP or relay, and bounce and complaint handling in place.

The twelve checklist items, in order, spelled exactly like this:

itemWhat its note covers
SPF record present and validA single v=spf1 record for the sending domain, including the actual sender and ending in -all or ~all — never +all.
DKIM signing configuredA published selector under _domainkey and signing switched on at the sender, so the body is cryptographically attributable.
DMARC policy publishedA _dmarc TXT record with a policy (p=none while you watch reports, tightening to quarantine or reject) and an rua address.
Plain-text alternative includedA text part generated alongside every HTML send — not an empty part, and not HTML with the tags stripped.
Visible one-click unsubscribeAn unsubscribe link a human can see and use in one click, with no login and no survey — required for everything except genuine transactional mail.
List-Unsubscribe headerList-Unsubscribe and List-Unsubscribe-Post set, so mailbox providers can offer their own native unsubscribe button.
Preview text setA deliberate preheader — hidden block or ESP field — that continues the subject, rather than whatever the first line of markup happens to be.
Balanced image-to-text ratioEnough real text to carry the message with images blocked; no image-only body, no text baked into a single banner.
Single clear call to actionOne primary action, repeated if useful but not competing with three others.
Subject free of spam triggersNo FREE!!!, no all-caps shouting, no $$$, no manufactured urgency, and a length that survives a phone's inbox list.
From aligned with sending domainThe visible From domain matches the domain that SPF and DKIM authenticate, so DMARC alignment passes.
Links match their visible textEvery link points where its text says it points; no URL shorteners and no redirect chains through an unrelated host.

A small, realistic result for the shipping-confirmation paste above, trimmed for length:

{
  "audit_name": "Order-shipped confirmation - fernway.com",
  "verdict_level": "spam",
  "verdict": "The content is fine, but 'v=spf1 +all' authenticates nobody and there is
              no DKIM or DMARC, so this mail is trivially spoofable and will be
              filtered; fix the DNS before touching the copy.",
  "overview": "A short plain-text shipping confirmation for order #58214. As copy it
               is close to ideal for transactional mail: one purpose, one link, a
               postal address and a real reply path. The deliverability problem is
               entirely below the content. fernway.com publishes 'v=spf1 +all', which
               tells receivers every host on the internet is a legitimate sender for
               the domain, and neither DKIM nor DMARC is published at all.

               The notes also say the weekly marketing digest goes out from this same
               address and IP, so a promotional complaint rate will drag receipts down
               with it.",
  "health": [
    { "area": "Authentication & identity", "status": "bad",
      "note": "'v=spf1 +all' passes for any sender; no DKIM selector and no _dmarc
               record were supplied." },
    { "area": "Content & structure", "status": "good",
      "note": "Plain-text body, one link, no images - renders identically everywhere." },
    { "area": "Compliance & consent", "status": "good",
      "note": "Transactional mail, so no opt-in or unsubscribe is required; the postal
               address 'Fernway Goods, 410 Mercer St, Portland OR' is present." },
    { "area": "Subject & preheader", "status": "risk",
      "note": "'Your order has shipped' is clear but omits the order number, and a
               plain-text send has no preheader field." },
    { "area": "Infrastructure & sending", "status": "bad",
      "note": "Notes say the marketing digest shares this address and IP - one
               reputation for two very different streams." }
  ],
  "findings": [
    { "severity": "high", "category": "authentication",
      "title": "SPF ends in +all, so it authorises every sender",
      "detail": "'fernway.com TXT \"v=spf1 +all\"' is a pass for any host on the
                 internet - functionally worse than publishing nothing.",
      "fix_code": "fernway.com. IN TXT \"v=spf1 ip4:203.0.113.10 include:_spf.your-esp.com -all\"" },
    { "severity": "high", "category": "authentication",
      "title": "No DKIM signing and no DMARC policy",
      "detail": "The notes state no selector is published and no DMARC record exists,
                 so receipts carry no verifiable signature and nobody is told what to
                 do with forgeries.",
      "fix_code": "_dmarc.fernway.com. IN TXT \"v=DMARC1; p=none; rua=mailto:dmarc@fernway.com; fo=1\"" },
    { "severity": "high", "category": "infrastructure",
      "title": "Marketing and transactional mail share one sending identity",
      "detail": "'We also send the weekly marketing digest from this same address and
                 IP' - digest complaints will delay or filter order receipts.",
      "fix_code": "orders@fernway.com   -> transactional subdomain (mail.fernway.com)\nnews@fernway.com     -> marketing subdomain (news.fernway.com)" },
    { "severity": "low", "category": "subject",
      "title": "Subject omits the order number recipients search for",
      "detail": "'Your order has shipped' is generic; the body already has #58214.",
      "fix_code": "Subject: Order #58214 has shipped - arriving Thursday" }
  ],
  "checklist": [
    { "item": "SPF record present and valid", "status": "fail",
      "note": "Present but '+all' makes it meaningless." },
    { "item": "DKIM signing configured", "status": "fail",
      "note": "Notes say no selector is published." },
    { "item": "DMARC policy published", "status": "fail",
      "note": "No _dmarc record supplied or claimed." },
    { "item": "Plain-text alternative included", "status": "pass",
      "note": "The send is plain text throughout." },
    { "item": "Visible one-click unsubscribe", "status": "na",
      "note": "Transactional mail - not required, and adding one would be wrong here." },
    { "item": "List-Unsubscribe header", "status": "na",
      "note": "Not applicable to transactional receipts." },
    { "item": "Preview text set", "status": "na",
      "note": "Plain-text sends have no preheader slot." },
    { "item": "Balanced image-to-text ratio", "status": "pass",
      "note": "No images; 38 words of real text." },
    { "item": "Single clear call to action", "status": "pass",
      "note": "One tracking link and nothing competing with it." },
    { "item": "Subject free of spam triggers", "status": "pass",
      "note": "No caps, no punctuation abuse, no trigger phrasing." },
    { "item": "From aligned with sending domain", "status": "fail",
      "note": "orders@fernway.com cannot align while SPF is '+all' and DKIM is absent." },
    { "item": "Links match their visible text", "status": "pass",
      "note": "The bare URL 'https://fernway.com/track/58214' is its own label." }
  ],
  "coverage_check": [
    { "id": "spf-plus-all", "addressed": true,
      "note": "Finding 1 - replace with an explicit include list ending in -all." },
    { "id": "dmarc-absent", "addressed": true,
      "note": "Finding 2 - covered together with the missing DKIM selector." },
    { "id": "plaintext-part", "addressed": true,
      "note": "Confirmed: the body is plain text, so the text-part item passes." },
    { "id": "counts", "addressed": true,
      "note": "38 words, 1 link, 0 images - consistent with the content findings." }
  ],
  "rewrite": { "filename": "improved-email.txt",
               "code": "Subject: Order #58214 has shipped - arriving Thursday\nPreview: Track it any time…" },
  "next_steps": [
    "Publish a real SPF record for fernway.com ending in -all.",
    "Turn on DKIM at the sender and publish the selector under _domainkey.fernway.com.",
    "Publish _dmarc.fernway.com at p=none with rua, read a week of reports, then tighten.",
    "Move the weekly digest to its own subdomain so receipts stop sharing its reputation."
  ],
  "summary": "The copy is what a transactional receipt should be; the DNS is what gets it
              filtered. …"
}

The audit is a starting point, not a sign-off: it is written to be complete and self-consistent with the findings, but it is AI-generated and it only sees what you pasted — no DNS lookup, no seed-list test, no reputation data. Verify the records with dig, send a seed test through your own ESP, and keep a human in the loop before a real send.

Step 5 — Stream the audit as it is written

POST /run-stream

/run-stream takes exactly the same body as /run but answers with server-sent events, so you can show progress instead of a spinner — useful here because the improved email makes for a long reply. This app's own progress panel is this endpoint. Events are separated by a blank line; each has an event: line and a data: line carrying JSON.

EventPayloadMeaning
job{job_id, status}Sent once, when the job is accepted — show "starting".
delta{text}A chunk of the reply, in order. Append it; the accumulated length is your only progress signal (the total is not known in advance).
done{job_id, status, charged_credits, output}The final, authoritative result — read the audit from output.output rather than trusting concatenated deltas, and the settled price from charged_credits.
error{code, message}Replaces done when the run fails.
# -N disables buffering so events print as they arrive
curl -N -s -X POST "$API/run-stream" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -H "Idempotency-Key: audit-$(date +%s)" \
  -d @input.json

# event: job
# data: {"job_id":"job_...","status":"running"}
#
# event: delta
# data: {"text":"{\"audit_name\":\"Order-shipped confirmation"}
# ...
# event: done
# data: {"job_id":"job_...","status":"succeeded","charged_credits":548,"output":{"output":"{...}"}}
import json, requests

result = None
with requests.post(
    API + "/run-stream",
    headers={"Authorization": f"Bearer {TOKEN}",
             "Idempotency-Key": "audit-001"},
    json=payload,
    stream=True,
) as r:
    r.raise_for_status()
    event = None
    for line in r.iter_lines(decode_unicode=True):
        if not line:
            continue
        if line.startswith("event:"):
            event = line[len("event:"):].strip()
        elif line.startswith("data:"):
            data = json.loads(line[len("data:"):].strip())
            if event == "delta":
                print(".", end="", flush=True)          # live progress
            elif event == "done":
                result = data
            elif event == "error":
                raise RuntimeError(data.get("message", "run failed"))

audit = json.loads(result["output"]["output"])          # authoritative
print("charged:", result["charged_credits"], "-", audit["audit_name"])
for area in audit["health"]:
    print(f'  [{area["status"]}] {area["area"]}')
open(audit["rewrite"]["filename"], "w", encoding="utf-8").write(audit["rewrite"]["code"])
const res = await fetch(API + "/run-stream", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${TOKEN}`,
    "Content-Type": "application/json",
    "Idempotency-Key": crypto.randomUUID(),
  },
  body: JSON.stringify(payload),
});

const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "", done = null;

for (;;) {
  const chunk = await reader.read();
  if (chunk.done) break;
  buf += decoder.decode(chunk.value, { stream: true });
  const frames = buf.split("\n\n");
  buf = frames.pop();
  for (const frame of frames) {
    const name = /^event:\s*(.+)$/m.exec(frame)?.[1];
    const body = /^data:\s*(.+)$/m.exec(frame)?.[1];
    if (!name || !body) continue;
    const data = JSON.parse(body);
    if (name === "delta") process.stdout.write(".");   // live progress
    if (name === "done") done = data;
    if (name === "error") throw new Error(data.message ?? "run failed");
  }
}

const audit = JSON.parse(done.output.output);
console.log(`\n${done.charged_credits} credits - ${audit.audit_name}`);
for (const area of audit.health) console.log(`  [${area.status}] ${area.area}`);
writeFileSync(audit.rewrite.filename, audit.rewrite.code);   // improved-email.txt
body, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", API+"/run-stream", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "audit-001")

res, err := http.DefaultClient.Do(req)
if err != nil {
	log.Fatal(err)
}
defer res.Body.Close()

var event string
var final map[string]any
sc := bufio.NewScanner(res.Body)
sc.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
for sc.Scan() {
	line := sc.Text()
	switch {
	case strings.HasPrefix(line, "event:"):
		event = strings.TrimSpace(strings.TrimPrefix(line, "event:"))
	case strings.HasPrefix(line, "data:"):
		var data map[string]any
		json.Unmarshal([]byte(strings.TrimPrefix(line, "data:")), &data)
		switch event {
		case "delta":
			fmt.Print(".") // live progress
		case "done":
			final = data
		case "error":
			log.Fatal(data["message"])
		}
	}
}
// final["output"].(map[string]any)["output"].(string) is the audit JSON —
// unmarshal it into the Audit struct from step 4, then write audit.Rewrite.Code to disk.
// Java 17+ — read the stream line by line instead of buffering the body.
var req = HttpRequest.newBuilder(URI.create(API + "/run-stream"))
    .header("Authorization", "Bearer " + TOKEN)
    .header("Content-Type", "application/json")
    .header("Idempotency-Key", "audit-001")
    .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
    .build();

var res = HTTP.send(req, HttpResponse.BodyHandlers.ofLines());
String event = null, done = null;
for (String line : (Iterable<String>) res.body()::iterator) {
    if (line.startsWith("event:")) {
        event = line.substring(6).trim();
    } else if (line.startsWith("data:")) {
        String data = line.substring(5).trim();
        if ("delta".equals(event)) System.out.print(".");   // live progress
        else if ("done".equals(event)) done = data;
        else if ("error".equals(event)) throw new RuntimeException(data);
    }
}
// parse `done`, then parse data.output.output again — it is a JSON string holding
// audit_name, verdict_level, health[], findings[], checklist[], rewrite{filename, code} and the rest.
require "net/http"
require "json"

uri = URI(API + "/run-stream")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{TOKEN}"
req["Content-Type"] = "application/json"
req["Idempotency-Key"] = "audit-001"
req.body = payload.to_json

event = nil
done = nil
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
  http.request(req) do |res|
    res.read_body do |chunk|
      chunk.each_line do |line|
        line = line.strip
        if line.start_with?("event:")
          event = line.delete_prefix("event:").strip
        elsif line.start_with?("data:")
          data = JSON.parse(line.delete_prefix("data:").strip)
          case event
          when "delta" then print "."           # live progress
          when "done"  then done = data
          when "error" then raise (data["message"] || "run failed")
          end
        end
      end
    end
  end
end

audit = JSON.parse(done["output"]["output"])
puts "\n#{done["charged_credits"]} credits - #{audit["audit_name"]}"
audit["health"].each { |a| puts "  [#{a["status"]}] #{a["area"]}" }
File.write(audit["rewrite"]["filename"], audit["rewrite"]["code"])   # improved-email.txt
$event = null;
$done  = null;

$ch = curl_init(API . "/run-stream");
curl_setopt_array($ch, [
    CURLOPT_POST       => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $TOKEN",
        "Content-Type: application/json",
        "Idempotency-Key: audit-001",
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_WRITEFUNCTION => function ($ch, $chunk) use (&$event, &$done) {
        foreach (explode("\n", $chunk) as $line) {
            $line = trim($line);
            if (str_starts_with($line, "event:")) {
                $event = trim(substr($line, 6));
            } elseif (str_starts_with($line, "data:")) {
                $data = json_decode(trim(substr($line, 5)), true);
                if ($event === "delta") { echo "."; }        // live progress
                elseif ($event === "done") { $done = $data; }
                elseif ($event === "error") { throw new Exception($data["message"] ?? "run failed"); }
            }
        }
        return strlen($chunk);
    },
]);
curl_exec($ch);
curl_close($ch);

$audit = json_decode($done["output"]["output"], true);
echo "\n{$done['charged_credits']} credits - {$audit['audit_name']}\n";
foreach ($audit["health"] as $a) { echo "  [{$a['status']}] {$a['area']}\n"; }
file_put_contents($audit["rewrite"]["filename"], $audit["rewrite"]["code"]);   // improved-email.txt
var req = new HttpRequestMessage(HttpMethod.Post, Api + "/run-stream") {
    Content = JsonContent.Create(payload),
};
req.Headers.Add("Idempotency-Key", "audit-001");

using var res = await Http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead);
using var reader = new StreamReader(await res.Content.ReadAsStreamAsync());

string? evt = null, done = null;
while (await reader.ReadLineAsync() is { } line)
{
    if (line.StartsWith("event:")) evt = line[6..].Trim();
    else if (line.StartsWith("data:"))
    {
        var data = line[5..].Trim();
        if (evt == "delta") Console.Write(".");            // live progress
        else if (evt == "done") done = data;
        else if (evt == "error") throw new Exception(data);
    }
}

using var final = JsonDocument.Parse(done!);
var text = final.RootElement.GetProperty("output").GetProperty("output").GetString();
using var auditDoc = JsonDocument.Parse(text!);
var audit = auditDoc.RootElement;
Console.WriteLine(audit.GetProperty("audit_name"));
foreach (var a in audit.GetProperty("health").EnumerateArray())
    Console.WriteLine($"  [{a.GetProperty("status")}] {a.GetProperty("area")}");
var rewrite = audit.GetProperty("rewrite");
await File.WriteAllTextAsync(rewrite.GetProperty("filename").GetString()!,   // improved-email.txt
                             rewrite.GetProperty("code").GetString()!);

In a browser, the native EventSource only speaks GET, and this endpoint is a POST — read the fetch response body incrementally, as the JavaScript sample above does. On an idempotent replay the server may answer with a plain JSON envelope instead of an event stream; check the Content-Type before you start parsing frames.