Files
devos/Docs/DevOS-Platform-v2/26_API_SDK_EXTERNAL_INTEGRATION_RUNTIME.md
T
phptits 851ccf1d7f v2 platform runtime (docs 22 Phase 2/4/7 + 17): Project/Environment + Config + Storage + Observability
- Project/Environment model with default environments (dev/staging/prod)
- Config Runtime: cascade resolution (platform→org→project→env), secrets via vault
- Storage Runtime: local provider, sha256 dedup, integrity check, file list/upload/delete
- Observability: execution query, per-action summary (success rate, avg, p95), health
- Realtime SSE: workspace event stream endpoint (GET /api/v1/v2/realtime/events)
- Phase 1 acceptance: core.health.check, core.user.create, core.user.list
- Actions: core.project.*, core.config.*, core.file.*, core.user.* (62 total)
2026-09-11 21:11:07 +00:00

38 KiB
Raw Blame History

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。

统一模型:

External Client
     ↓
API / SDK / CLI / Webhook / Integration
     ↓
Authentication
     ↓
Authorization
     ↓
Scope
     ↓
Action / Query / Task Runtime
     ↓
Execution
     ↓
Event

2. API 的定位

DevOS API 不是简单的:

Controller → Service → Database

而是:

API
 ↓
Runtime Contract
 ↓
Security
 ↓
Action / Query / Task
 ↓
Execution

API 是 Runtime 的一个入口。


3. API Architecture

                    DevOS API
                       │
          ┌────────────┼────────────┐
          ↓            ↓            ↓
        REST          SSE          WebSocket
          ↓            ↓            ↓
       API Runtime / Transport Runtime
                       ↓
              Security Context
                       ↓
        ┌──────────────┼──────────────┐
        ↓              ↓              ↓
      Query          Action          Task
        ↓              ↓              ↓
                  DevOS Runtime

4. API 不应该拥有业务逻辑

禁止:

@Controller()
createWebsite() {
  // 大量业务逻辑
  // DB
  // Queue
  // Event
}

正确:

@Controller()
createWebsite() {
  return actionRuntime.execute(...)
}

API Controller 负责:

  • 输入解析
  • Schema Validation
  • Authentication Context
  • 调用 Runtime
  • Response Mapping

5. API Resource

API 应围绕 Resource / Action / Query 建模。

例如:

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 强行把所有能力映射成:

POST /update
POST /execute

6. Action API

推荐:

POST /api/v1/resources/seo.website/{id}/actions/scan

或者提供更自然的领域 URL:

POST /api/v1/websites/{id}/scan

两者最终都必须映射到:

Action:
seo.website.scan

7. Action ID 是唯一业务执行标识

例如:

seo.website.scan
seo.website.publish
seo.keyword.search
devops.server.restart
core.file.delete

API 路由只是 Transport Layer。

真正的执行语义来自:

Action ID

8. Query API

Query 不应该修改数据。

例如:

GET /api/v1/websites
GET /api/v1/websites/:id
GET /api/v1/websites/:id/keywords

进入:

Query Runtime
 ↓
Authorization
 ↓
Scope
 ↓
Data Runtime

9. API Contract

每个公开 API 必须拥有:

Request Schema
Response Schema
Error Schema
Authentication
Permission
Scope
Rate Limit
Version
Idempotency

Schema 推荐:

Zod
+
OpenAPI

10. OpenAPI

OpenAPI 是:

API Contract 的机器可读表示。

不要让 OpenAPI 成为手工维护的第二份事实来源。

推荐:

Domain / Action Definition
        ↓
API Contract
        ↓
OpenAPI
        ↓
SDK

11. Single Source of Truth

核心定义:

Resource Schema
Action Definition
Query Definition

驱动:

REST
OpenAPI
SDK
CLI
Plugin UI
MCP

形成:

One Runtime
Many Transports

12. API Versioning

公开 API 使用:

/v1
/v2

版本只在真正发生 Breaking Change 时升级。

