KsADK

远程运行时 API

这页说明 Agent 或运行时产品部署后的公开安全 API 形态。外部可见 base URL 是控制面 返回的 hosted PublicEndpoint

公开示例使用占位值:

https://<public-endpoint>

入口模型

Remote runtime 接入与运行时类型

runtime pod 可能实现本地路由,但外部调用方应以 gateway 暴露的 PublicEndpoint 路由作为 contract。

鉴权

客户端推荐鉴权
SDK、CLI、自动化Authorization: Bearer <api_key>
Hosted 浏览器会话hosted link flow 创建的 ae_ui_session cookie
Hermes 终端 WebSocketbearer auth 加 Sec-WebSocket-Protocol: ks-terminal.v1

外部调用方不要手工构造 X-Auth-Agent-IdX-Auth-Account-Id 或运行时专用 forwarded header。

Bearer Token 校验

托管运行时要求 Authorization: Bearer <token>。本地开发 server 默认不强制鉴权, 但上线时由 gateway 注入并校验 Bearer。客户端应始终携带,避免本地与托管行为不一致。

常见 Header

Header用途
Authorization: Bearer <api_key>通过 public endpoint 调用 API
Content-Type: application/jsonJSON 请求
Accept: application/json非流式响应
Accept: text/event-stream流式响应

multipart 上传路由的 multipart/form-data boundary 应由 HTTP client 自动生成。

运行时类型

运行时主要公开 surface
代码框架 Agent/v1/responses/v1/chat/completions、workspace files、hosted UI actions
Hermesdashboard、/v1/* proxy、终端 WebSocket、workspace files
OpenClawOpenClaw gateway 加 KsADK workspace files

OpenAI 兼容路由

POST /v1/responses

Responses 兼容客户端使用这个入口。

字段含义
input用户输入字符串或 message/content 数组
model可选模型覆盖
instructions请求级系统/开发者指令
conversation稳定 conversation id 或 { "id": "..." }
previous_response_id兼容客户端续聊 handle
safety_identifier稳定最终用户 id,建议 hash 后传入
streamtrue 时返回 SSE
metadataruntime 保留的请求 metadata
curl -sS https://<public-endpoint>/v1/responses \
  -H "Authorization: Bearer <api_key>" \
  -H "Content-Type: application/json" \
  -d '{"input":"hello","stream":false}'

POST /v1/chat/completions

Chat Completions 兼容客户端使用这个入口。

curl -sS https://<public-endpoint>/v1/chat/completions \
  -H "Authorization: Bearer <api_key>" \
  -H "Content-Type: application/json" \
  -d '{"model":"my-model","messages":[{"role":"user","content":"hello"}]}'

Responses 和 Chat Completions 在公开边界保持各自协议语义。KsADK 会在调用框架 代码前把两类入口归一化为 runner input。

Hosted UI Actions

Hosted UI 使用 action 风格路由管理 session、event、upload、workspace file、 cancel 和 model listing。公开 API 客户端优先使用 OpenAI 兼容的 /v1/* 路由; 只有明确集成 hosted UI surface 时才直接对接 action 路由。

所有 action 路径都挂在 POST /agentengine/api/v1/*(下载类 surface 为 GET), 返回统一的 action envelope:

envelope.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "RunAgent",
  "Data": { /* action-specific payload */ }
}
分组用途Actions
会话 Sessions创建、获取、列出、删除会话,读取投影后的聊天消息CreateSessionGetSessionListSessionsListSessionMessagesDeleteSession
运行 Runs调用或取消 Agent run、订阅事件RunAgentSubscribeRunEventsCancelRun
事件 Events列出 session 历史 events,支持增量续订与向前翻页ListSessionEvents
文件 Files上传、下载附件、workspace 文件、导出 archiveUploadFileAttachmentContentListWorkspaceFilesAddWorkspaceFileDeleteWorkspaceFileGetWorkspaceFileContentExportWorkspaceZip
模型 Models列出可用模型目录ListAgentModels
UI Bootstrap获取 UI 渲染与能力探测所需 metadataGetAgentUiBootstrap

0.6.7 新增

checkpoint/resume 与 GetAgentUiBootstrap 能力可见性均以 bootstrap 返回的 RuntimeCapabilitiesRunLifecycle 为准;公开 API 客户端通常不直接对接这些 action 路由,优先使用 OpenAI 兼容的 /v1/*

会话 Sessions

  1. 探测能力:先调用 GetAgentUiBootstrap,确认 Capabilities.WorkspaceFilesCapabilities.ResumeRun 等。
  2. 创建会话CreateSession,拿到 Session.SessionId
  3. 拉取历史ListSessions 渲染侧栏,ListSessionMessages 渲染聊天历史;只有调试或原始时间线才直接读 ListSessionEvents
  4. 发起运行RunAgent(前台或后台),用 SubscribeRunEvents 续订进度。
  5. 回收会话DeleteSession 释放持久化记录。

CreateSession

创建(或复用)一个会话。SessionId 缺省时由运行时生成。

POST /agentengine/api/v1/CreateSession,body 为 JSON:

字段类型必填说明
AgentIdstring目标 Agent id
UserIdstring缺省 user
SessionIdstring复用已有 session;缺省运行时生成
request.json
{
  "AgentId": "my-agent",
  "UserId": "user",
  "SessionId": "local-demo-session"
}
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "CreateSession",
  "Data": {
    "Session": {
      "SessionId": "local-demo-session",
      "AgentId": "my-agent",
      "UserId": "user",
      "Title": "New session",
      "TitleSource": "fallback_first_prompt",
      "Summary": null,
      "FirstPrompt": "",
      "LastPrompt": "",
      "ActiveInvocationId": "",
      "ActiveRunStatus": "",
      "ActiveRunMode": "unknown",
      "ActiveRunTrigger": "unknown",
      "ActiveRunUpdatedAt": "",
      "Model": null,
      "ContextUsage": null,
      "TokenUsage": null,
      "State": {},
      "CreatedAt": 1719900000.0,
      "UpdatedAt": 1719900000.0,
      "Version": 1
    }
  }
}

Session payload 字段:

字段说明
SessionId / AgentId / UserId会话主键三元组
Title / TitleSource会话标题及其来源(fallback_first_promptheuristic 等)
Summary运行时维护的会话摘要
FirstPrompt / LastPrompt截断后的首/末用户消息预览
ActiveInvocationId / ActiveRunStatus当前会话活跃 run 的 invocation 与状态;读侧会把超时孤儿活跃态兜底显示为 interrupted
ActiveRunMode / ActiveRunTrigger0.6.9+ run 状态双维度:background / foreground / unknownnew_run / checkpoint_resume / approval_resume / unknown
ActiveRunUpdatedAt0.6.9+ active_run 自身更新时间,主要用于诊断;孤儿判定使用 session UpdatedAt 心跳
Model最近一次 run 的模型 metadata(如可用)
ContextUsage0.6.9+ 最近一轮上下文窗口占用:used_tokenscached_tokenscontext_window_tokenspercent
TokenUsage0.6.9+ 会话累计 token 消耗:input_tokensoutput_tokenstotal_tokensturnslast_response_id 与明细字段
State会话状态 dict(已脱敏)
CreatedAt / UpdatedAt / Version时间戳与版本号
Continuity可选:runner 适配器描述的连续性信息
状态码场景detail
400AgentId 缺失Pydantic 校验失败
503session backend 不可用{"code":"session_backend_unavailable","message":...}

ListSessions

分页列出某 Agent / User 下的会话,按 page-based 分页。

POST /agentengine/api/v1/ListSessions

字段类型必填说明
AgentIdstring目标 Agent id
UserIdstring缺省 user
Pageint1-based,缺省 1,最小 1
PageSizeint缺省 20,范围 1..200
request.json
{
  "AgentId": "my-agent",
  "UserId": "user",
  "Page": 1,
  "PageSize": 20
}
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "ListSessions",
  "Data": {
    "Sessions": [ /* Session payload,同 CreateSession */ ],
    "Total": 42,
    "Page": 1,
    "PageSize": 20
  }
}

分页字段:

字段说明
Total该 Agent/User 下的会话总数
Page / PageSize当前页与每页大小(原样回填)

实际 offset 由运行时按 (Page - 1) * PageSize 计算。

GetSession

获取单个会话及其最新事件。

POST /agentengine/api/v1/GetSession

字段类型必填说明
SessionIdstring目标会话 id
request.json
{ "SessionId": "local-demo-session" }
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "GetSession",
  "Data": {
    "Session": { /* 同 CreateSession 的 Session payload */ }
  }
}
状态码场景detail
404session 不存在Session not found

DeleteSession

删除会话,并取消该会话上仍在进行的 detached stream。

POST /agentengine/api/v1/DeleteSession

字段类型必填说明
SessionIdstring目标会话 id
request.json
{ "SessionId": "local-demo-session" }
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "DeleteSession",
  "Data": { "Deleted": true }
}

副作用

删除前会先取消该 session 关联的 detached 后台 stream,避免悬挂的 in-progress run_status 事件。

状态码场景detail
404session 不存在Session not found

运行 Runs

RunAgent

调用 Agent 执行一轮对话。支持前台同步、前台流式、后台执行三种模式。

POST /agentengine/api/v1/RunAgent,body 为 JSON(基于 RunAgentActionRequest):

字段类型必填说明
AgentIdstring目标 Agent id
Messagesarray消息数组(Chat Completions 风格);与 ResponsesInput 二选一
ResponsesInputanyResponses 风格 input;与 Messages 二选一
UserIdstring缺省 user
AccountIdstring0.6.5+ 账号隔离 id,透传给 runner
SessionIdstring关联会话;缺省由运行时创建
InvocationIdstring调用方传入的 invocation id;缺省运行时生成
ApiFormatstringresponses(缺省)或 chat_completions
Streambooltrue 返回 SSE;缺省 false
Backgroundbool0.6.5+ true 立即返回 job 句柄,后台执行,进度走 SubscribeRunEvents;缺省 false
Modelstring模型或 Agent 名称覆盖
ModelMetadataobject模型元数据,含 reasoning / multimodal / context_window_tokens 等
ModelOptionsobject请求级模型选项(temperature、max_tokens 等)透传给 runner
PreviousResponseIdstringResponses 续聊 handle;写入 request metadata

前台同步调用:

request.json
{
  "AgentId": "my-agent",
  "Messages": [{"role": "user", "content": "hello"}],
  "ApiFormat": "responses",
  "Stream": false
}

后台执行:

background.json
{
  "AgentId": "my-agent",
  "Messages": [{"role": "user", "content": "summarize the workspace"}],
  "Background": true,
  "InvocationId": "inv_demo_001",
  "AccountId": "acct_42",
  "Model": "glm-5.1",
  "ModelMetadata": {"reasoning": true, "multimodal": false, "context_window_tokens": 128000},
  "ModelOptions": {"temperature": 0.2, "max_tokens": 4096}
}

Background 与 Stream 互斥

Background: true 时忽略 Stream,立即返回 job 句柄;前台 Stream: true 返回 SSE, 两者不能同时启用。

前台同步Background: falseStream: false)返回 Responses 或 Chat Completions 形态的 payload,外层包 action envelope:

response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "RunAgent",
  "Data": {
    "id": "resp_a1b2c3",
    "object": "response",
    "status": "completed",
    "model": "glm-5.1",
    "output": [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "..."}]}],
    "output_text": "...",
    "session_id": "local-demo-session"
  }
}

后台执行Background: true)立即返回 job 句柄:

background-response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "RunAgent",
  "Data": {
    "InvocationId": "inv_demo_001",
    "Status": "running",
    "Background": true,
    "SubscribeUrl": "/agentengine/api/v1/SubscribeRunEvents?SessionId=local-demo-session&InvocationId=inv_demo_001"
  }
}

后台返回字段:

字段说明
InvocationIdrun 的 invocation id,用于订阅与取消
Statusrunning 表示后台任务已就绪
Background始终 true
SubscribeUrl相对路径,拼接 host 即可作为 SSE 订阅入口

前台 Stream: true 时返回 text/event-stream,事件经 runtime 归一化后下发:

sse
curl -N https://<public-endpoint>/agentengine/api/v1/RunAgent \
  -H "Authorization: Bearer <api_key>" \
  -H "Content-Type: application/json" \
  -d '{"AgentId":"my-agent","Messages":[{"role":"user","content":"count to three"}],"Stream":true}'

客户端应处理文本 delta、工具事件、错误和完成事件。

状态码场景detail
400MessagesResponsesInput 同传或都缺Pydantic / runtime 校验失败
409同 session 的 resume 已在运行{"code":"resume_already_running",...}
500Runner 未初始化或加载失败Runner 未初始化

0.6.5+ 透传字段

AccountIdInvocationIdModelMetadataModelOptions 会原样透传给 runner, 用于按账号隔离 Skill/Workspace/Sandbox/Memory,并支持请求级模型参数覆盖。AccountId 缺省时 runner 侧按运行时默认账号处理。

SubscribeRunEvents

订阅某个 invocation 的 run events,SSE 推送。支持 5 分钟重连窗口。

GET /agentengine/api/v1/SubscribeRunEvents,参数走 query string:

参数类型必填说明
SessionIdstring目标会话 id
InvocationIdstring目标 run 的 invocation id
AfterSeqIdint仅推送 SeqId > AfterSeqId 的事件,缺省 0
subscribe-url
/agentengine/api/v1/SubscribeRunEvents?SessionId=local-demo-session&InvocationId=inv_demo_001&AfterSeqId=12

