# 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 只知道: ```text Model Capability ↓ Model Runtime ↓ Model Router ↓ Model Provider ↓ External AI Provider ``` --- # 2. 核心原则 DevOS 的 AI 架构必须遵循: ```text Model ≠ Provider Provider ≠ Credential Credential ≠ Model Policy Model Policy ≠ Agent ``` 分别定义: ### Model 模型能力的抽象。 例如: ```text gpt-x claude-x gemini-x deepseek-x embedding-x rerank-x ``` --- ### Provider 模型服务提供者。 例如: ```text OpenAI Anthropic Google DeepSeek Azure OpenAI AWS Bedrock Local Ollama Custom Provider ``` --- ### Credential 访问 Provider 所需要的凭证。 例如: ```text credential://openai/default credential://anthropic/production credential://azure/prod ``` --- ### Model Policy 决定: ```text 什么场景 使用什么模型 什么 Provider 什么预算 什么 fallback 什么区域 什么数据级别 ``` --- # 3. 总体架构 ```text 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 模型调用入口。 负责: ```text 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 ``` 不负责: ```text Agent Planning Skill Logic Business Logic Task Orchestration Plugin Business Logic ``` 这些由其他 Runtime 负责。 --- # 5. Agent 与 Model Runtime 的边界 Agent: ```text 我应该做什么? ``` Skill: ```text 应该使用什么方法? ``` Model Runtime: ```text 应该调用哪个 AI Model? ``` Provider: ```text 怎么访问这个 Model? ``` Execution: ```text 这次调用实际发生了什么? ``` 因此: ```text Agent ↓ Skill ↓ Model Capability ↓ Model Runtime ↓ Model Router ↓ Provider Adapter ↓ External API ``` --- # 6. Model Capability DevOS 不应该要求 Agent 直接指定供应商 API。 Agent 应请求: ```text capability = text.generate ``` 或者: ```text capability = text.reason capability = text.structured_output capability = text.tool_calling capability = embedding.generate capability = rerank capability = vision.analyze ``` 例如: ```ts 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。 例如: ```ts 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; } ``` --- # 8. Model ID Model ID 必须稳定。 推荐: ```text provider:model ``` 例如: ```text openai:gpt-x anthropic:claude-x google:gemini-x deepseek:deepseek-x ``` 但 Runtime 内部还需要: ```text modelId modelVersion providerVersion adapterVersion ``` 这样 Execution 才能复现。 --- # 9. Model Version 不能只保存: ```text gpt-x ``` 生产执行必须记录: ```text modelId modelVersion providerId providerAdapterVersion ``` 因为: ```text 同一个 Model ID ≠ 永远得到相同结果 ``` 因此 Agent Run 应保存: ```ts interface ModelSnapshot { modelId: string; modelVersion?: string; providerId: string; providerAdapterVersion: string; contextWindow: number; } ``` --- # 10. Provider Registry Provider Runtime 管理外部 AI 服务。 ```ts 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 不统一。 因此: ```text OpenAI Adapter Anthropic Adapter Google Adapter Azure Adapter Bedrock Adapter Ollama Adapter Custom Adapter ``` 全部实现统一接口: ```ts interface ModelProviderAdapter { generate( request: ModelRequest, context: ProviderContext, ): Promise; stream?( request: ModelRequest, context: ProviderContext, ): AsyncIterable; } ``` --- # 12. Provider Adapter 不能包含业务逻辑 Provider Adapter 只负责: ```text DevOS Request ↓ Provider Request ↓ External API ↓ Provider Response ↓ DevOS Response ``` 不能负责: ```text SEO CRM Agent Planning Task Creation Business Rules ``` --- # 13. Credential Runtime Provider Credential 必须由: ```text Credential Runtime ``` 管理。 禁止: ```ts process.env.OPENAI_API_KEY ``` 出现在 Agent、Skill、Plugin、Service 中。 统一: ```text Model Runtime ↓ Provider Resolver ↓ Credential Resolver ↓ Secret Runtime ``` --- # 14. Credential 示例 ```text credential://openai/default credential://anthropic/default credential://azure/production ``` Model Runtime 只得到: ```ts ResolvedCredential ``` Credential 明文: - 不进入 Agent Context - 不进入 Prompt - 不进入 Event - 不进入 Audit - 不进入 Log - 不进入 Trace - 不进入 Task Payload --- # 15. Model Request 统一请求模型: ```ts interface ModelRequest { model?: string; capability: ModelCapability; messages: ModelMessage[]; system?: string; temperature?: number; maxOutputTokens?: number; tools?: ModelTool[]; responseFormat?: ResponseFormat; stream?: boolean; metadata?: Record; budget?: ModelBudget; } ``` --- # 16. Model Message 统一消息: ```ts interface ModelMessage { role: | 'system' | 'user' | 'assistant' | 'tool'; content: ModelContent[]; } ``` Content 支持: ```text text image audio file tool-call tool-result structured ``` Provider Adapter 再转换为各 Provider 的格式。 --- # 17. Structured Output Agent 不应该依赖: ```text JSON.parse(modelText) ``` 实现结构化输出。 应该: ```text Model Runtime ↓ Structured Output Schema ↓ Provider Native Structured Output ↓ Validation ↓ Typed Result ``` 使用: ```ts Zod ``` 例如: ```ts 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 ```ts interface StructuredOutputRequest { schema: Schema; strict?: boolean; repair?: boolean; } ``` Runtime 必须: ```text Generate ↓ Parse ↓ Validate ↓ Repair if allowed ↓ Return Typed Result ``` 如果失败: ```text MODEL_INVALID_OUTPUT ``` 不能静默接受错误结构。 --- # 19. Tool Calling Tool Calling 必须统一为 DevOS Capability。 模型看到: ```text tool ``` 实际上对应: ```text Capability ↓ Action ↓ Action Runtime ``` 例如: ```text search_web ``` 最终不能直接执行: ```text fetch() ``` 而是: ```text Model ↓ Tool Call ↓ Capability Registry ↓ Authorization ↓ Action Runtime ↓ Execution ``` --- # 20. Model Runtime 不能绕过 Action Runtime AI Tool Calling 是最容易产生安全漏洞的地方。 禁止: ```text LLM ↓ Tool ↓ Direct DB ``` 必须: ```text LLM ↓ Capability ↓ Security Context ↓ Authorization ↓ Action ↓ Action Runtime ↓ Execution ``` --- # 21. Model Routing Agent 不应该自行决定: ```text 调用 OpenAI 调用 Anthropic 调用 DeepSeek ``` 而是请求: ```text Model Policy ``` 例如: ```ts interface ModelPolicy { id: string; capability: ModelCapability; preferredModels: string[]; fallbackModels?: string[]; maxCost?: number; maxLatencyMs?: number; requiredCapabilities?: ModelCapability[]; allowedProviders?: string[]; deniedProviders?: string[]; } ``` --- # 22. Model Router Router 根据: ```text Capability Policy Context Window Cost Latency Availability Region Data Policy Provider Health Quota Tenant Policy ``` 选择 Model。 流程: ```text 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 非常重要: 权限、安全、数据范围: ```text Hard Filter ``` 不能因为便宜而允许不符合安全策略的 Model。 例如: ```text restricted data ``` 不能: ```text 因为 Provider A 更便宜 → 把数据发送给不允许的 Provider ``` 正确: ```text Security Policy ↓ Hard Filter ↓ Allowed Models ↓ Cost / Latency Ranking ``` --- # 24. Model Selection Score 在已经通过安全和能力过滤之后,可以: ```text score = quality × availability × latencyScore × costScore ``` 但: ```text permission scope data policy ``` 绝对不能作为普通加权项。 --- # 25. Fallback 模型调用失败时支持: ```text Primary ↓ Retry ↓ Fallback Model ↓ Fallback Provider ``` 例如: ```text Model A ↓ timeout Model A retry ↓ fail Model B ↓ fail Model C ``` 必须记录: ```text attempt model provider error latency cost ``` --- # 26. Retry Retry 必须由 Model Runtime 管理。 支持: ```text fixed linear exponential jitter ``` 例如: ```text 1s 2s 4s 8s ``` 但是: ```text invalid request permission denied invalid schema context too large ``` 通常不应该重试。 --- # 27. Context Window Model Runtime 必须知道: ```text contextWindow maxOutputTokens ``` Context Runtime 提供: ```text estimatedTokens ``` Model Runtime 最终检查: ```text inputTokens + outputTokens <= modelContextWindow ``` 如果超出: ```text CONTEXT_WINDOW_EXCEEDED ``` 或者交给 Context Runtime: ```text compress ``` 但不能无限自动截断。 --- # 28. Token Runtime Token 统计统一。 ```ts interface TokenUsage { inputTokens: number; outputTokens: number; cachedInputTokens?: number; reasoningTokens?: number; totalTokens: number; } ``` 不同 Provider 字段可能不同。 Provider Adapter 转换成统一结构。 --- # 29. Token 估算 请求执行前可能无法得到准确 Token 数。 因此支持: ```text estimatedInputTokens actualInputTokens ``` 执行前: ```text estimate ``` 执行后: ```text actual ``` Cost Runtime 使用实际值结算。 --- # 30. Cost Runtime 所有模型调用必须记录成本。 ```ts interface ModelCost { inputCost: number; outputCost: number; cachedInputCost?: number; totalCost: number; currency: string; } ``` 成本归属: ```text organization project environment agent task job execution plugin skill model provider ``` --- # 31. Usage Attribution 一次 Model Execution 必须可以回答: ```text 谁调用的? ``` ```text 哪个 Agent? ``` ```text 哪个 Skill? ``` ```text 哪个 Task? ``` ```text 哪个 Job? ``` ```text 哪个 Plugin? ``` ```text 哪个 Model? ``` ```text 花了多少钱? ``` --- # 32. AI Budget Agent 已经存在 Budget Runtime。 Model Runtime 必须接入。 支持: ```text maxTokens maxCost maxRequests maxLatency maxRetries ``` 例如: ```ts interface ModelBudget { maxInputTokens?: number; maxOutputTokens?: number; maxCost?: number; maxRequests?: number; maxLatencyMs?: number; } ``` 超过: ```text MODEL_BUDGET_EXCEEDED ``` --- # 33. Budget Hierarchy 预算可以继承: ```text Global ↓ Organization ↓ Project ↓ Environment ↓ Agent ↓ Task ↓ Job ↓ Execution ``` 子级不能突破父级预算。 --- # 34. Rate Limit Provider 可能有: ```text RPM TPM Concurrency Daily quota Monthly quota ``` DevOS 自己也需要: ```text organization limit project limit agent limit plugin limit action limit ``` 统一由 Rate Limit Runtime 管理。 --- # 35. Provider Health Provider 必须有健康状态: ```text healthy degraded down disabled unknown ``` Health 数据来自: ```text health checks recent failures latency rate limits timeouts provider errors ``` Router 可以根据健康状态选择备用 Provider。 --- # 36. Circuit Breaker 当 Provider 连续失败: ```text closed ↓ open ↓ half-open ↓ closed ``` 避免 Agent 大量请求继续打向故障 Provider。 --- # 37. Streaming 统一支持: ```text stream() ``` Stream Chunk: ```ts interface ModelStreamChunk { type: | 'text' | 'tool_call' | 'tool_result' | 'usage' | 'error' | 'done'; data?: unknown; } ``` UI: ```text Model Runtime ↓ Event / Realtime Runtime ↓ SSE / WebSocket ↓ Agent UI ``` --- # 38. Streaming 不是第二套 Runtime 禁止: ```text 普通调用 → Model Runtime 流式调用 → 自己写另一套 Provider ``` 正确: ```text Model Runtime ├── generate() └── stream() ``` 两者共享: ```text Security Routing Credential Budget Usage Cost Audit Observability ``` --- # 39. Embedding Runtime Embedding 属于 Model Runtime 的子能力。 ```text Embedding Request ↓ Model Router ↓ Embedding Model ↓ Provider ``` 用于: ```text Agent Memory Search Knowledge RAG Semantic Search Plugin Data ``` Embedding 不应该由每个模块自己调用 Provider。 --- # 40. Embedding Model 例如: ```ts interface EmbeddingModel { id: string; dimensions: number; maxInputTokens: number; providerId: string; } ``` Embedding 维度必须稳定。 如果更换: ```text embedding model ``` 可能需要: ```text re-index ``` 不能静默混用不同维度。 --- # 41. Rerank Runtime Reranking 也是统一能力: ```text Search ↓ Candidate Results ↓ Rerank Model ↓ Ranked Results ``` 属于: ```text Model Capability ``` 而不是 Search Runtime 自己实现 Provider 调用。 --- # 42. Multimodal Model Runtime 应统一支持: ```text Text Image Audio Video File ``` 但不要求所有 Model 支持所有类型。 通过 Capability Registry 判断: ```text vision.analyze audio.transcribe ``` --- # 43. File 与 Model Runtime Agent 不应该把巨大文件直接塞进 Prompt。 流程: ```text File ↓ Storage Runtime ↓ File Processing ↓ Extracted Content / Reference ↓ Context Runtime ↓ Model Runtime ``` 例如 PDF: ```text PDF ↓ Text Extraction ↓ Relevant Pages ↓ Context ↓ Model ``` --- # 44. Model Context 与 Agent Context 的区别 这是两个不同层次: ```text Agent Context ``` 回答: > Agent 当前需要知道什么? 而: ```text Model Context ``` 回答: > 这一次模型请求实际发送了什么? 因此: ```text Agent Context ↓ Context Assembly ↓ Model Request ↓ Model Context ``` Model Runtime 负责最终请求边界。 --- # 45. Prompt Runtime Prompt 应当独立于 Provider。 建议: ```text Prompt Template Prompt Version Prompt Variable Prompt Policy Prompt Rendering ``` 但 Prompt Runtime 不拥有 Agent Planning。 --- # 46. Prompt Template 例如: ```ts interface PromptTemplate { id: string; version: string; systemTemplate?: string; userTemplate?: string; variables: PromptVariable[]; status: 'draft' | 'active' | 'deprecated'; } ``` --- # 47. Prompt Injection 外部数据必须视为: ```text UNTRUSTED DATA ``` 例如: ```text 网页内容 搜索结果 MCP 返回值 插件返回值 用户上传文件 第三方 API ``` 绝不能因为文本中出现: ```text Ignore previous instructions ``` 就改变系统策略。 正确: ```text System Policy ↓ Developer Policy ↓ Agent Policy ↓ User Goal ↓ Retrieved Data ``` Retrieved Data 永远不是系统指令。 --- # 48. Model Output 不等于可信结果 模型返回: ```text text tool call structured output ``` 都必须经过验证。 尤其是: ```text Tool Call ``` 必须: ```text schema validation ↓ authorization ↓ scope validation ↓ Action Runtime ``` 模型不能自行提升权限。 --- # 49. AI Data Policy 不同 Model Provider 对数据处理能力不同。 Model Registry 必须允许声明: ```ts interface ModelDataPolicy { trainingUse?: boolean; retention?: string; region?: string; dataResidency?: string[]; sensitiveDataAllowed?: boolean; restrictedDataAllowed?: boolean; } ``` 最终由 Security / Policy Runtime 决定是否允许发送。 --- # 50. Data Residency 例如: ```text Project Environment ↓ Data Policy ↓ Allowed Regions ↓ Allowed Providers ``` 如果 Project 要求: ```text Japan only ``` Router 不能选择: ```text 不符合区域要求的 Provider ``` --- # 51. Sensitive Data Model Runtime 必须支持: ```text normal sensitive restricted ``` 数据级别。 但: ```text 是否可以发送 ``` 由: ```text Security Policy ``` 决定。 不能由 Agent 自己决定。 --- # 52. Redaction 必要时: ```text Context ↓ Sensitive Data Detection ↓ Redaction / Masking ↓ Model ``` 例如: ```text secret token credential password ``` 绝不能自动进入 Prompt。 --- # 53. Model Call Execution 每次调用都应该产生: ```text ModelExecution ``` 例如: ```ts 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 模型调用本身可以作为: ```text Capability ``` 但不能破坏 Action Runtime。 推荐: ```text Agent ↓ Action: model.generate ↓ Action Runtime ↓ Model Runtime ↓ Provider ``` 因此: ```text Model Execution ``` 可以关联: ```text Action Execution ``` 形成完整链路。 --- # 55. 完整 Trace 一次 Agent 执行: ```text Agent Goal ↓ Agent Run ↓ Task ↓ Job ↓ Action Execution ↓ model.generate ↓ Model Execution ↓ Provider Request ↓ Provider Response ↓ Event ``` 可以完整追踪。 --- # 56. Model Events 推荐事件: ```text 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 ``` 事件统一进入: ```text Event Runtime ``` --- # 57. Audit Model Runtime 必须记录语义审计: ```text 谁 在什么 Scope 以什么 Policy 调用了什么 Model 通过什么 Provider 结果如何 花费多少 ``` 但: ```text API Key Secret 完整敏感 Prompt ``` 不能进入 Audit。 --- # 58. Prompt Logging 默认禁止无限保存完整 Prompt。 建议: ```text Prompt Metadata ``` 默认保存: ```text templateId templateVersion inputTokenCount hash contextSnapshotId ``` 必要时通过受控 Debug Mode 保存内容。 Debug Mode 必须: ```text explicit enable restricted permission short retention audited ``` --- # 59. Response Logging 同样不能默认无限保存完整模型输出。 默认保存: ```text outputTokenCount resultHash structuredResultMetadata execution reference ``` 如果业务需要完整结果: ```text Artifact / Task Result / Conversation ``` 负责持久化,而不是 Observability。 --- # 60. Model Cache 允许缓存: ```text deterministic requests embeddings metadata model capability ``` 但必须考虑: ```text tenant isolation scope sensitivity expiration model version prompt version ``` 缓存 Key 至少应该包含: ```text model version request hash policy context ``` --- # 61. 不允许跨租户共享敏感 Model Cache 例如: ```text Organization A ``` 生成的结果: ```text 不能直接被 Organization B 命中 ``` 除非明确声明该结果为: ```text global public cache ``` --- # 62. Model Policy 示例 ```yaml 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 可以声明: ```text quality: high speed: medium cost: low ``` 但最终必须经过: ```text Platform Policy ↓ Organization Policy ↓ Project Policy ↓ Agent Policy ``` Agent 不能绕过上层 Policy。 --- # 64. Model Routing Modes 支持: ```text fixed preferred automatic fallback load-balanced cost-optimized latency-optimized quality-optimized ``` 例如: ### Production ```text fixed ``` ### Agent ```text automatic ``` ### High-volume content ```text cost-optimized ``` ### Interactive chat ```text latency-optimized ``` --- # 65. Deterministic Mode 测试和部分 Workflow 需要: ```text deterministic model selection ``` 例如: ```yaml model: provider: mock model: deterministic-v1 ``` 这样测试不依赖真实 AI。 --- # 66. Mock Model Provider DevOS 必须提供: ```text MockModelProvider ``` 支持: ```text fixed response structured response tool call failure timeout rate limit malformed output streaming ``` 这是 Agent Runtime 测试的核心基础设施。 --- # 67. Model Runtime 与 Agent Memory Agent Memory 需要: ```text Embedding ``` 因此: ```text Agent Memory ↓ Embedding Runtime ↓ Model Runtime ``` Memory Runtime 不直接访问 Provider。 --- # 68. Model Runtime 与 Search Semantic Search: ```text Query ↓ Embedding ↓ Search Runtime ``` Reranking: ```text Search Results ↓ Rerank Model ↓ Model Runtime ``` 保持: ```text Search Runtime ≠ Model Runtime ``` --- # 69. Model Runtime 与 Plugin Plugin 可以声明: ```yaml modelCapabilities: - text.generate - embedding.generate ``` 但 Plugin: ```text 不能直接调用 Provider SDK ``` 必须: ```text Plugin ↓ Model Capability ↓ Model Runtime ``` --- # 70. Model Runtime 与 MCP MCP Server 如果需要 AI: ```text MCP ↓ Capability ↓ Model Runtime ``` 不能: ```text MCP ↓ Provider API Key ↓ OpenAI SDK ``` 除非它是完全独立、明确隔离的外部系统。 在 DevOS 内运行的 MCP Capability 必须遵循平台 Runtime。 --- # 71. Model Runtime 与 Workflow Workflow 可以声明: ```text model.generate ``` 例如: ```text Trigger ↓ Fetch Content ↓ Model Generate ↓ Validate ↓ Publish ``` Model 调用仍然: ```text Action Runtime ``` --- # 72. Model Runtime 与 Task 长时间 AI 工作: ```text Agent ↓ Task ↓ Job ↓ Worker ↓ Action ↓ Model Runtime ``` 不能: ```text HTTP Request ↓ 等待 10 分钟 ↓ Model ``` --- # 73. Large Batch AI 例如: ```text 生成 1000 篇文章 ``` Agent 不应该直接调用: ```text 1000 model.generate ``` 而应该: ```text Agent ↓ Task ↓ 1000 Jobs ↓ Queue ↓ Workers ↓ Action Runtime ↓ Model Runtime ``` 这样可以: ```text retry pause resume cancel rate limit budget progress ``` --- # 74. Model Concurrency 支持: ```text global concurrency provider concurrency model concurrency organization concurrency project concurrency agent concurrency task concurrency ``` 例如: ```text OpenAI: maxConcurrency = 20 Anthropic: maxConcurrency = 10 ``` --- # 75. Model Reservation 对于高优先级 Task: ```text priority ``` 可以影响 Model Queue。 但不能突破: ```text security budget rate limit ``` --- # 76. Model Queue Model Runtime 本身不应该再创建一套独立 Queue Runtime。 如果调用需要异步: ```text Task Runtime ``` 负责: ```text Task Job Queue Worker ``` Model Runtime 只负责一次 Model Execution。 --- # 77. Model Timeout 至少支持: ```text connect timeout request timeout stream timeout total execution timeout ``` 超时: ```text MODEL_TIMEOUT ``` 进入统一 Error Runtime。 --- # 78. Error Normalization Provider 错误: ```text OpenAIError AnthropicError GoogleError ``` 必须转换为 DevOS Error: ```text 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 内部可以保存: ```text provider providerErrorCode providerRequestId httpStatus retryAfter ``` 但用户只看到: ```text safeMessage ``` --- # 80. Content Safety Provider 返回: ```text content blocked ``` 统一为: ```text MODEL_CONTENT_REJECTED ``` 具体 Provider 原因作为内部 metadata。 --- # 81. Model Capability Discovery Agent 不应该读取整个 Model Registry。 支持: ```text model capability discovery ``` 例如: ```text 需要: structured output tool calling 32k context ``` Runtime 返回: ```text 3 candidate models ``` 而不是把所有 Provider、Model、Schema 全塞进 Agent Context。 --- # 82. Progressive Disclosure 继续沿用 DevOS 的核心 Token 优化原则。 第一层: ```text text.generate ``` 第二层: ```text available model capabilities ``` 第三层: ```text model details ``` 第四层: ```text request schema ``` 第五层: ```text provider-specific details ``` Agent 默认只看到必要信息。 --- # 83. Model Catalog UI 提供: ```text Models Providers Credentials Policies Usage Costs Health Routing ``` --- # 84. Provider 页面 例如: ```text AI Providers ├── OpenAI ├── Anthropic ├── Google ├── DeepSeek └── Local ``` 每个 Provider 可以查看: ```text Status Models Credentials Usage Latency Errors Limits ``` --- # 85. Model 页面 显示: ```text Model Provider Version Capabilities Context Window Pricing Availability Usage Cost Status ``` --- # 86. Model Policy 页面 允许管理员配置: ```text Default Model Agent Model Fast Model Reasoning Model Embedding Model Rerank Model Fallback Budget Data Policy ``` --- # 87. Usage Dashboard 支持: ```text tokens requests cost latency errors fallback provider usage model usage agent usage project usage organization usage ``` --- # 88. Cost Dashboard 例如: ```text Today $12.30 This Month $382.20 ``` 可以按: ```text Provider Model Agent Project Plugin Task Skill ``` 聚合。 --- # 89. Cost Attribution 一次模型调用: ```text Organization ↓ Project ↓ Agent ↓ Task ↓ Job ↓ Execution ↓ Model ``` 必须可以向上聚合。 --- # 90. AI Usage Event 例如: ```json { "type": "model.completed", "modelId": "openai:gpt-x", "providerId": "openai", "inputTokens": 1200, "outputTokens": 800, "cost": 0.012 } ``` 实际 Event 必须遵循: ```text Event Runtime ``` 统一 Envelope。 --- # 91. Database 推荐 PostgreSQL。 核心表: ```text 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 只负责: ```text rate limit provider health cache model metadata cache concurrency locks temporary routing state ``` 不作为 AI Usage Source of Truth。 --- # 93. Model Execution 数据生命周期 推荐: ```text PostgreSQL ↓ Active Execution ↓ Usage / Cost ↓ Retention ↓ Archive ``` Prompt/Response 原文如果保存,应有独立 retention。 --- # 94. Model Pricing Pricing 不应硬编码在 Agent。 推荐: ```ts interface ModelPricing { modelId: string; version?: string; inputPerMillionTokens: number; outputPerMillionTokens: number; cachedInputPerMillionTokens?: number; effectiveFrom: Date; effectiveTo?: Date; } ``` 这样价格变化不会破坏历史数据。 --- # 95. Historical Cost 历史 Execution 必须保留当时的: ```text pricingVersion unitPrice currency calculatedCost ``` 不能因为 Provider 后来涨价导致历史账单变化。 --- # 96. Model Adapter Version Provider API 也会变化。 因此: ```text providerAdapterVersion ``` 必须进入 Execution Snapshot。 --- # 97. Reproducibility 每一次 Model Execution 尽可能保存: ```text model model version provider adapter version prompt version context snapshot policy version temperature max tokens tool definitions hash structured schema version ``` 这样可以诊断: > 为什么这次 Agent 和上次行为不一样? --- # 98. 不要求完全确定性 AI 本身不保证: ```text same input → same output ``` DevOS 要做的是: ```text execution reproducibility ``` 即: > 能知道当时使用了什么配置和环境。 而不是承诺: > 一定得到完全相同文本。 --- # 99. Prompt Version Prompt 修改必须有: ```text version ``` 例如: ```text seo.article.generate@1 seo.article.generate@2 ``` Agent Execution 记录: ```text promptVersion ``` --- # 100. Schema Version Structured Output Schema 同样需要: ```text schemaVersion ``` 否则旧 Execution 无法解释。 --- # 101. Model Configuration Snapshot Execution 开始时生成: ```ts interface ModelExecutionSnapshot { model: ModelSnapshot; policyVersion: string; promptVersion?: string; schemaVersion?: string; parameters: Record; contextSnapshotId?: string; } ``` --- # 102. Security Context Model Runtime 必须接收: ```ts SecurityContext ``` 至少包含: ```text actor organization project environment permissions scopes policy ``` Model Router 必须根据 Security Context 过滤 Provider/Model。 --- # 103. Agent Authorization Agent: ```text 不是超级用户 ``` Agent 能调用: ```text User permissions ∩ Agent permissions ∩ Project scope ∩ Model policy ``` 最终得到: ```text Effective Model Access ``` --- # 104. Plugin Authorization Plugin 同样不能因为安装了 Provider 就拥有: ```text 所有模型 ``` Plugin Manifest 必须声明: ```yaml modelCapabilities: - text.generate ``` 管理员可以批准/拒绝。 --- # 105. Model Provider Credential 权限 管理员可能拥有: ```text provider.manage ``` 普通用户只拥有: ```text model.use ``` 不能查看: ```text credential.secret ``` --- # 106. Secret Boundary 绝对禁止: ```text Agent → Secret Plugin → Master Secret Model → API Key UI → Secret Table ``` 统一: ```text Model Runtime ↓ Credential Runtime ↓ Secret Runtime ``` --- # 107. Audit Actions 至少记录: ```text 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 提供: ```text devos model doctor ``` 检查: ```text Provider connectivity Credential validity Model availability Capability metadata Pricing Rate limits Context window Embedding dimension Routing policy ``` --- # 109. CLI 建议: ```bash devos model list devos model inspect devos provider list devos provider inspect devos provider health devos model test devos model policy list devos model policy inspect devos model usage devos model cost devos model doctor ``` --- # 110. API 推荐: ```text 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 ``` 实际模型执行: ```text POST /v1/actions/model.generate ``` 或者统一 Action API。 --- # 111. SDK 提供: ```ts sdk.models.list() sdk.models.generate() sdk.models.stream() sdk.embeddings.generate() sdk.models.inspect() ``` SDK 不实现 Provider Business Logic。 --- # 112. Model SDK 内部 SDK: ```ts interface DevOSModelClient { generate( request: ModelRequest, context: ModelContext, ): Promise; stream( request: ModelRequest, context: ModelContext, ): AsyncIterable; embed( request: EmbeddingRequest, context: ModelContext, ): Promise; } ``` --- # 113. Package Structure 推荐: ```text packages/ ├── model/ │ ├── registry/ │ ├── runtime/ │ ├── router/ │ ├── policy/ │ ├── provider/ │ ├── adapter/ │ ├── usage/ │ ├── cost/ │ ├── pricing/ │ ├── embedding/ │ ├── rerank/ │ ├── streaming/ │ └── testing/ │ ├── prompt/ │ └── ai/ ``` 如果当前项目规模较小,也可以先合并为: ```text packages/model/ ``` 然后内部模块化。 --- # 114. 推荐 Provider Adapter 目录 例如: ```text packages/model/providers/ ├── openai/ ├── anthropic/ ├── google/ ├── azure/ ├── bedrock/ ├── deepseek/ ├── ollama/ └── mock/ ``` Provider Adapter 必须实现统一接口。 --- # 115. 第三方 SDK 使用原则 允许: ```text Provider Adapter ↓ Official Provider SDK ``` 不允许: ```text Agent ↓ OpenAI SDK ``` 或者: ```text SEO Service ↓ Anthropic SDK ``` --- # 116. Provider Plugin 未来 Provider 可以作为 Plugin 安装。 例如: ```text @devos/provider-openai @devos/provider-anthropic @devos/provider-deepseek ``` 但 Provider Plugin: ```text 只能提供 Provider Adapter ``` 不能重新实现: ```text Model Runtime Security Budget Usage Cost Action ``` --- # 117. Official Provider DevOS 可以内置: ```text Mock OpenAI Anthropic Google ``` 具体 Provider 数量不是架构要求。 架构要求是: > Provider 必须可插拔。 --- # 118. Local Model 支持: ```text Ollama vLLM Local OpenAI-compatible API ``` 本地模型仍然遵循: ```text Provider Runtime ``` 因此 Agent 不需要知道它是: ```text cloud or local ``` --- # 119. Model Capability Registry Capability Registry 最终可以返回: ```json { "capability": "text.structured_output", "models": [ { "id": "provider:model", "contextWindow": 128000 } ] } ``` 但是需要根据: ```text Security Context Policy Scope ``` 过滤。 --- # 120. AI Capability Discovery Agent 不应该问: > 你有哪些模型? 而应该问: > 我现在需要什么能力? 例如: ```text 需要: - structured output - tool calling - 128k context - low cost ``` Router 自动选择。 --- # 121. Context Compression 如果模型 Context 不够: ```text Model Runtime ↓ Context Window Check ↓ Context Runtime.compress() ↓ Retry ``` 但是不能: ```text 随机截断 system prompt ``` 必须优先保证: ```text System Policy Security Policy Current Goal Required Tool Schema ``` --- # 122. Context Priority 推荐默认: ```text 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 的区别 ```text Cache ``` 是: > 相同输入尽快得到结果。 ```text Memory ``` 是: > Agent 未来运行时需要保留的信息。 不能混用。 --- # 124. AI Knowledge 与 Model Runtime RAG: ```text Knowledge ↓ Search ↓ Context ↓ Model ``` Model Runtime 不拥有: ```text Knowledge Base ``` 它只消费 Context。 --- # 125. Agent Memory 与 Model Runtime Memory: ```text Memory Runtime ↓ Retrieval ↓ Context ↓ Model ``` Embedding: ```text Memory ↓ Embedding Runtime ``` 两个 Runtime 解耦。 --- # 126. Observability Model Runtime 必须统一接入: ```text Logging Metrics Tracing Audit Usage Cost ``` 禁止 Provider Adapter 自己创建一套 telemetry。 --- # 127. Metrics 至少: ```text 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 ``` 避免: ```text unbounded model labels ``` --- # 128. Trace 推荐: ```text Agent Span ↓ Task Span ↓ Action Span ↓ Model Span ↓ Provider Span ``` Provider Request ID 放 metadata。 --- # 129. Model Runtime UI 建议: ```text AI ├── Models ├── Providers ├── Policies ├── Usage ├── Costs ├── Health └── Executions ``` --- # 130. Model Execution Inspector 管理员可以查看: ```text Execution ID Agent Task Model Provider Duration Tokens Cost Fallback Error Policy Prompt Version Schema Version ``` 默认不要直接展示: ```text Secret 完整敏感 Prompt 隐藏 Chain of Thought ``` --- # 131. Hidden Chain of Thought DevOS: ```text 不保存隐藏 Chain of Thought ``` 不要求 Provider 返回隐藏推理。 允许保存: ```text decision summary plan summary action rationale result summary ``` 这些属于: ```text Agent Runtime ``` 而不是 Model Runtime 的隐藏思维日志。 --- # 132. Agent Reasoning Summary 如果 Agent 需要向用户解释: ```text 为什么选择这个 Action ``` 可以生成: ```text Decision Summary ``` 例如: ```text 选择 GitHub Search, 因为当前 Task 需要寻找已有项目仓库。 ``` 但不保存: ```text 完整内部推理过程。 ``` --- # 133. Testing 必须建立 Model Runtime Contract Tests。 至少: ```text 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 必须通过: ```text generate stream tool calling structured output error mapping usage mapping timeout ``` 测试。 --- # 135. Fake Provider 测试环境: ```text Mock Provider ``` 必须支持模拟: ```text success timeout rate limit 500 invalid output provider down stream failure ``` 这样 CI 不依赖真实 API。 --- # 136. Routing Tests 必须测试: ```text preferred model fallback cost limit latency limit capability mismatch context mismatch provider down data policy violation credential failure ``` --- # 137. Security Tests 必须测试: ```text 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 必须测试: ```text input token calculation output token calculation pricing version fallback cost budget exceeded monthly aggregation project attribution agent attribution ``` --- # 139. Context Tests 必须测试: ```text context window compression system policy preservation tool schema preservation priority token budget large conversation large file multimodal input ``` --- # 140. Streaming Tests 测试: ```text first chunk multiple chunks tool call chunks usage chunk error chunk disconnect reconnect completion ``` Streaming 仍必须拥有: ```text Execution ID ``` --- # 141. Failure Recovery Provider 在: ```text request sent response lost ``` 这种情况下,系统无法永远确定 Provider 是否已经执行。 因此: ```text Model Execution ``` 必须允许: ```text unknown ``` 或者内部: ```text uncertain ``` 状态。 不能盲目重试可能产生副作用的 Tool Call。 --- # 142. Model + Tool Call Retry 纯文本: ```text safe retry ``` Tool Call: ```text potential side effect ``` 必须更加谨慎。 例如: ```text 模型生成: delete_server() ``` Provider 请求超时后: ```text 不能简单重新执行 ``` 需要依赖: ```text Action Idempotency ``` 以及: ```text Execution state ``` --- # 143. AI Request Idempotency 支持: ```text Idempotency-Key ``` 尤其对于: ```text tool calling structured generation async model jobs ``` --- # 144. Model Runtime 与 Action Runtime 的最终关系 推荐: ```text Action model.generate ↓ Action Runtime ↓ Model Runtime ↓ Model Router ↓ Provider Adapter ↓ Provider ``` 这样模型调用天然拥有: ```text permission audit execution task event retry idempotency observability ``` --- # 145. 推荐数据库关系 ```text 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 配置: ```text Config Runtime ``` Credential: ```text Secret / Credential Runtime ``` Model Metadata: ```text Model Registry ``` Policy: ```text Policy Runtime ``` 不能全部塞进: ```text .env ``` --- # 147. Environment 支持: ```text development staging production ``` 不同 Environment 可以拥有不同: ```text Provider Credential Model Policy Budget Allowed Models ``` 例如: ```text development → Mock Model staging → Low-cost Model production → Production Model ``` --- # 148. Production Protection Production 可以禁止: ```text mock provider community provider unverified model unknown provider ``` 由 Policy Runtime 控制。 --- # 149. Migration Model Runtime 数据变更必须使用: ```text Migration Runtime ``` 禁止: ```text startup ALTER TABLE ``` --- # 150. Provider Upgrade Provider Adapter 升级: ```text Compatibility Check ↓ Install ↓ Health Check ↓ Canary ↓ Activate ``` 历史 Execution 仍保留: ```text adapterVersion ``` --- # 151. Model Deprecation Model 状态: ```text active deprecated disabled ``` Deprecated: ```text 新 Task 不推荐使用 ``` 但旧 Execution 仍可以查看。 --- # 152. Model Removal 不能直接删除有历史 Execution 的 Model。 应该: ```text disabled ``` 保留历史 Metadata。 --- # 153. Plugin Provider Removal 如果 Plugin 提供 Provider: ```text disable plugin ``` 之前必须检查: ```text active model policies active tasks future schedules agents ``` 避免运行时突然失效。 --- # 154. Marketplace Provider 未来 Marketplace 可以安装: ```text AI Provider Plugin ``` 但必须声明: ```text network access model capabilities data policy credentials permissions ``` 并经过 Plugin Security。 --- # 155. Provider Trust 建议: ```text official verified community private unverified ``` 生产环境可以配置: ```text allowedTrustLevels ``` --- # 156. AI Policy 与 Security Policy 二者不是同一个东西。 ```text Security Policy ``` 回答: > 能不能? ```text AI Model Policy ``` 回答: > 如果能,应该用哪个? 因此: ```text Security ↓ Allowed Candidates ↓ Model Policy ↓ Router ``` --- # 157. AI Policy 与 Cost Policy Cost Policy: ```text 预算约束 ``` Model Policy: ```text 模型选择 ``` 例如: ```text Agent 要求 high quality ``` 但: ```text Project budget = $1/day ``` 最终 Router 必须遵守预算。 --- # 158. Agent Model Selection Agent 可以提出: ```text quality = high ``` Runtime 最终决定: ```text effectiveModel ``` Agent 不能强制: ```text provider=openai ``` 除非 Policy 允许。 --- # 159. Context Runtime 与 Model Runtime 职责严格分离: ```text Context Runtime → 决定发送什么 Model Runtime → 决定用什么模型发送 Provider Runtime → 决定怎么发送 ``` --- # 160. Final Architecture 完整链路: ```text 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: ```text 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 实现: ```text ModelDefinition ProviderDefinition Capability Pricing Version ``` --- ## Phase 2 — Provider Adapter 先实现: ```text Mock ``` 然后: ```text OpenAI-compatible ``` 再逐步增加其他 Provider。 --- ## Phase 3 — Model Runtime 实现: ```text generate stream structured output tool calling ``` --- ## Phase 4 — Routing 实现: ```text Model Registry Policy Candidate Selection Fallback Health ``` --- ## Phase 5 — Usage / Cost 实现: ```text Token Meter Pricing Cost Attribution Budget ``` --- ## Phase 6 — Embedding 接入: ```text Agent Memory Search RAG ``` --- ## Phase 7 — Security 接入: ```text Credential Secret Data Policy Scope Authorization ``` --- ## Phase 8 — Observability 接入: ```text Log Metric Trace Audit ``` --- ## Phase 9 — UI/API/SDK 实现: ```text Models Providers Policies Usage Costs Health Executions ``` --- # 164. Definition of Done Model Runtime 只有满足以下条件才算完成: ```text [ ] 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 必须存在: ```text 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 ``` 并验证: ```text Agent → Model Runtime Plugin → Model Runtime MCP → Model Runtime Workflow → Model Runtime API → Model Runtime CLI → Model Runtime ``` 最终都进入同一套 Runtime。 --- # 166. Architecture Forbidden Imports 以下代码原则上禁止: ```text apps/* → provider SDK packages/agent/* → provider SDK packages/skill/* → provider SDK plugins/* → provider SDK packages/mcp/* → provider SDK ``` Provider SDK 只能出现在: ```text packages/model/providers/* ``` 或者明确的 Provider Plugin Adapter 中。 --- # 167. Final Dependency Direction 必须保持: ```text Agent ↓ Skill ↓ Capability ↓ Action ↓ Model Runtime ↓ Provider Adapter ↓ External Provider ``` 而不是: ```text 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 最终模型 ```text ┌──────────────────────┐ │ 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 不应该成为: ```text 一个 Agent + 一个 OpenAI SDK ``` 而应该成为: ```text 一个统一的 AI Execution Platform ``` 其中: ```text 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 最终形成: ```text 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 是可替换实现,不是业务依赖。**