Skip to content

Background runs ​

Every call that starts an agent turn becomes an agent run: a record with an id, a status, a result and a history. How long the caller waits for it is a separate choice. A turn can take minutes (model round-trips, tool loops, guardrail checks), and load balancers, proxies and serverless functions cap connection time, so Cognipeer lets you hold the connection for a while and then let go without losing the turn.

Replaces the older synchronous ceiling

Earlier versions terminated a synchronous call that outlasted its ceiling with 504. Now the ceiling is a wait window: when it ends and the turn is still going, the call answers 202 Accepted with the run, and the run keeps going in the background. There is no per-agent Execution setting any more; the limits are operator settings (below).

How a call ends ​

CallWaitsThen
Runs API POST /agents/{key}/runswait seconds (default 0)200 with the run if it finished, otherwise 202 with the run.
OpenAI Responses / chat completions / A2A (not streaming)the wait window (AGENT_SYNC_TIMEOUT_MS, 10 min)200 with the answer, or 202 with a run in the dialect's shape.
Streaming (any API)no windowThe stream is bounded only by the run ceiling. A /responses stream that loses its reader stops the run, unless the request said background: true. A runs-API stream keeps the run going unless it said "on_disconnect": "cancel". An A2A message/stream client that disconnects does not stop the task: it reattaches with tasks/resubscribe (one stream follows a task for up to 60 minutes).
Queued, scheduled, deferrednone202 at once.

