Talk Lens — API

Paste a meeting transcript, get a communication-pattern review with the exact lines.

API tokens Open the app

Review how a meeting was actually talked through, from your own scripts

Send a meeting transcript — speaker-labeled lines, a Zoom or Meet export, VTT or SRT cue text — and get back one JSON object: a strong / mixed / needs-work verdict, a health check across five communication areas, the patterns that shaped the meeting ranked by severity, each quoted verbatim from the transcript with a better phrasing, a twelve-item checklist scored against what was said, and ordered next steps. Everything this app does goes through the SkillSafe App API — plain JSON over HTTPS — so you can wire the review into a post-meeting digest, a coaching log that tracks one person across a quarter, or a script that reviews every recorded 1:1 in a folder. 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 talk-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 review 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 transcript in, one review 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 reviewing a very long transcript).
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 review 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":"talk-lens"}' | jq -r '.data.token'
token = api("POST", "/guest", {"slug": "talk-lens"})["token"]
const { token } = await api("POST", "/guest", { slug: "talk-lens" });
var guest struct{ Token string `json:"token"` }
err := call("POST", "/guest", map[string]string{"slug": "talk-lens"}, &guest)
String envelope = api("POST", "/guest", """
    {"slug":"talk-lens"}""");
// token is at data.token in the returned JSON
token = api("POST", "/guest", { slug: "talk-lens" })["token"]
$token = api("POST", "/guest", ["slug" => "talk-lens"])["token"];
var guest = await SkillSafe.ApiAsync(HttpMethod.Post, "/guest",
    new { slug = "talk-lens" });
var token = guest.GetProperty("token").GetString();

The app stores this browser's token under the localStorage key skillsafe_app_token:talk-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 reviewing an hour-long transcript.

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 full hour of recording or a folder of weekly 1:1s and want a ceiling before spending credits.

Input fieldTypeNotes
transcriptstring, requiredThe meeting transcript to review: speaker-labeled lines (Name: …), optionally carrying [hh:mm:ss] or (mm:ss) timestamps, or raw VTT/SRT cue text. Very long transcripts may be clipped middle-out, with a [... clipped ...] marker showing where; the review never treats that marker as speech and never guesses at what was removed.
self_namestring, optionalThe speaker the coaching centers on, spelled the way it appears in the transcript's labels. Leave it empty to review the meeting as a whole — the coaching then centers on the speaker with the most influence on how the meeting went.
focusstringfull | conflict | balance | listening | facilitation — what you want out of the review. full (the default) weighs everything by what the transcript shows; conflict leads with directness, candor and tension-handling; balance leads with speaking ratios, interruptions and filler words; listening leads with questions, acknowledgment and building on others; facilitation leads with agenda, inclusion, decisions and action items. Every section still comes back whichever you pick — only the weighting and the depth of the patterns change.
notesstring, optionalExtra context or questions for the reviewer: what the meeting was for, a relationship history the transcript does not show, a habit you are already working on, a question you want answered.
prescan_factsobject, optionalWhat a client-side scanner mechanically counted before the run: {"speakers": [], "signals": {}}. speakers holds one {id, label, turns, words, talk_pct, questions, fillers, hedges, longest_turn_words} entry per detected speaker, with ids like spk-alex. signals is a counter object: {"format": "labeled", "lines": 0, "words": 0, "speaker_count": 0, "timestamps": 0, "duration_min": 0}. These are pattern-matched counts, not judgement — every speaker id you send comes back in coverage_check, and where the review's own reading disagrees with a count it says so in the relevant pattern's detail. The web UI fills this from its own scan; API callers may omit the field or send {"speakers": [], "signals": {}}.
retry_notestring, optionalOnly set by the app's automatic reformat retry when a first reply was not valid JSON. Leave it out.
cat > transcript.txt <<'TEXT'
[00:04:12] Alex: So, uh, I think the migration timeline might be a little
optimistic, maybe? If you think that makes sense.
[00:04:31] Priya: We committed to March in the board deck.
[00:04:38] Alex: Right, yeah, no, totally - we can probably make it work.
[00:05:02] Sam: The staging cluster still isn't provisioned.
[00:05:07] Alex: Okay, so, anyway - let's come back to that. Priya, what's
the plan for customer comms?
TEXT

jq -n --rawfile t transcript.txt \
  '{transcript: $t, self_name: "Alex", focus: "conflict", notes: "",
    prescan_facts: {speakers: [], 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'
TRANSCRIPT = """[00:04:12] Alex: So, uh, I think the migration timeline might be a little
optimistic, maybe? If you think that makes sense.
[00:04:31] Priya: We committed to March in the board deck.
[00:04:38] Alex: Right, yeah, no, totally - we can probably make it work.
[00:05:02] Sam: The staging cluster still isn't provisioned.
[00:05:07] Alex: Okay, so, anyway - let's come back to that. Priya, what's
the plan for customer comms?"""

payload = {
    "transcript": TRANSCRIPT,
    "self_name": "Alex",
    "focus": "conflict",
    "notes": "",
    "prescan_facts": {"speakers": [], "signals": {}},
}

est = api("POST", "/estimate", payload)
print("worst case:", est.get("hold_credits", est.get("credits")), "credits")
const transcript = `[00:04:12] Alex: So, uh, I think the migration timeline might be a little
optimistic, maybe? If you think that makes sense.
[00:04:31] Priya: We committed to March in the board deck.
[00:04:38] Alex: Right, yeah, no, totally - we can probably make it work.
[00:05:02] Sam: The staging cluster still isn't provisioned.
[00:05:07] Alex: Okay, so, anyway - let's come back to that. Priya, what's
the plan for customer comms?`;

const payload = {
  transcript,
  self_name: "Alex",
  focus: "conflict",
  notes: "",
  prescan_facts: { speakers: [], signals: {} },
};

const est = await api("POST", "/estimate", payload);
console.log("worst case:", est.hold_credits ?? est.credits, "credits");
const transcript = `[00:04:12] Alex: So, uh, I think the migration timeline might be a little
optimistic, maybe? If you think that makes sense.
[00:04:31] Priya: We committed to March in the board deck.
[00:04:38] Alex: Right, yeah, no, totally - we can probably make it work.
[00:05:02] Sam: The staging cluster still isn't provisioned.
[00:05:07] Alex: Okay, so, anyway - let's come back to that. Priya, what's
the plan for customer comms?`

payload := map[string]any{
	"transcript": transcript,
	"self_name":  "Alex",
	"focus":      "conflict",
	"notes":      "",
	"prescan_facts": map[string]any{
		"speakers": []any{}, "signals": map[string]any{},
	},
}

var est struct{ HoldCredits int64 `json:"hold_credits"` }
err := call("POST", "/estimate", payload, &est)
String transcript = """
    [00:04:12] Alex: So, uh, I think the migration timeline might be a little
    optimistic, maybe? If you think that makes sense.
    [00:04:31] Priya: We committed to March in the board deck.
    [00:04:38] Alex: Right, yeah, no, totally - we can probably make it work.
    [00:05:02] Sam: The staging cluster still isn't provisioned.
    [00:05:07] Alex: Okay, so, anyway - let's come back to that. Priya, what's
    the plan for customer comms?""";

String jsonPayload = """
    {"transcript": %s, "self_name": "Alex", "focus": "conflict",
     "notes": "",
     "prescan_facts": {"speakers": [], "signals": {}}}
    """.formatted(toJsonString(transcript));

String envelope = api("POST", "/estimate", jsonPayload);
// worst-case cost is at data.hold_credits
TRANSCRIPT_TEXT = <<~'TEXT'
  [00:04:12] Alex: So, uh, I think the migration timeline might be a little
  optimistic, maybe? If you think that makes sense.
  [00:04:31] Priya: We committed to March in the board deck.
  [00:04:38] Alex: Right, yeah, no, totally - we can probably make it work.
  [00:05:02] Sam: The staging cluster still isn't provisioned.
  [00:05:07] Alex: Okay, so, anyway - let's come back to that. Priya, what's
  the plan for customer comms?
TEXT

payload = { transcript: TRANSCRIPT_TEXT, self_name: "Alex", focus: "conflict",
            notes: "",
            prescan_facts: { speakers: [], signals: {} } }

est = api("POST", "/estimate", payload)
puts "worst case: #{est["hold_credits"] || est["credits"]} credits"
$transcript = <<<'TEXT'
[00:04:12] Alex: So, uh, I think the migration timeline might be a little
optimistic, maybe? If you think that makes sense.
[00:04:31] Priya: We committed to March in the board deck.
[00:04:38] Alex: Right, yeah, no, totally - we can probably make it work.
[00:05:02] Sam: The staging cluster still isn't provisioned.
[00:05:07] Alex: Okay, so, anyway - let's come back to that. Priya, what's
the plan for customer comms?
TEXT;

$payload = [
    "transcript"    => $transcript,
    "self_name"     => "Alex",
    "focus"         => "conflict",
    "notes"         => "",
    "prescan_facts" => ["speakers" => [], "signals" => new stdClass()],
];

$est = api("POST", "/estimate", $payload);
echo "worst case: " . ($est["hold_credits"] ?? $est["credits"]) . " credits\n";
var transcript = """
    [00:04:12] Alex: So, uh, I think the migration timeline might be a little
    optimistic, maybe? If you think that makes sense.
    [00:04:31] Priya: We committed to March in the board deck.
    [00:04:38] Alex: Right, yeah, no, totally - we can probably make it work.
    [00:05:02] Sam: The staging cluster still isn't provisioned.
    [00:05:07] Alex: Okay, so, anyway - let's come back to that. Priya, what's
    the plan for customer comms?
    """;

var payload = new {
    transcript,
    self_name = "Alex",
    focus = "conflict",
    notes = "",
    prescan_facts = new {
        speakers = Array.Empty<object>(),
        signals = new { },
    },
};

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 review answer for every voice in the room. Send {"speakers": [{"id": "spk-alex", "label": "Alex", "turns": 3, "words": 62, "talk_pct": 64, "questions": 1, "fillers": 4, "hedges": 5, "longest_turn_words": 26}, {"id": "spk-priya", "label": "Priya", "turns": 1, "words": 9, "talk_pct": 22, "questions": 0, "fillers": 0, "hedges": 0, "longest_turn_words": 9}, {"id": "spk-sam", "label": "Sam", "turns": 1, "words": 7, "talk_pct": 14, "questions": 0, "fillers": 0, "hedges": 0, "longest_turn_words": 7}], "signals": {"format": "labeled", "lines": 8, "words": 78, "speaker_count": 3, "timestamps": 5, "duration_min": 1}} and every one of those speaker ids comes back in coverage_check — weighed, or set aside with a reason (a label that is really a system message, say). Nobody you flagged is silently dropped.

Step 4 — Run the review 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 20–60 s, since every pattern carries quoted examples and the twelve-item checklist is written out in full). Always send an Idempotency-Key header so a network retry can't start a second, double-charged run. The report is in output — usually nested as output.output, and as a JSON string, so parse defensively. The samples below print the report name and verdict, the five health areas and the patterns with their quoted examples, then the numbers from stats and the ordered next_steps.

