pubsub

package
v0.8.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 5 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package pubsub implements the generic in-process event bus: one Broker[T] with three delivery classes — lossy Publish, bounded PublishMustDeliver, and coalescing by entity key — plus overflow notification for subscribers that must resync after a drop.

Delivery parameters: bufferSize 4096 per subscriber, must-deliver bound 50ms per subscriber, at most one pending event per coalescing key per subscriber.

Index

Constants

View Source
const (
	// BufferSize is the per-subscriber queue capacity.
	BufferSize = 4096
	// MustDeliverTimeout bounds the blocking send of PublishMustDeliver PER
	// SUBSCRIBER. A publisher with N stalled subscribers can wait
	// at most N times this bound, never unbounded.
	MustDeliverTimeout = 50 * time.Millisecond
)
View Source
const (
	// TypeMessage carries streaming message parts (deltas, tool arg previews).
	TypeMessage = "message"
	// TypePermissionRequest opens a permission prompt (publishes it).
	TypePermissionRequest = "permission_request"
	// TypePermissionNotification reports a prompt's state transitions.
	TypePermissionNotification = "permission_notification"
	// TypePermissionModeChanged reports a permission mode switch.
	TypePermissionModeChanged = "permission_mode_changed"
	// TypeRunComplete reports a finished turn/run.
	TypeRunComplete = "run_complete"
	// TypeSession carries session lifecycle/state changes.
	TypeSession = "session"
	// TypeAgentEvent carries agent notices, errors and tool events.
	TypeAgentEvent = "agent_event"
)

Wire-vocabulary discriminators. Every event that crosses a process boundary is {type, payload}; the tags are stable strings, additive only.

Variables

This section is empty.

Functions

func PublishPermissionModeChanged

func PublishPermissionModeChanged(ctx context.Context, b *Broker[PermissionModeChanged], change PermissionModeChanged)

PublishPermissionModeChanged publishes a mode switch. Must-deliver and unkeyed: observers must see every transition. Nil-safe for incremental wiring.

func PublishPermissionNotification

func PublishPermissionNotification(ctx context.Context, b *Broker[PermissionNotification], n PermissionNotification)

PublishPermissionNotification publishes a prompt state transition on the permission notification lane. Must-deliver and unkeyed: the UI must see every transition (open → granted/denied/cancelled), not just the latest. Nil-safe for incremental wiring.

func PublishPermissionRequest

func PublishPermissionRequest(ctx context.Context, b *Broker[PermissionRequest], req PermissionRequest)

PublishPermissionRequest publishes a prompt opening on the permission request lane. Must-deliver: a UI that never sees the prompt cannot answer it. Nil-safe so can wire it incrementally. No coalescing key: every request is a distinct prompt.

func Subscribe

func Subscribe[T any](b *Broker[T]) (<-chan Event[T], func())

Subscribe registers a subscriber and returns its event channel and an idempotent unsubscribe func. After Close the returned channel is already closed. The consumer must keep draining: a full queue drops lossy events.

func SubscribeWithOverflow

func SubscribeWithOverflow[T any](b *Broker[T]) (<-chan Event[T], <-chan struct{}, func())

SubscribeWithOverflow additionally returns a channel closed on the FIRST drop (lossy or must-deliver timeout), signalling that the subscriber missed events and should resync. It is not closed again on later drops.

Types

type Broker

type Broker[T any] struct {
	// contains filtered or unexported fields
}

Broker fans events out to subscribers. The zero value is not usable; call NewBroker. All methods are safe for concurrent use.

Structure: each subscriber owns a fixed-capacity ring of Event slots plus a key→sequence map. A publish with a coalescing key whose event is still queued OVERWRITES that slot in place (keeping its queue position); a new key or a keyless event appends at the tail. One pump goroutine per subscriber moves ring events to the subscriber's channel in FIFO order. An event already handed to the pump is in flight, not pending: coalescing applies to queued events, so a subscriber may see one in-flight event for a key followed by the coalesced latest — never two queued events for one key.

Drop counters are broker-wide atomics, queryable via DropCount and MustDeliverDropCount. Drops are silent (no logging dependency); the counters and the overflow channel are the observable signals.

func NewBroker

func NewBroker[T any]() *Broker[T]

NewBroker returns a broker with the default 4096-slot subscriber queues and 50ms must-deliver bound.

func NewBrokerWithBufferSize

func NewBrokerWithBufferSize[T any](size int) *Broker[T]

NewBrokerWithBufferSize returns a broker with a custom per-subscriber queue capacity (minimum 1). The must-deliver bound stays MustDeliverTimeout. Small capacities exist for contract tests and memory-constrained embedders.

