api

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package api provides the REST API for OpenBotStack runtime.

Package api provides the REST API for OpenBotStack runtime.

Index

Constants

View Source
const (
	ErrMethodNotAllowed   = "METHOD_NOT_ALLOWED"
	ErrInvalidRequest     = "INVALID_REQUEST"
	ErrUnauthorized       = "UNAUTHORIZED"
	ErrForbidden          = "FORBIDDEN"
	ErrNotFound           = "NOT_FOUND"
	ErrRateLimited        = "RATE_LIMITED"
	ErrInternal           = "INTERNAL_ERROR"
	ErrUnavailable        = "SERVICE_UNAVAILABLE"
	ErrAgentNotConfigured = "AGENT_NOT_CONFIGURED"
)

Error code constants (UPPER_SNAKE_CASE).

View Source
const (
	// CorrelationIDHeader is the HTTP header used to propagate correlation IDs.
	CorrelationIDHeader = "X-Correlation-ID"
)

Variables

This section is empty.

Functions

func CorrelationIDFromContext

func CorrelationIDFromContext(ctx context.Context) string

CorrelationIDFromContext retrieves the correlation ID from the context.

func CorrelationMiddleware

func CorrelationMiddleware(next http.Handler) http.Handler

CorrelationMiddleware injects a correlation ID into each request context and adds it to the response headers. If an incoming request already carries the X-Correlation-ID header, that value is reused; otherwise a new UUID is generated.

Every log line emitted via slog during the request will include the correlation_id attribute when the returned handler is used.

func MetricsHandler

func MetricsHandler() http.Handler

MetricsHandler returns an http.Handler that serves Prometheus-format metrics via the OpenTelemetry SDK.

Types

type APIErrorDetail

type APIErrorDetail struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

APIErrorDetail contains the error code and human-readable message.

type APIErrorResponse

type APIErrorResponse struct {
	Error APIErrorDetail `json:"error"`
}

APIErrorResponse is the standard error envelope.

type AdminRouter

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

AdminRouter handles admin CRUD endpoints.

func NewAdminRouter

func NewAdminRouter(db *sql.DB) *AdminRouter

NewAdminRouter creates an admin router backed by db.

func (*AdminRouter) Handler

func (ar *AdminRouter) Handler() http.Handler

Handler returns the admin http.Handler wrapped with RequireAdmin.

type AuditExecutionStore

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

AuditExecutionStore adapts AuditLogger to ExecutionStore.

func NewAuditExecutionStore

func NewAuditExecutionStore(logger audit.AuditLogger) *AuditExecutionStore

NewAuditExecutionStore creates an ExecutionStore backed by audit logs.

func (*AuditExecutionStore) QueryExecutions

func (s *AuditExecutionStore) QueryExecutions(ctx context.Context, limit int) ([]ExecutionRecord, error)

QueryExecutions returns recent execution records from audit logs.

type BuildInfo

type BuildInfo struct {
	Version   string `json:"version"`
	Commit    string `json:"commit"`
	Branch    string `json:"branch"`
	BuildTime string `json:"build_time"`
	GoVersion string `json:"go_version"`
}

BuildInfo holds build metadata injected via -ldflags.

type ChatRequest

type ChatRequest struct {
	TenantID  string `json:"tenant_id"`
	UserID    string `json:"user_id"`
	SessionID string `json:"session_id"`
	Message   string `json:"message"`
}

ChatRequest is the input for chat endpoint.

type ChatResponse

type ChatResponse struct {
	SessionID string `json:"session_id"`
	Message   string `json:"message"`
	SkillUsed string `json:"skill_used,omitempty"`
}

ChatResponse is the output from chat endpoint.

type ComponentHealth

type ComponentHealth struct {
	Status     string            `json:"status"`
	DurationMs int64             `json:"duration_ms"`
	Error      string            `json:"error,omitempty"`
	Details    map[string]string `json:"details,omitempty"`
}

ComponentHealth is the health status of a single dependency.

type ExecutionRecord

type ExecutionRecord struct {
	ExecutionID string `json:"execution_id"`
	SessionID   string `json:"session_id"`
	SkillID     string `json:"skill_id"`
	DurationMs  int64  `json:"duration_ms"`
	Status      string `json:"status"`
	Error       string `json:"error,omitempty"`
}

ExecutionRecord is a single execution entry.

type ExecutionStore

type ExecutionStore interface {
	QueryExecutions(ctx context.Context, limit int) ([]ExecutionRecord, error)
}

ExecutionStore provides access to execution history.

type HealthChecker

type HealthChecker interface {
	Name() string
	Check(ctx context.Context) ComponentHealth
}

HealthChecker checks a single dependency. Implementations MUST be safe for concurrent use.

type HealthReport

type HealthReport struct {
	Status     string                     `json:"status"`
	Version    string                     `json:"version"`
	Commit     string                     `json:"commit"`
	Branch     string                     `json:"branch"`
	BuildTime  string                     `json:"build_time"`
	GoVersion  string                     `json:"go_version"`
	Components map[string]ComponentHealth `json:"components"`
	CheckedAt  time.Time                  `json:"checked_at"`
}

HealthReport is the full system health report.

type HistoryProvider

type HistoryProvider interface {
	// GetSessionHistory retrieves messages for a session.
	GetSessionHistory(ctx context.Context, sessionID string) ([]Message, error)
}

HistoryProvider gives access to conversation history.

type HistoryResponse

type HistoryResponse struct {
	SessionID string    `json:"session_id"`
	Messages  []Message `json:"messages"`
}

HistoryResponse contains conversation history.

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

Message represents a single chat message.

type Metrics

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

Metrics holds simple counters for Prometheus-style exposition. Retained for backward compatibility; the /metrics endpoint now delegates to the OpenTelemetry Prometheus handler via MetricsHandler().

func NewMetrics

func NewMetrics() *Metrics

NewMetrics returns a new Metrics instance.

func (*Metrics) Handler

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

Handler returns an http.HandlerFunc that exposes the legacy atomic counters in Prometheus text exposition format. For production use prefer MetricsHandler() which delegates to the OTel Prometheus exporter.

func (*Metrics) IncErrors

func (m *Metrics) IncErrors()

IncErrors increments the error counter.

func (*Metrics) IncRequests

func (m *Metrics) IncRequests()

IncRequests increments the total request counter.

type ProviderHealthChecker

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

ProviderHealthChecker checks LLM provider connectivity via /models endpoint.

func NewProviderHealthChecker

func NewProviderHealthChecker(baseURL, apiKey string) *ProviderHealthChecker

NewProviderHealthChecker creates a health checker for an LLM provider.

func (*ProviderHealthChecker) Check

func (*ProviderHealthChecker) Name

func (c *ProviderHealthChecker) Name() string

type RedisHealthChecker

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

RedisHealthChecker checks Redis connectivity.

func NewRedisHealthChecker

func NewRedisHealthChecker(pingFunc func(ctx context.Context) error) *RedisHealthChecker

NewRedisHealthChecker creates a health checker for Redis.

func (*RedisHealthChecker) Check

func (*RedisHealthChecker) Name

func (c *RedisHealthChecker) Name() string

type Router

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

Router handles HTTP routing.

The Router is responsible ONLY for:

  • HTTP request/response handling
  • Request validation
  • Session management
  • Delegating to Agent

The Router does NOT:

  • Select skills (that's the Agent's job)
  • Execute skills (that's the Executor's job)
  • Make any decisions about which skill to use

func NewRouter

func NewRouter(a agent.Agent) *Router

NewRouter creates a new API router with an Agent.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements http.Handler.

func (*Router) SetAuthMiddleware

func (r *Router) SetAuthMiddleware(mw func(http.Handler) http.Handler)

SetAuthMiddleware sets an authentication middleware to be used for all /v1/ endpoints. This should be called before requests begin processing.

func (*Router) SetBuildInfo

func (r *Router) SetBuildInfo(info BuildInfo)

SetBuildInfo sets the build info for the /readyz and /version endpoints.

func (*Router) SetExecutionStore

func (r *Router) SetExecutionStore(es ExecutionStore)

SetExecutionStore sets the execution store for the /v1/executions endpoint.

func (*Router) SetHealthCheckers

func (r *Router) SetHealthCheckers(checkers ...HealthChecker)

SetHealthCheckers sets the health checkers for the /readyz endpoint.

func (*Router) SetHistoryProvider

func (r *Router) SetHistoryProvider(hp HistoryProvider)

SetHistoryProvider sets the history provider for the /v1/sessions/{id}/history endpoint.

func (*Router) SetSkillProvider

func (r *Router) SetSkillProvider(sp SkillProvider)

SetSkillProvider sets the skill registry for the /v1/skills endpoint.

type SSEEvent

type SSEEvent struct {
	ID    string
	Event string
	Data  string
}

SSEEvent represents a Server-Sent Event.

type SSEHandler

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

SSEHandler writes SSE events to an HTTP response.

func NewSSEHandler

func NewSSEHandler(w http.ResponseWriter) *SSEHandler

NewSSEHandler creates a new SSE handler.

func (*SSEHandler) WriteEvent

func (h *SSEHandler) WriteEvent(event SSEEvent) error

WriteEvent writes a single SSE event. Multi-line data is split into multiple "data:" lines per the SSE specification.

type SSEStream

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

SSEStream buffers events for streaming.

func NewSSEStream

func NewSSEStream() *SSEStream

NewSSEStream creates a new SSE stream.

func (*SSEStream) Close

func (s *SSEStream) Close() error

Close marks the stream as closed.

func (*SSEStream) Count

func (s *SSEStream) Count() int

Count returns the number of events.

func (*SSEStream) Send

func (s *SSEStream) Send(event SSEEvent) error

Send adds an event to the stream.

type SkillProvider

type SkillProvider interface {
	List() []string
	Get(id string) (skills.Skill, error)
}

SkillProvider provides access to loaded skills for the API.

type SkillResponse

type SkillResponse struct {
	ID           string      `json:"id"`
	Name         string      `json:"name"`
	Description  string      `json:"description"`
	Type         string      `json:"type"`
	InputSchema  interface{} `json:"input_schema,omitempty"`
	OutputSchema interface{} `json:"output_schema,omitempty"`
	Version      string      `json:"version"`
	Enabled      bool        `json:"enabled"`
}

SkillResponse is the JSON representation of a skills.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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