Files
devos/Docs/DevOS-Platform-v2/30_MODEL_AI_PROVIDER_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

56 KiB
Raw Blame History

DevOS Model / AI Provider Runtime

文档版本:v1.0
文档编号:30
状态:Architecture Specification
适用范围:DevOS Core / Agent Runtime / Skill Runtime / Plugin Runtime / MCP / Workflow / API / SDK
项目根目录:/home/dev/bun/devos


1. 文档目标

DevOS 必须拥有统一的 Model / AI Provider Runtime。

这一 Runtime 负责解决:

  • AI Model Registry
  • Model Provider
  • Provider Credential
  • Model Capability
  • Model Routing
  • Model Policy
  • Model Selection
  • Fallback
  • Retry
  • Timeout
  • Rate Limit
  • Token Usage
  • Cost Tracking
  • Context Window
  • Structured Output
  • Streaming
  • Tool Calling
  • Embedding
  • Reranking
  • Multimodal
  • Model Version
  • Provider Health
  • Provider Failover
  • AI Budget
  • AI Usage Attribution
  • AI Observability
  • AI Audit
  • Agent / Skill / Plugin 的统一模型调用

核心目标:

Agent 不知道 OpenAI、Anthropic、Google、DeepSeek 或其他 Provider 的 API 细节。

Agent 只知道:

Model Capability
        ↓
Model Runtime
        ↓
Model Router
        ↓
Model Provider
        ↓
External AI Provider

2. 核心原则

DevOS 的 AI 架构必须遵循:

Model ≠ Provider
Provider ≠ Credential
Credential ≠ Model Policy
Model Policy ≠ Agent

分别定义:

Model

模型能力的抽象。

例如:

gpt-x
claude-x
gemini-x
deepseek-x
embedding-x
rerank-x

Provider

模型服务提供者。

例如:

OpenAI
Anthropic
Google
DeepSeek
Azure OpenAI
AWS Bedrock
Local Ollama
Custom Provider

Credential

访问 Provider 所需要的凭证。

例如:

credential://openai/default
credential://anthropic/production
credential://azure/prod

Model Policy

决定:

什么场景
使用什么模型
什么 Provider
什么预算
什么 fallback
什么区域
什么数据级别

3. 总体架构

User
  │
Agent
  │
Skill
  │
Capability
  │
Model Runtime
  │
  ├── Model Registry
  ├── Provider Registry
  ├── Credential Resolver
  ├── Model Router
  ├── Model Policy
  ├── Context Adapter
  ├── Tool Calling Adapter
  ├── Structured Output Adapter
  ├── Streaming Adapter
  ├── Embedding Runtime
  ├── Rerank Runtime
  ├── Usage Meter
  ├── Cost Runtime
  ├── Rate Limit
  ├── Retry / Fallback
  ├── Health Check
  └── Observability
          │
          ↓
     Provider Adapter
          │
          ↓
     External AI API

4. Model Runtime 的职责

Model Runtime 是 DevOS 唯一的 AI 模型调用入口。

负责:

resolve model
resolve provider
resolve credential
authorize
select model
build request
validate context
execute
stream
parse result
record usage
record cost
emit events
handle retry
handle fallback
audit

不负责:

Agent Planning
Skill Logic
Business Logic
Task Orchestration
Plugin Business Logic

这些由其他 Runtime 负责。


5. Agent 与 Model Runtime 的边界

Agent:

我应该做什么?

Skill:

应该使用什么方法?

Model Runtime:

应该调用哪个 AI Model?

Provider:

怎么访问这个 Model?

Execution:

这次调用实际发生了什么?

因此:

Agent
  ↓
Skill
  ↓
Model Capability
  ↓
Model Runtime
  ↓
Model Router
  ↓
Provider Adapter
  ↓
External API

6. Model Capability

DevOS 不应该要求 Agent 直接指定供应商 API。

Agent 应请求:

capability = text.generate

或者:

capability = text.reason
capability = text.structured_output
capability = text.tool_calling
capability = embedding.generate
capability = rerank
capability = vision.analyze

例如:

type ModelCapability =
  | 'text.generate'
  | 'text.reason'
  | 'text.structured_output'
  | 'text.tool_calling'
  | 'text.streaming'
  | 'embedding.generate'
  | 'rerank'
  | 'vision.analyze'
  | 'audio.transcribe'
  | 'audio.generate';

7. Model Registry

DevOS 必须拥有统一 Model Registry。

例如:

interface ModelDefinition {
  id: string;

  providerId: string;

  name: string;

  version?: string;

  capabilities: ModelCapability[];

  contextWindow: number;

  maxOutputTokens?: number;

  inputTokenPrice?: number;

  outputTokenPrice?: number;

  currency?: string;

  supportsStreaming: boolean;

  supportsToolCalling: boolean;

  supportsStructuredOutput: boolean;

  supportsVision: boolean;

  status: 'active' | 'deprecated' | 'disabled';

  metadata?: Record<string, unknown>;
}

8. Model ID

Model ID 必须稳定。

推荐:

provider:model

例如:

openai:gpt-x
anthropic:claude-x
google:gemini-x
deepseek:deepseek-x

但 Runtime 内部还需要:

modelId
modelVersion
providerVersion
adapterVersion

这样 Execution 才能复现。


9. Model Version

不能只保存:

gpt-x

生产执行必须记录:

modelId
modelVersion
providerId
providerAdapterVersion

因为:

同一个 Model ID
≠ 永远得到相同结果

因此 Agent Run 应保存:

interface ModelSnapshot {
  modelId: string;
  modelVersion?: string;
  providerId: string;
  providerAdapterVersion: string;
  contextWindow: number;
}

10. Provider Registry

Provider Runtime 管理外部 AI 服务。

interface ModelProvider {
  id: string;

  name: string;

  type: string;

  capabilities: ModelCapability[];

  models: string[];

  healthStatus: 'healthy' | 'degraded' | 'down';

  enabled: boolean;
}

Provider 不直接暴露给 Agent。


11. Provider Adapter

不同 AI Provider API 不统一。

因此:

OpenAI Adapter
Anthropic Adapter
Google Adapter
Azure Adapter
Bedrock Adapter
Ollama Adapter
Custom Adapter

全部实现统一接口:

interface ModelProviderAdapter {
  generate(
    request: ModelRequest,
    context: ProviderContext,
  ): Promise<ModelResponse>;

  stream?(
    request: ModelRequest,
    context: ProviderContext,
  ): AsyncIterable<ModelStreamChunk>;
}

12. Provider Adapter 不能包含业务逻辑

Provider Adapter 只负责:

DevOS Request
    ↓
Provider Request
    ↓
External API
    ↓
Provider Response
    ↓
DevOS Response

不能负责:

SEO
CRM
Agent Planning
Task Creation
Business Rules

13. Credential Runtime

Provider Credential 必须由:

Credential Runtime

管理。

禁止:

process.env.OPENAI_API_KEY

出现在 Agent、Skill、Plugin、Service 中。

统一:

Model Runtime
  ↓
Provider Resolver
  ↓
Credential Resolver
  ↓
Secret Runtime

14. Credential 示例

credential://openai/default
credential://anthropic/default
credential://azure/production

Model Runtime 只得到:

ResolvedCredential

Credential 明文:

  • 不进入 Agent Context
  • 不进入 Prompt
  • 不进入 Event
  • 不进入 Audit
  • 不进入 Log
  • 不进入 Trace
  • 不进入 Task Payload

15. Model Request

统一请求模型:

interface ModelRequest {
  model?: string;

  capability: ModelCapability;

  messages: ModelMessage[];

  system?: string;

  temperature?: number;

  maxOutputTokens?: number;

  tools?: ModelTool[];

  responseFormat?: ResponseFormat;

  stream?: boolean;

  metadata?: Record<string, unknown>;

  budget?: ModelBudget;
}

16. Model Message

统一消息:

interface ModelMessage {
  role:
    | 'system'
    | 'user'
    | 'assistant'
    | 'tool';

  content: ModelContent[];
}

Content 支持:

text
image
audio
file
tool-call
tool-result
structured

Provider Adapter 再转换为各 Provider 的格式。


17. Structured Output

Agent 不应该依赖:

JSON.parse(modelText)

实现结构化输出。

应该:

Model Runtime
      ↓
Structured Output Schema
      ↓
Provider Native Structured Output
      ↓
Validation
      ↓
Typed Result

使用:

Zod

例如:

const PlanSchema = z.object({
  goal: z.string(),
  steps: z.array(
    z.object({
      id: z.string(),
      action: z.string(),
      reason: z.string(),
    }),
  ),
});

18. Structured Output Contract

interface StructuredOutputRequest<T> {
  schema: Schema<T>;

  strict?: boolean;

  repair?: boolean;
}

Runtime 必须:

Generate
 ↓
Parse
 ↓
Validate
 ↓
Repair if allowed
 ↓
Return Typed Result

如果失败:

MODEL_INVALID_OUTPUT

不能静默接受错误结构。


19. Tool Calling

Tool Calling 必须统一为 DevOS Capability。

模型看到:

tool

实际上对应:

Capability
  ↓
Action
  ↓
Action Runtime

例如:

search_web

最终不能直接执行:

fetch()

而是:

Model
 ↓
Tool Call
 ↓
Capability Registry
 ↓
Authorization
 ↓
Action Runtime
 ↓
Execution

20. Model Runtime 不能绕过 Action Runtime

AI Tool Calling 是最容易产生安全漏洞的地方。

禁止:

LLM
 ↓
Tool
 ↓
Direct DB

必须:

LLM
 ↓
Capability
 ↓
Security Context
 ↓
Authorization
 ↓
Action
 ↓
Action Runtime
 ↓
Execution

21. Model Routing

Agent 不应该自行决定:

调用 OpenAI
调用 Anthropic
调用 DeepSeek

而是请求:

Model Policy

例如:

interface ModelPolicy {
  id: string;

  capability: ModelCapability;

  preferredModels: string[];

  fallbackModels?: string[];

  maxCost?: number;

  maxLatencyMs?: number;

  requiredCapabilities?: ModelCapability[];

  allowedProviders?: string[];

  deniedProviders?: string[];
}

22. Model Router

Router 根据:

Capability
Policy
Context Window
Cost
Latency
Availability
Region
Data Policy
Provider Health
Quota
Tenant Policy

选择 Model。

流程:

Request
 ↓
Policy
 ↓
Candidate Models
 ↓
Capability Filter
 ↓
Security Filter
 ↓
Context Window Filter
 ↓
Provider Health
 ↓
Budget Filter
 ↓
Cost / Latency Ranking
 ↓
Selected Model

23. Hard Filter 与 Soft Ranking

非常重要:

权限、安全、数据范围:

Hard Filter

不能因为便宜而允许不符合安全策略的 Model。

例如:

restricted data

不能:

因为 Provider A 更便宜
→ 把数据发送给不允许的 Provider

正确:

Security Policy
 ↓
Hard Filter
 ↓
Allowed Models
 ↓
Cost / Latency Ranking

24. Model Selection Score

在已经通过安全和能力过滤之后,可以:

score =
  quality
  × availability
  × latencyScore
  × costScore

但:

permission
scope
data policy

绝对不能作为普通加权项。


25. Fallback

模型调用失败时支持:

Primary
 ↓
Retry
 ↓
Fallback Model
 ↓
Fallback Provider

例如:

Model A
 ↓ timeout
Model A retry
 ↓ fail
Model B
 ↓ fail
Model C

必须记录:

attempt
model
provider
error
latency
cost

26. Retry

Retry 必须由 Model Runtime 管理。

支持:

fixed
linear
exponential
jitter

例如:

1s
2s
4s
8s

但是:

invalid request
permission denied
invalid schema
context too large

通常不应该重试。


27. Context Window

Model Runtime 必须知道:

contextWindow
maxOutputTokens

Context Runtime 提供:

estimatedTokens

Model Runtime 最终检查:

inputTokens + outputTokens <= modelContextWindow

如果超出:

CONTEXT_WINDOW_EXCEEDED

或者交给 Context Runtime:

compress

但不能无限自动截断。


28. Token Runtime

Token 统计统一。

interface TokenUsage {
  inputTokens: number;

  outputTokens: number;

  cachedInputTokens?: number;

  reasoningTokens?: number;

  totalTokens: number;
}

不同 Provider 字段可能不同。

Provider Adapter 转换成统一结构。


29. Token 估算

请求执行前可能无法得到准确 Token 数。

因此支持:

estimatedInputTokens
actualInputTokens

执行前:

estimate

执行后:

actual

Cost Runtime 使用实际值结算。


30. Cost Runtime

所有模型调用必须记录成本。

interface ModelCost {
  inputCost: number;

  outputCost: number;

  cachedInputCost?: number;

  totalCost: number;

  currency: string;
}

成本归属:

organization
project
environment
agent
task
job
execution
plugin
skill
model
provider

31. Usage Attribution

一次 Model Execution 必须可以回答:

谁调用的?
哪个 Agent?
哪个 Skill?
哪个 Task?
哪个 Job?
哪个 Plugin?
哪个 Model?
花了多少钱?

32. AI Budget

Agent 已经存在 Budget Runtime。

Model Runtime 必须接入。

支持:

maxTokens
maxCost
maxRequests
maxLatency
maxRetries

例如:

interface ModelBudget {
  maxInputTokens?: number;

  maxOutputTokens?: number;

  maxCost?: number;

  maxRequests?: number;

  maxLatencyMs?: number;
}

超过:

MODEL_BUDGET_EXCEEDED

33. Budget Hierarchy

预算可以继承:

Global
 ↓
Organization
 ↓
Project
 ↓
Environment
 ↓
Agent
 ↓
Task
 ↓
Job
 ↓
Execution

子级不能突破父级预算。


34. Rate Limit

Provider 可能有:

RPM
TPM
Concurrency
Daily quota
Monthly quota

DevOS 自己也需要:

organization limit
project limit
agent limit
plugin limit
action limit

统一由 Rate Limit Runtime 管理。


35. Provider Health

Provider 必须有健康状态:

healthy
degraded
down
disabled
unknown

Health 数据来自:

health checks
recent failures
latency
rate limits
timeouts
provider errors

Router 可以根据健康状态选择备用 Provider。


36. Circuit Breaker

当 Provider 连续失败:

closed
 ↓
open
 ↓
half-open
 ↓
closed

避免 Agent 大量请求继续打向故障 Provider。


37. Streaming

统一支持:

stream()

Stream Chunk:

interface ModelStreamChunk {
  type:
    | 'text'
    | 'tool_call'
    | 'tool_result'
    | 'usage'
    | 'error'
    | 'done';

  data?: unknown;
}

UI:

Model Runtime
 ↓
Event / Realtime Runtime
 ↓
SSE / WebSocket
 ↓
Agent UI

38. Streaming 不是第二套 Runtime

禁止:

普通调用 → Model Runtime
流式调用 → 自己写另一套 Provider

正确:

Model Runtime
 ├── generate()
 └── stream()

两者共享:

Security
Routing
Credential
Budget
Usage
Cost
Audit
Observability

39. Embedding Runtime

Embedding 属于 Model Runtime 的子能力。

Embedding Request
 ↓
Model Router
 ↓
Embedding Model
 ↓
Provider

用于:

Agent Memory
Search
Knowledge
RAG
Semantic Search
Plugin Data

Embedding 不应该由每个模块自己调用 Provider。


40. Embedding Model

例如:

interface EmbeddingModel {
  id: string;

  dimensions: number;

  maxInputTokens: number;

  providerId: string;
}

Embedding 维度必须稳定。

如果更换:

embedding model

可能需要:

re-index

不能静默混用不同维度。


41. Rerank Runtime

Reranking 也是统一能力:

Search
 ↓
Candidate Results
 ↓
Rerank Model
 ↓
Ranked Results

属于:

Model Capability

而不是 Search Runtime 自己实现 Provider 调用。


42. Multimodal

Model Runtime 应统一支持:

Text
Image
Audio
Video
File

但不要求所有 Model 支持所有类型。

通过 Capability Registry 判断:

vision.analyze
audio.transcribe

43. File 与 Model Runtime

Agent 不应该把巨大文件直接塞进 Prompt。

流程:

File
 ↓
Storage Runtime
 ↓
File Processing
 ↓
Extracted Content / Reference
 ↓
Context Runtime
 ↓
Model Runtime

例如 PDF:

PDF
 ↓
Text Extraction
 ↓
Relevant Pages
 ↓
Context
 ↓
Model

44. Model Context 与 Agent Context 的区别

这是两个不同层次:

Agent Context

回答:

Agent 当前需要知道什么?

而:

Model Context

回答:

这一次模型请求实际发送了什么?

因此:

Agent Context
 ↓
Context Assembly
 ↓
Model Request
 ↓
Model Context

Model Runtime 负责最终请求边界。


45. Prompt Runtime

Prompt 应当独立于 Provider。

建议:

Prompt Template
Prompt Version
Prompt Variable
Prompt Policy
Prompt Rendering

但 Prompt Runtime 不拥有 Agent Planning。


46. Prompt Template

例如:

interface PromptTemplate {
  id: string;

  version: string;

  systemTemplate?: string;

  userTemplate?: string;

  variables: PromptVariable[];

  status: 'draft' | 'active' | 'deprecated';
}

47. Prompt Injection

外部数据必须视为:

UNTRUSTED DATA

例如:

网页内容
搜索结果
MCP 返回值
插件返回值
用户上传文件
第三方 API

绝不能因为文本中出现:

Ignore previous instructions

就改变系统策略。

正确:

System Policy
      ↓
Developer Policy
      ↓
Agent Policy
      ↓
User Goal
      ↓
Retrieved Data

Retrieved Data 永远不是系统指令。


48. Model Output 不等于可信结果

模型返回:

text
tool call
structured output

都必须经过验证。

尤其是:

Tool Call

必须:

schema validation
 ↓
authorization
 ↓
scope validation
 ↓
Action Runtime

模型不能自行提升权限。


49. AI Data Policy

不同 Model Provider 对数据处理能力不同。

Model Registry 必须允许声明:

interface ModelDataPolicy {
  trainingUse?: boolean;

  retention?: string;

  region?: string;

  dataResidency?: string[];

  sensitiveDataAllowed?: boolean;

  restrictedDataAllowed?: boolean;
}

最终由 Security / Policy Runtime 决定是否允许发送。


50. Data Residency

例如:

Project Environment
    ↓
Data Policy
    ↓
Allowed Regions
    ↓
Allowed Providers

如果 Project 要求:

Japan only

Router 不能选择:

不符合区域要求的 Provider

51. Sensitive Data

Model Runtime 必须支持:

normal
sensitive
restricted

数据级别。

但:

是否可以发送

由:

Security Policy

决定。

不能由 Agent 自己决定。


52. Redaction

必要时:

Context
 ↓
Sensitive Data Detection
 ↓
Redaction / Masking
 ↓
Model

例如:

secret
token
credential
password

绝不能自动进入 Prompt。


53. Model Call Execution

每次调用都应该产生:

ModelExecution

例如:

interface ModelExecution {
  id: string;

  requestId: string;

  correlationId: string;

  actorId: string;

  agentId?: string;

  taskId?: string;

  jobId?: string;

  modelId: string;

  providerId: string;

  startedAt: Date;

  completedAt?: Date;

  status:
    | 'pending'
    | 'running'
    | 'completed'
    | 'failed'
    | 'cancelled';

  usage?: TokenUsage;

  cost?: ModelCost;

  errorCode?: string;
}

54. Model Execution 与 Action Execution

模型调用本身可以作为:

Capability

但不能破坏 Action Runtime。

推荐:

Agent
 ↓
Action: model.generate
 ↓
Action Runtime
 ↓
Model Runtime
 ↓
Provider

因此:

Model Execution

可以关联:

Action Execution

形成完整链路。


55. 完整 Trace

