Agents API
List, retrieve, and invoke AI agents via the Console SDK. Agents are invoked through the runs API (client.agents.runs, canonical) or the OpenAI Responses format (client.agents.responses); client.agents.triggers starts them on a schedule, once, by hand or from a webhook.
What's new in 4.0.0
client.agents.runs (create, list, get with long-poll, cancel, wait, events, queue), client.agents.triggers, streaming and retrieve() on responses, structured output, variables, service_tier and metadata. client.agents.chat() is removed, and agents now run their published version by default. See the CHANGELOG for every breaking change.
Quick Start
import { ConsoleClient } from '@cognipeer/console-sdk';
const client = new ConsoleClient({
apiKey: process.env.COGNIPEER_API_KEY!,
});
// Invoke an agent (waits up to the Console's wait window)
const response = await client.agents.responses.create({
model: 'support-bot',
input: 'How do I reset my password?',
});
console.log(response.output_text);
// Or start a run and collect it later
const run = await client.agents.runs.create('support-bot', { input: 'Summarise open tickets' });
const done = await client.agents.runs.wait(run.id);
console.log(done.output_text);List Agents
Fetch all agents available to the current API token.
const agents = await client.agents.list();
console.log(agents);
// Filter by status
const activeAgents = await client.agents.list({ status: 'active' });Parameters
| Name | Type | Required | Description |
|---|---|---|---|
status | string | No | Filter: active, inactive, draft |
Return Type
interface AgentListItem {
key: string;
name: string;
description?: string;
config: {
modelKey: string;
temperature?: number;
topP?: number;
maxTokens?: number;
};
status: 'active' | 'inactive' | 'draft';
createdAt: string;
}Get Agent
Retrieve details for a specific agent.
const agent = await client.agents.get('support-bot');
console.log(agent.name, agent.config.modelKey);Parameters
| Name | Type | Required | Description |
|---|---|---|---|
agentKey | string | Yes | Unique agent key |
Variables and output: agent.variables_schema, agent.output_schema
The single-agent lookup (not list()) describes the agent as a typed function: variables_schema is the JSON Schema of the variables a caller may send (null when the agent declares none), output_schema the schema of its structured answer (null for a plain-text agent).
Files: agent.attachments
The single-agent lookup (not list()) also says whether the agent takes files, so a client can decide whether to show an attach button before it uploads anything:
const agent = await client.agents.get('support-bot');
if (agent.attachments?.enabled) {
console.log(agent.attachments.max_files, agent.attachments.max_file_size_mb, agent.attachments.allowed_mime_types);
if (!agent.attachments.accepts_images) console.log('Images would be replaced by a note: the model is text only');
}interface AgentAttachmentsInfo {
enabled: boolean; // files are on AND the agent's bucket can take a file now
max_files: number; // files one session holds (0 while off)
max_file_size_mb: number; // largest file (0 while off)
allowed_mime_types: string[]; // `image/*` wildcards allowed; empty = any
accepts_images: boolean; // the agent's model reads images
outputs: { // files the agent writes for the person (see below)
enabled: boolean; // outputs are on, a bucket is set and it can take a file now
max_files_per_turn: number;
max_file_size_mb: number;
types: string[]; // extensions it may write, without the dot
};
}outputs is independent of uploads: an agent with an attachments bucket can write files for the person while uploads (attachments.enabled) are off. By default outputs are on when uploads are on and a bucket is set, and stay off with uploads off until they are turned on. Files the agent wrote this turn come back as output_files on the Response ({ id, name, mime_type, size, download_url }, with file_path annotations on the message; download with sessions.files.content()). The agent can read session files (session_files_list / read) when uploads or outputs are on.
Where the files live (bucket, folder, retention) is the agent's Configure → Files setting in the Console, not something a caller chooses. Files are off by default for an agent and need a bucket; with files off (or on with no bucket) an upload is refused with 403 attachments_disabled. attachments is absent on a Console that predates session files. See Session files.
Variables
An agent can declare variables: named, typed values that a caller sends next to the message. A variable has a name and a type (string for text, number, integer, boolean for yes/no, or json), is required or optional, and may have a label, a list of allowed values and a default (Build → Variables in the Console; up to 32 per agent).
- They are checked before the model is called. A missing required value, an unknown name, a wrong type or a value outside the allowed ones is a
400 invalid_variableswitherrors: [{ field, message }], and nothing is spent. Defaults are applied; each text value is at most 8 KiB and all values together at most 32 KiB. - The agent sees them twice. Its instructions can use them as
{{variables.<name>}}, and every value is also added to the user message as aVariablesJSON block, so the model reads them even when the instructions do not mention them. - They are published.
agents.get(key).variables_schemais a JSON Schema of the agent's variables (nullwhen it has none), so n8n, CI scripts, other agents and forms know what to send.
const agent = await client.agents.get('report-bot');
agent.variables_schema; // { type: 'object', properties: { team: { type: 'string' }, ... }, required: ['team'] }
await client.agents.runs.create('report-bot', {
input: 'Weekly numbers', // the message
variables: { team: 'ops', region: 'EMEA' }, // the variables, next to it
});Best for programs and automation. Use variables for runs that a program starts: the runs API, triggers (a schedule trigger with fixed values, a webhook trigger that maps event fields into them, like {{payload.pull_request.number}}), n8n or CI pipelines, an agent that another agent calls as a tool, forms. variables is accepted by runs.create(), responses.create(), chat completions, A2A data parts and triggers.run().
Careful in chat. Chat clients (Open WebUI, other OpenAI-compatible apps, the portal chat UI) send only the person's text and never fill variables. A required variable without a default makes every chat message fail with 400 invalid_variables, so for an agent that is also used in chat keep its variables optional, or give each one a default.
Values belong to the turn that sends them. A follow-up turn of the same session sends them again (an optional one left out falls back to its default), and the Variables block of a turn stays in that turn's message in the session history, so sending the same values on every turn repeats the block there. Values that come from outside the caller's own request (a webhook delivery's payload, a public A2A caller's data part) are external content: they reach the model in the Variables block, never through {{variables.<name>}} in the instructions. The REST reference is Agents API → Variables.
Runs
client.agents.runs is the canonical, most complete surface: async-first, with scheduling, classes, callbacks, metadata and idempotency. The REST reference is the Agents API; walkthroughs are in Calling agents from other systems.
// Start now; answered later (a callback, or wait())
const run = await client.agents.runs.create('report-bot', {
input: 'Weekly numbers',
class: 'deferred', // low priority, own queue
metadata: { ticket: 'OPS-12' },
callback: { url: 'https://example.com/hooks/run', secret: process.env.CALLBACK_SECRET },
});
// run.status: 'queued' (HTTP 202). An Idempotency-Key is generated if you give none.
const done = await client.agents.runs.wait(run.id, { timeoutMs: 15 * 60_000 });
console.log(done.status, done.output_text, done.output_parsed);
// Hold the call up to 30 s: 200 with the finished run, or 202 with a running one
const quick = await client.agents.runs.create('support-bot', { input: 'Hi', wait: 30 });
// Start in an hour
await client.agents.runs.create('support-bot', { input: 'Check OPS-12', delay_seconds: 3600 },
{ idempotencyKey: 'followup-OPS-12' });| Method | |
|---|---|
runs.create(agentKey, body, options?) | Start a run. body: input, variables, session_id, version (number or 'draft'), class, run_at / delay_seconds, wait, metadata, callback, response_format, runtime_context, reasoning, agent_model, budget. options: idempotencyKey, prefer (the Prefer header), signal. |
runs.list(query?) | Newest first. Await for a page (data, has_more, getNextPage()), or for await over every run. Query: agent, status (one or an array), class, session_id, trigger_id, channel, metadata, created_after, created_before, limit, after. |
runs.get(id, { wait }) | One run. wait (seconds) long-polls: the Console answers when the run settles or the wait ends. |
runs.cancel(id) | The cancel standard. Cooperative: the returned run may still say running for about a second. |
runs.wait(id, options?) | Long-polls until the run is terminal or requires_action. waitSeconds (default 20) is one poll's length, pollIntervalMs the smallest gap between polls, timeoutMs throws AgentRunWaitTimeoutError, signal aborts. |
runs.events(id, query?) / runs.events.stream(id) | The session events of one run, as a page or live (SSE with resume). |
runs.queue() | Queue counts for the default and deferred classes. |
runs.resolveAction(runId, actionId, body) | Answer an approval or question of the run. |
runs.create with stream: true returns an async iterator of response.* events instead (the generated idempotency key applies to streams too); the run continues when the connection closes, unless on_disconnect: 'cancel'.
A2A message/stream runs the task on the same engine: a client disconnect does not cancel it, and tasks/resubscribe (params { id }) reattaches: the current Task first, then the status and artifact updates until the final status event (a task that already finished gets its Task and the final status event at once). tasks/cancel stops it.
The run object
type AgentRunStatus = 'scheduled' | 'queued' | 'running' | 'requires_action' | 'succeeded' | 'failed' | 'canceled';
interface AgentRun {
id: string; // "run_..."
object: 'agent.run';
status: AgentRunStatus;
class: 'default' | 'deferred';
agent: string;
version: number | null;
session_id: string;
channel: 'runs' | 'responses' | 'chat_completions' | 'a2a' | 'trigger';
trigger: 'request' | 'schedule' | 'once' | 'manual' | 'webhook'; // what started the run
trigger_id: string | null;
metadata: Record<string, string>;
stop_reason?: string | null;
result?: AgentResponse | null;
output_text?: string | null;
output_parsed?: unknown;
output_error?: string | null; // why the answer does not fit the schema
error?: { type: string; message: string | null } | null;
scheduled_for?: number | null;
created_at: number;
started_at?: number | null;
completed_at?: number | null;
detached_at?: number | null;
cancel_requested_at?: number | null;
max_duration_ms?: number | null;
callback?: { url: string; status: string | null; attempts: number; signed: boolean } | null;
}isAgentRunTerminal(run) is true for succeeded, failed and canceled; isAgentRunSettled(run) is also true for requires_action, which waits for a person (run.result.required_action.actions; answer with sessions.actions.resolve() or runs.resolveAction()).
Triggers
A trigger starts an agent on its own: on a schedule, once at a set time, by hand, or when an external system posts a webhook. An agent can have several triggers (a schedule trigger and a webhook trigger, say), and each trigger has one type, with the settings of that type in the sub-object named after it. A trigger saves a prompt (and variables). Every fire is an ordinary run (channel: 'trigger', runs.list({ trigger_id }) is the history), unattended: approvals follow the agent's unattended policy. Concepts: Triggers and Webhook triggers; REST reference: Triggers API.
type | Settings | Fires |
|---|---|---|
schedule | schedule: cron (5 fields), timezone (IANA, default UTC) | on every cron tick |
once | once: run_at (ISO 8601 or unix seconds, not in the past) or delay_seconds | once; run_at is returned as an ISO string |
manual | none | only with triggers.run() |
webhook | webhook: preset, auth, header_name, secret, events, filter, include_payload | when an authenticated delivery reaches the trigger's URL: Webhook triggers |
const trigger = await client.agents.triggers.create('report-bot', {
name: 'Weekday digest',
type: 'schedule',
schedule: { cron: '0 9 * * 1-5', timezone: 'Europe/Istanbul' },
// or type: 'once' with once: { run_at: '2026-12-01T09:00:00Z' } | once: { delay_seconds: 3600 }, or type: 'manual' (no sub-object)
prompt: 'Summarise yesterday', // required unless the agent has variables and `variables` gives them
variables: { team: 'ops' }, // values for the agent's variables
class: 'deferred', // 'default' | 'deferred'
version: 3, // pin a version; omitted / null = the published one
metadata: { source: 'trigger' }, // copied onto every run
callback: { url: 'https://example.com/hooks/digest', secret: process.env.DIGEST_SECRET }, // write-only secret
response_format: { type: 'json_object' },
});
trigger.id; // a bare id, no prefix
trigger.type; // 'schedule' | 'once' | 'manual' | 'webhook'
if (trigger.type === 'schedule') trigger.schedule.cron; // only the sub-object named after the type is present
trigger.next_fire_at; // unix seconds (null for manual, webhook and a finished once)
trigger.last_run_id; // "run_..." of the last fire that started a run
trigger.last_status; // 'started' | 'failed' | null (with `last_error`)
// An agent can have several triggers: add a webhook trigger next to the schedule one.
await client.agents.triggers.create('report-bot', {
name: 'On deploy',
type: 'webhook',
webhook: { preset: 'generic' },
prompt: 'Summarise the deploy',
});
await client.agents.triggers.list('report-bot'); // { object: 'list', data: AgentTrigger[], has_more: false }: both
await client.agents.triggers.get('report-bot', trigger.id);
await client.agents.triggers.update('report-bot', trigger.id, { enabled: false }); // PATCH: omitted fields stay
await client.agents.triggers.delete('report-bot', trigger.id); // { id, object: 'agent.trigger.deleted', deleted: true }Timestamps are unix seconds, except once.run_at (ISO). create() answers HTTP 201. To change the type of a trigger, or the settings of its type, update() takes type together with the sub-object. Errors: 400 invalid_trigger (error.response.error.errors lists { field, message }: a bad cron, timezone or type, a missing prompt, variables that do not fit the agent, an unknown version), 404 trigger_not_found, 404 agent_not_found.
Run now
const run = await client.agents.triggers.run(
'report-bot',
trigger.id,
{ variables: { team: 'sales' }, metadata: { requested_by: 'anil' } }, // merged over the trigger's variables / metadata
{ wait: 10, idempotencyKey: 'digest-2026-10-17' }, // idempotencyKey is generated when omitted
);
run.status; // 'succeeded' (HTTP 200) | 'queued' | 'running' (HTTP 202: never an error, follow it with runs.wait)wait holds the call up to that many seconds (capped by the Console's window); prefer: { wait, respondAsync } sends the Prefer header instead. Errors: 400 invalid_variables, invalid_metadata, agent_inactive; 404 trigger_not_found; 409 idempotency_key_conflict (the key was used by another request); 429 with a Retry-After header and agent_run_concurrency_limit, spend_limit_exceeded or agent_quota_exceeded.
Webhook triggers
A webhook trigger has a public URL. A sender posts JSON to it, the Console checks the delivery's credentials, applies the trigger's events and filter, builds the turn from the trigger's prompt and variables (templates over the event) and starts a run. Senders need no API token.
const trigger = await client.agents.triggers.create('pr-reviewer', {
name: 'Review pull requests',
type: 'webhook',
webhook: {
preset: 'github', // github | gitlab | azure_devops | generic
events: ['pull_request'], // event names to accept; empty / omitted = all
filter: [ // all must match
{ path: 'payload.action', op: 'in', value: ['opened', 'synchronize'] },
{ path: 'payload.pull_request.draft', op: 'eq', value: false },
],
include_payload: true, // default: append the event payload (JSON) to the message
},
prompt: 'Review pull request #{{payload.pull_request.number}} ({{payload.pull_request.html_url}})',
});
if (trigger.type === 'webhook') {
trigger.webhook.url; // the URL to give the sender
trigger.webhook.secret; // only in the answer that created the trigger (or gave it a new secret): shown once
// every later read: { url, preset, auth, header_name, secret_hint, secret_source, previous_secret_valid_until, events, filter, include_payload }
}The secret is generated by the Console and shown once, in webhook.secret of the answer that created the trigger; afterwards only webhook.secret_hint (its last 4 characters). With standard_webhooks the sender generates it: pass the sender's whsec_... as webhook.secret. (AgentTriggerWithSecret is the type of a webhook trigger that carries its secret.)
| Preset | auth (first = default) | The sender sends | Event name | Delivery id |
|---|---|---|---|---|
github | github_signature | X-Hub-Signature-256: sha256=<hex HMAC-SHA256(secret, body)> | X-GitHub-Event | X-GitHub-Delivery |
gitlab | gitlab_token, standard_webhooks | X-Gitlab-Token: <secret> | payload object_kind, event_name, or X-Gitlab-Event | webhook-id or Idempotency-Key |
azure_devops | basic, header | Basic auth with the secret as the password, or header_name (default x-cognipeer-token) | payload eventType | payload id |
generic | bearer, signature, header, standard_webhooks | Authorization: Bearer <secret>, a signature (below), or header_name | payload event or type, or X-Cognipeer-Event | X-Cognipeer-Event-Id, webhook-id or Idempotency-Key |
Prompt and variables are templates (Mustache) over payload, headers, event, delivery_id, preset, received_at, trigger and agent. Every value taken from the event is inserted as JSON text (a string comes quoted), and the turn tells the agent that everything from the event is external data. A variable whose value is exactly one tag ("{{payload.number}}") keeps the value's type. A webhook trigger needs a prompt unless it includes the payload or gives variables. filter rules read payload.*, headers.* (an allow-list per preset), event; ops: eq, neq, in, not_in, exists, not_exists, contains, starts_with, glob; * in a path matches every list item. The events list is a convenience filter on a name the sender (or its header) supplies: conditions that matter belong in payload.* filter rules. Full reference: Webhook triggers.
Sign a delivery (auth signature, preset generic) with signTriggerWebhook, exported from the package root (it needs no Node.js APIs):
import { signTriggerWebhook } from '@cognipeer/console-sdk';
const body = JSON.stringify({ event: 'deploy.failed', service: 'api' });
await fetch(url, { // url and secret: `trigger.webhook.url` / `.secret` of the answer that created the trigger
method: 'POST',
headers: {
'content-type': 'application/json',
...signTriggerWebhook(secret, body, { eventId: 'deploy-42' }),
},
body, // the exact string that was signed
});It returns x-cognipeer-signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<body>")> (accepted within 5 minutes of the Console's clock), x-cognipeer-event-id (yours, or a random one: the Console treats the same id with the same body as a duplicate and starts no second run, so reuse yours when retrying) and, with { event }, x-cognipeer-event. Options: { timestamp?, eventId?, event? }.
Try it without a sender. On a webhook trigger run() takes a sample payload and headers and builds the turn the way a delivery would (the events and filter checks are not applied, and the sample's own text is never treated as a template). With dry_run: true nothing starts: it answers an AgentTriggerDryRun.
const dry = await client.agents.triggers.run('pr-reviewer', trigger.id, {
payload: { action: 'opened', pull_request: { number: 7, draft: false } },
headers: { 'x-github-event': 'pull_request' },
dry_run: true,
});
dry.matched; // does it pass `events` and `filter`? (`dry.reason` says why not)
dry.prompt; // the message the run would get
dry.variables; // the resolved variables; `dry.errors` lists `{ field, message }` when the turn cannot be builtRotate the secret with rotateWebhookSecret; grace_seconds (0 to 86400, default 0) keeps the current secret accepted that long, so senders can switch over. Standard Webhooks triggers pass the sender's new secret.
const rotated = await client.agents.triggers.rotateWebhookSecret('pr-reviewer', trigger.id, { grace_seconds: 3600 });
rotated.secret; // the new secret, shown once (not returned with standard_webhooks)
rotated.previous_valid_until; // unix seconds the old one is accepted untilThe delivery log shows what became of each request to the URL (kept 7 days), never its payload:
const page = await client.agents.triggers.deliveries('pr-reviewer', trigger.id, { limit: 50 });
for (const d of page.data) console.log(d.received_at, d.outcome, d.http_status, d.event, d.run_id, d.reason);
if (page.has_more) await client.agents.triggers.deliveries('pr-reviewer', trigger.id, { before: page.data.at(-1)!.id });outcome is accepted (a run started), duplicate, filtered, ignored (a ping, a test, a disabled trigger), unauthorized, rejected (a rate or run limit) or failed; reason is a fixed text such as signature mismatch or event "x" is not selected. Errors: 400 trigger_not_webhook (rotateWebhookSecret on a trigger of another type), 400 invalid_limit.
Webhook subscriptions (client.webhooks) receive trigger.fired (data: triggerId, agentKey, trigger (what started the fire: schedule | once | manual | webhook), runId, and event for a webhook delivery) and trigger.failed (triggerId, agentKey, trigger, event?, reason; sent at most once per trigger and reason per hour).
Invoke Agent (Responses API)
Use client.agents.responses.create() for the OpenAI Responses shape. It posts to POST /api/client/v1/responses and runs the agent's published version (the draft only if it was never published; pin with version: 3, or run the draft with version: 'draft').
const response = await client.agents.responses.create({
model: 'support-bot',
input: 'What are your business hours?',
});
console.log(response.id); // "resp_<runId>"
console.log(response.output_text); // the answer
console.log(response.usage); // token usage
console.log(response.conversation?.id, response.cognipeer?.run_id);Parameters
| Name | Type | Required | Description |
|---|---|---|---|
model | string | Yes | Agent key (or agent:<key>) |
input | string | ResponseInputItem[] | Yes | User message, or message items (see Input parts) |
previous_response_id | string | No | Continue a conversation (resp_... or run_...) |
session_id | string | No | Continue a session (for example one from sessions.create()); same session as previous_response_id |
conversation | string | { id } | No | OpenAI-style alias of session_id |
version | number | 'draft' | No | A published version, or the draft |
stream | boolean | No | true returns an async iterator of response.* events (below) |
background | boolean | No | Return at once with status: 'queued'; the turn runs in the background |
text | { format } | No | Structured output: { type: 'json_schema', name, schema, strict }, { type: 'json_object' } or { type: 'text' } |
metadata | Record<string, string> | No | Up to 16 pairs, stored on the run |
service_tier | string | No | 'flex' runs in the deferred class |
variables | object | No | Values for the agent's variables, checked before the model is called (400 invalid_variables) |
runtime_context | RuntimeContext | No | Headers / metadata forwarded to the agent's downstream tool, MCP and connected-agent calls |
agent_model | string | No | Which of the agent's models answers (a key from agent.models) |
reasoning_effort / reasoning | ReasoningEffort / { effort } | No | Reasoning effort. ReasoningEffort is 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' |
include_reasoning | boolean | No | false leaves the reasoning item out of this response |
budget | { max_cost_usd, on_reach? } | No | Spend cap for the conversation this request creates. See Session budget |
callback_url / callback_secret | string | No | Async runs only |
instructions, temperature, top_p and max_output_tokens are no longer part of the agent request type: the agent's own configuration applies (the Console ignores them and lists them in X-Cognipeer-Ignored-Params).
A call that is still running when the Console's wait window ends, or that asked for background, answers HTTP 202; the SDK returns the AgentResponse with status: 'queued' | 'in_progress' and the run to follow in cognipeer.run_id. It is never an error. Use isAgentResponseFinal(response) to tell:
let r = await client.agents.responses.create({ model: 'research-agent', input: 'Compare three vendors', background: true });
while (!isAgentResponseFinal(r)) {
await new Promise((res) => setTimeout(res, 3000));
r = await client.agents.responses.retrieve(r.id);
}
await client.agents.responses.cancel(r.id); // POST /responses/{id}/cancel, returns the AgentResponseretrieve() reports background: true for a run started with background: true, also when it was started with stream: true.
Streaming
const stream = await client.agents.responses.create({ model: 'support-bot', input: 'Draft an update', stream: true });
for await (const event of stream) {
if (event.type === 'response.output_text.delta') process.stdout.write(event.delta);
if (event.type === 'response.completed') console.log('\n', event.response.id);
}Events are typed (AgentResponseStreamEvent, isResponseStreamEvent): response.created, response.in_progress, response.output_item.added, response.content_part.added, response.output_text.delta, response.output_text.done, response.content_part.done, response.output_item.done, reasoning-summary events, response.completed, response.failed, response.incomplete and error. Breaking the loop closes the connection, which cancels the turn unless you sent background: true.
Structured output
const res = await client.agents.responses.create({
model: 'ticket-triage',
input: "I was charged twice and the invoice page throws a 500",
text: { format: { type: 'json_schema', name: 'ticket', strict: true, schema: {
type: 'object', additionalProperties: false, required: ['category', 'urgency'],
properties: { category: { type: 'string' }, urgency: { type: 'integer' } },
} } },
});
console.log(res.output_parsed); // the validated object
console.log(res.output_error); // why validation failed, when it didMulti-Turn Conversations
Pass previous_response_id to continue a conversation:
const first = await client.agents.responses.create({
model: 'support-bot',
input: 'I have a billing question',
});
const followUp = await client.agents.responses.create({
model: 'support-bot',
input: 'Can you show me the pricing page?',
previous_response_id: first.id,
});session_id (alias conversation, a string or { id }) names the same conversation as previous_response_id in the session's own words. Give one, or several that agree: session_id or conversation naming a different session than previous_response_id is a 400 session_conflict (session_id and conversation disagreeing with each other is a plain 400 invalid_request), and a session of another agent or project is a 404 session_not_found. It is what you use to continue a session you started with sessions.create(), because that one has no response yet. The session id is response.conversation.id (or cognipeer.session_id); response ids are run-scoped (resp_<runId>), so do not strip the prefix to get it.
const session = await client.agents.sessions.create({ agent: 'support-bot' });
const reply = await client.agents.responses.create({
model: 'support-bot',
session_id: session.id,
input: 'I have a billing question',
});Input parts: files and images
input can be an array of message items whose content mixes text, files and images:
interface ResponseInputItem {
role: 'user' | 'system' | 'assistant';
content: string | Array<
| { type: 'input_text'; text: string }
| { type: 'input_file'; file_id?: string; file_data?: string; file_url?: string; filename?: string }
| { type: 'input_image'; file_id?: string; image_url?: string | { url: string } }
>;
}file_idnames a file already uploaded to the conversation withsessions.files.upload(). The request must name that conversation (session_id,conversationorprevious_response_id).file_datais inline base64 or adata:URL, used when there is nofile_id; the Console stores it as a session file (filenamenames it).file_urlis anhttp(s)URL the Console fetches (public hosts only).input_image.image_urlis adata:URL or anhttp(s)URL the Console fetches (public hosts only).- Sending files to an agent that takes none is a
403 attachments_disabled.
Response Type
interface AgentResponse {
id: string; // "resp_<runId>"
object: 'response';
model: string;
status: 'queued' | 'in_progress' | 'completed' | 'incomplete' | 'failed' | 'cancelled' | 'requires_action';
output: ResponseOutputMessage[];
output_text?: string; // the answer text
output_parsed?: unknown; // structured output, validated
output_error?: string; // why structured output failed validation
output_files?: Array<{ id: string; name: string; mime_type: string; size: number; download_url: string }>;
incomplete_details?: { reason: string } | null;
stop_reason?: string; // 'completed' | 'limit' | 'cancelled' | 'requires_action' | ...
required_action?: { type: 'agent_actions'; actions: PendingAction[] }; // when status is 'requires_action'
error?: { code: string; message: string } | null; // when status is 'failed'
usage: { input_tokens: number; output_tokens: number; total_tokens: number } | null; // null before there is an answer
created_at: number; // unix seconds
metadata?: Record<string, string>;
service_tier?: string;
background?: boolean;
previous_response_id: string | null;
conversation?: { id: string };
cognipeer?: { run_id: string; session_id: string; agent_model?: string };
version: number | null; // published version used
}An exhaustive switch over status needs every case. incomplete: a run limit or the session budget ended the turn before a final answer (see stop_reason). requires_action: the turn paused on a tool approval or a question; required_action.actions lists what to answer with sessions.actions.resolve().
Chat completions and models
client.chat.completions.create({ model: 'agent:support-bot', … }) runs an agent through chat completions; new request fields are response_format, stream_options, service_tier, metadata, variables and conversation_id, with per-call { sessionId, idempotencyKey, signal } (see Chat). client.models.list() returns the project's models and its active agents (id: 'agent:<key>', cognipeer.kind === 'agent'; isAgentModelEntry(entry) narrows).
Error codes
Errors are CognipeerAPIErrors; branch on errorCode (the body's error.code) with isAgentRunErrorCode:
import { AgentRunErrorCodes, isAgentRunErrorCode } from '@cognipeer/console-sdk';
try {
await client.agents.runs.create('research-agent', { input: '...', session_id: sessionId });
} catch (error) {
if (isAgentRunErrorCode(error, AgentRunErrorCodes.Conflict)) {
// 409: a run is already active on this session
} else if (isAgentRunErrorCode(error, AgentRunErrorCodes.ConcurrencyLimit)) {
// 429: too many active runs for this tenant: back off, or use class: 'deferred'
} else if (isAgentRunErrorCode(error, AgentRunErrorCodes.InvalidVariables)) {
// 400: `variables` do not fit agent.variables_schema (or a chat call lacks a required one); error.response.error.errors lists the fields
}
}errorCode | Status | Meaning |
|---|---|---|
agent_run_conflict | 409 | A run is already active on this session |
agent_run_concurrency_limit | 429 | Tenant's (or project's) active-run limit reached, or the deferred queue is full |
spend_limit_exceeded / agent_quota_exceeded | 429 | A spend limit or the plan's agent quota is used up (Retry-After); the same on triggers.run() |
agent_inactive | 400 | The agent (of a run or a trigger) is not active |
invalid_trigger | 400 | A trigger write was refused; the error body lists { field, message } |
trigger_not_found / trigger_not_webhook | 404 / 400 | No such trigger; rotateWebhookSecret() on a trigger that is not a webhook trigger |
invalid_payload / invalid_headers | 400 | The sample payload of triggers.run() is not a JSON object or array / headers is not an object of strings |
sandbox_secrets_unreadable | 409 | Saving an agent whose stored sandbox secrets cannot be decrypted (the encryption key changed) with masked values mixed with new ones; enter every secret again to replace them. Until then reads of the agent's sandbox config carry sandbox.secretsUnreadable: true with an empty secrets list, and the sandbox tools run without secrets and say so in their result |
idempotency_key_conflict | 409 | Idempotency-Key reused with a different request |
agent_run_already_terminal | 409 | cancel() on a finished run |
invalid_variables | 400 | variables do not fit the agent's variables_schema: a required one is missing (also on a chat call, which never sends them), a wrong type, a value outside the allowed ones (errors: [{ field, message }]) |
invalid_response_format | 400 | The response_format / text.format cannot be used |
A turn that outlasts the wait window is a 202 now, not a 504: the codes timeout, idempotency_key_sync_not_supported and agent_background_disabled are gone. Session, approval, file and budget codes (session_not_found, action_not_pending, file_too_large, budget_reached, …) are listed on Agent error codes.
Verifying Callbacks (Node.js)
When an async run finishes, the Console POSTs JSON to the run's callback URL with:
X-Cognipeer-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>X-Cognipeer-Event: agent_run.succeeded | agent_run.failed | agent_run.canceled | agent_run.requires_actionX-Cognipeer-Event-Id— stable per run + event; deliveries are retried, so dedupe on it
verifyWebhook (alias: verifyAgentRunCallback) lives in the Node-only @cognipeer/console-sdk/webhooks entry point (it uses node:crypto, which the browser-safe main entry avoids). Webhook subscriptions (client.webhooks) are signed with the same scheme. Always verify the raw request body:
import express from 'express';
import { verifyWebhook } from '@cognipeer/console-sdk/webhooks';
import type { AgentRunCallbackEvent } from '@cognipeer/console-sdk';
app.post('/hooks/agent-run', express.raw({ type: 'application/json' }), (req, res) => {
const ok = verifyWebhook({
rawBody: req.body, // Buffer
signatureHeader: req.get('X-Cognipeer-Signature'),
secret: process.env.AGENT_CALLBACK_SECRET!,
toleranceSeconds: 300, // default
});
if (!ok) return res.sendStatus(400);
const event = JSON.parse(req.body.toString('utf8')) as AgentRunCallbackEvent;
// event.event === 'agent_run.succeeded' → event.data.result
res.sendStatus(204);
});The callback body is an AgentRunCallbackEvent: { id, event, createdAt, runId, sessionId, conversationId, data }, where data is { result } on success and on requires_action (the result carries required_action), { errorReason, message? } on failure and {} on cancel. The run's status, class and metadata are not in it: read them with runs.get(runId). Callbacks fire only for async runs. For the full signature scheme, retries and troubleshooting see Webhooks.
Sessions, approvals, events, files and webhooks
A turn can pause for a tool approval or a question (status: 'requires_action', or a run in requires_action). Everything around a conversation's runtime lives under client.agents.sessions, and event subscriptions under client.webhooks:
| You want to... | Call | Page |
|---|---|---|
| Start a session without sending a message, list, read, update the budget of, cancel or delete sessions | sessions.create / list / get / update / cancel / delete | Agent sessions |
| Give the agent a file before or between messages, read it back | sessions.files.upload / list / content / contentStream / delete | Session files |
| Answer a tool approval or a question | sessions.actions.list / resolve | Approvals & questions |
| Page or follow the append-only event log | sessions.events.list / stream | Session events |
| Get called when a session idles, needs an answer, hits its budget, a run finishes or a trigger fires | webhooks.* and verifyWebhook | Webhooks |
| Branch on an error | errorCode, AgentActionErrorCodes | Agent error codes |
Answering an approval is the Console's agent.approve permission (the person who started the session always may); a question follows session ownership. Managing webhooks is the Console's webhooks permission: webhooks.read lists endpoints and deliveries (with each URL's userinfo and query string removed, https://host/path?…), webhooks.admin changes anything and sees the full URL. A call without the permission answers 403 (forbidden, with a decisionId).
Migrating from 3.x
| 3.x | 4.0 |
|---|---|
client.agents.chat(key, { message }) | client.agents.responses.create({ model: key, input: message }), then res.output_text |
responses.create({ background: true }) returned an AgentRun | Returns an AgentResponse (status: 'queued'); follow cognipeer.run_id with runs.wait(), or start with runs.create() |
| Draft agent by default | Published by default; version: 'draft' for the draft |
res.id minus resp_ was the session id | Use res.conversation.id |
responses.cancel() returned { cancelled, run_ids } | Returns the AgentResponse; sessions.cancel() still returns the cancel result |
AgentRunErrorCodes.SyncTimeout, agent_background_disabled | Removed; a slow turn is a 202 |
schedule.fired / schedule.failed webhook events | trigger.fired / trigger.failed |
See Also
- Agent Sessions guide
- Agents API (Gateway)
- Calling agents from other systems
- MCP API — MCP server tools; tools are bound to agents with
toolBindings - Client Reference

