Flight-check your browser-use automation from your own scripts
Send a browser-use Python script — one heredoc block or several, each preceded by a
# file: task.sh comment — or, in plan mode, a plain-language description of
the job, and get back one JSON object: a readiness posture, the browser call (does this need
a browser at all, and local Chrome or a managed cloud browser), the inventory of every
navigation, interaction, extraction, daemon and recording, prioritized findings across
correctness, resilience, efficiency, auth-and-secrets, billing hygiene and etiquette, each
with a corrected Python fragment, and the complete runnable script. Everything this app does
goes through the SkillSafe App API — plain JSON over HTTPS — so you can hang a
flight check off anything that produces automation. Wire it into whatever writes or reviews
your scripts: a pre-merge check on automation/, a nightly audit of the scripts
you schedule, or an editor command. Pick a language once and the whole page follows.
Basics
Base URL: https://api.skillsafe.ai/v1/app-api, app slug
browser-pilot. 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 flight check 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 script or
one task description in, one flight check 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 checking a very large script). |
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 flight-check
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":"browser-pilot"}' | jq -r '.data.token'
token = api("POST", "/guest", {"slug": "browser-pilot"})["token"]
const { token } = await api("POST", "/guest", { slug: "browser-pilot" });
var guest struct{ Token string `json:"token"` }
err := call("POST", "/guest", map[string]string{"slug": "browser-pilot"}, &guest)
String envelope = api("POST", "/guest", """
{"slug":"browser-pilot"}""");
// token is at data.token in the returned JSON
token = api("POST", "/guest", { slug: "browser-pilot" })["token"]
$token = api("POST", "/guest", ["slug" => "browser-pilot"])["token"];
var guest = await SkillSafe.ApiAsync(HttpMethod.Post, "/guest",
new { slug = "browser-pilot" });
var token = guest.GetProperty("token").GetString();
The app stores this browser's token under the localStorage key
skillsafe_app_token:browser-pilot, 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 checking a
long script.
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 piping a whole automation/
directory in and want a ceiling before spending credits.
| Input field | Type | Notes |
|---|---|---|
source | string, required | In review mode: the browser-use Python — a full browser-use <<'PY' … PY heredoc, several heredocs with comments between them, or bare Python that uses the harness helpers (new_tab, wait_for_load, page_info, click_at_xy, js, cdp). In plan mode: a plain-language description of the automation task. This is the model's only evidence — nothing is executed and no browser is launched. Inputs longer than 100,000 characters are clipped middle-out, with a # [... clipped ...] comment showing where. At least 40 characters are needed for a run. |
mode | string | review | plan. review corrects a script you already have; plan designs and writes one from a description. The app defaults to review; if you omit the field, the app infers it from whether the text looks like a script. |
target | string | local-chrome | cloud | unsure — where you expect to run the script. It is a starting assumption, not a constraint: the model will still recommend the other one (or no-browser) in browser_call.target when the task calls for it, and say why in target_why. |
context | string, optional | Extra context: site quirks, whether a logged-in session already exists in the profile, how many pages or items the run touches, how often it runs, any rate limiting or blocking you have already hit, and any trade-off you have already chosen to accept. Clipped at 20,000 characters. |
prescan_facts | object, optional | What the free client-side prescan mechanically matched in the text: {"resources": [], "flags": []}. Each entry is {id, label}. Resource ids look like res:blocks, res:nav/status-example-com, res:daemon/r7k2 or res:signal/login; flag ids are <check>:<name> — first-nav-goto:1, missing-wait:4, fixed-sleep:3, unverified-click:12, raw-ax-dump:18, screenshot-first:9, fetch-first:read-only, fetch-first:plan, daemon-leak:r7k2, daemon-name:r7k2, recording:no-stop, recording:latest, typed-secret:fill-password. Every flag id you send comes back in coverage_check. The web UI fills this from its own scan (buscan.js); API callers may omit the field or send the two empty arrays. |
retry_note | string, optional | A reformat instruction, set only when a previous reply failed to parse as JSON. The app's automatic retry uses it; leave it out. |
cat > task.sh <<'SRC'
browser-use <<'PY'
goto_url("https://status.example.com")
import time
time.sleep(5)
print(page_info())
PY
SRC
jq -n --rawfile source task.sh \
'{source: $source,
mode: "review",
target: "local-chrome",
context: "Runs hourly from a laptop; the status banner is rendered client-side.",
prescan_facts: {resources: [], flags: []}}' > input.json
curl -s -X POST "$API/estimate" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d @input.json | jq '.data.hold_credits'
SOURCE = """browser-use <<'PY'
goto_url("https://status.example.com")
import time
time.sleep(5)
print(page_info())
PY
"""
payload = {
"source": SOURCE,
"mode": "review",
"target": "local-chrome",
"context": "Runs hourly from a laptop; the status banner is rendered client-side.",
"prescan_facts": {"resources": [], "flags": []},
}
est = api("POST", "/estimate", payload)
print("worst case:", est.get("hold_credits", est.get("credits")), "credits")
const source = [
"browser-use <<'PY'",
'goto_url("https://status.example.com")',
"import time",
"time.sleep(5)",
"print(page_info())",
"PY",
].join("\n");
const payload = {
source,
mode: "review",
target: "local-chrome",
context: "Runs hourly from a laptop; the status banner is rendered client-side.",
prescan_facts: { resources: [], flags: [] },
};
const est = await api("POST", "/estimate", payload);
console.log("worst case:", est.hold_credits ?? est.credits, "credits");
const source = `browser-use <<'PY'
goto_url("https://status.example.com")
import time
time.sleep(5)
print(page_info())
PY`
payload := map[string]any{
"source": source,
"mode": "review",
"target": "local-chrome",
"context": "Runs hourly from a laptop; the status banner is rendered client-side.",
"prescan_facts": map[string]any{
"resources": []any{}, "flags": []any{},
},
}
var est struct{ HoldCredits int64 `json:"hold_credits"` }
err := call("POST", "/estimate", payload, &est)
String source = """
browser-use <<'PY'
goto_url("https://status.example.com")
import time
time.sleep(5)
print(page_info())
PY
""";
String jsonPayload = """
{"source": %s,
"mode": "review",
"target": "local-chrome",
"context": "Runs hourly from a laptop; the status banner is rendered client-side.",
"prescan_facts": {"resources": [], "flags": []}}
""".formatted(toJsonString(source));
String envelope = api("POST", "/estimate", jsonPayload);
// worst-case cost is at data.hold_credits
SOURCE = <<~PYSRC
browser-use <<'PY'
goto_url("https://status.example.com")
import time
time.sleep(5)
print(page_info())
PY
PYSRC
payload = { source: SOURCE,
mode: "review",
target: "local-chrome",
context: "Runs hourly from a laptop; the status banner is rendered client-side.",
prescan_facts: { resources: [], flags: [] } }
est = api("POST", "/estimate", payload)
puts "worst case: #{est["hold_credits"] || est["credits"]} credits"
$source = <<<'PYSRC'
browser-use <<'PY'
goto_url("https://status.example.com")
import time
time.sleep(5)
print(page_info())
PY
PYSRC;
$payload = [
"source" => $source,
"mode" => "review",
"target" => "local-chrome",
"context" => "Runs hourly from a laptop; the status banner is rendered client-side.",
"prescan_facts" => ["resources" => [], "flags" => []],
];
$est = api("POST", "/estimate", $payload);
echo "worst case: " . ($est["hold_credits"] ?? $est["credits"]) . " credits\n";
var source = """
browser-use <<'PY'
goto_url("https://status.example.com")
import time
time.sleep(5)
print(page_info())
PY
""";
var payload = new {
source,
mode = "review",
target = "local-chrome",
context = "Runs hourly from a laptop; the status banner is rendered client-side.",
prescan_facts = new {
resources = Array.Empty<object>(), flags = Array.Empty<object>(),
},
};
var est = await SkillSafe.ApiAsync(HttpMethod.Post, "/estimate", payload);
Console.WriteLine($"worst case: {est.GetProperty("hold_credits")} credits");
prescan_facts.flags is how you make the flight check answer for things you
already know about. Send {"resources": [{"id": "res:blocks", "label": "Blocks/1
browser-use invocation"}], "flags": [{"id": "first-nav-goto:1", "label": "goto_url is the
first navigation"}]} and every flag id comes back in coverage_check
— addressed by a finding, or set aside with the reason. Nothing you flag is silently
dropped, which makes it the field to assert on in a CI check.
Step 4 — Run the flight check 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 30–90 s, since every finding carries corrected Python and the reply ends
with a complete runnable script). Always send an Idempotency-Key header so a
network retry can't start a second, double-charged run. The flight check is in
output — usually nested as output.output, and as a JSON
string, so parse defensively. The samples below print the posture, the browser
call, the inventory, the prioritized findings and the focus areas, then save the whole
object to check.json and the runnable script to run-task.sh.
JOB_ID=$(curl -s -X POST "$API/run" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-H "Idempotency-Key: bp-$(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 flight check once, then read it
echo "$JOB" | jq -r '.data.output.output' > check.json
jq -r '
"\(.plan_name) [\(.posture)]: \(.verdict)",
"",
"BROWSER CALL",
" needed=\(.browser_call.needed) target=\(.browser_call.target)",
" \(.browser_call.why)",
" \(.browser_call.target_why)",
"",
"INVENTORY",
(.inventory[] | " \(.kind)/\(.name) in \(.scope) - \(.role)"),
"",
"FINDINGS",
(.findings[] | " [\(.priority)] \(.id) \(.category) \(.resource): \(.problem)"),
"",
"QUICK WINS",
(.quick_wins[] | " - \(.)"),
"",
"FOCUS AREAS",
(.focus_areas[] | " \(.area) - \(.why)"),
"",
"COVERAGE",
(.coverage_check[] | " \(.id): \(if .addressed then "ok" else "SET ASIDE" end) - \(.note)")' \
check.json
# the corrected, complete script comes back ready to run
jq -r '.script' check.json > run-task.sh
# fail the pipeline on anything critical
jq -e '[.findings[] | select(.priority == "critical")] | length == 0' check.json > /dev/null \
|| { echo "critical findings present"; exit 1; }
import time
job_id = api("POST", "/run", payload,
**{"Idempotency-Key": "bp-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"]
check = json.loads(raw) if isinstance(raw, str) else raw
print(f'{check["plan_name"]} [{check["posture"]}]: {check["verdict"]}')
bc = check["browser_call"]
print(f' browser needed={bc["needed"]} target={bc["target"]} - {bc["target_why"]}')
for r in check["inventory"]:
print(f' {r["kind"]}/{r["name"]:<28} in={r["scope"] or "-":<12} {r["role"]}')
for f in check["findings"]:
print(f' [{f["priority"]:>8}] {f["id"]} {f["category"]} {f["resource"]}')
print(f' L:{f["likelihood"]}/S:{f["severity"]} {f["problem"]}')
print(f' fix: {f["fix"]}')
if f["snippet"]:
print(" snippet:", f["snippet"].splitlines()[0], "...")
for w in check["quick_wins"]:
print(" win:", w)
for a in check["focus_areas"]:
print(f' focus {a["area"]} {a["finding_ids"]} - {a["why"]}')
for c in check["coverage_check"]:
print(f' {c["id"]}: {"ok" if c["addressed"] else "SET ASIDE"} - {c["note"]}')
with open("check.json", "w", encoding="utf-8") as fh:
json.dump(check, fh, indent=2)
with open("run-task.sh", "w", encoding="utf-8") as fh:
fh.write(check["script"])
critical = [f for f in check["findings"] if f["priority"] == "critical"]
if critical:
raise SystemExit(f"{len(critical)} critical finding(s)")
import { writeFileSync } from "node:fs";
const { job_id } = await api("POST", "/run", payload,
{ "Idempotency-Key": crypto.randomUUID() });
let job;
do {
await new Promise((r) => setTimeout(r, 1500));
job = await api("GET", `/jobs/${job_id}`);
} while (job.status !== "succeeded" && job.status !== "failed");
if (job.status === "failed") throw new Error(job.error ?? "run failed");
const raw = job.output?.output ?? job.output;
const check = typeof raw === "string" ? JSON.parse(raw) : raw;
console.log(`${check.plan_name} [${check.posture}]: ${check.verdict}`);
const bc = check.browser_call;
console.log(` browser needed=${bc.needed} target=${bc.target} - ${bc.target_why}`);
for (const r of check.inventory) {
console.log(` ${r.kind}/${r.name} (${r.scope || "-"}): ${r.role}`);
}
for (const f of check.findings) {
console.log(` [${f.priority}] ${f.id} ${f.category} ${f.resource}`);
console.log(` L:${f.likelihood}/S:${f.severity} - ${f.fix}`);
}
for (const w of check.quick_wins) console.log(` win: ${w}`);
for (const a of check.focus_areas) {
console.log(` focus ${a.area} (${a.finding_ids.join(", ")}): ${a.why}`);
}
for (const c of check.coverage_check) {
console.log(` ${c.id}: ${c.addressed ? "ok" : "SET ASIDE"} - ${c.note}`);
}
writeFileSync("check.json", JSON.stringify(check, null, 2));
writeFileSync("run-task.sh", check.script);
const critical = check.findings.filter((f) => f.priority === "critical");
if (critical.length) process.exitCode = 1;
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, then unmarshal:
type Check struct {
PlanName string `json:"plan_name"`
Posture string `json:"posture"`
Verdict string `json:"verdict"`
ExecSummary string `json:"exec_summary"`
Assumptions []string `json:"assumptions"`
OpenQuestions []string `json:"open_questions"`
BrowserCall struct {
Needed bool `json:"needed"`
Why string `json:"why"`
Target string `json:"target"`
TargetWhy string `json:"target_why"`
} `json:"browser_call"`
Inventory []struct {
Kind, Name, Scope, Role string
} `json:"inventory"`
Findings []struct {
ID, Category, Severity, Likelihood, Priority string
Resource, Problem, Impact, Fix, Snippet string
} `json:"findings"`
Script string `json:"script"`
CoverageCheck []struct {
ID, Note string
Addressed bool
} `json:"coverage_check"`
QuickWins []string `json:"quick_wins"`
FocusAreas []struct {
Area, Why string
FindingIDs []string `json:"finding_ids"`
} `json:"focus_areas"`
Summary string `json:"summary"`
}
var wrapper struct{ Output string `json:"output"` }
json.Unmarshal(job.Output, &wrapper)
var check Check
json.Unmarshal([]byte(wrapper.Output), &check)
fmt.Printf("%s [%s]: %s\n", check.PlanName, check.Posture, check.Verdict)
fmt.Printf(" browser needed=%v target=%s\n", check.BrowserCall.Needed, check.BrowserCall.Target)
for _, r := range check.Inventory {
fmt.Printf(" %s/%s (%s): %s\n", r.Kind, r.Name, r.Scope, r.Role)
}
for _, f := range check.Findings {
fmt.Printf(" [%s] %s %s %s: %s\n", f.Priority, f.ID, f.Category, f.Resource, f.Problem)
}
for _, a := range check.FocusAreas {
fmt.Printf(" focus %s %v: %s\n", a.Area, a.FindingIDs, a.Why)
}
os.WriteFile("check.json", []byte(wrapper.Output), 0o644)
os.WriteFile("run-task.sh", []byte(check.Script), 0o755)
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 flight check is at data.output.output as a JSON string — parse it again, then read
// plan_name, posture, verdict, exec_summary, assumptions[], open_questions[],
// browser_call (needed/why/target/target_why),
// inventory[] (kind/name/scope/role),
// findings[] (id/category/severity/likelihood/priority/resource/problem/impact/fix/snippet),
// script, coverage_check[] (id/addressed/note), quick_wins[],
// focus_areas[] (area/why/finding_ids[]) and summary.
// Finally keep the check and the runnable script on disk:
// Files.writeString(Path.of("check.json"), checkJson);
// Files.writeString(Path.of("run-task.sh"), script);
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"]
check = raw.is_a?(String) ? JSON.parse(raw) : raw
puts "#{check["plan_name"]} [#{check["posture"]}]: #{check["verdict"]}"
bc = check["browser_call"]
puts " browser needed=#{bc["needed"]} target=#{bc["target"]} - #{bc["target_why"]}"
check["inventory"].each { |r| puts " #{r["kind"]}/#{r["name"]} (#{r["scope"]}): #{r["role"]}" }
check["findings"].each do |f|
puts " [#{f["priority"]}] #{f["id"]} #{f["category"]} #{f["resource"]}"
puts " L:#{f["likelihood"]}/S:#{f["severity"]} - #{f["fix"]}"
end
check["quick_wins"].each { |w| puts " win: #{w}" }
check["focus_areas"].each { |a| puts " focus #{a["area"]} #{a["finding_ids"].join(", ")}" }
check["coverage_check"].each { |c| puts " #{c["id"]}: #{c["addressed"] ? "ok" : "SET ASIDE"}" }
File.write("check.json", JSON.pretty_generate(check))
File.write("run-task.sh", check["script"])
exit 1 if check["findings"].any? { |f| f["priority"] == "critical" }
$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"];
$check = is_string($raw) ? json_decode($raw, true) : $raw;
echo "{$check['plan_name']} [{$check['posture']}]: {$check['verdict']}\n";
$bc = $check["browser_call"];
echo " browser needed=" . ($bc["needed"] ? "true" : "false") . " target={$bc['target']}\n";
foreach ($check["inventory"] as $r) {
echo " {$r['kind']}/{$r['name']} ({$r['scope']}): {$r['role']}\n";
}
foreach ($check["findings"] as $f) {
echo " [{$f['priority']}] {$f['id']} {$f['category']} {$f['resource']}\n";
echo " L:{$f['likelihood']}/S:{$f['severity']} - {$f['fix']}\n";
}
foreach ($check["quick_wins"] as $w) {
echo " win: $w\n";
}
foreach ($check["focus_areas"] as $a) {
echo " focus {$a['area']}: " . implode(", ", $a["finding_ids"]) . "\n";
}
foreach ($check["coverage_check"] as $c) {
echo " {$c['id']}: " . ($c["addressed"] ? "ok" : "SET ASIDE") . "\n";
}
file_put_contents("check.json", json_encode($check, JSON_PRETTY_PRINT));
file_put_contents("run-task.sh", $check["script"]);
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 check = doc.RootElement;
Console.WriteLine($"{check.GetProperty("plan_name")} " +
$"[{check.GetProperty("posture")}]: {check.GetProperty("verdict")}");
var bc = check.GetProperty("browser_call");
Console.WriteLine($" browser needed={bc.GetProperty("needed")} target={bc.GetProperty("target")}");
foreach (var r in check.GetProperty("inventory").EnumerateArray())
{
Console.WriteLine($" {r.GetProperty("kind")}/{r.GetProperty("name")}: {r.GetProperty("role")}");
}
foreach (var f in check.GetProperty("findings").EnumerateArray())
{
Console.WriteLine($" [{f.GetProperty("priority")}] {f.GetProperty("id")} " +
$"{f.GetProperty("category")} {f.GetProperty("resource")} " +
$"(L:{f.GetProperty("likelihood")}/S:{f.GetProperty("severity")})");
}
foreach (var a in check.GetProperty("focus_areas").EnumerateArray())
{
Console.WriteLine($" focus {a.GetProperty("area")}: {a.GetProperty("why")}");
}
await File.WriteAllTextAsync("check.json", rawText!);
await File.WriteAllTextAsync("run-task.sh", check.GetProperty("script").GetString()!);
The model is asked for one JSON object and nothing else, but a stray code fence or preamble
is always possible. Strip a leading ```json fence, take the text between the
first { and the last }, and only then parse — that is what
the app does before it falls back to a retry_note reformat run.
The flight check object — output schema
One JSON object, always the same shape. Every array is present, and the check is grounded in
the text you sent alone: findings cite only navigations, interactions, extractions, daemons
and recordings that actually appear in source (or, in plan mode, planned steps
of the model's own design), and a construct that is simply absent (no
wait_for_load after a navigation, no verification after a click, no
stop_daemon) is reported against the closest real construct or against
(missing from the script). Where the source is silent on something that changes
the verdict you get an entry in assumptions and, if it would change the
ranking, in open_questions. Expect four to twelve findings in review mode and
two to six in plan mode — a well-built script may honestly yield two or three, and
findings is never empty.
| Field | Type | Meaning |
|---|---|---|
plan_name | string | A short title naming the task or the script — e.g. vendor invoice download — script review. |
posture | string | ready-to-run | needs-hardening | rethink-approach. See the table below. |
verdict | string | One sentence justifying the posture and naming the single most important change. |
exec_summary | string | Two or three paragraphs, separated by blank lines, on the dominant themes across the script or the plan. |
assumptions | string[] | Explicit assumptions filling gaps the source left open. Read these first — a wrong assumption invalidates the findings built on it. |
open_questions | string[] | Questions whose answers would change the design or the ranking. |
browser_call | object | {needed, why, target, target_why}. needed is a boolean: the fetch-first rule asks whether a browser is justified at all, and why names which of the four justifications applies — interaction, a logged-in session, JavaScript rendering, bot protection — or why none does. target is local-chrome | cloud | no-browser, and target_why ties it to the task's parallelism, blocking risk and session needs. It answers the target you sent but is not bound by it. |
inventory | array | {kind, name, scope, role} — every construct the check parsed out of the script, or, in plan mode, the planned steps in order, one row each. kind is one of Step, Navigation, Interaction, Extraction, Wait, Auth, Daemon, Recording, Helper, Signal. scope is the heredoc block it belongs to, e.g. block 1. |
findings | array | The prioritized findings table — ids BP-001, BP-002, … in sequence, at least one entry. Columns are listed below. |
script | string | The complete runnable script, not a fragment: one or more browser-use <<'PY' … PY heredocs with comments between them, with every finding's fix already applied. When browser_call.needed is false this is the non-browser alternative instead — a curl or Python-requests sketch — with a comment saying why the browser was dropped. Never contains a credential literal. Write it straight to a .sh file. |
coverage_check | array | {id, addressed, note} — one entry per prescan_facts.flags id you sent, each appearing exactly once. See the semantics below. |
quick_wins | string[] | One-line changes worth doing immediately, ahead of any planning. May be empty when nothing here is a one-liner. |
focus_areas | array | {area, why, finding_ids} — what to work through first, one sentence tied to the check, and the finding ids that motivate it. Every id in finding_ids exists in findings. |
summary | string | Closing paragraph: what to fix first, and what risk remains after that. |
The three posture values:
| posture | What it means |
|---|---|
ready-to-run | The script holds up as written: navigation discipline (a fresh tab for the first navigation, wait_for_load after each one), condition waits rather than sleeps, actions verified after the fact, a clean auth posture, daemons named and stopped. Findings still exist, but they are additions and refinements — deeper verification, a pagination limit, a cloud browser for scale — not blockers. Genuinely well-built scripts land here rather than having severity manufactured for them. |
needs-hardening | The approach is right, but named gaps should be closed before this runs unattended — a fixed sleep standing in for a load event, a click that is never verified, a daemon started without BU_NAME, a recording that is never stopped. |
rethink-approach | The design is wrong at the root: a browser where a plain fetch would do, an approach that must type credentials into a login form, a single shared tab where the task needs isolated parallel browsers. The fix is a different plan, not a patch — and script shows that different plan. |
Each entry in findings:
| Column | Meaning |
|---|---|
id | Sequential BP-001, BP-002, … — the stable handle referenced from focus_areas[].finding_ids. |
category | correctness | resilience | efficiency | auth-and-secrets | billing-hygiene | etiquette. Billing hygiene covers cloud daemons left running and recordings left open; etiquette covers pacing, rate limits and what a site would reasonably object to. |
severity | low | medium | high — how bad it is when it bites. |
likelihood | low | medium | high — how likely it is to bite. |
priority | critical | high | medium | low — severity by likelihood. critical is reserved for something that makes the run dishonest or unsafe (typed credentials, a remote daemon left billing, an action reported as successful on a page that was never verified) or that will fail or misbehave on most runs, so sort on this field and work top-down. This is also the field to gate a pipeline on. |
resource | The Navigation/new_tab(…), Interaction/click_at_xy, Daemon/r7k2 or planned step this is about — always something that appears in source or in the plan, or the literal (missing from the script) when the finding is about an absent construct. |
problem | What is wrong, in this script or plan specifically. |
impact | What happens when it runs because of this. |
fix | The concrete change to make — not "add error handling". |
snippet | A corrected Python fragment you can paste: the fixed block, correctly indented, using the harness helpers, not the whole script. Empty string when a snippet would add nothing. Secret values are never echoed — a placeholder appears instead. |
coverage_check semantics:
| Case | What you get |
|---|---|
| Every flag id you sent | Each prescan_facts.flags id appears in coverage_check exactly once. Nothing you flagged is silently dropped, which makes this the field to assert on in a CI check. Ids in prescan_facts.resources are not reconciled here — they shape the inventory instead. |
addressed: true | The flag is covered by the check; note names the finding id that covers it. |
addressed: false | The flag was deliberately set aside; note gives the reason — a check that fired but is not a real problem for this script (a fixed sleep that is a deliberate courtesy delay between requests, a fetch-first flag on a task that turns out to need a logged-in session after all). |
| Nothing sent | Omit prescan_facts, or send the two empty arrays, and coverage_check comes back empty. The rest of the check is unaffected. |
A small, realistic result for the snippet above, trimmed for length:
{
"plan_name": "status page check — script review",
"posture": "needs-hardening",
"verdict": "The approach is sound, but the first navigation must be new_tab and the fixed
sleep must become wait_for_load — a two-line fix.",
"exec_summary": "A single heredoc that opens a public status page and prints whatever
page_info() returns. The intent is clear and the scope is small.
Two harness rules are broken. goto_url is used as the first navigation, which
takes over whatever tab the user has focused, and time.sleep(5) stands in for
the load event — too long on a fast run, too short on a slow one. Both have
one-line fixes and neither changes the shape of the script.",
"assumptions": [
"The status page is public and needs no login.",
"The run is interactive, on a laptop where a visible Chrome window is acceptable."
],
"open_questions": [
"Is there a JSON status endpoint a plain fetch could read instead of a browser?",
"Which element on the page actually carries the status text you want?"
],
"browser_call": {
"needed": true,
"why": "The status banner is rendered by JavaScript, so a plain fetch returns a shell page.",
"target": "local-chrome",
"target_why": "One quick read in the user's own browser; no parallelism and no blocking risk,
so a cloud browser would add cost and latency for nothing."
},
"inventory": [
{ "kind": "Navigation", "name": "goto_url(https://status.example.com)", "scope": "block 1",
"role": "Opens the status page — the only navigation in the script." },
{ "kind": "Wait", "name": "time.sleep(5)", "scope": "block 1",
"role": "Stands in for the page load; not tied to any condition." },
{ "kind": "Extraction", "name": "page_info()", "scope": "block 1",
"role": "Prints the whole page summary rather than the status text." }
],
"findings": [
{ "id": "BP-001", "category": "correctness",
"severity": "medium", "likelihood": "high", "priority": "high",
"resource": "Navigation/goto_url(https://status.example.com)",
"problem": "goto_url is the first navigation, so it replaces whatever page the user's
current tab is showing.",
"impact": "The focused tab is hijacked mid-session; if it was an internal browser page the
call can fail outright and the run ends with no output.",
"fix": "Open the page in a fresh tab with new_tab, and keep wait_for_load right after it.",
"snippet": "new_tab(\"https://status.example.com\")\nwait_for_load()" },
{ "id": "BP-002", "category": "resilience",
"severity": "medium", "likelihood": "high", "priority": "high",
"resource": "Wait/time.sleep(5)",
"problem": "A fixed five-second sleep is used as the readiness signal instead of the load
event.",
"impact": "On a slow network the banner has not rendered yet and page_info() prints a
half-built page; on a fast one the script idles for five seconds every run.",
"fix": "Replace the sleep with wait_for_load(), which returns as soon as the page settles.",
"snippet": "wait_for_load()" },
{ "id": "BP-003", "category": "efficiency",
"severity": "low", "likelihood": "medium", "priority": "low",
"resource": "Extraction/page_info()",
"problem": "page_info() prints a whole-page summary when only the status banner is wanted.",
"impact": "The useful line is buried in noise, and any layout change silently shifts where
it appears.",
"fix": "Read the banner directly with js() and fall back to a clear message when the
selector misses.",
"snippet": "print(js(\"document.querySelector('.status-banner')?.innerText || 'no banner found'\"))" }
],
"script": "browser-use <<'PY'\nnew_tab(\"https://status.example.com\")\nwait_for_load()\ninfo = page_info()\nprint(info[\"title\"])\nprint(js(\"document.querySelector('.status-banner')?.innerText || 'no banner found'\"))\nPY",
"coverage_check": [],
"quick_wins": [
"Swap goto_url for new_tab on the first navigation.",
"Replace time.sleep(5) with wait_for_load()."
],
"focus_areas": [
{ "area": "Navigation discipline",
"why": "Both high-priority findings are the harness's two navigation rules, and both are
one-line fixes.",
"finding_ids": ["BP-001", "BP-002"] },
{ "area": "Extract the value, not the page",
"why": "Printing page_info() wholesale makes the output unusable by anything downstream.",
"finding_ids": ["BP-003"] }
],
"summary": "Fix the first navigation and the wait, then read the banner directly — after that
this is ready to run unattended. If the site exposes a JSON status endpoint, drop
the browser entirely and fetch it: cheaper, faster and nothing to hijack."
}
This is AI-generated guidance from source text, not a test run: it sees only what you sent,
never a real browser session, the actual site, or how it behaved last time. Check
assumptions and open_questions before you act on the rankings,
read script before you run it — it drives a real browser — and
keep a human in the loop for anything that logs in, pays or writes.
Step 5 — Stream the flight check 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 a findings table with corrected Python plus a complete script makes for a long
reply. This app's own progress panel is this endpoint. Events are separated by a blank
line; each has an event: line and a data: line carrying JSON.
| 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). The app advances its step list by watching for the "plan_name", "browser_call", "inventory", "findings", "script" and "coverage_check" keys as they arrive. |
done | {job_id, status, charged_credits, output} | The final, authoritative result — read the check 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: bp-$(date +%s)" \
-d @input.json
# event: job
# data: {"job_id":"job_...","status":"running"}
#
# event: delta
# data: {"text":"{\"plan_name\":\"status"}
# ...
# event: done
# data: {"job_id":"job_...","status":"succeeded","charged_credits":612,"output":{"output":"{...}"}}
import json, requests
result = None
with requests.post(
API + "/run-stream",
headers={"Authorization": f"Bearer {TOKEN}",
"Idempotency-Key": "bp-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"))
check = json.loads(result["output"]["output"]) # authoritative
print("charged:", result["charged_credits"], "-", check["plan_name"])
print("posture:", check["posture"], "| browser:", check["browser_call"]["target"])
for f in check["findings"]:
print(f' [{f["priority"]}] {f["id"]} {f["resource"]}: {f["problem"]}')
with open("check.json", "w", encoding="utf-8") as fh:
json.dump(check, fh, indent=2)
with open("run-task.sh", "w", encoding="utf-8") as fh:
fh.write(check["script"])
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 check = JSON.parse(done.output.output);
console.log(`\n${done.charged_credits} credits - ${check.plan_name} [${check.posture}]`);
for (const f of check.findings) console.log(` [${f.priority}] ${f.id} ${f.resource}`);
writeFileSync("check.json", JSON.stringify(check, null, 2));
writeFileSync("run-task.sh", check.script);
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", "bp-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 flight-check JSON —
// unmarshal it into the Check struct from step 4, then write check.json and run-task.sh.
// 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", "bp-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
// plan_name, posture, verdict, browser_call, inventory[], findings[], script,
// coverage_check[], quick_wins[], focus_areas[] 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"] = "bp-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
check = JSON.parse(done["output"]["output"])
puts "\n#{done["charged_credits"]} credits - #{check["plan_name"]} [#{check["posture"]}]"
check["findings"].each { |f| puts " [#{f["priority"]}] #{f["id"]} #{f["resource"]}" }
File.write("check.json", JSON.pretty_generate(check))
File.write("run-task.sh", check["script"])
$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: bp-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);
$check = json_decode($done["output"]["output"], true);
echo "\n{$done['charged_credits']} credits - {$check['plan_name']} [{$check['posture']}]\n";
foreach ($check["findings"] as $f) {
echo " [{$f['priority']}] {$f['id']} {$f['resource']}\n";
}
file_put_contents("check.json", json_encode($check, JSON_PRETTY_PRINT));
file_put_contents("run-task.sh", $check["script"]);
var req = new HttpRequestMessage(HttpMethod.Post, Api + "/run-stream") {
Content = JsonContent.Create(payload),
};
req.Headers.Add("Idempotency-Key", "bp-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 checkDoc = JsonDocument.Parse(text!);
var check = checkDoc.RootElement;
Console.WriteLine($"{check.GetProperty("plan_name")} [{check.GetProperty("posture")}]");
foreach (var f in check.GetProperty("findings").EnumerateArray())
Console.WriteLine($" [{f.GetProperty("priority")}] {f.GetProperty("id")} {f.GetProperty("resource")}");
await File.WriteAllTextAsync("check.json", text!);
await File.WriteAllTextAsync("run-task.sh", check.GetProperty("script").GetString()!);
In a browser, the native EventSource only speaks GET, and this endpoint is a
POST — read the fetch response body incrementally, as the JavaScript
sample above does. On an idempotent replay the server may answer with a plain JSON
envelope instead of an event stream; check the Content-Type before you start
parsing frames.