hooks

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package hooks provides event-driven extensibility for omniagent.

The hooks package supports three registration methods:

1. Quick handlers - WithHook(event, func) for simple function handlers 2. Compiled hooks - WithCompiledHook(hook) for complex, reusable hooks 3. Webhook handlers - YAML config for HTTP-based external integrations

Example Usage

agent, _ := agent.New(config,
    agent.WithHook(hooks.EventMessageReceived, func(ctx context.Context, e hooks.Event) error {
        msg := e.Data.(hooks.MessageEvent)
        log.Printf("Received: %s", msg.Content)
        return nil
    }),
)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Dispatcher

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

Dispatcher provides a convenient interface for emitting events.

func NewDispatcher

func NewDispatcher(registry *Registry) *Dispatcher

NewDispatcher creates a new dispatcher with the given registry.

func (*Dispatcher) Emit

func (d *Dispatcher) Emit(ctx context.Context, eventType EventType, data any) error

Emit creates and dispatches an event synchronously. Returns any error from handler execution.

func (*Dispatcher) EmitAsync

func (d *Dispatcher) EmitAsync(ctx context.Context, eventType EventType, data any)

EmitAsync creates and dispatches an event asynchronously. Errors are logged but not returned.

func (*Dispatcher) EmitAsyncWithSession

func (d *Dispatcher) EmitAsyncWithSession(ctx context.Context, eventType EventType, sessionID string, data any)

EmitAsyncWithSession creates and dispatches an event with a session ID asynchronously.

func (*Dispatcher) EmitWithSession

func (d *Dispatcher) EmitWithSession(ctx context.Context, eventType EventType, sessionID string, data any) error

EmitWithSession creates and dispatches an event with a session ID.

type Event

type Event struct {
	Type      EventType `json:"type"`
	Timestamp time.Time `json:"timestamp"`
	SessionID string    `json:"session_id,omitempty"`
	Data      any       `json:"data"`
}

Event represents an event in the hooks system.

func NewEvent

func NewEvent(eventType EventType, data any) Event

NewEvent creates a new event with the current timestamp.

func (Event) WithSessionID

func (e Event) WithSessionID(sessionID string) Event

WithSessionID returns a copy of the event with the session ID set.

type EventType

type EventType string

EventType identifies the type of event.

const (
	// EventMessageReceived fires when a user message is received.
	EventMessageReceived EventType = "message.received"

	// EventMessageSent fires when an assistant response is sent.
	EventMessageSent EventType = "message.sent"

	// EventToolCalled fires before a tool is executed.
	EventToolCalled EventType = "tool.called"

	// EventToolCompleted fires after a tool execution completes.
	EventToolCompleted EventType = "tool.completed"

	// EventSessionCreated fires when a new session is created.
	EventSessionCreated EventType = "session.created"

	// EventSessionUpdated fires when a session is updated.
	EventSessionUpdated EventType = "session.updated"

	// EventJobExecuted fires after a cron job runs.
	EventJobExecuted EventType = "job.executed"
)

Event types supported by the hooks system.

type HandlerConfig

type HandlerConfig struct {
	// Name is an optional identifier for the handler (used in logging).
	Name string

	// Events lists the event types this handler responds to.
	Events []EventType

	// Handler is the function to call when an event occurs.
	Handler HandlerFunc
}

HandlerConfig wraps a handler with configuration.

type HandlerFunc

type HandlerFunc func(ctx context.Context, event Event) error

HandlerFunc is the signature for quick hook handlers. It receives the context and event, and returns an error if handling fails.

type Hook

type Hook interface {
	// Name returns the hook identifier.
	Name() string

	// Events returns the event types this hook handles.
	Events() []EventType

	// Handle processes an event.
	Handle(ctx context.Context, event Event) error

	// Init initializes the hook. Called once at startup.
	Init(ctx context.Context) error

	// Close releases resources. Called on shutdown.
	Close() error
}

Hook is the interface for compiled hooks. Compiled hooks are complex, reusable event handlers that can maintain state and require initialization/cleanup.

Example Implementation

type AuditHook struct {
    logger *slog.Logger
}

func (h *AuditHook) Name() string { return "audit" }

func (h *AuditHook) Events() []EventType {
    return []EventType{EventMessageReceived, EventMessageSent}
}

func (h *AuditHook) Handle(ctx context.Context, event Event) error {
    h.logger.Info("event", "type", event.Type, "data", event.Data)
    return nil
}