Accept: text/event-stream。每个事件为 data: <json>\n\n,终态后下发 data: [DONE]\n\n 并关闭流:

events.sse
data: {"EventId":"evt_1","SessionId":"local-demo-session","InvocationId":"inv_demo_001","EventType":"run_status","Content":{"status":"in_progress"},"SeqId":13,"Timestamp":1719900001.0}

data: {"EventId":"evt_2","EventType":"tool_result","Content":{...},"SeqId":14,...}

data: {"EventId":"evt_3","EventType":"run_status","Content":{"status":"completed"},"SeqId":15,...}

data: [DONE]

事件 payload 字段:

字段说明
EventId / SessionId事件与所属会话
InvocationId关联的 run invocation id
Author事件作者(agent 或 user)
EventType事件类型(run_statustool_resultrun_checkpoint 等)
Content事件内容 dict
Timestamp事件时间戳
SeqId单调递增的会话内序列号,用于断点续传
Metadata事件 metadata

5 分钟重连窗口

流式连接的最长生命周期为 5 分钟(deadline = now + 5min)。超时后连接会静默关闭, 不会下发 [DONE]。客户端应记录已消费的最大 SeqId,作为下一次 AfterSeqId 重连续订的起点;只要 run 未到终态,重连后即可继续收到后续事件。

终态状态(任一出现即下发 [DONE]):

status说明
completed正常完成
failed / error失败
cancelled / canceled已取消
aborted中止
interrupted中断
状态码场景detail
400SessionIdInvocationId 缺失SessionId and InvocationId are required

CancelRun

请求取消一个正在进行的 run(detached stream 与 runner 双通道)。

POST /agentengine/api/v1/CancelRun

字段类型必填说明
AgentIdstring目标 Agent id(当前未强制校验)
InvocationIdstring要取消的 run invocation id
request.json
{ "AgentId": "my-agent", "InvocationId": "inv_demo_001" }
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "CancelRun",
  "Data": {
    "Cancelled": true,
    "Found": true,
    "Status": "cancelling",
    "RunnerCancelStatus": "accepted"
  }
}
字段说明
Cancelled是否已发起取消(detached stream 或 runner 任一接受即 true
Found是否找到 detached stream
Status汇总状态:cancelling / not_found / unsupported / error
RunnerCancelStatusrunner 侧取消结果:accepted / cancelling / cancelled / not_found / unsupported / error

事件 Events

ListSessionEvents

分页列出某 session 的历史 events。无游标时 Offset / Limit 表示从最新事件窗口向前分页; AfterSeqId 用于断线后增量读取,BeforeSeqId 用于向上翻更早历史。

POST /agentengine/api/v1/ListSessionEvents

字段类型必填说明
SessionIdstring目标会话 id
Offsetint0-based 偏移,缺省 0
Limitint每页大小,最小 1
AfterSeqIdint0.6.9+ 返回 SeqId > AfterSeqId 的事件,用于重连补齐
BeforeSeqIdint0.6.9+ 返回 SeqId < BeforeSeqId 的事件,用于向前翻页
request.json
{ "SessionId": "local-demo-session", "Offset": 0, "Limit": 50 }
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "ListSessionEvents",
  "Data": {
    "Events": [ /* event payload,同 SubscribeRunEvents */ ],
    "Total": 128,
    "Offset": 0,
    "Limit": 50,
    "AfterSeqId": null,
    "BeforeSeqId": null
  }
}

分页字段:

字段说明
Total该 session 的事件总数
Offset当前偏移(缺省回填 0
Limit当前页大小(未传时回填为实际返回数)
AfterSeqId / BeforeSeqId请求中的 seq 游标原样回填;二者语义相反,不应混用

ListSessionMessages

把原始 event log 投影为前端可直接渲染的聊天消息列表。它会在服务端完成 assistant snapshot 去重、reasoning 归并、tool / approval 配对和附件规范化,避免客户端 从 ListSessionEvents 自行筛消息。

POST /agentengine/api/v1/ListSessionMessages

字段类型必填说明
AgentIdstring传入时 server 调 runtime ListSessionEvents 再统一投影;不传则 hosted 直连 session store
SessionIdstring目标会话 id
Limitint返回消息条数上限,默认 50,范围 1..200
AfterSeqIdint返回 SeqId > AfterSeqId 的增量消息;用于重连补齐,不截断到 Limit
BeforeSeqIdint返回 SeqId < BeforeSeqId 之前的最新一页消息;用于向上加载更早历史
IncludeReasoningbool是否在 assistant 消息中返回 Reasoning[]
IncludeToolEventsbool是否在 assistant 消息中返回 ToolEvents[]
IncludeAttachmentsbool是否在 user 消息中返回 Attachments[],默认 true
request.json
{
  "SessionId": "local-demo-session",
  "Limit": 50,
  "IncludeAttachments": true
}
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "ListSessionMessages",
  "Data": {
    "SessionId": "local-demo-session",
    "Messages": [
      {
        "MessageId": "evt_user_1",
        "Role": "user",
        "Content": {"text": "总结这个文件"},
        "SeqId": 21,
        "InvocationId": "inv_demo_001",
        "Timestamp": 1719900001.0,
        "Attachments": [
          {
            "file_uri": "ae-upload://abc123_report.pdf",
            "name": "report.pdf",
            "mime": "application/pdf",
            "size": 204800,
            "url": "/agentengine/api/v1/AttachmentContent?FileUri=ae-upload%3A%2F%2Fabc123_report.pdf",
            "is_image": false
          }
        ]
      },
      {
        "MessageId": "evt_assistant_1",
        "Role": "assistant",
        "Content": {"text": "文件摘要如下..."},
        "SeqId": 24,
        "InvocationId": "inv_demo_001",
        "ResponseId": "resp_a1b2c3",
        "TraceId": "trace_abc",
        "RootSpanId": "span_root"
      }
    ],
    "LatestSeqId": 24,
    "HasMore": true,
    "NextCursor": 20
  }
}

分页语义:

字段说明
LatestSeqId本页最后一条消息的 SeqId;可作为 SubscribeRunEvents(AfterSeqId=...) 的续订起点
HasMore是否还有更早消息可取
NextCursor向前翻页游标;下一次请求传 BeforeSeqId=NextCursor

重连判断

ListSessionMessages 只负责历史消息投影。是否需要重连运行中的 SSE,应读取 GetSession.ActiveRunStatus / ActiveInvocationId,再用 SubscribeRunEvents(AfterSeqId=LatestSeqId) 续订。

文件 Files

UploadFile

上传一个附件,返回 ae-upload:// 句柄,供后续 RunAgent / AttachmentContent 引用。

POST /agentengine/api/v1/UploadFilemultipart/form-data

字段类型必填说明
filebinary上传文件内容
upload
curl -sS https://<public-endpoint>/agentengine/api/v1/UploadFile \
  -H "Authorization: Bearer <api_key>" \
  -F "file=@report.pdf"
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "UploadFile",
  "Data": {
    "FileData": {
      "fileUri": "ae-upload://abc123_report.pdf",
      "displayName": "report.pdf",
      "mimeType": "application/pdf",
      "sizeBytes": 204800
    }
  }
}

AttachmentContent

ae-upload:// 句柄读取已上传附件的字节流,原样返回原始 content-type。

GET /agentengine/api/v1/AttachmentContent?FileUri=...

参数类型必填说明
FileUristringUploadFile 返回的 fileUri
download-url
/agentengine/api/v1/AttachmentContent?FileUri=ae-upload://abc123_report.pdf
binary
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Disposition: inline; filename="report.pdf"

<binary bytes>

前缀解析

ae-upload:// 前缀的路径定位托管上传内容并返回字节流;非 ae-upload:// 前缀的 路径按 workspace 相对路径处理。

状态码场景detail
404附件不存在Attachment not found

ListWorkspaceFiles

列出 workspace 文件条目(透传到 /_ksadk/workspace/v1/entries)。

POST /agentengine/api/v1/ListWorkspaceFiles

字段类型必填说明
AgentIdstring目标 Agent id(当前未强制校验)
Pathstringworkspace 下相对路径,缺省 .
Recursivebool是否递归列出,缺省 false
request.json
{ "Path": ".", "Recursive": true }
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "ListWorkspaceFiles",
  "Data": {
    "Entries": [
      { "Path": "notes/todo.md", "Type": "file" },
      { "Path": "notes/", "Type": "dir" }
    ]
  }
}

AddWorkspaceFile

新增或覆盖一个 workspace 文件(透传到 /_ksadk/workspace/v1/files/<path>)。

POST /agentengine/api/v1/AddWorkspaceFilemultipart/form-data

字段类型必填说明
filebinary上传文件内容
Pathstringworkspace 下相对路径
AgentIdstring目标 Agent id(当前未强制校验)
upload
curl -sS https://<public-endpoint>/agentengine/api/v1/AddWorkspaceFile \
  -H "Authorization: Bearer <api_key>" \
  -F "Path=notes/todo.md" \
  -F "file=@todo.md"
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "AddWorkspaceFile",
  "Data": { "Path": "notes/todo.md", "Size": 128 }
}

