Files
devos/Docs/DevOS-Platform-v2/16_EVENT_STREAMING_NOTIFICATION_REALTIME_RUNTIME.md
T
phptits b1f17cf637 v2 platform foundation (docs 01/02/03): Action Runtime + Registry + unified API
- v2 foundation: ActionResult/DevError/ActorContext/ResourceRef/Execution types
- ActionRegistry + ResourceRegistry (namespaced types, FAIL FAST on duplicates)
- ActionRuntime pipeline: validate -> authorize -> middleware -> handler ->
  output validation -> audit -> event -> execution persisted (devos_action_executions)
- Legacy bridge: v1 services registered as devops.*/core.* resources & actions (47 actions, 9 resources)
- Unified Action API: POST /api/v2/actions/:actionId, GET discovery (actions/resources)
- 10 v2 unit tests (registry fail-fast, validation, authz, failure audit, events)
2026-09-10 21:09:44 +00:00

68 KiB
Raw Blame History

DevOS 16 — Event / Streaming / Notification / Realtime Runtime

Version: 1.0 Status: Implementation Specification Target: Zcode Depends on:

  • 03_RESOURCE_ACTION_MODEL.md
  • 06_MCP_SKILL_AGENT_RUNTIME.md
  • 09_TASK_JOB_QUEUE_RUNTIME.md
  • 12_MIGRATION_VERSIONING_COMPATIBILITY.md
  • 14_DATA_QUERY_SEARCH_INDEX_RUNTIME.md
  • 15_FILE_ARTIFACT_STORAGE_RUNTIME.md

1. Document Purpose

本文件定义 DevOS 的统一:

  • Event Runtime
  • Event Bus
  • Event Store
  • Event Subscription
  • Event Handler
  • Event Delivery
  • Event Replay
  • Webhook Runtime
  • Notification Runtime
  • Realtime Runtime
  • WebSocket
  • SSE
  • Task Progress Streaming
  • Agent Observation Streaming
  • Plugin Event Integration
  • MCP Event Integration

目标是让整个 DevOS 使用同一套事件与实时通信基础设施。

核心原则:

Action
   ↓
Execution
   ↓
Domain Event
   ↓
Event Runtime
   ├── Event Handler
   ├── Task
   ├── Search Index
   ├── Cache
   ├── Notification
   ├── Webhook
   ├── Agent
   ├── Plugin
   └── Realtime

任何模块都不得自己实现第二套 Event Bus。


2. Core Philosophy

DevOS 中必须区分:

Event
Event Delivery
Notification
Realtime Message
Webhook

它们不是同一个概念。


2.1 Event

Event 表示:

系统中已经发生了一件事情。

例如:

user.created
seo.website.scanned
task.completed
job.failed
artifact.created
plugin.installed
server.deployed

Event 是事实。


2.2 Event Handler

Handler 表示:

某个模块希望对某个 Event 做事情。

例如:

task.completed
    ↓
create notification

或者:

seo.website.scanned
    ↓
update search index

2.3 Notification

Notification 表示:

系统希望某个用户/Agent/系统知道某件事情。

例如:

通知:
SEO Scan completed

Notification 是用户体验层。


2.4 Realtime Message

Realtime Message 表示:

系统需要立即把状态变化推送给在线客户端。

例如:

Task progress:
37%

它不一定需要永久保存。


2.5 Webhook

Webhook 表示:

把 DevOS Event 推送给外部系统。

例如:

task.completed
    ↓
https://example.com/webhook

3. Unified Architecture

整体结构:

                         ┌─────────────────────┐
                         │       Action        │
                         └──────────┬──────────┘
                                    │
                                    ▼
                         ┌─────────────────────┐
                         │     Execution       │
                         └──────────┬──────────┘
                                    │
                                    ▼
                         ┌─────────────────────┐
                         │    Event Runtime    │
                         └──────────┬──────────┘
                                    │
             ┌──────────────────────┼──────────────────────┐
             │                      │                      │
             ▼                      ▼                      ▼
      ┌────────────┐        ┌────────────┐        ┌────────────┐
      │ Event Bus  │        │ Event Store│        │ Event Outbox│
      └─────┬──────┘        └────────────┘        └────────────┘
            │
            ├──────────────┬──────────────┬──────────────┐
            │              │              │              │
            ▼              ▼              ▼              ▼
       Handler         Notification    Webhook       Realtime
            │              │              │              │
            ▼              ▼              ▼              ▼
         Task          In-App/Email    External       WS/SSE
            │
            ▼
        Agent Runtime

4. Event Types

DevOS Event 至少分为四类。

Domain Event
Integration Event
System Event
Lifecycle Event

4.1 Domain Event

描述业务事实。

例如:

seo.website.created
seo.website.scanned
seo.keyword.updated
crm.customer.created
content.article.published

4.2 Integration Event

用于模块之间或外部系统之间通信。

例如:

github.repository.synced
stripe.payment.completed
slack.message.received

4.3 System Event

系统基础设施事件。

例如:

worker.started
worker.stopped
queue.overloaded
storage.degraded
database.connection.failed

4.4 Lifecycle Event

DevOS 对象生命周期事件。

例如:

resource.created
resource.updated
resource.deleted

task.created
task.started
task.completed

job.created
job.started
job.completed
job.failed

execution.started
execution.completed
execution.failed

5. Event Naming

统一使用:

<namespace>.<resource>.<verb>

例如:

core.user.created

core.task.created
core.task.started
core.task.completed
core.task.failed

core.job.started
core.job.completed

seo.website.created
seo.website.scanned

devops.server.deployed

禁止:

userCreated
UserCreated
createdUser
taskDone

推荐:

core.user.created
core.task.completed

6. Event Version

Event 必须支持版本。

格式:

eventType
eventVersion

例如:

core.task.completed
version: 1

未来:

core.task.completed
version: 2

禁止直接破坏旧 Event Contract。


7. Event Envelope

所有 Event 使用统一 Envelope。

export interface DevOSEvent<T = unknown> {
  id: string

  type: string

  version: number

  occurredAt: string

  publishedAt?: string

  actor: EventActor

  organizationId?: string

  projectId?: string

  environment?: string

  resource?: EventResourceRef

  payload: T

  metadata?: Record<string, unknown>

  correlationId?: string

  causationId?: string

  requestId?: string

  executionId?: string

  taskId?: string

  jobId?: string
}

8. Event Actor

export interface EventActor {
  type:
    | "user"
    | "agent"
    | "service"
    | "system"

  id?: string

  name?: string
}

例如:

{
  "type": "agent",
  "id": "agent_123"
}

9. Event Resource Reference

export interface EventResourceRef {
  type: string
  id: string
}

例如:

{
  "type": "seo.website",
  "id": "site_123"
}

10. Correlation / Causation

DevOS 必须支持事件链追踪。

例如:

User
 ↓
Agent Goal
 ↓
Task
 ↓
Job
 ↓
Action
 ↓
Execution
 ↓
Event
 ↓
Handler
 ↓
Notification

使用:

correlationId
causationId

10.1 correlationId

表示:

整个业务流程属于哪个 Trace。


10.2 causationId

表示:

当前 Event 是由哪个 Event / Execution 导致的。


11. Event Bus

定义统一 EventBus:

export interface EventBus {
  publish<T>(
    event: DevOSEvent<T>
  ): Promise<void>

