Skip to content

Agents API ​

Manage and invoke AI agents via the client API. Agents combine a model, system prompt, tools, guardrails, and Knowledge Engine modules into a single deployable unit.

This page covers the agent resource (list, read, create, update, publish, delete) and the ways of invoking an agent: the runs API (canonical), the OpenAI Responses endpoint, and chat completions. What happens around a conversation — sessions, events, approvals, files, budgets — has its own reference: Agent Sessions API, Triggers API, Webhooks API, and the Agent runtime guide. Task-oriented walkthroughs with copy-paste examples are in Calling agents from other systems.

Field names of the agent family (Responses, runs, sessions) are snake_case. The agent resource itself keeps its older camelCase shape (createdAt).

List Agents ​

GET /api/client/v1/agents

Query Parameters ​

ParameterTypeRequiredDescription
statusstringNoFilter by status: active, inactive, draft

Response ​

json
{
  "agents": [
    {
      "key": "support-bot",
      "name": "Support Bot",
      "description": "Customer support agent",
      "config": {
        "modelKey": "gpt-4o",
        "temperature": 0.7,
        "topP": 1,
        "maxTokens": 4096
      },
      "status": "active",
      "createdAt": "2026-01-15T10:00:00.000Z"
    }
  ]
}

Get Agent ​

GET /api/client/v1/agents/:agentKey

Path Parameters ​

ParameterTypeRequiredDescription
agentKeystringYesUnique agent key

Response ​

json
{
  "agent": {
    "key": "support-bot",
    "name": "Support Bot",
    "description": "Customer support agent",
    "config": {
      "modelKey": "gpt-4o",
      "temperature": 0.7,
      "topP": 1,
      "maxTokens": 4096,
      "showReasoning": true
    },
    "status": "active",
    "createdAt": "2026-01-15T10:00:00.000Z",
    "attachments": {
      "enabled": true,
      "max_files": 10,
      "max_file_size_mb": 20,
      "allowed_mime_types": ["application/pdf", "image/*"],
      "accepts_images": true,
      "outputs": {
        "enabled": true,
        "max_files_per_turn": 10,
        "max_file_size_mb": 2,
        "types": ["md", "csv", "txt", "json", "html", "xml", "yaml"]
      }
    },
    "variables_schema": {
      "type": "object",
      "properties": { "customer_id": { "type": "string", "description": "Customer to look up" } },
      "required": ["customer_id"],
      "additionalProperties": false
    },
    "output_schema": null
  }
}

Three blocks are additive and appear only on this single-agent read, so a client can treat an agent as a typed function:

  • attachments — what a client needs before it offers an attach button: enabled is true only when files are on, a bucket is chosen and that bucket can take a file right now; accepts_images is true only while uploads are on (so it is false whenever uploads are off or the bucket is unusable) and the agent's model reads images. outputs says whether the agent can create files (CSV, Markdown, …) for the caller and within which limits; it does not depend on enabled, so an agent can create files while uploads are off. See Session files.
  • variables_schema — a JSON Schema built from the agent's declared variables, or null when it declares none.
  • output_schema — the agent's configured structured-output schema, or null.

The config shown here is a summary (modelKey, temperature, topP, maxTokens, showReasoning); the portal experience settings are not part of this response. models is added when the agent offers more than one model. The full config (with secrets masked) is returned by create, update and publish.

Create Agent ​

POST /api/client/v1/agents
FieldTypeRequiredDescription
namestringYesDisplay name. The agent key is generated from it.
descriptionstringNo
statusstringNoactive, inactive, draft.
configobjectYesThe agent's configuration — see below.
bash
curl -X POST "$CONSOLE_URL/api/client/v1/agents" \
  -H "Authorization: Bearer $COGNIPEER_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Support Bot",
    "config": {
      "modelKey": "gpt-4o",
      "systemPrompt": "You are a support agent.",
      "humanInTheLoop": { "toolApproval": { "enabled": true } },
      "attachments": { "enabled": true, "bucketKey": "uploads" },
      "budget": { "maxCostUsd": 2, "onReach": "pause" }
    }
  }'

201: { "agent": { …, "key": "support-bot-a1b2c3", "config": { … } } }. The config is validated before it is stored; nothing is saved if it would not run as configured. An old config.execution block is ignored and dropped on the next save. Errors: 400 { "error": "Invalid agent config — <field>: <message> (and N more)", "validation": { "errors": [...], "warnings": [...] } }; 403 files_write_required when config.attachments.bucketKey is set without write access to Files.

The configuration sections that belong to the agent runtime:

SectionKeyGuide
Callbackconfig.callback — url, secret (write-only): where a finished async run is POSTed when the request names noneBackground runs
Session budgetconfig.budget — maxCostUsd, onReach, allowClientOverrideSession budgets
Variablesconfig.variables — up to 32 typed values a caller sends next to the message (below)Variables
Filesconfig.attachments, including attachments.outputs (file output tools)Session files
Approvals & questionsconfig.humanInTheLoopApprovals & questions
Client toolsconfig.clientTools (up to 20 tools the caller runs: name, description, inputSchema, timeoutSeconds, enabled) and config.clientToolSurfaces (api, playground, portal, all on by default)Client tools

Update Agent ​

PATCH /api/client/v1/agents/:agentKey

Accepts name, description, status, config and metadata; anything else is ignored. config replaces the stored config wholesale — send it complete, not only the part you changed. A native-shaped config sent to a connected (external) agent is ignored so it cannot overwrite the connection. 200: { "agent": { … } }. Same validation errors as create; 404 { "error": "Agent not found" }.

When the agent's stored sandbox secrets cannot be decrypted (the encryption key changed), reads of the full config carry config.sandbox.secretsUnreadable: true with an empty secrets list. A save that mixes masked values with new ones answers 409 with the body { "error": "…", "type": "sandbox_secrets_unreadable", "code": "sandbox_secrets_unreadable", "field": "config.sandbox.secrets" } and stores nothing; a save that sends only masks keeps the stored secrets; a save that sends every secret again, with no masks, replaces them. secretsUnreadable is read only and is dropped on save.

Publish Agent ​

POST /api/client/v1/agents/:agentKey/publish

Publishes the current draft config as a new immutable version. The draft is validated first. Body: { "changelog": "…" } (optional). 201: { "version": { … } }. The runs API, the Responses and chat completions endpoints, A2A and portals all run the published version by default, so settings you change in the draft — files, approvals, experience — reach them only after you publish. (An agent that was never published runs its draft.)

Delete Agent ​

DELETE /api/client/v1/agents/:agentKey

200: { "success": true }.

Invoking an agent ​

SurfaceEndpoint
Runs APIPOST /api/client/v1/agents/{agentKey}/runsCanonical. Async-first, the most complete.
ResponsesPOST /api/client/v1/responses with model: "agent:<key>"OpenAI Responses shape; also serves models. Alias: POST /api/client/v1/agents/responses (agents only).
Chat completionsPOST /api/client/v1/chat/completions with model: "agent:<key>"OpenAI chat shape.
A2APOST /api/client/v1/a2a/{agentKey}JSON-RPC; see LiteLLM and A2A.

All of them start the same engine and produce the same run, run the published version unless you send version, and count against the same limits. Everything here is snake_case.

Runs API ​

Create a run ​

POST /api/client/v1/agents/{agentKey}/runs
FieldTypeDescription
inputstring | arrayRequired unless variables carries the request. A plain string, or message items with input_text, input_file (file_id, file_data or file_url) and input_image parts, as on Responses.
variablesobjectValues for the agent's declared variables, sent next to the message.
session_idstringContinue a session. Omitted: a new session is created; its id is in the run and the Location header.
versionnumber | "draft"Pin a published version, or run the draft. Default: the published version.
class"default" | "deferred"The run class. Default default.
run_atISO 8601 string or unix secondsStart at this time. The run is scheduled until due. At most 30 days ahead; a time already past starts the run now.
delay_secondsintegerStart after this many seconds (0 or more). Give run_at or delay_seconds.
waitnumberSeconds to hold the request for the answer. Default 0 (return at once with 202); at most the server's wait window. Prefer: wait=N and Prefer: respond-async work too.
streambooleantrue answers with Server-Sent Events using the Responses event vocabulary. Not with class: "deferred" or a scheduled start (400 invalid_request).
on_disconnect"continue" | "cancel"Streaming only: what a dropped connection does. Default continue (the run goes on detached).
metadataobjectUp to 16 string pairs (key ≤ 64 characters of A-Za-z0-9_.-, value ≤ 512). Stored on the run, echoed back, filterable in the list.
callback{ url, secret? }Where to POST the result of an async run. url must be a public http(s) address; secret (16–256 characters) signs the delivery. Without one, the agent's default callback applies.
response_formatobjectStructured output for this turn (below).
runtime_contextobjectDownstream headers and prompt placeholders for this turn (not the agent's variables).
reasoning{ effort }Reasoning effort for this turn. Applied to a streamed run only: a queued run (the default, deferred, scheduled) uses the agent's own effort.
agent_modelstringOne of the models the agent offers (Agent models).
budgetobject | nullSpend budget for the session this request starts: { "max_cost_usd": 2, "on_reach": "pause" }.
session{ scope?, key?, when_busy? }Session Rooms (Enterprise). scope: conversation, user, workspace or key (with key); when_busy: steer, queue, agent or reject. A shared scope other than the agent's own needs the agent's API calls may pick another scope setting (403 session_scope_not_allowed). See Session rooms. Also accepted by POST /responses.
header Idempotency-Keystring≤ 255 characters. Same key and same request returns the same run; a different request is 409. Accepted on every call.
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: ticket-OPS-12-triage" \
  -d '{
    "input": "Triage ticket OPS-12",
    "metadata": { "ticket": "OPS-12" },
    "wait": 30
  }'

Status codes