If the run a waiting call is attached to is ended elsewhere before it finishes (the server shut down and handed its runs over, or its worker was lost), the call answers 503 agent_run_interrupted (retryable, side_effects_possible; a stream gets an error event and response.failed), never the partial answer its turn had. A long-poll (?wait=, Prefer: wait=N, a trigger's Run now) also stops waiting when its client disconnects; the run is not affected. The run's session events are closed like a failed turn's (session.error with code: agent_run_interrupted, then session.status_idle), see Session events.

A run still going when it reaches the ceiling is stopped and ends failed with max_duration_exceeded; a call that was still waiting then gets 504 agent_run_max_duration_exceeded (side_effects_possible: true, retryable: false: do not retry blindly).

A 202 carries a Location header (the run's URL in the runs API) and Retry-After: 2. Follow the run with GET /agents/runs/{id}?wait=60 (long-poll), a callback, or a webhook. See Calling agents from other systems for copy-paste examples.

Run lifecycle ​

                  ┌──────────────── cancel ────────────────┐
scheduled ─(due)─► queued ─► running ─► succeeded           ▼
   (run_at,          ▲          │  └──► failed         canceled
    delay_seconds)   │          └─────► requires_action ─(answered)─► running
                     └─ default: published to a worker; deferred: dispatched to a slot
StatusMeaning
scheduledHas a start time in the future (run_at, delay_seconds, a trigger). Not active: it holds no capacity and no session lock.
queuedWaiting for a worker.
runningExecuting, in a worker or inline in the request that started it. Proves it is alive by heartbeat.
requires_actionPaused for an approval or a question. It waits for a person; see approvals.
succeeded, failed, canceledTerminal.

stop_reason says how the agent turn ended (end_turn, limit, requires_action, cancelled, error, budget_reached). A run that a limit stopped still ends succeeded; stop_reason says how. error.type of a failed run is one of agent_error, worker_lost, max_duration_exceeded, canceled_by_caller, expired, interrupted, precondition_failed (the agent or token is no longer valid when the run starts), owner_disabled and owner_unverifiable (the user who queued the run has since been disabled, or could not be verified; a run never executes on a disabled user's authority).

Inline, detached and queued ​

  • Inline. A synchronous call executes in the request that carried it, and is recorded. If it finishes inside the window you get the answer. If not, the run is marked detached (detached_at) and the call answers 202; the turn keeps running in the same process and finishes the same way.
  • Queued. wait: 0, background: true, a deferred class or a trigger puts the run on a queue; a worker on any node picks it up.
  • Callbacks and webhooks fire only for async runs: queued, scheduled or deferred runs, and inline runs that detached. A turn answered inside the wait window sends neither.

The run ceiling (AGENT_BACKGROUND_MAX_DURATION_MS, 30 minutes) applies to every run, inline or queued. A run still going after it is stopped and marked failed with max_duration_exceeded.

Classes ​

A run is in one of two classes: default (interactive, capped per tenant at 250 active runs) and deferred (low priority, its own queue and caps, may wait up to 24 hours). Ask for deferred with "class": "deferred" or service_tier: "flex".

Scheduled runs ​

run_at (an ISO time) or delay_seconds on a run request makes it scheduled until due, at most 30 days ahead; a trigger creates scheduled or immediate runs for you on a cron schedule, once, on demand or when a webhook arrives. A scheduled run is promoted only while the tenant (or project) is under its default-class active-run cap; at the cap it stays scheduled and starts as soon as a slot is free, so it can start later than its run_at. A scheduled run can be cancelled before it starts. A scheduled or deferred run that does not start within 24 hours of becoming due ends failed with expired.

Start a run ​

bash
curl -X POST "$CONSOLE_URL/api/client/v1/agents/support-bot/runs" \
  -H "Authorization: Bearer $COGNIPEER_API_TOKEN" -H "Content-Type: application/json" \
  -H "Idempotency-Key: 3f1c9a2e-7b1d-4c55-9a51-0d6c2f1e8b7a" \
  -d '{
    "input": "Research this topic in depth and summarize the findings",
    "callback": { "url": "https://your-server.com/webhooks/agent-run", "secret": "a-shared-secret-of-16-plus-chars" },
    "metadata": { "topic": "pricing" }
  }'

Answer: 202 Accepted with the run (200 instead, with the existing run, for a replayed Idempotency-Key of a finished run):

json
{
  "id": "run_65f1c0a2b9d3e4f5a6b7c8d9",
  "object": "agent.run",
  "status": "queued",
  "class": "default",
  "agent": "support-bot",
  "session_id": "6f1c0a2b9d3e4f5a6b7c8d9e",
  "channel": "runs",
  "trigger": "request",
  "metadata": { "topic": "pricing" },
  "result": null,
  "error": null,
  "conversation_id": "6f1c0a2b9d3e4f5a6b7c8d9e",
  "trigger_id": null,
  "output_text": null, "output_parsed": null, "output_error": null,
  "scheduled_for": null, "created_at": 1760000000, "started_at": null, "completed_at": null,
  "detached_at": null, "cancel_requested_at": null,
  "max_duration_ms": 1800000,
  "callback": { "url": "https://your-server.com/webhooks/agent-run", "status": "pending", "attempts": 0, "signed": true }
}

The same on the OpenAI endpoints is background: true with optional callback_url and callback_secret; the reference for every field is on the Agents API page.

Poll, wait, cancel ​

http
GET  /api/client/v1/agents/runs/{runId}            # status + result
GET  /api/client/v1/agents/runs/{runId}?wait=60    # long-poll: returns when the run settles, or after 60 s
GET  /api/client/v1/agents/runs                    # list, filter, page
POST /api/client/v1/agents/runs/{runId}/cancel     # cancel

The list takes agent, status (comma separated), class, session_id, trigger_id (the runs one saved trigger started), channel, trigger (what started the run), metadata[key]=value (up to 3), created_after, created_before, limit (1-100, default 20) and after (a run id), newest first. channel is runs, responses, chat_completions, a2a, trigger or reminder (a reminder the agent set for itself); trigger is request, schedule, once, manual or webhook. The run's events are at GET /agents/runs/{runId}/events (and …/events/stream), and a paused run is answered with POST /agents/runs/{runId}/actions/{actionId}.

All resolve the run through the caller's tenant and project: a token cannot read or cancel a run of another project, even if it guesses the id. {runId} is run_<id>; the resp_<id> form is accepted too.

bash
# Poll until a terminal state, and stop on requires_action too: it waits for a person.
while true; do
  RUN=$(curl -s "$CONSOLE_URL/api/client/v1/agents/runs/$RUN_ID?wait=50" -H "Authorization: Bearer $COGNIPEER_API_TOKEN")
  STATUS=$(echo "$RUN" | jq -r .status)
  case "$STATUS" in succeeded|failed|canceled|requires_action) break ;; esac
done
echo "$RUN" | jq '{status, output_text, output_parsed}'

Cancellation is cooperative. A scheduled or queued run is cancelled at once; a running one gets cancel_requested_at and ends canceled at its next checkpoint (about a second), keeping its partial answer; a run waiting on a person is ended right away, its open approvals and questions are cancelled and the session goes idle (this is answering them "no", so it needs the right to answer them: 403 action_forbidden otherwise). A cancel that arrives after the run has finished is 409 agent_run_already_terminal. The routes that cancel by session, by response id or over A2A are on Stopping a turn.

What "cancelled" and "timed out" do not promise

Cancellation and the run ceiling stop the agent loop from starting its next step. They do not interrupt a tool call or a model call already in flight: a tool that is mid-way through sending an email will finish. "Terminated" means no further steps run and the caller stops waiting, not that a side effect in progress is guaranteed to be interrupted.

One active run per session ​

A session can have at most one active run, and the rule covers every way of starting one: a request on a session that already has a queued, running or detached run is refused with 409 agent_run_conflict before any turn starts. Two turns writing the same session at once would silently erase one of them. The check is atomic, not a read followed by a write. Deleting a session with an active run is refused the same way. A scheduled run does not hold the session until it becomes due.

The session option ​

A run request (and POST /responses) may carry a session object (Session Rooms, Enterprise; see Session rooms): session.scope (conversation, user, workspace or key) chooses the session of a call that names none, session.key names the room with scope: "key", and session.when_busy (steer, queue, agent or reject) lets the message wait when the session's agent is already working. A waiting message is answered 202 with a session.input object instead of a run. Without that opt-in a busy conversation answers 409 agent_run_conflict, and details.when_busy: "off" when the agent takes no message while it works. A session.scope other than the agent's own needs the agent's API calls may pick another scope setting (403 session_scope_not_allowed otherwise).

Idempotency ​

Send Idempotency-Key (at most 255 characters) on any call, synchronous or not. It is looked up within your tenant and project:

  • The same request (agent, session, message, version and the file ids you named) with the same key returns the existing run: 200 with the result if it finished, otherwise the call waits for it like a new call (the window) and answers 200 or 202. A replay of a stream: true request is answered as a stream (the stored terminal event of a finished run). Two identical requests that arrive together do not conflict: the second waits briefly for the first one's run and replays it. The key lives as long as its run, which is kept from the moment it finished.
  • A different request under the same key is 409 idempotency_key_conflict.

This stops a retried request from repeating tool side effects; it does not undo side effects of an earlier attempt made without a key. A key that starts with trigger: or hook: is refused (400 idempotency_key_reserved): those name the runs triggers start themselves.

Capacity and refusals ​

  • 409 agent_run_conflict: the session already has an active run.
  • 429 agent_run_concurrency_limit (error.type: rate_limit_error, with limit, scope and class; Retry-After: 30): the tenant or project already has the maximum number of active default-class runs (inline, queued and running), or the tenant's deferred backlog is full. Retry with backoff, or send the work as deferred.
  • 429 spend_limit_exceeded up front when the tenant's spend limit is used up; you get it at once, not after a 202.
  • 429 agent_quota_exceeded (Retry-After: 60) when the agent-run quota is used up. A run uses a quota unit only once it is admitted: a call refused for a conflict or a cap costs none.
  • 504 agent_run_max_duration_exceeded: a call was still waiting when the run reached its maximum duration (see above).
  • 400 attachment_unreachable: a remote file_url / image_url could not be fetched within the outbound timeout (30 seconds).
  • A stream is checked against the caps and the quota before it opens, so over a limit you get the plain JSON 429 with Retry-After and no session is created; only a limit reached in the instant after that check ends an open stream with an error event.

A refused request creates no run, so a retry never duplicates work, and the session that the same request created is removed again (a session it continued is kept). Continuing a paused run (an approval, a raised budget) is not refused by the cap: it carries on work that was already accepted. Queue state is visible at GET /agents/runs/queue.

Operator settings ​

Environment variables, read once at start-up. There are no per-agent execution settings: the agent keeps only its callback and its session budget.

VariableDefault
AGENT_SYNC_TIMEOUT_MS600000 (10 min, minimum 5000)The wait window of a synchronous call. After it the call answers 202 and the run continues. Set it below the shortest infrastructure timeout in your deployment (load balancer idle timeout, API gateway timeout, function max duration), so a slow turn becomes a clean 202 instead of an opaque proxy error.
AGENT_BACKGROUND_MAX_DURATION_MS1800000 (30 min)The wall-clock ceiling of any run: inline after detaching, queued or deferred.
AGENT_RUN_MAX_ACTIVE_PER_TENANT250Default class: queued + running runs of all kinds per tenant; 0 = no cap. The effective cap is the smaller of this and the tenant quota maxConcurrentAgentRuns.
AGENT_RUN_MAX_ACTIVE_PER_PROJECT0 (off)The same per project.
AGENT_RUN_CONCURRENCY4Default-class queue workers per node.
AGENT_DEFERRED_MAX_RUNNING_PER_TENANT2Deferred runs running at once, per tenant.
AGENT_DEFERRED_MAX_QUEUED_PER_TENANT10000Deferred runs queued or scheduled per tenant; over it, 429.
AGENT_DEFERRED_CONCURRENCYhalf of AGENT_RUN_CONCURRENCY, at least 1Deferred queue workers per node.
AGENT_DEFERRED_MAX_WAIT_MS86400000 (24 h)A deferred or scheduled run not started this long after it became due ends failed / expired.
AGENT_RUN_CALLBACK_CONCURRENCY4Callback delivery workers per node (their own queue).
AGENT_RUN_DRAIN_TIMEOUT_MS10000On shutdown, how long to wait for local runs before marking leftovers interrupted. Runs before the HTTP server waits for its open connections, so callers waiting on such a run are answered and open streams end. Clamped to the shutdown timeout minus 3 s.
AGENT_TRIGGER_TICK_MS30000 (minimum 5000)How often the trigger scheduler looks for due triggers.
AGENT_TRIGGER_MISFIRE_GRACE_MS3600000 (1 h)A missed trigger slot older than this is skipped; a younger one fires once to catch up.
AGENT_CHAT_CONCURRENCY4Interactive chat turns a node works on at once.
AGENT_WEBHOOK_BODY_LIMIT_BYTES5242880 (5 MiB; at least 16 KiB, at most 25 MiB)Largest body a webhook trigger accepts.
AGENT_WEBHOOK_RATE_LIMIT_PER_MINUTE60 (0 = off)Runs one webhook trigger may start per minute. Counted per node; shared across nodes with RATE_LIMIT_PROVIDER=redis.
AGENT_RUN_RETENTION_DAYS30Runs (and their message and result) are kept this long, counted from when the run finished (whichever way), and for a scheduled run from its due time. Runs waiting for a person are never deleted by retention.
AGENT_SESSION_EVENT_RETENTION_DAYS30The session event log is kept this long.
AGENT_RUN_HEARTBEAT_INTERVAL_MS, AGENT_RUN_HEARTBEAT_STALE_MS15000, 45000How often a run proves it is alive, and when a silent run is declared lost.
AGENT_RUN_REQUEUE_AFTER_MS120000A queued run no worker picked up is published again after this (with a job id of its own for each window, so a job that failed before it claimed its run is tried again).

Tenant quotas can lower the wait window, the maximum duration and the active-run cap (maxAgentSyncTimeoutSeconds, maxAgentBackgroundDurationMinutes, maxConcurrentAgentRuns); they never raise them above the environment. An agent has no run limits of its own except the ones inside a turn.

Renamed in this release

AGENT_BACKGROUND_MAX_CONCURRENT_RUNS_PER_TENANT (default 10) and AGENT_BACKGROUND_MAX_CONCURRENT_RUNS_PER_PROJECT are replaced by AGENT_RUN_MAX_ACTIVE_PER_TENANT (default 250) and AGENT_RUN_MAX_ACTIVE_PER_PROJECT. The semantics changed with the name: the cap now counts synchronous calls too, not only background runs. Remove the old variables from your deployment; they are no longer read.

Callbacks ​

When an async run has a callback, Cognipeer POSTs to it when the run finishes, fails, is cancelled or pauses for a person. The callback comes from the request (callback: { url, secret }, or callback_url / callback_secret on the OpenAI endpoints), from a trigger, or from the agent's own default (Build → Callback & budget, config.callback), in that order.

WhereNotes
callback.urlhttp or https, at most 2048 characters, must resolve to a public address, otherwise 400 invalid_callback.
callback.secret16–256 characters. Signs each delivery. A url sent without a secret is delivered unsigned: the agent's default secret goes only with the agent's default URL. Write-only: once saved on an agent, the page shows a mask, and sending the mask back keeps the stored value. To remove an agent's default callback, clear its URL: the stored secret goes with it.

A runs API call that waits for its run gets no per-run callback for the state it was answered with (finished, or paused for a person): the caller already has it. Webhook subscriptions still fire. Later states are called back: the outcome of a run that outlived the wait, the outcome after a pause the caller was answered with, and the outcome of a run whose caller disconnected, or whose node stopped, before the answer. A callback that never settled, because a node died or the queue lost the job, is queued again by the reconciler. The run's own status is the source of truth: poll it if a callback does not arrive.

http
POST /webhooks/agent-run
content-type: application/json
user-agent: cognipeer-agent-runs/1.0
x-cognipeer-event: agent_run.succeeded
x-cognipeer-event-id: evt_65f1c0a2b9d3e4f5a6b7c8d9_succeeded
x-cognipeer-signature: t=1760000042,v1=…
json
{
  "id": "evt_65f1c0a2b9d3e4f5a6b7c8d9_succeeded",
  "event": "agent_run.succeeded",
  "createdAt": "2026-10-11T09:15:02.000Z",
  "runId": "run_65f1c0a2b9d3e4f5a6b7c8d9",
  "sessionId": "6f1c0a2b9d3e4f5a6b7c8d9e",
  "conversationId": "6f1c0a2b9d3e4f5a6b7c8d9e",
  "data": {
    "result": { "id": "resp_65f1c0a2b9d3e4f5a6b7c8d9", "object": "response", "status": "completed", "…": "…" }
  }
}
eventdata
agent_run.succeededresult: the run's result, as GET /agents/runs/{id} returns it
agent_run.failederrorReason (for example agent_error, max_duration_exceeded) and, when there is one, message
agent_run.canceled{}
agent_run.requires_actionresult, carrying required_action

The callback body is deliberately small: the run's status, class, metadata and trigger_id are not in it. Read them with GET /agents/runs/{runId}, or put your own correlation id in the callback URL (https://erp.example.com/hooks/receipts?claim=8841). The webhook subscription events for the same transitions do carry status, class, metadata and triggerId in data.

The event id is stable per run and event, so a receiver can deduplicate retries on it. After a run paused and was resumed, the id carries the run's generation (evt_<runId>_<event>_<generation> from the second outcome on), so each outcome has its own id, and a late delivery of an older event never overwrites the state of a newer one. A paused run whose pause is dropped (a new message to an agent set to cancel pending requests, a session truncate, a timeout of onTimeout: cancel) ends canceled and sends the agent_run.canceled callback and webhook. The signature is HMAC-SHA256(secret, "<t>.<raw body>"), the same scheme as webhooks and the verifyAgentRunCallback helper in @cognipeer/console-sdk/webhooks (an alias of verifyWebhook). Delivery has a 10-second timeout and is retried up to 5 times with exponential backoff (2, 4, 8, 16, 32 seconds); the run's callback.status and attempts are stored on the run, so a restart mid-retry does not lose the notification. Deliveries have their own queue and workers (AGENT_RUN_CALLBACK_CONCURRENCY), so a slow receiver cannot hold up runs. Callbacks fire for failed and canceled outcomes too.

If you would rather not run an endpoint per call, subscribe a webhook to agent_run.* instead: it hears about every async run of the project, whether or not the run carries a callback.

Restarts and lost workers ​

  • A node stops gracefully. On SIGTERM the node stops taking new runs, waits up to AGENT_RUN_DRAIN_TIMEOUT_MS for the runs it holds (inline and worker), then marks any that are still going failed with error.type: interrupted ("The server restarted while this run was in progress. It was not completed; retry it."), notifies them like any failure, and exits. The drain happens before the HTTP server waits for its open connections: a caller that is waiting on such a run gets its 503 agent_run_interrupted, and open session event streams are ended (clients reconnect with Last-Event-ID). interrupted runs are not restarted automatically: a turn may already have called a tool with real side effects. Start them again yourself. Queued runs stay queued; the next boot publishes them again.
  • A node dies. A reconciler (every 30 seconds) finds running runs whose heartbeat has gone stale and finalizes them failed with error.type: worker_lost. A queued run that never started is safe to publish again, and is. An inline call that never detached gets no callback or webhook, because its caller already saw the connection fail.

Security notes ​

  • Runs are project-scoped. GET, list and cancel resolve the run through tenant and project; a token from another project in the same tenant gets 404 even with the right id.
  • A run never executes on a disabled user's authority. If the user who queued it was disabled in the meantime (or cannot be verified), the run fails with owner_disabled / owner_unverifiable instead of running.
  • Callback URLs are validated twice. Submitting one that does not resolve to a public address is 400 invalid_callback; delivery then re-resolves, pins the address and re-checks every redirect hop, so a name that rebinds to an internal service later is still refused.
  • Callbacks should be signed. Send a secret (16–256 characters), or set the agent's default callback secret, and verify the signature.
  • Secrets are never returned. Neither the request secret nor the agent's callback secret appears in a run, a list or a published version.
  • Idempotency keys are scoped to your tenant and project, and compared against the whole request, not just the key.

Troubleshooting ​

409 agent_run_conflict when I send a message. A run is active on the session. Wait for it, or cancel it. A run that is requires_action does not hold the session in the same way: answer its requests instead (approvals).

The run sits in queued. No worker has picked it up: check that the node serving the queue is running. After AGENT_RUN_REQUEUE_AFTER_MS the reconciler publishes it again. A deferred run waits for a slot: look at GET /agents/runs/queue.

I got 202 on a call I expected to finish. It outlasted the wait window (AGENT_SYNC_TIMEOUT_MS). Nothing was lost: follow the run (Location header, or resp_<runId> / run_<runId>). For turns that can take minutes, start with wait: 0 and long-poll or use a callback.

My callback never arrives. Callbacks fire only for async runs: a call answered inside the wait window sends none. Otherwise check callback.status on the run: failed means all five attempts were refused. The URL must be public and answer 2xx within 10 seconds.

I polled until "terminal" and my loop never ended. requires_action is non-terminal but waits for a person. Stop polling on it, too.

A run ended interrupted. The node restarted while it ran. Start it again; use an Idempotency-Key that includes an attempt number if the earlier one should not be replayed.

Studio · Pulse · Console · Agent SDK and more — the Cognipeer documentation hub