  publishMany(
    events: DevOSEvent[]
  ): Promise<void>

  subscribe(
    subscription: EventSubscription
  ): Promise<EventSubscriptionHandle>

  unsubscribe(
    subscriptionId: string
  ): Promise<void>
}

12. Event Subscription

export interface EventSubscription {
  id: string

  name: string

  eventTypes: string[]

  handlerId: string

  filter?: EventFilter

  enabled: boolean

  concurrency?: number

  retryPolicy?: RetryPolicy

  metadata?: Record<string, unknown>
}

13. Event Filter

订阅不能只支持 Event Type。

必须支持条件过滤。

例如:

event.type = "core.task.completed"
AND
event.organizationId = "org_123"

接口:

export interface EventFilter {
  expression?: string

  fields?: Record<
    string,
    unknown
  >
}

建议第一版支持:

eq
neq
in
notIn
contains
startsWith
exists

14. Event Handler

export interface EventHandler {
  id: string

  name: string

  eventTypes: string[]

  handle(
    event: DevOSEvent,
    context: EventHandlerContext
  ): Promise<void>
}

Context:

export interface EventHandlerContext {
  requestId: string

  correlationId?: string

  organizationId?: string

  signal: AbortSignal

  logger: Logger
}

15. Handler 不允许直接做危险业务操作

Handler 不应该:

db.user.delete()

也不应该:

server.exec()

必须:

Event
 ↓
Handler
 ↓
Action Runtime

例如:

await actionRuntime.execute(
  "seo.website.reindex",
  input,
  context
)

16. Event Delivery

Event 发布后不应该直接同步执行所有 Handler。

推荐:

publish
   ↓
Event Outbox
   ↓
Event Queue
   ↓
Event Worker
   ↓
Handler

这样可以:

  • retry
  • DLQ
  • concurrency
  • backpressure
  • replay
  • observability

17. Outbox Pattern

这是 DevOS 的关键一致性机制。

错误方式:

DB Transaction
    ↓
commit

EventBus.publish()
    ↓
failed

这样会出现:

数据库已经成功
Event 没有发送

正确方式:

DB Transaction
    ├── Business Data
    └── Outbox Event
          ↓
       COMMIT
          ↓
      Outbox Worker
          ↓
       Event Bus

18. Outbox Schema

export interface EventOutboxRecord {
  id: string

  eventId: string

  eventType: string

  eventVersion: number

  payload: unknown

  status:
    | "pending"
    | "published"
    | "failed"

  attempts: number

  nextAttemptAt?: Date

  createdAt: Date

  publishedAt?: Date

  lastError?: string
}

19. Inbox Pattern

对于需要严格幂等的 Consumer:

Event
 ↓
Inbox
 ↓
check eventId
 ↓
already processed?
 ├── yes → skip
 └── no
      ↓
   process
      ↓
   mark processed

接口:

export interface EventInboxRecord {
  consumerId: string

  eventId: string

  processedAt: Date

  result?: unknown
}

唯一索引:

(consumerId, eventId)

20. Event Idempotency

默认:

At-Least-Once Delivery

而不是:

Exactly-Once

因此 Handler 必须幂等。

例如:

if (await inbox.exists(event.id)) {
  return
}

21. Retry

Event Handler 支持:

fixed
linear
exponential

例如:

1s
5s
30s
2m
10m

失败后:

retry
 ↓
retry
 ↓
retry
 ↓
DLQ

22. Dead Letter Queue

Event DLQ:

export interface EventDeadLetter {
  id: string

  eventId: string

  subscriptionId: string

  handlerId: string

  event: DevOSEvent

  error: unknown

  attempts: number

  failedAt: Date

  metadata?: Record<string, unknown>
}

支持:

view
retry
retry selected
retry all
discard
export

23. Event Replay

Event Store 必须支持 Replay。

用途:

重新建立 Search Index
重新计算统计
恢复插件状态
调试 Handler
数据迁移

Replay:

Event Store
    ↓
filter
    ↓
Replay
    ↓
Event Bus
    ↓
Selected Handler

Replay 必须支持:

event type
date range
organization
resource
event id
handler

24. Replay Safety

Replay 默认:

DO NOT execute destructive actions

除非明确允许。

例如:

handler.metadata.replaySafe = true

对于:

delete
deploy
payment
send email
send webhook

默认禁止 replay。


25. Event Ordering

不要假设全局事件顺序。

只保证指定 Partition 内顺序。

推荐 Partition Key:

organizationId
resourceId
taskId

例如:

task_123

相关事件:

task.created
task.started
task.progress
task.completed

必须保持顺序。


26. Event Partition

export interface EventPartitionStrategy {
  getPartitionKey(
    event: DevOSEvent
  ): string
}

默认:

resource.id

如果没有:

organizationId

27. Event Store

Event Store 用于:

  • 审计
  • Debug
  • Replay
  • Timeline
  • Agent observation
  • Plugin events
  • Integration

定义:

export interface EventStore {
  append(
    event: DevOSEvent
  ): Promise<void>

  get(
    id: string
  ): Promise<DevOSEvent | null>

  query(
    input: EventQuery
  ): Promise<EventPage>

  replay(
    input: EventReplayInput
  ): Promise<ReplayResult>
}

28. Event Query

export interface EventQuery {
  types?: string[]

  organizationId?: string

  projectId?: string

  resourceType?: string

  resourceId?: string

  actorType?: string

  actorId?: string

  correlationId?: string

  from?: Date

  to?: Date

  cursor?: string

  limit?: number
}

29. Event Timeline

任何核心 Resource 都应该能够查看 Timeline:

Task #123

22:01 created
22:01 queued
22:02 started
22:03 progress 20%
22:04 progress 60%
22:06 completed

Timeline 数据来源:

Event Store

而不是 UI 自己维护。


30. Notification Runtime

Notification 是 Event 的用户体验层。

架构:

Event
 ↓
Notification Rule
 ↓
Notification Runtime
 ↓
Channel

支持:

in-app
email
webhook
push

未来可扩展:

Slack
Discord
Telegram
SMS

31. Notification

export interface Notification {
  id: string

  organizationId?: string

  recipientType:
    | "user"
    | "agent"
    | "organization"

  recipientId: string

  type: string

  title: string

  body: string

  severity:
    | "info"
    | "success"
    | "warning"
    | "error"

  readAt?: Date

  createdAt: Date

  data?: Record<string, unknown>

  sourceEventId?: string

  actionUrl?: string
}

32. Notification Channels

定义:

export interface NotificationChannel {
  id: string

  type:
    | "in_app"
    | "email"
    | "webhook"
    | "push"

  send(
    notification: Notification
  ): Promise<void>
}

33. Notification Preferences

用户可以设置:

Task Completed
    In-App: ON
    Email: ON

Task Failed
    In-App: ON
    Email: ON

Task Progress
    In-App: ON
    Email: OFF

System Warning
    In-App: ON
    Email: ON

Preference Resource:

core.notificationPreference

34. Notification Rule

系统管理员 / Plugin 可以定义:

export interface NotificationRule {
  id: string

  eventTypes: string[]

  recipientResolver: string

  templateId: string

  channels: string[]

  filter?: EventFilter

  enabled: boolean
}

例如:

core.task.failed
    ↓
Task Owner
    ↓
in_app + email

