events

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bus

type Bus struct {
	// contains filtered or unexported fields
}

Bus routes events to subscribers while preserving order and isolating subscriber failures. A single dispatch loop keeps ordering deterministic, while per-subscriber queues prevent one slow consumer from blocking others.

func NewBus

func NewBus(opts ...BusOption) *Bus

NewBus constructs an event bus and starts its dispatch loop immediately.

func (*Bus) Close

func (b *Bus) Close()

Close stops the dispatch loop and waits for all subscriptions to drain.

func (*Bus) Publish

func (b *Bus) Publish(evt Event) error

Publish enqueues an event for delivery. Ordering is preserved by the dispatch loop. De-duplication is applied if configured.

func (*Bus) Subscribe

func (b *Bus) Subscribe(t EventType, handler Handler, opts ...SubscriptionOption) func()

Subscribe registers a handler for a specific event type. It returns an unsubscribe function that is safe to call multiple times.

type BusOption

type BusOption func(*Bus)

BusOption configures a Bus.

func WithBufferSize

func WithBufferSize(size int) BusOption

WithBufferSize adjusts the per-subscriber fan-out buffer. Minimum 1.

func WithDedupWindow

func WithDedupWindow(limit int) BusOption

WithDedupWindow enables event de-duplication using a bounded LRU window.

func WithQueueDepth

func WithQueueDepth(depth int) BusOption

WithQueueDepth customizes the central publish queue capacity.

type ContextCompactedPayload

type ContextCompactedPayload struct {
	Summary               string `json:"summary"`
	OriginalMessages      int    `json:"original_messages"`
	PreservedMessages     int    `json:"preserved_messages"`
	EstimatedTokensBefore int    `json:"estimated_tokens_before"`
	EstimatedTokensAfter  int    `json:"estimated_tokens_after"`
}

ContextCompactedPayload is emitted after context compaction completes.

type Event

type Event struct {
	ID        string      // optional explicit identifier; generated when empty
	Type      EventType   // required
	Timestamp time.Time   // auto-populated when zero
	SessionID string      // optional session identifier for hook payloads
	RequestID string      // optional request identifier for distributed tracing
	Payload   interface{} // optional, type asserted by hook executors
}

Event represents a single occurrence in the system. It is intentionally lightweight; any structured payloads are stored in the Payload field.

func (Event) Validate

func (e Event) Validate() error

Validate performs cheap sanity checks for callers that need stronger contracts than the zero-value guarantees.

type EventType

type EventType string

EventType enumerates all hookable lifecycle events supported by the SDK. Keeping the list small and explicit prevents accidental proliferation of loosely defined event names.

const (
	PreToolUse         EventType = "PreToolUse"
	PostToolUse        EventType = "PostToolUse"
	PostToolUseFailure EventType = "PostToolUseFailure"
	PreCompact         EventType = "PreCompact"
	ContextCompacted   EventType = "ContextCompacted"
	UserPromptSubmit   EventType = "UserPromptSubmit"
	SessionStart       EventType = "SessionStart"
	SessionEnd         EventType = "SessionEnd"
	Stop               EventType = "Stop"
	SubagentStart      EventType = "SubagentStart"
	SubagentStop       EventType = "SubagentStop"
	Notification       EventType = "Notification"
	TokenUsage         EventType = "TokenUsage"
	PermissionRequest  EventType = "PermissionRequest"
	ModelSelected      EventType = "ModelSelected"
	MCPToolsChanged    EventType = "MCPToolsChanged"
)

type Handler

type Handler func(context.Context, Event)

Handler processes an incoming event.

type MCPToolDescriptor

type MCPToolDescriptor struct {
	Name         string
	Description  string
	InputSchema  any
	OutputSchema any
	Title        string
}

MCPToolDescriptor is a minimal copy of MCP tool metadata suitable for reacting to list-changed notifications without depending on the MCP SDK.

type MCPToolsChangedPayload

type MCPToolsChangedPayload struct {
	// Server identifies the MCP server that triggered the update. Callers should
	// treat this as an opaque identifier (often the connection spec/URL).
	Server string
	// SessionID is the MCP session identifier when available.
	SessionID string
	// Tools is the refreshed tool snapshot.
	Tools []MCPToolDescriptor
	// Error is set when refreshing tools failed.
	Error string
}

MCPToolsChangedPayload is emitted when an MCP server notifies the client that its tool list changed (notifications/tools/list_changed) and the client has refreshed its tool snapshot.

type ModelSelectedPayload

