hooks

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package hooks implements fan-out hooks for runtime observability and memory.

The hooks package provides an event bus that enables the runtime to publish lifecycle events (workflow start/completion, tool execution, planner notes) to multiple subscribers. This decouples event producers (workflows, planners, tool executors) from consumers (memory stores, streaming sinks, telemetry).

The primary types are:

  • Bus: the event bus interface for publishing and subscribing
  • Event: the event payload carrying type, IDs, and metadata
  • Subscriber: the interface implementations must satisfy to receive events
  • Subscription: a handle for unregistering from the bus

Typical usage pattern:

bus := hooks.NewBus()

// Register a subscriber
sub := hooks.SubscriberFunc(func(ctx context.Context, evt hooks.Event) error {
    if evt.Type == hooks.WorkflowStarted {
        fmt.Printf("Workflow %s started\n", evt.RunID)
    }
    return nil
})
subscription, _ := bus.Register(sub)
defer subscription.Close()

// Publish events
bus.Publish(ctx, hooks.Event{
    Type:    hooks.WorkflowStarted,
    RunID:   "run-123",
    AgentID: "chat-agent",
})

Index

Constants

View Source
const (
	// ErrorKindTimeout indicates the run failed because a required operation timed out.
	ErrorKindTimeout = "timeout"

	// ErrorKindInternal indicates the run failed for an unclassified reason.
	ErrorKindInternal = "internal"
)

Variables

View Source
var (
	// PublicErrorTimeout is emitted when a run fails due to a timeout (provider or runtime).
	PublicErrorTimeout = "The request timed out. Please retry."

	// PublicErrorInternal is emitted when a run fails for an unclassified reason.
	PublicErrorInternal = "The request failed. Please retry."

	// PublicErrorProviderRateLimited is emitted when the model provider is throttling requests.
	PublicErrorProviderRateLimited = "The AI provider is rate-limiting requests. Please wait a moment and retry."

	// PublicErrorProviderUnavailable is emitted when the model provider is temporarily unavailable.
	PublicErrorProviderUnavailable = "The AI provider is temporarily unavailable. Please retry."

	// PublicErrorProviderInvalidRequest is emitted when the provider rejects the request as invalid.
	PublicErrorProviderInvalidRequest = "The AI provider rejected the request."

	// PublicErrorProviderAuth is emitted when provider authentication/authorization fails.
	PublicErrorProviderAuth = "The AI provider authentication failed."

	// PublicErrorProviderUnknown is emitted for unclassified provider failures.
	PublicErrorProviderUnknown = "The AI provider returned an unexpected error. Please retry."

	// PublicErrorProviderDefault is emitted when a provider failure does not match any known kind.
	PublicErrorProviderDefault = "The AI provider returned an error. Please retry."
)

This file defines the user-facing error messages emitted by the runtime.

Callers may override these variables at process startup (before the runtime begins emitting events) to customize UX text without forking loom-mcp.

Contract: - These messages are intended to be rendered directly in UIs. - Do not mutate these values concurrently with active runs.

Functions

func WrapRunCompletionError

func WrapRunCompletionError(err error) error

WrapRunCompletionError encodes provider failures into a Temporal application error envelope so Wait()/Get()-based terminal paths can recover structured provider metadata after the workflow engine serializes the error.

Types

type ActivityInput

type ActivityInput struct {
	// Type identifies the hook event variant (for example, ToolCallScheduled).
	Type EventType

	// EventKey is the stable logical identity for this event within the run.
	EventKey string

	// RunID identifies the run that owns this event.
	RunID string

	// AgentID identifies the agent that owns this event.
	AgentID agent.Ident

	// SessionID identifies the logical session that owns this event.
	SessionID string

	// TurnID groups events for a single conversational turn. Empty when turn tracking is disabled.
	TurnID string

	// TimestampMS records when the event originally occurred.
	TimestampMS int64

	// Payload holds event-specific fields encoded as JSON.
	Payload rawjson.Message
}

ActivityInput describes a hook event emitted from workflow code and published by the hook activity. Payload contains the event-specific fields encoded as JSON.

func EncodeToHookInput

func EncodeToHookInput(evt Event, turnID string) (*ActivityInput, error)

EncodeToHookInput creates a hook activity input envelope from a hook event for serialization and transport to the hook activity.

type AssistantMessageEvent

type AssistantMessageEvent struct {

	// Message is the textual content of the assistant's response.
	Message string
	// Structured contains optional typed output (e.g., Pydantic-style structured data).
	// Nil if only a text message is provided.
	Structured any
	// contains filtered or unexported fields
}

AssistantMessageEvent fires when a final assistant response is produced, indicating the workflow is completing with a user-facing message.

func NewAssistantMessageEvent

func NewAssistantMessageEvent(runID string, agentID agent.Ident, sessionID string, message string, structured any) *AssistantMessageEvent

NewAssistantMessageEvent constructs an AssistantMessageEvent. Structured may be nil if only a text message is provided.

func (AssistantMessageEvent) AgentID

func (e AssistantMessageEvent) AgentID() string

AgentID returns the agent identifier.

func (AssistantMessageEvent) EventKey

func (e AssistantMessageEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (AssistantMessageEvent) RunID

func (e AssistantMessageEvent) RunID() string

RunID returns the workflow run identifier.

func (AssistantMessageEvent) SessionID

func (e AssistantMessageEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*AssistantMessageEvent) SetEventKey

func (e *AssistantMessageEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*AssistantMessageEvent) SetSessionID

func (e *AssistantMessageEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*AssistantMessageEvent) SetTimestampMS

func (e *AssistantMessageEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*AssistantMessageEvent) SetTurnID

func (e *AssistantMessageEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (AssistantMessageEvent) Timestamp

func (e AssistantMessageEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (AssistantMessageEvent) TurnID

func (e AssistantMessageEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*AssistantMessageEvent) Type

func (e *AssistantMessageEvent) Type() EventType

type AwaitClarificationEvent

type AwaitClarificationEvent struct {

	// ID correlates this await with a subsequent ProvideClarification.
	ID string
	// Question is the prompt to present to the user.
	Question string
	// MissingFields optionally lists fields needed to proceed.
	MissingFields []string
	// RestrictToTool optionally narrows the next turn to a specific tool.
	RestrictToTool tools.Ident
	// ExampleInput optionally provides a schema-compliant example.
	ExampleInput map[string]any
	// contains filtered or unexported fields
}

AwaitClarificationEvent indicates the planner requested a human-provided clarification before continuing execution.

func NewAwaitClarificationEvent

func NewAwaitClarificationEvent(runID string, agentID agent.Ident, sessionID, id, question string, missing []string, restrict tools.Ident, example map[string]any) *AwaitClarificationEvent

NewAwaitClarificationEvent constructs an AwaitClarificationEvent with the provided details.

func (AwaitClarificationEvent) AgentID

func (e AwaitClarificationEvent) AgentID() string

AgentID returns the agent identifier.

func (AwaitClarificationEvent) EventKey

func (e AwaitClarificationEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (AwaitClarificationEvent) RunID

func (e AwaitClarificationEvent) RunID() string

RunID returns the workflow run identifier.

func (AwaitClarificationEvent) SessionID

func (e AwaitClarificationEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*AwaitClarificationEvent) SetEventKey

func (e *AwaitClarificationEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*AwaitClarificationEvent) SetSessionID

func (e *AwaitClarificationEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*AwaitClarificationEvent) SetTimestampMS

func (e *AwaitClarificationEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*AwaitClarificationEvent) SetTurnID

func (e *AwaitClarificationEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (AwaitClarificationEvent) Timestamp

func (e AwaitClarificationEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (AwaitClarificationEvent) TurnID

func (e AwaitClarificationEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*AwaitClarificationEvent) Type

Type implements Event for AwaitClarificationEvent.

type AwaitConfirmationEvent

type AwaitConfirmationEvent struct {

	// ID correlates this await with a subsequent confirmation decision.
	ID string
	// Title is an optional display title for the confirmation UI.
	Title string
	// Prompt is the operator-facing confirmation prompt.
	Prompt string
	// ToolName identifies the tool that requires confirmation.
	ToolName tools.Ident
	// ToolCallID is the tool_call_id for the pending tool call.
	ToolCallID string
	// Payload is the canonical JSON arguments for the pending tool call.
	Payload rawjson.Message
	// contains filtered or unexported fields
}

AwaitConfirmationEvent indicates the runtime requested an explicit operator confirmation before executing a sensitive tool call.

func NewAwaitConfirmationEvent

func NewAwaitConfirmationEvent(runID string, agentID agent.Ident, sessionID, id, title, prompt string, toolName tools.Ident, toolCallID string, payload rawjson.Message) *AwaitConfirmationEvent

NewAwaitConfirmationEvent constructs an AwaitConfirmationEvent with the provided details.

func (AwaitConfirmationEvent) AgentID

func (e AwaitConfirmationEvent) AgentID() string

AgentID returns the agent identifier.

func (AwaitConfirmationEvent) EventKey

func (e AwaitConfirmationEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (AwaitConfirmationEvent) RunID

func (e AwaitConfirmationEvent) RunID() string

RunID returns the workflow run identifier.

func (AwaitConfirmationEvent) SessionID

func (e AwaitConfirmationEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*AwaitConfirmationEvent) SetEventKey

func (e *AwaitConfirmationEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*AwaitConfirmationEvent) SetSessionID

func (e *AwaitConfirmationEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*AwaitConfirmationEvent) SetTimestampMS

func (e *AwaitConfirmationEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*AwaitConfirmationEvent) SetTurnID

func (e *AwaitConfirmationEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (AwaitConfirmationEvent) Timestamp

func (e AwaitConfirmationEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (AwaitConfirmationEvent) TurnID

func (e AwaitConfirmationEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*AwaitConfirmationEvent) Type

Type implements Event for AwaitConfirmationEvent.

type AwaitExternalToolsEvent

type AwaitExternalToolsEvent struct {

	// ID correlates this await with a subsequent ProvideToolResults.
	ID string
	// Items enumerate the external tool calls to be satisfied.
	Items []AwaitToolItem
	// contains filtered or unexported fields
}

AwaitExternalToolsEvent indicates the planner requested external tool execution.

func NewAwaitExternalToolsEvent

func NewAwaitExternalToolsEvent(runID string, agentID agent.Ident, sessionID, id string, items []AwaitToolItem) *AwaitExternalToolsEvent

NewAwaitExternalToolsEvent constructs an AwaitExternalToolsEvent.

func (AwaitExternalToolsEvent) AgentID

func (e AwaitExternalToolsEvent) AgentID() string

AgentID returns the agent identifier.

func (AwaitExternalToolsEvent) EventKey

func (e AwaitExternalToolsEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (AwaitExternalToolsEvent) RunID

func (e AwaitExternalToolsEvent) RunID() string

RunID returns the workflow run identifier.

func (AwaitExternalToolsEvent) SessionID

func (e AwaitExternalToolsEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*AwaitExternalToolsEvent) SetEventKey

func (e *AwaitExternalToolsEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*AwaitExternalToolsEvent) SetSessionID

func (e *AwaitExternalToolsEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*AwaitExternalToolsEvent) SetTimestampMS

func (e *AwaitExternalToolsEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*AwaitExternalToolsEvent) SetTurnID

func (e *AwaitExternalToolsEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (AwaitExternalToolsEvent) Timestamp

func (e AwaitExternalToolsEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (AwaitExternalToolsEvent) TurnID

func (e AwaitExternalToolsEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*AwaitExternalToolsEvent) Type

Type implements Event for AwaitExternalToolsEvent.

type AwaitQuestion

type AwaitQuestion struct {
	ID            string
	Prompt        string
	Options       []AwaitQuestionOption
	AllowMultiple bool
}

AwaitQuestion describes a single multiple-choice question.

type AwaitQuestionOption

type AwaitQuestionOption struct {
	ID    string
	Label string
}

AwaitQuestionOption describes a selectable answer option.

type AwaitQuestionsEvent

type AwaitQuestionsEvent struct {

	// ID correlates this await with a subsequent ProvideToolResults.
	ID string
	// ToolName identifies the tool awaiting user answers.
	ToolName tools.Ident
	// ToolCallID correlates the provided result with this requested call.
	ToolCallID string
	// Payload is the canonical JSON arguments for the awaited tool call.
	Payload rawjson.Message
	// Title is an optional display title for the questions UI.
	Title *string
	// Questions are the structured questions to present to the user.
	Questions []AwaitQuestion
	// contains filtered or unexported fields
}

AwaitQuestionsEvent indicates the planner requested structured multiple-choice answers to be provided out-of-band (typically by a UI) before the run can resume.

func NewAwaitQuestionsEvent

func NewAwaitQuestionsEvent(runID string, agentID agent.Ident, sessionID, id string, toolName tools.Ident, toolCallID string, payload rawjson.Message, title *string, questions []AwaitQuestion) *AwaitQuestionsEvent

NewAwaitQuestionsEvent constructs an AwaitQuestionsEvent for a structured questions prompt.

func (AwaitQuestionsEvent) AgentID

func (e AwaitQuestionsEvent) AgentID() string

AgentID returns the agent identifier.

func (AwaitQuestionsEvent) EventKey

func (e AwaitQuestionsEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (AwaitQuestionsEvent) RunID

func (e AwaitQuestionsEvent) RunID() string

RunID returns the workflow run identifier.

func (AwaitQuestionsEvent) SessionID

func (e AwaitQuestionsEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*AwaitQuestionsEvent) SetEventKey

func (e *AwaitQuestionsEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*AwaitQuestionsEvent) SetSessionID

func (e *AwaitQuestionsEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*AwaitQuestionsEvent) SetTimestampMS

func (e *AwaitQuestionsEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*AwaitQuestionsEvent) SetTurnID

func (e *AwaitQuestionsEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (AwaitQuestionsEvent) Timestamp

func (e AwaitQuestionsEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (AwaitQuestionsEvent) TurnID

func (e AwaitQuestionsEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*AwaitQuestionsEvent) Type

func (e *AwaitQuestionsEvent) Type() EventType

Type implements Event for AwaitQuestionsEvent.

type AwaitToolItem

type AwaitToolItem struct {
	ToolName   tools.Ident
	ToolCallID string
	Payload    rawjson.Message
}

AwaitToolItem describes a single external tool call to be executed out-of-band.

type Bus

type Bus interface {
	// Publish delivers the event to every currently registered subscriber.
	// Subscribers are invoked in registration order, and iteration stops at
	// the first error returned by any subscriber.
	//
	// The context is forwarded to each subscriber's HandleEvent method.
	Publish(ctx context.Context, event Event) error

	// Register adds a subscriber to the bus and returns a Subscription that
	// can be closed to unregister. Register returns an error if sub is nil.
	Register(sub Subscriber) (Subscription, error)
}

Bus publishes runtime events to registered subscribers in a fan-out pattern. The bus is thread-safe and supports concurrent Publish, Register, and Close operations.

Events are delivered synchronously in the publisher's goroutine, and iteration stops at the first subscriber error. This fail-fast behavior ensures critical subscribers (e.g., memory persistence) can halt execution if they encounter unrecoverable errors.

func NewBus

func NewBus() Bus

NewBus constructs a new in-memory event bus for publishing runtime events to subscribers. The returned bus is thread-safe and ready for immediate use.

The bus implements a synchronous fan-out pattern: when Publish is called, each registered subscriber receives the event in registration order. If any subscriber returns an error, iteration stops immediately and that error is returned to the publisher.

Typical usage:

bus := hooks.NewBus()
sub := hooks.SubscriberFunc(func(ctx context.Context, evt hooks.Event) error {
    log.Printf("received: %s", evt.Type)
    return nil
})
subscription, _ := bus.Register(sub)
defer subscription.Close()

bus.Publish(ctx, hooks.Event{Type: hooks.WorkflowStarted})

type ChildRunLinkedEvent

type ChildRunLinkedEvent struct {

	// ToolName is the canonical tool identifier for the parent tool.
	ToolName tools.Ident
	// ToolCallID is the parent tool call identifier.
	ToolCallID string
	// ChildRunID is the run identifier of the nested agent execution.
	ChildRunID string
	// ChildAgentID is the identifier of the nested agent.
	ChildAgentID agent.Ident
	// contains filtered or unexported fields
}

ChildRunLinkedEvent links a parent run/tool call to a spawned child agent run. It is emitted on the parent run and allows consumers to correlate child-run events without flattening them into the parent.

func NewChildRunLinkedEvent

func NewChildRunLinkedEvent(runID string, agentID agent.Ident, sessionID string, toolName tools.Ident, toolCallID, childRunID string, childAgentID agent.Ident) *ChildRunLinkedEvent

NewChildRunLinkedEvent constructs a ChildRunLinkedEvent for the given parent run, tool call, and child run identifiers.

func (ChildRunLinkedEvent) AgentID

func (e ChildRunLinkedEvent) AgentID() string

AgentID returns the agent identifier.

func (ChildRunLinkedEvent) EventKey

func (e ChildRunLinkedEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (ChildRunLinkedEvent) RunID

func (e ChildRunLinkedEvent) RunID() string

RunID returns the workflow run identifier.

func (ChildRunLinkedEvent) SessionID

func (e ChildRunLinkedEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*ChildRunLinkedEvent) SetEventKey

func (e *ChildRunLinkedEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*ChildRunLinkedEvent) SetSessionID

func (e *ChildRunLinkedEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*ChildRunLinkedEvent) SetTimestampMS

func (e *ChildRunLinkedEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*ChildRunLinkedEvent) SetTurnID

func (e *ChildRunLinkedEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (ChildRunLinkedEvent) Timestamp

func (e ChildRunLinkedEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (ChildRunLinkedEvent) TurnID

func (e ChildRunLinkedEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*ChildRunLinkedEvent) Type

func (e *ChildRunLinkedEvent) Type() EventType

type Event

type Event interface {
	// Type returns the specific event type constant (e.g., RunStarted, ToolCallScheduled).
	// Subscribers use this to filter events or route to specific handlers without
	// type assertions.
	Type() EventType
	// RunID returns the unique identifier for the workflow run that produced this event.
	// All events within a single run execution share the same run ID. This allows
	// correlation across distributed systems and enables filtering events by run.
	RunID() string
	// SessionID returns the logical session identifier associated with the run.
	// All events for a given run share the same session ID, providing a stable
	// join key across processes and transports.
	SessionID() string
	// AgentID returns the agent identifier that triggered this event. Subscribers can
	// use this to filter events by agent when multiple agents run in the same system.
	AgentID() string
	// Timestamp returns the Unix timestamp in milliseconds when the event occurred.
	// Events are timestamped at creation, not at delivery, so subscribers can calculate
	// durations and latencies between related events.
	Timestamp() int64
	// EventKey returns the stable logical identity for this event within the run.
	// Durable stores use it to make canonical event publishing exact-once even when
	// the hook activity is retried.
	EventKey() string
	// TurnID returns the conversational turn identifier if turn tracking is active,
	// empty string otherwise. A turn groups events for a single user interaction cycle
	// (e.g., from user message through final assistant response). UI systems use this
	// to render threaded conversations.
	TurnID() string
}

Event is the interface all hook events must implement. The runtime publishes events through the Bus, and subscribers receive them via HandleEvent. Concrete event types carry typed payloads for each lifecycle phase.

Subscribers use type switches to access event-specific fields:

func (s *MySubscriber) HandleEvent(ctx context.Context, evt Event) error {
    switch e := evt.(type) {
    case *WorkflowStartedEvent:
        log.Printf("Context: %+v", e.RunContext)
    case *ToolResultReceivedEvent:
        log.Printf("Tool %s took %v", e.ToolName, e.Duration)
    }
    return nil
}

func DecodeFromHookInput

func DecodeFromHookInput(input *ActivityInput) (Event, error)

DecodeFromHookInput reconstructs a hooks.Event from the serialized hook input.

type EventType

type EventType string

EventType enumerates well-known runtime events broadcast on the hook bus. Each type corresponds to a specific phase in the agent workflow lifecycle.

const (
	// RunStarted fires when a run begins execution. The Payload
	// typically contains the initial RunContext and input parameters.
	RunStarted EventType = "run_started"

	// RunCompleted fires after a run finishes, whether successfully
	// or with a failure. The Payload contains final status and any error details.
	RunCompleted EventType = "run_completed"

	// RunPaused fires when execution is suspended awaiting external action.
	RunPaused EventType = "run_paused"

	// AwaitClarification fires when the planner requests a human clarification.
	AwaitClarification EventType = "await_clarification"

	// AwaitQuestions fires when the planner requests structured multiple-choice user input.
	AwaitQuestions EventType = "await_questions"

	// AwaitConfirmation fires when the runtime requests operator confirmation.
	AwaitConfirmation EventType = "await_confirmation"

	// AwaitExternalTools fires when the planner requests external tools to run out-of-band.
	AwaitExternalTools EventType = "await_external_tools"

	// ToolAuthorization fires when an operator provides an explicit approval/denial
	// decision for a pending tool call.
	ToolAuthorization EventType = "tool_authorization"

	// RunResumed fires when a previously paused run resumes execution.
	RunResumed EventType = "run_resumed"

	// ToolCallScheduled fires when the runtime schedules a tool activity for
	// execution. The Payload contains the tool name, arguments, and queue metadata.
	ToolCallScheduled EventType = "tool_call_scheduled"

	// ToolCallArgsDelta fires when a provider streams an incremental tool-call
	// argument fragment while constructing the final tool input JSON.
	//
	// Naming note: This is an args *delta* (not a “tool call” in itself). The
	// fragment may not be valid JSON and must not be treated as canonical.
	//
	// This event is best-effort and intended for streaming UX only. Consumers
	// may ignore it entirely; the canonical tool payload is still emitted via
	// ToolCallScheduled and the final tool call completion events.
	ToolCallArgsDelta EventType = "tool_call_args_delta"

	// ToolResultReceived fires when a tool activity completes and returns a
	// result or error. The Payload contains the tool name, result, duration,
	// and any execution errors.
	ToolResultReceived EventType = "tool_result_received"

	// ToolCallUpdated fires when a tool call's metadata is updated, typically
	// when a parent tool (agent-as-tool) dynamically discovers additional child
	// tools. The Payload contains the updated expected child count.
	ToolCallUpdated EventType = "tool_call_updated"

	// PlannerNote fires when the planner emits an annotation or intermediate
	// thought. The Payload contains the note text and optional labels for
	// categorization.
	PlannerNote EventType = "planner_note"

	// ThinkingBlock fires when the planner emits a structured thinking block
	// (signed plaintext or redacted bytes). Payload is a ThinkingBlockEvent.
	ThinkingBlock EventType = "thinking_block"

	// AssistantMessage fires when a final assistant response is produced,
	// indicating the workflow is completing with a user-facing message. The
	// Payload contains the message content and any structured output.
	AssistantMessage EventType = "assistant_message"

	// RetryHintIssued fires when the planner or runtime suggests a retry
	// policy change, such as disabling a failing tool or adjusting caps.
	// The Payload contains the hint reason and affected tool metadata.
	RetryHintIssued EventType = "retry_hint"

	// MemoryAppended fires when new memory entries are successfully persisted
	// to the memory store. The Payload may contain the event IDs or counts
	// for observability.
	MemoryAppended EventType = "memory_appended"

	// PolicyDecision fires when a policy engine returns a decision for the turn.
	PolicyDecision EventType = "policy_decision"

	// Usage reports token usage for a model invocation within a run.
	Usage EventType = "usage"

	// HardProtectionTriggered fires when a runtime hard protection is applied to
	// avoid pathological behavior (e.g., agent-tool produced no child calls).
	// Payload is a HardProtectionEvent.
	HardProtectionTriggered EventType = "hard_protection_triggered"

	// RunPhaseChanged fires when a run transitions between lifecycle phases
	// (prompted, planning, executing_tools, synthesizing, completed, failed,
	// canceled). Payload is a RunPhaseChangedEvent.
	RunPhaseChanged EventType = "run_phase_changed"

	// ChildRunLinked links a parent run/tool call to a spawned child agent run.
	// Payload is a ChildRunLinkedEvent.
	ChildRunLinked EventType = "child_run_linked"

	// PromptRendered fires when the runtime resolves and renders a prompt
	// template for a run.
	PromptRendered EventType = "prompt_rendered"
)

type HardProtectionEvent

type HardProtectionEvent struct {

	// Reason is a fixed string describing the protection that was applied.
	// Example: "agent_tool_no_children".
	Reason string
	// ExecutedAgentTools is the number of agent-as-tool executions in the turn.
	ExecutedAgentTools int
	// ChildrenTotal is the total number of child tool calls produced by those
	// agent tools (typically zero when this event fires).
	ChildrenTotal int
	// ToolNames lists the agent-tool identifiers executed in the turn.
	ToolNames []tools.Ident
	// contains filtered or unexported fields
}

HardProtectionEvent signals that the runtime applied a hard protection to avoid a pathological loop or expensive no-op behavior. For example, when an agent-as-tool produced zero child tool calls, the runtime finalizes instead of resuming.

func NewHardProtectionEvent

func NewHardProtectionEvent(runID string, agentID agent.Ident, sessionID string, reason string, executedAgentTools, childrenTotal int, toolNames []tools.Ident) *HardProtectionEvent

NewHardProtectionEvent constructs a HardProtectionEvent.

func (HardProtectionEvent) AgentID

func (e HardProtectionEvent) AgentID() string

AgentID returns the agent identifier.

func (HardProtectionEvent) EventKey

func (e HardProtectionEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (HardProtectionEvent) RunID

func (e HardProtectionEvent) RunID() string

RunID returns the workflow run identifier.

func (HardProtectionEvent) SessionID

func (e HardProtectionEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*HardProtectionEvent) SetEventKey

func (e *HardProtectionEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*HardProtectionEvent) SetSessionID

func (e *HardProtectionEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*HardProtectionEvent) SetTimestampMS

func (e *HardProtectionEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*HardProtectionEvent) SetTurnID

func (e *HardProtectionEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (HardProtectionEvent) Timestamp

func (e HardProtectionEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (HardProtectionEvent) TurnID

func (e HardProtectionEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*HardProtectionEvent) Type

func (e *HardProtectionEvent) Type() EventType

type MemoryAppendedEvent

type MemoryAppendedEvent struct {

	// EventCount indicates how many memory events were written in this operation.
	EventCount int
	// contains filtered or unexported fields
}

MemoryAppendedEvent fires when new memory entries are successfully persisted to the memory store.

func NewMemoryAppendedEvent

func NewMemoryAppendedEvent(runID string, agentID agent.Ident, sessionID string, eventCount int) *MemoryAppendedEvent

NewMemoryAppendedEvent constructs a MemoryAppendedEvent indicating successful persistence of memory entries.

func (MemoryAppendedEvent) AgentID

func (e MemoryAppendedEvent) AgentID() string

AgentID returns the agent identifier.

func (MemoryAppendedEvent) EventKey

func (e MemoryAppendedEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (MemoryAppendedEvent) RunID

func (e MemoryAppendedEvent) RunID() string

RunID returns the workflow run identifier.

func (MemoryAppendedEvent) SessionID

func (e MemoryAppendedEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*MemoryAppendedEvent) SetEventKey

func (e *MemoryAppendedEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*MemoryAppendedEvent) SetSessionID

func (e *MemoryAppendedEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*MemoryAppendedEvent) SetTimestampMS

func (e *MemoryAppendedEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*MemoryAppendedEvent) SetTurnID

func (e *MemoryAppendedEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (MemoryAppendedEvent) Timestamp

func (e MemoryAppendedEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (MemoryAppendedEvent) TurnID

func (e MemoryAppendedEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*MemoryAppendedEvent) Type

func (e *MemoryAppendedEvent) Type() EventType

type PlannerNoteEvent

type PlannerNoteEvent struct {

	// Note is the text content of the planner's annotation.
	Note string
	// Labels provide optional categorization metadata (e.g., "type": "reasoning").
	Labels map[string]string
	// contains filtered or unexported fields
}

PlannerNoteEvent fires when the planner emits an annotation or intermediate thought during execution.

func NewPlannerNoteEvent

func NewPlannerNoteEvent(runID string, agentID agent.Ident, sessionID string, note string, labels map[string]string) *PlannerNoteEvent

NewPlannerNoteEvent constructs a PlannerNoteEvent with the given note text and optional labels for categorization.

func (PlannerNoteEvent) AgentID

func (e PlannerNoteEvent) AgentID() string

AgentID returns the agent identifier.

func (PlannerNoteEvent) EventKey

func (e PlannerNoteEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (PlannerNoteEvent) RunID

func (e PlannerNoteEvent) RunID() string

RunID returns the workflow run identifier.

func (PlannerNoteEvent) SessionID

func (e PlannerNoteEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*PlannerNoteEvent) SetEventKey

func (e *PlannerNoteEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*PlannerNoteEvent) SetSessionID

func (e *PlannerNoteEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*PlannerNoteEvent) SetTimestampMS

func (e *PlannerNoteEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*PlannerNoteEvent) SetTurnID

func (e *PlannerNoteEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (PlannerNoteEvent) Timestamp

func (e PlannerNoteEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (PlannerNoteEvent) TurnID

func (e PlannerNoteEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*PlannerNoteEvent) Type

func (e *PlannerNoteEvent) Type() EventType

type PolicyDecisionEvent

type PolicyDecisionEvent struct {

	// AllowedTools lists the globally unique tool identifiers that the policy engine
	// permitted for this turn. The runtime enforces this allowlist: planners can only
	// invoke tools in this list. An empty slice means no tools are allowed for this turn,
	// forcing the planner to produce a final response. Subscribers use this for security
	// auditing and debugging tool restrictions.
	AllowedTools []tools.Ident
	// Caps reflects the updated execution budgets after policy evaluation for this turn.
	// This includes remaining tool call limits, consecutive failure thresholds, and time
	// budgets. Policies may adjust these dynamically based on observed behavior (e.g.,
	// reducing limits after repeated failures). Subscribers can monitor cap consumption
	// to predict run termination or trigger alerts.
	Caps policy.CapsState
	// Labels carries policy-applied metadata merged into the run context and propagated
	// to subsequent turns. Examples: {"circuit_breaker": "active", "policy_version": "v2"}.
	// These labels appear in downstream telemetry, memory records, and hooks. Subscribers
	// can use them to correlate policy decisions with run outcomes. Nil if the policy did
	// not add labels.
	Labels map[string]string
	// Metadata holds policy-specific structured data for audit trails and compliance
	// reporting (e.g., approval IDs, justification codes, external system responses).
	// The runtime persists this alongside run records. Subscribers can extract this for
	// governance dashboards or regulatory logging. Nil if the policy did not provide metadata.
	Metadata map[string]any
	// contains filtered or unexported fields
}

PolicyDecisionEvent captures the outcome of a policy evaluation so downstream systems can audit allowlists, cap adjustments, and metadata applied for a turn.

func NewPolicyDecisionEvent

func NewPolicyDecisionEvent(runID string, agentID agent.Ident, sessionID string, allowed []tools.Ident, caps policy.CapsState, labels map[string]string, metadata map[string]any) *PolicyDecisionEvent

NewPolicyDecisionEvent constructs a PolicyDecisionEvent with the provided metadata.

func (PolicyDecisionEvent) AgentID

func (e PolicyDecisionEvent) AgentID() string

AgentID returns the agent identifier.

func (PolicyDecisionEvent) EventKey

func (e PolicyDecisionEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (PolicyDecisionEvent) RunID

func (e PolicyDecisionEvent) RunID() string

RunID returns the workflow run identifier.

func (PolicyDecisionEvent) SessionID

func (e PolicyDecisionEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*PolicyDecisionEvent) SetEventKey

func (e *PolicyDecisionEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*PolicyDecisionEvent) SetSessionID

func (e *PolicyDecisionEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*PolicyDecisionEvent) SetTimestampMS

func (e *PolicyDecisionEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*PolicyDecisionEvent) SetTurnID

func (e *PolicyDecisionEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (PolicyDecisionEvent) Timestamp

func (e PolicyDecisionEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (PolicyDecisionEvent) TurnID

func (e PolicyDecisionEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*PolicyDecisionEvent) Type

func (e *PolicyDecisionEvent) Type() EventType

type PromptRenderedEvent

type PromptRenderedEvent struct {

	// PromptID identifies the rendered prompt specification.
	PromptID prompt.Ident
	// Version is the resolved prompt version used for rendering.
	Version string
	// Scope is the resolved override scope used during prompt resolution.
	Scope prompt.Scope
	// contains filtered or unexported fields
}

PromptRenderedEvent fires when the runtime resolves and renders a prompt.

func NewPromptRenderedEvent

func NewPromptRenderedEvent(runID string, agentID agent.Ident, sessionID string, promptID prompt.Ident, version string, scope prompt.Scope) *PromptRenderedEvent

NewPromptRenderedEvent constructs a PromptRenderedEvent for one rendered prompt.

func (PromptRenderedEvent) AgentID

func (e PromptRenderedEvent) AgentID() string

AgentID returns the agent identifier.

func (PromptRenderedEvent) EventKey

func (e PromptRenderedEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (PromptRenderedEvent) RunID

func (e PromptRenderedEvent) RunID() string

RunID returns the workflow run identifier.

func (PromptRenderedEvent) SessionID

func (e PromptRenderedEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*PromptRenderedEvent) SetEventKey

func (e *PromptRenderedEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*PromptRenderedEvent) SetSessionID

func (e *PromptRenderedEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*PromptRenderedEvent) SetTimestampMS

func (e *PromptRenderedEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*PromptRenderedEvent) SetTurnID

func (e *PromptRenderedEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (PromptRenderedEvent) Timestamp

func (e PromptRenderedEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (PromptRenderedEvent) TurnID

func (e PromptRenderedEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*PromptRenderedEvent) Type

func (e *PromptRenderedEvent) Type() EventType

type RetryHintIssuedEvent

type RetryHintIssuedEvent struct {

	// Reason summarizes why the retry hint was issued (e.g., "invalid_arguments").
	Reason string
	// ToolName identifies the tool involved in the failure, if applicable.
	ToolName tools.Ident
	// Message provides human-readable guidance for the retry adjustment.
	Message string
	// contains filtered or unexported fields
}

RetryHintIssuedEvent fires when the planner or runtime suggests a retry policy change, such as disabling a failing tool or adjusting caps.

func NewRetryHintIssuedEvent

func NewRetryHintIssuedEvent(runID string, agentID agent.Ident, sessionID string, reason string, toolName tools.Ident, message string) *RetryHintIssuedEvent

NewRetryHintIssuedEvent constructs a RetryHintIssuedEvent indicating a suggested retry policy adjustment.

func (RetryHintIssuedEvent) AgentID

func (e RetryHintIssuedEvent) AgentID() string

AgentID returns the agent identifier.

func (RetryHintIssuedEvent) EventKey

func (e RetryHintIssuedEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (RetryHintIssuedEvent) RunID

func (e RetryHintIssuedEvent) RunID() string

RunID returns the workflow run identifier.

func (RetryHintIssuedEvent) SessionID

func (e RetryHintIssuedEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*RetryHintIssuedEvent) SetEventKey

func (e *RetryHintIssuedEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*RetryHintIssuedEvent) SetSessionID

func (e *RetryHintIssuedEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*RetryHintIssuedEvent) SetTimestampMS

func (e *RetryHintIssuedEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*RetryHintIssuedEvent) SetTurnID

func (e *RetryHintIssuedEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (RetryHintIssuedEvent) Timestamp

func (e RetryHintIssuedEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (RetryHintIssuedEvent) TurnID

func (e RetryHintIssuedEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*RetryHintIssuedEvent) Type

func (e *RetryHintIssuedEvent) Type() EventType

type RunCompletedEvent

type RunCompletedEvent struct {

	// Status indicates the final outcome: "success", "failed", or "canceled".
	Status string
	// PublicError is a user-safe, deterministic summary of the terminal failure.
	// It is empty on success and cancellations. On failures, it is populated
	// and is intended to be rendered directly in UIs without additional parsing.
	PublicError string
	// Error contains any terminal error that halted the run. Nil on success.
	Error error
	// ErrorProvider identifies the model provider when the terminal error was
	// caused by a provider failure (for example, "bedrock").
	ErrorProvider string
	// ErrorOperation identifies the provider operation when available.
	ErrorOperation string
	// ErrorKind classifies provider failures into a small set of stable categories
	// suitable for retry and UX decisions (for example, "auth" or "invalid_request").
	ErrorKind string
	// ErrorCode is the provider-specific error code when available.
	ErrorCode string
	// HTTPStatus is the provider HTTP status code when available.
	HTTPStatus int
	// Retryable reports whether retrying may succeed without changing the request.
	Retryable bool
	// Phase captures the terminal phase for the run. For successful runs this
	// is typically PhaseCompleted; failures map to PhaseFailed; cancellations
	// map to PhaseCanceled.
	Phase run.Phase
	// contains filtered or unexported fields
}

RunCompletedEvent fires after a run finishes, whether successfully or with a failure.

func NewRunCompletedEvent

func NewRunCompletedEvent(runID string, agentID agent.Ident, sessionID, status string, phase run.Phase, err error) *RunCompletedEvent

NewRunCompletedEvent constructs a RunCompletedEvent. Status should be "success", "failed", or "canceled"; phase must be the terminal lifecycle phase for the run. err may be nil on success.

func (RunCompletedEvent) AgentID

func (e RunCompletedEvent) AgentID() string

AgentID returns the agent identifier.

func (RunCompletedEvent) EventKey

func (e RunCompletedEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (RunCompletedEvent) RunID

func (e RunCompletedEvent) RunID() string

RunID returns the workflow run identifier.

func (RunCompletedEvent) SessionID

func (e RunCompletedEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*RunCompletedEvent) SetEventKey

func (e *RunCompletedEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*RunCompletedEvent) SetSessionID

func (e *RunCompletedEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*RunCompletedEvent) SetTimestampMS

func (e *RunCompletedEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*RunCompletedEvent) SetTurnID

func (e *RunCompletedEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (RunCompletedEvent) Timestamp

func (e RunCompletedEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (RunCompletedEvent) TurnID

func (e RunCompletedEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*RunCompletedEvent) Type

func (e *RunCompletedEvent) Type() EventType

type RunPausedEvent

type RunPausedEvent struct {

	// Reason provides a human-readable explanation for why the run was paused.
	// Examples: "user_requested", "approval_required", "manual_review_needed".
	// Subscribers can use this to categorize pause events and display appropriate
	// messages to end users.
	Reason string
	// RequestedBy identifies the actor who initiated the pause (e.g., user ID,
	// service name, or "policy_engine"). This enables audit logging and attribution
	// for governance workflows.
	RequestedBy string
	// Labels carries optional key-value metadata for categorizing the pause event.
	// These labels are propagated from the pause request and can be used for filtering,
	// reporting, or triggering downstream workflows. Nil if no labels were provided.
	Labels map[string]string
	// Metadata holds arbitrary structured data attached to the pause request for audit
	// trails or workflow-specific logic (e.g., approval ticket IDs, escalation reasons).
	// The runtime persists this alongside the run status. Nil if no metadata was provided.
	Metadata map[string]any
	// contains filtered or unexported fields
}

RunPausedEvent fires when a run is intentionally paused.

func NewRunPausedEvent

func NewRunPausedEvent(runID string, agentID agent.Ident, sessionID, reason, requestedBy string, labels map[string]string, metadata map[string]any) *RunPausedEvent

NewRunPausedEvent constructs a RunPausedEvent with provided metadata.

func (RunPausedEvent) AgentID

func (e RunPausedEvent) AgentID() string

AgentID returns the agent identifier.

func (RunPausedEvent) EventKey

func (e RunPausedEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (RunPausedEvent) RunID

func (e RunPausedEvent) RunID() string

RunID returns the workflow run identifier.

func (RunPausedEvent) SessionID

func (e RunPausedEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*RunPausedEvent) SetEventKey

func (e *RunPausedEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*RunPausedEvent) SetSessionID

func (e *RunPausedEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*RunPausedEvent) SetTimestampMS

func (e *RunPausedEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*RunPausedEvent) SetTurnID

func (e *RunPausedEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (RunPausedEvent) Timestamp

func (e RunPausedEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (RunPausedEvent) TurnID

func (e RunPausedEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*RunPausedEvent) Type

func (e *RunPausedEvent) Type() EventType

type RunPhaseChangedEvent

type RunPhaseChangedEvent struct {

	// Phase is the new lifecycle phase for the run.
	Phase run.Phase
	// contains filtered or unexported fields
}

RunPhaseChangedEvent fires when a run transitions between lifecycle phases (prompted, planning, executing_tools, synthesizing, completed, failed, canceled). This is a higher-fidelity signal than Status and is primarily intended for streaming/UX consumers.

func NewRunPhaseChangedEvent

func NewRunPhaseChangedEvent(runID string, agentID agent.Ident, sessionID string, phase run.Phase) *RunPhaseChangedEvent

NewRunPhaseChangedEvent constructs a RunPhaseChangedEvent for the given run and agent.

func (RunPhaseChangedEvent) AgentID

func (e RunPhaseChangedEvent) AgentID() string

AgentID returns the agent identifier.

func (RunPhaseChangedEvent) EventKey

func (e RunPhaseChangedEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (RunPhaseChangedEvent) RunID

func (e RunPhaseChangedEvent) RunID() string

RunID returns the workflow run identifier.

func (RunPhaseChangedEvent) SessionID

func (e RunPhaseChangedEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*RunPhaseChangedEvent) SetEventKey

func (e *RunPhaseChangedEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*RunPhaseChangedEvent) SetSessionID

func (e *RunPhaseChangedEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*RunPhaseChangedEvent) SetTimestampMS

func (e *RunPhaseChangedEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*RunPhaseChangedEvent) SetTurnID

func (e *RunPhaseChangedEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (RunPhaseChangedEvent) Timestamp

func (e RunPhaseChangedEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (RunPhaseChangedEvent) TurnID

func (e RunPhaseChangedEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*RunPhaseChangedEvent) Type

func (e *RunPhaseChangedEvent) Type() EventType

type RunResumedEvent

type RunResumedEvent struct {

	// Notes carries optional human-readable context provided when resuming the run.
	// This might include instructions for the planner ("focus on X"), approval
	// summaries, or other guidance. Empty if no notes were provided with the resume request.
	Notes string
	// RequestedBy identifies the actor who initiated the resume (e.g., user ID,
	// service name, or "approval_system"). This enables audit logging and attribution
	// for governance workflows.
	RequestedBy string
	// Labels carries optional key-value metadata for categorizing the resume event.
	// These labels are propagated from the resume request and can be used for filtering,
	// reporting, or triggering downstream workflows. Nil if no labels were provided.
	Labels map[string]string
	// MessageCount indicates how many new conversational messages were injected when
	// resuming the run. When greater than zero, these messages are appended to the
	// planner's context before execution continues. Subscribers can use this to track
	// human-in-the-loop interventions.
	MessageCount int
	// contains filtered or unexported fields
}

RunResumedEvent fires when a paused run resumes.

func NewRunResumedEvent

func NewRunResumedEvent(runID string, agentID agent.Ident, sessionID, notes, requestedBy string, labels map[string]string, messageCount int) *RunResumedEvent

NewRunResumedEvent constructs a RunResumedEvent with provided metadata.

func (RunResumedEvent) AgentID

func (e RunResumedEvent) AgentID() string

AgentID returns the agent identifier.

func (RunResumedEvent) EventKey

func (e RunResumedEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (RunResumedEvent) RunID

func (e RunResumedEvent) RunID() string

RunID returns the workflow run identifier.

func (RunResumedEvent) SessionID

func (e RunResumedEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*RunResumedEvent) SetEventKey

func (e *RunResumedEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*RunResumedEvent) SetSessionID

func (e *RunResumedEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*RunResumedEvent) SetTimestampMS

func (e *RunResumedEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*RunResumedEvent) SetTurnID

func (e *RunResumedEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (RunResumedEvent) Timestamp

func (e RunResumedEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (RunResumedEvent) TurnID

func (e RunResumedEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*RunResumedEvent) Type

func (e *RunResumedEvent) Type() EventType

type RunStartedEvent

type RunStartedEvent struct {

	// RunContext carries the execution metadata (run ID, attempt, labels, caps)
	// for this run invocation.
	RunContext run.Context
	// Input is the initial payload passed to the run, typically containing
	// messages and caller-provided metadata.
	Input any
	// contains filtered or unexported fields
}

RunStartedEvent fires when a run begins execution.

func NewRunStartedEvent

func NewRunStartedEvent(runID string, agentID agent.Ident, runContext run.Context, input any) *RunStartedEvent

NewRunStartedEvent constructs a RunStartedEvent with the current timestamp. RunContext and Input capture the initial run state.

func (RunStartedEvent) AgentID

func (e RunStartedEvent) AgentID() string

AgentID returns the agent identifier.

func (RunStartedEvent) EventKey

func (e RunStartedEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (RunStartedEvent) RunID

func (e RunStartedEvent) RunID() string

RunID returns the workflow run identifier.

func (RunStartedEvent) SessionID

func (e RunStartedEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*RunStartedEvent) SetEventKey

func (e *RunStartedEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*RunStartedEvent) SetSessionID

func (e *RunStartedEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*RunStartedEvent) SetTimestampMS

func (e *RunStartedEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*RunStartedEvent) SetTurnID

func (e *RunStartedEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (RunStartedEvent) Timestamp

func (e RunStartedEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (RunStartedEvent) TurnID

func (e RunStartedEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*RunStartedEvent) Type

func (e *RunStartedEvent) Type() EventType

type Subscriber

type Subscriber interface {
	// HandleEvent processes a single event. The context passed to this method
	// originates from the Bus.Publish call and may have deadlines or
	// cancellation signals that implementations should respect.
	//
	// If HandleEvent returns an error, the Bus immediately stops delivering
	// the event to remaining subscribers and returns the error to the publisher.
	HandleEvent(ctx context.Context, event Event) error
}

Subscriber reacts to published runtime events by implementing HandleEvent. Subscribers are registered with a Bus and receive all events in FIFO order until their subscription is closed.

Implementations must be thread-safe if the same subscriber instance is registered with multiple buses or if HandleEvent performs concurrent work.

HandleEvent should return an error only if event processing fails in a way that should halt the workflow (e.g., critical persistence failure). The Bus stops iterating at the first error, so non-critical failures should be logged and ignored to avoid blocking other subscribers.

type SubscriberFunc

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

SubscriberFunc is an adapter that allows ordinary functions to act as Subscribers. This is useful for quick prototypes, tests, or simple handlers that don't require stateful subscriber implementations.

Example:

sub := hooks.SubscriberFunc(func(ctx context.Context, evt hooks.Event) error {
    log.Printf("Received %s for run %s", evt.Type, evt.RunID)
    return nil
})
subscription, _ := bus.Register(sub)

func (SubscriberFunc) HandleEvent

func (fn SubscriberFunc) HandleEvent(ctx context.Context, event Event) error

HandleEvent implements Subscriber by invoking the function.

type Subscription

type Subscription interface {
	// Close removes the subscriber from the bus. The method is idempotent
	// and thread-safe. After Close returns, the subscriber will not receive
	// new events, though in-flight events may still be delivered if Close
	// is called during a Publish operation.
	//
	// Close always returns nil to satisfy io.Closer-like interfaces.
	Close() error
}

Subscription represents an active registration on a Bus. Calling Close removes the subscriber from the bus, ensuring it receives no further events.

Subscriptions are safe to close multiple times; subsequent Close calls are no-ops. This makes it safe to use defer or cleanup patterns without tracking whether Close has been called.

type ThinkingBlockEvent

type ThinkingBlockEvent struct {

	// Text is the plaintext reasoning content when provided by the model.
	Text string
	// Signature is the provider signature for plaintext reasoning (when required).
	Signature string
	// Redacted contains provider-issued redacted reasoning bytes (mutually exclusive with Text).
	Redacted []byte
	// ContentIndex is the provider content block index.
	ContentIndex int
	// Final indicates that the reasoning block was finalized by the provider.
	Final bool
	// contains filtered or unexported fields
}

ThinkingBlockEvent fires when the planner emits a structured reasoning block (either signed plaintext or redacted bytes). This preserves provider-accurate thinking suitable for exact replay and auditing.

func NewThinkingBlockEvent

func NewThinkingBlockEvent(runID string, agentID agent.Ident, sessionID string, text, signature string, redacted []byte, contentIndex int, final bool) *ThinkingBlockEvent

NewThinkingBlockEvent constructs a ThinkingBlockEvent with structured reasoning fields.

func (ThinkingBlockEvent) AgentID

func (e ThinkingBlockEvent) AgentID() string

AgentID returns the agent identifier.

func (ThinkingBlockEvent) EventKey

func (e ThinkingBlockEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (ThinkingBlockEvent) RunID

func (e ThinkingBlockEvent) RunID() string

RunID returns the workflow run identifier.

func (ThinkingBlockEvent) SessionID

func (e ThinkingBlockEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*ThinkingBlockEvent) SetEventKey

func (e *ThinkingBlockEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*ThinkingBlockEvent) SetSessionID

func (e *ThinkingBlockEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*ThinkingBlockEvent) SetTimestampMS

func (e *ThinkingBlockEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*ThinkingBlockEvent) SetTurnID

func (e *ThinkingBlockEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (ThinkingBlockEvent) Timestamp

func (e ThinkingBlockEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (ThinkingBlockEvent) TurnID

func (e ThinkingBlockEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*ThinkingBlockEvent) Type

func (e *ThinkingBlockEvent) Type() EventType

type ToolAuthorizationEvent

type ToolAuthorizationEvent struct {

	// ToolName identifies the tool that was authorized.
	ToolName tools.Ident
	// ToolCallID is the tool_call_id for the pending tool call.
	ToolCallID string
	// Approved reports whether the operator approved execution.
	Approved bool
	// Summary is a deterministic, human-facing description of what was approved.
	Summary string
	// ApprovedBy identifies the actor that provided the decision, formatted as
	// "<principal_type>:<principal_id>".
	ApprovedBy string
	// contains filtered or unexported fields
}

ToolAuthorizationEvent indicates an operator provided an explicit approval or denial decision for a pending tool call. This is emitted immediately when the decision is received so subscribers can record a durable audit trail and UIs can render an approval record independent of tool execution.

func NewToolAuthorizationEvent

func NewToolAuthorizationEvent(runID string, agentID agent.Ident, sessionID string, toolName tools.Ident, toolCallID string, approved bool, summary, approvedBy string) *ToolAuthorizationEvent

NewToolAuthorizationEvent constructs a ToolAuthorizationEvent for a pending tool call.

func (ToolAuthorizationEvent) AgentID

func (e ToolAuthorizationEvent) AgentID() string

AgentID returns the agent identifier.

func (ToolAuthorizationEvent) EventKey

func (e ToolAuthorizationEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (ToolAuthorizationEvent) RunID

func (e ToolAuthorizationEvent) RunID() string

RunID returns the workflow run identifier.

func (ToolAuthorizationEvent) SessionID

func (e ToolAuthorizationEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*ToolAuthorizationEvent) SetEventKey

func (e *ToolAuthorizationEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*ToolAuthorizationEvent) SetSessionID

func (e *ToolAuthorizationEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*ToolAuthorizationEvent) SetTimestampMS

func (e *ToolAuthorizationEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*ToolAuthorizationEvent) SetTurnID

func (e *ToolAuthorizationEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (ToolAuthorizationEvent) Timestamp

func (e ToolAuthorizationEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (ToolAuthorizationEvent) TurnID

func (e ToolAuthorizationEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*ToolAuthorizationEvent) Type

Type implements Event for ToolAuthorizationEvent.

type ToolCallArgsDeltaEvent

type ToolCallArgsDeltaEvent struct {

	// ToolCallID is the provider-issued identifier for the tool call.
	ToolCallID string
	// ToolName is the canonical tool identifier when known.
	ToolName tools.Ident
	// Delta is a raw JSON fragment emitted while streaming tool input JSON.
	Delta string
	// contains filtered or unexported fields
}

ToolCallArgsDeltaEvent fires when a provider streams an incremental tool-call argument fragment while constructing the final tool input JSON.

Contract:

  • This event is best-effort and may be ignored or dropped entirely.
  • Delta is not guaranteed to be valid JSON on its own.
  • The canonical tool payload is still emitted via ToolCallScheduledEvent and ToolResultReceivedEvent (and, at the model boundary, the finalized tool call chunk).

func NewToolCallArgsDeltaEvent

func NewToolCallArgsDeltaEvent(runID string, agentID agent.Ident, sessionID string, toolCallID string, toolName tools.Ident, delta string) *ToolCallArgsDeltaEvent

NewToolCallArgsDeltaEvent constructs a ToolCallArgsDeltaEvent.

func (ToolCallArgsDeltaEvent) AgentID

func (e ToolCallArgsDeltaEvent) AgentID() string

AgentID returns the agent identifier.

func (ToolCallArgsDeltaEvent) EventKey

func (e ToolCallArgsDeltaEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (ToolCallArgsDeltaEvent) RunID

func (e ToolCallArgsDeltaEvent) RunID() string

RunID returns the workflow run identifier.

func (ToolCallArgsDeltaEvent) SessionID

func (e ToolCallArgsDeltaEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*ToolCallArgsDeltaEvent) SetEventKey

func (e *ToolCallArgsDeltaEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*ToolCallArgsDeltaEvent) SetSessionID

func (e *ToolCallArgsDeltaEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*ToolCallArgsDeltaEvent) SetTimestampMS

func (e *ToolCallArgsDeltaEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*ToolCallArgsDeltaEvent) SetTurnID

func (e *ToolCallArgsDeltaEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (ToolCallArgsDeltaEvent) Timestamp

func (e ToolCallArgsDeltaEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (ToolCallArgsDeltaEvent) TurnID

func (e ToolCallArgsDeltaEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*ToolCallArgsDeltaEvent) Type

type ToolCallScheduledEvent

type ToolCallScheduledEvent struct {

	// ToolCallID uniquely identifies the scheduled tool invocation so progress
	// updates can correlate with the original request.
	ToolCallID string
	// ToolName is the globally unique tool identifier (simple DSL name).
	ToolName tools.Ident
	// Payload contains the canonical JSON tool arguments for the scheduled tool.
	// It is a json.RawMessage representing the tool payload object as seen by the
	// runtime and codecs.
	Payload rawjson.Message
	// Queue is the activity queue name where the tool execution is scheduled.
	Queue string
	// ParentToolCallID optionally identifies the tool call that requested this tool.
	// Empty for top-level planner-requested tools. Used to track parent-child chains.
	ParentToolCallID string
	// ExpectedChildrenTotal indicates how many child tools are expected from this batch.
	// A value of 0 means no children expected or count not tracked by the planner.
	ExpectedChildrenTotal int
	// DisplayHint is a human-facing summary of the in-flight tool work derived
	// from the tool's call hint template. It is computed once by the runtime
	// so downstream subscribers (streaming, session persistence, memory) can
	// surface consistent labels without re-rendering templates.
	DisplayHint string
	// contains filtered or unexported fields
}

ToolCallScheduledEvent fires when the runtime schedules a tool activity for execution.

func NewToolCallScheduledEvent

func NewToolCallScheduledEvent(runID string, agentID agent.Ident, sessionID string, toolName tools.Ident, toolCallID string, payload rawjson.Message, queue string, parentToolCallID string, expectedChildren int) *ToolCallScheduledEvent

NewToolCallScheduledEvent constructs a ToolCallScheduledEvent. Payload is the canonical JSON arguments for the scheduled tool; queue is the activity queue name. ParentToolCallID and expectedChildren are optional (empty/0 for top-level calls).

func (ToolCallScheduledEvent) AgentID

func (e ToolCallScheduledEvent) AgentID() string

AgentID returns the agent identifier.

func (ToolCallScheduledEvent) EventKey

func (e ToolCallScheduledEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (ToolCallScheduledEvent) RunID

func (e ToolCallScheduledEvent) RunID() string

RunID returns the workflow run identifier.

func (ToolCallScheduledEvent) SessionID

func (e ToolCallScheduledEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*ToolCallScheduledEvent) SetEventKey

func (e *ToolCallScheduledEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*ToolCallScheduledEvent) SetSessionID

func (e *ToolCallScheduledEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*ToolCallScheduledEvent) SetTimestampMS

func (e *ToolCallScheduledEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*ToolCallScheduledEvent) SetTurnID

func (e *ToolCallScheduledEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (ToolCallScheduledEvent) Timestamp

func (e ToolCallScheduledEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (ToolCallScheduledEvent) TurnID

func (e ToolCallScheduledEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*ToolCallScheduledEvent) Type

type ToolCallUpdatedEvent

type ToolCallUpdatedEvent struct {

	// ToolCallID identifies the tool call being updated (usually a parent call).
	ToolCallID string
	// ExpectedChildrenTotal is the new count of expected child tools. This value
	// grows as child tools are discovered dynamically during execution.
	ExpectedChildrenTotal int
	// contains filtered or unexported fields
}

ToolCallUpdatedEvent fires when a tool call's metadata is updated after initial scheduling. This typically occurs when a parent tool (agent-as-tool) dynamically discovers additional child tools across multiple planning iterations. UIs use this to update progress displays ("3 of 5 children complete").

func NewToolCallUpdatedEvent

func NewToolCallUpdatedEvent(runID string, agentID agent.Ident, sessionID string, toolCallID string, expectedChildrenTotal int) *ToolCallUpdatedEvent

NewToolCallUpdatedEvent constructs a ToolCallUpdatedEvent to signal that a parent tool's child count has increased due to dynamic discovery.

func (ToolCallUpdatedEvent) AgentID

func (e ToolCallUpdatedEvent) AgentID() string

AgentID returns the agent identifier.

func (ToolCallUpdatedEvent) EventKey

func (e ToolCallUpdatedEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (ToolCallUpdatedEvent) RunID

func (e ToolCallUpdatedEvent) RunID() string

RunID returns the workflow run identifier.

func (ToolCallUpdatedEvent) SessionID

func (e ToolCallUpdatedEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*ToolCallUpdatedEvent) SetEventKey

func (e *ToolCallUpdatedEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*ToolCallUpdatedEvent) SetSessionID

func (e *ToolCallUpdatedEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*ToolCallUpdatedEvent) SetTimestampMS

func (e *ToolCallUpdatedEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*ToolCallUpdatedEvent) SetTurnID

func (e *ToolCallUpdatedEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (ToolCallUpdatedEvent) Timestamp

func (e ToolCallUpdatedEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (ToolCallUpdatedEvent) TurnID

func (e ToolCallUpdatedEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*ToolCallUpdatedEvent) Type

func (e *ToolCallUpdatedEvent) Type() EventType

type ToolResultReceivedEvent

type ToolResultReceivedEvent struct {

	// ToolCallID uniquely identifies the tool invocation that produced this result.
	ToolCallID string
	// ParentToolCallID identifies the parent tool call if this tool was invoked by another tool.
	// Empty when the tool call was scheduled directly by the planner.
	ParentToolCallID string
	// ToolName is the globally unique tool identifier that was executed.
	ToolName tools.Ident
	// Result contains the tool's output payload. Nil if Error is set.
	Result any
	// ResultJSON contains the canonical JSON encoding of Result as produced
	// by the tool's generated result codec.
	//
	// This is used by stream sinks and persistence layers that must serialize
	// tool results without relying on `encoding/json` and Go field names.
	ResultJSON rawjson.Message
	// ServerData carries server-only data emitted by tool providers. This payload
	// must not be serialized into model provider requests and is treated as opaque
	// JSON bytes by the runtime.
	ServerData rawjson.Message
	// ResultPreview is a concise, user-facing summary of the tool result rendered
	// from the registered ResultHintTemplate for this tool. Result templates
	// receive the runtime preview wrapper (`.Result` for semantic data,
	// `.Bounds` for bounded-result metadata). The preview is computed while the
	// result is still strongly typed so downstream subscribers do not need to
	// re-render templates from JSON-decoded maps.
	ResultPreview string
	// Bounds, when non-nil, describes how the tool result has been bounded
	// relative to the full underlying data set. It is supplied by tool
	// implementations and surfaced for observability; the runtime does not
	// modify it.
	Bounds *agent.Bounds
	// Duration is the wall-clock execution time for the tool activity.
	Duration time.Duration
	// Telemetry holds structured observability metadata (tokens, model, retries).
	// Nil if no telemetry was collected.
	Telemetry *telemetry.ToolTelemetry
	// RetryHint carries structured guidance for recovering from tool failures.
	// It is typically populated for validation/repair flows (missing fields,
	// invalid arguments) and surfaced to clients so they can prompt the user
	// and retry deterministically.
	RetryHint *planner.RetryHint
	// Error contains any error returned by the tool execution. Nil on success.
	Error *toolerrors.ToolError
	// contains filtered or unexported fields
}

ToolResultReceivedEvent fires when a tool activity completes and returns a result or error.

func NewToolResultReceivedEvent

func NewToolResultReceivedEvent(runID string, agentID agent.Ident, sessionID string, toolName tools.Ident, toolCallID, parentToolCallID string, result any, resultJSON, serverData rawjson.Message, resultPreview string, bounds *agent.Bounds, duration time.Duration, telemetry *telemetry.ToolTelemetry, retryHint *planner.RetryHint, err *toolerrors.ToolError) *ToolResultReceivedEvent

NewToolResultReceivedEvent constructs a ToolResultReceivedEvent. Result and err capture the tool outcome; duration is the wall-clock execution time; telemetry carries structured observability metadata (nil if not collected).

func (ToolResultReceivedEvent) AgentID

func (e ToolResultReceivedEvent) AgentID() string

AgentID returns the agent identifier.

func (ToolResultReceivedEvent) EventKey

func (e ToolResultReceivedEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (ToolResultReceivedEvent) RunID

func (e ToolResultReceivedEvent) RunID() string

RunID returns the workflow run identifier.

func (ToolResultReceivedEvent) SessionID

func (e ToolResultReceivedEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*ToolResultReceivedEvent) SetEventKey

func (e *ToolResultReceivedEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*ToolResultReceivedEvent) SetSessionID

func (e *ToolResultReceivedEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*ToolResultReceivedEvent) SetTimestampMS

func (e *ToolResultReceivedEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*ToolResultReceivedEvent) SetTurnID

func (e *ToolResultReceivedEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (ToolResultReceivedEvent) Timestamp

func (e ToolResultReceivedEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (ToolResultReceivedEvent) TurnID

func (e ToolResultReceivedEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*ToolResultReceivedEvent) Type

type UsageEvent

type UsageEvent struct {

	// TokenUsage contains the attributed token counts reported by the model
	// adapter. Model and ModelClass identify the specific model that produced
	// this delta.
	model.TokenUsage
	// contains filtered or unexported fields
}

UsageEvent reports token usage for a model invocation within a run. Emitted when the model stream reports usage deltas or a final summary.

func NewUsageEvent

func NewUsageEvent(runID string, agentID agent.Ident, sessionID string, usage model.TokenUsage) *UsageEvent

NewUsageEvent constructs a UsageEvent from an attributed usage snapshot.

func (UsageEvent) AgentID

func (e UsageEvent) AgentID() string

AgentID returns the agent identifier.

func (UsageEvent) EventKey

func (e UsageEvent) EventKey() string

EventKey returns the stable logical identity for this event.

func (UsageEvent) RunID

func (e UsageEvent) RunID() string

RunID returns the workflow run identifier.

func (UsageEvent) SessionID

func (e UsageEvent) SessionID() string

SessionID returns the logical session identifier associated with the run.

func (*UsageEvent) SetEventKey

func (e *UsageEvent) SetEventKey(eventKey string)

SetEventKey restores the original event key when reconstructing an event from a hook activity input envelope.

func (*UsageEvent) SetSessionID

func (e *UsageEvent) SetSessionID(id string)

SetSessionID updates the session identifier associated with the event. This is called by the runtime when constructing events so downstream subscribers can rely on SessionID as a stable join key across processes.

func (*UsageEvent) SetTimestampMS

func (e *UsageEvent) SetTimestampMS(timestampMS int64)

SetTimestampMS restores the original event timestamp when reconstructing an event from a hook activity input envelope.

func (*UsageEvent) SetTurnID

func (e *UsageEvent) SetTurnID(turnID string)

SetTurnID updates the turn identifier. This is called by the runtime to stamp events with turn information after construction.

func (UsageEvent) Timestamp

func (e UsageEvent) Timestamp() int64

Timestamp returns the Unix timestamp in milliseconds when the event occurred.

func (UsageEvent) TurnID

func (e UsageEvent) TurnID() string

TurnID returns the conversational turn identifier (empty if not set).

func (*UsageEvent) Type

func (e *UsageEvent) Type() EventType

Jump to

Keyboard shortcuts

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