event

package
v0.2.9 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2025 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package event provides a unified event system for streaming responses across client, agent, and workflow packages. The event types are designed for 1:1 mapping with the AG-UI protocol.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Emit

func Emit(ch chan<- Event, e Event)

emit sends an event with timestamp to the channel (non-blocking).

func EmitDelta added in v0.2.9

func EmitDelta(ch chan<- Event, patches ...JSONPatch)

EmitDelta sends a StateDelta event to the channel. Used internally by SharedState.Update().

func EmitField added in v0.2.9

func EmitField(ch chan<- Event, path string, value any)

EmitField sends a StateDelta event for a single field update. Used internally by SharedState.UpdateField().

func EmitMessagesSnapshot added in v0.2.9

func EmitMessagesSnapshot(ch chan<- Event, messages []ai.Message)

EmitMessagesSnapshot is a convenience function that sends a MessagesSnapshot event. Use this to sync the complete conversation history with the frontend:

event.EmitMessagesSnapshot(eventCh, conversation.Messages())

func EmitSnapshot added in v0.2.9

func EmitSnapshot(ch chan<- Event, state any)

EmitSnapshot sends a StateSnapshot event to the channel. Used internally by SharedState.Set().

func EmitToolApprovalApproved added in v0.2.9

func EmitToolApprovalApproved(ch chan<- Event, toolCallID string)

EmitToolApprovalApproved emits a tool approval approved activity update.

func EmitToolApprovalPending added in v0.2.9

func EmitToolApprovalPending(ch chan<- Event, toolCallID, toolName, arguments string)

EmitToolApprovalPending emits a tool approval pending activity.

func EmitToolApprovalRejected added in v0.2.9

func EmitToolApprovalRejected(ch chan<- Event, toolCallID, reason string)

EmitToolApprovalRejected emits a tool approval rejected activity update.

func EmitUserInputCancelled added in v0.2.9

func EmitUserInputCancelled(ch chan<- Event, requestID string)

EmitUserInputCancelled emits a user input cancelled activity update.

func EmitUserInputPending added in v0.2.9

func EmitUserInputPending(ch chan<- Event, requestID, inputType, title, message string, choices []string, defaultVal, placeholder string)

EmitUserInputPending emits a user input pending activity.

func EmitUserInputResponded added in v0.2.9

func EmitUserInputResponded(ch chan<- Event, requestID, value string, confirmed bool)

EmitUserInputResponded emits a user input responded activity update.

func EmitUserInputTimeout added in v0.2.9

func EmitUserInputTimeout(ch chan<- Event, requestID string)

EmitUserInputTimeout emits a user input timeout activity update.

func ForwardChannelFromContext added in v0.2.9

func ForwardChannelFromContext(ctx context.Context) chan<- Event

ForwardChannelFromContext retrieves the event forwarding channel from the context. Returns nil if no channel is set.

func NewChannel

func NewChannel() chan Event

NewChannel creates a buffered event channel with standard capacity.

func WithForwardChannel added in v0.2.9

func WithForwardChannel(ctx context.Context, ch chan<- Event) context.Context

WithForwardChannel returns a new context with the given event channel for forwarding. Tool handlers can use ForwardChannelFromContext to retrieve this channel and forward sub-run events to the parent event stream.

func WithSharedState added in v0.2.9

func WithSharedState(ctx context.Context, state *SharedState) context.Context

WithSharedState returns a new context with the shared state attached.

Types

type ActivityType added in v0.2.9

type ActivityType string

ActivityType categorizes activities for AG-UI ACTIVITY events.

const (
	// ActivityToolApproval indicates a tool call awaiting user approval.
	ActivityToolApproval ActivityType = "tool_approval"

	// ActivityLoading indicates a loading/processing state.
	ActivityLoading ActivityType = "loading"

	// ActivityUserInput indicates a request for user input.
	ActivityUserInput ActivityType = "user_input"
)

Activity type constants for human-in-the-loop interactions.

type ApprovalStatus added in v0.2.9

type ApprovalStatus string

ApprovalStatus represents the status of a tool approval request.

