bridgeadapter

package
v0.0.0-...-f0e47c8 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RejectReasonOwnerOnly     = "only_owner"
	RejectReasonExpired       = "expired"
	RejectReasonInvalidOption = "invalid_option"
)
View Source
const (
	AIRoomKindAgent = "agent"
)
View Source
const ApprovalDecisionKey = "com.beeper.ai.approval_decision"
View Source
const DefaultApprovalExpiry = 10 * time.Minute

DefaultApprovalExpiry is the fallback expiry duration when no TTL is specified.

Variables

View Source
var (
	ErrApprovalMissingID      = errors.New("missing approval id")
	ErrApprovalMissingRoom    = errors.New("missing room id")
	ErrApprovalOnlyOwner      = errors.New("only the owner can approve")
	ErrApprovalUnknown        = errors.New("unknown or expired approval id")
	ErrApprovalWrongRoom      = errors.New("approval id does not belong to this room")
	ErrApprovalExpired        = errors.New("approval expired")
	ErrApprovalAlreadyHandled = errors.New("approval already resolved")
)

Shared sentinel errors for approval resolution.

Functions

func ApplyAIBridgeInfo

func ApplyAIBridgeInfo(content *event.BridgeEventContent, protocolID string, roomType database.RoomType, aiKind string)

func ApprovalErrorToastText

func ApprovalErrorToastText(err error) string

ApprovalErrorToastText maps an approval error to a user-facing toast string.

func BuildApprovalPromptBody

func BuildApprovalPromptBody(toolName string, options []ApprovalOption) string

func BuildBotUserInfo

func BuildBotUserInfo(name string, identifiers ...string) *bridgev2.UserInfo

BuildBotUserInfo returns a UserInfo for an AI bot ghost with the given name and identifiers.

func BuildChatInfoWithFallback

func BuildChatInfoWithFallback(metaTitle, portalName, fallbackTitle, portalTopic string) *bridgev2.ChatInfo

func BuildDMChatInfo

func BuildDMChatInfo(p DMChatInfoParams) *bridgev2.ChatInfo

BuildDMChatInfo creates a ChatInfo for a DM room between a human user and a bot ghost.

func BuildMetaTypes

func BuildMetaTypes(portal, message, userLogin, ghost func() any) database.MetaTypes

func BuildSystemNotice

func BuildSystemNotice(body string) *bridgev2.ConvertedMessage

BuildSystemNotice creates a ConvertedMessage containing a single MsgNotice part.

func ComputeApprovalExpiry

func ComputeApprovalExpiry(ttlSeconds int) time.Time

ComputeApprovalExpiry returns the expiry time based on ttlSeconds, falling back to DefaultApprovalExpiry when ttlSeconds <= 0.

func DefaultBridgeInfoVersion

func DefaultBridgeInfoVersion() (info, capabilities int)

DefaultBridgeInfoVersion returns the shared bridge info/capability schema version pair.

func DefaultNetworkCapabilities

func DefaultNetworkCapabilities() *bridgev2.NetworkGeneralCapabilities

DefaultNetworkCapabilities returns the common baseline capabilities for bridge connectors.

func DownloadAndEncodeMedia

func DownloadAndEncodeMedia(ctx context.Context, login *bridgev2.UserLogin, mediaURL string, encFile *event.EncryptedFileInfo, maxMB int) (string, string, error)

DownloadAndEncodeMedia downloads media from a Matrix content URI, enforces an optional size limit, and returns the base64-encoded content.

func EnsureClientMap

func EnsureClientMap(mu *sync.Mutex, clients *map[networkid.UserLoginID]bridgev2.NetworkAPI)

EnsureClientMap initializes the connector client cache map when needed.

func EnsureLoginMetadata

func EnsureLoginMetadata[T any](login *bridgev2.UserLogin) *T

func EnsurePortalMetadata

func EnsurePortalMetadata[T any](portal *bridgev2.Portal) *T

func EnsureReactionContent

func EnsureReactionContent(msg *bridgev2.MatrixReaction) *event.ReactionEventContent

EnsureReactionContent lazily parses the reaction content from a MatrixReaction.

func HumanUserID

func HumanUserID(prefix string, loginID networkid.UserLoginID) networkid.UserID

func IsMatrixBotUser

func IsMatrixBotUser(ctx context.Context, bridge *bridgev2.Bridge, userID id.UserID) bool

IsMatrixBotUser returns true if the given user ID belongs to the bridge bot or a ghost.

func LoadOrCreateClient