35. Notification Template

模板必须支持:

title
body
variables
locale

例如:

Title:
Task {{task.name}} failed

Body:
Task {{task.id}} failed because:
{{error.message}}

36. Notification Center

前端必须提供统一 Notification Center。

包含:

All
Unread
Mentions
Tasks
System
Plugin

支持:

mark read
mark unread
mark all read
delete
open

37. Realtime Runtime

Realtime Runtime 用于:

WebSocket
SSE

统一抽象:

export interface RealtimeRuntime {
  publish(
    channel: string,
    message: RealtimeMessage
  ): Promise<void>

  subscribe(
    connection: RealtimeConnection,
    channel: string
  ): Promise<void>

  unsubscribe(
    connection: RealtimeConnection,
    channel: string
  ): Promise<void>
}

38. Realtime Message

export interface RealtimeMessage<T = unknown> {
  id: string

  type: string

  channel: string

  timestamp: string

  payload: T

  eventId?: string
}

39. Channels

推荐:

user:{userId}

organization:{organizationId}

project:{projectId}

task:{taskId}

job:{jobId}

agent-run:{runId}

resource:{resourceType}:{resourceId}

例如:

task:task_123

40. Channel Authorization

客户端订阅:

task:task_123

必须检查:

User Permission
+
Resource Permission
+
Organization Scope
+
Project Scope

禁止:

client.subscribe("task:someone_else")

直接获取数据。


41. WebSocket

WebSocket 适用于:

双向通信
Agent Chat
实时控制
Interactive UI

例如:

Browser
   ↕
WebSocket
   ↕
Realtime Runtime

42. SSE

SSE 适用于:

Server → Browser

特别适合:

Task Progress
Agent Output
Logs
Execution Events
Streaming Text

例如:

GET /api/tasks/:id/stream

服务器发送:

event: task.progress
data: {...}

43. Task Streaming

Task 必须支持实时观察。

Task
 ↓
Events
 ↓
Realtime
 ↓
UI

客户端:

Task created
Task queued
Task started
Task progress
Task log
Task artifact
Task completed

44. Agent Streaming

Agent Runtime 必须支持:

Goal created
Plan created
Step started
Capability selected
Action started
Action completed
Observation
Replan
Completed

但:

不允许向客户端暴露模型隐藏 Chain-of-Thought。

只允许:

decision summary
action
status
result
reason summary

例如:

{
  "type": "agent.step",
  "status": "running",
  "summary": "正在检查网站当前索引状态"
}

禁止保存:

完整内部思维链

45. Agent Observation

Agent 可以订阅:

task events
job events
action events
resource events
plugin events

然后:

Event
 ↓
Agent Observation
 ↓
Agent Runtime
 ↓
Continue / Replan / Finish

46. Plugin Event Integration

Plugin Manifest 可以声明:

{
  "events": {
    "subscribe": [
      "core.task.completed",
      "seo.website.scanned"
    ],
    "publish": [
      "seo.website.scanned"
    ]
  }
}

安装 Plugin 后:

Plugin
 ↓
Event Registry

自动注册。


47. Plugin Event Handler

Plugin 可以定义:

export default {
  events: {
    "seo.website.scanned": async (event, ctx) => {
      // ...
    }
  }
}

但是最终执行仍然必须:

Handler
 ↓
Action Runtime

48. MCP Event Integration

MCP Server 不应该绕过 Event Runtime。

MCP 可以:

read events
subscribe events
trigger actions

例如:

mcp.devos.events.search
mcp.devos.events.subscribe

但是:

MCP
 ↓
Capability
 ↓
Action Runtime / Event Runtime

49. Webhook Runtime

Webhook 是 Event Runtime 的外部出口。

架构:

Event
 ↓
Webhook Subscription
 ↓
Webhook Delivery
 ↓
HTTP

50. Webhook Subscription

export interface WebhookSubscription {
  id: string

  name: string

  url: string

  eventTypes: string[]

  secret: string

  enabled: boolean

  headers?: Record<string, string>

  retryPolicy?: RetryPolicy
}

51. Webhook Security

Webhook 必须签名。

例如:

X-DevOS-Signature
X-DevOS-Event
X-DevOS-Timestamp

推荐:

HMAC-SHA256

签名内容:

timestamp + "." + rawBody

接收方必须验证:

signature
timestamp
replay window

52. Webhook Retry

失败:

2xx
    ↓
success

4xx
    ↓
通常不 retry

5xx
    ↓
retry

timeout
    ↓
retry

支持:

exponential backoff
jitter
max attempts

53. Webhook Delivery Resource

core.webhookDelivery

字段:

export interface WebhookDelivery {
  id: string

  subscriptionId: string

  eventId: string

  status:
    | "pending"
    | "sending"
    | "delivered"
    | "failed"

  attempts: number

  responseStatus?: number

  responseBody?: string

  lastError?: string

  createdAt: Date

  deliveredAt?: Date
}

54. Event → Notification → Realtime

三者必须统一。

例如:

task.completed
      │
      ├──────────────→ Event Store
      │
      ├──────────────→ Notification
      │                       │
      │                       ├── In-App
      │                       └── Email
      │
      ├──────────────→ Realtime
      │                       │
      │                       └── Browser
      │
      └──────────────→ Webhook

禁止:

Task Service
   ├── sendWebSocket()
   ├── sendEmail()
   ├── sendWebhook()
   └── createNotification()

Task Service 只应该:

publish Event

55. Event Triggered Task

Event 可以创建 Task。

例如:

server.health.failed
       ↓
Event Handler
       ↓
Task
       ↓
Agent
       ↓
diagnose server

或者:

seo.website.scan.completed
       ↓
create analysis task

56. Event Triggered Agent

支持:

Event
 ↓
Agent Trigger
 ↓
Goal
 ↓
Agent Runtime

定义:

export interface AgentEventTrigger {
  id: string

  eventTypes: string[]

  agentProfileId: string

  goalTemplate: string

  filter?: EventFilter

  enabled: boolean
}

例如:

Event:
seo.website.scan.failed

Agent:
SEO Diagnostic Agent

Goal:
分析扫描失败原因并给出修复方案

57. Scheduler + Event

Scheduler 可以产生 Event:

Cron
 ↓
Scheduler
 ↓
Event
 ↓
Agent / Task / Plugin

也可以直接创建 Task。

两种都必须通过 Runtime。


58. Event Trigger Resource

统一:

core.eventTrigger

支持:

Event → Action
Event → Task
Event → Agent
Event → Notification
Event → Webhook

59. Event Trigger Model

export interface EventTrigger {
  id: string

  name: string

  eventTypes: string[]

  filter?: EventFilter

  target:
    | {
        type: "action"
        actionId: string
      }
    | {
        type: "task"
        taskType: string
      }
    | {
        type: "agent"
        agentProfileId: string
      }
    | {
        type: "notification"
        templateId: string
      }
    | {
        type: "webhook"
        subscriptionId: string
      }

  enabled: boolean
}

60. Event Permission

事件本身也是受权限控制的。

例如:

core.user.created

普通用户不能读取所有 User Events。

必须:

Event Permission
+
Resource Permission
+
Scope

61. Sensitive Event

Event Payload 可能包含敏感数据。

例如:

password
token
API key
private URL
secret

禁止直接进入:

Event Store
Log
Realtime
Webhook
Notification

必须:

redact
mask
reference

62. Event Data Classification

Event Payload 支持:

public
internal
sensitive
secret

推荐:

export interface EventSecurityMetadata {
  classification:
    | "public"
    | "internal"
    | "sensitive"
    | "secret"
}

63. Tenant Isolation

Event 必须支持:

organizationId
projectId
environment

Event Query 必须自动注入 Scope。

例如:

User A
 ↓
query events
 ↓
organizationId = org_A

禁止客户端自己指定:

organizationId = org_B

覆盖服务端 Scope。


64. Event Retention

不是所有 Event 永久保存。

支持:

retention policy

例如:

Audit Events:
365 days

Task Events:
180 days

Debug Events:
30 days

Realtime-only:
not persisted

65. Event Archiving

大规模 Event:

PostgreSQL
   ↓
Archive
   ↓
Object Storage

可以使用:

15_FILE_ARTIFACT_STORAGE_RUNTIME

保存:

event archive

66. Event Compaction

部分高频事件不需要永久保存每一次。

例如:

task.progress

可能每秒产生多个事件。

Realtime 可以全部发送。

Event Store 可以:

sampling
aggregation
compaction

例如:

0%
1%
2%
3%
...
99%

长期存储只保留:

0%
25%
50%
75%
100%

但:

Audit / Security / Financial Events 不允许丢失。


67. Backpressure

如果 Event Producer 很快:

10000 events/s

而 Consumer:

1000 events/s

必须产生 Backpressure。

策略:

queue
batch
concurrency
rate limit
priority
sampling

68. Event Priority

export type EventPriority =
  | "low"
  | "normal"
  | "high"
  | "critical"

例如:

security.alert = critical

task.progress = low

69. Event Batch

支持:

publishMany(events)

减少:

DB IO
Redis IO
Network IO

70. Event Transaction

Action Runtime 中:

Action
 ↓
DB Transaction
 ├── mutate data
 └── append Outbox Event
 ↓
commit

Action 成功但 Event 不应该丢失。


71. Event Failure Isolation

一个 Handler 失败:

Handler A ❌
Handler B ✅
Handler C ✅

不能导致整个 Event 失败。

Event Delivery 必须独立:

Event
 ├── Delivery A
 ├── Delivery B
 └── Delivery C

72. Event Delivery Resource

core.eventDelivery
export interface EventDelivery {
  id: string

  eventId: string

  subscriptionId: string

  handlerId: string

  status:
    | "pending"
    | "running"
    | "completed"
    | "retrying"
    | "failed"

  attempts: number

  startedAt?: Date

  completedAt?: Date

  lastError?: string
}

73. Observability

Event Runtime 必须提供:

events published
events processed
events failed
events retried
events DLQ
handler latency
handler error rate
webhook delivery rate
notification delivery rate
realtime connections
realtime messages

74. Metrics

至少:

devos_events_published_total

devos_events_processed_total

devos_events_failed_total

devos_event_handler_duration_ms

devos_event_queue_depth

devos_event_dlq_total

devos_webhook_delivery_total

devos_webhook_failure_total

devos_notification_sent_total

devos_notification_failed_total

devos_realtime_connections

devos_realtime_messages_total

75. Logging

Event Log:

eventId
eventType
eventVersion
organizationId
resourceId
correlationId
causationId
handlerId
deliveryId
duration
status

不要默认记录完整敏感 Payload。


76. Tracing

推荐:

OpenTelemetry

Trace:

HTTP Request
 ↓
Action
 ↓
Execution
 ↓
Event Publish
 ↓
Event Delivery
 ↓
Handler
 ↓
Action

使用:

traceId
spanId

77. Database Model

至少:

events

event_outbox

event_inbox

event_subscriptions

event_deliveries

event_dead_letters

event_triggers

notifications

notification_preferences

notification_templates

webhook_subscriptions

webhook_deliveries

78. PostgreSQL Schema

建议:

events

字段:

id
type
version
occurred_at
published_at
actor_type
actor_id
organization_id
project_id
environment
resource_type
resource_id
correlation_id
causation_id
request_id
execution_id
task_id
job_id
payload
metadata
created_at

索引:

(type, occurred_at)

(organization_id, occurred_at)

(resource_type, resource_id, occurred_at)

(correlation_id)

(task_id, occurred_at)

(execution_id, occurred_at)

79. Redis

Redis 用于:

Event Queue
Realtime Pub/Sub
Connection Coordination
Rate Limit
Locks
Short-lived Event State

不要把 Redis 作为唯一 Event Store。

数据库 / Durable Storage 才是长期事实来源。


80. Event Bus Provider

DevOS 必须抽象:

export interface EventBusProvider {
  publish(
    event: DevOSEvent
  ): Promise<void>

  consume(
    consumer: EventConsumer
  ): Promise<void>
}

第一版可以:

Redis Streams

后续可以:

NATS
Kafka
RabbitMQ

不允许业务层依赖具体实现。


81. Recommended Initial Implementation

第一阶段:

PostgreSQL
+
Redis Streams
+
WebSocket/SSE

架构:

PostgreSQL
  ├── Event Store
  ├── Outbox
  ├── Inbox
  └── Notification

Redis
  ├── Event Queue
  ├── Realtime Pub/Sub
  └── Distributed Coordination

82. Event Runtime API

export interface EventRuntime {
  publish<T>(
    input: PublishEventInput
  ): Promise<DevOSEvent<T>>

  publishMany(
    input: PublishEventInput[]
  ): Promise<void>

  query(
    input: EventQuery
  ): Promise<EventPage>

  replay(
    input: EventReplayInput
  ): Promise<ReplayResult>

  subscribe(
    input: SubscribeEventInput
  ): Promise<EventSubscription>

  unsubscribe(
    subscriptionId: string
  ): Promise<void>
}

83. Notification Runtime API

export interface NotificationRuntime {
  create(
    input: CreateNotificationInput
  ): Promise<Notification>

  send(
    notificationId: string
  ): Promise<void>

  markRead(
    notificationId: string
  ): Promise<void>

  markAllRead(
    recipientId: string
  ): Promise<void>

  list(
    input: NotificationQuery
  ): Promise<NotificationPage>
}

84. Realtime API

export interface RealtimeRuntime {
  publish<T>(
    channel: string,
    message: RealtimeMessage<T>
  ): Promise<void>

  authorize(
    connection: RealtimeConnection,
    channel: string
  ): Promise<boolean>

  subscribe(
    connection: RealtimeConnection,
    channel: string
  ): Promise<void>

  unsubscribe(
    connection: RealtimeConnection,
    channel: string
  ): Promise<void>
}

85. Generic Resource Events

所有 Resource 默认可以产生:

resource.created
resource.updated
resource.deleted

但实际 Event Type 应该使用完整 namespace。

例如:

core.user.created
seo.website.created
core.task.updated

86. Generic Action Events

Action Runtime 默认可以产生:

action.started
action.completed
action.failed
action.cancelled

建议具体化:

execution.started
execution.completed
execution.failed
execution.cancelled

87. Task Events

Task Runtime 必须发布:

core.task.created
core.task.queued
core.task.started
core.task.progress
core.task.paused
core.task.resumed
core.task.waiting
core.task.completed
core.task.failed
core.task.cancelled

88. Job Events

core.job.created
core.job.queued
core.job.started
core.job.progress
core.job.retrying
core.job.completed
core.job.failed
core.job.cancelled

89. Execution Events

core.execution.started
core.execution.completed
core.execution.failed
core.execution.cancelled

90. Artifact Events

来自:

15_FILE_ARTIFACT_STORAGE_RUNTIME

支持:

core.artifact.created
core.artifact.version.created
core.artifact.ready
core.artifact.deleted

91. File Events

core.file.created
core.file.uploaded
core.file.processing
core.file.ready
core.file.quarantined
core.file.failed
core.file.deleted

92. Search Events

来自:

14_DATA_QUERY_SEARCH_INDEX_RUNTIME

例如:

core.searchIndex.created
core.searchIndex.rebuilding
core.searchIndex.ready
core.searchIndex.failed

以及:

resource.changed

触发:

Index Job

93. Cache Invalidation

不要让 Plugin 自己调用 Redis 删除 Cache。

正确:

Action
 ↓
Resource Event
 ↓
Cache Handler
 ↓
Cache Runtime

94. Global Event Timeline

DevOS UI 必须支持:

System
Organization
Project
Resource
Task
Agent
Plugin

统一 Timeline。

例如:

10:31 Agent started task
10:32 Website scan started
10:33 Website scan completed
10:33 17 issues found
10:34 Report artifact created
10:35 Task completed

数据来源:

Event Store

95. UI Realtime Architecture

前端:

React
   ↓
Realtime Client
   ↓
WebSocket / SSE
   ↓
Realtime Runtime
   ↓
Event

建议提供:

packages/realtime-client

统一 API:

const stream = realtime.subscribe(
  "task:task_123"
)

stream.on("message", handler)

96. Frontend Event Store

前端可以使用:

Zustand
+
TanStack Query

但是:

前端 State 不是 Event Store。

Realtime Event 到达后:

Realtime
 ↓
Client Event Dispatcher
 ├── invalidate Query
 ├── update Zustand
 └── show Notification

97. Query Invalidation

例如:

core.task.completed

前端收到后:

invalidate:
["task", taskId]

以及:

["tasks"]

必要时刷新。


98. Optimistic UI

可以:

Action
 ↓
optimistic update
 ↓
Event
 ↓
server authoritative state

服务器 Event / Query 结果最终拥有最高权威。


99. Connection Management

Realtime Server 必须支持:

connect
authenticate
subscribe
unsubscribe
heartbeat
disconnect
reconnect

Connection:

export interface RealtimeConnection {
  id: string

  userId: string

  organizationId?: string

  connectedAt: Date

  metadata?: Record<string, unknown>
}

100. Reconnect

客户端断线后:

connect
 ↓
authenticate
 ↓
restore subscriptions
 ↓
resume stream

如果需要可靠恢复:

lastEventId

服务器可以:

replay missed events

101. Last Event ID

SSE 必须支持:

Last-Event-ID

WebSocket 可以:

{
  "resumeFrom": "event_123"
}

Realtime Runtime 根据 Event Store 决定是否可以恢复。


102. Event Delivery Guarantees

DevOS 明确声明:

Event Store:
Durable

Event Queue:
At-Least-Once

Handler:
At-Least-Once

Webhook:
At-Least-Once

Realtime:
Best Effort by default

Notification:
At-Least-Once with deduplication

不要宣称:

Exactly Once

除非底层 Provider + Handler 真正保证。


103. Security

必须防止:

Cross Tenant Event Leak
Cross Project Event Leak
Unauthorized Subscription
Webhook SSRF
Webhook Secret Leak
Event Payload Secret Leak
Realtime Channel Hijacking
Notification Spoofing
Replay Abuse

104. Webhook SSRF Protection

Webhook URL 创建时必须检查:

localhost
127.0.0.1
0.0.0.0
private IP
link-local
metadata service
internal hostname

并支持:

DNS rebinding protection
IP validation
redirect restrictions
timeout
max response size

105. Event Payload Limits

必须限制:

max event payload size
max metadata size
max notification body size
max webhook response size
max realtime message size

推荐默认:

Event payload:
256 KB

Realtime:
64 KB

Notification:
64 KB

具体值允许配置。


106. Large Payload

如果 Event Payload 很大:

不要:

{
  "payload": "10MB..."
}

应该:

{
  "artifactId": "artifact_123"
}

然后:

Artifact Runtime

读取。


107. Event Artifact Integration

例如:

Agent generated report

Event:

{
  "type": "core.artifact.created",
  "payload": {
    "artifactId": "artifact_123"
  }
}

而不是把整个报告塞进 Event。


108. Event Schema Registry

Event 必须注册 Schema。

export interface EventSchema {
  type: string

  version: number

  schema: unknown

  description?: string

  deprecated?: boolean

  breakingChanges?: string[]
}

Registry:

Event Schema Registry

用于:

validation
documentation
version compatibility
MCP discovery
Agent discovery

109. Plugin Event Schema

Plugin 安装后注册:

Plugin
 ├── Actions
 ├── Resources
 ├── Skills
 ├── MCP
 └── Events

Event 也进入:

Capability Registry

但 Event Capability 类型应与 Action Capability 区分。


110. Agent Event Capability

Agent 可以发现:

event.subscribe
event.query
event.observe

但必须经过:

permission
scope
policy

111. Agent Event Trigger Example

用户:

如果服务器宕机,就让 Agent 自动诊断。

系统:

Event Trigger
   ↓
devops.server.down
   ↓
Agent Goal
   ↓
Agent Runtime
   ↓
Skill
   ↓
Action

Agent 不需要轮询服务器。


112. Event Driven Architecture

DevOS 最终形成:

Action Driven
+
Event Driven
+
Task Driven
+
Agent Driven

关系:

Action
  ↓
Event
  ↓
Task / Agent / Plugin / Notification

113. 不允许 Event 无限递归

例如:

A
 ↓
B
 ↓
C
 ↓
A

必须支持:

max event depth

Event Metadata:

{
  eventDepth: 3
}

超过限制:

reject / DLQ

114. Event Loop Detection

使用:

causationId
correlationId
event chain

检测:

same event type
same resource
same handler

短时间重复触发。

必要时:

circuit breaker

115. Handler Concurrency

Handler 可以定义:

concurrency: 10

但是资源敏感 Handler:

concurrency = 1

例如:

production deployment

116. Handler Timeout

每个 Handler:

timeout

例如:

30s
5m

超时:

AbortSignal
 ↓
retry

117. Handler Transaction

如果 Handler 修改多个 DB 表:

Action Runtime
 ↓
Transaction

不要自己创建不可控 Transaction。


118. Event Consumer Groups

支持:

consumer group

例如:

search-indexer
notification-service
webhook-service
analytics-service

同一个 Event:

Event
 ├── search-indexer
 ├── notification-service
 ├── webhook-service
 └── analytics-service

每个 Consumer Group 独立消费。


119. Event Priority Queues

推荐:

critical
high
normal
low

例如:

security.alert → critical

task.completed → normal

task.progress → low

120. Batch Processing

Consumer 可以:

1 event

也可以:

100 events

例如 Search Index:

100 Resource Events
 ↓
one index batch

121. Notification Deduplication

避免:

same event
 ↓
same notification
 ↓
duplicate

使用:

deduplicationKey

例如:

