sdk

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultAgentMaxTextLength = 100000

Variables

This section is empty.

Functions

func AcceptProviderLogin

func AcceptProviderLogin(
	login *bridgev2.UserLogin,
	provider string,
	unsupportedReason string,
	enabled func() bool,
	disabledReason string,
	metadataProvider func(*bridgev2.UserLogin) string,
) (bool, string)

func AppendArtifactPart

func AppendArtifactPart(td *TurnData, raw map[string]any)

func AppendChatMessagesToPromptContext

func AppendChatMessagesToPromptContext(ctx *PromptContext, messages []openai.ChatCompletionMessageParamUnion)

func AppendPromptText

func AppendPromptText(dst *string, text string)

func ApplyBoolDefault

func ApplyBoolDefault(target **bool, value bool)

ApplyBoolDefault initializes a nil bool pointer to the provided value.

func ApplyDefaultCommandPrefix

func ApplyDefaultCommandPrefix(prefix *string, value string)

ApplyDefaultCommandPrefix sets the command prefix when it is empty.

func ApplyStreamPart

func ApplyStreamPart(turn *Turn, part map[string]any, opts PartApplyOptions) bool

ApplyStreamPart maps a canonical stream part onto a turn. It returns true when the part type is recognized and applied.

func BroadcastCommandDescriptions

func BroadcastCommandDescriptions(ctx context.Context, portal *bridgev2.Portal, bot bridgev2.MatrixAPI, cmds []Command)

BroadcastCommandDescriptions sends MSC4391 command-description state events for all SDK commands into the given room.

func BuildCompactFinalUIMessage

func BuildCompactFinalUIMessage(uiMessage map[string]any) map[string]any

BuildCompactFinalUIMessage removes streaming-only parts from a UI message so the payload is suitable for attachment to the final Matrix edit.

func BuildDataURL

func BuildDataURL(mimeType, b64Data string) string

func BuildDefaultFinalEditTopLevelExtra

func BuildDefaultFinalEditTopLevelExtra(uiMessage map[string]any) map[string]any

BuildDefaultFinalEditTopLevelExtra builds the SDK's default metadata payload for terminal final edits.

func BuildStandardMetaTypes

func BuildStandardMetaTypes(
	newPortal func() any,
	newMessage func() any,
	newLogin func() any,
	newGhost func() any,
) database.MetaTypes

BuildStandardMetaTypes returns the common bridge metadata registrations.

func CanonicalToolArguments

func CanonicalToolArguments(raw any) string

func EnsurePortalLifecycle

func EnsurePortalLifecycle(ctx context.Context, opts PortalLifecycleOptions) (bool, error)

EnsurePortalLifecycle creates or refreshes a portal room and then applies the shared room-state lifecycle used across bridge implementations.

func FormatCanonicalValue

func FormatCanonicalValue(raw any) string

func HasUnsupportedResponsesPromptContext

func HasUnsupportedResponsesPromptContext(ctx PromptContext) bool

func NewConnectorBase

func NewConnectorBase(cfg *Config) *agentremote.ConnectorBase

NewConnectorBase builds an SDK-backed connector base that can be embedded by custom bridges.

func PromptContextHasBlockType

func PromptContextHasBlockType(ctx PromptContext, kinds ...PromptBlockType) bool

func PromptContextToChatCompletionMessages

func PromptContextToChatCompletionMessages(ctx PromptContext, supportsVideoURL bool) []openai.ChatCompletionMessageParamUnion

PromptContextToChatCompletionMessages converts the canonical prompt model into Chat Completions messages.

func PromptContextToResponsesInput

func PromptContextToResponsesInput(ctx PromptContext) responses.ResponseInputParam

PromptContextToResponsesInput converts the canonical prompt model into Responses input items.

func RefreshPortalLifecycle

func RefreshPortalLifecycle(ctx context.Context, opts PortalLifecycleOptions)

RefreshPortalLifecycle applies explicit room-state refresh steps that are expected after room creation, room refresh, or portal re-ID.

func ResolveCommandLogin

func ResolveCommandLogin(ctx context.Context, ce *commands.Event, defaultLogin *bridgev2.UserLogin) (*bridgev2.UserLogin, error)

ResolveCommandLogin resolves the login for a command event.

In-room commands are bound to the portal owner and must not fall back to a different default login if that ownership can't be resolved.

func TurnDataHasFilePart

func TurnDataHasFilePart(td TurnData, partType, filename, title string) bool

func TurnDataHasPartType

func TurnDataHasPartType(td TurnData, partType string) bool

func TurnDataHasToolCall

func TurnDataHasToolCall(td TurnData, callID string) bool

func TurnDataHasURLPart

func TurnDataHasURLPart(td TurnData, partType, url string) bool

func TurnGeneratedFiles

func TurnGeneratedFiles(td TurnData) []agentremote.GeneratedFileRef

func TurnReasoningText

func TurnReasoningText(td TurnData) string

func TurnText

func TurnText(td TurnData) string

func TurnToolCalls

func TurnToolCalls(td TurnData, toolType string) []agentremote.ToolCallMetadata

func TypedClientCreator

func TypedClientCreator[T bridgev2.NetworkAPI](create func(*bridgev2.UserLogin) (T, error)) func(*bridgev2.UserLogin) (bridgev2.NetworkAPI, error)

func TypedClientUpdater

func TypedClientUpdater[T interface {
	bridgev2.NetworkAPI
	loginAwareClient
}]() func(bridgev2.NetworkAPI, *bridgev2.UserLogin)

func UIMessageFromTurnData

func UIMessageFromTurnData(td TurnData) map[string]any

UIMessageFromTurnData projects canonical turn data into an AI SDK UIMessage shape suitable for Matrix transport.

Types

type Agent

type Agent struct {
	ID           string
	Name         string
	Description  string
	AvatarURL    string
	Identifiers  []string
	ModelKey     string
	Capabilities AgentCapabilities
	Metadata     map[string]any
}

Agent is the thin SDK identity model for an AI agent.

func (*Agent) EnsureGhost

func (a *Agent) EnsureGhost(ctx context.Context, login *bridgev2.UserLogin) error

EnsureGhost ensures the ghost user exists in the bridge database.

func (*Agent) EventSender

func (a *Agent) EventSender(loginID networkid.UserLoginID) bridgev2.EventSender

EventSender returns the bridgev2.EventSender for this agent.

func (*Agent) UserInfo

func (a *Agent) UserInfo() *bridgev2.UserInfo

UserInfo returns a bridgev2.UserInfo for this agent.

type AgentCapabilities

type AgentCapabilities struct {
	SupportsStreaming   bool
	SupportsReasoning   bool
	SupportsToolCalling bool

	SupportsTextInput  bool
	SupportsImageInput bool
	SupportsAudioInput bool
	SupportsVideoInput bool
	SupportsFileInput  bool
	SupportsPDFInput   bool

	SupportsImageOutput bool
	SupportsAudioOutput bool
	SupportsFilesOutput bool

	MaxTextLength int
}

AgentCapabilities contains the SDK-relevant capability truth for an agent.

func BaseAgentCapabilities

func BaseAgentCapabilities() AgentCapabilities

BaseAgentCapabilities returns the common capabilities shared by text-first bridge agents.

func MultimodalAgentCapabilities

func MultimodalAgentCapabilities() AgentCapabilities

MultimodalAgentCapabilities extends the base agent capabilities with broad media input support.

type AgentCatalog

type AgentCatalog interface {
	DefaultAgent(ctx context.Context, login *bridgev2.UserLogin) (*Agent, error)
	ListAgents(ctx context.Context, login *bridgev2.UserLogin) ([]*Agent, error)
	ResolveAgent(ctx context.Context, login *bridgev2.UserLogin, identifier string) (*Agent, error)
}

AgentCatalog resolves agents for contacts, identifier lookup, and default selection.

type ApprovalController

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

func (*ApprovalController) EmitRequest

func (a *ApprovalController) EmitRequest(ctx context.Context, approvalID, toolCallID string)

EmitRequest emits the approval-request UI state for a provider-managed approval.

func (*ApprovalController) Request

Request creates a new approval request.

func (*ApprovalController) Respond

func (a *ApprovalController) Respond(ctx context.Context, approvalID, toolCallID string, approved bool, reason string)

Respond emits the approval-response UI state for a provider-managed approval.

func (*ApprovalController) SetHandler

func (a *ApprovalController) SetHandler(handler func(ctx context.Context, turn *Turn, req ApprovalRequest) ApprovalHandle)

SetHandler configures a provider-specific approval handler for this turn.

type ApprovalHandle

type ApprovalHandle interface {
	ID() string
	ToolCallID() string
	Wait(ctx context.Context) (ToolApprovalResponse, error)
}

ApprovalHandle tracks an individual approval request.

type ApprovalRequest

type ApprovalRequest struct {
	ApprovalID   string
	ToolCallID   string
	ToolName     string
	TTL          time.Duration
	Presentation *agentremote.ApprovalPromptPresentation
	Metadata     map[string]any
}

ApprovalRequest describes a single approval request within a turn.

type ChatInfo

type ChatInfo struct {
	ID       string
	Name     string
	Topic    string
	Metadata map[string]any
}

ChatInfo describes a chat/portal.

type Command

type Command struct {
	Name        string
	Description string
	Args        string // e.g. "<query>", "[options...]"
	Handler     func(conv *Conversation, args string) error
}

Command defines a slash command that users can invoke.

type Config

type Config struct {
	// Required
	Name        string
	Description string

	// Agent identity (optional, used for ghost sender)
	Agent *Agent
	// Optional agent catalog used for contact listing and room agent management.
	AgentCatalog AgentCatalog

	// Message handling (required)
	// session is the value returned by OnConnect; conv is the conversation;
	// msg is the incoming message; turn is the pre-created Turn for streaming responses.
	OnMessage func(session any, conv *Conversation, msg *Message, turn *Turn) error

	// Event hooks (optional)
	OnConnect    func(ctx context.Context, login *LoginInfo) (any, error) // returns session state
	OnDisconnect func(session any)
	OnReaction   func(session any, conv *Conversation, reaction *Reaction) error
	OnTyping     func(session any, conv *Conversation, typing bool)
	OnEdit       func(session any, conv *Conversation, edit *MessageEdit) error
	OnDelete     func(session any, conv *Conversation, msgID string) error
	OnRoomName   func(session any, conv *Conversation, name string) (bool, error)
	OnRoomTopic  func(session any, conv *Conversation, topic string) (bool, error)

	// Turn management (optional)
	TurnManagement *TurnConfig

	// Capabilities (optional, dynamic per-conversation)
	GetCapabilities func(session any, conv *Conversation) *RoomFeatures

	// Search & chat ops (optional)
	SearchUsers       func(ctx context.Context, session any, query string) ([]*bridgev2.ResolveIdentifierResponse, error)
	GetContactList    func(ctx context.Context, session any) ([]*bridgev2.ResolveIdentifierResponse, error)
	ResolveIdentifier func(ctx context.Context, session any, id string, createChat bool) (*bridgev2.ResolveIdentifierResponse, error)
	CreateChat        func(ctx context.Context, session any, params *CreateChatParams) (*bridgev2.CreateChatResponse, error)
	DeleteChat        func(conv *Conversation) error
	GetChatInfo       func(conv *Conversation) (*bridgev2.ChatInfo, error)
	GetUserInfo       func(ghost *bridgev2.Ghost) (*bridgev2.UserInfo, error)
	IsThisUser        func(userID string) bool

	// Commands
	Commands []Command

	// Room features (static default; overridden by GetCapabilities if set)
	RoomFeatures *RoomFeatures // nil = AI agent defaults

	// Login — use bridgev2 types directly.
	LoginFlows    []bridgev2.LoginFlow // nil = single auto-login
	GetLoginFlows func() []bridgev2.LoginFlow
	CreateLogin   func(ctx context.Context, user *bridgev2.User, flowID string) (bridgev2.LoginProcess, error) // nil = auto-login
	AcceptLogin   func(login *bridgev2.UserLogin) (bool, string)

	// Connector lifecycle and overrides.
	InitConnector       func(br *bridgev2.Bridge)
	StartConnector      func(ctx context.Context, br *bridgev2.Bridge) error
	StopConnector       func(ctx context.Context, br *bridgev2.Bridge)
	BridgeName          func() bridgev2.BridgeName
	NetworkCapabilities func() *bridgev2.NetworkGeneralCapabilities
	BridgeInfoVersion   func() (info, capabilities int)
	FillBridgeInfo      func(portal *bridgev2.Portal, content *event.BridgeEventContent)
	MakeBrokenLogin     func(login *bridgev2.UserLogin, reason string) *agentremote.BrokenLoginClient
	LoadLogin           func(ctx context.Context, login *bridgev2.UserLogin) error
	CreateClient        func(login *bridgev2.UserLogin) (bridgev2.NetworkAPI, error)
	UpdateClient        func(client bridgev2.NetworkAPI, login *bridgev2.UserLogin)
	AfterLoadClient     func(client bridgev2.NetworkAPI)
	ProviderIdentity    ProviderIdentity
	ClientCacheMu       *sync.Mutex
	ClientCache         *map[networkid.UserLoginID]bridgev2.NetworkAPI

	// Backfill — use bridgev2 types directly.
	FetchMessages func(ctx context.Context, params bridgev2.FetchMessagesParams) (*bridgev2.FetchMessagesResponse, error) // nil = no backfill

	// Advanced
	ProtocolID     string                    // default: "sdk-<Name>"
	Port           int                       // default: 29400
	DBName         string                    // default: "<Name>.db"
	ConfigPath     string                    // default: auto-discover
	DBMeta         func() database.MetaTypes // nil = default
	ExampleConfig  string                    // YAML
	ConfigData     any                       // config struct pointer
	ConfigUpgrader configupgrade.Upgrader
}

Config configures the SDK bridge.

func NewStandardConnectorConfig

func NewStandardConnectorConfig(p StandardConnectorConfigParams) *Config

NewStandardConnectorConfig builds the common bridgesdk.Config skeleton used by the dedicated bridge connectors.

type Conversation

type Conversation struct {
	ID    string
	Title string
	// contains filtered or unexported fields
}

Conversation represents a chat room the agent is participating in.

func NewConversation

func NewConversation(ctx context.Context, login *bridgev2.UserLogin, portal *bridgev2.Portal, sender bridgev2.EventSender, cfg *Config, session any, opts ...NewConversationOptions) *Conversation

NewConversation creates an SDK conversation wrapper for provider bridges that want to drive SDK turns without using the default sdkClient implementation.

func (*Conversation) BroadcastCapabilities

func (c *Conversation) BroadcastCapabilities(ctx context.Context) error

BroadcastCapabilities computes and sends room capability state events.

func (*Conversation) Context

func (c *Conversation) Context() context.Context

Context returns the conversation's context.

func (*Conversation) EnsureRoomAgent

func (c *Conversation) EnsureRoomAgent(ctx context.Context, agent *Agent) error

EnsureRoomAgent ensures the agent is part of the room agent set.

func (*Conversation) Login

func (c *Conversation) Login() *bridgev2.UserLogin

Login returns the underlying bridgev2.UserLogin.

func (*Conversation) LoginHandle

func (c *Conversation) LoginHandle() *LoginHandle

LoginHandle returns the login-scoped conversation helper.

func (*Conversation) Portal

func (c *Conversation) Portal() *bridgev2.Portal

Portal returns the underlying bridgev2.Portal.

func (*Conversation) QueueRemoteEvent

func (c *Conversation) QueueRemoteEvent(evt bridgev2.RemoteEvent)

QueueRemoteEvent queues a remote event for processing.

func (*Conversation) RoomAgents

func (c *Conversation) RoomAgents(ctx context.Context) (*RoomAgentSet, error)

RoomAgents returns the current room agent set.

func (*Conversation) SendHTML

func (c *Conversation) SendHTML(ctx context.Context, text, html string) error

SendHTML sends a message with both plaintext and HTML body.

func (*Conversation) SendMedia

func (c *Conversation) SendMedia(ctx context.Context, data []byte, mediaType, filename string) error

SendMedia sends a media message.

func (*Conversation) SendNotice

func (c *Conversation) SendNotice(ctx context.Context, text string) error

SendNotice sends a notice message.

func (*Conversation) Sender

func (c *Conversation) Sender() bridgev2.EventSender

Sender returns the event sender for this conversation.

func (*Conversation) Session

func (c *Conversation) Session() any

Session returns the session state from the client, if available.

func (*Conversation) SetRoomName

func (c *Conversation) SetRoomName(ctx context.Context, name string) error

SetRoomName sets the room name.

func (*Conversation) SetRoomTopic

func (c *Conversation) SetRoomTopic(ctx context.Context, topic string) error

SetRoomTopic sets the room topic.

func (*Conversation) SetTyping

func (c *Conversation) SetTyping(ctx context.Context, typing bool) error

SetTyping sets the typing indicator for this conversation.

func (*Conversation) Spec

func (c *Conversation) Spec() ConversationSpec

Spec returns the current persisted conversation spec snapshot.

func (*Conversation) StartTurn

func (c *Conversation) StartTurn(ctx context.Context, agent *Agent, source *SourceRef) *Turn

StartTurn creates a new Turn for this conversation.

func (*Conversation) Stream

func (c *Conversation) Stream(ctx context.Context) *Turn

Stream starts a new streaming response in this conversation.

type ConversationKind

type ConversationKind string

ConversationKind identifies the runtime shape of a conversation.

const (
	ConversationKindNormal    ConversationKind = "normal"
	ConversationKindDelegated ConversationKind = "delegated"
)

type ConversationSpec

type ConversationSpec struct {
	PortalID             string
	Kind                 ConversationKind
	Visibility           ConversationVisibility
	ParentConversationID string
	ParentEventID        string
	Title                string
	Metadata             map[string]any
	ArchiveOnCompletion  bool
}

ConversationSpec describes how to resolve or create a conversation.

type ConversationStateCarrier

type ConversationStateCarrier interface {
	GetSDKPortalMetadata() *SDKPortalMetadata
	SetSDKPortalMetadata(*SDKPortalMetadata)
}

ConversationStateCarrier allows bridge-specific portal metadata types to preserve SDK conversation state alongside their own fields.

type ConversationVisibility

type ConversationVisibility string

ConversationVisibility controls whether the room should be hidden in the client.

const (
	ConversationVisibilityNormal ConversationVisibility = "normal"
	ConversationVisibilityHidden ConversationVisibility = "hidden"
)

type CreateChatParams

type CreateChatParams struct {
	UserID   string
	Name     string
	Metadata map[string]any
}

CreateChatParams contains parameters for creating a new chat.

type FinalEditPayload

type FinalEditPayload struct {
	Content       *event.MessageEventContent
	TopLevelExtra map[string]any
	ReplyTo       id.EventID
	ThreadRoot    id.EventID
}

type FinalMetadataProvider

type FinalMetadataProvider interface {
	FinalMetadata(turn *Turn, finishReason string) any
}

type FinalMetadataProviderFunc

type FinalMetadataProviderFunc func(turn *Turn, finishReason string) any

func (FinalMetadataProviderFunc) FinalMetadata

func (f FinalMetadataProviderFunc) FinalMetadata(turn *Turn, finishReason string) any

type LoginHandle

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

LoginHandle wraps a UserLogin and provides convenience methods for creating conversations and accessing login state.

func (*LoginHandle) Conversation

func (l *LoginHandle) Conversation(ctx context.Context, portalID string) (*Conversation, error)

Conversation returns a Conversation for the given portal ID.

func (*LoginHandle) EnsureConversation

func (l *LoginHandle) EnsureConversation(ctx context.Context, spec ConversationSpec) (*Conversation, error)

EnsureConversation resolves or creates a conversation for the given spec.

func (*LoginHandle) UserLogin

func (l *LoginHandle) UserLogin() *bridgev2.UserLogin

UserLogin returns the underlying bridgev2.UserLogin.

type LoginInfo

type LoginInfo struct {
	UserID   string
	Domain   string
	Login    *bridgev2.UserLogin // escape hatch
	Metadata map[string]any
}

LoginInfo contains information about a bridge login.

type Message

type Message struct {
	ID        string
	Text      string
	HTML      string
	MediaURL  string      // MXC URL for media messages
	MediaType string      // MIME type
	MsgType   MessageType // Text, Image, Audio, Video, File
	Sender    string
	ReplyTo   string // event ID being replied to
	Timestamp time.Time
	Metadata  map[string]any

	// Escape hatches for power users.
	RawEvent *event.Event
	RawMsg   *bridgev2.MatrixMessage
}

Message represents an incoming user message.

type MessageEdit

type MessageEdit struct {
	OriginalID string
	NewText    string
	NewHTML    string
	RawEdit    *bridgev2.MatrixEdit
}

MessageEdit represents an edit to a previously sent message.

type MessageType

type MessageType string

MessageType identifies the kind of message.

const (
	MessageText  MessageType = "text"
	MessageImage MessageType = "image"
	MessageAudio MessageType = "audio"
	MessageVideo MessageType = "video"
	MessageFile  MessageType = "file"
)

type ModelInfo

type ModelInfo struct {
	ID           string
	Name         string
	Provider     string
	Capabilities []string
}

ModelInfo describes an AI model.

type NewConversationOptions

type NewConversationOptions struct {
	ApprovalFlow *agentremote.ApprovalFlow[*pendingSDKApprovalData]
}

NewConversationOptions configures optional parameters for NewConversation.

type PartApplyOptions

type PartApplyOptions struct {
	ResetMetadataOnStartMarkers     bool
	ResetMetadataOnEmptyMessageMeta bool
	ResetMetadataOnEmptyTextDelta   bool
	ResetMetadataOnAbort            bool
	ResetMetadataOnDataParts        bool
	HandleTerminalEvents            bool
	DefaultFinishReason             string
}

PartApplyOptions controls provider-specific edge cases when applying streamed UI/tool parts to a turn.

type PlaceholderMessagePayload

type PlaceholderMessagePayload struct {
	Content    *event.MessageEventContent
	Extra      map[string]any
	DBMetadata any
}

type PortalLifecycleOptions

type PortalLifecycleOptions struct {
	Login                *bridgev2.UserLogin
	Portal               *bridgev2.Portal
	ChatInfo             *bridgev2.ChatInfo
	SaveBeforeCreate     bool
	CleanupOnCreateError func(context.Context, *bridgev2.Portal)
	AIRoomKind           string
	ForceCapabilities    bool
	RefreshExtra         func(context.Context, *bridgev2.Portal)
}

type PromptBlock

type PromptBlock struct {
	Type PromptBlockType

	Text string

	ImageURL string
	ImageB64 string
	MimeType string

	FileURL  string
	FileB64  string
	Filename string

	ToolCallID        string
	ToolName          string
	ToolCallArguments string

	AudioB64    string
	AudioFormat string

	VideoURL string
	VideoB64 string
}

type PromptBlockType

type PromptBlockType string
const (
	PromptBlockText     PromptBlockType = "text"
	PromptBlockImage    PromptBlockType = "image"
	PromptBlockFile     PromptBlockType = "file"
	PromptBlockThinking PromptBlockType = "thinking"
	PromptBlockToolCall PromptBlockType = "tool_call"
	PromptBlockAudio    PromptBlockType = "audio"
	PromptBlockVideo    PromptBlockType = "video"
)

type PromptContext

type PromptContext struct {
	SystemPrompt    string
	DeveloperPrompt string
	Messages        []PromptMessage
}

PromptContext is the canonical provider-facing prompt representation.

func ChatMessagesToPromptContext

func ChatMessagesToPromptContext(messages []openai.ChatCompletionMessageParamUnion) PromptContext

ChatMessagesToPromptContext converts chat-completions-shaped messages into the canonical prompt model.

func UserPromptContext

func UserPromptContext(blocks ...PromptBlock) PromptContext

type PromptMessage

type PromptMessage struct {
	Role       PromptRole
	Blocks     []PromptBlock
	ToolCallID string
	ToolName   string
	IsError    bool
}

func PromptMessagesFromTurnData

func PromptMessagesFromTurnData(td TurnData) []PromptMessage

func (PromptMessage) Text

func (m PromptMessage) Text() string

type PromptRole

type PromptRole string
const (
	PromptRoleUser       PromptRole = "user"
	PromptRoleAssistant  PromptRole = "assistant"
	PromptRoleToolResult PromptRole = "tool_result"
)

type ProviderIdentity

type ProviderIdentity struct {
	IDPrefix      string
	LogKey        string
	StatusNetwork string
}

ProviderIdentity controls provider-specific IDs and status naming used by the SDK runtime.

type Reaction

type Reaction struct {
	MessageID string
	Emoji     string
	Sender    string
	RawMsg    *bridgev2.MatrixReaction
}

Reaction represents a user reaction on a message.

type RoomAgentSet

type RoomAgentSet struct {
	AgentIDs []string
}

RoomAgentSet tracks the agents available in a conversation.

type RoomFeatures

type RoomFeatures struct {
	MaxTextLength        int
	SupportsImages       bool
	SupportsAudio        bool
	SupportsVideo        bool
	SupportsFiles        bool
	SupportsReply        bool
	SupportsEdit         bool
	SupportsDelete       bool
	SupportsReactions    bool
	SupportsTyping       bool
	SupportsReadReceipts bool
	SupportsDeleteChat   bool
	CustomCapabilityID   string              // for dynamic capability IDs
	Custom               *event.RoomFeatures // escape hatch: override everything
}

RoomFeatures describes what a room supports.

type SDKPortalMetadata

type SDKPortalMetadata struct {
	Conversation sdkConversationState `json:"conversation,omitempty"`
}

SDKPortalMetadata can be used as a connector portal metadata type when the SDK owns the portal metadata schema.

type SourceKind

type SourceKind string

SourceKind identifies the origin of a turn.

const (
	SourceKindUserMessage SourceKind = "user_message"
	SourceKindProactive   SourceKind = "proactive"
	SourceKindSystem      SourceKind = "system"
	SourceKindBackfill    SourceKind = "backfill"
	SourceKindDelegated   SourceKind = "delegated"
	SourceKindSteering    SourceKind = "steering"
	SourceKindFollowUp    SourceKind = "follow_up"
)

type SourceRef

type SourceRef struct {
	Kind                 SourceKind
	EventID              string
	SenderID             string
	ParentConversationID string
	Metadata             map[string]any
}

SourceRef captures the source metadata that a turn should relate to.

func UserMessageSource

func UserMessageSource(eventID string) *SourceRef

Convenience helpers for common source kinds.

type StandardConnectorConfigParams

type StandardConnectorConfigParams struct {
	Name                 string
	Description          string
	ProtocolID           string
	ProviderIdentity     ProviderIdentity
	ClientCacheMu        *sync.Mutex
	ClientCache          *map[networkid.UserLoginID]bridgev2.NetworkAPI
	AgentCatalog         AgentCatalog
	GetCapabilities      func(session any, conv *Conversation) *RoomFeatures
	InitConnector        func(br *bridgev2.Bridge)
	StartConnector       func(ctx context.Context, br *bridgev2.Bridge) error
	StopConnector        func(ctx context.Context, br *bridgev2.Bridge)
	DisplayName          string
	NetworkURL           string
	NetworkIcon          string
	NetworkID            string
	BeeperBridgeType     string
	DefaultPort          uint16
	DefaultCommandPrefix func() string
	ExampleConfig        string
	ConfigData           any
	ConfigUpgrader       configupgrade.Upgrader
	NewPortal            func() any
	NewMessage           func() any
	NewLogin             func() any
	NewGhost             func() any
	NetworkCapabilities  func() *bridgev2.NetworkGeneralCapabilities
	FillBridgeInfo       func(portal *bridgev2.Portal, content *event.BridgeEventContent)
	AcceptLogin          func(login *bridgev2.UserLogin) (bool, string)
	MakeBrokenLogin      func(login *bridgev2.UserLogin, reason string) *agentremote.BrokenLoginClient
	LoadLogin            func(ctx context.Context, login *bridgev2.UserLogin) error
	CreateClient         func(login *bridgev2.UserLogin) (bridgev2.NetworkAPI, error)
	UpdateClient         func(client bridgev2.NetworkAPI, login *bridgev2.UserLogin)
	AfterLoadClient      func(client bridgev2.NetworkAPI)
	LoginFlows           []bridgev2.LoginFlow
	GetLoginFlows        func() []bridgev2.LoginFlow
	CreateLogin          func(ctx context.Context, user *bridgev2.User, flowID string) (bridgev2.LoginProcess, error)
}

type StreamPartState

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

func (*StreamPartState) AccumulatedText

func (s *StreamPartState) AccumulatedText() string

func (*StreamPartState) ApplyPart

func (s *StreamPartState) ApplyPart(part map[string]any, partTimestamp time.Time)

func (*StreamPartState) CompletedAtMs

func (s *StreamPartState) CompletedAtMs() int64

func (*StreamPartState) ErrorText

func (s *StreamPartState) ErrorText() string

func (*StreamPartState) FinishReason

func (s *StreamPartState) FinishReason() string

func (*StreamPartState) FirstTokenAtMs

func (s *StreamPartState) FirstTokenAtMs() int64

func (*StreamPartState) LastVisibleText

func (s *StreamPartState) LastVisibleText() string

func (*StreamPartState) SetCompletedAtMs

func (s *StreamPartState) SetCompletedAtMs(v int64)

func (*StreamPartState) SetErrorText

func (s *StreamPartState) SetErrorText(errText string)

func (*StreamPartState) SetFinishReason

func (s *StreamPartState) SetFinishReason(reason string)

func (*StreamPartState) SetFirstTokenAtMs

func (s *StreamPartState) SetFirstTokenAtMs(v int64)

func (*StreamPartState) SetLastVisibleText

func (s *StreamPartState) SetLastVisibleText(text string)

func (*StreamPartState) SetStartedAtMs

func (s *StreamPartState) SetStartedAtMs(v int64)

func (*StreamPartState) StartedAtMs

func (s *StreamPartState) StartedAtMs() int64

func (*StreamPartState) VisibleText

func (s *StreamPartState) VisibleText() string

type ToolApprovalResponse

type ToolApprovalResponse struct {
	Approved bool
	Always   bool   // "always allow this tool"
	Reason   string // allow_once, allow_always, deny, timeout, expired
}

ToolApprovalResponse is the user's decision on a tool approval request.

type ToolInputOptions

type ToolInputOptions struct {
	ToolName         string
	ProviderExecuted bool
	DisplayTitle     string
	Extra            map[string]any
}

ToolInputOptions controls how a tool input start is represented in the SDK UI stream.

type ToolOutputOptions

type ToolOutputOptions struct {
	ProviderExecuted bool
	Streaming        bool
	Extra            map[string]any
}

ToolOutputOptions controls how a tool output is represented in the SDK UI stream.

type ToolsController

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

func (*ToolsController) Denied

func (c *ToolsController) Denied(ctx context.Context, toolCallID string)

Denied emits a denied tool result.

func (*ToolsController) EnsureInputStart

func (c *ToolsController) EnsureInputStart(ctx context.Context, toolCallID string, input any, opts ToolInputOptions)

EnsureInputStart ensures the tool input UI exists and optionally publishes input.

func (*ToolsController) Input

func (c *ToolsController) Input(ctx context.Context, toolCallID, toolName string, input any, providerExecuted bool)

Input emits a complete tool input payload.

func (*ToolsController) InputDelta

func (c *ToolsController) InputDelta(ctx context.Context, toolCallID, toolName, delta string, providerExecuted bool)

InputDelta emits a tool input delta.

func (*ToolsController) InputError

func (c *ToolsController) InputError(ctx context.Context, toolCallID, toolName, rawInput, errText string, providerExecuted bool)

InputError emits a tool input parsing error.

func (*ToolsController) Output

func (c *ToolsController) Output(ctx context.Context, toolCallID string, output any, opts ToolOutputOptions)

Output emits a tool output payload.

func (*ToolsController) OutputError

func (c *ToolsController) OutputError(ctx context.Context, toolCallID, errText string, providerExecuted bool)

OutputError emits a tool error payload.

type Turn

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

Turn is the central abstraction for an AI response turn.

func (*Turn) Abort

func (t *Turn) Abort(reason string)

Abort aborts the turn.

func (*Turn) Agent

func (t *Turn) Agent() *Agent

Agent returns the turn's selected agent.

func (*Turn) Approvals

func (t *Turn) Approvals() *ApprovalController

Approvals returns the turn's approval controller.

func (*Turn) Context

func (t *Turn) Context() context.Context

Context returns the turn-scoped context.

func (*Turn) Emitter

func (t *Turn) Emitter() *streamui.Emitter

Emitter returns the underlying streamui.Emitter for escape hatch access.

func (*Turn) End

func (t *Turn) End(finishReason string)

End finishes the turn with a reason.

func (*Turn) EndWithError

func (t *Turn) EndWithError(errText string)

EndWithError finishes the turn with an error.

func (*Turn) Err

func (t *Turn) Err() error

Err returns any startup error encountered by the turn transport.

func (*Turn) ID

func (t *Turn) ID() string

ID returns the turn's unique identifier.

func (*Turn) InitialEventID

func (t *Turn) InitialEventID() id.EventID

InitialEventID returns the Matrix event ID of the placeholder message.

func (*Turn) NetworkMessageID

func (t *Turn) NetworkMessageID() networkid.MessageID

NetworkMessageID returns the bridge network message ID of the placeholder.

func (*Turn) SendStatus

func (t *Turn) SendStatus(status event.MessageStatus, message string)

SendStatus emits a bridge-level status update for the source event when possible.

func (*Turn) Session

func (t *Turn) Session() *turns.StreamSession

Session returns the underlying turns.StreamSession.

func (*Turn) SetFinalEditPayload

func (t *Turn) SetFinalEditPayload(payload *FinalEditPayload)

SetFinalEditPayload stores the final edit payload that the SDK should send when the turn completes.

func (*Turn) SetFinalMetadataProvider

func (t *Turn) SetFinalMetadataProvider(provider FinalMetadataProvider)

SetFinalMetadataProvider overrides the final DB metadata object persisted for the assistant message.

func (*Turn) SetID

func (t *Turn) SetID(turnID string)

SetID overrides the turn identifier before the turn starts. Provider bridges can use this to preserve upstream turn/message IDs in SDK-managed streams.

func (*Turn) SetPlaceholderMessagePayload

func (t *Turn) SetPlaceholderMessagePayload(payload *PlaceholderMessagePayload)

SetPlaceholderMessagePayload overrides the placeholder message content while leaving stream descriptor attachment and relation wiring to the SDK.

func (*Turn) SetReplyTo

func (t *Turn) SetReplyTo(eventID id.EventID)

SetReplyTo sets the m.in_reply_to relation for this turn's message.

func (*Turn) SetSendFunc

func (t *Turn) SetSendFunc(fn func(ctx context.Context) (id.EventID, networkid.MessageID, error))

SetSendFunc overrides the default placeholder message sending in ensureStarted. The function should send the initial message and return the event/message IDs.

func (*Turn) SetSender

func (t *Turn) SetSender(sender bridgev2.EventSender)

SetSender overrides the bridge sender used for turn output. Call before the turn produces visible output.

func (*Turn) SetStreamHook

func (t *Turn) SetStreamHook(hook func(turnID string, seq int, content map[string]any, txnID string) bool)

SetStreamHook captures stream envelopes instead of sending ephemeral Matrix events when provided.

func (*Turn) SetStreamPublisherFunc

func (t *Turn) SetStreamPublisherFunc(fn func(ctx context.Context) (bridgev2.BeeperStreamPublisher, bool))

SetStreamPublisherFunc overrides how the Turn resolves the shared stream publisher.

func (*Turn) SetStreamTransport

func (t *Turn) SetStreamTransport(fn func(ctx context.Context, portal *bridgev2.Portal, part map[string]any))

SetStreamTransport overrides the stream delivery mechanism. The provided function is called for every emitted part instead of the default session- based transport. UIState tracking (ApplyChunk) is still handled automatically.

func (*Turn) SetSuppressFinalEdit

func (t *Turn) SetSuppressFinalEdit(suppress bool)

SetSuppressFinalEdit disables the SDK's automatic final edit construction when the bridge does not provide an explicit final edit payload.

func (*Turn) SetSuppressSend

func (t *Turn) SetSuppressSend(suppress bool)

SetSuppressSend prevents the turn from sending any messages to the room. The turn still tracks state and emits UI events for local consumption.

func (*Turn) SetThread

func (t *Turn) SetThread(rootEventID id.EventID)

SetThread sets the m.thread relation for this turn's message.

func (*Turn) Source

func (t *Turn) Source() *SourceRef

Source returns the turn's structured source reference.

func (*Turn) Stream

func (t *Turn) Stream() *TurnStream

Stream returns the turn's transport/escape-hatch surface.

func (*Turn) StreamDescriptor

func (t *Turn) StreamDescriptor(ctx context.Context) (*event.BeeperStreamInfo, error)

StreamDescriptor returns the com.beeper.stream descriptor for the turn's placeholder message.

func (*Turn) SuppressSend

func (t *Turn) SuppressSend() bool

SuppressSend reports whether room sends are currently suppressed.

func (*Turn) ThreadRoot added in v0.0.3

func (t *Turn) ThreadRoot() id.EventID

ThreadRoot returns the Matrix thread root event ID for this turn.

func (*Turn) UIState

func (t *Turn) UIState() *streamui.UIState

UIState returns the underlying streamui.UIState.

func (*Turn) VisibleText

func (t *Turn) VisibleText() string

VisibleText returns the raw text body accumulated through the semantic writer.

func (*Turn) Writer

func (t *Turn) Writer() *Writer

Writer returns the turn's canonical semantic writer surface.

type TurnConfig

type TurnConfig struct {
	OneAtATime bool
	DebounceMs int
	QueueSize  int
	// IdleTimeoutMs aborts turns that stop emitting streamed parts for too long.
	// Zero uses the SDK default; a negative value disables the watchdog.
	IdleTimeoutMs int

	// KeyFunc customizes the serialization key. By default, the portal ID is
	// used directly. Multi-agent rooms can return "roomID:agentID" so that
	// agents within the same room run concurrently.
	KeyFunc func(portalID string) string
}

TurnConfig configures helper-managed turn serialization and coalescing.

type TurnData

