Cadenya API usage
Overview
- Base URL
https://api.cadenya.com, every route under/v1. OpenAPI 3.1 spec:https://openapi.cadenya.com/api-spec.yml. Reference pages:https://cadenya.com/docs/api-reference. - JSON in and out, camelCase field names, gRPC-transcoded: every error is a
google.rpc.Status, every list is{ items, pagination }, enums areSCREAMING_SNAKEstrings with a type prefix (STATE_PUBLISHED,OBJECTIVE_STATE_WAITING). - Almost everything lives under
/v1/workspaces/{workspaceId}/…. Account-level routes:GET /v1/whoami,GET /v1/workspaces,GET /v1/account,POST /v1/account:rotateWebhookSigningKey,/v1/account/api_keys…,/v1/account/trusted_endpoints…, and/v1/account/workspaces…(admin role only; API keys cannot call these). - The mental model: a Tool Set syncs tools from an MCP server, OpenAPI spec, or HTTP API (or is Bare and waits for your app), and may only call hosts on the account's trusted endpoints; an Agent has variations (model, prompt, assigned Tool Sets, sub-agents, agent pools, memory layers); an objective runs a variation against a message and emits events; you approve tool calls,
continuethe conversation, and submit feedback.
Account and API key
- A person creates the account at https://app.cadenya.com/signup, and the Free plan needs no card. When a call fails for lack of a key, give your user that link.
- The API keys page, https://app.cadenya.com/account/apiKeys, lists the account's keys. Sign-up creates a default key with the external ID
defaultthat reaches every workspace (GET /v1/account/api_keys/external_id:defaultreads it). - Set the key as
CADENYA_API_KEY.GET /v1/whoamichecks it and returns the default workspace asdefaultWorkspace.id, the value forCADENYA_WORKSPACE_ID. - From a terminal,
cadenya auth loginsigns in through the browser with a one-time code (RFC 8628 device flow). Seecadenya-cli. - Keep Tool Sets, Agents, variations, memory layers and Widgets as YAML files in
.cadenya/next to acadenya.yaml, and apply them withcadenya config applyaftercadenya config plan(format, GitHub Action). That keeps the setup in the repository instead of in a one-off provisioning script.
Authentication and scopes
Authorization: Bearer <api key>
- API keys are JWTs (HS256, no expiry) that belong to the account. Create one with
POST /v1/account/api_keys(reference), assigned to workspaces withspec.workspaceAssignmentsor to every workspace withspec.allWorkspaces: true. The raw token isspec.tokenin the create and rotate responses, andPOST /v1/account/api_keys/{id}:revealreturns it again. Change the workspaces with:addWorkspaceand:removeWorkspace; revoke with:disableor:rotate. - The workspace is not in the token. A key reaches the workspaces assigned to it, or every workspace when
spec.allWorkspacesis true, as for the default key. Using a key against another workspace is 403WORKSPACE_ACCESS_DENIEDwithmetadata.workspace_id, never 404. - Credential failures are HTTP 403 with code 7, not 401: missing header, malformed token, bad signature, disabled key (
ErrorInfo.reasonisAUTH_TOKEN_INVALIDorAPI_KEY_DISABLED). Two exceptions return 401: the SSE stream endpoints, and the key of a temporary workspace that has been claimed (TEMPORARY_WORKSPACE_CLAIMED). For all of them, the fix is a key from https://app.cadenya.com/account/apiKeys. - Scopes are
resource:readorresource:managestrings on the key (spec.permissions, up to 16):agents,agent_pools,models,objectives,tools,memory,api_keys,workspaces,widgets,widget_sessions,tenants,endpoints(trusted endpoints), plus manage-onlysecretsandaccount, or*.manageimpliesread, andapi_keys:adminimpliesapi_keys:manage: it is needed to create or change a key that reaches every workspace and to manage keys that other members created (API_KEY_NOT_OWNED). Models and AI provider keys usemodels:*(swapping a model on variations takesagents:manage), uploads useobjectives:*, and workspace secret endpoints (even GET) needsecrets:manage, while Tool Set secrets usetools:*. A key cannot be grantedtools:managewithoutsecrets:manage(scope "tools:manage" cannot be granted without "secrets:manage"), because Tool Set requests resolve workspace secrets. A missing scope is 403SCOPE_MISSINGwithmetadata.required_scope. Keys can only mint or rotate keys with scopes and workspaces they hold (SCOPE_NOT_HELD,WORKSPACE_NOT_HELD).
IDs and external IDs
- IDs are
<prefix>_<ULID>:workspace_,agent_,agentvar_,apool_(agent pool),as_(schedule),toolset_,tool_,toolsecret_,wsecret_,te_(trusted endpoint),memlyr_,mementry_,obj_,objevt_,objwin_,objqa_(queued action),toolcall_,objfb_,apikey_,aipk_,model_,tenant_,subj_,wgt_,wsess_,upload_,whkdlv_(webhook delivery). - Set
metadata.externalId(≤64 chars, unique per parent) on create, then use it anywhere the API takes that resource's ID: path segments including{workspaceId}, body references such asagentId,toolSetIdandmemoryLayerId, and list filters (agent pool references are the exception). A bare value that does not start with the resource's own prefix is treated as an external ID; writeexternal_id:<value>to force the lookup when your IDs look like Cadenya's. - Unresolved path segment or objective
agentId: 404not found. Unresolved assignment target or list filter: 400 with afieldViolationsentry. - Objects carry
metadata(id,accountId,workspaceId,name,externalId,labels,profileId,createdAt,updatedAt), user-ownedspec, read-onlyinfo(populated on lists only withincludeInfo=true), and often a read-onlystate. Operations (objectives, events, tool calls, feedback, widget sessions) useOperationMetadata, which has noname. - Create bodies take only
metadata.name(required, ≤64),metadata.externalId,metadata.labels(≤10 pairs, K8s-shaped keys, values ≤63), andspec. Sending a read-only field (metadata.id,createdAt,state,info) is a 400 from the transcoder.
Request conventions
- Discriminated unions carry
typenaming the populated key:{"type": "mcp", "mcp": {…}},{"type": "toolSetId", "toolSetId": "…"}, eventdata.type. Both keys must agree. - Custom verbs are
POST …/{id}:verbwith a{}body unless noted:agents/{id}:publish|unpublish|archive|unarchive,agent_pools/{id}:activate|deactivate|archive|unarchive,agents/{agentId}/schedules/{id}:pause|resume|archive,agents/{agentId}/variations/{id}:addAssignment|removeAssignment|addMemoryLayer|updateMemoryLayer|removeMemoryLayer,api_keys/{id}:rotate|disable|enable,models/{id}:enable|disable,models:swapModelOnVariations({"modelSwaps": [{"currentModelId": "…", "nextModelId": "…"}]}),objectives/{id}:continue|interrupt|cancel|compact,objectives/{id}/tool_calls/{toolCallId}:approve|deny|setContent,objectives/{id}/queued_actions/{id}:remove,tool_sets/{id}:archive|unarchive,tool_sets/{toolSetId}/tools/{id}:omit|restore,widgets/{id}:archive|unarchive,widget_sessions/{id}:revoke,account/trusted_endpoints:verify. - Durations are strings in seconds (
"3600s"), not integers, even where the spec saysinteger.int64fields such assizeBytesare JSON strings. - Secrets are referenced from Tool Set headers and base URLs as Liquid output
{{ secrets.NAME }}(case-insensitive name).${NAME}is rejected withlegacy dollar references are not supported, even where an OpenAPI field description shows it. Resolution order, later wins: workspace secret, Tool Set secret, objective secret. Pinned parameters interpolate as{{ pinnedParameters.key }}, notpinned_parameters. - There is no general idempotency key and no dry-run mode. The one idempotent create is
POST …/objectives:stream, keyed onmetadata.externalId. - Requests are rate limited per account; objective create, continue and compact, create-and-stream, Tool Set create and update,
models:swapModelOnVariations, andtrusted_endpoints:verifyhave a much smaller budget than the rest. A 429 from the limiter carriesRetryInfoand aretry-afterheader; wait that long and retry.
Updates (PATCH with a field mask)
PATCH /v1/workspaces/development/agents/support-triager
{"metadata": {"name": "Support Triager v2"}, "updateMask": "metadata.name"}
updateMaskis a comma-separated string of camelCase dotted paths (metadata.name,spec.description,metadata.labels). Only masked paths change.- Maps and lists (
metadata.labels,spec.overlays,spec.permissions,spec.assignments,spec.memoryLayerAssignments) are replaced whole; a masked empty collection clears it. Map-key paths (metadata.labels.env) are invalid. - Without a mask the server merges: set scalars overwrite, unset scalars are kept, and any collection you include replaces the stored one. You cannot clear a scalar without a mask. Masking
metadatawhile omittingexternalIdclears the external ID, so round-trip the whole metadata object. - An unknown path is 400
invalid field mask. When a body carriesmetadata, includemetadata.name; when it carries a variation'sspec.modelConfig, includemodelId.
Lists, pagination, filters
GET /v1/workspaces/development/agents?limit=50&labels=env%3Dprod%2Cteam%3Dai&state=STATE_PUBLISHED&sortOrder=desc
- Response
{"items": [...], "pagination": {"nextCursor": "…"}}. Fetch the next page withcursor=<nextCursor>; a missing or empty cursor means the last page. There is no total count.GET /v1/workspacesitems carrystatus(STATUS_ENABLED) rather thanstate, and list only the workspaces the key reaches. limitis 1 to 100, default 20.sortOrderisascordesc(by creation time; by sequence for events). Any other value is a 400.labels=k=v,k2=v2requires every pair to match exactly (AND).prefixis a case-insensitive name prefix (on models it also matches the external ID or ID).queryis a case-insensitive name substring. State filters take the enum string. Agents, agent pools and Tool Sets hide archived ones by default; passstate=STATE_ARCHIVED(pools:AGENT_POOL_STATE_ARCHIVED) to see them.
Errors
Every error body is a google.rpc.Status:
{"code": 3, "message": "validation failed", "details": [{
"@type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [{"field": "spec.model_config.model_id", "description": "model_id must be a reference key in the form <provider-key-slug>.<model-slug> or a canonical model_ ID"}]}]}
| HTTP | code |
Meaning | Typical details |
|---|---|---|---|
| 400 | 3 INVALID_ARGUMENT |
validation (message validation failed), bad mask, unknown JSON field, unresolved filter or assignment target, untrusted Tool Set host, objective on an unpublished Agent (agent must be published to create an objective), continue on a non-waiting objective without enqueue |
BadRequest.fieldViolations[].field (usually the proto snake_case path) |
| 400 | 9 FAILED_PRECONDITION |
approve or deny a call that is not waiting, :interrupt on an objective that is not running, deleting an assigned agent pool, locked account, plan lacks the feature, unclaimed temporary workspace |
message; ErrorInfo.reason ENTITLEMENT_REQUIRED or REQUIRES_CLAIM with metadata.feature |
| 403 | 7 PERMISSION_DENIED |
auth, scope, workspace access, archived workspace, admin role | ErrorInfo.reason: AUTH_TOKEN_INVALID, API_KEY_DISABLED, SCOPE_MISSING, SCOPE_NOT_HELD, WORKSPACE_ACCESS_DENIED, WORKSPACE_NOT_HELD, API_KEY_NOT_OWNED, WORKSPACE_ARCHIVED, ADMIN_ROLE_REQUIRED |
| 404 | 5 NOT_FOUND |
ID or external ID does not resolve in this workspace | none |
| 409 | 6 ALREADY_EXISTS |
duplicate external ID or trusted host (resource with the same identifier already exists); repeated :addAssignment (tool set … already assigned to variation) or :addMemoryLayer (memory layer … is already attached to variation) |
none |
| 429 | 8 RESOURCE_EXHAUSTED |
rate limit, or an account-wide plan limit | rate limit: RetryInfo and retry-after; plan limit: ErrorInfo.reason ENTITLEMENT_LIMIT_REACHED with metadata.feature, limit, usage (upgrade, do not retry) |
Workflow: first integration
Request bodies for every resource are in references/resources.md. Copy this checklist and verify each step before the next:
-
GET /v1/whoamireturnsdefaultWorkspace.id. Verify: 200, not 403. - Add the Tool Set's host as a trusted endpoint. Verify:
POST /v1/account/trusted_endpoints:verifyreturnsRESULT_TRUSTEDfor the URL. - Create the Tool Set, with its secrets in
spec.secretsor as workspace secrets. Verify (MCP and OpenAPI sources):GET …/tool_sets/{id}/toolslists the synced tools. - Pick a model:
GET …/models?state=STATE_ENABLED, then use a returned model'smetadata.id(or<provider-key-externalId>.<model-externalId>). Never hardcode a model slug. - Create the Agent with
defaultVariation. Verify:GET …/agents/{id}/variationsshows the variation with its assignments. -
:publishthe Agent. Verify:GET …/agents/{id}hasstateSTATE_PUBLISHED. - Run an objective with
POST …/objectives:stream(see Streaming). Verify: astateChangedtoOBJECTIVE_STATE_WAITINGor a terminal state arrives. - Submit feedback on the objective.
Objective lifecycle and events
States: OBJECTIVE_STATE_PENDING → OBJECTIVE_STATE_RUNNING → OBJECTIVE_STATE_WAITING (turn finished, awaiting continue) → back to running; OBJECTIVE_STATE_INTERRUPTING while an interrupt settles; terminal OBJECTIVE_STATE_FINALIZED (structured output extracted or sub-objective done), OBJECTIVE_STATE_FAILED, OBJECTIVE_STATE_CANCELLED, OBJECTIVE_STATE_TIMED_OUT (inactivity). The objective stays running while a tool call waits for approval or bare content.
POST …/objectives/{id}:continue{"message": "…"}fromOBJECTIVE_STATE_WAITINGreturns{"type": "event", "event": <userMessage>}. With"enqueue": truea busy objective queues it instead and returns{"type": "queuedAction", "queuedAction": {…}}; list them atGET …/queued_actionsand drop one with…/queued_actions/{id}:removebefore the Agent picks it up. Sub-objectives and schedule-driven objectives cannot be continued.:interrupt{}stops foreground work (tool calls, approval waits, foreground sub-agents) and returns theinterruptedevent; the objective goes toOBJECTIVE_STATE_INTERRUPTING, thenOBJECTIVE_STATE_WAITING.:compact{}(optionalcompactionConfigoverride) returns a queued action: a waiting objective compacts now, a busy one before its next assistant turn. Running objectives also compact themselves atcompactionConfig.triggerThreshold.:cancel{}cancels a waiting or pending objective at once; a running one is cancelled asynchronously, so poll forOBJECTIVE_STATE_CANCELLEDor thecancelledevent.- Tool approval: a tool with
requiresApprovalemitstoolApprovalRequested{toolCallId}and waits up to 24h.GET …/tool_calls?status=TOOL_CALL_STATUS_WAITING_FOR_APPROVAL, then:approve{}or:deny{"memo": "Use the read-only lookup instead."}. Bare calls sit inexecutionStatus=TOOL_CALL_EXECUTION_STATUS_WAITING_FOR_CONTENTuntil:setContent{"content": [{"type": "text", "text": {"text": "…"}}]}(alsoimage/audioblocks with base64dataandmimeType). - Structured output lands in the objective's
outputonceOBJECTIVE_STATE_FINALIZED. Terminal objectives are hard-deleted after the account's retention TTL.
Events (GET …/objectives/{id}/events?sortOrder=asc, resumable with sinceEventId): {"metadata": {"id": "objevt_…"}, "contextWindowId": "objwin_…", "data": {"type": "<kind>", "<kind>": {…}}}. Kinds: userMessage{content}, assistantMessage{content, toolCalls[], completionId}, reasoning, toolApprovalRequested{toolCallId}, toolApproved, toolDenied{memo}, toolCalled{toolCallId, tool, arguments}, toolResult{toolCallId, result}, toolError{toolCallId, message}, memoryRead, contextWindowCompacted, subAgentSpawned, subAgentUpdated, notice, stateChanged{fromState, toState, message}, interrupted{message}, error{type, message} (objective fails), cancelled, timedOut, finalized{output}. A turn ends with stateChanged whose toState is OBJECTIVE_STATE_WAITING; terminal states write their own event (finalized, error, cancelled, timedOut) just before their stateChanged.
Streaming (SSE)
GET /v1/workspaces/development/objectives/ticket-4821/events:stream?includeDeltas=true
Authorization: Bearer …
Last-Event-ID: objevt_01M1338C9KQKAAB646W83TK8SS
- Frames:
event: <data.type>,id: objevt_…,data: <ObjectiveEvent JSON>. Frames without anidare never resume points:open(once) andping(every 15s) housekeeping,heartbeatevents (hb_…), and withincludeDeltas=truetheassistantMessageDelta/reasoningDeltatext fragments (dlt_…). Concatenate deltas bycompletionId, then replace them with the durableassistantMessageorreasoningthat carries the samecompletionId. - Without
Last-Event-IDyou receive only events created after connecting. With it, the server replays everything after that ID, then goes live. A non-objevt_ID fails with 400Last-Event-ID must be a persisted objevt_ event ID, and an ID that is not an event of this objective with 409Last-Event-ID does not name an event of this objective, both before the stream opens; drop the header and backfill from the events list instead. - Attaching with no checkpoint: page through
GET …/events?sortOrder=ascfirst. Handle what you find there (an approval already requested is never sent again on a live-only stream), and take the lateststateChanged.toState: if it isOBJECTIVE_STATE_WAITINGor terminal, the objective has settled and a stream would wait forever for an event that never comes. Otherwise stream withLast-Event-IDset to the last listed ID.OBJECTIVE_STATE_INTERRUPTINGis not settled; keep reading until thestateChangedthat follows it. events:streamnever closes, not even on a terminal state. Stop reading at astateChangedtoOBJECTIVE_STATE_WAITING(end of turn) or to a terminal state. Use it only to attach to an existing objective; to start one, use create-and-stream.POST …/objectives:streamtakes the objective create body plus optionalincludeDeltas, withmetadata.externalIdrequired: it creates the objective (or attaches to the existing one with that external ID, resuming fromLast-Event-ID) and streams it on the same response; this is the default way to run an objective. A newly created objective streams from its first event. The first frame isevent: objectivewith{"type": "objective", "objective": {…}}; every later frame is{"type": "event", "event": <ObjectiveEvent>}. This stream ends by itself once the objective isOBJECTIVE_STATE_WAITINGor terminal. The objective frame carriesstate: an attach withoutLast-Event-IDto an objective that has already settled sends only that frame, then ends, so read the settled state from it. An attach withoutLast-Event-IDto an objective still working sends only new events, so replay the events list first as above.- Resuming a stored checkpoint (one saved by an earlier process) on
events:streamhangs the same way when the objective settled at or before it:GET …/objectives/{id}first, and if itsstateisOBJECTIVE_STATE_WAITINGor terminal, readGET …/events?sortOrder=asc&sinceEventId=<checkpoint>(events after it) instead of streaming. AtoolApprovalRequestedbefore the checkpoint is never replayed, so also listtool_calls?status=TOOL_CALL_STATUS_WAITING_FOR_APPROVAL. Create-and-stream withLast-Event-IDneeds neither: on a settled objective it sends the events after the checkpoint, then ends. - Connections are cut after about 10 minutes; reconnect with
Last-Event-IDset to the lastobjevt_ID you received. Errors on these two stream endpoints are{"message": "…"}bodies with nocodeordetails, 401 for bad credentials, and 409 (not 400) for a failed precondition; unary calls such as:approvestill return 400 code 9. Without the field violations, create-and-stream on a draft Agent reports only 400validation failed(unary create namesagent must be published to create an objective), and a missing external ID reportsmetadata.externalId is required: ….
Webhooks
Set spec.webhookEventsUrl (HTTPS) on an Agent and Cadenya POSTs every durable objective event for that Agent:
{"type": "objective_event.tool_approval_requested", "timestamp": "2026-08-28T02:30:00Z",
"data": {"agent": {…}, "agentVariation": {…}, "objective": {"id": "obj_…", "externalId": "ticket-4821"}, "objectiveEvent": {"metadata": {"id": "objevt_…"}, "data": {"type": "toolApprovalRequested", "toolApprovalRequested": {"toolCallId": "toolcall_…"}}}}}
typeisobjective_event.plus the snake_case event kind:user_message,assistant_message,reasoning,tool_approval_requested,tool_approved,tool_denied,tool_called,tool_result,tool_error,memory_read,context_window_compacted,sub_agent_spawned,sub_agent_updated,notice,state_changed,interrupted,error,cancelled,timed_out,finalized. Heartbeats and deltas are never sent.- Standard Webhooks headers:
webhook-id(wh_…, idempotency key),webhook-timestamp(unix seconds),webhook-signature(one or more space-separatedv1,<base64>entries; one valid entry is enough). The signature is HMAC-SHA256 over the string<id>.<timestamp>.<raw body>, keyed with the base64-decoded part after thewhsec_prefix of the account'sinfo.webhookEventsHmacSecret(visible onGET /v1/account, rotated byPOST /v1/account:rotateWebhookSigningKey). Verify against the raw body bytes (not a re-serialized object) and reject timestamps more than 5 minutes off. - Delivery: 5 attempts with backoff. Any non-2xx retries, except 410, which stops retrying that delivery. Inspect attempts with
GET …/agents/{agentId}/webhook_deliveries?objectiveId=….
Quick recipe (curl)
API=https://api.cadenya.com/v1/workspaces/development
H=(-H "Authorization: Bearer $CADENYA_API_KEY" -H "Content-Type: application/json")
curl -s "$API/agents/support-triager:publish" "${H[@]}" -d '{}'
curl -sN "$API/objectives:stream" "${H[@]}" \
-d '{"agentId":"support-triager","metadata":{"externalId":"ticket-4821"},"systemPromptData":{"customer_name":"Ada"},"firstUserMessage":"Summarize the open tickets."}' \
| sed -un 's/^data: //p' | jq -c 'select(.type=="event") | {type: .event.data.type, text: .event.data.assistantMessage.content}'
curl -s "$API/objectives/ticket-4821/feedback" "${H[@]}" -d '{"metadata":{},"data":{"score":1}}'
Rerunning the stream call with the same externalId reattaches to the objective instead of starting another; pass -H "Last-Event-ID: objevt_…" with the last ID you saw, or the rerun sends only new events. If a tool needs approval, the stream stays open at toolApprovalRequested until you :approve or :deny the call from another request; approvals do not end the turn.
Related skills
cadenya-cli: the same API from a terminal (cadenya schema <cmd>prints exact request schemas;--dry-runprints bodies).cadenya-typescript-sdk,cadenya-go-sdk,cadenya-python-sdk,cadenya-ruby-sdk: typed clients with pagination, retries, streaming, and webhook verification built in. Their bodies match references/resources.md field for field (snake_case keys in Python and Ruby).