func LoadOrCreateClient(
	mu *sync.Mutex,
	clients map[networkid.UserLoginID]bridgev2.NetworkAPI,
	loginID networkid.UserLoginID,
	reuse func(existing bridgev2.NetworkAPI) bool,
	create func() (bridgev2.NetworkAPI, error),
) (bridgev2.NetworkAPI, error)

LoadOrCreateClient returns a cached client if reusable, otherwise creates and caches a new one.

func LoadOrCreateTypedClient

func LoadOrCreateTypedClient[T bridgev2.NetworkAPI](
	mu *sync.Mutex,
	clients map[networkid.UserLoginID]bridgev2.NetworkAPI,
	login *bridgev2.UserLogin,
	reuse func(T, *bridgev2.UserLogin),
	create func() (T, error),
) (T, error)

LoadOrCreateTypedClient wraps LoadOrCreateClient with typed reuse/create callbacks.

func LoadUserLogin

func LoadUserLogin[C bridgev2.NetworkAPI](login *bridgev2.UserLogin, cfg LoadUserLoginConfig[C]) error

LoadUserLogin loads or creates a typed client using LoadOrCreateTypedClient. On failure it assigns a BrokenLoginClient and returns nil error, matching the convention used by all bridge connectors.

func LoggerFromContext

func LoggerFromContext(ctx context.Context, fallback *zerolog.Logger) *zerolog.Logger

LoggerFromContext returns the logger from the context if available, otherwise falls back to the provided logger.

func MakeUserLoginID

func MakeUserLoginID(prefix string, mxid id.UserID, ordinal int) networkid.UserLoginID

MakeUserLoginID creates a login ID in the format "prefix:escaped-mxid[:ordinal]".

func MatrixEventTimestamp

func MatrixEventTimestamp(evt *event.Event) time.Time

MatrixEventTimestamp returns the event's timestamp as a time.Time, falling back to time.Now() if the event is nil or has no timestamp.

func MatrixMessageID

func MatrixMessageID(eventID id.EventID) networkid.MessageID

func MatrixSenderID

func MatrixSenderID(userID id.UserID) networkid.UserID

MatrixSenderID returns the standard networkid.UserID for a Matrix user.

func MessageSendStatusError

func MessageSendStatusError(
	err error,
	message string,
	reason event.MessageStatusReason,
	statusForError func(error) event.MessageStatus,
	reasonForError func(error) event.MessageStatusReason,
) error

func NewEventID

func NewEventID(prefix string) id.EventID

NewEventID generates a unique Matrix-style event ID with the given prefix.

func NewMessageID

func NewMessageID(prefix string) networkid.MessageID

NewMessageID generates a unique message ID in the format "prefix:uuid".

func NextUserLoginID

func NextUserLoginID(user *bridgev2.User, prefix string) networkid.UserLoginID

NextUserLoginID finds the next available ordinal for a login ID with the given prefix.

func NormalizeAIRoomTypeV2

func NormalizeAIRoomTypeV2(roomType database.RoomType, aiKind string) string

func PreHandleApprovalReaction

func PreHandleApprovalReaction(msg *bridgev2.MatrixReaction) (bridgev2.MatrixReactionPreResponse, error)

PreHandleApprovalReaction implements the common PreHandleMatrixReaction logic shared by all bridges. The SenderID is derived from the Matrix sender.

func PrimeUserLoginCache

func PrimeUserLoginCache(ctx context.Context, br *bridgev2.Bridge)

PrimeUserLoginCache preloads all logins into bridgev2's in-memory user/login caches.

func RedactApprovalPromptReactions

func RedactApprovalPromptReactions(
	ctx context.Context,
	login *bridgev2.UserLogin,
	portal *bridgev2.Portal,
	sender bridgev2.EventSender,
	targetMessage *database.Message,
	triggerEventID id.EventID,
	keepEventID id.EventID,
) error

RedactApprovalPromptReactions redacts all reactions on targetMessage except keepEventID. If targetMessage is nil and keepEventID is empty, triggerEventID is redacted directly.

func RedactEventAsSender

func RedactEventAsSender(
	ctx context.Context,
	login *bridgev2.UserLogin,
	portal *bridgev2.Portal,
	sender bridgev2.EventSender,
	targetEventID id.EventID,
) error

RedactEventAsSender redacts an event ID in a room using the intent resolved for sender.

func RemoveClientFromCache

func RemoveClientFromCache(
	mu *sync.Mutex,
	clients map[networkid.UserLoginID]bridgev2.NetworkAPI,
	loginID networkid.UserLoginID,
)