例如:

/v1/websites

未来:

/v2/websites

不要因为新增字段就创建:

v2

13. Versioning 原则

兼容修改:

增加 optional field
增加新的 endpoint
增加新的 Action

通常不需要 Major API Version。

Breaking Change:

删除字段
改变字段类型
改变语义
改变认证要求
改变错误结构
改变分页协议

需要版本策略。


14. API Deprecation

旧 API:

GET /api/v1/websites

如果废弃:

deprecated

必须提供:

deprecationAt
sunsetAt
replacement

并在 OpenAPI 中标记。


15. Response Envelope

建议统一:

{
  "data": {},
  "requestId": "req_xxx"
}

列表:

{
  "data": [],
  "pagination": {
    "page": 1,
    "pageSize": 50,
    "total": 123
  },
  "requestId": "req_xxx"
}

16. Async Response

如果 Action 异步执行:

{
  "taskId": "task_xxx",
  "status": "queued",
  "requestId": "req_xxx"
}

HTTP:

202 Accepted

17. Task API

统一:

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 必须通过:

Task Runtime
+
Authorization
+
Scope

18. Execution API

GET /api/v1/executions/:id
GET /api/v1/executions/:id/logs
GET /api/v1/executions/:id/events
GET /api/v1/executions/:id/artifacts

用户必须能够查看:

谁执行
为什么执行
执行什么
哪个版本
结果是什么

19. Action Discovery API

平台可以暴露:

GET /api/v1/capabilities

但必须根据:

Actor
Organization
Project
Environment
Permission

过滤。

不能返回:

all actions

20. Capability Discovery

建议支持:

GET /api/v1/capabilities?level=summary

以及:

GET /api/v1/capabilities/:id

Level:

summary
schema
instructions

与 Agent Progressive Disclosure 保持一致。


21. API Authentication

支持:

Session
Bearer Token
API Key
Service Account Token
OAuth2/OIDC

最终转换为:

SecurityContext

与文档 25 完全一致。


22. API Key

API Key:

devos_sk_xxxxx

数据库只存:

hash

同时记录:

id
actorId
organizationId
scopes
createdAt
expiresAt
lastUsedAt
revokedAt

23. API Key Scope

API Key 不应该默认拥有用户全部权限。

例如:

{
  "scopes": [
    "seo.website.read",
    "seo.website.scan"
  ]
}

最终权限:

User Permissions
∩
API Key Scopes
∩
Policy
∩
Resource Scope

24. Service Account API

外部系统建议使用:

Service Account

而不是个人用户 Token。

例如:

ci-deployer
seo-importer
analytics-sync
crm-sync

25. Service Account 最小权限

例如:

id: seo-importer

permissions:
  - seo.website.read
  - seo.keyword.create

禁止:

*

26. OAuth / OIDC

DevOS 可以支持:

OAuth 2.0
OpenID Connect

用于:

  • 企业登录
  • 第三方应用
  • External Integration
  • Provider Authorization

但 OAuth 本身不是 DevOS Authorization。

最终仍然进入:

Identity
 ↓
SecurityContext
 ↓
Authorization

27. External Integration

External Integration 是:

DevOS 与外部系统之间的长期连接。

例如:

GitHub
GitLab
Google
Slack
Discord
Cloudflare
AWS
Docker
SSH
SMTP
Search APIs
AI Providers

28. Integration Runtime

建议:

packages/integration/

统一模型:

interface IntegrationDefinition {
  id: string
  name: string

  provider: string

  capabilities: string[]

  authMethods: string[]

  configSchema: unknown
}

29. Integration Instance

Definition:

github

Instance:

github / organization-A / production

即:

IntegrationDefinition
        ↓
IntegrationInstance

30. Integration 不应该直接暴露 Credential

Integration 使用:

Credential Runtime

例如:

GitHub Integration
 ↓
Credential Resolver
 ↓
Secret Runtime
 ↓
GitHub API

31. Provider Runtime

External Integration 可以基于 Provider Runtime。

