gateway

package
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package gateway provides the WebSocket control plane for omniagent.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AgentProcessor

type AgentProcessor interface {
	Process(ctx context.Context, sessionID, content string) (string, error)
}

AgentProcessor processes messages through an AI agent.

type AgentSecretStore added in v0.18.0

type AgentSecretStore interface {
	SetAgentSecret(ctx context.Context, agentID uuid.UUID, name, value string) error
	DeleteAgentSecret(ctx context.Context, agentID uuid.UUID, name string) error
	ListAgentSecretNames(ctx context.Context, agentID uuid.UUID) ([]string, error)
}

AgentSecretStore is the write-only agent-secret store the secrets surface drives (satisfied by *team/secrets.Service). Values are set/deleted and listed by env-var name only — a value is never read back over HTTP (INIT-OMNIAGENT-004).

type AgentsHTTP added in v0.16.0

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

AgentsHTTP serves the virtual-agents management + discovery surface (INIT-OMNIAGENT-005 Phase 5): the owner/maintainer configuration area (RMI-311: create/update/delete, enabled skills, maintainers, visibility), the discovery catalog and agent-bound chat starts (RMI-312, chat starts live on TeamChatHTTP), and superadmin featured curation (RMI-313).

It is a thin HTTP adapter over agents.Service — every route is scoped to the authenticated principal (set on the context by TeamHTTP.RequireAuth, which must wrap this handler) and every authorization decision is the service's (Can / requireEditor / requireOwner); PostgreSQL row-level security is the defense-in-depth backstop. Secret management is intentionally out of scope here (an INIT-004 concern), so no secret values cross this surface.

func NewAgentsHTTP added in v0.16.0

func NewAgentsHTTP(cfg AgentsHTTPConfig) *AgentsHTTP

NewAgentsHTTP builds the agents handler set.

func (*AgentsHTTP) Handler added in v0.16.0

func (h *AgentsHTTP) Handler() http.Handler

Handler returns the routed handler. Mount it at "/api/agents", "/api/agents/" and "/api/catalog", wrapped in TeamHTTP.RequireAuth so every route has an authenticated principal on its context.

type AgentsHTTPConfig added in v0.16.0

type AgentsHTTPConfig struct {
	Agents *agents.Service
	Logger *slog.Logger
	// Secrets, when non-nil, enables the agent Secrets surface
	// (/api/agents/{id}/secrets). Nil (no secret vault configured) leaves
	// those routes unregistered.
	Secrets AgentSecretStore
	// SkillSecretDecls maps an enabled skill name to the secrets it declares,
	// supplied by the composition root (which owns the skill manager). Nil is
	// treated as "no declarations".
	SkillSecretDecls func(skillName string) []SecretDecl
	// InvalidateAgent evicts an agent's cached runtime instance so a
	// freshly-set secret takes effect on its next turn. Nil is a no-op.
	InvalidateAgent func(agentID uuid.UUID)
}

AgentsHTTPConfig configures the agents handler.

type AuthMessage

type AuthMessage struct {
	Token    string `json:"token,omitempty"`
	DeviceID string `json:"device_id,omitempty"`
}

AuthMessage represents an authentication message.

type ChatMessage

type ChatMessage struct {
	SessionID string `json:"session_id,omitempty"`
	Content   string `json:"content"`
	Channel   string `json:"channel,omitempty"`
	ReplyTo   string `json:"reply_to,omitempty"`
}

ChatMessage represents a chat message.

type Client

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

Client represents a connected WebSocket client.

func (*Client) Close

func (c *Client) Close()

Close closes the client connection.

func (*Client) GetMetadata

func (c *Client) GetMetadata(key string) (interface{}, bool)

GetMetadata gets a metadata value.

func (*Client) RemoteIP added in v0.16.0

func (c *Client) RemoteIP() string

RemoteIP returns the client's source IP. Falls back to the client ID when the connection carries no address (e.g. in tests), so penalty keying still distinguishes callers.

func (*Client) Send

func (c *Client) Send(msg *Message)

