Book the meeting from your own tools
Send a scheduling conversation — an email thread with its quoted replies, a Slack or Teams exchange, or your own notes on who needs to meet — and get back one JSON object: every participant placed in an IANA time zone with the basis for that placement, every stated constraint with the shortest verbatim quote that establishes it, up to three concrete slots ranked best-first, each carrying a per-participant local-time table computed to the minute with daylight saving applied, and a ready-to-send reply email that proposes them in each recipient's own clock. Everything this app does goes through the SkillSafe App API — plain JSON over HTTPS — so you can wire it to the mailbox that receives the thread, run it from a helpdesk workflow, or turn the top slot straight into a calendar invite. 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
meet-desk. Every request sends
Authorization: Bearer <token> and JSON bodies with
Content-Type: application/json. Responses are wrapped in an envelope:
{"data": …} on success, {"error": {"code", "message"}} on failure.
The plan 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 of a thread
in, one scheduling plan 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 submitting 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 scheduling
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":"meet-desk"}' | jq -r '.data.token'
token = api("POST", "/guest", {"slug": "meet-desk"})["token"]
const { token } = await api("POST", "/guest", { slug: "meet-desk" });
var guest struct{ Token string `json:"token"` }
err := call("POST", "/guest", map[string]string{"slug": "meet-desk"}, &guest)
String envelope = api("POST", "/guest", """
{"slug":"meet-desk"}""");
// token is at data.token in the returned JSON
token = api("POST", "/guest", { slug: "meet-desk" })["token"]
$token = api("POST", "/guest", ["slug" => "meet-desk"])["token"];
var guest = await SkillSafe.ApiAsync(HttpMethod.Post, "/guest",
new { slug = "meet-desk" });
var token = guest.GetProperty("token").GetString();
The app stores this browser's token under the localStorage key
skillsafe_app_token:meet-desk, on the app's own origin. The
token page reads and manages it for you — you never need
to open developer tools.
Step 2 — Check who you are and your balance
Returns subject_type ("user" or "guest"),
subject_id and your credits balance. Check this before sending a
long thread.
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 long forwarded thread in and want
a ceiling before spending credits.
| Input field | Type | Notes |
|---|---|---|
thread | string, required | The pasted scheduling conversation: an email thread including its quoted and nested replies, a chat transcript, or free-form notes on who needs to meet and when people are free. This is the model's only evidence about the other participants — no mailbox or calendar is read. A thread clipped in the middle should carry a [... clipped ...] line where the cut is. |
own_availability | string, optional | Your own availability and preferences in prose — "free most of next week except Thursday, prefer mornings". The sender is treated as a participant named You, or by their real name when the thread reveals it. |
own_timezone | string | Your IANA zone, e.g. America/New_York. The web UI detects it from the browser; API callers send it explicitly. It is trusted unless the thread contradicts it, and the contradiction then surfaces in open_questions. |
current_datetime | string | Your current date and time, ISO 8601 with offset, plus the weekday in parentheses: 2026-08-05T14:12:00-04:00 (Wednesday). Every relative date in the thread — "tomorrow", "next Tuesday", "week after next" — is resolved against this, never against the model's guess at today, and every proposed slot must be in the future relative to it. Send the real clock or the plan will be anchored wrongly. |
meeting | object | {title, duration_minutes, format}. title may be an empty string — one is then derived from the thread. duration_minutes is one of 15, 25, 30, 45, 50, 60, 90, and every slot spans it exactly. format is video | phone | in-person | any. |
reply_tone | string | professional | friendly | brief. Sets the register of reply_email only — the analysis sections stay plain and direct whatever you pick. |
prescan_facts | object, optional | What a client-side scanner mechanically matched in the text: {"participants": [], "flags": []}. Each entry is {id, label}. Participant ids look like email:priya@northbeam.example or name:daniel; flag ids are the deterministic checks that fired — no-tz:anywhere, relative-date:1 (one per unanchored phrase), no-availability:1, big-group:1. Every flag id you send comes back in coverage_check. The web UI fills this from its own scan; API callers may omit the field or send the two empty arrays. |
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 > thread.txt <<'THREAD'
From: Priya Raman <priya@northbeam.example>
To: Alex Chen <alex@northbeam.example>, Daniel Okafor <daniel@northbeam.example>
Subject: Q3 roadmap sync
Hi both — we should get the Q3 roadmap sync booked before the offsite.
I'm in Bangalore; next week I'm free after 2pm my time every day except Wednesday.
Priya
From: Daniel Okafor <daniel@northbeam.example>
Works for me. I'm London-based — Tuesday and Thursday are wide open, and
please nothing before 9am my time (school run).
Daniel
THREAD
jq -n --rawfile thread thread.txt \
'{thread: $thread,
own_availability: "I am Alex, in New York. Free most of next week except Thursday. Prefer mornings but can do up to 12:30pm.",
own_timezone: "America/New_York",
current_datetime: "2026-08-05T14:12:00-04:00 (Wednesday)",
meeting: {title: "Q3 roadmap sync", duration_minutes: 45, format: "video"},
reply_tone: "friendly",
prescan_facts: {participants: [], 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'
THREAD = """From: Priya Raman <priya@northbeam.example>
To: Alex Chen <alex@northbeam.example>, Daniel Okafor <daniel@northbeam.example>
Subject: Q3 roadmap sync
Hi both — we should get the Q3 roadmap sync booked before the offsite.
I'm in Bangalore; next week I'm free after 2pm my time every day except Wednesday.
Priya
From: Daniel Okafor <daniel@northbeam.example>
Works for me. I'm London-based — Tuesday and Thursday are wide open, and
please nothing before 9am my time (school run).
Daniel
"""
payload = {
"thread": THREAD,
"own_availability": ("I am Alex, in New York. Free most of next week except Thursday. "
"Prefer mornings but can do up to 12:30pm."),
"own_timezone": "America/New_York",
"current_datetime": "2026-08-05T14:12:00-04:00 (Wednesday)",
"meeting": {"title": "Q3 roadmap sync", "duration_minutes": 45, "format": "video"},
"reply_tone": "friendly",
"prescan_facts": {"participants": [], "flags": []},
}
est = api("POST", "/estimate", payload)
print("worst case:", est.get("hold_credits", est.get("credits")), "credits")
const thread = [
"From: Priya Raman <priya@northbeam.example>",
"To: Alex Chen <alex@northbeam.example>, Daniel Okafor <daniel@northbeam.example>",
"Subject: Q3 roadmap sync",
"",
"Hi both — we should get the Q3 roadmap sync booked before the offsite.",
"I'm in Bangalore; next week I'm free after 2pm my time every day except Wednesday.",
"",
"Priya",
"",
"From: Daniel Okafor <daniel@northbeam.example>",
"",
"Works for me. I'm London-based — Tuesday and Thursday are wide open, and",
"please nothing before 9am my time (school run).",
"",
"Daniel",
].join("\n");
const payload = {
thread,
own_availability:
"I am Alex, in New York. Free most of next week except Thursday. Prefer mornings but can do up to 12:30pm.",
own_timezone: "America/New_York",
current_datetime: "2026-08-05T14:12:00-04:00 (Wednesday)",
meeting: { title: "Q3 roadmap sync", duration_minutes: 45, format: "video" },
reply_tone: "friendly",
prescan_facts: { participants: [], flags: [] },
};
const est = await api("POST", "/estimate", payload);
console.log("worst case:", est.hold_credits ?? est.credits, "credits");
const thread = "From: Priya Raman <priya@northbeam.example>\n" +
"To: Alex Chen <alex@northbeam.example>, Daniel Okafor <daniel@northbeam.example>\n" +
"Subject: Q3 roadmap sync\n" +
"\n" +
"Hi both — we should get the Q3 roadmap sync booked before the offsite.\n" +
"I'm in Bangalore; next week I'm free after 2pm my time every day except Wednesday.\n" +
"\n" +
"Priya\n" +
"\n" +
"From: Daniel Okafor <daniel@northbeam.example>\n" +
"\n" +
"Works for me. I'm London-based — Tuesday and Thursday are wide open, and\n" +
"please nothing before 9am my time (school run).\n" +
"\n" +
"Daniel\n"
payload := map[string]any{
"thread": thread,
"own_availability": "I am Alex, in New York. Free most of next week except Thursday. Prefer mornings but can do up to 12:30pm.",
"own_timezone": "America/New_York",
"current_datetime": "2026-08-05T14:12:00-04:00 (Wednesday)",
"meeting": map[string]any{
"title": "Q3 roadmap sync", "duration_minutes": 45, "format": "video",
},
"reply_tone": "friendly",
"prescan_facts": map[string]any{
"participants": []any{}, "flags": []any{},
},
}
var est struct{ HoldCredits int64 `json:"hold_credits"` }
err := call("POST", "/estimate", payload, &est)
String thread = """
From: Priya Raman <priya@northbeam.example>
To: Alex Chen <alex@northbeam.example>, Daniel Okafor <daniel@northbeam.example>
Subject: Q3 roadmap sync
Hi both — we should get the Q3 roadmap sync booked before the offsite.
I'm in Bangalore; next week I'm free after 2pm my time every day except Wednesday.
Priya
From: Daniel Okafor <daniel@northbeam.example>
Works for me. I'm London-based — Tuesday and Thursday are wide open, and
please nothing before 9am my time (school run).
Daniel
""";
String jsonPayload = """
{"thread": %s,
"own_availability": "I am Alex, in New York. Free most of next week except Thursday. Prefer mornings but can do up to 12:30pm.",
"own_timezone": "America/New_York",
"current_datetime": "2026-08-05T14:12:00-04:00 (Wednesday)",
"meeting": {"title": "Q3 roadmap sync", "duration_minutes": 45, "format": "video"},
"reply_tone": "friendly",
"prescan_facts": {"participants": [], "flags": []}}
""".formatted(toJsonString(thread));
String envelope = api("POST", "/estimate", jsonPayload);
// worst-case cost is at data.hold_credits
THREAD = <<~THREAD
From: Priya Raman <priya@northbeam.example>
To: Alex Chen <alex@northbeam.example>, Daniel Okafor <daniel@northbeam.example>
Subject: Q3 roadmap sync
Hi both — we should get the Q3 roadmap sync booked before the offsite.
I'm in Bangalore; next week I'm free after 2pm my time every day except Wednesday.
Priya
From: Daniel Okafor <daniel@northbeam.example>
Works for me. I'm London-based — Tuesday and Thursday are wide open, and
please nothing before 9am my time (school run).
Daniel
THREAD
payload = { thread: THREAD,
own_availability: "I am Alex, in New York. Free most of next week except Thursday. " \
"Prefer mornings but can do up to 12:30pm.",
own_timezone: "America/New_York",
current_datetime: "2026-08-05T14:12:00-04:00 (Wednesday)",
meeting: { title: "Q3 roadmap sync", duration_minutes: 45, format: "video" },
reply_tone: "friendly",
prescan_facts: { participants: [], flags: [] } }
est = api("POST", "/estimate", payload)
puts "worst case: #{est["hold_credits"] || est["credits"]} credits"
$thread = <<<'THREAD'
From: Priya Raman <priya@northbeam.example>
To: Alex Chen <alex@northbeam.example>, Daniel Okafor <daniel@northbeam.example>
Subject: Q3 roadmap sync
Hi both — we should get the Q3 roadmap sync booked before the offsite.
I'm in Bangalore; next week I'm free after 2pm my time every day except Wednesday.
Priya
From: Daniel Okafor <daniel@northbeam.example>
Works for me. I'm London-based — Tuesday and Thursday are wide open, and
please nothing before 9am my time (school run).
Daniel
THREAD;
$payload = [
"thread" => $thread,
"own_availability" => "I am Alex, in New York. Free most of next week except Thursday. "
. "Prefer mornings but can do up to 12:30pm.",
"own_timezone" => "America/New_York",
"current_datetime" => "2026-08-05T14:12:00-04:00 (Wednesday)",
"meeting" => ["title" => "Q3 roadmap sync", "duration_minutes" => 45, "format" => "video"],
"reply_tone" => "friendly",
"prescan_facts" => ["participants" => [], "flags" => []],
];
$est = api("POST", "/estimate", $payload);
echo "worst case: " . ($est["hold_credits"] ?? $est["credits"]) . " credits\n";
var thread = """
From: Priya Raman <priya@northbeam.example>
To: Alex Chen <alex@northbeam.example>, Daniel Okafor <daniel@northbeam.example>
Subject: Q3 roadmap sync
Hi both — we should get the Q3 roadmap sync booked before the offsite.
I'm in Bangalore; next week I'm free after 2pm my time every day except Wednesday.
Priya
From: Daniel Okafor <daniel@northbeam.example>
Works for me. I'm London-based — Tuesday and Thursday are wide open, and
please nothing before 9am my time (school run).
Daniel
""";
var payload = new {
thread,
own_availability = "I am Alex, in New York. Free most of next week except Thursday. "
+ "Prefer mornings but can do up to 12:30pm.",
own_timezone = "America/New_York",
current_datetime = "2026-08-05T14:12:00-04:00 (Wednesday)",
meeting = new { title = "Q3 roadmap sync", duration_minutes = 45, format = "video" },
reply_tone = "friendly",
prescan_facts = new {
participants = 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 plan answer for things you already
know about. Send {"participants": [{"id": "email:priya@northbeam.example", "label": "priya@northbeam.example"}],
"flags": [{"id": "relative-date:1", "label": "“next week”"}]} and every
flag id comes back in coverage_check — addressed by a section of the plan,
or set aside with the reason. Nothing you flag is silently dropped, which makes it the field
to assert on in an automated check.
Step 4 — Run the scheduler 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 the reply carries a per-participant local-time table for every
slot as well as the full reply email). Always send an Idempotency-Key header so a
network retry can't start a second, double-charged run. The reply is in output
— usually nested as output.output, and as a JSON string, so parse
defensively. The samples below print the posture, the participants with their zones, each
proposed slot with everyone's local clock and the reply email, then save the whole object to
plan.json and the reply on its own to reply.txt.
JOB_ID=$(curl -s -X POST "$API/run" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-H "Idempotency-Key: md-$(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 reply once, then read it
echo "$JOB" | jq -r '.data.output.output' > plan.json
# the reply email is what you actually send — pull it out on its own
jq -r '"Subject: " + .reply_email.subject + "\n\n" + .reply_email.body' plan.json > reply.txt
jq -r '
"\(.meeting_name) [\(.posture)]: \(.verdict)",
"",
"PARTICIPANTS",
(.participants[] | " \(.name) <\(.email)> \(.timezone) (\(.tz_basis)) - \(.availability_summary)"),
"",
"CONSTRAINTS",
(.constraints[] | " [\(.kind)] \(.participant): \(.constraint) <= \"\(.source_quote)\""),
"",
"SLOTS",
(.proposed_slots[] | " #\(.rank) \(.start_utc) (\(.duration_minutes)m) - \(.why)",
(.timezone_table[] | " \(.participant): \(.local) [\(.fit)]"),
(if .risks == "" then empty else " risk: \(.risks)" end)),
"",
"COVERAGE",
(.coverage_check[] | " \(.id): \(if .addressed then "ok" else "SET ASIDE" end) - \(.note)"),
"",
"NEXT",
(.next_steps[] | " - \(.)")' \
plan.json
# only auto-send when the plan says it is ready
jq -e '.posture == "ready-to-send"' plan.json > /dev/null \
|| { echo "needs a human before sending"; exit 1; }
import time
job_id = api("POST", "/run", payload,
**{"Idempotency-Key": "md-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"]
plan = json.loads(raw) if isinstance(raw, str) else raw
print(f'{plan["meeting_name"]} [{plan["posture"]}]: {plan["verdict"]}')
for p in plan["participants"]:
print(f' {p["name"]:<8} {p["timezone"]:<20} ({p["tz_basis"]}) {p["availability_summary"]}')
for c in plan["constraints"]:
print(f' [{c["kind"]:>10}] {c["participant"]}: {c["constraint"]}')
if c["source_quote"]:
print(f' quote: "{c["source_quote"]}"')
for s in plan["proposed_slots"]:
print(f' #{s["rank"]} {s["start_utc"]} ({s["duration_minutes"]}m) - {s["why"]}')
for row in s["timezone_table"]:
print(f' {row["participant"]:<8} {row["local"]:<20} [{row["fit"]}]')
if s["risks"]:
print(" risk:", s["risks"])
for q in plan["open_questions"]:
print(" open:", q)
for c in plan["coverage_check"]:
print(f' {c["id"]}: {"ok" if c["addressed"] else "SET ASIDE"} - {c["note"]}')
for n in plan["next_steps"]:
print(" next:", n)
with open("plan.json", "w", encoding="utf-8") as fh:
json.dump(plan, fh, indent=2)
with open("reply.txt", "w", encoding="utf-8") as fh:
fh.write(f'Subject: {plan["reply_email"]["subject"]}\n\n{plan["reply_email"]["body"]}\n')
if plan["posture"] != "ready-to-send":
raise SystemExit(f'posture is {plan["posture"]} — review before sending')
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 plan = typeof raw === "string" ? JSON.parse(raw) : raw;
console.log(`${plan.meeting_name} [${plan.posture}]: ${plan.verdict}`);
for (const p of plan.participants) {
console.log(` ${p.name} ${p.timezone} (${p.tz_basis}): ${p.availability_summary}`);
}
for (const c of plan.constraints) {
console.log(` [${c.kind}] ${c.participant}: ${c.constraint} <= "${c.source_quote}"`);
}
for (const s of plan.proposed_slots) {
console.log(` #${s.rank} ${s.start_utc} (${s.duration_minutes}m): ${s.why}`);
for (const row of s.timezone_table) {
console.log(` ${row.participant}: ${row.local} [${row.fit}]`);
}
if (s.risks) console.log(` risk: ${s.risks}`);
}
for (const c of plan.coverage_check) {
console.log(` ${c.id}: ${c.addressed ? "ok" : "SET ASIDE"} - ${c.note}`);
}
for (const n of plan.next_steps) console.log(` next: ${n}`);
writeFileSync("plan.json", JSON.stringify(plan, null, 2));
writeFileSync("reply.txt",
`Subject: ${plan.reply_email.subject}\n\n${plan.reply_email.body}\n`);
if (plan.posture !== "ready-to-send") 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 Plan struct {
MeetingName string `json:"meeting_name"`
Posture string `json:"posture"`
Verdict string `json:"verdict"`
ExecSummary string `json:"exec_summary"`
Assumptions []string `json:"assumptions"`
OpenQuestions []string `json:"open_questions"`
Participants []struct {
Name, Email, Timezone string
TzBasis string `json:"tz_basis"`
AvailabilitySummary string `json:"availability_summary"`
} `json:"participants"`
Constraints []struct {
Participant, Kind, Constraint string
SourceQuote string `json:"source_quote"`
} `json:"constraints"`
ProposedSlots []struct {
Rank int `json:"rank"`
StartUTC string `json:"start_utc"`
DurationMinutes int `json:"duration_minutes"`
TimezoneTable []struct {
Participant, Local, Fit string
} `json:"timezone_table"`
Why, Risks string
} `json:"proposed_slots"`
ReplyEmail struct {
Subject, Body string
} `json:"reply_email"`
CoverageCheck []struct {
ID, Note string
Addressed bool
} `json:"coverage_check"`
NextSteps []string `json:"next_steps"`
Summary string `json:"summary"`
}
var wrapper struct{ Output string `json:"output"` }
json.Unmarshal(job.Output, &wrapper)
var plan Plan
json.Unmarshal([]byte(wrapper.Output), &plan)
fmt.Printf("%s [%s]: %s\n", plan.MeetingName, plan.Posture, plan.Verdict)
for _, p := range plan.Participants {
fmt.Printf(" %s %s (%s): %s\n", p.Name, p.Timezone, p.TzBasis, p.AvailabilitySummary)
}
for _, c := range plan.Constraints {
fmt.Printf(" [%s] %s: %s <= %q\n", c.Kind, c.Participant, c.Constraint, c.SourceQuote)
}
for _, s := range plan.ProposedSlots {
fmt.Printf(" #%d %s (%dm): %s\n", s.Rank, s.StartUTC, s.DurationMinutes, s.Why)
for _, row := range s.TimezoneTable {
fmt.Printf(" %s: %s [%s]\n", row.Participant, row.Local, row.Fit)
}
}
os.WriteFile("plan.json", []byte(wrapper.Output), 0o644)
os.WriteFile("reply.txt",
[]byte("Subject: "+plan.ReplyEmail.Subject+"\n\n"+plan.ReplyEmail.Body+"\n"), 0o644)
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 reply is at data.output.output as a JSON string — parse it again, then read
// meeting_name, posture, verdict, exec_summary, assumptions[], open_questions[],
// participants[] (name/email/timezone/tz_basis/availability_summary),
// constraints[] (participant/kind/constraint/source_quote),
// proposed_slots[] (rank/start_utc/duration_minutes/timezone_table[]/why/risks) —
// timezone_table rows are {participant, local, fit} and are the core deliverable,
// reply_email {subject, body}, coverage_check[] (id/addressed/note),
// next_steps[] and summary.
// Finally keep both on disk:
// Files.writeString(Path.of("plan.json"), planJson);
// Files.writeString(Path.of("reply.txt"), "Subject: " + subject + "\n\n" + body);
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"]
plan = raw.is_a?(String) ? JSON.parse(raw) : raw
puts "#{plan["meeting_name"]} [#{plan["posture"]}]: #{plan["verdict"]}"
plan["participants"].each { |p| puts " #{p["name"]} #{p["timezone"]} (#{p["tz_basis"]}): #{p["availability_summary"]}" }
plan["constraints"].each do |c|
puts " [#{c["kind"]}] #{c["participant"]}: #{c["constraint"]}"
puts " quote: #{c["source_quote"].inspect}" unless c["source_quote"].empty?
end
plan["proposed_slots"].each do |s|
puts " ##{s["rank"]} #{s["start_utc"]} (#{s["duration_minutes"]}m): #{s["why"]}"
s["timezone_table"].each { |r| puts " #{r["participant"]}: #{r["local"]} [#{r["fit"]}]" }
puts " risk: #{s["risks"]}" unless s["risks"].empty?
end
plan["coverage_check"].each { |c| puts " #{c["id"]}: #{c["addressed"] ? "ok" : "SET ASIDE"}" }
plan["next_steps"].each { |n| puts " next: #{n}" }
File.write("plan.json", JSON.pretty_generate(plan))
File.write("reply.txt",
"Subject: #{plan["reply_email"]["subject"]}\n\n#{plan["reply_email"]["body"]}\n")
exit 1 unless plan["posture"] == "ready-to-send"
$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"];
$plan = is_string($raw) ? json_decode($raw, true) : $raw;
echo "{$plan['meeting_name']} [{$plan['posture']}]: {$plan['verdict']}\n";
foreach ($plan["participants"] as $p) {
echo " {$p['name']} {$p['timezone']} ({$p['tz_basis']}): {$p['availability_summary']}\n";
}
foreach ($plan["constraints"] as $c) {
echo " [{$c['kind']}] {$c['participant']}: {$c['constraint']}\n";
if ($c["source_quote"] !== "") {
echo " quote: \"{$c['source_quote']}\"\n";
}
}
foreach ($plan["proposed_slots"] as $s) {
echo " #{$s['rank']} {$s['start_utc']} ({$s['duration_minutes']}m): {$s['why']}\n";
foreach ($s["timezone_table"] as $r) {
echo " {$r['participant']}: {$r['local']} [{$r['fit']}]\n";
}
if ($s["risks"] !== "") {
echo " risk: {$s['risks']}\n";
}
}
foreach ($plan["coverage_check"] as $c) {
echo " {$c['id']}: " . ($c["addressed"] ? "ok" : "SET ASIDE") . "\n";
}
foreach ($plan["next_steps"] as $n) {
echo " next: $n\n";
}
file_put_contents("plan.json", json_encode($plan, JSON_PRETTY_PRINT));
file_put_contents("reply.txt",
"Subject: {$plan['reply_email']['subject']}\n\n{$plan['reply_email']['body']}\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 plan = doc.RootElement;
Console.WriteLine($"{plan.GetProperty("meeting_name")} " +
$"[{plan.GetProperty("posture")}]: {plan.GetProperty("verdict")}");
foreach (var p in plan.GetProperty("participants").EnumerateArray())
{
Console.WriteLine($" {p.GetProperty("name")} {p.GetProperty("timezone")} " +
$"({p.GetProperty("tz_basis")}): {p.GetProperty("availability_summary")}");
}
foreach (var c in plan.GetProperty("constraints").EnumerateArray())
{
Console.WriteLine($" [{c.GetProperty("kind")}] {c.GetProperty("participant")}: " +
$"{c.GetProperty("constraint")}");
}
foreach (var s in plan.GetProperty("proposed_slots").EnumerateArray())
{
Console.WriteLine($" #{s.GetProperty("rank")} {s.GetProperty("start_utc")} " +
$"({s.GetProperty("duration_minutes")}m): {s.GetProperty("why")}");
foreach (var r in s.GetProperty("timezone_table").EnumerateArray())
Console.WriteLine($" {r.GetProperty("participant")}: " +
$"{r.GetProperty("local")} [{r.GetProperty("fit")}]");
}
var email = plan.GetProperty("reply_email");
await File.WriteAllTextAsync("plan.json", rawText!);
await File.WriteAllTextAsync("reply.txt",
$"Subject: {email.GetProperty("subject").GetString()}\n\n{email.GetProperty("body").GetString()}\n");
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 reply object — output schema
One JSON object, always the same shape. Every array is present, and every claim in it is
grounded in what you sent: participants, stated preferences and acceptances come from
thread, own_availability and own_timezone alone, never
from invention. Where an inference fills a gap — a time zone read from a city mention,
working hours assumed from silence (09:00–17:30 local), a relative date anchored to
current_datetime — it is recorded in assumptions, and in
open_questions when the answer would change the ranking. Slots always start at
:00, :15, :30 or :45, always lie in the future relative to current_datetime, and
proposed_slots is never empty — even under
cannot-schedule, where the least-bad options appear with the violated
constraint named in risks.
| Field | Type | Meaning |
|---|---|---|
meeting_name | string | A short title for this meeting, taken from the thread's own naming — e.g. Q3 roadmap sync — you, Priya, Daniel. |
posture | string | ready-to-send | needs-confirmation | cannot-schedule. See the table below. |
verdict | string | One sentence justifying the posture and naming either the best slot or the missing fact. |
exec_summary | string | Two or three short paragraphs, separated by blank lines: who needs to meet, what the constraints boil down to, and why the top slot wins. |
assumptions | string[] | Explicit inferences that fill gaps the thread left open — an anchored relative date, a zone read from a city, default working hours. Read these first: a wrong assumption invalidates every slot built on it. |
open_questions | string[] | Questions whose answers would change the proposed slots or their order. |
participants | array | {name, email, timezone, tz_basis, availability_summary} — the sender (as You, or their real name if the thread reveals it) plus every person the thread expects in the meeting, and never more than the thread supports. Columns are listed below. |
constraints | array | {participant, kind, constraint, source_quote} — every stated limit or preference, attributed to a named participant and backed by a quote. Columns are listed below. |
proposed_slots | array | The core deliverable — 1 to 3 entries ranked best-first, each with {rank, start_utc, duration_minutes, timezone_table, why, risks} and a timezone_table row for every participant. Columns are listed below. |
reply_email | object | {subject, body} — the reply you can send as-is. body is plain text with blank-line paragraphs, proposes at most the same slots as proposed_slots in the same order, each expressed in the recipients' own local times, and matches the reply_tone you sent. Under needs-confirmation it asks for exactly the missing fact; under cannot-schedule it makes the honest ask (drop a participant, split the meeting, go async) rather than a fake booking. Signatures, phone numbers and legal footers from the thread are never echoed back. |
coverage_check | array | {id, addressed, note} — one entry per prescan_facts.flags id you sent, each appearing exactly once. See the semantics below. |
next_steps | string[] | The sender's concrete next actions — e.g. "Send the reply, then the .ics for slot 1 once Priya confirms". |
summary | string | Closing paragraph: the recommendation in one breath. |
The three posture values:
| posture | What it means |
|---|---|
ready-to-send | The reply could go out as-is: every participant is placed in a zone, every hard constraint is satisfied by the top slot, and nothing material is missing. This is the case to gate an auto-send on. |
needs-confirmation | Exactly one or two facts are missing — an unknown time zone, an unanchored "next week", nobody stating any availability — and reply_email asks for precisely those. The slots are still real proposals under the stated assumptions. |
cannot-schedule | The stated constraints admit no compliant slot. proposed_slots still carries the least-bad options with the violated constraint named in risks, and the reply makes an honest ask instead of pretending the meeting fits. |
Each entry in participants:
| Column | Meaning |
|---|---|
name | As the thread names them; You for the sender when the thread does not reveal their name. |
email | The address if the thread shows one, otherwise the empty string. |
timezone | An IANA zone — America/New_York, Asia/Kolkata, Europe/London. Abbreviations like "ET" or "CET" are resolved to the zone that matches the meeting's date, not to a fixed offset. |
tz_basis | stated | inferred-from-city | inferred-from-abbreviation | default — how firmly that zone is established. Anything other than stated is worth a glance before you send. |
availability_summary | One line on when this person can meet, per the thread. |
Each entry in constraints:
| Column | Meaning |
|---|---|
participant | The named participant this constrains — matches a participants[].name. |
kind | hard (cannot) or preference (would rather not). Only hard entries must be satisfied by every proposed slot. |
constraint | The constraint in plain words, with concrete local times rather than the thread's vagueness. |
source_quote | The shortest verbatim fragment of the paste that establishes it, trimmed with … where useful. The empty string for a default the model supplied rather than read — and constraint then says so. |
Each entry in proposed_slots:
| Column | Meaning |
|---|---|
rank | 1 is the recommendation; the rest are ordered backups. The reply email proposes them in this order. |
start_utc | A valid UTC instant, ISO 8601 — e.g. 2026-08-11T13:30:00Z. Always in the future relative to current_datetime, always on a :00/:15/:30/:45 boundary. This is the field to turn into a calendar event. |
duration_minutes | Exactly the meeting.duration_minutes you asked for. |
timezone_table | One row per participant, {participant, local, fit}: local is the wall-clock rendering in that person's zone (Tue 11 Aug, 09:30), correct to the minute with DST applied on that date, and fit is good | edge | bad — who pays the pain for this slot. Every participant appears, including the sender. |
why | One sentence on why this slot, tied to the constraints above. |
risks | What could make it fail, or the empty string. Under cannot-schedule this names the constraint the slot violates. |
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 an automated check. Ids in prescan_facts.participants are not reconciled here — they shape the participants list instead. |
addressed: true | The flag is resolved by a section of the plan; note names which one — an assumption that anchored the date, a participant row that supplied the missing zone, a question the reply email asks. |
addressed: false | The flag was deliberately set aside; note gives the reason — a check that fired but is not a real problem for this thread (a "next week" that a later message already pinned to a date, a large group where only three people actually need to attend). |
| Nothing sent | Omit prescan_facts, or send the two empty arrays, and coverage_check comes back empty. The rest of the reply is unaffected. |
A small, realistic result for the thread above (long strings wrapped for readability):
{
"meeting_name": "Q3 roadmap sync — you, Priya, Daniel",
"posture": "ready-to-send",
"verdict": "Tuesday 11 August at 12:30 UTC — 08:30 New York, 13:30 London, 18:00 Bangalore —
is the only slot inside all three stated windows; the reply proposes it with one
backup.",
"exec_summary": "Three people across three zones, each with one stated window: Priya is free
after 14:00 Asia/Kolkata on any day next week except Wednesday, Daniel is
wide open Tuesday and Thursday from 09:00 Europe/London, and you prefer
mornings up to 12:30 America/New_York and are out on Thursday.
That leaves Tuesday as the only day all three can meet, and the overlap runs
12:30-16:30 UTC. The top slot takes the earliest end of it, which keeps
Priya's evening as short as possible while staying inside your morning.",
"assumptions": [
"\"next week\" resolves to the week of Monday 10 August 2026, the week after the current date.",
"\"Bangalore\" is read as Asia/Kolkata (UTC+05:30 on this date, no DST).",
"No end time was stated for Daniel, so 17:30 Europe/London is assumed."
],
"open_questions": [
"Is Priya's \"after 2pm\" a hard start or would 13:30 her time also work?"
],
"participants": [
{ "name": "You", "email": "alex@northbeam.example", "timezone": "America/New_York",
"tz_basis": "stated",
"availability_summary": "Free next week except Thursday; prefers mornings, latest 12:30." },
{ "name": "Priya", "email": "priya@northbeam.example", "timezone": "Asia/Kolkata",
"tz_basis": "inferred-from-city",
"availability_summary": "After 14:00 local, any day next week except Wednesday." },
{ "name": "Daniel", "email": "daniel@northbeam.example", "timezone": "Europe/London",
"tz_basis": "stated",
"availability_summary": "Tuesday and Thursday, from 09:00 local." }
],
"constraints": [
{ "participant": "Priya", "kind": "hard",
"constraint": "Not before 14:00 Asia/Kolkata, and not on Wednesday.",
"source_quote": "free after 2pm my time every day except Wednesday" },
{ "participant": "Daniel", "kind": "hard",
"constraint": "Nothing before 09:00 Europe/London; Tuesday or Thursday only.",
"source_quote": "please nothing before 9am my time (school run)" },
{ "participant": "You", "kind": "hard",
"constraint": "Not Thursday.",
"source_quote": "Free most of next week except Thursday" },
{ "participant": "You", "kind": "preference",
"constraint": "Mornings, ending by 12:30 America/New_York.",
"source_quote": "Prefer mornings but can do up to 12:30pm" }
],
"proposed_slots": [
{ "rank": 1, "start_utc": "2026-08-11T12:30:00Z", "duration_minutes": 45,
"timezone_table": [
{ "participant": "You", "local": "Tue 11 Aug, 08:30", "fit": "good" },
{ "participant": "Priya", "local": "Tue 11 Aug, 18:00", "fit": "edge" },
{ "participant": "Daniel", "local": "Tue 11 Aug, 13:30", "fit": "good" }
],
"why": "The earliest point inside all three windows, which keeps Priya's evening
shortest.",
"risks": "18:00 is late in Priya's day even though it satisfies her stated window." },
{ "rank": 2, "start_utc": "2026-08-11T13:30:00Z", "duration_minutes": 45,
"timezone_table": [
{ "participant": "You", "local": "Tue 11 Aug, 09:30", "fit": "good" },
{ "participant": "Priya", "local": "Tue 11 Aug, 19:00", "fit": "bad" },
{ "participant": "Daniel", "local": "Tue 11 Aug, 14:30", "fit": "good" }
],
"why": "An hour later if 08:30 is too early for you; still inside every stated window.",
"risks": "Runs to 19:45 for Priya." }
],
"reply_email": {
"subject": "Re: Q3 roadmap sync — Tuesday 11 August?",
"body": "Hi both,\n\nTuesday looks like the only day that works for all three of us —
Priya, Wednesday is out for you and Thursday is out for me.\n\nHow about
Tuesday 11 August, 45 minutes: 13:30 London / 18:00 Bangalore / 08:30 New
York? If that evening is tight, Priya, the hour later (19:00 your time) also
works.\n\nI'll send the invite once you both confirm.\n\nBest,\nAlex"
},
"coverage_check": [
{ "id": "relative-date:1", "addressed": true,
"note": "\"next week\" anchored to the week of 10 August 2026 in assumptions." }
],
"next_steps": [
"Send the reply, then the .ics for slot 1 once Priya and Daniel confirm.",
"If Priya pushes back on 18:00, ask whether a 13:30 Kolkata start is possible."
],
"summary": "Propose Tuesday 11 August 13:30 London / 18:00 Bangalore / 08:30 New York,
with the hour-later backup — both clear every stated constraint. …"
}
This is an AI-generated scheduling plan from pasted text, not a booked meeting: it sees only
the thread you sent, never anyone's calendar, and it cannot know about the commitment nobody
mentioned. Check assumptions, tz_basis and every
timezone_table row before you send — a wrong zone quietly moves the whole
slot — and let a human read the reply.
Step 5 — Stream the plan 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 local-time tables and the full reply email 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). The app advances its step list by watching for the "participants", "constraints", "proposed_slots", "reply_email", "coverage_check", "next_steps" and "summary" keys as they arrive. |
done | {job_id, status, charged_credits, output} | The final, authoritative result — read the plan 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: md-$(date +%s)" \
-d @input.json
# event: job
# data: {"job_id":"job_...","status":"running"}
#
# event: delta
# data: {"text":"{\"meeting_name\":\"Q3 roadmap sync"}
# ...
# event: done
# data: {"job_id":"job_...","status":"succeeded","charged_credits":486,"output":{"output":"{...}"}}
import json, requests
result = None
with requests.post(
API + "/run-stream",
headers={"Authorization": f"Bearer {TOKEN}",
"Idempotency-Key": "md-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"))
plan = json.loads(result["output"]["output"]) # authoritative
print("charged:", result["charged_credits"], "-", plan["meeting_name"])
print("posture:", plan["posture"])
for s in plan["proposed_slots"]:
print(f' #{s["rank"]} {s["start_utc"]}')
for row in s["timezone_table"]:
print(f' {row["participant"]}: {row["local"]} [{row["fit"]}]')
with open("plan.json", "w", encoding="utf-8") as fh:
json.dump(plan, fh, indent=2)
with open("reply.txt", "w", encoding="utf-8") as fh:
fh.write(f'Subject: {plan["reply_email"]["subject"]}\n\n{plan["reply_email"]["body"]}\n')
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 plan = JSON.parse(done.output.output);
console.log(`\n${done.charged_credits} credits - ${plan.meeting_name} [${plan.posture}]`);
for (const s of plan.proposed_slots) {
console.log(` #${s.rank} ${s.start_utc}`);
for (const row of s.timezone_table) {
console.log(` ${row.participant}: ${row.local} [${row.fit}]`);
}
}
writeFileSync("plan.json", JSON.stringify(plan, null, 2));
writeFileSync("reply.txt",
`Subject: ${plan.reply_email.subject}\n\n${plan.reply_email.body}\n`);
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", "md-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 reply JSON —
// unmarshal it into the Plan struct from step 4, then write it to plan.json
// and plan.ReplyEmail to reply.txt.
// 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", "md-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
// meeting_name, posture, verdict, participants[], constraints[],
// proposed_slots[] (with the timezone_table rows), reply_email {subject, body},
// coverage_check[], next_steps[] 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"] = "md-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
plan = JSON.parse(done["output"]["output"])
puts "\n#{done["charged_credits"]} credits - #{plan["meeting_name"]} [#{plan["posture"]}]"
plan["proposed_slots"].each do |s|
puts " ##{s["rank"]} #{s["start_utc"]}"
s["timezone_table"].each { |r| puts " #{r["participant"]}: #{r["local"]} [#{r["fit"]}]" }
end
File.write("plan.json", JSON.pretty_generate(plan))
File.write("reply.txt",
"Subject: #{plan["reply_email"]["subject"]}\n\n#{plan["reply_email"]["body"]}\n")
$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: md-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);
$plan = json_decode($done["output"]["output"], true);
echo "\n{$done['charged_credits']} credits - {$plan['meeting_name']} [{$plan['posture']}]\n";
foreach ($plan["proposed_slots"] as $s) {
echo " #{$s['rank']} {$s['start_utc']}\n";
foreach ($s["timezone_table"] as $r) {
echo " {$r['participant']}: {$r['local']} [{$r['fit']}]\n";
}
}
file_put_contents("plan.json", json_encode($plan, JSON_PRETTY_PRINT));
file_put_contents("reply.txt",
"Subject: {$plan['reply_email']['subject']}\n\n{$plan['reply_email']['body']}\n");
var req = new HttpRequestMessage(HttpMethod.Post, Api + "/run-stream") {
Content = JsonContent.Create(payload),
};
req.Headers.Add("Idempotency-Key", "md-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 planDoc = JsonDocument.Parse(text!);
var plan = planDoc.RootElement;
Console.WriteLine($"{plan.GetProperty("meeting_name")} [{plan.GetProperty("posture")}]");
foreach (var s in plan.GetProperty("proposed_slots").EnumerateArray())
{
Console.WriteLine($" #{s.GetProperty("rank")} {s.GetProperty("start_utc")}");
foreach (var r in s.GetProperty("timezone_table").EnumerateArray())
Console.WriteLine($" {r.GetProperty("participant")}: " +
$"{r.GetProperty("local")} [{r.GetProperty("fit")}]");
}
var email = plan.GetProperty("reply_email");
await File.WriteAllTextAsync("plan.json", text!);
await File.WriteAllTextAsync("reply.txt",
$"Subject: {email.GetProperty("subject").GetString()}\n\n{email.GetProperty("body").GetString()}\n");
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.