Provider
 ↓
Credential
 ↓
Integration
 ↓
Capability
 ↓
Action

32. External Provider Health

每个 Provider 支持:

health()
capabilities()
limits()
version()

例如:

{
  "provider": "github",
  "status": "healthy",
  "latencyMs": 84
}

33. Provider Failover

未来支持:

OpenAI
 ↓
Provider A
 ↓
Provider B

或者:

Search Provider A
 ↓
Provider B

但 Failover 必须由 Provider Runtime 决定。

业务代码不能自己:

if (providerA.fail) providerB()

34. External API Call

外部调用统一经过:

Integration Runtime
 ↓
Provider Runtime
 ↓
Credential Runtime
 ↓
Network Runtime
 ↓
External API

必须具备:

timeout
retry
rate limit
circuit breaker
audit
metrics
trace

35. Retry

外部 API:

429
500
502
503
504

可以 retry。

例如:

exponential backoff
+
jitter

但:

400
401
403

通常不应该无限 retry。


36. Idempotency

所有可能被重复提交的写 Action 支持:

Idempotency-Key: xxx

例如:

POST /deploy
POST /publish
POST /send
POST /create

37. Idempotency Contract

服务器记录:

organizationId
actorId
actionId
idempotencyKey
requestHash
executionId
result

如果相同 Key:

same request

返回之前结果。

如果:

same key
different request

返回:

409 Conflict

38. Request ID

每个 API 请求必须拥有:

X-Request-ID

如果客户端提供:

valid

可以复用。

否则服务端生成。


39. Correlation ID

跨服务:

X-Correlation-ID

保持一致。

用于:

API
Task
Job
Execution
Event
Webhook
Provider

追踪整个业务链。


40. Trace Context

如果存在 OpenTelemetry:

traceparent

必须正确传播。

API 不创建第二套 Trace 系统。


41. Error Contract

统一:

{
  "error": {
    "code": "RESOURCE_NOT_FOUND",
    "message": "Resource not found",
    "details": {}
  },
  "requestId": "req_xxx"
}

42. Error Code

不要依赖:

message

客户端应该依赖:

error.code

例如:

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 统一:

validation
authentication
authorization
not_found
conflict
rate_limit
timeout
provider
execution
system

并包含:

retryable

44. 安全错误

不要返回:

database SQL
stack trace
secret
credential
internal hostname
private IP
provider token

生产 API:

safe message

内部日志:

diagnostic detail

45. Pagination

列表 API 必须统一。

第一阶段:

page
pageSize

大数据场景推荐:

cursor
limit

不要不同模块各自定义:

offset
skip
page
cursor
start

46. Cursor Pagination

推荐:

GET /websites?limit=50&cursor=xxx

返回:

{
  "data": [],
  "pagination": {
    "nextCursor": "xxx",
    "hasMore": true
  }
}

47. Filtering

统一 Filter AST:

{
  "and": [
    {
      "field": "status",
      "operator": "eq",
      "value": "active"
    }
  ]
}

与文档 14 Data Runtime 一致。


48. Sorting

统一:

sort=-createdAt,name

但最终必须经过:

FieldDefinition

检查:

sortable

49. Field Permission

API 不能因为:

GET resource

就返回所有字段。

字段必须支持:

readable
sensitive

例如:

email
apiKey
credentialId
internalMetadata

50. API Export

Export:

POST /api/v1/websites/export

如果数据量大:

202
 ↓
Task
 ↓
Job
 ↓
Artifact

返回:

{
  "taskId": "task_xxx"
}

完成后:

Artifact
 ↓
Signed URL

51. File Upload API

推荐:

POST /api/v1/files/uploads

返回:

{
  "uploadId": "upload_xxx",
  "uploadUrl": "..."
}

实际 Blob:

Object Storage

元数据:

File Runtime

52. File Download

禁止直接:

object storage public URL

推荐:

GET /api/v1/files/:id/download

API 验证:

permission
scope
visibility