const (
	ApprovalPending  ApprovalStatus = "pending"
	ApprovalApproved ApprovalStatus = "approved"
	ApprovalRejected ApprovalStatus = "rejected"
)

Approval status constants.

type Event

type Event struct {
	// Type identifies the kind of event.
	Type Type

	// MessageID identifies the message for Start/Delta/End correlation.
	MessageID string

	// Delta contains streaming content for MessageDelta events.
	Delta string

	// Response contains the complete response for MessageEnd and RunEnd events.
	Response *ai.Response

	// ToolCall contains the tool call for tool-related events.
	ToolCall *ai.ToolCall

	// ToolResult contains the result for ToolCallResult events.
	ToolResult *ai.ToolResult

	// Step is the current iteration number (1-indexed) for agent events.
	Step int

	// StepName identifies the step for workflow events.
	StepName string

	// RouteName identifies the selected route for RouteSelected events.
	RouteName string

	// Iteration is the loop iteration (1-indexed) for LoopIteration events.
	Iteration int

	// Attempt is the retry attempt number (1-indexed) for retry events.
	Attempt int

	// Error contains the error for RunError events.
	Error error

	// Message contains additional context (e.g., rejection reason, termination reason).
	Message string

	// PendingToolCalls contains tool calls awaiting client-side execution.
	// Set on RunEnd events when termination is due to client tool calls.
	PendingToolCalls []ai.ToolCall

	// State contains the full state for StateSnapshot events.
	State any

	// StatePatches contains JSON Patch operations for StateDelta events.
	StatePatches []JSONPatch

	// Messages contains the complete message history for MessagesSnapshot events.
	Messages []ai.Message

	// Activity fields for ActivitySnapshot and ActivityDelta events.
	ActivityID      string       // Unique ID for activity correlation
	Activity        ActivityType // Type of activity (tool_approval, loading, etc.)
	ActivityContent any          // Content for the activity (e.g., ToolApprovalActivity)
	ActivityPatches []JSONPatch  // Patches for ActivityDelta events

	// Timestamp is when the event occurred.
	Timestamp time.Time
}

Event represents an observable occurrence during streaming execution. This unified type is used by client, agent, and workflow packages.

func NewActivityDelta added in v0.2.9

func NewActivityDelta(activityID string, activityType ActivityType, patches ...JSONPatch) Event

NewActivityDelta creates an ActivityDelta event. Use the same activityID as the corresponding ActivitySnapshot to update it.

func NewActivitySnapshot added in v0.2.9

func NewActivitySnapshot(activityID string, activityType ActivityType, content any) Event

NewActivitySnapshot creates an ActivitySnapshot event. The activityID should be unique for each activity instance and is used for correlation between snapshot and delta events.

func NewMessagesSnapshot added in v0.2.9

func NewMessagesSnapshot(messages []ai.Message) Event

NewMessagesSnapshot creates a MessagesSnapshot event with the given messages.

func NewStateDelta

func NewStateDelta(patches ...JSONPatch) Event

NewStateDelta creates a StateDelta event with the given patches.

func NewStateSnapshot

func NewStateSnapshot(state any) Event

NewStateSnapshot creates a StateSnapshot event with the given state.

func NewToolApprovalApproved added in v0.2.9

func NewToolApprovalApproved(toolCallID string) Event

NewToolApprovalApproved creates an ActivityDelta event to mark a tool as approved.

func NewToolApprovalPending added in v0.2.9

func NewToolApprovalPending(toolCallID, toolName, arguments string) Event

NewToolApprovalPending creates an ActivitySnapshot event for a pending tool approval. The frontend will display this as a tool approval request with approve/reject buttons.

func NewToolApprovalRejected added in v0.2.9

func NewToolApprovalRejected(toolCallID, reason string) Event

NewToolApprovalRejected creates an ActivityDelta event to mark a tool as rejected.

func NewUserInputCancelled added in v0.2.9

func NewUserInputCancelled(requestID string) Event

NewUserInputCancelled creates an ActivityDelta event to mark an input as cancelled.

func NewUserInputPending added in v0.2.9

func NewUserInputPending(requestID, inputType, title, message string, choices []string, defaultVal, placeholder string) Event