JOB_ID=$(curl -s -X POST "$API/run" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -H "Idempotency-Key: talk-lens-$(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 report once, then read it
echo "$JOB" | jq -r '.data.output.output' > report.json

jq -r '
  "\(.report_name) [\(.verdict_level)]: \(.verdict)",
  "",
  "HEALTH",
  (.health[] | "  [\(.status)] \(.area) - \(.note)"),
  "",
  "PATTERNS",
  (.patterns[] | "  (\(.severity)/\(.lens)) \(.title) - \(.frequency)",
                 (.examples[] | "      \(.where): \(.quote)")),
  "",
  "CHECKLIST",
  (.checklist[] | "  [\(.status)] \(.item) - \(.note)"),
  "",
  "STATS: talk \(.stats.self_talk_pct)% - questions \(.stats.questions_asked)"' report.json

# and the ordered next steps
jq -r '.next_steps[]' report.json
import time

job_id = api("POST", "/run", payload,
             **{"Idempotency-Key": "talk-lens-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"]
report = json.loads(raw) if isinstance(raw, str) else raw

print(f'{report["report_name"]} [{report["verdict_level"]}]: {report["verdict"]}')
for area in report["health"]:
    print(f'  [{area["status"]:>4}] {area["area"]:<30} {area["note"]}')
for p in report["patterns"]:
    print(f'  ({p["severity"]}/{p["lens"]}) {p["title"]} - {p["frequency"]}')
    for ex in p["examples"]:
        print(f'      {ex["where"]}: "{ex["quote"]}"')
        print(f'        better: {ex["better"] or "(positive example)"}')
    print(f'      -> {p["recommendation"]}')
for item in report["checklist"]:
    print(f'  [{item["status"]:>4}] {item["item"]:<48} {item["note"]}')
for c in report["coverage_check"]:
    print(f'  {c["id"]}: {"weighed" if c["addressed"] else "SET ASIDE"} - {c["note"]}')

print(report["stats"])
for s in report["strengths"]:
    print(" +", s)
for g in report["growth"]:
    print(f'  {g["area"]}: {g["advice"]}')
for step in report["next_steps"]:
    print(" -", step)
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 report = typeof raw === "string" ? JSON.parse(raw) : raw;

console.log(`${report.report_name} [${report.verdict_level}]: ${report.verdict}`);
for (const area of report.health) {
  console.log(`  [${area.status}] ${area.area}: ${area.note}`);
}
for (const p of report.patterns) {
  console.log(`  (${p.severity}/${p.lens}) ${p.title} - ${p.frequency}`);
  for (const ex of p.examples) {
    console.log(`      ${ex.where}: "${ex.quote}"`);
    if (ex.better) console.log(`        better: ${ex.better}`);
  }
  console.log(`      -> ${p.recommendation}`);
}
for (const item of report.checklist) console.log(`  [${item.status}] ${item.item}: ${item.note}`);
for (const c of report.coverage_check) {
  console.log(`  ${c.id}: ${c.addressed ? "weighed" : "SET ASIDE"} - ${c.note}`);
}

console.log(report.stats);
for (const s of report.strengths) console.log(" +", s);
for (const g of report.growth) console.log(`  ${g.area}: ${g.advice}`);
for (const step of report.next_steps) console.log(" -", step);
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 Report struct {
	ReportName   string `json:"report_name"`
	VerdictLevel string `json:"verdict_level"`
	Verdict      string `json:"verdict"`
	Health       []struct {
		Area, Status, Note string
	} `json:"health"`
	Patterns []struct {
		Severity, Lens, Title, Detail, Frequency string
		Examples                                 []struct {
			Where, Quote, Why, Better string
		} `json:"examples"`
		Recommendation string `json:"recommendation"`
	} `json:"patterns"`
	Stats struct {
		SelfTalkPct         *float64 `json:"self_talk_pct"`
		QuestionsAsked      *float64 `json:"questions_asked"`
		FillersPer100Words  *float64 `json:"fillers_per_100_words"`
		InterruptionsGiven  *float64 `json:"interruptions_given"`
		InterruptionsRecvd  *float64 `json:"interruptions_received"`
	} `json:"stats"`
	Checklist []struct {
		Item, Status, Note string
	} `json:"checklist"`
	Strengths []string `json:"strengths"`
	Growth    []struct {
		Area, Advice string
	} `json:"growth"`
	NextSteps []string `json:"next_steps"`
	Summary   string   `json:"summary"`
}
var wrapper struct{ Output string `json:"output"` }
json.Unmarshal(job.Output, &wrapper)
var report Report
json.Unmarshal([]byte(wrapper.Output), &report)

fmt.Printf("%s [%s]: %s\n", report.ReportName, report.VerdictLevel, report.Verdict)
for _, a := range report.Health {
	fmt.Printf("  [%s] %s: %s\n", a.Status, a.Area, a.Note)
}
for _, p := range report.Patterns {
	fmt.Printf("  (%s/%s) %s - %s\n", p.Severity, p.Lens, p.Title, p.Frequency)
	for _, ex := range p.Examples {
		fmt.Printf("      %s: %q\n", ex.Where, ex.Quote)
	}
	fmt.Printf("      -> %s\n", p.Recommendation)
}
for _, c := range report.Checklist {
	fmt.Printf("  [%s] %s: %s\n", c.Status, c.Item, c.Note)
}
for _, s := range report.Strengths {
	fmt.Println("  + " + s)
}
for _, g := range report.Growth {
	fmt.Printf("  %s: %s\n", g.Area, g.Advice)
}
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 report is at data.output.output as a JSON string - parse it again, then read
// report_name, verdict_level, verdict, overview, health[] (five areas with area/status/note),
// patterns[] (severity/lens/title/detail/frequency, examples[where, quote, why, better],
// recommendation), stats{self_talk_pct, questions_asked, fillers_per_100_words,
// interruptions_given, interruptions_received}, checklist[] (item/status/note),
// coverage_check[] (id/addressed/note), strengths[], growth[area, advice], next_steps[]
// and summary.
// A quoted example prints as:
//   System.out.printf("      %s: \"%s\"%n", exampleWhere, exampleQuote);
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"]
report = raw.is_a?(String) ? JSON.parse(raw) : raw

puts "#{report["report_name"]} [#{report["verdict_level"]}]: #{report["verdict"]}"
report["health"].each { |a| puts "  [#{a["status"]}] #{a["area"]}: #{a["note"]}" }
report["patterns"].each do |p|
  puts "  (#{p["severity"]}/#{p["lens"]}) #{p["title"]} - #{p["frequency"]}"
  p["examples"].each { |ex| puts "      #{ex["where"]}: \"#{ex["quote"]}\"" }
  puts "      -> #{p["recommendation"]}"
end
report["checklist"].each { |c| puts "  [#{c["status"]}] #{c["item"]}: #{c["note"]}" }
report["coverage_check"].each { |c| puts "  #{c["id"]}: #{c["addressed"] ? "weighed" : "SET ASIDE"}" }

puts report["stats"].inspect
report["strengths"].each { |s| puts " + #{s}" }
report["growth"].each { |g| puts "  #{g["area"]}: #{g["advice"]}" }
report["next_steps"].each { |s| puts " - #{s}" }
$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"];
$report = is_string($raw) ? json_decode($raw, true) : $raw;

echo "{$report['report_name']} [{$report['verdict_level']}]: {$report['verdict']}\n";
foreach ($report["health"] as $a) {
    echo "  [{$a['status']}] {$a['area']}: {$a['note']}\n";
}
foreach ($report["patterns"] as $p) {
    echo "  ({$p['severity']}/{$p['lens']}) {$p['title']} - {$p['frequency']}\n";
    foreach ($p["examples"] as $ex) {
        echo "      {$ex['where']}: \"{$ex['quote']}\"\n";
    }
    echo "      -> {$p['recommendation']}\n";
}
foreach ($report["checklist"] as $item) {
    echo "  [{$item['status']}] {$item['item']}: {$item['note']}\n";
}
foreach ($report["coverage_check"] as $c) {
    echo "  {$c['id']}: " . ($c["addressed"] ? "weighed" : "SET ASIDE") . "\n";
}

echo "talk share: {$report['stats']['self_talk_pct']}%\n";
foreach ($report["growth"] as $g) {
    echo "  {$g['area']}: {$g['advice']}\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 rawText = job.GetProperty("output").GetProperty("output").GetString();
using var doc = JsonDocument.Parse(rawText!);
var report = doc.RootElement;

Console.WriteLine($"{report.GetProperty("report_name")} " +
                  $"[{report.GetProperty("verdict_level")}]: {report.GetProperty("verdict")}");
foreach (var a in report.GetProperty("health").EnumerateArray())
{
    Console.WriteLine($"  [{a.GetProperty("status")}] {a.GetProperty("area")}: {a.GetProperty("note")}");
}
foreach (var p in report.GetProperty("patterns").EnumerateArray())
{
    Console.WriteLine($"  ({p.GetProperty("severity")}/{p.GetProperty("lens")}) " +
                      $"{p.GetProperty("title")} - {p.GetProperty("frequency")}");
    foreach (var ex in p.GetProperty("examples").EnumerateArray())
    {
        Console.WriteLine($"      {ex.GetProperty("where")}: {ex.GetProperty("quote")}");
    }
    Console.WriteLine($"      -> {p.GetProperty("recommendation")}");
}
foreach (var c in report.GetProperty("checklist").EnumerateArray())
{
    Console.WriteLine($"  [{c.GetProperty("status")}] {c.GetProperty("item")}: {c.GetProperty("note")}");
}

var stats = report.GetProperty("stats");
Console.WriteLine($"talk share: {stats.GetProperty("self_talk_pct")}%");
foreach (var g in report.GetProperty("growth").EnumerateArray())
{
    Console.WriteLine($"  {g.GetProperty("area")}: {g.GetProperty("advice")}");
}

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 communication report — output schema

One JSON object, always the same shape. Every array is present (patterns holds two to eight entries, fewer only when the transcript is genuinely too short to support them); health always has exactly the five areas, and checklist always has exactly the twelve items. If the transcript was too thin to review responsibly, you still get this object: the overview says so, the patterns stay inside what the text supports, and the checklist uses na liberally rather than padding. The review never invents a person, a quote, a timestamp, a decision or a history — every high-severity pattern carries at least one verbatim quote from the transcript, and a pattern with no quotable moment does not go in the report at all.

FieldTypeMeaning
report_namestringA short name for the review, taken from what the transcript shows — for example 1:1 with Sarah - candor review.
verdict_levelstringstrong (the centered speaker communicated well and the meeting worked), mixed (real strengths alongside one or two costly habits) or needs_work (recurring patterns materially reduced the meeting's honesty or effectiveness).
verdictstringOne or two sentences naming the single most important thing to change — or to keep doing — grounded in the transcript.
overviewstringTwo to three paragraphs, separated by blank lines: what the meeting was, how it went, and what the centered speaker's presence in the room was like.
healtharray of 5{area, status, note} — the five areas listed below, each exactly once. status is good (nothing material), risk (works, with caveats) or bad (a high-severity pattern lives here). Each note references something concrete in the transcript.
patternsarray of 2–8{severity, lens, title, detail, frequency, examples, recommendation}. severity is high | medium | low, by how much the pattern cost the meeting. lens is conflict, balance, fillers, listening or facilitation. detail says what the pattern is and what it did to this meeting, and is where any disagreement with the prescan counts is stated. frequency is plain language (4 times in this meeting). examples is 1–3 entries of {where, quote, why, better}, where where is a timestamp or turn N (Name), quote is verbatim transcript text, why says why the moment matters and better gives the specific alternative phrasing — empty when the example is a positive one being praised. recommendation is the concrete change for that pattern.
statsobject{self_talk_pct, questions_asked, fillers_per_100_words, interruptions_given, interruptions_received} — the review's own read of the numbers, centered on self_name when you sent one. Any figure the transcript genuinely cannot support is null (no interruption markers in the export, for instance), so check for null before formatting.
checklistarray of 12{item, status, note} — the twelve items listed below, each exactly once and spelled verbatim. status is pass, fail or na (the transcript does not show it either way). The note says what was seen or what is missing.
coverage_checkarray{id, addressed, note} — one entry per speaker id you sent in prescan_facts.speakers (spk-alex, spk-priya, …). addressed: true means that speaker's behaviour was weighed in the review; false means it was set aside, and the note says why. Nobody you flagged is silently dropped.
strengthsarray of 2–4 stringsWhat the centered speaker already does well, each grounded in a real moment in the transcript.
growtharray of 2–4{area, advice}area is a short name, advice is specific and actionable, tied to what the transcript shows.
next_stepsstring[] (3–5)Ordered and concrete, with the first one doable in the speaker's very next meeting.
summarystringTwo or three sentences a busy person can read instead of the report.

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

areaWhat its note covers
Directness & candorWhether hard messages landed as hard messages. Hedging looks like "maybe", "kind of", "sort of", "I think we could possibly", "if you think that makes sense", raising a serious issue and immediately softening it, or agreeing without commitment ("yeah, but…"). Conflict avoidance looks like changing the subject when tension arises, leaving an obvious problem unnamed, or padding a hard message until the urgency disappears.
Speaking balanceHow the airtime was distributed against each person's role in the meeting, how long the longest turns ran, whether interruptions happened and whether they were repaired.
Listening & buildingWhether people were heard: questions that reference someone's earlier point by name, paraphrasing before disagreeing, building on an idea rather than restating one's own.
Question qualityWhether questions were asked at all rather than statements made, and whether they opened the discussion (clarifying before disagreeing) or merely checked a box.
Facilitation & follow-throughJudged by what happened, not by intent: were quieter people drawn in, did decisions close with an owner, did action items carry names and dates, did the agenda survive without anyone being steamrolled.

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

itemWhat its note covers
Critical feedback given directly, without hedgingThe hard thing was said plainly, not wrapped in qualifiers or withdrawn a line later.
Speaking share proportionate to role in the meetingThe airtime matches what the person was there to do — a facilitator who talks 70% of a five-person meeting is not facilitating.
Questions asked, not just statements madeThe transcript shows real questions, not a run of declarations with an occasional "right?" on the end.
Others' points acknowledged and built onSomeone's contribution is named and extended rather than passed over on the way back to one's own point.
Clarifying questions asked before disagreeingDisagreement follows an attempt to understand the position, not a first reading of it.
Quieter participants drawn into the discussionPeople who had not spoken were invited in by name, and given room to answer.
Interruptions rare, and repaired when they happenCut-offs are uncommon, and when one happens the floor is handed back ("sorry, you were saying").
Filler words under control"Um", "uh", "like" and "you know" stay low enough not to undercut the message.
Tension addressed when it surfaces, not deflectedWhen disagreement or discomfort appears in the room, it is named and worked rather than moved past.
Decisions closed with an explicit ownerEach decision ends with a named person, not with a general nod of agreement.
Action items specific, owned and datedFollow-ups carry a what, a who and a when — not "we should look into that".
Agenda kept on track without steamrollingThe meeting covered what it set out to cover, and the tracking did not come at the cost of cutting people off.

A small, realistic result for the transcript.txt paste above, trimmed for length:

{
  "report_name": "Migration standup - candor review for Alex",
  "verdict_level": "needs_work",
  "verdict": "Alex raised the one thing that mattered - the March timeline is not
              real - and then took it back within two turns; say it once, plainly,
              and let the silence do the work.",
  "overview": "A short segment of a migration standup between Alex, Priya and Sam.
               Alex holds the floor for most of it and is the only person who names
               a risk, but every risk is delivered pre-softened. ...",
  "health": [
    { "area": "Directness & candor", "status": "bad",
      "note": "The timeline concern arrives wrapped in 'I think', 'might be',
               'a little' and 'maybe' in a single sentence, then is withdrawn at
               04:38." },
    { "area": "Speaking balance", "status": "risk",
      "note": "Alex takes 3 of 5 turns and roughly 64% of the words in a
               three-person conversation." },
    { "area": "Listening & building", "status": "bad",
      "note": "Sam's provisioning blocker gets no acknowledgment at all before the
               subject changes." },
    { "area": "Question quality", "status": "risk",
      "note": "One real question is asked, and it is a redirect rather than an
               attempt to understand Priya's March commitment." },
    { "area": "Facilitation & follow-through", "status": "bad",
      "note": "Two open items - the timeline and the staging cluster - are left
               without an owner or a date." }
  ],
  "patterns": [
    { "severity": "high", "lens": "conflict",
      "title": "Hedging a schedule risk into invisibility",
      "detail": "The concern is real and correctly aimed, but four qualifiers in one
                 sentence let the room hear it as a passing thought. The prescan
                 counted 5 hedges for Alex; on reading, four of them land in a single
                 turn, which is what makes this costly rather than merely frequent.",
      "frequency": "2 turns of 3",
      "examples": [
        { "where": "[00:04:12]",
          "quote": "So, uh, I think the migration timeline might be a little
                    optimistic, maybe? If you think that makes sense.",
          "why": "The only warning in the meeting is delivered as a question about
                  whether it is worth mentioning.",
          "better": "The March date assumes staging is up this week. It isn't, so I
                     don't believe the timeline - here's what I'd move." },
        { "where": "[00:04:38]",
          "quote": "Right, yeah, no, totally - we can probably make it work.",
          "why": "Withdrawing the concern seven seconds after raising it tells Priya
                  the risk was never serious.",
          "better": "I hear the board commitment. I still think March slips - can we
                     book 20 minutes to re-plan it?" }
      ],
      "recommendation": "State the risk in one unqualified sentence, then stop
                         talking until someone responds." },
    { "severity": "medium", "lens": "facilitation",
      "title": "Blockers surfaced and immediately deferred",
      "detail": "Sam raises an unprovisioned staging cluster - the concrete reason
                 the timeline is at risk - and it is parked without an owner.",
      "frequency": "1 time in this meeting",
      "examples": [
        { "where": "turn 5 (Alex)",
          "quote": "Okay, so, anyway - let's come back to that.",
          "why": "'Come back to that' with no owner and no time is how a blocker
                  survives to the next standup unchanged.",
          "better": "Sam, who owns provisioning and what do you need from me to have
                     it up by Thursday?" }
      ],
      "recommendation": "Close every parked item with a name and a date before moving
                         the agenda on." }
  ],
  "stats": {
    "self_talk_pct": 64,
    "questions_asked": 1,
    "fillers_per_100_words": 6.5,
    "interruptions_given": null,
    "interruptions_received": null
  },
  "checklist": [
    { "item": "Critical feedback given directly, without hedging", "status": "fail",
      "note": "Four qualifiers in the one sentence that carried the risk." },
    { "item": "Speaking share proportionate to role in the meeting", "status": "fail",
      "note": "About 64% of the words across three participants." },
    { "item": "Questions asked, not just statements made", "status": "pass",
      "note": "One question, at 05:07, though it changes the subject." },
    { "item": "Others' points acknowledged and built on", "status": "fail",
      "note": "Sam's blocker draws no acknowledgment." },
    { "item": "Clarifying questions asked before disagreeing", "status": "fail",
      "note": "Priya's board commitment is conceded, never explored." },
    { "item": "Quieter participants drawn into the discussion", "status": "na",
      "note": "Too short a segment to show whether anyone was invited in." },
    { "item": "Interruptions rare, and repaired when they happen", "status": "na",
      "note": "The export carries no overlap or interruption markers." },
    { "item": "Filler words under control", "status": "fail",
      "note": "'So, uh', 'yeah, no, totally', 'okay, so, anyway' in five turns." },
    { "item": "Tension addressed when it surfaces, not deflected", "status": "fail",
      "note": "The board-deck disagreement is dropped rather than worked." },
    { "item": "Decisions closed with an explicit owner", "status": "fail",
      "note": "Neither the timeline nor the cluster gets an owner." },
    { "item": "Action items specific, owned and dated", "status": "fail",
      "note": "No action item is stated in this segment." },
    { "item": "Agenda kept on track without steamrolling", "status": "na",
      "note": "No agenda is visible in the supplied text." }
  ],
  "coverage_check": [
    { "id": "spk-alex", "addressed": true,
      "note": "The centered speaker; both patterns are built on Alex's turns." },
    { "id": "spk-priya", "addressed": true,
      "note": "Weighed as the counterparty whose single line closed the topic." },
    { "id": "spk-sam", "addressed": true,
      "note": "Weighed in the facilitation pattern as the ignored blocker." }
  ],
  "strengths": [
    "Alex is the only person who names the schedule risk at all - the instinct is
     right, only the delivery is not.",
    "The redirect at 05:07 is aimed at a real next topic and names Priya directly
     rather than trailing off."
  ],
  "growth": [
    { "area": "One-sentence risk",
      "advice": "Write the concern as a single unqualified sentence before the
                 meeting, then read it out as written." },
    { "area": "Closing the loop",
      "advice": "When you park an item, say the owner and the day out loud in the
                 same breath - 'Sam, Thursday' is enough." }
  ],
  "next_steps": [
    "In your next standup, say the timeline risk once, unhedged, and wait.",
    "Reply to Sam today with an owner and a date for the staging cluster.",
    "Ask Priya what the board deck actually committed to, before conceding it again.",
    "Re-run this review on next week's standup and compare self_talk_pct."
  ],
  "summary": "Alex sees the right risk and talks himself out of it inside two turns,
              while the blocker that proves the risk goes unacknowledged. ..."
}

The report is a coaching starting point, not a performance review: it is written to be internally consistent with the quoted moments, but it is AI-generated and it only sees the text you pasted — no tone, no faces, no history between the people in the room. Check the quotes against the recording before you repeat them to anyone, and treat transcripts of other people's speech as the sensitive material they are.

Step 5 — Stream the review 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 overview, the quoted pattern examples and the twelve-item checklist make 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 report 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: talk-lens-$(date +%s)" \
  -d @input.json

# event: job
# data: {"job_id":"job_...","status":"running"}
#
# event: delta
# data: {"text":"{\"report_name\":\"Migration standup - candor"}
# ...
# event: done
# data: {"job_id":"job_...","status":"succeeded","charged_credits":480,"output":{"output":"{...}"}}
import json, requests

result = None
with requests.post(
    API + "/run-stream",
    headers={"Authorization": f"Bearer {TOKEN}",
             "Idempotency-Key": "talk-lens-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"))

report = json.loads(result["output"]["output"])         # authoritative
print("charged:", result["charged_credits"], "-", report["report_name"])
for area in report["health"]:
    print(f'  [{area["status"]}] {area["area"]}')
for p in report["patterns"]:
    print(f'  ({p["severity"]}) {p["title"]}')
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 report = JSON.parse(done.output.output);
console.log(`\n${done.charged_credits} credits - ${report.report_name}`);
for (const area of report.health) console.log(`  [${area.status}] ${area.area}`);
for (const p of report.patterns) console.log(`  (${p.severity}) ${p.title}`);
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", "talk-lens-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 report JSON -
// unmarshal it into the Report struct from step 4, then print report.Patterns.
// 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", "talk-lens-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
// report_name, verdict_level, health[], patterns[] with their examples[], stats{},
// checklist[], coverage_check[], strengths[], growth[], next_steps[] and summary.
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"] = "talk-lens-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

report = JSON.parse(done["output"]["output"])
puts "\n#{done["charged_credits"]} credits - #{report["report_name"]}"
report["health"].each { |a| puts "  [#{a["status"]}] #{a["area"]}" }
report["patterns"].each { |p| puts "  (#{p["severity"]}) #{p["title"]}" }
$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: talk-lens-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);

$report = json_decode($done["output"]["output"], true);
echo "\n{$done['charged_credits']} credits - {$report['report_name']}\n";
foreach ($report["health"] as $a) { echo "  [{$a['status']}] {$a['area']}\n"; }
foreach ($report["patterns"] as $p) { echo "  ({$p['severity']}) {$p['title']}\n"; }
var req = new HttpRequestMessage(HttpMethod.Post, Api + "/run-stream") {
    Content = JsonContent.Create(payload),
};
req.Headers.Add("Idempotency-Key", "talk-lens-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 reportDoc = JsonDocument.Parse(text!);
var report = reportDoc.RootElement;
Console.WriteLine(report.GetProperty("report_name"));
foreach (var a in report.GetProperty("health").EnumerateArray())
    Console.WriteLine($"  [{a.GetProperty("status")}] {a.GetProperty("area")}");
foreach (var p in report.GetProperty("patterns").EnumerateArray())
    Console.WriteLine($"  ({p.GetProperty("severity")}) {p.GetProperty("title")}");

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.