DeleteWorkspaceFile

删除一个 workspace 文件(透传到 /_ksadk/workspace/v1/files/<path>)。

POST /agentengine/api/v1/DeleteWorkspaceFile

字段类型必填说明
AgentIdstring目标 Agent id(当前未强制校验)
Pathstringworkspace 下相对路径
request.json
{ "Path": "notes/old.md" }
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "DeleteWorkspaceFile",
  "Data": { "Deleted": true }
}

GetWorkspaceFileContent

读取 workspace 文件内容,原样返回原始 content-type 与 content-disposition。

GET /agentengine/api/v1/GetWorkspaceFileContent?FilePath=...

参数类型必填说明
FilePathstringworkspace 下相对路径
AgentIdstring目标 Agent id(当前未强制校验)
download-url
/agentengine/api/v1/GetWorkspaceFileContent?FilePath=notes/todo.md
binary
HTTP/1.1 200 OK
Content-Type: text/markdown
Content-Disposition: inline; filename="todo.md"

<file bytes>

HTML 文件会经 preview CSP 注入后返回,便于在 hosted UI 内嵌预览。

ExportWorkspaceZip

把 workspace(或其子目录)打包成 zip 下载。

GET /agentengine/api/v1/ExportWorkspaceZip

参数类型必填说明
Pathstringworkspace 下相对目录,缺省 .
AgentIdstring目标 Agent id(当前未强制校验)
download-url
/agentengine/api/v1/ExportWorkspaceZip?Path=.
binary
HTTP/1.1 200 OK
Content-Type: application/zip
Content-Disposition: attachment; filename="workspace.zip"

<zip bytes>

文件名按 Path 派生:根目录为 workspace.zip,子目录为 workspace-<dir-with-dashes>.zip。打包时会跳过符号链接与越界路径,保证只含 workspace root 内的常规文件。

模型 Models

ListAgentModels

列出运行时可用模型目录,含当前模型与来源。

POST /agentengine/api/v1/ListAgentModels

字段类型必填说明
AgentIdstring目标 Agent id(当前未使用)
Namestring模型名过滤(当前未使用)
request.json
{}
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "ListAgentModels",
  "Data": {
    "Models": [
      {
        "id": "glm-5.1",
        "display_name": "glm-5.1",
        "context_window_tokens": 128000,
        "max_output_tokens": 32000,
        "capabilities": {
          "multimodal_input_image": true,
          "multimodal_input_video": false,
          "multimodal_input_file": false
        },
        "limits": {
          "context_window_tokens": 128000,
          "max_input_tokens": 128000,
          "max_output_tokens": 32000,
          "max_reasoning_tokens": 8192,
          "rpm": 600,
          "tpm": 200000
        },
        "pricing": {},
        "auto_compact_threshold_tokens": 102400,
        "auto_compact_threshold_percentage": 0.8
      }
    ],
    "Current": "glm-5.1",
    "Source": "OPENAI_MODEL_NAME"
  }
}

Models 元素字段(经 normalize_model_metadata 规范化):

字段说明
id / display_name模型 id 与展示名
context_window_tokens / max_output_tokens / max_input_tokens / max_reasoning_tokenstoken 上下文限制
capabilities能力集,含 multimodal_input_image/video/file
limits规范化后的限制 dict(rpm / tpm 等)
pricing价格 dict
auto_compact_threshold_tokens / _percentage自动压缩阈值

Current 为运行时当前模型,Source 标注来源环境变量 (OPENAI_MODEL_NAME / MODEL_NAME / COZE_MODEL_NAME)。OpenAI 兼容入口 GET /v1/models 返回相同 data,仅顶层 envelope 不同。

UI Bootstrap

GetAgentUiBootstrap

返回 hosted UI 渲染与能力探测所需的 bootstrap metadata。是 hosted UI 启动的 第一个调用。

POST /agentengine/api/v1/GetAgentUiBootstrap

字段类型必填说明
AgentIdstring目标 Agent id;缺省取运行时 Agent 名
SessionIdstring关联会话(原样回填到响应)
request.json
{ "AgentId": "my-agent", "SessionId": "local-demo-session" }
response.json
{
  "Code": 0,
  "Message": "Success",
  "RequestId": "req_abc123",
  "Action": "GetAgentUiBootstrap",
  "Data": {
    "Agent": {
      "AgentId": "my-agent",
      "Name": "my-agent",
      "Description": "demo agent",
      "Framework": "langgraph"
    },
    "Modules": ["Chat", "Build", "Deploy"],
    "Capabilities": {
      "Attachments": true,
      "WorkspaceFiles": true,
      "Approval": true,
      "Thinking": true,
      "StopRun": true,
      "ResumeRun": true,
      "RuntimeCapabilities": { /* runner.get_runtime_capabilities() 原样返回 */ },
      "CheckpointResumeCapability": {
        "Supported": true,
        "Checkpoint": {},
        "ResumeRun": {}
      },
      "RunLifecycle": {
        "Enabled": true,
        "Resume": true,
        "Abort": true,
        "Checkpoints": true,
        "CheckpointResume": true,
        "CheckpointResumePreview": true
      },
      "MCP": false,
      "HostedRuntime": false,
      "NativeTerminal": { "Enabled": false, "Mode": null, "Protocol": "ks-terminal.v1", "Path": null },
      "BuiltinTools": []
    },
    "WorkspaceFiles": { "Enabled": true },
    "AccessMode": "Owner",
    "SharePermissions": { "Interactive": true, "DefaultPath": "/chat", "SharePath": "/chat" },
    "CustomUI": {
      "Enabled": false,
      "Profile": null,
      "Path": null,
      "Url": null,
      "BundlePath": null
    },
    "ApiFormats": ["responses", "chat_completions"],
    "Stream": true,
    "SessionId": "local-demo-session",
    "SessionBackend": "memory",
    "HostedRuntime": null,
    "Model": { "id": "glm-5.1", "source": "OPENAI_MODEL_NAME", /* ... */ }
  }
}

顶层 Data 字段:

字段说明
AgentAgent id / 名 / 描述 / 框架(来自 detection_result)
ModulesUI 模块清单
Capabilities运行时能力集合,见下表
WorkspaceFilesworkspace files bootstrap
AccessMode访问模式,固定 Owner
SharePermissions分享与默认路径
CustomUI自定义 UI 资源信息(0.6.7 规范化)
ApiFormats支持的 API 形态:responseschat_completions
Stream是否支持流式
SessionBackendsession 后端描述(memory / postgres 等)
Model当前模型元数据

Capabilities 子字段:

字段说明
Attachments / WorkspaceFiles附件与 workspace files 能力
Approval / Thinking / StopRun / ResumeRunrun 控制类能力
RuntimeCapabilitiesrunner 原样返回的能力集合(含 CheckpointResumeRun 等)
CheckpointResumeCapability0.6.7 规范化:Supported + Checkpoint + ResumeRun 详情
RunLifecycle0.6.7 规范化:run 生命周期语义(ResumeAbortCheckpointsCheckpointResumeCheckpointResumePreview
MCP / HostedRuntime平台能力标记,当前固定 false
NativeTerminal终端能力(含 Enabled / Mode / Protocol / Path
BuiltinTools内置工具描述

CustomUI 子字段(0.6.7):

字段说明
Enabled是否启用自定义 UI
ProfileUI profile 名
Path / Url自定义 UI 路径或外链 URL
BundlePath自定义 UI bundle 路径

0.6.7 能力可见性

CheckpointResumeCapabilityRunLifecycle 是 0.6.7 规范化的能力描述。调用方 应以这两个字段为准判断 checkpoint/resume 是否可用;若 SupportedfalseRunLifecycle.CheckpointResumefalse,应视为不支持 checkpoint/resume。

Checkpoint 与 Resume Actions

新增:0.6.7

以下四个 action 路径均受 gateway Hosted UI 白名单放行,POST /agentengine/api/v1/*。公开 API 客户端通常不直接对接,优先用 /v1/*

Action方法与路径用途
ListSessionCheckpointsPOST /agentengine/api/v1/ListSessionCheckpoints列出某 session 下的 checkpoint,供 resume 选择
GetCheckpointResumePreviewPOST /agentengine/api/v1/GetCheckpointResumePreview预览从某 checkpoint resume 的内容与影响面
ResumeRunPOST /agentengine/api/v1/ResumeRun从 checkpoint 恢复 run 执行
CancelRunPOST /agentengine/api/v1/CancelRun取消正在进行的 run

能力可见性以 GetAgentUiBootstrap 返回的 RunLifecycleRuntimeCapabilities(含 CheckpointResumeCapability)为准。若 bootstrap 未声明该 能力,调用方应视为不支持 checkpoint/resume。

ListSessionCheckpoints

POST /agentengine/api/v1/ListSessionCheckpoints

字段类型必填说明
AgentId / SessionIdstring会话定位
RunIdstring按 run 过滤
Frameworkstring按框架过滤
OnlyResumablebool仅返回可恢复 checkpoint,缺省 false
Offset / Limitint分页,Limit 范围 1..500

返回 Checkpoints 数组,每个元素含 RunIdCheckpointIdFrameworkFrameworkRefIsResumableResumeStatusIsTerminalCheckpointStatusBackendScopeDurableResumeCountReplayAllowedExpiresAt 等。

GetCheckpointResumePreview

POST /agentengine/api/v1/GetCheckpointResumePreview

字段类型必填说明
AgentId / SessionIdstring会话定位
RunId / CheckpointIdstringcheckpoint 定位

返回 Preview,含 CheckpointCapabilitiesCanResumeReasonNextNodeExpectedActionToolReceiptsRisk(含 Level 与副作用计数)、 Summary

ResumeRun

POST /agentengine/api/v1/ResumeRun

字段类型必填说明
AgentId / SessionIdstring会话定位
RunId / CheckpointIdstringcheckpoint 定位
ResumeAttemptIdstringresume 尝试 id;缺省运行时生成
InvocationIdstring透传给 runner 的 invocation id
Streambooltrue 返回 SSE
Model / ModelMetadata / ModelOptionsstring / object模型参数透传
ResumeInstructionEnabledbool0.6.7 是否允许注入 resume instruction
ResumeInstructionstring0.6.7 resume instruction 文本

终态 checkpoint 会返回 status: "noop" 而非 409,避免阻塞 UI。非终态但不可恢复 时返回 409

GetAgentUiBootstrap

GetAgentUiBootstrap 返回 hosted UI 渲染与能力探测所需的 bootstrap metadata, 字段表见上文 UI Bootstrap 小节。

列表与分页字段

ListSessionsListSessionEvents 支持分页,但使用不同字段命名:

端点字段组字段
ListSessionspage-basedPagePageSizeTotal
ListSessionEventsoffset-basedOffsetLimitTotal
ListSessionCheckpointsoffset-basedOffsetLimitTotal

AttachmentContent 在解析 ae-upload:// 协议的 attachment 时,会按 ae-upload:// 前缀定位托管上传内容并返回其字节流;非 ae-upload:// 前缀的路径 按 workspace 相对路径处理。

RunAgent 透传字段

RunAgent(hosted UI action)与 /v1/responses/v1/chat/completions 一样会把 请求级模型参数透传给 runner:

字段含义
ModelMetadata模型元数据,含 reasoningmultimodalcontext_window_tokens
ModelOptions请求级模型选项(temperature、max_tokens 等)

ModelMetadata.reasoning 标注是否启用推理模式,multimodal 标注多模态能力, context_window_tokens 标注模型上下文窗口大小。

Workspace Files

代码框架运行时,以及启用 KsADK workspace surface 的运行时产品,都可以使用 workspace routes。

  • 列出文件。
  • 获取文件内容或 metadata。
  • 新增或更新文件。
  • 允许时删除文件。
  • 支持时导出 workspace archive。

Hosted UI 下载类 surface 通常包括:

  • GET /agentengine/api/v1/AttachmentContent
  • GET /agentengine/api/v1/GetWorkspaceFileContent
  • GET /agentengine/api/v1/ExportWorkspaceZip

所有路径都应是 workspace root 下的相对路径。公开示例不要暴露宿主机绝对路径。

Hermes 特有边界

Hermes 包装了自己的 dashboard 和 API server。公开文档只描述这些 surface:

Surface用途
/Hermes dashboard
/v1/*Hermes API proxy surface
/_ksadk/workspace/v1/*KsADK workspace files
/_ksadk/terminal/wsterminal WebSocket

终端客户端必须使用:

Sec-WebSocket-Protocol: ks-terminal.v1

OpenClaw 特有边界

OpenClaw 上游 gateway 拥有其原生路由。KsADK 公开文档只承诺平台补充 contract:

Surface用途
OpenClaw gateway rootOpenClaw 原生 UI 和 API
/_ksadk/workspace/v1/*KsADK workspace files
health route运行时产品暴露的 gateway liveness

不要把每个上游 OpenClaw 原生 endpoint 都写成 KsADK contract,除非它由 KsADK 实现或稳定化。

流式输出

流式调用使用 SSE:

Accept: text/event-stream

客户端应处理文本 delta、工具事件、错误和完成事件。LangGraph 与 ADK 内部事件 可能不同,但公开客户端应消费 runtime 归一化后的 stream。

公开文档规则

公开示例不得包含私有 endpoint hostname、真实 API key、gateway token、cookie、 kdocs token、内部 forwarded header、kubeconfig 路径、集群名称、私有镜像 registry、客户数据、session id 或 workspace 路径。

本页导航