一次 Agent 执行:

Agent Goal
 ↓
Agent Run
 ↓
Task
 ↓
Job
 ↓
Action Execution
 ↓
model.generate
 ↓
Model Execution
 ↓
Provider Request
 ↓
Provider Response
 ↓
Event

可以完整追踪。


56. Model Events

推荐事件:

model.requested
model.started
model.completed
model.failed
model.fallback
model.rate_limited
model.budget_exceeded
model.provider_degraded
model.provider_recovered
model.embedding.completed
model.rerank.completed

事件统一进入:

Event Runtime

57. Audit

Model Runtime 必须记录语义审计:

谁
在什么 Scope
以什么 Policy
调用了什么 Model
通过什么 Provider
结果如何
花费多少

但:

API Key
Secret
完整敏感 Prompt

不能进入 Audit。


58. Prompt Logging

默认禁止无限保存完整 Prompt。

建议:

Prompt Metadata

默认保存:

templateId
templateVersion
inputTokenCount
hash
contextSnapshotId

必要时通过受控 Debug Mode 保存内容。

Debug Mode 必须:

explicit enable
restricted permission
short retention
audited

59. Response Logging

同样不能默认无限保存完整模型输出。

默认保存:

outputTokenCount
resultHash
structuredResultMetadata
execution reference

如果业务需要完整结果:

Artifact / Task Result / Conversation

负责持久化,而不是 Observability。


60. Model Cache

允许缓存:

deterministic requests
embeddings
metadata
model capability

但必须考虑:

tenant isolation
scope
sensitivity
expiration
model version
prompt version

缓存 Key 至少应该包含:

model
version
request hash
policy context

61. 不允许跨租户共享敏感 Model Cache

例如:

Organization A

生成的结果:

不能直接被 Organization B 命中

除非明确声明该结果为:

global public cache

62. Model Policy 示例

id: agent.default

capability: text.generate

preferredModels:
  - openai:gpt-x
  - anthropic:claude-x

fallbackModels:
  - deepseek:deepseek-x

limits:
  maxCost: 0.5
  maxLatencyMs: 30000

dataPolicy:
  sensitiveDataAllowed: false

63. Agent Model Policy

Agent 可以声明:

quality: high
speed: medium
cost: low

但最终必须经过:

Platform Policy
 ↓
Organization Policy
 ↓
Project Policy
 ↓
Agent Policy

Agent 不能绕过上层 Policy。


64. Model Routing Modes

支持:

fixed
preferred
automatic
fallback
load-balanced
cost-optimized
latency-optimized
quality-optimized

例如:

Production

fixed

Agent

automatic

High-volume content

cost-optimized

Interactive chat

latency-optimized

65. Deterministic Mode

测试和部分 Workflow 需要:

deterministic model selection

例如:

model:
  provider: mock
  model: deterministic-v1

这样测试不依赖真实 AI。


66. Mock Model Provider

DevOS 必须提供:

MockModelProvider

支持:

fixed response
structured response
tool call
failure
timeout
rate limit
malformed output
streaming

这是 Agent Runtime 测试的核心基础设施。


67. Model Runtime 与 Agent Memory

Agent Memory 需要:

Embedding

因此:

Agent Memory
 ↓
Embedding Runtime
 ↓
Model Runtime

Memory Runtime 不直接访问 Provider。


68. Model Runtime 与 Search

Semantic Search:

Query
 ↓
Embedding
 ↓
Search Runtime

Reranking:

Search Results
 ↓
Rerank Model
 ↓
Model Runtime

保持:

Search Runtime
≠
Model Runtime

69. Model Runtime 与 Plugin

Plugin 可以声明:

modelCapabilities:
  - text.generate
  - embedding.generate

但 Plugin:

不能直接调用 Provider SDK

必须:

Plugin
 ↓
Model Capability
 ↓
Model Runtime

70. Model Runtime 与 MCP

MCP Server 如果需要 AI:

MCP
 ↓
Capability
 ↓
Model Runtime

不能:

MCP
 ↓
Provider API Key
 ↓
OpenAI SDK

除非它是完全独立、明确隔离的外部系统。

在 DevOS 内运行的 MCP Capability 必须遵循平台 Runtime。


71. Model Runtime 与 Workflow

Workflow 可以声明:

model.generate

例如:

Trigger
 ↓
Fetch Content
 ↓
Model Generate
 ↓
Validate
 ↓
Publish

Model 调用仍然:

Action Runtime

72. Model Runtime 与 Task

长时间 AI 工作:

Agent
 ↓
Task
 ↓
Job
 ↓
Worker
 ↓
Action
 ↓
Model Runtime

不能:

HTTP Request
 ↓
等待 10 分钟
 ↓
Model

73. Large Batch AI

例如:

生成 1000 篇文章

Agent 不应该直接调用:

1000 model.generate

而应该:

Agent
 ↓
Task
 ↓
1000 Jobs
 ↓
Queue
 ↓
Workers
 ↓
Action Runtime
 ↓
Model Runtime

这样可以:

retry
pause
resume
cancel
rate limit
budget
progress

74. Model Concurrency

支持:

global concurrency
provider concurrency
model concurrency
organization concurrency
project concurrency
agent concurrency
task concurrency

例如:

OpenAI:
  maxConcurrency = 20

Anthropic:
  maxConcurrency = 10

75. Model Reservation

对于高优先级 Task:

priority

可以影响 Model Queue。

但不能突破:

security
budget
rate limit

76. Model Queue

Model Runtime 本身不应该再创建一套独立 Queue Runtime。

如果调用需要异步:

Task Runtime

负责:

Task
Job
Queue
Worker

Model Runtime 只负责一次 Model Execution。


77. Model Timeout

至少支持:

connect timeout
request timeout
stream timeout
total execution timeout

超时:

MODEL_TIMEOUT

进入统一 Error Runtime。


78. Error Normalization

Provider 错误:

OpenAIError
AnthropicError
GoogleError

必须转换为 DevOS Error:

MODEL_AUTH_ERROR
MODEL_RATE_LIMITED
MODEL_TIMEOUT
MODEL_CONTEXT_TOO_LARGE
MODEL_INVALID_REQUEST
MODEL_INVALID_OUTPUT
MODEL_PROVIDER_UNAVAILABLE
MODEL_CONTENT_REJECTED
MODEL_BUDGET_EXCEEDED
MODEL_UNKNOWN_ERROR

79. Provider Error Metadata

内部可以保存:

provider
providerErrorCode
providerRequestId
httpStatus
retryAfter

但用户只看到:

safeMessage

80. Content Safety

Provider 返回:

content blocked

统一为:

MODEL_CONTENT_REJECTED

具体 Provider 原因作为内部 metadata。


81. Model Capability Discovery

