🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
📝 docs(api): public API and SDK developer guide, versioning policy and changelog (#23351)
Arvin Xu79dcf87e8f07
diff --git a/docs/development/api/authentication.mdx b/docs/development/api/authentication.mdxnew file mode 100644index 00000000000..3597e4c598b--- /dev/null+++ b/docs/development/api/authentication.mdx@@ -0,0 +1,193 @@+---+title: LobeHub API Authentication, Workspaces, and Scopes+description: >-+ Authenticate LobeHub public API calls with an API key or an OIDC access token+ obtained with PKCE, select a Workspace, and choose API key scopes.+tags:+ - LobeHub+ - REST API+ - Authentication+ - OIDC+ - PKCE+ - API Key+---++# LobeHub API Authentication, Workspaces, and Scopes++Every `/api/v1` request except `GET /api/v1/health`, `/api/v1/openapi.json`, and `/api/v1/docs` must carry a bearer token:++```http+Authorization: Bearer <token>+```++The server decides what kind of token it is by its shape:++- A token in the API key format (`sk-lh-` plus 16 lowercase letters and digits) is looked up as an **API key**. The key must be enabled and not expired.+- Any other token is validated as an **OIDC access token** (an RS256 JWT for the audience `urn:lobehub:chat`), signed by the deployment's OIDC provider. Self-hosted instances accept OIDC tokens only when `JWKS_KEY` is configured.++There is no `X-API-Key` header. A missing or invalid token returns `401`.++## Choose a Credential++| You are building | Use |+| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |+| A server-side integration, script, or CI job acting as yourself | An API key with the narrowest scopes that work |+| A native or desktop app where each user signs in | OIDC authorization code with PKCE, with a public client the deployment provides (see [OIDC with PKCE](#oidc-with-pkce)) |+| A third-party web app that users authorize | An OAuth app registered in Settings: client secret plus PKCE (see below) |+| A command-line tool on a device without a browser | The OIDC device flow (used by the built-in `lobehub-cli` client) |++## API Keys++Create keys in **Settings → API Keys** of a Workspace (`/<workspace>/settings/apikey`). A key belongs to the person who created it and to that Workspace.++- What a key can do is the **intersection** of its creator's own permissions (Workspace role and RBAC) and the key's scopes. Scopes only narrow access; they never grant more than the creator has.+- The creator can change a key's scopes later on its detail page (**Edit permissions**). Workspace admins can revoke other members' keys but cannot change their scopes.+- A key created before scopes existed, or created with **Full access**, has every scope.++## OIDC with PKCE++LobeHub runs an OpenID Connect provider at `<origin>/oidc`.++| Endpoint | Path |+| -------------------- | ---------------------------------------- |+| Discovery | `/oidc/.well-known/openid-configuration` |+| Authorization | `/oidc/auth` |+| Token | `/oidc/token` |+| User info | `/oidc/me` |+| JWKS | `/oidc/jwks` |+| Device authorization | `/oidc/device/auth` |+| Revocation | `/oidc/token/revocation` |++PKCE is required for every authorization code request. Use `code_challenge_method=S256`.++Which client you can use:++- **LobeHub's own apps** use built-in public clients (`lobehub-desktop`, `lobehub-mobile`, and others). A public client has no secret, so the token request below sends only `client_id`.+- **Your own app on LobeHub Cloud** registers a web OAuth app in Settings (see [OAuth Apps](#oauth-apps)). It is a confidential client: add `client_secret` to the token request, and use an `https` or loopback `http` redirect URI. Custom URL schemes such as `myapp://` are not accepted for self-registered apps today.+- **Public clients for third-party native apps** become possible with dynamic client registration (`token_endpoint_auth_method: none`), which is coming soon in [#23322](https://github.com/lobehub/lobehub/pull/23322).++### Authorization Code Flow++1. Create a random `code_verifier` and its S256 `code_challenge` (base64url of the SHA-256 digest).++2. Open the authorization URL in the system browser:++ ```text+ https://app.lobehub.com/oidc/auth+ ?response_type=code+ &client_id=<client id>+ &redirect_uri=<registered redirect uri>+ &scope=openid profile email offline_access+ &resource=urn:lobehub:chat+ &code_challenge=<code_challenge>+ &code_challenge_method=S256+ &prompt=consent+ &state=<random state>+ ```++ `resource=urn:lobehub:chat` asks for an access token that `/api/v1` accepts. `offline_access` with `prompt=consent` returns a refresh token.++3. After sign-in, LobeHub redirects to `redirect_uri` with `code` and `state`. Reject the callback if `state` does not match.++4. Exchange the code:++ ```bash+ curl https://app.lobehub.com/oidc/token \+ -d grant_type=authorization_code \+ -d client_id=<client id> \+ -d code=<code> \+ -d redirect_uri=<redirect uri> \+ -d code_verifier=<code_verifier>+ # confidential clients (a web OAuth app) also send:+ # -d client_secret=<client secret>+ ```++5. Call the API with `Authorization: Bearer <access_token>`. Refresh with `grant_type=refresh_token` before it expires.++Refresh tokens rotate: every refresh returns a new refresh token and the old one stops working, so always store the latest. Refresh tokens and sessions last 30 days.++The TypeScript SDK implements these steps as `createPkcePair`, `createAuthorizationUrl`, `parseAuthorizationCallback`, `exchangeAuthorizationCode`, and `refreshAccessToken` for public clients; they do not send a client secret. See [SDKs](/docs/development/api/sdks#sign-in-with-oidc-and-pkce).++### OAuth Apps++To let other people authorize your application, register it in **Settings → OAuth Apps** (`/<workspace>/settings/oauth-apps`):++- A web app gets a client id `lca_…` and a client secret `lcs_…`, shown once. It uses the `authorization_code` and `refresh_token` grants with `client_secret_post`.+- A device app is a public client that uses the device flow.+- Redirect URIs must use `https`, or `http` on a loopback address. Wildcards are not allowed, and an app can have at most 20.++Today an OAuth access token is a full user token: it reaches the same API as its user, without scope narrowing.++<Callout type="info">+ **Coming soon** ([#23322](https://github.com/lobehub/lobehub/pull/23322)): fine-grained API scopes+ for OAuth tokens (the same names as API key scopes, shown on the consent page), dynamic client+ registration at `POST /oidc/reg` with a single-use registration token, and the+ `client_credentials` grant for server-to-server apps. Each is turned on per deployment with an+ environment variable.+</Callout>++## Workspace Selection++Requests run in either the caller's personal space or one Workspace. The Workspace is resolved from the credential and the optional `X-Workspace-Id` header:++| Credential | `X-Workspace-Id` | Result |+| ----------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------ |+| Workspace API key | Not sent | Runs in the key's Workspace |+| Workspace API key | Same Workspace | Runs in the key's Workspace |+| Workspace API key | Different Workspace | `403` `Workspace API Key cannot access a different workspace` |+| Personal API key | Sent | `403` `Personal API Key cannot access workspace data` |+| OIDC token | Sent | Runs in that Workspace if the user is a member, otherwise `403` `Not a member of this workspace` |+| OIDC token | Unknown Workspace id | `404` `Workspace not found` |+| Workspace API key | Its Workspace does not allow API keys | `403` `Workspace API Key access is not available` |++Inside a Workspace, some operations also need a minimum Workspace role (`viewer` \< `member` \< `admin` \< `owner`). A request below it returns `403` `Requires <role> role or higher`.++## Scopes++Scopes are defined in [`packages/const/src/apiKeyScope.ts`](https://github.com/lobehub/lobehub/blob/canary/packages/const/src/apiKeyScope.ts). A `:write` scope also grants the matching `:read` scope.++### Available Scopes++| Scope | Grants |+| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |+| `*` | Full access: everything the creator can do, except the explicit-only scopes listed below once they ship |+| `agent:read` / `agent:write` | Agents, Agent groups, tasks, goals, plugins, skills |+| `agent:credential:write` | Setting a password, token, or signing key on an Agent account (needs `agent:write` as well) |+| `chat:read` / `chat:write` | Topics, messages, threads, sessions, translations |+| `model:invoke` | Calling models: `POST /responses`, chat, image, video, speech, transcription. This is the scope that spends credits |+| `model:read` / `model:write` | Providers and model configuration |+| `file:read` / `file:write` | Files, uploads, parsing, and chunks |+| `knowledge:read` / `knowledge:write` | Libraries (knowledge bases), documents, chunks |+| `mcp:read` / `mcp:write` | MCP server configuration |+| `eval:read` / `eval:write` | Evaluations, Benchmarks, Datasets, Test Cases |+| `usage:read` | Usage and credit quota |+| `workspace:read` / `workspace:write` | Workspace details, members, audit log |+| `user:read` / `user:write` | The user profile, settings, Memory, notifications |++Some operations need several scopes. For example `POST /responses` needs `model:invoke`, `chat:write`, and `agent:write`, because it runs an Agent and writes the conversation.++Restricted keys can never reach API key management, roles and RBAC administration, or billing, whatever scopes they hold.++A scope check failure returns `403`. Once unified error codes ship, the code is `insufficient_scope`; see [Errors](/docs/development/api/conventions#error-codes).++### Coming Soon Scopes++These scopes are added by open pull requests together with the endpoints that need them:++| Scope | Endpoints | Pull request |+| --------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------- |+| `run:read` / `run:write` | `/runs` (Agent runs, events, cancel, steer, approvals) | [#23253](https://github.com/lobehub/lobehub/pull/23253) |+| `webhook:read` / `webhook:write` | `/webhooks` | [#23272](https://github.com/lobehub/lobehub/pull/23272) |+| `document:read` / `document:write` | `/documents`, `/notebooks` | [#23255](https://github.com/lobehub/lobehub/pull/23255) |+| `generation:read` / `generation:write` | `/images`, `/videos`, `/generations`, `/audio` | [#23267](https://github.com/lobehub/lobehub/pull/23267) |+| `tool:invoke` | `POST /tools/call` | [#23274](https://github.com/lobehub/lobehub/pull/23274) |+| `agent:transfer` | Moving an Agent to another Workspace or member | [#23292](https://github.com/lobehub/lobehub/pull/23292) |+| `share:read` / `share:write` | Public share links | [#23301](https://github.com/lobehub/lobehub/pull/23301) |+| `project:read` / `project:write`, `widget:read` / `widget:write` / `widget:publish`, `dashboard:read` / `dashboard:write`, `artifact:publish` | `/projects`, `/widgets`, `/dashboards`, artifact publishing | [#23311](https://github.com/lobehub/lobehub/pull/23311) |+| `oauth_app:read` / `oauth_app:write`, `trash:read` / `trash:write` | `/oauth-apps`, `/trash` | [#23315](https://github.com/lobehub/lobehub/pull/23315) |+| `device:read` / `device:operate` | `/devices`, sandboxes | [#23316](https://github.com/lobehub/lobehub/pull/23316) |+| `bot:read` / `bot:write` | `/bots` | [#23332](https://github.com/lobehub/lobehub/pull/23332) |++`device:operate` is planned as an **explicit** scope: full access does not include it, and it must be ticked by name when the key is created.++After [#23246](https://github.com/lobehub/lobehub/pull/23246) ships, each operation in the OpenAPI spec lists the scopes it needs under `x-required-scopes`, and the SDK shows them in each method's documentation.diff --git a/docs/development/api/authentication.zh-CN.mdx b/docs/development/api/authentication.zh-CN.mdxnew file mode 100644index 00000000000..cce99ee0a16--- /dev/null+++ b/docs/development/api/authentication.zh-CN.mdx@@ -0,0 +1,199 @@+---+title: LobeHub API 鉴权、工作区与 scope+description: >-+ 使用 API Key 或通过 PKCE 获取的 OIDC 访问令牌为 LobeHub 公开 API 调用鉴权,选择工作区,并为+ API Key 选择 scope。+tags:+ - LobeHub+ - REST API+ - 鉴权+ - OIDC+ - PKCE+ - API Key+---++# LobeHub API 鉴权、工作区与 scope++除 `GET /api/v1/health`、`/api/v1/openapi.json` 和 `/api/v1/docs` 外,每个 `/api/v1` 请求都必须携带 Bearer 令牌:++```http+Authorization: Bearer <token>+```++服务端根据令牌的形态判断其类型:++- 符合 API Key 格式(`sk-lh-` 加 16 位小写字母和数字)的令牌按 **API Key** 查找。Key 必须处于启用状态且未过期。+- 其他令牌一律按 **OIDC 访问令牌** 校验(受众为 `urn:lobehub:chat` 的 RS256 JWT),由部署自身的 OIDC 提供方签发。自托管实例只有在配置了 `JWKS_KEY` 时才接受 OIDC 令牌。++不存在 `X-API-Key` 请求头。缺少令牌或令牌无效时返回 `401`。++## 选择凭证++| 你要构建的是 | 使用 |+| ------------------------ | ------------------------------------------------------------------ |+| 以你本人身份运行的服务端集成、脚本或 CI 任务 | 仅授予必要最小 scope 的 API Key |+| 由每位用户各自登录的原生或桌面应用 | 带 PKCE 的 OIDC 授权码流程,使用部署提供的公开客户端(见 [OIDC 与 PKCE](#oidc-with-pkce)) |+| 由用户授权的第三方 Web 应用 | 在设置中注册的 OAuth 应用:客户端密钥加 PKCE(见下文) |+| 运行在无浏览器设备上的命令行工具 | OIDC 设备流程(内置的 `lobehub-cli` 客户端即使用此流程) |++## API Key++在工作区的 **设置 → API Keys**(`/<workspace>/settings/apikey`)中创建 Key。Key 属于创建它的人以及该工作区。++- Key 的权限是其创建者自身权限(工作区角色与 RBAC)与 Key 的 scope 的**交集**。scope 只会收窄访问范围,永远不会超出创建者拥有的权限。+- 创建者之后可以在 Key 详情页(**编辑权限**)修改 scope。工作区管理员可以吊销其他成员的 Key,但不能修改其 scope。+- 在 scope 机制引入之前创建的 Key,或以 **完全访问** 创建的 Key,拥有全部 scope。++<a id="oidc-with-pkce" />++## OIDC 与 PKCE++LobeHub 在 `<origin>/oidc` 运行 OpenID Connect 提供方。++| 端点 | 路径 |+| ---- | ---------------------------------------- |+| 发现 | `/oidc/.well-known/openid-configuration` |+| 授权 | `/oidc/auth` |+| 令牌 | `/oidc/token` |+| 用户信息 | `/oidc/me` |+| JWKS | `/oidc/jwks` |+| 设备授权 | `/oidc/device/auth` |+| 撤销 | `/oidc/token/revocation` |++每个授权码请求都必须使用 PKCE,且使用 `code_challenge_method=S256`。++可以使用哪种客户端:++- **LobeHub 自己的应用**使用内置的公开客户端(`lobehub-desktop`、`lobehub-mobile` 等)。公开客户端没有密钥,因此下面的令牌请求只发送 `client_id`。+- **你在 LobeHub Cloud 上的应用**需要在设置中注册 Web OAuth 应用(见 [OAuth 应用](#oauth-apps))。它是机密客户端:令牌请求需要附加 `client_secret`,重定向 URI 使用 `https` 或回环地址上的 `http`。自行注册的应用目前不支持 `myapp://` 这类自定义 URL scheme。+- **第三方原生应用的公开客户端**将随动态客户端注册(`token_endpoint_auth_method: none`)提供,即将推出,见 [#23322](https://github.com/lobehub/lobehub/pull/23322)。++### 授权码流程++1. 生成随机的 `code_verifier` 及其 S256 `code_challenge`(SHA-256 摘要的 base64url 编码)。++2. 在系统浏览器中打开授权 URL:++ ```text+ https://app.lobehub.com/oidc/auth+ ?response_type=code+ &client_id=<client id>+ &redirect_uri=<registered redirect uri>+ &scope=openid profile email offline_access+ &resource=urn:lobehub:chat+ &code_challenge=<code_challenge>+ &code_challenge_method=S256+ &prompt=consent+ &state=<random state>+ ```++ `resource=urn:lobehub:chat` 用于请求 `/api/v1` 接受的访问令牌。`offline_access` 配合 `prompt=consent` 会返回刷新令牌。++3. 登录后,LobeHub 携带 `code` 和 `state` 重定向到 `redirect_uri`。如果 `state` 不匹配,应拒绝该回调。++4. 兑换授权码:++ ```bash+ curl https://app.lobehub.com/oidc/token \+ -d grant_type=authorization_code \+ -d client_id=<client id> \+ -d code=<code> \+ -d redirect_uri=<redirect uri> \+ -d code_verifier=<code_verifier>+ # confidential clients (a web OAuth app) also send:+ # -d client_secret=<client secret>+ ```++5. 使用 `Authorization: Bearer <access_token>` 调用 API。在访问令牌过期前使用 `grant_type=refresh_token` 刷新。++刷新令牌会轮换:每次刷新都会返回新的刷新令牌,旧令牌随即失效,因此务必保存最新的那个。刷新令牌和会话有效期为 30 天。++TypeScript SDK 将上述步骤实现为 `createPkcePair`、`createAuthorizationUrl`、`parseAuthorizationCallback`、`exchangeAuthorizationCode` 和 `refreshAccessToken`,适用于公开客户端,不会发送客户端密钥。见 [SDK](/zh/docs/development/api/sdks#sign-in-with-oidc-and-pkce)。++<a id="oauth-apps" />++### OAuth 应用++如需让其他人授权你的应用,请在 **设置 → OAuth 应用**(`/<workspace>/settings/oauth-apps`)中注册:++- Web 应用会获得客户端 id `lca_…` 和客户端密钥 `lcs_…`,密钥只显示一次。它使用 `authorization_code` 和 `refresh_token` 授权类型,认证方式为 `client_secret_post`。+- 设备应用是使用设备流程的公开客户端。+- 重定向 URI 必须使用 `https`,或在回环地址上使用 `http`。不允许使用通配符,每个应用最多 20 个。++目前 OAuth 访问令牌是完整的用户令牌:它能访问的 API 与其用户相同,不做 scope 收窄。++<Callout type="info">+ **即将推出**([#23322](https://github.com/lobehub/lobehub/pull/23322)):OAuth 令牌的细粒度 API+ scope(名称与 API Key scope 相同,并显示在授权同意页上)、在 `POST /oidc/reg` 使用一次性注册令牌进行动态客户端注册,以及面向服务端到服务端应用的+ `client_credentials` 授权类型。每项能力都按部署通过环境变量开启。+</Callout>++<a id="workspace-selection" />++## 工作区选择++请求要么在调用者的个人空间中执行,要么在某一个工作区中执行。工作区由凭证和可选的 `X-Workspace-Id` 请求头决定:++| 凭证 | `X-Workspace-Id` | 结果 |+| ----------- | ------------------ | -------------------------------------------------------------- |+| 工作区 API Key | 未发送 | 在 Key 所属工作区中执行 |+| 工作区 API Key | 同一工作区 | 在 Key 所属工作区中执行 |+| 工作区 API Key | 不同工作区 | `403` `Workspace API Key cannot access a different workspace` |+| 个人 API Key | 已发送 | `403` `Personal API Key cannot access workspace data` |+| OIDC 令牌 | 已发送 | 用户是该工作区成员时在该工作区中执行,否则返回 `403` `Not a member of this workspace` |+| OIDC 令牌 | 未知的工作区 id | `404` `Workspace not found` |+| 工作区 API Key | 所属工作区不允许使用 API Key | `403` `Workspace API Key access is not available` |++在工作区内,部分操作还要求最低工作区角色(`viewer` \< `member` \< `admin` \< `owner`)。角色不足时返回 `403` `Requires <role> role or higher`。++<a id="scopes" />++## Scope++scope 定义在 [`packages/const/src/apiKeyScope.ts`](https://github.com/lobehub/lobehub/blob/canary/packages/const/src/apiKeyScope.ts) 中。`:write` scope 同时授予对应的 `:read` scope。++### 已可用的 scope++| Scope | 授予 |+| ------------------------------------ | ---------------------------------------------------- |+| `*` | 完全访问:创建者能做的一切,但不包括下文所列、上线后仅可显式授予的 scope |+| `agent:read` / `agent:write` | Agent、Agent 群组、任务、目标、插件、技能 |+| `agent:credential:write` | 为 Agent 账户设置密码、令牌或签名密钥(还需要 `agent:write`) |+| `chat:read` / `chat:write` | 话题、消息、子话题、会话、翻译 |+| `model:invoke` | 调用模型:`POST /responses`、聊天、图像、视频、语音、转写。这是会消耗额度的 scope |+| `model:read` / `model:write` | 模型服务商与模型配置 |+| `file:read` / `file:write` | 文件、上传、解析和分块 |+| `knowledge:read` / `knowledge:write` | 资源库(知识库)、文档、分块 |+| `mcp:read` / `mcp:write` | MCP 服务器配置 |+| `eval:read` / `eval:write` | 评测、Benchmark、数据集、测试用例 |+| `usage:read` | 用量与额度配额 |+| `workspace:read` / `workspace:write` | 工作区详情、成员、审计日志 |+| `user:read` / `user:write` | 用户资料、设置、记忆、通知 |++部分操作需要多个 scope。例如 `POST /responses` 需要 `model:invoke`、`chat:write` 和 `agent:write`,因为它会运行 Agent 并写入对话。++受限 Key 无论持有哪些 scope,都无法访问 API Key 管理、角色与 RBAC 管理或计费。++scope 校验失败时返回 `403`。统一错误码上线后,错误码为 `insufficient_scope`;见[错误](/zh/docs/development/api/conventions#error-codes)。++### 即将推出的 scope++以下 scope 由尚未合并的 Pull Request 与所需端点一同添加:++| Scope | 端点 | Pull Request |+| ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------------- |+| `run:read` / `run:write` | `/runs`(Agent 运行、事件、取消、引导、审批) | [#23253](https://github.com/lobehub/lobehub/pull/23253) |+| `webhook:read` / `webhook:write` | `/webhooks` | [#23272](https://github.com/lobehub/lobehub/pull/23272) |+| `document:read` / `document:write` | `/documents`、`/notebooks` | [#23255](https://github.com/lobehub/lobehub/pull/23255) |+| `generation:read` / `generation:write` | `/images`、`/videos`、`/generations`、`/audio` | [#23267](https://github.com/lobehub/lobehub/pull/23267) |+| `tool:invoke` | `POST /tools/call` | [#23274](https://github.com/lobehub/lobehub/pull/23274) |+| `agent:transfer` | 将 Agent 转移到其他工作区或成员 | [#23292](https://github.com/lobehub/lobehub/pull/23292) |+| `share:read` / `share:write` | 公开分享链接 | [#23301](https://github.com/lobehub/lobehub/pull/23301) |+| `project:read` / `project:write`、`widget:read` / `widget:write` / `widget:publish`、`dashboard:read` / `dashboard:write`、`artifact:publish` | `/projects`、`/widgets`、`/dashboards`、Artifact 发布 | [#23311](https://github.com/lobehub/lobehub/pull/23311) |+| `oauth_app:read` / `oauth_app:write`、`trash:read` / `trash:write` | `/oauth-apps`、`/trash` | [#23315](https://github.com/lobehub/lobehub/pull/23315) |+| `device:read` / `device:operate` | `/devices`、沙箱 | [#23316](https://github.com/lobehub/lobehub/pull/23316) |+| `bot:read` / `bot:write` | `/bots` | [#23332](https://github.com/lobehub/lobehub/pull/23332) |++`device:operate` 计划作为**显式** scope:完全访问不包含它,创建 Key 时必须单独勾选。++[#23246](https://github.com/lobehub/lobehub/pull/23246) 上线后,OpenAPI 规范中的每个操作都会在 `x-required-scopes` 下列出所需 scope,SDK 也会在每个方法的文档中展示这些 scope。diff --git a/docs/development/api/conventions.mdx b/docs/development/api/conventions.mdxnew file mode 100644index 00000000000..7c15d3aee44--- /dev/null+++ b/docs/development/api/conventions.mdx@@ -0,0 +1,177 @@+---+title: LobeHub API Errors, Pagination, Rate Limits, and Retries+description: >-+ Error format and error code catalog, pagination, rate limits, idempotency+ keys, and retry advice for the LobeHub public REST API.+tags:+ - LobeHub+ - REST API+ - Errors+ - Pagination+ - Rate Limit+ - Idempotency+---++# LobeHub API Errors, Pagination, Rate Limits, and Retries++This page describes the conventions shared by every `/api/v1` endpoint. Each section starts with today's behavior on `canary`, then the behavior added by [#23231](https://github.com/lobehub/lobehub/pull/23231), which is **coming soon**.++## Response Envelope++Successful JSON responses are wrapped:++```json+{ "success": true, "data": {}, "message": "optional", "timestamp": "2026-11-18T08:00:00.000Z" }+```++Every `DELETE` returns `{ "deleted": true, "id": "…" }`, or `{ "deleted": true, "count": 3 }` for bulk deletes. `GET /health` and streaming responses are not wrapped. `POST /responses` returns the OpenResponses object without the envelope.++## Errors++### Available: Current Error Body++```json+{ "success": false, "error": "Agent not found", "timestamp": "2026-11-18T08:00:00.000Z" }+```++Use the HTTP status to branch:++| Status | Meaning |+| ------ | ------------------------------------------------------------------------------------------------------------------------- |+| `400` | Validation failed or the request cannot be processed. For validation errors, `error` contains the serialized field errors |+| `401` | Missing, invalid, or expired credential |+| `403` | Authenticated but not allowed: missing scope, Workspace role, or Workspace mismatch |+| `404` | The resource does not exist or is not visible to the caller |+| `405` | Method not supported |+| `408` | Timeout |+| `409` | Conflicts with the current state of the resource |+| `412` | A precondition is not met, for example the task is archived |+| `413` | Request body too large |+| `422` | Valid request that cannot be applied |+| `429` | Too many requests |+| `500` | Unexpected server error |++### Coming Soon: Unified Error Body and Codes++[#23231](https://github.com/lobehub/lobehub/pull/23231) adds a stable `code`, a human-readable `message`, field `details`, and a `requestId` to every error. The old `error` field stays, with the same text as `message`, so current clients keep working.++```json+{+ "success": false,+ "code": "validation_error",+ "message": "Too big: expected number to be <=100",+ "details": [{ "path": "query.limit", "message": "Too big: expected number to be <=100" }],+ "error": "Too big: expected number to be <=100",+ "requestId": "req_6f1c2b…",+ "timestamp": "2026-11-18T08:00:00.000Z"+}+```++`details[].path` starts with the part of the request that failed: `json`, `query`, `param`, or `header`.++#### Error Codes++Codes are only ever added, never renamed or removed. Treat an unknown code by its HTTP status.++| Code | Status | Meaning | Retry |+| ---------------------- | --------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------- |+| `validation_error` | 400 | A field failed validation; see `details` | No, fix the request |+| `bad_request` | 400 | Understood but cannot be processed as sent | No |+| `unauthorized` | 401 | Missing, invalid, or expired credential | After refreshing the token |+| `payment_required` | 402 | Needs credits or a plan the caller does not have | No |+| `forbidden` | 403 | Authenticated but not allowed | No |+| `insufficient_scope` | 403 | The API key lacks a required scope | No, issue a key with the scope |+| `workspace_mismatch` | 403 | `X-Workspace-Id` does not match the key, or the caller is not a member | No |+| `not_found` | 404 | Does not exist or is not visible | No |+| `conflict` | 409 | Conflicts with the current resource state | After re-reading the resource |+| `idempotency_conflict` | 409 / 422 | 409: a request with this `Idempotency-Key` is still running. 422: the key was first used for a different request | 409: yes, with backoff. 422: no |+| `precondition_failed` | 412 | A precondition is not met | No |+| `payload_too_large` | 413 | Body exceeds the accepted size | No |+| `unprocessable_entity` | 422 | Valid but cannot be applied | No |+| `rate_limited` | 429 | Too many requests for this key | Yes, after `Retry-After` |+| `internal_error` | 500 | Unexpected error | Yes, with backoff |+| `upstream_error` | 502 | A model provider or other upstream failed | Yes, with backoff |+| `service_unavailable` | 503 | A dependency is temporarily unavailable | Yes, with backoff |++`POST /responses` keeps the OpenResponses error shape, `{ "error": { "type", "message", "code", "param" } }`, with `code` taken from the same catalog. The `/openai` and `/anthropic` compatible routes keep their vendors' error bodies.++#### Request IDs++Every response carries `X-Request-Id`. Send your own (up to 128 characters of letters, digits, `_`, `.`, `:`, `-`) to correlate logs; otherwise the server generates `req_…`. Include it when you report a problem.++## Pagination++### Available: Page Numbers++List endpoints accept `page` (from 1) and `pageSize` (1–100, default 20). Most also accept `keyword` (up to 100 characters). Responses name the array after the resource and include the total:++```json+{ "success": true, "data": { "agents": [], "total": 42 } }+```++Three lists are exceptions and return a bare array of every item today: `GET /agent-groups`, `GET /api-keys`, and `GET /mcp-servers`.++### Coming Soon: Cursors++With [#23231](https://github.com/lobehub/lobehub/pull/23231), lists accept `limit` (1–100, default 20) and `cursor`, and return `hasMore` and `nextCursor`:++```bash+curl "https://app.lobehub.com/api/v1/agent-groups?limit=50" -H "Authorization: Bearer $KEY"+# next page:+curl "https://app.lobehub.com/api/v1/agent-groups?limit=50&cursor=bzo1MA" -H "Authorization: Bearer $KEY"+```++```json+{ "success": true, "data": { "items": [], "total": 120, "hasMore": true, "nextCursor": "bzo1MA" } }+```++- Treat `nextCursor` as opaque and pass it back unchanged. It is `null` on the last page. An invalid cursor returns `400` `validation_error` on `query.cursor`.+- `total` is returned only where it is cheap to compute.+- New endpoints use `items`. Existing lists keep their array key (`agents`, `topics`, …) and gain `hasMore` and `nextCursor`.+- **Shape change:** `GET /agent-groups`, `GET /api-keys`, and `GET /mcp-servers` switch from a bare array to `{ items, total, hasMore, nextCursor }`. Send `format=array` (deprecated) to keep the old bare array with every item while you migrate.+- `page`, `pageSize`, and `offset` keep working but are deprecated. If several are sent, `cursor` wins over `offset`, which wins over `page`.++## Rate Limits++Today the public API does not send rate limit headers.++**Coming soon** ([#23231](https://github.com/lobehub/lobehub/pull/23231)): each API key gets a fixed window of 600 requests per 60 seconds by default (self-hosted instances set it with `OPENAPI_RATE_LIMIT_PER_MINUTE`). Every API key response then carries:++| Header | Meaning |+| ----------------------- | --------------------------------------- |+| `X-RateLimit-Limit` | Requests allowed in the window |+| `X-RateLimit-Remaining` | Requests left in the current window |+| `X-RateLimit-Reset` | When the window resets, in Unix seconds |++A request over the limit returns `429` `rate_limited` with `Retry-After` in seconds. The limit and its headers apply to API key requests only; OIDC sessions are not counted. On a self-hosted instance without Redis, requests are not limited and the headers are not sent.++## Idempotency++**Coming soon** ([#23231](https://github.com/lobehub/lobehub/pull/23231)): send `Idempotency-Key` on a `POST` to make it safe to retry.++```bash+curl https://app.lobehub.com/api/v1/agents \+ -H "Authorization: Bearer $KEY" \+ -H "Idempotency-Key: 0b8f6a52-6c1e-4b8a-9d55-3f0d7f2a91c4" \+ -H "Content-Type: application/json" \+ -d '{"title":"Researcher"}'+```++- The key is 1–255 characters; a UUID per logical operation works well.+- The first response is stored for 24 hours. Repeating the same method, path, query, and body with the same key returns the stored response with `Idempotent-Replayed: true`, without running the operation again.+- Keys are scoped to the caller and the Workspace, so two keys or two Workspaces never collide.+- Repeating while the first request is still running returns `409` `idempotency_conflict`. Reusing the key with a different body returns `422` `idempotency_conflict`.+- Error responses of `5xx` and `429`, streaming responses, and empty responses are not stored, so a retry runs the operation again.++## Retry Advice++| Situation | Retry? | How |+| ---------------------------------------------------------- | --------------------------------------- | -------------------------------------------------------------------------- |+| Network error or timeout on `GET`, `HEAD`, `PUT`, `DELETE` | Yes | Exponential backoff |+| Network error on `POST` | Only with `Idempotency-Key` | Same key, same body |+| `408`, `500`, `502`, `503`, `504` | Yes, for safe methods or a keyed `POST` | Exponential backoff with jitter |+| `429` | Yes | Wait for `Retry-After`; if it is very long, report back instead of waiting |+| `409` `idempotency_conflict` | Yes | Backoff; the first request is still running |+| Other `4xx` | No | Fix the request, credential, or scope |++A good default backoff is 0.5 s, doubling each attempt up to 8 s, with ±25% random jitter and at most 2 retries. This is the policy of the TypeScript and Python SDKs once [#23246](https://github.com/lobehub/lobehub/pull/23246) and [#23337](https://github.com/lobehub/lobehub/pull/23337) ship. The SDK returns the error without waiting when `Retry-After` is longer than 60 seconds. Never retry `PATCH` or an unkeyed `POST` automatically: it can apply the change twice.diff --git a/docs/development/api/conventions.zh-CN.mdx b/docs/development/api/conventions.zh-CN.mdxnew file mode 100644index 00000000000..5dd854bb402--- /dev/null+++ b/docs/development/api/conventions.zh-CN.mdx@@ -0,0 +1,178 @@+---+title: LobeHub API 错误、分页、限流与重试+description: >-+ LobeHub 公开 REST API 的错误格式与错误码目录、分页、限流、幂等键以及重试建议。+tags:+ - LobeHub+ - REST API+ - 错误+ - 分页+ - 限流+ - 幂等+---++# LobeHub API 错误、分页、限流与重试++本页介绍所有 `/api/v1` 端点共享的约定。每一节先说明 `canary` 上当前的行为,再说明由 [#23231](https://github.com/lobehub/lobehub/pull/23231) 新增、**即将推出**的行为。++## 响应信封++成功的 JSON 响应会被包裹:++```json+{ "success": true, "data": {}, "message": "optional", "timestamp": "2026-11-18T08:00:00.000Z" }+```++每个 `DELETE` 都返回 `{ "deleted": true, "id": "…" }`,批量删除返回 `{ "deleted": true, "count": 3 }`。`GET /health` 和流式响应不被包裹。`POST /responses` 返回不带信封的 OpenResponses 对象。++## 错误++### 已可用:当前错误体++```json+{ "success": false, "error": "Agent not found", "timestamp": "2026-11-18T08:00:00.000Z" }+```++使用 HTTP 状态码区分处理:++| 状态码 | 含义 |+| ----- | ------------------------------------- |+| `400` | 校验失败或请求无法处理。校验错误时,`error` 包含序列化后的字段错误 |+| `401` | 凭证缺失、无效或已过期 |+| `403` | 已通过鉴权但不被允许:缺少 scope、工作区角色不足或工作区不匹配 |+| `404` | 资源不存在,或对调用者不可见 |+| `405` | 不支持该方法 |+| `408` | 超时 |+| `409` | 与资源当前状态冲突 |+| `412` | 前置条件不满足,例如任务已归档 |+| `413` | 请求体过大 |+| `422` | 请求有效,但无法应用 |+| `429` | 请求过多 |+| `500` | 意外的服务端错误 |++### 即将推出:统一错误体与错误码++[#23231](https://github.com/lobehub/lobehub/pull/23231) 为每个错误添加稳定的 `code`、人类可读的 `message`、字段级 `details` 以及 `requestId`。原有的 `error` 字段保留,内容与 `message` 相同,因此现有客户端可以继续工作。++```json+{+ "success": false,+ "code": "validation_error",+ "message": "Too big: expected number to be <=100",+ "details": [{ "path": "query.limit", "message": "Too big: expected number to be <=100" }],+ "error": "Too big: expected number to be <=100",+ "requestId": "req_6f1c2b…",+ "timestamp": "2026-11-18T08:00:00.000Z"+}+```++`details[].path` 以请求中出错的部分开头:`json`、`query`、`param` 或 `header`。++<a id="error-codes" />++#### 错误码++错误码只会新增,不会重命名或删除。遇到未知错误码时,按其 HTTP 状态码处理。++| 错误码 | 状态码 | 含义 | 是否重试 |+| ---------------------- | --------- | -------------------------------------------------------- | ---------------------- |+| `validation_error` | 400 | 某个字段校验失败,见 `details` | 否,修正请求 |+| `bad_request` | 400 | 请求可以理解,但按原样无法处理 | 否 |+| `unauthorized` | 401 | 凭证缺失、无效或已过期 | 刷新令牌后重试 |+| `payment_required` | 402 | 需要调用者没有的额度或套餐 | 否 |+| `forbidden` | 403 | 已通过鉴权但不被允许 | 否 |+| `insufficient_scope` | 403 | API Key 缺少所需 scope | 否,签发带该 scope 的 Key |+| `workspace_mismatch` | 403 | `X-Workspace-Id` 与 Key 不匹配,或调用者不是成员 | 否 |+| `not_found` | 404 | 不存在或不可见 | 否 |+| `conflict` | 409 | 与资源当前状态冲突 | 重新读取资源后重试 |+| `idempotency_conflict` | 409 / 422 | 409:使用该 `Idempotency-Key` 的请求仍在执行。422:该 Key 首次用于另一个不同的请求 | 409:是,配合退避。422:否 |+| `precondition_failed` | 412 | 前置条件不满足 | 否 |+| `payload_too_large` | 413 | 请求体超过允许大小 | 否 |+| `unprocessable_entity` | 422 | 请求有效但无法应用 | 否 |+| `rate_limited` | 429 | 该 Key 请求过多 | 是,等待 `Retry-After` 后重试 |+| `internal_error` | 500 | 意外错误 | 是,配合退避 |+| `upstream_error` | 502 | 模型服务商或其他上游失败 | 是,配合退避 |+| `service_unavailable` | 503 | 某个依赖暂时不可用 | 是,配合退避 |++`POST /responses` 保持 OpenResponses 的错误结构 `{ "error": { "type", "message", "code", "param" } }`,其中 `code` 取自同一目录。`/openai` 和 `/anthropic` 兼容路由保留各自厂商的错误体。++#### 请求 ID++每个响应都携带 `X-Request-Id`。你可以自行发送(最多 128 个字符,允许字母、数字、`_`、`.`、`:`、`-`)以便关联日志;否则服务端会生成 `req_…`。反馈问题时请附上该 ID。++## 分页++### 已可用:页码++列表端点接受 `page`(从 1 开始)和 `pageSize`(1–100,默认 20)。大多数端点还接受 `keyword`(最多 100 个字符)。响应中的数组以资源名命名,并包含总数:++```json+{ "success": true, "data": { "agents": [], "total": 42 } }+```++有三个列表例外,目前直接返回包含全部条目的数组:`GET /agent-groups`、`GET /api-keys` 和 `GET /mcp-servers`。++### 即将推出:游标++在 [#23231](https://github.com/lobehub/lobehub/pull/23231) 中,列表接受 `limit`(1–100,默认 20)和 `cursor`,并返回 `hasMore` 和 `nextCursor`:++```bash+curl "https://app.lobehub.com/api/v1/agent-groups?limit=50" -H "Authorization: Bearer $KEY"+# next page:+curl "https://app.lobehub.com/api/v1/agent-groups?limit=50&cursor=bzo1MA" -H "Authorization: Bearer $KEY"+```++```json+{ "success": true, "data": { "items": [], "total": 120, "hasMore": true, "nextCursor": "bzo1MA" } }+```++- 将 `nextCursor` 视为不透明值,原样传回。最后一页时它为 `null`。无效游标会在 `query.cursor` 上返回 `400` `validation_error`。+- 只有在计算成本较低时才返回 `total`。+- 新端点使用 `items`。现有列表保留原来的数组键(`agents`、`topics` 等),并新增 `hasMore` 和 `nextCursor`。+- **返回结构变化:**`GET /agent-groups`、`GET /api-keys` 和 `GET /mcp-servers` 将从数组改为 `{ items, total, hasMore, nextCursor }`。迁移期间可以发送 `format=array`(已弃用)继续获得包含全部条目的旧数组。+- `page`、`pageSize` 和 `offset` 仍可使用,但已弃用。同时发送多个时,`cursor` 优先于 `offset`,`offset` 优先于 `page`。++## 限流++目前公开 API 不发送限流相关的响应头。++**即将推出**([#23231](https://github.com/lobehub/lobehub/pull/23231)):每个 API Key 默认获得每 60 秒 600 个请求的固定窗口(自托管实例通过 `OPENAPI_RATE_LIMIT_PER_MINUTE` 设置)。届时每个 API Key 请求的响应都会携带:++| 响应头 | 含义 |+| ----------------------- | ----------------- |+| `X-RateLimit-Limit` | 窗口内允许的请求数 |+| `X-RateLimit-Remaining` | 当前窗口剩余的请求数 |+| `X-RateLimit-Reset` | 窗口重置时间,单位为 Unix 秒 |++超出限制的请求返回 `429` `rate_limited`,并带有以秒为单位的 `Retry-After`。限流及其响应头只作用于 API Key 请求,OIDC 会话不计入。自托管实例未配置 Redis 时不限流,也不发送这些响应头。++## 幂等++**即将推出**([#23231](https://github.com/lobehub/lobehub/pull/23231)):在 `POST` 请求中发送 `Idempotency-Key`,即可安全重试。++```bash+curl https://app.lobehub.com/api/v1/agents \+ -H "Authorization: Bearer $KEY" \+ -H "Idempotency-Key: 0b8f6a52-6c1e-4b8a-9d55-3f0d7f2a91c4" \+ -H "Content-Type: application/json" \+ -d '{"title":"Researcher"}'+```++- Key 长度为 1–255 个字符;每个逻辑操作使用一个 UUID 即可。+- 首次响应会保存 24 小时。使用同一 Key 重复相同的方法、路径、查询参数和请求体时,返回已保存的响应并带上 `Idempotent-Replayed: true`,不会再次执行操作。+- Key 按调用者和工作区隔离,因此不同 API Key 或不同工作区之间不会冲突。+- 在首个请求仍在执行时重复请求,返回 `409` `idempotency_conflict`。用同一 Key 发送不同请求体,返回 `422` `idempotency_conflict`。+- `5xx` 和 `429` 错误响应、流式响应以及空响应不会被保存,因此重试会再次执行操作。++## 重试建议++| 情况 | 是否重试 | 方式 |+| ------------------------------------- | ----------------------- | ---------------------------------- |+| `GET`、`HEAD`、`PUT`、`DELETE` 出现网络错误或超时 | 是 | 指数退避 |+| `POST` 出现网络错误 | 仅在带 `Idempotency-Key` 时 | 相同 Key、相同请求体 |+| `408`、`500`、`502`、`503`、`504` | 是,限安全方法或带 Key 的 `POST` | 带抖动的指数退避 |+| `429` | 是 | 等待 `Retry-After`;如果时间很长,应向上报告而不是等待 |+| `409` `idempotency_conflict` | 是 | 退避;首个请求仍在执行 |+| 其他 `4xx` | 否 | 修正请求、凭证或 scope |++推荐的默认退避策略:初始 0.5 秒,每次翻倍,最长 8 秒,加 ±25% 随机抖动,最多重试 2 次。这也是 [#23246](https://github.com/lobehub/lobehub/pull/23246) 和 [#23337](https://github.com/lobehub/lobehub/pull/23337) 上线后 TypeScript 与 Python SDK 采用的策略。当 `Retry-After` 超过 60 秒时,SDK 不等待,直接返回错误。不要自动重试 `PATCH` 或不带 Key 的 `POST`:这可能导致变更被应用两次。diff --git a/docs/development/api/mcp-server.mdx b/docs/development/api/mcp-server.mdxnew file mode 100644index 00000000000..fa8e5f6dbd3--- /dev/null+++ b/docs/development/api/mcp-server.mdx@@ -0,0 +1,89 @@+---+title: Connect to LobeHub as an MCP Server+description: >-+ Use LobeHub from Claude Code, Cursor, or Codex through its MCP server at+ /api/v1/mcp: tools, resources, authentication, and scopes.+tags:+ - LobeHub+ - MCP+ - MCP Server+ - Claude Code+ - Cursor+---++# Connect to LobeHub as an MCP Server++<Callout type="info">+ **Coming soon** ([#23318](https://github.com/lobehub/lobehub/pull/23318)). The MCP server is not+ on LobeHub Cloud yet. It also depends on the Agent runs API+ ([#23253](https://github.com/lobehub/lobehub/pull/23253)) for its `run:*` scopes. Tool names and+ limits below come from the pull request and can change before release.+</Callout>++LobeHub can act as an [MCP](https://modelcontextprotocol.io) server, so a coding assistant or any MCP client can list your Agents, run one, and read Topics, messages, files, and Libraries.++The same pull request adds a user guide for this at `docs/usage/integrations/mcp-server`; this page is the developer reference.++This is the opposite direction from the MCP servers you add **to** LobeHub Agents (managed through `/api/v1/mcp-servers`, available today).++## Endpoint and Authentication++- URL: `https://app.lobehub.com/api/v1/mcp` (or `<your origin>/api/v1/mcp`)+- Transport: Streamable HTTP, stateless. Clients send JSON-RPC with `POST`; `GET` and `DELETE` return `405`.+- Authentication: the same as the REST API, `Authorization: Bearer <API key or OIDC token>`. Send `X-Workspace-Id` with an OIDC token to work in a Workspace; a Workspace API key uses its own Workspace.++The server only lists the tools your credential's scopes reach. Create a dedicated API key with only the scopes below that you want the assistant to have.++## Tools++| Tool | What it does | Scopes |+| ----------------------------------------------- | -------------------------------------------------------------------------- | --------------------------- |+| `list_agents`, `get_agent` | List Agents, read one | `agent:read` |+| `run_agent` | Run an Agent and wait for the reply (`waitSeconds`, default 50, up to 120) | `run:write`, `model:invoke` |+| `get_run` | Read a run's status and result | `run:read` |+| `search_topics`, `get_topic`, `search_messages` | Find and read conversations | `chat:read` |+| `list_files`, `read_file` | List and read files | `file:read` |+| `upload_file` | Upload a file | `file:write` |+| `list_knowledge_bases` | List Libraries | `knowledge:read` |++Resources: `lobehub://agents`, `lobehub://agents/{agentId}`, `lobehub://topics/{topicId}`. Prompt: `summarize_topic`.++When `run_agent` does not finish within `waitSeconds`, it returns the run id; call `get_run` later.++## Client Configuration++### Claude Code++```bash+claude mcp add --transport http lobehub https://app.lobehub.com/api/v1/mcp \+ --header "Authorization: Bearer sk-lh-your-key"+```++### Cursor++Add to `~/.cursor/mcp.json`:++```json+{+ "mcpServers": {+ "lobehub": {+ "url": "https://app.lobehub.com/api/v1/mcp",+ "headers": { "Authorization": "Bearer sk-lh-your-key" }+ }+ }+}+```++### Codex++Add to `~/.codex/config.toml` and export `LOBEHUB_API_KEY`:++```toml+[mcp_servers.lobehub]+url = "https://app.lobehub.com/api/v1/mcp"+bearer_token_env_var = "LOBEHUB_API_KEY"+```++## Check the Connection++After adding the server, ask the assistant to "list my LobeHub agents". It should call `list_agents` and show your Agents. If it reports `401`, check the key; if a tool is missing, the key lacks that tool's scope.diff --git a/docs/development/api/mcp-server.zh-CN.mdx b/docs/development/api/mcp-server.zh-CN.mdxnew file mode 100644index 00000000000..df318affc2f--- /dev/null+++ b/docs/development/api/mcp-server.zh-CN.mdx@@ -0,0 +1,88 @@+---+title: 将 LobeHub 作为 MCP Server 连接+description: >-+ 通过 /api/v1/mcp 上的 MCP Server,在 Claude Code、Cursor 或 Codex 中使用+ LobeHub:工具、资源、鉴权与 scope。+tags:+ - LobeHub+ - MCP+ - MCP Server+ - Claude Code+ - Cursor+---++# 将 LobeHub 作为 MCP Server 连接++<Callout type="info">+ **即将推出**([#23318](https://github.com/lobehub/lobehub/pull/23318))。MCP Server 尚未上线+ LobeHub Cloud,其 `run:*` scope 还依赖 Agent 运行 API([#23253](https://github.com/lobehub/lobehub/pull/23253))。+ 下文的工具名称和限制来自该 PR,正式发布前可能调整。+</Callout>++LobeHub 可以作为 [MCP](https://modelcontextprotocol.io) Server,让编码助手或任意 MCP 客户端列出你的 Agent、运行 Agent,并读取话题、消息、文件和资源库。++同一 PR 还在 `docs/usage/integrations/mcp-server` 添加了面向用户的使用指南;本页是开发者参考。++这与你**向** LobeHub Agent 添加 MCP Server 的方向相反(后者通过 `/api/v1/mcp-servers` 管理,现已可用)。++## 端点与鉴权++- URL:`https://app.lobehub.com/api/v1/mcp`(或 `<your origin>/api/v1/mcp`)+- 传输方式:Streamable HTTP,无状态。客户端用 `POST` 发送 JSON-RPC;`GET` 和 `DELETE` 返回 `405`。+- 鉴权:与 REST API 相同,`Authorization: Bearer <API key or OIDC token>`。使用 OIDC token 时,发送 `X-Workspace-Id` 以在工作区中操作;工作区 API Key 使用其所属的工作区。++服务器只列出凭证 scope 可访问的工具。建议单独创建一个 API Key,只授予你希望助手拥有的下列 scope。++## 工具++| 工具 | 作用 | Scope |+| --------------------------------------------- | ------------------------------------------ | -------------------------- |+| `list_agents`、`get_agent` | 列出 Agent,读取单个 Agent | `agent:read` |+| `run_agent` | 运行 Agent 并等待回复(`waitSeconds`,默认 50,最多 120) | `run:write`、`model:invoke` |+| `get_run` | 读取运行的状态和结果 | `run:read` |+| `search_topics`、`get_topic`、`search_messages` | 查找和读取对话 | `chat:read` |+| `list_files`、`read_file` | 列出和读取文件 | `file:read` |+| `upload_file` | 上传文件 | `file:write` |+| `list_knowledge_bases` | 列出资源库 | `knowledge:read` |++资源:`lobehub://agents`、`lobehub://agents/{agentId}`、`lobehub://topics/{topicId}`。提示词:`summarize_topic`。++如果 `run_agent` 未在 `waitSeconds` 内完成,会返回运行 id;稍后调用 `get_run` 获取结果。++## 客户端配置++### Claude Code++```bash+claude mcp add --transport http lobehub https://app.lobehub.com/api/v1/mcp \+ --header "Authorization: Bearer sk-lh-your-key"+```++### Cursor++添加到 `~/.cursor/mcp.json`:++```json+{+ "mcpServers": {+ "lobehub": {+ "url": "https://app.lobehub.com/api/v1/mcp",+ "headers": { "Authorization": "Bearer sk-lh-your-key" }+ }+ }+}+```++### Codex++添加到 `~/.codex/config.toml`,并导出 `LOBEHUB_API_KEY`:++```toml+[mcp_servers.lobehub]+url = "https://app.lobehub.com/api/v1/mcp"+bearer_token_env_var = "LOBEHUB_API_KEY"+```++## 检查连接++添加服务器后,让助手「list my LobeHub agents」。它应当调用 `list_agents` 并显示你的 Agent。如果返回 `401`,请检查 API Key;如果缺少某个工具,说明该 API Key 没有对应工具的 scope。diff --git a/docs/development/api/overview.mdx b/docs/development/api/overview.mdxnew file mode 100644index 00000000000..4d86693e307--- /dev/null+++ b/docs/development/api/overview.mdx@@ -0,0 +1,118 @@+---+title: LobeHub Public API Overview and Quick Start+description: >-+ Call the LobeHub public REST API and SDKs: what is available today, what is+ coming soon, and a first request with an API key.+tags:+ - LobeHub+ - REST API+ - SDK+ - OpenAPI+ - Developer Guide+---++# LobeHub Public API Overview and Quick Start++The public API lets your own application, script, or agent read and act on a LobeHub account or Workspace: Agents, Topics, messages, files, Libraries, tasks, goals, and model calls. It is a REST API under `/api/v1`, described by an OpenAPI 3.1 specification, with an official TypeScript SDK generated from that specification.++This guide only describes behavior that exists in LobeHub source code. Each capability carries one of two labels:++- **Available**: merged into the `canary` branch, which runs LobeHub Cloud.+- **Coming soon**: implemented in an open pull request that has not been merged. Names, fields, and limits can still change before release. Do not build production integrations on them yet.++## Guide Contents++| Page | What it covers |+| --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |+| [Authentication and Scopes](/docs/development/api/authentication) | API keys, OIDC with PKCE, OAuth apps, `X-Workspace-Id`, and the scope table |+| [Errors, Pagination, Rate Limits, and Retries](/docs/development/api/conventions) | Error format and code catalog, pagination, rate limits, `Idempotency-Key`, and retry advice |+| [Streaming, Runs, and Human Approval](/docs/development/api/streaming) | `POST /responses` stream events, Agent run events, approvals, and client tool results |+| [Webhooks](/docs/development/api/webhooks) | Event catalog, delivery format, and signature verification |+| [MCP Server](/docs/development/api/mcp-server) | Connecting Claude Code, Cursor, or Codex to LobeHub over MCP |+| [SDKs and File Uploads](/docs/development/api/sdks) | TypeScript and Python SDK examples, and uploading files |+| [Versioning, Deprecation, and Changelog](/docs/development/api/versioning) | Compatibility rules and the API changelog |++## Availability at a Glance++| Capability | Status | Source |+| ---------------------------------------------------------------------------- | ----------- | ------------------------------------------------------- |+| REST API under `/api/v1` with typed success responses | Available | [#23217](https://github.com/lobehub/lobehub/pull/23217) |+| API key and OIDC bearer authentication, `X-Workspace-Id` | Available | `packages/openapi/src/middleware` |+| TypeScript SDK `@lobehub/sdk` (`createLobeHub`, OAuth PKCE helpers) | Available | `packages/sdk` |+| `POST /responses` streaming, task runs, multipart file upload | Available | `packages/openapi/src/routes` |+| Unified error codes, cursor pagination, rate limits, idempotency | Coming soon | [#23231](https://github.com/lobehub/lobehub/pull/23231) |+| SDK retries, typed errors, `paginate`, `responses.stream`, `workspaceId` | Coming soon | [#23246](https://github.com/lobehub/lobehub/pull/23246) |+| Agent runs API with event stream and human approval | Coming soon | [#23253](https://github.com/lobehub/lobehub/pull/23253) |+| Developer webhooks with HMAC signatures | Coming soon | [#23272](https://github.com/lobehub/lobehub/pull/23272) |+| MCP server at `/api/v1/mcp` | Coming soon | [#23318](https://github.com/lobehub/lobehub/pull/23318) |+| OAuth open platform (dynamic registration, `client_credentials`, API scopes) | Coming soon | [#23322](https://github.com/lobehub/lobehub/pull/23322) |+| Python SDK `lobehub` | Coming soon | [#23337](https://github.com/lobehub/lobehub/pull/23337) |++The full list of merged and pending changes is in the [API Changelog](/docs/development/api/versioning#api-changelog).++## Quick Start++### 1. Create an API Key++1. Open the Workspace where your data lives and go to **Settings → API Keys** (`/<workspace>/settings/apikey`).+2. Create a key. Choose **Full access** or pick only the [scopes](/docs/development/api/authentication#scopes) your integration needs.+3. Copy the key. It starts with `sk-lh-` and is followed by 16 lowercase letters and digits.++You can change a key's scopes later on its detail page. Only the key's creator can do this.++### 2. Send a First Request++```bash+curl https://app.lobehub.com/api/v1/users/me \+ -H "Authorization: Bearer $LOBEHUB_API_KEY"+```++A successful response is wrapped in an envelope:++```json+{+ "success": true,+ "data": { "id": "user_…", "email": "…" },+ "timestamp": "2026-11-18T08:00:00.000Z"+}+```++For a self-hosted instance, replace `https://app.lobehub.com` with your deployment's origin. The base path is always `/api/v1`.++### 3. Choose the Workspace++A key created inside a Workspace is bound to it: requests run in that Workspace without extra headers. An OIDC access token can address a Workspace by sending its id:++```bash+curl https://app.lobehub.com/api/v1/agents \+ -H "Authorization: Bearer $ACCESS_TOKEN" \+ -H "X-Workspace-Id: $WORKSPACE_ID"+```++See [Workspace selection](/docs/development/api/authentication#workspace-selection) for the full rules.++### 4. Explore the Specification++- Interactive reference: `https://app.lobehub.com/api/v1/docs`+- Machine-readable spec: `https://app.lobehub.com/api/v1/openapi.json`+- Source spec in the repository: [`packages/openapi/openapi.yml`](https://github.com/lobehub/lobehub/blob/canary/packages/openapi/openapi.yml)++Internal application routes (`/trpc/*`, `/webapi/*`) are not part of the public API and can change without notice.++### 5. Use the TypeScript SDK++```bash+npm install @lobehub/sdk+```++```ts+import { createLobeHub } from '@lobehub/sdk';++const lobehub = createLobeHub({ apiKey: process.env.LOBEHUB_API_KEY! });++const { data, error } = await lobehub.agents.list();+if (error) throw new Error(JSON.stringify(error));+console.log(data.data.agents.map((agent) => agent.id));+```++More examples are in [SDKs and File Uploads](/docs/development/api/sdks).diff --git a/docs/development/api/overview.zh-CN.mdx b/docs/development/api/overview.zh-CN.mdxnew file mode 100644index 00000000000..09a8b26c613--- /dev/null+++ b/docs/development/api/overview.zh-CN.mdx@@ -0,0 +1,118 @@+---+title: LobeHub 公开 API 概览与快速开始+description: >-+ 调用 LobeHub 公开 REST API 与 SDK:当前已可用和即将推出的能力,以及如何用 API Key+ 发出第一个请求。+tags:+ - LobeHub+ - REST API+ - SDK+ - OpenAPI+ - 开发者指南+---++# LobeHub 公开 API 概览与快速开始++公开 API 让你自己的应用、脚本或 Agent 读取并操作 LobeHub 账户或工作区(Workspace)中的数据:Agent、话题、消息、文件、资源库、任务、目标和模型调用。它是位于 `/api/v1` 下的 REST API,由 OpenAPI 3.1 规范描述,并提供基于该规范生成的官方 TypeScript SDK。++本指南只描述 LobeHub 源码中已存在的行为。每项能力带有以下两种标签之一:++- **已可用**:已合并到 `canary` 分支,即 LobeHub Cloud 运行的分支。+- **即将推出**:已在尚未合并的 Pull Request 中实现。发布前名称、字段和限制仍可能变化,暂不要基于它们构建生产集成。++## 指南目录++| 页面 | 内容 |+| ---------------------------------------------------- | -------------------------------------------------------- |+| [鉴权与 scope](/zh/docs/development/api/authentication) | API Key、OIDC 与 PKCE、OAuth 应用、`X-Workspace-Id` 以及 scope 表 |+| [错误、分页、限流与重试](/zh/docs/development/api/conventions) | 错误格式与错误码目录、分页、限流、`Idempotency-Key` 和重试建议 |+| [流式、运行与人工审批](/zh/docs/development/api/streaming) | `POST /responses` 流式事件、Agent 运行事件、审批和客户端工具结果 |+| [Webhook](/zh/docs/development/api/webhooks) | 事件目录、投递格式和签名校验 |+| [MCP 服务器](/zh/docs/development/api/mcp-server) | 通过 MCP 将 Claude Code、Cursor 或 Codex 连接到 LobeHub |+| [SDK 与文件上传](/zh/docs/development/api/sdks) | TypeScript 和 Python SDK 示例,以及文件上传 |+| [版本、弃用与变更日志](/zh/docs/development/api/versioning) | 兼容性规则和 API 变更日志 |++## 可用性一览++| 能力 | 状态 | 来源 |+| -------------------------------------------------------------- | ---- | ------------------------------------------------------- |+| `/api/v1` 下的 REST API,成功响应带类型 | 已可用 | [#23217](https://github.com/lobehub/lobehub/pull/23217) |+| API Key 与 OIDC Bearer 鉴权、`X-Workspace-Id` | 已可用 | `packages/openapi/src/middleware` |+| TypeScript SDK `@lobehub/sdk`(`createLobeHub`、OAuth PKCE 辅助函数) | 已可用 | `packages/sdk` |+| `POST /responses` 流式、任务运行、multipart 文件上传 | 已可用 | `packages/openapi/src/routes` |+| 统一错误码、游标分页、限流、幂等 | 即将推出 | [#23231](https://github.com/lobehub/lobehub/pull/23231) |+| SDK 重试、类型化错误、`paginate`、`responses.stream`、`workspaceId` | 即将推出 | [#23246](https://github.com/lobehub/lobehub/pull/23246) |+| 带事件流和人工审批的 Agent 运行 API | 即将推出 | [#23253](https://github.com/lobehub/lobehub/pull/23253) |+| 带 HMAC 签名的开发者 Webhook | 即将推出 | [#23272](https://github.com/lobehub/lobehub/pull/23272) |+| 位于 `/api/v1/mcp` 的 MCP 服务器 | 即将推出 | [#23318](https://github.com/lobehub/lobehub/pull/23318) |+| OAuth 开放平台(动态注册、`client_credentials`、API scope) | 即将推出 | [#23322](https://github.com/lobehub/lobehub/pull/23322) |+| Python SDK `lobehub` | 即将推出 | [#23337](https://github.com/lobehub/lobehub/pull/23337) |++已合并和待合并变更的完整列表见 [API 变更日志](/zh/docs/development/api/versioning#api-changelog)。++## 快速开始++### 1. 创建 API Key++1. 打开数据所在的工作区,进入 **设置 → API Keys**(`/<workspace>/settings/apikey`)。+2. 创建一个 Key。选择 **完全访问**,或只勾选集成所需的 [scope](/zh/docs/development/api/authentication#scopes)。+3. 复制 Key。它以 `sk-lh-` 开头,后跟 16 位小写字母和数字。++之后可以在 Key 的详情页修改 scope,只有 Key 的创建者可以修改。++### 2. 发送第一个请求++```bash+curl https://app.lobehub.com/api/v1/users/me \+ -H "Authorization: Bearer $LOBEHUB_API_KEY"+```++成功响应包裹在信封结构中:++```json+{+ "success": true,+ "data": { "id": "user_…", "email": "…" },+ "timestamp": "2026-11-18T08:00:00.000Z"+}+```++自托管实例请将 `https://app.lobehub.com` 替换为你部署的源地址。基础路径始终是 `/api/v1`。++### 3. 选择工作区++在工作区内创建的 Key 绑定该工作区:请求无需额外请求头即在该工作区中执行。OIDC 访问令牌可通过发送工作区 id 指定工作区:++```bash+curl https://app.lobehub.com/api/v1/agents \+ -H "Authorization: Bearer $ACCESS_TOKEN" \+ -H "X-Workspace-Id: $WORKSPACE_ID"+```++完整规则见[工作区选择](/zh/docs/development/api/authentication#workspace-selection)。++### 4. 查阅规范++- 交互式参考:`https://app.lobehub.com/api/v1/docs`+- 机器可读规范:`https://app.lobehub.com/api/v1/openapi.json`+- 仓库中的源规范:[`packages/openapi/openapi.yml`](https://github.com/lobehub/lobehub/blob/canary/packages/openapi/openapi.yml)++应用内部路由(`/trpc/*`、`/webapi/*`)不属于公开 API,可能随时变更且不另行通知。++### 5. 使用 TypeScript SDK++```bash+npm install @lobehub/sdk+```++```ts+import { createLobeHub } from '@lobehub/sdk';++const lobehub = createLobeHub({ apiKey: process.env.LOBEHUB_API_KEY! });++const { data, error } = await lobehub.agents.list();+if (error) throw new Error(JSON.stringify(error));+console.log(data.data.agents.map((agent) => agent.id));+```++更多示例见 [SDK 与文件上传](/zh/docs/development/api/sdks)。diff --git a/docs/development/api/sdks.mdx b/docs/development/api/sdks.mdxnew file mode 100644index 00000000000..023f9ef2f03--- /dev/null+++ b/docs/development/api/sdks.mdx@@ -0,0 +1,269 @@+---+title: LobeHub TypeScript and Python SDKs and File Uploads+description: >-+ Call the LobeHub public API with @lobehub/sdk for TypeScript and the+ upcoming lobehub package for Python, and upload files over REST.+tags:+ - LobeHub+ - SDK+ - TypeScript+ - Python+ - File Upload+---++# LobeHub TypeScript and Python SDKs and File Uploads++Both SDKs are generated from the same OpenAPI specification, so resources and method names match: `agents.list` is `lobehub.agents.list()` in TypeScript and `client.agents.list()` in Python.++| SDK | Package | Status |+| ---------- | ------------------------------------------------------------------- | --------------------------------------------------------------------- |+| TypeScript | [`@lobehub/sdk`](https://www.npmjs.com/package/@lobehub/sdk) on npm | Available |+| Python | `lobehub` on PyPI | Coming soon ([#23337](https://github.com/lobehub/lobehub/pull/23337)) |++## TypeScript SDK++```bash+npm install @lobehub/sdk+```++### Create a Client++```ts+import { createLobeHub } from '@lobehub/sdk';++const lobehub = createLobeHub({+ apiKey: process.env.LOBEHUB_API_KEY!, // an API key (sk-lh-…) or an OIDC access token+ // baseURL: 'https://lobehub.example.com', // a self-hosted deployment+});+```++Options: `apiKey`, `accessToken` (a function returning the current token, which takes precedence over `apiKey`), `baseURL` (default `https://app.lobehub.com`), and any client option such as a custom `fetch` or `headers`.++### Call Methods++Resources follow the API's top-level paths (`agents`, `topics`, `messages`, `files`, `knowledgeBases`, `tasks`, `goals`, `responses`, …). Methods are `list`, `get`, `create`, `update`, and `delete`, plus named actions such as `files.uploadBatch`, `tasks.run`, and `users.me`.++Methods do not throw on HTTP errors. They return `{ data, error, response }`, where `data` is the full response envelope:++```ts+const { data, error } = await lobehub.agents.get({ path: { id: 'agt_xxx' } });+if (error) {+ console.error('Request failed', error);+} else {+ console.log(data.data.title);+}++const created = await lobehub.topics.create({+ body: { agentId: 'agt_xxx', title: 'Weekly review' },+});+```++Send `X-Workspace-Id` per call, or set it once with `headers`:++```ts+import { createLobeHub } from '@lobehub/sdk';++const team = createLobeHub({+ apiKey: process.env.LOBEHUB_TOKEN!,+ headers: { 'X-Workspace-Id': 'ws_xxx' },+});+```++### Stream a Response++```ts+const { response } = await lobehub.responses.create({+ body: { model: 'agt_xxx', input: 'Summarize my week', stream: true },+ parseAs: 'stream',+});+if (!response?.ok || !response.body) throw new Error(`Stream failed: ${response?.status}`);++const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();+let buffer = '';+while (true) {+ const { done, value } = 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').find((line) => line.startsWith('data: '));+ if (!data) continue;+ const event = JSON.parse(data.slice(6));+ if (event.type === 'response.output_text.delta') process.stdout.write(event.delta);+ }+}+```++Event types are listed in [Streaming](/docs/development/api/streaming#with-streaming).++### Sign In with OIDC and PKCE++For native and desktop apps where each user signs in through a **public client** (no client secret), such as LobeHub's built-in clients. These helpers never send a client secret, so they do not work with a web OAuth app registered in Settings, which is a confidential client; see [OIDC with PKCE](/docs/development/api/authentication#oidc-with-pkce).++```ts+import {+ createAuthorizationUrl,+ createLobeHub,+ createPkcePair,+ exchangeAuthorizationCode,+ parseAuthorizationCallback,+ refreshAccessToken,+} from '@lobehub/sdk';++const client = { clientId: 'your-public-client-id', redirectUri: 'http://127.0.0.1:8765/callback' };+const state = crypto.randomUUID();+const pkce = await createPkcePair();+const url = createAuthorizationUrl({ ...client, codeChallenge: pkce.challenge, state });+// open `url` in the system browser, then receive `callbackUrl`++const code = parseAuthorizationCallback(callbackUrl, state);+let tokens = await exchangeAuthorizationCode({ ...client, code, codeVerifier: pkce.verifier });++const lobehub = createLobeHub({+ accessToken: async () => {+ if (tokens.expiresAt - Date.now() < 60_000) {+ tokens = await refreshAccessToken({+ clientId: client.clientId,+ refreshToken: tokens.refreshToken!,+ });+ // persist tokens.refreshToken: refresh tokens rotate+ }+ return tokens.accessToken;+ },+});+```++A `LobeHubOAuthError` with `code: 'invalid_grant'` means the user has to sign in again.++### Coming Soon in the TypeScript SDK++[#23246](https://github.com/lobehub/lobehub/pull/23246) adds:++```ts+import { createLobeHub, LobeHubAPIError } from '@lobehub/sdk';++const lobehub = createLobeHub({+ apiKey: process.env.LOBEHUB_API_KEY!,+ workspaceId: 'ws_xxx', // sent as X-Workspace-Id+ maxRetries: 2, // default+ timeout: 600_000, // default, ms per attempt+});++// typed errors+const { error } = await lobehub.agents.get({ path: { id } });+if (error instanceof LobeHubAPIError && error.code === 'not_found') {+ // error.status, error.code, error.message, error.details, error.requestId+}++// a POST that is safe to retry+await lobehub.agents.create({ body: { title: 'Researcher' }, idempotencyKey: crypto.randomUUID() });++// walk every page+for await (const agent of lobehub.paginate(lobehub.agents.list, { query: { limit: 100 } })) {+ console.log(agent.id);+}++// typed stream events+const stream = lobehub.responses.stream({ model: 'agt_xxx', input: 'Summarize my week' });+for await (const event of stream) {+ if (event.type === 'response.output_text.delta') process.stdout.write(event.delta);+}++// upload from a path, Blob, File, or bytes+await lobehub.files.upload('./report.pdf', { knowledgeBaseId: 'kb_xxx' });+```++It also exports `LobeHubConnectionError` and `LobeHubTimeoutError`, lets you pass `throwOnError: true` to throw instead of returning `error`, and documents each method's API key scopes.++## Python SDK++<Callout type="info">+ **Coming soon** ([#23337](https://github.com/lobehub/lobehub/pull/23337)). The `lobehub` package+ is not published to PyPI yet. The examples below show the interface in that pull request and can+ change before release.+</Callout>++```bash+pip install lobehub+```++Python 3.9 or later. Both a sync client (`LobeHub`) and an async client (`AsyncLobeHub`) are provided. Methods return the `data` of the response envelope as plain dicts, typed with `TypedDict`.++```python+from lobehub import LobeHub, NotFoundError++client = LobeHub(api_key="sk-lh-...") # or set LOBEHUB_API_KEY; workspace_id="ws_..." for a Workspace++me = client.users.me()+print(me["id"])++for agent in client.agents.iter_list(limit=50):+ print(agent["id"], agent["title"])++agent = client.agents.create({"title": "Reviewer"}, idempotency_key="create-reviewer-1")++try:+ client.agents.get("agt_missing")+except NotFoundError as error:+ print(error.status_code, error.code, error.request_id)++with client.responses.stream({"model": "agt_...", "input": "Summarize my week"}) as stream:+ for event in stream:+ if event["type"] == "response.output_text.delta":+ print(event["delta"], end="", flush=True)+ final = stream.final_response()+```++```python+import asyncio+from lobehub import AsyncLobeHub+++async def main() -> None:+ async with AsyncLobeHub() as client:+ me = await client.users.me()+ print(me["id"])+++asyncio.run(main())+```++Options: `api_key`, `access_token` (string or callable), `base_url` (or `LOBEHUB_BASE_URL`), `workspace_id`, `timeout` (seconds, default 600), and `max_retries` (default 2). Errors are `APIError` subclasses by status (`BadRequestError`, `AuthenticationError`, `PermissionDeniedError`, `NotFoundError`, `ConflictError`, `UnprocessableEntityError`, `RateLimitError`, `InternalServerError`), and `APIConnectionError` / `APITimeoutError` when no answer arrives. `lobehub.oauth` provides the same PKCE helpers as the TypeScript SDK.++## File Uploads++Uploads are `multipart/form-data` and need the `file:write` scope.++| Endpoint | Fields |+| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |+| `POST /api/v1/files` | `file` (required); optional `knowledgeBaseId`, `agentId`, `sessionId`, `directory`, `skipCheckFileType`, `skipDeduplication` |+| `POST /api/v1/files/batches` | `files` (1–20 files); the same optional fields except `skipDeduplication` |++Limits: up to 100 MB per file, names up to 255 characters, and a type allowlist covering images, video, audio, text, PDF, Office documents, YAML, JSON, Markdown, and CSV. An upload can also be refused when the account is over its storage limit.++```bash+curl https://app.lobehub.com/api/v1/files \+ -H "Authorization: Bearer $LOBEHUB_API_KEY" \+ -F "file=@./report.pdf" \+ -F "knowledgeBaseId=kb_xxx"+```++```ts+import { readFile } from 'node:fs/promises';++const bytes = await readFile('./report.pdf');+const { data, error } = await lobehub.files.create({+ body: {+ file: new File([bytes], 'report.pdf', { type: 'application/pdf' }),+ knowledgeBaseId: 'kb_xxx',+ },+});+if (!error) console.log(data.data.file.id);+```++The response contains the file record, `{ file: { id, name, fileType, url, … } }`. After uploading:++- `GET /files/{id}/url?expiresIn=3600` returns a temporary download URL.+- `POST /files/{id}/parses` extracts the text; `POST /files/{id}/chunks` splits and embeds it for search.+- Adding `knowledgeBaseId` at upload puts the file in that Library directly.diff --git a/docs/development/api/sdks.zh-CN.mdx b/docs/development/api/sdks.zh-CN.mdxnew file mode 100644index 00000000000..9b7b187c94f--- /dev/null+++ b/docs/development/api/sdks.zh-CN.mdx@@ -0,0 +1,270 @@+---+title: LobeHub TypeScript 与 Python SDK 及文件上传+description: >-+ 使用 TypeScript 的 @lobehub/sdk 和即将推出的 Python 包 lobehub 调用 LobeHub+ 公开 API,并通过 REST 上传文件。+tags:+ - LobeHub+ - SDK+ - TypeScript+ - Python+ - 文件上传+---++# LobeHub TypeScript 与 Python SDK 及文件上传++两个 SDK 都由同一份 OpenAPI 规范生成,因此资源和方法名一致:`agents.list` 在 TypeScript 中是 `lobehub.agents.list()`,在 Python 中是 `client.agents.list()`。++| SDK | 包 | 状态 |+| ---------- | ------------------------------------------------------------------- | ------------------------------------------------------------- |+| TypeScript | npm 上的 [`@lobehub/sdk`](https://www.npmjs.com/package/@lobehub/sdk) | 已可用 |+| Python | PyPI 上的 `lobehub` | 即将推出([#23337](https://github.com/lobehub/lobehub/pull/23337)) |++## TypeScript SDK++```bash+npm install @lobehub/sdk+```++### 创建客户端++```ts+import { createLobeHub } from '@lobehub/sdk';++const lobehub = createLobeHub({+ apiKey: process.env.LOBEHUB_API_KEY!, // an API key (sk-lh-…) or an OIDC access token+ // baseURL: 'https://lobehub.example.com', // a self-hosted deployment+});+```++选项:`apiKey`、`accessToken`(返回当前 token 的函数,优先级高于 `apiKey`)、`baseURL`(默认 `https://app.lobehub.com`),以及任意客户端选项,如自定义 `fetch` 或 `headers`。++### 调用方法++资源与 API 的顶层路径对应(`agents`、`topics`、`messages`、`files`、`knowledgeBases`、`tasks`、`goals`、`responses`……)。方法包括 `list`、`get`、`create`、`update` 和 `delete`,以及 `files.uploadBatch`、`tasks.run`、`users.me` 等具名操作。++方法在 HTTP 出错时不会抛出异常,而是返回 `{ data, error, response }`,其中 `data` 是完整的响应信封:++```ts+const { data, error } = await lobehub.agents.get({ path: { id: 'agt_xxx' } });+if (error) {+ console.error('Request failed', error);+} else {+ console.log(data.data.title);+}++const created = await lobehub.topics.create({+ body: { agentId: 'agt_xxx', title: 'Weekly review' },+});+```++可以在每次调用时发送 `X-Workspace-Id`,也可以通过 `headers` 统一设置:++```ts+import { createLobeHub } from '@lobehub/sdk';++const team = createLobeHub({+ apiKey: process.env.LOBEHUB_TOKEN!,+ headers: { 'X-Workspace-Id': 'ws_xxx' },+});+```++### 流式获取响应++```ts+const { response } = await lobehub.responses.create({+ body: { model: 'agt_xxx', input: 'Summarize my week', stream: true },+ parseAs: 'stream',+});+if (!response?.ok || !response.body) throw new Error(`Stream failed: ${response?.status}`);++const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();+let buffer = '';+while (true) {+ const { done, value } = 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').find((line) => line.startsWith('data: '));+ if (!data) continue;+ const event = JSON.parse(data.slice(6));+ if (event.type === 'response.output_text.delta') process.stdout.write(event.delta);+ }+}+```++事件类型见[流式响应](/zh/docs/development/api/streaming#with-streaming)。++<a id="sign-in-with-oidc-and-pkce" />++### 使用 OIDC 和 PKCE 登录++适用于每位用户通过**公开客户端**(没有客户端密钥,例如 LobeHub 内置客户端)登录的原生应用和桌面应用。这些辅助函数不会发送客户端密钥,因此不适用于在设置中注册的 Web OAuth 应用(机密客户端);见 [OIDC 与 PKCE](/zh/docs/development/api/authentication#oidc-with-pkce)。++```ts+import {+ createAuthorizationUrl,+ createLobeHub,+ createPkcePair,+ exchangeAuthorizationCode,+ parseAuthorizationCallback,+ refreshAccessToken,+} from '@lobehub/sdk';++const client = { clientId: 'your-public-client-id', redirectUri: 'http://127.0.0.1:8765/callback' };+const state = crypto.randomUUID();+const pkce = await createPkcePair();+const url = createAuthorizationUrl({ ...client, codeChallenge: pkce.challenge, state });+// open `url` in the system browser, then receive `callbackUrl`++const code = parseAuthorizationCallback(callbackUrl, state);+let tokens = await exchangeAuthorizationCode({ ...client, code, codeVerifier: pkce.verifier });++const lobehub = createLobeHub({+ accessToken: async () => {+ if (tokens.expiresAt - Date.now() < 60_000) {+ tokens = await refreshAccessToken({+ clientId: client.clientId,+ refreshToken: tokens.refreshToken!,+ });+ // persist tokens.refreshToken: refresh tokens rotate+ }+ return tokens.accessToken;+ },+});+```++`code: 'invalid_grant'` 的 `LobeHubOAuthError` 表示用户需要重新登录。++### TypeScript SDK 即将推出的能力++[#23246](https://github.com/lobehub/lobehub/pull/23246) 新增:++```ts+import { createLobeHub, LobeHubAPIError } from '@lobehub/sdk';++const lobehub = createLobeHub({+ apiKey: process.env.LOBEHUB_API_KEY!,+ workspaceId: 'ws_xxx', // sent as X-Workspace-Id+ maxRetries: 2, // default+ timeout: 600_000, // default, ms per attempt+});++// typed errors+const { error } = await lobehub.agents.get({ path: { id } });+if (error instanceof LobeHubAPIError && error.code === 'not_found') {+ // error.status, error.code, error.message, error.details, error.requestId+}++// a POST that is safe to retry+await lobehub.agents.create({ body: { title: 'Researcher' }, idempotencyKey: crypto.randomUUID() });++// walk every page+for await (const agent of lobehub.paginate(lobehub.agents.list, { query: { limit: 100 } })) {+ console.log(agent.id);+}++// typed stream events+const stream = lobehub.responses.stream({ model: 'agt_xxx', input: 'Summarize my week' });+for await (const event of stream) {+ if (event.type === 'response.output_text.delta') process.stdout.write(event.delta);+}++// upload from a path, Blob, File, or bytes+await lobehub.files.upload('./report.pdf', { knowledgeBaseId: 'kb_xxx' });+```++它还导出 `LobeHubConnectionError` 和 `LobeHubTimeoutError`,支持传入 `throwOnError: true` 改为抛出异常而不是返回 `error`,并在文档中标注每个方法所需的 API Key scope。++## Python SDK++<Callout type="info">+ **即将推出**([#23337](https://github.com/lobehub/lobehub/pull/23337))。`lobehub` 包尚未发布到+ PyPI。以下示例展示的是该 PR 中的接口,正式发布前可能调整。+</Callout>++```bash+pip install lobehub+```++需要 Python 3.9 或更高版本。同时提供同步客户端(`LobeHub`)和异步客户端(`AsyncLobeHub`)。方法以普通 dict 返回响应信封中的 `data`,并用 `TypedDict` 标注类型。++```python+from lobehub import LobeHub, NotFoundError++client = LobeHub(api_key="sk-lh-...") # or set LOBEHUB_API_KEY; workspace_id="ws_..." for a Workspace++me = client.users.me()+print(me["id"])++for agent in client.agents.iter_list(limit=50):+ print(agent["id"], agent["title"])++agent = client.agents.create({"title": "Reviewer"}, idempotency_key="create-reviewer-1")++try:+ client.agents.get("agt_missing")+except NotFoundError as error:+ print(error.status_code, error.code, error.request_id)++with client.responses.stream({"model": "agt_...", "input": "Summarize my week"}) as stream:+ for event in stream:+ if event["type"] == "response.output_text.delta":+ print(event["delta"], end="", flush=True)+ final = stream.final_response()+```++```python+import asyncio+from lobehub import AsyncLobeHub+++async def main() -> None:+ async with AsyncLobeHub() as client:+ me = await client.users.me()+ print(me["id"])+++asyncio.run(main())+```++选项:`api_key`、`access_token`(字符串或可调用对象)、`base_url`(或 `LOBEHUB_BASE_URL`)、`workspace_id`、`timeout`(秒,默认 600)和 `max_retries`(默认 2)。错误按状态码分为 `APIError` 的各个子类(`BadRequestError`、`AuthenticationError`、`PermissionDeniedError`、`NotFoundError`、`ConflictError`、`UnprocessableEntityError`、`RateLimitError`、`InternalServerError`),未收到响应时抛出 `APIConnectionError` / `APITimeoutError`。`lobehub.oauth` 提供与 TypeScript SDK 相同的 PKCE 辅助函数。++## 文件上传++上传使用 `multipart/form-data`,需要 `file:write` scope。++| 端点 | 字段 |+| ---------------------------- | --------------------------------------------------------------------------------------------------------- |+| `POST /api/v1/files` | `file`(必填);可选 `knowledgeBaseId`、`agentId`、`sessionId`、`directory`、`skipCheckFileType`、`skipDeduplication` |+| `POST /api/v1/files/batches` | `files`(1–20 个文件);可选字段同上,但不含 `skipDeduplication` |++限制:单个文件最大 100 MB,文件名最长 255 个字符,文件类型需在允许列表内,涵盖图片、视频、音频、文本、PDF、Office 文档、YAML、JSON、Markdown 和 CSV。账户超出存储上限时,上传也可能被拒绝。++```bash+curl https://app.lobehub.com/api/v1/files \+ -H "Authorization: Bearer $LOBEHUB_API_KEY" \+ -F "file=@./report.pdf" \+ -F "knowledgeBaseId=kb_xxx"+```++```ts+import { readFile } from 'node:fs/promises';++const bytes = await readFile('./report.pdf');+const { data, error } = await lobehub.files.create({+ body: {+ file: new File([bytes], 'report.pdf', { type: 'application/pdf' }),+ knowledgeBaseId: 'kb_xxx',+ },+});+if (!error) console.log(data.data.file.id);+```++响应包含文件记录 `{ file: { id, name, fileType, url, … } }`。上传之后:++- `GET /files/{id}/url?expiresIn=3600` 返回临时下载 URL。+- `POST /files/{id}/parses` 提取文本;`POST /files/{id}/chunks` 对文本切分并向量化,以便搜索。+- 上传时附带 `knowledgeBaseId`,文件会直接放入对应资源库。diff --git a/docs/development/api/streaming.mdx b/docs/development/api/streaming.mdxnew file mode 100644index 00000000000..900d4801ace--- /dev/null+++ b/docs/development/api/streaming.mdx@@ -0,0 +1,175 @@+---+title: LobeHub API Streaming, Agent Runs, and Human Approval+description: >-+ Stream Agent replies from POST /responses, follow Agent run events, approve+ tool calls, and return client tool results through the LobeHub public API.+tags:+ - LobeHub+ - REST API+ - Streaming+ - SSE+ - Agent Runs+ - Human in the Loop+---++# LobeHub API Streaming, Agent Runs, and Human Approval++There are two ways to run an Agent over the public API:++- **`POST /responses`** (available): one request in, one reply out, optionally streamed. It follows the OpenResponses format, so OpenAI Responses clients work with small changes.+- **`/runs`** (coming soon, [#23253](https://github.com/lobehub/lobehub/pull/23253)): start a run in the background, then read its status and event stream, cancel or steer it, approve tool calls, and supply your own tool results.++Both stream with [Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html): `Content-Type: text/event-stream`, one `event:` line naming the type and one `data:` line of JSON per event.++## Responses++`POST /api/v1/responses` needs the scopes `model:invoke`, `chat:write`, and `agent:write`.++| Field | Notes |+| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |+| `model` | Required. The **Agent id** to run (`agt_…`) |+| `input` | Required. A string, or an array of `message`, `function_call`, and `function_call_output` items |+| `instructions` | Extra instructions for this request |+| `stream` | `true` to stream events |+| `previous_response_id` | Continue the conversation of an earlier response |+| `tools`, `tool_choice` | Your own function tools (`{ "type": "function", "name", "parameters" }`) and how the model may use them |+| `tools_mode` | `additional` (default: your tools plus the Agent's) or `exclusive` (only yours) |+| `max_output_tokens`, `temperature`, `top_p`, `reasoning`, `metadata` | Standard generation options |++### Without Streaming++The response is the bare response object (no `success` envelope). A run that fails still answers `200`, with `"status": "failed"` and an `error`. Always check `status`.++### With Streaming++```bash+curl -N https://app.lobehub.com/api/v1/responses \+ -H "Authorization: Bearer $LOBEHUB_API_KEY" \+ -H "Content-Type: application/json" \+ -d '{"model":"agt_xxx","input":"Summarize my week","stream":true}'+```++```text+event: response.created+data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_…","status":"in_progress",…}}++event: response.output_text.delta+data: {"type":"response.output_text.delta","sequence_number":4,"item_id":"msg_…","output_index":0,"content_index":0,"delta":"This week you…"}++event: response.completed+data: {"type":"response.completed","sequence_number":31,"response":{"id":"resp_…","status":"completed",…}}+```++Every event has `type` and `sequence_number`.++| Event | Extra fields |+| ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |+| `response.created`, `response.in_progress`, `response.completed`, `response.failed`, `response.incomplete` | `response` |+| `response.output_item.added`, `response.output_item.done` | `item`, `output_index` |+| `response.content_part.added`, `response.content_part.done` | `part`, `item_id`, `output_index`, `content_index` |+| `response.output_text.delta` | `delta`, `item_id`, `output_index`, `content_index` |+| `response.output_text.done` | `text`, `item_id`, `output_index`, `content_index` |+| `response.function_call_arguments.delta` / `.done` | `delta` / `arguments`, `item_id`, `output_index` |+| `response.reasoning_summary_text.delta` / `.done` | `delta` / `text`, `item_id`, `output_index` |++The stream ends after `response.completed`, `response.failed`, or `response.incomplete`. A `/responses` stream has no event ids and cannot be resumed, and there is no read endpoint for a finished response: re-sending with `previous_response_id` **starts a new Agent turn** on the same topic, so it repeats tool side effects instead of replaying the dropped output. If the connection drops, the run still finishes on the server and its reply lands in the Agent's topic, which you can open in the app. A replayable stream arrives with `/runs` ([#23253](https://github.com/lobehub/lobehub/pull/23253)): `GET /runs/{id}/events` serves stored events, each with an `id` you can resume after.++When the model calls one of your function tools, the response ends with a `function_call` output item. Run the tool yourself, then send a new request with `previous_response_id` and a `function_call_output` item carrying the same `call_id`.++## Agent Runs++<Callout type="info">+ **Coming soon** ([#23253](https://github.com/lobehub/lobehub/pull/23253)). The endpoints, events,+ and fields below come from that pull request and can change before release. They need the new+ `run:read` / `run:write` scopes; starting a run or resuming one also needs `model:invoke`.+</Callout>++Today you can already start a **task** run with `POST /api/v1/tasks/{id}/runs` (`202`, returns `operationId` and `topicId`) and list past runs with `GET /api/v1/tasks/{id}/runs`.++### Endpoints++| Method and path | Purpose |+| ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |+| `POST /runs` | Start a run of an Agent (`agentId`) or group (`groupId`). Returns `202` with the run `id` and `status: "queued"` or `"scheduled"` |+| `GET /runs/{id}` | Read a run: `status`, `result`, `usage`, `cost`, `pendingToolCalls`, `continuedByRunId`, … |+| `GET /runs/{id}/events` | Event stream (SSE) |+| `POST /runs/{id}/cancel` | Cancel a run |+| `GET /runs/{id}/interventions` | Tool calls waiting for a person |+| `POST /runs/{id}/interventions/{interventionId}` | Approve, reject, answer, or skip one |+| `POST /runs/{id}/tool-results` | Return results for your own function tools |+| `POST /runs/{id}/messages` | Steer a running Agent with an extra message |++`POST /runs` takes `input`, `agentId` or `groupId`, and optionally `topicId`, `fileIds`, `tools` (your function tools), `approvalMode` (`headless` by default, `manual`, `allow-list`, or `auto-run`), `allowList`, and `scheduledAt`.++Run statuses: `scheduled`, `queued`, `running`, `waiting_for_human`, `waiting_for_tool_results`, `waiting_for_async_tool`, and the final `completed`, `failed`, `cancelled`, `abandoned`.++### Run Events++Each SSE frame has `event: <type>`, `data: <json>`, and an `id:` when the event is stored. The JSON is `{ id, runId, stepIndex, timestamp, type, data }`.++| Event | `data` |+| ---------------------------------- | --------------------------------------------------------------- |+| `run.started` | `{}` |+| `step.started`, `step.completed` | `{ llmCalls }` |+| `message.delta`, `reasoning.delta` | `{ delta }` |+| `message.completed` | `{ content, reasoning, toolCalls }` |+| `tool_call.started` | `{ toolCall: { id, name, arguments } }` |+| `tool_call.completed` | `{ toolCall, content, isSuccess }` |+| `intervention.requested` | `{ interventions }` |+| `tool_results.required` | `{ toolCalls }` |+| `run.error` | `{ error }`, a step failed |+| `run.waiting` | `{ status: "waiting_for_human" \| "waiting_for_tool_results" }` |+| `run.completed` | `{ result: { content, messageId } \| null }` |+| `run.failed` | `{ error: { message, type } }` |+| `run.cancelled` | `{}` |++- The server closes the stream after `run.completed`, `run.failed`, `run.cancelled`, or `run.waiting`.+- **Resume** after a drop with the `Last-Event-ID` header (or `?after=<id>`), set to the last `id` you received. Without it the stream replays from the first event.+- A stream also closes after 5 minutes; reconnect with `Last-Event-ID` to continue. During quiet periods the server sends a `: ping` comment every 15 seconds.++## Human Approval++When a run uses `approvalMode: "manual"`, or `allow-list` and the tool is not on the list, the Agent stops before calling the tool and asks a person. `auto-run` also stops for calls that always need a person, such as a question to the user or a call flagged by the security check.++1. The stream sends `intervention.requested`, then `run.waiting` with `status: "waiting_for_human"`, and closes. A webhook subscriber also receives `run.intervention_requested`.++2. Read what is waiting:++ ```bash+ curl https://app.lobehub.com/api/v1/runs/$RUN_ID/interventions -H "Authorization: Bearer $KEY"+ ```++ Each item is `{ id, type: "approval" | "question", tool: { identifier, apiName, arguments } }`.++3. Resolve it. The body is one of:++ ```json+ { "action": "approve" }+ { "action": "reject", "reason": "Do not email customers", "continue": true }+ { "action": "answer", "content": "Use the EU region" }+ { "action": "skip" }+ ```++ ```bash+ curl -X POST https://app.lobehub.com/api/v1/runs/$RUN_ID/interventions/$INTERVENTION_ID \+ -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \+ -d '{"action":"approve"}'+ ```++4. The response contains `continuedByRunId`. The Agent continues in that **new run**: stream `GET /runs/{continuedByRunId}/events` to follow it. The waiting run does not resume under its own id.++## Client Tool Results++If you pass your own `tools` to `POST /runs`, the run pauses when the model calls one:++1. The stream sends `tool_results.required` with `toolCalls`, then `run.waiting` with `status: "waiting_for_tool_results"`.++2. Run the tools and send one result per pending call:++ ```bash+ curl -X POST https://app.lobehub.com/api/v1/runs/$RUN_ID/tool-results \+ -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \+ -d '{"results":[{"callId":"call_abc","output":"{\"temperature\":21}"}]}'+ ```++3. The run resumes under the **same** id. Reconnect to its event stream with `Last-Event-ID`.diff --git a/docs/development/api/streaming.zh-CN.mdx b/docs/development/api/streaming.zh-CN.mdxnew file mode 100644index 00000000000..2948901ab0d--- /dev/null+++ b/docs/development/api/streaming.zh-CN.mdx@@ -0,0 +1,178 @@+---+title: LobeHub API 流式、Agent 运行与人工审批+description: >-+ 通过 LobeHub 公开 API 从 POST /responses 流式获取 Agent 回复、跟踪 Agent 运行事件、审批工具调用并回传客户端工具结果。+tags:+ - LobeHub+ - REST API+ - 流式+ - SSE+ - Agent 运行+ - 人工审批+---++# LobeHub API 流式、Agent 运行与人工审批++通过公开 API 运行 Agent 有两种方式:++- **`POST /responses`**(已可用):一个请求输入,一个回复输出,可选流式。它遵循 OpenResponses 格式,OpenAI Responses 客户端稍作修改即可使用。+- **`/runs`**(即将推出,[#23253](https://github.com/lobehub/lobehub/pull/23253)):在后台启动运行,然后读取其状态和事件流、取消或引导运行、审批工具调用,并提供你自己的工具结果。++两者都使用 [Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html) 进行流式传输:`Content-Type: text/event-stream`,每个事件包含一行指明类型的 `event:` 和一行 JSON 格式的 `data:`。++## Responses++`POST /api/v1/responses` 需要 `model:invoke`、`chat:write` 和 `agent:write` 三个 scope。++| 字段 | 说明 |+| ---------------------------------------------------------------- | ------------------------------------------------------------------- |+| `model` | 必填。要运行的 **Agent id**(`agt_…`) |+| `input` | 必填。字符串,或由 `message`、`function_call`、`function_call_output` 项组成的数组 |+| `instructions` | 本次请求的额外指令 |+| `stream` | 设为 `true` 以流式返回事件 |+| `previous_response_id` | 延续某个先前响应的对话 |+| `tools`、`tool_choice` | 你自己的函数工具(`{ "type": "function", "name", "parameters" }`)以及模型使用它们的方式 |+| `tools_mode` | `additional`(默认:你的工具加上 Agent 的工具)或 `exclusive`(仅使用你的工具) |+| `max_output_tokens`、`temperature`、`top_p`、`reasoning`、`metadata` | 标准生成选项 |++### 非流式++响应是裸的响应对象(没有 `success` 信封)。运行失败时仍返回 `200`,并带有 `"status": "failed"` 和 `error`。务必检查 `status`。++<a id="with-streaming" />++### 流式++```bash+curl -N https://app.lobehub.com/api/v1/responses \+ -H "Authorization: Bearer $LOBEHUB_API_KEY" \+ -H "Content-Type: application/json" \+ -d '{"model":"agt_xxx","input":"Summarize my week","stream":true}'+```++```text+event: response.created+data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_…","status":"in_progress",…}}++event: response.output_text.delta+data: {"type":"response.output_text.delta","sequence_number":4,"item_id":"msg_…","output_index":0,"content_index":0,"delta":"This week you…"}++event: response.completed+data: {"type":"response.completed","sequence_number":31,"response":{"id":"resp_…","status":"completed",…}}+```++每个事件都有 `type` 和 `sequence_number`。++| 事件 | 额外字段 |+| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------ |+| `response.created`、`response.in_progress`、`response.completed`、`response.failed`、`response.incomplete` | `response` |+| `response.output_item.added`、`response.output_item.done` | `item`、`output_index` |+| `response.content_part.added`、`response.content_part.done` | `part`、`item_id`、`output_index`、`content_index` |+| `response.output_text.delta` | `delta`、`item_id`、`output_index`、`content_index` |+| `response.output_text.done` | `text`、`item_id`、`output_index`、`content_index` |+| `response.function_call_arguments.delta` / `.done` | `delta` / `arguments`、`item_id`、`output_index` |+| `response.reasoning_summary_text.delta` / `.done` | `delta` / `text`、`item_id`、`output_index` |++流在 `response.completed`、`response.failed` 或 `response.incomplete` 之后结束。`/responses` 流没有事件 id,无法恢复;已结束的响应也没有读取端点——用 `previous_response_id` 重新发起请求**会开启新的一轮 Agent 运行**(topic 相同),重复工具副作用而不是重放中断掉的输出。连接中断时,运行仍会在服务端跑完,回复写进该 Agent 的 topic,可在应用内查看。可重放的流随 `/runs`([#23253](https://github.com/lobehub/lobehub/pull/23253))提供:`GET /runs/{id}/events` 返回已存储的事件,每条带 `id`,可据此续读。++当模型调用你的某个函数工具时,响应以一个 `function_call` 输出项结束。请自行执行该工具,然后携带 `previous_response_id` 和一个使用相同 `call_id` 的 `function_call_output` 项发送新请求。++## Agent 运行++<Callout type="info">+ **即将推出**([#23253](https://github.com/lobehub/lobehub/pull/23253))。下文的端点、事件和字段来自该+ Pull Request,发布前可能变化。它们需要新的 `run:read` / `run:write` scope;启动或恢复运行还需要+ `model:invoke`。+</Callout>++目前你已经可以通过 `POST /api/v1/tasks/{id}/runs` 启动**任务**运行(返回 `202`,包含 `operationId` 和 `topicId`),并通过 `GET /api/v1/tasks/{id}/runs` 列出历史运行。++### 端点++| 方法与路径 | 用途 |+| ------------------------------------------------ | --------------------------------------------------------------------------------------------- |+| `POST /runs` | 启动 Agent(`agentId`)或群组(`groupId`)的运行。返回 `202`,包含运行 `id` 以及 `status: "queued"` 或 `"scheduled"` |+| `GET /runs/{id}` | 读取运行:`status`、`result`、`usage`、`cost`、`pendingToolCalls`、`continuedByRunId` 等 |+| `GET /runs/{id}/events` | 事件流(SSE) |+| `POST /runs/{id}/cancel` | 取消运行 |+| `GET /runs/{id}/interventions` | 等待人工处理的工具调用 |+| `POST /runs/{id}/interventions/{interventionId}` | 批准、拒绝、回答或跳过其中一项 |+| `POST /runs/{id}/tool-results` | 回传你自己的函数工具的结果 |+| `POST /runs/{id}/messages` | 通过追加消息引导正在运行的 Agent |++`POST /runs` 接受 `input`、`agentId` 或 `groupId`,以及可选的 `topicId`、`fileIds`、`tools`(你的函数工具)、`approvalMode`(默认 `headless`,可选 `manual`、`allow-list` 或 `auto-run`)、`allowList` 和 `scheduledAt`。++运行状态:`scheduled`、`queued`、`running`、`waiting_for_human`、`waiting_for_tool_results`、`waiting_for_async_tool`,以及终态 `completed`、`failed`、`cancelled`、`abandoned`。++### 运行事件++每个 SSE 帧包含 `event: <type>`、`data: <json>`,事件被存储时还带有 `id:`。JSON 结构为 `{ id, runId, stepIndex, timestamp, type, data }`。++| 事件 | `data` |+| --------------------------------- | --------------------------------------------------------------- |+| `run.started` | `{}` |+| `step.started`、`step.completed` | `{ llmCalls }` |+| `message.delta`、`reasoning.delta` | `{ delta }` |+| `message.completed` | `{ content, reasoning, toolCalls }` |+| `tool_call.started` | `{ toolCall: { id, name, arguments } }` |+| `tool_call.completed` | `{ toolCall, content, isSuccess }` |+| `intervention.requested` | `{ interventions }` |+| `tool_results.required` | `{ toolCalls }` |+| `run.error` | `{ error }`,某个步骤失败 |+| `run.waiting` | `{ status: "waiting_for_human" \| "waiting_for_tool_results" }` |+| `run.completed` | `{ result: { content, messageId } \| null }` |+| `run.failed` | `{ error: { message, type } }` |+| `run.cancelled` | `{}` |++- 服务端在 `run.completed`、`run.failed`、`run.cancelled` 或 `run.waiting` 之后关闭流。+- 连接中断后,使用 `Last-Event-ID` 请求头(或 `?after=<id>`)**恢复**,值为你收到的最后一个 `id`。不带它时,流会从第一个事件开始重放。+- 流也会在 5 分钟后关闭;使用 `Last-Event-ID` 重新连接即可继续。空闲期间,服务端每 15 秒发送一次 `: ping` 注释。++<a id="human-approval" />++## 人工审批++当运行使用 `approvalMode: "manual"`,或使用 `allow-list` 且工具不在列表中时,Agent 会在调用工具前停下并请求人工处理。`auto-run` 模式下,始终需要人工处理的调用(例如向用户提问,或被安全检查拦下的调用)同样会停下。++1. 流发送 `intervention.requested`,随后发送 `status: "waiting_for_human"` 的 `run.waiting`,然后关闭。Webhook 订阅者也会收到 `run.intervention_requested`。++2. 读取待处理项:++ ```bash+ curl https://app.lobehub.com/api/v1/runs/$RUN_ID/interventions -H "Authorization: Bearer $KEY"+ ```++ 每一项为 `{ id, type: "approval" | "question", tool: { identifier, apiName, arguments } }`。++3. 处理该项。请求体为以下之一:++ ```json+ { "action": "approve" }+ { "action": "reject", "reason": "Do not email customers", "continue": true }+ { "action": "answer", "content": "Use the EU region" }+ { "action": "skip" }+ ```++ ```bash+ curl -X POST https://app.lobehub.com/api/v1/runs/$RUN_ID/interventions/$INTERVENTION_ID \+ -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \+ -d '{"action":"approve"}'+ ```++4. 响应包含 `continuedByRunId`。Agent 在这个**新运行**中继续:订阅 `GET /runs/{continuedByRunId}/events` 跟踪它。等待中的运行不会以原 id 恢复。++## 客户端工具结果++如果你在 `POST /runs` 中传入了自己的 `tools`,模型调用其中之一时运行会暂停:++1. 流发送带 `toolCalls` 的 `tool_results.required`,随后发送 `status: "waiting_for_tool_results"` 的 `run.waiting`。++2. 执行这些工具,并为每个待处理调用发送一个结果:++ ```bash+ curl -X POST https://app.lobehub.com/api/v1/runs/$RUN_ID/tool-results \+ -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \+ -d '{"results":[{"callId":"call_abc","output":"{\"temperature\":21}"}]}'+ ```++3. 运行以**同一个** id 恢复。使用 `Last-Event-ID` 重新连接其事件流。diff --git a/docs/development/api/versioning.mdx b/docs/development/api/versioning.mdxnew file mode 100644index 00000000000..a1b08dd842e--- /dev/null+++ b/docs/development/api/versioning.mdx@@ -0,0 +1,102 @@+---+title: LobeHub API Versioning, Deprecation, and Changelog+description: >-+ How the LobeHub public API and SDKs are versioned, what counts as a breaking+ change, how deprecations are announced, and the API changelog.+tags:+ - LobeHub+ - REST API+ - Versioning+ - Deprecation+ - Changelog+---++# LobeHub API Versioning, Deprecation, and Changelog++## Versioning++- **The major version is in the path.** Every public endpoint is under `/api/v1`. Within `v1`, changes are backward compatible. A change that would break existing clients ships under a new major path instead, and `v1` keeps working alongside it.+- **The specification is the contract.** [`packages/openapi/openapi.yml`](https://github.com/lobehub/lobehub/blob/canary/packages/openapi/openapi.yml) is generated from the route definitions on every change, and the SDKs are generated from it. A deployment serves its own spec at `/api/v1/openapi.json`; a self-hosted instance on an older release supports only what its own spec lists.+- **LobeHub Cloud follows `canary`.** A merged change reaches LobeHub Cloud with the next deployment. Self-hosted instances get it with the next release that includes it.++### Compatible Changes Within v1++Clients must tolerate these, and they can happen without notice:++- New endpoints, new optional request fields, new query parameters+- New fields in responses+- New values in enumerations such as event types, statuses, and error codes. Treat an unknown value as its closest known category (an unknown error code by its HTTP status, an unknown event by ignoring it)+- New webhook event types, which reach an endpoint only after you subscribe to them+- New API key scopes. Scopes are added for new endpoints. An existing key keeps exactly the access it had; a few high-risk scopes such as `device:operate` are explicit and are not included in full access++### Breaking Changes++These are not made within `v1`: removing or renaming an endpoint, field, or SDK method; changing a field's type; making an optional field required; changing the meaning of a status code or error code; requiring a new scope for an existing operation.++Error codes are only ever added. Operation ids, which become SDK method names (`agents.list`), do not change once shipped.++## Deprecation++When a field, parameter, or endpoint is replaced:++1. The old form keeps working, and the OpenAPI spec marks it `deprecated: true`. The SDKs show the deprecation in their type documentation.+2. The replacement is documented in the [changelog](#api-changelog) with a migration note.+3. The old form is removed only in a new major version.++Current deprecations, effective when [#23231](https://github.com/lobehub/lobehub/pull/23231) ships:++| Deprecated | Replacement |+| ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------- |+| `page`, `pageSize`, `offset` query parameters | `limit` and `cursor` |+| `error` text in error bodies | `code` and `message` |+| `format=array` on `GET /agent-groups`, `/api-keys`, `/mcp-servers` (the old bare-array response) | The paginated `{ items, total, hasMore, nextCursor }` response |++**Exception to the compatibility rule.** When [#23231](https://github.com/lobehub/lobehub/pull/23231) ships, `GET /agent-groups`, `GET /api-keys`, and `GET /mcp-servers` change their default response from a bare array to the paginated object. This is a breaking change inside `v1`. A client that reads these lists as arrays must send `format=array` or move to the paginated response before that release.++## SDK Versions++- `@lobehub/sdk` is published to npm from `canary` automatically when the SDK changes, as `1.0.<UTC timestamp>` under the `latest` tag.+- With [#23246](https://github.com/lobehub/lobehub/pull/23246), releases follow semantic versioning with a `CHANGELOG.md`: versions with a changelog entry are published as `latest`, and every other change as `x.y.z-canary.<timestamp>` under the `canary` tag. Pin `latest` versions in production. A pull request that changes the spec without regenerating the SDK then fails CI.+- The Python SDK `lobehub` ([#23337](https://github.com/lobehub/lobehub/pull/23337)) starts at `0.1.0`.++## API Changelog++Entries are grouped by status. **Released** entries are merged and on LobeHub Cloud; **Coming soon** entries are open pull requests and can change before release.++### Released++| Date | Change | Pull request |+| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |+| 2026-11-18 | Every success response has a typed schema in the spec, so SDK return types are concrete. Every `DELETE` returns `{ deleted, id }` or `{ deleted, count }` | [#23217](https://github.com/lobehub/lobehub/pull/23217) |+| 2026-11-16 | `GET /users/me` returns `messageCount` only when the caller asks for it | [#23119](https://github.com/lobehub/lobehub/pull/23119) |+| 2026-10-30 | `GET /usage` exposes the caller's credit quota | [#21933](https://github.com/lobehub/lobehub/pull/21933) |+| 2026-10-22 | `POST /tasks/{id}/runs` runs a task now; `GET /tasks/{id}/runs` lists its runs | [#21470](https://github.com/lobehub/lobehub/pull/21470) |+| 2026-10-20 | `/chat-groups` for multi-agent groups, and `sdk.chatGroups` | [#21280](https://github.com/lobehub/lobehub/pull/21280) |++### Coming Soon++| Change | Pull request |+| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |+| Unified error body with `code`, `requestId`, and `details`; cursor pagination; per-key rate limits; `Idempotency-Key` | [#23231](https://github.com/lobehub/lobehub/pull/23231) |+| SDK: readable method names, `workspaceId`, retries, timeouts, typed errors, `paginate`, `responses.stream`, `files.upload`, scopes in docs, CI drift check | [#23246](https://github.com/lobehub/lobehub/pull/23246) |+| `/runs`: start, read, stream, cancel, and steer Agent runs; human approval; client tool results; `run:read` / `run:write` | [#23253](https://github.com/lobehub/lobehub/pull/23253) |+| Messages and Topics: edits, fork / clone / branch, transcripts, export / import, search, batch, share, thread writes | [#23254](https://github.com/lobehub/lobehub/pull/23254) |+| `/documents` and `/notebooks`: Pages, versions, comments, sharing; `document:*` | [#23255](https://github.com/lobehub/lobehub/pull/23255) |+| Library semantic search; Memory write, search, and extraction | [#23265](https://github.com/lobehub/lobehub/pull/23265) |+| Image, video, speech, and transcription generation; `generation:*` | [#23267](https://github.com/lobehub/lobehub/pull/23267) |+| Developer webhooks with HMAC signatures and retried delivery; `webhook:*` | [#23272](https://github.com/lobehub/lobehub/pull/23272) |+| Skills, plugin install, connectors, and direct tool calls; `tool:invoke` | [#23274](https://github.com/lobehub/lobehub/pull/23274) |+| Advanced Agent configuration, Agent labels, session groups, chat group operations; `agent:transfer` | [#23292](https://github.com/lobehub/lobehub/pull/23292) |+| Workspaces, members, invitations, audit logs, collaborators, transfer requests, share links; `share:*` | [#23301](https://github.com/lobehub/lobehub/pull/23301) |+| Task sub-resources, task templates, and goal control | [#23303](https://github.com/lobehub/lobehub/pull/23303) |+| Projects, widgets, dashboards, artifact publishing; `project:*`, `widget:*`, `dashboard:*`, `artifact:publish` | [#23311](https://github.com/lobehub/lobehub/pull/23311) |+| Settings, model and provider operations, OAuth apps, trash, export / import; `oauth_app:*`, `trash:*` | [#23315](https://github.com/lobehub/lobehub/pull/23315) |+| Devices and sandboxes; `device:read`, explicit `device:operate` | [#23316](https://github.com/lobehub/lobehub/pull/23316) |+| MCP server at `/api/v1/mcp` | [#23318](https://github.com/lobehub/lobehub/pull/23318) |+| OAuth open platform: dynamic client registration, `client_credentials`, API scopes for OAuth tokens | [#23322](https://github.com/lobehub/lobehub/pull/23322) |+| Custom Webhook channel and `/bots`; `bot:*` | [#23332](https://github.com/lobehub/lobehub/pull/23332) |+| Python SDK `lobehub` | [#23337](https://github.com/lobehub/lobehub/pull/23337) |++Related developer surfaces, also coming soon: MCP-UI rendering of `ui://` resources in tool cards ([#23325](https://github.com/lobehub/lobehub/pull/23325)), the publishable widget spec package ([#23321](https://github.com/lobehub/lobehub/pull/23321)), embedding a shared Agent on any website ([#23333](https://github.com/lobehub/lobehub/pull/23333)), and the `lh` CLI calling the REST API through `@lobehub/sdk` ([#23350](https://github.com/lobehub/lobehub/pull/23350)).++When an entry merges, it moves to **Released** with its date, and the pages of this guide drop their "Coming soon" label for it.diff --git a/docs/development/api/versioning.zh-CN.mdx b/docs/development/api/versioning.zh-CN.mdxnew file mode 100644index 00000000000..e730f9749dc--- /dev/null+++ b/docs/development/api/versioning.zh-CN.mdx@@ -0,0 +1,104 @@+---+title: LobeHub API 版本管理、弃用与变更日志+description: >-+ LobeHub 公开 API 和 SDK 的版本规则、哪些改动属于破坏性变更、弃用如何公告,以及+ API 变更日志。+tags:+ - LobeHub+ - REST API+ - 版本管理+ - 弃用+ - 变更日志+---++# LobeHub API 版本管理、弃用与变更日志++## 版本管理++- **主版本号在路径中。** 所有公开端点都位于 `/api/v1` 下。`v1` 内的改动保持向后兼容。会破坏现有客户端的改动改为在新的主版本路径下发布,`v1` 与其并存并继续可用。+- **规范即契约。** [`packages/openapi/openapi.yml`](https://github.com/lobehub/lobehub/blob/canary/packages/openapi/openapi.yml) 在每次改动时由路由定义生成,SDK 再由它生成。每个部署都在 `/api/v1/openapi.json` 提供自己的规范;运行旧版本的自托管实例只支持其规范中列出的内容。+- **LobeHub Cloud 跟随 `canary`。** 合并的改动随下一次部署进入 LobeHub Cloud。自托管实例在包含该改动的下一个版本中获得它。++### v1 内的兼容改动++客户端必须能容忍以下改动,它们可能不经通知发生:++- 新增端点、新增可选请求字段、新增查询参数+- 响应中新增字段+- 枚举中新增取值,例如事件类型、状态和错误码。遇到未知取值时,按最接近的已知类别处理(未知错误码按其 HTTP 状态码处理,未知事件直接忽略)+- 新增 Webhook 事件类型,只有订阅后才会投递到端点+- 新增 API Key scope。新 scope 随新端点增加。现有 API Key 的访问权限保持不变;少数高风险 scope(如 `device:operate`)需要显式授予,不包含在完全访问权限中++### 破坏性变更++以下改动不会在 `v1` 内进行:删除或重命名端点、字段或 SDK 方法;修改字段类型;将可选字段改为必填;改变状态码或错误码的含义;要求现有操作使用新的 scope。++错误码只增不减。操作 id 会成为 SDK 方法名(`agents.list`),一经发布便不再变更。++## 弃用++当字段、参数或端点被替代时:++1. 旧形式继续可用,OpenAPI 规范将其标记为 `deprecated: true`。SDK 在类型文档中显示弃用信息。+2. 替代方案连同迁移说明记录在[变更日志](#api-changelog)中。+3. 旧形式只会在新的主版本中移除。++当前的弃用项,自 [#23231](https://github.com/lobehub/lobehub/pull/23231) 发布后生效:++| 已弃用 | 替代方案 |+| ------------------------------------------------------------------------- | -------------------------------------------- |+| 查询参数 `page`、`pageSize`、`offset` | `limit` 和 `cursor` |+| 错误响应体中的 `error` 文本 | `code` 和 `message` |+| `GET /agent-groups`、`/api-keys`、`/mcp-servers` 上的 `format=array`(旧的裸数组响应) | 分页响应 `{ items, total, hasMore, nextCursor }` |++**兼容规则的例外。**[#23231](https://github.com/lobehub/lobehub/pull/23231) 上线后,`GET /agent-groups`、`GET /api-keys` 和 `GET /mcp-servers` 的默认响应会从数组改为分页对象。这是 `v1` 内的破坏性变更。把这些列表当作数组读取的客户端,需要在该版本发布前发送 `format=array`,或改用分页响应。++## SDK 版本++- SDK 有改动时,`@lobehub/sdk` 会从 `canary` 自动发布到 npm,版本号为 `1.0.<UTC timestamp>`,使用 `latest` 标签。+- [#23246](https://github.com/lobehub/lobehub/pull/23246) 合并后,版本遵循语义化版本并维护 `CHANGELOG.md`:有变更日志条目的版本以 `latest` 发布,其余改动以 `x.y.z-canary.<timestamp>` 发布在 `canary` 标签下。生产环境请固定使用 `latest` 版本。届时,修改了规范却未重新生成 SDK 的 PR 会在 CI 中失败。+- Python SDK `lobehub`([#23337](https://github.com/lobehub/lobehub/pull/23337))从 `0.1.0` 起步。++<a id="api-changelog" />++## API 变更日志++条目按状态分组。**已发布**的条目已合并并上线 LobeHub Cloud;**即将推出**的条目是尚未合并的 PR,正式发布前可能调整。++### 已发布++| 日期 | 变更 | PR |+| ---------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------- |+| 2026-11-18 | 规范中每个成功响应都有类型化 schema,SDK 返回类型因此是具体的。所有 `DELETE` 都返回 `{ deleted, id }` 或 `{ deleted, count }` | [#23217](https://github.com/lobehub/lobehub/pull/23217) |+| 2026-11-16 | `GET /users/me` 仅在调用方请求时返回 `messageCount` | [#23119](https://github.com/lobehub/lobehub/pull/23119) |+| 2026-10-30 | `GET /usage` 返回调用方的额度配额 | [#21933](https://github.com/lobehub/lobehub/pull/21933) |+| 2026-10-22 | `POST /tasks/{id}/runs` 立即运行任务;`GET /tasks/{id}/runs` 列出其运行记录 | [#21470](https://github.com/lobehub/lobehub/pull/21470) |+| 2026-10-20 | 用于多 Agent 群组的 `/chat-groups`,以及 `sdk.chatGroups` | [#21280](https://github.com/lobehub/lobehub/pull/21280) |++### 即将推出++| 变更 | PR |+| ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |+| 统一的错误响应体,包含 `code`、`requestId` 和 `details`;游标分页;按 API Key 限流;`Idempotency-Key` | [#23231](https://github.com/lobehub/lobehub/pull/23231) |+| SDK:可读的方法名、`workspaceId`、重试、超时、类型化错误、`paginate`、`responses.stream`、`files.upload`、文档中的 scope、CI 漂移检查 | [#23246](https://github.com/lobehub/lobehub/pull/23246) |+| `/runs`:启动、读取、流式获取、取消和引导 Agent 运行;人工审批;客户端工具结果;`run:read` / `run:write` | [#23253](https://github.com/lobehub/lobehub/pull/23253) |+| 消息和话题:编辑、fork /clone/branch、对话记录、导出 / 导入、搜索、批量操作、分享、thread 写入 | [#23254](https://github.com/lobehub/lobehub/pull/23254) |+| `/documents` 和 `/notebooks`:文稿、版本、评论、分享;`document:*` | [#23255](https://github.com/lobehub/lobehub/pull/23255) |+| 资源库语义搜索;记忆的写入、搜索和提取 | [#23265](https://github.com/lobehub/lobehub/pull/23265) |+| 图像、视频、语音和转录生成;`generation:*` | [#23267](https://github.com/lobehub/lobehub/pull/23267) |+| 带 HMAC 签名和重试投递的开发者 Webhook;`webhook:*` | [#23272](https://github.com/lobehub/lobehub/pull/23272) |+| 技能、插件安装、连接器和直接工具调用;`tool:invoke` | [#23274](https://github.com/lobehub/lobehub/pull/23274) |+| 高级 Agent 配置、Agent 标签、会话分组、群聊操作;`agent:transfer` | [#23292](https://github.com/lobehub/lobehub/pull/23292) |+| 工作区、成员、邀请、审计日志、协作者、转移请求、分享链接;`share:*` | [#23301](https://github.com/lobehub/lobehub/pull/23301) |+| 任务子资源、任务模板和目标控制 | [#23303](https://github.com/lobehub/lobehub/pull/23303) |+| 项目、组件、仪表盘、Artifact 发布;`project:*`、`widget:*`、`dashboard:*`、`artifact:publish` | [#23311](https://github.com/lobehub/lobehub/pull/23311) |+| 设置、模型和服务商操作、OAuth 应用、回收站、导出 / 导入;`oauth_app:*`、`trash:*` | [#23315](https://github.com/lobehub/lobehub/pull/23315) |+| 设备和沙箱;`device:read`、需显式授予的 `device:operate` | [#23316](https://github.com/lobehub/lobehub/pull/23316) |+| 位于 `/api/v1/mcp` 的 MCP Server | [#23318](https://github.com/lobehub/lobehub/pull/23318) |+| OAuth 开放平台:动态客户端注册、`client_credentials`、OAuth token 的 API scope | [#23322](https://github.com/lobehub/lobehub/pull/23322) |+| Custom Webhook 渠道和 `/bots`;`bot:*` | [#23332](https://github.com/lobehub/lobehub/pull/23332) |+| Python SDK `lobehub` | [#23337](https://github.com/lobehub/lobehub/pull/23337) |++相关的开发者能力同样即将推出:在工具卡片中以 MCP-UI 渲染 `ui://` 资源([#23325](https://github.com/lobehub/lobehub/pull/23325))、可发布的组件规范包([#23321](https://github.com/lobehub/lobehub/pull/23321))、在任意网站嵌入分享的 Agent([#23333](https://github.com/lobehub/lobehub/pull/23333)),以及 `lh` CLI 改为通过 `@lobehub/sdk` 调用 REST API([#23350](https://github.com/lobehub/lobehub/pull/23350))。++条目合并后会移入**已发布**并注明日期,本指南各页面也会去掉对应能力的「即将推出」标记。diff --git a/docs/development/api/webhooks.mdx b/docs/development/api/webhooks.mdxnew file mode 100644index 00000000000..d857927d9e0--- /dev/null+++ b/docs/development/api/webhooks.mdx@@ -0,0 +1,191 @@+---+title: LobeHub Developer Webhooks+description: >-+ Subscribe to LobeHub events, receive signed deliveries, and verify the+ X-LobeHub-Signature header in Node.js and Python.+tags:+ - LobeHub+ - REST API+ - Webhooks+ - HMAC+ - Signature+---++# LobeHub Developer Webhooks++<Callout type="info">+ **Coming soon** ([#23272](https://github.com/lobehub/lobehub/pull/23272)). Developer webhooks are+ not on LobeHub Cloud yet. This page describes the delivery format and signature scheme+ implemented in that pull request so you can prepare a receiver; names and limits can still change+ before release.+</Callout>++A webhook endpoint is a URL of yours that LobeHub calls with a signed `POST` when something happens in your personal space or Workspace: a run finishes, a message is created, a file is parsed. Endpoints are managed through `/api/v1/webhooks` with the `webhook:read` and `webhook:write` scopes, or from **Settings → Webhooks** in the app, which the same pull request adds.++## Manage Endpoints++| Method and path | Purpose |+| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |+| `GET /webhooks` | List endpoints (cursor pagination) |+| `POST /webhooks` | Create an endpoint: `url`, `events`, optional `description` and `enabled`. The response contains the signing secret, shown only here |+| `GET /webhooks/{id}` | Read an endpoint |+| `PATCH /webhooks/{id}` | Change its URL, events, description, or enable it again |+| `DELETE /webhooks/{id}` | Delete it |+| `POST /webhooks/{id}/rotate-secret` | Issue a new signing secret (shown once) |+| `POST /webhooks/{id}/test` | Send a `webhook.test` event |+| `GET /webhooks/{id}/deliveries` | Delivery log |+| `POST /webhooks/{id}/deliveries/{deliveryId}/redeliver` | Send a past delivery again, with the same event id and body |++```bash+curl -X POST https://app.lobehub.com/api/v1/webhooks \+ -H "Authorization: Bearer $LOBEHUB_API_KEY" -H "Content-Type: application/json" \+ -d '{"url":"https://example.com/lobehub/webhook","events":["run.completed","run.failed"]}'+```++A space can have up to 20 endpoints. Subscribing to an event also needs the read scope of its data, for example `run:read` for `run.*`; otherwise the request returns `403` `insufficient_scope`.++## Event Catalog++| Event | Sent when | `data` | Read scope |+| ---------------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------- | ---------------- |+| `run.started` | An Agent run starts | `{ runId, agentId, topicId }` | `run:read` |+| `run.completed` | A run finishes | Run fields plus `assistantMessageId`, `steps` | `run:read` |+| `run.failed` | A run fails | Run fields plus `error` | `run:read` |+| `run.intervention_requested` | A run waits for [human approval](/docs/development/api/streaming#human-approval) | `{ runId, agentId, topicId }` | `run:read` |+| `message.created` | A message is created | `{ messageId, role, topicId, threadId, agentId }` | `chat:read` |+| `topic.created` | A Topic is created | `{ topicId, title, agentId }` | `chat:read` |+| `task.status_changed` | A task changes status | `{ taskId, identifier, status, previousStatus }` | `agent:read` |+| `goal.status_changed` | A goal changes status | `{ goalId, status, previousStatus }` | `agent:read` |+| `file.parsed` | File parsing finishes | `{ fileId, name, status: "success" \| "error", error }` | `file:read` |+| `notification.created` | A notification is created | `{ notificationId, category, type, title }` | `user:read` |+| `webhook.test` | You call `POST /webhooks/{id}/test` | `{ webhookId, message }` | Not subscribable |++## Delivery Format++```http+POST /lobehub/webhook HTTP/1.1+Content-Type: application/json+User-Agent: LobeHub-Webhooks/1.0+X-LobeHub-Event-Id: evt_…+X-LobeHub-Event-Type: run.completed+X-LobeHub-Delivery-Id: …+X-LobeHub-Timestamp: 1795075200+X-LobeHub-Signature: v1=5d41402abc4b2a76b9719d911017c592…++{"id":"evt_…","type":"run.completed","createdAt":"2026-11-18T08:00:00.000Z","workspaceId":"ws_…","data":{…}}+```++- `id` stays the same across retries and redeliveries. Use it to ignore duplicates.+- `workspaceId` is `null` for events from a personal space.+- Only a `2xx` answer counts as delivered. Redirects are not followed. Answer within 10 seconds and do slow work afterwards.++### Retries++A failed delivery is attempted up to 6 times in total, waiting 30 seconds, 2 minutes, 8 minutes, 32 minutes, and about 2 hours between attempts. After 5 deliveries in a row fail every attempt, the endpoint is disabled; enable it again with `PATCH /webhooks/{id}` once the receiver is fixed. Test deliveries are attempted once.++## Verify the Signature++Every delivery is signed with the endpoint's secret (`whsec_…`):++```text+X-LobeHub-Signature: v1=<hex HMAC-SHA256(secret, "<X-LobeHub-Timestamp>.<raw body>")>+```++- The HMAC key is the whole secret string, including the `whsec_` prefix.+- The signed string is the timestamp header, a dot, and the **raw request body as received**. Parsing and re-serializing the JSON changes it and the signature will not match.+- Reject a timestamp more than 300 seconds away from your clock, so a captured request cannot be replayed later.+- The header can hold several `v1=` values separated by spaces or commas, for example right after a secret rotation. Accept the request if any of them matches.+- Compare in constant time.++### Node.js++```ts+import { createHmac, timingSafeEqual } from 'node:crypto';++const TOLERANCE_SECONDS = 300;++export function verifyLobeHubWebhook(+ rawBody: string,+ headers: Record<string, string | undefined>,+ secret: string,+): void {+ const timestamp = headers['x-lobehub-timestamp'];+ const signatureHeader = headers['x-lobehub-signature'];+ if (!timestamp || !signatureHeader) throw new Error('Missing signature headers');++ const age = Math.abs(Date.now() / 1000 - Number(timestamp));+ if (!Number.isFinite(age) || age > TOLERANCE_SECONDS) throw new Error('Timestamp out of range');++ const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest();+ const matches = signatureHeader+ .split(/[\s,]+/)+ .filter((part) => part.startsWith('v1='))+ .some((part) => {+ const received = Buffer.from(part.slice(3), 'hex');+ return received.length === expected.length && timingSafeEqual(received, expected);+ });+ if (!matches) throw new Error('Signature does not match');+}+```++With Express, read the raw body before any JSON parser: `app.post('/lobehub/webhook', express.raw({ type: 'application/json' }), …)`, then pass `req.body.toString('utf8')` and `req.headers`.++### Python++```python+import hashlib+import hmac+import time++TOLERANCE_SECONDS = 300+++def verify_lobehub_webhook(raw_body: bytes, headers: dict, secret: str) -> None:+ timestamp = headers.get("x-lobehub-timestamp")+ signature_header = headers.get("x-lobehub-signature")+ if not timestamp or not signature_header:+ raise ValueError("Missing signature headers")++ if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:+ raise ValueError("Timestamp out of range")++ signed = timestamp.encode() + b"." + raw_body+ expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()+ candidates = [+ part[3:]+ for part in signature_header.replace(",", " ").split()+ if part.startswith("v1=")+ ]+ if not any(hmac.compare_digest(candidate, expected) for candidate in candidates):+ raise ValueError("Signature does not match")+```++Pass header names in lower case (Flask: `{k.lower(): v for k, v in request.headers.items()}`) and the body from `request.get_data()`.++### With the TypeScript SDK++The same pull request adds verification helpers to `@lobehub/sdk`. They work with Fetch `Headers` or Node header objects:++```ts+import { constructWebhookEvent } from '@lobehub/sdk';++export async function POST(request: Request) {+ const rawBody = await request.text();+ const event = await constructWebhookEvent({+ headers: request.headers,+ payload: rawBody,+ secret: process.env.LOBEHUB_WEBHOOK_SECRET!,+ });++ if (event.type === 'run.completed') {+ // event.data is typed for run.completed+ }+ return new Response(null, { status: 204 });+}+```++`verifyWebhookSignature` checks without parsing. Both throw `WebhookSignatureVerificationError` with a `code` such as `missing_signature`, `timestamp_out_of_range`, or `signature_mismatch`.++## Webhook Channels for Chat Platforms++A separate pull request, [#23332](https://github.com/lobehub/lobehub/pull/23332) (**coming soon**), adds a **Custom Webhook** channel that connects any chat platform to an Agent, plus `/api/v1/bots` (`bot:read`, `bot:write`) to manage bots. Its inbound and outbound messages use the same `X-LobeHub-Timestamp` and `X-LobeHub-Signature` scheme, signed with the bot's own secret.diff --git a/docs/development/api/webhooks.zh-CN.mdx b/docs/development/api/webhooks.zh-CN.mdxnew file mode 100644index 00000000000..69d859381fc--- /dev/null+++ b/docs/development/api/webhooks.zh-CN.mdx@@ -0,0 +1,189 @@+---+title: LobeHub 开发者 Webhook+description: >-+ 订阅 LobeHub 事件,接收带签名的投递,并在 Node.js 和 Python 中校验+ X-LobeHub-Signature 请求头。+tags:+ - LobeHub+ - REST API+ - Webhook+ - HMAC+ - 签名+---++# LobeHub 开发者 Webhook++<Callout type="info">+ **即将推出**([#23272](https://github.com/lobehub/lobehub/pull/23272))。开发者 Webhook 尚未上线+ LobeHub Cloud。本页介绍该 PR 中实现的投递格式和签名方案,方便你提前准备接收端;正式发布前,名称和限制仍可能调整。+</Callout>++Webhook 端点是你提供的一个 URL。当你的个人空间或工作区中发生特定事件(例如运行结束、消息创建、文件解析完成)时,LobeHub 会向它发送一个带签名的 `POST` 请求。端点通过 `/api/v1/webhooks` 管理,需要 `webhook:read` 和 `webhook:write` scope;也可以在应用的 **设置 → Webhook** 中管理,该页面由同一 PR 添加。++## 管理端点++| 方法与路径 | 用途 |+| ------------------------------------------------------- | ----------------------------------------------------------------- |+| `GET /webhooks` | 列出端点(游标分页) |+| `POST /webhooks` | 创建端点:`url`、`events`,可选 `description` 和 `enabled`。响应中包含签名密钥,仅在此处显示 |+| `GET /webhooks/{id}` | 读取端点 |+| `PATCH /webhooks/{id}` | 修改 URL、事件、描述,或重新启用端点 |+| `DELETE /webhooks/{id}` | 删除端点 |+| `POST /webhooks/{id}/rotate-secret` | 签发新的签名密钥(仅显示一次) |+| `POST /webhooks/{id}/test` | 发送一个 `webhook.test` 事件 |+| `GET /webhooks/{id}/deliveries` | 投递日志 |+| `POST /webhooks/{id}/deliveries/{deliveryId}/redeliver` | 重新发送一次历史投递,事件 id 和请求体保持不变 |++```bash+curl -X POST https://app.lobehub.com/api/v1/webhooks \+ -H "Authorization: Bearer $LOBEHUB_API_KEY" -H "Content-Type: application/json" \+ -d '{"url":"https://example.com/lobehub/webhook","events":["run.completed","run.failed"]}'+```++每个空间最多可创建 20 个端点。订阅某个事件还需要该事件数据的读取 scope,例如订阅 `run.*` 需要 `run:read`;否则请求返回 `403` `insufficient_scope`。++## 事件目录++| 事件 | 触发时机 | `data` | 读取 scope |+| ---------------------------- | ------------------------------------------------------------- | ------------------------------------------------------- | ------------ |+| `run.started` | Agent 运行开始 | `{ runId, agentId, topicId }` | `run:read` |+| `run.completed` | 运行结束 | 运行字段,外加 `assistantMessageId`、`steps` | `run:read` |+| `run.failed` | 运行失败 | 运行字段,外加 `error` | `run:read` |+| `run.intervention_requested` | 运行等待[人工审批](/zh/docs/development/api/streaming#human-approval) | `{ runId, agentId, topicId }` | `run:read` |+| `message.created` | 创建了一条消息 | `{ messageId, role, topicId, threadId, agentId }` | `chat:read` |+| `topic.created` | 创建了一个话题 | `{ topicId, title, agentId }` | `chat:read` |+| `task.status_changed` | 任务状态变化 | `{ taskId, identifier, status, previousStatus }` | `agent:read` |+| `goal.status_changed` | 目标状态变化 | `{ goalId, status, previousStatus }` | `agent:read` |+| `file.parsed` | 文件解析完成 | `{ fileId, name, status: "success" \| "error", error }` | `file:read` |+| `notification.created` | 创建了一条通知 | `{ notificationId, category, type, title }` | `user:read` |+| `webhook.test` | 调用 `POST /webhooks/{id}/test` 时 | `{ webhookId, message }` | 不可订阅 |++## 投递格式++```http+POST /lobehub/webhook HTTP/1.1+Content-Type: application/json+User-Agent: LobeHub-Webhooks/1.0+X-LobeHub-Event-Id: evt_…+X-LobeHub-Event-Type: run.completed+X-LobeHub-Delivery-Id: …+X-LobeHub-Timestamp: 1795075200+X-LobeHub-Signature: v1=5d41402abc4b2a76b9719d911017c592…++{"id":"evt_…","type":"run.completed","createdAt":"2026-11-18T08:00:00.000Z","workspaceId":"ws_…","data":{…}}+```++- `id` 在重试和重新投递时保持不变,可用它忽略重复事件。+- 来自个人空间的事件,`workspaceId` 为 `null`。+- 只有 `2xx` 响应才算投递成功,不跟随重定向。请在 10 秒内响应,耗时操作放到响应之后处理。++### 重试++投递失败后最多共尝试 6 次,每次间隔依次为 30 秒、2 分钟、8 分钟、32 分钟和约 2 小时。如果连续 5 次投递的所有尝试都失败,端点会被停用;修复接收端后,用 `PATCH /webhooks/{id}` 重新启用。测试投递只尝试一次。++## 校验签名++每次投递都使用端点的签名密钥(`whsec_…`)签名:++```text+X-LobeHub-Signature: v1=<hex HMAC-SHA256(secret, "<X-LobeHub-Timestamp>.<raw body>")>+```++- HMAC 的密钥是完整的签名密钥字符串,包括 `whsec_` 前缀。+- 被签名的字符串由时间戳请求头、一个点号和**收到的原始请求体**拼接而成。解析后再序列化 JSON 会改变内容,导致签名不匹配。+- 拒绝与本地时钟相差超过 300 秒的时间戳,防止截获的请求在之后被重放。+- 请求头中可以包含多个 `v1=` 值,以空格或逗号分隔,例如刚轮换签名密钥之后。只要其中任意一个匹配,就接受该请求。+- 使用常量时间比较。++### Node.js++```ts+import { createHmac, timingSafeEqual } from 'node:crypto';++const TOLERANCE_SECONDS = 300;++export function verifyLobeHubWebhook(+ rawBody: string,+ headers: Record<string, string | undefined>,+ secret: string,+): void {+ const timestamp = headers['x-lobehub-timestamp'];+ const signatureHeader = headers['x-lobehub-signature'];+ if (!timestamp || !signatureHeader) throw new Error('Missing signature headers');++ const age = Math.abs(Date.now() / 1000 - Number(timestamp));+ if (!Number.isFinite(age) || age > TOLERANCE_SECONDS) throw new Error('Timestamp out of range');++ const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest();+ const matches = signatureHeader+ .split(/[\s,]+/)+ .filter((part) => part.startsWith('v1='))+ .some((part) => {+ const received = Buffer.from(part.slice(3), 'hex');+ return received.length === expected.length && timingSafeEqual(received, expected);+ });+ if (!matches) throw new Error('Signature does not match');+}+```++使用 Express 时,需要在任何 JSON 解析器之前读取原始请求体:`app.post('/lobehub/webhook', express.raw({ type: 'application/json' }), …)`,然后传入 `req.body.toString('utf8')` 和 `req.headers`。++### Python++```python+import hashlib+import hmac+import time++TOLERANCE_SECONDS = 300+++def verify_lobehub_webhook(raw_body: bytes, headers: dict, secret: str) -> None:+ timestamp = headers.get("x-lobehub-timestamp")+ signature_header = headers.get("x-lobehub-signature")+ if not timestamp or not signature_header:+ raise ValueError("Missing signature headers")++ if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:+ raise ValueError("Timestamp out of range")++ signed = timestamp.encode() + b"." + raw_body+ expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()+ candidates = [+ part[3:]+ for part in signature_header.replace(",", " ").split()+ if part.startswith("v1=")+ ]+ if not any(hmac.compare_digest(candidate, expected) for candidate in candidates):+ raise ValueError("Signature does not match")+```++请求头名称需转为小写后传入(Flask:`{k.lower(): v for k, v in request.headers.items()}`),请求体取自 `request.get_data()`。++### 使用 TypeScript SDK++同一个 PR 为 `@lobehub/sdk` 增加了校验辅助函数,支持 Fetch `Headers` 和 Node 请求头对象:++```ts+import { constructWebhookEvent } from '@lobehub/sdk';++export async function POST(request: Request) {+ const rawBody = await request.text();+ const event = await constructWebhookEvent({+ headers: request.headers,+ payload: rawBody,+ secret: process.env.LOBEHUB_WEBHOOK_SECRET!,+ });++ if (event.type === 'run.completed') {+ // event.data is typed for run.completed+ }+ return new Response(null, { status: 204 });+}+```++`verifyWebhookSignature` 只校验、不解析。两者都会抛出 `WebhookSignatureVerificationError`,其 `code` 取值如 `missing_signature`、`timestamp_out_of_range` 或 `signature_mismatch`。++## 聊天平台的 Webhook 渠道++另一个 PR [#23332](https://github.com/lobehub/lobehub/pull/23332)(**即将推出**)新增了 **Custom Webhook** 渠道,可将任意聊天平台连接到 Agent,并提供 `/api/v1/bots`(`bot:read`、`bot:write`)用于管理机器人。其入站和出站消息使用相同的 `X-LobeHub-Timestamp` 与 `X-LobeHub-Signature` 方案,并以机器人自己的签名密钥签名。diff --git a/docs/development/start.mdx b/docs/development/start.mdxindex 016fdb55656..bbe719634e0 100644--- a/docs/development/start.mdx+++ b/docs/development/start.mdx@@ -17,13 +17,14 @@ Choose a path based on your goal: changing LobeHub source code, operating an exi## Choose a Development Path-| Goal | Start here | Boundary |-| --- | --- | --- |-| Change the UI, server, or runtimes | [Development environment setup](/docs/development/basic/setup-development), then the stack and directory structure below | Requires a source development environment. Using the CLI or API alone does not require the full application development setup. |-| Operate an existing instance from a terminal | [CLI README](https://github.com/lobehub/lobehub/blob/659db0780b263f023019337a48f23e17e77e260d/apps/cli/README.md); task examples in [Task Tools](/docs/usage/agent/connectors#using-the-cli) | The README covers source builds, shell linking, and server configuration. Check the installed version, target server, and account permissions. |-| Integrate through HTTP | [OpenAPI specification](https://github.com/lobehub/lobehub/blob/659db0780b263f023019337a48f23e17e77e260d/packages/openapi/openapi.yml) | Use the public REST API, authentication, and parameters supported by the target deployment. Internal application routes are not the public API contract. |-| Integrate through TypeScript | [Official SDK README](https://github.com/lobehub/lobehub/blob/659db0780b263f023019337a48f23e17e77e260d/packages/sdk/README.md) | `@lobehub/sdk` is generated from OpenAPI. Follow the matching README and specification for methods, authentication, and streaming. Do not assume every UI or CLI feature has an SDK method. |-| Understand internal chat calls | [Chat API internals](/docs/development/basic/chat-api) | For source reading and debugging, not an external application integration tutorial. |+| Goal | Start here | Boundary |+| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Change the UI, server, or runtimes | [Development environment setup](/docs/development/basic/setup-development), then the stack and directory structure below | Requires a source development environment. Using the CLI or API alone does not require the full application development setup. |+| Operate an existing instance from a terminal | [CLI README](https://github.com/lobehub/lobehub/blob/canary/apps/cli/README.md); task examples in [Task Tools](/docs/usage/agent/connectors#using-the-cli) | The README covers source builds, shell linking, and server configuration. Check the installed version, target server, and account permissions. |+| Build on the public API | [Public API guide](/docs/development/api/overview): authentication, scopes, errors, streaming, webhooks, and SDK examples | Marks each capability as available or coming soon. Check the target deployment's own `/api/v1/openapi.json` for what it supports. |+| Integrate through HTTP | [OpenAPI specification](https://github.com/lobehub/lobehub/blob/canary/packages/openapi/openapi.yml) | Use the public REST API, authentication, and parameters supported by the target deployment. Internal application routes are not the public API contract. |+| Integrate through TypeScript | [Official SDK README](https://github.com/lobehub/lobehub/blob/canary/packages/sdk/README.md) | `@lobehub/sdk` is generated from OpenAPI. Follow the matching README and specification for methods, authentication, and streaming. Do not assume every UI or CLI feature has an SDK method. |+| Understand internal chat calls | [Chat API internals](/docs/development/basic/chat-api) | For source reading and debugging, not an external application integration tutorial. |### CLI and Execution Environments@@ -33,7 +34,6 @@ The [May 4, 2026 release](/changelog/2026-05-04-task-scheduler) described ClaudeThese entry points were checked against the repository snapshot on September 14, 2026. Verify your installed version before integration. Do not treat `/webapi/chat/[provider]` or internal tRPC routes as stable public interfaces.-## Basic Technology StackThe core technology stack of LobeHub is as follows:diff --git a/docs/development/start.zh-CN.mdx b/docs/development/start.zh-CN.mdxindex 7898d0ea6e8..64867c774c7 100644--- a/docs/development/start.zh-CN.mdx+++ b/docs/development/start.zh-CN.mdx@@ -15,13 +15,14 @@ tags:## 选择开发路径-| 目标 | 入口 | 边界 |-| --- | --- | --- |-| 修改界面、服务端或运行时 | [开发环境设置](/zh/docs/development/basic/setup-development),再阅读下方技术栈和目录结构 | 需要源码开发环境;仅使用 CLI 或 API 不必搭建完整开发环境。 |-| 从终端操作现有 LobeHub 实例 | [CLI README](https://github.com/lobehub/lobehub/blob/659db0780b263f023019337a48f23e17e77e260d/apps/cli/README.md),任务示例见[任务工具](/zh/docs/usage/agent/connectors#using-the-cli) | README 包含源码构建、链接命令和服务器配置。使用已安装的 CLI 前,核对版本、目标服务器及账户权限。 |-| 用 HTTP 集成应用 | [OpenAPI 规范](https://github.com/lobehub/lobehub/blob/659db0780b263f023019337a48f23e17e77e260d/packages/openapi/openapi.yml) | 按目标部署支持的公开 REST API、认证方式和参数调用;应用内部路由不等于公开 API 契约。 |-| 用 TypeScript 集成应用 | [官方 SDK README](https://github.com/lobehub/lobehub/blob/659db0780b263f023019337a48f23e17e77e260d/packages/sdk/README.md) | `@lobehub/sdk` 基于 OpenAPI 生成;方法、认证和流式处理以对应版本的 README 与规范为准。不要假定所有界面或 CLI 功能都有 SDK 方法。 |-| 理解应用内部聊天调用 | [Chat API 内部实现](/zh/docs/development/basic/chat-api) | 供源码阅读和调试,不是外部应用的接口接入教程。 |+| 目标 | 入口 | 边界 |+| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- |+| 修改界面、服务端或运行时 | [开发环境设置](/zh/docs/development/basic/setup-development),再阅读下方技术栈和目录结构 | 需要源码开发环境;仅使用 CLI 或 API 不必搭建完整开发环境。 |+| 从终端操作现有 LobeHub 实例 | [CLI README](https://github.com/lobehub/lobehub/blob/canary/apps/cli/README.md),任务示例见[任务工具](/zh/docs/usage/agent/connectors#using-the-cli) | README 包含源码构建、链接命令和服务器配置。使用已安装的 CLI 前,核对版本、目标服务器及账户权限。 |+| 基于公开 API 开发 | [公开 API 指南](/zh/docs/development/api/overview):鉴权、scope、错误、流式、Webhook 与 SDK 示例 | 每项能力标明「已可用」或「即将推出」;目标部署支持哪些接口,以它自己的 `/api/v1/openapi.json` 为准。 |+| 用 HTTP 集成应用 | [OpenAPI 规范](https://github.com/lobehub/lobehub/blob/canary/packages/openapi/openapi.yml) | 按目标部署支持的公开 REST API、认证方式和参数调用;应用内部路由不等于公开 API 契约。 |+| 用 TypeScript 集成应用 | [官方 SDK README](https://github.com/lobehub/lobehub/blob/canary/packages/sdk/README.md) | `@lobehub/sdk` 基于 OpenAPI 生成;方法、认证和流式处理以对应版本的 README 与规范为准。不要假定所有界面或 CLI 功能都有 SDK 方法。 |+| 理解应用内部聊天调用 | [Chat API 内部实现](/zh/docs/development/basic/chat-api) | 供源码阅读和调试,不是外部应用的接口接入教程。 |### CLI 与执行环境@@ -31,7 +32,6 @@ tags:以上入口依据 2026-09-14 核对的仓库快照。接入前核对实际安装版本;不要将 `/webapi/chat/[provider]` 或内部 tRPC 路由当作稳定的公开接口。-## 基础技术栈LobeHub 的核心技术栈如下: