# DevOS API / SDK / External Integration Runtime > 文档版本:v1.0 > 文件名:`26_API_SDK_EXTERNAL_INTEGRATION_RUNTIME.md` > 适用项目:`/home/dev/bun/devos` > 状态:Architecture / Implementation Specification > 前置文档:01–25 --- # 1. 文档目的 本文件定义 DevOS 的统一: - API Runtime - REST API - OpenAPI - API Versioning - TypeScript SDK - Server SDK - CLI - Webhook - External Integration - Service Account - API Key - OAuth / OIDC Integration - External Provider - Rate Limit - Pagination - Error Contract - Idempotency - Async Task API - Streaming API - File API - Search API - Agent API - Plugin API - MCP API Boundary 核心目标: > **所有外部调用最终进入 DevOS Runtime,而不是直接进入业务数据库或业务 Service。** 统一模型: ```text External Client ↓ API / SDK / CLI / Webhook / Integration ↓ Authentication ↓ Authorization ↓ Scope ↓ Action / Query / Task Runtime ↓ Execution ↓ Event ``` --- # 2. API 的定位 DevOS API 不是简单的: ```text Controller → Service → Database ``` 而是: ```text API ↓ Runtime Contract ↓ Security ↓ Action / Query / Task ↓ Execution ``` API 是 Runtime 的一个入口。 --- # 3. API Architecture ```text DevOS API │ ┌────────────┼────────────┐ ↓ ↓ ↓ REST SSE WebSocket ↓ ↓ ↓ API Runtime / Transport Runtime ↓ Security Context ↓ ┌──────────────┼──────────────┐ ↓ ↓ ↓ Query Action Task ↓ ↓ ↓ DevOS Runtime ``` --- # 4. API 不应该拥有业务逻辑 禁止: ```ts @Controller() createWebsite() { // 大量业务逻辑 // DB // Queue // Event } ``` 正确: ```ts @Controller() createWebsite() { return actionRuntime.execute(...) } ``` API Controller 负责: - 输入解析 - Schema Validation - Authentication Context - 调用 Runtime - Response Mapping --- # 5. API Resource API 应围绕 Resource / Action / Query 建模。 例如: ```text GET /api/v1/websites GET /api/v1/websites/:id POST /api/v1/websites POST /api/v1/websites/:id/actions/scan POST /api/v1/websites/:id/actions/publish ``` 不要为了 CRUD 强行把所有能力映射成: ```text POST /update POST /execute ``` --- # 6. Action API 推荐: ```http POST /api/v1/resources/seo.website/{id}/actions/scan ``` 或者提供更自然的领域 URL: ```http POST /api/v1/websites/{id}/scan ``` 两者最终都必须映射到: ```text Action: seo.website.scan ``` --- # 7. Action ID 是唯一业务执行标识 例如: ```text seo.website.scan seo.website.publish seo.keyword.search devops.server.restart core.file.delete ``` API 路由只是 Transport Layer。 真正的执行语义来自: ```text Action ID ``` --- # 8. Query API Query 不应该修改数据。 例如: ```http GET /api/v1/websites GET /api/v1/websites/:id GET /api/v1/websites/:id/keywords ``` 进入: ```text Query Runtime ↓ Authorization ↓ Scope ↓ Data Runtime ``` --- # 9. API Contract 每个公开 API 必须拥有: ```text Request Schema Response Schema Error Schema Authentication Permission Scope Rate Limit Version Idempotency ``` Schema 推荐: ```text Zod + OpenAPI ``` --- # 10. OpenAPI OpenAPI 是: > API Contract 的机器可读表示。 不要让 OpenAPI 成为手工维护的第二份事实来源。 推荐: ```text Domain / Action Definition ↓ API Contract ↓ OpenAPI ↓ SDK ``` --- # 11. Single Source of Truth 核心定义: ```text Resource Schema Action Definition Query Definition ``` 驱动: ```text REST OpenAPI SDK CLI Plugin UI MCP ``` 形成: ```text One Runtime Many Transports ``` --- # 12. API Versioning 公开 API 使用: ```text /v1 /v2 ``` 版本只在真正发生 Breaking Change 时升级。 例如: ```text /v1/websites ``` 未来: ```text /v2/websites ``` 不要因为新增字段就创建: ```text v2 ``` --- # 13. Versioning 原则 兼容修改: ```text 增加 optional field 增加新的 endpoint 增加新的 Action ``` 通常不需要 Major API Version。 Breaking Change: ```text 删除字段 改变字段类型 改变语义 改变认证要求 改变错误结构 改变分页协议 ``` 需要版本策略。 --- # 14. API Deprecation 旧 API: ```http GET /api/v1/websites ``` 如果废弃: ```text deprecated ``` 必须提供: ```text deprecationAt sunsetAt replacement ``` 并在 OpenAPI 中标记。 --- # 15. Response Envelope 建议统一: ```json { "data": {}, "requestId": "req_xxx" } ``` 列表: ```json { "data": [], "pagination": { "page": 1, "pageSize": 50, "total": 123 }, "requestId": "req_xxx" } ``` --- # 16. Async Response 如果 Action 异步执行: ```json { "taskId": "task_xxx", "status": "queued", "requestId": "req_xxx" } ``` HTTP: ```text 202 Accepted ``` --- # 17. Task API 统一: ```http GET /api/v1/tasks/:id GET /api/v1/tasks/:id/jobs GET /api/v1/tasks/:id/executions POST /api/v1/tasks/:id/cancel POST /api/v1/tasks/:id/retry ``` 所有 Task API 必须通过: ```text Task Runtime + Authorization + Scope ``` --- # 18. Execution API ```http GET /api/v1/executions/:id GET /api/v1/executions/:id/logs GET /api/v1/executions/:id/events GET /api/v1/executions/:id/artifacts ``` 用户必须能够查看: ```text 谁执行 为什么执行 执行什么 哪个版本 结果是什么 ``` --- # 19. Action Discovery API 平台可以暴露: ```http GET /api/v1/capabilities ``` 但必须根据: ```text Actor Organization Project Environment Permission ``` 过滤。 不能返回: ```text all actions ``` --- # 20. Capability Discovery 建议支持: ```http GET /api/v1/capabilities?level=summary ``` 以及: ```http GET /api/v1/capabilities/:id ``` Level: ```text summary schema instructions ``` 与 Agent Progressive Disclosure 保持一致。 --- # 21. API Authentication 支持: ```text Session Bearer Token API Key Service Account Token OAuth2/OIDC ``` 最终转换为: ```text SecurityContext ``` 与文档 25 完全一致。 --- # 22. API Key API Key: ```text devos_sk_xxxxx ``` 数据库只存: ```text hash ``` 同时记录: ```text id actorId organizationId scopes createdAt expiresAt lastUsedAt revokedAt ``` --- # 23. API Key Scope API Key 不应该默认拥有用户全部权限。 例如: ```json { "scopes": [ "seo.website.read", "seo.website.scan" ] } ``` 最终权限: ```text User Permissions ∩ API Key Scopes ∩ Policy ∩ Resource Scope ``` --- # 24. Service Account API 外部系统建议使用: ```text Service Account ``` 而不是个人用户 Token。 例如: ```text ci-deployer seo-importer analytics-sync crm-sync ``` --- # 25. Service Account 最小权限 例如: ```yaml id: seo-importer permissions: - seo.website.read - seo.keyword.create ``` 禁止: ```text * ``` --- # 26. OAuth / OIDC DevOS 可以支持: ```text OAuth 2.0 OpenID Connect ``` 用于: - 企业登录 - 第三方应用 - External Integration - Provider Authorization 但 OAuth 本身不是 DevOS Authorization。 最终仍然进入: ```text Identity ↓ SecurityContext ↓ Authorization ``` --- # 27. External Integration External Integration 是: > DevOS 与外部系统之间的长期连接。 例如: ```text GitHub GitLab Google Slack Discord Cloudflare AWS Docker SSH SMTP Search APIs AI Providers ``` --- # 28. Integration Runtime 建议: ```text packages/integration/ ``` 统一模型: ```ts interface IntegrationDefinition { id: string name: string provider: string capabilities: string[] authMethods: string[] configSchema: unknown } ``` --- # 29. Integration Instance Definition: ```text github ``` Instance: ```text github / organization-A / production ``` 即: ```text IntegrationDefinition ↓ IntegrationInstance ``` --- # 30. Integration 不应该直接暴露 Credential Integration 使用: ```text Credential Runtime ``` 例如: ```text GitHub Integration ↓ Credential Resolver ↓ Secret Runtime ↓ GitHub API ``` --- # 31. Provider Runtime External Integration 可以基于 Provider Runtime。 ```text Provider ↓ Credential ↓ Integration ↓ Capability ↓ Action ``` --- # 32. External Provider Health 每个 Provider 支持: ```text health() capabilities() limits() version() ``` 例如: ```json { "provider": "github", "status": "healthy", "latencyMs": 84 } ``` --- # 33. Provider Failover 未来支持: ```text OpenAI ↓ Provider A ↓ Provider B ``` 或者: ```text Search Provider A ↓ Provider B ``` 但 Failover 必须由 Provider Runtime 决定。 业务代码不能自己: ```ts if (providerA.fail) providerB() ``` --- # 34. External API Call 外部调用统一经过: ```text Integration Runtime ↓ Provider Runtime ↓ Credential Runtime ↓ Network Runtime ↓ External API ``` 必须具备: ```text timeout retry rate limit circuit breaker audit metrics trace ``` --- # 35. Retry 外部 API: ```text 429 500 502 503 504 ``` 可以 retry。 例如: ```text exponential backoff + jitter ``` 但: ```text 400 401 403 ``` 通常不应该无限 retry。 --- # 36. Idempotency 所有可能被重复提交的写 Action 支持: ```http Idempotency-Key: xxx ``` 例如: ```text POST /deploy POST /publish POST /send POST /create ``` --- # 37. Idempotency Contract 服务器记录: ```text organizationId actorId actionId idempotencyKey requestHash executionId result ``` 如果相同 Key: ```text same request ``` 返回之前结果。 如果: ```text same key different request ``` 返回: ```text 409 Conflict ``` --- # 38. Request ID 每个 API 请求必须拥有: ```text X-Request-ID ``` 如果客户端提供: ```text valid ``` 可以复用。 否则服务端生成。 --- # 39. Correlation ID 跨服务: ```text X-Correlation-ID ``` 保持一致。 用于: ```text API Task Job Execution Event Webhook Provider ``` 追踪整个业务链。 --- # 40. Trace Context 如果存在 OpenTelemetry: ```text traceparent ``` 必须正确传播。 API 不创建第二套 Trace 系统。 --- # 41. Error Contract 统一: ```json { "error": { "code": "RESOURCE_NOT_FOUND", "message": "Resource not found", "details": {} }, "requestId": "req_xxx" } ``` --- # 42. Error Code 不要依赖: ```text message ``` 客户端应该依赖: ```text error.code ``` 例如: ```text AUTH_REQUIRED AUTH_FORBIDDEN RESOURCE_NOT_FOUND VALIDATION_ERROR CONFLICT RATE_LIMITED IDEMPOTENCY_CONFLICT TASK_NOT_FOUND APPROVAL_REQUIRED EXECUTION_FAILED PROVIDER_UNAVAILABLE ``` --- # 43. Error Classification 与 Error Runtime 统一: ```text validation authentication authorization not_found conflict rate_limit timeout provider execution system ``` 并包含: ```text retryable ``` --- # 44. 安全错误 不要返回: ```text database SQL stack trace secret credential internal hostname private IP provider token ``` 生产 API: ```text safe message ``` 内部日志: ```text diagnostic detail ``` --- # 45. Pagination 列表 API 必须统一。 第一阶段: ```text page pageSize ``` 大数据场景推荐: ```text cursor limit ``` 不要不同模块各自定义: ```text offset skip page cursor start ``` --- # 46. Cursor Pagination 推荐: ```http GET /websites?limit=50&cursor=xxx ``` 返回: ```json { "data": [], "pagination": { "nextCursor": "xxx", "hasMore": true } } ``` --- # 47. Filtering 统一 Filter AST: ```json { "and": [ { "field": "status", "operator": "eq", "value": "active" } ] } ``` 与文档 14 Data Runtime 一致。 --- # 48. Sorting 统一: ```http sort=-createdAt,name ``` 但最终必须经过: ```text FieldDefinition ``` 检查: ```text sortable ``` --- # 49. Field Permission API 不能因为: ```text GET resource ``` 就返回所有字段。 字段必须支持: ```text readable sensitive ``` 例如: ```text email apiKey credentialId internalMetadata ``` --- # 50. API Export Export: ```http POST /api/v1/websites/export ``` 如果数据量大: ```text 202 ↓ Task ↓ Job ↓ Artifact ``` 返回: ```json { "taskId": "task_xxx" } ``` 完成后: ```text Artifact ↓ Signed URL ``` --- # 51. File Upload API 推荐: ```http POST /api/v1/files/uploads ``` 返回: ```json { "uploadId": "upload_xxx", "uploadUrl": "..." } ``` 实际 Blob: ```text Object Storage ``` 元数据: ```text File Runtime ``` --- # 52. File Download 禁止直接: ```text object storage public URL ``` 推荐: ```http GET /api/v1/files/:id/download ``` API 验证: ```text permission scope visibility ``` 然后生成: ```text short-lived signed URL ``` --- # 53. Webhook DevOS 对外 Webhook: ```text Event Runtime ↓ Webhook Runtime ↓ External URL ``` Webhook 不应该由业务模块自行实现。 --- # 54. Webhook Subscription ```ts interface WebhookSubscription { id: string organizationId: string url: string events: string[] secretRef: string active: boolean } ``` --- # 55. Webhook Event Envelope 例如: ```json { "id": "evt_xxx", "type": "seo.website.scan.completed", "version": "1", "createdAt": "...", "organizationId": "org_xxx", "data": {} } ``` --- # 56. Webhook Signature 使用: ```text HMAC-SHA256 ``` 建议: ```text X-DevOS-Webhook-ID X-DevOS-Webhook-Timestamp X-DevOS-Webhook-Signature ``` 签名: ```text timestamp + "." + rawBody ``` --- # 57. Webhook Retry 失败: ```text 5xx timeout network ``` 进入: ```text retry queue ``` 策略: ```text exponential backoff + jitter ``` 最终: ```text Dead Letter ``` --- # 58. Webhook SSRF Webhook URL 必须经过: ```text SSRF Protection ``` 禁止: ```text localhost 127.0.0.1 private IP metadata endpoint file:// ``` 并处理 DNS Rebinding。 --- # 59. Incoming Webhook DevOS 可以接收: ```text GitHub Webhook GitLab Webhook Stripe Webhook Cloudflare Event ``` 统一: ```text Webhook Receiver ↓ Signature Verification ↓ Event Normalization ↓ Event Runtime ``` --- # 60. External Event Normalization 外部: ```text GitHub push ``` 转换成: ```text integration.github.push.received ``` 然后进入: ```text Event Runtime ``` 业务不直接依赖 GitHub HTTP Payload。 --- # 61. Webhook → Task 例如: ```text GitHub Push ↓ Event ↓ Trigger ↓ Task ↓ Job ↓ Action ``` 不要: ```text Webhook Controller ↓ 直接执行一堆业务代码 ``` --- # 62. API → Task 长时间操作: ```text POST /scan ``` 不要让 HTTP Request 一直等待。 正确: ```text API ↓ Action Runtime ↓ Task ↓ 202 ``` --- # 63. Streaming API 支持: ```text SSE WebSocket ``` 用于: - Agent output - Task progress - Execution logs - Realtime events 但 Streaming 只是 Transport。 实际数据来自: ```text Event Runtime ``` --- # 64. SSE 例如: ```http GET /api/v1/tasks/:id/events ``` 事件: ```text task.started job.started execution.progress execution.completed task.completed ``` 必须支持: ```text Last-Event-ID ``` 用于断线恢复。 --- # 65. WebSocket WebSocket 用于: ```text interactive realtime ``` 例如: ```text Agent Chat Live Task Monitor Command Center ``` 连接建立时必须完成: ```text Authentication Authorization Scope ``` --- # 66. API Rate Limit 统一 Rate Limit: ```text organization actor API key IP route action provider ``` Response: ```http 429 Too Many Requests ``` 并返回: ```text Retry-After ``` --- # 67. Quota Rate Limit ≠ Quota。 Rate Limit: > 一段时间允许多少次。 Quota: > 一个组织总共拥有多少资源。 例如: ```text 1000 API calls/hour ``` vs: ```text 1,000,000 API calls/month ``` 两者分离。 --- # 68. Usage Runtime 所有 API 使用量进入: ```text Usage Runtime ``` 记录: ```text apiCalls actionExecutions tokens storage bandwidth taskCount providerCalls ``` 与文档 17 Observability / Usage 统一。 --- # 69. Cost Attribution 一次外部调用: ```text User ↓ Agent ↓ Task ↓ Action ↓ Provider ``` 成本必须可以追踪到: ```text organization project environment actor task execution provider ``` --- # 70. SDK 第一官方 SDK: ```text @devos/sdk ``` 推荐: ```text TypeScript ``` --- # 71. SDK Architecture ```text @devos/sdk ├── client ├── auth ├── resources ├── actions ├── tasks ├── executions ├── files ├── search ├── agents └── events ``` --- # 72. SDK 不复制业务逻辑 错误: ```ts sdk.websites.scan() ``` 内部实现: ```text 自己调用多个 API 自己做权限 自己做 retry 自己管理状态 ``` SDK 只负责: ```text Transport Serialization Authentication Typed Contract Error Mapping ``` --- # 73. SDK 示例 ```ts const client = new DevOSClient({ baseUrl, apiKey, }) const result = await client.actions.execute({ action: "seo.website.scan", resourceId: websiteId, input: { deep: true, }, }) ``` 最终: ```text Action Runtime ``` --- # 74. SDK Async ```ts const task = await client.actions.executeAsync({ action: "seo.website.scan", resourceId: websiteId, }) ``` 然后: ```ts await client.tasks.wait(task.id) ``` SDK 可以提供便利方法。 但最终仍使用: ```text Task Runtime ``` --- # 75. SDK Retry SDK 可以提供: ```text network retry ``` 但不能绕过服务端: ```text idempotency rate limit authorization ``` --- # 76. SDK Versioning SDK: ```text @devos/sdk@1.x ``` 对应: ```text API v1 ``` 但 SDK minor version 可以增加新 API。 --- # 77. Generated SDK 优先考虑: ```text OpenAPI ↓ Code Generator ↓ Typed SDK ``` 避免手写大量 CRUD Client。 --- # 78. CLI 官方 CLI: ```bash devos ``` 核心: ```bash devos login devos whoami devos project list devos action list devos action run devos task list devos task inspect devos execution inspect devos plugin list devos mcp list devos agent list devos security doctor ``` --- # 79. CLI 与 SDK CLI 不应该直接: ```text DB Redis Queue ``` CLI: ```text CLI ↓ SDK ↓ API ↓ Runtime ``` --- # 80. CLI Login ```bash devos login ``` 支持: ```text browser OAuth device flow API key ``` 本地 Token 必须安全存储。 --- # 81. CLI Action 例如: ```bash devos action run seo.website.scan \ --resource website_123 ``` 最终: ```text Action Runtime ``` 而不是: ```text CLI → WebsiteService ``` --- # 82. CLI Task ```bash devos task inspect task_123 ``` 应该显示: ```text Task Jobs Executions Progress Artifacts Errors Events ``` --- # 83. API 与 MCP MCP 可以复用: ```text Capability Registry Action Registry Schema Authorization ``` 不要: ```text REST API MCP API Plugin API ``` 分别实现三套业务逻辑。 --- # 84. API 与 Plugin Plugin 可以注册: ```text Actions Resources Queries Routes Webhooks Providers ``` 但所有业务 Action: ```text Plugin ↓ Action Registry ↓ Action Runtime ``` --- # 85. API 与 Agent Agent API: ```http POST /api/v1/agents/:id/goals ``` 创建: ```text Agent Goal ``` Agent 自己: ```text Plan ↓ Task ↓ Action ``` API 不应该暴露: ```text internal chain of thought ``` --- # 86. Agent API Response 可以返回: ```json { "goalId": "goal_xxx", "taskId": "task_xxx", "status": "running" } ``` 完成后: ```json { "goalId": "goal_xxx", "status": "completed", "result": {}, "artifacts": [] } ``` --- # 87. 不暴露 Hidden CoT API: ```text Agent reasoning ``` 不得返回: ```text hidden chain-of-thought ``` 可以返回: ```text decision summary plan actions observations results ``` --- # 88. External Integration UI Settings: ```text Settings └── Integrations ├── Installed ├── Available ├── Credentials ├── Providers └── Health ``` Project: ```text Project └── Integrations ``` --- # 89. Integration Lifecycle ```text discover ↓ install ↓ configure ↓ authorize ↓ health check ↓ active ↓ rotate credential ↓ disable ↓ remove ``` --- # 90. Integration Permission 安装 Integration 必须明确: ```text permissions network access credentials scopes data access webhooks ``` --- # 91. External Data Sync 例如: ```text GitHub ↓ Sync Task ↓ Jobs ↓ Actions ↓ Resources ``` 而不是: ```text Cron ↓ 直接写数据库 ``` --- # 92. Sync Cursor Integration Sync 必须支持: ```text cursor checkpoint lastSyncAt remoteVersion ``` 失败后可以: ```text resume ``` --- # 93. Integration Webhook + Polling 优先: ```text Webhook ``` 如果 Provider 不支持: ```text Polling ``` Polling 也必须: ```text Task Job Scheduler ``` 统一执行。 --- # 94. External API Compatibility Provider Adapter 必须隔离第三方 API 差异。 例如: ```text GitHubProvider GitLabProvider ``` 业务层使用: ```text GitProvider ``` 而不是: ```ts github.rest.repos.create() ``` 散落在业务代码中。 --- # 95. Integration Contract 定义: ```ts interface ProviderAdapter { id: string health(): Promise capabilities(): ProviderCapability[] execute( operation: ProviderOperation ): Promise } ``` --- # 96. Provider Errors 第三方错误: ```text GitHub 422 AWS AccessDenied Cloudflare 10000 ``` 转换为 DevOS Error: ```text PROVIDER_VALIDATION_ERROR PROVIDER_AUTH_ERROR PROVIDER_PERMISSION_ERROR PROVIDER_RATE_LIMITED PROVIDER_UNAVAILABLE ``` 业务层不应依赖第三方 HTTP Status。 --- # 97. Provider Rate Limit Provider Runtime 必须知道: ```text provider quota provider rate limit retry-after ``` 并避免整个系统同时打爆 Provider。 --- # 98. Circuit Breaker 连续失败: ```text Provider ↓ Circuit Open ``` 暂时停止请求。 恢复: ```text Half Open ``` 避免级联故障。 --- # 99. Timeout 所有 External Request 必须有: ```text connect timeout request timeout idle timeout ``` 禁止无限等待。 --- # 100. Integration Observability 每次 External Request 必须可追踪: ```text provider operation actor organization project task job execution requestId traceId latency status retryCount ``` --- # 101. API Audit 以下必须 Audit: ```text API key created API key revoked service account created integration installed integration authorized credential changed webhook created webhook deleted agent goal created dangerous action executed ``` --- # 102. API Security API 必须支持: ```text Authentication Authorization Scope Rate Limit Input Validation Output Filtering Audit Idempotency SSRF Protection Request Size Limit Timeout ``` --- # 103. Request Size 默认限制: ```text JSON body file upload query length header size ``` 具体数值通过 Configuration Runtime 管理。 --- # 104. Input Validation 所有外部输入: ```text API CLI Webhook MCP Plugin Agent ``` 必须 Schema Validate。 推荐: ```text Zod ``` --- # 105. Output Validation 对于: ```text Agent Provider Plugin External API ``` 外部结果也必须经过: ```text schema validation ``` 尤其是: ```text AI structured output ``` --- # 106. OpenAPI Security Scheme OpenAPI 必须声明: ```text bearerAuth apiKeyAuth oauth2 ``` 每个 endpoint 明确: ```text security permissions ``` --- # 107. API Documentation 自动生成: ```text /api/docs ``` 但生产环境可以限制访问。 文档必须包含: ```text Authentication Resources Actions Schemas Errors Pagination Webhooks Rate Limits Examples ``` --- # 108. API Playground DevOS 可以提供: ```text API Explorer ``` 支持: ```text select Action select Resource input JSON preview Permission execute view Execution ``` 但执行仍必须通过: ```text Action Runtime ``` --- # 109. API Capability Explorer 管理员可以看到: ```text Action Permission Risk Scope Input Schema Output Schema Provider Version ``` 用于: - Debug - Integration - Agent - Plugin - SDK --- # 110. External Developer Model 未来第三方开发者: ```text Developer ↓ Application ↓ OAuth ↓ Organization Grant ↓ API ``` 可以形成: ```text Developer App ``` 而不是直接给第三方一个超级 API Key。 --- # 111. Application 建议未来支持: ```ts interface DeveloperApplication { id: string organizationId: string name: string clientId: string redirectUris: string[] scopes: string[] status: "active" | "disabled" } ``` --- # 112. OAuth Consent 第三方 App 请求: ```text seo.website.read seo.website.scan ``` 用户看到: ```text Application: SEO Automation Requested: ✓ Read websites ✓ Scan websites ``` 明确批准后才能使用。 --- # 113. External App Permission 最终: ```text User Permission ∩ Application Scope ∩ Delegation ∩ Policy ``` --- # 114. API Tenant Isolation 所有 API 必须测试: ```text Org A token ↓ Org B resource ``` 必须: ```text DENY ``` 包括: ```text GET POST PUT PATCH DELETE SEARCH EXPORT TASK EXECUTION ARTIFACT FILE WEBHOOK ``` --- # 115. API Contract Tests 建立: ```text packages/api-contract-tests/ ``` 测试: ```text OpenAPI compliance authentication authorization pagination error format idempotency async behavior versioning tenant isolation ``` --- # 116. SDK Contract Tests SDK 必须测试: ```text request serialization response parsing error mapping auth retry pagination task waiting streaming ``` --- # 117. Integration Contract Tests 每个 Provider 至少: ```text health authentication basic read basic write rate limit retry error mapping timeout ``` 使用: ```text Mock Provider ``` 避免 CI 强依赖真实第三方。 --- # 118. Webhook Contract Tests 必须测试: ```text signature valid signature invalid timestamp expired duplicate event replay event retry DLQ SSRF tenant scope ``` --- # 119. CLI Contract Tests 测试: ```text login logout whoami action run task inspect JSON output human output error code exit code ``` --- # 120. API Performance 至少监控: ```text API latency P50 P95 P99 error rate throughput rate-limit count provider latency ``` --- # 121. API Health ```http GET /health ``` 用于: ```text liveness ``` ```http GET /ready ``` 用于: ```text readiness ``` 不要让: ```text /health ``` 暴露敏感系统信息。 --- # 122. API Dependency Health 内部: ```text database redis storage event bus provider ``` 由 Health Runtime 统一管理。 --- # 123. API Cache GET Query 可以缓存。 但必须: ```text tenant-aware scope-aware permission-aware ``` 不要: ```text global cache ``` 导致跨租户泄漏。 --- # 124. ETag 支持: ```http ETag If-None-Match ``` 用于稳定资源。 但 ETag 不得泄漏: ```text cross-tenant information ``` --- # 125. Optimistic Concurrency 更新资源可以支持: ```text version ETag If-Match ``` 避免: ```text last write wins ``` 覆盖其他修改。 --- # 126. Conflict 如果版本不一致: ```text 409 Conflict ``` 例如: ```json { "error": { "code": "RESOURCE_VERSION_CONFLICT" } } ``` --- # 127. Bulk API 批量操作: ```http POST /api/v1/websites/bulk-scan ``` 不能循环: ```text API ↓ 1000 synchronous actions ``` 必须: ```text Bulk Request ↓ Task ↓ Jobs ↓ Queue ↓ Workers ``` --- # 128. Batch Idempotency Bulk Task 必须有: ```text batchId idempotencyKey ``` 每个 Job 也需要: ```text job idempotency ``` 避免重复执行。 --- # 129. API Transaction API 不自己创建: ```text random transaction ``` 事务边界由: ```text Action Runtime Data Runtime ``` 定义。 --- # 130. API Event API Action 完成: ```text Action ↓ Execution ↓ Event ``` 不要: ```text Controller ↓ manual event ``` 避免重复事件。 --- # 131. API Notification 如果需要通知: ```text Event ↓ Notification Rule ↓ Notification Runtime ``` API 不直接: ```text sendEmail() ``` --- # 132. API 与 Audit API 访问本身不一定每次都需要语义 Audit。 但以下必须: ```text security changes credential access permission changes dangerous actions data export production operations ``` 记录 Audit。 普通 GET 可以主要依赖: ```text Access Log ``` 避免 Audit 数据爆炸。 --- # 133. API Logging Structured Log: ```json { "requestId": "req_x", "route": "/api/v1/websites", "method": "GET", "status": 200, "durationMs": 42 } ``` 禁止记录: ```text Authorization Cookie API Key Secret ``` --- # 134. API Gateway 第一阶段: ```text NestJS / Fastify ``` 直接提供 API Runtime。 不要一开始为了“架构完整”引入: ```text Kong Envoy API Gateway Cluster Service Mesh ``` 除非实际规模需要。 --- # 135. Reverse Proxy 生产环境可以: ```text Cloudflare Nginx Caddy Load Balancer ``` 但 DevOS 内部 API Contract 不依赖具体代理。 --- # 136. Internal API 内部模块调用: 优先: ```text TypeScript Runtime API ``` 而不是: ```text HTTP localhost ``` 例如: ```text Agent Runtime ↓ Action Runtime ``` 不需要: ```text HTTP ``` --- # 137. Service-to-Service API 如果未来拆分服务: ```text Service A ↓ Internal API ↓ Service B ``` 也必须使用: ```text Authentication Authorization Service Identity Trace Audit where needed ``` --- # 138. API Boundary 最终: ```text Browser CLI SDK Plugin MCP External App Webhook Agent Service ↓ API / Runtime ↓ Security + Authorization ↓ Query / Action / Task ↓ DevOS Runtime ``` --- # 139. Package Structure 建议: ```text packages/api/ packages/api-contract/ packages/openapi/ packages/sdk/ packages/cli/ packages/integration/ packages/provider/ packages/webhook/ packages/oauth/ packages/developer-app/ ``` 如果现有结构已经存在: > 优先复用,而不是重新创建同名 Runtime。 --- # 140. 推荐依赖方向 ```text api ↓ api-contract ↓ security ↓ action/query/task ↓ runtime ``` SDK: ```text sdk ↓ api contract ``` CLI: ```text cli ↓ sdk ``` Webhook: ```text webhook ↓ event ↓ task/action ``` Integration: ```text integration ↓ provider ↓ credential ↓ network ``` --- # 141. 禁止依赖 禁止: ```text CLI → Prisma SDK → Prisma Webhook → Prisma External Integration → Prisma Plugin → Prisma MCP → Prisma Agent → Prisma ``` --- # 142. API Implementation Order Zcode 应按照: ```text 1. API Contract 2. Authentication 3. Authorization 4. Scope 5. Query / Action Mapping 6. Error Contract 7. OpenAPI 8. Integration Tests 9. SDK 10. CLI 11. Webhook 12. External Integration ``` 实施。 --- # 143. Vertical Slice 不要一次创建全部 API。 第一个 Vertical Slice: ```text Resource ↓ Action ↓ Security ↓ REST ↓ OpenAPI ↓ SDK ↓ CLI ↓ Contract Test ``` 全部跑通后再扩展。 --- # 144. Example Vertical Slice 以: ```text seo.website.scan ``` 为例: ```text POST /api/v1/websites/:id/scan ``` 进入: ```text Authentication ↓ Authorization ↓ Scope ↓ Action Runtime ↓ Task ↓ Job ↓ Worker ↓ Execution ↓ Event ``` SDK: ```ts client.websites.scan(id) ``` CLI: ```bash devos website scan ``` 三者最终调用同一个 Action。 --- # 145. API Definition of Done 每一个新 API: - [ ] Authentication - [ ] Authorization - [ ] Scope - [ ] Request Schema - [ ] Response Schema - [ ] Error Contract - [ ] Action/Query Mapping - [ ] OpenAPI - [ ] Audit requirement evaluated - [ ] Rate Limit - [ ] Idempotency if required - [ ] Tenant Isolation Test - [ ] Contract Test - [ ] SDK if public - [ ] CLI if appropriate - [ ] Documentation --- # 146. Integration Definition of Done 每个 Integration: - [ ] Manifest - [ ] Provider - [ ] Credential - [ ] Configuration - [ ] Permissions - [ ] Scope - [ ] Health Check - [ ] Retry - [ ] Timeout - [ ] Rate Limit - [ ] Error Mapping - [ ] Audit - [ ] Metrics - [ ] Contract Test - [ ] Mock Provider - [ ] Webhook if applicable --- # 147. Zcode Implementation Protocol Zcode 开发 API 时必须先问: ```text 这个 API 对应什么 Resource? 这个 API 对应什么 Action? 这个 API 对应什么 Query? 这个 API 的 Permission 是什么? Scope 是什么? 是否异步? 是否需要 Idempotency? 是否需要 Approval? 是否需要 Audit? ``` 如果这些问题没有答案: > 不允许直接开始写 Controller。 --- # 148. Zcode 禁止创建第二套 API 逻辑 禁止: ```text REST Business Logic SDK Business Logic CLI Business Logic MCP Business Logic Plugin Business Logic Webhook Business Logic ``` 必须: ```text Transport ↓ Runtime ``` --- # 149. Zcode Master Prompt ```text DEVOS API / SDK / INTEGRATION MASTER PROTOCOL You are implementing API and integration code inside DevOS. API is a transport layer over the DevOS Runtime. Before creating an endpoint: 1. Identify Resource. 2. Identify Query or Action. 3. Identify Permission. 4. Identify Organization scope. 5. Identify Project scope. 6. Identify Environment scope. 7. Determine sync vs async. 8. Determine idempotency requirements. 9. Determine approval requirements. 10. Determine audit requirements. 11. Define request schema. 12. Define response schema. 13. Define error contract. 14. Implement API mapping. 15. Generate/update OpenAPI. 16. Add contract tests. 17. Add tenant-isolation tests. 18. Add SDK support if public. 19. Add CLI support when appropriate. 20. Add observability. Never: - put business logic in controllers; - access Prisma directly from CLI; - access Prisma directly from SDK; - access Prisma directly from Webhook; - bypass Action Runtime; - create a second business implementation for MCP; - create a second business implementation for Plugin; - create a second authorization system; - expose secrets; - expose hidden chain-of-thought; - create public storage URLs; - create unlimited API keys; - bypass tenant scope; - use unbounded retries; - create duplicate Runtime systems. All transports must converge to: Authentication → Authorization → Scope → Query / Action / Task Runtime → Execution → Event. Prefer existing DevOS Runtime components over introducing new infrastructure. Do not introduce an API Gateway, service mesh, Kafka, or distributed architecture merely for architectural appearance. Implement one vertical slice at a time. ``` --- # 150. Security Golden Rule 外部调用必须满足: ```text WHO ↓ AUTHENTICATED? ↓ AUTHORIZED? ↓ WHICH TENANT? ↓ WHICH PROJECT? ↓ WHICH ENVIRONMENT? ↓ WHICH RESOURCE? ↓ WHICH ACTION? ↓ WHICH POLICY? ↓ WHICH APPROVAL? ↓ EXECUTION ``` --- # 151. API Golden Rule > **API、SDK、CLI、Webhook、Plugin、MCP、Agent 都只是 DevOS Runtime 的不同入口;它们不能拥有自己的业务执行体系。** --- # 152. Integration Golden Rule > **所有外部系统都必须通过 Integration / Provider / Credential / Network Runtime 访问,不能让业务模块散落第三方 API 调用。** --- # 153. 最终架构 ```text External World │ ┌─────────┬───────────┼───────────┬──────────┐ ↓ ↓ ↓ ↓ ↓ REST SDK CLI Webhook OAuth │ │ │ │ │ └─────────┴───────────┼───────────┴──────────┘ ↓ API Runtime ↓ Authentication ↓ Authorization ↓ Scope ↓ ┌──────────────┼──────────────┐ ↓ ↓ ↓ Query Action Task ↓ ↓ ↓ DevOS Runtime ↓ Execution ↓ Event ↓ ┌───────────┼───────────┐ ↓ ↓ ↓ Notification Webhook Realtime ``` 外部 Provider: ```text Action ↓ Integration ↓ Provider ↓ Credential ↓ Secret ↓ Network ↓ External Service ``` 最终形成: ```text ONE RUNTIME │ ┌────────────┼────────────┐ ↓ ↓ ↓ REST MCP Plugin ↓ ↓ ↓ SDK Agent CLI ↓ ↓ ↓ External Workflow Webhook └────────────┼────────────┘ ↓ Security Runtime ↓ Action / Query / Task ↓ DevOS Execution ``` --- # 154. Final Principle DevOS 不是: ```text 一个 REST API 项目 ``` 也不是: ```text 一个 SDK 项目 ``` 更不是: ```text 一堆第三方 API Adapter ``` DevOS 应成为: > **一个拥有统一 Runtime Contract,并可以通过 REST、SDK、CLI、Plugin、MCP、Agent、Webhook 和 External Integration 被任何人或任何 Agent 安全调用的 Developer Work OS。** 最终目标: ```text BUILD ONCE Resource Action Query Task Event Capability Security ↓ EXPOSE EVERYWHERE UI REST SDK CLI MCP Plugin Agent Webhook Integration ``` **One Runtime. Many Interfaces. No Duplicate Business Logic.**