Files
devos/Docs/DevOS-Platform-v2/31_NOTIFICATION_COMMUNICATION_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

51 KiB
Raw Blame History

DevOS Notification / Communication Runtime

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


1. 文档目标

DevOS 必须提供统一的:

Notification / Communication Runtime

用于处理:

  • Notification
  • Message
  • Communication
  • Delivery
  • Channel
  • Provider
  • Template
  • Subscription
  • Preference
  • Recipient
  • Audience
  • Routing
  • Delivery Policy
  • Retry
  • Rate Limit
  • Deduplication
  • Scheduling
  • Batch Sending
  • Webhook
  • Email
  • Push
  • SMS
  • In-App Notification
  • Provider Failover
  • Delivery Tracking
  • Bounce / Complaint
  • Unsubscribe
  • Digest
  • Notification Center
  • Agent Notification
  • Task Notification
  • Workflow Notification
  • System Alert

核心目标:

业务系统只产生“应该通知什么”,Communication Runtime 决定“发给谁、通过什么渠道、什么时候发、如何发送、失败后怎么办”。


2. 核心原则

必须严格区分:

Event
Notification
Message
Delivery
Provider
Channel

它们不是同一个东西。


3. Event

Event 表示:

系统发生了什么。

例如:

task.completed
plugin.installed
agent.failed
server.offline
article.published

Event 不负责发送。


4. Notification

Notification 表示:

某个事件/条件是否需要通知某个受众。

例如:

Task 完成
→ 通知项目负责人

Notification 是语义层。


5. Message

Message 表示:

实际准备发送的内容。

例如:

Title:
任务已完成

Body:
SEO 批量生成任务已完成,共生成 100 篇。

6. Delivery

Delivery 表示:

一条 Message 通过某个 Channel 向某个 Recipient 进行的一次发送尝试。

例如:

Message
 ↓
Email
 ↓
user@example.com

这是一次 Delivery。


7. Provider

Provider 是实际的外部发送实现。

例如:

SMTP
SendGrid
Resend
AWS SES
Twilio
FCM
APNs
Discord
Slack
Generic Webhook

Provider 是实现。


8. Channel

Channel 表示通信方式:

in_app
email
webhook
push
sms
chat

Channel 不等于 Provider。

例如:

email
 ├── SMTP
 ├── SES
 ├── Resend
 └── SendGrid

9. 总体架构

                         Event
                           │
                           ↓
                  Notification Rules
                           │
                           ↓
                    Notification
                           │
                  ┌────────┴────────┐
                  ↓                 ↓
             Recipient          Template
                  │                 │
                  └────────┬────────┘
                           ↓
                       Message
                           │
                           ↓
                   Delivery Planner
                           │
              ┌────────────┼────────────┐
              ↓            ↓            ↓
            In-App       Email        Webhook
              ↓            ↓            ↓
           Provider     Provider     Provider
              │            │            │
              └────────────┼────────────┘
                           ↓
                       Delivery
                           │
                  ┌────────┴────────┐
                  ↓                 ↓
                Event          Observability

10. Runtime 边界

Communication Runtime 负责:

Recipient Resolution
Template Rendering
Channel Selection
Provider Selection
Delivery
Retry
Scheduling
Deduplication
Rate Limit
Status Tracking

不负责:

Business Logic
Agent Planning
Task Execution
Authorization
Secret Storage
Event Bus

这些由其他 Runtime 提供。


11. 与 Event Runtime 的关系

Event Runtime:

Action
 ↓
Execution
 ↓
Event

Communication Runtime:

Event
 ↓
Notification Rule
 ↓
Message
 ↓
Delivery

因此:

Event ≠ Notification

一个 Event 可以:

不通知

也可以:

通知一个人
通知 1000 人
发送 Email
发送 Push
发送 Webhook
生成 Digest

12. 与 Task Runtime 的关系

发送大量消息:

Notification
 ↓
Task
 ↓
Jobs
 ↓
Queue
 ↓
Worker
 ↓
Delivery

Communication Runtime 不创建自己的 Queue。


13. 与 Security Runtime 的关系

Communication Runtime 必须使用:

Security Context
Authorization
Scope
Policy

但是不实现自己的 Authorization。

例如:

Agent
 ↓
Notification
 ↓
Recipient

Agent 不能因为拥有 Notification Capability 就读取所有用户邮箱。


14. Recipient

Recipient 是通知目标。

类型:

type RecipientType =
  | 'user'
  | 'organization'
  | 'project'
  | 'team'
  | 'role'
  | 'email'
  | 'phone'
  | 'webhook'
  | 'external';

15. Recipient Resolution

通知可以声明:

project.owner
project.members
organization.admins
task.requester
agent.owner

Runtime 负责解析:

Recipient Selector
 ↓
Security Scope
 ↓
Recipient Resolver
 ↓
Concrete Recipients

16. Recipient Selector

推荐:

interface RecipientSelector {
  type:
    | 'user'
    | 'role'
    | 'team'
    | 'project'
    | 'organization'
    | 'expression';

  id?: string;

  role?: string;

  filters?: Record<string, unknown>;
}

不允许业务代码自己查询用户表发送消息。


17. Recipient Address

最终 Delivery 需要:

interface RecipientAddress {
  type: 'email' | 'phone' | 'push' | 'webhook' | 'in_app';

  valueRef: string;

  verified?: boolean;

  metadata?: Record<string, unknown>;
}

敏感地址必须遵循 Credential / Identity / Security Policy。


18. 不直接暴露 Recipient 敏感信息

UI、Agent、Plugin 不应该任意读取:

所有用户 Email
所有电话号码
所有 Webhook URL

而应该请求:

Notification Capability

得到允许使用的 Recipient。


19. Audience

Audience 表示通知受众。

例如:

Task Owner
Project Admin
SEO Team
Organization Admin

Audience 可以是动态计算的。


20. Audience 与 Recipient

Audience
 ↓
Recipient Resolver
 ↓
Recipients

例如:

"项目管理员"

最终解析为:

User A
User B
User C

21. Notification

统一定义:

interface Notification {
  id: string;

  type: string;

  sourceEventId?: string;

  organizationId?: string;

  projectId?: string;

  environmentId?: string;

  recipients: RecipientSelector[];

  channels?: NotificationChannel[];

  templateId?: string;

  data: Record<string, unknown>;

  priority?: 'low' | 'normal' | 'high' | 'critical';

  scheduledAt?: Date;

  expiresAt?: Date;
}

22. Notification Type

使用稳定的语义 ID。

例如:

task.completed
task.failed
agent.completed
agent.failed
plugin.updated
security.alert
deployment.failed
server.offline

插件可以注册:

seo.article.published
seo.scan.completed

23. Notification Type Registry

DevOS 维护统一 Registry。

定义:

interface NotificationTypeDefinition {
  id: string;

  description: string;

  defaultChannels: NotificationChannel[];

  defaultPriority: NotificationPriority;

  templateSchema?: unknown;

  sensitive?: boolean;
}

24. Notification 不直接发送

禁止:

sendEmail(...)

出现在业务 Service 中。

必须:

Business Event
 ↓
Notification Runtime
 ↓
Communication Runtime

25. Message

Message 是渲染后的通信内容。

interface Message {
  id: string;

  notificationId: string;

  channel: NotificationChannel;

  subject?: string;

  body: string;

  format?: 'text' | 'html' | 'markdown' | 'json';

  metadata?: Record<string, unknown>;
}

26. Template Runtime

模板必须独立。

支持:

Email Template
In-App Template
Webhook Template
Push Template
SMS Template

27. Template Version

模板必须版本化:

task.completed@1
task.completed@2

Delivery 必须记录:

templateId
templateVersion

这样历史消息可以追溯。


28. Template Rendering

流程:

Template
 ↓
Variables
 ↓
Validation
 ↓
Render
 ↓
Message

禁止模板执行任意代码。


29. Template Variables

例如:

{{task.name}}
{{task.status}}
{{project.name}}
{{execution.id}}

变量来源必须来自:

Notification Context

不能直接执行任意 JavaScript。


30. Template Security

禁止:

eval()
new Function()
arbitrary template code

模板只能使用:

approved variables
approved helpers

31. HTML Email

HTML 邮件必须经过:

Template
 ↓
Render
 ↓
Sanitize
 ↓
Message

防止:

XSS
unsafe HTML
external injection

32. Markdown

Markdown 只允许在明确支持 Markdown 的 Channel。

例如:

in_app
chat

Email 是否转换 HTML 由 Template/Channel Policy 决定。


33. Channel Registry

统一注册:

in_app
email
webhook
push
sms
chat

插件可以贡献新的 Channel Adapter。


34. In-App Notification

In-App 不需要外部 Provider。

流程:

Notification
 ↓
Message
 ↓
In-App Delivery
 ↓
Notification Store
 ↓
Realtime
 ↓
UI

35. Notification Center

UI:

Notifications
├── All
├── Unread
├── Important
├── System
├── Tasks
├── Agents
└── Security

36. Read State

每个用户需要:

readAt
seenAt
archivedAt

Notification 内容本身可以共享。

Delivery/User State 单独存储。


37. Realtime

新通知:

Notification
 ↓
Event Runtime
 ↓
Realtime Runtime
 ↓
SSE / WebSocket
 ↓
UI

不要创建第二套 WebSocket Runtime。


38. Email Channel

Email Channel 负责:

Message
 ↓
Email Provider

Provider 可以:

SMTP
SES
Resend
SendGrid

39. Email Provider

Provider Adapter:

interface EmailProvider {
  send(
    message: EmailMessage,
    context: DeliveryContext,
  ): Promise<ProviderDeliveryResult>;
}

40. SMTP

SMTP Provider 可以使用:

host
port
username
credential

Credential 通过:

Credential Runtime

管理。


41. Email 不直接读取 Secret

禁止:

process.env.SMTP_PASSWORD

业务代码直接使用。

必须:

Communication Runtime
 ↓
Provider Resolver
 ↓
Credential Runtime
 ↓
Secret Runtime

42. Webhook Channel

Webhook 是:

Notification
 ↓
JSON Message
 ↓
Webhook Delivery

43. Webhook Security

必须支持:

HMAC Signature
Timestamp
Nonce
Replay Protection
Timeout
Retry

44. SSRF Protection

Webhook URL 必须经过:

Network Policy

禁止访问:

127.0.0.1
localhost
169.254.169.254
internal network
private CIDR

除非明确允许。


45. Webhook Payload

统一:

{
  "id": "delivery-id",
  "type": "task.completed",
  "timestamp": "2026-09-12T00:00:00Z",
  "data": {}
}

46. Webhook Version

Webhook Schema 必须版本化:

v1
v2

Event Type:

task.completed

Schema:

eventVersion: 1

47. Push

Push Channel 可以支持:

FCM
APNs
Web Push

Provider Adapter 统一:

Push Runtime
 ↓
Provider

48. SMS

SMS 也作为 Channel:

sms

Provider:

Twilio
Vonage
Custom

SMS 必须受到:

cost
rate limit
country policy
user preference

约束。


49. Chat Channel

未来支持:

Slack
Discord
Teams
Telegram

但都统一为:

chat

然后 Provider Adapter。


50. Channel Policy

用户可能:

Email = enabled
Push = enabled
SMS = disabled

项目可能:

SMS = forbidden

Organization 可能:

External Webhook = disabled

最终:

Global Policy
 ↓