type TurnData struct {
	ID       string         `json:"id,omitempty"`
	Role     string         `json:"role,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
	Extra    map[string]any `json:"extra,omitempty"`
	Parts    []TurnPart     `json:"parts,omitempty"`
}

TurnData is the SDK-owned semantic turn record used as the canonical source of truth for persistence. PromptContext and UIMessage are derived views.

func BuildTurnDataFromUIMessage

func BuildTurnDataFromUIMessage(uiMessage map[string]any, opts TurnDataBuildOptions) TurnData

BuildTurnDataFromUIMessage merges semantic runtime data into turn data derived from a UIMessage snapshot.

func DecodeTurnData

func DecodeTurnData(raw map[string]any) (TurnData, bool)

func TurnDataFromUIMessage

func TurnDataFromUIMessage(uiMessage map[string]any) (TurnData, bool)

TurnDataFromUIMessage derives semantic turn data from a UIMessage. This is primarily used by the SDK turn runtime, where the canonical turn record is assembled from the same streaming state that drives UI deltas.

func TurnDataFromUserPromptMessages

func TurnDataFromUserPromptMessages(messages []PromptMessage) (TurnData, bool)

func (TurnData) Clone

func (td TurnData) Clone() TurnData

func (TurnData) ToMap

func (td TurnData) ToMap() map[string]any

type TurnDataBuildOptions

type TurnDataBuildOptions struct {
	ID             string
	Role           string
	Metadata       map[string]any
	Text           string
	Reasoning      string
	ToolCalls      []agentremote.ToolCallMetadata
	GeneratedFiles []agentremote.GeneratedFileRef
	ArtifactParts  []map[string]any
}

TurnDataBuildOptions describes provider/runtime-specific data that should be merged into canonical turn data derived from a UI message snapshot.

type TurnManager

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

TurnManager provides reusable per-key run helpers.

func NewTurnManager

func NewTurnManager(cfg *TurnConfig) *TurnManager

NewTurnManager creates a new helper-managed turn manager.

func (*TurnManager) Acquire

func (tm *TurnManager) Acquire(ctx context.Context, key string) (func(), error)

Acquire reserves the key until the returned release function is called.

func (*TurnManager) DebounceWindow

func (tm *TurnManager) DebounceWindow() time.Duration

DebounceWindow returns the configured debounce interval.

func (*TurnManager) IsActive

func (tm *TurnManager) IsActive(key string) bool

IsActive reports whether the key currently has an active run.

func (*TurnManager) QueueLimit

func (tm *TurnManager) QueueLimit() int

QueueLimit returns the configured queue size hint.

func (*TurnManager) ResolveKey

func (tm *TurnManager) ResolveKey(portalID string) string

ResolveKey applies the configured KeyFunc (or identity) to a portal ID.

func (*TurnManager) Run

func (tm *TurnManager) Run(ctx context.Context, key string, fn func(context.Context) error) error

Run serializes fn for the given key when one-at-a-time is enabled. When DebounceMs > 0, the first call is delayed to coalesce rapid messages.

type TurnPart

type TurnPart struct {
	Type             string         `json:"type"`
	State            string         `json:"state,omitempty"`
	Text             string         `json:"text,omitempty"`
	Reasoning        string         `json:"reasoning,omitempty"`
	ToolCallID       string         `json:"toolCallId,omitempty"`
	ToolName         string         `json:"toolName,omitempty"`
	ToolType         string         `json:"toolType,omitempty"`
	Input            any            `json:"input,omitempty"`
	Output           any            `json:"output,omitempty"`
	ErrorText        string         `json:"errorText,omitempty"`
	Approval         map[string]any `json:"approval,omitempty"`
	URL              string         `json:"url,omitempty"`
	Title            string         `json:"title,omitempty"`
	Filename         string         `json:"filename,omitempty"`
	MediaType        string         `json:"mediaType,omitempty"`
	ProviderExecuted bool           `json:"providerExecuted,omitempty"`
	Extra            map[string]any `json:"extra,omitempty"`
}

TurnPart is a semantic unit within a turn. It intentionally keeps a stable shape that can be projected into UI parts and provider prompt messages.

type TurnSnapshot

type TurnSnapshot struct {
	TurnData        TurnData
	UIMessage       map[string]any
	PromptMessages  []PromptMessage
	Body            string
	ThinkingContent string
	ToolCalls       []agentremote.ToolCallMetadata
	GeneratedFiles  []agentremote.GeneratedFileRef
}

func BuildTurnSnapshot

func BuildTurnSnapshot(uiMessage map[string]any, opts TurnDataBuildOptions, toolType string) TurnSnapshot

func SnapshotFromTurnData

func SnapshotFromTurnData(td TurnData, toolType string) TurnSnapshot

type TurnStream

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

TurnStream is the transport/escape-hatch surface for a turn.

func (*TurnStream) Emitter

func (s *TurnStream) Emitter() *streamui.Emitter

Emitter returns the underlying stream emitter as an escape hatch.

func (*TurnStream) SetTransport

func (s *TurnStream) SetTransport(hook func(turnID string, seq int, content map[string]any, txnID string) bool)

SetTransport configures a custom transport for streamed turn events.

type UIStateReplayer

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

func NewUIStateReplayer

func NewUIStateReplayer(state *streamui.UIState) UIStateReplayer

func (UIStateReplayer) ApprovalRequest

func (r UIStateReplayer) ApprovalRequest(approvalID, toolCallID string)

func (UIStateReplayer) Artifact

func (r UIStateReplayer) Artifact(sourceID string, citation citations.SourceCitation, doc citations.SourceDocument, mediaType string)

func (UIStateReplayer) DataPart

func (r UIStateReplayer) DataPart(part map[string]any)

func (UIStateReplayer) File

func (r UIStateReplayer) File(url, mediaType, filename string)

func (UIStateReplayer) Finish

func (r UIStateReplayer) Finish(finishReason string, metadata map[string]any)

func (UIStateReplayer) Reasoning

func (r UIStateReplayer) Reasoning(partID, text string)

func (UIStateReplayer) SourceDocument

func (r UIStateReplayer) SourceDocument(doc citations.SourceDocument)

func (UIStateReplayer) SourceURL

func (r UIStateReplayer) SourceURL(citation citations.SourceCitation, sourceID string)

func (UIStateReplayer) Start

func (r UIStateReplayer) Start(metadata map[string]any)

func (UIStateReplayer) StepFinish

func (r UIStateReplayer) StepFinish()

func (UIStateReplayer) StepStart

func (r UIStateReplayer) StepStart()

func (UIStateReplayer) Text

func (r UIStateReplayer) Text(partID, text string)

func (UIStateReplayer) ToolInput

func (r UIStateReplayer) ToolInput(toolCallID, toolName string, input any, providerExecuted bool)

func (UIStateReplayer) ToolInputText

func (r UIStateReplayer) ToolInputText(toolCallID, toolName, inputText string, providerExecuted bool)

func (UIStateReplayer) ToolOutput

func (r UIStateReplayer) ToolOutput(toolCallID string, output any, providerExecuted bool)

func (UIStateReplayer) ToolOutputDenied

func (r UIStateReplayer) ToolOutputDenied(toolCallID string)

func (UIStateReplayer) ToolOutputError

func (r UIStateReplayer) ToolOutputError(toolCallID, errorText string, providerExecuted bool)

type UserInfo

type UserInfo struct {
	ID       string
	Name     string
	Avatar   string
	Metadata map[string]any
}

UserInfo describes a user/agent/model for search results.

type Writer

type Writer struct {
	State   *streamui.UIState
	Emitter *streamui.Emitter
	Portal  *bridgev2.Portal
	// contains filtered or unexported fields
}

Writer emits semantic turn parts onto a streamui emitter.

This is the canonical write surface for both SDK-managed turns and bridge- managed streaming state. Direct emitter access should be reserved for rare raw-part escape hatches only.

func (*Writer) Abort

func (w *Writer) Abort(ctx context.Context, reason string)

func (*Writer) Approvals

func (w *Writer) Approvals() *ApprovalController

Approvals returns the writer's approval controller.

func (*Writer) Data

func (w *Writer) Data(ctx context.Context, name string, payload any, transient bool)

Data emits a bridge-specific custom event using the reserved data-* namespace.

func (*Writer) Error

func (w *Writer) Error(ctx context.Context, errText string)

func (*Writer) File

func (w *Writer) File(ctx context.Context, url, mediaType string)

func (*Writer) Finish

func (w *Writer) Finish(ctx context.Context, finishReason string, metadata map[string]any)

func (*Writer) FinishReasoning

func (w *Writer) FinishReasoning(ctx context.Context)

func (*Writer) FinishText

func (w *Writer) FinishText(ctx context.Context)

func (*Writer) MessageMetadata

func (w *Writer) MessageMetadata(ctx context.Context, metadata map[string]any)

func (*Writer) RawPart

func (w *Writer) RawPart(ctx context.Context, part map[string]any)

RawPart emits an arbitrary stream part. This is the lowest-level escape hatch.

func (*Writer) ReasoningDelta

func (w *Writer) ReasoningDelta(ctx context.Context, delta string)

func (*Writer) SourceDocument

func (w *Writer) SourceDocument(ctx context.Context, document citations.SourceDocument)

func (*Writer) SourceURL

func (w *Writer) SourceURL(ctx context.Context, citation citations.SourceCitation)

func (*Writer) Start

func (w *Writer) Start(ctx context.Context, metadata map[string]any)

func (*Writer) StepFinish

func (w *Writer) StepFinish(ctx context.Context)

func (*Writer) StepStart

func (w *Writer) StepStart(ctx context.Context)

func (*Writer) TextDelta

func (w *Writer) TextDelta(ctx context.Context, delta string)

func (*Writer) Tools

func (w *Writer) Tools() *ToolsController

Tools returns the writer's tool streaming controller.

Jump to

Keyboard shortcuts

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