然后生成:

short-lived signed URL

53. Webhook

DevOS 对外 Webhook:

Event Runtime
 ↓
Webhook Runtime
 ↓
External URL

Webhook 不应该由业务模块自行实现。


54. Webhook Subscription

interface WebhookSubscription {
  id: string

  organizationId: string

  url: string

  events: string[]

  secretRef: string

  active: boolean
}

55. Webhook Event Envelope

例如:

{
  "id": "evt_xxx",
  "type": "seo.website.scan.completed",
  "version": "1",
  "createdAt": "...",
  "organizationId": "org_xxx",
  "data": {}
}

56. Webhook Signature

使用:

HMAC-SHA256

建议:

X-DevOS-Webhook-ID
X-DevOS-Webhook-Timestamp
X-DevOS-Webhook-Signature

签名:

timestamp + "." + rawBody

57. Webhook Retry

失败:

5xx
timeout
network

进入:

retry queue

策略:

exponential backoff
+
jitter

最终:

Dead Letter

58. Webhook SSRF

Webhook URL 必须经过:

SSRF Protection

禁止:

localhost
127.0.0.1
private IP
metadata endpoint
file://

并处理 DNS Rebinding。


59. Incoming Webhook

DevOS 可以接收:

GitHub Webhook
GitLab Webhook
Stripe Webhook
Cloudflare Event

统一:

Webhook Receiver
 ↓
Signature Verification
 ↓
Event Normalization
 ↓
Event Runtime

60. External Event Normalization

外部:

GitHub push

转换成:

integration.github.push.received

然后进入:

Event Runtime

业务不直接依赖 GitHub HTTP Payload。


61. Webhook → Task

例如:

GitHub Push
 ↓
Event
 ↓
Trigger
 ↓
Task
 ↓
Job
 ↓
Action

不要:

Webhook Controller
 ↓
直接执行一堆业务代码

62. API → Task

长时间操作:

POST /scan

不要让 HTTP Request 一直等待。

正确:

API
 ↓
Action Runtime
 ↓
Task
 ↓
202

63. Streaming API

支持:

SSE
WebSocket

用于:

  • Agent output
  • Task progress
  • Execution logs
  • Realtime events

但 Streaming 只是 Transport。

实际数据来自:

Event Runtime

64. SSE

例如:

GET /api/v1/tasks/:id/events

事件:

task.started
job.started
execution.progress
execution.completed
task.completed

必须支持:

Last-Event-ID

用于断线恢复。


65. WebSocket

WebSocket 用于:

interactive realtime

例如:

Agent Chat
Live Task Monitor
Command Center

连接建立时必须完成:

Authentication
Authorization
Scope

66. API Rate Limit

统一 Rate Limit:

organization
actor
API key
IP
route
action
provider

Response:

429 Too Many Requests

并返回:

Retry-After

67. Quota

Rate Limit ≠ Quota。

Rate Limit:

一段时间允许多少次。

Quota:

一个组织总共拥有多少资源。

例如:

1000 API calls/hour

vs:

1,000,000 API calls/month

两者分离。


68. Usage Runtime

所有 API 使用量进入:

Usage Runtime

记录:

apiCalls
actionExecutions
tokens
storage
bandwidth
taskCount
providerCalls

与文档 17 Observability / Usage 统一。


69. Cost Attribution

一次外部调用:

User
 ↓
Agent
 ↓
Task
 ↓
Action
 ↓
Provider

成本必须可以追踪到:

organization
project
environment
actor
task
execution
provider

70. SDK

第一官方 SDK:

@devos/sdk

推荐:

TypeScript

71. SDK Architecture

@devos/sdk
 ├── client
 ├── auth
 ├── resources
 ├── actions
 ├── tasks
 ├── executions
 ├── files
 ├── search
 ├── agents
 └── events

72. SDK 不复制业务逻辑

错误:

sdk.websites.scan()

内部实现:

自己调用多个 API
自己做权限
自己做 retry
自己管理状态

SDK 只负责:

Transport
Serialization
Authentication
Typed Contract
Error Mapping

73. SDK 示例

const client = new DevOSClient({
  baseUrl,
  apiKey,
})

const result = await client.actions.execute({
  action: "seo.website.scan",
  resourceId: websiteId,
  input: {
    deep: true,
  },
})

最终:

Action Runtime

74. SDK Async

const task = await client.actions.executeAsync({
  action: "seo.website.scan",
  resourceId: websiteId,
})

然后:

await client.tasks.wait(task.id)

SDK 可以提供便利方法。

但最终仍使用:

Task Runtime

75. SDK Retry

SDK 可以提供:

network retry

但不能绕过服务端:

idempotency
rate limit
authorization

76. SDK Versioning

SDK:

@devos/sdk@1.x

对应:

API v1

但 SDK minor version 可以增加新 API。


77. Generated SDK

优先考虑:

OpenAPI
 ↓
Code Generator
 ↓
Typed SDK

避免手写大量 CRUD Client。


78. CLI

官方 CLI:

devos

核心:

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 不应该直接:

DB
Redis
Queue

CLI:

CLI
 ↓
SDK
 ↓
API
 ↓
Runtime

80. CLI Login

devos login

支持:

browser OAuth
device flow
API key

本地 Token 必须安全存储。


81. CLI Action

例如:

devos action run seo.website.scan \
  --resource website_123

最终:

Action Runtime

而不是:

CLI → WebsiteService

82. CLI Task

devos task inspect task_123

应该显示:

Task
Jobs
Executions
Progress
Artifacts
Errors
Events

83. API 与 MCP

MCP 可以复用:

Capability Registry
Action Registry
Schema
Authorization

不要:

REST API
MCP API
Plugin API

分别实现三套业务逻辑。


84. API 与 Plugin

Plugin 可以注册:

Actions
Resources
Queries
Routes
Webhooks
Providers

但所有业务 Action:

Plugin
 ↓
Action Registry
 ↓
Action Runtime

85. API 与 Agent

Agent API:

POST /api/v1/agents/:id/goals

创建:

Agent Goal

Agent 自己:

Plan
 ↓
Task
 ↓
Action

API 不应该暴露:

internal chain of thought

86. Agent API Response

可以返回:

{
  "goalId": "goal_xxx",
  "taskId": "task_xxx",
  "status": "running"
}

完成后:

{
  "goalId": "goal_xxx",
  "status": "completed",
  "result": {},
  "artifacts": []
}

87. 不暴露 Hidden CoT

API:

Agent reasoning

不得返回:

hidden chain-of-thought

可以返回:

decision summary
plan
actions
observations
results

88. External Integration UI

Settings:

Settings
 └── Integrations
      ├── Installed
      ├── Available
      ├── Credentials
      ├── Providers
      └── Health

Project:

Project
 └── Integrations

89. Integration Lifecycle

discover
 ↓
install
 ↓
configure
 ↓
authorize
 ↓
health check
 ↓
active
 ↓
rotate credential
 ↓
disable
 ↓
remove

90. Integration Permission

安装 Integration 必须明确:

permissions
network access
credentials
scopes
data access
webhooks

91. External Data Sync

例如:

GitHub
 ↓
Sync Task
 ↓
Jobs
 ↓
Actions
 ↓
Resources

而不是:

Cron
 ↓
直接写数据库

92. Sync Cursor

Integration Sync 必须支持:

cursor
checkpoint
lastSyncAt
remoteVersion

失败后可以:

resume

93. Integration Webhook + Polling

优先:

Webhook

如果 Provider 不支持:

Polling

Polling 也必须:

Task
Job
Scheduler

统一执行。


94. External API Compatibility

Provider Adapter 必须隔离第三方 API 差异。

例如:

GitHubProvider
GitLabProvider

业务层使用:

GitProvider

而不是:

github.rest.repos.create()

散落在业务代码中。


95. Integration Contract

