AgentKit Studio
Reference

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 RPCAgentEngine Action (this page)
Who talks to whomBrowser ↔ local HostLocal Host ↔ cloud control plane
Size139 operations37 Actions + 5 skill-service Actions
Channel/agentkitPOST /agentengine/api/v1/{Action} or KOP /?Action=…&Version=v1
Envelope{ ok, value } / { ok, error }{ Code, RequestId, Error, Data }
AuthenticationLocal Host sessionAuthorization: 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

LayerAddress shapePurposeShape validation
Studio RPCLocal Host portBrowser 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 cloudMust be a clean origin: a port, userinfo, query or non-root path yields SERVER_URL_INVALID (src/server-client.mjs:507)
Runtime endpointhttps://<AgentId>.agent.kspmas.ksyun.comCall a deployed Agent at /v1/responses, /health, /v1/agentkit/runtimeOnly 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):

FieldWhen it is present
Network.PublicEndpointDeployments whose network is ready
QuickAccess.PublicEndpointQuick-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.

ItemCustom serverKOP (AICP gateway)
CredentialService tokenSub-account AK/SK
Primary headerAuthorization: Bearer <token>Authorization generated by AWS SigV4
Signing—SigV4, service=aicp, region=cn-beijing-6
Session headerloopback adds X-AgentKit-Session—
Required headersX-Ksc-Request-Id, X-Ksc-Region, X-Ksc-SourceSame, plus X-Action, X-Version
Optional headers—X-Ksc-Account-Id, X-Ksc-User-uuid
Pre-online—Extra X-KSC-CUSTOM-SOURCE: pre
Request bodyThe payload as-isAlso 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 RunAgentRuntime /v1/responses
AddressPOST {controlPlane}/agentengine/api/v1/RunAgent (KOP: POST /?Action=RunAgent&Version=v1)POST https://<AgentId>.agent.kspmas.ksyun.com/v1/responses
AuthenticationAuthorization: Bearer or AWS SigV4Authorization: Bearer <runtime-token>
Field stylePascalCasesnake_case
Used byHost 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:

FieldTypeRequiredNotes
AgentIdstringYesIdentifier of the deployed Agent
SessionIdstringYesCloud session id; missing yields INVALID_CONVERSATION_INPUT
MessagesarrayYes[{ role: 'user', content: string }]
StreambooleanYesFixed to true; streaming is the only supported form
ApiFormatstringYesFixed to 'responses', OpenAI Responses-compatible frames
InvocationIdstringNoIdempotency 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.

FieldUse
SessionIdPlatform session ID. Use Data.Session.SessionId from CreateSession or session_id from the first RunAgent response, and reuse it on later turns.
InvocationIdUse a new ID for a new turn and keep it for retries of that turn.
UserIdOptional business user ID for MCP. Platform authorization still uses the authenticated principal.
BusinessSessionIdOptional 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:

FieldTypeRequiredNotes
inputstringYesThe user input for this turn
streambooleanYesFixed to true
modelstringYesBound model name; must match the frozen version
session_idstringYesstudio- plus the first 40 chars of sha256(sessionId)
request_idstringYesmessage- plus the first 40 chars of sha256(JSON.stringify([sessionId, messageId]))
x-agentkit-permission-modeheaderNoSent 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:

FrameMeaning
response.createdThe turn starts; carries runId
response.output_text.deltaText delta; append it
response.output_item.addedA tool call or message item appears
response.completedThe turn finished; carries usage
response.failedThe 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.