Agent 不应该读取整个 Model Registry。

支持:

model capability discovery

例如:

需要:
structured output
tool calling
32k context

Runtime 返回:

3 candidate models

而不是把所有 Provider、Model、Schema 全塞进 Agent Context。


82. Progressive Disclosure

继续沿用 DevOS 的核心 Token 优化原则。

第一层:

text.generate

第二层:

available model capabilities

第三层:

model details

第四层:

request schema

第五层:

provider-specific details

Agent 默认只看到必要信息。


83. Model Catalog

UI 提供:

Models
Providers
Credentials
Policies
Usage
Costs
Health
Routing

84. Provider 页面

例如:

AI Providers
 ├── OpenAI
 ├── Anthropic
 ├── Google
 ├── DeepSeek
 └── Local

每个 Provider 可以查看:

Status
Models
Credentials
Usage
Latency
Errors
Limits

85. Model 页面

显示:

Model
Provider
Version
Capabilities
Context Window
Pricing
Availability
Usage
Cost
Status

86. Model Policy 页面

允许管理员配置:

Default Model
Agent Model
Fast Model
Reasoning Model
Embedding Model
Rerank Model
Fallback
Budget
Data Policy

87. Usage Dashboard

支持:

tokens
requests
cost
latency
errors
fallback
provider usage
model usage
agent usage
project usage
organization usage

88. Cost Dashboard

例如:

Today
  $12.30

This Month
  $382.20

可以按:

Provider
Model
Agent
Project
Plugin
Task
Skill

聚合。


89. Cost Attribution

一次模型调用:

Organization
    ↓
Project
    ↓
Agent
    ↓
Task
    ↓
Job
    ↓
Execution
    ↓
Model

必须可以向上聚合。


90. AI Usage Event

例如:

{
  "type": "model.completed",
  "modelId": "openai:gpt-x",
  "providerId": "openai",
  "inputTokens": 1200,
  "outputTokens": 800,
  "cost": 0.012
}

实际 Event 必须遵循:

Event Runtime

统一 Envelope。


91. Database

推荐 PostgreSQL。

核心表:

model_providers
models
model_versions
model_capabilities
model_policies
model_credentials
model_executions
model_usage
model_costs
model_health
model_routes
model_pricing
model_embeddings

不建议一开始拆成多个数据库。


92. Redis

Redis 只负责:

rate limit
provider health cache
model metadata cache
concurrency locks
temporary routing state

不作为 AI Usage Source of Truth。


93. Model Execution 数据生命周期

推荐:

PostgreSQL
  ↓
Active Execution
  ↓
Usage / Cost
  ↓
Retention
  ↓
Archive

Prompt/Response 原文如果保存,应有独立 retention。


94. Model Pricing

Pricing 不应硬编码在 Agent。

推荐:

interface ModelPricing {
  modelId: string;

  version?: string;

  inputPerMillionTokens: number;

  outputPerMillionTokens: number;

  cachedInputPerMillionTokens?: number;

  effectiveFrom: Date;

  effectiveTo?: Date;
}

这样价格变化不会破坏历史数据。


95. Historical Cost

历史 Execution 必须保留当时的:

pricingVersion
unitPrice
currency
calculatedCost

不能因为 Provider 后来涨价导致历史账单变化。


96. Model Adapter Version

Provider API 也会变化。

因此:

providerAdapterVersion

必须进入 Execution Snapshot。


97. Reproducibility

每一次 Model Execution 尽可能保存:

model
model version
provider
adapter version
prompt version
context snapshot
policy version
temperature
max tokens
tool definitions hash
structured schema version

这样可以诊断:

为什么这次 Agent 和上次行为不一样?


98. 不要求完全确定性

AI 本身不保证:

same input → same output

DevOS 要做的是:

execution reproducibility

即:

能知道当时使用了什么配置和环境。

而不是承诺:

一定得到完全相同文本。


99. Prompt Version

Prompt 修改必须有:

version

例如:

seo.article.generate@1
seo.article.generate@2

Agent Execution 记录:

promptVersion

100. Schema Version

Structured Output Schema 同样需要:

schemaVersion

否则旧 Execution 无法解释。


101. Model Configuration Snapshot

Execution 开始时生成:

interface ModelExecutionSnapshot {
  model: ModelSnapshot;

  policyVersion: string;

  promptVersion?: string;

  schemaVersion?: string;

  parameters: Record<string, unknown>;

  contextSnapshotId?: string;
}

102. Security Context

Model Runtime 必须接收:

SecurityContext

至少包含:

actor
organization
project
environment
permissions
scopes
policy

Model Router 必须根据 Security Context 过滤 Provider/Model。


103. Agent Authorization

Agent:

不是超级用户

Agent 能调用:

User permissions
∩
Agent permissions
∩
Project scope
∩
Model policy

最终得到:

Effective Model Access

104. Plugin Authorization

Plugin 同样不能因为安装了 Provider 就拥有:

所有模型

Plugin Manifest 必须声明:

modelCapabilities:
  - text.generate

管理员可以批准/拒绝。


105. Model Provider Credential 权限

管理员可能拥有:

provider.manage

普通用户只拥有:

model.use

不能查看:

credential.secret

106. Secret Boundary

绝对禁止:

Agent → Secret
Plugin → Master Secret
Model → API Key
UI → Secret Table

统一:

Model Runtime
 ↓
Credential Runtime
 ↓
Secret Runtime

107. Audit Actions

至少记录:

model.policy.updated
model.provider.created
model.provider.updated
model.credential.bound
model.credential.rotated
model.model.enabled
model.model.disabled
model.route.updated

108. Model Health Doctor

提供:

devos model doctor

检查:

Provider connectivity
Credential validity
Model availability
Capability metadata
Pricing
Rate limits
Context window
Embedding dimension
Routing policy

109. CLI

建议:

devos model list
devos model inspect <id>

devos provider list
devos provider inspect <id>
devos provider health <id>

devos model test <model>

devos model policy list
devos model policy inspect <id>

devos model usage
devos model cost

devos model doctor

110. API

推荐:

GET /v1/models
GET /v1/models/:id

GET /v1/providers
GET /v1/providers/:id

GET /v1/model-policies
GET /v1/model-executions

GET /v1/model-usage
GET /v1/model-costs

实际模型执行:

POST /v1/actions/model.generate

或者统一 Action API。


111. SDK

提供:

sdk.models.list()

sdk.models.generate()

sdk.models.stream()

sdk.embeddings.generate()

sdk.models.inspect()

SDK 不实现 Provider Business Logic。


112. Model SDK

内部 SDK:

interface DevOSModelClient {
  generate(
    request: ModelRequest,
    context: ModelContext,
  ): Promise<ModelResponse>;

  stream(
    request: ModelRequest,
    context: ModelContext,
  ): AsyncIterable<ModelStreamChunk>;

  embed(
    request: EmbeddingRequest,
    context: ModelContext,
  ): Promise<EmbeddingResponse>;
}

113. Package Structure

推荐:

packages/
├── model/
│   ├── registry/
│   ├── runtime/
│   ├── router/
│   ├── policy/
│   ├── provider/
│   ├── adapter/
│   ├── usage/
│   ├── cost/
│   ├── pricing/
│   ├── embedding/
│   ├── rerank/
│   ├── streaming/
│   └── testing/
│
├── prompt/
│
└── ai/

如果当前项目规模较小,也可以先合并为:

packages/model/

然后内部模块化。


114. 推荐 Provider Adapter 目录

例如:

packages/model/providers/
├── openai/
├── anthropic/
├── google/
├── azure/
├── bedrock/
├── deepseek/
├── ollama/
└── mock/

Provider Adapter 必须实现统一接口。


115. 第三方 SDK 使用原则

允许:

Provider Adapter
 ↓
Official Provider SDK

不允许:

Agent
 ↓
OpenAI SDK

或者:

SEO Service
 ↓
Anthropic SDK

116. Provider Plugin

未来 Provider 可以作为 Plugin 安装。

例如:

@devos/provider-openai
@devos/provider-anthropic
@devos/provider-deepseek

但 Provider Plugin:

只能提供 Provider Adapter

不能重新实现:

Model Runtime
Security
Budget
Usage
Cost
Action

117. Official Provider

DevOS 可以内置:

Mock
OpenAI
Anthropic
Google

具体 Provider 数量不是架构要求。

架构要求是:

Provider 必须可插拔。


118. Local Model

支持:

Ollama
vLLM
Local OpenAI-compatible API

本地模型仍然遵循:

Provider Runtime

因此 Agent 不需要知道它是:

cloud
or
local

119. Model Capability Registry

Capability Registry 最终可以返回:

{
  "capability": "text.structured_output",
  "models": [
    {
      "id": "provider:model",
      "contextWindow": 128000
    }
  ]
}

但是需要根据:

Security Context
Policy
Scope

过滤。


120. AI Capability Discovery

Agent 不应该问:

你有哪些模型?

而应该问:

我现在需要什么能力?

例如:

需要:
- structured output
- tool calling
- 128k context
- low cost

Router 自动选择。


121. Context Compression

如果模型 Context 不够:

Model Runtime
 ↓
Context Window Check
 ↓
Context Runtime.compress()
 ↓
Retry

但是不能:

随机截断 system prompt

必须优先保证:

System Policy
Security Policy
Current Goal
Required Tool Schema

122. Context Priority

推荐默认:

1. System / Security Policy
2. Current Goal
3. Active Task Context
4. Required Capability Instructions
5. Relevant Resources
6. Relevant Memory
7. Historical Conversation
8. Optional Metadata

具体优先级可以由 Context Policy 配置。


123. AI Cache 与 Memory 的区别

Cache

是:

相同输入尽快得到结果。

Memory

是:

Agent 未来运行时需要保留的信息。

不能混用。


124. AI Knowledge 与 Model Runtime

RAG:

Knowledge
 ↓
Search
 ↓
Context
 ↓
Model

Model Runtime 不拥有:

Knowledge Base

它只消费 Context。


125. Agent Memory 与 Model Runtime

Memory:

Memory Runtime
 ↓
Retrieval
 ↓
Context
 ↓
Model

Embedding:

Memory
 ↓
Embedding Runtime

两个 Runtime 解耦。


126. Observability

Model Runtime 必须统一接入:

Logging
Metrics
Tracing
Audit
Usage
Cost

禁止 Provider Adapter 自己创建一套 telemetry。


127. Metrics

至少:

model_requests_total
model_success_total
model_failures_total
model_latency_ms
model_input_tokens
model_output_tokens
model_cost
model_fallback_total
model_rate_limit_total
model_context_exceeded_total

避免:

unbounded model labels

128. Trace

推荐:

Agent Span
 ↓
Task Span
 ↓
Action Span
 ↓
Model Span
 ↓
Provider Span

Provider Request ID 放 metadata。


129. Model Runtime UI

建议:

AI
├── Models
├── Providers
├── Policies
├── Usage
├── Costs
├── Health
└── Executions

130. Model Execution Inspector

管理员可以查看:

Execution ID
Agent
Task
Model
Provider
Duration
Tokens
Cost
Fallback
Error
Policy
Prompt Version
Schema Version

默认不要直接展示:

Secret
完整敏感 Prompt
隐藏 Chain of Thought

131. Hidden Chain of Thought

DevOS:

不保存隐藏 Chain of Thought

不要求 Provider 返回隐藏推理。

允许保存:

decision summary
plan summary
action rationale
result summary

这些属于:

Agent Runtime

而不是 Model Runtime 的隐藏思维日志。


132. Agent Reasoning Summary

如果 Agent 需要向用户解释:

为什么选择这个 Action

可以生成:

Decision Summary

例如:

选择 GitHub Search,
因为当前 Task 需要寻找已有项目仓库。

但不保存:

完整内部推理过程。

133. Testing

必须建立 Model Runtime Contract Tests。

至少:

Provider Adapter
Model Routing
Credential
Authorization
Budget
Rate Limit
Retry
Fallback
Timeout
Structured Output
Streaming
Embedding
Cost
Usage
Context Window
Data Policy

134. Provider Contract Test

每一个 Provider Adapter 必须通过:

generate
stream
tool calling
structured output
error mapping
usage mapping
timeout

测试。


135. Fake Provider

测试环境:

Mock Provider

必须支持模拟:

success
timeout
rate limit
500
invalid output
provider down
stream failure

这样 CI 不依赖真实 API。


136. Routing Tests

必须测试:

preferred model
fallback
cost limit
latency limit
capability mismatch
context mismatch
provider down
data policy violation
credential failure

137. Security Tests

必须测试:

Agent cannot use forbidden model
Plugin cannot use forbidden provider
Tenant cannot access another tenant credential
Restricted data cannot route to forbidden provider
Model cannot bypass Action authorization
Secret never appears in model logs

138. Cost Tests

必须测试:

input token calculation
output token calculation
pricing version
fallback cost
budget exceeded
monthly aggregation
project attribution
agent attribution

139. Context Tests

必须测试:

context window
compression
system policy preservation
tool schema preservation
priority
token budget
large conversation
large file
multimodal input

140. Streaming Tests

测试:

first chunk
multiple chunks
tool call chunks
usage chunk
error chunk
disconnect
reconnect
completion

Streaming 仍必须拥有:

Execution ID

141. Failure Recovery

Provider 在:

request sent
response lost