func (h *AuditHook) Init(ctx context.Context) error { return nil }
func (h *AuditHook) Close() error { return nil }

type JobEvent

type JobEvent struct {
	JobID   string `json:"job_id"`
	JobName string `json:"job_name"`
	Success bool   `json:"success"`
}

JobEvent is the data for job events.

type MessageEvent

type MessageEvent struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

MessageEvent is the data for message events.

type Registry

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

Registry manages hook registrations and event dispatch.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new hook registry.

func (*Registry) Close

func (r *Registry) Close() error

Close releases resources for all registered hooks.

func (*Registry) Dispatch

func (r *Registry) Dispatch(ctx context.Context, event Event) error

Dispatch dispatches an event to all registered handlers synchronously. Returns the first error encountered, but continues dispatching to remaining handlers.

func (*Registry) DispatchAsync

func (r *Registry) DispatchAsync(ctx context.Context, event Event)

DispatchAsync dispatches an event asynchronously (fire-and-forget). Errors are logged but not returned.

func (*Registry) HandlerCount

func (r *Registry) HandlerCount(event EventType) int

HandlerCount returns the number of handlers registered for an event type.

func (*Registry) HookCount

func (r *Registry) HookCount() int

HookCount returns the total number of compiled hooks registered.

func (*Registry) Init

func (r *Registry) Init(ctx context.Context) error

Init initializes all registered hooks.

func (*Registry) RegisterHandler

func (r *Registry) RegisterHandler(event EventType, name string, handler HandlerFunc)

RegisterHandler registers a quick handler for an event type. The name is optional and used for logging.

func (*Registry) RegisterHook

func (r *Registry) RegisterHook(hook Hook) error

RegisterHook registers a compiled hook. The hook will be initialized when Init() is called on the registry.

func (*Registry) RegisterWebhook

func (r *Registry) RegisterWebhook(webhook *WebhookHook)

RegisterWebhook registers a webhook-based hook.

func (*Registry) SetStorage

func (r *Registry) SetStorage(s kvs.Store)

SetStorage sets the storage backend for storage-aware hooks.

type SessionEvent

type SessionEvent struct {
	SessionID string `json:"session_id"`
	Action    string `json:"action"` // created, updated
}

SessionEvent is the data for session events.

type StorageAware

type StorageAware interface {
	SetStorage(s kvs.Store)
}

StorageAware is an optional interface for hooks that need persistence. If a hook implements this interface, the registry will inject the storage backend after registration and before Init() is called.

type ToolEvent

type ToolEvent struct {
	Name   string         `json:"name"`
	Params map[string]any `json:"params,omitempty"`
	Result string         `json:"result,omitempty"`
	Error  string         `json:"error,omitempty"`
}

ToolEvent is the data for tool events.

type WebhookHook

type WebhookHook struct {
	// HookName is the identifier for this webhook.
	HookName string `json:"name" yaml:"name"`

	// HookEvents lists the event types this webhook receives.
	HookEvents []EventType `json:"events" yaml:"events"`

	// URL is the endpoint to send events to.
	URL string `json:"url" yaml:"url"`

	// Method is the HTTP method (POST or PUT). Defaults to POST.
	Method string `json:"method" yaml:"method"`

	// Headers are additional HTTP headers to send.
	Headers map[string]string `json:"headers" yaml:"headers"`

	// Timeout is the request timeout. Defaults to 10 seconds.
	Timeout time.Duration `json:"timeout" yaml:"timeout"`

	// RetryCount is the number of retries on failure. Defaults to 0.
	RetryCount int `json:"retry_count" yaml:"retry_count"`

	// RetryDelay is the delay between retries. Defaults to 1 second.
	RetryDelay time.Duration `json:"retry_delay" yaml:"retry_delay"`
	// contains filtered or unexported fields
}

WebhookHook sends events to an HTTP endpoint.

func (*WebhookHook) Close

func (w *WebhookHook) Close() error

Close implements Hook.

func (*WebhookHook) Events

func (w *WebhookHook) Events() []EventType

Events implements Hook.

func (*WebhookHook) Handle

func (w *WebhookHook) Handle(ctx context.Context, event Event) error

Handle implements Hook.

func (*WebhookHook) Init

func (w *WebhookHook) Init(_ context.Context) error

Init implements Hook.

func (*WebhookHook) Name

func (w *WebhookHook) Name() string

Name implements Hook.

Jump to

Keyboard shortcuts

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