taskId + eventType

122. Notification Aggregation

高频通知:

100 task progress events

不应该:

100 emails

支持聚合:

You have 37 task updates.

123. Email Queue

Email 不允许在 HTTP Request 中直接发送。

必须:

Notification
 ↓
Task / Job
 ↓
Queue
 ↓
Worker
 ↓
Email Provider

124. Notification Provider

抽象:

export interface NotificationProvider {
  send(
    message: NotificationMessage
  ): Promise<NotificationDeliveryResult>
}

未来:

SMTP
SES
SendGrid
Resend
Slack
Discord
Telegram

都只是 Provider。


125. Realtime Provider

抽象:

export interface RealtimeProvider {
  publish(
    channel: string,
    message: RealtimeMessage
  ): Promise<void>
}

第一版:

Redis Pub/Sub
+
WebSocket
+
SSE

126. API

至少提供:

GET    /api/events
GET    /api/events/:id

POST   /api/events/replay

GET    /api/event-subscriptions
POST   /api/event-subscriptions
PATCH  /api/event-subscriptions/:id
DELETE /api/event-subscriptions/:id

GET    /api/notifications
POST   /api/notifications/:id/read
POST   /api/notifications/read-all

GET    /api/webhooks
POST   /api/webhooks
PATCH  /api/webhooks/:id
DELETE /api/webhooks/:id

GET    /api/tasks/:id/events
GET    /api/tasks/:id/stream

GET    /api/agent-runs/:id/stream

127. WebSocket API

例如:

/ws

客户端:

{
  "type": "subscribe",
  "channel": "task:task_123"
}

服务端:

{
  "type": "subscribed",
  "channel": "task:task_123"
}

事件:

{
  "type": "task.progress",
  "channel": "task:task_123",
  "payload": {
    "progress": 65
  }
}

128. SSE API

例如:

GET /api/tasks/task_123/stream

返回:

event: task.started
data: {...}

event: task.progress
data: {...}

event: task.completed
data: {...}

129. CLI

必须提供:

devos events list

devos events get <id>

devos events replay <id>

devos events replay --type core.task.completed

devos events subscriptions

devos events dlq

devos events dlq retry <id>

devos notifications list

devos webhooks list

devos webhooks test <id>

130. Admin UI

必须提供:

System
 ├── Events
 │    ├── Event Explorer
 │    ├── Event Detail
 │    ├── Event Replay
 │    ├── Subscriptions
 │    ├── Deliveries
 │    └── Dead Letter Queue
 │
 ├── Notifications
 │    ├── Templates
 │    ├── Rules
 │    ├── Preferences
 │    └── Delivery Logs
 │
 ├── Webhooks
 │    ├── Subscriptions
 │    ├── Deliveries
 │    └── Logs
 │
 └── Realtime
      ├── Connections
      └── Channels

131. Event Explorer

支持:

Event Type
Version
Organization
Project
Resource
Actor
Task
Job
Execution
Correlation ID
Date Range
Status

结果:

Timeline

132. Event Detail

必须显示:

Event ID
Type
Version
Occurred At
Actor
Resource
Organization
Project
Correlation
Causation
Payload
Metadata
Deliveries

敏感字段必须隐藏。


133. Event Delivery UI

例如:

Event:
core.task.completed

Deliveries:

Notification    completed
Webhook #1       completed
Search Index     completed
Analytics        failed → retrying

134. DLQ UI

支持:

inspect
retry
bulk retry
discard
filter

必须显示:

event
handler
attempts
error
last attempt

135. Plugin Developer API

Plugin 可以:

devos.events.publish(...)
devos.events.subscribe(...)
devos.notifications.create(...)
devos.realtime.publish(...)

但是这些 API 最终进入:

Event Runtime
Notification Runtime
Realtime Runtime

不能访问:

Redis
PostgreSQL
WebSocket Server

136. SDK

推荐:

packages/events
packages/notifications
packages/realtime
packages/webhooks

例如:

import {
  eventRuntime
} from "@devos/events"

137. Package Structure

最终:

packages/
├── event/
│   ├── core/
│   ├── runtime/
│   ├── bus/
│   ├── store/
│   ├── outbox/
│   ├── inbox/
│   ├── subscription/
│   ├── delivery/
│   ├── replay/
│   └── schema/
│
├── notification/
│   ├── core/
│   ├── runtime/
│   ├── template/
│   ├── preference/
│   └── providers/
│
├── realtime/
│   ├── core/
│   ├── runtime/
│   ├── websocket/
│   ├── sse/
│   └── client/
│
└── webhook/
    ├── core/
    ├── runtime/
    ├── delivery/
    └── security/

138. NestJS Backend Modules

建议:

EventModule

NotificationModule

RealtimeModule

WebhookModule

依赖:

EventModule
   ↓
TaskModule
ActionModule
PluginModule
AgentModule
SearchModule
StorageModule

注意不要形成循环依赖。


139. Dependency Rule

推荐依赖方向:

Core Runtime
    ↑
Event Runtime
    ↑
Feature Modules

Feature Module:

can publish Event
can subscribe Event

但 Event Runtime:

must not import SEO
must not import CRM
must not import DevOps

140. Event Registry

统一:

export interface EventRegistry {
  register(
    schema: EventSchema
  ): void

  get(
    type: string,
    version: number
  ): EventSchema | undefined

  list(): EventSchema[]
}

Plugin 安装时自动注册。


141. Event Validation

Publish:

Event
 ↓
Registry
 ↓
Schema Validation
 ↓
Security Validation
 ↓
Outbox

非法 Event:

reject

142. Event Compatibility

参考:

12_MIGRATION_VERSIONING_COMPATIBILITY.md

Event Schema 必须检查:

backward compatibility
forward compatibility
breaking change
deprecated fields

143. Deprecated Event

Event 可以:

deprecated: true

但不能立即删除。

流程:

v1
 ↓
deprecated
 ↓
v2
 ↓
migration period
 ↓
remove

144. Event Contract Test

每个 Plugin Event 必须有:

schema test
publish test
subscription test
permission test
version test
replay test

145. Integration with Task Runtime

Task Runtime:

Task created
 ↓
Event
 ↓
Realtime
 ↓
UI

Worker:

Job started
 ↓
Event
 ↓
Realtime

不要:

TaskService
 ↓
WebSocket

146. Integration with Agent Runtime

Agent:

Goal
 ↓
Agent Run
 ↓
Task
 ↓
Event
 ↓
Observation
 ↓
Agent

Agent 不应该轮询:

SELECT task WHERE status = ...

而应该:

subscribe / observe Event

147. Integration with Search Runtime

Resource changed
 ↓
Event
 ↓
Search Index Handler
 ↓
Index Job
 ↓
Worker

数据库是 Source of Truth。


148. Integration with Storage Runtime

File uploaded
 ↓
file.uploaded
 ↓
Processing Task
 ↓
Artifact
 ↓
Event

149. Integration with Plugin Runtime

Plugin 生命周期:

plugin.install
plugin.installed

plugin.enable
plugin.enabled

plugin.disable
plugin.disabled

plugin.upgrade
plugin.upgraded

plugin.uninstall
plugin.uninstalled

150. Integration with Migration Runtime

Migration:

migration.started
migration.progress
migration.completed
migration.failed

可以实时显示:

Upgrade UI