Status
200The run finished inside wait (or an Idempotency-Key replay of a finished run). Body: the run, with output_text and output_parsed.
202The run is scheduled, queued or running. Headers: Location (the run's URL) and Retry-After: 2. When the session's agent is already working and the message may wait (session.when_busy, or a room), the body is a session.input object without those headers: see waiting messages.
400invalid_json (the body is not a JSON object), invalid_request, attachment_unreachable (a remote file URL did not arrive within the outbound timeout), invalid_variables (with errors: [{ field, message }]), invalid_response_format, invalid_callback, invalid_class, invalid_schedule (a bad run_at or delay_seconds, or one more than 30 days ahead), invalid_wait, invalid_metadata, invalid_version, unsupported_content_part, attachment_not_found, agent_inactive, …
402, 403budget_reached; attachments_disabled, budget_override_forbidden, a permission error.
404agent_not_found, version_not_found, session_not_found in the token's project.
409agent_run_conflict (the session has an active run and the message may not wait; details.when_busy: "off" when the call asked it to wait and the agent takes no message while it works), attachments_not_queued, pending_action (it waits for an approval), idempotency_key_conflict.
429agent_run_concurrency_limit (with limit, scope, class; Retry-After: 30), spend_limit_exceeded, agent_quota_exceeded (Retry-After: 60 on a stream). A call refused before its run exists removes the session it created. The quota counts a run only once it is admitted.

A stream (stream: true) is checked against the run caps and the agent quota before it opens: over a limit the answer is this plain JSON 429 with Retry-After, not an error event, and no session is created.

An Idempotency-Key replay of a stream: true request answers as a stream too (response.created, response.in_progress and the stored terminal event of a finished run; a run that is still going ends with a further response.in_progress and no terminal event), not as JSON. The wait of wait / Prefer ends early when the client disconnects; the run carries on. A run's record is kept for AGENT_RUN_RETENTION_DAYS counted from when it finished, and a scheduled run is promoted only while the tenant is under its active-run cap, so it can start later than run_at while the cap is full.

The run object ​

json
{
  "id": "run_65f1c0a2b9d3e4f5a6b7c8d9",
  "object": "agent.run",
  "status": "succeeded",
  "class": "default",
  "agent": "support-bot",
  "version": 3,
  "session_id": "6f1c0a2b9d3e4f5a6b7c8d9e",
  "conversation_id": "6f1c0a2b9d3e4f5a6b7c8d9e",
  "channel": "runs",
  "trigger": "request",
  "trigger_id": null,
  "metadata": { "ticket": "OPS-12" },
  "stop_reason": "end_turn",
  "result": { "id": "resp_65f1c0a2b9d3e4f5a6b7c8d9", "object": "response", "status": "completed", "output": [ … ], "output_text": "Ticket OPS-12 is a billing issue…" },
  "output_text": "Ticket OPS-12 is a billing issue…",
  "output_parsed": null,
  "output_error": null,
  "error": null,
  "scheduled_for": null,
  "created_at": 1760000000,
  "started_at": 1760000001,
  "completed_at": 1760000012,
  "detached_at": null,
  "cancel_requested_at": null,
  "max_duration_ms": 1800000,
  "callback": null
}
Field
statusscheduled, queued, running, requires_action, succeeded, failed, canceled.
classdefault or deferred.
channelHow the run was started: runs, responses, chat_completions, a2a or trigger.
triggerWhat started the run: request, or for a trigger's fires schedule, once, manual or webhook (webhook triggers).
trigger_idThe id of the trigger that fired the run (channel: "trigger"), else null.
stop_reasonHow the agent turn ended (end_turn, limit, requires_action, cancelled, error, budget_reached); null while active.
resultThe Responses body the turn produced (without the transcript), once finished and while requires_action.
output_text, output_parsed, output_errorConvenience copies from result. output_parsed is the validated object of a structured-output turn; output_error says why validation failed (the run is still succeeded).
error{ type, message } once failed or canceled (message can be null). type is one of agent_error, worker_lost, max_duration_exceeded, canceled_by_caller, expired, interrupted, precondition_failed, owner_disabled, owner_unverifiable.
scheduled_for, created_at, started_at, completed_at, detached_at, cancel_requested_atEpoch seconds. detached_at is set when a synchronous call stopped waiting and the run continued in the background.
callbacknull, or { url, status, attempts, signed }. The secret is never returned.

Get a run ​

GET /api/client/v1/agents/runs/{runId}
GET /api/client/v1/agents/runs/{runId}?wait=60

runId is run_<id>; the resp_<id> form is accepted too. With ?wait=<seconds> the server holds the request until the run reaches a terminal state or requires_action, or the wait ends (at most the server's wait window), and then answers 200 with the run as it is. That is the cheapest way to follow a run: one request per minute instead of a poll every two seconds.

List runs ​

GET /api/client/v1/agents/runs
Query
agentAgent key.
statusOne status or a comma-separated list (queued,running).
classdefault or deferred.
session_id, trigger_id, channel, triggerExact match. channel: runs, responses, chat_completions, a2a, trigger. trigger: request, schedule, once, manual, webhook.
metadata[key]=valueExact match; up to 3 pairs.
created_after, created_beforeUnix seconds or ISO 8601.
limitDefault 20, at most 100.
afterA run id: continue after it.
json
{ "object": "list", "data": [ { "id": "run_…", "object": "agent.run", "…": "…" } ], "first_id": "run_…", "last_id": "run_…", "has_more": true }

An unknown status, class, channel or trigger, a bad limit or date is 400 (invalid_status, invalid_class, invalid_channel, invalid_trigger, invalid_limit, invalid_date, invalid_metadata). Dashboard reservation rows of interactive chat turns are not listed. Runs are kept for AGENT_RUN_RETENTION_DAYS (30 by default).

Queue ​

GET /api/client/v1/agents/runs/queue
json
{
  "object": "agent.run_queue",
  "default":  { "running": 3, "queued": 0, "scheduled": 1, "limit": 250 },
  "deferred": { "running": 2, "queued": 148, "scheduled": 12, "running_limit": 2, "queued_limit": 10000, "oldest_queued_at": 1760000000 },
  "project": { "default": { "running": 1, "queued": 0, "scheduled": 0 }, "deferred": { "running": 0, "queued": 20, "scheduled": 0 } }
}

Tenant-wide counts, plus the counts of the token's project under project.

Cancel a run ​

POST /api/client/v1/agents/runs/{runId}/cancel

The canonical cancel. See Cancel for the semantics. 200 with the run: canceled for a scheduled, queued or paused run; still running with cancel_requested_at set for a running one (it ends canceled within about a second, keeping its partial answer). 409 agent_run_already_terminal when the run has already finished.

Events and actions of a run ​

GET  /api/client/v1/agents/runs/{runId}/events?after_seq=0        # the session events of this run, JSON
GET  /api/client/v1/agents/runs/{runId}/events/stream             # the same as Server-Sent Events; resume with Last-Event-ID
POST /api/client/v1/agents/runs/{runId}/actions/{actionId}        # answer an approval or question of this run

The events are the session events restricted to this run; a run that paused and was answered inline keeps its events across the resume (the continuation writes them with the same run id), so they do not stop at the pause. The action call is the session action call scoped to the run. Use them to watch tool calls live or to answer an approval from a pipeline.

Streaming ​

"stream": true answers 200 with Content-Type: text/event-stream. Each frame is event: <type> and data: <json>; every data has type and sequence_number:

Event
response.created, response.in_progressThe run started (the first carries the run id in cognipeer.run_id).
response.output_item.added, response.content_part.addedA message item and its text part begin.
response.output_text.deltaA chunk of the answer (delta).
response.output_text.done, response.content_part.done, response.output_item.doneThe text is complete.
response.reasoning_summary_part.added, …_text.delta, …_text.doneReasoning, when the agent shows it.
response.completedThe full response object. Or response.failed, or response.incomplete.
errorAn error after the stream began: a limit reached in the instant after the pre-check, a failing run, or a run ended elsewhere during the stream (agent_run_interrupted; followed by response.failed).

A : ping comment arrives every 15 seconds. A stream is bounded by the run ceiling, not by wait. When the client disconnects, on_disconnect: "continue" (the default on this API) lets the run finish detached; "cancel" stops it.

Responses API ​

POST /api/client/v1/responses
POST /api/client/v1/agents/responses          # agents only
GET  /api/client/v1/responses/{id}
POST /api/client/v1/responses/{id}/cancel

/responses serves models and agents. model is resolved as agent:<key>, else a model key in the project, else an agent key, else 404 model_not_found. /agents/responses always means an agent. The token needs the agents service for an agent target and models for a model target; a missing one is 403 permission_error.

Request (agent target) ​

FieldTypeDescription
modelstringRequired. agent:<key> (or an agent key).
inputstring | arrayRequired. User message; see Input formats.
previous_response_idstringresp_<runId> or run_<runId> of an earlier turn; legacy resp_<conversationId> still works.
session_idstringContinue a session created with POST /agents/sessions. Names the same thing as previous_response_id.
conversationstring | objectOpenAI-style alias of session_id: an id, or { "id": "…" }. Give one of the three, or several that agree.
versionnumber | "draft"A published version, or the draft. Default: the published version.
streambooleanSSE with the response.* events. Not with service_tier: "flex" (400 unsupported_parameter).
backgroundbooleanReturn at once with a queued run (202); with stream: true the turn streams as usual but a dropped connection no longer cancels it. Also header X-Cognipeer-Background: true.
text.formatobject{ "type": "json_schema", "name", "schema", "strict" }, { "type": "json_object" } or { "type": "text" }. See Structured output.
reasoning.effort, reasoning_effortstringReasoning effort for the turn.
metadataobjectUp to 16 string pairs, stored on the run and echoed.
service_tierstringflex runs in the deferred class, and the call waits for it like a plain one; anything else, the default class.
variablesobjectValues for the agent's variables (extension).
agent_modelstringA model the agent offers.
runtime_context, budgetobjectPer-turn headers and variables; session budget.
callback_url, callback_secretstringAsync runs only: where to POST the result and the signing secret.
include_reasoningbooleanInclude reasoning items in the output.
storebooleanIgnored: a response is always stored.
header Idempotency-KeystringAs on the runs API.

Ignored for agents (the agent's own configuration applies): instructions, temperature, top_p, max_output_tokens, tools, tool_choice, parallel_tool_calls, truncation. The response header X-Cognipeer-Ignored-Params lists the ones you sent. To use these, target a model.

Input formats ​

json
{ "model": "agent:support-bot", "input": "Hello, I need help" }
json
{
  "model": "agent:support-bot",
  "session_id": "6f1c0a2b9d3e4f5a6b7c8d9e",
  "input": [
    {
      "role": "user",
      "content": [
        { "type": "input_text", "text": "Compare these" },
        { "type": "input_file", "file_url": "https://files.example.com/a.pdf" },
        { "type": "input_file", "file_data": "data:application/pdf;base64,JVBERi0x…", "filename": "b.pdf" },
        { "type": "input_image", "image_url": "https://example.com/cat.png" }
      ]
    }
  ]
}

Of the last user message, all input_text parts are joined with a blank line. input_file takes file_id (a session file), file_data (a base64 data: URL) or file_url (http or https, fetched safely and size-capped). input_image takes image_url. An agent that takes no attachments answers a request that carries one with 403 attachments_disabled; an unsupported part such as input_audio is 400 unsupported_content_part.

Response ​

json
{
  "id": "resp_65f1c0a2b9d3e4f5a6b7c8d9",
  "object": "response",
  "status": "completed",
  "model": "agent:support-bot",
  "output": [
    { "type": "message", "role": "assistant", "content": [ { "type": "output_text", "text": "To reset your password, go to Settings > Security…" } ] }
  ],
  "output_text": "To reset your password, go to Settings > Security…",
  "usage": { "input_tokens": 12, "input_tokens_details": { "cached_tokens": 0 }, "output_tokens": 45, "output_tokens_details": { "reasoning_tokens": 0 }, "total_tokens": 57 },
  "created_at": 1760000000,
  "metadata": { "ticket": "OPS-12" },
  "service_tier": "default",
  "background": false,
  "text": { "format": { "type": "text" } },
  "previous_response_id": null,
  "conversation": { "id": "6f1c0a2b9d3e4f5a6b7c8d9e" },
  "stop_reason": "end_turn",
  "error": null,
  "incomplete_details": null,
  "version": 3,
  "cognipeer": { "run_id": "run_65f1c0a2b9d3e4f5a6b7c8d9", "session_id": "6f1c0a2b9d3e4f5a6b7c8d9e" }
}

The id is run-scoped: resp_<runId>, also for synchronous calls, so GET /responses/{id} and the runs API address the same thing. background is what the request asked for: true for a run started with background: true, whether or not it streamed, and also when you read it back with GET /responses/{id}; a service_tier: "flex" call is queued but reads false. usage always has the two detail objects, 0 when a detail was not reported (reasoning_tokens is 0 for an agent run).

status is queued (queued or scheduled), in_progress (running), completed, incomplete (a run limit ended the turn; incomplete_details.reason and stop_reason say which), failed, cancelled, or requires_action (an extension: the agent waits for an approval or an answer, see below). When the agent has structured output the response also has output_parsed (the validated object) or output_error. A failed run has error: { code, message }.

HTTP
200The turn completed within the wait window, or an idempotent replay.
202The run is queued, scheduled, or still running when the window ended. status is queued or in_progress; Location points at the run. The turn continues; fetch it with GET /responses/{id} or the runs API.

The wait window is the server's AGENT_SYNC_TIMEOUT_MS (10 minutes by default). It is a window, not a limit: a turn that outlasts it keeps running.

If the run a call waits on is ended elsewhere before it finishes (the server shut down and handed its runs over, or the worker was lost), the call answers 503 agent_run_interrupted (retryable: true, side_effects_possible: true) and never the partial answer as if it were complete; read the run, or send the request again. A body that is not a JSON object is 400 invalid_json. reasoning.effort applies to a run that executes in the request; a queued run (background: true, service_tier: "flex") uses the agent's own effort.

Streaming events ​

With stream: true the answer is Server-Sent Events, with the events listed above: response.created … response.output_text.delta … response.completed. Output files ride on the completed response (output_files and annotations). A client that disconnects cancels the turn unless background: true was sent, in which case it carries on detached.

Get and cancel ​

GET /responses/{id} returns the response object of a run (resp_ or run_ ids; also under /agents/responses/{id}); an unknown id is 404 in the OpenAI error envelope. POST /responses/{id}/cancel follows the cancel standard and returns the response object: cancelled, or in_progress while a cooperative cancel is landing. Cancelling a finished response is 200 with the finished object (OpenAI behaviour); the runs API answers 409 instead.

Waiting for an approval or an answer ​

An agent with approvals & questions can pause. The response then has status: "requires_action", stop_reason: "requires_action" and the requests to answer in required_action:

json
{
  "id": "resp_65f1c0a2b9d3e4f5a6b7c8d9",
  "object": "response",
  "status": "requires_action",
  "stop_reason": "requires_action",
  "required_action": {
    "type": "agent_actions",
    "actions": [
      { "id": "act_0123456789abcdef01234567", "kind": "tool_approval", "tool_name": "sandbox_exec", "args": { "command": "ls" }, "status": "pending" }
    ]
  }
}

Answer with POST /api/client/v1/agents/runs/{runId}/actions/{actionId} (or the session form). The answer to an approval continues the paused run: its response id is resp_<runId> of that run (also while other requests of the pause are still open), and the run's events include the continuation. 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 (canceled_by_caller) with its callback and agent_run.canceled event. An agent that does not use these features never returns this status.

Model target ​

When model resolves to a model, /responses is a thin translation onto the gateway path of /chat/completions, so quota, usage, guardrails and routing apply as usual. Supported: input (string, or messages with text and image parts), instructions (a system message), text.format (as response_format), function tools and tool_choice, temperature, top_p, max_output_tokens, reasoning.effort, metadata (echoed), stream, and function_call / function_call_output input items. Not supported for models, 400 unsupported_parameter: previous_response_id, conversation, background; built-in tool types are 400 too. Nothing is stored, so GET /responses/{id} is 404 for a model response.

Chat completions ​

POST /api/client/v1/chat/completions      # model: "agent:<key>"

The model path is described on Chat Completions. For an agent:

  • Session: conversation_id in the body, or the X-Cognipeer-Session-Id header, continues a session. Otherwise Cognipeer matches the resent history against the stored transcript of the caller's sessions with this agent. The match covers the messages, the references of files and images, and the OpenAI user field, and a session is continued only when exactly one of the caller's sessions matches: no match, or an ambiguous one, starts a new session. The response always carries X-Cognipeer-Session-Id (and conversation_id in the body; for a stream, in the first and final chunk).
  • Input: the last user message; text parts are joined, image_url and file parts (file_data, file_id) become session files (the agent must accept attachments, else 403 in the OpenAI envelope). An image-only message is valid. system and developer messages are ignored.
  • Output: message.content is the answer; with response_format: { "type": "json_schema", … } it is the JSON string.
  • Options: stream (with stream_options.include_usage for a final usage chunk; the first chunk has delta.role: "assistant"; : ping every 15 s; an error chunk then [DONE]), service_tier: "flex" (deferred), metadata, variables, agent_model, reasoning_effort, and version (a positive integer or numeric string pins a published version, "draft" runs the draft; anything else is 400 invalid_version, an unknown version 404 version_not_found). A stream is checked against the run caps and the agent quota before it opens (a plain JSON 429 with Retry-After). Ignored params are listed in X-Cognipeer-Ignored-Params.
  • Disconnect cancels the run, as with OpenAI.
  • Past the wait window, a non-streaming call answers 202 with { "id": "chatcmpl-…", "object": "chat.completion", "created": …, "model": "agent:support-bot", "choices": [], "cognipeer": { "status": "in_progress", "run_id": "run_…", "session_id": "…" } } and a Location header.

Every turn is recorded as a run with channel: "chat_completions".

A2A ​

POST /api/client/v1/a2a/{agentKey} is a JSON-RPC 2.0 endpoint for Agent2Agent clients; an agent is served once Publish via A2A is on. The agent card is at GET /api/client/v1/a2a/{agentKey}/.well-known/agent-card.json. The contextId is the session id and the task id is the run id (run_…); every A2A turn is a run with channel: "a2a".

Method
message/sendRuns the turn and answers a Task: completed, input-required (an approval or question waits, in metadata.pendingActions), canceled (the run was stopped while the call waited), failed (the run failed after it started, the agent quota refusal and a pending request included: the status message holds the error and metadata has errorType, errorCode and the error's other fields), or working when the wait window ended first (the run carries on; poll tasks/get). configuration.blocking: false (token route only) queues the run and answers submitted at once. A dropped connection does not cancel it.
message/streamThe same turn as Server-Sent Events, one JSON-RPC response per event: the Task (submitted), a working status event, the answer as artifact-update events (the first chunk creates the artifact with append: false, later chunks append, an empty last chunk has lastChunk: true), file and structured-answer artifacts, and a final status-update with final: true (completed, input-required, failed or canceled). A refusal before the stream opens (409, 429) is a plain JSON-RPC error. A client that disconnects does not cancel the task: it keeps running, and you can reattach with tasks/resubscribe or stop it with tasks/cancel.
tasks/resubscribeParams { "id": "run_…" }. Reattaches to a task's stream: the current Task first, then the status and artifact updates that follow, until the final status event. For a task that already finished, or that waits on input (input-required), the Task and its final status event arrive at once. One resubscribe stream follows a task for up to 60 minutes; if it is still running then, the stream closes without a final event and you resubscribe. An unknown id is -32001.
tasks/getThe Task for a run id.
tasks/cancelThe cancel standard: -32002 (TaskNotCancelable) when the task cannot be canceled (finished, or not running).

JSON-RPC errors are HTTP 200 with an error object: -32602 invalid params (including an unknown contextId), -32001 task not found, -32601 unknown method, -32002 the task cannot be canceled (it was -32004 before), -32010 the caller may not end a task that waits on a person. A refusal before the run exists (a running turn on the session, a concurrency limit, a spend limit) is a JSON-RPC error, and a session that the request created for it is removed again; a remote file uri that does not arrive within the outbound timeout is -32602 (attachment_unreachable).

On the public A2A route (/api/public/a2a/{tenantId}/{slug}) every caller is one anonymous identity, so a task and its session are bound to the caller that created them by a random nonce: the Task you get carries id: run_<runId>.<nonce> and contextId: <sessionId>.<nonce>, and you hand them back whole. tasks/get, tasks/cancel and tasks/resubscribe with a missing or wrong nonce (or an older task_… id) answer -32001, and message/send with a contextId that lacks the nonce answers -32602 (unknown contextId). A public conversation that was started before the nonce existed can no longer be reached from the public route. The variables of a public caller's data part are external content: they reach the run in the message, never in the system prompt. Walkthrough with examples: LiteLLM and A2A.

Variables ​

An agent can declare variables: named, typed values that a caller sends next to the message instead of writing them into free text. A variable is a text, number, integer, yes/no or JSON value; it can be required or optional, limited to a list of allowed values, and have a default. Declare them in Studio (Build → Variables) or as config.variables. They make an agent callable like a typed function: the caller knows what to send, and Cognipeer refuses a wrong call before the model is involved.

json
{
  "config": {
    "variables": [
      { "name": "customer_id", "label": "Customer", "type": "string", "required": true },
      { "name": "period", "type": "string", "enum": ["day", "week", "month"], "default": "week" },
      { "name": "include_closed", "type": "boolean", "default": false }
    ]
  }
}

A variable has a name (^[A-Za-z_][A-Za-z0-9_]{0,63}$, unique), a type (string, number, integer, boolean or json) and optionally label, description, enum (allowed values, for string, number and integer), required and default. An agent can declare at most 32 variables.

Send them ​

Send the values as variables next to input: on a run, a Responses request, a chat completions request, an A2A data part, a trigger or Run now on a trigger.

bash
curl -X POST "$CONSOLE_URL/api/client/v1/agents/support-bot/runs" \
  -H "Authorization: Bearer $COGNIPEER_API_TOKEN" -H "Content-Type: application/json" \
  -d '{ "input": "Summarise this customer", "variables": { "customer_id": "c-1042", "period": "month" }, "wait": 30 }'

Cognipeer checks them before the model is called, so a wrong call is a 400 and nothing is spent. A missing required variable, a wrong type, a value outside enum or a name the agent does not declare is 400 invalid_variables with every problem in errors: [{ "field", "message" }]:

json
{ "error": { "type": "invalid_request_error", "code": "invalid_variables", "param": "variables",
  "message": "Invalid variables - customer_id: Required",
  "errors": [ { "field": "customer_id", "message": "Required" } ] } }

Defaults fill in what is not sent (null counts as not sent). A text value can be up to 8 192 characters and all values together up to 32 KiB. The message itself may be empty, so a request can be variables alone.

What the agent receives ​

The agent gets the values in two places:

  • As {{variables.customer_id}} in the agent's instructions: wherever the author wrote that tag. An instruction that never mentions a variable is unchanged.
  • As a Variables block appended to the user message, so the model sees every value even when the instructions do not mention them:
text
Summarise this customer

Variables:
```json
{
  "customer_id": "c-1042",
  "period": "month",
  "include_closed": false
}
```

GET /agents/{key} publishes the declaration as variables_schema (a JSON Schema, null when there are none), so n8n, CI scripts, other agents and forms can learn what to send without reading the agent's configuration.

Values that arrive from outside, such as a webhook trigger's payload or the data part of an anonymous A2A caller, reach the model only in the Variables block and never fill {{variables.…}} in the instructions.

When to use variables ​

Use them when a program starts the run and knows exactly what the agent needs:

  • the runs API called from your own code, including wait and callback flows;
  • triggers: a schedule with fixed values, or a webhook trigger that maps fields of the event, like "pr_number": "{{payload.pull_request.number}}";
  • n8n or CI pipelines (n8n, GitHub Actions, Azure DevOps);
  • an agent that another agent calls as a tool (variables_schema can serve as that tool's parameter schema);
  • a form in front of the agent.

Chat is different ​

Chat clients (Open WebUI, any OpenAI-compatible chat, the portal chat, Studio's test chat) send only the person's text and never fill variables. Over the API's chat dialects (chat completions, Responses, A2A) a required variable without a default therefore makes every chat message fail (400 invalid_variables, a JSON-RPC -32602 over A2A). For an agent that is also used in chat, keep its variables optional, or give each one a default (a default is used whenever nothing is sent). Studio's test chat and the portals do not check; they run without the values.

On the API a variable with a default is added to the Variables block of every turn that does not send it, chat dialects included, so the model always sees it.

Across turns of a session ​

Variables belong to one turn (one run), not to the session:

  • The values of a turn are checked, filled with defaults and written into that turn's user message and that turn's {{variables.…}} tags. The session does not remember them.
  • The Variables block is part of the stored user message, so later turns still see it in the history.
  • A later turn that sends nothing renders only the defaults in {{variables.…}}: send the values again on every turn whose instructions need them. Resending them on every turn writes one Variables block per message into the history; for values the model only needs to read, send them once.
  • A turn that pauses for an approval and continues applies its own variables again.

Variables and runtime context ​

runtime_context.metadata is a different, looser channel: it fills top-level prompt tags such as {{tier}} for one call, is not declared, not validated and not part of variables_schema. Use variables for what the call must provide, runtime context for ambient values.

Structured output ​

Each dialect carries the schema in its own place; all of them use the same converter and validation.

DialectRequestResult
Runs APIresponse_formatoutput_parsed (object) and output_text (JSON string)
Responsestext.formatoutput_text (JSON), plus output_parsed / output_error
Chat completionsresponse_formatmessage.content is the JSON string
A2Athe agent's configured schemaa data artifact with the object
json
{ "type": "json_schema", "json_schema": { "name": "ticket", "strict": true, "schema": { "type": "object", "properties": { "category": { "type": "string" } }, "required": ["category"], "additionalProperties": false } } }

{ "type": "json_object" } asks for any JSON object. A request-level format replaces the agent's configured structured output for that turn, and it is kept if the turn pauses and resumes. A schema Cognipeer cannot convert (empty, or using unsupported keywords) is 400 invalid_response_format. A structured-output failure does not change the run's status: it still ends succeeded, and output_error says why validation failed, so check it before trusting output_parsed.

File outputs ​

An agent with a files bucket can create files for the caller without a sandbox. This is the Agent file outputs switch (Build → Files, attachments.outputs.enabled) and it is independent of uploads: an agent can write files while it takes none (attachments.enabled: false). The default is on when uploads are on and a bucket is set; with uploads off, outputs stay off until you turn them on. Two tools write files and are exempt from approvals:

Tool
session_files_create({ filename, content, mime_type? })Creates a file. Allowed types: .md .csv .txt .json .html .xml .yaml .yml; the name is sanitised; a clash becomes name-1.ext. What the agent writes is stored byte for byte (no text copy; a Markdown file keeps its own object).
session_files_append({ file_id, content })Appends to a file this agent created in this session.

session_files_list and read (the agent looks at the session's files) are offered when uploads or outputs are on and the session holds a file; with uploads off they see only the session's own files. Setting attachments.outputs.enabled: true without attachments.bucketKey is refused with 400 (field: attachments.bucketKey).

Limits (attachments.outputs): files per turn (default 10, max 20) and size per file (default 2 MB, max 10 MB). Created files are attached to the answer: output_files on the response and the run's result, file artifacts on A2A, and an agent.output_file session event. Each entry is { id, name, mime_type, size, download_url }, where download_url is /api/client/v1/agents/sessions/{id}/files/{fileId}/content relative to the Cognipeer origin. Agent outputs do not count towards the user's upload limit. GET /agents/{key} reports the effective state under attachments.outputs (enabled, max_files_per_turn, max_file_size_mb, types).

Cancel standard ​

One semantic behind four routes. All of them also work for an agent running a synchronous call.

Route
POST /api/client/v1/agents/runs/{runId}/cancelCanonical.
POST /api/client/v1/agents/sessions/{sessionId}/cancelCancels the session's active or paused run (Agent Sessions API).
POST /api/client/v1/responses/{id}/cancelOpenAI form; returns the response object.
A2A tasks/cancelJSON-RPC.
Run stateEffect
scheduled, queuedBecomes canceled at once.
runningcancel_requested_at is set; the executor stops at its next checkpoint (about a second) and the run ends canceled, keeping its partial answer.
requires_actionBecomes canceled at once: pending actions are cancelled and the conversation is released. A pause dropped by a new message (agent set to cancel pending requests), a session truncate or onTimeout: cancel ends its run the same way, with the callback and agent_run.canceled event.
Terminal409 agent_run_already_terminal on the runs API; the OpenAI route answers 200 with the final object.

Cancellation stops the agent loop from starting its next step; it does not interrupt a tool call or a model call already in flight. Older routes (/agents/conversations/{id}/cancel, /agents/responses/{id}/cancel) remain as aliases with the same behaviour.

Models list ​

GET /api/client/v1/models

data contains the project's models and its active agents, so OpenAI clients that discover models find agents by themselves. An agent entry:

json
{ "id": "agent:support-bot", "object": "model", "created": 1760000000, "owned_by": "cognipeer-agent", "name": "Support Bot", "description": "Customer support agent", "cognipeer": { "kind": "agent", "key": "support-bot" } }

The route admits a token that holds the models or the agents service (read), and each sees its own part: an agents-only token gets data with the agents, models: [] and no providers; a token with models only gets no agents; a token with neither is 403. GET /models/agent:support-bot retrieves one (it needs the agents service; a model id needs models read, so an agents-only token gets 403 for it). See Models.

Sessions ​

The conversation a response belongs to is a session, documented in full on the Agent Sessions API page:

Endpoint
POST /agents/sessionsStart an empty session (to upload files first, give it a budget, or tag it)
GET /agents/sessionsList the project's sessions
GET /agents/sessions/{sessionId}Runtime state: idle, running, requires_action or budget_paused; the pending requests; budget and spend
PATCH /agents/sessions/{sessionId}Set, raise or remove the spend budget; continues a session paused on it
DELETE /agents/sessions/{sessionId}Delete the session with its files, events and open requests
POST /agents/sessions/{sessionId}/cancelCancel the active or paused turn
GET /agents/sessions/{sessionId}/eventsThe event log (poll)
GET /agents/sessions/{sessionId}/events/streamThe event log as Server-Sent Events, resumable with Last-Event-ID
POST /agents/sessions/{sessionId}/actions/{actionId}Answer an approval or question
PUT, DELETE /agents/sessions/{sessionId}/messages/{messageId}/feedbackRate an answer or withdraw the rating
POST, GET /agents/sessions/{sessionId}/files, GET …/files/{fileId}/content, DELETE …/files/{fileId}Session files

Webhooks notify your service when a session goes idle, needs an answer, reaches its budget, or a run finishes; triggers start runs on a schedule, once, by hand or from an incoming webhook. The full request and response shapes are in the OpenAPI spec.

Agent features ​

Agents configured in the dashboard can include:

FeatureDescription
System PromptBase instructions for the agent
ToolsBound tools from the unified tool system or MCP servers
GuardrailsInput/output validation rules
Knowledge Engine ModulesRetrieval-augmented generation sources
Temperature / Top-P / Max TokensModel parameter overrides (configured on the agent, not per request)
Approvals & questionsPause a turn for a person: tool approvals, questions, page tools
Session filesDocuments and images attached to a session, stored in a bucket you choose; the agent can also create files
Variables and structured outputA typed request and a validated answer
Session budgetA cap on what a whole session may spend
CallbackDefault result URL for async runs
VersioningPublish and pin specific agent configurations

Errors ​

Runs API and session routes answer { "error": { "type", "message", "code", … } }. The OpenAI endpoints answer the OpenAI envelope { "error": { "message", "type", "param", "code" } }. A2A answers JSON-RPC errors.

StatusDescription
400Missing model (missing_model) or input, a body that is not a JSON object (invalid_json), a remote file that did not arrive in time (attachment_unreachable), agent is not active (agent_inactive), or an invalid field (invalid_budget, invalid_callback, invalid_variables, invalid_response_format, invalid_schedule, invalid_version, unsupported_content_part, unsupported_parameter, session_conflict, …)
401Invalid API token
402The session has reached its spend budget (budget_reached, with spent_usd and max_cost_usd)
403The agent takes no attachments (attachments_disabled), the token lacks the needed service (permission_error), or the session budget forbids the change (budget_override_forbidden)
404agent_not_found, version_not_found, run not found, model_not_found, previous_response_not_found, or session_id names no session of this agent (session_not_found)
409Another run is active for the session (agent_run_conflict), it waits for an approval or an answer (pending_action, with pending_action_ids), agent_run_already_terminal, or an Idempotency-Key was reused with a different request (idempotency_key_conflict)
429The tenant's spend limit is used up (spend_limit_exceeded), too many runs are active or queued (agent_run_concurrency_limit, Retry-After: 30), or the agent-run quota is used up (agent_quota_exceeded, Retry-After: 60)
500Internal error during agent execution
503The run a call waited on was ended elsewhere before it finished (agent_run_interrupted, retryable) or the permission engine could not decide (authorization_unavailable)
502The model provider rejected the credentials stored for it (provider_authentication_error): fix the provider, not your token

A turn that outlasts the wait window is not an error any more: the call answers 202 and the run continues (Background runs). A run that exceeds the run ceiling ends failed with max_duration_exceeded.

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