type ModelSelectedPayload struct {
	ToolName  string
	ModelTier string
	Reason    string
}

ModelSelectedPayload is emitted when a model is selected for tool execution.

type NotificationPayload

type NotificationPayload struct {
	Title            string
	Message          string
	NotificationType string // type of notification for matcher filtering
	Meta             map[string]any
}

NotificationPayload transports informational messages.

type PermissionDecisionType

type PermissionDecisionType string

PermissionDecisionType represents the decision from a permission request hook.

const (
	PermissionAllow PermissionDecisionType = "allow"
	PermissionDeny  PermissionDecisionType = "deny"
	PermissionAsk   PermissionDecisionType = "ask"
)

type PermissionRequestPayload

type PermissionRequestPayload struct {
	ToolName   string
	ToolParams map[string]any
	Reason     string // optional reason for the permission request
}

PermissionRequestPayload is emitted when a tool requests permission.

type PreCompactPayload

type PreCompactPayload struct {
	Trigger            string  `json:"trigger,omitempty"`
	CustomInstructions string  `json:"custom_instructions,omitempty"`
	EstimatedTokens    int     `json:"estimated_tokens"`
	TokenLimit         int     `json:"token_limit"`
	Threshold          float64 `json:"threshold"`
	PreserveCount      int     `json:"preserve_count"`
}

PreCompactPayload is emitted before automatic context compaction.

type SessionEndPayload

type SessionEndPayload struct {
	SessionID string
	Reason    string // reason for ending (e.g., "user_exit", "error")
	Metadata  map[string]any
}

SessionEndPayload is emitted when a session ends.

type SessionPayload

type SessionPayload struct {
	SessionID string
	Metadata  map[string]any
}

SessionPayload signals session lifecycle transitions (legacy, kept for backward compat).

type SessionStartPayload

type SessionStartPayload struct {
	SessionID string
	Source    string // entry point source (e.g., "cli", "api")
	Model     string // model being used
	AgentType string // agent type (e.g., "main", "subagent")
	Metadata  map[string]any
}

SessionStartPayload is emitted when a session starts.

type StopPayload

type StopPayload struct {
	Reason         string
	StopHookActive bool // whether a stop hook is currently active
}

StopPayload indicates a stop notification for the main agent.

type SubagentStartPayload

type SubagentStartPayload struct {
	Name      string
	AgentID   string         // unique identifier for the subagent instance
	AgentType string         // type of the subagent
	Metadata  map[string]any // optional metadata
}

SubagentStartPayload is emitted when a subagent starts.

type SubagentStopPayload

type SubagentStopPayload struct {
	Name           string
	Reason         string
	AgentID        string // unique identifier for the subagent instance
	AgentType      string // type of the subagent
	TranscriptPath string // path to the subagent transcript file
	StopHookActive bool   // whether a stop hook is currently active
}

SubagentStopPayload is emitted when a subagent stops independently.

type SubscriptionOption

type SubscriptionOption func(*subscriptionConfig)

SubscriptionOption configures per-subscription behaviour.

func WithSubscriptionTimeout

func WithSubscriptionTimeout(d time.Duration) SubscriptionOption

WithSubscriptionTimeout enforces a per-event timeout for the handler.

type TokenUsagePayload

type TokenUsagePayload struct {
	InputTokens   int64  `json:"input_tokens"`
	OutputTokens  int64  `json:"output_tokens"`
	TotalTokens   int64  `json:"total_tokens"`
	CacheCreation int64  `json:"cache_creation_input_tokens,omitempty"`
	CacheRead     int64  `json:"cache_read_input_tokens,omitempty"`
	Model         string `json:"model,omitempty"`
	SessionID     string `json:"session_id,omitempty"`
	RequestID     string `json:"request_id,omitempty"`
}

TokenUsagePayload reports model token usage for a completed run.

type ToolResultPayload

type ToolResultPayload struct {
	Name      string
	Params    map[string]any // original tool input params
	ToolUseID string         // matches the ToolUsePayload.ToolUseID
	Result    any
	Duration  time.Duration
	Err       error
}

ToolResultPayload is emitted after tool execution.

type ToolUsePayload

type ToolUsePayload struct {
	Name      string
	Params    map[string]any
	ToolUseID string // unique identifier for this tool use
}

ToolUsePayload is emitted before tool execution.

type UserPromptPayload

type UserPromptPayload struct {
	Prompt string
}

UserPromptPayload captures a user supplied prompt.

Jump to

Keyboard shortcuts

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