Outreach Desk — API

Company facts and investor context in, a sendable draft out.

API tokens Open the app

Draft investor outreach from your own scripts

Send one labelled text block — what the company does, what you know about the investor, the mode — and get back a Markdown reply with a fixed set of ## sections: a subject line, a sendable message, a personalization map that traces every tailored line to a fact you supplied, a follow-up cadence, a quality gate and the gaps worth filling. Wire it into a CRM, a fundraise tracker, or a script that turns a list of target funds into a folder of drafts you still have to read before sending. 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 outreach-desk. 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. Drafts are written by the gpt-terra model. Estimates are free; runs are metered against your credit balance. There is a single run task — one block in, one draft 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 sending a very large block).
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 draft 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":"outreach-desk"}' | jq -r '.data.token'
token = api("POST", "/guest", {"slug": "outreach-desk"})["token"]
const { token } = await api("POST", "/guest", { slug: "outreach-desk" });
var guest struct{ Token string `json:"token"` }
err := call("POST", "/guest", map[string]string{"slug": "outreach-desk"}, &guest)
String envelope = api("POST", "/guest", """
    {"slug":"outreach-desk"}""");
// token is at data.token in the returned JSON
token = api("POST", "/guest", { slug: "outreach-desk" })["token"]
$token = api("POST", "/guest", ["slug" => "outreach-desk"])["token"];
var guest = await SkillSafe.ApiAsync(HttpMethod.Post, "/guest",
    new { slug = "outreach-desk" });
var token = guest.GetProperty("token").GetString();

The app stores this browser's token under the localStorage key skillsafe_app_token:outreach-desk, 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. The app compares this balance against the estimate's hold_credits before it enables the run button; do the same before you loop over a list of funds.

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");

The input block

The request body has two fields the app always sends, and one it sets only on a reformat retry. Everything the model reads lives in input: a single plain-text block with six labelled sections, always present and always in this order. An unfilled optional field is sent as the literal (none supplied) — do not drop the label.

FieldTypeNotes
inputstring, requiredThe labelled block below. The web UI builds it from the form; you build it from whatever your data source is.
modestringcold | warm_intro | followup | update. It also appears on the block's MODE: line; send both, matching. The mode decides which output sections are required and what the message word ceiling is.
retry_notestring, optionalOnly set by the app's automatic reformat retry when a first reply did not follow the output contract. Leave it out.

The exact block format, as app.js composes it:

MODE: cold

COMPANY:
<what the company does, traction, proof points, the round>

INVESTOR:
<fund and partner, thesis, portfolio companies, talks or posts, mutual connections>

CONTEXT:
<mode-specific extras — the prior thread, the meeting, the connector>

ASK:
<the concrete next step you want, or (none supplied)>

PRESCAN:
- word counts: company 24, investor 19, context 0, ask 5
- personalization signals detected in the investor/context text: portfolio, post
- banned or softener phrases already present in the supplied context/ask: none
- an explicit ask was supplied by the user
- message word ceiling for this mode: 180 words
Block sectionWhat belongs in it
MODE:One of the four modes, on the same line as the label.
COMPANY:What the company does and the numbers that prove it. The draft may only use proof that appears here — nothing is invented, and a thin company section produces a thin email plus entries in ## Gaps.
INVESTOR:Fund and partner, thesis, portfolio companies, a post or talk, mutual connections. Whatever is missing here cannot be personalized; it will be reported as missing rather than faked. Optional for update.
CONTEXT:Mode-specific: the prior thread for followup, what was promised in the meeting for update, how the connector is known for warm_intro.
ASK:The one concrete next step. Send (none supplied) and the draft proposes one.
PRESCAN:Facts a client-side lint counted: exact word counts, which personalization signals matched (portfolio, thesis, post, mutual, fit), any banned or softener phrase already sitting in the supplied text, whether an ask was supplied, and the word ceiling for the mode. It makes the quality gate checkable — the same lint re-runs on the returned message. You may compute your own; keep the line shapes.

Fields longer than 12,000 characters are clipped middle-out by the web UI, with a [... N characters cut from the middle of this field ...] marker in place of what was removed. Do the same rather than truncating the tail: a follow-up thread carries its point at the end.

Step 3 — Estimate the cost

POST /estimate

Send exactly the body you would send to /run; the response's hold_credits is the worst-case cost and min_credits is the floor below which the run will not start. Nothing is charged and no job is created, so estimating is free — useful when you are about to draft against forty funds and want a ceiling first.

cat > block.txt <<'BLOCK'
MODE: cold

COMPANY:
Halyard replaces the whiteboard nursing units use to build shift schedules.
14 hospitals live, $612k ARR, 128% net revenue retention. Raising a $4M seed.

INVESTOR:
Mira Kovac, partner at Northbank Capital. Wrote the essay "Buy the whiteboard".
Led the seed in Pallet Health (nurse credentialing).

CONTEXT:
(none supplied)

ASK:
20 minutes Thursday or Friday

PRESCAN:
- word counts: company 24, investor 19, context 0, ask 5
- personalization signals detected in the investor/context text: portfolio, post
- banned or softener phrases already present in the supplied context/ask: none
- an explicit ask was supplied by the user
- message word ceiling for this mode: 180 words
BLOCK

jq -n --rawfile b block.txt '{input: $b, mode: "cold"}' > input.json

curl -s -X POST "$API/estimate" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d @input.json | jq '.data | {hold_credits, min_credits, model}'
BLOCK = """MODE: cold

COMPANY:
Halyard replaces the whiteboard nursing units use to build shift schedules.
14 hospitals live, $612k ARR, 128% net revenue retention. Raising a $4M seed.

INVESTOR:
Mira Kovac, partner at Northbank Capital. Wrote the essay "Buy the whiteboard".
Led the seed in Pallet Health (nurse credentialing).

CONTEXT:
(none supplied)

ASK:
20 minutes Thursday or Friday

PRESCAN:
- word counts: company 24, investor 19, context 0, ask 5
- personalization signals detected in the investor/context text: portfolio, post
- banned or softener phrases already present in the supplied context/ask: none
- an explicit ask was supplied by the user
- message word ceiling for this mode: 180 words"""

payload = {"input": BLOCK, "mode": "cold"}

est = api("POST", "/estimate", payload)
print("worst case:", est["hold_credits"], "credits on", est["model"])
const block = `MODE: cold

COMPANY:
Halyard replaces the whiteboard nursing units use to build shift schedules.
14 hospitals live, $612k ARR, 128% net revenue retention. Raising a $4M seed.

INVESTOR:
Mira Kovac, partner at Northbank Capital. Wrote the essay "Buy the whiteboard".
Led the seed in Pallet Health (nurse credentialing).

CONTEXT:
(none supplied)

ASK:
20 minutes Thursday or Friday

PRESCAN:
- word counts: company 24, investor 19, context 0, ask 5
- personalization signals detected in the investor/context text: portfolio, post
- banned or softener phrases already present in the supplied context/ask: none
- an explicit ask was supplied by the user
- message word ceiling for this mode: 180 words`;

const payload = { input: block, mode: "cold" };

const est = await api("POST", "/estimate", payload);
console.log("worst case:", est.hold_credits, "credits on", est.model);
const block = `MODE: cold

COMPANY:
Halyard replaces the whiteboard nursing units use to build shift schedules.
14 hospitals live, $612k ARR, 128% net revenue retention. Raising a $4M seed.

INVESTOR:
Mira Kovac, partner at Northbank Capital. Wrote the essay "Buy the whiteboard".
Led the seed in Pallet Health (nurse credentialing).

CONTEXT:
(none supplied)

ASK:
20 minutes Thursday or Friday

PRESCAN:
- word counts: company 24, investor 19, context 0, ask 5
- personalization signals detected in the investor/context text: portfolio, post
- banned or softener phrases already present in the supplied context/ask: none
- an explicit ask was supplied by the user
- message word ceiling for this mode: 180 words`

payload := map[string]any{"input": block, "mode": "cold"}