151. Integration with Scheduler

Scheduler:

schedule.triggered

然后:

Event
 ↓
Task / Agent

152. Event-Driven UI

UI 中任何需要实时状态的模块都必须优先考虑:

Event + Query

而不是:

setInterval(fetch, 1000)

例如:

Task Progress
Job Progress
Agent Run
Deployment
File Processing
Plugin Upgrade
Migration

153. Polling Fallback

如果客户端不支持 WebSocket/SSE:

Realtime unavailable
 ↓
fallback polling

但是:

Polling 是 fallback,不是主架构。


154. Offline / Reconnect

客户端必须处理:

connection lost
reconnecting
resubscribing
event gap

状态:

connected
reconnecting
disconnected

155. Event Gap

如果客户端发现:

event_100
event_105

中间缺失:

event_101-104

可以:

GET /api/events?after=event_100

重新同步。


156. Reliable UI State

Realtime 只是:

notification / update signal

最终数据:

Query Runtime

例如:

task.completed
 ↓
invalidate task query
 ↓
GET task
 ↓
authoritative state

不要完全依赖客户端 Event Payload 作为最终状态。


157. Event Storm Protection

如果一个资源:

每秒 10000 updates

系统必须支持:

coalescing
debounce
sampling
aggregation

尤其:

progress events
metrics
logs

158. Event Coalescing

例如:

task.progress 1
task.progress 2
task.progress 3
...

Realtime 可以合并:

task.progress = 3

但:

security.alert
payment.completed
deployment.failed

禁止合并。


159. Event Categories

可以定义:

export type EventCategory =
  | "audit"
  | "domain"
  | "system"
  | "integration"
  | "progress"
  | "debug"

不同 Category:

retention
priority
storage
delivery

策略不同。


160. Event Governance

系统管理员可以查看:

Event Types
Schemas
Consumers
Handlers
Subscriptions
Failure Rate
Retention

Plugin 开发者只能管理:

own namespace

161. Namespace Isolation

Plugin:

seo

只能注册:

seo.*

不能覆盖:

core.*

除非系统明确授权。


162. Event Ownership

Schema:

owner: string

例如:

core.task.completed
owner = devos-core

seo.website.scanned
owner = seo-plugin

163. Event Documentation

每个 Event 自动生成:

Event Type
Description
Version
Schema
Producer
Consumers
Permissions
Retention

可以作为:

Developer Portal
MCP Discovery
Agent Capability Discovery

164. Agent-Friendly Event Description

Agent 不需要接收完整所有 Event。

Capability Discovery:

Level 1:
event type + description

Level 2:
schema

Level 3:
subscription instructions

继续遵守:

06_MCP_SKILL_AGENT_RUNTIME.md

的 Progressive Disclosure。


165. Event Search

使用:

14_DATA_QUERY_SEARCH_INDEX_RUNTIME

支持:

keyword
event type
resource
actor
task
correlation

但:

Event Store 是事实来源,Search Index 只是加速查询。


166. Event Audit

Audit Event 不允许被普通用户删除。

例如:

user.login
permission.changed
role.changed
api_key.created
plugin.installed
deployment.started

Audit Event:

immutable

167. Event Immutability

Event 一旦写入:

不可修改

如果发现错误:

publish correction event

例如:

billing.payment.created
billing.payment.corrected

而不是修改原 Event。


168. Event Integrity

关键 Event 可以保存:

checksum

例如:

SHA-256

用于:

audit integrity
archive verification

169. Event Encryption

敏感 Event Payload:

encryption at rest

Secret 类型:

不要进入 Event Payload

优先保存:

secret reference

170. Multi-Instance Realtime

DevOS 多实例:

Browser
 ↓
Instance A

Event:

Instance B

必须:

Redis Pub/Sub

广播:

Instance B
 ↓
Redis
 ↓
Instance A
 ↓
Browser

171. Horizontal Scaling

Event Worker:

Worker 1
Worker 2
Worker 3

使用:

consumer group
partition
lease

保证:

same partition
ordered

172. Realtime Scaling

Realtime:

WebSocket Server 1
WebSocket Server 2
WebSocket Server 3

共享:

Redis

173. Health Checks

必须:

GET /health/events

GET /health/realtime

GET /health/webhooks

GET /health/notifications

检查:

DB
Redis
Queue
Worker
Provider

174. Graceful Shutdown

关闭:

stop accepting new events
 ↓
drain consumers
 ↓
close realtime connections
 ↓
flush buffers
 ↓
shutdown

175. Event Runtime Configuration

配置:

EVENT_BUS_PROVIDER
EVENT_MAX_PAYLOAD_SIZE
EVENT_RETENTION
EVENT_RETRY_POLICY

REALTIME_PROVIDER
REALTIME_MAX_CONNECTIONS
REALTIME_MESSAGE_LIMIT

WEBHOOK_TIMEOUT
WEBHOOK_MAX_RETRIES

NOTIFICATION_PROVIDER
NOTIFICATION_BATCH_SIZE

176. Testing

必须实现:

Unit Tests

Event Envelope
Event Schema
Event Registry
Filter
Subscription
Retry
Idempotency
Replay
Notification
Webhook Signature
Realtime Channel Authorization

177. Integration Tests

至少:

Action
 ↓
Execution
 ↓
Event
 ↓
Handler

验证完整链路。


178. Outbox Test

测试:

DB success
Outbox success
Event published

以及:

DB success
Outbox worker crash
 ↓
restart
 ↓
event eventually published

179. Inbox Test

重复 Event:

event_123
event_123
event_123

Handler 最终:

execute once

180. Retry Test

模拟:

handler fails 2 times
success on third

验证:

attempts = 3

181. DLQ Test

模拟:

all retries failed

验证:

DLQ record created

然后:

retry DLQ

必须可以恢复。


182. Replay Test

Event Store
 ↓
Replay
 ↓
selected handler

验证:

non-replay-safe handler

不能执行。


183. Permission Test

User A:

org_A

不能:

subscribe org_B event

验证:

403

184. Webhook Security Test

验证:

valid signature
invalid signature
expired timestamp
replay request
private IP
redirect
timeout

185. Realtime Test

验证:

connect
authenticate
subscribe
publish
receive
unsubscribe
reconnect
resume

186. Agent Integration Test

测试:

Event
 ↓
Agent Trigger
 ↓
Goal
 ↓
Agent Run
 ↓
Task
 ↓
Action
 ↓
Event

必须完整通过。


187. Plugin Integration Test

Plugin 安装:

Plugin
 ↓
Event Schema
 ↓
Event Subscription
 ↓
Handler

卸载:

subscription removed
handler removed

历史 Event 不删除。


188. Performance Requirements

第一阶段目标:

Event publish p95 < 100ms

Event handler scheduling p95 < 200ms

Realtime publish p95 < 100ms

Notification enqueue p95 < 200ms

这些是初始工程目标,允许根据实际部署调整。


189. Reliability Requirements

目标:

No event loss after committed transaction

At-least-once delivery

Retry recovery

DLQ recovery

Realtime reconnect

Webhook retry

190. Zcode Implementation Rules

Zcode 必须严格遵守:

Rule 1

禁止 Plugin 自己创建:

Event Bus
WebSocket Server
Notification Service
Webhook Queue

必须使用:

DevOS Runtime

Rule 2

禁止:

Action → Email
Action → WebSocket
Action → Webhook

正确:

Action
 ↓
Event
 ↓
Notification / Realtime / Webhook

Rule 3

禁止 Handler 绕过:

Action Runtime

Rule 4

Event 必须:

versioned
immutable
traceable
tenant-aware
permission-aware

Rule 5

默认:

At-Least-Once

所有 Consumer 必须考虑:

idempotency

Rule 6

Event Store 与 Realtime 必须分离。

Event Store = durable fact

Realtime = delivery mechanism

Rule 7

Realtime 不是最终数据来源。

UI 收到 Event 后:

invalidate Query

必要时重新 Query。


Rule 8

Agent 不能直接访问:

Event DB
Redis
WebSocket
Webhook
Notification Provider

必须通过:

Capability / Runtime

Rule 9

MCP 不允许绕过:

Event Runtime
Action Runtime
Permission
Scope
Audit

Rule 10

所有 Event 都必须包含:

eventId
type
version
occurredAt
actor
correlationId

适用时还必须包含:

causationId
requestId
executionId
taskId
jobId
resource

Rule 11

大 Payload 不允许直接放 Event。

使用:

Artifact
File
Resource Reference

Rule 12

高频 Progress Event 必须支持:

coalescing
sampling
aggregation

Rule 13

Event Handler 必须独立失败。

Handler A failed

不能影响:

Handler B
Handler C

Rule 14

Webhook 必须具备:

HMAC Signature
Replay Protection
SSRF Protection
Timeout
Retry

Rule 15

Realtime Channel 必须进行:

Authentication
Authorization
Tenant Scope
Resource Scope

191. Acceptance Criteria

本模块完成必须满足:

[ ] Event Envelope
[ ] Event Schema Registry
[ ] Event Registry
[ ] Event Store
[ ] Event Bus
[ ] Outbox
[ ] Inbox
[ ] Subscription
[ ] Event Handler
[ ] Event Delivery
[ ] Retry
[ ] DLQ
[ ] Replay
[ ] Event Filter
[ ] Event Permission
[ ] Tenant Isolation
[ ] Event Ordering
[ ] Event Partition
[ ] Event Retention
[ ] Event Observability

[ ] Notification Runtime
[ ] Notification Template
[ ] Notification Preference
[ ] In-App Notification
[ ] Email Queue
[ ] Notification Deduplication
[ ] Notification Aggregation

[ ] Webhook Runtime
[ ] Webhook Subscription
[ ] Webhook Delivery
[ ] HMAC Signature
[ ] Webhook Retry
[ ] SSRF Protection

[ ] Realtime Runtime
[ ] WebSocket
[ ] SSE
[ ] Channel Authorization
[ ] Reconnect
[ ] Last Event ID
[ ] Event Gap Recovery
[ ] Horizontal Scaling

[ ] Task Streaming
[ ] Job Streaming
[ ] Execution Streaming
[ ] Agent Streaming
[ ] Migration Streaming
[ ] Plugin Streaming

[ ] Plugin Event Integration
[ ] MCP Event Integration
[ ] Agent Event Trigger
[ ] Scheduler Event Trigger
[ ] Search Integration
[ ] Storage Integration
[ ] Task Integration

[ ] Event Explorer
[ ] Event Timeline
[ ] Notification Center
[ ] Webhook Dashboard
[ ] DLQ UI
[ ] Realtime Connection UI

[ ] CLI
[ ] API
[ ] Unit Tests
[ ] Integration Tests
[ ] Security Tests
[ ] Performance Tests

192. Final Architecture

完成本模块后,DevOS 的整体 Runtime 应该变成:

                         ┌───────────────┐
                         │     User      │
                         └───────┬───────┘
                                 │
                                 ▼
                         ┌───────────────┐
                         │     Goal      │
                         └───────┬───────┘
                                 │
                                 ▼
                         ┌───────────────┐
                         │ Agent Runtime │
                         └───────┬───────┘
                                 │
                                 ▼
                         ┌───────────────┐
                         │     Task      │
                         └───────┬───────┘
                                 │
                                 ▼
                         ┌───────────────┐
                         │      Job      │
                         └───────┬───────┘
                                 │
                                 ▼
                         ┌───────────────┐
                         │     Action    │
                         └───────┬───────┘
                                 │
                                 ▼
                       ┌─────────────────────┐
                       │   Action Runtime    │
                       └──────────┬──────────┘
                                  │
                                  ▼
                       ┌─────────────────────┐
                       │     Execution       │
                       └──────────┬──────────┘
                                  │
                                  ▼
                       ┌─────────────────────┐
                       │    Event Runtime    │
                       └──────────┬──────────┘
                                  │
        ┌─────────────────────────┼─────────────────────────┐
        │                         │                         │
        ▼                         ▼                         ▼
 ┌──────────────┐         ┌──────────────┐         ┌──────────────┐
 │ Event Store  │         │ Event Queue  │         │   Outbox     │
 └──────────────┘         └──────┬───────┘         └──────────────┘
                                 │
                 ┌───────────────┼────────────────┐
                 │               │                │
                 ▼               ▼                ▼
             Handlers       Notifications       Webhook
                 │               │                │
                 ▼               ▼                ▼
              Actions        In-App/Email     External Apps
                 │
                 ▼
             Realtime
                 │
           ┌─────┴─────┐
           ▼           ▼
       WebSocket       SSE
           │           │
           └─────┬─────┘
                 ▼
             DevOS UI

193. Final Golden Rule

DevOS 的事件体系最终必须遵守:

ACTION
   ↓
EXECUTION
   ↓
EVENT
   ↓
EVENT RUNTIME
   ↓
┌───────────┬────────────┬────────────┬────────────┐
│           │            │            │
▼           ▼            ▼            ▼
TASK      AGENT      NOTIFICATION   WEBHOOK
│           │            │            │
▼           ▼            ▼            ▼
JOB      OBSERVE      IN-APP/EMAIL  EXTERNAL
│
▼
REALTIME
│
├── WebSocket
└── SSE

最终原则:

Event 是系统事实,Action 是系统行为,Task 是工作,Agent 是决策,Notification 是通知,Realtime 是传输,Webhook 是外部集成。

所有这些能力必须建立在同一个 Event Runtime 之上,任何 Plugin、MCP、Agent、Task、UI 都不得自行建立第二套事件、通知或实时系统。


194. Zcode 最终检查

实现完成后,必须能够回答:

一个 Action 执行成功后,Event 在哪里产生?
Event 如何保证不会丢?
Event 如何 Retry?
Event 如何保证 Consumer 幂等?
Event 如何进入 Notification?
Event 如何进入 Webhook?
Event 如何实时推送给 UI?
Agent 如何观察 Event?
Plugin 如何订阅 Event?
MCP 如何访问 Event?
Event 如何 Replay?
Event 如何做权限控制?
Event 如何做 Tenant Isolation?
Event 如何追踪 Correlation?
Event 如何与 Task / Job / Execution 关联?
Realtime 断线后如何恢复?
Webhook 如何防 SSRF?
高频 Progress Event 如何防 Event Storm?

如果上述问题全部可以通过 DevOS Runtime 回答,而不是某个 Plugin 自己实现一套机制,则 16_EVENT_STREAMING_NOTIFICATION_REALTIME_RUNTIME.md 达标。