Cloud Agent HTTP API
The AgentEngine HTTP surface for a deployed Agent: 37 Actions, two call paths, SSE frames, the error envelope, and timeouts.
This page covers how to call an Agent over HTTP once it is deployed to the cloud. It is not the same surface as the control protocol.
| Studio RPC | AgentEngine Action (this page) | |
|---|---|---|
| Who talks to whom | Browser ↔ local Host | Local Host ↔ cloud control plane |
| Size | 139 operations | 37 Actions + 5 skill-service Actions |
| Channel | /agentkit | POST /agentengine/api/v1/{Action} or KOP /?Action=…&Version=v1 |
| Envelope | { ok, value } / { ok, error } | { Code, RequestId, Error, Data } |
| Authentication | Local Host session | Authorization: Bearer or AWS SigV4 |
Mixing the two is the most common mistake here: a Studio RPC operation id is not a cloud Action name, and the reverse is also false.
Three address layers, never mixed
| Layer | Address shape | Purpose | Shape validation |
|---|---|---|---|
| Studio RPC | Local Host port | Browser drives the local Host | — |
| Control plane (KOP) | https://aicp.api.ksyun.com (public)<inner-kop-host> (intranet, usually http://) | Host calls 37 Actions on the cloud | Must be a clean origin: a port, userinfo, query or non-root path yields SERVER_URL_INVALID (src/server-client.mjs:507) |
| Runtime endpoint | https://<AgentId>.agent.kspmas.ksyun.com | Call a deployed Agent at /v1/responses, /health, /v1/agentkit/runtime | Only the public shape is validated (src/studio-deployments.mjs:47-49) |
Intranet addresses have no shape validation
Intranet runtime addresses (and the <inner-kop-host> some accounts are restricted to) have no shape validation — that is a console and gateway capability, and the SDK does not guess. This page does not claim the SDK validates intranet addresses.
Endpoint discovery
Recommended (for a human): AICP console → deployment details → copy the endpoint. Both the public and intranet addresses are shown, together with the API key.
Programmatic path (for code): GetAgent returns a deployment record with two shapes; fall back in this order (src/studio-deployments.mjs:44-46):
| Field | When it is present |
|---|---|
Network.PublicEndpoint | Deployments whose network is ready |
QuickAccess.PublicEndpoint | Quick-access entry point |
QuickAccess.ApiKey is the runtime token (src/studio-deployments.mjs:381,445,511); it authorises access to the runtime endpoint.
Identity probe: GET /v1/agentkit/runtime (src/build-runtime-http.mjs:99) returns the runtime identity and execution policy; GET /health returns { status: "ready" | "stopping" } (line 95).
Authentication
The two routes authenticate completely differently. Do not mix them.
| Item | Custom server | KOP (AICP gateway) |
|---|---|---|
| Credential | Service token | Sub-account AK/SK |
| Primary header | Authorization: Bearer <token> | Authorization generated by AWS SigV4 |
| Signing | — | SigV4, service=aicp, region=cn-beijing-6 |
| Session header | loopback adds X-AgentKit-Session | — |
| Required headers | X-Ksc-Request-Id, X-Ksc-Region, X-Ksc-Source | Same, plus X-Action, X-Version |
| Optional headers | — | X-Ksc-Account-Id, X-Ksc-User-uuid |
| Pre-online | — | Extra X-KSC-CUSTOM-SOURCE: pre |
| Request body | The payload as-is | Also carries Service, Action, Version, SdkVersion, Region, Accesskey |
The intranet fallback only applies to 403
When the public IAM returns 403 whose body contains inner account, the client retries once against the intranet IAM (src/cloud-identity.mjs:82-83, src/server-client.mjs:556). That is endpoint selection, not a retry of a mutating request — every other 4xx is never retried.
Two call paths, two body shapes
There are two ways to call a deployed Agent, and their request bodies differ. Mixing them yields a 400 or an empty response:
| Control-plane RunAgent | Runtime /v1/responses | |
|---|---|---|
| Address | POST {controlPlane}/agentengine/api/v1/RunAgent (KOP: POST /?Action=RunAgent&Version=v1) | POST https://<AgentId>.agent.kspmas.ksyun.com/v1/responses |
| Authentication | Authorization: Bearer or AWS SigV4 | Authorization: Bearer <runtime-token> |
| Field style | PascalCase | snake_case |
| Used by | Host local conversation bridge (src/host/routes/http.mjs:110-113) | Direct to the deployed Agent (src/deployment-conversation.mjs:26-27,99) |
Control-plane RunAgent
Fields come from src/host/routes/http.mjs:110-113:
| Field | Type | Required | Notes |
|---|---|---|---|
AgentId | string | Yes | Identifier of the deployed Agent |
SessionId | string | Yes | Cloud session id; missing yields INVALID_CONVERSATION_INPUT |
Messages | array | Yes | [{ role: 'user', content: string }] |
Stream | boolean | Yes | Fixed to true; streaming is the only supported form |
ApiFormat | string | Yes | Fixed to 'responses', OpenAI Responses-compatible frames |
InvocationId | string | No | Idempotency key, see Timeouts and retries |
curl -N "https://aicp.api.ksyun.com/agentengine/api/v1/RunAgent" \
-H "Authorization: Bearer <service-token>" \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-H "X-Ksc-Request-Id: $(uuidgen)" \
-H "X-Ksc-Region: cn-beijing-6" \
-H "X-Ksc-Source: agentkit-studio" \
-d '{
"AgentId": "<AgentId>",
"SessionId": "<SessionId>",
"Messages": [{ "role": "user", "content": "list the files in this workspace" }],
"Stream": true,
"ApiFormat": "responses",
"InvocationId": "'"$(uuidgen)"'"
}'Call DSH ManagedRuntime from a public endpoint
Use the Agent API key to call POST {PublicEndpoint}/agentengine/api/v1/RunAgent. Set ApiFormat: "responses" and send the current turn as ResponsesInput.
| Field | Use |
|---|---|
SessionId | Platform session ID. Use Data.Session.SessionId from CreateSession or session_id from the first RunAgent response, and reuse it on later turns. |
InvocationId | Use a new ID for a new turn and keep it for retries of that turn. |
UserId | Optional business user ID for MCP. Platform authorization still uses the authenticated principal. |
BusinessSessionId | Optional business session ID for MCP. It is independent of SessionId and does not select the conversation. |
Server forwards both business fields, and the Host sends them to bound MCP servers in tool-call _meta and HTTP headers. Later turns can omit previously bound fields. Business IDs are excluded from model requests and transcripts.
Runtime /v1/responses
Fields come from src/deployment-conversation.mjs:26-27. Note that session_id and request_id are derived deterministically from the original identifiers rather than being random — that is what lets a resend be recognised as the same request:
| Field | Type | Required | Notes |
|---|---|---|---|
input | string | Yes | The user input for this turn |
stream | boolean | Yes | Fixed to true |
model | string | Yes | Bound model name; must match the frozen version |
session_id | string | Yes | studio- plus the first 40 chars of sha256(sessionId) |
request_id | string | Yes | message- plus the first 40 chars of sha256(JSON.stringify([sessionId, messageId])) |
x-agentkit-permission-mode | header | No | Sent only when the frozen image declares allowed modes (lines 34-35) |
const sha = (value) => createHash('sha256').update(value).digest('hex').slice(0, 40);
const response = await fetch(`https://${agentId}.agent.kspmas.ksyun.com/v1/responses`, {
method: 'POST',
headers: {
Authorization: `Bearer ${runtimeToken}`,
'Content-Type': 'application/json',
Accept: 'text/event-stream',
},
body: JSON.stringify({
input: userText,
stream: true,
model,
session_id: `studio-${sha(sessionId)}`,
request_id: `message-${sha(JSON.stringify([sessionId, messageId]))}`,
}),
redirect: 'error',
});
if (!response.ok || !response.headers.get('content-type')?.includes('text/event-stream')) {
throw new Error(`cloud conversation rejected (HTTP ${response.status})`);
}Consuming the SSE stream
The response is text/event-stream, with OpenAI responses -compatible frames and not the Action JSON envelope:
| Frame | Meaning |
|---|---|
response.created | The turn starts; carries runId |
response.output_text.delta | Text delta; append it |
response.output_item.added | A tool call or message item appears |
response.completed | The turn finished; carries usage |
response.failed | The turn failed; carries an error summary |
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = '';
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buffer += value;
const frames = buffer.split('\n\n');
buffer = frames.pop() ?? '';
for (const frame of frames) {
const data = frame.split('\n').filter((line) => line.startsWith('data:')).map((line) => line.slice(5).trim()).join('');
if (!data || data === '[DONE]') continue;
const event = JSON.parse(data);
if (event.type === 'response.output_text.delta') process.stdout.write(event.delta ?? '');
if (event.type === 'response.failed') throw new Error(event.response?.error?.message ?? 'run failed');
}
}Neither Stream nor ApiFormat is optional
Stream: true makes the response SSE rather than JSON; ApiFormat: 'responses' makes the frames Responses-shaped. Drop either one and the client parses the response with the wrong reader.
Action reference
42 Actions, all derived from the two src/server-client.mjs new Set([...]) literals in new Set([...]) — 37 AgentEngine Actions + 5 skill-service Actions. A new Action must be added to ACTION_DOCS or --check fails.
| Domain | Action | Route | Meaning | Known request fields | Call site |
|---|---|---|---|---|---|
| Templates | ListStudioTemplates | AgentEngine Action (POST) | List expert template market entries | — | src/server-client.mjs |
| Templates | GetStudioTemplate | AgentEngine Action (POST) | Read one template | — | src/server-client.mjs |
| Templates | GetStudioTemplateDownload | AgentEngine Action (POST) | Resolve the template download URL | — | src/server-client.mjs |
| Templates | GetStudioTemplateCatalogCapabilities | AgentEngine Action (POST) | Capabilities the template catalog declares | — | src/server-client.mjs |
| Agents | ListAgents | AgentEngine Action (POST) | List Agents in the account | Page, PageSize | src/server-client.mjs:193 |
| Agents | GetAgent | AgentEngine Action (POST) | Read an Agent and its deployment record | AgentId | src/server-client.mjs:210 |
| Agents | UpdateAgent | AgentEngine Action (POST) | Update an Agent declaration | AgentId | src/server-client.mjs:211 |
| Sessions | CreateSession | AgentEngine Action (POST) | Create a cloud session for an Agent | — | src/server-client.mjs |
| Knowledge base | ListKnowledgeBases | AgentEngine Action (POST) | List knowledge bases | — | src/server-client.mjs |
| Memory | ListMemoryInstances | AgentEngine Action (POST) | List memory instances | — | src/server-client.mjs |
| MCP | ListMCPs | AgentEngine Action (POST) | List MCP servers | — | src/server-client.mjs |
| MCP | GetMCP | AgentEngine Action (POST) | Read one MCP server | — | src/server-client.mjs |
| MCP | DeleteMCP | AgentEngine Action (POST) | Delete an MCP server and its cloud resources | — | src/server-client.mjs |
| Knowledge base | RetrieveKnowledge | AgentEngine Action (POST) | Retrieve knowledge chunks for a query | — | src/server-client.mjs |
| Memory | QueryMemorySdk | AgentEngine Action (POST) | Query memory | — | src/server-client.mjs |
| Memory | CreateMemorySdk | AgentEngine Action (POST) | Write one memory record | — | src/server-client.mjs |
| Memory | ListMemories | AgentEngine Action (POST) | Page through memory records | — | src/server-client.mjs |
| Memory | UpdateMemory | AgentEngine Action (POST) | Update one memory record | — | src/server-client.mjs |
| Memory | DeleteMemory | AgentEngine Action (POST) | Delete one memory record | — | src/server-client.mjs |
| Skill | ListSkillWorkspaces | AgentEngine Action (POST) | List skill workspaces | — | src/server-client.mjs |
| Agents | ListAgentModels | AgentEngine Action (POST) | List models available to the Agent | — | src/server-client.mjs |
| Sessions | ListSessions | AgentEngine Action (POST) | List sessions | — | src/server-client.mjs |
| Sessions | GetSession | AgentEngine Action (POST) | Read one session | — | src/server-client.mjs |
| Sessions | ListSessionMessages | AgentEngine Action (POST) | Page through session messages | — | src/server-client.mjs |
| Sessions | ListSessionEvents | AgentEngine Action (POST) | Read the session event stream | — | src/server-client.mjs |
| Schedules | ListAgentSchedules | AgentEngine Action (POST) | List schedules for the Agent | AgentId | src/server-client.mjs:215 |
| Schedules | GetAgentSchedule | AgentEngine Action (POST) | Read one schedule | AgentId | src/server-client.mjs:216 |
| Schedules | ListAgentScheduleOccurrences | AgentEngine Action (POST) | List schedule occurrences | AgentId | src/server-client.mjs:217 |
| Observability | GetObservabilityOverview | AgentEngine Action (POST) | Observability overview for a window | StartTime, EndTime | src/server-client.mjs:563 |
| Observability | ListAgentRuntimeStats | AgentEngine Action (POST) | Per-Agent runtime statistics | StartTime, EndTime | src/server-client.mjs:569 |
| Run control | RunAgent | AgentEngine Action (POST) | Send one turn, optionally streamed | AgentId, SessionId, Messages, Stream, ApiFormat, InvocationId | src/server-client.mjs |
| Run control | CancelRun | AgentEngine Action (POST) | Cancel the current Run | — | src/server-client.mjs |
| Run control | ResumeRun | AgentEngine Action (POST) | Resume a Run (declared unsupported) | — | src/server-client.mjs |
| Run control | SubmitInteraction | AgentEngine Action (POST) | Submit a human approval decision | — | src/server-client.mjs |
| Run control | SubmitAgentControl | AgentEngine Action (POST) | Send a run-time control command | — | src/server-client.mjs |
| Credentials | ListAgentApiKeys | AgentEngine Action (POST) | List the Agent's API keys | — | src/server-client.mjs |
| Credentials | CreateAgentApiKey | AgentEngine Action (POST) | Create an API key for the Agent | — | src/server-client.mjs |
| Skill | ListSkillSpaces | Skill service (AICP GET) | List skill spaces (AICP) | — | src/server-client.mjs |
| Skill | ListAvailablePremadeSkills | Skill service (AICP GET) | List available premade skills | — | src/server-client.mjs |
| Skill | ListSkillsBySpaceId | Skill service (AICP GET) | List skills in a space | — | src/server-client.mjs |
| Skill | GetSkillDownloadUrl | Skill service (AICP GET) | Resolve a skill download URL | — | src/server-client.mjs |
| Skill | GetPremadeSkillDownloadUrl | Skill service (AICP GET) | Resolve a premade skill download URL | — | src/server-client.mjs |
Counted by domain:
| Domain | Count | Actions |
|---|---|---|
| Templates | 4 | ListStudioTemplates · GetStudioTemplate · GetStudioTemplateDownload · GetStudioTemplateCatalogCapabilities |
| Agents | 4 | ListAgents · GetAgent · UpdateAgent · ListAgentModels |
| Sessions | 5 | CreateSession · ListSessions · GetSession · ListSessionMessages · ListSessionEvents |
| Knowledge base | 2 | ListKnowledgeBases · RetrieveKnowledge |
| Memory | 6 | ListMemoryInstances · QueryMemorySdk · CreateMemorySdk · ListMemories · UpdateMemory · DeleteMemory |
| MCP | 3 | ListMCPs · GetMCP · DeleteMCP |
| Skill | 6 | ListSkillWorkspaces · ListSkillSpaces · ListAvailablePremadeSkills · ListSkillsBySpaceId · GetSkillDownloadUrl · GetPremadeSkillDownloadUrl |
| Schedules | 3 | ListAgentSchedules · GetAgentSchedule · ListAgentScheduleOccurrences |
| Observability | 2 | GetObservabilityOverview · ListAgentRuntimeStats |
| Run control | 5 | RunAgent · CancelRun · ResumeRun · SubmitInteraction · SubmitAgentControl |
| Credentials | 2 | ListAgentApiKeys · CreateAgentApiKey |
Error envelope and codes
Success and failure share one envelope (src/server-client.mjs:420-431):
{
"Code": 0,
"RequestId": "<request-id>",
"Data": {},
"Error": null
}Rule: Code must be 0 or 200 and there must be no Error . A few resource Actions (such as ListSessions) allow Code to be absent. On failure the client throws AgentEngineError and carries the RequestId with it.
| Code | Trigger | What the client should do | Thrown at |
|---|---|---|---|
SERVER_ACTION_FAILED | The cloud returned a Code other than 0/200, or an Error field | Read RequestId in the cloud logs; do not blind-retry a mutating request | src/server-client.mjs:434 |
SERVER_ACTION_NOT_REGISTERED | KOP reports InvalidActionOrVersion; the Action is not published in this environment | Confirm the environment and API version; retry after it is published | src/server-client.mjs:427 |
SERVER_URL_INVALID | The control-plane address is not an HTTPS origin, or carries a port, userinfo or query | Pass an origin only; HTTP is limited to loopback or a runtime-configured intranet entry | src/server-client.mjs:507 |
SERVER_CREDENTIALS_MISSING | A non-loopback custom server has no service token | Configure cloudServiceToken | src/server-client.mjs:392 |
SERVER_UNAVAILABLE | The request did not complete (connection failure or timeout) | Check the network; mutating requests are not retried | src/server-client.mjs:404 |
SERVER_INVALID_RESPONSE | The response body is not valid JSON | Check whether a gateway or proxy rewrote the response | src/server-client.mjs:418 |
SERVER_RATE_LIMITED | The upstream returned 429 | Back off and retry; streaming requests are limited too | src/server-client.mjs:434 |
ACTION_NOT_ALLOWED | The Action is not in the SERVER_ACTIONS allowlist | Studio does not expose this Action; use a supported one | src/server-client.mjs:348 |
CLOUD_CREDENTIALS_MISSING | The KOP route needs AK/SK and none is configured | Settings → Models & credentials → cloud credentials | src/server-client.mjs:375 |
CLOUD_SUBACCOUNT_REQUIRED | A create Action used a root-account AK/SK | Use a verified sub-account AK/SK | src/server-client.mjs:357 |
REQUEST_CANCELLED | The caller's AbortSignal fired | Not a failure — treat it as a cancellation | src/server-client.mjs:404 |
SKILL_SERVICE_FAILED | The Skill Service returned a Code other than 0/200 | As above: use RequestId to locate it | src/server-client.mjs:492 |
SKILL_SERVICE_UNAVAILABLE | The Skill Service needs AICP credentials and this is not a KOP route | Switch to KOP cloud credentials | src/server-client.mjs:457 |
INVALID_QUERY | Paging is out of range (pageSize 1–100) | Clamp the paging parameters | src/server-client.mjs:575 |
INVALID_AGENT_ID | AgentId is empty | Pass a non-empty AgentId | src/server-client.mjs:596 |
DEPLOYMENT_AGENT_MISMATCH | The request AgentId does not match the deployment record | Use the AgentId from the deployment record | src/server-client.mjs:206 |
DEPLOYMENT_ENDPOINT_INVALID | The runtime address protocol, hostname, port or path does not match the deployment | Copy the full address from the console; do not build it by hand | src/studio-deployments.mjs:49 |
RUNTIME_SESSION_BUSY | The session already has an active Run | Cancel or wait for the current Run | src/build-runtime-http.mjs:193 |
RUNTIME_DEPLOYMENT_CHANGED | A version-guard header does not match the loaded declaration | Re-read the runtime identity before sending | src/build-runtime-http.mjs:105 |
RUNTIME_ACTION_UNSUPPORTED | The action is unavailable in this runtime's declaration | Read the capability declaration; do not retry | src/frozen-hosted-actions.mjs:106 |
RUNTIME_ACTION_INPUT_UNSUPPORTED | The body carries a field outside the declaration | Send only the declared fields | src/managed-runtime-actions.mjs:168 |
RUNTIME_TRANSPORT_CLOSED | The transport is closed | Rebuild the client | src/cloud-runtime-fetch.mjs:7 |
Capability declaration
A deployed Agent declares what it supports through GET /v1/agentkit/runtime (src/managed-runtime-capabilities.mjs:12-37). The capability keys in the current manifest:
| Capability | Meaning | Enabled |
|---|
Unsupported capabilities are explicit, not silently approximated
ResumeRun, BackgroundRun, CheckpointResume, KernelSessionEvents, Attachments, WorkspaceFiles, Thinking are all declared unsupported today. Callers should read the declaration first, not call once and read the error.
Timeouts and retries
The two windows are separate because a streaming request can spend longer in hosted-runtime admission (src/server-client.mjs:537-540 comment):
| Case | Default timeout | Source |
|---|---|---|
| Regular JSON Action | 15 s | timeoutMs = 15000 |
Streaming RunAgent | 180 s (the larger of the two) | streamTimeoutMs = Math.max(timeoutMs, 180000) |
Mutating requests are never retried automatically
The SERVER_UNAVAILABLE message states outright that mutating requests are not retried, because the client cannot know whether the upstream accepted the call. For idempotency the caller must supply a key:
| Key | Scope | Source |
|---|---|---|
InvocationId | One RunAgent | src/host/routes/http.mjs:113 |
X-Ksc-Request-Id | One HTTP request | src/server-client.mjs:378 |
Resending with the same InvocationId is what lets the cloud treat the two calls as one turn. Do not use a fresh random value to fake a retry — that is two independent submissions.