Send queues a message to be sent to the client.

func (*Client) SetMetadata

func (c *Client) SetMetadata(key string, value interface{})

SetMetadata sets a metadata value.

type Config

type Config struct {
	Address         string
	ReadTimeout     time.Duration
	WriteTimeout    time.Duration
	PingInterval    time.Duration
	Logger          *slog.Logger
	Agent           AgentProcessor
	WebhookHandlers map[string]http.Handler // Path -> Handler for webhook endpoints
	AllowedOrigins  []string                // Allowed origins for WebSocket connections (empty allows all)
	APIKeys         []string                // Valid API keys for authentication (empty disables auth)
	RequireAuth     bool                    // If true, clients must authenticate before sending messages
	RateLimit       *RateLimitConfig        // Per-sender rate limiting config (nil disables)
	EnableMetrics   bool                    // If true, expose /metrics endpoint for Prometheus
}

Config configures the gateway server.

type ConnectAuthorizer added in v0.16.0

type ConnectAuthorizer func(r *http.Request) (userID string, ok bool)

ConnectAuthorizer authorizes a WebSocket upgrade request. It returns the authenticated user ID and true to allow the upgrade, or false to reject it (the caller responds 401 before upgrading).

type DefaultMessageHandler

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

DefaultMessageHandler provides a basic message handler implementation.

func NewDefaultMessageHandler

func NewDefaultMessageHandler(gw *Gateway) *DefaultMessageHandler

NewDefaultMessageHandler creates a new default message handler.

func (*DefaultMessageHandler) Handle

func (h *DefaultMessageHandler) Handle(ctx context.Context, client *Client, msg *Message) (*Message, error)

Handle processes incoming messages.

type EventMessage

type EventMessage struct {
	Event   string                 `json:"event"`
	Channel string                 `json:"channel,omitempty"`
	Data    map[string]interface{} `json:"data,omitempty"`
}

EventMessage represents an event notification.

type Gateway

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

Gateway is the WebSocket control plane server.

func New

func New(config Config) (*Gateway, error)

New creates a new Gateway.

func (*Gateway) Broadcast

func (g *Gateway) Broadcast(msg *Message)

Broadcast sends a message to all connected clients.

func (*Gateway) BroadcastToUsers added in v0.16.0

func (g *Gateway) BroadcastToUsers(userIDs []string, msg *Message)

BroadcastToUsers sends a message only to connected clients whose authenticated user_id is in userIDs — the membership-scoped fan-out for chat rooms (RMI-112). A chat's message is delivered to exactly its members' sockets and no others, so there is no cross-chat leakage: a client whose user is not a member never receives it. Clients with no bound user_id (unauthenticated) are never matched.

func (*Gateway) ClientCount

func (g *Gateway) ClientCount() int

ClientCount returns the number of connected clients.

func (*Gateway) GetClient

func (g *Gateway) GetClient(id string) *Client

GetClient returns a client by ID.

func (*Gateway) Handle added in v0.16.0

func (g *Gateway) Handle(pattern string, handler http.Handler)

Handle registers an additional HTTP handler at pattern, applied to the server mux when Run starts. Patterns follow http.ServeMux rules; a trailing slash (e.g. "/api/") mounts a subtree.

func (*Gateway) OnMessage

func (g *Gateway) OnMessage(handler MessageHandler)

OnMessage sets the message handler.

func (*Gateway) Run

func (g *Gateway) Run(ctx context.Context) error

Run starts the gateway server.

func (*Gateway) SetConnectAuthorizer added in v0.16.0

func (g *Gateway) SetConnectAuthorizer(a ConnectAuthorizer)

SetConnectAuthorizer installs a WebSocket upgrade authorizer (team mode).

type GlobalSecretBinding added in v0.18.0

type GlobalSecretBinding struct {
	Name   string `json:"name"`
	Source string `json:"source"`
	Set    bool   `json:"set"`
}

GlobalSecretBinding is one configured secret binding's name and set-state — never its value (RMI-OMNIAGENT-213). Source is "global" or the skill name a per-skill binding is scoped to.

type Message

type Message struct {
	ID        string                 `json:"id,omitempty"`
	Type      MessageType            `json:"type"`
	Channel   string                 `json:"channel,omitempty"`
	Content   string                 `json:"content,omitempty"`
	Data      map[string]interface{} `json:"data,omitempty"`
	Error     string                 `json:"error,omitempty"`
	Timestamp time.Time              `json:"timestamp,omitempty"`
}

Message is the base message structure for gateway communication.

func NewChatResponse

func NewChatResponse(id, content string) *Message

NewChatResponse creates a chat response message.

func NewErrorMessage

func NewErrorMessage(id, errMsg string) *Message

NewErrorMessage creates an error message.

func NewEventMessage

func NewEventMessage(event, channel string, data map[string]interface{}) *Message

NewEventMessage creates an event message.

type MessageHandler

type MessageHandler func(ctx context.Context, client *Client, msg *Message) (*Message, error)

MessageHandler handles incoming messages from clients.

type MessageType

type MessageType string

MessageType represents the type of gateway message.

const (
	// Client -> Gateway
	MessageTypeChat         MessageType = "chat"
	MessageTypePing         MessageType = "ping"
	MessageTypeAuth         MessageType = "auth"
	MessageTypeSubscribe    MessageType = "subscribe"
	MessageTypeSessionTools MessageType = "session_tools"
	MessageTypeSessionModel MessageType = "session_model"

	// Gateway -> Client
	MessageTypeResponse MessageType = "response"
	MessageTypePong     MessageType = "pong"
	MessageTypeError    MessageType = "error"
	MessageTypeEvent    MessageType = "event"
)

type Metrics added in v0.16.0

type Metrics struct {
	// Connection metrics
	ActiveConnections prometheus.Gauge
	TotalConnections  prometheus.Counter

	// Message metrics
	MessagesReceived  *prometheus.CounterVec
	MessagesSent      *prometheus.CounterVec
	MessageDurationMs *prometheus.HistogramVec
	RateLimitedCount  prometheus.Counter

	// Agent metrics
	AgentRequests   prometheus.Counter
	AgentErrors     prometheus.Counter
	AgentDurationMs prometheus.Histogram

	// Tool metrics
	ToolInvocations *prometheus.CounterVec
	ToolDurationMs  *prometheus.HistogramVec
}

Metrics holds Prometheus metrics for the gateway.

func NewMetrics added in v0.16.0

func NewMetrics(namespace string) *Metrics

NewMetrics creates and registers Prometheus metrics.

func (*Metrics) Handler added in v0.16.0

func (m *Metrics) Handler() http.Handler

Handler returns an HTTP handler for the /metrics endpoint.

func (*Metrics) RecordAgentRequest added in v0.16.0

func (m *Metrics) RecordAgentRequest(duration time.Duration, err error)

RecordAgentRequest records an agent request.

func (*Metrics) RecordConnection added in v0.16.0

func (m *Metrics) RecordConnection()

RecordConnection records a new connection.

func (*Metrics) RecordDisconnection added in v0.16.0

func (m *Metrics) RecordDisconnection()

RecordDisconnection records a disconnection.

func (*Metrics) RecordMessage added in v0.16.0

func (m *Metrics) RecordMessage(msgType string, direction string, duration time.Duration)

RecordMessage records a message received or sent.

func (*Metrics) RecordRateLimited added in v0.16.0

func (m *Metrics) RecordRateLimited()

RecordRateLimited records a rate-limited message.

func (*Metrics) RecordToolInvocation added in v0.16.0

func (m *Metrics) RecordToolInvocation(toolName string, duration time.Duration, err error)

RecordToolInvocation records a tool invocation.

type Observability added in v0.9.0

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

Observability provides gateway instrumentation.

func NewObservability added in v0.9.0

func NewObservability(config ObservabilityConfig) (*Observability, error)

NewObservability creates a new observability instance.

func (*Observability) CompleteWorkflow added in v0.9.0

func (o *Observability) CompleteWorkflow(ctx context.Context, workflowID string, output map[string]any) error

CompleteWorkflow completes an agentops workflow.

func (*Observability) EndTrace added in v0.9.0

func (o *Observability) EndTrace(tc *TraceContext, err error)

EndTrace ends a trace with optional error.

func (*Observability) FailWorkflow added in v0.9.0

func (o *Observability) FailWorkflow(ctx context.Context, workflowID string, err error) error

FailWorkflow marks an agentops workflow as failed.

func (*Observability) ForceFlush added in v0.9.0

func (o *Observability) ForceFlush(ctx context.Context) error

ForceFlush forces any buffered telemetry to be exported.

func (*Observability) Provider added in v0.9.0

func (o *Observability) Provider() observops.Provider

Provider returns the observops provider.

func (*Observability) RecordClientConnect added in v0.9.0

func (o *Observability) RecordClientConnect(ctx context.Context, clientID string)

RecordClientConnect records a client connection event.

func (*Observability) RecordClientDisconnect added in v0.9.0

func (o *Observability) RecordClientDisconnect(ctx context.Context, clientID string)

RecordClientDisconnect records a client disconnection event.

func (*Observability) RecordEvent added in v0.9.0

func (o *Observability) RecordEvent(ctx context.Context, eventType, category string, data map[string]any) error

RecordEvent records a generic event.

func (*Observability) RecordMessage added in v0.9.0

func (o *Observability) RecordMessage(ctx context.Context, clientID string, msgType MessageType, err error)

RecordMessage records a message processing event.

func (*Observability) RecordToolInvocation added in v0.9.0

func (o *Observability) RecordToolInvocation(ctx context.Context, toolName string, duration time.Duration, err error)

RecordToolInvocation records a tool invocation event.

func (*Observability) Shutdown added in v0.9.0

func (o *Observability) Shutdown(ctx context.Context) error

Shutdown shuts down observability, flushing any buffered data.

func (*Observability) StartTrace added in v0.9.0

func (o *Observability) StartTrace(ctx context.Context, operationName string, attrs ...observops.KeyValue) *TraceContext

StartTrace starts a new trace for a gateway operation.

func (*Observability) StartWorkflow added in v0.9.0

func (o *Observability) StartWorkflow(ctx context.Context, name string, input map[string]any) (*agentops.Workflow, error)

StartWorkflow starts a new agentops workflow for tracking.

func (*Observability) Store added in v0.9.0

func (o *Observability) Store() agentops.Store

Store returns the agentops store.

type ObservabilityConfig added in v0.9.0

type ObservabilityConfig struct {
	// ServiceName is the name of this gateway service.
	ServiceName string

	// ServiceVersion is the version of this gateway service.
	ServiceVersion string

	// ObservopsProvider is the observops provider for metrics/traces.
	ObservopsProvider observops.Provider

	// AgentopsStore is the agentops store for workflow/task tracking.
	AgentopsStore agentops.Store

	// Logger is the logger for observability events.
	Logger *slog.Logger
}

ObservabilityConfig configures gateway observability.

type PersonalChatHTTP added in v0.16.0

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

PersonalChatHTTP serves the personal-mode chat endpoints.

func NewPersonalChatHTTP added in v0.16.0

func NewPersonalChatHTTP(cfg PersonalChatHTTPConfig) *PersonalChatHTTP

NewPersonalChatHTTP builds the personal chat handler set.

func (*PersonalChatHTTP) ChatHandler added in v0.16.0

func (h *PersonalChatHTTP) ChatHandler() http.Handler

ChatHandler serves GET /api/chat: the caller's private chat and its newest page of history (oldest-first), with hasMore driving scroll-back via HistoryHandler.

func (*PersonalChatHTTP) HistoryHandler added in v0.16.0

func (h *PersonalChatHTTP) HistoryHandler() http.Handler

HistoryHandler serves GET /api/chat/history?before=<id>&limit=<n>: a page of messages older than the cursor for scroll-back (keyset pagination).

func (*PersonalChatHTTP) SendHandler added in v0.16.0

func (h *PersonalChatHTTP) SendHandler() http.Handler

SendHandler serves POST /api/chat/messages: it persists the user's message and returns it immediately (202). The agent turn runs asynchronously and its reply is delivered over the WebSocket (chat.message event) — a slow LLM turn must not block the HTTP response.

func (*PersonalChatHTTP) SetBroadcaster added in v0.16.0

func (h *PersonalChatHTTP) SetBroadcaster(b func(*Message))

SetBroadcaster wires live agent-reply delivery to a broadcast sink (the gateway's Broadcast). Called after the gateway is constructed since the chat handler is built first. Personal mode is single-user, so broadcasting to every connected client is equivalent to targeting the one user.

type PersonalChatHTTPConfig added in v0.16.0

type PersonalChatHTTPConfig struct {
	Chats  *chats.Service
	UserID uuid.UUID
	Logger *slog.Logger
}

PersonalChatHTTPConfig configures the personal-mode chat handler: a single implicit user's DM with the agent (TRD §1a "Personal" profile; §5 "private chat always responds"). Team mode's chat/membership/group HTTP surface (RMI-110-114) is a separate, not-yet-built endpoint set behind auth.

type RateLimitConfig added in v0.16.0

type RateLimitConfig struct {
	// Rate is the number of messages allowed per second per sender.
	Rate float64
	// Burst is the maximum number of messages that can be sent in a burst.
	Burst int
	// CleanupInterval is how often to clean up stale buckets.
	CleanupInterval time.Duration
}

RateLimitConfig configures the rate limiter.

func DefaultRateLimitConfig added in v0.16.0

func DefaultRateLimitConfig() RateLimitConfig

DefaultRateLimitConfig returns sensible defaults for rate limiting.

type RateLimiter added in v0.16.0

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

RateLimiter implements per-sender rate limiting using a token bucket algorithm.

func NewRateLimiter added in v0.16.0

func NewRateLimiter(config RateLimitConfig) *RateLimiter

NewRateLimiter creates a new rate limiter with the given configuration.

func (*RateLimiter) Allow added in v0.16.0

func (rl *RateLimiter) Allow(senderID string) bool

Allow checks if a message from the given sender should be allowed. Returns true if the message is allowed, false if rate limited.

func (*RateLimiter) Reset added in v0.16.0

func (rl *RateLimiter) Reset(senderID string)

Reset removes all rate limit state for a sender.

type SSOProvider added in v0.17.0

type SSOProvider interface {
	// AuthURL returns the redirect URL for the provider's consent screen,
	// carrying state (CSRF) and nonce (OIDC replay protection).
	AuthURL(state, nonce string) string
	// Exchange trades an authorization code for the provider's verified
	// subject (a stable per-account id) and verified email. nonce is echoed
	// back for providers that need it (Google); others ignore it.
	Exchange(ctx context.Context, code, nonce string) (subject, verifiedEmail string, err error)
}

SSOProvider drives one OAuth/OIDC sign-in provider's browser-facing redirect flow. Symmetric across providers — GitHub's implementation ignores nonce — so the gateway's start/callback handling is one shared implementation with no per-provider branching, and is fully testable with a fake implementation independent of real provider connectivity.

type SecretDecl added in v0.18.0

type SecretDecl struct {
	Name        string
	Description string
	Env         string
	Required    bool
}

SecretDecl is a gateway-local projection of a skill's declared secret (skills.SecretRequirement), so this package needn't import skills.

type SessionModelConfigurator added in v0.16.0

type SessionModelConfigurator interface {
	SetSessionModel(ctx context.Context, sessionID, model string, sticky bool) error
}

SessionModelConfigurator applies per-session model selection. Agents that support it implement this in addition to AgentProcessor; the gateway feature is unavailable otherwise.

type SessionToolConfigurator added in v0.16.0

type SessionToolConfigurator interface {
	SetSessionToolOverrides(ctx context.Context, sessionID string, overrides *sessions.ToolOverrides) error
}

SessionToolConfigurator applies per-session tool overrides. Agents that support session-scoped tool scoping implement it in addition to AgentProcessor; the gateway feature is unavailable otherwise.

type TeamChatHTTP added in v0.16.0

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

TeamChatHTTP serves the multi-user (team-mode) chat surface: private DMs and group chats with membership fan-out (RMI-110/111/112). It is the team counterpart to PersonalChatHTTP; each request is scoped to the authenticated principal (set on the context by TeamHTTP.RequireAuth, which must wrap this handler) and enforced again by row-level security in the store.

The agent turn follows the RMI-113 mention policy (chats.Service.AgentTurn): private chats always respond; group chats respond only when the message @-mentions the bound agent's slug. The reply runs on the chat's bound agent runtime and is persisted then broadcast. Per-agent runtime construction (persona + skills + secrets) is supplied by INIT-005 RMI-309; until a runtime is wired, agent-bound chats stay silent and agent-less DMs use the fallback.

func NewTeamChatHTTP added in v0.16.0

func NewTeamChatHTTP(cfg TeamChatHTTPConfig) *TeamChatHTTP

NewTeamChatHTTP builds the team chat handler set.

func (*TeamChatHTTP) Handler added in v0.16.0

func (h *TeamChatHTTP) Handler() http.Handler

Handler returns the routed handler. Mount it at "/api/chats" and "/api/chats/", wrapped in TeamHTTP.RequireAuth so every route has an authenticated principal on its context.

func (*TeamChatHTTP) SetBroadcaster added in v0.16.0

func (h *TeamChatHTTP) SetBroadcaster(b func(userIDs []string, msg *Message))

SetBroadcaster wires membership-scoped live delivery (the gateway's BroadcastToUsers). Called after the gateway is constructed.

type TeamChatHTTPConfig added in v0.16.0

type TeamChatHTTPConfig struct {
	Chats  *chats.Service
	Logger *slog.Logger
}

TeamChatHTTPConfig configures the team chat handler.

type TeamHTTP added in v0.16.0

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

TeamHTTP serves the team auth and admin API.

func NewTeamHTTP added in v0.16.0

func NewTeamHTTP(authSvc *auth.Service, teamSvc *team.Service, cfg TeamHTTPConfig) *TeamHTTP

NewTeamHTTP builds the team HTTP handler.

func (*TeamHTTP) ConnectAuthorizer added in v0.16.0

func (h *TeamHTTP) ConnectAuthorizer() ConnectAuthorizer

ConnectAuthorizer returns a gateway ConnectAuthorizer that authenticates a WebSocket upgrade from the session cookie.

func (*TeamHTTP) Handler added in v0.16.0

func (h *TeamHTTP) Handler() http.Handler

Handler returns the routed http.Handler (mount at "/api/").

func (*TeamHTTP) RequireAuth added in v0.16.0

func (h *TeamHTTP) RequireAuth(next http.Handler) http.Handler

RequireAuth wraps next, requiring a valid session cookie before it runs (401 otherwise). It lets HTTP surfaces outside this package (e.g. the personal-mode chat API) gate themselves on the same cookie/session logic without duplicating it.

type TeamHTTPConfig added in v0.16.0

type TeamHTTPConfig struct {
	// CookieSecure sets the Secure attribute and selects the cookie name:
	// __Host-oa_session (secure) or oa_session (dev/plain HTTP).
	CookieSecure bool
	// SessionTTL bounds the cookie Max-Age (mirrors auth.Config.SessionTTL).
	SessionTTL time.Duration
	// BaseURL is the origin verify redirects land on.
	BaseURL string
	Logger  *slog.Logger

	// Personal, when true, serves personal single-account auth
	// (auth.enabled=true, team.enabled=false — TRD §4) instead of full
	// team mode: the admin allowlist endpoint is not registered. It must
	// stay unreachable in this mode because the personal SQLite store has
	// no row-level security — a second allowlisted account would see the
	// sole account's data with no isolation.
	Personal bool

	// GoogleProvider and GitHubProvider are nil-able: nil means that
	// provider is not configured, and its /api/auth/{provider}* routes are
	// not registered at all (mirrors the Personal-mode convention for
	// /api/admin/*).
	GoogleProvider SSOProvider
	GitHubProvider SSOProvider

	// GlobalSecretBindings is a startup snapshot of the single-operator
	// config-level secret bindings (config.Config.Secrets and
	// Skills.Config[name].Secrets) — names and set-state only, never
	// values. Served read-only to superadmins (RMI-OMNIAGENT-213).
	GlobalSecretBindings []GlobalSecretBinding
}

TeamHTTPConfig configures the team HTTP handler.

type ToolInfo added in v0.9.0

type ToolInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Parameters  any    `json:"parameters,omitempty"`

	// Source is the tool's origin kind ("mcp", "skill"); empty for tools
	// registered directly.
	Source string `json:"source,omitempty"`

	// MCPServer is the originating MCP server name (MCP tools only).
	MCPServer string `json:"mcp_server,omitempty"`

	// MCPToolName is the tool's original name on its MCP server, before
	// any renaming applied at registration (MCP tools only).
	MCPToolName string `json:"mcp_tool_name,omitempty"`

	// DeniedBySession marks tools excluded for the requested session by
	// its tool overrides. Only populated on session-scoped listings
	// (?session_id=), where denied tools remain listed rather than hidden
	// so a read-only inventory stays complete.
	DeniedBySession bool `json:"denied_by_session,omitempty"`
}

ToolInfo describes a tool for listing. Tools sourced from an MCP server expose their originating identity; non-MCP tools omit the MCP fields.

type ToolInvokeRequest added in v0.9.0

type ToolInvokeRequest struct {
	// Tool is the name of the tool to invoke.
	Tool string `json:"tool"`

	// Arguments are the tool arguments as JSON.
	Arguments json.RawMessage `json:"arguments"`

	// WorkflowID is the optional workflow ID for tracking.
	WorkflowID string `json:"workflow_id,omitempty"`

	// TaskID is the optional task ID for tracking.
	TaskID string `json:"task_id,omitempty"`

	// AgentID is the agent invoking the tool.
	AgentID string `json:"agent_id,omitempty"`

	// TraceID is the optional trace ID for correlation.
	TraceID string `json:"trace_id,omitempty"`

	// Metadata contains optional request metadata.
	Metadata map[string]any `json:"metadata,omitempty"`
}

ToolInvokeRequest is the request format for tools.invoke RPC.

type ToolInvokeResponse added in v0.9.0

type ToolInvokeResponse struct {
	// Result is the tool execution result.
	Result string `json:"result,omitempty"`

	// Error is the error message if execution failed.
	Error string `json:"error,omitempty"`

	// ToolName is the name of the tool that was invoked.
	ToolName string `json:"tool_name"`

	// DurationMs is the execution duration in milliseconds.
	DurationMs int64 `json:"duration_ms"`

	// InvocationID is the unique ID for this invocation.
	InvocationID string `json:"invocation_id,omitempty"`

	// TraceID is the trace ID for correlation.
	TraceID string `json:"trace_id,omitempty"`
}

ToolInvokeResponse is the response format for tools.invoke RPC.

type ToolsListHandler added in v0.9.0

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

ToolsListHandler handles listing available tools.

func NewToolsListHandler added in v0.9.0

func NewToolsListHandler(registry *agent.ToolRegistry, logger *slog.Logger) *ToolsListHandler

NewToolsListHandler creates a new tools list handler.

func (*ToolsListHandler) ServeHTTP added in v0.9.0

func (h *ToolsListHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles the HTTP request.

func (*ToolsListHandler) WithSessions added in v0.16.0

func (h *ToolsListHandler) WithSessions(store *sessions.Store) *ToolsListHandler

WithSessions enables session-scoped listings (?session_id=) by giving the handler access to session tool overrides. Returns the handler for chaining.

type ToolsListResponse added in v0.9.0

type ToolsListResponse struct {
	Tools []ToolInfo `json:"tools"`
}

ToolsListResponse is the response format for tools.list RPC.

type ToolsRPCConfig added in v0.9.0

type ToolsRPCConfig struct {
	// ToolRegistry is the registry of available tools.
	ToolRegistry *agent.ToolRegistry

	// Observability provides tracing and metrics.
	Observability *Observability

	// Logger is the logger for RPC events.
	Logger *slog.Logger

	// MaxRequestSize is the maximum request body size in bytes.
	// Default is 1MB.
	MaxRequestSize int64

	// Timeout is the maximum time for a tool invocation.
	// Default is 30 seconds.
	Timeout time.Duration
}

ToolsRPCConfig configures the tools RPC handler.

type ToolsRPCHandler added in v0.9.0

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

ToolsRPCHandler handles SDK-facing tools.invoke RPC requests.

func NewToolsRPCHandler added in v0.9.0

func NewToolsRPCHandler(config ToolsRPCConfig) *ToolsRPCHandler

NewToolsRPCHandler creates a new tools RPC handler.

func (*ToolsRPCHandler) ServeHTTP added in v0.9.0

func (h *ToolsRPCHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles the HTTP request.

type TraceContext added in v0.9.0

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

TraceContext holds trace context for a request.

type TranslateHTTP added in v0.18.0

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

TranslateHTTP serves POST /api/translate: a one-shot, non-persisting LLM completion that translates composer text before it's sent. Unlike the chat surfaces (team/chats.Service, gateway/personal_chat_http.go), this never touches a chat ID or writes a Message row — it calls the LLM directly via omnillm.ChatClient, bypassing agent.Agent's tool loop and session/memory entirely (the same pattern voice/gateway.go uses for its own one-shot completions). It is mode-agnostic: mounted behind whichever RequireAuth the deployment already uses (team or personal), so it needs no actor/principal type of its own — authentication is enforced by the wrapping middleware.

func NewTranslateHTTP added in v0.18.0

func NewTranslateHTTP(llm chatCompleter, model string) *TranslateHTTP

NewTranslateHTTP builds the translate handler. llm is a client constructed from the deployment's single global cfg.Agent provider/API key/base URL (never per-virtual-agent — see config/capabilities.go's Translate flag, which is only true when cfg.Agent.APIKey is set).

func (*TranslateHTTP) Handler added in v0.18.0

func (h *TranslateHTTP) Handler() http.Handler

Handler returns the routed handler. Mount it at "/api/translate", wrapped in the deployment's RequireAuth (TeamHTTP or PersonalAuthHTTP).

type WebHTTP added in v0.16.0

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

WebHTTP serves the embedded SPA and its capabilities endpoint. The two handlers are mounted separately (CapabilitiesHandler at the exact path "/api/capabilities", AssetsHandler at the subtree "/") so capabilities keeps working even when team mode also mounts "/api/" — Go's ServeMux prefers the longer, more specific pattern.

func NewWebHTTP added in v0.16.0

func NewWebHTTP(cfg WebHTTPConfig) *WebHTTP

NewWebHTTP builds the web UI handler set.

func (*WebHTTP) AssetsHandler added in v0.16.0

func (h *WebHTTP) AssetsHandler() http.Handler

AssetsHandler serves the embedded SPA at "/".

func (*WebHTTP) CapabilitiesHandler added in v0.16.0

func (h *WebHTTP) CapabilitiesHandler() http.Handler

CapabilitiesHandler serves GET /api/capabilities.

type WebHTTPConfig added in v0.16.0

type WebHTTPConfig struct {
	// Capabilities is served at GET /api/capabilities and drives the SPA's
	// capability-aware rendering (TRD §1a/§6).
	Capabilities config.Capabilities
	// Assets is the embedded web/dist directory (index.html, app.js,
	// style.css, ...). No external/CDN assets are ever referenced.
	Assets fs.FS
	Logger *slog.Logger
}

WebHTTPConfig configures the embedded web UI handlers.

Jump to

Keyboard shortcuts

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