定义:

interface ProviderAdapter {
  id: string

  health(): Promise<HealthResult>

  capabilities(): ProviderCapability[]

  execute(
    operation: ProviderOperation
  ): Promise<ProviderResult>
}

96. Provider Errors

第三方错误:

GitHub 422
AWS AccessDenied
Cloudflare 10000

转换为 DevOS Error:

PROVIDER_VALIDATION_ERROR
PROVIDER_AUTH_ERROR
PROVIDER_PERMISSION_ERROR
PROVIDER_RATE_LIMITED
PROVIDER_UNAVAILABLE

业务层不应依赖第三方 HTTP Status。


97. Provider Rate Limit

Provider Runtime 必须知道:

provider quota
provider rate limit
retry-after

并避免整个系统同时打爆 Provider。


98. Circuit Breaker

连续失败:

Provider
 ↓
Circuit Open

暂时停止请求。

恢复:

Half Open

避免级联故障。


99. Timeout

所有 External Request 必须有:

connect timeout
request timeout
idle timeout

禁止无限等待。


100. Integration Observability

每次 External Request 必须可追踪:

provider
operation
actor
organization
project
task
job
execution
requestId
traceId
latency
status
retryCount

101. API Audit

以下必须 Audit:

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 必须支持:

Authentication
Authorization
Scope
Rate Limit
Input Validation
Output Filtering
Audit
Idempotency
SSRF Protection
Request Size Limit
Timeout

103. Request Size

默认限制:

JSON body
file upload
query length
header size

具体数值通过 Configuration Runtime 管理。


104. Input Validation

所有外部输入:

API
CLI
Webhook
MCP
Plugin
Agent

必须 Schema Validate。

推荐:

Zod

105. Output Validation

对于:

Agent
Provider
Plugin
External API

外部结果也必须经过:

schema validation

尤其是:

AI structured output

106. OpenAPI Security Scheme

OpenAPI 必须声明:

bearerAuth
apiKeyAuth
oauth2

每个 endpoint 明确:

security
permissions

107. API Documentation

自动生成:

/api/docs

但生产环境可以限制访问。

文档必须包含:

Authentication
Resources
Actions
Schemas
Errors
Pagination
Webhooks
Rate Limits
Examples

108. API Playground

DevOS 可以提供:

API Explorer

支持:

select Action
select Resource
input JSON
preview Permission
execute
view Execution

但执行仍必须通过:

Action Runtime

109. API Capability Explorer

管理员可以看到:

Action
Permission
Risk
Scope
Input Schema
Output Schema
Provider
Version

用于:

  • Debug
  • Integration
  • Agent
  • Plugin
  • SDK

110. External Developer Model

未来第三方开发者:

Developer
 ↓
Application
 ↓
OAuth
 ↓
Organization Grant
 ↓
API

可以形成:

Developer App

而不是直接给第三方一个超级 API Key。


111. Application

建议未来支持:

interface DeveloperApplication {
  id: string

  organizationId: string

  name: string

  clientId: string

  redirectUris: string[]

  scopes: string[]

  status: "active" | "disabled"
}

112. OAuth Consent

第三方 App 请求:

seo.website.read
seo.website.scan

用户看到:

Application:
SEO Automation

Requested:
✓ Read websites
✓ Scan websites

明确批准后才能使用。


113. External App Permission

最终:

User Permission
∩
Application Scope
∩
Delegation
∩
Policy

114. API Tenant Isolation

所有 API 必须测试:

Org A token
 ↓
Org B resource

必须:

DENY

包括:

GET
POST
PUT
PATCH
DELETE
SEARCH
EXPORT
TASK
EXECUTION
ARTIFACT
FILE
WEBHOOK

115. API Contract Tests

建立:

packages/api-contract-tests/

测试:

OpenAPI compliance
authentication
authorization
pagination
error format
idempotency
async behavior
versioning
tenant isolation

116. SDK Contract Tests

SDK 必须测试:

request serialization
response parsing
error mapping
auth
retry
pagination
task waiting
streaming

117. Integration Contract Tests

每个 Provider 至少:

health
authentication
basic read
basic write
rate limit
retry
error mapping
timeout

使用:

Mock Provider

避免 CI 强依赖真实第三方。


118. Webhook Contract Tests

必须测试:

signature valid
signature invalid
timestamp expired
duplicate event
replay event
retry
DLQ
SSRF
tenant scope

119. CLI Contract Tests

测试:

login
logout
whoami
action run
task inspect
JSON output
human output
error code
exit code

120. API Performance

至少监控:

API latency
P50
P95
P99
error rate
throughput
rate-limit count
provider latency

121. API Health

GET /health

用于:

liveness
GET /ready

用于:

readiness

不要让:

/health

暴露敏感系统信息。


122. API Dependency Health

内部:

database
redis
storage
event bus
provider

由 Health Runtime 统一管理。


123. API Cache

GET Query 可以缓存。

但必须:

tenant-aware
scope-aware
permission-aware

不要:

global cache

导致跨租户泄漏。


124. ETag

支持:

ETag
If-None-Match

用于稳定资源。

但 ETag 不得泄漏:

cross-tenant information

125. Optimistic Concurrency

更新资源可以支持:

version
ETag
If-Match

避免:

last write wins

覆盖其他修改。


126. Conflict

如果版本不一致:

409 Conflict

例如:

{
  "error": {
    "code": "RESOURCE_VERSION_CONFLICT"
  }
}

127. Bulk API

批量操作:

POST /api/v1/websites/bulk-scan

不能循环:

API
 ↓
1000 synchronous actions

必须:

Bulk Request
 ↓
Task
 ↓
Jobs
 ↓
Queue
 ↓
Workers

128. Batch Idempotency

Bulk Task 必须有:

batchId
idempotencyKey

每个 Job 也需要:

job idempotency

避免重复执行。


129. API Transaction

API 不自己创建:

random transaction

事务边界由:

Action Runtime
Data Runtime

定义。


130. API Event

API Action 完成:

Action
 ↓
Execution
 ↓
Event

不要:

Controller
 ↓
manual event

避免重复事件。


131. API Notification

如果需要通知:

Event
 ↓
Notification Rule
 ↓
Notification Runtime

API 不直接:

sendEmail()

132. API 与 Audit

API 访问本身不一定每次都需要语义 Audit。

但以下必须:

security changes
credential access
permission changes
dangerous actions
data export
production operations

记录 Audit。

普通 GET 可以主要依赖:

Access Log

避免 Audit 数据爆炸。


133. API Logging

Structured Log:

{
  "requestId": "req_x",
  "route": "/api/v1/websites",
  "method": "GET",
  "status": 200,
  "durationMs": 42
}

禁止记录:

Authorization
Cookie
API Key
Secret

134. API Gateway

第一阶段:

NestJS / Fastify

直接提供 API Runtime。

不要一开始为了“架构完整”引入:

Kong
Envoy
API Gateway Cluster
Service Mesh

除非实际规模需要。


135. Reverse Proxy

生产环境可以:

Cloudflare
Nginx
Caddy
Load Balancer

但 DevOS 内部 API Contract 不依赖具体代理。


136. Internal API

内部模块调用:

优先:

TypeScript Runtime API

而不是:

HTTP localhost

例如:

Agent Runtime
 ↓
Action Runtime

不需要:

HTTP

137. Service-to-Service API

如果未来拆分服务:

Service A
 ↓
Internal API
 ↓
Service B

也必须使用:

Authentication
Authorization
Service Identity
Trace
Audit where needed

138. API Boundary

最终:

Browser
CLI
SDK
Plugin
MCP
External App
Webhook
Agent
Service
       ↓
     API / Runtime
       ↓
 Security + Authorization
       ↓
 Query / Action / Task
       ↓
 DevOS Runtime

139. Package Structure

建议:

packages/api/
packages/api-contract/
packages/openapi/
packages/sdk/
packages/cli/
packages/integration/
packages/provider/
packages/webhook/
packages/oauth/
packages/developer-app/

如果现有结构已经存在:

优先复用,而不是重新创建同名 Runtime。


140. 推荐依赖方向

api
 ↓
api-contract
 ↓
security
 ↓
action/query/task
 ↓
runtime

SDK:

sdk
 ↓
api contract

CLI:

cli
 ↓
sdk

Webhook:

webhook
 ↓
event
 ↓
task/action

Integration:

integration
 ↓
provider
 ↓
credential
 ↓
network

141. 禁止依赖

禁止:

CLI → Prisma
SDK → Prisma
Webhook → Prisma
External Integration → Prisma
Plugin → Prisma
MCP → Prisma
Agent → Prisma

142. API Implementation Order

Zcode 应按照:

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:

Resource
 ↓
Action
 ↓
Security
 ↓
REST
 ↓
OpenAPI
 ↓
SDK
 ↓
CLI
 ↓
Contract Test

全部跑通后再扩展。


144. Example Vertical Slice

以:

seo.website.scan

为例:

POST
/api/v1/websites/:id/scan

进入:

Authentication
 ↓
Authorization
 ↓
Scope
 ↓
Action Runtime
 ↓
Task
 ↓
Job
 ↓
Worker
 ↓
Execution
 ↓
Event

SDK:

client.websites.scan(id)

CLI:

devos website scan <id>

三者最终调用同一个 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 时必须先问:

这个 API 对应什么 Resource?
这个 API 对应什么 Action?
这个 API 对应什么 Query?
这个 API 的 Permission 是什么?
Scope 是什么?
是否异步?
是否需要 Idempotency?
是否需要 Approval?
是否需要 Audit?

如果这些问题没有答案:

不允许直接开始写 Controller。


148. Zcode 禁止创建第二套 API 逻辑

禁止:

REST Business Logic
SDK Business Logic
CLI Business Logic
MCP Business Logic
Plugin Business Logic
Webhook Business Logic

必须:

Transport
 ↓
Runtime

149. Zcode Master Prompt

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

外部调用必须满足:

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. 最终架构

                         External World
                              │
        ┌─────────┬───────────┼───────────┬──────────┐
        ↓         ↓           ↓           ↓          ↓
       REST      SDK         CLI       Webhook    OAuth
        │         │           │           │          │
        └─────────┴───────────┼───────────┴──────────┘
                              ↓
                         API Runtime
                              ↓
                     Authentication
                              ↓
                     Authorization
                              ↓
                           Scope
                              ↓
               ┌──────────────┼──────────────┐
               ↓              ↓              ↓
             Query          Action          Task
               ↓              ↓              ↓
                    DevOS Runtime
                         ↓
                     Execution
                         ↓
                       Event
                         ↓
             ┌───────────┼───────────┐
             ↓           ↓           ↓
        Notification   Webhook    Realtime

外部 Provider:

Action
 ↓
Integration
 ↓
Provider
 ↓
Credential
 ↓
Secret
 ↓
Network
 ↓
External Service

最终形成:

                ONE RUNTIME
                    │
       ┌────────────┼────────────┐
       ↓            ↓            ↓
      REST          MCP         Plugin
       ↓            ↓            ↓
      SDK          Agent        CLI
       ↓            ↓            ↓
    External     Workflow    Webhook
       └────────────┼────────────┘
                    ↓
             Security Runtime
                    ↓
            Action / Query / Task
                    ↓
              DevOS Execution

154. Final Principle

DevOS 不是:

一个 REST API 项目

也不是:

一个 SDK 项目

更不是:

一堆第三方 API Adapter

DevOS 应成为:

一个拥有统一 Runtime Contract,并可以通过 REST、SDK、CLI、Plugin、MCP、Agent、Webhook 和 External Integration 被任何人或任何 Agent 安全调用的 Developer Work OS。

最终目标:

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.