这种情况下,系统无法永远确定 Provider 是否已经执行。

因此:

Model Execution

必须允许:

unknown

或者内部:

uncertain

状态。

不能盲目重试可能产生副作用的 Tool Call。


142. Model + Tool Call Retry

纯文本:

safe retry

Tool Call:

potential side effect

必须更加谨慎。

例如:

模型生成:
delete_server()

Provider 请求超时后:

不能简单重新执行

需要依赖:

Action Idempotency

以及:

Execution state

143. AI Request Idempotency

支持:

Idempotency-Key

尤其对于:

tool calling
structured generation
async model jobs

144. Model Runtime 与 Action Runtime 的最终关系

推荐:

Action
  model.generate
       ↓
Action Runtime
       ↓
Model Runtime
       ↓
Model Router
       ↓
Provider Adapter
       ↓
Provider

这样模型调用天然拥有:

permission
audit
execution
task
event
retry
idempotency
observability

145. 推荐数据库关系

model_providers
       │
       ├── models
       │      │
       │      ├── model_versions
       │      ├── model_pricing
       │      └── model_capabilities
       │
       ├── provider_credentials
       │
       └── provider_health

model_policies
       │
       ↓
model_routes

action_executions
       │
       ↓
model_executions
       │
       ├── model_usage
       └── model_cost

146. 配置原则

Provider 配置:

Config Runtime

Credential:

Secret / Credential Runtime

Model Metadata:

Model Registry

Policy:

Policy Runtime

不能全部塞进:

.env

147. Environment

支持:

development
staging
production

不同 Environment 可以拥有不同:

Provider
Credential
Model Policy
Budget
Allowed Models

例如:

development
→ Mock Model

staging
→ Low-cost Model

production
→ Production Model

148. Production Protection

Production 可以禁止:

mock provider
community provider
unverified model
unknown provider

由 Policy Runtime 控制。


149. Migration

Model Runtime 数据变更必须使用:

Migration Runtime

禁止:

startup ALTER TABLE

150. Provider Upgrade

Provider Adapter 升级:

Compatibility Check
 ↓
Install
 ↓
Health Check
 ↓
Canary
 ↓
Activate

历史 Execution 仍保留:

adapterVersion

151. Model Deprecation

Model 状态:

active
deprecated
disabled

Deprecated:

新 Task 不推荐使用

但旧 Execution 仍可以查看。


152. Model Removal

不能直接删除有历史 Execution 的 Model。

应该:

disabled

保留历史 Metadata。


153. Plugin Provider Removal

如果 Plugin 提供 Provider:

disable plugin

之前必须检查:

active model policies
active tasks
future schedules
agents

避免运行时突然失效。


154. Marketplace Provider

未来 Marketplace 可以安装:

AI Provider Plugin

但必须声明:

network access
model capabilities
data policy
credentials
permissions

并经过 Plugin Security。


155. Provider Trust

建议:

official
verified
community
private
unverified

生产环境可以配置:

allowedTrustLevels

156. AI Policy 与 Security Policy

二者不是同一个东西。

Security Policy

回答:

能不能?

AI Model Policy

回答:

如果能,应该用哪个?

因此:

Security
 ↓
Allowed Candidates
 ↓
Model Policy
 ↓
Router

157. AI Policy 与 Cost Policy

Cost Policy:

预算约束

Model Policy:

模型选择

例如:

Agent 要求 high quality

但:

Project budget = $1/day

最终 Router 必须遵守预算。


158. Agent Model Selection

Agent 可以提出:

quality = high

Runtime 最终决定:

effectiveModel

Agent 不能强制:

provider=openai

除非 Policy 允许。


159. Context Runtime 与 Model Runtime

职责严格分离:

Context Runtime
→ 决定发送什么

Model Runtime
→ 决定用什么模型发送

Provider Runtime
→ 决定怎么发送

160. Final Architecture

完整链路:

                USER / AGENT
                     │
                     ↓
               Security Context
                     │
                     ↓
              Context Runtime
                     │
                     ↓
              Model Capability
                     │
                     ↓
              Action Runtime
                     │
                     ↓
              Model Runtime
                     │
        ┌────────────┼────────────┐
        ↓            ↓            ↓
   Model Registry  Policy      Usage/Cost
        │            │
        └──────┬─────┘
               ↓
          Model Router
               │
               ↓
       Provider Resolver
               │
               ↓
      Credential Resolver
               │
               ↓
         Secret Runtime
               │
               ↓
        Provider Adapter
               │
               ↓
        External AI API
               │
               ↓
        Model Execution
               │
        ┌──────┼─────────┐
        ↓      ↓         ↓
      Usage   Cost     Event

161. 与整个 DevOS Runtime 的关系

最终 DevOS:

User
 │
 ↓
Security Runtime
 │
 ↓
Agent Runtime
 │
 ├── Context Runtime
 ├── Memory Runtime
 ├── Skill Runtime
 └── Model Runtime
          │
          ↓
      Action Runtime
          │
          ↓
       Execution
          │
     ┌────┴────┐
     ↓         ↓
   Task       Event
     ↓         ↓
   Worker   Realtime

162. Zcode Implementation Rules

Zcode 实现 Model Runtime 时必须遵守:

Rule 1

禁止 Agent 直接调用 Provider SDK。

Rule 2

禁止 Plugin 直接调用 Provider SDK。

Rule 3

禁止 MCP 直接绕过 Model Runtime。

Rule 4

所有 Model Execution 必须拥有 Execution ID。

Rule 5

所有 Model Execution 必须关联 Security Context。

Rule 6

所有 Model 调用必须经过 Model Policy。

Rule 7

Provider Credential 必须经过 Credential/Secret Runtime。

Rule 8

Provider Adapter 不允许包含业务逻辑。

Rule 9

Model Runtime 不实现自己的 Queue。

Rule 10

Model Runtime 不实现自己的 Audit。

Rule 11

Model Runtime 不实现自己的 Permission。

Rule 12

Model Runtime 不实现自己的 Event Bus。

Rule 13

Model Runtime 不保存隐藏 Chain of Thought。

Rule 14

Model Runtime 不允许模型自行提升权限。

Rule 15

所有 Tool Calling 必须最终进入 Action Runtime。

Rule 16

所有 Token/Cost 必须统一计量。

Rule 17

所有 Provider 错误必须标准化。

Rule 18

所有生产 Model 必须可以记录版本。

Rule 19

历史 Execution 必须保存 Model/Provider/Policy/Prompt 等必要 Snapshot。

Rule 20

不能因为支持一个新 Provider 而复制整个 AI Runtime。


163. Zcode Implementation Order

推荐分阶段:

Phase 1 — Model Domain

实现:

ModelDefinition
ProviderDefinition
Capability
Pricing
Version