var est struct {
	HoldCredits int64  `json:"hold_credits"`
	MinCredits  int64  `json:"min_credits"`
	Model       string `json:"model"`
}
err := call("POST", "/estimate", payload, &est)
String block = """
    MODE: cold

    COMPANY:
    Halyard replaces the whiteboard nursing units use to build shift schedules.
    14 hospitals live, $612k ARR, 128% net revenue retention. Raising a $4M seed.

    INVESTOR:
    Mira Kovac, partner at Northbank Capital. Wrote the essay "Buy the whiteboard".
    Led the seed in Pallet Health (nurse credentialing).

    CONTEXT:
    (none supplied)

    ASK:
    20 minutes Thursday or Friday

    PRESCAN:
    - word counts: company 24, investor 19, context 0, ask 5
    - personalization signals detected in the investor/context text: portfolio, post
    - banned or softener phrases already present in the supplied context/ask: none
    - an explicit ask was supplied by the user
    - message word ceiling for this mode: 180 words""";

// toJsonString() is your JSON library's string escaper
String jsonPayload = """
    {"input": %s, "mode": "cold"}""".formatted(toJsonString(block));

String envelope = api("POST", "/estimate", jsonPayload);
// worst-case cost is at data.hold_credits
BLOCK = <<~TEXT
  MODE: cold

  COMPANY:
  Halyard replaces the whiteboard nursing units use to build shift schedules.
  14 hospitals live, $612k ARR, 128% net revenue retention. Raising a $4M seed.

  INVESTOR:
  Mira Kovac, partner at Northbank Capital. Wrote the essay "Buy the whiteboard".
  Led the seed in Pallet Health (nurse credentialing).

  CONTEXT:
  (none supplied)

  ASK:
  20 minutes Thursday or Friday

  PRESCAN:
  - word counts: company 24, investor 19, context 0, ask 5
  - personalization signals detected in the investor/context text: portfolio, post
  - banned or softener phrases already present in the supplied context/ask: none
  - an explicit ask was supplied by the user
  - message word ceiling for this mode: 180 words
TEXT

payload = { input: BLOCK, mode: "cold" }

est = api("POST", "/estimate", payload)
puts "worst case: #{est["hold_credits"]} credits on #{est["model"]}"
$block = <<<'TEXT'
MODE: cold

COMPANY:
Halyard replaces the whiteboard nursing units use to build shift schedules.
14 hospitals live, $612k ARR, 128% net revenue retention. Raising a $4M seed.

INVESTOR:
Mira Kovac, partner at Northbank Capital. Wrote the essay "Buy the whiteboard".
Led the seed in Pallet Health (nurse credentialing).

CONTEXT:
(none supplied)

ASK:
20 minutes Thursday or Friday

PRESCAN:
- word counts: company 24, investor 19, context 0, ask 5
- personalization signals detected in the investor/context text: portfolio, post
- banned or softener phrases already present in the supplied context/ask: none
- an explicit ask was supplied by the user
- message word ceiling for this mode: 180 words
TEXT;

$payload = ["input" => $block, "mode" => "cold"];

$est = api("POST", "/estimate", $payload);
echo "worst case: {$est['hold_credits']} credits on {$est['model']}\n";
var block = """
    MODE: cold

    COMPANY:
    Halyard replaces the whiteboard nursing units use to build shift schedules.
    14 hospitals live, $612k ARR, 128% net revenue retention. Raising a $4M seed.

    INVESTOR:
    Mira Kovac, partner at Northbank Capital. Wrote the essay "Buy the whiteboard".
    Led the seed in Pallet Health (nurse credentialing).

    CONTEXT:
    (none supplied)

    ASK:
    20 minutes Thursday or Friday

    PRESCAN:
    - word counts: company 24, investor 19, context 0, ask 5
    - personalization signals detected in the investor/context text: portfolio, post
    - banned or softener phrases already present in the supplied context/ask: none
    - an explicit ask was supplied by the user
    - message word ceiling for this mode: 180 words
    """;

var payload = new { input = block, mode = "cold" };

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

PRESCAN is how you make the draft answer for what you already counted. Send the real word counts and the phrases your own text contains, and the returned ## Quality Gate has to survive being compared against them — which is exactly what the web UI's "Lint vs model" card does after every run.

Step 4 — Write the draft and wait for it

POST /run
GET /jobs/{job_id}

/run takes the same body 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 15–45 s). Always send an Idempotency-Key header so a network retry cannot start a second, double-charged run. The draft is in output — usually nested as output.output — as one Markdown string you split on ## headings.