func (*Broker[T]) Close

func (b *Broker[T]) Close()

Close stops delivery and closes every subscriber channel. It is idempotent; Publish and PublishMustDeliver afterwards are no-ops, and Subscribe returns an already-closed channel. Pumps exit promptly, so no goroutine outlives the broker.

func (*Broker[T]) DropCount

func (b *Broker[T]) DropCount() int64

DropCount reports lossy drops across all subscribers since creation.

func (*Broker[T]) MustDeliverDropCount

func (b *Broker[T]) MustDeliverDropCount() int64

MustDeliverDropCount reports must-deliver timeouts/cancellations across all subscribers since creation. A non-zero value means a terminal event was lost to a stalled subscriber — the overflow channel flags the same loss.

func (*Broker[T]) Publish

func (b *Broker[T]) Publish(ev Event[T])

Publish delivers ev to every subscriber without blocking. A subscriber whose queue is full drops the event and increments DropCount. Events with a non-empty Key coalesce: at most one queued event per key per subscriber, the newest overwriting in place at the old queue position. Publishing to a closed broker is a no-op.

func (*Broker[T]) PublishMustDeliver

func (b *Broker[T]) PublishMustDeliver(ctx context.Context, ev Event[T])

PublishMustDeliver delivers terminal events (turn end, tool result, error, exit, permission prompts). It first attempts a non-blocking enqueue per subscriber; a full queue gets a blocking retry bounded by MustDeliverTimeout PER SUBSCRIBER, honouring ctx. On timeout or cancellation the event is dropped for that subscriber and MustDeliverDropCount is incremented. The publisher is never blocked beyond the per-subscriber bound (plus scheduling), and a closed broker is a no-op.

func (*Broker[T]) Subscribe

func (b *Broker[T]) Subscribe() (<-chan Event[T], func())

Subscribe is the method form of Subscribe.

func (*Broker[T]) SubscribeWithOverflow

func (b *Broker[T]) SubscribeWithOverflow() (<-chan Event[T], <-chan struct{}, func())

SubscribeWithOverflow is the method form of SubscribeWithOverflow.

type Event

type Event[T any] struct {
	Type        string
	Key         string
	Payload     T
	MustDeliver bool
}

Event is one bus message. MustDeliver travels ON the event (not on the publish call) so fan-in re-publishers preserve the delivery class.

Type is the wire-vocabulary discriminator (see events.go); Key is the coalescing entity id — empty means the event never coalesces.

type PermissionModeChanged

type PermissionModeChanged struct {
	Mode     string `json:"mode"`
	Previous string `json:"previous,omitempty"`
}

PermissionModeChanged reports a permission mode switch (: mode changes publish on the bus). Previous is empty for the initial install.

type PermissionNotification

type PermissionNotification struct {
	ID        string `json:"id"`
	Tool      string `json:"tool,omitempty"`
	Granted   bool   `json:"granted"`
	Denied    bool   `json:"denied"`
	Cancelled bool   `json:"cancelled"`
	// Reason carries denial/cancellation detail (additive).
	Reason string `json:"reason,omitempty"`
}

PermissionNotification is the prompt state machine the UI renders: all three flags false means a prompt is OPEN; exactly one of Granted, Denied, Cancelled is true once it resolves. Cancelled means the turn was cancelled while the prompt was open.

func (PermissionNotification) Open

func (n PermissionNotification) Open() bool

Open reports whether the notification describes an open prompt (the all-false state).

type PermissionRequest

type PermissionRequest struct {
	ID          string          `json:"id"`
	Tool        string          `json:"tool"`
	Action      string          `json:"action,omitempty"`
	Args        json.RawMessage `json:"args,omitempty"`
	Description string          `json:"description,omitempty"`
	Danger      bool            `json:"danger,omitempty"`
	// DangerReason carries the classifier's human-readable reason.
	DangerReason string `json:"danger_reason,omitempty"`
	SessionID    string `json:"session_id,omitempty"`
	ToolCallID   string `json:"tool_call_id,omitempty"`
	Path         string `json:"path,omitempty"`
	GrantKey     string `json:"grant_key,omitempty"`
}

PermissionRequest is the payload of a permission prompt. defined the shape and lanes; adds the keyed-grant fields and starts publishing it from the approval gate. Args is the raw tool-call JSON the user is asked to approve — the same bytes the gate already presents, so redaction stays the gate's job.

The wire uses `tool`/`args` field names; the shape is the published contract and the schema is additive-only. Path is normalized to a DIRECTORY and GrantKey narrows the grant (shell tools: the command string).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL