Guard Direct API quickstart
This page takes a custom harness from nothing to one accepted batch. It covers the whole contract a producer needs: check status, record the member's consent, sign and send a batch, and handle every answer. The complete list of values, limits and errors is in the wire reference.
Guard is not switched on yet, so a live call to a Guard route currently answers 404 {"code":"guard_not_available","error":"Guard is not available."}. Build and test against that answer now: it is exactly what a harness must handle, by sending nothing and not retrying in a loop. The examples below show real answers from a server with Guard on.
#Before you start
- A Radient Team organization with Guard on, and a member of it. Guard is a Team feature; a non-Team account is never asked and a harness must make no Guard calls for it.
- The member's Radient user token, sent as
Authorization: Bearer <token>. API keys are refused. See Authentication. - The organization's
tenant_id, the same id used in Team plan commands. Every Guard request names it. A harness learns it for the signed-in member fromGET /v1/me/memberships(user token): each entry ofresult.membershipshas atenant_id, atenant_nameand the member'srole. Pick the Team organization the member chose to work in. - Ed25519 signing. Node 22.18 or later has it built in (these examples were run on Node 24). Python needs
pip install cryptography.
All requests go to https://api.radienthq.com. Every successful answer is wrapped as {"msg": "…", "result": {…}}; every Guard refusal is {"code": "…", "error": "…"} with a fixed, safe sentence. Guard answers are never cached (Cache-Control: no-store).
Names used on this page. The curl examples and both clients read the same three values:
| Name | What it is |
|---|---|
RADIENT_ACCESS_TOKEN | The member's user token. |
RADIENT_TENANT | The organization's tenant_id. The curl examples write acme-team in its place. |
INSTALL_ID | The random id your harness makes once per computer. The two clients below make theirs on the first run and keep it in guard-state.json (installId in the TypeScript client, install_id in the Python client), so after a first run you can use it in curl with export INSTALL_ID=$(jq -r '.installId // .install_id' guard-state.json). For a status check before any client has run, any new id will do: export INSTALL_ID=$(openssl rand -hex 16). |
#The flow
| Step | Call | Signed with the computer's key? |
|---|---|---|
| 1. Ask whether to prompt | GET /v1/guard/status | No |
| 2. Prompt the member, then record consent | POST /v1/guard/consents | Yes, and only after a person agreed |
| 3. Read what you may send | GET /v1/guard/binding | No |
| 4. Send a batch | POST /v1/guard/ingest | Yes |
| 5. Stop sharing, whenever asked | POST /v1/guard/consents/revoke | No |
#Two rules that are not optional
- Consent happens only inside your harness's own consent prompt. The grant call and the key enrolment that rides on it must run only from the handler of a prompt that a person answered. A model, a tool result, a chat message or an auto-approve mode must never be able to answer it. The server cannot see your prompt, so this rule is enforced by your code and checked by the conformance checklist.
- No consent means no network. Until a member has agreed, make no Guard request at all beyond the status check. A non-Team account makes none.
#1. Check status
Send the status check at the moments you would naturally ask: when a member signs in, and periodically while an organization is on. Always send install_id: a stable random id your harness makes once per computer (letters, digits, _, -, up to 128 characters).
curl "https://api.radienthq.com/v1/guard/status?tenant=acme-team&install_id=$INSTALL_ID" \
-H "Authorization: Bearer $RADIENT_ACCESS_TOKEN"
{
"msg": "Radient Guard status",
"result": {
"status": "consent_required",
"prompt": {
"tenant": "acme-team",
"org_display_name": "Acme Robotics",
"collection_rev": 1,
"revocation_gen": 0,
"scopes": ["decisions", "posture", "reports", "review_cycles", "task_time"],
"added_scopes": [],
"rendered_terms_digest": "sha256:edc09351c9cc258209f88c54547cc9031ae332cba346a0e2b621fbaec1fc95b5",
"reason": "new_org"
}
}
}
| Status | Meaning | What to do |
|---|---|---|
consent_required | The organization is on and this computer has no consent that covers it. prompt says what to ask. | Queue the prompt for the member. Do not block their work. |
sharing | This computer holds a live consent that covers the current ceiling. | Keep sending. |
org_off | The organization has not turned Guard on, or turned it off, or needs to turn it back on. | Send nothing. |
entitlement_lapsed | The organization is not on an active Team plan or trial. | Send nothing. |
membership_ended | The member is no longer in the organization. | Send nothing. |
prompt.reason tells the member why they are being asked: new_org, widened, reactivated, plan_gap, new_device or rejoined. The wording to show is on Privacy and consent. A widened prompt lists only the new scopes in added_scopes; until the member answers, they keep sharing what they already agreed to.
A tenant the caller does not belong to answers 403 {"code":"not_a_member", …}.
#2. Prompt the member, then record consent
Show your own prompt with the organization's name, one line per scope in prompt.scopes, and the "never sent" line, using the wording on Privacy and consent. The choices are all or nothing: the member agrees to exactly the scopes offered, or declines. Remember a decline or a revoke on this computer and do not ask again until the member asks to share.
On a yes, and only then, your harness:
- Generates this computer's Ed25519 key if it does not have one, and stores the private key where a model cannot read it: the operating system's credential store, never an environment variable, a log or a tool result.
- Sends one signed
POST /v1/guard/consents. The first grant from a computer carriesenroll.public_key, which registers the key in the same request. There is no separate enrolment call.
The signed payload is {tenant, install_id, collection_rev, revocation_gen, scopes, terms_digest, nonce, ts, enroll?}. Copy collection_rev, revocation_gen and scopes from the prompt, and terms_digest from prompt.rendered_terms_digest, which binds the grant to exactly the terms the member saw: a grant made against terms the organization has since changed is refused. nonce is 16 to 128 characters from A-Za-z0-9_- and must be new every time; ts is the current Unix time in seconds, accepted within 15 minutes either side.
A new consent answers 201; a repeat of one already in force answers 200:
{
"msg": "Radient Guard consent recorded",
"result": {
"consent_id": "e790d44707253c76b5cf74bc93c0bc82",
"device_id": "22481727531ab1a3d9aa2aa8be71413e",
"tenant": "acme-team",
"collection_rev": 1,
"scopes": ["decisions", "posture", "reports", "review_cycles", "task_time"],
"kind": "started",
"enrolled": true
}
}
The member is told straight away: Radient emails them, naming the organization, computer and scopes (up to 10 receipt emails per account per day), and every consent appears in their Guard timeline in the console, with a way to stop it. A grant request is refused if it carries a Cookie or Origin header (403 guard_browser_refused), so it can only come from a harness and never from a web page.
A computer whose key was removed from the account stays removed (403 guard_device_revoked): make a new key and a new install_id. An account can add 3 computers per 24 hours and hold 10 live ones (429 guard_enroll_quota).
#3. Sign and send a batch
Every signed request is an envelope around a payload:
{"payload": { "…": "…" }, "alg": "Ed25519", "key_id": "<first 32 hex of sha256(raw public key)>", "signature": "<base64url, unpadded>"}
The signature is Ed25519 over a domain prefix followed by the payload's canonical JSON: keys sorted, no whitespace, printable ASCII strings, integers only. The prefix for a batch is the ASCII text radient-guard-batch-v1 followed by one zero byte. Each message type has its own prefix, so a signature made for one can never be replayed as another. The server rebuilds the canonical form itself and accepts any key order or whitespace on the wire; what must match is the bytes you signed.
Before the first batch, you can check your signing with the known-answer test on the conformance checklist.
The two programs below are complete. Each one checks that consent exists before it touches the network, can record consent for a development organization (the grant command, which stands in for your prompt's accept handler), reads the binding, and sends two guardrail decisions.
#TypeScript
Save as guard-client.mts and run with Node 22.18 or later. It has no dependencies.
// Minimal Radient Guard producer: check status, enrol and grant (host consent only), send one batch.
// Node 22.18+ runs this file as-is (`node guard-client.mts`); no dependencies.
import {
createHash, createPrivateKey, generateKeyPairSync, randomBytes, randomUUID, sign,
} from "node:crypto";
import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
const API = process.env.RADIENT_API ?? "https://api.radienthq.com";
const TOKEN = process.env.RADIENT_ACCESS_TOKEN!; // the member's own login access token
const TENANT = process.env.RADIENT_TENANT!; // the organization (tenant) id
const STATE = process.env.GUARD_STATE ?? "guard-state.json"; // key + consent; keep it 0600
const DOMAIN_CONSENT = Buffer.from("radient-guard-consent-v1\0");
const DOMAIN_BATCH = Buffer.from("radient-guard-batch-v1\0");
type Decision = {
schema: string; day: string; outcome: string; rule_class: string; tool_class: string; record_id: string;
};
type State = {
installId: string; privateKeyPem: string; publicKey: string; enrolled: boolean;
// Records waiting for a 200, kept on disk so a retry re-sends the same ids. The queue stays bounded: a batch takes at most 1024 decisions, and conformance P12 drops records 72 hours after their day ends.
queue: Decision[];
};
// Sorted keys, no whitespace, integers and printable ASCII only: the bytes the server re-derives.
// Anything else (floats, booleans, null, other characters) is refused here, not as a 400 later.
function canonical(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
if (value !== null && typeof value === "object") {
const o = value as Record<string, unknown>;
return `{${Object.keys(o).sort().map((k) => `${canonical(k)}:${canonical(o[k])}`).join(",")}}`;
}
if (typeof value === "string" && /^[\x20-\x7e]*$/.test(value)) return JSON.stringify(value);
if (typeof value === "number" && Number.isInteger(value)) return String(value);
throw new Error("only integers, printable-ASCII strings, arrays and objects can be signed");
}
// DEMO ONLY: this file holds the private key so the example runs on its own. A real harness keeps
// the key in the operating system's credential store, where the model cannot read it (check N10).
function loadState(): State {
if (existsSync(STATE)) return JSON.parse(readFileSync(STATE, "utf8"));
const { privateKey, publicKey } = generateKeyPairSync("ed25519");
return {
installId: randomUUID().replaceAll("-", ""),
privateKeyPem: privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
publicKey: publicKey.export({ format: "jwk" }).x!, // the raw 32-byte key, base64url, unpadded
enrolled: false,
queue: [],
};
}
// Temp file then rename, so a crash mid-write never leaves a truncated state file and a lost queue.
const saveState = (s: State) => {
writeFileSync(`${STATE}.tmp`, JSON.stringify(s), { mode: 0o600 });
renameSync(`${STATE}.tmp`, STATE);
};
function envelope(domain: Buffer, payload: object, s: State) {
const raw = Buffer.from(s.publicKey, "base64url");
const message = Buffer.concat([domain, Buffer.from(canonical(payload))]);
const signature = sign(null, message, createPrivateKey(s.privateKeyPem));
return {
payload,
alg: "Ed25519",
key_id: createHash("sha256").update(raw).digest("hex").slice(0, 32),
signature: signature.toString("base64url"),
};
}
async function call(method: string, path: string, body?: object): Promise<{ status: number; body: any }> {
// No Cookie, no Origin: the server refuses a signed route that carries either.
const res = await fetch(API + path, {
method,
headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
});
return { status: res.status, body: await res.json().catch(() => ({})) };
}
const status = (s: State) => call("GET", `/v1/guard/status?tenant=${TENANT}&install_id=${s.installId}`);
/** Call ONLY from the handler of your own consent prompt, after the member said yes. */
async function grant(s: State, prompt: any) {
const payload: Record<string, unknown> = {
tenant: TENANT, install_id: s.installId,
collection_rev: prompt.collection_rev, revocation_gen: prompt.revocation_gen,
scopes: prompt.scopes, terms_digest: prompt.rendered_terms_digest,
nonce: randomBytes(16).toString("hex"), ts: Math.floor(Date.now() / 1000),
};
// The first grant from a computer carries its public key.
if (!s.enrolled) payload.enroll = { public_key: s.publicKey, device_name: "my-harness" };
const out = await call("POST", "/v1/guard/consents", envelope(DOMAIN_CONSENT, payload, s));
// 201: consent recorded. 200: an identical consent was already in force.
if (out.status === 200 || out.status === 201) saveState({ ...s, enrolled: true });
return out;
}
const stableId = (...parts: string[]) =>
createHash("sha256").update(parts.join("\x1f")).digest("hex").slice(0, 32);
// A record_id names ONE OCCURRENCE, not its attributes. Mint it when the event happens and keep it
// with the queued record, so a retry re-sends the same id (a `duplicate`) while two decisions that
// look alike still get two ids and both count. Never derive it from outcome, rule_class and tool_class.
function recordDecision(s: State, outcome: string, rule_class: string, tool_class: string) {
s.queue.push({
schema: "guard_decision_v1", day: new Date().toISOString().slice(0, 10),
outcome, rule_class, tool_class, record_id: randomUUID().replaceAll("-", ""),
});
saveState(s);
}
async function sendBatch(s: State, records: Record<string, any[]>) {
const b = await call("GET", `/v1/guard/binding?tenant=${TENANT}&install_id=${s.installId}`);
if (b.status !== 200) return b;
// batch_id = hash of the tenant and the sorted record ids, so re-sending the same queued records
// is recognised as one batch (`replayed`).
const ids = Object.values(records).flat().map((r) => r.record_id).filter(Boolean).sort();
const payload = {
schema: "guard_batch_v1", tenant: TENANT, install_id: s.installId,
batch_id: stableId(TENANT, ...ids), nonce: randomBytes(16).toString("hex"),
ts: Math.floor(Date.now() / 1000),
collection_rev: b.body.result.collection_rev, revocation_gen: b.body.result.revocation_gen,
...records,
};
return call("POST", "/v1/guard/ingest", envelope(DOMAIN_BATCH, payload, s));
}
const state = loadState();
const cmd = process.argv[2] ?? "send";
if (cmd === "status") {
console.log(await status(state));
} else if (cmd === "grant") {
// Dev-org trial of the contract. A real harness runs this from its consent prompt.
const st = await status(state);
console.log(st.body?.result?.prompt ? await grant(state, st.body.result.prompt) : st);
} else if (cmd === "send") {
if (!state.enrolled) { console.error("no consent on this computer: nothing sent"); process.exit(1); }
if (state.queue.length === 0) {
// Demo only: a real harness calls recordDecision() once per guardrail decision, as it happens.
// Two identical blocks are two occurrences and must both count.
recordDecision(state, "block", "dangerous_delete", "shell");
recordDecision(state, "block", "dangerous_delete", "shell");
recordDecision(state, "allow", "custom", "file_write");
}
const out = await sendBatch(state, { decisions: state.queue });
// Only a 200 means the records were stored. Anything else keeps the queue for a retry.
// GUARD_DEMO_LOST_ANSWER stands in for a network drop after the server answered.
if (out.status === 200 && !process.env.GUARD_DEMO_LOST_ANSWER) { state.queue = []; saveState(state); }
console.log(out);
}
export RADIENT_ACCESS_TOKEN=… # the member's user token
export RADIENT_TENANT=acme-team
node guard-client.mts send # no consent yet: prints "no consent on this computer: nothing sent"
node guard-client.mts grant # stands in for your prompt's accept handler
node guard-client.mts send # three decisions, two of them identical blocks: accepted 3
GUARD_DEMO_LOST_ANSWER=1 node guard-client.mts send # three more; pretend the answer was lost
node guard-client.mts send # the retry: the same three ids, answered "replayed": true
#Python
Save as guard_client.py, then pip install cryptography and run with Python 3.10 or later.
"""Minimal Radient Guard producer: check status, enrol and grant (host consent only), send one batch.
Needs `pip install cryptography` (Ed25519) and Python 3.10+; everything else is the standard library.
"""
import base64, hashlib, json, os, secrets, sys, time, urllib.error, urllib.request, uuid
from datetime import datetime, timezone
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
API = os.environ.get("RADIENT_API", "https://api.radienthq.com")
TOKEN = os.environ["RADIENT_ACCESS_TOKEN"] # the member's own login access token
TENANT = os.environ["RADIENT_TENANT"] # the organization (tenant) id
STATE = os.environ.get("GUARD_STATE", "guard-state.json") # key + consent; keep it 0600
DOMAIN_CONSENT = b"radient-guard-consent-v1\x00"
DOMAIN_BATCH = b"radient-guard-batch-v1\x00"
def b64u(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
def check_signable(v) -> None:
# Integers and printable ASCII only. Floats, booleans and None are refused here, not as a 400 later.
if isinstance(v, dict):
for k, x in v.items():
check_signable(k)
check_signable(x)
elif isinstance(v, list):
for x in v:
check_signable(x)
elif isinstance(v, str):
if not all(" " <= c <= "~" for c in v):
raise ValueError("printable ASCII only")
elif isinstance(v, bool) or not isinstance(v, int):
raise ValueError("only integers, printable-ASCII strings, lists and objects can be signed")
def canonical(obj) -> bytes:
# Sorted keys, no whitespace: the bytes the server re-derives.
check_signable(obj)
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()
# DEMO ONLY: this file holds the private key so the example runs on its own. A real harness keeps
# the key in the operating system's credential store, where the model cannot read it (check N10).
def load_state() -> dict:
if os.path.exists(STATE):
return json.load(open(STATE))
key = Ed25519PrivateKey.generate()
raw = key.private_bytes(
serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption())
# "queue" holds records waiting for a 200, kept on disk so a retry re-sends the same ids.
# The queue stays bounded: a batch takes at most 1024 decisions, and conformance P12 drops records 72 hours after their day ends.
return {"install_id": uuid.uuid4().hex, "private_key": raw.hex(), "enrolled": False, "queue": []}
def save_state(state: dict) -> None:
# Temp file then rename, so a crash mid-write never leaves a truncated state file and a lost queue.
fd = os.open(STATE + ".tmp", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
json.dump(state, f)
os.replace(STATE + ".tmp", STATE)
def signing_key(state: dict) -> Ed25519PrivateKey:
return Ed25519PrivateKey.from_private_bytes(bytes.fromhex(state["private_key"]))
def public_raw(key: Ed25519PrivateKey) -> bytes:
return key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
def envelope(domain: bytes, payload: dict, key: Ed25519PrivateKey) -> dict:
return {
"payload": payload,
"alg": "Ed25519",
"key_id": hashlib.sha256(public_raw(key)).hexdigest()[:32],
"signature": b64u(key.sign(domain + canonical(payload))),
}
def call(method: str, path: str, body: dict | None = None):
# No Cookie, no Origin: the server refuses a signed route that carries either.
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(API + path, data=data, method=method, headers={
"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=20) as resp:
return resp.status, json.load(resp)
except urllib.error.HTTPError as err:
return err.code, json.loads(err.read() or b"{}")
def status(state: dict):
return call("GET", f"/v1/guard/status?tenant={TENANT}&install_id={state['install_id']}")
def grant(state: dict, prompt: dict):
"""Call ONLY from the handler of your own consent prompt, after the member said yes."""
key = signing_key(state)
payload = {
"tenant": TENANT, "install_id": state["install_id"],
"collection_rev": prompt["collection_rev"], "revocation_gen": prompt["revocation_gen"],
"scopes": prompt["scopes"], "terms_digest": prompt["rendered_terms_digest"],
"nonce": secrets.token_hex(16), "ts": int(time.time()),
}
if not state["enrolled"]: # the first grant from this install carries its public key
payload["enroll"] = {"public_key": b64u(public_raw(key)), "device_name": "my-harness"}
code, body = call("POST", "/v1/guard/consents", envelope(DOMAIN_CONSENT, payload, key))
if code in (200, 201): # 201: consent recorded; 200: an identical re-grant already in force
state["enrolled"] = True
save_state(state)
return code, body
def stable_id(*parts: str) -> str:
return hashlib.sha256("\x1f".join(parts).encode()).hexdigest()[:32]
def record_decision(state: dict, outcome: str, rule_class: str, tool_class: str) -> None:
# A record_id names ONE OCCURRENCE, not its attributes. Mint it when the event happens and keep
# it with the queued record, so a retry re-sends the same id (a `duplicate`) while two decisions
# that look alike still get two ids and both count. Never derive it from the three values below.
state["queue"].append({
"schema": "guard_decision_v1", "day": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
"outcome": outcome, "rule_class": rule_class, "tool_class": tool_class,
"record_id": uuid.uuid4().hex,
})
save_state(state)
def send_batch(state: dict, records: dict):
code, body = call("GET", f"/v1/guard/binding?tenant={TENANT}&install_id={state['install_id']}")
if code != 200:
return code, body
binding = body["result"]
# batch_id = hash of the tenant and the sorted record ids, so re-sending the same queued records
# is recognised as one batch (`replayed`).
ids = sorted(r["record_id"] for family in records.values() for r in family if "record_id" in r)
payload = {
"schema": "guard_batch_v1", "tenant": TENANT, "install_id": state["install_id"],
"batch_id": stable_id(TENANT, *ids), "nonce": secrets.token_hex(16), "ts": int(time.time()),
"collection_rev": binding["collection_rev"], "revocation_gen": binding["revocation_gen"],
**records,
}
return call("POST", "/v1/guard/ingest", envelope(DOMAIN_BATCH, payload, signing_key(state)))
if __name__ == "__main__":
state = load_state()
cmd = sys.argv[1] if len(sys.argv) > 1 else "send"
if cmd == "status":
print(*status(state))
elif cmd == "grant":
# Dev-org trial of the contract. A real harness runs this from its consent prompt.
code, body = status(state)
prompt = body.get("result", {}).get("prompt") if code == 200 else None
print(*(grant(state, prompt) if prompt else (code, body)))
elif cmd == "send":
if not state.get("enrolled"): # no consent recorded: nothing leaves this machine
sys.exit("no consent on this computer: nothing sent")
if not state["queue"]:
# Demo only: a real harness calls record_decision() once per guardrail decision, as it
# happens. Two identical blocks are two occurrences and must both count.
record_decision(state, "block", "dangerous_delete", "shell")
record_decision(state, "block", "dangerous_delete", "shell")
record_decision(state, "allow", "custom", "file_write")
code, body = send_batch(state, {"decisions": state["queue"]})
# Only a 200 means the records were stored. Anything else keeps the queue for a retry.
# GUARD_DEMO_LOST_ANSWER stands in for a network drop after the server answered.
if code == 200 and not os.environ.get("GUARD_DEMO_LOST_ANSWER"):
state["queue"] = []
save_state(state)
print(code, body)
export RADIENT_ACCESS_TOKEN=… # the member's user token
export RADIENT_TENANT=acme-team
python guard_client.py send # no consent yet: exits with "no consent on this computer: nothing sent"
python guard_client.py grant # stands in for your prompt's accept handler
python guard_client.py send # three decisions, two of them identical blocks: accepted 3
GUARD_DEMO_LOST_ANSWER=1 python guard_client.py send # three more; pretend the answer was lost
python guard_client.py send # the retry: the same three ids, answered "replayed": true
The first send answers with a body like this. TypeScript prints it as { status: 200, body: … } and Python as 200 {…}, and the ids, and so batch_id, are new on every run:
{
"msg": "Radient Guard batch processed",
"result": {
"batch_id": "12e8deaca7c41e93a68243c310e5d312",
"replayed": false,
"accepted": 3,
"refused_fields": [],
"decisions": { "status": "accepted", "accepted": 3, "duplicate": 0, "rejected": [] }
}
}
Both identical blocks counted: accepted is 3, not 2. Run the last two commands from the list above and the retry answers "replayed": true with the same batch_id, because the queued records, and so their ids, did not change. Nothing is stored twice.
#How the ids work
A record_id identifies one occurrence: one decision, at one moment, on one computer. Mint it when the event happens (a random 128-bit id is enough) and store it with the queued record, so every retry of that record carries the same id. Two decisions with the same outcome, rule class and tool class on the same day are two events and need two ids: if you derived the id from those attributes, the second would be stored as a duplicate and never counted, and 50 blocks would be reported as 1.
A batch_id identifies one set of records: the clients hash the tenant and the sorted record ids. A retry of the same queue produces the same batch_id, so the server answers replayed and stores nothing twice.
What the server does when ids repeat:
- The same record sent again counts as a
duplicate. - A record sent again with different content, inside a batch whose
batch_idis new, is refused withguard_record_conflict. If that record travels alone and the first batch held only that record, the client derives the samebatch_idas the first batch, and the server answers409 guard_replay, because thatbatch_idwas already used for a different set of events. If the first batch held other records too, the lone record gets a newbatch_id, and the server answers200with the record underrejectedasguard_record_conflict. - Never put event content, paths or names inside an id. An id is random, or a hash, and nothing else.
#Read the answer
A batch answers 200 when it was admitted, even if some records were not accepted. Read the body:
acceptedcounts new records across all families. On a retried batch (replayed: true) the server repeats the counts from the first answer.refused_fieldslists families refused as a whole, with{"status": "refused", "code": "guard_scope_not_consented"}inside that family. This is what a member who has not yet answered a widening sees: they keep sending what they agreed to, and the new scope is refused until they agree.- Inside a family,
rejectedlists records the server will never accept:guard_day_closed(too old or not started yet),guard_record_conflict, orguard_posture_not_designated. Delete them locally with the rest of the batch; sending them again changes nothing.
Anything other than 200 means nothing was stored. Retries and backoff says what to do with each.
#Other calls you will want
binding tells you exactly what this computer may send now, without sending anything:
curl "https://api.radienthq.com/v1/guard/binding?tenant=acme-team&install_id=$INSTALL_ID" \
-H "Authorization: Bearer $RADIENT_ACCESS_TOKEN"
{
"msg": "Radient Guard binding",
"result": {
"tenant": "acme-team",
"install_id": "38ad252d14f043268aca40975fa060f9",
"collection_rev": 1,
"revocation_gen": 0,
"scopes": ["decisions", "posture", "reports", "review_cycles", "task_time"]
}
}
Stop sharing needs only the member's token, with no signature, so it works from anywhere the harness can reach the API. It always wins over a send that is racing it:
curl -X POST https://api.radienthq.com/v1/guard/consents/revoke \
-H "Authorization: Bearer $RADIENT_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"tenant": "acme-team"}'
{"msg": "Radient Guard sharing stopped", "result": {"tenant_id": "acme-team", "revocation_gen": 1, "revoked_consents": 2}}
A member can also stop sharing from the console, and any batch you then send is refused with 409 guard_revocation_stale. Treat that as a sticky stop: discard what you had queued and do not ask again until the member chooses to share.
GET /v1/guard/me?tenant_id=… returns the member's own state, computers and timeline, for a settings screen. A harness's passive indicator and revoke control can use it and status.
#Failures worth testing
These are real answers from a server with Guard on. A harness should handle each without sending anything it should not.
# a grant from a browser context (carries an Origin header)
curl -si -X POST https://api.radienthq.com/v1/guard/consents \
-H "Authorization: Bearer $RADIENT_ACCESS_TOKEN" -H "Origin: https://console.radienthq.com" \
-H "Content-Type: application/json" -d '{}'
# HTTP/1.1 403 Forbidden
# {"code":"guard_browser_refused","error":"Radient Guard sharing can only be started from Local Operator."}
# an unsigned batch
curl -si -X POST https://api.radienthq.com/v1/guard/ingest \
-H "Authorization: Bearer $RADIENT_ACCESS_TOKEN" -H "Content-Type: application/json" -d '{"payload":{}}'
# HTTP/1.1 403 Forbidden
# {"code":"guard_device_signature_required","error":"This request must be signed by the Local Operator install."}
# a computer the account never registered
curl -si "https://api.radienthq.com/v1/guard/binding?tenant=acme-team&install_id=nope" \
-H "Authorization: Bearer $RADIENT_ACCESS_TOKEN"
# HTTP/1.1 403 Forbidden
# {"code":"guard_device_unknown","error":"This Local Operator install is not registered for Radient Guard."}
# no token, Guard on: refused by authentication, so the body has no Guard code
curl -si "https://api.radienthq.com/v1/guard/status?tenant=acme-team"
# HTTP/1.1 401 Unauthorized
# {"error":"missing Authorization header"}
# a member of another organization
curl -si "https://api.radienthq.com/v1/guard/status?tenant=other-org" \
-H "Authorization: Bearer $RADIENT_ACCESS_TOKEN"
# HTTP/1.1 403 Forbidden
# {"code":"not_a_member","error":"You are not a member of this organization."}
# Guard not switched on for this deployment (the answer today, with or without a token)
curl -si "https://api.radienthq.com/v1/guard/status?tenant=acme-team"
# HTTP/1.1 404 Not Found
# {"code":"guard_not_available","error":"Guard is not available."}
Some of the fixed sentences still say "Local Operator", because Local Operator was the first harness. Match on the code, never the sentence, and do not show these sentences to members.
#Retries and backoff
Match on code, not on the sentence. Re-sign every attempt with a new nonce and a current ts; never resend an old envelope.
| Answer | What happened | What to do |
|---|---|---|
Network error, 5xx | Not delivered, or unknown | Retry the same records with exponential backoff and jitter. Stop when the records pass their window (72 hours for day records). |
429 guard_rate_limited | Too many writes | Wait for Retry-After, then continue. |
400 guard_request_expired | ts more than 15 minutes from the server's clock | Re-sign with the current time. If it repeats, the computer's clock is wrong. |
413 guard_batch_too_large | Over a size cap | Split the batch. |
400 guard_invalid_request | A key or value is outside the grammar | A bug in the producer. Drop the batch and log it. |
409 guard_binding_stale | A newer consent replaced the one this batch was prepared under | Discard what you prepared, read binding, and collect again under the new consent. |
409 guard_revocation_stale, 403 guard_consent_not_live | The member stopped sharing, or the consent ended | Sticky stop: discard the queue. |
403 guard_org_not_on, guard_not_entitled | The organization turned Guard off, or its plan lapsed | Pause. Resume only by asking the member again. |
403 guard_scope_not_consented | Every family was refused | Drop those families. |
409 guard_replay | A batch_id was reused for different events | A bug in the producer. |
404 guard_not_available | No Guard on this deployment | Stop. Do not loop. |
The full table, including membership and device refusals, is in the wire reference.