RemoveClientFromCache removes a client from the cache by login ID.

func SendAIRoomInfo

func SendAIRoomInfo(ctx context.Context, portal *bridgev2.Portal, aiKind string) bool

func SendDebouncedStreamEdit

func SendDebouncedStreamEdit(p SendDebouncedStreamEditParams) error

SendDebouncedStreamEdit builds and queues a debounced stream edit via the bridge pipeline.

func SendMatrixMessageStatus

func SendMatrixMessageStatus(
	ctx context.Context,
	portal *bridgev2.Portal,
	evt *event.Event,
	status bridgev2.MessageStatus,
)

func SendViaPortal

SendViaPortal sends a pre-built message through bridgev2's QueueRemoteEvent pipeline. If MsgID is empty, a new one is generated using IDPrefix.

func SingleLoginFlow

func SingleLoginFlow(enabled bool, flow bridgev2.LoginFlow) []bridgev2.LoginFlow

func StopClients

func StopClients(mu *sync.Mutex, clients *map[networkid.UserLoginID]bridgev2.NetworkAPI)

StopClients disconnects all cached clients that expose Disconnect().

func UnsupportedMessageStatus

func UnsupportedMessageStatus(err error) error

func UpsertAssistantMessage

func UpsertAssistantMessage(ctx context.Context, p UpsertAssistantMessageParams)

UpsertAssistantMessage updates an existing message's metadata or inserts a new one. If NetworkMessageID is set, tries to find and update the existing row first. Falls back to inserting a new row keyed by InitialEventID.

func ValidateSingleLoginFlow

func ValidateSingleLoginFlow(flowID, expectedFlowID string, enabled bool) error

Types

type ApprovalDecisionPayload

type ApprovalDecisionPayload struct {
	ApprovalID string
	Approved   bool
	Always     bool
	Reason     string
}

ApprovalDecisionPayload is the standardized decision type for all approval flows.

type ApprovalFlow

type ApprovalFlow[D any] struct {
	// contains filtered or unexported fields
}

ApprovalFlow owns the full lifecycle of approval prompts and pending approvals. D is the bridge-specific pending data type.

func NewApprovalFlow

func NewApprovalFlow[D any](cfg ApprovalFlowConfig[D]) *ApprovalFlow[D]

NewApprovalFlow creates an ApprovalFlow from the given config.

func (*ApprovalFlow[D]) Drop

func (f *ApprovalFlow[D]) Drop(approvalID string)

Drop removes a pending approval and its associated prompt from both stores.

func (*ApprovalFlow[D]) FindByData

func (f *ApprovalFlow[D]) FindByData(predicate func(data D) bool) string

FindByData iterates pending approvals and returns the id of the first one for which the predicate returns true. Returns "" if none match.

func (*ApprovalFlow[D]) Get

func (f *ApprovalFlow[D]) Get(approvalID string) *Pending[D]

Get returns the pending approval for the given id, or nil if not found.

func (*ApprovalFlow[D]) HandleReaction

func (f *ApprovalFlow[D]) HandleReaction(ctx context.Context, msg *bridgev2.MatrixReaction, targetEventID id.EventID, emoji string) bool

HandleReaction checks whether a reaction targets a known approval prompt. If so, it validates room, resolves the approval (via channel or DeliverDecision), and redacts prompt reactions.

func (*ApprovalFlow[D]) Register

func (f *ApprovalFlow[D]) Register(approvalID string, ttl time.Duration, data D) (*Pending[D], bool)

Register adds a new pending approval with the given TTL and bridge-specific data. Returns the Pending and true if newly created, or the existing one and false if a non-expired approval with the same ID already exists.

func (*ApprovalFlow[D]) Resolve

func (f *ApprovalFlow[D]) Resolve(approvalID string, decision ApprovalDecisionPayload) error

Resolve programmatically delivers a decision to a pending approval's channel. Use this when a decision arrives from an external source (e.g. the upstream server or auto-approval) rather than a Matrix reaction. Unlike HandleReaction, Resolve does NOT drop the pending entry — the caller (typically Wait or an explicit Drop) is responsible for cleanup.

func (*ApprovalFlow[D]) SendPrompt

func (f *ApprovalFlow[D]) SendPrompt(ctx context.Context, portal *bridgev2.Portal, params SendPromptParams)

SendPrompt builds an approval prompt message, registers it in the prompt store, sends it via the configured sender, binds the event ID, and queues prefill reactions.

func (*ApprovalFlow[D]) SetData

func (f *ApprovalFlow[D]) SetData(approvalID string, updater func(D) D) bool

SetData updates the Data field on a pending approval under the lock. Returns false if the approval is not found.

func (*ApprovalFlow[D]) Wait

func (f *ApprovalFlow[D]) Wait(ctx context.Context, approvalID string) (ApprovalDecisionPayload, bool)

Wait blocks until a decision arrives via reaction, the approval expires, or ctx is cancelled. Only useful for channel-based flows (DeliverDecision is nil).

type ApprovalFlowConfig

type ApprovalFlowConfig[D any] struct {
	// Login returns the current UserLogin. Required.
	Login func() *bridgev2.UserLogin

	// Sender returns the EventSender to use for a given portal (e.g. the agent ghost).
	Sender func(portal *bridgev2.Portal) bridgev2.EventSender

	// BackgroundContext optionally returns a context detached from the request lifecycle.
	BackgroundContext func(ctx context.Context) context.Context

	// RoomIDFromData extracts the stored room ID from pending data for validation.
	// Return "" to skip the room check.
	RoomIDFromData func(data D) id.RoomID

	// DeliverDecision is called for non-channel flows when a valid reaction resolves
	// an approval. The flow has already validated owner, expiration, and room.
	// If nil, the flow is channel-based: decisions are delivered via an internal
	// channel and retrieved with Wait().
	DeliverDecision func(ctx context.Context, portal *bridgev2.Portal, pending *Pending[D], decision ApprovalDecisionPayload) error

	// SendNotice sends a system notice to a portal. Used for error toasts.
	SendNotice func(ctx context.Context, portal *bridgev2.Portal, msg string)

	// DBMetadata produces bridge-specific metadata for the approval prompt message.
	// If nil, a default *BaseMessageMetadata is used.
	DBMetadata func(prompt ApprovalPromptMessage) any

	IDPrefix    string
	LogKey      string
	SendTimeout time.Duration
}

ApprovalFlowConfig holds the bridge-specific callbacks for ApprovalFlow.

type ApprovalOption

type ApprovalOption struct {
	ID          string `json:"id"`
	Key         string `json:"key"`
	FallbackKey string `json:"fallback_key,omitempty"`
	Label       string `json:"label,omitempty"`
	Approved    bool   `json:"approved"`
	Always      bool   `json:"always,omitempty"`
	Reason      string `json:"reason,omitempty"`
}

func DefaultApprovalOptions

func DefaultApprovalOptions() []ApprovalOption

type ApprovalPromptMessage

type ApprovalPromptMessage struct {
	Body      string
	UIMessage map[string]any
	Raw       map[string]any
	Options   []ApprovalOption
}

type ApprovalPromptMessageParams

type ApprovalPromptMessageParams struct {
	ApprovalID     string
	ToolCallID     string
	ToolName       string
	TurnID         string
	Body           string
	ReplyToEventID id.EventID
	ExpiresAt      time.Time
	Options        []ApprovalOption
}

type ApprovalPromptReactionMatch

type ApprovalPromptReactionMatch struct {
	KnownPrompt   bool
	ShouldResolve bool
	ApprovalID    string
	Decision      ApprovalDecisionPayload
	RejectReason  string
	Prompt        ApprovalPromptRegistration
}

type ApprovalPromptRegistration

type ApprovalPromptRegistration struct {
	ApprovalID    string
	RoomID        id.RoomID
	OwnerMXID     id.UserID
	ToolCallID    string
	ToolName      string
	TurnID        string
	ExpiresAt     time.Time
	Options       []ApprovalOption
	PromptEventID id.EventID
}

type ApprovalReactionHandler

type ApprovalReactionHandler interface {
	HandleReaction(ctx context.Context, msg *bridgev2.MatrixReaction, targetEventID id.EventID, emoji string) bool
}

ApprovalReactionHandler is the interface used by BaseReactionHandler to dispatch reactions to the approval system without knowing the concrete type.

type AssistantMetadataParams

type AssistantMetadataParams struct {
	Body             string
	FinishReason     string
	TurnID           string
	AgentID          string
	StartedAtMs      int64
	CompletedAtMs    int64
	ThinkingContent  string
	PromptTokens     int64
	CompletionTokens int64
	ReasoningTokens  int64
	ToolCalls        []ToolCallMetadata
	GeneratedFiles   []GeneratedFileRef

	// Canonical prompt schema (used by pkg/connector).
	CanonicalPromptSchema   string
	CanonicalPromptMessages []map[string]any

	// Canonical UI message schema (used by codex, opencode).
	CanonicalSchema    string
	CanonicalUIMessage map[string]any
}

