hooks

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 13 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 AgentEndEvent added in v0.16.0

type AgentEndEvent struct {
	SessionID  string `json:"session_id,omitempty"`
	Success    bool   `json:"success"`
	Error      string `json:"error,omitempty"`
	Aborted    bool   `json:"aborted"`
	Response   string `json:"response,omitempty"`
	DurationMs int64  `json:"duration_ms"`
}

AgentEndEvent is the data for the agent.end lifecycle event. Classification: abort outranks error — a run cancelled by the caller reports Aborted=true with an empty Error, even when the cancellation surfaced as an error from a provider or tool call.

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"

	// EventAgentEnd fires exactly once when an agent run reaches any
	// terminal state: normal completion, error, or abort (context
	// cancellation). Aborted runs still settle through this event.
	EventAgentEnd EventType = "agent.end"

	// EventSessionRollover fires when a session automatically rolls over
	// (idle timeout or daily boundary) — as opposed to a manual clear,
	// which emits no rollover. It carries the ENDED session's transcript
	// so hooks can persist it before the fresh session begins.
	EventSessionRollover EventType = "session.rollover"
)

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 PromptTurn added in v0.16.0

type PromptTurn struct {
	// SessionID is the session the run belongs to (empty when the agent
	// runs without a session).
	SessionID string `json:"session_id,omitempty"`

	// Content is the user message that started the run.
	Content string `json:"content"`

	// Iteration is the zero-based tool-call loop iteration within the run.
	Iteration int `json:"iteration"`

	// Tools is the set of tool names currently available to the turn.
	Tools []string `json:"tools"`
}

PromptTurn describes an upcoming model turn for synchronous pre-turn hooks.

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). Concurrent async dispatches are bounded to prevent resource exhaustion. If the concurrency limit is reached, the dispatch is dropped with a warning. 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 SessionRolloverEvent added in v0.16.0

type SessionRolloverEvent struct {
	SessionID string `json:"session_id"`

	// Reason is the machine-readable rollover cause ("idle" or "daily").
	Reason string `json:"reason"`

	// Transcript holds the ended conversation as role/content pairs.
	Transcript []MessageEvent `json:"transcript"`

	// StartedAt is when the ended conversation began.
	StartedAt time.Time `json:"started_at"`

	// EndedAt is the ended conversation's last activity.
	EndedAt time.Time `json:"ended_at"`
}

SessionRolloverEvent is the data for the session.rollover event: an automatic session boundary. Transcript is a snapshot of the ended conversation, taken before the session is reset, so handlers can persist it without racing the reset.

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 ToolsAllowFunc added in v0.16.0

type ToolsAllowFunc func(ctx context.Context, turn PromptTurn) []string

ToolsAllowFunc is a synchronous pre-turn hook that can narrow the tools submitted to the model for a single turn. Unlike event hooks — which are asynchronous, fire-and-forget observers — its return value is consumed by the agent:

  • nil leaves the tool set unchanged
  • an empty slice removes all optional tools for this turn
  • a list of names narrows the set to its intersection with Tools

The hook runs on every loop iteration of a run, so narrowing applies per-turn and a later turn can widen again. It must not block: it runs on the request path before each model call.

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