JOB_ID=$(curl -s -X POST "$API/run" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -H "Idempotency-Key: draft-$(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

echo "$JOB" | jq -r '.data.output.output' > draft.md

# the subject and the body, which is all you need to send it
awk '/^## Subject$/{f="s";next} /^## Message$/{f="m";next} /^## /{f=""} f=="s"&&NF{print "SUBJECT: "$0} f=="m"{print}' draft.md
import re, time

job_id = api("POST", "/run", payload,
             **{"Idempotency-Key": "draft-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"]

def sections(md):
    out, name, buf = {}, None, []
    for line in md.splitlines():
        m = re.match(r"^\s{0,3}#{2,3}\s+(.+?)\s*$", line)
        if m:
            if name:
                out[name] = "\n".join(buf).strip()
            name, buf = m.group(1), []
        elif name:
            buf.append(line)
    if name:
        out[name] = "\n".join(buf).strip()
    return out

draft = sections(raw)
print("SUBJECT:", draft["Subject"])
print(draft["Message"])
print("--- gate ---")
print(draft["Quality Gate"])
print("--- gaps ---")
print(draft["Gaps"])
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;

function sections(md) {
  const out = {};
  let name = null, buf = [];
  for (const line of md.split("\n")) {
    const m = /^\s{0,3}#{2,3}\s+(.+?)\s*$/.exec(line);
    if (m) {
      if (name) out[name] = buf.join("\n").trim();
      name = m[1];
      buf = [];
    } else if (name) buf.push(line);
  }
  if (name) out[name] = buf.join("\n").trim();
  return out;
}

const draft = sections(raw);
console.log("SUBJECT:", draft["Subject"]);
console.log(draft["Message"]);
console.log(draft["Quality Gate"]);
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)
}

var wrapper struct{ Output string `json:"output"` }
json.Unmarshal(job.Output, &wrapper)

// split the Markdown into sections
head := regexp.MustCompile(`(?m)^\s{0,3}#{2,3}\s+(.+?)\s*$`)
sections := map[string]string{}
name := ""
start := 0
for _, loc := range head.FindAllStringSubmatchIndex(wrapper.Output, -1) {
	if name != "" {
		sections[name] = strings.TrimSpace(wrapper.Output[start:loc[0]])
	}
	name = wrapper.Output[loc[2]:loc[3]]
	start = loc[1]
}
if name != "" {
	sections[name] = strings.TrimSpace(wrapper.Output[start:])
}

fmt.Println("SUBJECT:", sections["Subject"])
fmt.Println(sections["Message"])
fmt.Println(sections["Quality Gate"])
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 draft is at data.output.output as one Markdown string. Split it on lines
// matching ^\s{0,3}#{2,3}\s+(.+)$ into a Map<String,String> keyed by heading:
//   Subject, Message, Forwardable Blurb (warm_intro only), Alternates,
//   Personalization Map, Follow-Up Plan, Quality Gate, Gaps.
// Send Subject + Message; log Quality Gate and Gaps for the human to read.
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"]