Organization Policy
 ↓
Project Policy
 ↓
User Preference
 ↓
Notification Policy

51. Notification Preference

用户可以设置:

Task Completed
  In-App ✓
  Email ✓
  Push ✓

Task Failed
  In-App ✓
  Email ✓
  Push ✓

Marketing
  Email ✗

52. Preference 不等于 Security

Preference:

用户想不想收到?

Security:

系统允不允许发送?

所以:

Security Policy
 ↓
Preference
 ↓
Delivery Policy

53. Critical Notification

某些通知:

security.alert
production.down
critical.failure

可能:

不能被普通偏好完全关闭

但必须明确由:

Notification Policy

决定。


54. Notification Routing

例如:

task.failed

Routing:

In-App
Email

而:

task.completed

可能只有:

In-App

55. Routing Policy

interface NotificationPolicy {
  notificationType: string;

  channels: NotificationChannel[];

  priority?: NotificationPriority;

  quietHours?: boolean;

  dedupeWindowSeconds?: number;

  digest?: boolean;
}

56. Quiet Hours

支持:

22:00 - 08:00

普通通知:

delay

Critical:

send immediately

由 Policy 决定。


57. Digest

大量通知可以合并:

100 Task Completed

变成:

今日任务摘要
完成 100 个任务
失败 3 个任务

58. Digest Runtime

流程:

Notifications
 ↓
Group
 ↓
Aggregate
 ↓
Digest Template
 ↓
Message
 ↓
Delivery

Digest 不需要第二套 Queue。


59. Deduplication

例如:

server.offline

短时间内连续产生:

100 Events

不能发送:

100 Email

支持:

dedupeKey
dedupeWindow

60. Dedup Key

例如:

server.offline:{serverId}

或者:

task.failed:{taskId}

61. Delivery

interface Delivery {
  id: string;

  notificationId: string;

  messageId: string;

  channel: NotificationChannel;

  providerId?: string;

  recipientId?: string;

  status:
    | 'pending'
    | 'scheduled'
    | 'sending'
    | 'sent'
    | 'delivered'
    | 'failed'
    | 'retrying'
    | 'cancelled';

  attempts: number;

  scheduledAt?: Date;

  sentAt?: Date;

  deliveredAt?: Date;

  failedAt?: Date;

  providerMessageId?: string;
}

62. Delivery Attempt

一次 Delivery 可以:

Attempt 1
 ↓ fail

Attempt 2
 ↓ fail

Attempt 3
 ↓ success

必须记录每次 Attempt。


63. Delivery Attempt Schema

interface DeliveryAttempt {
  id: string;

  deliveryId: string;

  attempt: number;

  providerId: string;

  startedAt: Date;

  completedAt?: Date;

  status: 'success' | 'failed';

  providerStatus?: string;

  providerRequestId?: string;

  errorCode?: string;

  latencyMs?: number;
}

64. Retry

支持:

fixed
linear
exponential
jitter

例如:

1 min
5 min
15 min
1 hour

65. Retryable Error

通常:

timeout
429
5xx
temporary network error
provider unavailable

可以 Retry。

通常不能:

invalid recipient
invalid credentials
invalid template
permission denied
unsubscribed

66. Dead Letter Queue

多次失败:

Delivery
 ↓
Retry
 ↓
Retry
 ↓
DLQ

DLQ 使用:

Task / Job Runtime

已有 Queue Runtime。


67. Manual Replay

管理员可以:

Replay Delivery

但必须:

permission
audit
idempotency

68. Idempotency

发送通信也必须考虑:

network timeout
provider accepted
response lost

因此:

Idempotency-Key

非常重要。


69. Provider Message ID

Provider 返回:

providerMessageId

必须保存。

用于:

delivery tracking
provider webhook
debugging
dedupe

70. Delivery Status

标准状态:

pending
scheduled
sending
sent
delivered
failed
retrying
cancelled

Email 可能额外:

bounced
complained

71. Bounce

Email Provider 可能通知:

bounce

Event:

communication.email.bounced

进入:

Event Runtime

72. Complaint

同样:

communication.email.complained

可更新:

Recipient Preference

防止继续发送。


73. Unsubscribe

必须支持:

global unsubscribe
channel unsubscribe
notification-type unsubscribe

但系统安全通知可以由 Policy 决定是否可关闭。


74. Consent

营销/商业通信如果涉及用户同意:

Consent

应该独立建模。

不要简单用:

notification_preferences

替代所有法律/合规语义。


75. Consent Runtime

如果产品需要:

consent
withdrawal
proof
timestamp
source
policyVersion

建议独立:

Consent Runtime

Communication Runtime 消费 Consent 状态。


76. Communication Provider

统一 Provider:

interface CommunicationProvider {
  id: string;

  channel: NotificationChannel;

  capabilities: string[];

  send(
    message: Message,
    context: DeliveryContext,
  ): Promise<ProviderDeliveryResult>;
}

77. Provider Health

Provider 必须支持:

healthy
degraded
down
disabled

Communication Router 根据健康状态选择。


78. Provider Failover

例如:

Email
 ↓
Provider A
 ↓ timeout
Provider B

但要特别注意:

Provider A 可能已经接受消息但响应丢失。

因此 Failover 必须依赖:

idempotency
provider semantics
delivery state

不能简单地认为 timeout = 未发送。


79. Communication Router

流程:

Delivery
 ↓
Allowed Channels
 ↓
Provider Candidates
 ↓
Credential Check
 ↓
Health
 ↓
Rate Limit
 ↓
Cost
 ↓
Policy
 ↓
Selected Provider

80. Cost Routing

SMS/Email/Push 可能有不同成本。

Router 可以考虑:

cost
latency
reliability
region

但:

security
consent
policy

仍然是 Hard Filter。


81. Region

Provider 可以声明:

region
dataResidency
supportedCountries

Policy 可以要求:

Japan
EU
US

Router 过滤不符合要求的 Provider。


82. Communication Rate Limit

支持:

global
organization
project
user
recipient
provider
channel
notificationType

例如:

每用户每小时最多 10 条 SMS。

83. Anti-Spam

批量 Agent 自动化特别容易产生:

10000 Email

因此必须支持:

quota
rate limit
daily limit
per-recipient limit
per-notification-type limit

84. Batch Sending

批量发送:

Notification
 ↓
Task
 ↓
Jobs
 ↓
Queue
 ↓
Workers

每个 Job 可以处理:

100 recipients

具体 batch size 由 Provider Capability 决定。


85. Parallel Sending

可以并发:

Worker 1
Worker 2
Worker 3

但必须遵守:

provider concurrency
channel rate limit
organization quota

86. Scheduling

Notification 可以:

send now
send at time
delay
digest

例如:

Task 完成
 ↓
Delay 5 min
 ↓
Email

Schedule 交给:

Scheduler Runtime

87. Event Trigger

Event 可以触发:

Notification Rule

例如:

deployment.failed

触发:

security/admin notification

88. Workflow Trigger

Workflow 可以执行:

notification.send

例如:

Webhook
 ↓
Process
 ↓
Approval
 ↓
Notification

但发送仍然走:

Communication Runtime

89. Agent Notification

Agent 可以请求:

notify user

但 Agent 只能提出:

Notification Request

最终:

Security
 ↓
Preference
 ↓
Policy
 ↓
Communication Runtime

90. Agent 不直接 Email

禁止:

Agent
 ↓
SMTP

禁止:

Agent
 ↓
SendGrid API

必须:

Agent
 ↓
Capability
 ↓
Action
 ↓
Communication Runtime

91. Plugin Notification

Plugin 可以注册:

notification types
templates
channels
providers

但不能建立:

Plugin-owned Notification Runtime

92. MCP Notification

MCP 可以暴露:

notification.send

但:

MCP
 ↓
Action Runtime
 ↓
Communication Runtime

不能绕过权限。


93. API

推荐:

POST /v1/actions/notification.send

GET /v1/notifications
GET /v1/notifications/:id

POST /v1/notifications/:id/read
POST /v1/notifications/:id/archive

GET /v1/notification-preferences
PUT /v1/notification-preferences

GET /v1/deliveries
GET /v1/deliveries/:id

94. SDK

sdk.notifications.list();

sdk.notifications.markRead();

sdk.notifications.send();

sdk.notifications.preferences.get();

sdk.notifications.preferences.update();

SDK 不负责发送 Provider API。


95. CLI

建议:

devos notification list
devos notification inspect <id>

devos notification send-test

devos notification preferences

devos delivery list
devos delivery inspect <id>
devos delivery retry <id>

devos communication provider list
devos communication provider health

devos communication doctor

96. Notification UI

建议:

System
 └── Notifications
      ├── Notification Center
      ├── Preferences
      ├── Templates
      ├── Channels
      ├── Providers
      ├── Deliveries
      └── Failed / DLQ

97. Delivery Inspector

显示:

Delivery ID
Notification ID
Recipient
Channel
Provider
Status
Attempts
Created
Scheduled
Sent
Delivered
Error
Provider Message ID

98. 不默认显示敏感信息

例如:

Webhook URL
Email Address
Phone
Provider Credential

需要根据权限脱敏。


99. Template UI

管理员可以:

Create
Edit
Preview
Validate
Publish
Deprecate

Template 发布后版本固定。


100. Template Preview

支持:

Preview Email
Preview Push
Preview In-App
Preview Webhook JSON

使用:

sample context

不能真实发送。


101. Test Delivery

提供:

Send Test

必须明确:

permission
audit
rate limit

防止管理员误发送大量消息。


102. Notification Search

Global Search 可以搜索:

notification
delivery
template
provider

但必须应用:

Security Scope

103. Notification Data Model

建议:

notifications
notification_recipients
notification_messages
notification_templates
notification_template_versions
notification_preferences
notification_policies

deliveries
delivery_attempts

communication_providers
communication_provider_credentials
communication_provider_health

notification_digests
notification_subscriptions

104. In-App 数据

可以额外:

notification_user_state

保存:

readAt
seenAt
archivedAt

避免修改共享 Notification。


105. Provider Credentials

数据库只保存:

credentialId

而不是:

smtpPassword
apiKey
webhookSecret

实际 Secret:

Secret Runtime

106. Outbox

Event → Notification 的可靠性建议使用:

Transactional Outbox

例如:

Business Transaction
 ├── Resource Update
 └── Outbox Event
          ↓
      Event Runtime
          ↓
   Notification Runtime

避免:

DB 成功
Email 逻辑失败

导致状态不一致。


107. Notification Event

推荐:

notification.created
notification.scheduled
notification.sent
notification.failed
notification.cancelled
notification.deduplicated

108. Delivery Event

推荐:

delivery.created
delivery.started
delivery.sent
delivery.delivered
delivery.failed
delivery.retrying
delivery.cancelled
delivery.bounced
delivery.complained

109. Event Runtime Integration

这些 Event 全部进入:

Event Runtime

不能:

Notification Event Bus

另起一套。


110. Observability

所有 Delivery 必须有:

requestId
correlationId
notificationId
deliveryId
attemptId
providerId

111. Metrics

至少:

notifications_created_total
deliveries_total
deliveries_success_total
deliveries_failed_total
deliveries_retry_total
delivery_latency_ms
provider_failures_total
provider_rate_limit_total
email_bounce_total
email_complaint_total
notification_deduplicated_total

112. Cost

Communication Cost 可以计入:

organization
project
agent
task
job
notification
delivery
provider
channel

例如:

SMS:
$0.01 × 1000

最终可以归因到:

Agent Task

113. Usage

统一 Usage:

emails sent
SMS sent
push sent
webhooks sent
in-app notifications

并可以和:

Model Usage
Storage Usage
Network Usage

统一进入:

Usage Runtime

114. Budget

通信也应该支持:

daily budget
monthly budget
per-task budget
per-project budget

例如:

Agent Task:
Max communication cost = $2

达到预算:

COMMUNICATION_BUDGET_EXCEEDED

115. Priority

支持:

low
normal
high
critical

Queue 优先级由 Task/Job Runtime 处理。


116. Cancellation

尚未发送:

pending
scheduled

可以取消。

已经发送:

sent

不能假装取消。

因此:

cancel()

只影响尚未执行的 Delivery。


117. Expiration

Notification 可以设置:

expiresAt

例如:

Task Approval

过期后:

不要继续发送

118. Approval Notification

Approval Runtime 可以产生:

approval.requested
approval.approved
approval.rejected
approval.expired

Communication Runtime 负责通知。

但:

Communication Runtime

不负责 Approval Decision。


119. Security Alert

Security Runtime 可以产生:

security.alert

Communication Runtime 负责:

In-App
Email
Push

Security Runtime 不直接操作 SMTP。


120. Task Notification

Task Runtime 可以产生:

task.started
task.completed
task.failed
task.cancelled

Communication Runtime 负责通知。


121. Agent Notification

Agent Runtime 可以产生:

agent.started
agent.waiting
agent.completed
agent.failed
agent.approval_required

Communication Runtime 负责发送。


122. Workflow Notification

Workflow 可以声明:

notify:
  type: workflow.failed
  recipients:
    - project.owner

Workflow Engine 不直接发送。


123. Communication Context

模板渲染使用:

interface CommunicationContext {
  notification: Notification;

  event?: EventReference;

  actor?: ActorReference;

  organization?: ResourceReference;

  project?: ResourceReference;

  task?: ResourceReference;

  job?: ResourceReference;

  execution?: ResourceReference;

  data: Record<string, unknown>;
}

124. Context Security

Communication Context 必须经过:

Authorization
Scope
Field Permission
Redaction

防止模板意外输出敏感字段。


125. Template Field Permission

例如模板想使用:

{{user.email}}

必须判断:

communication context
+
recipient visibility

不能因为模板管理员可以编辑模板,就自动获得所有用户字段。


126. External Recipient

如果 Recipient 是:

external email

必须确认:

data policy
external sharing policy

否则可能产生数据泄露。


127. External Webhook

Webhook 更加敏感。

需要:

allowed domains
network policy
payload policy
signature

128. Webhook Secret

Webhook Secret:

Secret Runtime

签名:

HMAC

Secret 不能进入:

logs
events
audit
delivery payload

129. Email Security

支持:

SPF
DKIM
DMARC

但这些属于:

Provider / Domain Configuration

不是 Notification Runtime 自己实现邮件服务器。


130. Email Tracking

如果业务需要:

open
click
bounce
complaint

可以接入 Provider Webhook。

但需要注意:

privacy
consent
regional policy

131. Provider Webhook

Provider 状态回调:

Provider
 ↓
Webhook Endpoint
 ↓
Authentication
 ↓
Event Runtime
 ↓
Delivery Update

不能直接修改业务表。


132. Provider Webhook Idempotency

Provider 可能重复发送:

delivered
delivered
delivered

必须:

eventId / providerEventId

去重。


133. Communication Provider Plugin

未来可以安装:

@devos/provider-resend
@devos/provider-twilio
@devos/provider-slack

但它们只能提供:

Provider Adapter

不能拥有:

Notification Runtime
Queue
Audit
Permission
Secret Runtime

134. Plugin Notification Extension

插件可以贡献:

Notification Type
Template
Recipient Resolver
Channel
Provider

例如 SEO Plugin:

seo.scan.completed
seo.keyword.alert
seo.article.published

135. Plugin UI

插件可以贡献:

Notification Settings
Template Settings
Provider Settings
Dashboard Widget

但使用:

DevOS UI Shell

不能创建第二套 Notification Center。


136. MCP

MCP 可以暴露:

notification.send
notification.list
notification.mark_read

但全部进入:

Security
 ↓
Action Runtime
 ↓
Communication Runtime

137. Agent Capability

Agent 可看到:

notification.send

但 Capability Discovery 必须根据:

permission
scope
channel
recipient
policy

过滤。


138. Agent Notification Example

Agent:

任务已经完成。

请求:

{
  "type": "task.completed",
  "recipient": "task.requester",
  "channels": ["in_app", "email"]
}

Runtime:

Security
 ↓
Resolve Recipient
 ↓
Check Preference
 ↓
Check Policy
 ↓
Render Template
 ↓
Create Delivery
 ↓
Queue
 ↓
Provider

139. Batch Agent Example

例如:

生成 100 篇文章

完成后不要:

Agent → 100 Email

而:

Task
 ↓
Event
 ↓
Notification
 ↓
Digest
 ↓
Email

可以最终只发:

任务完成:
100 篇文章
97 成功
3 失败

140. Communication Runtime 不做业务摘要

“100 篇文章,97 成功,3 失败”应该由:

Task / Agent / Workflow

提供结构化数据。

Communication Runtime 只负责:

Render
Deliver
Track

141. Digest 可以聚合,但不理解业务

Digest Runtime 可以:

count
group
sum

例如:

100 task.completed

但不应该理解:

SEO
CRM
DevOps

142. Message Localization

支持:

en-US
zh-CN
ja-JP

模板:

task.completed.en
task.completed.zh
task.completed.ja

143. Locale Resolution

优先级:

Recipient Preference
 ↓
Project
 ↓
Organization
 ↓
System Default

144. Timezone

Notification Scheduler 必须考虑:

recipient timezone
project timezone
organization timezone

例如:

每日 09:00

不是服务器 UTC 09:00。


145. Internationalization

Notification Type 不应该直接存:

任务完成

而存:

task.completed

模板负责本地化。


146. Accessibility

In-App Notification 必须支持:

ARIA
keyboard navigation
screen reader
contrast
notification grouping

147. Notification Center Performance

不要一次加载:

100000 notifications

必须:

cursor pagination

推荐:

createdAt + id

作为稳定排序。


148. Notification Read Optimization

未读数:

unread_count

可以使用缓存/计数,但 PostgreSQL 作为最终一致性 Source of Truth。


149. Redis

Redis 可以用于:

unread count cache
rate limit
dedupe lock
delivery concurrency
provider health cache

不能成为:

notification source of truth

150. Storage

如果消息包含附件:

Message
 ↓
Attachment
 ↓
Storage Runtime

Communication Runtime 不自己管理 Blob。


151. Large Attachments

Email 附件不应该直接把:

100MB

塞进数据库。

使用:

Storage Reference

Provider 根据能力:

signed URL
stream
attachment

发送。


152. Artifact

Task 生成:

report.pdf

应该:

Artifact
 ↓
Storage

Notification 只引用:

artifactId

153. Communication 与 Artifact

正确:

Artifact
 ↓
Message Attachment Reference
 ↓
Provider

错误:

Notification DB
 ↓
复制整个 PDF Blob

154. Data Retention

不同数据可以有不同 retention:

Notification
Delivery
Delivery Attempt
Provider Response
Message Content
Audit

155. Message Content Retention

敏感通信内容不能无限保存。

支持:

retention policy
redaction
deletion
archive

156. Audit Retention

Audit 按:

Audit Runtime

的规则保存。

Communication Runtime 不自己定义完整 Audit System。


157. Privacy

Communication Runtime 必须支持:

data minimization
purpose limitation
retention
redaction
access control
export
deletion

158. User Data Export

如果平台需要用户数据导出:

Notification
Delivery
Preferences

可以通过:

Export Runtime

统一导出。


159. Deletion

删除用户时:

Identity
 ↓
Data Lifecycle
 ↓
Notification References

按照平台 Data Retention Policy 处理。


160. Tenant Isolation

必须保证:

Organization A

无法读取:

Organization B

的:

Notification
Delivery
Template
Provider
Recipient

161. Project Isolation

同一个 Organization 内:

Project A

默认不能读取:

Project B

的项目级 Notification。


162. Environment Isolation

例如:

production

不能错误发送:

staging recipient

必须通过:

Environment Scope

隔离。


163. Production Guard

Production 可以要求:

approved provider
verified sender
verified domain

防止测试配置向真实用户发消息。


164. Development Safety

Development 环境建议:

Email → Mailpit
SMS → Mock
Push → Mock
Webhook → Local Receiver

防止开发环境误发真实消息。


165. Test Provider

必须提供:

MockCommunicationProvider

支持:

success
failure
timeout
rate limit
bounce
duplicate
provider accepted but response lost

166. Contract Tests

必须测试:

Provider Adapter
Notification Routing
Template Rendering
Recipient Resolution
Preference
Deduplication
Retry
Rate Limit
Scheduling
Delivery
Webhook

167. Security Tests

必须测试:

Tenant isolation
Recipient authorization
Template injection
SSRF
Webhook signature
Secret leakage
External sharing
Unsubscribe
Agent authorization
Plugin authorization
MCP authorization

168. Delivery Tests

必须覆盖:

success
failure
retry
DLQ
manual replay
timeout
provider failover
idempotency
duplicate provider webhook

169. Notification Tests

必须覆盖:

event → notification
notification → recipients
preferences
quiet hours
critical notifications
digest
dedupe
expiration
localization

170. Performance Tests

测试:

10k notifications
100k deliveries
large recipient list
high concurrency
provider rate limit
large digest

重点不是单纯吞吐,而是:

不会重复发送
不会跨租户
不会突破 Provider Rate Limit
不会突破预算

171. Failure Recovery

Worker Crash:

Delivery
 ↓
Lease
 ↓
Worker crash
 ↓
Lease expire
 ↓
Retry

继续使用:

Task/Job/Queue/Worker Runtime

172. Provider Down

Provider A
 ↓
down

Router:

Provider B

如果没有备用:

Delivery → retry

最终:

DLQ

173. Network Timeout

如果:

request timeout

不能直接假设:

provider did not receive

必须使用:

idempotency
provider status
providerMessageId

尽可能判断。


174. Communication State Machine

pending
   ↓
scheduled
   ↓
sending
   ├──→ sent
   │      ↓
   │   delivered
   │
   └──→ retrying
           ↓
        sending
           ↓
         failed
           ↓
          DLQ

175. Notification State

Notification:

created
scheduled
processing
partially_sent
completed
failed
cancelled
expired

176. Partial Completion

例如:

100 recipients
97 delivered
3 failed

Notification:

partially_completed

而不是:

failed

177. Aggregated Delivery Status

可以计算:

total
pending
sending
sent
delivered
failed

用于:

Notification Detail

178. Communication Doctor

CLI:

devos communication doctor

检查:

Provider
Credential
DNS
SMTP
Webhook
Rate Limit
Templates
Scheduler
Queue
Worker
Event
Realtime

179. Provider Test

devos communication provider test <id>

应该执行:

credential check
connectivity
test message
provider response

测试消息必须明确标记:

TEST

180. Architecture Package

推荐:

packages/
├── notification/
│   ├── domain/
│   ├── runtime/
│   ├── policy/
│   ├── template/
│   ├── recipient/
│   ├── routing/
│   ├── preference/
│   ├── digest/
│   └── testing/
│
├── communication/
│   ├── runtime/
│   ├── provider/
│   ├── delivery/
│   ├── email/
│   ├── webhook/
│   ├── push/
│   ├── sms/
│   └── chat/

如果项目当前规模较小:

packages/notification/

内部模块化即可。


181. Provider Package

未来:

packages/communication/providers/
├── mock/
├── smtp/
├── ses/
├── resend/
├── twilio/
├── fcm/
├── apns/
├── slack/
└── generic-webhook/

不要求一次全部实现。


182. Recommended Initial Providers

第一阶段只需要:

Mock
In-App
SMTP
Generic Webhook

之后再增加:

Push
SMS
Chat

183. 为什么不一开始实现所有 Channel

因为 DevOS 的目标是:

建立统一 Runtime,而不是第一天实现几十个 Provider。

先保证:

Notification
 ↓
Delivery
 ↓
Provider

架构稳定,再增加 Provider。


184. 与 API / Integration Runtime 的关系

26 号文档定义:

Integration / Provider Runtime

Communication Runtime 应复用:

Credential
Network
Provider
Webhook
Rate Limit

不要重新实现。


185. 与 Event Runtime 的关系

16 号:

Event Runtime

负责:

Event
Event Store
Event Bus
Replay
Subscription
Webhook
Realtime

31 号:

Notification Runtime

消费 Event。


186. 与 Observability Runtime 的关系

17 号:

Observability

负责:

Log
Metric
Trace
Audit
Alert

31 号只产生 telemetry。


187. 与 Configuration Runtime 的关系

18 号:

Configuration Runtime

负责:

SMTP host
Provider configuration
Channel configuration

Secret:

Secret Runtime

188. 与 Storage Runtime 的关系

15 号:

Storage Runtime

负责:

attachments
artifacts
large files

Communication Runtime 只引用。


189. 与 Model Runtime 的关系

30 号:

Model Runtime

可以用于:

AI-generated notification
translation
summarization
classification

例如:

Notification Data
 ↓
Model Runtime
 ↓
Localized Summary
 ↓
Communication Runtime

但这不是 Communication Runtime 自己调用 Provider。


190. AI Notification

如果需要:

“帮我把这 20 个任务失败信息总结成一封邮件”

正确:

Agent
 ↓
Model Runtime
 ↓
Structured Result
 ↓
Notification
 ↓
Communication Runtime

191. Model Failure

如果 AI Summary 失败:

Communication Runtime

应该可以使用:

fallback template

而不是让整个通知系统失败。


192. Agent + Communication

最终:

Agent
 ↓
Goal
 ↓
Task
 ↓
Action
 ↓
Event
 ↓
Notification
 ↓
Communication

这样 Agent 不需要理解:

SMTP
FCM
Twilio

193. Project Factory

Project Manifest 可以声明:

capabilities:
  - notification
  - email
  - webhook

Factory 根据 Capability 安装:

Notification Runtime
Provider Modules
UI
API

194. Plugin Manifest

插件可以声明:

notifications:
  - type: seo.scan.completed
  - type: seo.article.published

templates:
  - seo.scan.completed

195. Plugin Permission

例如:

permissions:
  - notification.create
  - notification.read

如果插件需要:

external email

还应该明确:

communication.email.send

196. Agent Capability

Agent 默认只获得:

notification.send

如果需要外部渠道:

notification.send.email
notification.send.webhook

需要额外授权。


197. MCP Capability

MCP Capability:

notification.send

实际:

MCP
 ↓
Security Context
 ↓
Action Runtime
 ↓
Notification Runtime

198. No Second Communication Runtime

绝对禁止:

Plugin EmailService
Agent EmailService
Workflow EmailService
SEO EmailService

最终全部应该使用:

Communication Runtime

199. Architecture Contract

任何发送行为必须满足:

Security
 ↓
Authorization
 ↓
Scope
 ↓
Notification
 ↓
Delivery
 ↓
Communication Provider

200. Zcode Forbidden Patterns

禁止:

await transporter.sendMail(...)

出现在:

business service
agent
plugin
workflow
controller
mcp

禁止:

fetch(webhookUrl)

直接出现在业务逻辑。

禁止:

twilio.messages.create(...)

直接出现在 Agent/Plugin。


201. Zcode Correct Pattern

await actionRuntime.execute(
  'notification.send',
  {
    type: 'task.completed',
    recipients: [
      {
        type: 'user',
        id: userId,
      },
    ],
    data: {
      taskId,
    },
  },
  context,
);

之后:

Action Runtime
 ↓
Notification Runtime
 ↓
Communication Runtime
 ↓
Provider

202. Implementation Phase 1

实现:

Notification Domain
Notification Type Registry
Recipient
Message
Delivery

先使用:

Mock Provider

203. Implementation Phase 2

实现:

Template Runtime
Preference
Routing
Deduplication
Retry

204. Implementation Phase 3

实现:

In-App
Realtime
Notification Center

205. Implementation Phase 4

实现:

SMTP
Generic Webhook

206. Implementation Phase 5

实现:

Provider Health
Failover
Rate Limit
Budget
Cost
Usage

207. Implementation Phase 6

实现:

Push
SMS
Chat

按真实业务需要逐步添加。


208. Implementation Phase 7

实现:

Digest
Quiet Hours
Scheduling
Localization
Advanced Preferences

209. Implementation Phase 8

接入:

Agent
Workflow
Plugin
MCP
Task
Event

210. Definition of Done

Notification / Communication Runtime 完成必须至少满足:

[ ] Notification Domain
[ ] Message
[ ] Recipient
[ ] Audience
[ ] Template
[ ] Template Version
[ ] Channel
[ ] Provider
[ ] Delivery
[ ] Delivery Attempt
[ ] Retry
[ ] DLQ
[ ] Deduplication
[ ] Preference
[ ] Routing Policy
[ ] Quiet Hours
[ ] Scheduling
[ ] Digest
[ ] In-App
[ ] Email
[ ] Webhook
[ ] Provider Health
[ ] Provider Failover
[ ] Rate Limit
[ ] Budget
[ ] Usage
[ ] Cost
[ ] Realtime
[ ] Event Integration
[ ] Task Integration
[ ] Agent Integration
[ ] Plugin Integration
[ ] MCP Integration
[ ] Security
[ ] Audit
[ ] Observability
[ ] Localization
[ ] Contract Tests
[ ] Security Tests
[ ] Mock Provider

211. Security Definition of Done

必须证明:

[ ] No cross-tenant notification access
[ ] No unauthorized recipient access
[ ] No secret leakage
[ ] No webhook SSRF
[ ] No template code execution
[ ] No unauthorized external communication
[ ] No preference bypass
[ ] No Agent privilege escalation
[ ] No Plugin privilege escalation
[ ] No MCP privilege escalation
[ ] No duplicate delivery after retry

212. Performance Definition of Done

必须证明:

[ ] Async batch delivery
[ ] Provider rate limiting
[ ] Worker concurrency control
[ ] Delivery lease recovery
[ ] Notification pagination
[ ] Deduplication
[ ] Backpressure
[ ] Provider failover

213. 最终 Runtime 关系

                    EVENT
                      │
                      ↓
              Notification Rule
                      │
                      ↓
                NOTIFICATION
                      │
          ┌───────────┴───────────┐
          ↓                       ↓
      RECIPIENT                 TEMPLATE
          │                       │
          └───────────┬───────────┘
                      ↓
                   MESSAGE
                      │
                      ↓
              DELIVERY PLANNER
                      │
                      ↓
              COMMUNICATION
                  RUNTIME
                      │
          ┌───────────┼───────────┐
          ↓           ↓           ↓
        In-App       Email      Webhook
          ↓           ↓           ↓
       Provider    Provider    Provider
          │           │           │
          └───────────┼───────────┘
                      ↓
                   DELIVERY
                      │
          ┌───────────┴───────────┐
          ↓                       ↓
        EVENT                OBSERVABILITY

214. DevOS 完整通信链

User / Agent / Workflow / Plugin
              │
              ↓
         Action Runtime
              │
              ↓
             Event
              │
              ↓
      Notification Runtime
              │
      ┌───────┼────────┐
      ↓       ↓        ↓
   Policy  Recipient  Template
      │       │        │
      └───────┼────────┘
              ↓
           Message
              │
              ↓
      Communication Runtime
              │
        Provider Router
              │
      ┌───────┼────────┐
      ↓       ↓        ↓
    Email    Push     Webhook
      │       │        │
      └───────┼────────┘
              ↓
           Delivery
              │
        ┌─────┴─────┐
        ↓           ↓
      Event      Metrics
        ↓           ↓
    Realtime    Observability

215. 最终 Golden Rules

Golden Rule 1

Event 表示发生了什么,Notification 表示需要通知什么。

Golden Rule 2

Notification 不直接发送,Delivery 才代表一次实际发送。

Golden Rule 3

Channel 是通信方式,Provider 是通信实现。

Golden Rule 4

所有 Email / SMS / Push / Webhook / Chat 都必须进入统一 Communication Runtime。

Golden Rule 5

业务代码不能直接调用 SMTP、Twilio、SendGrid、FCM 等 Provider SDK。

Golden Rule 6

Provider Credential 永远通过 Credential / Secret Runtime。

Golden Rule 7

所有批量发送必须使用 Task → Job → Queue → Worker Runtime。

Golden Rule 8

Communication Runtime 不重新实现 Queue、Event、Security、Audit、Storage。

Golden Rule 9

Security / Consent / Scope 是发送前的硬性约束。

Golden Rule 10

Preference 决定用户偏好,但不能覆盖 Security Policy。

Golden Rule 11

所有 Delivery 必须支持状态、Attempt、Retry、Idempotency 和 Observability。

Golden Rule 12

Provider 可以替换,但 Notification API 不应该变化。


216. 最终结论

DevOS 最终不应该出现:

SEOEmailService
AgentEmailService
WorkflowEmailService
PluginEmailService
CRMEmailService

而应该只有:

Notification Runtime
        ↓
Communication Runtime
        ↓
Provider Runtime

业务只需要说:

“任务完成,请通知项目负责人。”

DevOS 自己负责:

找谁
 ↓
是否允许通知
 ↓
用户喜欢什么渠道
 ↓
选择什么 Channel
 ↓
选择什么 Provider
 ↓
使用什么 Credential
 ↓
什么时候发送
 ↓
是否需要 Digest
 ↓
是否重复
 ↓
是否超过 Rate Limit
 ↓
是否超过 Budget
 ↓
发送
 ↓
失败 Retry
 ↓
Provider Failover
 ↓
记录 Delivery
 ↓
产生 Event
 ↓
Realtime / Audit / Metrics

最终形成:

EVENT
  ↓
NOTIFICATION
  ↓
RECIPIENT + POLICY + TEMPLATE
  ↓
MESSAGE
  ↓
DELIVERY
  ↓
COMMUNICATION RUNTIME
  ↓
PROVIDER
  ↓
EXTERNAL CHANNEL

最终 Golden Rule:

业务系统只描述“通知什么”;Notification Runtime 决定“通知谁”;Communication Runtime 决定“怎么发送”;Provider 只负责“实际通信”。任何 Agent、Plugin、Workflow、MCP 或业务模块都不能创建第二套发送系统。