Review your product's pricing from your own scripts
Send a description of a technical product and what it charges — a pricing page, a plan table, a strategy memo, or a grab-bag of notes and metrics — and get back one JSON object: an honest raise / hold / restructure verdict, a health check across five pricing areas, findings ranked by severity each with a concrete recommendation, a twelve-item pricing checklist scored against the paste, and a recommended tier structure. Everything this app does goes through the SkillSafe App API — plain JSON over HTTPS — so you can wire the review into a pricing-committee doc generator, a quarterly pricing audit, or a script that re-reviews every plan page in your product line. 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
price-signal. 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 paste
in, one review out, no follow-up calls and no session state to carry.
| Status | Meaning |
|---|---|
401 | Missing or expired token — create a new session. |
402 | Not enough credits — top up at skillsafe.ai/account/credits. |
403 | The token isn't allowed to do this (e.g. a guest reviewing a very large paste). |
404 | Unknown job or record id. |
5xx | Transient 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
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":"price-signal"}' | jq -r '.data.token'
token = api("POST", "/guest", {"slug": "price-signal"})["token"]
const { token } = await api("POST", "/guest", { slug: "price-signal" });
var guest struct{ Token string `json:"token"` }
err := call("POST", "/guest", map[string]string{"slug": "price-signal"}, &guest)
String envelope = api("POST", "/guest", """
{"slug":"price-signal"}""");
// token is at data.token in the returned JSON
token = api("POST", "/guest", { slug: "price-signal" })["token"]
$token = api("POST", "/guest", ["slug" => "price-signal"])["token"];
var guest = await SkillSafe.ApiAsync(HttpMethod.Post, "/guest",
new { slug = "price-signal" });
var token = guest.GetProperty("token").GetString();
The app stores this browser's token under the localStorage key
skillsafe_app_token:price-signal, 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
Returns subject_type ("user" or "guest"),
subject_id and your credits balance. Check this before reviewing
a large paste.
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
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 whole pricing page or a
directory of plan memos and want a ceiling before spending credits.
| Input field | Type | Notes |
|---|---|---|
context | string, required | The product and pricing description to review, up to 60000 characters: what the product is (API, developer tool, SaaS, infrastructure), the current plans and prices, the GTM motion, the cost to serve, the customer's alternative, competitors, and whatever metrics you have. Very long pastes may be clipped middle-out, with a [... clipped ...] marker showing where. |
goal | string | full | model | raise | freemium | enterprise — what you want out of the review. full (the default) weighs everything by what the paste shows; model leads with seat vs usage vs outcome vs hybrid fit; raise leads with raise-readiness, sizing and rollout; freemium leads with where free ends and paid begins; enterprise leads with structuring the enterprise pricing conversation. Every section still comes back whichever you pick — only the weighting changes. |
notes | string, optional | Extra questions or constraints, up to 10000 characters: a board question you must answer, a floor you cannot go under, a contract you must not break, a segment you are aiming at. The web app also appends one machine-written line here when its value-ratio calculator has both numbers filled in, beginning Value-ratio inputs from the app’s client-side calculator: and carrying the alternative cost, the price, the computed ratio and its band. Calling the API directly you may send that same line yourself, or omit it — it is an ordinary part of notes, not a separate field. |
prescan_facts | object, optional | What a client-side prescan mechanically detected in the paste: {"figures": [], "models": [], "signals": {}}. figures and models hold {id, label, lines} entries — dollar amounts, percentages and metrics found (fig-dollar-1-49, fig-winrate, fig-margin) and pricing-model mentions found (model-seat, model-usage, model-freemium, model-enterprise, model-hybrid), each with the line numbers it was seen on. signals is a counter object: {"lines": 0, "words": 0, "dollar_figures": 0, "percentages": 0, "model_mentions": 0}. Every id you send comes back in coverage_check. The web UI fills this from its own scan; API callers may omit the field or send {"figures": [], "models": [], "signals": {}}. |
retry_note | string, optional | Only set by the app's automatic reformat retry when a first reply was not valid JSON. Leave it out. |
cat > pricing.txt <<'TEXT'
CI build-cache API, self-serve only. Free: 5 GB cache.
Pro: $49/mo flat, 100 GB, unlimited seats. No enterprise tier.
Costs about $9/mo to serve a Pro account.
Customers say it cuts 20 minutes off every build; a 20-engineer
team saves roughly $6,000/mo of engineer time.
Win rate 62%. No price pushback in 9 months.
TEXT
jq -n --rawfile c pricing.txt \
'{context: $c, goal: "full", notes: "",
prescan_facts: {figures: [], models: [], 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'
CONTEXT = """CI build-cache API, self-serve only. Free: 5 GB cache.
Pro: $49/mo flat, 100 GB, unlimited seats. No enterprise tier.
Costs about $9/mo to serve a Pro account.
Customers say it cuts 20 minutes off every build; a 20-engineer
team saves roughly $6,000/mo of engineer time.
Win rate 62%. No price pushback in 9 months."""
payload = {
"context": CONTEXT,
"goal": "full",
"notes": "",
"prescan_facts": {"figures": [], "models": [], "signals": {}},
}
est = api("POST", "/estimate", payload)
print("worst case:", est.get("hold_credits", est.get("credits")), "credits")
const context = `CI build-cache API, self-serve only. Free: 5 GB cache.
Pro: $49/mo flat, 100 GB, unlimited seats. No enterprise tier.
Costs about $9/mo to serve a Pro account.
Customers say it cuts 20 minutes off every build; a 20-engineer
team saves roughly $6,000/mo of engineer time.
Win rate 62%. No price pushback in 9 months.`;
const payload = {
context,
goal: "full",
notes: "",
prescan_facts: { figures: [], models: [], signals: {} },
};
const est = await api("POST", "/estimate", payload);
console.log("worst case:", est.hold_credits ?? est.credits, "credits");
const context = `CI build-cache API, self-serve only. Free: 5 GB cache.
Pro: $49/mo flat, 100 GB, unlimited seats. No enterprise tier.
Costs about $9/mo to serve a Pro account.
Customers say it cuts 20 minutes off every build; a 20-engineer
team saves roughly $6,000/mo of engineer time.
Win rate 62%. No price pushback in 9 months.`
payload := map[string]any{
"context": context,
"goal": "full",
"notes": "",
"prescan_facts": map[string]any{
"figures": []any{}, "models": []any{}, "signals": map[string]any{},
},
}
var est struct{ HoldCredits int64 `json:"hold_credits"` }
err := call("POST", "/estimate", payload, &est)
String context = """
CI build-cache API, self-serve only. Free: 5 GB cache.
Pro: $49/mo flat, 100 GB, unlimited seats. No enterprise tier.
Costs about $9/mo to serve a Pro account.
Customers say it cuts 20 minutes off every build; a 20-engineer
team saves roughly $6,000/mo of engineer time.
Win rate 62%. No price pushback in 9 months.""";
String jsonPayload = """
{"context": %s, "goal": "full",
"notes": "",
"prescan_facts": {"figures": [], "models": [], "signals": {}}}
""".formatted(toJsonString(context));
String envelope = api("POST", "/estimate", jsonPayload);
// worst-case cost is at data.hold_credits
CONTEXT_TEXT = <<~'TEXT'
CI build-cache API, self-serve only. Free: 5 GB cache.
Pro: $49/mo flat, 100 GB, unlimited seats. No enterprise tier.
Costs about $9/mo to serve a Pro account.
Customers say it cuts 20 minutes off every build; a 20-engineer
team saves roughly $6,000/mo of engineer time.
Win rate 62%. No price pushback in 9 months.
TEXT
payload = { context: CONTEXT_TEXT, goal: "full",
notes: "",
prescan_facts: { figures: [], models: [], signals: {} } }
est = api("POST", "/estimate", payload)
puts "worst case: #{est["hold_credits"] || est["credits"]} credits"
$context = <<<'TEXT'
CI build-cache API, self-serve only. Free: 5 GB cache.
Pro: $49/mo flat, 100 GB, unlimited seats. No enterprise tier.
Costs about $9/mo to serve a Pro account.
Customers say it cuts 20 minutes off every build; a 20-engineer
team saves roughly $6,000/mo of engineer time.
Win rate 62%. No price pushback in 9 months.
TEXT;
$payload = [
"context" => $context,
"goal" => "full",
"notes" => "",
"prescan_facts" => ["figures" => [], "models" => [], "signals" => new stdClass()],
];
$est = api("POST", "/estimate", $payload);
echo "worst case: " . ($est["hold_credits"] ?? $est["credits"]) . " credits\n";
var context = """
CI build-cache API, self-serve only. Free: 5 GB cache.
Pro: $49/mo flat, 100 GB, unlimited seats. No enterprise tier.
Costs about $9/mo to serve a Pro account.
Customers say it cuts 20 minutes off every build; a 20-engineer
team saves roughly $6,000/mo of engineer time.
Win rate 62%. No price pushback in 9 months.
""";
var payload = new {
context,
goal = "full",
notes = "",
prescan_facts = new {
figures = Array.Empty<object>(), models = 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 things you already know
about. Send {"figures": [{"id": "fig-dollar-1-49", "label": "$49 mentioned",
"lines": [2]}, {"id": "fig-winrate", "label": "win rate", "lines": [6]}], "models":
[{"id": "model-freemium", "label": "free tier / freemium mentioned", "lines": [1]},
{"id": "model-flat", "label": "flat-rate pricing mentioned", "lines": [2]}], "signals":
{"lines": 6, "words": 62, "dollar_figures": 3, "percentages": 1, "model_mentions": 2}}
and every one of those ids comes back in coverage_check — addressed, or
explained away as a false positive. Nothing you flag is silently dropped.
Step 4 — Run the review and wait for the result
/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 the tier plan and the twelve-item checklist are 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 findings, then the
recommended tier structure from plan.
JOB_ID=$(curl -s -X POST "$API/run" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-H "Idempotency-Key: pricing-$(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)"),
"",
"FINDINGS",
(.findings[] | " (\(.severity)) \(.category): \(.title)"),
"",
"CHECKLIST",
(.checklist[] | " [\(.status)] \(.item) - \(.note)"),
"",
"PLAN: \(.plan.model)",
(.plan.tiers[] | " \(.name) - \(.price) - \(.target)")' report.json
# and the ordered next steps
jq -r '.next_steps[]' report.json
import time
job_id = api("POST", "/run", payload,
**{"Idempotency-Key": "pricing-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"]:<32} {area["note"]}')
for f in report["findings"]:
print(f' ({f["severity"]}) {f["category"]}: {f["title"]}')
print(f' -> {f["recommendation"]}')
for item in report["checklist"]:
print(f' [{item["status"]:>4}] {item["item"]:<42} {item["note"]}')
for c in report["coverage_check"]:
print(f' {c["id"]}: {"ok" if c["addressed"] else "SET ASIDE"} - {c["note"]}')
print(report["plan"]["model"])
for tier in report["plan"]["tiers"]:
print(f' {tier["name"]:<14} {tier["price"]:<28} {tier["target"]}')
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 f of report.findings) {
console.log(` (${f.severity}) ${f.category}: ${f.title}`);
console.log(` -> ${f.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 ? "ok" : "SET ASIDE"} - ${c.note}`);
}
console.log(report.plan.model);
for (const tier of report.plan.tiers) {
console.log(` ${tier.name} - ${tier.price} - ${tier.target} (${tier.trigger})`);
}
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"`
Findings []struct {
Severity, Category, Title, Detail string
Recommendation string `json:"recommendation"`
} `json:"findings"`
Checklist []struct {
Item, Status, Note string
} `json:"checklist"`
Plan struct {
Model string `json:"model"`
Tiers []struct {
Name, Price, Target, Includes, Trigger string
} `json:"tiers"`
Rationale string `json:"rationale"`
} `json:"plan"`
NextSteps []string `json:"next_steps"`
}
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 _, f := range report.Findings {
fmt.Printf(" (%s) %s: %s\n -> %s\n", f.Severity, f.Category, f.Title, f.Recommendation)
}
for _, c := range report.Checklist {
fmt.Printf(" [%s] %s: %s\n", c.Status, c.Item, c.Note)
}
fmt.Println(report.Plan.Model)
for _, t := range report.Plan.Tiers {
fmt.Printf(" %s - %s - %s\n", t.Name, t.Price, t.Target)
}
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),
// findings[] (severity/category/title/detail/recommendation), checklist[] (item/status/note),
// coverage_check[] (id/addressed/note), plan{model, tiers[name, price, target, includes,
// trigger], rationale}, next_steps[] and summary.
// A tier row prints as:
// System.out.printf(" %s - %s - %s%n", tierName, tierPrice, tierTarget);
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["findings"].each do |f|
puts " (#{f["severity"]}) #{f["category"]}: #{f["title"]}"
puts " -> #{f["recommendation"]}"
end
report["checklist"].each { |c| puts " [#{c["status"]}] #{c["item"]}: #{c["note"]}" }
report["coverage_check"].each { |c| puts " #{c["id"]}: #{c["addressed"] ? "ok" : "SET ASIDE"}" }
puts report["plan"]["model"]
report["plan"]["tiers"].each { |t| puts " #{t["name"]} - #{t["price"]} - #{t["target"]}" }
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["findings"] as $f) {
echo " ({$f['severity']}) {$f['category']}: {$f['title']}\n";
echo " -> {$f['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"] ? "ok" : "SET ASIDE") . "\n";
}
echo $report["plan"]["model"] . "\n";
foreach ($report["plan"]["tiers"] as $t) {
echo " {$t['name']} - {$t['price']} - {$t['target']}\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 f in report.GetProperty("findings").EnumerateArray())
{
Console.WriteLine($" ({f.GetProperty("severity")}) {f.GetProperty("category")}: " +
$"{f.GetProperty("title")}");
Console.WriteLine($" -> {f.GetProperty("recommendation")}");
}
foreach (var c in report.GetProperty("checklist").EnumerateArray())
{
Console.WriteLine($" [{c.GetProperty("status")}] {c.GetProperty("item")}: {c.GetProperty("note")}");
}
var plan = report.GetProperty("plan");
Console.WriteLine(plan.GetProperty("model"));
foreach (var t in plan.GetProperty("tiers").EnumerateArray())
{
Console.WriteLine($" {t.GetProperty("name")} - {t.GetProperty("price")} - {t.GetProperty("target")}");
}
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 pricing report — output schema
One JSON object, always the same shape. Every array is present (findings is
empty only if genuinely nothing applies); health always has exactly the five
areas, checklist always has exactly the twelve items, and plan
always carries between two and four tiers. If the paste was too thin to review responsibly,
you still get this object: what is there gets reviewed, the verdict says the
context is thin, and the numbers you would need to supply land in next_steps.
The review never invents a figure the context does not support — it either derives it
and states the arithmetic in the finding's detail, or it names the input you
need to measure. Directional judgements without hard numbers are fine and are labelled as
such.
| Field | Type | Meaning |
|---|---|---|
report_name | string | A short name for the review, in the form Pricing review - <short product name>, taken from the pasted context. |
verdict_level | string | raise (the price is below what the value supports and the signals say go), hold (the structure and level are broadly right) or restructure (the model itself is wrong, not just the number). |
verdict | string | One or two sentences: the single most important pricing move. |
overview | string | Two to four paragraphs, separated by blank lines: what the product is, what it charges today, what the value ratio says, and why the verdict follows. |
health | array 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 finding lives here). Each note references something concrete in the pasted context. |
findings | array | {severity, category, title, detail, recommendation}. severity is high (money is being left on the table or lost as pasted — a value ratio above 10x, a flat fee under the cost to serve at the top of the range, an enterprise number published on the pricing page) | medium (works today but breaks as you scale or move upmarket) | low (polish). category is value-capture, model, freemium, enterprise, positioning, packaging, discounting or communication. detail grounds the finding in the pasted numbers and shows the arithmetic; recommendation is the concrete change to make, with numbers where the context supports them. |
checklist | array of 12 | {item, status, note} — the twelve pricing items listed below, each exactly once. status is pass (the context shows it handled), fail (the context shows it mishandled — a finding backs this) or na (the context gives no evidence either way, e.g. no enterprise motion). The note says what was seen or what is missing. |
coverage_check | array | {id, addressed, note} — one entry per prescan_facts.figures and prescan_facts.models id you sent (fig-dollar-1-49, model-freemium, …), saying how the review used the fact or why it was set aside (a keyword hit can be a false positive; the note says so). Nothing you flagged is silently dropped. |
plan | object | {model, tiers, rationale} — model is one line naming the recommended pricing model (for example Hybrid: platform fee + usage). tiers is 2–4 entries of {name, price, target, includes, trigger}, where price carries its unit ($99/mo, $0.008/call after included volume, Custom (conversation)) and trigger says what moves a customer up into the tier. rationale is one short paragraph on why the structure fits the usage variance, cost to serve and target segment. The plan is always consistent with the verdict and findings. |
next_steps | string[] | Ordered and concrete, with the first one doable this week: instrument the alternative-cost question in onboarding, move the free ceiling to 2 GB, run a grandfathered increase on the Pro plan, and so on. |
summary | string | One sentence a founder could paste into a board update. |
The five health areas, in order, spelled exactly like this:
| area | What its note covers |
|---|---|
Value capture & price level | The value ratio — the customer's alternative cost divided by your price. Above 10x is massively underpriced, 5–10x underpriced, 3–5x healthy, 2–3x approaching the ceiling, below 2x expensive and needing real differentiation. The anchor is the customer's alternative (manual hours, a build-in-house cost, an incumbent tool plus switching), never your own cost or a competitor's list price. |
Pricing model fit | Whether seat, usage, outcome or hybrid matches how value actually accrues: seats work when value scales with users and usage is uniform, usage works when usage varies more than 5x across customers, outcomes need a reliably measurable result, and the hybrid that usually wins is a platform fee covering cost to serve plus a variable that scales with value. |
Free-to-paid boundary | Whether the free tier ends just below where production usage starts, so hobbyists and learners stay free while production users convert, and whether the paid trigger is a real signal: a usage limit, a team or collaboration gate, or an enterprise feature gate. |
Enterprise & segmentation | Whether enterprise stays a conversation rather than a published number, and whether deployment model, scale, support level and compliance are priced explicitly instead of absorbed — along with a discount floor that never falls below cost to serve plus margin. |
Positioning signal | Whether the price level says what the positioning says: $0 hobbyist, $20–100/mo teams and SMB, $500–2,000/mo production, $5K–50K/yr enterprise, $100K+/yr mission-critical. A price that contradicts the target segment is undermining it. |
The twelve checklist items, in order, spelled exactly like this:
| item | What its note covers |
|---|---|
Price anchored to customer value, not cost | The price is derived from what the customer would otherwise spend or lose, rather than from a cost-plus markup or a glance at a competitor's page. |
Value ratio inside the 3-5x healthy band | Alternative cost divided by price lands in the healthy band — not above 10x, where you are giving the product away, and not below 2x, where every renewal is a fight. |
Pricing model matches usage variance | Seats where usage is uniform, usage-based where it varies more than 5x across customers, and a hybrid where both a floor and a scaling component are needed. |
Base fee covers cost to serve | The recurring floor pays for the infrastructure, support and compliance of an average account before any variable revenue arrives. |
Free tier ends below production usage | The free ceiling sits just under the point where a real workload starts, so learners stay and production users hit the wall and convert. |
Paid trigger tied to a conversion signal | What forces the upgrade is a usage limit, a team gate or an enterprise feature gate that correlates with getting value, not an arbitrary nag. |
Enterprise pricing kept as a conversation | No enterprise number is published; the tier says contact sales and the price is set per deal against deployment, scale, support and compliance. |
Volume discounts floored above cost plus margin | No discount ladder drops a deal below cost to serve plus roughly 40% margin, however large the commitment. |
Support and compliance priced explicitly | Premium support, a dedicated CSM, a 24/7 SLA and each compliance standard carry their own multiplier rather than being absorbed into the base price. |
Price level matches the target segment | The number sits in the band the target buyer expects, so the price itself does not argue against the positioning. |
Annual escalator in enterprise contracts | Multi-year agreements carry a 5–10% annual uplift clause, so the price does not silently erode across the term. |
Grandfathering plan for price changes | An increase comes with a 12–24 month grandfather window, added value to justify the jump, and a plan for how it is communicated — without apologising for it. |
A small, realistic result for the pricing.txt paste above, trimmed for length:
{
"report_name": "Pricing review - CI build-cache API",
"verdict_level": "raise",
"verdict": "A 20-engineer team saves about $6,000/mo and pays $49/mo, a value ratio near
120x; move to a platform fee plus a cache-volume variable and take the
flat Pro plan to $299/mo with a 12-month grandfather.",
"overview": "A self-serve CI build-cache API with two plans: a 5 GB free tier and a
$49/mo flat Pro plan carrying 100 GB and unlimited seats. ...",
"health": [
{ "area": "Value capture & price level", "status": "bad",
"note": "$6,000/mo of saved engineer time against $49/mo is roughly 120x - far
past the 10x massively-underpriced line." },
{ "area": "Pricing model fit", "status": "bad",
"note": "A flat fee with unlimited seats and a hard 100 GB cap charges the same
for a 3-engineer team and a 200-engineer team." },
{ "area": "Free-to-paid boundary", "status": "risk",
"note": "5 GB is generous enough that a small production repo may never leave the
free tier; the paste gives no conversion rate to confirm." },
{ "area": "Enterprise & segmentation", "status": "bad",
"note": "There is no enterprise motion at all, so SSO, audit logs and SLA demand
arrives with nowhere to land." },
{ "area": "Positioning signal", "status": "bad",
"note": "$49/mo reads as an SMB side-tool, not the production build infrastructure
a 20-engineer team depends on." }
],
"findings": [
{ "severity": "high", "category": "value-capture",
"title": "Pro is priced at roughly 1% of the value it delivers",
"detail": "20 minutes saved per build across a 20-engineer team is the $6,000/mo
figure in the paste; $6,000 / $49 is about 120x, against a healthy band
of 3-5x. A 62% win rate and no pushback in 9 months confirm it.",
"recommendation": "Take the flat plan to $299/mo now and re-test in two quarters;
even at 20x you are still well inside what the value supports." },
{ "severity": "high", "category": "model",
"title": "A flat fee cannot track cache volume that varies by an order of magnitude",
"detail": "Cost to serve is stated at $9/mo for an average Pro account, but the
100 GB ceiling means a heavy team costs many times that while paying the
same $49.",
"recommendation": "Platform fee of $299/mo covering 250 GB, then $0.40/GB-month
beyond it - the fee covers cost to serve, the variable scales." },
{ "severity": "medium", "category": "enterprise",
"title": "No enterprise tier for the buyers who need SSO and an SLA",
"detail": "The paste says self-serve only and no enterprise tier, yet the product
sits on the critical path of every build.",
"recommendation": "Add a Custom tier - contact sales, priced per deal against
deployment, support level and compliance - and never publish a
number for it." }
],
"checklist": [
{ "item": "Price anchored to customer value, not cost", "status": "fail",
"note": "$49 is not derived from the $6,000/mo alternative the paste names." },
{ "item": "Value ratio inside the 3-5x healthy band", "status": "fail",
"note": "Roughly 120x for the 20-engineer case." },
{ "item": "Pricing model matches usage variance", "status": "fail",
"note": "Flat fee against a 100 GB range that plainly varies more than 5x." },
{ "item": "Base fee covers cost to serve", "status": "pass",
"note": "$49 against a stated $9/mo cost to serve on an average account." },
{ "item": "Free tier ends below production usage", "status": "na",
"note": "No conversion or free-tier usage data in the paste." },
{ "item": "Paid trigger tied to a conversion signal", "status": "pass",
"note": "The 5 GB cache limit is a real usage wall." },
{ "item": "Enterprise pricing kept as a conversation", "status": "na",
"note": "There is no enterprise motion yet." },
{ "item": "Volume discounts floored above cost plus margin", "status": "na",
"note": "No discounting is described." },
{ "item": "Support and compliance priced explicitly", "status": "fail",
"note": "Neither is mentioned as a priced line." },
{ "item": "Price level matches the target segment", "status": "fail",
"note": "$49/mo signals SMB tooling for production build infrastructure." },
{ "item": "Annual escalator in enterprise contracts", "status": "na",
"note": "No contracts described." },
{ "item": "Grandfathering plan for price changes", "status": "na",
"note": "No prior price change described." }
],
"coverage_check": [
{ "id": "fig-dollar-1-49", "addressed": true,
"note": "The Pro price; the value-capture finding is built on it." },
{ "id": "fig-winrate", "addressed": true,
"note": "62% is above the 40% raise-readiness threshold." },
{ "id": "model-freemium", "addressed": true,
"note": "Covered by the free-to-paid boundary area." },
{ "id": "model-flat", "addressed": true,
"note": "The flat fee is the subject of the model finding." }
],
"plan": {
"model": "Hybrid: platform fee + cache-volume usage, with a sales-led Custom tier",
"tiers": [
{ "name": "Free", "price": "$0", "target": "learners and side projects",
"includes": "2 GB cache, community support",
"trigger": "crossing 2 GB, which is where a real repo lands" },
{ "name": "Team", "price": "$299/mo + $0.40/GB-month over 250 GB",
"target": "production engineering teams",
"includes": "250 GB included, unlimited seats, email support",
"trigger": "any team running CI on a shared repo daily" },
{ "name": "Custom", "price": "Custom (conversation)",
"target": "enterprises with compliance or SLA requirements",
"includes": "SSO, audit logs, 24/7 SLA, dedicated CSM",
"trigger": "a security review or an SLA request" }
],
"rationale": "The platform fee covers cost to serve at every account size while the
per-GB variable tracks the one thing that both costs you money and
correlates with value. ..."
},
"next_steps": [
"Add one onboarding question: what would you do without this? Instrument the answer.",
"Move the free ceiling from 5 GB to 2 GB for new signups only.",
"Announce $299/mo for new accounts; grandfather existing Pro accounts for 12 months.",
"Stand up a Custom tier page with contact sales and no published number."
],
"summary": "We are capturing about 1% of the value we create; the move is a hybrid
platform fee at $299/mo plus per-GB overage, grandfathered for a year. ..."
}
The report is a starting point, not a pricing decision: it is written to be internally consistent with the findings, but it is AI-generated and it only sees what you pasted. Check the numbers against your own cost and revenue data, talk to customers before you move a published price, and keep finance and legal in the loop on contracts and grandfathering — a price change is a commitment to every customer you have.
Step 5 — Stream the review as it is written
/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 twelve-item checklist and the tier plan 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.
| Event | Payload | Meaning |
|---|---|---|
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: pricing-$(date +%s)" \
-d @input.json
# event: job
# data: {"job_id":"job_...","status":"running"}
#
# event: delta
# data: {"text":"{\"report_name\":\"Pricing review - CI build"}
# ...
# event: done
# data: {"job_id":"job_...","status":"succeeded","charged_credits":540,"output":{"output":"{...}"}}
import json, requests
result = None
with requests.post(
API + "/run-stream",
headers={"Authorization": f"Bearer {TOKEN}",
"Idempotency-Key": "pricing-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 tier in report["plan"]["tiers"]:
print(f' {tier["name"]}: {tier["price"]}')
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 tier of report.plan.tiers) console.log(` ${tier.name}: ${tier.price}`);
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", "pricing-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.Plan.Tiers.
// 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", "pricing-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[], findings[], checklist[], plan{model, tiers[]} and the rest.
require "net/http"
require "json"
uri = URI(API + "/run-stream")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{TOKEN}"
req["Content-Type"] = "application/json"
req["Idempotency-Key"] = "pricing-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["plan"]["tiers"].each { |t| puts " #{t["name"]}: #{t["price"]}" }
$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: pricing-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["plan"]["tiers"] as $t) { echo " {$t['name']}: {$t['price']}\n"; }
var req = new HttpRequestMessage(HttpMethod.Post, Api + "/run-stream") {
Content = JsonContent.Create(payload),
};
req.Headers.Add("Idempotency-Key", "pricing-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 t in report.GetProperty("plan").GetProperty("tiers").EnumerateArray())
Console.WriteLine($" {t.GetProperty("name")}: {t.GetProperty("price")}");
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.