def sections(md)
  out = {}
  name = nil
  buf = []
  md.each_line do |line|
    if (m = line.match(/\A\s{0,3}\#{2,3}\s+(.+?)\s*\z/))
      out[name] = buf.join.strip if name
      name = m[1]
      buf = []
    elsif name
      buf << line
    end
  end
  out[name] = buf.join.strip if name
  out
end

draft = sections(raw)
puts "SUBJECT: #{draft["Subject"]}"
puts draft["Message"]
puts draft["Quality Gate"]
$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"];

function sections(string $md): array {
    $out = [];
    $name = null;
    $buf = [];
    foreach (explode("\n", $md) as $line) {
        if (preg_match('/^\s{0,3}#{2,3}\s+(.+?)\s*$/', $line, $m)) {
            if ($name !== null) { $out[$name] = trim(implode("\n", $buf)); }
            $name = $m[1];
            $buf = [];
        } elseif ($name !== null) {
            $buf[] = $line;
        }
    }
    if ($name !== null) { $out[$name] = trim(implode("\n", $buf)); }
    return $out;
}

$draft = sections($raw);
echo "SUBJECT: {$draft['Subject']}\n";
echo $draft["Message"] . "\n";
echo $draft["Quality Gate"] . "\n";
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 raw = job.GetProperty("output").GetProperty("output").GetString()!;

static Dictionary<string, string> Sections(string md)
{
    var outMap = new Dictionary<string, string>();
    string? name = null;
    var buf = new List<string>();
    foreach (var line in md.Split('\n'))
    {
        var m = System.Text.RegularExpressions.Regex.Match(line, @"^\s{0,3}#{2,3}\s+(.+?)\s*$");
        if (m.Success)
        {
            if (name != null) outMap[name] = string.Join("\n", buf).Trim();
            name = m.Groups[1].Value;
            buf.Clear();
        }
        else if (name != null) buf.Add(line);
    }
    if (name != null) outMap[name] = string.Join("\n", buf).Trim();
    return outMap;
}

var draft = Sections(raw);
Console.WriteLine($"SUBJECT: {draft["Subject"]}");
Console.WriteLine(draft["Message"]);
Console.WriteLine(draft["Quality Gate"]);

The model is asked for headings and nothing else, but a stray code fence or preamble is always possible. Strip a leading ``` fence and ignore anything before the first ## line — that is what the app does before it falls back to a retry_note reformat run, reusing the same idempotency key derived from the input so the retry cannot double-bill.

The draft — output contract

One Markdown reply, parsed by ## heading into a map and rendered in this fixed order. Section names are spelled exactly as below. Optional sections may be absent entirely — treat a missing heading as "nothing here", never as an error, and never render an empty header for it. Required sections depend on the mode.

SectionRequired inContent
## Subjectevery modeOne line, eight words or fewer. For warm_intro this is the subject of the email to the connector.
## Messageevery modeThe email body, ready to send, plain text with blank lines between paragraphs. [Your name] stands in for an unknown sender.
## Forwardable Blurbwarm_intro onlyA single paragraph under 100 words the connector forwards untouched. Absent in every other mode — if it appears there, ignore it.
## AlternatesoptionalBullet list of two alternate subject lines.
## Personalization Mapevery modeBullets - <element in the message> — <the input fact it ties to>. Every personalized element traces to something you sent. When the input supplied no personalization material, this section says so in words instead of inventing a tie.
## Follow-Up Plancold, followupBullets - Day 0: …, - Day 4-5: …, - Day 10-12: …. Three touches, then stop.
## Quality Gateevery modeFive bullets, each - <check>: pass|fail — <note>, for Personalized, Explicit ask, Concrete proof, Banned phrases and Word count, in that order.
## Gapsevery modeBullets naming the missing information worth supplying next time, or the single bullet - None.

A real reply for the Halyard block above, trimmed for length:

## Subject

Whiteboard replaced: 14 hospitals, 128% NRR

## Message

Mira -

"Buy the whiteboard" is close to a literal description of what we sell: nursing
units build shift schedules on a whiteboard and a group chat, and Halyard
replaces that process.

Where we are: 14 hospitals live, ARR $612k, 128% net revenue retention.

We are raising a $4M seed. Are you open to 20 minutes Thursday or Friday to walk
through the retention numbers?

- [Your name], co-founder, Halyard

## Alternates

- 11 unfilled shifts a month to 2, in six weeks
- Operator-sold scheduling: 14 hospitals, 128% NRR

## Personalization Map

- Opening line about "Buy the whiteboard" - your essay of that title, named in the
  investor notes
- "the same operator-led motion as Pallet Health" - the nurse-credentialing seed
  you led

## Follow-Up Plan

- Day 0: send this email.
- Day 4-5: two lines with one new data point and the same 20-minute ask.
- Day 10-12: final note with a clean close.

## Quality Gate

- Personalized: pass - the opening quotes a named essay and a portfolio company is
  used as the comparison.
- Explicit ask: pass - one ask, "20 minutes Thursday or Friday".
- Concrete proof: pass - 14 hospitals, $612k ARR, 128% NRR, all supplied.
- Banned phrases: pass - no connect-request language, no soft closing question.
- Word count: pass - 166 words in the body, under the 180-word ceiling.

## Gaps

- The sender's name and title are placeholders.
- No round detail beyond the $4M size: no lead status, no target close.

Nothing factual in a draft is invented: every number, portfolio company and connection comes from the block you sent, and anything missing is named in ## Gaps instead. That also means the draft is only as good as the INVESTOR section — send thin investor notes and the quality gate will honestly return Personalized: fail. Read the gate and the gaps before you send anything.

Step 5 — Stream the draft 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. The app's own progress panel is this endpoint: it advances its stages when ## Subject, ## Message and ## Quality Gate arrive in the delta stream. 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 "request accepted".
delta{text}A chunk of the reply, in order. Append it; the headings that have arrived are your progress signal.
done{job_id, status, charged_credits, truncated, output}The final, authoritative result — read the draft from output.output rather than trusting concatenated deltas. truncated: true means the balance cut the reply short; render what parsed and say so.
error{code, message}Replaces done when the run fails. Anything already accumulated is still worth parsing.
# -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: draft-$(date +%s)" \
  -d @input.json

# event: job
# data: {"job_id":"job_...","status":"running"}
#
# event: delta
# data: {"text":"## Subject\n\nWhiteboard replaced"}
# ...
# event: done
# data: {"job_id":"job_...","status":"succeeded","charged_credits":410,"output":{"output":"## Subject\n..."}}
import json, requests

result = None
with requests.post(
    API + "/run-stream",
    headers={"Authorization": f"Bearer {TOKEN}",
             "Idempotency-Key": "draft-001"},
    json=payload,
    stream=True,
) as r:
    r.raise_for_status()
    event, acc = 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":
                acc += data.get("text", "")
                if "## Message" in acc:
                    print("\rwriting the message…", end="")
            elif event == "done":
                result = data
            elif event == "error":
                raise RuntimeError(data.get("message", "run failed"))

draft = sections(result["output"]["output"])   # authoritative
print("charged:", result["charged_credits"])
print(draft["Subject"])
print(draft["Message"])
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 = "", acc = "", 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") acc += data.text ?? "";      // live progress
    if (name === "done") done = data;
    if (name === "error") throw new Error(data.message ?? "run failed");
  }
}

const draft = sections(done?.output?.output ?? acc);
console.log(draft["Subject"]);
console.log(draft["Message"]);
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", "draft-001")

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

var event string
var acc strings.Builder
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":
			if t, ok := data["text"].(string); ok {
				acc.WriteString(t)
			}
		case "done":
			final = data
		case "error":
			log.Fatal(data["message"])
		}
	}
}
// final["output"].(map[string]any)["output"].(string) is the Markdown draft —
// split it with the same heading regexp from step 4.
// 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", "draft-001")
    .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
    .build();

var res = HTTP.send(req, HttpResponse.BodyHandlers.ofLines());
String event = null, done = null;
var acc = new StringBuilder();
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)) acc.append(data);        // live progress
        else if ("done".equals(event)) done = data;
        else if ("error".equals(event)) throw new RuntimeException(data);
    }
}
// parse `done`, read data.output.output, then split it on "## " headings as in step 4.
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"] = "draft-001"
req.body = payload.to_json

event = nil
done = nil
acc = +""
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 acc << data.fetch("text", "")
          when "done"  then done = data
          when "error" then raise (data["message"] || "run failed")
          end
        end
      end
    end
  end
end

draft = sections(done["output"]["output"])
puts "#{done["charged_credits"]} credits"
puts draft["Subject"]
puts draft["Message"]
$event = null;
$done  = null;
$acc   = "";

$ch = curl_init(API . "/run-stream");
curl_setopt_array($ch, [
    CURLOPT_POST       => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $TOKEN",
        "Content-Type: application/json",
        "Idempotency-Key: draft-001",
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_WRITEFUNCTION => function ($ch, $chunk) use (&$event, &$done, &$acc) {
        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") { $acc .= $data["text"] ?? ""; }
                elseif ($event === "done") { $done = $data; }
                elseif ($event === "error") { throw new Exception($data["message"] ?? "run failed"); }
            }
        }
        return strlen($chunk);
    },
]);
curl_exec($ch);
curl_close($ch);

$draft = sections($done["output"]["output"]);
echo "{$done['charged_credits']} credits\n";
echo $draft["Subject"] . "\n";
echo $draft["Message"] . "\n";
var req = new HttpRequestMessage(HttpMethod.Post, Api + "/run-stream") {
    Content = JsonContent.Create(payload),
};
req.Headers.Add("Idempotency-Key", "draft-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 == "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()!;
var draft = Sections(text);
Console.WriteLine(draft["Subject"]);
Console.WriteLine(draft["Message"]);

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. If the stream dies mid-flight, parse what you accumulated: the sections are ordered so that Subject and Message arrive first.