NewUserInputPending creates an ActivitySnapshot event for a pending user input request. The frontend will display this as an input dialog appropriate for the type.

func NewUserInputResponded added in v0.2.9

func NewUserInputResponded(requestID, value string, confirmed bool) Event

NewUserInputResponded creates an ActivityDelta event to mark an input as responded.

func NewUserInputTimeout added in v0.2.9

func NewUserInputTimeout(requestID string) Event

NewUserInputTimeout creates an ActivityDelta event to mark an input as timed out.

type ForwardChannel added in v0.2.9

type ForwardChannel = chan<- Event

ForwardChannel is the type of channel used for event forwarding.

type JSONPatch

type JSONPatch struct {
	Op    PatchOp `json:"op"`              // Operation type
	Path  string  `json:"path"`            // JSON Pointer path
	Value any     `json:"value,omitempty"` // Value for add, replace, test
	From  string  `json:"from,omitempty"`  // Source path for move, copy
}

JSONPatch represents a JSON Patch operation (RFC 6902).

func Add

func Add(path string, value any) JSONPatch

Add creates a JSON Patch add operation.

func Copy

func Copy(from, path string) JSONPatch

Copy creates a JSON Patch copy operation.

func Move

func Move(from, path string) JSONPatch

Move creates a JSON Patch move operation.

func Remove

func Remove(path string) JSONPatch

Remove creates a JSON Patch remove operation.

func Replace

func Replace(path string, value any) JSONPatch

Replace creates a JSON Patch replace operation.

func Test

func Test(path string, value any) JSONPatch

Test creates a JSON Patch test operation.

type PatchOp

type PatchOp string

PatchOp represents a JSON Patch operation type (RFC 6902).

const (
	PatchAdd     PatchOp = "add"
	PatchRemove  PatchOp = "remove"
	PatchReplace PatchOp = "replace"
	PatchMove    PatchOp = "move"
	PatchCopy    PatchOp = "copy"
	PatchTest    PatchOp = "test"
)

JSON Patch operation types.

type SharedState added in v0.2.9

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

SharedState holds the current shared state and provides thread-safe access. It tracks the current state and can emit updates via the event channel.

func NewSharedState added in v0.2.9

func NewSharedState(initial any) *SharedState

NewSharedState creates a new SharedState from the initial state. If initial is nil, creates an empty state.

func SharedStateFromContext added in v0.2.9

func SharedStateFromContext(ctx context.Context) *SharedState

SharedStateFromContext retrieves the shared state from the context. Returns nil if no shared state is attached.

func (*SharedState) Get added in v0.2.9

func (s *SharedState) Get() map[string]any

Get returns the current state as a map.

func (*SharedState) GetField added in v0.2.9

func (s *SharedState) GetField(path string) any

GetField returns a specific field from the state.

func (*SharedState) Set added in v0.2.9

func (s *SharedState) Set(ctx context.Context, newState map[string]any)

Set replaces the entire state and emits a STATE_SNAPSHOT event.

func (*SharedState) Update added in v0.2.9

func (s *SharedState) Update(ctx context.Context, patches ...JSONPatch)

Update updates specific fields and emits a STATE_DELTA event.

func (*SharedState) UpdateField added in v0.2.9

func (s *SharedState) UpdateField(ctx context.Context, path string, value any)

UpdateField is a convenience method to update a single field.

type ToolApprovalActivity added in v0.2.9

type ToolApprovalActivity struct {
	ToolCallID string         `json:"toolCallId"`
	ToolName   string         `json:"toolName"`
	Arguments  string         `json:"arguments"`
	Status     ApprovalStatus `json:"status"`
	Reason     string         `json:"reason,omitempty"` // Reason for rejection
}

ToolApprovalActivity represents the state of a tool approval request. This is the content structure for ActivityToolApproval events.

type Type

type Type string

Type identifies the kind of event.

const (
	// RunStart fires when execution begins (agent run, workflow run, or chat stream).
	RunStart Type = "run_start"

	// RunEnd fires when execution completes successfully.
	RunEnd Type = "run_end"

	// RunError fires when an unrecoverable error occurs.
	RunError Type = "run_error"
)

Run lifecycle events

const (
	// StepStart fires when a step begins.
	StepStart Type = "step_start"

	// StepEnd fires when a step completes.
	StepEnd Type = "step_end"

	// StepSkipped fires when a step is skipped (e.g., routing).
	StepSkipped Type = "step_skipped"
)

Step lifecycle events (agent/workflow only)

const (
	// MessageStart fires when an assistant message begins.
	MessageStart Type = "message_start"

	// MessageDelta fires for each streaming token.
	MessageDelta Type = "message_delta"

	// MessageEnd fires when an assistant message completes.
	MessageEnd Type = "message_end"
)

Message lifecycle events

const (
	// ToolCallStart fires when a tool call begins (contains tool name).
	ToolCallStart Type = "tool_call_start"

	// ToolCallArgs fires with tool call arguments.
	ToolCallArgs Type = "tool_call_args"

	// ToolCallEnd fires when tool call transmission is complete.
	ToolCallEnd Type = "tool_call_end"

	// ToolCallResult fires with the tool execution result.
	ToolCallResult Type = "tool_call_result"
)

Tool call lifecycle events

const (
	// ToolCallApproved fires when a tool call is approved (human-in-the-loop).
	ToolCallApproved Type = "tool_call_approved"

	// ToolCallRejected fires when a tool call is rejected.
	ToolCallRejected Type = "tool_call_rejected"

	// ToolCallExecuting fires before tool handler execution begins.
	ToolCallExecuting Type = "tool_call_executing"
)

Tool approval events (agent only)

const (
	// ParallelStart fires when parallel execution begins.
	ParallelStart Type = "parallel_start"

	// ParallelEnd fires when all parallel branches complete.
	ParallelEnd Type = "parallel_end"

	// RouteSelected fires when a route is chosen.
	RouteSelected Type = "route_selected"

	// LoopIteration fires at the start of each loop iteration.
	LoopIteration Type = "loop_iteration"
)

Workflow-specific events

const (
	// RetryAttempt fires when a retry attempt starts.
	RetryAttempt Type = "retry_attempt"

	// RetryFailed fires when an attempt fails (may or may not retry).
	RetryFailed Type = "retry_failed"

	// RetryScheduled fires when a retry is scheduled after a failure.
	RetryScheduled Type = "retry_scheduled"

	// RetrySuccess fires when an attempt succeeds.
	RetrySuccess Type = "retry_success"

	// RetryExhausted fires when all retry attempts are exhausted.
	RetryExhausted Type = "retry_exhausted"
)

Retry events

const (
	// StateSnapshot fires to send the complete state to the frontend.
	StateSnapshot Type = "state_snapshot"

	// StateDelta fires to send incremental state changes using JSON Patch.
	StateDelta Type = "state_delta"

	// MessagesSnapshot fires to send the complete message history to the frontend.
	MessagesSnapshot Type = "messages_snapshot"
)

State synchronization events (AG-UI shared state)

const (
	// ActivitySnapshot fires to send the complete activity state to the frontend.
	// Used for tool approval UI, loading states, and other transient activities.
	ActivitySnapshot Type = "activity_snapshot"

	// ActivityDelta fires to send incremental activity state changes.
	ActivityDelta Type = "activity_delta"
)

Activity events (AG-UI human-in-the-loop)

type UserInputActivity added in v0.2.9

type UserInputActivity struct {
	RequestID   string   `json:"requestId"`
	Type        string   `json:"type"` // "confirm", "text", "choice"
	Title       string   `json:"title,omitempty"`
	Message     string   `json:"message"`
	Choices     []string `json:"choices,omitempty"`
	Default     string   `json:"default,omitempty"`
	Placeholder string   `json:"placeholder,omitempty"`
	Status      string   `json:"status"` // "pending", "responded", "cancelled", "timeout"
	Value       string   `json:"value,omitempty"`
	Confirmed   bool     `json:"confirmed,omitempty"`
}

UserInputActivity represents the state of a user input request. This is the content structure for ActivityUserInput events.

Jump to

Keyboard shortcuts

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