DomainActionRouteMeaningKnown request fieldsCall site
TemplatesListStudioTemplatesAgentEngine Action (POST)List expert template market entries—src/server-client.mjs
TemplatesGetStudioTemplateAgentEngine Action (POST)Read one template—src/server-client.mjs
TemplatesGetStudioTemplateDownloadAgentEngine Action (POST)Resolve the template download URL—src/server-client.mjs
TemplatesGetStudioTemplateCatalogCapabilitiesAgentEngine Action (POST)Capabilities the template catalog declares—src/server-client.mjs
AgentsListAgentsAgentEngine Action (POST)List Agents in the accountPage, PageSizesrc/server-client.mjs:193
AgentsGetAgentAgentEngine Action (POST)Read an Agent and its deployment recordAgentIdsrc/server-client.mjs:210
AgentsUpdateAgentAgentEngine Action (POST)Update an Agent declarationAgentIdsrc/server-client.mjs:211
SessionsCreateSessionAgentEngine Action (POST)Create a cloud session for an Agent—src/server-client.mjs
Knowledge baseListKnowledgeBasesAgentEngine Action (POST)List knowledge bases—src/server-client.mjs
MemoryListMemoryInstancesAgentEngine Action (POST)List memory instances—src/server-client.mjs
MCPListMCPsAgentEngine Action (POST)List MCP servers—src/server-client.mjs
MCPGetMCPAgentEngine Action (POST)Read one MCP server—src/server-client.mjs
MCPDeleteMCPAgentEngine Action (POST)Delete an MCP server and its cloud resources—src/server-client.mjs
Knowledge baseRetrieveKnowledgeAgentEngine Action (POST)Retrieve knowledge chunks for a query—src/server-client.mjs
MemoryQueryMemorySdkAgentEngine Action (POST)Query memory—src/server-client.mjs
MemoryCreateMemorySdkAgentEngine Action (POST)Write one memory record—src/server-client.mjs
MemoryListMemoriesAgentEngine Action (POST)Page through memory records—src/server-client.mjs
MemoryUpdateMemoryAgentEngine Action (POST)Update one memory record—src/server-client.mjs
MemoryDeleteMemoryAgentEngine Action (POST)Delete one memory record—src/server-client.mjs
SkillListSkillWorkspacesAgentEngine Action (POST)List skill workspaces—src/server-client.mjs
AgentsListAgentModelsAgentEngine Action (POST)List models available to the Agent—src/server-client.mjs
SessionsListSessionsAgentEngine Action (POST)List sessions—src/server-client.mjs
SessionsGetSessionAgentEngine Action (POST)Read one session—src/server-client.mjs
SessionsListSessionMessagesAgentEngine Action (POST)Page through session messages—src/server-client.mjs
SessionsListSessionEventsAgentEngine Action (POST)Read the session event stream—src/server-client.mjs
SchedulesListAgentSchedulesAgentEngine Action (POST)List schedules for the AgentAgentIdsrc/server-client.mjs:215
SchedulesGetAgentScheduleAgentEngine Action (POST)Read one scheduleAgentIdsrc/server-client.mjs:216
SchedulesListAgentScheduleOccurrencesAgentEngine Action (POST)List schedule occurrencesAgentIdsrc/server-client.mjs:217
ObservabilityGetObservabilityOverviewAgentEngine Action (POST)Observability overview for a windowStartTime, EndTimesrc/server-client.mjs:563
ObservabilityListAgentRuntimeStatsAgentEngine Action (POST)Per-Agent runtime statisticsStartTime, EndTimesrc/server-client.mjs:569
Run controlRunAgentAgentEngine Action (POST)Send one turn, optionally streamedAgentId, SessionId, Messages, Stream, ApiFormat, InvocationIdsrc/server-client.mjs
Run controlCancelRunAgentEngine Action (POST)Cancel the current Run—src/server-client.mjs
Run controlResumeRunAgentEngine Action (POST)Resume a Run (declared unsupported)—src/server-client.mjs
Run controlSubmitInteractionAgentEngine Action (POST)Submit a human approval decision—src/server-client.mjs
Run controlSubmitAgentControlAgentEngine Action (POST)Send a run-time control command—src/server-client.mjs
CredentialsListAgentApiKeysAgentEngine Action (POST)List the Agent's API keys—src/server-client.mjs
CredentialsCreateAgentApiKeyAgentEngine Action (POST)Create an API key for the Agent—src/server-client.mjs
SkillListSkillSpacesSkill service (AICP GET)List skill spaces (AICP)—src/server-client.mjs
SkillListAvailablePremadeSkillsSkill service (AICP GET)List available premade skills—src/server-client.mjs
SkillListSkillsBySpaceIdSkill service (AICP GET)List skills in a space—src/server-client.mjs
SkillGetSkillDownloadUrlSkill service (AICP GET)Resolve a skill download URL—src/server-client.mjs
SkillGetPremadeSkillDownloadUrlSkill service (AICP GET)Resolve a premade skill download URL—src/server-client.mjs

Counted by domain:

DomainCountActions
Templates4ListStudioTemplates · GetStudioTemplate · GetStudioTemplateDownload · GetStudioTemplateCatalogCapabilities
Agents4ListAgents · GetAgent · UpdateAgent · ListAgentModels
Sessions5CreateSession · ListSessions · GetSession · ListSessionMessages · ListSessionEvents
Knowledge base2ListKnowledgeBases · RetrieveKnowledge
Memory6ListMemoryInstances · QueryMemorySdk · CreateMemorySdk · ListMemories · UpdateMemory · DeleteMemory
MCP3ListMCPs · GetMCP · DeleteMCP
Skill6ListSkillWorkspaces · ListSkillSpaces · ListAvailablePremadeSkills · ListSkillsBySpaceId · GetSkillDownloadUrl · GetPremadeSkillDownloadUrl
Schedules3ListAgentSchedules · GetAgentSchedule · ListAgentScheduleOccurrences
Observability2GetObservabilityOverview · ListAgentRuntimeStats
Run control5RunAgent · CancelRun · ResumeRun · SubmitInteraction · SubmitAgentControl
Credentials2ListAgentApiKeys · 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.