Phase 2 — Provider Adapter

先实现:

Mock

然后:

OpenAI-compatible

再逐步增加其他 Provider。


Phase 3 — Model Runtime

实现:

generate
stream
structured output
tool calling

Phase 4 — Routing

实现:

Model Registry
Policy
Candidate Selection
Fallback
Health

Phase 5 — Usage / Cost

实现:

Token Meter
Pricing
Cost
Attribution
Budget

Phase 6 — Embedding

接入:

Agent Memory
Search
RAG

Phase 7 — Security

接入:

Credential
Secret
Data Policy
Scope
Authorization

Phase 8 — Observability

接入:

Log
Metric
Trace
Audit

Phase 9 — UI/API/SDK

实现:

Models
Providers
Policies
Usage
Costs
Health
Executions

164. Definition of Done

Model Runtime 只有满足以下条件才算完成:

[ ] Model Registry
[ ] Provider Registry
[ ] Provider Adapter
[ ] Credential Resolver
[ ] Model Capability
[ ] Model Policy
[ ] Model Router
[ ] Fallback
[ ] Retry
[ ] Timeout
[ ] Rate Limit
[ ] Context Window
[ ] Structured Output
[ ] Tool Calling
[ ] Streaming
[ ] Embedding
[ ] Token Usage
[ ] Cost
[ ] Budget
[ ] Provider Health
[ ] Error Normalization
[ ] Security Context
[ ] Audit
[ ] Metrics
[ ] Tracing
[ ] API
[ ] SDK
[ ] UI
[ ] Mock Provider
[ ] Contract Tests
[ ] Migration

165. Architecture Contract Tests

必须存在:

model-runtime.contract.spec.ts
provider-adapter.contract.spec.ts
model-router.contract.spec.ts
model-security.contract.spec.ts
model-budget.contract.spec.ts
model-cost.contract.spec.ts
model-streaming.contract.spec.ts
model-tool-calling.contract.spec.ts

并验证:

Agent → Model Runtime
Plugin → Model Runtime
MCP → Model Runtime
Workflow → Model Runtime
API → Model Runtime
CLI → Model Runtime

最终都进入同一套 Runtime。


166. Architecture Forbidden Imports

以下代码原则上禁止:

apps/* → provider SDK
packages/agent/* → provider SDK
packages/skill/* → provider SDK
plugins/* → provider SDK
packages/mcp/* → provider SDK

Provider SDK 只能出现在:

packages/model/providers/*

或者明确的 Provider Plugin Adapter 中。


167. Final Dependency Direction

必须保持:

Agent
  ↓
Skill
  ↓
Capability
  ↓
Action
  ↓
Model Runtime
  ↓
Provider Adapter
  ↓
External Provider

而不是:

Agent
 ↓
OpenAI SDK
 ↓
Business Logic

168. 最终 Golden Rules

Golden Rule 1

Model 是能力,Provider 是实现。

Golden Rule 2

Agent 选择需求,不直接选择 Provider。

Golden Rule 3

Model Runtime 是 DevOS 唯一统一 AI 调用层。

Golden Rule 4

Provider Adapter 只负责协议适配,不负责业务逻辑。

Golden Rule 5

Credential 永远通过 Credential / Secret Runtime。

Golden Rule 6

Tool Calling 最终必须进入 Action Runtime。

Golden Rule 7

Security Policy 决定能不能,Model Policy 决定用什么。

Golden Rule 8

Token、Cost、Budget、Usage 必须统一计量。

Golden Rule 9

Model、Provider、Prompt、Policy、Schema 都必须可版本化。

Golden Rule 10

Model Runtime 不复制 Task、Event、Security、Audit、Queue 等 Runtime。


169. DevOS AI Runtime 最终模型

                 ┌──────────────────────┐
                 │       Agent          │
                 └──────────┬───────────┘
                            ↓
                 ┌──────────────────────┐
                 │   Context Runtime    │
                 └──────────┬───────────┘
                            ↓
                 ┌──────────────────────┐
                 │   Model Capability   │
                 └──────────┬───────────┘
                            ↓
                 ┌──────────────────────┐
                 │    Action Runtime    │
                 └──────────┬───────────┘
                            ↓
                 ┌──────────────────────┐
                 │    Model Runtime     │
                 └──────────┬───────────┘
                            ↓
              ┌─────────────┴─────────────┐
              ↓                           ↓
      ┌───────────────┐           ┌───────────────┐
      │ Model Registry │           │ Model Policy  │
      └───────┬───────┘           └───────┬───────┘
              └─────────────┬─────────────┘
                            ↓
                    ┌──────────────┐
                    │ Model Router │
                    └──────┬───────┘
                           ↓
                 ┌───────────────────┐
                 │ Provider Resolver │
                 └─────────┬─────────┘
                           ↓
                 ┌───────────────────┐
                 │Credential Runtime │
                 └─────────┬─────────┘
                           ↓
                 ┌───────────────────┐
                 │ Provider Adapter  │
                 └─────────┬─────────┘
                           ↓
                    External AI API
                           │
                           ↓
                    Model Execution
                     │     │      │
                     ↓     ↓      ↓
                   Usage  Cost   Event

170. 最终结论

DevOS 不应该成为:

一个 Agent + 一个 OpenAI SDK

而应该成为:

一个统一的 AI Execution Platform

其中:

Agent
    = Goal Solver

Skill
    = Domain Method

Context Runtime
    = 当前需要知道什么

Memory Runtime
    = 未来可以记住什么

Model Runtime
    = 用什么 AI 能力完成推理/生成

Model Router
    = 选择哪个 Model

Provider Runtime
    = 通过哪个外部服务访问

Credential Runtime
    = 使用什么凭证

Action Runtime
    = 实际执行什么能力

Task Runtime
    = 如何进行长期/批量执行

Event Runtime
    = 发生了什么

Observability Runtime
    = 如何知道发生了什么

Security Runtime
    = 是否允许发生

因此 DevOS 最终形成:

GOAL
 ↓
AGENT
 ↓
CONTEXT
 ↓
SKILL / CAPABILITY
 ↓
ACTION
 ↓
MODEL RUNTIME
 ↓
MODEL ROUTER
 ↓
PROVIDER
 ↓
EXECUTION
 ↓
TASK / EVENT / AUDIT / USAGE / COST

最终 Golden Rule:

Agent 不拥有 AI Provider;Plugin 不拥有 AI Provider;业务模块不拥有 AI Provider。DevOS Model Runtime 统一拥有模型选择、Provider 适配、Credential、Routing、Fallback、Token、Cost、Budget、Security、Audit 和 Observability。

Model Runtime 是 AI 的基础设施,不是业务逻辑;Provider 是可替换实现,不是业务依赖。