AssistantMetadataParams holds the bridge-agnostic fields needed to populate an assistant message's BaseMessageMetadata. Each bridge extracts these from its own streamingState type and passes them here.

type BaseConnectorMethods

type BaseConnectorMethods struct {
	ProtocolID string // e.g. "ai-opencode"
}

BaseConnectorMethods is an embeddable mixin that provides default implementations for common NetworkConnector methods. Bridges can override individual methods when they need different behaviour (e.g. OpenClaw overrides GetCapabilities to disable disappearing messages).

func (BaseConnectorMethods) FillPortalBridgeInfo

func (b BaseConnectorMethods) FillPortalBridgeInfo(portal *bridgev2.Portal, content *event.BridgeEventContent)

func (BaseConnectorMethods) GetBridgeInfoVersion

func (b BaseConnectorMethods) GetBridgeInfoVersion() (info, capabilities int)

func (BaseConnectorMethods) GetCapabilities

type BaseLoginProcess

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

BaseLoginProcess provides background context management for login flows. Embed this in bridge-specific login structs to get free Cancel() and BackgroundProcessContext() implementations.

func (*BaseLoginProcess) BackgroundProcessContext

func (p *BaseLoginProcess) BackgroundProcessContext() context.Context

BackgroundProcessContext returns a long-lived context for background operations. The context is lazily initialized on first call and reused for subsequent calls.

func (*BaseLoginProcess) Cancel

func (p *BaseLoginProcess) Cancel()

Cancel cancels the background context and clears all references.

type BaseMessageMetadata

type BaseMessageMetadata struct {
	Role                    string             `json:"role,omitempty"`
	Body                    string             `json:"body,omitempty"`
	FinishReason            string             `json:"finish_reason,omitempty"`
	PromptTokens            int64              `json:"prompt_tokens,omitempty"`
	CompletionTokens        int64              `json:"completion_tokens,omitempty"`
	ReasoningTokens         int64              `json:"reasoning_tokens,omitempty"`
	TurnID                  string             `json:"turn_id,omitempty"`
	AgentID                 string             `json:"agent_id,omitempty"`
	CanonicalPromptSchema   string             `json:"canonical_prompt_schema,omitempty"`
	CanonicalPromptMessages []map[string]any   `json:"canonical_prompt_messages,omitempty"`
	CanonicalSchema         string             `json:"canonical_schema,omitempty"`
	CanonicalUIMessage      map[string]any     `json:"canonical_ui_message,omitempty"`
	StartedAtMs             int64              `json:"started_at_ms,omitempty"`
	CompletedAtMs           int64              `json:"completed_at_ms,omitempty"`
	ThinkingContent         string             `json:"thinking_content,omitempty"`
	ToolCalls               []ToolCallMetadata `json:"tool_calls,omitempty"`
	GeneratedFiles          []GeneratedFileRef `json:"generated_files,omitempty"`
	ExcludeFromHistory      bool               `json:"exclude_from_history,omitempty"`
}

BaseMessageMetadata contains fields common to all bridge MessageMetadata structs. Embed this in each bridge's MessageMetadata to share CopyFrom logic.

func BuildAssistantBaseMetadata

func BuildAssistantBaseMetadata(p AssistantMetadataParams) BaseMessageMetadata

BuildAssistantBaseMetadata constructs a BaseMessageMetadata for an assistant message from the given params. This deduplicates the common field-population logic shared across bridge saveAssistantMessage implementations.

func (*BaseMessageMetadata) CopyFromBase

func (b *BaseMessageMetadata) CopyFromBase(src *BaseMessageMetadata)

CopyFromBase copies non-zero common fields from src into the receiver.

type BaseReactionHandler

type BaseReactionHandler struct {
	Target ReactionTarget
}

BaseReactionHandler is an embeddable mixin that implements the three reaction interface methods (PreHandleMatrixReaction, HandleMatrixReaction, HandleMatrixReactionRemove) for bridges whose reaction handling is limited to approval prompt reactions.

func (BaseReactionHandler) HandleMatrixReaction

func (h BaseReactionHandler) HandleMatrixReaction(ctx context.Context, msg *bridgev2.MatrixReaction) (*database.Reaction, error)

func (BaseReactionHandler) HandleMatrixReactionRemove

func (h BaseReactionHandler) HandleMatrixReactionRemove(_ context.Context, _ *bridgev2.MatrixReactionRemove) error

func (BaseReactionHandler) PreHandleMatrixReaction

