# Worked examples: jobs, streams and conversations

Drive a background job through approval, parse a streamed run and hold a multi-turn conversation, with complete scripts you can copy.

[Run an agent from your own system](https://centerofagentic.com/docs/guides/run-an-agent) explains the three ways to run and how to read an outcome. This page is the code for them. Every script runs an activated agent, so it requests a launch ticket first and sends the headers listed under [The request](https://centerofagentic.com/docs/guides/run-an-agent#request).

## Before you start

- **Tools.** The shell scripts need `bash`, `curl`, `jq` and `uuidgen`. The Python scripts need Python 3.9 or later. The TypeScript example runs with `node stream-run.ts` on Node.js 22.18 or later, or with `npx tsx stream-run.ts` on Node.js 18 or later. Neither the Python scripts nor the TypeScript example imports a package.

- **A key** in `COA_API_KEY`. The job and stream examples need the `run` scope. The conversation example needs `admin`.

- **An agent.** Replace the example `AGENT_ID` with an agent of yours whose `activeGrant.state` is `available`. The job example needs an agent with at least one connection. For a hold like the one under [When the job is held](https://centerofagentic.com/docs/guides/run-examples#held-for-approval), the agent must call a write tool that its authority level grants, and its active version must give that connection write access. A write that fails either condition is refused, not held, and its `toolLog` entry has `outcome` set to `denied`. The [Quickstart](https://centerofagentic.com/docs/quickstart#before-you-start) lists what the workspace needs before any run, such as a model key.

```bash
export COA_API_KEY="ak_..."
```

## A background job

`run-job.sh` starts a job, continues it one step per call until it ends, prints the answer and fetches the stored receipt. It writes the `jobId` to stderr; `./run-job.sh <jobId>` continues that job after an interruption.

```bash
#!/usr/bin/env bash
set -euo pipefail
BASE="https://centerofagentic.com"
AUTH="Authorization: Bearer $COA_API_KEY"
PROTO="X-CoA-Agent-Protocol: agent-active-grants/1"
JSON="Content-Type: application/json"
AGENT_ID="3f1c2a9e-0b7d-4e55-9a51-6f2f1c0e8d11"
JOB_ID="${1:-}" # pass a job id to continue that job instead of starting one

if [ -z "$JOB_ID" ]; then
  REQUEST=$(jq -cn --arg a "$AGENT_ID" --arg p "Draft the renewal reminder for account 1042." \
    '{agentId: $a, prompt: $p}')

  # 1. Launch ticket. The ticket request is saved: sending it again later returns the job id.
  jq -cn --arg a "$AGENT_ID" --arg n "$(uuidgen)" --argjson r "$REQUEST" \
    '{agentId: $a, purpose: "run_job", nonce: $n, request: $r}' > job-launch.json
  TICKET_RESPONSE=$(curl -sS "$BASE/api/agent-runtime/ticket" \
    -H "$AUTH" -H "$PROTO" -H "$JSON" -d @job-launch.json)
  TICKET=$(jq -r '.ticketId // empty' <<<"$TICKET_RESPONSE")
  [ -n "$TICKET" ] || { echo "Ticket refused: $TICKET_RESPONSE" >&2; exit 1; }

  # 2. Start the job. This request already runs the first step.
  STEP=$(curl -sS --max-time 90 "$BASE/api/run/job" \
    -H "$AUTH" -H "$PROTO" -H "$JSON" -H "X-CoA-Agent-Ticket: $TICKET" \
    -H "X-CoA-Model-Request: $(date +%s)000.$(uuidgen)" -d "$REQUEST") || STEP=""
  jq -e 'type == "object"' <<<"$STEP" >/dev/null 2>&1 || {
    echo "No JSON start response, so a job may exist. Recover its id from job-launch.json before you start again." >&2
    printf '%.300s\n' "$STEP" >&2; exit 1; }
  JOB_ID=$(jq -r '.jobId // empty' <<<"$STEP")
  [ -n "$JOB_ID" ] || { echo "No job started: $STEP" >&2; exit 1; }
  echo "jobId: $JOB_ID" >&2
else
  STEP='{"status":"running"}'
fi

# 3. Continue, one step per call, until the job ends.
PREVIOUS="" IDLE=0
while :; do
  case "$(jq -r '.status // "none"' <<<"$STEP" 2>/dev/null || true)" in
    running)
      # The same answer twice: no step ran, because another request is advancing the job.
      if [ "$STEP" = "$PREVIOUS" ]; then IDLE=$((IDLE + 1)); sleep 5; else IDLE=0; fi
      [ "$IDLE" -lt 24 ] || { echo "Job $JOB_ID has not advanced for two minutes" >&2; exit 1; } ;;
    pending_approval)
      # Held. Show what waits for a reviewer, then ask again later.
      curl -sS "$BASE/api/approvals" -H "$AUTH" \
        | jq -c --arg j "$JOB_ID" '.approvals[]? | select(.jobId == $j) | {action, expiresAt}' >&2 || true
      sleep 30 ;;
    "done") break ;;
    none|"") # An error response or no response: this says nothing about the job itself.
      echo "No job state in the answer. Continue later with: ./run-job.sh $JOB_ID" >&2
      printf '%.300s\n' "$STEP" >&2; exit 1 ;;
    *) echo "Job stopped: $(jq -c '{status, error, reasonCode, detail}' <<<"$STEP")" >&2; exit 1 ;;
  esac
  PREVIOUS=$STEP
  STEP=$(curl -sS --max-time 90 "$BASE/api/run/job" -H "$AUTH" -H "$PROTO" -H "$JSON" \
    -d "$(jq -cn --arg j "$JOB_ID" '{jobId: $j}')") || STEP=""
done

# 4. The answer, then the stored receipt.
jq -r .output <<<"$STEP"
RECEIPT_ID=$(jq -r '.receipt.id // empty' <<<"$STEP")
if [ -n "$RECEIPT_ID" ]; then
  curl -sS "$BASE/api/receipts/$RECEIPT_ID" -H "$AUTH" \
    | jq '{id, assuranceTier, evidenceClass, rawUploaded, costUsd}'
else
  echo "Another request finished the job, so this answer has no receipt. List receipts to find it." >&2
fi
```

The start request uses up the ticket and already runs the first step. A run refused before it starts creates no job: the response has `decision` set to `deny`, a `receipt` and no `jobId`. Only the response that finishes the job carries `receipt`. While another request is advancing the job, a call answers `running` without running a step: the script then waits, and stops if the answer stays the same for two minutes.

If the script stops that way, read the stored status with `GET /api/run/job?jobId=<job id>`. `claimed` means a step is in progress, and a step takes at most 60 seconds. A job of an activated agent that stays `claimed` for longer has lost that step: it does not advance again, and `POST /api/run/job/cancel` covers only jobs with Deep Agents delegation. Before you start a replacement, check the connected system, because the lost step may have made tool calls that `toolLog` does not show.

### When the job is held

A step that reaches a tool call needing approval returns `pending_approval` and names the held tools in `heldActions`; those calls have not run. Later calls with the `jobId` return the status without `heldActions`, so the script reads the held operation and its expiry from `GET /api/approvals`.

```json
{
  "jobId": "9c2b7e41-3d5a-4f80-b6e2-1a0d9c8b7f36",
  "status": "pending_approval",
  "output": null,
  "rounds": 2,
  "chunks": 1,
  "heldActions": ["c0__create_email"],
  "toolLog": [
    {
      "tool": "create_email",
      "connection": "Marketing Cloud EU",
      "ok": false,
      "detail": "Held until approval is given.",
      "decisionId": "a3e81b56-2c7d-4f09-9b14-6d5e0c8f7a23",
      "outcome": "pending",
      "reasonCode": "APPROVAL_REQUIRED",
      "placement": "cloud_connector_write"
    }
  ]
}
```

Who decides

A workspace admin signed in to the web workspace approves or denies each held operation in the Review Queue. API keys and device tokens can list holds but cannot decide them, and the admin who created the key that started the job cannot approve. Approval therefore takes a second workspace admin: in a workspace with one admin, such a hold can only be denied or expire. See [Pending approvals](https://centerofagentic.com/docs/api/receipts#approvals).

Keep calling with the `jobId`. The answer depends on the review.

| Review outcome | What the next call returns |
| --- | --- |
| An operation is still undecided | `pending_approval`. The call does not advance the job. |
| All decided, at least one approved | The job continues. Each approved call is decided again against the current policy and runs only if it is still allowed. The web workspace starts that step itself after the last decision, so your next call can find the job further along or already `done`. |
| All denied | `status` is `error` and `error` is `approval_denied`. |
| The hold expired, after 24 hours by default | `status` is `error` and `error` is `APPROVAL_EXPIRED`. The held calls did not run. |

When the step that the web workspace started finishes the job, your next call returns `done` with the `output` but without `receipt`. Find the receipt by listing `GET /api/receipts?agentId=<agent id>&user=api-key:<key id>` and matching your prompt, as described under [After a replayed response](https://centerofagentic.com/docs/guides/automation#after-a-replay). If the agent is paused or revoked while the job waits, the call answers `409 agent_admission_unavailable` instead of the job state, and the held calls do not run.

### Recover a lost job id

If the start response never arrives, do not start a second job. `run-job.sh` saved its ticket request as `job-launch.json`: sending the same file again returns the same ticket, and `rootId` is the job id once the ticket has started a job. `GET /api/run/job` reads the stored status without advancing the job.

```bash
# The same ticket request again. Once the ticket has started a job, rootId is the job id.
TICKET_RESPONSE=$(curl -sS https://centerofagentic.com/api/agent-runtime/ticket \
  -H "Authorization: Bearer $COA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "X-CoA-Agent-Protocol: agent-active-grants/1" \
  -d @job-launch.json)
JOB_ID=$(jq -r '.rootId // empty' <<<"$TICKET_RESPONSE" 2>/dev/null)

# The stored status. This call does not advance the job.
if [ -n "$JOB_ID" ]; then
  curl -sS "https://centerofagentic.com/api/run/job?jobId=$JOB_ID" \
    -H "Authorization: Bearer $COA_API_KEY"
elif jq -e '.ticketId' <<<"$TICKET_RESPONSE" >/dev/null 2>&1; then
  echo "The ticket has not started a job" >&2
else
  echo "The ticket could not be read, so do not start a new job yet: $TICKET_RESPONSE" >&2
fi
```

```json
{
  "managed": true,
  "deepAgents": false,
  "status": "pending_approval",
  "rootId": "9c2b7e41-3d5a-4f80-b6e2-1a0d9c8b7f36"
}
```

Continue with `./run-job.sh "$JOB_ID"`. `404 not_found` from the status call means the start request created no job. A ticket that was never used expires after ten minutes: the ticket request then answers `409 agent_admission_unavailable`, and no job exists. The start response also carries the job id in its `X-CoA-Agent-Root` header.

### The same job in Python

`run_job.py` does what `run-job.sh` does. Pass a job id as the first argument to continue one.

```python
#!/usr/bin/env python3
"""Start a background job, or continue one, until it ends. Python 3.9+, standard library only."""
import json
import os
import sys
import time
import urllib.error
import urllib.request
import uuid

BASE = "https://centerofagentic.com"
AGENT_ID = "3f1c2a9e-0b7d-4e55-9a51-6f2f1c0e8d11"
HEADERS = {
    "Authorization": "Bearer " + os.environ["COA_API_KEY"],
    "Content-Type": "application/json",
    "X-CoA-Agent-Protocol": "agent-active-grants/1",
}


def call(method, url_path, body=None, extra=None):
    data = None if body is None else json.dumps(body).encode()
    req = urllib.request.Request(
        BASE + url_path, data=data, method=method, headers={**HEADERS, **(extra or {})}
    )
    try:
        with urllib.request.urlopen(req, timeout=90) as res:
            return json.load(res)
    except urllib.error.HTTPError as err:
        sys.exit(f"{method} {url_path}: HTTP {err.code} {err.read().decode()}")


def start(prompt):
    request = {"agentId": AGENT_ID, "prompt": prompt}
    launch = {"agentId": AGENT_ID, "purpose": "run_job", "nonce": str(uuid.uuid4()), "request": request}
    with open("job-launch.json", "w") as f:  # sending this again later returns the job id
        json.dump(launch, f)
    ticket = call("POST", "/api/agent-runtime/ticket", launch)
    step = call("POST", "/api/run/job", request, {
        "X-CoA-Agent-Ticket": ticket["ticketId"],
        "X-CoA-Model-Request": f"{int(time.time() * 1000)}.{uuid.uuid4()}",
    })
    if "jobId" not in step:  # refused before a job existed, or the ticket was already used
        sys.exit("No job started: " + json.dumps(step))
    return step


if len(sys.argv) > 1:  # continue the job whose id was passed
    step = {"jobId": sys.argv[1], "status": "running"}
else:
    step = start("Draft the renewal reminder for account 1042.")
job_id = step["jobId"]
print("jobId:", job_id, file=sys.stderr)

previous, idle = None, 0
while step.get("status") in ("running", "pending_approval"):
    if step["status"] == "pending_approval":  # held: list what waits for a reviewer, ask again later
        held = [a for a in call("GET", "/api/approvals")["approvals"] if a["jobId"] == job_id]
        print("held:", [(a["action"], a["expiresAt"]) for a in held], file=sys.stderr)
        time.sleep(30)
    elif step == previous:  # the same answer twice: another request is advancing the job
        idle += 1
        if idle >= 24:
            sys.exit(f"Job {job_id} has not advanced for two minutes")
        time.sleep(5)
    else:
        idle = 0
    previous = step
    step = call("POST", "/api/run/job", {"jobId": job_id})

if step.get("status") != "done":
    keys = ("status", "error", "reasonCode", "detail")
    sys.exit("Job stopped: " + json.dumps({k: step.get(k) for k in keys}))

print(step["output"])
receipt_id = (step.get("receipt") or {}).get("id")  # only the finishing response carries it
if receipt_id:
    receipt = call("GET", "/api/receipts/" + receipt_id)
    keys = ("id", "assuranceTier", "evidenceClass", "rawUploaded", "costUsd")
    print(json.dumps({k: receipt.get(k) for k in keys}), file=sys.stderr)
else:
    print("Another request finished the job, so this answer has no receipt. List receipts to find it.", file=sys.stderr)
```

## A streamed run

`POST /api/run/stream` takes the body of `POST /api/run` and a ticket with the purpose `run_stream`, and answers with `text/event-stream`. Each event is an `event:` line, a `data:` line with one JSON object, and a blank line. The receipt is shortened to its `id` here.

```text
event: meta
data: {"decision":"allow","reasonCode":"ALLOWED","model":"example-lab/example-chat-1"}

event: delta
data: {"text":"1. Budget pressure"}

event: delta
data: {"text":" at renewal time."}

event: done
data: {"output":"1. Budget pressure at renewal time.","receipt":{"id":"e7b1c9a4-3d52-4f8e-a6c0-1f9d2b7e5a38"}}
```

| Event | Sent | Payload |
| --- | --- | --- |
| `meta` | First | `decision` (`allow` or `deny`), `reasonCode` and `model`. |
| `delta` | Zero or more times | `text`, the next fragment of the answer. An agent with connections sends its whole answer in one `delta`. |
| `done` | Last, on a completed or refused run | `output` and `receipt`. Adds `decision` set to `deny`, `reasonCode` and `detail` when a budget or model-call check refused the run, and `approvalRequired` and `detail` when tool calls needed approval. |
| `error` | Last, on a failure | `detail` and, where available, `error` and `evidence`. |

### Detect the end

- **Check before you parse.** A problem found before the run starts is a JSON error, and a ticket that was already used answers `200` with the JSON body `{ replayed: true, root: { id, status } }`. Parse events only when the content type is `text/event-stream`.

- **`done` or `error` is the last event.** The server then closes the connection.

- **A refusal is not an `error`.** A policy refusal shows in `meta`, a budget or model-call refusal in `done`: read `decision` in both. One budget refusal is the exception: `spend_reservation_refused` arrives as an `error` event whose payload has `invoked` set to `false`. Do not send that run again automatically; see [Budget and accounting refusals](https://centerofagentic.com/docs/api/errors#budget-refusals).

- **A stream that closes with neither has an unknown outcome.** The run may have finished and written a receipt, so do not resend it blindly. Look for the receipt first; see [After a replayed response](https://centerofagentic.com/docs/guides/automation#after-a-replay). A request sent without the `X-CoA-Model-Request` header can end this way.

### Parsers

The shell script reads the stream line by line, prints the answer as it arrives and saves the `done` payload as `done.json`.

```bash
#!/usr/bin/env bash
set -euo pipefail
BASE="https://centerofagentic.com"
AUTH="Authorization: Bearer $COA_API_KEY"
PROTO="X-CoA-Agent-Protocol: agent-active-grants/1"
JSON="Content-Type: application/json"
AGENT_ID="3f1c2a9e-0b7d-4e55-9a51-6f2f1c0e8d11"

REQUEST=$(jq -cn --arg a "$AGENT_ID" \
  --arg p "List three renewal risks for a mid-market software customer." \
  '{agentId: $a, prompt: $p}')
TICKET_RESPONSE=$(jq -cn --arg a "$AGENT_ID" --arg n "$(uuidgen)" --argjson r "$REQUEST" \
    '{agentId: $a, purpose: "run_stream", nonce: $n, request: $r}' \
  | curl -sS "$BASE/api/agent-runtime/ticket" -H "$AUTH" -H "$PROTO" -H "$JSON" -d @-)
TICKET=$(jq -r '.ticketId // empty' <<<"$TICKET_RESPONSE")
[ -n "$TICKET" ] || { echo "Ticket refused: $TICKET_RESPONSE" >&2; exit 1; }

rm -f done.json # an earlier run's payload must not survive a run that fails
EVENT="" LAST=""
while IFS= read -r LINE || [ -n "$LINE" ]; do
  case "$LINE" in
    "event: "*) EVENT=${LINE#event: } ;;
    "data: "*)
      DATA=${LINE#data: }
      case "$EVENT" in
        meta)   jq -r '"verdict: \(.decision) \(.reasonCode)"' <<<"$DATA" >&2 ;;
        delta)  jq -j .text <<<"$DATA" ;;
        "done") LAST="done"; printf '%s\n' "$DATA" > done.json ;;
        error)  LAST="error"; echo "Run failed: $DATA" >&2 ;;
      esac ;;
    "{"*) echo "Not a stream: $LINE" >&2; exit 1 ;; # a JSON error, or a ticket that was already used
  esac
done < <(curl -sS -N --max-time 90 "$BASE/api/run/stream" \
  -H "$AUTH" -H "$PROTO" -H "$JSON" -H "X-CoA-Agent-Ticket: $TICKET" \
  -H "X-CoA-Model-Request: $(date +%s)000.$(uuidgen)" -d "$REQUEST")

case "$LAST" in
  "done") jq -r '"\nreceipt: \(.receipt.id) \(.decision // "") \(.reasonCode // "")"' done.json >&2 ;;
  error)  exit 1 ;;
  *)      echo "Stream closed without done or error: the outcome is unknown" >&2; exit 1 ;;
esac
```

In Python, `events()` yields one name and payload per event.

```python
#!/usr/bin/env python3
"""Stream one run and print the answer as it arrives. Python 3.9+, standard library only."""
import http.client
import json
import os
import sys
import time
import urllib.error
import urllib.request
import uuid

BASE = "https://centerofagentic.com"
AGENT_ID = "3f1c2a9e-0b7d-4e55-9a51-6f2f1c0e8d11"
HEADERS = {
    "Authorization": "Bearer " + os.environ["COA_API_KEY"],
    "Content-Type": "application/json",
    "X-CoA-Agent-Protocol": "agent-active-grants/1",
}


def post(url_path, body, extra=None):
    req = urllib.request.Request(
        BASE + url_path, data=json.dumps(body).encode(), headers={**HEADERS, **(extra or {})}
    )
    try:
        return urllib.request.urlopen(req, timeout=90)
    except urllib.error.HTTPError as err:  # a problem found before the run starts is a JSON error
        sys.exit(f"{url_path}: HTTP {err.code} {err.read().decode()}")


def events(res):
    """Yield (name, payload) for each server-sent event in the response."""
    name = None
    for raw in res:
        line = raw.decode().rstrip("\r\n")
        if line.startswith("event: "):
            name = line[7:]
        elif line.startswith("data: ") and name:
            yield name, json.loads(line[6:])
            name = None


request = {"agentId": AGENT_ID, "prompt": "List three renewal risks for a mid-market software customer."}
launch = {"agentId": AGENT_ID, "purpose": "run_stream", "nonce": str(uuid.uuid4()), "request": request}
with post("/api/agent-runtime/ticket", launch) as res:
    ticket_id = json.load(res)["ticketId"]

meta, final = {}, None
with post("/api/run/stream", request, {
    "X-CoA-Agent-Ticket": ticket_id,
    "X-CoA-Model-Request": f"{int(time.time() * 1000)}.{uuid.uuid4()}",
}) as res:
    if not res.headers.get("Content-Type", "").startswith("text/event-stream"):
        sys.exit("Not a stream: " + res.read().decode())  # the ticket was already used
    try:
        for name, payload in events(res):
            if name == "meta":
                meta = payload
            elif name == "delta":
                print(payload["text"], end="", flush=True)
            elif name in ("done", "error"):
                final = (name, payload)
    except (http.client.HTTPException, OSError):
        pass  # a dropped connection leaves final unset

if final is None:
    sys.exit("Stream closed without done or error: the outcome is unknown")
name, payload = final
if name == "error":
    sys.exit(f"Run failed: {payload.get('error') or payload.get('detail')}")

# A refusal shows in meta (policy) or in done (budget or model call), so read both.
refused = "deny" in (meta.get("decision"), payload.get("decision"))
reason = payload.get("reasonCode") or meta.get("reasonCode")
verdict = "refused" if refused else "allowed"
print(f"\n{verdict} {reason}, receipt {payload['receipt']['id']}", file=sys.stderr)
```

In TypeScript, `readEvents()` splits the body on blank lines, and `streamRun()` resolves with the verdict, the output and the receipt id.

```ts
// No packages. Run with: node stream-run.ts (Node.js 22.18 or later) or npx tsx stream-run.ts
import { randomUUID } from "node:crypto";

const BASE = "https://centerofagentic.com";
const PROTOCOL = "agent-active-grants/1";

type Meta = { decision: "allow" | "deny"; reasonCode: string; model: string | null };
type Done = {
  output: string;
  receipt: { id: string };
  decision?: "deny";
  reasonCode?: string;
  detail?: string;
  approvalRequired?: string[];
};
type RunEvent =
  | { event: "meta"; data: Meta }
  | { event: "delta"; data: { text: string } }
  | { event: "done"; data: Done }
  | { event: "error"; data: { detail?: string; error?: string } };

/** Turn a text/event-stream body into events. */
async function* readEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<RunEvent> {
  const reader = body.getReader();
  const decoder = new TextDecoder();
  let buffer = "";
  for (;;) {
    // A dropped connection ends the events like a normal close: the caller then sees no final event.
    const { value, done } = await reader.read().catch(() => ({ value: undefined, done: true }));
    if (done) return;
    buffer += decoder.decode(value, { stream: true });
    // Events end with a blank line.
    for (let end = buffer.indexOf("\n\n"); end >= 0; end = buffer.indexOf("\n\n")) {
      const lines = buffer.slice(0, end).split("\n");
      buffer = buffer.slice(end + 2);
      const event = lines.find((line) => line.startsWith("event: "))?.slice(7);
      const data = lines.find((line) => line.startsWith("data: "))?.slice(6);
      if (event && data) yield { event, data: JSON.parse(data) } as RunEvent;
    }
  }
}

export async function streamRun(agentId: string, prompt: string, onText: (text: string) => void) {
  const headers = {
    Authorization: "Bearer " + process.env.COA_API_KEY,
    "Content-Type": "application/json",
    "X-CoA-Agent-Protocol": PROTOCOL,
  };
  const request = { agentId, prompt };

  const ticket = await fetch(BASE + "/api/agent-runtime/ticket", {
    method: "POST",
    headers,
    body: JSON.stringify({ agentId, purpose: "run_stream", nonce: randomUUID(), request }),
    signal: AbortSignal.timeout(30_000),
  });
  if (!ticket.ok) throw new Error("Ticket refused: " + ticket.status + " " + (await ticket.text()));
  const { ticketId } = (await ticket.json()) as { ticketId: string };

  const res = await fetch(BASE + "/api/run/stream", {
    method: "POST",
    headers: {
      ...headers,
      "X-CoA-Agent-Ticket": ticketId,
      "X-CoA-Model-Request": Date.now() + "." + randomUUID(),
    },
    body: JSON.stringify(request),
    signal: AbortSignal.timeout(90_000), // a stalled stream then ends like a dropped one
  });
  // A problem found before the run starts, and a ticket that was already used, answer with JSON.
  const isStream = (res.headers.get("content-type") ?? "").startsWith("text/event-stream");
  if (!res.ok || !isStream || !res.body) {
    throw new Error("No stream: " + res.status + " " + (await res.text()));
  }

  let meta: Meta | undefined;
  for await (const item of readEvents(res.body)) {
    if (item.event === "meta") meta = item.data;
    if (item.event === "delta") onText(item.data.text);
    if (item.event === "error") throw new Error("Run failed: " + (item.data.error ?? item.data.detail));
    if (item.event === "done") {
      // A refusal shows in meta (policy) or in done (budget or model call), so read both.
      const refused = meta?.decision === "deny" || item.data.decision === "deny";
      return {
        decision: refused ? ("deny" as const) : ("allow" as const),
        reasonCode: item.data.reasonCode ?? meta?.reasonCode,
        output: item.data.output,
        receiptId: item.data.receipt.id,
      };
    }
  }
  throw new Error("Stream closed without done or error: the outcome is unknown");
}

streamRun(
  "3f1c2a9e-0b7d-4e55-9a51-6f2f1c0e8d11",
  "List three renewal risks for a mid-market software customer.",
  (text) => process.stdout.write(text),
)
  .then((run) => console.error("\n" + run.decision, run.reasonCode, "receipt", run.receiptId))
  .catch((err) => {
    console.error(err);
    process.exitCode = 1;
  });
```

## A conversation

`conversation.sh` creates a conversation, sends two turns and reads the stored messages. Each turn needs its own ticket, with the purpose `conversation`, `parentScope` set to the conversation id and `request` set to the turn body, and its own `X-CoA-Model-Request` value. See [Multi-turn conversations](https://centerofagentic.com/docs/guides/run-an-agent#conversations).

This script needs an admin-scope key

With an API key, creating a conversation requires the `admin` scope; sending a turn requires `run`. A conversation belongs to the credential that created it, so the same key must send its turns. `admin` is the widest key scope and includes `run` and `read`: give such a key only to the service that owns the conversations.

```bash
#!/usr/bin/env bash
set -euo pipefail
BASE="https://centerofagentic.com"
AUTH="Authorization: Bearer $COA_API_KEY" # a key with the admin scope
PROTO="X-CoA-Agent-Protocol: agent-active-grants/1"
JSON="Content-Type: application/json"
AGENT_ID="3f1c2a9e-0b7d-4e55-9a51-6f2f1c0e8d11"

# 1. Create the conversation. This is the call that needs the admin scope.
CONVERSATION=$(jq -cn --arg a "$AGENT_ID" '{agentId: $a, title: "Renewal questions"}' \
  | curl -sS "$BASE/api/conversations" -H "$AUTH" -H "$JSON" -d @-)
CONVERSATION_ID=$(jq -r '.id // empty' <<<"$CONVERSATION")
[ -n "$CONVERSATION_ID" ] || { echo "Conversation not created: $CONVERSATION" >&2; exit 1; }

# 2. One turn: a ticket bound to the conversation and the turn body, then the streamed reply.
turn() {
  local request response ticket line event="" last=""
  request=$(jq -cn --arg p "$1" '{prompt: $p}')
  response=$(jq -cn --arg a "$AGENT_ID" --arg c "$CONVERSATION_ID" --arg n "$(uuidgen)" \
      --argjson r "$request" \
      '{agentId: $a, purpose: "conversation", parentScope: $c, nonce: $n, request: $r}' \
    | curl -sS "$BASE/api/agent-runtime/ticket" -H "$AUTH" -H "$PROTO" -H "$JSON" -d @-)
  ticket=$(jq -r '.ticketId // empty' <<<"$response")
  [ -n "$ticket" ] || { echo "Ticket refused: $response" >&2; return 1; }

  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      "event: "*) event=${line#event: } ;;
      "data: "*)
        case "$event" in
          delta)  jq -j .text <<<"${line#data: }" ;;
          "done") last="done"; echo # end the answer on stdout
                  jq -r '"[\(.message.reasonCode), receipt \(.receiptId // "none")]"' \
                    <<<"${line#data: }" >&2 ;;
          error)  echo "Turn failed: ${line#data: }" >&2; return 1 ;;
        esac ;;
      "{"*) echo "Not a stream: $line" >&2; return 1 ;;
    esac
  done < <(curl -sS -N --max-time 90 "$BASE/api/conversations/$CONVERSATION_ID/run/stream" \
    -H "$AUTH" -H "$PROTO" -H "$JSON" -H "X-CoA-Agent-Ticket: $ticket" \
    -H "X-CoA-Model-Request: $(date +%s)000.$(uuidgen)" -d "$request")
  [ "$last" = "done" ] || { echo "Turn ended without done or error: the outcome is unknown" >&2; return 1; }
}

turn "Which renewal risks matter most for a mid-market software customer?"
turn "Turn the first one into a two-sentence summary."

# 3. Read the stored messages, oldest first.
curl -sS "$BASE/api/conversations/$CONVERSATION_ID" -H "$AUTH" \
  | jq -r '.messages[] | "\(.role): \(.content)"'
```

A turn streams `meta` and `delta` like a run. Its `done` event carries the stored `message`, the run's `steps` and, for most outcomes, a `receiptId` in place of a receipt. A refused turn is stored too, as a short assistant message with the refusal's `reasonCode`. [Conversation turns](https://centerofagentic.com/docs/api/runs#conversation-turns) lists every field.

## Next steps

- [**Run an agent** The request, the three ways to run, outcomes and budgets.](https://centerofagentic.com/docs/guides/run-an-agent)

- [**Automation and CI** Least-privilege keys, safe retries and what to do after a replay.](https://centerofagentic.com/docs/guides/automation)

- [**Runs and conversations** The reference for every run, stream, job and conversation operation.](https://centerofagentic.com/docs/api/runs)

Source: https://centerofagentic.com/docs/guides/run-examples

## Related pages

- [Run an agent from your own system](https://centerofagentic.com/docs/guides/run-an-agent)
- [The request](https://centerofagentic.com/docs/guides/run-an-agent#request)
- [When the job is held](https://centerofagentic.com/docs/guides/run-examples#held-for-approval)
- [Quickstart](https://centerofagentic.com/docs/quickstart#before-you-start)
- [Pending approvals](https://centerofagentic.com/docs/api/receipts#approvals)
- [After a replayed response](https://centerofagentic.com/docs/guides/automation#after-a-replay)
- [Budget and accounting refusals](https://centerofagentic.com/docs/api/errors#budget-refusals)
- [Multi-turn conversations](https://centerofagentic.com/docs/guides/run-an-agent#conversations)
- [Conversation turns](https://centerofagentic.com/docs/api/runs#conversation-turns)
- [Run an agent The request, the three ways to run, outcomes and budgets.](https://centerofagentic.com/docs/guides/run-an-agent)
- [Automation and CI Least-privilege keys, safe retries and what to do after a replay.](https://centerofagentic.com/docs/guides/automation)
- [Runs and conversations The reference for every run, stream, job and conversation operation.](https://centerofagentic.com/docs/api/runs)