CodeTriggerWhat the client should doThrown at
SERVER_ACTION_FAILEDThe cloud returned a Code other than 0/200, or an Error fieldRead RequestId in the cloud logs; do not blind-retry a mutating requestsrc/server-client.mjs:434
SERVER_ACTION_NOT_REGISTEREDKOP reports InvalidActionOrVersion; the Action is not published in this environmentConfirm the environment and API version; retry after it is publishedsrc/server-client.mjs:427
SERVER_URL_INVALIDThe control-plane address is not an HTTPS origin, or carries a port, userinfo or queryPass an origin only; HTTP is limited to loopback or a runtime-configured intranet entrysrc/server-client.mjs:507
SERVER_CREDENTIALS_MISSINGA non-loopback custom server has no service tokenConfigure cloudServiceTokensrc/server-client.mjs:392
SERVER_UNAVAILABLEThe request did not complete (connection failure or timeout)Check the network; mutating requests are not retriedsrc/server-client.mjs:404
SERVER_INVALID_RESPONSEThe response body is not valid JSONCheck whether a gateway or proxy rewrote the responsesrc/server-client.mjs:418
SERVER_RATE_LIMITEDThe upstream returned 429Back off and retry; streaming requests are limited toosrc/server-client.mjs:434
ACTION_NOT_ALLOWEDThe Action is not in the SERVER_ACTIONS allowlistStudio does not expose this Action; use a supported onesrc/server-client.mjs:348
CLOUD_CREDENTIALS_MISSINGThe KOP route needs AK/SK and none is configuredSettings → Models & credentials → cloud credentialssrc/server-client.mjs:375
CLOUD_SUBACCOUNT_REQUIREDA create Action used a root-account AK/SKUse a verified sub-account AK/SKsrc/server-client.mjs:357
REQUEST_CANCELLEDThe caller's AbortSignal firedNot a failure — treat it as a cancellationsrc/server-client.mjs:404
SKILL_SERVICE_FAILEDThe Skill Service returned a Code other than 0/200As above: use RequestId to locate itsrc/server-client.mjs:492
SKILL_SERVICE_UNAVAILABLEThe Skill Service needs AICP credentials and this is not a KOP routeSwitch to KOP cloud credentialssrc/server-client.mjs:457
INVALID_QUERYPaging is out of range (pageSize 1–100)Clamp the paging parameterssrc/server-client.mjs:575
INVALID_AGENT_IDAgentId is emptyPass a non-empty AgentIdsrc/server-client.mjs:596
DEPLOYMENT_AGENT_MISMATCHThe request AgentId does not match the deployment recordUse the AgentId from the deployment recordsrc/server-client.mjs:206
DEPLOYMENT_ENDPOINT_INVALIDThe runtime address protocol, hostname, port or path does not match the deploymentCopy the full address from the console; do not build it by handsrc/studio-deployments.mjs:49
RUNTIME_SESSION_BUSYThe session already has an active RunCancel or wait for the current Runsrc/build-runtime-http.mjs:193
RUNTIME_DEPLOYMENT_CHANGEDA version-guard header does not match the loaded declarationRe-read the runtime identity before sendingsrc/build-runtime-http.mjs:105
RUNTIME_ACTION_UNSUPPORTEDThe action is unavailable in this runtime's declarationRead the capability declaration; do not retrysrc/frozen-hosted-actions.mjs:106
RUNTIME_ACTION_INPUT_UNSUPPORTEDThe body carries a field outside the declarationSend only the declared fieldssrc/managed-runtime-actions.mjs:168
RUNTIME_TRANSPORT_CLOSEDThe transport is closedRebuild the clientsrc/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:

CapabilityMeaningEnabled

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):

CaseDefault timeoutSource
Regular JSON Action15 stimeoutMs = 15000
Streaming RunAgent180 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:

KeyScopeSource
InvocationIdOne RunAgentsrc/host/routes/http.mjs:113
X-Ksc-Request-IdOne HTTP requestsrc/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.

On this page