type BaseStreamState

type BaseStreamState struct {
	StreamMu                  sync.Mutex
	StreamSessions            map[string]*streamtransport.StreamSession
	StreamFallbackToDebounced atomic.Bool
	// contains filtered or unexported fields
}

BaseStreamState provides the common stream session fields and lifecycle methods shared across bridges that use streamtransport.

func (*BaseStreamState) BeginStreamShutdown

func (s *BaseStreamState) BeginStreamShutdown()

func (*BaseStreamState) CloseAllSessions

func (s *BaseStreamState) CloseAllSessions()

CloseAllSessions ends every active stream session and clears the map.

func (*BaseStreamState) InitStreamState

func (s *BaseStreamState) InitStreamState()

InitStreamState initialises the StreamSessions map. Call this during client construction.

func (*BaseStreamState) IsStreamShuttingDown

func (s *BaseStreamState) IsStreamShuttingDown() bool

func (*BaseStreamState) ResetStreamShutdown

func (s *BaseStreamState) ResetStreamShutdown()

type BrokenLoginClient

type BrokenLoginClient struct {
	UserLogin *bridgev2.UserLogin
	Reason    string
	OnLogout  func(context.Context, *bridgev2.UserLogin)
}

BrokenLoginClient keeps invalid logins loadable/deletable.

func NewBrokenLoginClient

func NewBrokenLoginClient(login *bridgev2.UserLogin, reason string) *BrokenLoginClient

NewBrokenLoginClient creates a BrokenLoginClient for a login that cannot be fully initialized (e.g. missing credentials or invalid config).

func (*BrokenLoginClient) Connect

func (c *BrokenLoginClient) Connect(_ context.Context)

func (*BrokenLoginClient) Disconnect

func (c *BrokenLoginClient) Disconnect()

func (*BrokenLoginClient) GetCapabilities

func (c *BrokenLoginClient) GetCapabilities(_ context.Context, _ *bridgev2.Portal) *event.RoomFeatures

func (*BrokenLoginClient) GetChatInfo

func (*BrokenLoginClient) GetUserInfo

func (*BrokenLoginClient) HandleMatrixMessage

func (*BrokenLoginClient) IsLoggedIn

func (c *BrokenLoginClient) IsLoggedIn() bool

func (*BrokenLoginClient) IsThisUser

func (c *BrokenLoginClient) IsThisUser(_ context.Context, _ networkid.UserID) bool

func (*BrokenLoginClient) LogoutRemote

func (c *BrokenLoginClient) LogoutRemote(ctx context.Context)

type DMChatInfoParams

type DMChatInfoParams struct {
	Title             string
	HumanUserID       networkid.UserID
	LoginID           networkid.UserLoginID
	BotUserID         networkid.UserID
	BotDisplayName    string
	CanBackfill       bool
	CapabilitiesEvent event.Type
	SettingsEvent     event.Type
}

DMChatInfoParams holds the parameters for BuildDMChatInfo.

type GeneratedFileRef

type GeneratedFileRef struct {
	URL      string `json:"url"`
	MimeType string `json:"mime_type"`
}

GeneratedFileRef stores a reference to a file generated by the assistant (e.g., image generation).

func GeneratedFileRefsFromParts

func GeneratedFileRefsFromParts(parts []citations.GeneratedFilePart) []GeneratedFileRef

GeneratedFileRefsFromParts converts citations.GeneratedFilePart values into GeneratedFileRef values suitable for message metadata storage.

type LoadUserLoginConfig

type LoadUserLoginConfig[C bridgev2.NetworkAPI] struct {
	Mu      *sync.Mutex
	Clients map[networkid.UserLoginID]bridgev2.NetworkAPI

	// BridgeName is used in error messages (e.g. "OpenCode").
	BridgeName string

	// MakeBroken returns a BrokenLoginClient for the given reason.
	// If nil, a default BrokenLoginClient is used.
	MakeBroken func(login *bridgev2.UserLogin, reason string) *BrokenLoginClient

	Update func(existing C, login *bridgev2.UserLogin)
	Create func(login *bridgev2.UserLogin) (C, error)

	// AfterLoad is called after a client is successfully loaded or created.
	// Optional — use for post-load setup like scheduling bootstrap.
	AfterLoad func(client C)
}

LoadUserLoginConfig configures the generic LoadUserLogin helper.

type Pending

type Pending[D any] struct {
	ExpiresAt time.Time
	Data      D
	// contains filtered or unexported fields
}

Pending represents a single pending approval.

type ReactionContext

type ReactionContext struct {
	Emoji         string
	TargetEventID id.EventID
}

ReactionContext holds the extracted emoji and target event ID from a reaction.

func ExtractReactionContext

func ExtractReactionContext(msg *bridgev2.MatrixReaction) ReactionContext

ExtractReactionContext pulls the emoji and target event ID from a MatrixReaction.

type ReactionTarget

type ReactionTarget interface {
	GetUserLogin() *bridgev2.UserLogin
	GetApprovalHandler() ApprovalReactionHandler
}

ReactionTarget provides the bridge-specific context that BaseReactionHandler needs to validate and route approval reactions.

type RemoteEdit

type RemoteEdit struct {
	Portal        networkid.PortalKey
	Sender        bridgev2.EventSender
	TargetMessage networkid.MessageID
	Timestamp     time.Time
	PreBuilt      *bridgev2.ConvertedEdit

	// LogKey is the zerolog field name used in AddLogContext (e.g. "ai_edit_target", "codex_edit_target").
	LogKey string
}

RemoteEdit is a bridge-agnostic RemoteEdit implementation backed by pre-built content.

func (*RemoteEdit) AddLogContext

func (e *RemoteEdit) AddLogContext(c zerolog.Context) zerolog.Context

func (*RemoteEdit) ConvertEdit

func (*RemoteEdit) GetPortalKey

func (e *RemoteEdit) GetPortalKey() networkid.PortalKey

func (*RemoteEdit) GetSender

func (e *RemoteEdit) GetSender() bridgev2.EventSender

func (*RemoteEdit) GetStreamOrder

func (e *RemoteEdit) GetStreamOrder() int64

func (*RemoteEdit) GetTargetMessage

func (e *RemoteEdit) GetTargetMessage() networkid.MessageID

func (*RemoteEdit) GetTimestamp

func (e *RemoteEdit) GetTimestamp() time.Time

func (*RemoteEdit) GetType

func (e *RemoteEdit) GetType() bridgev2.RemoteEventType

type RemoteMessage

type RemoteMessage struct {
	Portal    networkid.PortalKey
	ID        networkid.MessageID
	Sender    bridgev2.EventSender
	Timestamp time.Time
	PreBuilt  *bridgev2.ConvertedMessage

	// LogKey is the zerolog field name used in AddLogContext (e.g. "ai_msg_id", "codex_msg_id").
	LogKey string
}

RemoteMessage is a bridge-agnostic RemoteMessage implementation backed by pre-built content.

func BuildContinuationMessage

func BuildContinuationMessage(portal networkid.PortalKey, body string, sender bridgev2.EventSender, idPrefix, logKey string) *RemoteMessage

BuildContinuationMessage constructs a ConvertedMessage for overflow continuation text, flagged with "com.beeper.continuation".

func (*RemoteMessage) AddLogContext

func (m *RemoteMessage) AddLogContext(c zerolog.Context) zerolog.Context

func (*RemoteMessage) ConvertMessage

func (*RemoteMessage) GetID

func (m *RemoteMessage) GetID() networkid.MessageID

func (*RemoteMessage) GetPortalKey

func (m *RemoteMessage) GetPortalKey() networkid.PortalKey

func (*RemoteMessage) GetSender

func (m *RemoteMessage) GetSender() bridgev2.EventSender

func (*RemoteMessage) GetStreamOrder

func (m *RemoteMessage) GetStreamOrder() int64

func (*RemoteMessage) GetTimestamp

func (m *RemoteMessage) GetTimestamp() time.Time

func (*RemoteMessage) GetType

func (m *RemoteMessage) GetType() bridgev2.RemoteEventType

type RemoteReaction

type RemoteReaction struct {
	Portal        networkid.PortalKey
	Sender        bridgev2.EventSender
	TargetMessage networkid.MessageID
	Emoji         string
	EmojiID       networkid.EmojiID
	Timestamp     time.Time
	DBMeta        *database.Reaction
	ExtraContent  map[string]any

	// LogKey is the zerolog field name used in AddLogContext (e.g. "ai_reaction_target").
	LogKey string
}

RemoteReaction is a bridge-agnostic RemoteReaction implementation.

func (*RemoteReaction) AddLogContext

func (r *RemoteReaction) AddLogContext(c zerolog.Context) zerolog.Context

func (*RemoteReaction) GetPortalKey

func (r *RemoteReaction) GetPortalKey() networkid.PortalKey

func (*RemoteReaction) GetReactionDBMetadata

func (r *RemoteReaction) GetReactionDBMetadata() any

