Skip to content
Context docs
Build

Run a session and stream its events

The scripts p2-run-stream.sh, p2-run-stream.py and p2-run-stream.ts are in full under Complete script.

Before you start

Set CONTEXT_BASE_URL, CONTEXT_API_KEY and AGENT_ID as in the Quickstart.

Client setup used by every step
#!/usr/bin/env bash set -euo pipefail : "${CONTEXT_BASE_URL:?Set CONTEXT_BASE_URL, for example https://api.context.ai}" : "${CONTEXT_API_KEY:?Set CONTEXT_API_KEY to a personal Task API key}" : "${AGENT_ID:?Set AGENT_ID to an id from GET /v1/agents}" api() { local path=$1; shift curl -sS --fail-with-body "$CONTEXT_BASE_URL/v1$path" -H "x-api-key: $CONTEXT_API_KEY" "$@" } fail() { echo "error: $*" >&2; exit 1; } # Opens the session's event stream; exec makes the background job's pid the curl process itself. stream() { exec curl -sS --fail-with-body -N "$CONTEXT_BASE_URL/v1/sessions/$1/events/stream" \ -H "x-api-key: $CONTEXT_API_KEY" "${@:2}" } # The JSON of every event received so far on a stream saved to a file. Ping frames carry no id and are skipped. events_in() { sed -n 's/^data: //p' "$1" | jq -c 'select(.id)'; } # Waits until the stream file holds a session.status_idle that ends the turn (not requires_action). wait_for_end_of_turn() { for _ in $(seq 1 300); do grep -q '^event: error' "$1" && fail "the stream ended with an error: $(grep -A2 '^event: error' "$1" | sed -n 's/^data: //p')" events_in "$1" | jq -se 'any(.[]; .type == "session.status_idle" and .stop_reason.type != "requires_action")' >/dev/null && return 0 sleep 1 done fail "the turn did not end within 300 seconds" } WORK=$(mktemp -d)
  1. Create a session

    A new session is idle until you send it a message.

    SESSION=$(api /sessions -H "content-type: application/json" \ -d "$(jq -n --arg agent "$AGENT_ID" '{agent: $agent, environment_id: "env_default", title: "Streaming demo"}')") SESSION_ID=$(jq -r .id <<<"$SESSION") [[ $(jq -r .status <<<"$SESSION") == "idle" ]] || fail "expected an idle session: $SESSION" echo "step 1: session $SESSION_ID idle"

    Sample output:

    Code
    step 1: session dd13d728-93e3-440a-874c-4efeb58c97e0 idle
  2. Open the stream before sending

    Stream events says why the stream opens first.

    stream "$SESSION_ID" > "$WORK/stream.txt" & STREAM_PID=$! sleep 1 kill -0 "$STREAM_PID" 2>/dev/null || fail "the stream did not open: $(cat "$WORK/stream.txt")" echo "step 2: stream open"

    Sample output:

    Code
    step 2: stream open
  3. Send a message

    Sending returns one receipt for each event you send, with a sevt_receipt_ id. The stored event, with its own id, arrives on the stream. Don’t use a receipt id as Last-Event-ID. To resume, use the id of a stored event from the stream.

    SENT=$(api "/sessions/$SESSION_ID/events" -H "content-type: application/json" -d '{"events": [ {"type": "user.message", "content": [{"type": "text", "text": "Reply with one sentence about Tokyo."}]}]}') [[ $(jq -r '.data[0].id' <<<"$SENT") == sevt_receipt_* ]] || fail "unexpected receipt: $SENT" echo "step 3: sent, receipt $(jq -r '.data[0].id' <<<"$SENT")"

    Sample output:

    Code
    step 3: sent, receipt sevt_receipt_219b3afe-157c-452d-981b-c71353fb80bc
  4. Read events until the turn ends

    Events arrive as server-sent events. The turn is over at a session.status_idle whose stop_reason.type is not requires_action (usually end_turn).

    wait_for_end_of_turn "$WORK/stream.txt" kill "$STREAM_PID" ANSWER=$(events_in "$WORK/stream.txt" | jq -r 'select(.type == "agent.message") | .content[] | select(.type == "text") | .text') [[ -n $ANSWER ]] || fail "no agent.message on the stream" FIRST_ID=$(events_in "$WORK/stream.txt" | jq -rs '.[0].id') LAST_ID=$(events_in "$WORK/stream.txt" | jq -rs '.[-1].id') echo "step 4: $(events_in "$WORK/stream.txt" | wc -l) events, last $LAST_ID, agent said: $ANSWER"

    Sample output:

    Code
    step 4: 6 events, last sevt_4_1, agent said: Tokyo is the most populous metropolitan area in the world.
  5. Resume the stream from an event id

    If the connection drops, reopen the stream with a Last-Event-ID header set to the last event id you received. The server replays every event after it.

    # After a dropped connection, send the id of the last event you received. Here we resume from the first one. stream "$SESSION_ID" -H "Last-Event-ID: $FIRST_ID" > "$WORK/resumed.txt" & RESUME_PID=$! wait_for_end_of_turn "$WORK/resumed.txt" kill "$RESUME_PID" [[ $(events_in "$WORK/resumed.txt" | jq -rs '.[0].id') != "$FIRST_ID" ]] || fail "the resumed stream repeated $FIRST_ID" echo "step 5: resumed after $FIRST_ID, replayed $(events_in "$WORK/resumed.txt" | wc -l) events up to $(events_in "$WORK/resumed.txt" | jq -rs '.[-1].id')"

    Sample output:

    Code
    step 5: resumed after sevt_1_0, replayed 5 events up to sevt_4_1
  6. List the session’s events

    The events endpoint returns the stored history with the same ids the stream carried, oldest first. The script prints how many events it listed and which event types they include.

    LISTED=$(api "/sessions/$SESSION_ID/events") jq -e --arg id "$LAST_ID" 'any(.data[]; .id == $id)' <<<"$LISTED" >/dev/null || fail "$LAST_ID is not listed" echo "step 6: $(jq '.data | length' <<<"$LISTED") events listed: $(jq -r '[.data[].type] | unique | join(", ")' <<<"$LISTED")"

    Sample output:

    Code
    step 6: 6 events listed: agent.message, session.status_idle, session.status_running, session.usage, user.message
  7. Archive the session

    Archiving ends the session. Its status becomes terminated and its history stays readable. Sending it a message returns 400.

    ARCHIVED=$(api "/sessions/$SESSION_ID/archive" -X POST) [[ $(jq -r .status <<<"$ARCHIVED") == "terminated" ]] || fail "expected terminated: $ARCHIVED" [[ $(jq -r .archived_at <<<"$ARCHIVED") != null ]] || fail "archived_at is not set: $ARCHIVED" echo "step 7: session terminated at $(jq -r .archived_at <<<"$ARCHIVED")"

    Sample output:

    Code
    step 7: session terminated at 2026-10-21T01:47:50.964Z

If something goes wrong

What you seeWhyWhat to do
The stream opens but no events arriveThe message was sent before the stream was opened, and the turn finished first.Open the stream, then send. To catch up, list the events or reopen the stream with Last-Event-ID.
The loop stops while the agent still waitsThe loop treated a session.status_idle whose stop_reason.type is requires_action as the end of the turn.Stop only on an idle whose stop_reason.type is not requires_action. Answer requires_action as shown in Approve or deny tool calls.
429 rate_limit_error when opening a streamThe key already holds the most open streams one key may have on the server instance that answered (see Agent API streams).Close streams you no longer read (abort the controller or close the stream object), then open the new one.

Complete script

#!/usr/bin/env bash set -euo pipefail : "${CONTEXT_BASE_URL:?Set CONTEXT_BASE_URL, for example https://api.context.ai}" : "${CONTEXT_API_KEY:?Set CONTEXT_API_KEY to a personal Task API key}" : "${AGENT_ID:?Set AGENT_ID to an id from GET /v1/agents}" api() { local path=$1; shift curl -sS --fail-with-body "$CONTEXT_BASE_URL/v1$path" -H "x-api-key: $CONTEXT_API_KEY" "$@" } fail() { echo "error: $*" >&2; exit 1; } # Opens the session's event stream; exec makes the background job's pid the curl process itself. stream() { exec curl -sS --fail-with-body -N "$CONTEXT_BASE_URL/v1/sessions/$1/events/stream" \ -H "x-api-key: $CONTEXT_API_KEY" "${@:2}" } # The JSON of every event received so far on a stream saved to a file. Ping frames carry no id and are skipped. events_in() { sed -n 's/^data: //p' "$1" | jq -c 'select(.id)'; } # Waits until the stream file holds a session.status_idle that ends the turn (not requires_action). wait_for_end_of_turn() { for _ in $(seq 1 300); do grep -q '^event: error' "$1" && fail "the stream ended with an error: $(grep -A2 '^event: error' "$1" | sed -n 's/^data: //p')" events_in "$1" | jq -se 'any(.[]; .type == "session.status_idle" and .stop_reason.type != "requires_action")' >/dev/null && return 0 sleep 1 done fail "the turn did not end within 300 seconds" } WORK=$(mktemp -d) # @step 1 Create a session SESSION=$(api /sessions -H "content-type: application/json" \ -d "$(jq -n --arg agent "$AGENT_ID" '{agent: $agent, environment_id: "env_default", title: "Streaming demo"}')") SESSION_ID=$(jq -r .id <<<"$SESSION") [[ $(jq -r .status <<<"$SESSION") == "idle" ]] || fail "expected an idle session: $SESSION" echo "step 1: session $SESSION_ID idle" # @step 2 Open the stream before sending stream "$SESSION_ID" > "$WORK/stream.txt" & STREAM_PID=$! sleep 1 kill -0 "$STREAM_PID" 2>/dev/null || fail "the stream did not open: $(cat "$WORK/stream.txt")" echo "step 2: stream open" # @step 3 Send a message SENT=$(api "/sessions/$SESSION_ID/events" -H "content-type: application/json" -d '{"events": [ {"type": "user.message", "content": [{"type": "text", "text": "Reply with one sentence about Tokyo."}]}]}') [[ $(jq -r '.data[0].id' <<<"$SENT") == sevt_receipt_* ]] || fail "unexpected receipt: $SENT" echo "step 3: sent, receipt $(jq -r '.data[0].id' <<<"$SENT")" # @step 4 Read events until the turn ends wait_for_end_of_turn "$WORK/stream.txt" kill "$STREAM_PID" ANSWER=$(events_in "$WORK/stream.txt" | jq -r 'select(.type == "agent.message") | .content[] | select(.type == "text") | .text') [[ -n $ANSWER ]] || fail "no agent.message on the stream" FIRST_ID=$(events_in "$WORK/stream.txt" | jq -rs '.[0].id') LAST_ID=$(events_in "$WORK/stream.txt" | jq -rs '.[-1].id') echo "step 4: $(events_in "$WORK/stream.txt" | wc -l) events, last $LAST_ID, agent said: $ANSWER" # @step 5 Resume the stream from an event id # After a dropped connection, send the id of the last event you received. Here we resume from the first one. stream "$SESSION_ID" -H "Last-Event-ID: $FIRST_ID" > "$WORK/resumed.txt" & RESUME_PID=$! wait_for_end_of_turn "$WORK/resumed.txt" kill "$RESUME_PID" [[ $(events_in "$WORK/resumed.txt" | jq -rs '.[0].id') != "$FIRST_ID" ]] || fail "the resumed stream repeated $FIRST_ID" echo "step 5: resumed after $FIRST_ID, replayed $(events_in "$WORK/resumed.txt" | wc -l) events up to $(events_in "$WORK/resumed.txt" | jq -rs '.[-1].id')" # @step 6 List the session's events LISTED=$(api "/sessions/$SESSION_ID/events") jq -e --arg id "$LAST_ID" 'any(.data[]; .id == $id)' <<<"$LISTED" >/dev/null || fail "$LAST_ID is not listed" echo "step 6: $(jq '.data | length' <<<"$LISTED") events listed: $(jq -r '[.data[].type] | unique | join(", ")' <<<"$LISTED")" # @step 7 Archive the session ARCHIVED=$(api "/sessions/$SESSION_ID/archive" -X POST) [[ $(jq -r .status <<<"$ARCHIVED") == "terminated" ]] || fail "expected terminated: $ARCHIVED" [[ $(jq -r .archived_at <<<"$ARCHIVED") != null ]] || fail "archived_at is not set: $ARCHIVED" echo "step 7: session terminated at $(jq -r .archived_at <<<"$ARCHIVED")" # @end