> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_11_event_bus_and_scheduler/11.1_event_bus.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 11.1 Event Bus (Bus)

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2026-02-17

***

In a complex system composed of multiple modules, the communication method between modules determines the system's coupling and maintainability. If the Session module had to directly call the TUI module to refresh the interface, call the Server module to push SSE events, and call the statistics module to record data every time a session was created, then Session would depend on all downstream consumers, forming a tightly coupled "spider web."

OpenCode solves this problem through an **Event Bus** -- the Session module only needs to publish a `session.created` event, and all modules that care about this event subscribe to and handle it on their own. Publishers do not need to know which subscribers exist, and subscribers do not need to know where events come from.

> **Extended Explanation: Publish-Subscribe Pattern (Pub/Sub Pattern)**
>
> The Publish-Subscribe Pattern (Pub/Sub for short) is a messaging communication pattern. In this pattern:
>
> * **Publishers** send messages to an intermediary (message broker) rather than directly to receivers.
> * **Subscribers** register their interest in specific message types with the intermediary.
> * When a publisher publishes a message, the intermediary is responsible for forwarding it to all matching subscribers.
>
> Compared to direct invocation, the core advantage of Pub/Sub is **decoupling** -- publishers and subscribers are unaware of each other's existence. This means:
>
> 1. Adding new consumers does not require modifying publisher code.
> 2. Removing consumers does not affect other parts.
> 3. The same event can have zero, one, or multiple consumers.
>
> Pub/Sub is widely used in GUI frameworks (such as DOM events), message queues (such as Kafka, RabbitMQ), and microservice architectures. OpenCode's event bus is a lightweight in-process Pub/Sub implementation.

## 11.1.1 BusEvent.define() -- Type-Safe Event Definition

The foundation of the event bus is event definition. OpenCode uses the `BusEvent.define()` factory function to create type-safe event definitions:

```typescript
// bus/bus-event.ts
export namespace BusEvent {
  export type Definition = ReturnType<typeof define>

  // Global event registry
  const registry = new Map<string, Definition>()

  export function define<Type extends string, Properties extends ZodType>(
    type: Type,
    properties: Properties
  ) {
    const result = {
      type,        // Event type identifier, e.g., "session.created"
      properties,  // Zod Schema defining the data structure carried by the event
    }
    registry.set(type, result)
    return result
  }
}
```

This design has several noteworthy characteristics:

**1. Type Inference**: `define()` uses generic parameters `<Type extends string, Properties extends ZodType>`, allowing the TypeScript compiler to infer the specific type literal from the call site. For example, the return type of `define("session.created", ...)` has `type` not as `string`, but as the literal type `"session.created"`. This provides precise type hints for subsequent subscription callbacks.

**2. Global Registry**: Every event created through `define()` is automatically registered in the global `registry` Map. This registry supports an important function -- the `payloads()` method:

```typescript
export function payloads() {
  return z.discriminatedUnion(
    "type",
    registry.entries().map(([type, def]) => {
      return z.object({
        type: z.literal(type),
        properties: def.properties,
      }).meta({ ref: "Event" + "." + def.type })
    }).toArray() as any,
  ).meta({ ref: "Event" })
}
```

`payloads()` combines all registered events into a Zod **Discriminated Union**. This means that by checking the value of the `type` field, the specific type of `properties` can be automatically inferred. This union type is used for automatic OpenAPI Schema generation -- the Server's SSE push endpoint can generate precise API documentation based on it.

**3. Event Naming Convention**: All event types follow a dot-separated naming convention of `module.action`, for example:

| Event Type             | Meaning                            |
| ---------------------- | ---------------------------------- |
| `session.created`      | A session was created              |
| `message.updated`      | A message was updated              |
| `mcp.tools.changed`    | The MCP tool list changed          |
| `file.watcher.updated` | A file change was detected         |
| `permission.asked`     | A permission request was initiated |

## 11.1.2 Bus.publish() -- Event Publishing

`Bus.publish()` is the core method for event publishing. Its implementation reveals the dual-layer broadcast mechanism of OpenCode's event bus:

```typescript
// bus/index.ts
export namespace Bus {
  export async function publish<Definition extends BusEvent.Definition>(
    def: Definition,
    properties: z.output<Definition["properties"]>,
  ) {
    const payload = {
      type: def.type,
      properties,
    }
    log.info("publishing", { type: def.type })

    // Layer 1: Local broadcast (Instance level)
    const pending = []
    for (const key of [def.type, "*"]) {
      const match = state().subscriptions.get(key)
      for (const sub of match ?? []) {
        pending.push(sub(payload))
      }
    }

    // Layer 2: Global broadcast (cross-Instance)
    GlobalBus.emit("event", {
      directory: Instance.directory,
      payload,
    })

    return Promise.all(pending)
  }
}
```

When an event is published, two things happen:

1. **Local Broadcast**: The subscription map of the current Instance is searched for matching subscribers, including exact matches (`def.type`) and wildcard matches (`"*"`). All matching callback functions are invoked concurrently, and their return values are aggregated via `Promise.all()`.
2. **Global Broadcast**: The event is forwarded to the global event channel via `GlobalBus.emit()`. GlobalBus is a simple Node.js `EventEmitter` responsible for cross-Instance event propagation:

```typescript
// bus/global.ts
import { EventEmitter } from "events"

export const GlobalBus = new EventEmitter<{
  event: [{
    directory?: string
    payload: any
  }]
}>()
```

The purpose of this dual-layer design is to support **multi-Instance concurrency** scenarios. When multiple Worktree instances are running simultaneously, subscribers within each Instance only receive events from their own Instance; while GlobalBus listeners (such as the Server's SSE push endpoint) can receive events from all Instances and route them based on the `directory` field.

## 11.1.3 Bus.subscribe() / Bus.once() -- Event Subscription

The event subscription API is concise and type-safe:

```typescript
// Persistent subscription
export function subscribe<Definition extends BusEvent.Definition>(
  def: Definition,
  callback: (event: {
    type: Definition["type"]
    properties: z.infer<Definition["properties"]>
  }) => void,
) {
  return raw(def.type, callback)
}

// One-time subscription (auto-unsubscribes when callback returns "done")
export function once<Definition extends BusEvent.Definition>(
  def: Definition,
  callback: (event: {
    type: Definition["type"]
    properties: z.infer<Definition["properties"]>
  }) => "done" | undefined,
) {
  const unsub = subscribe(def, (event) => {
    if (callback(event)) unsub()
  })
}
```

`subscribe()` returns an unsubscribe function that the caller can invoke at the appropriate time to cancel the subscription:

```typescript
// Usage example
const unsub = Bus.subscribe(Session.Event.Created, (event) => {
  console.log(`New session: ${event.properties.info.id}`)
})

// Unsubscribe when no longer needed
unsub()
```

`once()` is a wrapper around `subscribe()` -- when the callback returns the string `"done"`, the subscription is automatically cancelled. This is very useful in scenarios where you need to "wait for a specific event to occur."

## 11.1.4 Wildcard Subscription ("\*")

The `subscribeAll()` function allows subscribing to all events:

```typescript
export function subscribeAll(callback: (event: any) => void) {
  return raw("*", callback)
}
```

A typical use case for wildcard subscriptions is event forwarding. For example, the Server's SSE endpoint needs to push all events to clients -- it doesn't care about specific event types, it just needs to serialize the entire event payload as an SSE message.

The underlying `raw()` function handles both exact subscriptions and wildcard subscriptions uniformly:

```typescript
function raw(type: string, callback: (event: any) => void) {
  log.info("subscribing", { type })
  const subscriptions = state().subscriptions
  let match = subscriptions.get(type) ?? []
  match.push(callback)
  subscriptions.set(type, match)

  return () => {
    log.info("unsubscribing", { type })
    const match = subscriptions.get(type)
    if (!match) return
    const index = match.indexOf(callback)
    if (index === -1) return
    match.splice(index, 1)
  }
}
```

The subscription map uses `Map<string, Subscription[]>` for storage, where the key is the event type string (or `"*"`) and the value is an array of callback functions. When unsubscribing, the corresponding callback is found and removed via `indexOf`.

## 11.1.5 GlobalBus: Cross-Instance Global Event Channel

The implementation of `GlobalBus` is extremely concise -- it is simply an `EventEmitter` with type parameters:

```typescript
// bus/global.ts
export const GlobalBus = new EventEmitter<{
  event: [{
    directory?: string
    payload: any
  }]
}>()
```

It has only one event type `"event"`, and each event carries a `directory` (the working directory of the originating Instance) and a `payload` (the raw event data).

The main consumers of GlobalBus include:

1. **Server SSE Endpoint**: Pushes events to connected web clients.
2. **TUI Rendering Layer**: Listens to global events to update the terminal interface.
3. **Cross-Instance Coordination**: For example, when an Instance is destroyed, other components need to be notified.

Unlike `Bus` (Instance level), `GlobalBus` is a singleton object not bound to any Instance context. Events from all Instances converge here, and consumers filter for events they care about by checking the `directory` field.

## 11.1.6 Event Cleanup on Instance Destruction

The event bus's subscription map is managed using `Instance.state()`, which means that when an Instance is destroyed, all subscriptions for that Instance are automatically cleaned up. Additionally, the cleanup function sends an `InstanceDisposed` event to wildcard subscribers:

```typescript
const state = Instance.state(
  () => {
    // Initialization: create an empty subscription map
    const subscriptions = new Map<any, Subscription[]>()
    return { subscriptions }
  },
  async (entry) => {
    // Cleanup: notify wildcard subscribers that the Instance is being destroyed
    const wildcard = entry.subscriptions.get("*")
    if (!wildcard) return
    const event = {
      type: InstanceDisposed.type,
      properties: { directory: Instance.directory },
    }
    for (const sub of [...wildcard]) {
      sub(event)
    }
  },
)
```

The `InstanceDisposed` event itself is also defined via `BusEvent.define()`:

```typescript
export const InstanceDisposed = BusEvent.define(
  "server.instance.disposed",
  z.object({ directory: z.string() }),
)
```

This "automatic cleanup + final notification" pattern ensures that:

1. No residual subscribers continue to receive events after Instance destruction (preventing memory leaks).
2. Components that care about Instance lifecycle can execute cleanup logic upon destruction.

## 11.1.7 Summary

OpenCode's event bus is a concise yet comprehensive in-process Pub/Sub implementation. Its design can be summarized in the following key points:

| Feature               | Implementation                                                 |
| --------------------- | -------------------------------------------------------------- |
| Type Safety           | `BusEvent.define()` + Zod Schema + TypeScript Generics         |
| Event Registration    | Global `registry` Map, supporting automatic OpenAPI generation |
| Dual-Layer Broadcast  | Instance-level Bus + Global GlobalBus                          |
| Wildcard Subscription | `"*"` key matches all events                                   |
| Unsubscription        | Returns an unsubscribe function                                |
| Lifecycle Management  | Automatic cleanup via `Instance.state()`                       |
| Concurrency Safety    | Independent subscription maps per Instance                     |

The entire event bus implementation is under 150 lines of code (`bus-event.ts` 44 lines + `index.ts` 106 lines + `global.ts` 11 lines), yet it effectively decouples communication among 20+ modules in the system.