func (*RemoteReaction) GetReactionEmoji

func (r *RemoteReaction) GetReactionEmoji() (string, networkid.EmojiID)

func (*RemoteReaction) GetReactionExtraContent

func (r *RemoteReaction) GetReactionExtraContent() map[string]any

func (*RemoteReaction) GetSender

func (r *RemoteReaction) GetSender() bridgev2.EventSender

func (*RemoteReaction) GetTargetMessage

func (r *RemoteReaction) GetTargetMessage() networkid.MessageID

func (*RemoteReaction) GetTimestamp

func (r *RemoteReaction) GetTimestamp() time.Time

func (*RemoteReaction) GetType

type RemoteReactionRemove

type RemoteReactionRemove struct {
	Portal        networkid.PortalKey
	Sender        bridgev2.EventSender
	TargetMessage networkid.MessageID
	EmojiID       networkid.EmojiID

	// LogKey is the zerolog field name used in AddLogContext (e.g. "ai_reaction_remove_target").
	LogKey string
}

RemoteReactionRemove is a bridge-agnostic RemoteReactionRemove implementation.

func (*RemoteReactionRemove) AddLogContext

func (r *RemoteReactionRemove) AddLogContext(c zerolog.Context) zerolog.Context

func (*RemoteReactionRemove) GetPortalKey

func (r *RemoteReactionRemove) GetPortalKey() networkid.PortalKey

func (*RemoteReactionRemove) GetRemovedEmojiID

func (r *RemoteReactionRemove) GetRemovedEmojiID() networkid.EmojiID

func (*RemoteReactionRemove) GetSender

func (r *RemoteReactionRemove) GetSender() bridgev2.EventSender

func (*RemoteReactionRemove) GetTargetMessage

func (r *RemoteReactionRemove) GetTargetMessage() networkid.MessageID

func (*RemoteReactionRemove) GetType

type SendDebouncedStreamEditParams

type SendDebouncedStreamEditParams struct {
	Login            *bridgev2.UserLogin
	Portal           *bridgev2.Portal
	Sender           bridgev2.EventSender
	NetworkMessageID networkid.MessageID
	SuppressSend     bool
	VisibleBody      string
	FallbackBody     string
	LogKey           string
	Force            bool
	UIMessage        map[string]any
}

SendDebouncedStreamEditParams holds the parameters for SendDebouncedStreamEdit.

type SendPromptParams

type SendPromptParams struct {
	ApprovalPromptMessageParams
	RoomID    id.RoomID
	OwnerMXID id.UserID
}

SendPromptParams holds the parameters for sending an approval prompt.

type SendViaPortalParams

type SendViaPortalParams struct {
	Login     *bridgev2.UserLogin
	Portal    *bridgev2.Portal
	Sender    bridgev2.EventSender
	IDPrefix  string // e.g. "ai", "codex", "opencode"
	LogKey    string // zerolog field name, e.g. "ai_msg_id"
	MsgID     networkid.MessageID
	Converted *bridgev2.ConvertedMessage
}

SendViaPortalParams holds the parameters for SendViaPortal.

type ToolCallMetadata

type ToolCallMetadata struct {
	CallID        string         `json:"call_id"`
	ToolName      string         `json:"tool_name"`
	ToolType      string         `json:"tool_type"`
	Input         map[string]any `json:"input,omitempty"`
	Output        map[string]any `json:"output,omitempty"`
	Status        string         `json:"status"`
	ResultStatus  string         `json:"result_status,omitempty"`
	ErrorMessage  string         `json:"error_message,omitempty"`
	StartedAtMs   int64          `json:"started_at_ms,omitempty"`
	CompletedAtMs int64          `json:"completed_at_ms,omitempty"`

	// Event IDs for timeline events (if emitted as separate events)
	CallEventID   string `json:"call_event_id,omitempty"`
	ResultEventID string `json:"result_event_id,omitempty"`
}

ToolCallMetadata tracks a tool call within a message. Both bridges and the connector share this type for JSON-serialized database storage.

type UpsertAssistantMessageParams

type UpsertAssistantMessageParams struct {
	Login            *bridgev2.UserLogin
	Portal           *bridgev2.Portal
	SenderID         networkid.UserID
	NetworkMessageID networkid.MessageID
	InitialEventID   id.EventID
	Metadata         any // must satisfy database.MetaMerger
	Logger           zerolog.Logger
}

UpsertAssistantMessageParams holds parameters for UpsertAssistantMessage.

Jump to

Keyboard shortcuts

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